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 {
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 { return Range; }
190 SourceLocation getBeginLoc() const LLVM_READONLY { return Range.getBegin(); }
191 SourceLocation getEndLoc() const LLVM_READONLY { return Range.getEnd(); }
192
193 /// Get the location at which the base class type was written.
194 SourceLocation getBaseTypeLoc() const LLVM_READONLY {
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");
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");
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());
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() ||
679 (data().DeclaredSpecialMembers & SMF_CopyConstructor)) &&
680 "this property has not yet been computed by Sema");
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() ||
688 (data().DeclaredSpecialMembers & SMF_MoveConstructor)) &&
689 "this property has not yet been computed by Sema");
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() ||
696 (data().DeclaredSpecialMembers & SMF_Destructor)) &&
697 "this property has not yet been computed by Sema");
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 // FIXME: Proposed fix to core wording issue: if a class inherits
751 // a default constructor and doesn't explicitly declare one, one
752 // is declared implicitly.
753 (data().HasInheritedDefaultConstructor &&
754 !(data().DeclaredSpecialMembers & SMF_DefaultConstructor));
755 }
756
757 /// Determine whether this class has any user-declared constructors.
758 ///
759 /// When true, a default constructor will not be implicitly declared.
760 bool hasUserDeclaredConstructor() const {
761 return data().UserDeclaredConstructor;
762 }
763
764 /// Whether this class has a user-provided default constructor
765 /// per C++11.
766 bool hasUserProvidedDefaultConstructor() const {
767 return data().UserProvidedDefaultConstructor;
768 }
769
770 /// Determine whether this class has a user-declared copy constructor.
771 ///
772 /// When false, a copy constructor will be implicitly declared.
773 bool hasUserDeclaredCopyConstructor() const {
774 return data().UserDeclaredSpecialMembers & SMF_CopyConstructor;
775 }
776
777 /// Determine whether this class needs an implicit copy
778 /// constructor to be lazily declared.
779 bool needsImplicitCopyConstructor() const {
780 return !(data().DeclaredSpecialMembers & SMF_CopyConstructor);
781 }
782
783 /// Determine whether we need to eagerly declare a defaulted copy
784 /// constructor for this class.
785 bool needsOverloadResolutionForCopyConstructor() const {
786 // C++17 [class.copy.ctor]p6:
787 // If the class definition declares a move constructor or move assignment
788 // operator, the implicitly declared copy constructor is defined as
789 // deleted.
790 // In MSVC mode, sometimes a declared move assignment does not delete an
791 // implicit copy constructor, so defer this choice to Sema.
792 if (data().UserDeclaredSpecialMembers &
793 (SMF_MoveConstructor | SMF_MoveAssignment))
794 return true;
795 return data().NeedOverloadResolutionForCopyConstructor;
796 }
797
798 /// Determine whether an implicit copy constructor for this type
799 /// would have a parameter with a const-qualified reference type.
800 bool implicitCopyConstructorHasConstParam() const {
801 return data().ImplicitCopyConstructorCanHaveConstParamForNonVBase &&
802 (isAbstract() ||
803 data().ImplicitCopyConstructorCanHaveConstParamForVBase);
804 }
805
806 /// Determine whether this class has a copy constructor with
807 /// a parameter type which is a reference to a const-qualified type.
808 bool hasCopyConstructorWithConstParam() const {
809 return data().HasDeclaredCopyConstructorWithConstParam ||
810 (needsImplicitCopyConstructor() &&
811 implicitCopyConstructorHasConstParam());
812 }
813
814 /// Whether this class has a user-declared move constructor or
815 /// assignment operator.
816 ///
817 /// When false, a move constructor and assignment operator may be
818 /// implicitly declared.
819 bool hasUserDeclaredMoveOperation() const {
820 return data().UserDeclaredSpecialMembers &
821 (SMF_MoveConstructor | SMF_MoveAssignment);
822 }
823
824 /// Determine whether this class has had a move constructor
825 /// declared by the user.
826 bool hasUserDeclaredMoveConstructor() const {
827 return data().UserDeclaredSpecialMembers & SMF_MoveConstructor;
828 }
829
830 /// Determine whether this class has a move constructor.
831 bool hasMoveConstructor() const {
832 return (data().DeclaredSpecialMembers & SMF_MoveConstructor) ||
833 needsImplicitMoveConstructor();
834 }
835
836 /// Set that we attempted to declare an implicit copy
837 /// constructor, but overload resolution failed so we deleted it.
838 void setImplicitCopyConstructorIsDeleted() {
839 assert((data().DefaultedCopyConstructorIsDeleted ||
840 needsOverloadResolutionForCopyConstructor()) &&
841 "Copy constructor should not be deleted");
842 data().DefaultedCopyConstructorIsDeleted = true;
843 }
844
845 /// Set that we attempted to declare an implicit move
846 /// constructor, but overload resolution failed so we deleted it.
847 void setImplicitMoveConstructorIsDeleted() {
848 assert((data().DefaultedMoveConstructorIsDeleted ||
849 needsOverloadResolutionForMoveConstructor()) &&
850 "move constructor should not be deleted");
851 data().DefaultedMoveConstructorIsDeleted = true;
852 }
853
854 /// Set that we attempted to declare an implicit destructor,
855 /// but overload resolution failed so we deleted it.
856 void setImplicitDestructorIsDeleted() {
857 assert((data().DefaultedDestructorIsDeleted ||
858 needsOverloadResolutionForDestructor()) &&
859 "destructor should not be deleted");
860 data().DefaultedDestructorIsDeleted = true;
861 }
862
863 /// Determine whether this class should get an implicit move
864 /// constructor or if any existing special member function inhibits this.
865 bool needsImplicitMoveConstructor() const {
866 return !(data().DeclaredSpecialMembers & SMF_MoveConstructor) &&
867 !hasUserDeclaredCopyConstructor() &&
868 !hasUserDeclaredCopyAssignment() &&
869 !hasUserDeclaredMoveAssignment() &&
870 !hasUserDeclaredDestructor();
871 }
872
873 /// Determine whether we need to eagerly declare a defaulted move
874 /// constructor for this class.
875 bool needsOverloadResolutionForMoveConstructor() const {
876 return data().NeedOverloadResolutionForMoveConstructor;
877 }
878
879 /// Determine whether this class has a user-declared copy assignment
880 /// operator.
881 ///
882 /// When false, a copy assignment operator will be implicitly declared.
883 bool hasUserDeclaredCopyAssignment() const {
884 return data().UserDeclaredSpecialMembers & SMF_CopyAssignment;
885 }
886
887 /// Set that we attempted to declare an implicit copy assignment
888 /// operator, but overload resolution failed so we deleted it.
889 void setImplicitCopyAssignmentIsDeleted() {
890 assert((data().DefaultedCopyAssignmentIsDeleted ||
891 needsOverloadResolutionForCopyAssignment()) &&
892 "copy assignment should not be deleted");
893 data().DefaultedCopyAssignmentIsDeleted = true;
894 }
895
896 /// Determine whether this class needs an implicit copy
897 /// assignment operator to be lazily declared.
898 bool needsImplicitCopyAssignment() const {
899 return !(data().DeclaredSpecialMembers & SMF_CopyAssignment);
900 }
901
902 /// Determine whether we need to eagerly declare a defaulted copy
903 /// assignment operator for this class.
904 bool needsOverloadResolutionForCopyAssignment() const {
905 // C++20 [class.copy.assign]p2:
906 // If the class definition declares a move constructor or move assignment
907 // operator, the implicitly declared copy assignment operator is defined
908 // as deleted.
909 // In MSVC mode, sometimes a declared move constructor does not delete an
910 // implicit copy assignment, so defer this choice to Sema.
911 if (data().UserDeclaredSpecialMembers &
912 (SMF_MoveConstructor | SMF_MoveAssignment))
913 return true;
914 return data().NeedOverloadResolutionForCopyAssignment;
915 }
916
917 /// Determine whether an implicit copy assignment operator for this
918 /// type would have a parameter with a const-qualified reference type.
919 bool implicitCopyAssignmentHasConstParam() const {
920 return data().ImplicitCopyAssignmentHasConstParam;
921 }
922
923 /// Determine whether this class has a copy assignment operator with
924 /// a parameter type which is a reference to a const-qualified type or is not
925 /// a reference.
926 bool hasCopyAssignmentWithConstParam() const {
927 return data().HasDeclaredCopyAssignmentWithConstParam ||
928 (needsImplicitCopyAssignment() &&
929 implicitCopyAssignmentHasConstParam());
930 }
931
932 /// Determine whether this class has had a move assignment
933 /// declared by the user.
934 bool hasUserDeclaredMoveAssignment() const {
935 return data().UserDeclaredSpecialMembers & SMF_MoveAssignment;
936 }
937
938 /// Determine whether this class has a move assignment operator.
939 bool hasMoveAssignment() const {
940 return (data().DeclaredSpecialMembers & SMF_MoveAssignment) ||
941 needsImplicitMoveAssignment();
942 }
943
944 /// Set that we attempted to declare an implicit move assignment
945 /// operator, but overload resolution failed so we deleted it.
946 void setImplicitMoveAssignmentIsDeleted() {
947 assert((data().DefaultedMoveAssignmentIsDeleted ||
948 needsOverloadResolutionForMoveAssignment()) &&
949 "move assignment should not be deleted");
950 data().DefaultedMoveAssignmentIsDeleted = true;
951 }
952
953 /// Determine whether this class should get an implicit move
954 /// assignment operator or if any existing special member function inhibits
955 /// this.
956 bool needsImplicitMoveAssignment() const {
957 return !(data().DeclaredSpecialMembers & SMF_MoveAssignment) &&
958 !hasUserDeclaredCopyConstructor() &&
959 !hasUserDeclaredCopyAssignment() &&
960 !hasUserDeclaredMoveConstructor() &&
961 !hasUserDeclaredDestructor() &&
962 (!isLambda() || lambdaIsDefaultConstructibleAndAssignable());
963 }
964
965 /// Determine whether we need to eagerly declare a move assignment
966 /// operator for this class.
967 bool needsOverloadResolutionForMoveAssignment() const {
968 return data().NeedOverloadResolutionForMoveAssignment;
969 }
970
971 /// Determine whether this class has a user-declared destructor.
972 ///
973 /// When false, a destructor will be implicitly declared.
974 bool hasUserDeclaredDestructor() const {
975 return data().UserDeclaredSpecialMembers & SMF_Destructor;
976 }
977
978 /// Determine whether this class needs an implicit destructor to
979 /// be lazily declared.
980 bool needsImplicitDestructor() const {
981 return !(data().DeclaredSpecialMembers & SMF_Destructor);
982 }
983
984 /// Determine whether we need to eagerly declare a destructor for this
985 /// class.
986 bool needsOverloadResolutionForDestructor() const {
987 return data().NeedOverloadResolutionForDestructor;
988 }
989
990 /// Determine whether this class describes a lambda function object.
991 bool isLambda() const {
992 // An update record can't turn a non-lambda into a lambda.
993 auto *DD = DefinitionData;
994 return DD && DD->IsLambda;
995 }
996
997 /// Determine whether this class describes a generic
998 /// lambda function object (i.e. function call operator is
999 /// a template).
1000 bool isGenericLambda() const;
1001
1002 /// Determine whether this lambda should have an implicit default constructor
1003 /// and copy and move assignment operators.
1004 bool lambdaIsDefaultConstructibleAndAssignable() const;
1005
1006 /// Retrieve the lambda call operator of the closure type
1007 /// if this is a closure type.
1008 CXXMethodDecl *getLambdaCallOperator() const;
1009
1010 /// Retrieve the dependent lambda call operator of the closure type
1011 /// if this is a templated closure type.
1012 FunctionTemplateDecl *getDependentLambdaCallOperator() const;
1013
1014 /// Retrieve the lambda static invoker, the address of which
1015 /// is returned by the conversion operator, and the body of which
1016 /// is forwarded to the lambda call operator. The version that does not
1017 /// take a calling convention uses the 'default' calling convention for free
1018 /// functions if the Lambda's calling convention was not modified via
1019 /// attribute. Otherwise, it will return the calling convention specified for
1020 /// the lambda.
1021 CXXMethodDecl *getLambdaStaticInvoker() const;
1022 CXXMethodDecl *getLambdaStaticInvoker(CallingConv CC) const;
1023
1024 /// Retrieve the generic lambda's template parameter list.
1025 /// Returns null if the class does not represent a lambda or a generic
1026 /// lambda.
1027 TemplateParameterList *getGenericLambdaTemplateParameterList() const;
1028
1029 /// Retrieve the lambda template parameters that were specified explicitly.
1030 ArrayRef<NamedDecl *> getLambdaExplicitTemplateParameters() const;
1031
1032 LambdaCaptureDefault getLambdaCaptureDefault() const {
1033 assert(isLambda());
1034 return static_cast<LambdaCaptureDefault>(getLambdaData().CaptureDefault);
1035 }
1036
1037 /// Set the captures for this lambda closure type.
1038 void setCaptures(ASTContext &Context, ArrayRef<LambdaCapture> Captures);
1039
1040 /// For a closure type, retrieve the mapping from captured
1041 /// variables and \c this to the non-static data members that store the
1042 /// values or references of the captures.
1043 ///
1044 /// \param Captures Will be populated with the mapping from captured
1045 /// variables to the corresponding fields.
1046 ///
1047 /// \param ThisCapture Will be set to the field declaration for the
1048 /// \c this capture.
1049 ///
1050 /// \note No entries will be added for init-captures, as they do not capture
1051 /// variables.
1052 void getCaptureFields(llvm::DenseMap<const VarDecl *, FieldDecl *> &Captures,
1053 FieldDecl *&ThisCapture) const;
1054
1055 using capture_const_iterator = const LambdaCapture *;
1056 using capture_const_range = llvm::iterator_range<capture_const_iterator>;
1057
1058 capture_const_range captures() const {
1059 return capture_const_range(captures_begin(), captures_end());
1060 }
1061
1062 capture_const_iterator captures_begin() const {
1063 return isLambda() ? getLambdaData().Captures : nullptr;
1064 }
1065
1066 capture_const_iterator captures_end() const {
1067 return isLambda() ? captures_begin() + getLambdaData().NumCaptures
1068 : nullptr;
1069 }
1070
1071 unsigned capture_size() const { return getLambdaData().NumCaptures; }
1072
1073 using conversion_iterator = UnresolvedSetIterator;
1074
1075 conversion_iterator conversion_begin() const {
1076 return data().Conversions.get(getASTContext()).begin();
1077 }
1078
1079 conversion_iterator conversion_end() const {
1080 return data().Conversions.get(getASTContext()).end();
1081 }
1082
1083 /// Removes a conversion function from this class. The conversion
1084 /// function must currently be a member of this class. Furthermore,
1085 /// this class must currently be in the process of being defined.
1086 void removeConversion(const NamedDecl *Old);
1087
1088 /// Get all conversion functions visible in current class,
1089 /// including conversion function templates.
1090 llvm::iterator_range<conversion_iterator>
1091 getVisibleConversionFunctions() const;
1092
1093 /// Determine whether this class is an aggregate (C++ [dcl.init.aggr]),
1094 /// which is a class with no user-declared constructors, no private
1095 /// or protected non-static data members, no base classes, and no virtual
1096 /// functions (C++ [dcl.init.aggr]p1).
1097 bool isAggregate() const { return data().Aggregate; }
1098
1099 /// Whether this class has any in-class initializers
1100 /// for non-static data members (including those in anonymous unions or
1101 /// structs).
1102 bool hasInClassInitializer() const { return data().HasInClassInitializer; }
1103
1104 /// Whether this class or any of its subobjects has any members of
1105 /// reference type which would make value-initialization ill-formed.
1106 ///
1107 /// Per C++03 [dcl.init]p5:
1108 /// - if T is a non-union class type without a user-declared constructor,
1109 /// then every non-static data member and base-class component of T is
1110 /// value-initialized [...] A program that calls for [...]
1111 /// value-initialization of an entity of reference type is ill-formed.
1112 bool hasUninitializedReferenceMember() const {
1113 return !isUnion() && !hasUserDeclaredConstructor() &&
1114 data().HasUninitializedReferenceMember;
1115 }
1116
1117 /// Whether this class is a POD-type (C++ [class]p4)
1118 ///
1119 /// For purposes of this function a class is POD if it is an aggregate
1120 /// that has no non-static non-POD data members, no reference data
1121 /// members, no user-defined copy assignment operator and no
1122 /// user-defined destructor.
1123 ///
1124 /// Note that this is the C++ TR1 definition of POD.
1125 bool isPOD() const { return data().PlainOldData; }
1126
1127 /// True if this class is C-like, without C++-specific features, e.g.
1128 /// it contains only public fields, no bases, tag kind is not 'class', etc.
1129 bool isCLike() const;
1130
1131 /// Determine whether this is an empty class in the sense of
1132 /// (C++11 [meta.unary.prop]).
1133 ///
1134 /// The CXXRecordDecl is a class type, but not a union type,
1135 /// with no non-static data members other than bit-fields of length 0,
1136 /// no virtual member functions, no virtual base classes,
1137 /// and no base class B for which is_empty<B>::value is false.
1138 ///
1139 /// \note This does NOT include a check for union-ness.
1140 bool isEmpty() const { return data().Empty; }
1141
1142 bool hasPrivateFields() const {
1143 return data().HasPrivateFields;
1144 }
1145
1146 bool hasProtectedFields() const {
1147 return data().HasProtectedFields;
1148 }
1149
1150 /// Determine whether this class has direct non-static data members.
1151 bool hasDirectFields() const {
1152 auto &D = data();
1153 return D.HasPublicFields || D.HasProtectedFields || D.HasPrivateFields;
1154 }
1155
1156 /// Whether this class is polymorphic (C++ [class.virtual]),
1157 /// which means that the class contains or inherits a virtual function.
1158 bool isPolymorphic() const { return data().Polymorphic; }
1159
1160 /// Determine whether this class has a pure virtual function.
1161 ///
1162 /// The class is is abstract per (C++ [class.abstract]p2) if it declares
1163 /// a pure virtual function or inherits a pure virtual function that is
1164 /// not overridden.
1165 bool isAbstract() const { return data().Abstract; }
1166
1167 /// Determine whether this class is standard-layout per
1168 /// C++ [class]p7.
1169 bool isStandardLayout() const { return data().IsStandardLayout; }
1170
1171 /// Determine whether this class was standard-layout per
1172 /// C++11 [class]p7, specifically using the C++11 rules without any DRs.
1173 bool isCXX11StandardLayout() const { return data().IsCXX11StandardLayout; }
1174
1175 /// Determine whether this class, or any of its class subobjects,
1176 /// contains a mutable field.
1177 bool hasMutableFields() const { return data().HasMutableFields; }
1178
1179 /// Determine whether this class has any variant members.
1180 bool hasVariantMembers() const { return data().HasVariantMembers; }
1181
1182 /// Determine whether this class has a trivial default constructor
1183 /// (C++11 [class.ctor]p5).
1184 bool hasTrivialDefaultConstructor() const {
1185 return hasDefaultConstructor() &&
1186 (data().HasTrivialSpecialMembers & SMF_DefaultConstructor);
1187 }
1188
1189 /// Determine whether this class has a non-trivial default constructor
1190 /// (C++11 [class.ctor]p5).
1191 bool hasNonTrivialDefaultConstructor() const {
1192 return (data().DeclaredNonTrivialSpecialMembers & SMF_DefaultConstructor) ||
1193 (needsImplicitDefaultConstructor() &&
1194 !(data().HasTrivialSpecialMembers & SMF_DefaultConstructor));
1195 }
1196
1197 /// Determine whether this class has at least one constexpr constructor
1198 /// other than the copy or move constructors.
1199 bool hasConstexprNonCopyMoveConstructor() const {
1200 return data().HasConstexprNonCopyMoveConstructor ||
1201 (needsImplicitDefaultConstructor() &&
1202 defaultedDefaultConstructorIsConstexpr());
1203 }
1204
1205 /// Determine whether a defaulted default constructor for this class
1206 /// would be constexpr.
1207 bool defaultedDefaultConstructorIsConstexpr() const {
1208 return data().DefaultedDefaultConstructorIsConstexpr &&
1209 (!isUnion() || hasInClassInitializer() || !hasVariantMembers() ||
1210 getLangOpts().CPlusPlus20);
1211 }
1212
1213 /// Determine whether this class has a constexpr default constructor.
1214 bool hasConstexprDefaultConstructor() const {
1215 return data().HasConstexprDefaultConstructor ||
1216 (needsImplicitDefaultConstructor() &&
1217 defaultedDefaultConstructorIsConstexpr());
1218 }
1219
1220 /// Determine whether this class has a trivial copy constructor
1221 /// (C++ [class.copy]p6, C++11 [class.copy]p12)
1222 bool hasTrivialCopyConstructor() const {
1223 return data().HasTrivialSpecialMembers & SMF_CopyConstructor;
1224 }
1225
1226 bool hasTrivialCopyConstructorForCall() const {
1227 return data().HasTrivialSpecialMembersForCall & SMF_CopyConstructor;
1228 }
1229
1230 /// Determine whether this class has a non-trivial copy constructor
1231 /// (C++ [class.copy]p6, C++11 [class.copy]p12)
1232 bool hasNonTrivialCopyConstructor() const {
1233 return data().DeclaredNonTrivialSpecialMembers & SMF_CopyConstructor ||
1234 !hasTrivialCopyConstructor();
1235 }
1236
1237 bool hasNonTrivialCopyConstructorForCall() const {
1238 return (data().DeclaredNonTrivialSpecialMembersForCall &
1239 SMF_CopyConstructor) ||
1240 !hasTrivialCopyConstructorForCall();
1241 }
1242
1243 /// Determine whether this class has a trivial move constructor
1244 /// (C++11 [class.copy]p12)
1245 bool hasTrivialMoveConstructor() const {
1246 return hasMoveConstructor() &&
1247 (data().HasTrivialSpecialMembers & SMF_MoveConstructor);
1248 }
1249
1250 bool hasTrivialMoveConstructorForCall() const {
1251 return hasMoveConstructor() &&
1252 (data().HasTrivialSpecialMembersForCall & SMF_MoveConstructor);
1253 }
1254
1255 /// Determine whether this class has a non-trivial move constructor
1256 /// (C++11 [class.copy]p12)
1257 bool hasNonTrivialMoveConstructor() const {
1258 return (data().DeclaredNonTrivialSpecialMembers & SMF_MoveConstructor) ||
1259 (needsImplicitMoveConstructor() &&
1260 !(data().HasTrivialSpecialMembers & SMF_MoveConstructor));
1261 }
1262
1263 bool hasNonTrivialMoveConstructorForCall() const {
1264 return (data().DeclaredNonTrivialSpecialMembersForCall &
1265 SMF_MoveConstructor) ||
1266 (needsImplicitMoveConstructor() &&
1267 !(data().HasTrivialSpecialMembersForCall & SMF_MoveConstructor));
1268 }
1269
1270 /// Determine whether this class has a trivial copy assignment operator
1271 /// (C++ [class.copy]p11, C++11 [class.copy]p25)
1272 bool hasTrivialCopyAssignment() const {
1273 return data().HasTrivialSpecialMembers & SMF_CopyAssignment;
1274 }
1275
1276 /// Determine whether this class has a non-trivial copy assignment
1277 /// operator (C++ [class.copy]p11, C++11 [class.copy]p25)
1278 bool hasNonTrivialCopyAssignment() const {
1279 return data().DeclaredNonTrivialSpecialMembers & SMF_CopyAssignment ||
1280 !hasTrivialCopyAssignment();
1281 }
1282
1283 /// Determine whether this class has a trivial move assignment operator
1284 /// (C++11 [class.copy]p25)
1285 bool hasTrivialMoveAssignment() const {
1286 return hasMoveAssignment() &&
1287 (data().HasTrivialSpecialMembers & SMF_MoveAssignment);
1288 }
1289
1290 /// Determine whether this class has a non-trivial move assignment
1291 /// operator (C++11 [class.copy]p25)
1292 bool hasNonTrivialMoveAssignment() const {
1293 return (data().DeclaredNonTrivialSpecialMembers & SMF_MoveAssignment) ||
1294 (needsImplicitMoveAssignment() &&
1295 !(data().HasTrivialSpecialMembers & SMF_MoveAssignment));
1296 }
1297
1298 /// Determine whether a defaulted default constructor for this class
1299 /// would be constexpr.
1300 bool defaultedDestructorIsConstexpr() const {
1301 return data().DefaultedDestructorIsConstexpr &&
1302 getLangOpts().CPlusPlus20;
1303 }
1304
1305 /// Determine whether this class has a constexpr destructor.
1306 bool hasConstexprDestructor() const;
1307
1308 /// Determine whether this class has a trivial destructor
1309 /// (C++ [class.dtor]p3)
1310 bool hasTrivialDestructor() const {
1311 return data().HasTrivialSpecialMembers & SMF_Destructor;
1312 }
1313
1314 bool hasTrivialDestructorForCall() const {
1315 return data().HasTrivialSpecialMembersForCall & SMF_Destructor;
1316 }
1317
1318 /// Determine whether this class has a non-trivial destructor
1319 /// (C++ [class.dtor]p3)
1320 bool hasNonTrivialDestructor() const {
1321 return !(data().HasTrivialSpecialMembers & SMF_Destructor);
1322 }
1323
1324 bool hasNonTrivialDestructorForCall() const {
1325 return !(data().HasTrivialSpecialMembersForCall & SMF_Destructor);
1326 }
1327
1328 void setHasTrivialSpecialMemberForCall() {
1329 data().HasTrivialSpecialMembersForCall =
1330 (SMF_CopyConstructor | SMF_MoveConstructor | SMF_Destructor);
1331 }
1332
1333 /// Determine whether declaring a const variable with this type is ok
1334 /// per core issue 253.
1335 bool allowConstDefaultInit() const {
1336 return !data().HasUninitializedFields ||
1337 !(data().HasDefaultedDefaultConstructor ||
1338 needsImplicitDefaultConstructor());
1339 }
1340
1341 /// Determine whether this class has a destructor which has no
1342 /// semantic effect.
1343 ///
1344 /// Any such destructor will be trivial, public, defaulted and not deleted,
1345 /// and will call only irrelevant destructors.
1346 bool hasIrrelevantDestructor() const {
1347 return data().HasIrrelevantDestructor;
1348 }
1349
1350 /// Determine whether this class has a non-literal or/ volatile type
1351 /// non-static data member or base class.
1352 bool hasNonLiteralTypeFieldsOrBases() const {
1353 return data().HasNonLiteralTypeFieldsOrBases;
1354 }
1355
1356 /// Determine whether this class has a using-declaration that names
1357 /// a user-declared base class constructor.
1358 bool hasInheritedConstructor() const {
1359 return data().HasInheritedConstructor;
1360 }
1361
1362 /// Determine whether this class has a using-declaration that names
1363 /// a base class assignment operator.
1364 bool hasInheritedAssignment() const {
1365 return data().HasInheritedAssignment;
1366 }
1367
1368 /// Determine whether this class is considered trivially copyable per
1369 /// (C++11 [class]p6).
1370 bool isTriviallyCopyable() const;
1371
1372 /// Determine whether this class is considered trivial.
1373 ///
1374 /// C++11 [class]p6:
1375 /// "A trivial class is a class that has a trivial default constructor and
1376 /// is trivially copyable."
1377 bool isTrivial() const {
1378 return isTriviallyCopyable() && hasTrivialDefaultConstructor();
1379 }
1380
1381 /// Determine whether this class is a literal type.
1382 ///
1383 /// C++11 [basic.types]p10:
1384 /// A class type that has all the following properties:
1385 /// - it has a trivial destructor
1386 /// - every constructor call and full-expression in the
1387 /// brace-or-equal-intializers for non-static data members (if any) is
1388 /// a constant expression.
1389 /// - it is an aggregate type or has at least one constexpr constructor
1390 /// or constructor template that is not a copy or move constructor, and
1391 /// - all of its non-static data members and base classes are of literal
1392 /// types
1393 ///
1394 /// We resolve DR1361 by ignoring the second bullet. We resolve DR1452 by
1395 /// treating types with trivial default constructors as literal types.
1396 ///
1397 /// Only in C++17 and beyond, are lambdas literal types.
1398 bool isLiteral() const {
1399 const LangOptions &LangOpts = getLangOpts();
1400 return (LangOpts.CPlusPlus20 ? hasConstexprDestructor()
1401 : hasTrivialDestructor()) &&
1402 (!isLambda() || LangOpts.CPlusPlus17) &&
1403 !hasNonLiteralTypeFieldsOrBases() &&
1404 (isAggregate() || isLambda() ||
1405 hasConstexprNonCopyMoveConstructor() ||
1406 hasTrivialDefaultConstructor());
1407 }
1408
1409 /// Determine whether this is a structural type.
1410 bool isStructural() const {
1411 return isLiteral() && data().StructuralIfLiteral;
1412 }
1413
1414 /// If this record is an instantiation of a member class,
1415 /// retrieves the member class from which it was instantiated.
1416 ///
1417 /// This routine will return non-null for (non-templated) member
1418 /// classes of class templates. For example, given:
1419 ///
1420 /// \code
1421 /// template<typename T>
1422 /// struct X {
1423 /// struct A { };
1424 /// };
1425 /// \endcode
1426 ///
1427 /// The declaration for X<int>::A is a (non-templated) CXXRecordDecl
1428 /// whose parent is the class template specialization X<int>. For
1429 /// this declaration, getInstantiatedFromMemberClass() will return
1430 /// the CXXRecordDecl X<T>::A. When a complete definition of
1431 /// X<int>::A is required, it will be instantiated from the
1432 /// declaration returned by getInstantiatedFromMemberClass().
1433 CXXRecordDecl *getInstantiatedFromMemberClass() const;
1434
1435 /// If this class is an instantiation of a member class of a
1436 /// class template specialization, retrieves the member specialization
1437 /// information.
1438 MemberSpecializationInfo *getMemberSpecializationInfo() const;
1439
1440 /// Specify that this record is an instantiation of the
1441 /// member class \p RD.
1442 void setInstantiationOfMemberClass(CXXRecordDecl *RD,
1443 TemplateSpecializationKind TSK);
1444
1445 /// Retrieves the class template that is described by this
1446 /// class declaration.
1447 ///
1448 /// Every class template is represented as a ClassTemplateDecl and a
1449 /// CXXRecordDecl. The former contains template properties (such as
1450 /// the template parameter lists) while the latter contains the
1451 /// actual description of the template's
1452 /// contents. ClassTemplateDecl::getTemplatedDecl() retrieves the
1453 /// CXXRecordDecl that from a ClassTemplateDecl, while
1454 /// getDescribedClassTemplate() retrieves the ClassTemplateDecl from
1455 /// a CXXRecordDecl.
1456 ClassTemplateDecl *getDescribedClassTemplate() const;
1457
1458 void setDescribedClassTemplate(ClassTemplateDecl *Template);
1459
1460 /// Determine whether this particular class is a specialization or
1461 /// instantiation of a class template or member class of a class template,
1462 /// and how it was instantiated or specialized.
1463 TemplateSpecializationKind getTemplateSpecializationKind() const;
1464
1465 /// Set the kind of specialization or template instantiation this is.
1466 void setTemplateSpecializationKind(TemplateSpecializationKind TSK);
1467
1468 /// Retrieve the record declaration from which this record could be
1469 /// instantiated. Returns null if this class is not a template instantiation.
1470 const CXXRecordDecl *getTemplateInstantiationPattern() const;
1471
1472 CXXRecordDecl *getTemplateInstantiationPattern() {
1473 return const_cast<CXXRecordDecl *>(const_cast<const CXXRecordDecl *>(this)
1474 ->getTemplateInstantiationPattern());
1475 }
1476
1477 /// Returns the destructor decl for this class.
1478 CXXDestructorDecl *getDestructor() const;
1479
1480 /// Returns true if the class destructor, or any implicitly invoked
1481 /// destructors are marked noreturn.
1482 bool isAnyDestructorNoReturn() const;
1483
1484 /// If the class is a local class [class.local], returns
1485 /// the enclosing function declaration.
1486 const FunctionDecl *isLocalClass() const {
1487 if (const auto *RD = dyn_cast<CXXRecordDecl>(getDeclContext()))
1488 return RD->isLocalClass();
1489
1490 return dyn_cast<FunctionDecl>(getDeclContext());
1491 }
1492
1493 FunctionDecl *isLocalClass() {
1494 return const_cast<FunctionDecl*>(
1495 const_cast<const CXXRecordDecl*>(this)->isLocalClass());
1496 }
1497
1498 /// Determine whether this dependent class is a current instantiation,
1499 /// when viewed from within the given context.
1500 bool isCurrentInstantiation(const DeclContext *CurContext) const;
1501
1502 /// Determine whether this class is derived from the class \p Base.
1503 ///
1504 /// This routine only determines whether this class is derived from \p Base,
1505 /// but does not account for factors that may make a Derived -> Base class
1506 /// ill-formed, such as private/protected inheritance or multiple, ambiguous
1507 /// base class subobjects.
1508 ///
1509 /// \param Base the base class we are searching for.
1510 ///
1511 /// \returns true if this class is derived from Base, false otherwise.
1512 bool isDerivedFrom(const CXXRecordDecl *Base) const;
1513
1514 /// Determine whether this class is derived from the type \p Base.
1515 ///
1516 /// This routine only determines whether this class is derived from \p Base,
1517 /// but does not account for factors that may make a Derived -> Base class
1518 /// ill-formed, such as private/protected inheritance or multiple, ambiguous
1519 /// base class subobjects.
1520 ///
1521 /// \param Base the base class we are searching for.
1522 ///
1523 /// \param Paths will contain the paths taken from the current class to the
1524 /// given \p Base class.
1525 ///
1526 /// \returns true if this class is derived from \p Base, false otherwise.
1527 ///
1528 /// \todo add a separate parameter to configure IsDerivedFrom, rather than
1529 /// tangling input and output in \p Paths
1530 bool isDerivedFrom(const CXXRecordDecl *Base, CXXBasePaths &Paths) const;
1531
1532 /// Determine whether this class is virtually derived from
1533 /// the class \p Base.
1534 ///
1535 /// This routine only determines whether this class is virtually
1536 /// derived from \p Base, but does not account for factors that may
1537 /// make a Derived -> Base class ill-formed, such as
1538 /// private/protected inheritance or multiple, ambiguous base class
1539 /// subobjects.
1540 ///
1541 /// \param Base the base class we are searching for.
1542 ///
1543 /// \returns true if this class is virtually derived from Base,
1544 /// false otherwise.
1545 bool isVirtuallyDerivedFrom(const CXXRecordDecl *Base) const;
1546
1547 /// Determine whether this class is provably not derived from
1548 /// the type \p Base.
1549 bool isProvablyNotDerivedFrom(const CXXRecordDecl *Base) const;
1550
1551 /// Function type used by forallBases() as a callback.
1552 ///
1553 /// \param BaseDefinition the definition of the base class
1554 ///
1555 /// \returns true if this base matched the search criteria
1556 using ForallBasesCallback =
1557 llvm::function_ref<bool(const CXXRecordDecl *BaseDefinition)>;
1558
1559 /// Determines if the given callback holds for all the direct
1560 /// or indirect base classes of this type.
1561 ///
1562 /// The class itself does not count as a base class. This routine
1563 /// returns false if the class has non-computable base classes.
1564 ///
1565 /// \param BaseMatches Callback invoked for each (direct or indirect) base
1566 /// class of this type until a call returns false.
1567 bool forallBases(ForallBasesCallback BaseMatches) const;
1568
1569 /// Function type used by lookupInBases() to determine whether a
1570 /// specific base class subobject matches the lookup criteria.
1571 ///
1572 /// \param Specifier the base-class specifier that describes the inheritance
1573 /// from the base class we are trying to match.
1574 ///
1575 /// \param Path the current path, from the most-derived class down to the
1576 /// base named by the \p Specifier.
1577 ///
1578 /// \returns true if this base matched the search criteria, false otherwise.
1579 using BaseMatchesCallback =
1580 llvm::function_ref<bool(const CXXBaseSpecifier *Specifier,
1581 CXXBasePath &Path)>;
1582
1583 /// Look for entities within the base classes of this C++ class,
1584 /// transitively searching all base class subobjects.
1585 ///
1586 /// This routine uses the callback function \p BaseMatches to find base
1587 /// classes meeting some search criteria, walking all base class subobjects
1588 /// and populating the given \p Paths structure with the paths through the
1589 /// inheritance hierarchy that resulted in a match. On a successful search,
1590 /// the \p Paths structure can be queried to retrieve the matching paths and
1591 /// to determine if there were any ambiguities.
1592 ///
1593 /// \param BaseMatches callback function used to determine whether a given
1594 /// base matches the user-defined search criteria.
1595 ///
1596 /// \param Paths used to record the paths from this class to its base class
1597 /// subobjects that match the search criteria.
1598 ///
1599 /// \param LookupInDependent can be set to true to extend the search to
1600 /// dependent base classes.
1601 ///
1602 /// \returns true if there exists any path from this class to a base class
1603 /// subobject that matches the search criteria.
1604 bool lookupInBases(BaseMatchesCallback BaseMatches, CXXBasePaths &Paths,
1605 bool LookupInDependent = false) const;
1606
1607 /// Base-class lookup callback that determines whether the given
1608 /// base class specifier refers to a specific class declaration.
1609 ///
1610 /// This callback can be used with \c lookupInBases() to determine whether
1611 /// a given derived class has is a base class subobject of a particular type.
1612 /// The base record pointer should refer to the canonical CXXRecordDecl of the
1613 /// base class that we are searching for.
1614 static bool FindBaseClass(const CXXBaseSpecifier *Specifier,
1615 CXXBasePath &Path, const CXXRecordDecl *BaseRecord);
1616
1617 /// Base-class lookup callback that determines whether the
1618 /// given base class specifier refers to a specific class
1619 /// declaration and describes virtual derivation.
1620 ///
1621 /// This callback can be used with \c lookupInBases() to determine
1622 /// whether a given derived class has is a virtual base class
1623 /// subobject of a particular type. The base record pointer should
1624 /// refer to the canonical CXXRecordDecl of the base class that we
1625 /// are searching for.
1626 static bool FindVirtualBaseClass(const CXXBaseSpecifier *Specifier,
1627 CXXBasePath &Path,
1628 const CXXRecordDecl *BaseRecord);
1629
1630 /// Retrieve the final overriders for each virtual member
1631 /// function in the class hierarchy where this class is the
1632 /// most-derived class in the class hierarchy.
1633 void getFinalOverriders(CXXFinalOverriderMap &FinaOverriders) const;
1634
1635 /// Get the indirect primary bases for this class.
1636 void getIndirectPrimaryBases(CXXIndirectPrimaryBaseSet& Bases) const;
1637
1638 /// Determine whether this class has a member with the given name, possibly
1639 /// in a non-dependent base class.
1640 ///
1641 /// No check for ambiguity is performed, so this should never be used when
1642 /// implementing language semantics, but it may be appropriate for warnings,
1643 /// static analysis, or similar.
1644 bool hasMemberName(DeclarationName N) const;
1645
1646 /// Performs an imprecise lookup of a dependent name in this class.
1647 ///
1648 /// This function does not follow strict semantic rules and should be used
1649 /// only when lookup rules can be relaxed, e.g. indexing.
1650 std::vector<const NamedDecl *>
1651 lookupDependentName(DeclarationName Name,
1652 llvm::function_ref<bool(const NamedDecl *ND)> Filter);
1653
1654 /// Renders and displays an inheritance diagram
1655 /// for this C++ class and all of its base classes (transitively) using
1656 /// GraphViz.
1657 void viewInheritance(ASTContext& Context) const;
1658
1659 /// Calculates the access of a decl that is reached
1660 /// along a path.
1661 static AccessSpecifier MergeAccess(AccessSpecifier PathAccess,
1662 AccessSpecifier DeclAccess) {
1663 assert(DeclAccess != AS_none);
1664 if (DeclAccess == AS_private) return AS_none;
1665 return (PathAccess > DeclAccess ? PathAccess : DeclAccess);
1666 }
1667
1668 /// Indicates that the declaration of a defaulted or deleted special
1669 /// member function is now complete.
1670 void finishedDefaultedOrDeletedMember(CXXMethodDecl *MD);
1671
1672 void setTrivialForCallFlags(CXXMethodDecl *MD);
1673
1674 /// Indicates that the definition of this class is now complete.
1675 void completeDefinition() override;
1676
1677 /// Indicates that the definition of this class is now complete,
1678 /// and provides a final overrider map to help determine
1679 ///
1680 /// \param FinalOverriders The final overrider map for this class, which can
1681 /// be provided as an optimization for abstract-class checking. If NULL,
1682 /// final overriders will be computed if they are needed to complete the
1683 /// definition.
1684 void completeDefinition(CXXFinalOverriderMap *FinalOverriders);
1685
1686 /// Determine whether this class may end up being abstract, even though
1687 /// it is not yet known to be abstract.
1688 ///
1689 /// \returns true if this class is not known to be abstract but has any
1690 /// base classes that are abstract. In this case, \c completeDefinition()
1691 /// will need to compute final overriders to determine whether the class is
1692 /// actually abstract.
1693 bool mayBeAbstract() const;
1694
1695 /// Determine whether it's impossible for a class to be derived from this
1696 /// class. This is best-effort, and may conservatively return false.
1697 bool isEffectivelyFinal() const;
1698
1699 /// If this is the closure type of a lambda expression, retrieve the
1700 /// number to be used for name mangling in the Itanium C++ ABI.
1701 ///
1702 /// Zero indicates that this closure type has internal linkage, so the
1703 /// mangling number does not matter, while a non-zero value indicates which
1704 /// lambda expression this is in this particular context.
1705 unsigned getLambdaManglingNumber() const {
1706 assert(isLambda() && "Not a lambda closure type!");
1707 return getLambdaData().ManglingNumber;
1708 }
1709
1710 /// The lambda is known to has internal linkage no matter whether it has name
1711 /// mangling number.
1712 bool hasKnownLambdaInternalLinkage() const {
1713 assert(isLambda() && "Not a lambda closure type!");
1714 return getLambdaData().HasKnownInternalLinkage;
1715 }
1716
1717 /// Retrieve the declaration that provides additional context for a
1718 /// lambda, when the normal declaration context is not specific enough.
1719 ///
1720 /// Certain contexts (default arguments of in-class function parameters and
1721 /// the initializers of data members) have separate name mangling rules for
1722 /// lambdas within the Itanium C++ ABI. For these cases, this routine provides
1723 /// the declaration in which the lambda occurs, e.g., the function parameter
1724 /// or the non-static data member. Otherwise, it returns NULL to imply that
1725 /// the declaration context suffices.
1726 Decl *getLambdaContextDecl() const;
1727
1728 /// Set the mangling number and context declaration for a lambda
1729 /// class.
1730 void setLambdaMangling(unsigned ManglingNumber, Decl *ContextDecl,
1731 bool HasKnownInternalLinkage = false) {
1732 assert(isLambda() && "Not a lambda closure type!");
1733 getLambdaData().ManglingNumber = ManglingNumber;
1734 getLambdaData().ContextDecl = ContextDecl;
1735 getLambdaData().HasKnownInternalLinkage = HasKnownInternalLinkage;
1736 }
1737
1738 /// Set the device side mangling number.
1739 void setDeviceLambdaManglingNumber(unsigned Num) const;
1740
1741 /// Retrieve the device side mangling number.
1742 unsigned getDeviceLambdaManglingNumber() const;
1743
1744 /// Returns the inheritance model used for this record.
1745 MSInheritanceModel getMSInheritanceModel() const;
1746
1747 /// Calculate what the inheritance model would be for this class.
1748 MSInheritanceModel calculateInheritanceModel() const;
1749
1750 /// In the Microsoft C++ ABI, use zero for the field offset of a null data
1751 /// member pointer if we can guarantee that zero is not a valid field offset,
1752 /// or if the member pointer has multiple fields. Polymorphic classes have a
1753 /// vfptr at offset zero, so we can use zero for null. If there are multiple
1754 /// fields, we can use zero even if it is a valid field offset because
1755 /// null-ness testing will check the other fields.
1756 bool nullFieldOffsetIsZero() const;
1757
1758 /// Controls when vtordisps will be emitted if this record is used as a
1759 /// virtual base.
1760 MSVtorDispMode getMSVtorDispMode() const;
1761
1762 /// Determine whether this lambda expression was known to be dependent
1763 /// at the time it was created, even if its context does not appear to be
1764 /// dependent.
1765 ///
1766 /// This flag is a workaround for an issue with parsing, where default
1767 /// arguments are parsed before their enclosing function declarations have
1768 /// been created. This means that any lambda expressions within those
1769 /// default arguments will have as their DeclContext the context enclosing
1770 /// the function declaration, which may be non-dependent even when the
1771 /// function declaration itself is dependent. This flag indicates when we
1772 /// know that the lambda is dependent despite that.
1773 bool isDependentLambda() const {
1774 return isLambda() && getLambdaData().Dependent;
1775 }
1776
1777 TypeSourceInfo *getLambdaTypeInfo() const {
1778 return getLambdaData().MethodTyInfo;
1779 }
1780
1781 // Determine whether this type is an Interface Like type for
1782 // __interface inheritance purposes.
1783 bool isInterfaceLike() const;
1784
1785 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1786 static bool classofKind(Kind K) {
1787 return K >= firstCXXRecord && K <= lastCXXRecord;
1788 }
1789};
1790
1791/// Store information needed for an explicit specifier.
1792/// Used by CXXDeductionGuideDecl, CXXConstructorDecl and CXXConversionDecl.
1793class ExplicitSpecifier {
1794 llvm::PointerIntPair<Expr *, 2, ExplicitSpecKind> ExplicitSpec{
1795 nullptr, ExplicitSpecKind::ResolvedFalse};
1796
1797public:
1798 ExplicitSpecifier() = default;
1799 ExplicitSpecifier(Expr *Expression, ExplicitSpecKind Kind)
1800 : ExplicitSpec(Expression, Kind) {}
1801 ExplicitSpecKind getKind() const { return ExplicitSpec.getInt(); }
1802 const Expr *getExpr() const { return ExplicitSpec.getPointer(); }
1803 Expr *getExpr() { return ExplicitSpec.getPointer(); }
1804
1805 /// Determine if the declaration had an explicit specifier of any kind.
1806 bool isSpecified() const {
1807 return ExplicitSpec.getInt() != ExplicitSpecKind::ResolvedFalse ||
1808 ExplicitSpec.getPointer();
1809 }
1810
1811 /// Check for equivalence of explicit specifiers.
1812 /// \return true if the explicit specifier are equivalent, false otherwise.
1813 bool isEquivalent(const ExplicitSpecifier Other) const;
1814 /// Determine whether this specifier is known to correspond to an explicit
1815 /// declaration. Returns false if the specifier is absent or has an
1816 /// expression that is value-dependent or evaluates to false.
1817 bool isExplicit() const {
1818 return ExplicitSpec.getInt() == ExplicitSpecKind::ResolvedTrue;
1819 }
1820 /// Determine if the explicit specifier is invalid.
1821 /// This state occurs after a substitution failures.
1822 bool isInvalid() const {
1823 return ExplicitSpec.getInt() == ExplicitSpecKind::Unresolved &&
1824 !ExplicitSpec.getPointer();
1825 }
1826 void setKind(ExplicitSpecKind Kind) { ExplicitSpec.setInt(Kind); }
1827 void setExpr(Expr *E) { ExplicitSpec.setPointer(E); }
1828 // Retrieve the explicit specifier in the given declaration, if any.
1829 static ExplicitSpecifier getFromDecl(FunctionDecl *Function);
1830 static const ExplicitSpecifier getFromDecl(const FunctionDecl *Function) {
1831 return getFromDecl(const_cast<FunctionDecl *>(Function));
1832 }
1833 static ExplicitSpecifier Invalid() {
1834 return ExplicitSpecifier(nullptr, ExplicitSpecKind::Unresolved);
1835 }
1836};
1837
1838/// Represents a C++ deduction guide declaration.
1839///
1840/// \code
1841/// template<typename T> struct A { A(); A(T); };
1842/// A() -> A<int>;
1843/// \endcode
1844///
1845/// In this example, there will be an explicit deduction guide from the
1846/// second line, and implicit deduction guide templates synthesized from
1847/// the constructors of \c A.
1848class CXXDeductionGuideDecl : public FunctionDecl {
1849 void anchor() override;
1850
1851private:
1852 CXXDeductionGuideDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1853 ExplicitSpecifier ES,
1854 const DeclarationNameInfo &NameInfo, QualType T,
1855 TypeSourceInfo *TInfo, SourceLocation EndLocation)
1856 : FunctionDecl(CXXDeductionGuide, C, DC, StartLoc, NameInfo, T, TInfo,
1857 SC_None, false, ConstexprSpecKind::Unspecified),
1858 ExplicitSpec(ES) {
1859 if (EndLocation.isValid())
1860 setRangeEnd(EndLocation);
1861 setIsCopyDeductionCandidate(false);
1862 }
1863
1864 ExplicitSpecifier ExplicitSpec;
1865 void setExplicitSpecifier(ExplicitSpecifier ES) { ExplicitSpec = ES; }
1866
1867public:
1868 friend class ASTDeclReader;
1869 friend class ASTDeclWriter;
1870
1871 static CXXDeductionGuideDecl *
1872 Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1873 ExplicitSpecifier ES, const DeclarationNameInfo &NameInfo, QualType T,
1874 TypeSourceInfo *TInfo, SourceLocation EndLocation);
1875
1876 static CXXDeductionGuideDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1877
1878 ExplicitSpecifier getExplicitSpecifier() { return ExplicitSpec; }
1879 const ExplicitSpecifier getExplicitSpecifier() const { return ExplicitSpec; }
1880
1881 /// Return true if the declartion is already resolved to be explicit.
1882 bool isExplicit() const { return ExplicitSpec.isExplicit(); }
1883
1884 /// Get the template for which this guide performs deduction.
1885 TemplateDecl *getDeducedTemplate() const {
1886 return getDeclName().getCXXDeductionGuideTemplate();
1887 }
1888
1889 void setIsCopyDeductionCandidate(bool isCDC = true) {
1890 FunctionDeclBits.IsCopyDeductionCandidate = isCDC;
1891 }
1892
1893 bool isCopyDeductionCandidate() const {
1894 return FunctionDeclBits.IsCopyDeductionCandidate;
1895 }
1896
1897 // Implement isa/cast/dyncast/etc.
1898 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1899 static bool classofKind(Kind K) { return K == CXXDeductionGuide; }
1900};
1901
1902/// \brief Represents the body of a requires-expression.
1903///
1904/// This decl exists merely to serve as the DeclContext for the local
1905/// parameters of the requires expression as well as other declarations inside
1906/// it.
1907///
1908/// \code
1909/// template<typename T> requires requires (T t) { {t++} -> regular; }
1910/// \endcode
1911///
1912/// In this example, a RequiresExpr object will be generated for the expression,
1913/// and a RequiresExprBodyDecl will be created to hold the parameter t and the
1914/// template argument list imposed by the compound requirement.
1915class RequiresExprBodyDecl : public Decl, public DeclContext {
1916 RequiresExprBodyDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc)
1917 : Decl(RequiresExprBody, DC, StartLoc), DeclContext(RequiresExprBody) {}
1918
1919public:
1920 friend class ASTDeclReader;
1921 friend class ASTDeclWriter;
1922
1923 static RequiresExprBodyDecl *Create(ASTContext &C, DeclContext *DC,
1924 SourceLocation StartLoc);
1925
1926 static RequiresExprBodyDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1927
1928 // Implement isa/cast/dyncast/etc.
1929 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1930 static bool classofKind(Kind K) { return K == RequiresExprBody; }
1931};
1932
1933/// Represents a static or instance method of a struct/union/class.
1934///
1935/// In the terminology of the C++ Standard, these are the (static and
1936/// non-static) member functions, whether virtual or not.
1937class CXXMethodDecl : public FunctionDecl {
1938 void anchor() override;
1939
1940protected:
1941 CXXMethodDecl(Kind DK, ASTContext &C, CXXRecordDecl *RD,
1942 SourceLocation StartLoc, const DeclarationNameInfo &NameInfo,
1943 QualType T, TypeSourceInfo *TInfo, StorageClass SC,
1944 bool isInline, ConstexprSpecKind ConstexprKind,
1945 SourceLocation EndLocation,
1946 Expr *TrailingRequiresClause = nullptr)
1947 : FunctionDecl(DK, C, RD, StartLoc, NameInfo, T, TInfo, SC, isInline,
1948 ConstexprKind, TrailingRequiresClause) {
1949 if (EndLocation.isValid())
1950 setRangeEnd(EndLocation);
1951 }
1952
1953public:
1954 static CXXMethodDecl *Create(ASTContext &C, CXXRecordDecl *RD,
1955 SourceLocation StartLoc,
1956 const DeclarationNameInfo &NameInfo, QualType T,
1957 TypeSourceInfo *TInfo, StorageClass SC,
1958 bool isInline, ConstexprSpecKind ConstexprKind,
1959 SourceLocation EndLocation,
1960 Expr *TrailingRequiresClause = nullptr);
1961
1962 static CXXMethodDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1963
1964 bool isStatic() const;
1965 bool isInstance() const { return !isStatic(); }
1966
1967 /// Returns true if the given operator is implicitly static in a record
1968 /// context.
1969 static bool isStaticOverloadedOperator(OverloadedOperatorKind OOK) {
1970 // [class.free]p1:
1971 // Any allocation function for a class T is a static member
1972 // (even if not explicitly declared static).
1973 // [class.free]p6 Any deallocation function for a class X is a static member
1974 // (even if not explicitly declared static).
1975 return OOK == OO_New || OOK == OO_Array_New || OOK == OO_Delete ||
1976 OOK == OO_Array_Delete;
1977 }
1978
1979 bool isConst() const { return getType()->castAs<FunctionType>()->isConst(); }
1980 bool isVolatile() const { return getType()->castAs<FunctionType>()->isVolatile(); }
1981
1982 bool isVirtual() const {
1983 CXXMethodDecl *CD = const_cast<CXXMethodDecl*>(this)->getCanonicalDecl();
1984
1985 // Member function is virtual if it is marked explicitly so, or if it is
1986 // declared in __interface -- then it is automatically pure virtual.
1987 if (CD->isVirtualAsWritten() || CD->isPure())
1988 return true;
1989
1990 return CD->size_overridden_methods() != 0;
1991 }
1992
1993 /// If it's possible to devirtualize a call to this method, return the called
1994 /// function. Otherwise, return null.
1995
1996 /// \param Base The object on which this virtual function is called.
1997 /// \param IsAppleKext True if we are compiling for Apple kext.
1998 CXXMethodDecl *getDevirtualizedMethod(const Expr *Base, bool IsAppleKext);
1999
2000 const CXXMethodDecl *getDevirtualizedMethod(const Expr *Base,
2001 bool IsAppleKext) const {
2002 return const_cast<CXXMethodDecl *>(this)->getDevirtualizedMethod(
2003 Base, IsAppleKext);
2004 }
2005
2006 /// Determine whether this is a usual deallocation function (C++
2007 /// [basic.stc.dynamic.deallocation]p2), which is an overloaded delete or
2008 /// delete[] operator with a particular signature. Populates \p PreventedBy
2009 /// with the declarations of the functions of the same kind if they were the
2010 /// reason for this function returning false. This is used by
2011 /// Sema::isUsualDeallocationFunction to reconsider the answer based on the
2012 /// context.
2013 bool isUsualDeallocationFunction(
2014 SmallVectorImpl<const FunctionDecl *> &PreventedBy) const;
2015
2016 /// Determine whether this is a copy-assignment operator, regardless
2017 /// of whether it was declared implicitly or explicitly.
2018 bool isCopyAssignmentOperator() const;
2019
2020 /// Determine whether this is a move assignment operator.
2021 bool isMoveAssignmentOperator() const;
2022
2023 CXXMethodDecl *getCanonicalDecl() override {
2024 return cast<CXXMethodDecl>(FunctionDecl::getCanonicalDecl());
2025 }
2026 const CXXMethodDecl *getCanonicalDecl() const {
2027 return const_cast<CXXMethodDecl*>(this)->getCanonicalDecl();
2028 }
2029
2030 CXXMethodDecl *getMostRecentDecl() {
2031 return cast<CXXMethodDecl>(
2032 static_cast<FunctionDecl *>(this)->getMostRecentDecl());
2033 }
2034 const CXXMethodDecl *getMostRecentDecl() const {
2035 return const_cast<CXXMethodDecl*>(this)->getMostRecentDecl();
2036 }
2037
2038 void addOverriddenMethod(const CXXMethodDecl *MD);
2039
2040 using method_iterator = const CXXMethodDecl *const *;
2041
2042 method_iterator begin_overridden_methods() const;
2043 method_iterator end_overridden_methods() const;
2044 unsigned size_overridden_methods() const;
2045
2046 using overridden_method_range = llvm::iterator_range<
2047 llvm::TinyPtrVector<const CXXMethodDecl *>::const_iterator>;
2048
2049 overridden_method_range overridden_methods() const;
2050
2051 /// Return the parent of this method declaration, which
2052 /// is the class in which this method is defined.
2053 const CXXRecordDecl *getParent() const {
2054 return cast<CXXRecordDecl>(FunctionDecl::getParent());
2055 }
2056
2057 /// Return the parent of this method declaration, which
2058 /// is the class in which this method is defined.
2059 CXXRecordDecl *getParent() {
2060 return const_cast<CXXRecordDecl *>(
2061 cast<CXXRecordDecl>(FunctionDecl::getParent()));
2062 }
2063
2064 /// Return the type of the \c this pointer.
2065 ///
2066 /// Should only be called for instance (i.e., non-static) methods. Note
2067 /// that for the call operator of a lambda closure type, this returns the
2068 /// desugared 'this' type (a pointer to the closure type), not the captured
2069 /// 'this' type.
2070 QualType getThisType() const;
2071
2072 /// Return the type of the object pointed by \c this.
2073 ///
2074 /// See getThisType() for usage restriction.
2075 QualType getThisObjectType() const;
2076
2077 static QualType getThisType(const FunctionProtoType *FPT,
2078 const CXXRecordDecl *Decl);
2079
2080 static QualType getThisObjectType(const FunctionProtoType *FPT,
2081 const CXXRecordDecl *Decl);
2082
2083 Qualifiers getMethodQualifiers() const {
2084 return getType()->castAs<FunctionProtoType>()->getMethodQuals();
2085 }
2086
2087 /// Retrieve the ref-qualifier associated with this method.
2088 ///
2089 /// In the following example, \c f() has an lvalue ref-qualifier, \c g()
2090 /// has an rvalue ref-qualifier, and \c h() has no ref-qualifier.
2091 /// @code
2092 /// struct X {
2093 /// void f() &;
2094 /// void g() &&;
2095 /// void h();
2096 /// };
2097 /// @endcode
2098 RefQualifierKind getRefQualifier() const {
2099 return getType()->castAs<FunctionProtoType>()->getRefQualifier();
2100 }
2101
2102 bool hasInlineBody() const;
2103
2104 /// Determine whether this is a lambda closure type's static member
2105 /// function that is used for the result of the lambda's conversion to
2106 /// function pointer (for a lambda with no captures).
2107 ///
2108 /// The function itself, if used, will have a placeholder body that will be
2109 /// supplied by IR generation to either forward to the function call operator
2110 /// or clone the function call operator.
2111 bool isLambdaStaticInvoker() const;
2112
2113 /// Find the method in \p RD that corresponds to this one.
2114 ///
2115 /// Find if \p RD or one of the classes it inherits from override this method.
2116 /// If so, return it. \p RD is assumed to be a subclass of the class defining
2117 /// this method (or be the class itself), unless \p MayBeBase is set to true.
2118 CXXMethodDecl *
2119 getCorrespondingMethodInClass(const CXXRecordDecl *RD,
2120 bool MayBeBase = false);
2121
2122 const CXXMethodDecl *
2123 getCorrespondingMethodInClass(const CXXRecordDecl *RD,
2124 bool MayBeBase = false) const {
2125 return const_cast<CXXMethodDecl *>(this)
2126 ->getCorrespondingMethodInClass(RD, MayBeBase);
2127 }
2128
2129 /// Find if \p RD declares a function that overrides this function, and if so,
2130 /// return it. Does not search base classes.
2131 CXXMethodDecl *getCorrespondingMethodDeclaredInClass(const CXXRecordDecl *RD,
2132 bool MayBeBase = false);
2133 const CXXMethodDecl *
2134 getCorrespondingMethodDeclaredInClass(const CXXRecordDecl *RD,
2135 bool MayBeBase = false) const {
2136 return const_cast<CXXMethodDecl *>(this)
2137 ->getCorrespondingMethodDeclaredInClass(RD, MayBeBase);
2138 }
2139
2140 // Implement isa/cast/dyncast/etc.
2141 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2142 static bool classofKind(Kind K) {
2143 return K >= firstCXXMethod && K <= lastCXXMethod;
2144 }
2145};
2146
2147/// Represents a C++ base or member initializer.
2148///
2149/// This is part of a constructor initializer that
2150/// initializes one non-static member variable or one base class. For
2151/// example, in the following, both 'A(a)' and 'f(3.14159)' are member
2152/// initializers:
2153///
2154/// \code
2155/// class A { };
2156/// class B : public A {
2157/// float f;
2158/// public:
2159/// B(A& a) : A(a), f(3.14159) { }
2160/// };
2161/// \endcode
2162class CXXCtorInitializer final {
2163 /// Either the base class name/delegating constructor type (stored as
2164 /// a TypeSourceInfo*), an normal field (FieldDecl), or an anonymous field
2165 /// (IndirectFieldDecl*) being initialized.
2166 llvm::PointerUnion<TypeSourceInfo *, FieldDecl *, IndirectFieldDecl *>
2167 Initializee;
2168
2169 /// The argument used to initialize the base or member, which may
2170 /// end up constructing an object (when multiple arguments are involved).
2171 Stmt *Init;
2172
2173 /// The source location for the field name or, for a base initializer
2174 /// pack expansion, the location of the ellipsis.
2175 ///
2176 /// In the case of a delegating
2177 /// constructor, it will still include the type's source location as the
2178 /// Initializee points to the CXXConstructorDecl (to allow loop detection).
2179 SourceLocation MemberOrEllipsisLocation;
2180
2181 /// Location of the left paren of the ctor-initializer.
2182 SourceLocation LParenLoc;
2183
2184 /// Location of the right paren of the ctor-initializer.
2185 SourceLocation RParenLoc;
2186
2187 /// If the initializee is a type, whether that type makes this
2188 /// a delegating initialization.
2189 unsigned IsDelegating : 1;
2190
2191 /// If the initializer is a base initializer, this keeps track
2192 /// of whether the base is virtual or not.
2193 unsigned IsVirtual : 1;
2194
2195 /// Whether or not the initializer is explicitly written
2196 /// in the sources.
2197 unsigned IsWritten : 1;
2198
2199 /// If IsWritten is true, then this number keeps track of the textual order
2200 /// of this initializer in the original sources, counting from 0.
2201 unsigned SourceOrder : 13;
2202
2203public:
2204 /// Creates a new base-class initializer.
2205 explicit
2206 CXXCtorInitializer(ASTContext &Context, TypeSourceInfo *TInfo, bool IsVirtual,
2207 SourceLocation L, Expr *Init, SourceLocation R,
2208 SourceLocation EllipsisLoc);
2209
2210 /// Creates a new member initializer.
2211 explicit
2212 CXXCtorInitializer(ASTContext &Context, FieldDecl *Member,
2213 SourceLocation MemberLoc, SourceLocation L, Expr *Init,
2214 SourceLocation R);
2215
2216 /// Creates a new anonymous field initializer.
2217 explicit
2218 CXXCtorInitializer(ASTContext &Context, IndirectFieldDecl *Member,
2219 SourceLocation MemberLoc, SourceLocation L, Expr *Init,
2220 SourceLocation R);
2221
2222 /// Creates a new delegating initializer.
2223 explicit
2224 CXXCtorInitializer(ASTContext &Context, TypeSourceInfo *TInfo,
2225 SourceLocation L, Expr *Init, SourceLocation R);
2226
2227 /// \return Unique reproducible object identifier.
2228 int64_t getID(const ASTContext &Context) const;
2229
2230 /// Determine whether this initializer is initializing a base class.
2231 bool isBaseInitializer() const {
2232 return Initializee.is<TypeSourceInfo*>() && !IsDelegating;
2233 }
2234
2235 /// Determine whether this initializer is initializing a non-static
2236 /// data member.
2237 bool isMemberInitializer() const { return Initializee.is<FieldDecl*>(); }
2238
2239 bool isAnyMemberInitializer() const {
2240 return isMemberInitializer() || isIndirectMemberInitializer();
2241 }
2242
2243 bool isIndirectMemberInitializer() const {
2244 return Initializee.is<IndirectFieldDecl*>();
2245 }
2246
2247 /// Determine whether this initializer is an implicit initializer
2248 /// generated for a field with an initializer defined on the member
2249 /// declaration.
2250 ///
2251 /// In-class member initializers (also known as "non-static data member
2252 /// initializations", NSDMIs) were introduced in C++11.
2253 bool isInClassMemberInitializer() const {
2254 return Init->getStmtClass() == Stmt::CXXDefaultInitExprClass;
2255 }
2256
2257 /// Determine whether this initializer is creating a delegating
2258 /// constructor.
2259 bool isDelegatingInitializer() const {
2260 return Initializee.is<TypeSourceInfo*>() && IsDelegating;
2261 }
2262
2263 /// Determine whether this initializer is a pack expansion.
2264 bool isPackExpansion() const {
2265 return isBaseInitializer() && MemberOrEllipsisLocation.isValid();
2266 }
2267
2268 // For a pack expansion, returns the location of the ellipsis.
2269 SourceLocation getEllipsisLoc() const {
2270 if (!isPackExpansion())
2271 return {};
2272 return MemberOrEllipsisLocation;
2273 }
2274
2275 /// If this is a base class initializer, returns the type of the
2276 /// base class with location information. Otherwise, returns an NULL
2277 /// type location.
2278 TypeLoc getBaseClassLoc() const;
2279
2280 /// If this is a base class initializer, returns the type of the base class.
2281 /// Otherwise, returns null.
2282 const Type *getBaseClass() const;
2283
2284 /// Returns whether the base is virtual or not.
2285 bool isBaseVirtual() const {
2286 assert(isBaseInitializer() && "Must call this on base initializer!");
2287
2288 return IsVirtual;
2289 }
2290
2291 /// Returns the declarator information for a base class or delegating
2292 /// initializer.
2293 TypeSourceInfo *getTypeSourceInfo() const {
2294 return Initializee.dyn_cast<TypeSourceInfo *>();
2295 }
2296
2297 /// If this is a member initializer, returns the declaration of the
2298 /// non-static data member being initialized. Otherwise, returns null.
2299 FieldDecl *getMember() const {
2300 if (isMemberInitializer())
2301 return Initializee.get<FieldDecl*>();
2302 return nullptr;
2303 }
2304
2305 FieldDecl *getAnyMember() const {
2306 if (isMemberInitializer())
2307 return Initializee.get<FieldDecl*>();
2308 if (isIndirectMemberInitializer())
2309 return Initializee.get<IndirectFieldDecl*>()->getAnonField();
2310 return nullptr;
2311 }
2312
2313 IndirectFieldDecl *getIndirectMember() const {
2314 if (isIndirectMemberInitializer())
2315 return Initializee.get<IndirectFieldDecl*>();
2316 return nullptr;
2317 }
2318
2319 SourceLocation getMemberLocation() const {
2320 return MemberOrEllipsisLocation;
2321 }
2322
2323 /// Determine the source location of the initializer.
2324 SourceLocation getSourceLocation() const;
2325
2326 /// Determine the source range covering the entire initializer.
2327 SourceRange getSourceRange() const LLVM_READONLY;
2328
2329 /// Determine whether this initializer is explicitly written
2330 /// in the source code.
2331 bool isWritten() const { return IsWritten; }
2332
2333 /// Return the source position of the initializer, counting from 0.
2334 /// If the initializer was implicit, -1 is returned.
2335 int getSourceOrder() const {
2336 return IsWritten ? static_cast<int>(SourceOrder) : -1;
2337 }
2338
2339 /// Set the source order of this initializer.
2340 ///
2341 /// This can only be called once for each initializer; it cannot be called
2342 /// on an initializer having a positive number of (implicit) array indices.
2343 ///
2344 /// This assumes that the initializer was written in the source code, and
2345 /// ensures that isWritten() returns true.
2346 void setSourceOrder(int Pos) {
2347 assert(!IsWritten &&
2348 "setSourceOrder() used on implicit initializer");
2349 assert(SourceOrder == 0 &&
2350 "calling twice setSourceOrder() on the same initializer");
2351 assert(Pos >= 0 &&
2352 "setSourceOrder() used to make an initializer implicit");
2353 IsWritten = true;
2354 SourceOrder = static_cast<unsigned>(Pos);
2355 }
2356
2357 SourceLocation getLParenLoc() const { return LParenLoc; }
2358 SourceLocation getRParenLoc() const { return RParenLoc; }
2359
2360 /// Get the initializer.
2361 Expr *getInit() const { return static_cast<Expr *>(Init); }
2362};
2363
2364/// Description of a constructor that was inherited from a base class.
2365class InheritedConstructor {
2366 ConstructorUsingShadowDecl *Shadow = nullptr;
2367 CXXConstructorDecl *BaseCtor = nullptr;
2368
2369public:
2370 InheritedConstructor() = default;
2371 InheritedConstructor(ConstructorUsingShadowDecl *Shadow,
2372 CXXConstructorDecl *BaseCtor)
2373 : Shadow(Shadow), BaseCtor(BaseCtor) {}
2374
2375 explicit operator bool() const { return Shadow; }
2376
2377 ConstructorUsingShadowDecl *getShadowDecl() const { return Shadow; }
2378 CXXConstructorDecl *getConstructor() const { return BaseCtor; }
2379};
2380
2381/// Represents a C++ constructor within a class.
2382///
2383/// For example:
2384///
2385/// \code
2386/// class X {
2387/// public:
2388/// explicit X(int); // represented by a CXXConstructorDecl.
2389/// };
2390/// \endcode
2391class CXXConstructorDecl final
2392 : public CXXMethodDecl,
2393 private llvm::TrailingObjects<CXXConstructorDecl, InheritedConstructor,
2394 ExplicitSpecifier> {
2395 // This class stores some data in DeclContext::CXXConstructorDeclBits
2396 // to save some space. Use the provided accessors to access it.
2397
2398 /// \name Support for base and member initializers.
2399 /// \{
2400 /// The arguments used to initialize the base or member.
2401 LazyCXXCtorInitializersPtr CtorInitializers;
2402
2403 CXXConstructorDecl(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2404 const DeclarationNameInfo &NameInfo, QualType T,
2405 TypeSourceInfo *TInfo, ExplicitSpecifier ES, bool isInline,
2406 bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind,
2407 InheritedConstructor Inherited,
2408 Expr *TrailingRequiresClause);
2409
2410 void anchor() override;
2411
2412 size_t numTrailingObjects(OverloadToken<InheritedConstructor>) const {
2413 return CXXConstructorDeclBits.IsInheritingConstructor;
2414 }
2415 size_t numTrailingObjects(OverloadToken<ExplicitSpecifier>) const {
2416 return CXXConstructorDeclBits.HasTrailingExplicitSpecifier;
2417 }
2418
2419 ExplicitSpecifier getExplicitSpecifierInternal() const {
2420 if (CXXConstructorDeclBits.HasTrailingExplicitSpecifier)
2421 return *getTrailingObjects<ExplicitSpecifier>();
2422 return ExplicitSpecifier(
2423 nullptr, CXXConstructorDeclBits.IsSimpleExplicit
2424 ? ExplicitSpecKind::ResolvedTrue
2425 : ExplicitSpecKind::ResolvedFalse);
2426 }
2427
2428 enum TrailingAllocKind {
2429 TAKInheritsConstructor = 1,
2430 TAKHasTailExplicit = 1 << 1,
2431 };
2432
2433 uint64_t getTrailingAllocKind() const {
2434 return numTrailingObjects(OverloadToken<InheritedConstructor>()) |
2435 (numTrailingObjects(OverloadToken<ExplicitSpecifier>()) << 1);
2436 }
2437
2438public:
2439 friend class ASTDeclReader;
2440 friend class ASTDeclWriter;
2441 friend TrailingObjects;
2442
2443 static CXXConstructorDecl *CreateDeserialized(ASTContext &C, unsigned ID,
2444 uint64_t AllocKind);
2445 static CXXConstructorDecl *
2446 Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2447 const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo,
2448 ExplicitSpecifier ES, bool isInline, bool isImplicitlyDeclared,
2449 ConstexprSpecKind ConstexprKind,
2450 InheritedConstructor Inherited = InheritedConstructor(),
2451 Expr *TrailingRequiresClause = nullptr);
2452
2453 void setExplicitSpecifier(ExplicitSpecifier ES) {
2454 assert((!ES.getExpr() ||
2455 CXXConstructorDeclBits.HasTrailingExplicitSpecifier) &&
2456 "cannot set this explicit specifier. no trail-allocated space for "
2457 "explicit");
2458 if (ES.getExpr())
2459 *getCanonicalDecl()->getTrailingObjects<ExplicitSpecifier>() = ES;
2460 else
2461 CXXConstructorDeclBits.IsSimpleExplicit = ES.isExplicit();
2462 }
2463
2464 ExplicitSpecifier getExplicitSpecifier() {
2465 return getCanonicalDecl()->getExplicitSpecifierInternal();
2466 }
2467 const ExplicitSpecifier getExplicitSpecifier() const {
2468 return getCanonicalDecl()->getExplicitSpecifierInternal();
2469 }
2470
2471 /// Return true if the declartion is already resolved to be explicit.
2472 bool isExplicit() const { return getExplicitSpecifier().isExplicit(); }
2473
2474 /// Iterates through the member/base initializer list.
2475 using init_iterator = CXXCtorInitializer **;
2476
2477 /// Iterates through the member/base initializer list.
2478 using init_const_iterator = CXXCtorInitializer *const *;
2479
2480 using init_range = llvm::iterator_range<init_iterator>;
2481 using init_const_range = llvm::iterator_range<init_const_iterator>;
2482
2483 init_range inits() { return init_range(init_begin(), init_end()); }
2484 init_const_range inits() const {
2485 return init_const_range(init_begin(), init_end());
2486 }
2487
2488 /// Retrieve an iterator to the first initializer.
2489 init_iterator init_begin() {
2490 const auto *ConstThis = this;
2491 return const_cast<init_iterator>(ConstThis->init_begin());
2492 }
2493
2494 /// Retrieve an iterator to the first initializer.
2495 init_const_iterator init_begin() const;
2496
2497 /// Retrieve an iterator past the last initializer.
2498 init_iterator init_end() {
2499 return init_begin() + getNumCtorInitializers();
2500 }
2501
2502 /// Retrieve an iterator past the last initializer.
2503 init_const_iterator init_end() const {
2504 return init_begin() + getNumCtorInitializers();
2505 }
2506
2507 using init_reverse_iterator = std::reverse_iterator<init_iterator>;
2508 using init_const_reverse_iterator =
2509 std::reverse_iterator<init_const_iterator>;
2510
2511 init_reverse_iterator init_rbegin() {
2512 return init_reverse_iterator(init_end());
2513 }
2514 init_const_reverse_iterator init_rbegin() const {
2515 return init_const_reverse_iterator(init_end());
2516 }
2517
2518 init_reverse_iterator init_rend() {
2519 return init_reverse_iterator(init_begin());
2520 }
2521 init_const_reverse_iterator init_rend() const {
2522 return init_const_reverse_iterator(init_begin());
2523 }
2524
2525 /// Determine the number of arguments used to initialize the member
2526 /// or base.
2527 unsigned getNumCtorInitializers() const {
2528 return CXXConstructorDeclBits.NumCtorInitializers;
2529 }
2530
2531 void setNumCtorInitializers(unsigned numCtorInitializers) {
2532 CXXConstructorDeclBits.NumCtorInitializers = numCtorInitializers;
2533 // This assert added because NumCtorInitializers is stored
2534 // in CXXConstructorDeclBits as a bitfield and its width has
2535 // been shrunk from 32 bits to fit into CXXConstructorDeclBitfields.
2536 assert(CXXConstructorDeclBits.NumCtorInitializers ==
2537 numCtorInitializers && "NumCtorInitializers overflow!");
2538 }
2539
2540 void setCtorInitializers(CXXCtorInitializer **Initializers) {
2541 CtorInitializers = Initializers;
2542 }
2543
2544 /// Determine whether this constructor is a delegating constructor.
2545 bool isDelegatingConstructor() const {
2546 return (getNumCtorInitializers() == 1) &&
2547 init_begin()[0]->isDelegatingInitializer();
2548 }
2549
2550 /// When this constructor delegates to another, retrieve the target.
2551 CXXConstructorDecl *getTargetConstructor() const;
2552
2553 /// Whether this constructor is a default
2554 /// constructor (C++ [class.ctor]p5), which can be used to
2555 /// default-initialize a class of this type.
2556 bool isDefaultConstructor() const;
2557
2558 /// Whether this constructor is a copy constructor (C++ [class.copy]p2,
2559 /// which can be used to copy the class.
2560 ///
2561 /// \p TypeQuals will be set to the qualifiers on the
2562 /// argument type. For example, \p TypeQuals would be set to \c
2563 /// Qualifiers::Const for the following copy constructor:
2564 ///
2565 /// \code
2566 /// class X {
2567 /// public:
2568 /// X(const X&);
2569 /// };
2570 /// \endcode
2571 bool isCopyConstructor(unsigned &TypeQuals) const;
2572
2573 /// Whether this constructor is a copy
2574 /// constructor (C++ [class.copy]p2, which can be used to copy the
2575 /// class.
2576 bool isCopyConstructor() const {
2577 unsigned TypeQuals = 0;
2578 return isCopyConstructor(TypeQuals);
2579 }
2580
2581 /// Determine whether this constructor is a move constructor
2582 /// (C++11 [class.copy]p3), which can be used to move values of the class.
2583 ///
2584 /// \param TypeQuals If this constructor is a move constructor, will be set
2585 /// to the type qualifiers on the referent of the first parameter's type.
2586 bool isMoveConstructor(unsigned &TypeQuals) const;
2587
2588 /// Determine whether this constructor is a move constructor
2589 /// (C++11 [class.copy]p3), which can be used to move values of the class.
2590 bool isMoveConstructor() const {
2591 unsigned TypeQuals = 0;
2592 return isMoveConstructor(TypeQuals);
2593 }
2594
2595 /// Determine whether this is a copy or move constructor.
2596 ///
2597 /// \param TypeQuals Will be set to the type qualifiers on the reference
2598 /// parameter, if in fact this is a copy or move constructor.
2599 bool isCopyOrMoveConstructor(unsigned &TypeQuals) const;
2600
2601 /// Determine whether this a copy or move constructor.
2602 bool isCopyOrMoveConstructor() const {
2603 unsigned Quals;
2604 return isCopyOrMoveConstructor(Quals);
2605 }
2606
2607 /// Whether this constructor is a
2608 /// converting constructor (C++ [class.conv.ctor]), which can be
2609 /// used for user-defined conversions.
2610 bool isConvertingConstructor(bool AllowExplicit) const;
2611
2612 /// Determine whether this is a member template specialization that
2613 /// would copy the object to itself. Such constructors are never used to copy
2614 /// an object.
2615 bool isSpecializationCopyingObject() const;
2616
2617 /// Determine whether this is an implicit constructor synthesized to
2618 /// model a call to a constructor inherited from a base class.
2619 bool isInheritingConstructor() const {
2620 return CXXConstructorDeclBits.IsInheritingConstructor;
2621 }
2622
2623 /// State that this is an implicit constructor synthesized to
2624 /// model a call to a constructor inherited from a base class.
2625 void setInheritingConstructor(bool isIC = true) {
2626 CXXConstructorDeclBits.IsInheritingConstructor = isIC;
2627 }
2628
2629 /// Get the constructor that this inheriting constructor is based on.
2630 InheritedConstructor getInheritedConstructor() const {
2631 return isInheritingConstructor() ?
2632 *getTrailingObjects<InheritedConstructor>() : InheritedConstructor();
2633 }
2634
2635 CXXConstructorDecl *getCanonicalDecl() override {
2636 return cast<CXXConstructorDecl>(FunctionDecl::getCanonicalDecl());
2637 }
2638 const CXXConstructorDecl *getCanonicalDecl() const {
2639 return const_cast<CXXConstructorDecl*>(this)->getCanonicalDecl();
2640 }
2641
2642 // Implement isa/cast/dyncast/etc.
2643 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2644 static bool classofKind(Kind K) { return K == CXXConstructor; }
2645};
2646
2647/// Represents a C++ destructor within a class.
2648///
2649/// For example:
2650///
2651/// \code
2652/// class X {
2653/// public:
2654/// ~X(); // represented by a CXXDestructorDecl.
2655/// };
2656/// \endcode
2657class CXXDestructorDecl : public CXXMethodDecl {
2658 friend class ASTDeclReader;
2659 friend class ASTDeclWriter;
2660
2661 // FIXME: Don't allocate storage for these except in the first declaration
2662 // of a virtual destructor.
2663 FunctionDecl *OperatorDelete = nullptr;
2664 Expr *OperatorDeleteThisArg = nullptr;
2665
2666 CXXDestructorDecl(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2667 const DeclarationNameInfo &NameInfo, QualType T,
2668 TypeSourceInfo *TInfo, bool isInline,
2669 bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind,
2670 Expr *TrailingRequiresClause = nullptr)
2671 : CXXMethodDecl(CXXDestructor, C, RD, StartLoc, NameInfo, T, TInfo,
2672 SC_None, isInline, ConstexprKind, SourceLocation(),
2673 TrailingRequiresClause) {
2674 setImplicit(isImplicitlyDeclared);
2675 }
2676
2677 void anchor() override;
2678
2679public:
2680 static CXXDestructorDecl *Create(ASTContext &C, CXXRecordDecl *RD,
2681 SourceLocation StartLoc,
2682 const DeclarationNameInfo &NameInfo,
2683 QualType T, TypeSourceInfo *TInfo,
2684 bool isInline, bool isImplicitlyDeclared,
2685 ConstexprSpecKind ConstexprKind,
2686 Expr *TrailingRequiresClause = nullptr);
2687 static CXXDestructorDecl *CreateDeserialized(ASTContext & C, unsigned ID);
2688
2689 void setOperatorDelete(FunctionDecl *OD, Expr *ThisArg);
2690
2691 const FunctionDecl *getOperatorDelete() const {
2692 return getCanonicalDecl()->OperatorDelete;
2693 }
2694
2695 Expr *getOperatorDeleteThisArg() const {
2696 return getCanonicalDecl()->OperatorDeleteThisArg;
2697 }
2698
2699 CXXDestructorDecl *getCanonicalDecl() override {
2700 return cast<CXXDestructorDecl>(FunctionDecl::getCanonicalDecl());
2701 }
2702 const CXXDestructorDecl *getCanonicalDecl() const {
2703 return const_cast<CXXDestructorDecl*>(this)->getCanonicalDecl();
2704 }
2705
2706 // Implement isa/cast/dyncast/etc.
2707 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2708 static bool classofKind(Kind K) { return K == CXXDestructor; }
2709};
2710
2711/// Represents a C++ conversion function within a class.
2712///
2713/// For example:
2714///
2715/// \code
2716/// class X {
2717/// public:
2718/// operator bool();
2719/// };
2720/// \endcode
2721class CXXConversionDecl : public CXXMethodDecl {
2722 CXXConversionDecl(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2723 const DeclarationNameInfo &NameInfo, QualType T,
2724 TypeSourceInfo *TInfo, bool isInline, ExplicitSpecifier ES,
2725 ConstexprSpecKind ConstexprKind, SourceLocation EndLocation,
2726 Expr *TrailingRequiresClause = nullptr)
2727 : CXXMethodDecl(CXXConversion, C, RD, StartLoc, NameInfo, T, TInfo,
2728 SC_None, isInline, ConstexprKind, EndLocation,
2729 TrailingRequiresClause),
2730 ExplicitSpec(ES) {}
2731 void anchor() override;
2732
2733 ExplicitSpecifier ExplicitSpec;
2734
2735public:
2736 friend class ASTDeclReader;
2737 friend class ASTDeclWriter;
2738
2739 static CXXConversionDecl *
2740 Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2741 const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo,
2742 bool isInline, ExplicitSpecifier ES, ConstexprSpecKind ConstexprKind,
2743 SourceLocation EndLocation, Expr *TrailingRequiresClause = nullptr);
2744 static CXXConversionDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2745
2746 ExplicitSpecifier getExplicitSpecifier() {
2747 return getCanonicalDecl()->ExplicitSpec;
2748 }
2749
2750 const ExplicitSpecifier getExplicitSpecifier() const {
2751 return getCanonicalDecl()->ExplicitSpec;
2752 }
2753
2754 /// Return true if the declartion is already resolved to be explicit.
2755 bool isExplicit() const { return getExplicitSpecifier().isExplicit(); }
2756 void setExplicitSpecifier(ExplicitSpecifier ES) { ExplicitSpec = ES; }
2757
2758 /// Returns the type that this conversion function is converting to.
2759 QualType getConversionType() const {
2760 return getType()->castAs<FunctionType>()->getReturnType();
2761 }
2762
2763 /// Determine whether this conversion function is a conversion from
2764 /// a lambda closure type to a block pointer.
2765 bool isLambdaToBlockPointerConversion() const;
2766
2767 CXXConversionDecl *getCanonicalDecl() override {
2768 return cast<CXXConversionDecl>(FunctionDecl::getCanonicalDecl());
2769 }
2770 const CXXConversionDecl *getCanonicalDecl() const {
2771 return const_cast<CXXConversionDecl*>(this)->getCanonicalDecl();
2772 }
2773
2774 // Implement isa/cast/dyncast/etc.
2775 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2776 static bool classofKind(Kind K) { return K == CXXConversion; }
2777};
2778
2779/// Represents a linkage specification.
2780///
2781/// For example:
2782/// \code
2783/// extern "C" void foo();
2784/// \endcode
2785class LinkageSpecDecl : public Decl, public DeclContext {
2786 virtual void anchor();
2787 // This class stores some data in DeclContext::LinkageSpecDeclBits to save
2788 // some space. Use the provided accessors to access it.
2789public:
2790 /// Represents the language in a linkage specification.
2791 ///
2792 /// The values are part of the serialization ABI for
2793 /// ASTs and cannot be changed without altering that ABI.
2794 enum LanguageIDs { lang_c = 1, lang_cxx = 2 };
2795
2796private:
2797 /// The source location for the extern keyword.
2798 SourceLocation ExternLoc;
2799
2800 /// The source location for the right brace (if valid).
2801 SourceLocation RBraceLoc;
2802
2803 LinkageSpecDecl(DeclContext *DC, SourceLocation ExternLoc,
2804 SourceLocation LangLoc, LanguageIDs lang, bool HasBraces);
2805
2806public:
2807 static LinkageSpecDecl *Create(ASTContext &C, DeclContext *DC,
2808 SourceLocation ExternLoc,
2809 SourceLocation LangLoc, LanguageIDs Lang,
2810 bool HasBraces);
2811 static LinkageSpecDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2812
2813 /// Return the language specified by this linkage specification.
2814 LanguageIDs getLanguage() const {
2815 return static_cast<LanguageIDs>(LinkageSpecDeclBits.Language);
2816 }
2817
2818 /// Set the language specified by this linkage specification.
2819 void setLanguage(LanguageIDs L) { LinkageSpecDeclBits.Language = L; }
2820
2821 /// Determines whether this linkage specification had braces in
2822 /// its syntactic form.
2823 bool hasBraces() const {
2824 assert(!RBraceLoc.isValid() || LinkageSpecDeclBits.HasBraces);
2825 return LinkageSpecDeclBits.HasBraces;
2826 }
2827
2828 SourceLocation getExternLoc() const { return ExternLoc; }
2829 SourceLocation getRBraceLoc() const { return RBraceLoc; }
2830 void setExternLoc(SourceLocation L) { ExternLoc = L; }
2831 void setRBraceLoc(SourceLocation L) {
2832 RBraceLoc = L;
2833 LinkageSpecDeclBits.HasBraces = RBraceLoc.isValid();
2834 }
2835
2836 SourceLocation getEndLoc() const LLVM_READONLY {
2837 if (hasBraces())
2838 return getRBraceLoc();
2839 // No braces: get the end location of the (only) declaration in context
2840 // (if present).
2841 return decls_empty() ? getLocation() : decls_begin()->getEndLoc();
2842 }
2843
2844 SourceRange getSourceRange() const override LLVM_READONLY {
2845 return SourceRange(ExternLoc, getEndLoc());
2846 }
2847
2848 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2849 static bool classofKind(Kind K) { return K == LinkageSpec; }
2850
2851 static DeclContext *castToDeclContext(const LinkageSpecDecl *D) {
2852 return static_cast<DeclContext *>(const_cast<LinkageSpecDecl*>(D));
2853 }
2854
2855 static LinkageSpecDecl *castFromDeclContext(const DeclContext *DC) {
2856 return static_cast<LinkageSpecDecl *>(const_cast<DeclContext*>(DC));
2857 }
2858};
2859
2860/// Represents C++ using-directive.
2861///
2862/// For example:
2863/// \code
2864/// using namespace std;
2865/// \endcode
2866///
2867/// \note UsingDirectiveDecl should be Decl not NamedDecl, but we provide
2868/// artificial names for all using-directives in order to store
2869/// them in DeclContext effectively.
2870class UsingDirectiveDecl : public NamedDecl {
2871 /// The location of the \c using keyword.
2872 SourceLocation UsingLoc;
2873
2874 /// The location of the \c namespace keyword.
2875 SourceLocation NamespaceLoc;
2876
2877 /// The nested-name-specifier that precedes the namespace.
2878 NestedNameSpecifierLoc QualifierLoc;
2879
2880 /// The namespace nominated by this using-directive.
2881 NamedDecl *NominatedNamespace;
2882
2883 /// Enclosing context containing both using-directive and nominated
2884 /// namespace.
2885 DeclContext *CommonAncestor;
2886
2887 UsingDirectiveDecl(DeclContext *DC, SourceLocation UsingLoc,
2888 SourceLocation NamespcLoc,
2889 NestedNameSpecifierLoc QualifierLoc,
2890 SourceLocation IdentLoc,
2891 NamedDecl *Nominated,
2892 DeclContext *CommonAncestor)
2893 : NamedDecl(UsingDirective, DC, IdentLoc, getName()), UsingLoc(UsingLoc),
2894 NamespaceLoc(NamespcLoc), QualifierLoc(QualifierLoc),
2895 NominatedNamespace(Nominated), CommonAncestor(CommonAncestor) {}
2896
2897 /// Returns special DeclarationName used by using-directives.
2898 ///
2899 /// This is only used by DeclContext for storing UsingDirectiveDecls in
2900 /// its lookup structure.
2901 static DeclarationName getName() {
2902 return DeclarationName::getUsingDirectiveName();
2903 }
2904
2905 void anchor() override;
2906
2907public:
2908 friend class ASTDeclReader;
2909
2910 // Friend for getUsingDirectiveName.
2911 friend class DeclContext;
2912
2913 /// Retrieve the nested-name-specifier that qualifies the
2914 /// name of the namespace, with source-location information.
2915 NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
2916
2917 /// Retrieve the nested-name-specifier that qualifies the
2918 /// name of the namespace.
2919 NestedNameSpecifier *getQualifier() const {
2920 return QualifierLoc.getNestedNameSpecifier();
2921 }
2922
2923 NamedDecl *getNominatedNamespaceAsWritten() { return NominatedNamespace; }
2924 const NamedDecl *getNominatedNamespaceAsWritten() const {
2925 return NominatedNamespace;
2926 }
2927
2928 /// Returns the namespace nominated by this using-directive.
2929 NamespaceDecl *getNominatedNamespace();
2930
2931 const NamespaceDecl *getNominatedNamespace() const {
2932 return const_cast<UsingDirectiveDecl*>(this)->getNominatedNamespace();
2933 }
2934
2935 /// Returns the common ancestor context of this using-directive and
2936 /// its nominated namespace.
2937 DeclContext *getCommonAncestor() { return CommonAncestor; }
2938 const DeclContext *getCommonAncestor() const { return CommonAncestor; }
2939
2940 /// Return the location of the \c using keyword.
2941 SourceLocation getUsingLoc() const { return UsingLoc; }
2942
2943 // FIXME: Could omit 'Key' in name.
2944 /// Returns the location of the \c namespace keyword.
2945 SourceLocation getNamespaceKeyLocation() const { return NamespaceLoc; }
2946
2947 /// Returns the location of this using declaration's identifier.
2948 SourceLocation getIdentLocation() const { return getLocation(); }
2949
2950 static UsingDirectiveDecl *Create(ASTContext &C, DeclContext *DC,
2951 SourceLocation UsingLoc,
2952 SourceLocation NamespaceLoc,
2953 NestedNameSpecifierLoc QualifierLoc,
2954 SourceLocation IdentLoc,
2955 NamedDecl *Nominated,
2956 DeclContext *CommonAncestor);
2957 static UsingDirectiveDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2958
2959 SourceRange getSourceRange() const override LLVM_READONLY {
2960 return SourceRange(UsingLoc, getLocation());
2961 }
2962
2963 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2964 static bool classofKind(Kind K) { return K == UsingDirective; }
2965};
2966
2967/// Represents a C++ namespace alias.
2968///
2969/// For example:
2970///
2971/// \code
2972/// namespace Foo = Bar;
2973/// \endcode
2974class NamespaceAliasDecl : public NamedDecl,
2975 public Redeclarable<NamespaceAliasDecl> {
2976 friend class ASTDeclReader;
2977
2978 /// The location of the \c namespace keyword.
2979 SourceLocation NamespaceLoc;
2980
2981 /// The location of the namespace's identifier.
2982 ///
2983 /// This is accessed by TargetNameLoc.
2984 SourceLocation IdentLoc;
2985
2986 /// The nested-name-specifier that precedes the namespace.
2987 NestedNameSpecifierLoc QualifierLoc;
2988
2989 /// The Decl that this alias points to, either a NamespaceDecl or
2990 /// a NamespaceAliasDecl.
2991 NamedDecl *Namespace;
2992
2993 NamespaceAliasDecl(ASTContext &C, DeclContext *DC,
2994 SourceLocation NamespaceLoc, SourceLocation AliasLoc,
2995 IdentifierInfo *Alias, NestedNameSpecifierLoc QualifierLoc,
2996 SourceLocation IdentLoc, NamedDecl *Namespace)
2997 : NamedDecl(NamespaceAlias, DC, AliasLoc, Alias), redeclarable_base(C),
2998 NamespaceLoc(NamespaceLoc), IdentLoc(IdentLoc),
2999 QualifierLoc(QualifierLoc), Namespace(Namespace) {}
3000
3001 void anchor() override;
3002
3003 using redeclarable_base = Redeclarable<NamespaceAliasDecl>;
3004
3005 NamespaceAliasDecl *getNextRedeclarationImpl() override;
3006 NamespaceAliasDecl *getPreviousDeclImpl() override;
3007 NamespaceAliasDecl *getMostRecentDeclImpl() override;
3008
3009public:
3010 static NamespaceAliasDecl *Create(ASTContext &C, DeclContext *DC,
3011 SourceLocation NamespaceLoc,
3012 SourceLocation AliasLoc,
3013 IdentifierInfo *Alias,
3014 NestedNameSpecifierLoc QualifierLoc,
3015 SourceLocation IdentLoc,
3016 NamedDecl *Namespace);
3017
3018 static NamespaceAliasDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3019
3020 using redecl_range = redeclarable_base::redecl_range;
3021 using redecl_iterator = redeclarable_base::redecl_iterator;
3022
3023 using redeclarable_base::redecls_begin;
3024 using redeclarable_base::redecls_end;
3025 using redeclarable_base::redecls;
3026 using redeclarable_base::getPreviousDecl;
3027 using redeclarable_base::getMostRecentDecl;
3028
3029 NamespaceAliasDecl *getCanonicalDecl() override {
3030 return getFirstDecl();
3031 }
3032 const NamespaceAliasDecl *getCanonicalDecl() const {
3033 return getFirstDecl();
3034 }
3035
3036 /// Retrieve the nested-name-specifier that qualifies the
3037 /// name of the namespace, with source-location information.
3038 NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
3039
3040 /// Retrieve the nested-name-specifier that qualifies the
3041 /// name of the namespace.
3042 NestedNameSpecifier *getQualifier() const {
3043 return QualifierLoc.getNestedNameSpecifier();
3044 }
3045
3046 /// Retrieve the namespace declaration aliased by this directive.
3047 NamespaceDecl *getNamespace() {
3048 if (auto *AD = dyn_cast<NamespaceAliasDecl>(Namespace))
3049 return AD->getNamespace();
3050
3051 return cast<NamespaceDecl>(Namespace);
3052 }
3053
3054 const NamespaceDecl *getNamespace() const {
3055 return const_cast<NamespaceAliasDecl *>(this)->getNamespace();
3056 }
3057
3058 /// Returns the location of the alias name, i.e. 'foo' in
3059 /// "namespace foo = ns::bar;".
3060 SourceLocation getAliasLoc() const { return getLocation(); }
3061
3062 /// Returns the location of the \c namespace keyword.
3063 SourceLocation getNamespaceLoc() const { return NamespaceLoc; }
3064
3065 /// Returns the location of the identifier in the named namespace.
3066 SourceLocation getTargetNameLoc() const { return IdentLoc; }
3067
3068 /// Retrieve the namespace that this alias refers to, which
3069 /// may either be a NamespaceDecl or a NamespaceAliasDecl.
3070 NamedDecl *getAliasedNamespace() const { return Namespace; }
3071
3072 SourceRange getSourceRange() const override LLVM_READONLY {
3073 return SourceRange(NamespaceLoc, IdentLoc);
3074 }
3075
3076 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3077 static bool classofKind(Kind K) { return K == NamespaceAlias; }
3078};
3079
3080/// Implicit declaration of a temporary that was materialized by
3081/// a MaterializeTemporaryExpr and lifetime-extended by a declaration
3082class LifetimeExtendedTemporaryDecl final
3083 : public Decl,
3084 public Mergeable<LifetimeExtendedTemporaryDecl> {
3085 friend class MaterializeTemporaryExpr;
3086 friend class ASTDeclReader;
3087
3088 Stmt *ExprWithTemporary = nullptr;
3089
3090 /// The declaration which lifetime-extended this reference, if any.
3091 /// Either a VarDecl, or (for a ctor-initializer) a FieldDecl.
3092 ValueDecl *ExtendingDecl = nullptr;
3093 unsigned ManglingNumber;
3094
3095 mutable APValue *Value = nullptr;
3096
3097 virtual void anchor();
3098
3099 LifetimeExtendedTemporaryDecl(Expr *Temp, ValueDecl *EDecl, unsigned Mangling)
3100 : Decl(Decl::LifetimeExtendedTemporary, EDecl->getDeclContext(),
3101 EDecl->getLocation()),
3102 ExprWithTemporary(Temp), ExtendingDecl(EDecl),
3103 ManglingNumber(Mangling) {}
3104
3105 LifetimeExtendedTemporaryDecl(EmptyShell)
3106 : Decl(Decl::LifetimeExtendedTemporary, EmptyShell{}) {}
3107
3108public:
3109 static LifetimeExtendedTemporaryDecl *Create(Expr *Temp, ValueDecl *EDec,
3110 unsigned Mangling) {
3111 return new (EDec->getASTContext(), EDec->getDeclContext())
3112 LifetimeExtendedTemporaryDecl(Temp, EDec, Mangling);
3113 }
3114 static LifetimeExtendedTemporaryDecl *CreateDeserialized(ASTContext &C,
3115 unsigned ID) {
3116 return new (C, ID) LifetimeExtendedTemporaryDecl(EmptyShell{});
3117 }
3118
3119 ValueDecl *getExtendingDecl() { return ExtendingDecl; }
3120 const ValueDecl *getExtendingDecl() const { return ExtendingDecl; }
3121
3122 /// Retrieve the storage duration for the materialized temporary.
3123 StorageDuration getStorageDuration() const;
3124
3125 /// Retrieve the expression to which the temporary materialization conversion
3126 /// was applied. This isn't necessarily the initializer of the temporary due
3127 /// to the C++98 delayed materialization rules, but
3128 /// skipRValueSubobjectAdjustments can be used to find said initializer within
3129 /// the subexpression.
3130 Expr *getTemporaryExpr() { return cast<Expr>(ExprWithTemporary); }
3131 const Expr *getTemporaryExpr() const { return cast<Expr>(ExprWithTemporary); }
3132
3133 unsigned getManglingNumber() const { return ManglingNumber; }
3134
3135 /// Get the storage for the constant value of a materialized temporary
3136 /// of static storage duration.
3137 APValue *getOrCreateValue(bool MayCreate) const;
3138
3139 APValue *getValue() const { return Value; }
3140
3141 // Iterators
3142 Stmt::child_range childrenExpr() {
3143 return Stmt::child_range(&ExprWithTemporary, &ExprWithTemporary + 1);
3144 }
3145
3146 Stmt::const_child_range childrenExpr() const {
3147 return Stmt::const_child_range(&ExprWithTemporary, &ExprWithTemporary + 1);
3148 }
3149
3150 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3151 static bool classofKind(Kind K) {
3152 return K == Decl::LifetimeExtendedTemporary;
3153 }
3154};
3155
3156/// Represents a shadow declaration introduced into a scope by a
3157/// (resolved) using declaration.
3158///
3159/// For example,
3160/// \code
3161/// namespace A {
3162/// void foo();
3163/// }
3164/// namespace B {
3165/// using A::foo; // <- a UsingDecl
3166/// // Also creates a UsingShadowDecl for A::foo() in B
3167/// }
3168/// \endcode
3169class UsingShadowDecl : public NamedDecl, public Redeclarable<UsingShadowDecl> {
3170 friend class UsingDecl;
3171
3172 /// The referenced declaration.
3173 NamedDecl *Underlying = nullptr;
3174
3175 /// The using declaration which introduced this decl or the next using
3176 /// shadow declaration contained in the aforementioned using declaration.
3177 NamedDecl *UsingOrNextShadow = nullptr;
3178
3179 void anchor() override;
3180
3181 using redeclarable_base = Redeclarable<UsingShadowDecl>;
3182
3183 UsingShadowDecl *getNextRedeclarationImpl() override {
3184 return getNextRedeclaration();
3185 }
3186
3187 UsingShadowDecl *getPreviousDeclImpl() override {
3188 return getPreviousDecl();
3189 }
3190
3191 UsingShadowDecl *getMostRecentDeclImpl() override {
3192 return getMostRecentDecl();
3193 }
3194
3195protected:
3196 UsingShadowDecl(Kind K, ASTContext &C, DeclContext *DC, SourceLocation Loc,
3197 UsingDecl *Using, NamedDecl *Target);
3198 UsingShadowDecl(Kind K, ASTContext &C, EmptyShell);
3199
3200public:
3201 friend class ASTDeclReader;
3202 friend class ASTDeclWriter;
3203
3204 static UsingShadowDecl *Create(ASTContext &C, DeclContext *DC,
3205 SourceLocation Loc, UsingDecl *Using,
3206 NamedDecl *Target) {
3207 return new (C, DC) UsingShadowDecl(UsingShadow, C, DC, Loc, Using, Target);
3208 }
3209
3210 static UsingShadowDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3211
3212 using redecl_range = redeclarable_base::redecl_range;
3213 using redecl_iterator = redeclarable_base::redecl_iterator;
3214
3215 using redeclarable_base::redecls_begin;
3216 using redeclarable_base::redecls_end;
3217 using redeclarable_base::redecls;
3218 using redeclarable_base::getPreviousDecl;
3219 using redeclarable_base::getMostRecentDecl;
3220 using redeclarable_base::isFirstDecl;
3221
3222 UsingShadowDecl *getCanonicalDecl() override {
3223 return getFirstDecl();
3224 }
3225 const UsingShadowDecl *getCanonicalDecl() const {
3226 return getFirstDecl();
3227 }
3228
3229 /// Gets the underlying declaration which has been brought into the
3230 /// local scope.
3231 NamedDecl *getTargetDecl() const { return Underlying; }
3232
3233 /// Sets the underlying declaration which has been brought into the
3234 /// local scope.
3235 void setTargetDecl(NamedDecl *ND) {
3236 assert(ND && "Target decl is null!");
3237 Underlying = ND;
3238 // A UsingShadowDecl is never a friend or local extern declaration, even
3239 // if it is a shadow declaration for one.
3240 IdentifierNamespace =
3241 ND->getIdentifierNamespace() &
3242 ~(IDNS_OrdinaryFriend | IDNS_TagFriend | IDNS_LocalExtern);
3243 }
3244
3245 /// Gets the using declaration to which this declaration is tied.
3246 UsingDecl *getUsingDecl() const;
3247
3248 /// The next using shadow declaration contained in the shadow decl
3249 /// chain of the using declaration which introduced this decl.
3250 UsingShadowDecl *getNextUsingShadowDecl() const {
3251 return dyn_cast_or_null<UsingShadowDecl>(UsingOrNextShadow);
3252 }
3253
3254 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3255 static bool classofKind(Kind K) {
3256 return K == Decl::UsingShadow || K == Decl::ConstructorUsingShadow;
3257 }
3258};
3259
3260/// Represents a shadow constructor declaration introduced into a
3261/// class by a C++11 using-declaration that names a constructor.
3262///
3263/// For example:
3264/// \code
3265/// struct Base { Base(int); };
3266/// struct Derived {
3267/// using Base::Base; // creates a UsingDecl and a ConstructorUsingShadowDecl
3268/// };
3269/// \endcode
3270class ConstructorUsingShadowDecl final : public UsingShadowDecl {
3271 /// If this constructor using declaration inherted the constructor
3272 /// from an indirect base class, this is the ConstructorUsingShadowDecl
3273 /// in the named direct base class from which the declaration was inherited.
3274 ConstructorUsingShadowDecl *NominatedBaseClassShadowDecl = nullptr;
3275
3276 /// If this constructor using declaration inherted the constructor
3277 /// from an indirect base class, this is the ConstructorUsingShadowDecl
3278 /// that will be used to construct the unique direct or virtual base class
3279 /// that receives the constructor arguments.
3280 ConstructorUsingShadowDecl *ConstructedBaseClassShadowDecl = nullptr;
3281
3282 /// \c true if the constructor ultimately named by this using shadow
3283 /// declaration is within a virtual base class subobject of the class that
3284 /// contains this declaration.
3285 unsigned IsVirtual : 1;
3286
3287 ConstructorUsingShadowDecl(ASTContext &C, DeclContext *DC, SourceLocation Loc,
3288 UsingDecl *Using, NamedDecl *Target,
3289 bool TargetInVirtualBase)
3290 : UsingShadowDecl(ConstructorUsingShadow, C, DC, Loc, Using,
3291 Target->getUnderlyingDecl()),
3292 NominatedBaseClassShadowDecl(
3293 dyn_cast<ConstructorUsingShadowDecl>(Target)),
3294 ConstructedBaseClassShadowDecl(NominatedBaseClassShadowDecl),
3295 IsVirtual(TargetInVirtualBase) {
3296 // If we found a constructor that chains to a constructor for a virtual
3297 // base, we should directly call that virtual base constructor instead.
3298 // FIXME: This logic belongs in Sema.
3299 if (NominatedBaseClassShadowDecl &&
3300 NominatedBaseClassShadowDecl->constructsVirtualBase()) {
3301 ConstructedBaseClassShadowDecl =
3302 NominatedBaseClassShadowDecl->ConstructedBaseClassShadowDecl;
3303 IsVirtual = true;
3304 }
3305 }
3306
3307 ConstructorUsingShadowDecl(ASTContext &C, EmptyShell Empty)
3308 : UsingShadowDecl(ConstructorUsingShadow, C, Empty), IsVirtual(false) {}
3309
3310 void anchor() override;
3311
3312public:
3313 friend class ASTDeclReader;
3314 friend class ASTDeclWriter;
3315
3316 static ConstructorUsingShadowDecl *Create(ASTContext &C, DeclContext *DC,
3317 SourceLocation Loc,
3318 UsingDecl *Using, NamedDecl *Target,
3319 bool IsVirtual);
3320 static ConstructorUsingShadowDecl *CreateDeserialized(ASTContext &C,
3321 unsigned ID);
3322
3323 /// Returns the parent of this using shadow declaration, which
3324 /// is the class in which this is declared.
3325 //@{
3326 const CXXRecordDecl *getParent() const {
3327 return cast<CXXRecordDecl>(getDeclContext());
3328 }
3329 CXXRecordDecl *getParent() {
3330 return cast<CXXRecordDecl>(getDeclContext());
3331 }
3332 //@}
3333
3334 /// Get the inheriting constructor declaration for the direct base
3335 /// class from which this using shadow declaration was inherited, if there is
3336 /// one. This can be different for each redeclaration of the same shadow decl.
3337 ConstructorUsingShadowDecl *getNominatedBaseClassShadowDecl() const {
3338 return NominatedBaseClassShadowDecl;
3339 }
3340
3341 /// Get the inheriting constructor declaration for the base class
3342 /// for which we don't have an explicit initializer, if there is one.
3343 ConstructorUsingShadowDecl *getConstructedBaseClassShadowDecl() const {
3344 return ConstructedBaseClassShadowDecl;
3345 }
3346
3347 /// Get the base class that was named in the using declaration. This
3348 /// can be different for each redeclaration of this same shadow decl.
3349 CXXRecordDecl *getNominatedBaseClass() const;
3350
3351 /// Get the base class whose constructor or constructor shadow
3352 /// declaration is passed the constructor arguments.
3353 CXXRecordDecl *getConstructedBaseClass() const {
3354 return cast<CXXRecordDecl>((ConstructedBaseClassShadowDecl
3355 ? ConstructedBaseClassShadowDecl
3356 : getTargetDecl())
3357 ->getDeclContext());
3358 }
3359
3360 /// Returns \c true if the constructed base class is a virtual base
3361 /// class subobject of this declaration's class.
3362 bool constructsVirtualBase() const {
3363 return IsVirtual;
3364 }
3365
3366 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3367 static bool classofKind(Kind K) { return K == ConstructorUsingShadow; }
3368};
3369
3370/// Represents a C++ using-declaration.
3371///
3372/// For example:
3373/// \code
3374/// using someNameSpace::someIdentifier;
3375/// \endcode
3376class UsingDecl : public NamedDecl, public Mergeable<UsingDecl> {
3377 /// The source location of the 'using' keyword itself.
3378