1 //===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file implements semantic analysis for C++ declarations.
11 //===----------------------------------------------------------------------===//
13 #include "clang/AST/ASTConsumer.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/ASTLambda.h"
16 #include "clang/AST/ASTMutationListener.h"
17 #include "clang/AST/CXXInheritance.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/ComparisonCategories.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/EvaluatedExprVisitor.h"
23 #include "clang/AST/Expr.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/AST/RecordLayout.h"
26 #include "clang/AST/RecursiveASTVisitor.h"
27 #include "clang/AST/StmtVisitor.h"
28 #include "clang/AST/TypeLoc.h"
29 #include "clang/AST/TypeOrdering.h"
30 #include "clang/Basic/AttributeCommonInfo.h"
31 #include "clang/Basic/PartialDiagnostic.h"
32 #include "clang/Basic/Specifiers.h"
33 #include "clang/Basic/TargetInfo.h"
34 #include "clang/Lex/LiteralSupport.h"
35 #include "clang/Lex/Preprocessor.h"
36 #include "clang/Sema/CXXFieldCollector.h"
37 #include "clang/Sema/DeclSpec.h"
38 #include "clang/Sema/EnterExpressionEvaluationContext.h"
39 #include "clang/Sema/Initialization.h"
40 #include "clang/Sema/Lookup.h"
41 #include "clang/Sema/Ownership.h"
42 #include "clang/Sema/ParsedTemplate.h"
43 #include "clang/Sema/Scope.h"
44 #include "clang/Sema/ScopeInfo.h"
45 #include "clang/Sema/SemaInternal.h"
46 #include "clang/Sema/Template.h"
47 #include "llvm/ADT/ArrayRef.h"
48 #include "llvm/ADT/STLExtras.h"
49 #include "llvm/ADT/ScopeExit.h"
50 #include "llvm/ADT/SmallString.h"
51 #include "llvm/ADT/StringExtras.h"
52 #include "llvm/Support/ConvertUTF.h"
53 #include "llvm/Support/SaveAndRestore.h"
58 using namespace clang
;
60 //===----------------------------------------------------------------------===//
61 // CheckDefaultArgumentVisitor
62 //===----------------------------------------------------------------------===//
65 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
66 /// the default argument of a parameter to determine whether it
67 /// contains any ill-formed subexpressions. For example, this will
68 /// diagnose the use of local variables or parameters within the
69 /// default argument expression.
70 class CheckDefaultArgumentVisitor
71 : public ConstStmtVisitor
<CheckDefaultArgumentVisitor
, bool> {
73 const Expr
*DefaultArg
;
76 CheckDefaultArgumentVisitor(Sema
&S
, const Expr
*DefaultArg
)
77 : S(S
), DefaultArg(DefaultArg
) {}
79 bool VisitExpr(const Expr
*Node
);
80 bool VisitDeclRefExpr(const DeclRefExpr
*DRE
);
81 bool VisitCXXThisExpr(const CXXThisExpr
*ThisE
);
82 bool VisitLambdaExpr(const LambdaExpr
*Lambda
);
83 bool VisitPseudoObjectExpr(const PseudoObjectExpr
*POE
);
86 /// VisitExpr - Visit all of the children of this expression.
87 bool CheckDefaultArgumentVisitor::VisitExpr(const Expr
*Node
) {
88 bool IsInvalid
= false;
89 for (const Stmt
*SubStmt
: Node
->children())
91 IsInvalid
|= Visit(SubStmt
);
95 /// VisitDeclRefExpr - Visit a reference to a declaration, to
96 /// determine whether this declaration can be used in the default
97 /// argument expression.
98 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(const DeclRefExpr
*DRE
) {
99 const ValueDecl
*Decl
= dyn_cast
<ValueDecl
>(DRE
->getDecl());
101 if (!isa
<VarDecl
, BindingDecl
>(Decl
))
104 if (const auto *Param
= dyn_cast
<ParmVarDecl
>(Decl
)) {
105 // C++ [dcl.fct.default]p9:
106 // [...] parameters of a function shall not be used in default
107 // argument expressions, even if they are not evaluated. [...]
109 // C++17 [dcl.fct.default]p9 (by CWG 2082):
110 // [...] A parameter shall not appear as a potentially-evaluated
111 // expression in a default argument. [...]
113 if (DRE
->isNonOdrUse() != NOUR_Unevaluated
)
114 return S
.Diag(DRE
->getBeginLoc(),
115 diag::err_param_default_argument_references_param
)
116 << Param
->getDeclName() << DefaultArg
->getSourceRange();
117 } else if (auto *VD
= Decl
->getPotentiallyDecomposedVarDecl()) {
118 // C++ [dcl.fct.default]p7:
119 // Local variables shall not be used in default argument
122 // C++17 [dcl.fct.default]p7 (by CWG 2082):
123 // A local variable shall not appear as a potentially-evaluated
124 // expression in a default argument.
126 // C++20 [dcl.fct.default]p7 (DR as part of P0588R1, see also CWG 2346):
127 // Note: A local variable cannot be odr-used (6.3) in a default
130 if (VD
->isLocalVarDecl() && !DRE
->isNonOdrUse())
131 return S
.Diag(DRE
->getBeginLoc(),
132 diag::err_param_default_argument_references_local
)
133 << Decl
<< DefaultArg
->getSourceRange();
138 /// VisitCXXThisExpr - Visit a C++ "this" expression.
139 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(const CXXThisExpr
*ThisE
) {
140 // C++ [dcl.fct.default]p8:
141 // The keyword this shall not be used in a default argument of a
143 return S
.Diag(ThisE
->getBeginLoc(),
144 diag::err_param_default_argument_references_this
)
145 << ThisE
->getSourceRange();
148 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(
149 const PseudoObjectExpr
*POE
) {
150 bool Invalid
= false;
151 for (const Expr
*E
: POE
->semantics()) {
152 // Look through bindings.
153 if (const auto *OVE
= dyn_cast
<OpaqueValueExpr
>(E
)) {
154 E
= OVE
->getSourceExpr();
155 assert(E
&& "pseudo-object binding without source expression?");
163 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(const LambdaExpr
*Lambda
) {
164 // [expr.prim.lambda.capture]p9
165 // a lambda-expression appearing in a default argument cannot implicitly or
166 // explicitly capture any local entity. Such a lambda-expression can still
167 // have an init-capture if any full-expression in its initializer satisfies
168 // the constraints of an expression appearing in a default argument.
169 bool Invalid
= false;
170 for (const LambdaCapture
&LC
: Lambda
->captures()) {
171 if (!Lambda
->isInitCapture(&LC
))
172 return S
.Diag(LC
.getLocation(), diag::err_lambda_capture_default_arg
);
173 // Init captures are always VarDecl.
174 auto *D
= cast
<VarDecl
>(LC
.getCapturedVar());
175 Invalid
|= Visit(D
->getInit());
182 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc
,
183 const CXXMethodDecl
*Method
) {
184 // If we have an MSAny spec already, don't bother.
185 if (!Method
|| ComputedEST
== EST_MSAny
)
188 const FunctionProtoType
*Proto
189 = Method
->getType()->getAs
<FunctionProtoType
>();
190 Proto
= Self
->ResolveExceptionSpec(CallLoc
, Proto
);
194 ExceptionSpecificationType EST
= Proto
->getExceptionSpecType();
196 // If we have a throw-all spec at this point, ignore the function.
197 if (ComputedEST
== EST_None
)
200 if (EST
== EST_None
&& Method
->hasAttr
<NoThrowAttr
>())
201 EST
= EST_BasicNoexcept
;
205 case EST_Uninstantiated
:
206 case EST_Unevaluated
:
207 llvm_unreachable("should not see unresolved exception specs here");
209 // If this function can throw any exceptions, make a note of that.
212 // FIXME: Whichever we see last of MSAny and None determines our result.
213 // We should make a consistent, order-independent choice here.
217 case EST_NoexceptFalse
:
219 ComputedEST
= EST_None
;
221 // FIXME: If the call to this decl is using any of its default arguments, we
222 // need to search them for potentially-throwing calls.
223 // If this function has a basic noexcept, it doesn't affect the outcome.
224 case EST_BasicNoexcept
:
225 case EST_NoexceptTrue
:
228 // If we're still at noexcept(true) and there's a throw() callee,
229 // change to that specification.
230 case EST_DynamicNone
:
231 if (ComputedEST
== EST_BasicNoexcept
)
232 ComputedEST
= EST_DynamicNone
;
234 case EST_DependentNoexcept
:
236 "should not generate implicit declarations for dependent cases");
240 assert(EST
== EST_Dynamic
&& "EST case not considered earlier.");
241 assert(ComputedEST
!= EST_None
&&
242 "Shouldn't collect exceptions when throw-all is guaranteed.");
243 ComputedEST
= EST_Dynamic
;
244 // Record the exceptions in this function's exception specification.
245 for (const auto &E
: Proto
->exceptions())
246 if (ExceptionsSeen
.insert(Self
->Context
.getCanonicalType(E
)).second
)
247 Exceptions
.push_back(E
);
250 void Sema::ImplicitExceptionSpecification::CalledStmt(Stmt
*S
) {
251 if (!S
|| ComputedEST
== EST_MSAny
)
256 // C++0x [except.spec]p14:
257 // [An] implicit exception-specification specifies the type-id T if and
258 // only if T is allowed by the exception-specification of a function directly
259 // invoked by f's implicit definition; f shall allow all exceptions if any
260 // function it directly invokes allows all exceptions, and f shall allow no
261 // exceptions if every function it directly invokes allows no exceptions.
263 // Note in particular that if an implicit exception-specification is generated
264 // for a function containing a throw-expression, that specification can still
265 // be noexcept(true).
267 // Note also that 'directly invoked' is not defined in the standard, and there
268 // is no indication that we should only consider potentially-evaluated calls.
270 // Ultimately we should implement the intent of the standard: the exception
271 // specification should be the set of exceptions which can be thrown by the
272 // implicit definition. For now, we assume that any non-nothrow expression can
273 // throw any exception.
275 if (Self
->canThrow(S
))
276 ComputedEST
= EST_None
;
279 ExprResult
Sema::ConvertParamDefaultArgument(ParmVarDecl
*Param
, Expr
*Arg
,
280 SourceLocation EqualLoc
) {
281 if (RequireCompleteType(Param
->getLocation(), Param
->getType(),
282 diag::err_typecheck_decl_incomplete_type
))
285 // C++ [dcl.fct.default]p5
286 // A default argument expression is implicitly converted (clause
287 // 4) to the parameter type. The default argument expression has
288 // the same semantic constraints as the initializer expression in
289 // a declaration of a variable of the parameter type, using the
290 // copy-initialization semantics (8.5).
291 InitializedEntity Entity
= InitializedEntity::InitializeParameter(Context
,
293 InitializationKind Kind
= InitializationKind::CreateCopy(Param
->getLocation(),
295 InitializationSequence
InitSeq(*this, Entity
, Kind
, Arg
);
296 ExprResult Result
= InitSeq
.Perform(*this, Entity
, Kind
, Arg
);
297 if (Result
.isInvalid())
299 Arg
= Result
.getAs
<Expr
>();
301 CheckCompletedExpr(Arg
, EqualLoc
);
302 Arg
= MaybeCreateExprWithCleanups(Arg
);
307 void Sema::SetParamDefaultArgument(ParmVarDecl
*Param
, Expr
*Arg
,
308 SourceLocation EqualLoc
) {
309 // Add the default argument to the parameter
310 Param
->setDefaultArg(Arg
);
312 // We have already instantiated this parameter; provide each of the
313 // instantiations with the uninstantiated default argument.
314 UnparsedDefaultArgInstantiationsMap::iterator InstPos
315 = UnparsedDefaultArgInstantiations
.find(Param
);
316 if (InstPos
!= UnparsedDefaultArgInstantiations
.end()) {
317 for (unsigned I
= 0, N
= InstPos
->second
.size(); I
!= N
; ++I
)
318 InstPos
->second
[I
]->setUninstantiatedDefaultArg(Arg
);
320 // We're done tracking this parameter's instantiations.
321 UnparsedDefaultArgInstantiations
.erase(InstPos
);
325 /// ActOnParamDefaultArgument - Check whether the default argument
326 /// provided for a function parameter is well-formed. If so, attach it
327 /// to the parameter declaration.
329 Sema::ActOnParamDefaultArgument(Decl
*param
, SourceLocation EqualLoc
,
331 if (!param
|| !DefaultArg
)
334 ParmVarDecl
*Param
= cast
<ParmVarDecl
>(param
);
335 UnparsedDefaultArgLocs
.erase(Param
);
337 // Default arguments are only permitted in C++
338 if (!getLangOpts().CPlusPlus
) {
339 Diag(EqualLoc
, diag::err_param_default_argument
)
340 << DefaultArg
->getSourceRange();
341 return ActOnParamDefaultArgumentError(param
, EqualLoc
, DefaultArg
);
344 // Check for unexpanded parameter packs.
345 if (DiagnoseUnexpandedParameterPack(DefaultArg
, UPPC_DefaultArgument
))
346 return ActOnParamDefaultArgumentError(param
, EqualLoc
, DefaultArg
);
348 // C++11 [dcl.fct.default]p3
349 // A default argument expression [...] shall not be specified for a
351 if (Param
->isParameterPack()) {
352 Diag(EqualLoc
, diag::err_param_default_argument_on_parameter_pack
)
353 << DefaultArg
->getSourceRange();
354 // Recover by discarding the default argument.
355 Param
->setDefaultArg(nullptr);
359 ExprResult Result
= ConvertParamDefaultArgument(Param
, DefaultArg
, EqualLoc
);
360 if (Result
.isInvalid())
361 return ActOnParamDefaultArgumentError(param
, EqualLoc
, DefaultArg
);
363 DefaultArg
= Result
.getAs
<Expr
>();
365 // Check that the default argument is well-formed
366 CheckDefaultArgumentVisitor
DefaultArgChecker(*this, DefaultArg
);
367 if (DefaultArgChecker
.Visit(DefaultArg
))
368 return ActOnParamDefaultArgumentError(param
, EqualLoc
, DefaultArg
);
370 SetParamDefaultArgument(Param
, DefaultArg
, EqualLoc
);
373 /// ActOnParamUnparsedDefaultArgument - We've seen a default
374 /// argument for a function parameter, but we can't parse it yet
375 /// because we're inside a class definition. Note that this default
376 /// argument will be parsed later.
377 void Sema::ActOnParamUnparsedDefaultArgument(Decl
*param
,
378 SourceLocation EqualLoc
,
379 SourceLocation ArgLoc
) {
383 ParmVarDecl
*Param
= cast
<ParmVarDecl
>(param
);
384 Param
->setUnparsedDefaultArg();
385 UnparsedDefaultArgLocs
[Param
] = ArgLoc
;
388 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
389 /// the default argument for the parameter param failed.
390 void Sema::ActOnParamDefaultArgumentError(Decl
*param
, SourceLocation EqualLoc
,
395 ParmVarDecl
*Param
= cast
<ParmVarDecl
>(param
);
396 Param
->setInvalidDecl();
397 UnparsedDefaultArgLocs
.erase(Param
);
400 RE
= CreateRecoveryExpr(EqualLoc
, DefaultArg
->getEndLoc(), {DefaultArg
},
401 Param
->getType().getNonReferenceType());
403 RE
= CreateRecoveryExpr(EqualLoc
, EqualLoc
, {},
404 Param
->getType().getNonReferenceType());
406 Param
->setDefaultArg(RE
.get());
409 /// CheckExtraCXXDefaultArguments - Check for any extra default
410 /// arguments in the declarator, which is not a function declaration
411 /// or definition and therefore is not permitted to have default
412 /// arguments. This routine should be invoked for every declarator
413 /// that is not a function declaration or definition.
414 void Sema::CheckExtraCXXDefaultArguments(Declarator
&D
) {
415 // C++ [dcl.fct.default]p3
416 // A default argument expression shall be specified only in the
417 // parameter-declaration-clause of a function declaration or in a
418 // template-parameter (14.1). It shall not be specified for a
419 // parameter pack. If it is specified in a
420 // parameter-declaration-clause, it shall not occur within a
421 // declarator or abstract-declarator of a parameter-declaration.
422 bool MightBeFunction
= D
.isFunctionDeclarationContext();
423 for (unsigned i
= 0, e
= D
.getNumTypeObjects(); i
!= e
; ++i
) {
424 DeclaratorChunk
&chunk
= D
.getTypeObject(i
);
425 if (chunk
.Kind
== DeclaratorChunk::Function
) {
426 if (MightBeFunction
) {
427 // This is a function declaration. It can have default arguments, but
428 // keep looking in case its return type is a function type with default
430 MightBeFunction
= false;
433 for (unsigned argIdx
= 0, e
= chunk
.Fun
.NumParams
; argIdx
!= e
;
435 ParmVarDecl
*Param
= cast
<ParmVarDecl
>(chunk
.Fun
.Params
[argIdx
].Param
);
436 if (Param
->hasUnparsedDefaultArg()) {
437 std::unique_ptr
<CachedTokens
> Toks
=
438 std::move(chunk
.Fun
.Params
[argIdx
].DefaultArgTokens
);
440 if (Toks
->size() > 1)
441 SR
= SourceRange((*Toks
)[1].getLocation(),
442 Toks
->back().getLocation());
444 SR
= UnparsedDefaultArgLocs
[Param
];
445 Diag(Param
->getLocation(), diag::err_param_default_argument_nonfunc
)
447 } else if (Param
->getDefaultArg()) {
448 Diag(Param
->getLocation(), diag::err_param_default_argument_nonfunc
)
449 << Param
->getDefaultArg()->getSourceRange();
450 Param
->setDefaultArg(nullptr);
453 } else if (chunk
.Kind
!= DeclaratorChunk::Paren
) {
454 MightBeFunction
= false;
459 static bool functionDeclHasDefaultArgument(const FunctionDecl
*FD
) {
460 return llvm::any_of(FD
->parameters(), [](ParmVarDecl
*P
) {
461 return P
->hasDefaultArg() && !P
->hasInheritedDefaultArg();
465 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
466 /// function, once we already know that they have the same
467 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
468 /// error, false otherwise.
469 bool Sema::MergeCXXFunctionDecl(FunctionDecl
*New
, FunctionDecl
*Old
,
471 bool Invalid
= false;
473 // The declaration context corresponding to the scope is the semantic
474 // parent, unless this is a local function declaration, in which case
475 // it is that surrounding function.
476 DeclContext
*ScopeDC
= New
->isLocalExternDecl()
477 ? New
->getLexicalDeclContext()
478 : New
->getDeclContext();
480 // Find the previous declaration for the purpose of default arguments.
481 FunctionDecl
*PrevForDefaultArgs
= Old
;
482 for (/**/; PrevForDefaultArgs
;
483 // Don't bother looking back past the latest decl if this is a local
484 // extern declaration; nothing else could work.
485 PrevForDefaultArgs
= New
->isLocalExternDecl()
487 : PrevForDefaultArgs
->getPreviousDecl()) {
488 // Ignore hidden declarations.
489 if (!LookupResult::isVisible(*this, PrevForDefaultArgs
))
492 if (S
&& !isDeclInScope(PrevForDefaultArgs
, ScopeDC
, S
) &&
493 !New
->isCXXClassMember()) {
494 // Ignore default arguments of old decl if they are not in
495 // the same scope and this is not an out-of-line definition of
496 // a member function.
500 if (PrevForDefaultArgs
->isLocalExternDecl() != New
->isLocalExternDecl()) {
501 // If only one of these is a local function declaration, then they are
502 // declared in different scopes, even though isDeclInScope may think
503 // they're in the same scope. (If both are local, the scope check is
504 // sufficient, and if neither is local, then they are in the same scope.)
508 // We found the right previous declaration.
512 // C++ [dcl.fct.default]p4:
513 // For non-template functions, default arguments can be added in
514 // later declarations of a function in the same
515 // scope. Declarations in different scopes have completely
516 // distinct sets of default arguments. That is, declarations in
517 // inner scopes do not acquire default arguments from
518 // declarations in outer scopes, and vice versa. In a given
519 // function declaration, all parameters subsequent to a
520 // parameter with a default argument shall have default
521 // arguments supplied in this or previous declarations. A
522 // default argument shall not be redefined by a later
523 // declaration (not even to the same value).
525 // C++ [dcl.fct.default]p6:
526 // Except for member functions of class templates, the default arguments
527 // in a member function definition that appears outside of the class
528 // definition are added to the set of default arguments provided by the
529 // member function declaration in the class definition.
530 for (unsigned p
= 0, NumParams
= PrevForDefaultArgs
531 ? PrevForDefaultArgs
->getNumParams()
533 p
< NumParams
; ++p
) {
534 ParmVarDecl
*OldParam
= PrevForDefaultArgs
->getParamDecl(p
);
535 ParmVarDecl
*NewParam
= New
->getParamDecl(p
);
537 bool OldParamHasDfl
= OldParam
? OldParam
->hasDefaultArg() : false;
538 bool NewParamHasDfl
= NewParam
->hasDefaultArg();
540 if (OldParamHasDfl
&& NewParamHasDfl
) {
541 unsigned DiagDefaultParamID
=
542 diag::err_param_default_argument_redefinition
;
544 // MSVC accepts that default parameters be redefined for member functions
545 // of template class. The new default parameter's value is ignored.
547 if (getLangOpts().MicrosoftExt
) {
548 CXXMethodDecl
*MD
= dyn_cast
<CXXMethodDecl
>(New
);
549 if (MD
&& MD
->getParent()->getDescribedClassTemplate()) {
550 // Merge the old default argument into the new parameter.
551 NewParam
->setHasInheritedDefaultArg();
552 if (OldParam
->hasUninstantiatedDefaultArg())
553 NewParam
->setUninstantiatedDefaultArg(
554 OldParam
->getUninstantiatedDefaultArg());
556 NewParam
->setDefaultArg(OldParam
->getInit());
557 DiagDefaultParamID
= diag::ext_param_default_argument_redefinition
;
562 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
563 // hint here. Alternatively, we could walk the type-source information
564 // for NewParam to find the last source location in the type... but it
565 // isn't worth the effort right now. This is the kind of test case that
566 // is hard to get right:
568 // void g(int (*fp)(int) = f);
569 // void g(int (*fp)(int) = &f);
570 Diag(NewParam
->getLocation(), DiagDefaultParamID
)
571 << NewParam
->getDefaultArgRange();
573 // Look for the function declaration where the default argument was
574 // actually written, which may be a declaration prior to Old.
575 for (auto Older
= PrevForDefaultArgs
;
576 OldParam
->hasInheritedDefaultArg(); /**/) {
577 Older
= Older
->getPreviousDecl();
578 OldParam
= Older
->getParamDecl(p
);
581 Diag(OldParam
->getLocation(), diag::note_previous_definition
)
582 << OldParam
->getDefaultArgRange();
583 } else if (OldParamHasDfl
) {
584 // Merge the old default argument into the new parameter unless the new
585 // function is a friend declaration in a template class. In the latter
586 // case the default arguments will be inherited when the friend
587 // declaration will be instantiated.
588 if (New
->getFriendObjectKind() == Decl::FOK_None
||
589 !New
->getLexicalDeclContext()->isDependentContext()) {
590 // It's important to use getInit() here; getDefaultArg()
591 // strips off any top-level ExprWithCleanups.
592 NewParam
->setHasInheritedDefaultArg();
593 if (OldParam
->hasUnparsedDefaultArg())
594 NewParam
->setUnparsedDefaultArg();
595 else if (OldParam
->hasUninstantiatedDefaultArg())
596 NewParam
->setUninstantiatedDefaultArg(
597 OldParam
->getUninstantiatedDefaultArg());
599 NewParam
->setDefaultArg(OldParam
->getInit());
601 } else if (NewParamHasDfl
) {
602 if (New
->getDescribedFunctionTemplate()) {
603 // Paragraph 4, quoted above, only applies to non-template functions.
604 Diag(NewParam
->getLocation(),
605 diag::err_param_default_argument_template_redecl
)
606 << NewParam
->getDefaultArgRange();
607 Diag(PrevForDefaultArgs
->getLocation(),
608 diag::note_template_prev_declaration
)
610 } else if (New
->getTemplateSpecializationKind()
611 != TSK_ImplicitInstantiation
&&
612 New
->getTemplateSpecializationKind() != TSK_Undeclared
) {
613 // C++ [temp.expr.spec]p21:
614 // Default function arguments shall not be specified in a declaration
615 // or a definition for one of the following explicit specializations:
616 // - the explicit specialization of a function template;
617 // - the explicit specialization of a member function template;
618 // - the explicit specialization of a member function of a class
619 // template where the class template specialization to which the
620 // member function specialization belongs is implicitly
622 Diag(NewParam
->getLocation(), diag::err_template_spec_default_arg
)
623 << (New
->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization
)
624 << New
->getDeclName()
625 << NewParam
->getDefaultArgRange();
626 } else if (New
->getDeclContext()->isDependentContext()) {
627 // C++ [dcl.fct.default]p6 (DR217):
628 // Default arguments for a member function of a class template shall
629 // be specified on the initial declaration of the member function
630 // within the class template.
632 // Reading the tea leaves a bit in DR217 and its reference to DR205
633 // leads me to the conclusion that one cannot add default function
634 // arguments for an out-of-line definition of a member function of a
637 if (CXXRecordDecl
*Record
638 = dyn_cast
<CXXRecordDecl
>(New
->getDeclContext())) {
639 if (Record
->getDescribedClassTemplate())
641 else if (isa
<ClassTemplatePartialSpecializationDecl
>(Record
))
647 Diag(NewParam
->getLocation(),
648 diag::err_param_default_argument_member_template_redecl
)
650 << NewParam
->getDefaultArgRange();
655 // DR1344: If a default argument is added outside a class definition and that
656 // default argument makes the function a special member function, the program
657 // is ill-formed. This can only happen for constructors.
658 if (isa
<CXXConstructorDecl
>(New
) &&
659 New
->getMinRequiredArguments() < Old
->getMinRequiredArguments()) {
660 CXXSpecialMember NewSM
= getSpecialMember(cast
<CXXMethodDecl
>(New
)),
661 OldSM
= getSpecialMember(cast
<CXXMethodDecl
>(Old
));
662 if (NewSM
!= OldSM
) {
663 ParmVarDecl
*NewParam
= New
->getParamDecl(New
->getMinRequiredArguments());
664 assert(NewParam
->hasDefaultArg());
665 Diag(NewParam
->getLocation(), diag::err_default_arg_makes_ctor_special
)
666 << NewParam
->getDefaultArgRange() << NewSM
;
667 Diag(Old
->getLocation(), diag::note_previous_declaration
);
671 const FunctionDecl
*Def
;
672 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
673 // template has a constexpr specifier then all its declarations shall
674 // contain the constexpr specifier.
675 if (New
->getConstexprKind() != Old
->getConstexprKind()) {
676 Diag(New
->getLocation(), diag::err_constexpr_redecl_mismatch
)
677 << New
<< static_cast<int>(New
->getConstexprKind())
678 << static_cast<int>(Old
->getConstexprKind());
679 Diag(Old
->getLocation(), diag::note_previous_declaration
);
681 } else if (!Old
->getMostRecentDecl()->isInlined() && New
->isInlined() &&
682 Old
->isDefined(Def
) &&
683 // If a friend function is inlined but does not have 'inline'
684 // specifier, it is a definition. Do not report attribute conflict
685 // in this case, redefinition will be diagnosed later.
686 (New
->isInlineSpecified() ||
687 New
->getFriendObjectKind() == Decl::FOK_None
)) {
688 // C++11 [dcl.fcn.spec]p4:
689 // If the definition of a function appears in a translation unit before its
690 // first declaration as inline, the program is ill-formed.
691 Diag(New
->getLocation(), diag::err_inline_decl_follows_def
) << New
;
692 Diag(Def
->getLocation(), diag::note_previous_definition
);
696 // C++17 [temp.deduct.guide]p3:
697 // Two deduction guide declarations in the same translation unit
698 // for the same class template shall not have equivalent
699 // parameter-declaration-clauses.
700 if (isa
<CXXDeductionGuideDecl
>(New
) &&
701 !New
->isFunctionTemplateSpecialization() && isVisible(Old
)) {
702 Diag(New
->getLocation(), diag::err_deduction_guide_redeclared
);
703 Diag(Old
->getLocation(), diag::note_previous_declaration
);
706 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
707 // argument expression, that declaration shall be a definition and shall be
708 // the only declaration of the function or function template in the
710 if (Old
->getFriendObjectKind() == Decl::FOK_Undeclared
&&
711 functionDeclHasDefaultArgument(Old
)) {
712 Diag(New
->getLocation(), diag::err_friend_decl_with_def_arg_redeclared
);
713 Diag(Old
->getLocation(), diag::note_previous_declaration
);
717 // C++11 [temp.friend]p4 (DR329):
718 // When a function is defined in a friend function declaration in a class
719 // template, the function is instantiated when the function is odr-used.
720 // The same restrictions on multiple declarations and definitions that
721 // apply to non-template function declarations and definitions also apply
722 // to these implicit definitions.
723 const FunctionDecl
*OldDefinition
= nullptr;
724 if (New
->isThisDeclarationInstantiatedFromAFriendDefinition() &&
725 Old
->isDefined(OldDefinition
, true))
726 CheckForFunctionRedefinition(New
, OldDefinition
);
731 void Sema::DiagPlaceholderVariableDefinition(SourceLocation Loc
) {
732 Diag(Loc
, getLangOpts().CPlusPlus26
733 ? diag::warn_cxx23_placeholder_var_definition
734 : diag::ext_placeholder_var_definition
);
738 Sema::ActOnDecompositionDeclarator(Scope
*S
, Declarator
&D
,
739 MultiTemplateParamsArg TemplateParamLists
) {
740 assert(D
.isDecompositionDeclarator());
741 const DecompositionDeclarator
&Decomp
= D
.getDecompositionDeclarator();
743 // The syntax only allows a decomposition declarator as a simple-declaration,
744 // a for-range-declaration, or a condition in Clang, but we parse it in more
746 if (!D
.mayHaveDecompositionDeclarator()) {
747 Diag(Decomp
.getLSquareLoc(), diag::err_decomp_decl_context
)
748 << Decomp
.getSourceRange();
752 if (!TemplateParamLists
.empty()) {
753 // FIXME: There's no rule against this, but there are also no rules that
754 // would actually make it usable, so we reject it for now.
755 Diag(TemplateParamLists
.front()->getTemplateLoc(),
756 diag::err_decomp_decl_template
);
760 Diag(Decomp
.getLSquareLoc(),
761 !getLangOpts().CPlusPlus17
762 ? diag::ext_decomp_decl
763 : D
.getContext() == DeclaratorContext::Condition
764 ? diag::ext_decomp_decl_cond
765 : diag::warn_cxx14_compat_decomp_decl
)
766 << Decomp
.getSourceRange();
768 // The semantic context is always just the current context.
769 DeclContext
*const DC
= CurContext
;
771 // C++17 [dcl.dcl]/8:
772 // The decl-specifier-seq shall contain only the type-specifier auto
773 // and cv-qualifiers.
774 // C++20 [dcl.dcl]/8:
775 // If decl-specifier-seq contains any decl-specifier other than static,
776 // thread_local, auto, or cv-qualifiers, the program is ill-formed.
777 // C++23 [dcl.pre]/6:
778 // Each decl-specifier in the decl-specifier-seq shall be static,
779 // thread_local, auto (9.2.9.6 [dcl.spec.auto]), or a cv-qualifier.
780 auto &DS
= D
.getDeclSpec();
782 // Note: While constrained-auto needs to be checked, we do so separately so
783 // we can emit a better diagnostic.
784 SmallVector
<StringRef
, 8> BadSpecifiers
;
785 SmallVector
<SourceLocation
, 8> BadSpecifierLocs
;
786 SmallVector
<StringRef
, 8> CPlusPlus20Specifiers
;
787 SmallVector
<SourceLocation
, 8> CPlusPlus20SpecifierLocs
;
788 if (auto SCS
= DS
.getStorageClassSpec()) {
789 if (SCS
== DeclSpec::SCS_static
) {
790 CPlusPlus20Specifiers
.push_back(DeclSpec::getSpecifierName(SCS
));
791 CPlusPlus20SpecifierLocs
.push_back(DS
.getStorageClassSpecLoc());
793 BadSpecifiers
.push_back(DeclSpec::getSpecifierName(SCS
));
794 BadSpecifierLocs
.push_back(DS
.getStorageClassSpecLoc());
797 if (auto TSCS
= DS
.getThreadStorageClassSpec()) {
798 CPlusPlus20Specifiers
.push_back(DeclSpec::getSpecifierName(TSCS
));
799 CPlusPlus20SpecifierLocs
.push_back(DS
.getThreadStorageClassSpecLoc());
801 if (DS
.hasConstexprSpecifier()) {
802 BadSpecifiers
.push_back(
803 DeclSpec::getSpecifierName(DS
.getConstexprSpecifier()));
804 BadSpecifierLocs
.push_back(DS
.getConstexprSpecLoc());
806 if (DS
.isInlineSpecified()) {
807 BadSpecifiers
.push_back("inline");
808 BadSpecifierLocs
.push_back(DS
.getInlineSpecLoc());
811 if (!BadSpecifiers
.empty()) {
812 auto &&Err
= Diag(BadSpecifierLocs
.front(), diag::err_decomp_decl_spec
);
813 Err
<< (int)BadSpecifiers
.size()
814 << llvm::join(BadSpecifiers
.begin(), BadSpecifiers
.end(), " ");
815 // Don't add FixItHints to remove the specifiers; we do still respect
816 // them when building the underlying variable.
817 for (auto Loc
: BadSpecifierLocs
)
818 Err
<< SourceRange(Loc
, Loc
);
819 } else if (!CPlusPlus20Specifiers
.empty()) {
820 auto &&Warn
= Diag(CPlusPlus20SpecifierLocs
.front(),
821 getLangOpts().CPlusPlus20
822 ? diag::warn_cxx17_compat_decomp_decl_spec
823 : diag::ext_decomp_decl_spec
);
824 Warn
<< (int)CPlusPlus20Specifiers
.size()
825 << llvm::join(CPlusPlus20Specifiers
.begin(),
826 CPlusPlus20Specifiers
.end(), " ");
827 for (auto Loc
: CPlusPlus20SpecifierLocs
)
828 Warn
<< SourceRange(Loc
, Loc
);
830 // We can't recover from it being declared as a typedef.
831 if (DS
.getStorageClassSpec() == DeclSpec::SCS_typedef
)
835 // C++2a [dcl.struct.bind]p1:
836 // A cv that includes volatile is deprecated
837 if ((DS
.getTypeQualifiers() & DeclSpec::TQ_volatile
) &&
838 getLangOpts().CPlusPlus20
)
839 Diag(DS
.getVolatileSpecLoc(),
840 diag::warn_deprecated_volatile_structured_binding
);
842 TypeSourceInfo
*TInfo
= GetTypeForDeclarator(D
, S
);
843 QualType R
= TInfo
->getType();
845 if (DiagnoseUnexpandedParameterPack(D
.getIdentifierLoc(), TInfo
,
846 UPPC_DeclarationType
))
849 // The syntax only allows a single ref-qualifier prior to the decomposition
850 // declarator. No other declarator chunks are permitted. Also check the type
852 if (DS
.getTypeSpecType() != DeclSpec::TST_auto
||
853 D
.hasGroupingParens() || D
.getNumTypeObjects() > 1 ||
854 (D
.getNumTypeObjects() == 1 &&
855 D
.getTypeObject(0).Kind
!= DeclaratorChunk::Reference
)) {
856 Diag(Decomp
.getLSquareLoc(),
857 (D
.hasGroupingParens() ||
858 (D
.getNumTypeObjects() &&
859 D
.getTypeObject(0).Kind
== DeclaratorChunk::Paren
))
860 ? diag::err_decomp_decl_parens
861 : diag::err_decomp_decl_type
)
864 // In most cases, there's no actual problem with an explicitly-specified
865 // type, but a function type won't work here, and ActOnVariableDeclarator
866 // shouldn't be called for such a type.
867 if (R
->isFunctionType())
871 // Constrained auto is prohibited by [decl.pre]p6, so check that here.
872 if (DS
.isConstrainedAuto()) {
873 TemplateIdAnnotation
*TemplRep
= DS
.getRepAsTemplateId();
874 assert(TemplRep
->Kind
== TNK_Concept_template
&&
875 "No other template kind should be possible for a constrained auto");
877 SourceRange TemplRange
{TemplRep
->TemplateNameLoc
,
878 TemplRep
->RAngleLoc
.isValid()
879 ? TemplRep
->RAngleLoc
880 : TemplRep
->TemplateNameLoc
};
881 Diag(TemplRep
->TemplateNameLoc
, diag::err_decomp_decl_constraint
)
882 << TemplRange
<< FixItHint::CreateRemoval(TemplRange
);
885 // Build the BindingDecls.
886 SmallVector
<BindingDecl
*, 8> Bindings
;
888 // Build the BindingDecls.
889 for (auto &B
: D
.getDecompositionDeclarator().bindings()) {
890 // Check for name conflicts.
891 DeclarationNameInfo
NameInfo(B
.Name
, B
.NameLoc
);
892 IdentifierInfo
*VarName
= B
.Name
;
893 assert(VarName
&& "Cannot have an unnamed binding declaration");
895 LookupResult
Previous(*this, NameInfo
, LookupOrdinaryName
,
896 ForVisibleRedeclaration
);
897 LookupName(Previous
, S
,
898 /*CreateBuiltins*/DC
->getRedeclContext()->isTranslationUnit());
900 // It's not permitted to shadow a template parameter name.
901 if (Previous
.isSingleResult() &&
902 Previous
.getFoundDecl()->isTemplateParameter()) {
903 DiagnoseTemplateParameterShadow(D
.getIdentifierLoc(),
904 Previous
.getFoundDecl());
908 auto *BD
= BindingDecl::Create(Context
, DC
, B
.NameLoc
, VarName
);
910 // Find the shadowed declaration before filtering for scope.
911 NamedDecl
*ShadowedDecl
= D
.getCXXScopeSpec().isEmpty()
912 ? getShadowedDeclaration(BD
, Previous
)
915 bool ConsiderLinkage
= DC
->isFunctionOrMethod() &&
916 DS
.getStorageClassSpec() == DeclSpec::SCS_extern
;
917 FilterLookupForScope(Previous
, DC
, S
, ConsiderLinkage
,
918 /*AllowInlineNamespace*/false);
920 bool IsPlaceholder
= DS
.getStorageClassSpec() != DeclSpec::SCS_static
&&
921 DC
->isFunctionOrMethod() && VarName
->isPlaceholder();
922 if (!Previous
.empty()) {
924 bool sameDC
= (Previous
.end() - 1)
927 ->Equals(DC
->getRedeclContext());
929 isDeclInScope(*(Previous
.end() - 1), CurContext
, S
, false)) {
931 DiagPlaceholderVariableDefinition(B
.NameLoc
);
934 auto *Old
= Previous
.getRepresentativeDecl();
935 Diag(B
.NameLoc
, diag::err_redefinition
) << B
.Name
;
936 Diag(Old
->getLocation(), diag::note_previous_definition
);
938 } else if (ShadowedDecl
&& !D
.isRedeclaration()) {
939 CheckShadow(BD
, ShadowedDecl
, Previous
);
941 PushOnScopeChains(BD
, S
, true);
942 Bindings
.push_back(BD
);
943 ParsingInitForAutoVars
.insert(BD
);
946 // There are no prior lookup results for the variable itself, because it
948 DeclarationNameInfo
NameInfo((IdentifierInfo
*)nullptr,
949 Decomp
.getLSquareLoc());
950 LookupResult
Previous(*this, NameInfo
, LookupOrdinaryName
,
951 ForVisibleRedeclaration
);
953 // Build the variable that holds the non-decomposed object.
954 bool AddToScope
= true;
956 ActOnVariableDeclarator(S
, D
, DC
, TInfo
, Previous
,
957 MultiTemplateParamsArg(), AddToScope
, Bindings
);
960 CurContext
->addHiddenDecl(New
);
963 if (isInOpenMPDeclareTargetContext())
964 checkDeclIsAllowedInOpenMPTarget(nullptr, New
);
969 static bool checkSimpleDecomposition(
970 Sema
&S
, ArrayRef
<BindingDecl
*> Bindings
, ValueDecl
*Src
,
971 QualType DecompType
, const llvm::APSInt
&NumElems
, QualType ElemType
,
972 llvm::function_ref
<ExprResult(SourceLocation
, Expr
*, unsigned)> GetInit
) {
973 if ((int64_t)Bindings
.size() != NumElems
) {
974 S
.Diag(Src
->getLocation(), diag::err_decomp_decl_wrong_number_bindings
)
975 << DecompType
<< (unsigned)Bindings
.size()
976 << (unsigned)NumElems
.getLimitedValue(UINT_MAX
)
977 << toString(NumElems
, 10) << (NumElems
< Bindings
.size());
982 for (auto *B
: Bindings
) {
983 SourceLocation Loc
= B
->getLocation();
984 ExprResult E
= S
.BuildDeclRefExpr(Src
, DecompType
, VK_LValue
, Loc
);
987 E
= GetInit(Loc
, E
.get(), I
++);
990 B
->setBinding(ElemType
, E
.get());
996 static bool checkArrayLikeDecomposition(Sema
&S
,
997 ArrayRef
<BindingDecl
*> Bindings
,
998 ValueDecl
*Src
, QualType DecompType
,
999 const llvm::APSInt
&NumElems
,
1000 QualType ElemType
) {
1001 return checkSimpleDecomposition(
1002 S
, Bindings
, Src
, DecompType
, NumElems
, ElemType
,
1003 [&](SourceLocation Loc
, Expr
*Base
, unsigned I
) -> ExprResult
{
1004 ExprResult E
= S
.ActOnIntegerConstant(Loc
, I
);
1007 return S
.CreateBuiltinArraySubscriptExpr(Base
, Loc
, E
.get(), Loc
);
1011 static bool checkArrayDecomposition(Sema
&S
, ArrayRef
<BindingDecl
*> Bindings
,
1012 ValueDecl
*Src
, QualType DecompType
,
1013 const ConstantArrayType
*CAT
) {
1014 return checkArrayLikeDecomposition(S
, Bindings
, Src
, DecompType
,
1015 llvm::APSInt(CAT
->getSize()),
1016 CAT
->getElementType());
1019 static bool checkVectorDecomposition(Sema
&S
, ArrayRef
<BindingDecl
*> Bindings
,
1020 ValueDecl
*Src
, QualType DecompType
,
1021 const VectorType
*VT
) {
1022 return checkArrayLikeDecomposition(
1023 S
, Bindings
, Src
, DecompType
, llvm::APSInt::get(VT
->getNumElements()),
1024 S
.Context
.getQualifiedType(VT
->getElementType(),
1025 DecompType
.getQualifiers()));
1028 static bool checkComplexDecomposition(Sema
&S
,
1029 ArrayRef
<BindingDecl
*> Bindings
,
1030 ValueDecl
*Src
, QualType DecompType
,
1031 const ComplexType
*CT
) {
1032 return checkSimpleDecomposition(
1033 S
, Bindings
, Src
, DecompType
, llvm::APSInt::get(2),
1034 S
.Context
.getQualifiedType(CT
->getElementType(),
1035 DecompType
.getQualifiers()),
1036 [&](SourceLocation Loc
, Expr
*Base
, unsigned I
) -> ExprResult
{
1037 return S
.CreateBuiltinUnaryOp(Loc
, I
? UO_Imag
: UO_Real
, Base
);
1041 static std::string
printTemplateArgs(const PrintingPolicy
&PrintingPolicy
,
1042 TemplateArgumentListInfo
&Args
,
1043 const TemplateParameterList
*Params
) {
1044 SmallString
<128> SS
;
1045 llvm::raw_svector_ostream
OS(SS
);
1048 for (auto &Arg
: Args
.arguments()) {
1051 Arg
.getArgument().print(PrintingPolicy
, OS
,
1052 TemplateParameterList::shouldIncludeTypeForArgument(
1053 PrintingPolicy
, Params
, I
));
1057 return std::string(OS
.str());
1060 static bool lookupStdTypeTraitMember(Sema
&S
, LookupResult
&TraitMemberLookup
,
1061 SourceLocation Loc
, StringRef Trait
,
1062 TemplateArgumentListInfo
&Args
,
1064 auto DiagnoseMissing
= [&] {
1066 S
.Diag(Loc
, DiagID
) << printTemplateArgs(S
.Context
.getPrintingPolicy(),
1067 Args
, /*Params*/ nullptr);
1071 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
1072 NamespaceDecl
*Std
= S
.getStdNamespace();
1074 return DiagnoseMissing();
1076 // Look up the trait itself, within namespace std. We can diagnose various
1077 // problems with this lookup even if we've been asked to not diagnose a
1078 // missing specialization, because this can only fail if the user has been
1079 // declaring their own names in namespace std or we don't support the
1080 // standard library implementation in use.
1081 LookupResult
Result(S
, &S
.PP
.getIdentifierTable().get(Trait
),
1082 Loc
, Sema::LookupOrdinaryName
);
1083 if (!S
.LookupQualifiedName(Result
, Std
))
1084 return DiagnoseMissing();
1085 if (Result
.isAmbiguous())
1088 ClassTemplateDecl
*TraitTD
= Result
.getAsSingle
<ClassTemplateDecl
>();
1090 Result
.suppressDiagnostics();
1091 NamedDecl
*Found
= *Result
.begin();
1092 S
.Diag(Loc
, diag::err_std_type_trait_not_class_template
) << Trait
;
1093 S
.Diag(Found
->getLocation(), diag::note_declared_at
);
1097 // Build the template-id.
1098 QualType TraitTy
= S
.CheckTemplateIdType(TemplateName(TraitTD
), Loc
, Args
);
1099 if (TraitTy
.isNull())
1101 if (!S
.isCompleteType(Loc
, TraitTy
)) {
1103 S
.RequireCompleteType(
1104 Loc
, TraitTy
, DiagID
,
1105 printTemplateArgs(S
.Context
.getPrintingPolicy(), Args
,
1106 TraitTD
->getTemplateParameters()));
1110 CXXRecordDecl
*RD
= TraitTy
->getAsCXXRecordDecl();
1111 assert(RD
&& "specialization of class template is not a class?");
1113 // Look up the member of the trait type.
1114 S
.LookupQualifiedName(TraitMemberLookup
, RD
);
1115 return TraitMemberLookup
.isAmbiguous();
1118 static TemplateArgumentLoc
1119 getTrivialIntegralTemplateArgument(Sema
&S
, SourceLocation Loc
, QualType T
,
1121 TemplateArgument
Arg(S
.Context
, S
.Context
.MakeIntValue(I
, T
), T
);
1122 return S
.getTrivialTemplateArgumentLoc(Arg
, T
, Loc
);
1125 static TemplateArgumentLoc
1126 getTrivialTypeTemplateArgument(Sema
&S
, SourceLocation Loc
, QualType T
) {
1127 return S
.getTrivialTemplateArgumentLoc(TemplateArgument(T
), QualType(), Loc
);
1130 namespace { enum class IsTupleLike
{ TupleLike
, NotTupleLike
, Error
}; }
1132 static IsTupleLike
isTupleLike(Sema
&S
, SourceLocation Loc
, QualType T
,
1133 llvm::APSInt
&Size
) {
1134 EnterExpressionEvaluationContext
ContextRAII(
1135 S
, Sema::ExpressionEvaluationContext::ConstantEvaluated
);
1137 DeclarationName Value
= S
.PP
.getIdentifierInfo("value");
1138 LookupResult
R(S
, Value
, Loc
, Sema::LookupOrdinaryName
);
1140 // Form template argument list for tuple_size<T>.
1141 TemplateArgumentListInfo
Args(Loc
, Loc
);
1142 Args
.addArgument(getTrivialTypeTemplateArgument(S
, Loc
, T
));
1144 // If there's no tuple_size specialization or the lookup of 'value' is empty,
1145 // it's not tuple-like.
1146 if (lookupStdTypeTraitMember(S
, R
, Loc
, "tuple_size", Args
, /*DiagID*/ 0) ||
1148 return IsTupleLike::NotTupleLike
;
1150 // If we get this far, we've committed to the tuple interpretation, but
1151 // we can still fail if there actually isn't a usable ::value.
1153 struct ICEDiagnoser
: Sema::VerifyICEDiagnoser
{
1155 TemplateArgumentListInfo
&Args
;
1156 ICEDiagnoser(LookupResult
&R
, TemplateArgumentListInfo
&Args
)
1157 : R(R
), Args(Args
) {}
1158 Sema::SemaDiagnosticBuilder
diagnoseNotICE(Sema
&S
,
1159 SourceLocation Loc
) override
{
1160 return S
.Diag(Loc
, diag::err_decomp_decl_std_tuple_size_not_constant
)
1161 << printTemplateArgs(S
.Context
.getPrintingPolicy(), Args
,
1162 /*Params*/ nullptr);
1164 } Diagnoser(R
, Args
);
1167 S
.BuildDeclarationNameExpr(CXXScopeSpec(), R
, /*NeedsADL*/false);
1169 return IsTupleLike::Error
;
1171 E
= S
.VerifyIntegerConstantExpression(E
.get(), &Size
, Diagnoser
);
1173 return IsTupleLike::Error
;
1175 return IsTupleLike::TupleLike
;
1178 /// \return std::tuple_element<I, T>::type.
1179 static QualType
getTupleLikeElementType(Sema
&S
, SourceLocation Loc
,
1180 unsigned I
, QualType T
) {
1181 // Form template argument list for tuple_element<I, T>.
1182 TemplateArgumentListInfo
Args(Loc
, Loc
);
1184 getTrivialIntegralTemplateArgument(S
, Loc
, S
.Context
.getSizeType(), I
));
1185 Args
.addArgument(getTrivialTypeTemplateArgument(S
, Loc
, T
));
1187 DeclarationName TypeDN
= S
.PP
.getIdentifierInfo("type");
1188 LookupResult
R(S
, TypeDN
, Loc
, Sema::LookupOrdinaryName
);
1189 if (lookupStdTypeTraitMember(
1190 S
, R
, Loc
, "tuple_element", Args
,
1191 diag::err_decomp_decl_std_tuple_element_not_specialized
))
1194 auto *TD
= R
.getAsSingle
<TypeDecl
>();
1196 R
.suppressDiagnostics();
1197 S
.Diag(Loc
, diag::err_decomp_decl_std_tuple_element_not_specialized
)
1198 << printTemplateArgs(S
.Context
.getPrintingPolicy(), Args
,
1199 /*Params*/ nullptr);
1201 S
.Diag(R
.getRepresentativeDecl()->getLocation(), diag::note_declared_at
);
1205 return S
.Context
.getTypeDeclType(TD
);
1209 struct InitializingBinding
{
1211 InitializingBinding(Sema
&S
, BindingDecl
*BD
) : S(S
) {
1212 Sema::CodeSynthesisContext Ctx
;
1213 Ctx
.Kind
= Sema::CodeSynthesisContext::InitializingStructuredBinding
;
1214 Ctx
.PointOfInstantiation
= BD
->getLocation();
1216 S
.pushCodeSynthesisContext(Ctx
);
1218 ~InitializingBinding() {
1219 S
.popCodeSynthesisContext();
1224 static bool checkTupleLikeDecomposition(Sema
&S
,
1225 ArrayRef
<BindingDecl
*> Bindings
,
1226 VarDecl
*Src
, QualType DecompType
,
1227 const llvm::APSInt
&TupleSize
) {
1228 if ((int64_t)Bindings
.size() != TupleSize
) {
1229 S
.Diag(Src
->getLocation(), diag::err_decomp_decl_wrong_number_bindings
)
1230 << DecompType
<< (unsigned)Bindings
.size()
1231 << (unsigned)TupleSize
.getLimitedValue(UINT_MAX
)
1232 << toString(TupleSize
, 10) << (TupleSize
< Bindings
.size());
1236 if (Bindings
.empty())
1239 DeclarationName GetDN
= S
.PP
.getIdentifierInfo("get");
1242 // The unqualified-id get is looked up in the scope of E by class member
1243 // access lookup ...
1244 LookupResult
MemberGet(S
, GetDN
, Src
->getLocation(), Sema::LookupMemberName
);
1245 bool UseMemberGet
= false;
1246 if (S
.isCompleteType(Src
->getLocation(), DecompType
)) {
1247 if (auto *RD
= DecompType
->getAsCXXRecordDecl())
1248 S
.LookupQualifiedName(MemberGet
, RD
);
1249 if (MemberGet
.isAmbiguous())
1251 // ... and if that finds at least one declaration that is a function
1252 // template whose first template parameter is a non-type parameter ...
1253 for (NamedDecl
*D
: MemberGet
) {
1254 if (FunctionTemplateDecl
*FTD
=
1255 dyn_cast
<FunctionTemplateDecl
>(D
->getUnderlyingDecl())) {
1256 TemplateParameterList
*TPL
= FTD
->getTemplateParameters();
1257 if (TPL
->size() != 0 &&
1258 isa
<NonTypeTemplateParmDecl
>(TPL
->getParam(0))) {
1259 // ... the initializer is e.get<i>().
1260 UseMemberGet
= true;
1268 for (auto *B
: Bindings
) {
1269 InitializingBinding
InitContext(S
, B
);
1270 SourceLocation Loc
= B
->getLocation();
1272 ExprResult E
= S
.BuildDeclRefExpr(Src
, DecompType
, VK_LValue
, Loc
);
1276 // e is an lvalue if the type of the entity is an lvalue reference and
1277 // an xvalue otherwise
1278 if (!Src
->getType()->isLValueReferenceType())
1279 E
= ImplicitCastExpr::Create(S
.Context
, E
.get()->getType(), CK_NoOp
,
1280 E
.get(), nullptr, VK_XValue
,
1281 FPOptionsOverride());
1283 TemplateArgumentListInfo
Args(Loc
, Loc
);
1285 getTrivialIntegralTemplateArgument(S
, Loc
, S
.Context
.getSizeType(), I
));
1288 // if [lookup of member get] finds at least one declaration, the
1289 // initializer is e.get<i-1>().
1290 E
= S
.BuildMemberReferenceExpr(E
.get(), DecompType
, Loc
, false,
1291 CXXScopeSpec(), SourceLocation(), nullptr,
1292 MemberGet
, &Args
, nullptr);
1296 E
= S
.BuildCallExpr(nullptr, E
.get(), Loc
, std::nullopt
, Loc
);
1298 // Otherwise, the initializer is get<i-1>(e), where get is looked up
1299 // in the associated namespaces.
1300 Expr
*Get
= UnresolvedLookupExpr::Create(
1301 S
.Context
, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
1302 DeclarationNameInfo(GetDN
, Loc
), /*RequiresADL*/ true, &Args
,
1303 UnresolvedSetIterator(), UnresolvedSetIterator(),
1304 /*KnownDependent=*/false);
1306 Expr
*Arg
= E
.get();
1307 E
= S
.BuildCallExpr(nullptr, Get
, Loc
, Arg
, Loc
);
1311 Expr
*Init
= E
.get();
1313 // Given the type T designated by std::tuple_element<i - 1, E>::type,
1314 QualType T
= getTupleLikeElementType(S
, Loc
, I
, DecompType
);
1318 // each vi is a variable of type "reference to T" initialized with the
1319 // initializer, where the reference is an lvalue reference if the
1320 // initializer is an lvalue and an rvalue reference otherwise
1322 S
.BuildReferenceType(T
, E
.get()->isLValue(), Loc
, B
->getDeclName());
1323 if (RefType
.isNull())
1325 auto *RefVD
= VarDecl::Create(
1326 S
.Context
, Src
->getDeclContext(), Loc
, Loc
,
1327 B
->getDeclName().getAsIdentifierInfo(), RefType
,
1328 S
.Context
.getTrivialTypeSourceInfo(T
, Loc
), Src
->getStorageClass());
1329 RefVD
->setLexicalDeclContext(Src
->getLexicalDeclContext());
1330 RefVD
->setTSCSpec(Src
->getTSCSpec());
1331 RefVD
->setImplicit();
1332 if (Src
->isInlineSpecified())
1333 RefVD
->setInlineSpecified();
1334 RefVD
->getLexicalDeclContext()->addHiddenDecl(RefVD
);
1336 InitializedEntity Entity
= InitializedEntity::InitializeBinding(RefVD
);
1337 InitializationKind Kind
= InitializationKind::CreateCopy(Loc
, Loc
);
1338 InitializationSequence
Seq(S
, Entity
, Kind
, Init
);
1339 E
= Seq
.Perform(S
, Entity
, Kind
, Init
);
1342 E
= S
.ActOnFinishFullExpr(E
.get(), Loc
, /*DiscardedValue*/ false);
1345 RefVD
->setInit(E
.get());
1346 S
.CheckCompleteVariableDeclaration(RefVD
);
1348 E
= S
.BuildDeclarationNameExpr(CXXScopeSpec(),
1349 DeclarationNameInfo(B
->getDeclName(), Loc
),
1354 B
->setBinding(T
, E
.get());
1361 /// Find the base class to decompose in a built-in decomposition of a class type.
1362 /// This base class search is, unfortunately, not quite like any other that we
1363 /// perform anywhere else in C++.
1364 static DeclAccessPair
findDecomposableBaseClass(Sema
&S
, SourceLocation Loc
,
1365 const CXXRecordDecl
*RD
,
1366 CXXCastPath
&BasePath
) {
1367 auto BaseHasFields
= [](const CXXBaseSpecifier
*Specifier
,
1368 CXXBasePath
&Path
) {
1369 return Specifier
->getType()->getAsCXXRecordDecl()->hasDirectFields();
1372 const CXXRecordDecl
*ClassWithFields
= nullptr;
1373 AccessSpecifier AS
= AS_public
;
1374 if (RD
->hasDirectFields())
1376 // Otherwise, all of E's non-static data members shall be public direct
1378 ClassWithFields
= RD
;
1382 Paths
.setOrigin(const_cast<CXXRecordDecl
*>(RD
));
1383 if (!RD
->lookupInBases(BaseHasFields
, Paths
)) {
1384 // If no classes have fields, just decompose RD itself. (This will work
1385 // if and only if zero bindings were provided.)
1386 return DeclAccessPair::make(const_cast<CXXRecordDecl
*>(RD
), AS_public
);
1389 CXXBasePath
*BestPath
= nullptr;
1390 for (auto &P
: Paths
) {
1393 else if (!S
.Context
.hasSameType(P
.back().Base
->getType(),
1394 BestPath
->back().Base
->getType())) {
1396 S
.Diag(Loc
, diag::err_decomp_decl_multiple_bases_with_members
)
1397 << false << RD
<< BestPath
->back().Base
->getType()
1398 << P
.back().Base
->getType();
1399 return DeclAccessPair();
1400 } else if (P
.Access
< BestPath
->Access
) {
1405 // ... unambiguous ...
1406 QualType BaseType
= BestPath
->back().Base
->getType();
1407 if (Paths
.isAmbiguous(S
.Context
.getCanonicalType(BaseType
))) {
1408 S
.Diag(Loc
, diag::err_decomp_decl_ambiguous_base
)
1409 << RD
<< BaseType
<< S
.getAmbiguousPathsDisplayString(Paths
);
1410 return DeclAccessPair();
1413 // ... [accessible, implied by other rules] base class of E.
1414 S
.CheckBaseClassAccess(Loc
, BaseType
, S
.Context
.getRecordType(RD
),
1415 *BestPath
, diag::err_decomp_decl_inaccessible_base
);
1416 AS
= BestPath
->Access
;
1418 ClassWithFields
= BaseType
->getAsCXXRecordDecl();
1419 S
.BuildBasePathArray(Paths
, BasePath
);
1422 // The above search did not check whether the selected class itself has base
1423 // classes with fields, so check that now.
1425 if (ClassWithFields
->lookupInBases(BaseHasFields
, Paths
)) {
1426 S
.Diag(Loc
, diag::err_decomp_decl_multiple_bases_with_members
)
1427 << (ClassWithFields
== RD
) << RD
<< ClassWithFields
1428 << Paths
.front().back().Base
->getType();
1429 return DeclAccessPair();
1432 return DeclAccessPair::make(const_cast<CXXRecordDecl
*>(ClassWithFields
), AS
);
1435 static bool checkMemberDecomposition(Sema
&S
, ArrayRef
<BindingDecl
*> Bindings
,
1436 ValueDecl
*Src
, QualType DecompType
,
1437 const CXXRecordDecl
*OrigRD
) {
1438 if (S
.RequireCompleteType(Src
->getLocation(), DecompType
,
1439 diag::err_incomplete_type
))
1442 CXXCastPath BasePath
;
1443 DeclAccessPair BasePair
=
1444 findDecomposableBaseClass(S
, Src
->getLocation(), OrigRD
, BasePath
);
1445 const CXXRecordDecl
*RD
= cast_or_null
<CXXRecordDecl
>(BasePair
.getDecl());
1448 QualType BaseType
= S
.Context
.getQualifiedType(S
.Context
.getRecordType(RD
),
1449 DecompType
.getQualifiers());
1451 auto DiagnoseBadNumberOfBindings
= [&]() -> bool {
1452 unsigned NumFields
= llvm::count_if(
1453 RD
->fields(), [](FieldDecl
*FD
) { return !FD
->isUnnamedBitfield(); });
1454 assert(Bindings
.size() != NumFields
);
1455 S
.Diag(Src
->getLocation(), diag::err_decomp_decl_wrong_number_bindings
)
1456 << DecompType
<< (unsigned)Bindings
.size() << NumFields
<< NumFields
1457 << (NumFields
< Bindings
.size());
1461 // all of E's non-static data members shall be [...] well-formed
1462 // when named as e.name in the context of the structured binding,
1463 // E shall not have an anonymous union member, ...
1465 for (auto *FD
: RD
->fields()) {
1466 if (FD
->isUnnamedBitfield())
1469 // All the non-static data members are required to be nameable, so they
1470 // must all have names.
1471 if (!FD
->getDeclName()) {
1472 if (RD
->isLambda()) {
1473 S
.Diag(Src
->getLocation(), diag::err_decomp_decl_lambda
);
1474 S
.Diag(RD
->getLocation(), diag::note_lambda_decl
);
1478 if (FD
->isAnonymousStructOrUnion()) {
1479 S
.Diag(Src
->getLocation(), diag::err_decomp_decl_anon_union_member
)
1480 << DecompType
<< FD
->getType()->isUnionType();
1481 S
.Diag(FD
->getLocation(), diag::note_declared_at
);
1485 // FIXME: Are there any other ways we could have an anonymous member?
1488 // We have a real field to bind.
1489 if (I
>= Bindings
.size())
1490 return DiagnoseBadNumberOfBindings();
1491 auto *B
= Bindings
[I
++];
1492 SourceLocation Loc
= B
->getLocation();
1494 // The field must be accessible in the context of the structured binding.
1495 // We already checked that the base class is accessible.
1496 // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1498 S
.CheckStructuredBindingMemberAccess(
1499 Loc
, const_cast<CXXRecordDecl
*>(OrigRD
),
1500 DeclAccessPair::make(FD
, CXXRecordDecl::MergeAccess(
1501 BasePair
.getAccess(), FD
->getAccess())));
1503 // Initialize the binding to Src.FD.
1504 ExprResult E
= S
.BuildDeclRefExpr(Src
, DecompType
, VK_LValue
, Loc
);
1507 E
= S
.ImpCastExprToType(E
.get(), BaseType
, CK_UncheckedDerivedToBase
,
1508 VK_LValue
, &BasePath
);
1511 E
= S
.BuildFieldReferenceExpr(E
.get(), /*IsArrow*/ false, Loc
,
1513 DeclAccessPair::make(FD
, FD
->getAccess()),
1514 DeclarationNameInfo(FD
->getDeclName(), Loc
));
1518 // If the type of the member is T, the referenced type is cv T, where cv is
1519 // the cv-qualification of the decomposition expression.
1521 // FIXME: We resolve a defect here: if the field is mutable, we do not add
1522 // 'const' to the type of the field.
1523 Qualifiers Q
= DecompType
.getQualifiers();
1524 if (FD
->isMutable())
1526 B
->setBinding(S
.BuildQualifiedType(FD
->getType(), Loc
, Q
), E
.get());
1529 if (I
!= Bindings
.size())
1530 return DiagnoseBadNumberOfBindings();
1535 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl
*DD
) {
1536 QualType DecompType
= DD
->getType();
1538 // If the type of the decomposition is dependent, then so is the type of
1540 if (DecompType
->isDependentType()) {
1541 for (auto *B
: DD
->bindings())
1542 B
->setType(Context
.DependentTy
);
1546 DecompType
= DecompType
.getNonReferenceType();
1547 ArrayRef
<BindingDecl
*> Bindings
= DD
->bindings();
1549 // C++1z [dcl.decomp]/2:
1550 // If E is an array type [...]
1551 // As an extension, we also support decomposition of built-in complex and
1553 if (auto *CAT
= Context
.getAsConstantArrayType(DecompType
)) {
1554 if (checkArrayDecomposition(*this, Bindings
, DD
, DecompType
, CAT
))
1555 DD
->setInvalidDecl();
1558 if (auto *VT
= DecompType
->getAs
<VectorType
>()) {
1559 if (checkVectorDecomposition(*this, Bindings
, DD
, DecompType
, VT
))
1560 DD
->setInvalidDecl();
1563 if (auto *CT
= DecompType
->getAs
<ComplexType
>()) {
1564 if (checkComplexDecomposition(*this, Bindings
, DD
, DecompType
, CT
))
1565 DD
->setInvalidDecl();
1569 // C++1z [dcl.decomp]/3:
1570 // if the expression std::tuple_size<E>::value is a well-formed integral
1571 // constant expression, [...]
1572 llvm::APSInt
TupleSize(32);
1573 switch (isTupleLike(*this, DD
->getLocation(), DecompType
, TupleSize
)) {
1574 case IsTupleLike::Error
:
1575 DD
->setInvalidDecl();
1578 case IsTupleLike::TupleLike
:
1579 if (checkTupleLikeDecomposition(*this, Bindings
, DD
, DecompType
, TupleSize
))
1580 DD
->setInvalidDecl();
1583 case IsTupleLike::NotTupleLike
:
1587 // C++1z [dcl.dcl]/8:
1588 // [E shall be of array or non-union class type]
1589 CXXRecordDecl
*RD
= DecompType
->getAsCXXRecordDecl();
1590 if (!RD
|| RD
->isUnion()) {
1591 Diag(DD
->getLocation(), diag::err_decomp_decl_unbindable_type
)
1592 << DD
<< !RD
<< DecompType
;
1593 DD
->setInvalidDecl();
1597 // C++1z [dcl.decomp]/4:
1598 // all of E's non-static data members shall be [...] direct members of
1599 // E or of the same unambiguous public base class of E, ...
1600 if (checkMemberDecomposition(*this, Bindings
, DD
, DecompType
, RD
))
1601 DD
->setInvalidDecl();
1604 /// Merge the exception specifications of two variable declarations.
1606 /// This is called when there's a redeclaration of a VarDecl. The function
1607 /// checks if the redeclaration might have an exception specification and
1608 /// validates compatibility and merges the specs if necessary.
1609 void Sema::MergeVarDeclExceptionSpecs(VarDecl
*New
, VarDecl
*Old
) {
1610 // Shortcut if exceptions are disabled.
1611 if (!getLangOpts().CXXExceptions
)
1614 assert(Context
.hasSameType(New
->getType(), Old
->getType()) &&
1615 "Should only be called if types are otherwise the same.");
1617 QualType NewType
= New
->getType();
1618 QualType OldType
= Old
->getType();
1620 // We're only interested in pointers and references to functions, as well
1621 // as pointers to member functions.
1622 if (const ReferenceType
*R
= NewType
->getAs
<ReferenceType
>()) {
1623 NewType
= R
->getPointeeType();
1624 OldType
= OldType
->castAs
<ReferenceType
>()->getPointeeType();
1625 } else if (const PointerType
*P
= NewType
->getAs
<PointerType
>()) {
1626 NewType
= P
->getPointeeType();
1627 OldType
= OldType
->castAs
<PointerType
>()->getPointeeType();
1628 } else if (const MemberPointerType
*M
= NewType
->getAs
<MemberPointerType
>()) {
1629 NewType
= M
->getPointeeType();
1630 OldType
= OldType
->castAs
<MemberPointerType
>()->getPointeeType();
1633 if (!NewType
->isFunctionProtoType())
1636 // There's lots of special cases for functions. For function pointers, system
1637 // libraries are hopefully not as broken so that we don't need these
1639 if (CheckEquivalentExceptionSpec(
1640 OldType
->getAs
<FunctionProtoType
>(), Old
->getLocation(),
1641 NewType
->getAs
<FunctionProtoType
>(), New
->getLocation())) {
1642 New
->setInvalidDecl();
1646 /// CheckCXXDefaultArguments - Verify that the default arguments for a
1647 /// function declaration are well-formed according to C++
1648 /// [dcl.fct.default].
1649 void Sema::CheckCXXDefaultArguments(FunctionDecl
*FD
) {
1650 unsigned NumParams
= FD
->getNumParams();
1651 unsigned ParamIdx
= 0;
1653 // This checking doesn't make sense for explicit specializations; their
1654 // default arguments are determined by the declaration we're specializing,
1656 if (FD
->getTemplateSpecializationKind() == TSK_ExplicitSpecialization
)
1658 if (auto *FTD
= FD
->getDescribedFunctionTemplate())
1659 if (FTD
->isMemberSpecialization())
1662 // Find first parameter with a default argument
1663 for (; ParamIdx
< NumParams
; ++ParamIdx
) {
1664 ParmVarDecl
*Param
= FD
->getParamDecl(ParamIdx
);
1665 if (Param
->hasDefaultArg())
1669 // C++20 [dcl.fct.default]p4:
1670 // In a given function declaration, each parameter subsequent to a parameter
1671 // with a default argument shall have a default argument supplied in this or
1672 // a previous declaration, unless the parameter was expanded from a
1673 // parameter pack, or shall be a function parameter pack.
1674 for (; ParamIdx
< NumParams
; ++ParamIdx
) {
1675 ParmVarDecl
*Param
= FD
->getParamDecl(ParamIdx
);
1676 if (!Param
->hasDefaultArg() && !Param
->isParameterPack() &&
1677 !(CurrentInstantiationScope
&&
1678 CurrentInstantiationScope
->isLocalPackExpansion(Param
))) {
1679 if (Param
->isInvalidDecl())
1680 /* We already complained about this parameter. */;
1681 else if (Param
->getIdentifier())
1682 Diag(Param
->getLocation(),
1683 diag::err_param_default_argument_missing_name
)
1684 << Param
->getIdentifier();
1686 Diag(Param
->getLocation(),
1687 diag::err_param_default_argument_missing
);
1692 /// Check that the given type is a literal type. Issue a diagnostic if not,
1693 /// if Kind is Diagnose.
1694 /// \return \c true if a problem has been found (and optionally diagnosed).
1695 template <typename
... Ts
>
1696 static bool CheckLiteralType(Sema
&SemaRef
, Sema::CheckConstexprKind Kind
,
1697 SourceLocation Loc
, QualType T
, unsigned DiagID
,
1699 if (T
->isDependentType())
1703 case Sema::CheckConstexprKind::Diagnose
:
1704 return SemaRef
.RequireLiteralType(Loc
, T
, DiagID
,
1705 std::forward
<Ts
>(DiagArgs
)...);
1707 case Sema::CheckConstexprKind::CheckValid
:
1708 return !T
->isLiteralType(SemaRef
.Context
);
1711 llvm_unreachable("unknown CheckConstexprKind");
1714 /// Determine whether a destructor cannot be constexpr due to
1715 static bool CheckConstexprDestructorSubobjects(Sema
&SemaRef
,
1716 const CXXDestructorDecl
*DD
,
1717 Sema::CheckConstexprKind Kind
) {
1718 auto Check
= [&](SourceLocation Loc
, QualType T
, const FieldDecl
*FD
) {
1719 const CXXRecordDecl
*RD
=
1720 T
->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1721 if (!RD
|| RD
->hasConstexprDestructor())
1724 if (Kind
== Sema::CheckConstexprKind::Diagnose
) {
1725 SemaRef
.Diag(DD
->getLocation(), diag::err_constexpr_dtor_subobject
)
1726 << static_cast<int>(DD
->getConstexprKind()) << !FD
1727 << (FD
? FD
->getDeclName() : DeclarationName()) << T
;
1728 SemaRef
.Diag(Loc
, diag::note_constexpr_dtor_subobject
)
1729 << !FD
<< (FD
? FD
->getDeclName() : DeclarationName()) << T
;
1734 const CXXRecordDecl
*RD
= DD
->getParent();
1735 for (const CXXBaseSpecifier
&B
: RD
->bases())
1736 if (!Check(B
.getBaseTypeLoc(), B
.getType(), nullptr))
1738 for (const FieldDecl
*FD
: RD
->fields())
1739 if (!Check(FD
->getLocation(), FD
->getType(), FD
))
1744 /// Check whether a function's parameter types are all literal types. If so,
1745 /// return true. If not, produce a suitable diagnostic and return false.
1746 static bool CheckConstexprParameterTypes(Sema
&SemaRef
,
1747 const FunctionDecl
*FD
,
1748 Sema::CheckConstexprKind Kind
) {
1749 unsigned ArgIndex
= 0;
1750 const auto *FT
= FD
->getType()->castAs
<FunctionProtoType
>();
1751 for (FunctionProtoType::param_type_iterator i
= FT
->param_type_begin(),
1752 e
= FT
->param_type_end();
1753 i
!= e
; ++i
, ++ArgIndex
) {
1754 const ParmVarDecl
*PD
= FD
->getParamDecl(ArgIndex
);
1755 assert(PD
&& "null in a parameter list");
1756 SourceLocation ParamLoc
= PD
->getLocation();
1757 if (CheckLiteralType(SemaRef
, Kind
, ParamLoc
, *i
,
1758 diag::err_constexpr_non_literal_param
, ArgIndex
+ 1,
1759 PD
->getSourceRange(), isa
<CXXConstructorDecl
>(FD
),
1766 /// Check whether a function's return type is a literal type. If so, return
1767 /// true. If not, produce a suitable diagnostic and return false.
1768 static bool CheckConstexprReturnType(Sema
&SemaRef
, const FunctionDecl
*FD
,
1769 Sema::CheckConstexprKind Kind
) {
1770 if (CheckLiteralType(SemaRef
, Kind
, FD
->getLocation(), FD
->getReturnType(),
1771 diag::err_constexpr_non_literal_return
,
1777 /// Get diagnostic %select index for tag kind for
1778 /// record diagnostic message.
1779 /// WARNING: Indexes apply to particular diagnostics only!
1781 /// \returns diagnostic %select index.
1782 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag
) {
1784 case TTK_Struct
: return 0;
1785 case TTK_Interface
: return 1;
1786 case TTK_Class
: return 2;
1787 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1791 static bool CheckConstexprFunctionBody(Sema
&SemaRef
, const FunctionDecl
*Dcl
,
1793 Sema::CheckConstexprKind Kind
);
1795 // Check whether a function declaration satisfies the requirements of a
1796 // constexpr function definition or a constexpr constructor definition. If so,
1797 // return true. If not, produce appropriate diagnostics (unless asked not to by
1798 // Kind) and return false.
1800 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1801 bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl
*NewFD
,
1802 CheckConstexprKind Kind
) {
1803 const CXXMethodDecl
*MD
= dyn_cast
<CXXMethodDecl
>(NewFD
);
1804 if (MD
&& MD
->isInstance()) {
1805 // C++11 [dcl.constexpr]p4:
1806 // The definition of a constexpr constructor shall satisfy the following
1808 // - the class shall not have any virtual base classes;
1810 // FIXME: This only applies to constructors and destructors, not arbitrary
1811 // member functions.
1812 const CXXRecordDecl
*RD
= MD
->getParent();
1813 if (RD
->getNumVBases()) {
1814 if (Kind
== CheckConstexprKind::CheckValid
)
1817 Diag(NewFD
->getLocation(), diag::err_constexpr_virtual_base
)
1818 << isa
<CXXConstructorDecl
>(NewFD
)
1819 << getRecordDiagFromTagKind(RD
->getTagKind()) << RD
->getNumVBases();
1820 for (const auto &I
: RD
->vbases())
1821 Diag(I
.getBeginLoc(), diag::note_constexpr_virtual_base_here
)
1822 << I
.getSourceRange();
1827 if (!isa
<CXXConstructorDecl
>(NewFD
)) {
1828 // C++11 [dcl.constexpr]p3:
1829 // The definition of a constexpr function shall satisfy the following
1831 // - it shall not be virtual; (removed in C++20)
1832 const CXXMethodDecl
*Method
= dyn_cast
<CXXMethodDecl
>(NewFD
);
1833 if (Method
&& Method
->isVirtual()) {
1834 if (getLangOpts().CPlusPlus20
) {
1835 if (Kind
== CheckConstexprKind::Diagnose
)
1836 Diag(Method
->getLocation(), diag::warn_cxx17_compat_constexpr_virtual
);
1838 if (Kind
== CheckConstexprKind::CheckValid
)
1841 Method
= Method
->getCanonicalDecl();
1842 Diag(Method
->getLocation(), diag::err_constexpr_virtual
);
1844 // If it's not obvious why this function is virtual, find an overridden
1845 // function which uses the 'virtual' keyword.
1846 const CXXMethodDecl
*WrittenVirtual
= Method
;
1847 while (!WrittenVirtual
->isVirtualAsWritten())
1848 WrittenVirtual
= *WrittenVirtual
->begin_overridden_methods();
1849 if (WrittenVirtual
!= Method
)
1850 Diag(WrittenVirtual
->getLocation(),
1851 diag::note_overridden_virtual_function
);
1856 // - its return type shall be a literal type;
1857 if (!CheckConstexprReturnType(*this, NewFD
, Kind
))
1861 if (auto *Dtor
= dyn_cast
<CXXDestructorDecl
>(NewFD
)) {
1862 // A destructor can be constexpr only if the defaulted destructor could be;
1863 // we don't need to check the members and bases if we already know they all
1864 // have constexpr destructors.
1865 if (!Dtor
->getParent()->defaultedDestructorIsConstexpr()) {
1866 if (Kind
== CheckConstexprKind::CheckValid
)
1868 if (!CheckConstexprDestructorSubobjects(*this, Dtor
, Kind
))
1873 // - each of its parameter types shall be a literal type;
1874 if (!CheckConstexprParameterTypes(*this, NewFD
, Kind
))
1877 Stmt
*Body
= NewFD
->getBody();
1879 "CheckConstexprFunctionDefinition called on function with no body");
1880 return CheckConstexprFunctionBody(*this, NewFD
, Body
, Kind
);
1883 /// Check the given declaration statement is legal within a constexpr function
1884 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1886 /// \return true if the body is OK (maybe only as an extension), false if we
1887 /// have diagnosed a problem.
1888 static bool CheckConstexprDeclStmt(Sema
&SemaRef
, const FunctionDecl
*Dcl
,
1889 DeclStmt
*DS
, SourceLocation
&Cxx1yLoc
,
1890 Sema::CheckConstexprKind Kind
) {
1891 // C++11 [dcl.constexpr]p3 and p4:
1892 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
1894 for (const auto *DclIt
: DS
->decls()) {
1895 switch (DclIt
->getKind()) {
1896 case Decl::StaticAssert
:
1898 case Decl::UsingShadow
:
1899 case Decl::UsingDirective
:
1900 case Decl::UnresolvedUsingTypename
:
1901 case Decl::UnresolvedUsingValue
:
1902 case Decl::UsingEnum
:
1903 // - static_assert-declarations
1904 // - using-declarations,
1905 // - using-directives,
1906 // - using-enum-declaration
1910 case Decl::TypeAlias
: {
1911 // - typedef declarations and alias-declarations that do not define
1912 // classes or enumerations,
1913 const auto *TN
= cast
<TypedefNameDecl
>(DclIt
);
1914 if (TN
->getUnderlyingType()->isVariablyModifiedType()) {
1915 // Don't allow variably-modified types in constexpr functions.
1916 if (Kind
== Sema::CheckConstexprKind::Diagnose
) {
1917 TypeLoc TL
= TN
->getTypeSourceInfo()->getTypeLoc();
1918 SemaRef
.Diag(TL
.getBeginLoc(), diag::err_constexpr_vla
)
1919 << TL
.getSourceRange() << TL
.getType()
1920 << isa
<CXXConstructorDecl
>(Dcl
);
1928 case Decl::CXXRecord
:
1929 // C++1y allows types to be defined, not just declared.
1930 if (cast
<TagDecl
>(DclIt
)->isThisDeclarationADefinition()) {
1931 if (Kind
== Sema::CheckConstexprKind::Diagnose
) {
1932 SemaRef
.Diag(DS
->getBeginLoc(),
1933 SemaRef
.getLangOpts().CPlusPlus14
1934 ? diag::warn_cxx11_compat_constexpr_type_definition
1935 : diag::ext_constexpr_type_definition
)
1936 << isa
<CXXConstructorDecl
>(Dcl
);
1937 } else if (!SemaRef
.getLangOpts().CPlusPlus14
) {
1943 case Decl::EnumConstant
:
1944 case Decl::IndirectField
:
1946 // These can only appear with other declarations which are banned in
1947 // C++11 and permitted in C++1y, so ignore them.
1951 case Decl::Decomposition
: {
1952 // C++1y [dcl.constexpr]p3 allows anything except:
1953 // a definition of a variable of non-literal type or of static or
1954 // thread storage duration or [before C++2a] for which no
1955 // initialization is performed.
1956 const auto *VD
= cast
<VarDecl
>(DclIt
);
1957 if (VD
->isThisDeclarationADefinition()) {
1958 if (VD
->isStaticLocal()) {
1959 if (Kind
== Sema::CheckConstexprKind::Diagnose
) {
1960 SemaRef
.Diag(VD
->getLocation(),
1961 SemaRef
.getLangOpts().CPlusPlus23
1962 ? diag::warn_cxx20_compat_constexpr_var
1963 : diag::ext_constexpr_static_var
)
1964 << isa
<CXXConstructorDecl
>(Dcl
)
1965 << (VD
->getTLSKind() == VarDecl::TLS_Dynamic
);
1966 } else if (!SemaRef
.getLangOpts().CPlusPlus23
) {
1970 if (SemaRef
.LangOpts
.CPlusPlus23
) {
1971 CheckLiteralType(SemaRef
, Kind
, VD
->getLocation(), VD
->getType(),
1972 diag::warn_cxx20_compat_constexpr_var
,
1973 isa
<CXXConstructorDecl
>(Dcl
),
1974 /*variable of non-literal type*/ 2);
1975 } else if (CheckLiteralType(
1976 SemaRef
, Kind
, VD
->getLocation(), VD
->getType(),
1977 diag::err_constexpr_local_var_non_literal_type
,
1978 isa
<CXXConstructorDecl
>(Dcl
))) {
1981 if (!VD
->getType()->isDependentType() &&
1982 !VD
->hasInit() && !VD
->isCXXForRangeDecl()) {
1983 if (Kind
== Sema::CheckConstexprKind::Diagnose
) {
1986 SemaRef
.getLangOpts().CPlusPlus20
1987 ? diag::warn_cxx17_compat_constexpr_local_var_no_init
1988 : diag::ext_constexpr_local_var_no_init
)
1989 << isa
<CXXConstructorDecl
>(Dcl
);
1990 } else if (!SemaRef
.getLangOpts().CPlusPlus20
) {
1996 if (Kind
== Sema::CheckConstexprKind::Diagnose
) {
1997 SemaRef
.Diag(VD
->getLocation(),
1998 SemaRef
.getLangOpts().CPlusPlus14
1999 ? diag::warn_cxx11_compat_constexpr_local_var
2000 : diag::ext_constexpr_local_var
)
2001 << isa
<CXXConstructorDecl
>(Dcl
);
2002 } else if (!SemaRef
.getLangOpts().CPlusPlus14
) {
2008 case Decl::NamespaceAlias
:
2009 case Decl::Function
:
2010 // These are disallowed in C++11 and permitted in C++1y. Allow them
2011 // everywhere as an extension.
2012 if (!Cxx1yLoc
.isValid())
2013 Cxx1yLoc
= DS
->getBeginLoc();
2017 if (Kind
== Sema::CheckConstexprKind::Diagnose
) {
2018 SemaRef
.Diag(DS
->getBeginLoc(), diag::err_constexpr_body_invalid_stmt
)
2019 << isa
<CXXConstructorDecl
>(Dcl
) << Dcl
->isConsteval();
2028 /// Check that the given field is initialized within a constexpr constructor.
2030 /// \param Dcl The constexpr constructor being checked.
2031 /// \param Field The field being checked. This may be a member of an anonymous
2032 /// struct or union nested within the class being checked.
2033 /// \param Inits All declarations, including anonymous struct/union members and
2034 /// indirect members, for which any initialization was provided.
2035 /// \param Diagnosed Whether we've emitted the error message yet. Used to attach
2036 /// multiple notes for different members to the same error.
2037 /// \param Kind Whether we're diagnosing a constructor as written or determining
2038 /// whether the formal requirements are satisfied.
2039 /// \return \c false if we're checking for validity and the constructor does
2040 /// not satisfy the requirements on a constexpr constructor.
2041 static bool CheckConstexprCtorInitializer(Sema
&SemaRef
,
2042 const FunctionDecl
*Dcl
,
2044 llvm::SmallSet
<Decl
*, 16> &Inits
,
2046 Sema::CheckConstexprKind Kind
) {
2047 // In C++20 onwards, there's nothing to check for validity.
2048 if (Kind
== Sema::CheckConstexprKind::CheckValid
&&
2049 SemaRef
.getLangOpts().CPlusPlus20
)
2052 if (Field
->isInvalidDecl())
2055 if (Field
->isUnnamedBitfield())
2058 // Anonymous unions with no variant members and empty anonymous structs do not
2059 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
2060 // indirect fields don't need initializing.
2061 if (Field
->isAnonymousStructOrUnion() &&
2062 (Field
->getType()->isUnionType()
2063 ? !Field
->getType()->getAsCXXRecordDecl()->hasVariantMembers()
2064 : Field
->getType()->getAsCXXRecordDecl()->isEmpty()))
2067 if (!Inits
.count(Field
)) {
2068 if (Kind
== Sema::CheckConstexprKind::Diagnose
) {
2070 SemaRef
.Diag(Dcl
->getLocation(),
2071 SemaRef
.getLangOpts().CPlusPlus20
2072 ? diag::warn_cxx17_compat_constexpr_ctor_missing_init
2073 : diag::ext_constexpr_ctor_missing_init
);
2076 SemaRef
.Diag(Field
->getLocation(),
2077 diag::note_constexpr_ctor_missing_init
);
2078 } else if (!SemaRef
.getLangOpts().CPlusPlus20
) {
2081 } else if (Field
->isAnonymousStructOrUnion()) {
2082 const RecordDecl
*RD
= Field
->getType()->castAs
<RecordType
>()->getDecl();
2083 for (auto *I
: RD
->fields())
2084 // If an anonymous union contains an anonymous struct of which any member
2085 // is initialized, all members must be initialized.
2086 if (!RD
->isUnion() || Inits
.count(I
))
2087 if (!CheckConstexprCtorInitializer(SemaRef
, Dcl
, I
, Inits
, Diagnosed
,
2094 /// Check the provided statement is allowed in a constexpr function
2097 CheckConstexprFunctionStmt(Sema
&SemaRef
, const FunctionDecl
*Dcl
, Stmt
*S
,
2098 SmallVectorImpl
<SourceLocation
> &ReturnStmts
,
2099 SourceLocation
&Cxx1yLoc
, SourceLocation
&Cxx2aLoc
,
2100 SourceLocation
&Cxx2bLoc
,
2101 Sema::CheckConstexprKind Kind
) {
2102 // - its function-body shall be [...] a compound-statement that contains only
2103 switch (S
->getStmtClass()) {
2104 case Stmt::NullStmtClass
:
2105 // - null statements,
2108 case Stmt::DeclStmtClass
:
2109 // - static_assert-declarations
2110 // - using-declarations,
2111 // - using-directives,
2112 // - typedef declarations and alias-declarations that do not define
2113 // classes or enumerations,
2114 if (!CheckConstexprDeclStmt(SemaRef
, Dcl
, cast
<DeclStmt
>(S
), Cxx1yLoc
, Kind
))
2118 case Stmt::ReturnStmtClass
:
2119 // - and exactly one return statement;
2120 if (isa
<CXXConstructorDecl
>(Dcl
)) {
2121 // C++1y allows return statements in constexpr constructors.
2122 if (!Cxx1yLoc
.isValid())
2123 Cxx1yLoc
= S
->getBeginLoc();
2127 ReturnStmts
.push_back(S
->getBeginLoc());
2130 case Stmt::AttributedStmtClass
:
2131 // Attributes on a statement don't affect its formal kind and hence don't
2132 // affect its validity in a constexpr function.
2133 return CheckConstexprFunctionStmt(
2134 SemaRef
, Dcl
, cast
<AttributedStmt
>(S
)->getSubStmt(), ReturnStmts
,
2135 Cxx1yLoc
, Cxx2aLoc
, Cxx2bLoc
, Kind
);
2137 case Stmt::CompoundStmtClass
: {
2138 // C++1y allows compound-statements.
2139 if (!Cxx1yLoc
.isValid())
2140 Cxx1yLoc
= S
->getBeginLoc();
2142 CompoundStmt
*CompStmt
= cast
<CompoundStmt
>(S
);
2143 for (auto *BodyIt
: CompStmt
->body()) {
2144 if (!CheckConstexprFunctionStmt(SemaRef
, Dcl
, BodyIt
, ReturnStmts
,
2145 Cxx1yLoc
, Cxx2aLoc
, Cxx2bLoc
, Kind
))
2151 case Stmt::IfStmtClass
: {
2152 // C++1y allows if-statements.
2153 if (!Cxx1yLoc
.isValid())
2154 Cxx1yLoc
= S
->getBeginLoc();
2156 IfStmt
*If
= cast
<IfStmt
>(S
);
2157 if (!CheckConstexprFunctionStmt(SemaRef
, Dcl
, If
->getThen(), ReturnStmts
,
2158 Cxx1yLoc
, Cxx2aLoc
, Cxx2bLoc
, Kind
))
2160 if (If
->getElse() &&
2161 !CheckConstexprFunctionStmt(SemaRef
, Dcl
, If
->getElse(), ReturnStmts
,
2162 Cxx1yLoc
, Cxx2aLoc
, Cxx2bLoc
, Kind
))
2167 case Stmt::WhileStmtClass
:
2168 case Stmt::DoStmtClass
:
2169 case Stmt::ForStmtClass
:
2170 case Stmt::CXXForRangeStmtClass
:
2171 case Stmt::ContinueStmtClass
:
2172 // C++1y allows all of these. We don't allow them as extensions in C++11,
2173 // because they don't make sense without variable mutation.
2174 if (!SemaRef
.getLangOpts().CPlusPlus14
)
2176 if (!Cxx1yLoc
.isValid())
2177 Cxx1yLoc
= S
->getBeginLoc();
2178 for (Stmt
*SubStmt
: S
->children()) {
2180 !CheckConstexprFunctionStmt(SemaRef
, Dcl
, SubStmt
, ReturnStmts
,
2181 Cxx1yLoc
, Cxx2aLoc
, Cxx2bLoc
, Kind
))
2186 case Stmt::SwitchStmtClass
:
2187 case Stmt::CaseStmtClass
:
2188 case Stmt::DefaultStmtClass
:
2189 case Stmt::BreakStmtClass
:
2190 // C++1y allows switch-statements, and since they don't need variable
2191 // mutation, we can reasonably allow them in C++11 as an extension.
2192 if (!Cxx1yLoc
.isValid())
2193 Cxx1yLoc
= S
->getBeginLoc();
2194 for (Stmt
*SubStmt
: S
->children()) {
2196 !CheckConstexprFunctionStmt(SemaRef
, Dcl
, SubStmt
, ReturnStmts
,
2197 Cxx1yLoc
, Cxx2aLoc
, Cxx2bLoc
, Kind
))
2202 case Stmt::LabelStmtClass
:
2203 case Stmt::GotoStmtClass
:
2204 if (Cxx2bLoc
.isInvalid())
2205 Cxx2bLoc
= S
->getBeginLoc();
2206 for (Stmt
*SubStmt
: S
->children()) {
2208 !CheckConstexprFunctionStmt(SemaRef
, Dcl
, SubStmt
, ReturnStmts
,
2209 Cxx1yLoc
, Cxx2aLoc
, Cxx2bLoc
, Kind
))
2214 case Stmt::GCCAsmStmtClass
:
2215 case Stmt::MSAsmStmtClass
:
2216 // C++2a allows inline assembly statements.
2217 case Stmt::CXXTryStmtClass
:
2218 if (Cxx2aLoc
.isInvalid())
2219 Cxx2aLoc
= S
->getBeginLoc();
2220 for (Stmt
*SubStmt
: S
->children()) {
2222 !CheckConstexprFunctionStmt(SemaRef
, Dcl
, SubStmt
, ReturnStmts
,
2223 Cxx1yLoc
, Cxx2aLoc
, Cxx2bLoc
, Kind
))
2228 case Stmt::CXXCatchStmtClass
:
2229 // Do not bother checking the language mode (already covered by the
2230 // try block check).
2231 if (!CheckConstexprFunctionStmt(
2232 SemaRef
, Dcl
, cast
<CXXCatchStmt
>(S
)->getHandlerBlock(), ReturnStmts
,
2233 Cxx1yLoc
, Cxx2aLoc
, Cxx2bLoc
, Kind
))
2241 // C++1y allows expression-statements.
2242 if (!Cxx1yLoc
.isValid())
2243 Cxx1yLoc
= S
->getBeginLoc();
2247 if (Kind
== Sema::CheckConstexprKind::Diagnose
) {
2248 SemaRef
.Diag(S
->getBeginLoc(), diag::err_constexpr_body_invalid_stmt
)
2249 << isa
<CXXConstructorDecl
>(Dcl
) << Dcl
->isConsteval();
2254 /// Check the body for the given constexpr function declaration only contains
2255 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
2257 /// \return true if the body is OK, false if we have found or diagnosed a
2259 static bool CheckConstexprFunctionBody(Sema
&SemaRef
, const FunctionDecl
*Dcl
,
2261 Sema::CheckConstexprKind Kind
) {
2262 SmallVector
<SourceLocation
, 4> ReturnStmts
;
2264 if (isa
<CXXTryStmt
>(Body
)) {
2265 // C++11 [dcl.constexpr]p3:
2266 // The definition of a constexpr function shall satisfy the following
2267 // constraints: [...]
2268 // - its function-body shall be = delete, = default, or a
2269 // compound-statement
2271 // C++11 [dcl.constexpr]p4:
2272 // In the definition of a constexpr constructor, [...]
2273 // - its function-body shall not be a function-try-block;
2275 // This restriction is lifted in C++2a, as long as inner statements also
2276 // apply the general constexpr rules.
2278 case Sema::CheckConstexprKind::CheckValid
:
2279 if (!SemaRef
.getLangOpts().CPlusPlus20
)
2283 case Sema::CheckConstexprKind::Diagnose
:
2284 SemaRef
.Diag(Body
->getBeginLoc(),
2285 !SemaRef
.getLangOpts().CPlusPlus20
2286 ? diag::ext_constexpr_function_try_block_cxx20
2287 : diag::warn_cxx17_compat_constexpr_function_try_block
)
2288 << isa
<CXXConstructorDecl
>(Dcl
);
2293 // - its function-body shall be [...] a compound-statement that contains only
2294 // [... list of cases ...]
2296 // Note that walking the children here is enough to properly check for
2297 // CompoundStmt and CXXTryStmt body.
2298 SourceLocation Cxx1yLoc
, Cxx2aLoc
, Cxx2bLoc
;
2299 for (Stmt
*SubStmt
: Body
->children()) {
2301 !CheckConstexprFunctionStmt(SemaRef
, Dcl
, SubStmt
, ReturnStmts
,
2302 Cxx1yLoc
, Cxx2aLoc
, Cxx2bLoc
, Kind
))
2306 if (Kind
== Sema::CheckConstexprKind::CheckValid
) {
2307 // If this is only valid as an extension, report that we don't satisfy the
2308 // constraints of the current language.
2309 if ((Cxx2bLoc
.isValid() && !SemaRef
.getLangOpts().CPlusPlus23
) ||
2310 (Cxx2aLoc
.isValid() && !SemaRef
.getLangOpts().CPlusPlus20
) ||
2311 (Cxx1yLoc
.isValid() && !SemaRef
.getLangOpts().CPlusPlus17
))
2313 } else if (Cxx2bLoc
.isValid()) {
2314 SemaRef
.Diag(Cxx2bLoc
,
2315 SemaRef
.getLangOpts().CPlusPlus23
2316 ? diag::warn_cxx20_compat_constexpr_body_invalid_stmt
2317 : diag::ext_constexpr_body_invalid_stmt_cxx23
)
2318 << isa
<CXXConstructorDecl
>(Dcl
);
2319 } else if (Cxx2aLoc
.isValid()) {
2320 SemaRef
.Diag(Cxx2aLoc
,
2321 SemaRef
.getLangOpts().CPlusPlus20
2322 ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
2323 : diag::ext_constexpr_body_invalid_stmt_cxx20
)
2324 << isa
<CXXConstructorDecl
>(Dcl
);
2325 } else if (Cxx1yLoc
.isValid()) {
2326 SemaRef
.Diag(Cxx1yLoc
,
2327 SemaRef
.getLangOpts().CPlusPlus14
2328 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
2329 : diag::ext_constexpr_body_invalid_stmt
)
2330 << isa
<CXXConstructorDecl
>(Dcl
);
2333 if (const CXXConstructorDecl
*Constructor
2334 = dyn_cast
<CXXConstructorDecl
>(Dcl
)) {
2335 const CXXRecordDecl
*RD
= Constructor
->getParent();
2337 // - every non-variant non-static data member and base class sub-object
2338 // shall be initialized;
2340 // - if the class is a union having variant members, exactly one of them
2341 // shall be initialized;
2342 if (RD
->isUnion()) {
2343 if (Constructor
->getNumCtorInitializers() == 0 &&
2344 RD
->hasVariantMembers()) {
2345 if (Kind
== Sema::CheckConstexprKind::Diagnose
) {
2348 SemaRef
.getLangOpts().CPlusPlus20
2349 ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init
2350 : diag::ext_constexpr_union_ctor_no_init
);
2351 } else if (!SemaRef
.getLangOpts().CPlusPlus20
) {
2355 } else if (!Constructor
->isDependentContext() &&
2356 !Constructor
->isDelegatingConstructor()) {
2357 assert(RD
->getNumVBases() == 0 && "constexpr ctor with virtual bases");
2359 // Skip detailed checking if we have enough initializers, and we would
2360 // allow at most one initializer per member.
2361 bool AnyAnonStructUnionMembers
= false;
2362 unsigned Fields
= 0;
2363 for (CXXRecordDecl::field_iterator I
= RD
->field_begin(),
2364 E
= RD
->field_end(); I
!= E
; ++I
, ++Fields
) {
2365 if (I
->isAnonymousStructOrUnion()) {
2366 AnyAnonStructUnionMembers
= true;
2371 // - if the class is a union-like class, but is not a union, for each of
2372 // its anonymous union members having variant members, exactly one of
2373 // them shall be initialized;
2374 if (AnyAnonStructUnionMembers
||
2375 Constructor
->getNumCtorInitializers() != RD
->getNumBases() + Fields
) {
2376 // Check initialization of non-static data members. Base classes are
2377 // always initialized so do not need to be checked. Dependent bases
2378 // might not have initializers in the member initializer list.
2379 llvm::SmallSet
<Decl
*, 16> Inits
;
2380 for (const auto *I
: Constructor
->inits()) {
2381 if (FieldDecl
*FD
= I
->getMember())
2383 else if (IndirectFieldDecl
*ID
= I
->getIndirectMember())
2384 Inits
.insert(ID
->chain_begin(), ID
->chain_end());
2387 bool Diagnosed
= false;
2388 for (auto *I
: RD
->fields())
2389 if (!CheckConstexprCtorInitializer(SemaRef
, Dcl
, I
, Inits
, Diagnosed
,
2395 if (ReturnStmts
.empty()) {
2396 // C++1y doesn't require constexpr functions to contain a 'return'
2397 // statement. We still do, unless the return type might be void, because
2398 // otherwise if there's no return statement, the function cannot
2399 // be used in a core constant expression.
2400 bool OK
= SemaRef
.getLangOpts().CPlusPlus14
&&
2401 (Dcl
->getReturnType()->isVoidType() ||
2402 Dcl
->getReturnType()->isDependentType());
2404 case Sema::CheckConstexprKind::Diagnose
:
2405 SemaRef
.Diag(Dcl
->getLocation(),
2406 OK
? diag::warn_cxx11_compat_constexpr_body_no_return
2407 : diag::err_constexpr_body_no_return
)
2408 << Dcl
->isConsteval();
2413 case Sema::CheckConstexprKind::CheckValid
:
2414 // The formal requirements don't include this rule in C++14, even
2415 // though the "must be able to produce a constant expression" rules
2416 // still imply it in some cases.
2417 if (!SemaRef
.getLangOpts().CPlusPlus14
)
2421 } else if (ReturnStmts
.size() > 1) {
2423 case Sema::CheckConstexprKind::Diagnose
:
2426 SemaRef
.getLangOpts().CPlusPlus14
2427 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2428 : diag::ext_constexpr_body_multiple_return
);
2429 for (unsigned I
= 0; I
< ReturnStmts
.size() - 1; ++I
)
2430 SemaRef
.Diag(ReturnStmts
[I
],
2431 diag::note_constexpr_body_previous_return
);
2434 case Sema::CheckConstexprKind::CheckValid
:
2435 if (!SemaRef
.getLangOpts().CPlusPlus14
)
2442 // C++11 [dcl.constexpr]p5:
2443 // if no function argument values exist such that the function invocation
2444 // substitution would produce a constant expression, the program is
2445 // ill-formed; no diagnostic required.
2446 // C++11 [dcl.constexpr]p3:
2447 // - every constructor call and implicit conversion used in initializing the
2448 // return value shall be one of those allowed in a constant expression.
2449 // C++11 [dcl.constexpr]p4:
2450 // - every constructor involved in initializing non-static data members and
2451 // base class sub-objects shall be a constexpr constructor.
2453 // Note that this rule is distinct from the "requirements for a constexpr
2454 // function", so is not checked in CheckValid mode.
2455 SmallVector
<PartialDiagnosticAt
, 8> Diags
;
2456 if (Kind
== Sema::CheckConstexprKind::Diagnose
&&
2457 !Expr::isPotentialConstantExpr(Dcl
, Diags
)) {
2458 SemaRef
.Diag(Dcl
->getLocation(),
2459 diag::ext_constexpr_function_never_constant_expr
)
2460 << isa
<CXXConstructorDecl
>(Dcl
) << Dcl
->isConsteval()
2461 << Dcl
->getNameInfo().getSourceRange();
2462 for (size_t I
= 0, N
= Diags
.size(); I
!= N
; ++I
)
2463 SemaRef
.Diag(Diags
[I
].first
, Diags
[I
].second
);
2464 // Don't return false here: we allow this for compatibility in
2471 bool Sema::CheckImmediateEscalatingFunctionDefinition(
2472 FunctionDecl
*FD
, const sema::FunctionScopeInfo
*FSI
) {
2473 if (!getLangOpts().CPlusPlus20
|| !FD
->isImmediateEscalating())
2475 FD
->setBodyContainsImmediateEscalatingExpressions(
2476 FSI
->FoundImmediateEscalatingExpression
);
2477 if (FSI
->FoundImmediateEscalatingExpression
) {
2478 auto it
= UndefinedButUsed
.find(FD
->getCanonicalDecl());
2479 if (it
!= UndefinedButUsed
.end()) {
2480 Diag(it
->second
, diag::err_immediate_function_used_before_definition
)
2482 Diag(FD
->getLocation(), diag::note_defined_here
) << FD
;
2483 if (FD
->isImmediateFunction() && !FD
->isConsteval())
2484 DiagnoseImmediateEscalatingReason(FD
);
2491 void Sema::DiagnoseImmediateEscalatingReason(FunctionDecl
*FD
) {
2492 assert(FD
->isImmediateEscalating() && !FD
->isConsteval() &&
2493 "expected an immediate function");
2494 assert(FD
->hasBody() && "expected the function to have a body");
2495 struct ImmediateEscalatingExpressionsVisitor
2496 : public RecursiveASTVisitor
<ImmediateEscalatingExpressionsVisitor
> {
2498 using Base
= RecursiveASTVisitor
<ImmediateEscalatingExpressionsVisitor
>;
2501 const FunctionDecl
*ImmediateFn
;
2502 bool ImmediateFnIsConstructor
;
2503 CXXConstructorDecl
*CurrentConstructor
= nullptr;
2504 CXXCtorInitializer
*CurrentInit
= nullptr;
2506 ImmediateEscalatingExpressionsVisitor(Sema
&SemaRef
, FunctionDecl
*FD
)
2507 : SemaRef(SemaRef
), ImmediateFn(FD
),
2508 ImmediateFnIsConstructor(isa
<CXXConstructorDecl
>(FD
)) {}
2510 bool shouldVisitImplicitCode() const { return true; }
2511 bool shouldVisitLambdaBody() const { return false; }
2513 void Diag(const Expr
*E
, const FunctionDecl
*Fn
, bool IsCall
) {
2514 SourceLocation Loc
= E
->getBeginLoc();
2515 SourceRange Range
= E
->getSourceRange();
2516 if (CurrentConstructor
&& CurrentInit
) {
2517 Loc
= CurrentConstructor
->getLocation();
2518 Range
= CurrentInit
->isWritten() ? CurrentInit
->getSourceRange()
2522 FieldDecl
* InitializedField
= CurrentInit
? CurrentInit
->getAnyMember() : nullptr;
2524 SemaRef
.Diag(Loc
, diag::note_immediate_function_reason
)
2525 << ImmediateFn
<< Fn
<< Fn
->isConsteval() << IsCall
2526 << isa
<CXXConstructorDecl
>(Fn
) << ImmediateFnIsConstructor
2527 << (InitializedField
!= nullptr)
2528 << (CurrentInit
&& !CurrentInit
->isWritten())
2529 << InitializedField
<< Range
;
2531 bool TraverseCallExpr(CallExpr
*E
) {
2532 if (const auto *DR
=
2533 dyn_cast
<DeclRefExpr
>(E
->getCallee()->IgnoreImplicit());
2534 DR
&& DR
->isImmediateEscalating()) {
2535 Diag(E
, E
->getDirectCallee(), /*IsCall=*/true);
2539 for (Expr
*A
: E
->arguments())
2540 if (!getDerived().TraverseStmt(A
))
2546 bool VisitDeclRefExpr(DeclRefExpr
*E
) {
2547 if (const auto *ReferencedFn
= dyn_cast
<FunctionDecl
>(E
->getDecl());
2548 ReferencedFn
&& E
->isImmediateEscalating()) {
2549 Diag(E
, ReferencedFn
, /*IsCall=*/false);
2556 bool VisitCXXConstructExpr(CXXConstructExpr
*E
) {
2557 CXXConstructorDecl
*D
= E
->getConstructor();
2558 if (E
->isImmediateEscalating()) {
2559 Diag(E
, D
, /*IsCall=*/true);
2565 bool TraverseConstructorInitializer(CXXCtorInitializer
*Init
) {
2566 llvm::SaveAndRestore
RAII(CurrentInit
, Init
);
2567 return Base::TraverseConstructorInitializer(Init
);
2570 bool TraverseCXXConstructorDecl(CXXConstructorDecl
*Ctr
) {
2571 llvm::SaveAndRestore
RAII(CurrentConstructor
, Ctr
);
2572 return Base::TraverseCXXConstructorDecl(Ctr
);
2575 bool TraverseType(QualType T
) { return true; }
2576 bool VisitBlockExpr(BlockExpr
*T
) { return true; }
2578 } Visitor(*this, FD
);
2579 Visitor
.TraverseDecl(FD
);
2582 /// Get the class that is directly named by the current context. This is the
2583 /// class for which an unqualified-id in this scope could name a constructor
2586 /// If the scope specifier denotes a class, this will be that class.
2587 /// If the scope specifier is empty, this will be the class whose
2588 /// member-specification we are currently within. Otherwise, there
2589 /// is no such class.
2590 CXXRecordDecl
*Sema::getCurrentClass(Scope
*, const CXXScopeSpec
*SS
) {
2591 assert(getLangOpts().CPlusPlus
&& "No class names in C!");
2593 if (SS
&& SS
->isInvalid())
2596 if (SS
&& SS
->isNotEmpty()) {
2597 DeclContext
*DC
= computeDeclContext(*SS
, true);
2598 return dyn_cast_or_null
<CXXRecordDecl
>(DC
);
2601 return dyn_cast_or_null
<CXXRecordDecl
>(CurContext
);
2604 /// isCurrentClassName - Determine whether the identifier II is the
2605 /// name of the class type currently being defined. In the case of
2606 /// nested classes, this will only return true if II is the name of
2607 /// the innermost class.
2608 bool Sema::isCurrentClassName(const IdentifierInfo
&II
, Scope
*S
,
2609 const CXXScopeSpec
*SS
) {
2610 CXXRecordDecl
*CurDecl
= getCurrentClass(S
, SS
);
2611 return CurDecl
&& &II
== CurDecl
->getIdentifier();
2614 /// Determine whether the identifier II is a typo for the name of
2615 /// the class type currently being defined. If so, update it to the identifier
2616 /// that should have been used.
2617 bool Sema::isCurrentClassNameTypo(IdentifierInfo
*&II
, const CXXScopeSpec
*SS
) {
2618 assert(getLangOpts().CPlusPlus
&& "No class names in C!");
2620 if (!getLangOpts().SpellChecking
)
2623 CXXRecordDecl
*CurDecl
;
2624 if (SS
&& SS
->isSet() && !SS
->isInvalid()) {
2625 DeclContext
*DC
= computeDeclContext(*SS
, true);
2626 CurDecl
= dyn_cast_or_null
<CXXRecordDecl
>(DC
);
2628 CurDecl
= dyn_cast_or_null
<CXXRecordDecl
>(CurContext
);
2630 if (CurDecl
&& CurDecl
->getIdentifier() && II
!= CurDecl
->getIdentifier() &&
2631 3 * II
->getName().edit_distance(CurDecl
->getIdentifier()->getName())
2632 < II
->getLength()) {
2633 II
= CurDecl
->getIdentifier();
2640 /// Determine whether the given class is a base class of the given
2641 /// class, including looking at dependent bases.
2642 static bool findCircularInheritance(const CXXRecordDecl
*Class
,
2643 const CXXRecordDecl
*Current
) {
2644 SmallVector
<const CXXRecordDecl
*, 8> Queue
;
2646 Class
= Class
->getCanonicalDecl();
2648 for (const auto &I
: Current
->bases()) {
2649 CXXRecordDecl
*Base
= I
.getType()->getAsCXXRecordDecl();
2653 Base
= Base
->getDefinition();
2657 if (Base
->getCanonicalDecl() == Class
)
2660 Queue
.push_back(Base
);
2666 Current
= Queue
.pop_back_val();
2672 /// Check the validity of a C++ base class specifier.
2674 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2675 /// and returns NULL otherwise.
2677 Sema::CheckBaseSpecifier(CXXRecordDecl
*Class
,
2678 SourceRange SpecifierRange
,
2679 bool Virtual
, AccessSpecifier Access
,
2680 TypeSourceInfo
*TInfo
,
2681 SourceLocation EllipsisLoc
) {
2682 // In HLSL, unspecified class access is public rather than private.
2683 if (getLangOpts().HLSL
&& Class
->getTagKind() == TTK_Class
&&
2687 QualType BaseType
= TInfo
->getType();
2688 if (BaseType
->containsErrors()) {
2689 // Already emitted a diagnostic when parsing the error type.
2692 // C++ [class.union]p1:
2693 // A union shall not have base classes.
2694 if (Class
->isUnion()) {
2695 Diag(Class
->getLocation(), diag::err_base_clause_on_union
)
2700 if (EllipsisLoc
.isValid() &&
2701 !TInfo
->getType()->containsUnexpandedParameterPack()) {
2702 Diag(EllipsisLoc
, diag::err_pack_expansion_without_parameter_packs
)
2703 << TInfo
->getTypeLoc().getSourceRange();
2704 EllipsisLoc
= SourceLocation();
2707 SourceLocation BaseLoc
= TInfo
->getTypeLoc().getBeginLoc();
2709 if (BaseType
->isDependentType()) {
2710 // Make sure that we don't have circular inheritance among our dependent
2711 // bases. For non-dependent bases, the check for completeness below handles
2713 if (CXXRecordDecl
*BaseDecl
= BaseType
->getAsCXXRecordDecl()) {
2714 if (BaseDecl
->getCanonicalDecl() == Class
->getCanonicalDecl() ||
2715 ((BaseDecl
= BaseDecl
->getDefinition()) &&
2716 findCircularInheritance(Class
, BaseDecl
))) {
2717 Diag(BaseLoc
, diag::err_circular_inheritance
)
2718 << BaseType
<< Context
.getTypeDeclType(Class
);
2720 if (BaseDecl
->getCanonicalDecl() != Class
->getCanonicalDecl())
2721 Diag(BaseDecl
->getLocation(), diag::note_previous_decl
)
2728 // Make sure that we don't make an ill-formed AST where the type of the
2729 // Class is non-dependent and its attached base class specifier is an
2730 // dependent type, which violates invariants in many clang code paths (e.g.
2731 // constexpr evaluator). If this case happens (in errory-recovery mode), we
2732 // explicitly mark the Class decl invalid. The diagnostic was already
2734 if (!Class
->getTypeForDecl()->isDependentType())
2735 Class
->setInvalidDecl();
2736 return new (Context
) CXXBaseSpecifier(SpecifierRange
, Virtual
,
2737 Class
->getTagKind() == TTK_Class
,
2738 Access
, TInfo
, EllipsisLoc
);
2741 // Base specifiers must be record types.
2742 if (!BaseType
->isRecordType()) {
2743 Diag(BaseLoc
, diag::err_base_must_be_class
) << SpecifierRange
;
2747 // C++ [class.union]p1:
2748 // A union shall not be used as a base class.
2749 if (BaseType
->isUnionType()) {
2750 Diag(BaseLoc
, diag::err_union_as_base_class
) << SpecifierRange
;
2754 // For the MS ABI, propagate DLL attributes to base class templates.
2755 if (Context
.getTargetInfo().getCXXABI().isMicrosoft() ||
2756 Context
.getTargetInfo().getTriple().isPS()) {
2757 if (Attr
*ClassAttr
= getDLLAttr(Class
)) {
2758 if (auto *BaseTemplate
= dyn_cast_or_null
<ClassTemplateSpecializationDecl
>(
2759 BaseType
->getAsCXXRecordDecl())) {
2760 propagateDLLAttrToBaseClassTemplate(Class
, ClassAttr
, BaseTemplate
,
2766 // C++ [class.derived]p2:
2767 // The class-name in a base-specifier shall not be an incompletely
2769 if (RequireCompleteType(BaseLoc
, BaseType
,
2770 diag::err_incomplete_base_class
, SpecifierRange
)) {
2771 Class
->setInvalidDecl();
2775 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2776 RecordDecl
*BaseDecl
= BaseType
->castAs
<RecordType
>()->getDecl();
2777 assert(BaseDecl
&& "Record type has no declaration");
2778 BaseDecl
= BaseDecl
->getDefinition();
2779 assert(BaseDecl
&& "Base type is not incomplete, but has no definition");
2780 CXXRecordDecl
*CXXBaseDecl
= cast
<CXXRecordDecl
>(BaseDecl
);
2781 assert(CXXBaseDecl
&& "Base type is not a C++ type");
2783 // Microsoft docs say:
2784 // "If a base-class has a code_seg attribute, derived classes must have the
2786 const auto *BaseCSA
= CXXBaseDecl
->getAttr
<CodeSegAttr
>();
2787 const auto *DerivedCSA
= Class
->getAttr
<CodeSegAttr
>();
2788 if ((DerivedCSA
|| BaseCSA
) &&
2789 (!BaseCSA
|| !DerivedCSA
|| BaseCSA
->getName() != DerivedCSA
->getName())) {
2790 Diag(Class
->getLocation(), diag::err_mismatched_code_seg_base
);
2791 Diag(CXXBaseDecl
->getLocation(), diag::note_base_class_specified_here
)
2796 // A class which contains a flexible array member is not suitable for use as a
2798 // - If the layout determines that a base comes before another base,
2799 // the flexible array member would index into the subsequent base.
2800 // - If the layout determines that base comes before the derived class,
2801 // the flexible array member would index into the derived class.
2802 if (CXXBaseDecl
->hasFlexibleArrayMember()) {
2803 Diag(BaseLoc
, diag::err_base_class_has_flexible_array_member
)
2804 << CXXBaseDecl
->getDeclName();
2809 // If a class is marked final and it appears as a base-type-specifier in
2810 // base-clause, the program is ill-formed.
2811 if (FinalAttr
*FA
= CXXBaseDecl
->getAttr
<FinalAttr
>()) {
2812 Diag(BaseLoc
, diag::err_class_marked_final_used_as_base
)
2813 << CXXBaseDecl
->getDeclName()
2814 << FA
->isSpelledAsSealed();
2815 Diag(CXXBaseDecl
->getLocation(), diag::note_entity_declared_at
)
2816 << CXXBaseDecl
->getDeclName() << FA
->getRange();
2820 if (BaseDecl
->isInvalidDecl())
2821 Class
->setInvalidDecl();
2823 // Create the base specifier.
2824 return new (Context
) CXXBaseSpecifier(SpecifierRange
, Virtual
,
2825 Class
->getTagKind() == TTK_Class
,
2826 Access
, TInfo
, EllipsisLoc
);
2829 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2830 /// one entry in the base class list of a class specifier, for
2832 /// class foo : public bar, virtual private baz {
2833 /// 'public bar' and 'virtual private baz' are each base-specifiers.
2834 BaseResult
Sema::ActOnBaseSpecifier(Decl
*classdecl
, SourceRange SpecifierRange
,
2835 const ParsedAttributesView
&Attributes
,
2836 bool Virtual
, AccessSpecifier Access
,
2837 ParsedType basetype
, SourceLocation BaseLoc
,
2838 SourceLocation EllipsisLoc
) {
2842 AdjustDeclIfTemplate(classdecl
);
2843 CXXRecordDecl
*Class
= dyn_cast
<CXXRecordDecl
>(classdecl
);
2847 // We haven't yet attached the base specifiers.
2848 Class
->setIsParsingBaseSpecifiers();
2850 // We do not support any C++11 attributes on base-specifiers yet.
2851 // Diagnose any attributes we see.
2852 for (const ParsedAttr
&AL
: Attributes
) {
2853 if (AL
.isInvalid() || AL
.getKind() == ParsedAttr::IgnoredAttribute
)
2855 if (AL
.getKind() == ParsedAttr::UnknownAttribute
)
2856 Diag(AL
.getLoc(), diag::warn_unknown_attribute_ignored
)
2857 << AL
<< AL
.getRange();
2859 Diag(AL
.getLoc(), diag::err_base_specifier_attribute
)
2860 << AL
<< AL
.isRegularKeywordAttribute() << AL
.getRange();
2863 TypeSourceInfo
*TInfo
= nullptr;
2864 GetTypeFromParser(basetype
, &TInfo
);
2866 if (EllipsisLoc
.isInvalid() &&
2867 DiagnoseUnexpandedParameterPack(SpecifierRange
.getBegin(), TInfo
,
2871 if (CXXBaseSpecifier
*BaseSpec
= CheckBaseSpecifier(Class
, SpecifierRange
,
2872 Virtual
, Access
, TInfo
,
2876 Class
->setInvalidDecl();
2881 /// Use small set to collect indirect bases. As this is only used
2882 /// locally, there's no need to abstract the small size parameter.
2883 typedef llvm::SmallPtrSet
<QualType
, 4> IndirectBaseSet
;
2885 /// Recursively add the bases of Type. Don't add Type itself.
2887 NoteIndirectBases(ASTContext
&Context
, IndirectBaseSet
&Set
,
2888 const QualType
&Type
)
2890 // Even though the incoming type is a base, it might not be
2891 // a class -- it could be a template parm, for instance.
2892 if (auto Rec
= Type
->getAs
<RecordType
>()) {
2893 auto Decl
= Rec
->getAsCXXRecordDecl();
2895 // Iterate over its bases.
2896 for (const auto &BaseSpec
: Decl
->bases()) {
2897 QualType Base
= Context
.getCanonicalType(BaseSpec
.getType())
2898 .getUnqualifiedType();
2899 if (Set
.insert(Base
).second
)
2900 // If we've not already seen it, recurse.
2901 NoteIndirectBases(Context
, Set
, Base
);
2906 /// Performs the actual work of attaching the given base class
2907 /// specifiers to a C++ class.
2908 bool Sema::AttachBaseSpecifiers(CXXRecordDecl
*Class
,
2909 MutableArrayRef
<CXXBaseSpecifier
*> Bases
) {
2913 // Used to keep track of which base types we have already seen, so
2914 // that we can properly diagnose redundant direct base types. Note
2915 // that the key is always the unqualified canonical type of the base
2917 std::map
<QualType
, CXXBaseSpecifier
*, QualTypeOrdering
> KnownBaseTypes
;
2919 // Used to track indirect bases so we can see if a direct base is
2921 IndirectBaseSet IndirectBaseTypes
;
2923 // Copy non-redundant base specifiers into permanent storage.
2924 unsigned NumGoodBases
= 0;
2925 bool Invalid
= false;
2926 for (unsigned idx
= 0; idx
< Bases
.size(); ++idx
) {
2927 QualType NewBaseType
2928 = Context
.getCanonicalType(Bases
[idx
]->getType());
2929 NewBaseType
= NewBaseType
.getLocalUnqualifiedType();
2931 CXXBaseSpecifier
*&KnownBase
= KnownBaseTypes
[NewBaseType
];
2933 // C++ [class.mi]p3:
2934 // A class shall not be specified as a direct base class of a
2935 // derived class more than once.
2936 Diag(Bases
[idx
]->getBeginLoc(), diag::err_duplicate_base_class
)
2937 << KnownBase
->getType() << Bases
[idx
]->getSourceRange();
2939 // Delete the duplicate base class specifier; we're going to
2940 // overwrite its pointer later.
2941 Context
.Deallocate(Bases
[idx
]);
2945 // Okay, add this new base class.
2946 KnownBase
= Bases
[idx
];
2947 Bases
[NumGoodBases
++] = Bases
[idx
];
2949 if (NewBaseType
->isDependentType())
2951 // Note this base's direct & indirect bases, if there could be ambiguity.
2952 if (Bases
.size() > 1)
2953 NoteIndirectBases(Context
, IndirectBaseTypes
, NewBaseType
);
2955 if (const RecordType
*Record
= NewBaseType
->getAs
<RecordType
>()) {
2956 const CXXRecordDecl
*RD
= cast
<CXXRecordDecl
>(Record
->getDecl());
2957 if (Class
->isInterface() &&
2958 (!RD
->isInterfaceLike() ||
2959 KnownBase
->getAccessSpecifier() != AS_public
)) {
2960 // The Microsoft extension __interface does not permit bases that
2961 // are not themselves public interfaces.
2962 Diag(KnownBase
->getBeginLoc(), diag::err_invalid_base_in_interface
)
2963 << getRecordDiagFromTagKind(RD
->getTagKind()) << RD
2964 << RD
->getSourceRange();
2967 if (RD
->hasAttr
<WeakAttr
>())
2968 Class
->addAttr(WeakAttr::CreateImplicit(Context
));
2973 // Attach the remaining base class specifiers to the derived class.
2974 Class
->setBases(Bases
.data(), NumGoodBases
);
2976 // Check that the only base classes that are duplicate are virtual.
2977 for (unsigned idx
= 0; idx
< NumGoodBases
; ++idx
) {
2978 // Check whether this direct base is inaccessible due to ambiguity.
2979 QualType BaseType
= Bases
[idx
]->getType();
2981 // Skip all dependent types in templates being used as base specifiers.
2982 // Checks below assume that the base specifier is a CXXRecord.
2983 if (BaseType
->isDependentType())
2986 CanQualType CanonicalBase
= Context
.getCanonicalType(BaseType
)
2987 .getUnqualifiedType();
2989 if (IndirectBaseTypes
.count(CanonicalBase
)) {
2990 CXXBasePaths
Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2991 /*DetectVirtual=*/true);
2993 = Class
->isDerivedFrom(CanonicalBase
->getAsCXXRecordDecl(), Paths
);
2997 if (Paths
.isAmbiguous(CanonicalBase
))
2998 Diag(Bases
[idx
]->getBeginLoc(), diag::warn_inaccessible_base_class
)
2999 << BaseType
<< getAmbiguousPathsDisplayString(Paths
)
3000 << Bases
[idx
]->getSourceRange();
3002 assert(Bases
[idx
]->isVirtual());
3005 // Delete the base class specifier, since its data has been copied
3006 // into the CXXRecordDecl.
3007 Context
.Deallocate(Bases
[idx
]);
3013 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
3014 /// class, after checking whether there are any duplicate base
3016 void Sema::ActOnBaseSpecifiers(Decl
*ClassDecl
,
3017 MutableArrayRef
<CXXBaseSpecifier
*> Bases
) {
3018 if (!ClassDecl
|| Bases
.empty())
3021 AdjustDeclIfTemplate(ClassDecl
);
3022 AttachBaseSpecifiers(cast
<CXXRecordDecl
>(ClassDecl
), Bases
);
3025 /// Determine whether the type \p Derived is a C++ class that is
3026 /// derived from the type \p Base.
3027 bool Sema::IsDerivedFrom(SourceLocation Loc
, QualType Derived
, QualType Base
) {
3028 if (!getLangOpts().CPlusPlus
)
3031 CXXRecordDecl
*DerivedRD
= Derived
->getAsCXXRecordDecl();
3035 CXXRecordDecl
*BaseRD
= Base
->getAsCXXRecordDecl();
3039 // If either the base or the derived type is invalid, don't try to
3040 // check whether one is derived from the other.
3041 if (BaseRD
->isInvalidDecl() || DerivedRD
->isInvalidDecl())
3044 // FIXME: In a modules build, do we need the entire path to be visible for us
3045 // to be able to use the inheritance relationship?
3046 if (!isCompleteType(Loc
, Derived
) && !DerivedRD
->isBeingDefined())
3049 return DerivedRD
->isDerivedFrom(BaseRD
);
3052 /// Determine whether the type \p Derived is a C++ class that is
3053 /// derived from the type \p Base.
3054 bool Sema::IsDerivedFrom(SourceLocation Loc
, QualType Derived
, QualType Base
,
3055 CXXBasePaths
&Paths
) {
3056 if (!getLangOpts().CPlusPlus
)
3059 CXXRecordDecl
*DerivedRD
= Derived
->getAsCXXRecordDecl();
3063 CXXRecordDecl
*BaseRD
= Base
->getAsCXXRecordDecl();
3067 if (!isCompleteType(Loc
, Derived
) && !DerivedRD
->isBeingDefined())
3070 return DerivedRD
->isDerivedFrom(BaseRD
, Paths
);
3073 static void BuildBasePathArray(const CXXBasePath
&Path
,
3074 CXXCastPath
&BasePathArray
) {
3075 // We first go backward and check if we have a virtual base.
3076 // FIXME: It would be better if CXXBasePath had the base specifier for
3077 // the nearest virtual base.
3079 for (unsigned I
= Path
.size(); I
!= 0; --I
) {
3080 if (Path
[I
- 1].Base
->isVirtual()) {
3086 // Now add all bases.
3087 for (unsigned I
= Start
, E
= Path
.size(); I
!= E
; ++I
)
3088 BasePathArray
.push_back(const_cast<CXXBaseSpecifier
*>(Path
[I
].Base
));
3092 void Sema::BuildBasePathArray(const CXXBasePaths
&Paths
,
3093 CXXCastPath
&BasePathArray
) {
3094 assert(BasePathArray
.empty() && "Base path array must be empty!");
3095 assert(Paths
.isRecordingPaths() && "Must record paths!");
3096 return ::BuildBasePathArray(Paths
.front(), BasePathArray
);
3098 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
3099 /// conversion (where Derived and Base are class types) is
3100 /// well-formed, meaning that the conversion is unambiguous (and
3101 /// that all of the base classes are accessible). Returns true
3102 /// and emits a diagnostic if the code is ill-formed, returns false
3103 /// otherwise. Loc is the location where this routine should point to
3104 /// if there is an error, and Range is the source range to highlight
3105 /// if there is an error.
3107 /// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the
3108 /// diagnostic for the respective type of error will be suppressed, but the
3109 /// check for ill-formed code will still be performed.
3111 Sema::CheckDerivedToBaseConversion(QualType Derived
, QualType Base
,
3112 unsigned InaccessibleBaseID
,
3113 unsigned AmbiguousBaseConvID
,
3114 SourceLocation Loc
, SourceRange Range
,
3115 DeclarationName Name
,
3116 CXXCastPath
*BasePath
,
3117 bool IgnoreAccess
) {
3118 // First, determine whether the path from Derived to Base is
3119 // ambiguous. This is slightly more expensive than checking whether
3120 // the Derived to Base conversion exists, because here we need to
3121 // explore multiple paths to determine if there is an ambiguity.
3122 CXXBasePaths
Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3123 /*DetectVirtual=*/false);
3124 bool DerivationOkay
= IsDerivedFrom(Loc
, Derived
, Base
, Paths
);
3125 if (!DerivationOkay
)
3128 const CXXBasePath
*Path
= nullptr;
3129 if (!Paths
.isAmbiguous(Context
.getCanonicalType(Base
).getUnqualifiedType()))
3130 Path
= &Paths
.front();
3132 // For MSVC compatibility, check if Derived directly inherits from Base. Clang
3133 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
3134 // user to access such bases.
3135 if (!Path
&& getLangOpts().MSVCCompat
) {
3136 for (const CXXBasePath
&PossiblePath
: Paths
) {
3137 if (PossiblePath
.size() == 1) {
3138 Path
= &PossiblePath
;
3139 if (AmbiguousBaseConvID
)
3140 Diag(Loc
, diag::ext_ms_ambiguous_direct_base
)
3141 << Base
<< Derived
<< Range
;
3148 if (!IgnoreAccess
) {
3149 // Check that the base class can be accessed.
3151 CheckBaseClassAccess(Loc
, Base
, Derived
, *Path
, InaccessibleBaseID
)) {
3152 case AR_inaccessible
:
3161 // Build a base path if necessary.
3163 ::BuildBasePathArray(*Path
, *BasePath
);
3167 if (AmbiguousBaseConvID
) {
3168 // We know that the derived-to-base conversion is ambiguous, and
3169 // we're going to produce a diagnostic. Perform the derived-to-base
3170 // search just one more time to compute all of the possible paths so
3171 // that we can print them out. This is more expensive than any of
3172 // the previous derived-to-base checks we've done, but at this point
3173 // performance isn't as much of an issue.
3175 Paths
.setRecordingPaths(true);
3176 bool StillOkay
= IsDerivedFrom(Loc
, Derived
, Base
, Paths
);
3177 assert(StillOkay
&& "Can only be used with a derived-to-base conversion");
3180 // Build up a textual representation of the ambiguous paths, e.g.,
3181 // D -> B -> A, that will be used to illustrate the ambiguous
3182 // conversions in the diagnostic. We only print one of the paths
3183 // to each base class subobject.
3184 std::string PathDisplayStr
= getAmbiguousPathsDisplayString(Paths
);
3186 Diag(Loc
, AmbiguousBaseConvID
)
3187 << Derived
<< Base
<< PathDisplayStr
<< Range
<< Name
;
3193 Sema::CheckDerivedToBaseConversion(QualType Derived
, QualType Base
,
3194 SourceLocation Loc
, SourceRange Range
,
3195 CXXCastPath
*BasePath
,
3196 bool IgnoreAccess
) {
3197 return CheckDerivedToBaseConversion(
3198 Derived
, Base
, diag::err_upcast_to_inaccessible_base
,
3199 diag::err_ambiguous_derived_to_base_conv
, Loc
, Range
, DeclarationName(),
3200 BasePath
, IgnoreAccess
);
3204 /// Builds a string representing ambiguous paths from a
3205 /// specific derived class to different subobjects of the same base
3208 /// This function builds a string that can be used in error messages
3209 /// to show the different paths that one can take through the
3210 /// inheritance hierarchy to go from the derived class to different
3211 /// subobjects of a base class. The result looks something like this:
3213 /// struct D -> struct B -> struct A
3214 /// struct D -> struct C -> struct A
3216 std::string
Sema::getAmbiguousPathsDisplayString(CXXBasePaths
&Paths
) {
3217 std::string PathDisplayStr
;
3218 std::set
<unsigned> DisplayedPaths
;
3219 for (CXXBasePaths::paths_iterator Path
= Paths
.begin();
3220 Path
!= Paths
.end(); ++Path
) {
3221 if (DisplayedPaths
.insert(Path
->back().SubobjectNumber
).second
) {
3222 // We haven't displayed a path to this particular base
3223 // class subobject yet.
3224 PathDisplayStr
+= "\n ";
3225 PathDisplayStr
+= Context
.getTypeDeclType(Paths
.getOrigin()).getAsString();
3226 for (CXXBasePath::const_iterator Element
= Path
->begin();
3227 Element
!= Path
->end(); ++Element
)
3228 PathDisplayStr
+= " -> " + Element
->Base
->getType().getAsString();
3232 return PathDisplayStr
;
3235 //===----------------------------------------------------------------------===//
3236 // C++ class member Handling
3237 //===----------------------------------------------------------------------===//
3239 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
3240 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access
, SourceLocation ASLoc
,
3241 SourceLocation ColonLoc
,
3242 const ParsedAttributesView
&Attrs
) {
3243 assert(Access
!= AS_none
&& "Invalid kind for syntactic access specifier!");
3244 AccessSpecDecl
*ASDecl
= AccessSpecDecl::Create(Context
, Access
, CurContext
,
3246 CurContext
->addHiddenDecl(ASDecl
);
3247 return ProcessAccessDeclAttributeList(ASDecl
, Attrs
);
3250 /// CheckOverrideControl - Check C++11 override control semantics.
3251 void Sema::CheckOverrideControl(NamedDecl
*D
) {
3252 if (D
->isInvalidDecl())
3255 // We only care about "override" and "final" declarations.
3256 if (!D
->hasAttr
<OverrideAttr
>() && !D
->hasAttr
<FinalAttr
>())
3259 CXXMethodDecl
*MD
= dyn_cast
<CXXMethodDecl
>(D
);
3261 // We can't check dependent instance methods.
3262 if (MD
&& MD
->isInstance() &&
3263 (MD
->getParent()->hasAnyDependentBases() ||
3264 MD
->getType()->isDependentType()))
3267 if (MD
&& !MD
->isVirtual()) {
3268 // If we have a non-virtual method, check if it hides a virtual method.
3269 // (In that case, it's most likely the method has the wrong type.)
3270 SmallVector
<CXXMethodDecl
*, 8> OverloadedMethods
;
3271 FindHiddenVirtualMethods(MD
, OverloadedMethods
);
3273 if (!OverloadedMethods
.empty()) {
3274 if (OverrideAttr
*OA
= D
->getAttr
<OverrideAttr
>()) {
3275 Diag(OA
->getLocation(),
3276 diag::override_keyword_hides_virtual_member_function
)
3277 << "override" << (OverloadedMethods
.size() > 1);
3278 } else if (FinalAttr
*FA
= D
->getAttr
<FinalAttr
>()) {
3279 Diag(FA
->getLocation(),
3280 diag::override_keyword_hides_virtual_member_function
)
3281 << (FA
->isSpelledAsSealed() ? "sealed" : "final")
3282 << (OverloadedMethods
.size() > 1);
3284 NoteHiddenVirtualMethods(MD
, OverloadedMethods
);
3285 MD
->setInvalidDecl();
3288 // Fall through into the general case diagnostic.
3289 // FIXME: We might want to attempt typo correction here.
3292 if (!MD
|| !MD
->isVirtual()) {
3293 if (OverrideAttr
*OA
= D
->getAttr
<OverrideAttr
>()) {
3294 Diag(OA
->getLocation(),
3295 diag::override_keyword_only_allowed_on_virtual_member_functions
)
3296 << "override" << FixItHint::CreateRemoval(OA
->getLocation());
3297 D
->dropAttr
<OverrideAttr
>();
3299 if (FinalAttr
*FA
= D
->getAttr
<FinalAttr
>()) {
3300 Diag(FA
->getLocation(),
3301 diag::override_keyword_only_allowed_on_virtual_member_functions
)
3302 << (FA
->isSpelledAsSealed() ? "sealed" : "final")
3303 << FixItHint::CreateRemoval(FA
->getLocation());
3304 D
->dropAttr
<FinalAttr
>();
3309 // C++11 [class.virtual]p5:
3310 // If a function is marked with the virt-specifier override and
3311 // does not override a member function of a base class, the program is
3313 bool HasOverriddenMethods
= MD
->size_overridden_methods() != 0;
3314 if (MD
->hasAttr
<OverrideAttr
>() && !HasOverriddenMethods
)
3315 Diag(MD
->getLocation(), diag::err_function_marked_override_not_overriding
)
3316 << MD
->getDeclName();
3319 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl
*D
, bool Inconsistent
) {
3320 if (D
->isInvalidDecl() || D
->hasAttr
<OverrideAttr
>())
3322 CXXMethodDecl
*MD
= dyn_cast
<CXXMethodDecl
>(D
);
3323 if (!MD
|| MD
->isImplicit() || MD
->hasAttr
<FinalAttr
>())
3326 SourceLocation Loc
= MD
->getLocation();
3327 SourceLocation SpellingLoc
= Loc
;
3328 if (getSourceManager().isMacroArgExpansion(Loc
))
3329 SpellingLoc
= getSourceManager().getImmediateExpansionRange(Loc
).getBegin();
3330 SpellingLoc
= getSourceManager().getSpellingLoc(SpellingLoc
);
3331 if (SpellingLoc
.isValid() && getSourceManager().isInSystemHeader(SpellingLoc
))
3334 if (MD
->size_overridden_methods() > 0) {
3335 auto EmitDiag
= [&](unsigned DiagInconsistent
, unsigned DiagSuggest
) {
3337 Inconsistent
&& !Diags
.isIgnored(DiagInconsistent
, MD
->getLocation())
3340 Diag(MD
->getLocation(), DiagID
) << MD
->getDeclName();
3341 const CXXMethodDecl
*OMD
= *MD
->begin_overridden_methods();
3342 Diag(OMD
->getLocation(), diag::note_overridden_virtual_function
);
3344 if (isa
<CXXDestructorDecl
>(MD
))
3346 diag::warn_inconsistent_destructor_marked_not_override_overriding
,
3347 diag::warn_suggest_destructor_marked_not_override_overriding
);
3349 EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding
,
3350 diag::warn_suggest_function_marked_not_override_overriding
);
3354 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
3355 /// function overrides a virtual member function marked 'final', according to
3356 /// C++11 [class.virtual]p4.
3357 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl
*New
,
3358 const CXXMethodDecl
*Old
) {
3359 FinalAttr
*FA
= Old
->getAttr
<FinalAttr
>();
3363 Diag(New
->getLocation(), diag::err_final_function_overridden
)
3364 << New
->getDeclName()
3365 << FA
->isSpelledAsSealed();
3366 Diag(Old
->getLocation(), diag::note_overridden_virtual_function
);
3370 static bool InitializationHasSideEffects(const FieldDecl
&FD
) {
3371 const Type
*T
= FD
.getType()->getBaseElementTypeUnsafe();
3372 // FIXME: Destruction of ObjC lifetime types has side-effects.
3373 if (const CXXRecordDecl
*RD
= T
->getAsCXXRecordDecl())
3374 return !RD
->isCompleteDefinition() ||
3375 !RD
->hasTrivialDefaultConstructor() ||
3376 !RD
->hasTrivialDestructor();
3380 // Check if there is a field shadowing.
3381 void Sema::CheckShadowInheritedFields(const SourceLocation
&Loc
,
3382 DeclarationName FieldName
,
3383 const CXXRecordDecl
*RD
,
3385 if (Diags
.isIgnored(diag::warn_shadow_field
, Loc
))
3388 // To record a shadowed field in a base
3389 std::map
<CXXRecordDecl
*, NamedDecl
*> Bases
;
3390 auto FieldShadowed
= [&](const CXXBaseSpecifier
*Specifier
,
3391 CXXBasePath
&Path
) {
3392 const auto Base
= Specifier
->getType()->getAsCXXRecordDecl();
3393 // Record an ambiguous path directly
3394 if (Bases
.find(Base
) != Bases
.end())
3396 for (const auto Field
: Base
->lookup(FieldName
)) {
3397 if ((isa
<FieldDecl
>(Field
) || isa
<IndirectFieldDecl
>(Field
)) &&
3398 Field
->getAccess() != AS_private
) {
3399 assert(Field
->getAccess() != AS_none
);
3400 assert(Bases
.find(Base
) == Bases
.end());
3401 Bases
[Base
] = Field
;
3408 CXXBasePaths
Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3409 /*DetectVirtual=*/true);
3410 if (!RD
->lookupInBases(FieldShadowed
, Paths
))
3413 for (const auto &P
: Paths
) {
3414 auto Base
= P
.back().Base
->getType()->getAsCXXRecordDecl();
3415 auto It
= Bases
.find(Base
);
3416 // Skip duplicated bases
3417 if (It
== Bases
.end())
3419 auto BaseField
= It
->second
;
3420 assert(BaseField
->getAccess() != AS_private
);
3422 CXXRecordDecl::MergeAccess(P
.Access
, BaseField
->getAccess())) {
3423 Diag(Loc
, diag::warn_shadow_field
)
3424 << FieldName
<< RD
<< Base
<< DeclIsField
;
3425 Diag(BaseField
->getLocation(), diag::note_shadow_field
);
3431 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
3432 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
3433 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
3434 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
3435 /// present (but parsing it has been deferred).
3437 Sema::ActOnCXXMemberDeclarator(Scope
*S
, AccessSpecifier AS
, Declarator
&D
,
3438 MultiTemplateParamsArg TemplateParameterLists
,
3439 Expr
*BW
, const VirtSpecifiers
&VS
,
3440 InClassInitStyle InitStyle
) {
3441 const DeclSpec
&DS
= D
.getDeclSpec();
3442 DeclarationNameInfo NameInfo
= GetNameForDeclarator(D
);
3443 DeclarationName Name
= NameInfo
.getName();
3444 SourceLocation Loc
= NameInfo
.getLoc();
3446 // For anonymous bitfields, the location should point to the type.
3447 if (Loc
.isInvalid())
3448 Loc
= D
.getBeginLoc();
3450 Expr
*BitWidth
= static_cast<Expr
*>(BW
);
3452 assert(isa
<CXXRecordDecl
>(CurContext
));
3453 assert(!DS
.isFriendSpecified());
3455 bool isFunc
= D
.isDeclarationOfFunction();
3456 const ParsedAttr
*MSPropertyAttr
=
3457 D
.getDeclSpec().getAttributes().getMSPropertyAttr();
3459 if (cast
<CXXRecordDecl
>(CurContext
)->isInterface()) {
3460 // The Microsoft extension __interface only permits public member functions
3461 // and prohibits constructors, destructors, operators, non-public member
3462 // functions, static methods and data members.
3463 unsigned InvalidDecl
;
3464 bool ShowDeclName
= true;
3466 (DS
.getStorageClassSpec() == DeclSpec::SCS_typedef
|| MSPropertyAttr
))
3470 else if (AS
!= AS_public
)
3472 else if (DS
.getStorageClassSpec() == DeclSpec::SCS_static
)
3474 else switch (Name
.getNameKind()) {
3475 case DeclarationName::CXXConstructorName
:
3477 ShowDeclName
= false;
3480 case DeclarationName::CXXDestructorName
:
3482 ShowDeclName
= false;
3485 case DeclarationName::CXXOperatorName
:
3486 case DeclarationName::CXXConversionFunctionName
:
3497 Diag(Loc
, diag::err_invalid_member_in_interface
)
3498 << (InvalidDecl
-1) << Name
;
3500 Diag(Loc
, diag::err_invalid_member_in_interface
)
3501 << (InvalidDecl
-1) << "";
3506 // C++ 9.2p6: A member shall not be declared to have automatic storage
3507 // duration (auto, register) or with the extern storage-class-specifier.
3508 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3509 // data members and cannot be applied to names declared const or static,
3510 // and cannot be applied to reference members.
3511 switch (DS
.getStorageClassSpec()) {
3512 case DeclSpec::SCS_unspecified
:
3513 case DeclSpec::SCS_typedef
:
3514 case DeclSpec::SCS_static
:
3516 case DeclSpec::SCS_mutable
:
3518 Diag(DS
.getStorageClassSpecLoc(), diag::err_mutable_function
);
3520 // FIXME: It would be nicer if the keyword was ignored only for this
3521 // declarator. Otherwise we could get follow-up errors.
3522 D
.getMutableDeclSpec().ClearStorageClassSpecs();
3526 Diag(DS
.getStorageClassSpecLoc(),
3527 diag::err_storageclass_invalid_for_member
);
3528 D
.getMutableDeclSpec().ClearStorageClassSpecs();
3532 bool isInstField
= ((DS
.getStorageClassSpec() == DeclSpec::SCS_unspecified
||
3533 DS
.getStorageClassSpec() == DeclSpec::SCS_mutable
) &&
3536 if (DS
.hasConstexprSpecifier() && isInstField
) {
3537 SemaDiagnosticBuilder B
=
3538 Diag(DS
.getConstexprSpecLoc(), diag::err_invalid_constexpr_member
);
3539 SourceLocation ConstexprLoc
= DS
.getConstexprSpecLoc();
3540 if (InitStyle
== ICIS_NoInit
) {
3542 if (D
.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const
)
3543 B
<< FixItHint::CreateRemoval(ConstexprLoc
);
3545 B
<< FixItHint::CreateReplacement(ConstexprLoc
, "const");
3546 D
.getMutableDeclSpec().ClearConstexprSpec();
3547 const char *PrevSpec
;
3549 bool Failed
= D
.getMutableDeclSpec().SetTypeQual(
3550 DeclSpec::TQ_const
, ConstexprLoc
, PrevSpec
, DiagID
, getLangOpts());
3552 assert(!Failed
&& "Making a constexpr member const shouldn't fail");
3556 const char *PrevSpec
;
3558 if (D
.getMutableDeclSpec().SetStorageClassSpec(
3559 *this, DeclSpec::SCS_static
, ConstexprLoc
, PrevSpec
, DiagID
,
3560 Context
.getPrintingPolicy())) {
3561 assert(DS
.getStorageClassSpec() == DeclSpec::SCS_mutable
&&
3562 "This is the only DeclSpec that should fail to be applied");
3565 B
<< 0 << FixItHint::CreateInsertion(ConstexprLoc
, "static ");
3566 isInstField
= false;
3573 CXXScopeSpec
&SS
= D
.getCXXScopeSpec();
3575 // Data members must have identifiers for names.
3576 if (!Name
.isIdentifier()) {
3577 Diag(Loc
, diag::err_bad_variable_name
)
3582 IdentifierInfo
*II
= Name
.getAsIdentifierInfo();
3584 // Member field could not be with "template" keyword.
3585 // So TemplateParameterLists should be empty in this case.
3586 if (TemplateParameterLists
.size()) {
3587 TemplateParameterList
* TemplateParams
= TemplateParameterLists
[0];
3588 if (TemplateParams
->size()) {
3589 // There is no such thing as a member field template.
3590 Diag(D
.getIdentifierLoc(), diag::err_template_member
)
3592 << SourceRange(TemplateParams
->getTemplateLoc(),
3593 TemplateParams
->getRAngleLoc());
3595 // There is an extraneous 'template<>' for this member.
3596 Diag(TemplateParams
->getTemplateLoc(),
3597 diag::err_template_member_noparams
)
3599 << SourceRange(TemplateParams
->getTemplateLoc(),
3600 TemplateParams
->getRAngleLoc());
3605 if (D
.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
) {
3606 Diag(D
.getIdentifierLoc(), diag::err_member_with_template_arguments
)
3608 << SourceRange(D
.getName().TemplateId
->LAngleLoc
,
3609 D
.getName().TemplateId
->RAngleLoc
)
3610 << D
.getName().TemplateId
->LAngleLoc
;
3611 D
.SetIdentifier(II
, Loc
);
3614 if (SS
.isSet() && !SS
.isInvalid()) {
3615 // The user provided a superfluous scope specifier inside a class
3621 if (DeclContext
*DC
= computeDeclContext(SS
, false))
3622 diagnoseQualifiedDeclaration(SS
, DC
, Name
, D
.getIdentifierLoc(),
3623 D
.getName().getKind() ==
3624 UnqualifiedIdKind::IK_TemplateId
);
3626 Diag(D
.getIdentifierLoc(), diag::err_member_qualification
)
3627 << Name
<< SS
.getRange();
3632 if (MSPropertyAttr
) {
3633 Member
= HandleMSProperty(S
, cast
<CXXRecordDecl
>(CurContext
), Loc
, D
,
3634 BitWidth
, InitStyle
, AS
, *MSPropertyAttr
);
3637 isInstField
= false;
3639 Member
= HandleField(S
, cast
<CXXRecordDecl
>(CurContext
), Loc
, D
,
3640 BitWidth
, InitStyle
, AS
);
3645 CheckShadowInheritedFields(Loc
, Name
, cast
<CXXRecordDecl
>(CurContext
));
3647 Member
= HandleDeclarator(S
, D
, TemplateParameterLists
);
3651 // Non-instance-fields can't have a bitfield.
3653 if (Member
->isInvalidDecl()) {
3654 // don't emit another diagnostic.
3655 } else if (isa
<VarDecl
>(Member
) || isa
<VarTemplateDecl
>(Member
)) {
3656 // C++ 9.6p3: A bit-field shall not be a static member.
3657 // "static member 'A' cannot be a bit-field"
3658 Diag(Loc
, diag::err_static_not_bitfield
)
3659 << Name
<< BitWidth
->getSourceRange();
3660 } else if (isa
<TypedefDecl
>(Member
)) {
3661 // "typedef member 'x' cannot be a bit-field"
3662 Diag(Loc
, diag::err_typedef_not_bitfield
)
3663 << Name
<< BitWidth
->getSourceRange();
3665 // A function typedef ("typedef int f(); f a;").
3666 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3667 Diag(Loc
, diag::err_not_integral_type_bitfield
)
3668 << Name
<< cast
<ValueDecl
>(Member
)->getType()
3669 << BitWidth
->getSourceRange();
3673 Member
->setInvalidDecl();
3676 NamedDecl
*NonTemplateMember
= Member
;
3677 if (FunctionTemplateDecl
*FunTmpl
= dyn_cast
<FunctionTemplateDecl
>(Member
))
3678 NonTemplateMember
= FunTmpl
->getTemplatedDecl();
3679 else if (VarTemplateDecl
*VarTmpl
= dyn_cast
<VarTemplateDecl
>(Member
))
3680 NonTemplateMember
= VarTmpl
->getTemplatedDecl();
3682 Member
->setAccess(AS
);
3684 // If we have declared a member function template or static data member
3685 // template, set the access of the templated declaration as well.
3686 if (NonTemplateMember
!= Member
)
3687 NonTemplateMember
->setAccess(AS
);
3689 // C++ [temp.deduct.guide]p3:
3690 // A deduction guide [...] for a member class template [shall be
3691 // declared] with the same access [as the template].
3692 if (auto *DG
= dyn_cast
<CXXDeductionGuideDecl
>(NonTemplateMember
)) {
3693 auto *TD
= DG
->getDeducedTemplate();
3694 // Access specifiers are only meaningful if both the template and the
3695 // deduction guide are from the same scope.
3696 if (AS
!= TD
->getAccess() &&
3697 TD
->getDeclContext()->getRedeclContext()->Equals(
3698 DG
->getDeclContext()->getRedeclContext())) {
3699 Diag(DG
->getBeginLoc(), diag::err_deduction_guide_wrong_access
);
3700 Diag(TD
->getBeginLoc(), diag::note_deduction_guide_template_access
)
3702 const AccessSpecDecl
*LastAccessSpec
= nullptr;
3703 for (const auto *D
: cast
<CXXRecordDecl
>(CurContext
)->decls()) {
3704 if (const auto *AccessSpec
= dyn_cast
<AccessSpecDecl
>(D
))
3705 LastAccessSpec
= AccessSpec
;
3707 assert(LastAccessSpec
&& "differing access with no access specifier");
3708 Diag(LastAccessSpec
->getBeginLoc(), diag::note_deduction_guide_access
)
3714 if (VS
.isOverrideSpecified())
3715 Member
->addAttr(OverrideAttr::Create(Context
, VS
.getOverrideLoc()));
3716 if (VS
.isFinalSpecified())
3717 Member
->addAttr(FinalAttr::Create(Context
, VS
.getFinalLoc(),
3718 VS
.isFinalSpelledSealed()
3719 ? FinalAttr::Keyword_sealed
3720 : FinalAttr::Keyword_final
));
3722 if (VS
.getLastLocation().isValid()) {
3723 // Update the end location of a method that has a virt-specifiers.
3724 if (CXXMethodDecl
*MD
= dyn_cast_or_null
<CXXMethodDecl
>(Member
))
3725 MD
->setRangeEnd(VS
.getLastLocation());
3728 CheckOverrideControl(Member
);
3730 assert((Name
|| isInstField
) && "No identifier for non-field ?");
3733 FieldDecl
*FD
= cast
<FieldDecl
>(Member
);
3734 FieldCollector
->Add(FD
);
3736 if (!Diags
.isIgnored(diag::warn_unused_private_field
, FD
->getLocation())) {
3737 // Remember all explicit private FieldDecls that have a name, no side
3738 // effects and are not part of a dependent type declaration.
3740 auto DeclHasUnusedAttr
= [](const QualType
&T
) {
3741 if (const TagDecl
*TD
= T
->getAsTagDecl())
3742 return TD
->hasAttr
<UnusedAttr
>();
3743 if (const TypedefType
*TDT
= T
->getAs
<TypedefType
>())
3744 return TDT
->getDecl()->hasAttr
<UnusedAttr
>();
3748 if (!FD
->isImplicit() && FD
->getDeclName() &&
3749 FD
->getAccess() == AS_private
&&
3750 !FD
->hasAttr
<UnusedAttr
>() &&
3751 !FD
->getParent()->isDependentContext() &&
3752 !DeclHasUnusedAttr(FD
->getType()) &&
3753 !InitializationHasSideEffects(*FD
))
3754 UnusedPrivateFields
.insert(FD
);
3762 class UninitializedFieldVisitor
3763 : public EvaluatedExprVisitor
<UninitializedFieldVisitor
> {
3765 // List of Decls to generate a warning on. Also remove Decls that become
3767 llvm::SmallPtrSetImpl
<ValueDecl
*> &Decls
;
3768 // List of base classes of the record. Classes are removed after their
3770 llvm::SmallPtrSetImpl
<QualType
> &BaseClasses
;
3771 // Vector of decls to be removed from the Decl set prior to visiting the
3772 // nodes. These Decls may have been initialized in the prior initializer.
3773 llvm::SmallVector
<ValueDecl
*, 4> DeclsToRemove
;
3774 // If non-null, add a note to the warning pointing back to the constructor.
3775 const CXXConstructorDecl
*Constructor
;
3776 // Variables to hold state when processing an initializer list. When
3777 // InitList is true, special case initialization of FieldDecls matching
3778 // InitListFieldDecl.
3780 FieldDecl
*InitListFieldDecl
;
3781 llvm::SmallVector
<unsigned, 4> InitFieldIndex
;
3784 typedef EvaluatedExprVisitor
<UninitializedFieldVisitor
> Inherited
;
3785 UninitializedFieldVisitor(Sema
&S
,
3786 llvm::SmallPtrSetImpl
<ValueDecl
*> &Decls
,
3787 llvm::SmallPtrSetImpl
<QualType
> &BaseClasses
)
3788 : Inherited(S
.Context
), S(S
), Decls(Decls
), BaseClasses(BaseClasses
),
3789 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3791 // Returns true if the use of ME is not an uninitialized use.
3792 bool IsInitListMemberExprInitialized(MemberExpr
*ME
,
3793 bool CheckReferenceOnly
) {
3794 llvm::SmallVector
<FieldDecl
*, 4> Fields
;
3795 bool ReferenceField
= false;
3797 FieldDecl
*FD
= dyn_cast
<FieldDecl
>(ME
->getMemberDecl());
3800 Fields
.push_back(FD
);
3801 if (FD
->getType()->isReferenceType())
3802 ReferenceField
= true;
3803 ME
= dyn_cast
<MemberExpr
>(ME
->getBase()->IgnoreParenImpCasts());
3806 // Binding a reference to an uninitialized field is not an
3807 // uninitialized use.
3808 if (CheckReferenceOnly
&& !ReferenceField
)
3811 llvm::SmallVector
<unsigned, 4> UsedFieldIndex
;
3812 // Discard the first field since it is the field decl that is being
3814 for (const FieldDecl
*FD
: llvm::drop_begin(llvm::reverse(Fields
)))
3815 UsedFieldIndex
.push_back(FD
->getFieldIndex());
3817 for (auto UsedIter
= UsedFieldIndex
.begin(),
3818 UsedEnd
= UsedFieldIndex
.end(),
3819 OrigIter
= InitFieldIndex
.begin(),
3820 OrigEnd
= InitFieldIndex
.end();
3821 UsedIter
!= UsedEnd
&& OrigIter
!= OrigEnd
; ++UsedIter
, ++OrigIter
) {
3822 if (*UsedIter
< *OrigIter
)
3824 if (*UsedIter
> *OrigIter
)
3831 void HandleMemberExpr(MemberExpr
*ME
, bool CheckReferenceOnly
,
3833 if (isa
<EnumConstantDecl
>(ME
->getMemberDecl()))
3836 // FieldME is the inner-most MemberExpr that is not an anonymous struct
3838 MemberExpr
*FieldME
= ME
;
3840 bool AllPODFields
= FieldME
->getType().isPODType(S
.Context
);
3843 while (MemberExpr
*SubME
=
3844 dyn_cast
<MemberExpr
>(Base
->IgnoreParenImpCasts())) {
3846 if (isa
<VarDecl
>(SubME
->getMemberDecl()))
3849 if (FieldDecl
*FD
= dyn_cast
<FieldDecl
>(SubME
->getMemberDecl()))
3850 if (!FD
->isAnonymousStructOrUnion())
3853 if (!FieldME
->getType().isPODType(S
.Context
))
3854 AllPODFields
= false;
3856 Base
= SubME
->getBase();
3859 if (!isa
<CXXThisExpr
>(Base
->IgnoreParenImpCasts())) {
3864 if (AddressOf
&& AllPODFields
)
3867 ValueDecl
* FoundVD
= FieldME
->getMemberDecl();
3869 if (ImplicitCastExpr
*BaseCast
= dyn_cast
<ImplicitCastExpr
>(Base
)) {
3870 while (isa
<ImplicitCastExpr
>(BaseCast
->getSubExpr())) {
3871 BaseCast
= cast
<ImplicitCastExpr
>(BaseCast
->getSubExpr());
3874 if (BaseCast
->getCastKind() == CK_UncheckedDerivedToBase
) {
3875 QualType T
= BaseCast
->getType();
3876 if (T
->isPointerType() &&
3877 BaseClasses
.count(T
->getPointeeType())) {
3878 S
.Diag(FieldME
->getExprLoc(), diag::warn_base_class_is_uninit
)
3879 << T
->getPointeeType() << FoundVD
;
3884 if (!Decls
.count(FoundVD
))
3887 const bool IsReference
= FoundVD
->getType()->isReferenceType();
3889 if (InitList
&& !AddressOf
&& FoundVD
== InitListFieldDecl
) {
3890 // Special checking for initializer lists.
3891 if (IsInitListMemberExprInitialized(ME
, CheckReferenceOnly
)) {
3895 // Prevent double warnings on use of unbounded references.
3896 if (CheckReferenceOnly
&& !IsReference
)
3900 unsigned diag
= IsReference
3901 ? diag::warn_reference_field_is_uninit
3902 : diag::warn_field_is_uninit
;
3903 S
.Diag(FieldME
->getExprLoc(), diag
) << FoundVD
;
3905 S
.Diag(Constructor
->getLocation(),
3906 diag::note_uninit_in_this_constructor
)
3907 << (Constructor
->isDefaultConstructor() && Constructor
->isImplicit());
3911 void HandleValue(Expr
*E
, bool AddressOf
) {
3912 E
= E
->IgnoreParens();
3914 if (MemberExpr
*ME
= dyn_cast
<MemberExpr
>(E
)) {
3915 HandleMemberExpr(ME
, false /*CheckReferenceOnly*/,
3916 AddressOf
/*AddressOf*/);
3920 if (ConditionalOperator
*CO
= dyn_cast
<ConditionalOperator
>(E
)) {
3921 Visit(CO
->getCond());
3922 HandleValue(CO
->getTrueExpr(), AddressOf
);
3923 HandleValue(CO
->getFalseExpr(), AddressOf
);
3927 if (BinaryConditionalOperator
*BCO
=
3928 dyn_cast
<BinaryConditionalOperator
>(E
)) {
3929 Visit(BCO
->getCond());
3930 HandleValue(BCO
->getFalseExpr(), AddressOf
);
3934 if (OpaqueValueExpr
*OVE
= dyn_cast
<OpaqueValueExpr
>(E
)) {
3935 HandleValue(OVE
->getSourceExpr(), AddressOf
);
3939 if (BinaryOperator
*BO
= dyn_cast
<BinaryOperator
>(E
)) {
3940 switch (BO
->getOpcode()) {
3945 HandleValue(BO
->getLHS(), AddressOf
);
3946 Visit(BO
->getRHS());
3949 Visit(BO
->getLHS());
3950 HandleValue(BO
->getRHS(), AddressOf
);
3958 void CheckInitListExpr(InitListExpr
*ILE
) {
3959 InitFieldIndex
.push_back(0);
3960 for (auto *Child
: ILE
->children()) {
3961 if (InitListExpr
*SubList
= dyn_cast
<InitListExpr
>(Child
)) {
3962 CheckInitListExpr(SubList
);
3966 ++InitFieldIndex
.back();
3968 InitFieldIndex
.pop_back();
3971 void CheckInitializer(Expr
*E
, const CXXConstructorDecl
*FieldConstructor
,
3972 FieldDecl
*Field
, const Type
*BaseClass
) {
3973 // Remove Decls that may have been initialized in the previous
3975 for (ValueDecl
* VD
: DeclsToRemove
)
3977 DeclsToRemove
.clear();
3979 Constructor
= FieldConstructor
;
3980 InitListExpr
*ILE
= dyn_cast
<InitListExpr
>(E
);
3984 InitListFieldDecl
= Field
;
3985 InitFieldIndex
.clear();
3986 CheckInitListExpr(ILE
);
3995 BaseClasses
.erase(BaseClass
->getCanonicalTypeInternal());
3998 void VisitMemberExpr(MemberExpr
*ME
) {
3999 // All uses of unbounded reference fields will warn.
4000 HandleMemberExpr(ME
, true /*CheckReferenceOnly*/, false /*AddressOf*/);
4003 void VisitImplicitCastExpr(ImplicitCastExpr
*E
) {
4004 if (E
->getCastKind() == CK_LValueToRValue
) {
4005 HandleValue(E
->getSubExpr(), false /*AddressOf*/);
4009 Inherited::VisitImplicitCastExpr(E
);
4012 void VisitCXXConstructExpr(CXXConstructExpr
*E
) {
4013 if (E
->getConstructor()->isCopyConstructor()) {
4014 Expr
*ArgExpr
= E
->getArg(0);
4015 if (InitListExpr
*ILE
= dyn_cast
<InitListExpr
>(ArgExpr
))
4016 if (ILE
->getNumInits() == 1)
4017 ArgExpr
= ILE
->getInit(0);
4018 if (ImplicitCastExpr
*ICE
= dyn_cast
<ImplicitCastExpr
>(ArgExpr
))
4019 if (ICE
->getCastKind() == CK_NoOp
)
4020 ArgExpr
= ICE
->getSubExpr();
4021 HandleValue(ArgExpr
, false /*AddressOf*/);
4024 Inherited::VisitCXXConstructExpr(E
);
4027 void VisitCXXMemberCallExpr(CXXMemberCallExpr
*E
) {
4028 Expr
*Callee
= E
->getCallee();
4029 if (isa
<MemberExpr
>(Callee
)) {
4030 HandleValue(Callee
, false /*AddressOf*/);
4031 for (auto *Arg
: E
->arguments())
4036 Inherited::VisitCXXMemberCallExpr(E
);
4039 void VisitCallExpr(CallExpr
*E
) {
4040 // Treat std::move as a use.
4041 if (E
->isCallToStdMove()) {
4042 HandleValue(E
->getArg(0), /*AddressOf=*/false);
4046 Inherited::VisitCallExpr(E
);
4049 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr
*E
) {
4050 Expr
*Callee
= E
->getCallee();
4052 if (isa
<UnresolvedLookupExpr
>(Callee
))
4053 return Inherited::VisitCXXOperatorCallExpr(E
);
4056 for (auto *Arg
: E
->arguments())
4057 HandleValue(Arg
->IgnoreParenImpCasts(), false /*AddressOf*/);
4060 void VisitBinaryOperator(BinaryOperator
*E
) {
4061 // If a field assignment is detected, remove the field from the
4062 // uninitiailized field set.
4063 if (E
->getOpcode() == BO_Assign
)
4064 if (MemberExpr
*ME
= dyn_cast
<MemberExpr
>(E
->getLHS()))
4065 if (FieldDecl
*FD
= dyn_cast
<FieldDecl
>(ME
->getMemberDecl()))
4066 if (!FD
->getType()->isReferenceType())
4067 DeclsToRemove
.push_back(FD
);
4069 if (E
->isCompoundAssignmentOp()) {
4070 HandleValue(E
->getLHS(), false /*AddressOf*/);
4075 Inherited::VisitBinaryOperator(E
);
4078 void VisitUnaryOperator(UnaryOperator
*E
) {
4079 if (E
->isIncrementDecrementOp()) {
4080 HandleValue(E
->getSubExpr(), false /*AddressOf*/);
4083 if (E
->getOpcode() == UO_AddrOf
) {
4084 if (MemberExpr
*ME
= dyn_cast
<MemberExpr
>(E
->getSubExpr())) {
4085 HandleValue(ME
->getBase(), true /*AddressOf*/);
4090 Inherited::VisitUnaryOperator(E
);
4094 // Diagnose value-uses of fields to initialize themselves, e.g.
4096 // where foo is not also a parameter to the constructor.
4097 // Also diagnose across field uninitialized use such as
4099 // TODO: implement -Wuninitialized and fold this into that framework.
4100 static void DiagnoseUninitializedFields(
4101 Sema
&SemaRef
, const CXXConstructorDecl
*Constructor
) {
4103 if (SemaRef
.getDiagnostics().isIgnored(diag::warn_field_is_uninit
,
4104 Constructor
->getLocation())) {
4108 if (Constructor
->isInvalidDecl())
4111 const CXXRecordDecl
*RD
= Constructor
->getParent();
4113 if (RD
->isDependentContext())
4116 // Holds fields that are uninitialized.
4117 llvm::SmallPtrSet
<ValueDecl
*, 4> UninitializedFields
;
4119 // At the beginning, all fields are uninitialized.
4120 for (auto *I
: RD
->decls()) {
4121 if (auto *FD
= dyn_cast
<FieldDecl
>(I
)) {
4122 UninitializedFields
.insert(FD
);
4123 } else if (auto *IFD
= dyn_cast
<IndirectFieldDecl
>(I
)) {
4124 UninitializedFields
.insert(IFD
->getAnonField());
4128 llvm::SmallPtrSet
<QualType
, 4> UninitializedBaseClasses
;
4129 for (const auto &I
: RD
->bases())
4130 UninitializedBaseClasses
.insert(I
.getType().getCanonicalType());
4132 if (UninitializedFields
.empty() && UninitializedBaseClasses
.empty())
4135 UninitializedFieldVisitor
UninitializedChecker(SemaRef
,
4136 UninitializedFields
,
4137 UninitializedBaseClasses
);
4139 for (const auto *FieldInit
: Constructor
->inits()) {
4140 if (UninitializedFields
.empty() && UninitializedBaseClasses
.empty())
4143 Expr
*InitExpr
= FieldInit
->getInit();
4147 if (CXXDefaultInitExpr
*Default
=
4148 dyn_cast
<CXXDefaultInitExpr
>(InitExpr
)) {
4149 InitExpr
= Default
->getExpr();
4152 // In class initializers will point to the constructor.
4153 UninitializedChecker
.CheckInitializer(InitExpr
, Constructor
,
4154 FieldInit
->getAnyMember(),
4155 FieldInit
->getBaseClass());
4157 UninitializedChecker
.CheckInitializer(InitExpr
, nullptr,
4158 FieldInit
->getAnyMember(),
4159 FieldInit
->getBaseClass());
4165 /// Enter a new C++ default initializer scope. After calling this, the
4166 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
4167 /// parsing or instantiating the initializer failed.
4168 void Sema::ActOnStartCXXInClassMemberInitializer() {
4169 // Create a synthetic function scope to represent the call to the constructor
4170 // that notionally surrounds a use of this initializer.
4171 PushFunctionScope();
4174 void Sema::ActOnStartTrailingRequiresClause(Scope
*S
, Declarator
&D
) {
4175 if (!D
.isFunctionDeclarator())
4177 auto &FTI
= D
.getFunctionTypeInfo();
4180 for (auto &Param
: ArrayRef
<DeclaratorChunk::ParamInfo
>(FTI
.Params
,
4182 auto *ParamDecl
= cast
<NamedDecl
>(Param
.Param
);
4183 if (ParamDecl
->getDeclName())
4184 PushOnScopeChains(ParamDecl
, S
, /*AddToContext=*/false);
4188 ExprResult
Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr
) {
4189 return ActOnRequiresClause(ConstraintExpr
);
4192 ExprResult
Sema::ActOnRequiresClause(ExprResult ConstraintExpr
) {
4193 if (ConstraintExpr
.isInvalid())
4196 ConstraintExpr
= CorrectDelayedTyposInExpr(ConstraintExpr
);
4197 if (ConstraintExpr
.isInvalid())
4200 if (DiagnoseUnexpandedParameterPack(ConstraintExpr
.get(),
4201 UPPC_RequiresClause
))
4204 return ConstraintExpr
;
4207 ExprResult
Sema::ConvertMemberDefaultInitExpression(FieldDecl
*FD
,
4209 SourceLocation InitLoc
) {
4210 InitializedEntity Entity
=
4211 InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD
);
4212 InitializationKind Kind
=
4213 FD
->getInClassInitStyle() == ICIS_ListInit
4214 ? InitializationKind::CreateDirectList(InitExpr
->getBeginLoc(),
4215 InitExpr
->getBeginLoc(),
4216 InitExpr
->getEndLoc())
4217 : InitializationKind::CreateCopy(InitExpr
->getBeginLoc(), InitLoc
);
4218 InitializationSequence
Seq(*this, Entity
, Kind
, InitExpr
);
4219 return Seq
.Perform(*this, Entity
, Kind
, InitExpr
);
4222 /// This is invoked after parsing an in-class initializer for a
4223 /// non-static C++ class member, and after instantiating an in-class initializer
4224 /// in a class template. Such actions are deferred until the class is complete.
4225 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl
*D
,
4226 SourceLocation InitLoc
,
4228 // Pop the notional constructor scope we created earlier.
4229 PopFunctionScopeInfo(nullptr, D
);
4231 FieldDecl
*FD
= dyn_cast
<FieldDecl
>(D
);
4232 assert((isa
<MSPropertyDecl
>(D
) || FD
->getInClassInitStyle() != ICIS_NoInit
) &&
4233 "must set init style when field is created");
4236 D
->setInvalidDecl();
4238 FD
->removeInClassInitializer();
4242 if (DiagnoseUnexpandedParameterPack(InitExpr
, UPPC_Initializer
)) {
4243 FD
->setInvalidDecl();
4244 FD
->removeInClassInitializer();
4248 ExprResult Init
= CorrectDelayedTyposInExpr(InitExpr
, /*InitDecl=*/nullptr,
4249 /*RecoverUncorrectedTypos=*/true);
4250 assert(Init
.isUsable() && "Init should at least have a RecoveryExpr");
4251 if (!FD
->getType()->isDependentType() && !Init
.get()->isTypeDependent()) {
4252 Init
= ConvertMemberDefaultInitExpression(FD
, Init
.get(), InitLoc
);
4253 // C++11 [class.base.init]p7:
4254 // The initialization of each base and member constitutes a
4256 if (!Init
.isInvalid())
4257 Init
= ActOnFinishFullExpr(Init
.get(), /*DiscarededValue=*/false);
4258 if (Init
.isInvalid()) {
4259 FD
->setInvalidDecl();
4264 FD
->setInClassInitializer(Init
.get());
4267 /// Find the direct and/or virtual base specifiers that
4268 /// correspond to the given base type, for use in base initialization
4269 /// within a constructor.
4270 static bool FindBaseInitializer(Sema
&SemaRef
,
4271 CXXRecordDecl
*ClassDecl
,
4273 const CXXBaseSpecifier
*&DirectBaseSpec
,
4274 const CXXBaseSpecifier
*&VirtualBaseSpec
) {
4275 // First, check for a direct base class.
4276 DirectBaseSpec
= nullptr;
4277 for (const auto &Base
: ClassDecl
->bases()) {
4278 if (SemaRef
.Context
.hasSameUnqualifiedType(BaseType
, Base
.getType())) {
4279 // We found a direct base of this type. That's what we're
4281 DirectBaseSpec
= &Base
;
4286 // Check for a virtual base class.
4287 // FIXME: We might be able to short-circuit this if we know in advance that
4288 // there are no virtual bases.
4289 VirtualBaseSpec
= nullptr;
4290 if (!DirectBaseSpec
|| !DirectBaseSpec
->isVirtual()) {
4291 // We haven't found a base yet; search the class hierarchy for a
4292 // virtual base class.
4293 CXXBasePaths
Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
4294 /*DetectVirtual=*/false);
4295 if (SemaRef
.IsDerivedFrom(ClassDecl
->getLocation(),
4296 SemaRef
.Context
.getTypeDeclType(ClassDecl
),
4298 for (CXXBasePaths::paths_iterator Path
= Paths
.begin();
4299 Path
!= Paths
.end(); ++Path
) {
4300 if (Path
->back().Base
->isVirtual()) {
4301 VirtualBaseSpec
= Path
->back().Base
;
4308 return DirectBaseSpec
|| VirtualBaseSpec
;
4311 /// Handle a C++ member initializer using braced-init-list syntax.
4313 Sema::ActOnMemInitializer(Decl
*ConstructorD
,
4316 IdentifierInfo
*MemberOrBase
,
4317 ParsedType TemplateTypeTy
,
4319 SourceLocation IdLoc
,
4321 SourceLocation EllipsisLoc
) {
4322 return BuildMemInitializer(ConstructorD
, S
, SS
, MemberOrBase
, TemplateTypeTy
,
4323 DS
, IdLoc
, InitList
,
4327 /// Handle a C++ member initializer using parentheses syntax.
4329 Sema::ActOnMemInitializer(Decl
*ConstructorD
,
4332 IdentifierInfo
*MemberOrBase
,
4333 ParsedType TemplateTypeTy
,
4335 SourceLocation IdLoc
,
4336 SourceLocation LParenLoc
,
4337 ArrayRef
<Expr
*> Args
,
4338 SourceLocation RParenLoc
,
4339 SourceLocation EllipsisLoc
) {
4340 Expr
*List
= ParenListExpr::Create(Context
, LParenLoc
, Args
, RParenLoc
);
4341 return BuildMemInitializer(ConstructorD
, S
, SS
, MemberOrBase
, TemplateTypeTy
,
4342 DS
, IdLoc
, List
, EllipsisLoc
);
4347 // Callback to only accept typo corrections that can be a valid C++ member
4348 // initializer: either a non-static field member or a base class.
4349 class MemInitializerValidatorCCC final
: public CorrectionCandidateCallback
{
4351 explicit MemInitializerValidatorCCC(CXXRecordDecl
*ClassDecl
)
4352 : ClassDecl(ClassDecl
) {}
4354 bool ValidateCandidate(const TypoCorrection
&candidate
) override
{
4355 if (NamedDecl
*ND
= candidate
.getCorrectionDecl()) {
4356 if (FieldDecl
*Member
= dyn_cast
<FieldDecl
>(ND
))
4357 return Member
->getDeclContext()->getRedeclContext()->Equals(ClassDecl
);
4358 return isa
<TypeDecl
>(ND
);
4363 std::unique_ptr
<CorrectionCandidateCallback
> clone() override
{
4364 return std::make_unique
<MemInitializerValidatorCCC
>(*this);
4368 CXXRecordDecl
*ClassDecl
;
4373 bool Sema::DiagRedefinedPlaceholderFieldDecl(SourceLocation Loc
,
4374 RecordDecl
*ClassDecl
,
4375 const IdentifierInfo
*Name
) {
4376 DeclContextLookupResult Result
= ClassDecl
->lookup(Name
);
4377 DeclContextLookupResult::iterator Found
=
4378 llvm::find_if(Result
, [this](const NamedDecl
*Elem
) {
4379 return isa
<FieldDecl
, IndirectFieldDecl
>(Elem
) &&
4380 Elem
->isPlaceholderVar(getLangOpts());
4382 // We did not find a placeholder variable
4383 if (Found
== Result
.end())
4385 Diag(Loc
, diag::err_using_placeholder_variable
) << Name
;
4386 for (DeclContextLookupResult::iterator It
= Found
; It
!= Result
.end(); It
++) {
4387 const NamedDecl
*ND
= *It
;
4388 if (ND
->getDeclContext() != ND
->getDeclContext())
4390 if (isa
<FieldDecl
, IndirectFieldDecl
>(ND
) &&
4391 ND
->isPlaceholderVar(getLangOpts()))
4392 Diag(ND
->getLocation(), diag::note_reference_placeholder
) << ND
;
4398 Sema::tryLookupUnambiguousFieldDecl(RecordDecl
*ClassDecl
,
4399 const IdentifierInfo
*MemberOrBase
) {
4400 ValueDecl
*ND
= nullptr;
4401 for (auto *D
: ClassDecl
->lookup(MemberOrBase
)) {
4402 if (isa
<FieldDecl
, IndirectFieldDecl
>(D
)) {
4403 bool IsPlaceholder
= D
->isPlaceholderVar(getLangOpts());
4405 if (IsPlaceholder
&& D
->getDeclContext() == ND
->getDeclContext())
4410 return cast
<ValueDecl
>(D
);
4411 ND
= cast
<ValueDecl
>(D
);
4417 ValueDecl
*Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl
*ClassDecl
,
4419 ParsedType TemplateTypeTy
,
4420 IdentifierInfo
*MemberOrBase
) {
4421 if (SS
.getScopeRep() || TemplateTypeTy
)
4423 return tryLookupUnambiguousFieldDecl(ClassDecl
, MemberOrBase
);
4426 /// Handle a C++ member initializer.
4428 Sema::BuildMemInitializer(Decl
*ConstructorD
,
4431 IdentifierInfo
*MemberOrBase
,
4432 ParsedType TemplateTypeTy
,
4434 SourceLocation IdLoc
,
4436 SourceLocation EllipsisLoc
) {
4437 ExprResult Res
= CorrectDelayedTyposInExpr(Init
, /*InitDecl=*/nullptr,
4438 /*RecoverUncorrectedTypos=*/true);
4439 if (!Res
.isUsable())
4446 AdjustDeclIfTemplate(ConstructorD
);
4448 CXXConstructorDecl
*Constructor
4449 = dyn_cast
<CXXConstructorDecl
>(ConstructorD
);
4451 // The user wrote a constructor initializer on a function that is
4452 // not a C++ constructor. Ignore the error for now, because we may
4453 // have more member initializers coming; we'll diagnose it just
4454 // once in ActOnMemInitializers.
4458 CXXRecordDecl
*ClassDecl
= Constructor
->getParent();
4460 // C++ [class.base.init]p2:
4461 // Names in a mem-initializer-id are looked up in the scope of the
4462 // constructor's class and, if not found in that scope, are looked
4463 // up in the scope containing the constructor's definition.
4464 // [Note: if the constructor's class contains a member with the
4465 // same name as a direct or virtual base class of the class, a
4466 // mem-initializer-id naming the member or base class and composed
4467 // of a single identifier refers to the class member. A
4468 // mem-initializer-id for the hidden base class may be specified
4469 // using a qualified name. ]
4471 // Look for a member, first.
4472 if (ValueDecl
*Member
= tryLookupCtorInitMemberDecl(
4473 ClassDecl
, SS
, TemplateTypeTy
, MemberOrBase
)) {
4474 if (EllipsisLoc
.isValid())
4475 Diag(EllipsisLoc
, diag::err_pack_expansion_member_init
)
4477 << SourceRange(IdLoc
, Init
->getSourceRange().getEnd());
4479 return BuildMemberInitializer(Member
, Init
, IdLoc
);
4481 // It didn't name a member, so see if it names a class.
4483 TypeSourceInfo
*TInfo
= nullptr;
4485 if (TemplateTypeTy
) {
4486 BaseType
= GetTypeFromParser(TemplateTypeTy
, &TInfo
);
4487 if (BaseType
.isNull())
4489 } else if (DS
.getTypeSpecType() == TST_decltype
) {
4490 BaseType
= BuildDecltypeType(DS
.getRepAsExpr());
4491 } else if (DS
.getTypeSpecType() == TST_decltype_auto
) {
4492 Diag(DS
.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid
);
4495 LookupResult
R(*this, MemberOrBase
, IdLoc
, LookupOrdinaryName
);
4496 LookupParsedName(R
, S
, &SS
);
4498 TypeDecl
*TyD
= R
.getAsSingle
<TypeDecl
>();
4500 if (R
.isAmbiguous()) return true;
4502 // We don't want access-control diagnostics here.
4503 R
.suppressDiagnostics();
4505 if (SS
.isSet() && isDependentScopeSpecifier(SS
)) {
4506 bool NotUnknownSpecialization
= false;
4507 DeclContext
*DC
= computeDeclContext(SS
, false);
4508 if (CXXRecordDecl
*Record
= dyn_cast_or_null
<CXXRecordDecl
>(DC
))
4509 NotUnknownSpecialization
= !Record
->hasAnyDependentBases();
4511 if (!NotUnknownSpecialization
) {
4512 // When the scope specifier can refer to a member of an unknown
4513 // specialization, we take it as a type name.
4514 BaseType
= CheckTypenameType(
4515 ElaboratedTypeKeyword::None
, SourceLocation(),
4516 SS
.getWithLocInContext(Context
), *MemberOrBase
, IdLoc
);
4517 if (BaseType
.isNull())
4520 TInfo
= Context
.CreateTypeSourceInfo(BaseType
);
4521 DependentNameTypeLoc TL
=
4522 TInfo
->getTypeLoc().castAs
<DependentNameTypeLoc
>();
4524 TL
.setNameLoc(IdLoc
);
4525 TL
.setElaboratedKeywordLoc(SourceLocation());
4526 TL
.setQualifierLoc(SS
.getWithLocInContext(Context
));
4530 R
.setLookupName(MemberOrBase
);
4534 if (getLangOpts().MSVCCompat
&& !getLangOpts().CPlusPlus20
) {
4535 if (auto UnqualifiedBase
= R
.getAsSingle
<ClassTemplateDecl
>()) {
4536 auto *TempSpec
= cast
<TemplateSpecializationType
>(
4537 UnqualifiedBase
->getInjectedClassNameSpecialization());
4538 TemplateName TN
= TempSpec
->getTemplateName();
4539 for (auto const &Base
: ClassDecl
->bases()) {
4541 Base
.getType()->getAs
<TemplateSpecializationType
>();
4542 if (BaseTemplate
&& Context
.hasSameTemplateName(
4543 BaseTemplate
->getTemplateName(), TN
)) {
4544 Diag(IdLoc
, diag::ext_unqualified_base_class
)
4545 << SourceRange(IdLoc
, Init
->getSourceRange().getEnd());
4546 BaseType
= Base
.getType();
4553 // If no results were found, try to correct typos.
4554 TypoCorrection Corr
;
4555 MemInitializerValidatorCCC
CCC(ClassDecl
);
4556 if (R
.empty() && BaseType
.isNull() &&
4557 (Corr
= CorrectTypo(R
.getLookupNameInfo(), R
.getLookupKind(), S
, &SS
,
4558 CCC
, CTK_ErrorRecovery
, ClassDecl
))) {
4559 if (FieldDecl
*Member
= Corr
.getCorrectionDeclAs
<FieldDecl
>()) {
4560 // We have found a non-static data member with a similar
4561 // name to what was typed; complain and initialize that
4564 PDiag(diag::err_mem_init_not_member_or_class_suggest
)
4565 << MemberOrBase
<< true);
4566 return BuildMemberInitializer(Member
, Init
, IdLoc
);
4567 } else if (TypeDecl
*Type
= Corr
.getCorrectionDeclAs
<TypeDecl
>()) {
4568 const CXXBaseSpecifier
*DirectBaseSpec
;
4569 const CXXBaseSpecifier
*VirtualBaseSpec
;
4570 if (FindBaseInitializer(*this, ClassDecl
,
4571 Context
.getTypeDeclType(Type
),
4572 DirectBaseSpec
, VirtualBaseSpec
)) {
4573 // We have found a direct or virtual base class with a
4574 // similar name to what was typed; complain and initialize
4577 PDiag(diag::err_mem_init_not_member_or_class_suggest
)
4578 << MemberOrBase
<< false,
4579 PDiag() /*Suppress note, we provide our own.*/);
4581 const CXXBaseSpecifier
*BaseSpec
= DirectBaseSpec
? DirectBaseSpec
4583 Diag(BaseSpec
->getBeginLoc(), diag::note_base_class_specified_here
)
4584 << BaseSpec
->getType() << BaseSpec
->getSourceRange();
4591 if (!TyD
&& BaseType
.isNull()) {
4592 Diag(IdLoc
, diag::err_mem_init_not_member_or_class
)
4593 << MemberOrBase
<< SourceRange(IdLoc
,Init
->getSourceRange().getEnd());
4598 if (BaseType
.isNull()) {
4599 BaseType
= getElaboratedType(ElaboratedTypeKeyword::None
, SS
,
4600 Context
.getTypeDeclType(TyD
));
4601 MarkAnyDeclReferenced(TyD
->getLocation(), TyD
, /*OdrUse=*/false);
4602 TInfo
= Context
.CreateTypeSourceInfo(BaseType
);
4603 ElaboratedTypeLoc TL
= TInfo
->getTypeLoc().castAs
<ElaboratedTypeLoc
>();
4604 TL
.getNamedTypeLoc().castAs
<TypeSpecTypeLoc
>().setNameLoc(IdLoc
);
4605 TL
.setElaboratedKeywordLoc(SourceLocation());
4606 TL
.setQualifierLoc(SS
.getWithLocInContext(Context
));
4611 TInfo
= Context
.getTrivialTypeSourceInfo(BaseType
, IdLoc
);
4613 return BuildBaseInitializer(BaseType
, TInfo
, Init
, ClassDecl
, EllipsisLoc
);
4617 Sema::BuildMemberInitializer(ValueDecl
*Member
, Expr
*Init
,
4618 SourceLocation IdLoc
) {
4619 FieldDecl
*DirectMember
= dyn_cast
<FieldDecl
>(Member
);
4620 IndirectFieldDecl
*IndirectMember
= dyn_cast
<IndirectFieldDecl
>(Member
);
4621 assert((DirectMember
|| IndirectMember
) &&
4622 "Member must be a FieldDecl or IndirectFieldDecl");
4624 if (DiagnoseUnexpandedParameterPack(Init
, UPPC_Initializer
))
4627 if (Member
->isInvalidDecl())
4631 if (ParenListExpr
*ParenList
= dyn_cast
<ParenListExpr
>(Init
)) {
4632 Args
= MultiExprArg(ParenList
->getExprs(), ParenList
->getNumExprs());
4633 } else if (InitListExpr
*InitList
= dyn_cast
<InitListExpr
>(Init
)) {
4634 Args
= MultiExprArg(InitList
->getInits(), InitList
->getNumInits());
4636 // Template instantiation doesn't reconstruct ParenListExprs for us.
4640 SourceRange InitRange
= Init
->getSourceRange();
4642 if (Member
->getType()->isDependentType() || Init
->isTypeDependent()) {
4643 // Can't check initialization for a member of dependent type or when
4644 // any of the arguments are type-dependent expressions.
4645 DiscardCleanupsInEvaluationContext();
4647 bool InitList
= false;
4648 if (isa
<InitListExpr
>(Init
)) {
4653 // Initialize the member.
4654 InitializedEntity MemberEntity
=
4655 DirectMember
? InitializedEntity::InitializeMember(DirectMember
, nullptr)
4656 : InitializedEntity::InitializeMember(IndirectMember
,
4658 InitializationKind Kind
=
4659 InitList
? InitializationKind::CreateDirectList(
4660 IdLoc
, Init
->getBeginLoc(), Init
->getEndLoc())
4661 : InitializationKind::CreateDirect(IdLoc
, InitRange
.getBegin(),
4662 InitRange
.getEnd());
4664 InitializationSequence
InitSeq(*this, MemberEntity
, Kind
, Args
);
4665 ExprResult MemberInit
= InitSeq
.Perform(*this, MemberEntity
, Kind
, Args
,
4667 if (!MemberInit
.isInvalid()) {
4668 // C++11 [class.base.init]p7:
4669 // The initialization of each base and member constitutes a
4671 MemberInit
= ActOnFinishFullExpr(MemberInit
.get(), InitRange
.getBegin(),
4672 /*DiscardedValue*/ false);
4675 if (MemberInit
.isInvalid()) {
4676 // Args were sensible expressions but we couldn't initialize the member
4677 // from them. Preserve them in a RecoveryExpr instead.
4678 Init
= CreateRecoveryExpr(InitRange
.getBegin(), InitRange
.getEnd(), Args
,
4684 Init
= MemberInit
.get();
4689 return new (Context
) CXXCtorInitializer(Context
, DirectMember
, IdLoc
,
4690 InitRange
.getBegin(), Init
,
4691 InitRange
.getEnd());
4693 return new (Context
) CXXCtorInitializer(Context
, IndirectMember
, IdLoc
,
4694 InitRange
.getBegin(), Init
,
4695 InitRange
.getEnd());
4700 Sema::BuildDelegatingInitializer(TypeSourceInfo
*TInfo
, Expr
*Init
,
4701 CXXRecordDecl
*ClassDecl
) {
4702 SourceLocation NameLoc
= TInfo
->getTypeLoc().getSourceRange().getBegin();
4703 if (!LangOpts
.CPlusPlus11
)
4704 return Diag(NameLoc
, diag::err_delegating_ctor
)
4705 << TInfo
->getTypeLoc().getSourceRange();
4706 Diag(NameLoc
, diag::warn_cxx98_compat_delegating_ctor
);
4708 bool InitList
= true;
4709 MultiExprArg Args
= Init
;
4710 if (ParenListExpr
*ParenList
= dyn_cast
<ParenListExpr
>(Init
)) {
4712 Args
= MultiExprArg(ParenList
->getExprs(), ParenList
->getNumExprs());
4715 SourceRange InitRange
= Init
->getSourceRange();
4716 // Initialize the object.
4717 InitializedEntity DelegationEntity
= InitializedEntity::InitializeDelegation(
4718 QualType(ClassDecl
->getTypeForDecl(), 0));
4719 InitializationKind Kind
=
4720 InitList
? InitializationKind::CreateDirectList(
4721 NameLoc
, Init
->getBeginLoc(), Init
->getEndLoc())
4722 : InitializationKind::CreateDirect(NameLoc
, InitRange
.getBegin(),
4723 InitRange
.getEnd());
4724 InitializationSequence
InitSeq(*this, DelegationEntity
, Kind
, Args
);
4725 ExprResult DelegationInit
= InitSeq
.Perform(*this, DelegationEntity
, Kind
,
4727 if (!DelegationInit
.isInvalid()) {
4728 assert((DelegationInit
.get()->containsErrors() ||
4729 cast
<CXXConstructExpr
>(DelegationInit
.get())->getConstructor()) &&
4730 "Delegating constructor with no target?");
4732 // C++11 [class.base.init]p7:
4733 // The initialization of each base and member constitutes a
4735 DelegationInit
= ActOnFinishFullExpr(
4736 DelegationInit
.get(), InitRange
.getBegin(), /*DiscardedValue*/ false);
4739 if (DelegationInit
.isInvalid()) {
4741 CreateRecoveryExpr(InitRange
.getBegin(), InitRange
.getEnd(), Args
,
4742 QualType(ClassDecl
->getTypeForDecl(), 0));
4743 if (DelegationInit
.isInvalid())
4746 // If we are in a dependent context, template instantiation will
4747 // perform this type-checking again. Just save the arguments that we
4748 // received in a ParenListExpr.
4749 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4750 // of the information that we have about the base
4751 // initializer. However, deconstructing the ASTs is a dicey process,
4752 // and this approach is far more likely to get the corner cases right.
4753 if (CurContext
->isDependentContext())
4754 DelegationInit
= Init
;
4757 return new (Context
) CXXCtorInitializer(Context
, TInfo
, InitRange
.getBegin(),
4758 DelegationInit
.getAs
<Expr
>(),
4759 InitRange
.getEnd());
4763 Sema::BuildBaseInitializer(QualType BaseType
, TypeSourceInfo
*BaseTInfo
,
4764 Expr
*Init
, CXXRecordDecl
*ClassDecl
,
4765 SourceLocation EllipsisLoc
) {
4766 SourceLocation BaseLoc
= BaseTInfo
->getTypeLoc().getBeginLoc();
4768 if (!BaseType
->isDependentType() && !BaseType
->isRecordType())
4769 return Diag(BaseLoc
, diag::err_base_init_does_not_name_class
)
4770 << BaseType
<< BaseTInfo
->getTypeLoc().getSourceRange();
4772 // C++ [class.base.init]p2:
4773 // [...] Unless the mem-initializer-id names a nonstatic data
4774 // member of the constructor's class or a direct or virtual base
4775 // of that class, the mem-initializer is ill-formed. A
4776 // mem-initializer-list can initialize a base class using any
4777 // name that denotes that base class type.
4779 // We can store the initializers in "as-written" form and delay analysis until
4780 // instantiation if the constructor is dependent. But not for dependent
4781 // (broken) code in a non-template! SetCtorInitializers does not expect this.
4782 bool Dependent
= CurContext
->isDependentContext() &&
4783 (BaseType
->isDependentType() || Init
->isTypeDependent());
4785 SourceRange InitRange
= Init
->getSourceRange();
4786 if (EllipsisLoc
.isValid()) {
4787 // This is a pack expansion.
4788 if (!BaseType
->containsUnexpandedParameterPack()) {
4789 Diag(EllipsisLoc
, diag::err_pack_expansion_without_parameter_packs
)
4790 << SourceRange(BaseLoc
, InitRange
.getEnd());
4792 EllipsisLoc
= SourceLocation();
4795 // Check for any unexpanded parameter packs.
4796 if (DiagnoseUnexpandedParameterPack(BaseLoc
, BaseTInfo
, UPPC_Initializer
))
4799 if (DiagnoseUnexpandedParameterPack(Init
, UPPC_Initializer
))
4803 // Check for direct and virtual base classes.
4804 const CXXBaseSpecifier
*DirectBaseSpec
= nullptr;
4805 const CXXBaseSpecifier
*VirtualBaseSpec
= nullptr;
4807 if (Context
.hasSameUnqualifiedType(QualType(ClassDecl
->getTypeForDecl(),0),
4809 return BuildDelegatingInitializer(BaseTInfo
, Init
, ClassDecl
);
4811 FindBaseInitializer(*this, ClassDecl
, BaseType
, DirectBaseSpec
,
4814 // C++ [base.class.init]p2:
4815 // Unless the mem-initializer-id names a nonstatic data member of the
4816 // constructor's class or a direct or virtual base of that class, the
4817 // mem-initializer is ill-formed.
4818 if (!DirectBaseSpec
&& !VirtualBaseSpec
) {
4819 // If the class has any dependent bases, then it's possible that
4820 // one of those types will resolve to the same type as
4821 // BaseType. Therefore, just treat this as a dependent base
4822 // class initialization. FIXME: Should we try to check the
4823 // initialization anyway? It seems odd.
4824 if (ClassDecl
->hasAnyDependentBases())
4827 return Diag(BaseLoc
, diag::err_not_direct_base_or_virtual
)
4828 << BaseType
<< Context
.getTypeDeclType(ClassDecl
)
4829 << BaseTInfo
->getTypeLoc().getSourceRange();
4834 DiscardCleanupsInEvaluationContext();
4836 return new (Context
) CXXCtorInitializer(Context
, BaseTInfo
,
4837 /*IsVirtual=*/false,
4838 InitRange
.getBegin(), Init
,
4839 InitRange
.getEnd(), EllipsisLoc
);
4842 // C++ [base.class.init]p2:
4843 // If a mem-initializer-id is ambiguous because it designates both
4844 // a direct non-virtual base class and an inherited virtual base
4845 // class, the mem-initializer is ill-formed.
4846 if (DirectBaseSpec
&& VirtualBaseSpec
)
4847 return Diag(BaseLoc
, diag::err_base_init_direct_and_virtual
)
4848 << BaseType
<< BaseTInfo
->getTypeLoc().getLocalSourceRange();
4850 const CXXBaseSpecifier
*BaseSpec
= DirectBaseSpec
;
4852 BaseSpec
= VirtualBaseSpec
;
4854 // Initialize the base.
4855 bool InitList
= true;
4856 MultiExprArg Args
= Init
;
4857 if (ParenListExpr
*ParenList
= dyn_cast
<ParenListExpr
>(Init
)) {
4859 Args
= MultiExprArg(ParenList
->getExprs(), ParenList
->getNumExprs());
4862 InitializedEntity BaseEntity
=
4863 InitializedEntity::InitializeBase(Context
, BaseSpec
, VirtualBaseSpec
);
4864 InitializationKind Kind
=
4865 InitList
? InitializationKind::CreateDirectList(BaseLoc
)
4866 : InitializationKind::CreateDirect(BaseLoc
, InitRange
.getBegin(),
4867 InitRange
.getEnd());
4868 InitializationSequence
InitSeq(*this, BaseEntity
, Kind
, Args
);
4869 ExprResult BaseInit
= InitSeq
.Perform(*this, BaseEntity
, Kind
, Args
, nullptr);
4870 if (!BaseInit
.isInvalid()) {
4871 // C++11 [class.base.init]p7:
4872 // The initialization of each base and member constitutes a
4874 BaseInit
= ActOnFinishFullExpr(BaseInit
.get(), InitRange
.getBegin(),
4875 /*DiscardedValue*/ false);
4878 if (BaseInit
.isInvalid()) {
4879 BaseInit
= CreateRecoveryExpr(InitRange
.getBegin(), InitRange
.getEnd(),
4881 if (BaseInit
.isInvalid())
4884 // If we are in a dependent context, template instantiation will
4885 // perform this type-checking again. Just save the arguments that we
4886 // received in a ParenListExpr.
4887 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4888 // of the information that we have about the base
4889 // initializer. However, deconstructing the ASTs is a dicey process,
4890 // and this approach is far more likely to get the corner cases right.
4891 if (CurContext
->isDependentContext())
4895 return new (Context
) CXXCtorInitializer(Context
, BaseTInfo
,
4896 BaseSpec
->isVirtual(),
4897 InitRange
.getBegin(),
4898 BaseInit
.getAs
<Expr
>(),
4899 InitRange
.getEnd(), EllipsisLoc
);
4902 // Create a static_cast\<T&&>(expr).
4903 static Expr
*CastForMoving(Sema
&SemaRef
, Expr
*E
) {
4904 QualType TargetType
=
4905 SemaRef
.BuildReferenceType(E
->getType(), /*SpelledAsLValue*/ false,
4906 SourceLocation(), DeclarationName());
4907 SourceLocation ExprLoc
= E
->getBeginLoc();
4908 TypeSourceInfo
*TargetLoc
= SemaRef
.Context
.getTrivialTypeSourceInfo(
4909 TargetType
, ExprLoc
);
4911 return SemaRef
.BuildCXXNamedCast(ExprLoc
, tok::kw_static_cast
, TargetLoc
, E
,
4912 SourceRange(ExprLoc
, ExprLoc
),
4913 E
->getSourceRange()).get();
4916 /// ImplicitInitializerKind - How an implicit base or member initializer should
4917 /// initialize its base or member.
4918 enum ImplicitInitializerKind
{
4926 BuildImplicitBaseInitializer(Sema
&SemaRef
, CXXConstructorDecl
*Constructor
,
4927 ImplicitInitializerKind ImplicitInitKind
,
4928 CXXBaseSpecifier
*BaseSpec
,
4929 bool IsInheritedVirtualBase
,
4930 CXXCtorInitializer
*&CXXBaseInit
) {
4931 InitializedEntity InitEntity
4932 = InitializedEntity::InitializeBase(SemaRef
.Context
, BaseSpec
,
4933 IsInheritedVirtualBase
);
4935 ExprResult BaseInit
;
4937 switch (ImplicitInitKind
) {
4940 InitializationKind InitKind
4941 = InitializationKind::CreateDefault(Constructor
->getLocation());
4942 InitializationSequence
InitSeq(SemaRef
, InitEntity
, InitKind
, std::nullopt
);
4943 BaseInit
= InitSeq
.Perform(SemaRef
, InitEntity
, InitKind
, std::nullopt
);
4949 bool Moving
= ImplicitInitKind
== IIK_Move
;
4950 ParmVarDecl
*Param
= Constructor
->getParamDecl(0);
4951 QualType ParamType
= Param
->getType().getNonReferenceType();
4954 DeclRefExpr::Create(SemaRef
.Context
, NestedNameSpecifierLoc(),
4955 SourceLocation(), Param
, false,
4956 Constructor
->getLocation(), ParamType
,
4957 VK_LValue
, nullptr);
4959 SemaRef
.MarkDeclRefReferenced(cast
<DeclRefExpr
>(CopyCtorArg
));
4961 // Cast to the base class to avoid ambiguities.
4963 SemaRef
.Context
.getQualifiedType(BaseSpec
->getType().getUnqualifiedType(),
4964 ParamType
.getQualifiers());
4967 CopyCtorArg
= CastForMoving(SemaRef
, CopyCtorArg
);
4970 CXXCastPath BasePath
;
4971 BasePath
.push_back(BaseSpec
);
4972 CopyCtorArg
= SemaRef
.ImpCastExprToType(CopyCtorArg
, ArgTy
,
4973 CK_UncheckedDerivedToBase
,
4974 Moving
? VK_XValue
: VK_LValue
,
4977 InitializationKind InitKind
4978 = InitializationKind::CreateDirect(Constructor
->getLocation(),
4979 SourceLocation(), SourceLocation());
4980 InitializationSequence
InitSeq(SemaRef
, InitEntity
, InitKind
, CopyCtorArg
);
4981 BaseInit
= InitSeq
.Perform(SemaRef
, InitEntity
, InitKind
, CopyCtorArg
);
4986 BaseInit
= SemaRef
.MaybeCreateExprWithCleanups(BaseInit
);
4987 if (BaseInit
.isInvalid())
4991 new (SemaRef
.Context
) CXXCtorInitializer(SemaRef
.Context
,
4992 SemaRef
.Context
.getTrivialTypeSourceInfo(BaseSpec
->getType(),
4994 BaseSpec
->isVirtual(),
4996 BaseInit
.getAs
<Expr
>(),
5003 static bool RefersToRValueRef(Expr
*MemRef
) {
5004 ValueDecl
*Referenced
= cast
<MemberExpr
>(MemRef
)->getMemberDecl();
5005 return Referenced
->getType()->isRValueReferenceType();
5009 BuildImplicitMemberInitializer(Sema
&SemaRef
, CXXConstructorDecl
*Constructor
,
5010 ImplicitInitializerKind ImplicitInitKind
,
5011 FieldDecl
*Field
, IndirectFieldDecl
*Indirect
,
5012 CXXCtorInitializer
*&CXXMemberInit
) {
5013 if (Field
->isInvalidDecl())
5016 SourceLocation Loc
= Constructor
->getLocation();
5018 if (ImplicitInitKind
== IIK_Copy
|| ImplicitInitKind
== IIK_Move
) {
5019 bool Moving
= ImplicitInitKind
== IIK_Move
;
5020 ParmVarDecl
*Param
= Constructor
->getParamDecl(0);
5021 QualType ParamType
= Param
->getType().getNonReferenceType();
5023 // Suppress copying zero-width bitfields.
5024 if (Field
->isZeroLengthBitField(SemaRef
.Context
))
5027 Expr
*MemberExprBase
=
5028 DeclRefExpr::Create(SemaRef
.Context
, NestedNameSpecifierLoc(),
5029 SourceLocation(), Param
, false,
5030 Loc
, ParamType
, VK_LValue
, nullptr);
5032 SemaRef
.MarkDeclRefReferenced(cast
<DeclRefExpr
>(MemberExprBase
));
5035 MemberExprBase
= CastForMoving(SemaRef
, MemberExprBase
);
5038 // Build a reference to this field within the parameter.
5040 LookupResult
MemberLookup(SemaRef
, Field
->getDeclName(), Loc
,
5041 Sema::LookupMemberName
);
5042 MemberLookup
.addDecl(Indirect
? cast
<ValueDecl
>(Indirect
)
5043 : cast
<ValueDecl
>(Field
), AS_public
);
5044 MemberLookup
.resolveKind();
5046 = SemaRef
.BuildMemberReferenceExpr(MemberExprBase
,
5050 /*TemplateKWLoc=*/SourceLocation(),
5051 /*FirstQualifierInScope=*/nullptr,
5053 /*TemplateArgs=*/nullptr,
5055 if (CtorArg
.isInvalid())
5058 // C++11 [class.copy]p15:
5059 // - if a member m has rvalue reference type T&&, it is direct-initialized
5060 // with static_cast<T&&>(x.m);
5061 if (RefersToRValueRef(CtorArg
.get())) {
5062 CtorArg
= CastForMoving(SemaRef
, CtorArg
.get());
5065 InitializedEntity Entity
=
5066 Indirect
? InitializedEntity::InitializeMember(Indirect
, nullptr,
5068 : InitializedEntity::InitializeMember(Field
, nullptr,
5071 // Direct-initialize to use the copy constructor.
5072 InitializationKind InitKind
=
5073 InitializationKind::CreateDirect(Loc
, SourceLocation(), SourceLocation());
5075 Expr
*CtorArgE
= CtorArg
.getAs
<Expr
>();
5076 InitializationSequence
InitSeq(SemaRef
, Entity
, InitKind
, CtorArgE
);
5077 ExprResult MemberInit
=
5078 InitSeq
.Perform(SemaRef
, Entity
, InitKind
, MultiExprArg(&CtorArgE
, 1));
5079 MemberInit
= SemaRef
.MaybeCreateExprWithCleanups(MemberInit
);
5080 if (MemberInit
.isInvalid())
5084 CXXMemberInit
= new (SemaRef
.Context
) CXXCtorInitializer(
5085 SemaRef
.Context
, Indirect
, Loc
, Loc
, MemberInit
.getAs
<Expr
>(), Loc
);
5087 CXXMemberInit
= new (SemaRef
.Context
) CXXCtorInitializer(
5088 SemaRef
.Context
, Field
, Loc
, Loc
, MemberInit
.getAs
<Expr
>(), Loc
);
5092 assert((ImplicitInitKind
== IIK_Default
|| ImplicitInitKind
== IIK_Inherit
) &&
5093 "Unhandled implicit init kind!");
5095 QualType FieldBaseElementType
=
5096 SemaRef
.Context
.getBaseElementType(Field
->getType());
5098 if (FieldBaseElementType
->isRecordType()) {
5099 InitializedEntity InitEntity
=
5100 Indirect
? InitializedEntity::InitializeMember(Indirect
, nullptr,
5102 : InitializedEntity::InitializeMember(Field
, nullptr,
5104 InitializationKind InitKind
=
5105 InitializationKind::CreateDefault(Loc
);
5107 InitializationSequence
InitSeq(SemaRef
, InitEntity
, InitKind
, std::nullopt
);
5108 ExprResult MemberInit
=
5109 InitSeq
.Perform(SemaRef
, InitEntity
, InitKind
, std::nullopt
);
5111 MemberInit
= SemaRef
.MaybeCreateExprWithCleanups(MemberInit
);
5112 if (MemberInit
.isInvalid())
5116 CXXMemberInit
= new (SemaRef
.Context
) CXXCtorInitializer(SemaRef
.Context
,
5122 CXXMemberInit
= new (SemaRef
.Context
) CXXCtorInitializer(SemaRef
.Context
,
5129 if (!Field
->getParent()->isUnion()) {
5130 if (FieldBaseElementType
->isReferenceType()) {
5131 SemaRef
.Diag(Constructor
->getLocation(),
5132 diag::err_uninitialized_member_in_ctor
)
5133 << (int)Constructor
->isImplicit()
5134 << SemaRef
.Context
.getTagDeclType(Constructor
->getParent())
5135 << 0 << Field
->getDeclName();
5136 SemaRef
.Diag(Field
->getLocation(), diag::note_declared_at
);
5140 if (FieldBaseElementType
.isConstQualified()) {
5141 SemaRef
.Diag(Constructor
->getLocation(),
5142 diag::err_uninitialized_member_in_ctor
)
5143 << (int)Constructor
->isImplicit()
5144 << SemaRef
.Context
.getTagDeclType(Constructor
->getParent())
5145 << 1 << Field
->getDeclName();
5146 SemaRef
.Diag(Field
->getLocation(), diag::note_declared_at
);
5151 if (FieldBaseElementType
.hasNonTrivialObjCLifetime()) {
5153 // Default-initialize Objective-C pointers to NULL.
5155 = new (SemaRef
.Context
) CXXCtorInitializer(SemaRef
.Context
, Field
,
5157 new (SemaRef
.Context
) ImplicitValueInitExpr(Field
->getType()),
5162 // Nothing to initialize.
5163 CXXMemberInit
= nullptr;
5168 struct BaseAndFieldInfo
{
5170 CXXConstructorDecl
*Ctor
;
5171 bool AnyErrorsInInits
;
5172 ImplicitInitializerKind IIK
;
5173 llvm::DenseMap
<const void *, CXXCtorInitializer
*> AllBaseFields
;
5174 SmallVector
<CXXCtorInitializer
*, 8> AllToInit
;
5175 llvm::DenseMap
<TagDecl
*, FieldDecl
*> ActiveUnionMember
;
5177 BaseAndFieldInfo(Sema
&S
, CXXConstructorDecl
*Ctor
, bool ErrorsInInits
)
5178 : S(S
), Ctor(Ctor
), AnyErrorsInInits(ErrorsInInits
) {
5179 bool Generated
= Ctor
->isImplicit() || Ctor
->isDefaulted();
5180 if (Ctor
->getInheritedConstructor())
5182 else if (Generated
&& Ctor
->isCopyConstructor())
5184 else if (Generated
&& Ctor
->isMoveConstructor())
5190 bool isImplicitCopyOrMove() const {
5201 llvm_unreachable("Invalid ImplicitInitializerKind!");
5204 bool addFieldInitializer(CXXCtorInitializer
*Init
) {
5205 AllToInit
.push_back(Init
);
5207 // Check whether this initializer makes the field "used".
5208 if (Init
->getInit()->HasSideEffects(S
.Context
))
5209 S
.UnusedPrivateFields
.remove(Init
->getAnyMember());
5214 bool isInactiveUnionMember(FieldDecl
*Field
) {
5215 RecordDecl
*Record
= Field
->getParent();
5216 if (!Record
->isUnion())
5219 if (FieldDecl
*Active
=
5220 ActiveUnionMember
.lookup(Record
->getCanonicalDecl()))
5221 return Active
!= Field
->getCanonicalDecl();
5223 // In an implicit copy or move constructor, ignore any in-class initializer.
5224 if (isImplicitCopyOrMove())
5227 // If there's no explicit initialization, the field is active only if it
5228 // has an in-class initializer...
5229 if (Field
->hasInClassInitializer())
5231 // ... or it's an anonymous struct or union whose class has an in-class
5233 if (!Field
->isAnonymousStructOrUnion())
5235 CXXRecordDecl
*FieldRD
= Field
->getType()->getAsCXXRecordDecl();
5236 return !FieldRD
->hasInClassInitializer();
5239 /// Determine whether the given field is, or is within, a union member
5240 /// that is inactive (because there was an initializer given for a different
5241 /// member of the union, or because the union was not initialized at all).
5242 bool isWithinInactiveUnionMember(FieldDecl
*Field
,
5243 IndirectFieldDecl
*Indirect
) {
5245 return isInactiveUnionMember(Field
);
5247 for (auto *C
: Indirect
->chain()) {
5248 FieldDecl
*Field
= dyn_cast
<FieldDecl
>(C
);
5249 if (Field
&& isInactiveUnionMember(Field
))
5257 /// Determine whether the given type is an incomplete or zero-lenfgth
5259 static bool isIncompleteOrZeroLengthArrayType(ASTContext
&Context
, QualType T
) {
5260 if (T
->isIncompleteArrayType())
5263 while (const ConstantArrayType
*ArrayT
= Context
.getAsConstantArrayType(T
)) {
5264 if (!ArrayT
->getSize())
5267 T
= ArrayT
->getElementType();
5273 static bool CollectFieldInitializer(Sema
&SemaRef
, BaseAndFieldInfo
&Info
,
5275 IndirectFieldDecl
*Indirect
= nullptr) {
5276 if (Field
->isInvalidDecl())
5279 // Overwhelmingly common case: we have a direct initializer for this field.
5280 if (CXXCtorInitializer
*Init
=
5281 Info
.AllBaseFields
.lookup(Field
->getCanonicalDecl()))
5282 return Info
.addFieldInitializer(Init
);
5284 // C++11 [class.base.init]p8:
5285 // if the entity is a non-static data member that has a
5286 // brace-or-equal-initializer and either
5287 // -- the constructor's class is a union and no other variant member of that
5288 // union is designated by a mem-initializer-id or
5289 // -- the constructor's class is not a union, and, if the entity is a member
5290 // of an anonymous union, no other member of that union is designated by
5291 // a mem-initializer-id,
5292 // the entity is initialized as specified in [dcl.init].
5294 // We also apply the same rules to handle anonymous structs within anonymous
5296 if (Info
.isWithinInactiveUnionMember(Field
, Indirect
))
5299 if (Field
->hasInClassInitializer() && !Info
.isImplicitCopyOrMove()) {
5301 SemaRef
.BuildCXXDefaultInitExpr(Info
.Ctor
->getLocation(), Field
);
5302 if (DIE
.isInvalid())
5305 auto Entity
= InitializedEntity::InitializeMember(Field
, nullptr, true);
5306 SemaRef
.checkInitializerLifetime(Entity
, DIE
.get());
5308 CXXCtorInitializer
*Init
;
5310 Init
= new (SemaRef
.Context
)
5311 CXXCtorInitializer(SemaRef
.Context
, Indirect
, SourceLocation(),
5312 SourceLocation(), DIE
.get(), SourceLocation());
5314 Init
= new (SemaRef
.Context
)
5315 CXXCtorInitializer(SemaRef
.Context
, Field
, SourceLocation(),
5316 SourceLocation(), DIE
.get(), SourceLocation());
5317 return Info
.addFieldInitializer(Init
);
5320 // Don't initialize incomplete or zero-length arrays.
5321 if (isIncompleteOrZeroLengthArrayType(SemaRef
.Context
, Field
->getType()))
5324 // Don't try to build an implicit initializer if there were semantic
5325 // errors in any of the initializers (and therefore we might be
5326 // missing some that the user actually wrote).
5327 if (Info
.AnyErrorsInInits
)
5330 CXXCtorInitializer
*Init
= nullptr;
5331 if (BuildImplicitMemberInitializer(Info
.S
, Info
.Ctor
, Info
.IIK
, Field
,
5338 return Info
.addFieldInitializer(Init
);
5342 Sema::SetDelegatingInitializer(CXXConstructorDecl
*Constructor
,
5343 CXXCtorInitializer
*Initializer
) {
5344 assert(Initializer
->isDelegatingInitializer());
5345 Constructor
->setNumCtorInitializers(1);
5346 CXXCtorInitializer
**initializer
=
5347 new (Context
) CXXCtorInitializer
*[1];
5348 memcpy(initializer
, &Initializer
, sizeof (CXXCtorInitializer
*));
5349 Constructor
->setCtorInitializers(initializer
);
5351 if (CXXDestructorDecl
*Dtor
= LookupDestructor(Constructor
->getParent())) {
5352 MarkFunctionReferenced(Initializer
->getSourceLocation(), Dtor
);
5353 DiagnoseUseOfDecl(Dtor
, Initializer
->getSourceLocation());
5356 DelegatingCtorDecls
.push_back(Constructor
);
5358 DiagnoseUninitializedFields(*this, Constructor
);
5363 bool Sema::SetCtorInitializers(CXXConstructorDecl
*Constructor
, bool AnyErrors
,
5364 ArrayRef
<CXXCtorInitializer
*> Initializers
) {
5365 if (Constructor
->isDependentContext()) {
5366 // Just store the initializers as written, they will be checked during
5368 if (!Initializers
.empty()) {
5369 Constructor
->setNumCtorInitializers(Initializers
.size());
5370 CXXCtorInitializer
**baseOrMemberInitializers
=
5371 new (Context
) CXXCtorInitializer
*[Initializers
.size()];
5372 memcpy(baseOrMemberInitializers
, Initializers
.data(),
5373 Initializers
.size() * sizeof(CXXCtorInitializer
*));
5374 Constructor
->setCtorInitializers(baseOrMemberInitializers
);
5377 // Let template instantiation know whether we had errors.
5379 Constructor
->setInvalidDecl();
5384 BaseAndFieldInfo
Info(*this, Constructor
, AnyErrors
);
5386 // We need to build the initializer AST according to order of construction
5387 // and not what user specified in the Initializers list.
5388 CXXRecordDecl
*ClassDecl
= Constructor
->getParent()->getDefinition();
5392 bool HadError
= false;
5394 for (unsigned i
= 0; i
< Initializers
.size(); i
++) {
5395 CXXCtorInitializer
*Member
= Initializers
[i
];
5397 if (Member
->isBaseInitializer())
5398 Info
.AllBaseFields
[Member
->getBaseClass()->getAs
<RecordType
>()] = Member
;
5400 Info
.AllBaseFields
[Member
->getAnyMember()->getCanonicalDecl()] = Member
;
5402 if (IndirectFieldDecl
*F
= Member
->getIndirectMember()) {
5403 for (auto *C
: F
->chain()) {
5404 FieldDecl
*FD
= dyn_cast
<FieldDecl
>(C
);
5405 if (FD
&& FD
->getParent()->isUnion())
5406 Info
.ActiveUnionMember
.insert(std::make_pair(
5407 FD
->getParent()->getCanonicalDecl(), FD
->getCanonicalDecl()));
5409 } else if (FieldDecl
*FD
= Member
->getMember()) {
5410 if (FD
->getParent()->isUnion())
5411 Info
.ActiveUnionMember
.insert(std::make_pair(
5412 FD
->getParent()->getCanonicalDecl(), FD
->getCanonicalDecl()));
5417 // Keep track of the direct virtual bases.
5418 llvm::SmallPtrSet
<CXXBaseSpecifier
*, 16> DirectVBases
;
5419 for (auto &I
: ClassDecl
->bases()) {
5421 DirectVBases
.insert(&I
);
5424 // Push virtual bases before others.
5425 for (auto &VBase
: ClassDecl
->vbases()) {
5426 if (CXXCtorInitializer
*Value
5427 = Info
.AllBaseFields
.lookup(VBase
.getType()->getAs
<RecordType
>())) {
5428 // [class.base.init]p7, per DR257:
5429 // A mem-initializer where the mem-initializer-id names a virtual base
5430 // class is ignored during execution of a constructor of any class that
5431 // is not the most derived class.
5432 if (ClassDecl
->isAbstract()) {
5433 // FIXME: Provide a fixit to remove the base specifier. This requires
5434 // tracking the location of the associated comma for a base specifier.
5435 Diag(Value
->getSourceLocation(), diag::warn_abstract_vbase_init_ignored
)
5436 << VBase
.getType() << ClassDecl
;
5437 DiagnoseAbstractType(ClassDecl
);
5440 Info
.AllToInit
.push_back(Value
);
5441 } else if (!AnyErrors
&& !ClassDecl
->isAbstract()) {
5442 // [class.base.init]p8, per DR257:
5443 // If a given [...] base class is not named by a mem-initializer-id
5444 // [...] and the entity is not a virtual base class of an abstract
5445 // class, then [...] the entity is default-initialized.
5446 bool IsInheritedVirtualBase
= !DirectVBases
.count(&VBase
);
5447 CXXCtorInitializer
*CXXBaseInit
;
5448 if (BuildImplicitBaseInitializer(*this, Constructor
, Info
.IIK
,
5449 &VBase
, IsInheritedVirtualBase
,
5455 Info
.AllToInit
.push_back(CXXBaseInit
);
5459 // Non-virtual bases.
5460 for (auto &Base
: ClassDecl
->bases()) {
5461 // Virtuals are in the virtual base list and already constructed.
5462 if (Base
.isVirtual())
5465 if (CXXCtorInitializer
*Value
5466 = Info
.AllBaseFields
.lookup(Base
.getType()->getAs
<RecordType
>())) {
5467 Info
.AllToInit
.push_back(Value
);
5468 } else if (!AnyErrors
) {
5469 CXXCtorInitializer
*CXXBaseInit
;
5470 if (BuildImplicitBaseInitializer(*this, Constructor
, Info
.IIK
,
5471 &Base
, /*IsInheritedVirtualBase=*/false,
5477 Info
.AllToInit
.push_back(CXXBaseInit
);
5482 for (auto *Mem
: ClassDecl
->decls()) {
5483 if (auto *F
= dyn_cast
<FieldDecl
>(Mem
)) {
5484 // C++ [class.bit]p2:
5485 // A declaration for a bit-field that omits the identifier declares an
5486 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
5488 if (F
->isUnnamedBitfield())
5491 // If we're not generating the implicit copy/move constructor, then we'll
5492 // handle anonymous struct/union fields based on their individual
5494 if (F
->isAnonymousStructOrUnion() && !Info
.isImplicitCopyOrMove())
5497 if (CollectFieldInitializer(*this, Info
, F
))
5502 // Beyond this point, we only consider default initialization.
5503 if (Info
.isImplicitCopyOrMove())
5506 if (auto *F
= dyn_cast
<IndirectFieldDecl
>(Mem
)) {
5507 if (F
->getType()->isIncompleteArrayType()) {
5508 assert(ClassDecl
->hasFlexibleArrayMember() &&
5509 "Incomplete array type is not valid");
5513 // Initialize each field of an anonymous struct individually.
5514 if (CollectFieldInitializer(*this, Info
, F
->getAnonField(), F
))
5521 unsigned NumInitializers
= Info
.AllToInit
.size();
5522 if (NumInitializers
> 0) {
5523 Constructor
->setNumCtorInitializers(NumInitializers
);
5524 CXXCtorInitializer
**baseOrMemberInitializers
=
5525 new (Context
) CXXCtorInitializer
*[NumInitializers
];
5526 memcpy(baseOrMemberInitializers
, Info
.AllToInit
.data(),
5527 NumInitializers
* sizeof(CXXCtorInitializer
*));
5528 Constructor
->setCtorInitializers(baseOrMemberInitializers
);
5530 // Constructors implicitly reference the base and member
5532 MarkBaseAndMemberDestructorsReferenced(Constructor
->getLocation(),
5533 Constructor
->getParent());
5539 static void PopulateKeysForFields(FieldDecl
*Field
, SmallVectorImpl
<const void*> &IdealInits
) {
5540 if (const RecordType
*RT
= Field
->getType()->getAs
<RecordType
>()) {
5541 const RecordDecl
*RD
= RT
->getDecl();
5542 if (RD
->isAnonymousStructOrUnion()) {
5543 for (auto *Field
: RD
->fields())
5544 PopulateKeysForFields(Field
, IdealInits
);
5548 IdealInits
.push_back(Field
->getCanonicalDecl());
5551 static const void *GetKeyForBase(ASTContext
&Context
, QualType BaseType
) {
5552 return Context
.getCanonicalType(BaseType
).getTypePtr();
5555 static const void *GetKeyForMember(ASTContext
&Context
,
5556 CXXCtorInitializer
*Member
) {
5557 if (!Member
->isAnyMemberInitializer())
5558 return GetKeyForBase(Context
, QualType(Member
->getBaseClass(), 0));
5560 return Member
->getAnyMember()->getCanonicalDecl();
5563 static void AddInitializerToDiag(const Sema::SemaDiagnosticBuilder
&Diag
,
5564 const CXXCtorInitializer
*Previous
,
5565 const CXXCtorInitializer
*Current
) {
5566 if (Previous
->isAnyMemberInitializer())
5567 Diag
<< 0 << Previous
->getAnyMember();
5569 Diag
<< 1 << Previous
->getTypeSourceInfo()->getType();
5571 if (Current
->isAnyMemberInitializer())
5572 Diag
<< 0 << Current
->getAnyMember();
5574 Diag
<< 1 << Current
->getTypeSourceInfo()->getType();
5577 static void DiagnoseBaseOrMemInitializerOrder(
5578 Sema
&SemaRef
, const CXXConstructorDecl
*Constructor
,
5579 ArrayRef
<CXXCtorInitializer
*> Inits
) {
5580 if (Constructor
->getDeclContext()->isDependentContext())
5583 // Don't check initializers order unless the warning is enabled at the
5584 // location of at least one initializer.
5585 bool ShouldCheckOrder
= false;
5586 for (unsigned InitIndex
= 0; InitIndex
!= Inits
.size(); ++InitIndex
) {
5587 CXXCtorInitializer
*Init
= Inits
[InitIndex
];
5588 if (!SemaRef
.Diags
.isIgnored(diag::warn_initializer_out_of_order
,
5589 Init
->getSourceLocation())) {
5590 ShouldCheckOrder
= true;
5594 if (!ShouldCheckOrder
)
5597 // Build the list of bases and members in the order that they'll
5598 // actually be initialized. The explicit initializers should be in
5599 // this same order but may be missing things.
5600 SmallVector
<const void*, 32> IdealInitKeys
;
5602 const CXXRecordDecl
*ClassDecl
= Constructor
->getParent();
5604 // 1. Virtual bases.
5605 for (const auto &VBase
: ClassDecl
->vbases())
5606 IdealInitKeys
.push_back(GetKeyForBase(SemaRef
.Context
, VBase
.getType()));
5608 // 2. Non-virtual bases.
5609 for (const auto &Base
: ClassDecl
->bases()) {
5610 if (Base
.isVirtual())
5612 IdealInitKeys
.push_back(GetKeyForBase(SemaRef
.Context
, Base
.getType()));
5615 // 3. Direct fields.
5616 for (auto *Field
: ClassDecl
->fields()) {
5617 if (Field
->isUnnamedBitfield())
5620 PopulateKeysForFields(Field
, IdealInitKeys
);
5623 unsigned NumIdealInits
= IdealInitKeys
.size();
5624 unsigned IdealIndex
= 0;
5626 // Track initializers that are in an incorrect order for either a warning or
5627 // note if multiple ones occur.
5628 SmallVector
<unsigned> WarnIndexes
;
5629 // Correlates the index of an initializer in the init-list to the index of
5630 // the field/base in the class.
5631 SmallVector
<std::pair
<unsigned, unsigned>, 32> CorrelatedInitOrder
;
5633 for (unsigned InitIndex
= 0; InitIndex
!= Inits
.size(); ++InitIndex
) {
5634 const void *InitKey
= GetKeyForMember(SemaRef
.Context
, Inits
[InitIndex
]);
5636 // Scan forward to try to find this initializer in the idealized
5637 // initializers list.
5638 for (; IdealIndex
!= NumIdealInits
; ++IdealIndex
)
5639 if (InitKey
== IdealInitKeys
[IdealIndex
])
5642 // If we didn't find this initializer, it must be because we
5643 // scanned past it on a previous iteration. That can only
5644 // happen if we're out of order; emit a warning.
5645 if (IdealIndex
== NumIdealInits
&& InitIndex
) {
5646 WarnIndexes
.push_back(InitIndex
);
5648 // Move back to the initializer's location in the ideal list.
5649 for (IdealIndex
= 0; IdealIndex
!= NumIdealInits
; ++IdealIndex
)
5650 if (InitKey
== IdealInitKeys
[IdealIndex
])
5653 assert(IdealIndex
< NumIdealInits
&&
5654 "initializer not found in initializer list");
5656 CorrelatedInitOrder
.emplace_back(IdealIndex
, InitIndex
);
5659 if (WarnIndexes
.empty())
5662 // Sort based on the ideal order, first in the pair.
5663 llvm::sort(CorrelatedInitOrder
, llvm::less_first());
5665 // Introduce a new scope as SemaDiagnosticBuilder needs to be destroyed to
5666 // emit the diagnostic before we can try adding notes.
5668 Sema::SemaDiagnosticBuilder D
= SemaRef
.Diag(
5669 Inits
[WarnIndexes
.front() - 1]->getSourceLocation(),
5670 WarnIndexes
.size() == 1 ? diag::warn_initializer_out_of_order
5671 : diag::warn_some_initializers_out_of_order
);
5673 for (unsigned I
= 0; I
< CorrelatedInitOrder
.size(); ++I
) {
5674 if (CorrelatedInitOrder
[I
].second
== I
)
5676 // Ideally we would be using InsertFromRange here, but clang doesn't
5677 // appear to handle InsertFromRange correctly when the source range is
5678 // modified by another fix-it.
5679 D
<< FixItHint::CreateReplacement(
5680 Inits
[I
]->getSourceRange(),
5681 Lexer::getSourceText(
5682 CharSourceRange::getTokenRange(
5683 Inits
[CorrelatedInitOrder
[I
].second
]->getSourceRange()),
5684 SemaRef
.getSourceManager(), SemaRef
.getLangOpts()));
5687 // If there is only 1 item out of order, the warning expects the name and
5688 // type of each being added to it.
5689 if (WarnIndexes
.size() == 1) {
5690 AddInitializerToDiag(D
, Inits
[WarnIndexes
.front() - 1],
5691 Inits
[WarnIndexes
.front()]);
5695 // More than 1 item to warn, create notes letting the user know which ones
5697 for (unsigned WarnIndex
: WarnIndexes
) {
5698 const clang::CXXCtorInitializer
*PrevInit
= Inits
[WarnIndex
- 1];
5699 auto D
= SemaRef
.Diag(PrevInit
->getSourceLocation(),
5700 diag::note_initializer_out_of_order
);
5701 AddInitializerToDiag(D
, PrevInit
, Inits
[WarnIndex
]);
5702 D
<< PrevInit
->getSourceRange();
5707 bool CheckRedundantInit(Sema
&S
,
5708 CXXCtorInitializer
*Init
,
5709 CXXCtorInitializer
*&PrevInit
) {
5715 if (FieldDecl
*Field
= Init
->getAnyMember())
5716 S
.Diag(Init
->getSourceLocation(),
5717 diag::err_multiple_mem_initialization
)
5718 << Field
->getDeclName()
5719 << Init
->getSourceRange();
5721 const Type
*BaseClass
= Init
->getBaseClass();
5722 assert(BaseClass
&& "neither field nor base");
5723 S
.Diag(Init
->getSourceLocation(),
5724 diag::err_multiple_base_initialization
)
5725 << QualType(BaseClass
, 0)
5726 << Init
->getSourceRange();
5728 S
.Diag(PrevInit
->getSourceLocation(), diag::note_previous_initializer
)
5729 << 0 << PrevInit
->getSourceRange();
5734 typedef std::pair
<NamedDecl
*, CXXCtorInitializer
*> UnionEntry
;
5735 typedef llvm::DenseMap
<RecordDecl
*, UnionEntry
> RedundantUnionMap
;
5737 bool CheckRedundantUnionInit(Sema
&S
,
5738 CXXCtorInitializer
*Init
,
5739 RedundantUnionMap
&Unions
) {
5740 FieldDecl
*Field
= Init
->getAnyMember();
5741 RecordDecl
*Parent
= Field
->getParent();
5742 NamedDecl
*Child
= Field
;
5744 while (Parent
->isAnonymousStructOrUnion() || Parent
->isUnion()) {
5745 if (Parent
->isUnion()) {
5746 UnionEntry
&En
= Unions
[Parent
];
5747 if (En
.first
&& En
.first
!= Child
) {
5748 S
.Diag(Init
->getSourceLocation(),
5749 diag::err_multiple_mem_union_initialization
)
5750 << Field
->getDeclName()
5751 << Init
->getSourceRange();
5752 S
.Diag(En
.second
->getSourceLocation(), diag::note_previous_initializer
)
5753 << 0 << En
.second
->getSourceRange();
5760 if (!Parent
->isAnonymousStructOrUnion())
5765 Parent
= cast
<RecordDecl
>(Parent
->getDeclContext());
5772 /// ActOnMemInitializers - Handle the member initializers for a constructor.
5773 void Sema::ActOnMemInitializers(Decl
*ConstructorDecl
,
5774 SourceLocation ColonLoc
,
5775 ArrayRef
<CXXCtorInitializer
*> MemInits
,
5777 if (!ConstructorDecl
)
5780 AdjustDeclIfTemplate(ConstructorDecl
);
5782 CXXConstructorDecl
*Constructor
5783 = dyn_cast
<CXXConstructorDecl
>(ConstructorDecl
);
5786 Diag(ColonLoc
, diag::err_only_constructors_take_base_inits
);
5790 // Mapping for the duplicate initializers check.
5791 // For member initializers, this is keyed with a FieldDecl*.
5792 // For base initializers, this is keyed with a Type*.
5793 llvm::DenseMap
<const void *, CXXCtorInitializer
*> Members
;
5795 // Mapping for the inconsistent anonymous-union initializers check.
5796 RedundantUnionMap MemberUnions
;
5798 bool HadError
= false;
5799 for (unsigned i
= 0; i
< MemInits
.size(); i
++) {
5800 CXXCtorInitializer
*Init
= MemInits
[i
];
5802 // Set the source order index.
5803 Init
->setSourceOrder(i
);
5805 if (Init
->isAnyMemberInitializer()) {
5806 const void *Key
= GetKeyForMember(Context
, Init
);
5807 if (CheckRedundantInit(*this, Init
, Members
[Key
]) ||
5808 CheckRedundantUnionInit(*this, Init
, MemberUnions
))
5810 } else if (Init
->isBaseInitializer()) {
5811 const void *Key
= GetKeyForMember(Context
, Init
);
5812 if (CheckRedundantInit(*this, Init
, Members
[Key
]))
5815 assert(Init
->isDelegatingInitializer());
5816 // This must be the only initializer
5817 if (MemInits
.size() != 1) {
5818 Diag(Init
->getSourceLocation(),
5819 diag::err_delegating_initializer_alone
)
5820 << Init
->getSourceRange() << MemInits
[i
? 0 : 1]->getSourceRange();
5821 // We will treat this as being the only initializer.
5823 SetDelegatingInitializer(Constructor
, MemInits
[i
]);
5824 // Return immediately as the initializer is set.
5832 DiagnoseBaseOrMemInitializerOrder(*this, Constructor
, MemInits
);
5834 SetCtorInitializers(Constructor
, AnyErrors
, MemInits
);
5836 DiagnoseUninitializedFields(*this, Constructor
);
5840 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location
,
5841 CXXRecordDecl
*ClassDecl
) {
5842 // Ignore dependent contexts. Also ignore unions, since their members never
5843 // have destructors implicitly called.
5844 if (ClassDecl
->isDependentContext() || ClassDecl
->isUnion())
5847 // FIXME: all the access-control diagnostics are positioned on the
5848 // field/base declaration. That's probably good; that said, the
5849 // user might reasonably want to know why the destructor is being
5850 // emitted, and we currently don't say.
5852 // Non-static data members.
5853 for (auto *Field
: ClassDecl
->fields()) {
5854 if (Field
->isInvalidDecl())
5857 // Don't destroy incomplete or zero-length arrays.
5858 if (isIncompleteOrZeroLengthArrayType(Context
, Field
->getType()))
5861 QualType FieldType
= Context
.getBaseElementType(Field
->getType());
5863 const RecordType
* RT
= FieldType
->getAs
<RecordType
>();
5867 CXXRecordDecl
*FieldClassDecl
= cast
<CXXRecordDecl
>(RT
->getDecl());
5868 if (FieldClassDecl
->isInvalidDecl())
5870 if (FieldClassDecl
->hasIrrelevantDestructor())
5872 // The destructor for an implicit anonymous union member is never invoked.
5873 if (FieldClassDecl
->isUnion() && FieldClassDecl
->isAnonymousStructOrUnion())
5876 CXXDestructorDecl
*Dtor
= LookupDestructor(FieldClassDecl
);
5877 // Dtor might still be missing, e.g because it's invalid.
5880 CheckDestructorAccess(Field
->getLocation(), Dtor
,
5881 PDiag(diag::err_access_dtor_field
)
5882 << Field
->getDeclName()
5885 MarkFunctionReferenced(Location
, Dtor
);
5886 DiagnoseUseOfDecl(Dtor
, Location
);
5889 // We only potentially invoke the destructors of potentially constructed
5891 bool VisitVirtualBases
= !ClassDecl
->isAbstract();
5893 // If the destructor exists and has already been marked used in the MS ABI,
5894 // then virtual base destructors have already been checked and marked used.
5895 // Skip checking them again to avoid duplicate diagnostics.
5896 if (Context
.getTargetInfo().getCXXABI().isMicrosoft()) {
5897 CXXDestructorDecl
*Dtor
= ClassDecl
->getDestructor();
5898 if (Dtor
&& Dtor
->isUsed())
5899 VisitVirtualBases
= false;
5902 llvm::SmallPtrSet
<const RecordType
*, 8> DirectVirtualBases
;
5905 for (const auto &Base
: ClassDecl
->bases()) {
5906 const RecordType
*RT
= Base
.getType()->getAs
<RecordType
>();
5910 // Remember direct virtual bases.
5911 if (Base
.isVirtual()) {
5912 if (!VisitVirtualBases
)
5914 DirectVirtualBases
.insert(RT
);
5917 CXXRecordDecl
*BaseClassDecl
= cast
<CXXRecordDecl
>(RT
->getDecl());
5918 // If our base class is invalid, we probably can't get its dtor anyway.
5919 if (BaseClassDecl
->isInvalidDecl())
5921 if (BaseClassDecl
->hasIrrelevantDestructor())
5924 CXXDestructorDecl
*Dtor
= LookupDestructor(BaseClassDecl
);
5925 // Dtor might still be missing, e.g because it's invalid.
5929 // FIXME: caret should be on the start of the class name
5930 CheckDestructorAccess(Base
.getBeginLoc(), Dtor
,
5931 PDiag(diag::err_access_dtor_base
)
5932 << Base
.getType() << Base
.getSourceRange(),
5933 Context
.getTypeDeclType(ClassDecl
));
5935 MarkFunctionReferenced(Location
, Dtor
);
5936 DiagnoseUseOfDecl(Dtor
, Location
);
5939 if (VisitVirtualBases
)
5940 MarkVirtualBaseDestructorsReferenced(Location
, ClassDecl
,
5941 &DirectVirtualBases
);
5944 void Sema::MarkVirtualBaseDestructorsReferenced(
5945 SourceLocation Location
, CXXRecordDecl
*ClassDecl
,
5946 llvm::SmallPtrSetImpl
<const RecordType
*> *DirectVirtualBases
) {
5948 for (const auto &VBase
: ClassDecl
->vbases()) {
5949 // Bases are always records in a well-formed non-dependent class.
5950 const RecordType
*RT
= VBase
.getType()->castAs
<RecordType
>();
5952 // Ignore already visited direct virtual bases.
5953 if (DirectVirtualBases
&& DirectVirtualBases
->count(RT
))
5956 CXXRecordDecl
*BaseClassDecl
= cast
<CXXRecordDecl
>(RT
->getDecl());
5957 // If our base class is invalid, we probably can't get its dtor anyway.
5958 if (BaseClassDecl
->isInvalidDecl())
5960 if (BaseClassDecl
->hasIrrelevantDestructor())
5963 CXXDestructorDecl
*Dtor
= LookupDestructor(BaseClassDecl
);
5964 // Dtor might still be missing, e.g because it's invalid.
5967 if (CheckDestructorAccess(
5968 ClassDecl
->getLocation(), Dtor
,
5969 PDiag(diag::err_access_dtor_vbase
)
5970 << Context
.getTypeDeclType(ClassDecl
) << VBase
.getType(),
5971 Context
.getTypeDeclType(ClassDecl
)) ==
5973 CheckDerivedToBaseConversion(
5974 Context
.getTypeDeclType(ClassDecl
), VBase
.getType(),
5975 diag::err_access_dtor_vbase
, 0, ClassDecl
->getLocation(),
5976 SourceRange(), DeclarationName(), nullptr);
5979 MarkFunctionReferenced(Location
, Dtor
);
5980 DiagnoseUseOfDecl(Dtor
, Location
);
5984 void Sema::ActOnDefaultCtorInitializers(Decl
*CDtorDecl
) {
5988 if (CXXConstructorDecl
*Constructor
5989 = dyn_cast
<CXXConstructorDecl
>(CDtorDecl
)) {
5990 SetCtorInitializers(Constructor
, /*AnyErrors=*/false);
5991 DiagnoseUninitializedFields(*this, Constructor
);
5995 bool Sema::isAbstractType(SourceLocation Loc
, QualType T
) {
5996 if (!getLangOpts().CPlusPlus
)
5999 const auto *RD
= Context
.getBaseElementType(T
)->getAsCXXRecordDecl();
6003 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
6004 // class template specialization here, but doing so breaks a lot of code.
6006 // We can't answer whether something is abstract until it has a
6007 // definition. If it's currently being defined, we'll walk back
6008 // over all the declarations when we have a full definition.
6009 const CXXRecordDecl
*Def
= RD
->getDefinition();
6010 if (!Def
|| Def
->isBeingDefined())
6013 return RD
->isAbstract();
6016 bool Sema::RequireNonAbstractType(SourceLocation Loc
, QualType T
,
6017 TypeDiagnoser
&Diagnoser
) {
6018 if (!isAbstractType(Loc
, T
))
6021 T
= Context
.getBaseElementType(T
);
6022 Diagnoser
.diagnose(*this, Loc
, T
);
6023 DiagnoseAbstractType(T
->getAsCXXRecordDecl());
6027 void Sema::DiagnoseAbstractType(const CXXRecordDecl
*RD
) {
6028 // Check if we've already emitted the list of pure virtual functions
6030 if (PureVirtualClassDiagSet
&& PureVirtualClassDiagSet
->count(RD
))
6033 // If the diagnostic is suppressed, don't emit the notes. We're only
6034 // going to emit them once, so try to attach them to a diagnostic we're
6035 // actually going to show.
6036 if (Diags
.isLastDiagnosticIgnored())
6039 CXXFinalOverriderMap FinalOverriders
;
6040 RD
->getFinalOverriders(FinalOverriders
);
6042 // Keep a set of seen pure methods so we won't diagnose the same method
6044 llvm::SmallPtrSet
<const CXXMethodDecl
*, 8> SeenPureMethods
;
6046 for (CXXFinalOverriderMap::iterator M
= FinalOverriders
.begin(),
6047 MEnd
= FinalOverriders
.end();
6050 for (OverridingMethods::iterator SO
= M
->second
.begin(),
6051 SOEnd
= M
->second
.end();
6052 SO
!= SOEnd
; ++SO
) {
6053 // C++ [class.abstract]p4:
6054 // A class is abstract if it contains or inherits at least one
6055 // pure virtual function for which the final overrider is pure
6059 if (SO
->second
.size() != 1)
6062 if (!SO
->second
.front().Method
->isPure())
6065 if (!SeenPureMethods
.insert(SO
->second
.front().Method
).second
)
6068 Diag(SO
->second
.front().Method
->getLocation(),
6069 diag::note_pure_virtual_function
)
6070 << SO
->second
.front().Method
->getDeclName() << RD
->getDeclName();
6074 if (!PureVirtualClassDiagSet
)
6075 PureVirtualClassDiagSet
.reset(new RecordDeclSetTy
);
6076 PureVirtualClassDiagSet
->insert(RD
);
6080 struct AbstractUsageInfo
{
6082 CXXRecordDecl
*Record
;
6083 CanQualType AbstractType
;
6086 AbstractUsageInfo(Sema
&S
, CXXRecordDecl
*Record
)
6087 : S(S
), Record(Record
),
6088 AbstractType(S
.Context
.getCanonicalType(
6089 S
.Context
.getTypeDeclType(Record
))),
6092 void DiagnoseAbstractType() {
6093 if (Invalid
) return;
6094 S
.DiagnoseAbstractType(Record
);
6098 void CheckType(const NamedDecl
*D
, TypeLoc TL
, Sema::AbstractDiagSelID Sel
);
6101 struct CheckAbstractUsage
{
6102 AbstractUsageInfo
&Info
;
6103 const NamedDecl
*Ctx
;
6105 CheckAbstractUsage(AbstractUsageInfo
&Info
, const NamedDecl
*Ctx
)
6106 : Info(Info
), Ctx(Ctx
) {}
6108 void Visit(TypeLoc TL
, Sema::AbstractDiagSelID Sel
) {
6109 switch (TL
.getTypeLocClass()) {
6110 #define ABSTRACT_TYPELOC(CLASS, PARENT)
6111 #define TYPELOC(CLASS, PARENT) \
6112 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
6113 #include "clang/AST/TypeLocNodes.def"
6117 void Check(FunctionProtoTypeLoc TL
, Sema::AbstractDiagSelID Sel
) {
6118 Visit(TL
.getReturnLoc(), Sema::AbstractReturnType
);
6119 for (unsigned I
= 0, E
= TL
.getNumParams(); I
!= E
; ++I
) {
6120 if (!TL
.getParam(I
))
6123 TypeSourceInfo
*TSI
= TL
.getParam(I
)->getTypeSourceInfo();
6124 if (TSI
) Visit(TSI
->getTypeLoc(), Sema::AbstractParamType
);
6128 void Check(ArrayTypeLoc TL
, Sema::AbstractDiagSelID Sel
) {
6129 Visit(TL
.getElementLoc(), Sema::AbstractArrayType
);
6132 void Check(TemplateSpecializationTypeLoc TL
, Sema::AbstractDiagSelID Sel
) {
6133 // Visit the type parameters from a permissive context.
6134 for (unsigned I
= 0, E
= TL
.getNumArgs(); I
!= E
; ++I
) {
6135 TemplateArgumentLoc TAL
= TL
.getArgLoc(I
);
6136 if (TAL
.getArgument().getKind() == TemplateArgument::Type
)
6137 if (TypeSourceInfo
*TSI
= TAL
.getTypeSourceInfo())
6138 Visit(TSI
->getTypeLoc(), Sema::AbstractNone
);
6139 // TODO: other template argument types?
6143 // Visit pointee types from a permissive context.
6144 #define CheckPolymorphic(Type) \
6145 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
6146 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
6148 CheckPolymorphic(PointerTypeLoc
)
6149 CheckPolymorphic(ReferenceTypeLoc
)
6150 CheckPolymorphic(MemberPointerTypeLoc
)
6151 CheckPolymorphic(BlockPointerTypeLoc
)
6152 CheckPolymorphic(AtomicTypeLoc
)
6154 /// Handle all the types we haven't given a more specific
6155 /// implementation for above.
6156 void Check(TypeLoc TL
, Sema::AbstractDiagSelID Sel
) {
6157 // Every other kind of type that we haven't called out already
6158 // that has an inner type is either (1) sugar or (2) contains that
6159 // inner type in some way as a subobject.
6160 if (TypeLoc Next
= TL
.getNextTypeLoc())
6161 return Visit(Next
, Sel
);
6163 // If there's no inner type and we're in a permissive context,
6165 if (Sel
== Sema::AbstractNone
) return;
6167 // Check whether the type matches the abstract type.
6168 QualType T
= TL
.getType();
6169 if (T
->isArrayType()) {
6170 Sel
= Sema::AbstractArrayType
;
6171 T
= Info
.S
.Context
.getBaseElementType(T
);
6173 CanQualType CT
= T
->getCanonicalTypeUnqualified().getUnqualifiedType();
6174 if (CT
!= Info
.AbstractType
) return;
6176 // It matched; do some magic.
6177 // FIXME: These should be at most warnings. See P0929R2, CWG1640, CWG1646.
6178 if (Sel
== Sema::AbstractArrayType
) {
6179 Info
.S
.Diag(Ctx
->getLocation(), diag::err_array_of_abstract_type
)
6180 << T
<< TL
.getSourceRange();
6182 Info
.S
.Diag(Ctx
->getLocation(), diag::err_abstract_type_in_decl
)
6183 << Sel
<< T
<< TL
.getSourceRange();
6185 Info
.DiagnoseAbstractType();
6189 void AbstractUsageInfo::CheckType(const NamedDecl
*D
, TypeLoc TL
,
6190 Sema::AbstractDiagSelID Sel
) {
6191 CheckAbstractUsage(*this, D
).Visit(TL
, Sel
);
6196 /// Check for invalid uses of an abstract type in a function declaration.
6197 static void CheckAbstractClassUsage(AbstractUsageInfo
&Info
,
6199 // Only definitions are required to refer to complete and
6200 // non-abstract types.
6201 if (!FD
->doesThisDeclarationHaveABody())
6204 // For safety's sake, just ignore it if we don't have type source
6205 // information. This should never happen for non-implicit methods,
6207 if (TypeSourceInfo
*TSI
= FD
->getTypeSourceInfo())
6208 Info
.CheckType(FD
, TSI
->getTypeLoc(), Sema::AbstractNone
);
6211 /// Check for invalid uses of an abstract type in a variable0 declaration.
6212 static void CheckAbstractClassUsage(AbstractUsageInfo
&Info
,
6214 // No need to do the check on definitions, which require that
6215 // the type is complete.
6216 if (VD
->isThisDeclarationADefinition())
6219 Info
.CheckType(VD
, VD
->getTypeSourceInfo()->getTypeLoc(),
6220 Sema::AbstractVariableType
);
6223 /// Check for invalid uses of an abstract type within a class definition.
6224 static void CheckAbstractClassUsage(AbstractUsageInfo
&Info
,
6225 CXXRecordDecl
*RD
) {
6226 for (auto *D
: RD
->decls()) {
6227 if (D
->isImplicit()) continue;
6229 // Step through friends to the befriended declaration.
6230 if (auto *FD
= dyn_cast
<FriendDecl
>(D
)) {
6231 D
= FD
->getFriendDecl();
6235 // Functions and function templates.
6236 if (auto *FD
= dyn_cast
<FunctionDecl
>(D
)) {
6237 CheckAbstractClassUsage(Info
, FD
);
6238 } else if (auto *FTD
= dyn_cast
<FunctionTemplateDecl
>(D
)) {
6239 CheckAbstractClassUsage(Info
, FTD
->getTemplatedDecl());
6241 // Fields and static variables.
6242 } else if (auto *FD
= dyn_cast
<FieldDecl
>(D
)) {
6243 if (TypeSourceInfo
*TSI
= FD
->getTypeSourceInfo())
6244 Info
.CheckType(FD
, TSI
->getTypeLoc(), Sema::AbstractFieldType
);
6245 } else if (auto *VD
= dyn_cast
<VarDecl
>(D
)) {
6246 CheckAbstractClassUsage(Info
, VD
);
6247 } else if (auto *VTD
= dyn_cast
<VarTemplateDecl
>(D
)) {
6248 CheckAbstractClassUsage(Info
, VTD
->getTemplatedDecl());
6250 // Nested classes and class templates.
6251 } else if (auto *RD
= dyn_cast
<CXXRecordDecl
>(D
)) {
6252 CheckAbstractClassUsage(Info
, RD
);
6253 } else if (auto *CTD
= dyn_cast
<ClassTemplateDecl
>(D
)) {
6254 CheckAbstractClassUsage(Info
, CTD
->getTemplatedDecl());
6259 static void ReferenceDllExportedMembers(Sema
&S
, CXXRecordDecl
*Class
) {
6260 Attr
*ClassAttr
= getDLLAttr(Class
);
6264 assert(ClassAttr
->getKind() == attr::DLLExport
);
6266 TemplateSpecializationKind TSK
= Class
->getTemplateSpecializationKind();
6268 if (TSK
== TSK_ExplicitInstantiationDeclaration
)
6269 // Don't go any further if this is just an explicit instantiation
6273 // Add a context note to explain how we got to any diagnostics produced below.
6274 struct MarkingClassDllexported
{
6276 MarkingClassDllexported(Sema
&S
, CXXRecordDecl
*Class
,
6277 SourceLocation AttrLoc
)
6279 Sema::CodeSynthesisContext Ctx
;
6280 Ctx
.Kind
= Sema::CodeSynthesisContext::MarkingClassDllexported
;
6281 Ctx
.PointOfInstantiation
= AttrLoc
;
6283 S
.pushCodeSynthesisContext(Ctx
);
6285 ~MarkingClassDllexported() {
6286 S
.popCodeSynthesisContext();
6288 } MarkingDllexportedContext(S
, Class
, ClassAttr
->getLocation());
6290 if (S
.Context
.getTargetInfo().getTriple().isWindowsGNUEnvironment())
6291 S
.MarkVTableUsed(Class
->getLocation(), Class
, true);
6293 for (Decl
*Member
: Class
->decls()) {
6294 // Skip members that were not marked exported.
6295 if (!Member
->hasAttr
<DLLExportAttr
>())
6298 // Defined static variables that are members of an exported base
6299 // class must be marked export too.
6300 auto *VD
= dyn_cast
<VarDecl
>(Member
);
6301 if (VD
&& VD
->getStorageClass() == SC_Static
&&
6302 TSK
== TSK_ImplicitInstantiation
)
6303 S
.MarkVariableReferenced(VD
->getLocation(), VD
);
6305 auto *MD
= dyn_cast
<CXXMethodDecl
>(Member
);
6309 if (MD
->isUserProvided()) {
6310 // Instantiate non-default class member functions ...
6312 // .. except for certain kinds of template specializations.
6313 if (TSK
== TSK_ImplicitInstantiation
&& !ClassAttr
->isInherited())
6316 // If this is an MS ABI dllexport default constructor, instantiate any
6317 // default arguments.
6318 if (S
.Context
.getTargetInfo().getCXXABI().isMicrosoft()) {
6319 auto *CD
= dyn_cast
<CXXConstructorDecl
>(MD
);
6320 if (CD
&& CD
->isDefaultConstructor() && TSK
== TSK_Undeclared
) {
6321 S
.InstantiateDefaultCtorDefaultArgs(CD
);
6325 S
.MarkFunctionReferenced(Class
->getLocation(), MD
);
6327 // The function will be passed to the consumer when its definition is
6329 } else if (MD
->isExplicitlyDefaulted()) {
6330 // Synthesize and instantiate explicitly defaulted methods.
6331 S
.MarkFunctionReferenced(Class
->getLocation(), MD
);
6333 if (TSK
!= TSK_ExplicitInstantiationDefinition
) {
6334 // Except for explicit instantiation defs, we will not see the
6335 // definition again later, so pass it to the consumer now.
6336 S
.Consumer
.HandleTopLevelDecl(DeclGroupRef(MD
));
6338 } else if (!MD
->isTrivial() ||
6339 MD
->isCopyAssignmentOperator() ||
6340 MD
->isMoveAssignmentOperator()) {
6341 // Synthesize and instantiate non-trivial implicit methods, and the copy
6342 // and move assignment operators. The latter are exported even if they
6343 // are trivial, because the address of an operator can be taken and
6344 // should compare equal across libraries.
6345 S
.MarkFunctionReferenced(Class
->getLocation(), MD
);
6347 // There is no later point when we will see the definition of this
6348 // function, so pass it to the consumer now.
6349 S
.Consumer
.HandleTopLevelDecl(DeclGroupRef(MD
));
6354 static void checkForMultipleExportedDefaultConstructors(Sema
&S
,
6355 CXXRecordDecl
*Class
) {
6356 // Only the MS ABI has default constructor closures, so we don't need to do
6357 // this semantic checking anywhere else.
6358 if (!S
.Context
.getTargetInfo().getCXXABI().isMicrosoft())
6361 CXXConstructorDecl
*LastExportedDefaultCtor
= nullptr;
6362 for (Decl
*Member
: Class
->decls()) {
6363 // Look for exported default constructors.
6364 auto *CD
= dyn_cast
<CXXConstructorDecl
>(Member
);
6365 if (!CD
|| !CD
->isDefaultConstructor())
6367 auto *Attr
= CD
->getAttr
<DLLExportAttr
>();
6371 // If the class is non-dependent, mark the default arguments as ODR-used so
6372 // that we can properly codegen the constructor closure.
6373 if (!Class
->isDependentContext()) {
6374 for (ParmVarDecl
*PD
: CD
->parameters()) {
6375 (void)S
.CheckCXXDefaultArgExpr(Attr
->getLocation(), CD
, PD
);
6376 S
.DiscardCleanupsInEvaluationContext();
6380 if (LastExportedDefaultCtor
) {
6381 S
.Diag(LastExportedDefaultCtor
->getLocation(),
6382 diag::err_attribute_dll_ambiguous_default_ctor
)
6384 S
.Diag(CD
->getLocation(), diag::note_entity_declared_at
)
6385 << CD
->getDeclName();
6388 LastExportedDefaultCtor
= CD
;
6392 static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema
&S
,
6393 CXXRecordDecl
*Class
) {
6394 bool ErrorReported
= false;
6395 auto reportIllegalClassTemplate
= [&ErrorReported
](Sema
&S
,
6396 ClassTemplateDecl
*TD
) {
6399 S
.Diag(TD
->getLocation(),
6400 diag::err_cuda_device_builtin_surftex_cls_template
)
6401 << /*surface*/ 0 << TD
;
6402 ErrorReported
= true;
6405 ClassTemplateDecl
*TD
= Class
->getDescribedClassTemplate();
6407 auto *SD
= dyn_cast
<ClassTemplateSpecializationDecl
>(Class
);
6409 S
.Diag(Class
->getLocation(),
6410 diag::err_cuda_device_builtin_surftex_ref_decl
)
6411 << /*surface*/ 0 << Class
;
6412 S
.Diag(Class
->getLocation(),
6413 diag::note_cuda_device_builtin_surftex_should_be_template_class
)
6417 TD
= SD
->getSpecializedTemplate();
6420 TemplateParameterList
*Params
= TD
->getTemplateParameters();
6421 unsigned N
= Params
->size();
6424 reportIllegalClassTemplate(S
, TD
);
6425 S
.Diag(TD
->getLocation(),
6426 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args
)
6429 if (N
> 0 && !isa
<TemplateTypeParmDecl
>(Params
->getParam(0))) {
6430 reportIllegalClassTemplate(S
, TD
);
6431 S
.Diag(TD
->getLocation(),
6432 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg
)
6433 << TD
<< /*1st*/ 0 << /*type*/ 0;
6436 auto *NTTP
= dyn_cast
<NonTypeTemplateParmDecl
>(Params
->getParam(1));
6437 if (!NTTP
|| !NTTP
->getType()->isIntegralOrEnumerationType()) {
6438 reportIllegalClassTemplate(S
, TD
);
6439 S
.Diag(TD
->getLocation(),
6440 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg
)
6441 << TD
<< /*2nd*/ 1 << /*integer*/ 1;
6446 static void checkCUDADeviceBuiltinTextureClassTemplate(Sema
&S
,
6447 CXXRecordDecl
*Class
) {
6448 bool ErrorReported
= false;
6449 auto reportIllegalClassTemplate
= [&ErrorReported
](Sema
&S
,
6450 ClassTemplateDecl
*TD
) {
6453 S
.Diag(TD
->getLocation(),
6454 diag::err_cuda_device_builtin_surftex_cls_template
)
6455 << /*texture*/ 1 << TD
;
6456 ErrorReported
= true;
6459 ClassTemplateDecl
*TD
= Class
->getDescribedClassTemplate();
6461 auto *SD
= dyn_cast
<ClassTemplateSpecializationDecl
>(Class
);
6463 S
.Diag(Class
->getLocation(),
6464 diag::err_cuda_device_builtin_surftex_ref_decl
)
6465 << /*texture*/ 1 << Class
;
6466 S
.Diag(Class
->getLocation(),
6467 diag::note_cuda_device_builtin_surftex_should_be_template_class
)
6471 TD
= SD
->getSpecializedTemplate();
6474 TemplateParameterList
*Params
= TD
->getTemplateParameters();
6475 unsigned N
= Params
->size();
6478 reportIllegalClassTemplate(S
, TD
);
6479 S
.Diag(TD
->getLocation(),
6480 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args
)
6483 if (N
> 0 && !isa
<TemplateTypeParmDecl
>(Params
->getParam(0))) {
6484 reportIllegalClassTemplate(S
, TD
);
6485 S
.Diag(TD
->getLocation(),
6486 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg
)
6487 << TD
<< /*1st*/ 0 << /*type*/ 0;
6490 auto *NTTP
= dyn_cast
<NonTypeTemplateParmDecl
>(Params
->getParam(1));
6491 if (!NTTP
|| !NTTP
->getType()->isIntegralOrEnumerationType()) {
6492 reportIllegalClassTemplate(S
, TD
);
6493 S
.Diag(TD
->getLocation(),
6494 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg
)
6495 << TD
<< /*2nd*/ 1 << /*integer*/ 1;
6499 auto *NTTP
= dyn_cast
<NonTypeTemplateParmDecl
>(Params
->getParam(2));
6500 if (!NTTP
|| !NTTP
->getType()->isIntegralOrEnumerationType()) {
6501 reportIllegalClassTemplate(S
, TD
);
6502 S
.Diag(TD
->getLocation(),
6503 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg
)
6504 << TD
<< /*3rd*/ 2 << /*integer*/ 1;
6509 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl
*Class
) {
6510 // Mark any compiler-generated routines with the implicit code_seg attribute.
6511 for (auto *Method
: Class
->methods()) {
6512 if (Method
->isUserProvided())
6514 if (Attr
*A
= getImplicitCodeSegOrSectionAttrForFunction(Method
, /*IsDefinition=*/true))
6519 /// Check class-level dllimport/dllexport attribute.
6520 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl
*Class
) {
6521 Attr
*ClassAttr
= getDLLAttr(Class
);
6523 // MSVC inherits DLL attributes to partial class template specializations.
6524 if (Context
.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr
) {
6525 if (auto *Spec
= dyn_cast
<ClassTemplatePartialSpecializationDecl
>(Class
)) {
6526 if (Attr
*TemplateAttr
=
6527 getDLLAttr(Spec
->getSpecializedTemplate()->getTemplatedDecl())) {
6528 auto *A
= cast
<InheritableAttr
>(TemplateAttr
->clone(getASTContext()));
6529 A
->setInherited(true);
6538 // MSVC allows imported or exported template classes that have UniqueExternal
6539 // linkage. This occurs when the template class has been instantiated with
6540 // a template parameter which itself has internal linkage.
6541 // We drop the attribute to avoid exporting or importing any members.
6542 if ((Context
.getTargetInfo().getCXXABI().isMicrosoft() ||
6543 Context
.getTargetInfo().getTriple().isPS()) &&
6544 (!Class
->isExternallyVisible() && Class
->hasExternalFormalLinkage())) {
6545 Class
->dropAttr
<DLLExportAttr
>();
6546 Class
->dropAttr
<DLLImportAttr
>();
6550 if (!Class
->isExternallyVisible()) {
6551 Diag(Class
->getLocation(), diag::err_attribute_dll_not_extern
)
6552 << Class
<< ClassAttr
;
6556 if (Context
.getTargetInfo().shouldDLLImportComdatSymbols() &&
6557 !ClassAttr
->isInherited()) {
6558 // Diagnose dll attributes on members of class with dll attribute.
6559 for (Decl
*Member
: Class
->decls()) {
6560 if (!isa
<VarDecl
>(Member
) && !isa
<CXXMethodDecl
>(Member
))
6562 InheritableAttr
*MemberAttr
= getDLLAttr(Member
);
6563 if (!MemberAttr
|| MemberAttr
->isInherited() || Member
->isInvalidDecl())
6566 Diag(MemberAttr
->getLocation(),
6567 diag::err_attribute_dll_member_of_dll_class
)
6568 << MemberAttr
<< ClassAttr
;
6569 Diag(ClassAttr
->getLocation(), diag::note_previous_attribute
);
6570 Member
->setInvalidDecl();
6574 if (Class
->getDescribedClassTemplate())
6575 // Don't inherit dll attribute until the template is instantiated.
6578 // The class is either imported or exported.
6579 const bool ClassExported
= ClassAttr
->getKind() == attr::DLLExport
;
6581 // Check if this was a dllimport attribute propagated from a derived class to
6582 // a base class template specialization. We don't apply these attributes to
6583 // static data members.
6584 const bool PropagatedImport
=
6586 cast
<DLLImportAttr
>(ClassAttr
)->wasPropagatedToBaseTemplate();
6588 TemplateSpecializationKind TSK
= Class
->getTemplateSpecializationKind();
6590 // Ignore explicit dllexport on explicit class template instantiation
6591 // declarations, except in MinGW mode.
6592 if (ClassExported
&& !ClassAttr
->isInherited() &&
6593 TSK
== TSK_ExplicitInstantiationDeclaration
&&
6594 !Context
.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
6595 Class
->dropAttr
<DLLExportAttr
>();
6599 // Force declaration of implicit members so they can inherit the attribute.
6600 ForceDeclarationOfImplicitMembers(Class
);
6602 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
6603 // seem to be true in practice?
6605 for (Decl
*Member
: Class
->decls()) {
6606 VarDecl
*VD
= dyn_cast
<VarDecl
>(Member
);
6607 CXXMethodDecl
*MD
= dyn_cast
<CXXMethodDecl
>(Member
);
6609 // Only methods and static fields inherit the attributes.
6614 // Don't process deleted methods.
6615 if (MD
->isDeleted())
6618 if (MD
->isInlined()) {
6619 // MinGW does not import or export inline methods. But do it for
6620 // template instantiations.
6621 if (!Context
.getTargetInfo().shouldDLLImportComdatSymbols() &&
6622 TSK
!= TSK_ExplicitInstantiationDeclaration
&&
6623 TSK
!= TSK_ExplicitInstantiationDefinition
)
6626 // MSVC versions before 2015 don't export the move assignment operators
6627 // and move constructor, so don't attempt to import/export them if
6628 // we have a definition.
6629 auto *Ctor
= dyn_cast
<CXXConstructorDecl
>(MD
);
6630 if ((MD
->isMoveAssignmentOperator() ||
6631 (Ctor
&& Ctor
->isMoveConstructor())) &&
6632 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015
))
6635 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
6636 // operator is exported anyway.
6637 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015
) &&
6638 (Ctor
|| isa
<CXXDestructorDecl
>(MD
)) && MD
->isTrivial())
6643 // Don't apply dllimport attributes to static data members of class template
6644 // instantiations when the attribute is propagated from a derived class.
6645 if (VD
&& PropagatedImport
)
6648 if (!cast
<NamedDecl
>(Member
)->isExternallyVisible())
6651 if (!getDLLAttr(Member
)) {
6652 InheritableAttr
*NewAttr
= nullptr;
6654 // Do not export/import inline function when -fno-dllexport-inlines is
6655 // passed. But add attribute for later local static var check.
6656 if (!getLangOpts().DllExportInlines
&& MD
&& MD
->isInlined() &&
6657 TSK
!= TSK_ExplicitInstantiationDeclaration
&&
6658 TSK
!= TSK_ExplicitInstantiationDefinition
) {
6659 if (ClassExported
) {
6660 NewAttr
= ::new (getASTContext())
6661 DLLExportStaticLocalAttr(getASTContext(), *ClassAttr
);
6663 NewAttr
= ::new (getASTContext())
6664 DLLImportStaticLocalAttr(getASTContext(), *ClassAttr
);
6667 NewAttr
= cast
<InheritableAttr
>(ClassAttr
->clone(getASTContext()));
6670 NewAttr
->setInherited(true);
6671 Member
->addAttr(NewAttr
);
6674 // Propagate DLLAttr to friend re-declarations of MD that have already
6675 // been constructed.
6676 for (FunctionDecl
*FD
= MD
->getMostRecentDecl(); FD
;
6677 FD
= FD
->getPreviousDecl()) {
6678 if (FD
->getFriendObjectKind() == Decl::FOK_None
)
6680 assert(!getDLLAttr(FD
) &&
6681 "friend re-decl should not already have a DLLAttr");
6682 NewAttr
= cast
<InheritableAttr
>(ClassAttr
->clone(getASTContext()));
6683 NewAttr
->setInherited(true);
6684 FD
->addAttr(NewAttr
);
6691 DelayedDllExportClasses
.push_back(Class
);
6694 /// Perform propagation of DLL attributes from a derived class to a
6695 /// templated base class for MS compatibility.
6696 void Sema::propagateDLLAttrToBaseClassTemplate(
6697 CXXRecordDecl
*Class
, Attr
*ClassAttr
,
6698 ClassTemplateSpecializationDecl
*BaseTemplateSpec
, SourceLocation BaseLoc
) {
6700 BaseTemplateSpec
->getSpecializedTemplate()->getTemplatedDecl())) {
6701 // If the base class template has a DLL attribute, don't try to change it.
6705 auto TSK
= BaseTemplateSpec
->getSpecializationKind();
6706 if (!getDLLAttr(BaseTemplateSpec
) &&
6707 (TSK
== TSK_Undeclared
|| TSK
== TSK_ExplicitInstantiationDeclaration
||
6708 TSK
== TSK_ImplicitInstantiation
)) {
6709 // The template hasn't been instantiated yet (or it has, but only as an
6710 // explicit instantiation declaration or implicit instantiation, which means
6711 // we haven't codegenned any members yet), so propagate the attribute.
6712 auto *NewAttr
= cast
<InheritableAttr
>(ClassAttr
->clone(getASTContext()));
6713 NewAttr
->setInherited(true);
6714 BaseTemplateSpec
->addAttr(NewAttr
);
6716 // If this was an import, mark that we propagated it from a derived class to
6717 // a base class template specialization.
6718 if (auto *ImportAttr
= dyn_cast
<DLLImportAttr
>(NewAttr
))
6719 ImportAttr
->setPropagatedToBaseTemplate();
6721 // If the template is already instantiated, checkDLLAttributeRedeclaration()
6722 // needs to be run again to work see the new attribute. Otherwise this will
6723 // get run whenever the template is instantiated.
6724 if (TSK
!= TSK_Undeclared
)
6725 checkClassLevelDLLAttribute(BaseTemplateSpec
);
6730 if (getDLLAttr(BaseTemplateSpec
)) {
6731 // The template has already been specialized or instantiated with an
6732 // attribute, explicitly or through propagation. We should not try to change
6737 // The template was previously instantiated or explicitly specialized without
6738 // a dll attribute, It's too late for us to add an attribute, so warn that
6739 // this is unsupported.
6740 Diag(BaseLoc
, diag::warn_attribute_dll_instantiated_base_class
)
6741 << BaseTemplateSpec
->isExplicitSpecialization();
6742 Diag(ClassAttr
->getLocation(), diag::note_attribute
);
6743 if (BaseTemplateSpec
->isExplicitSpecialization()) {
6744 Diag(BaseTemplateSpec
->getLocation(),
6745 diag::note_template_class_explicit_specialization_was_here
)
6746 << BaseTemplateSpec
;
6748 Diag(BaseTemplateSpec
->getPointOfInstantiation(),
6749 diag::note_template_class_instantiation_was_here
)
6750 << BaseTemplateSpec
;
6754 /// Determine the kind of defaulting that would be done for a given function.
6756 /// If the function is both a default constructor and a copy / move constructor
6757 /// (due to having a default argument for the first parameter), this picks
6758 /// CXXDefaultConstructor.
6760 /// FIXME: Check that case is properly handled by all callers.
6761 Sema::DefaultedFunctionKind
6762 Sema::getDefaultedFunctionKind(const FunctionDecl
*FD
) {
6763 if (auto *MD
= dyn_cast
<CXXMethodDecl
>(FD
)) {
6764 if (const CXXConstructorDecl
*Ctor
= dyn_cast
<CXXConstructorDecl
>(FD
)) {
6765 if (Ctor
->isDefaultConstructor())
6766 return Sema::CXXDefaultConstructor
;
6768 if (Ctor
->isCopyConstructor())
6769 return Sema::CXXCopyConstructor
;
6771 if (Ctor
->isMoveConstructor())
6772 return Sema::CXXMoveConstructor
;
6775 if (MD
->isCopyAssignmentOperator())
6776 return Sema::CXXCopyAssignment
;
6778 if (MD
->isMoveAssignmentOperator())
6779 return Sema::CXXMoveAssignment
;
6781 if (isa
<CXXDestructorDecl
>(FD
))
6782 return Sema::CXXDestructor
;
6785 switch (FD
->getDeclName().getCXXOverloadedOperator()) {
6787 return DefaultedComparisonKind::Equal
;
6789 case OO_ExclaimEqual
:
6790 return DefaultedComparisonKind::NotEqual
;
6793 // No point allowing this if <=> doesn't exist in the current language mode.
6794 if (!getLangOpts().CPlusPlus20
)
6796 return DefaultedComparisonKind::ThreeWay
;
6801 case OO_GreaterEqual
:
6802 // No point allowing this if <=> doesn't exist in the current language mode.
6803 if (!getLangOpts().CPlusPlus20
)
6805 return DefaultedComparisonKind::Relational
;
6812 return DefaultedFunctionKind();
6815 static void DefineDefaultedFunction(Sema
&S
, FunctionDecl
*FD
,
6816 SourceLocation DefaultLoc
) {
6817 Sema::DefaultedFunctionKind DFK
= S
.getDefaultedFunctionKind(FD
);
6818 if (DFK
.isComparison())
6819 return S
.DefineDefaultedComparison(DefaultLoc
, FD
, DFK
.asComparison());
6821 switch (DFK
.asSpecialMember()) {
6822 case Sema::CXXDefaultConstructor
:
6823 S
.DefineImplicitDefaultConstructor(DefaultLoc
,
6824 cast
<CXXConstructorDecl
>(FD
));
6826 case Sema::CXXCopyConstructor
:
6827 S
.DefineImplicitCopyConstructor(DefaultLoc
, cast
<CXXConstructorDecl
>(FD
));
6829 case Sema::CXXCopyAssignment
:
6830 S
.DefineImplicitCopyAssignment(DefaultLoc
, cast
<CXXMethodDecl
>(FD
));
6832 case Sema::CXXDestructor
:
6833 S
.DefineImplicitDestructor(DefaultLoc
, cast
<CXXDestructorDecl
>(FD
));
6835 case Sema::CXXMoveConstructor
:
6836 S
.DefineImplicitMoveConstructor(DefaultLoc
, cast
<CXXConstructorDecl
>(FD
));
6838 case Sema::CXXMoveAssignment
:
6839 S
.DefineImplicitMoveAssignment(DefaultLoc
, cast
<CXXMethodDecl
>(FD
));
6841 case Sema::CXXInvalid
:
6842 llvm_unreachable("Invalid special member.");
6846 /// Determine whether a type is permitted to be passed or returned in
6847 /// registers, per C++ [class.temporary]p3.
6848 static bool canPassInRegisters(Sema
&S
, CXXRecordDecl
*D
,
6849 TargetInfo::CallingConvKind CCK
) {
6850 if (D
->isDependentType() || D
->isInvalidDecl())
6853 // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
6854 // The PS4 platform ABI follows the behavior of Clang 3.2.
6855 if (CCK
== TargetInfo::CCK_ClangABI4OrPS4
)
6856 return !D
->hasNonTrivialDestructorForCall() &&
6857 !D
->hasNonTrivialCopyConstructorForCall();
6859 if (CCK
== TargetInfo::CCK_MicrosoftWin64
) {
6860 bool CopyCtorIsTrivial
= false, CopyCtorIsTrivialForCall
= false;
6861 bool DtorIsTrivialForCall
= false;
6863 // If a class has at least one eligible, trivial copy constructor, it
6864 // is passed according to the C ABI. Otherwise, it is passed indirectly.
6866 // Note: This permits classes with non-trivial copy or move ctors to be
6867 // passed in registers, so long as they *also* have a trivial copy ctor,
6868 // which is non-conforming.
6869 if (D
->needsImplicitCopyConstructor()) {
6870 if (!D
->defaultedCopyConstructorIsDeleted()) {
6871 if (D
->hasTrivialCopyConstructor())
6872 CopyCtorIsTrivial
= true;
6873 if (D
->hasTrivialCopyConstructorForCall())
6874 CopyCtorIsTrivialForCall
= true;
6877 for (const CXXConstructorDecl
*CD
: D
->ctors()) {
6878 if (CD
->isCopyConstructor() && !CD
->isDeleted() &&
6879 !CD
->isIneligibleOrNotSelected()) {
6880 if (CD
->isTrivial())
6881 CopyCtorIsTrivial
= true;
6882 if (CD
->isTrivialForCall())
6883 CopyCtorIsTrivialForCall
= true;
6888 if (D
->needsImplicitDestructor()) {
6889 if (!D
->defaultedDestructorIsDeleted() &&
6890 D
->hasTrivialDestructorForCall())
6891 DtorIsTrivialForCall
= true;
6892 } else if (const auto *DD
= D
->getDestructor()) {
6893 if (!DD
->isDeleted() && DD
->isTrivialForCall())
6894 DtorIsTrivialForCall
= true;
6897 // If the copy ctor and dtor are both trivial-for-calls, pass direct.
6898 if (CopyCtorIsTrivialForCall
&& DtorIsTrivialForCall
)
6901 // If a class has a destructor, we'd really like to pass it indirectly
6902 // because it allows us to elide copies. Unfortunately, MSVC makes that
6903 // impossible for small types, which it will pass in a single register or
6904 // stack slot. Most objects with dtors are large-ish, so handle that early.
6905 // We can't call out all large objects as being indirect because there are
6906 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
6907 // how we pass large POD types.
6909 // Note: This permits small classes with nontrivial destructors to be
6910 // passed in registers, which is non-conforming.
6911 bool isAArch64
= S
.Context
.getTargetInfo().getTriple().isAArch64();
6912 uint64_t TypeSize
= isAArch64
? 128 : 64;
6914 if (CopyCtorIsTrivial
&&
6915 S
.getASTContext().getTypeSize(D
->getTypeForDecl()) <= TypeSize
)
6920 // Per C++ [class.temporary]p3, the relevant condition is:
6921 // each copy constructor, move constructor, and destructor of X is
6922 // either trivial or deleted, and X has at least one non-deleted copy
6923 // or move constructor
6924 bool HasNonDeletedCopyOrMove
= false;
6926 if (D
->needsImplicitCopyConstructor() &&
6927 !D
->defaultedCopyConstructorIsDeleted()) {
6928 if (!D
->hasTrivialCopyConstructorForCall())
6930 HasNonDeletedCopyOrMove
= true;
6933 if (S
.getLangOpts().CPlusPlus11
&& D
->needsImplicitMoveConstructor() &&
6934 !D
->defaultedMoveConstructorIsDeleted()) {
6935 if (!D
->hasTrivialMoveConstructorForCall())
6937 HasNonDeletedCopyOrMove
= true;
6940 if (D
->needsImplicitDestructor() && !D
->defaultedDestructorIsDeleted() &&
6941 !D
->hasTrivialDestructorForCall())
6944 for (const CXXMethodDecl
*MD
: D
->methods()) {
6945 if (MD
->isDeleted() || MD
->isIneligibleOrNotSelected())
6948 auto *CD
= dyn_cast
<CXXConstructorDecl
>(MD
);
6949 if (CD
&& CD
->isCopyOrMoveConstructor())
6950 HasNonDeletedCopyOrMove
= true;
6951 else if (!isa
<CXXDestructorDecl
>(MD
))
6954 if (!MD
->isTrivialForCall())
6958 return HasNonDeletedCopyOrMove
;
6961 /// Report an error regarding overriding, along with any relevant
6962 /// overridden methods.
6964 /// \param DiagID the primary error to report.
6965 /// \param MD the overriding method.
6967 ReportOverrides(Sema
&S
, unsigned DiagID
, const CXXMethodDecl
*MD
,
6968 llvm::function_ref
<bool(const CXXMethodDecl
*)> Report
) {
6969 bool IssuedDiagnostic
= false;
6970 for (const CXXMethodDecl
*O
: MD
->overridden_methods()) {
6972 if (!IssuedDiagnostic
) {
6973 S
.Diag(MD
->getLocation(), DiagID
) << MD
->getDeclName();
6974 IssuedDiagnostic
= true;
6976 S
.Diag(O
->getLocation(), diag::note_overridden_virtual_function
);
6979 return IssuedDiagnostic
;
6982 /// Perform semantic checks on a class definition that has been
6983 /// completing, introducing implicitly-declared members, checking for
6984 /// abstract types, etc.
6986 /// \param S The scope in which the class was parsed. Null if we didn't just
6987 /// parse a class definition.
6988 /// \param Record The completed class.
6989 void Sema::CheckCompletedCXXClass(Scope
*S
, CXXRecordDecl
*Record
) {
6993 if (Record
->isAbstract() && !Record
->isInvalidDecl()) {
6994 AbstractUsageInfo
Info(*this, Record
);
6995 CheckAbstractClassUsage(Info
, Record
);
6998 // If this is not an aggregate type and has no user-declared constructor,
6999 // complain about any non-static data members of reference or const scalar
7000 // type, since they will never get initializers.
7001 if (!Record
->isInvalidDecl() && !Record
->isDependentType() &&
7002 !Record
->isAggregate() && !Record
->hasUserDeclaredConstructor() &&
7003 !Record
->isLambda()) {
7004 bool Complained
= false;
7005 for (const auto *F
: Record
->fields()) {
7006 if (F
->hasInClassInitializer() || F
->isUnnamedBitfield())
7009 if (F
->getType()->isReferenceType() ||
7010 (F
->getType().isConstQualified() && F
->getType()->isScalarType())) {
7012 Diag(Record
->getLocation(), diag::warn_no_constructor_for_refconst
)
7013 << Record
->getTagKind() << Record
;
7017 Diag(F
->getLocation(), diag::note_refconst_member_not_initialized
)
7018 << F
->getType()->isReferenceType()
7019 << F
->getDeclName();
7024 if (Record
->getIdentifier()) {
7025 // C++ [class.mem]p13:
7026 // If T is the name of a class, then each of the following shall have a
7027 // name different from T:
7028 // - every member of every anonymous union that is a member of class T.
7030 // C++ [class.mem]p14:
7031 // In addition, if class T has a user-declared constructor (12.1), every
7032 // non-static data member of class T shall have a name different from T.
7033 DeclContext::lookup_result R
= Record
->lookup(Record
->getDeclName());
7034 for (DeclContext::lookup_iterator I
= R
.begin(), E
= R
.end(); I
!= E
;
7036 NamedDecl
*D
= (*I
)->getUnderlyingDecl();
7037 if (((isa
<FieldDecl
>(D
) || isa
<UnresolvedUsingValueDecl
>(D
)) &&
7038 Record
->hasUserDeclaredConstructor()) ||
7039 isa
<IndirectFieldDecl
>(D
)) {
7040 Diag((*I
)->getLocation(), diag::err_member_name_of_class
)
7041 << D
->getDeclName();
7047 // Warn if the class has virtual methods but non-virtual public destructor.
7048 if (Record
->isPolymorphic() && !Record
->isDependentType()) {
7049 CXXDestructorDecl
*dtor
= Record
->getDestructor();
7050 if ((!dtor
|| (!dtor
->isVirtual() && dtor
->getAccess() == AS_public
)) &&
7051 !Record
->hasAttr
<FinalAttr
>())
7052 Diag(dtor
? dtor
->getLocation() : Record
->getLocation(),
7053 diag::warn_non_virtual_dtor
) << Context
.getRecordType(Record
);
7056 if (Record
->isAbstract()) {
7057 if (FinalAttr
*FA
= Record
->getAttr
<FinalAttr
>()) {
7058 Diag(Record
->getLocation(), diag::warn_abstract_final_class
)
7059 << FA
->isSpelledAsSealed();
7060 DiagnoseAbstractType(Record
);
7064 // Warn if the class has a final destructor but is not itself marked final.
7065 if (!Record
->hasAttr
<FinalAttr
>()) {
7066 if (const CXXDestructorDecl
*dtor
= Record
->getDestructor()) {
7067 if (const FinalAttr
*FA
= dtor
->getAttr
<FinalAttr
>()) {
7068 Diag(FA
->getLocation(), diag::warn_final_dtor_non_final_class
)
7069 << FA
->isSpelledAsSealed()
7070 << FixItHint::CreateInsertion(
7071 getLocForEndOfToken(Record
->getLocation()),
7072 (FA
->isSpelledAsSealed() ? " sealed" : " final"));
7073 Diag(Record
->getLocation(),
7074 diag::note_final_dtor_non_final_class_silence
)
7075 << Context
.getRecordType(Record
) << FA
->isSpelledAsSealed();
7080 // See if trivial_abi has to be dropped.
7081 if (Record
->hasAttr
<TrivialABIAttr
>())
7082 checkIllFormedTrivialABIStruct(*Record
);
7084 // Set HasTrivialSpecialMemberForCall if the record has attribute
7086 bool HasTrivialABI
= Record
->hasAttr
<TrivialABIAttr
>();
7089 Record
->setHasTrivialSpecialMemberForCall();
7091 // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=).
7092 // We check these last because they can depend on the properties of the
7093 // primary comparison functions (==, <=>).
7094 llvm::SmallVector
<FunctionDecl
*, 5> DefaultedSecondaryComparisons
;
7096 // Perform checks that can't be done until we know all the properties of a
7097 // member function (whether it's defaulted, deleted, virtual, overriding,
7099 auto CheckCompletedMemberFunction
= [&](CXXMethodDecl
*MD
) {
7100 // A static function cannot override anything.
7101 if (MD
->getStorageClass() == SC_Static
) {
7102 if (ReportOverrides(*this, diag::err_static_overrides_virtual
, MD
,
7103 [](const CXXMethodDecl
*) { return true; }))
7107 // A deleted function cannot override a non-deleted function and vice
7109 if (ReportOverrides(*this,
7110 MD
->isDeleted() ? diag::err_deleted_override
7111 : diag::err_non_deleted_override
,
7112 MD
, [&](const CXXMethodDecl
*V
) {
7113 return MD
->isDeleted() != V
->isDeleted();
7115 if (MD
->isDefaulted() && MD
->isDeleted())
7116 // Explain why this defaulted function was deleted.
7117 DiagnoseDeletedDefaultedFunction(MD
);
7121 // A consteval function cannot override a non-consteval function and vice
7123 if (ReportOverrides(*this,
7124 MD
->isConsteval() ? diag::err_consteval_override
7125 : diag::err_non_consteval_override
,
7126 MD
, [&](const CXXMethodDecl
*V
) {
7127 return MD
->isConsteval() != V
->isConsteval();
7129 if (MD
->isDefaulted() && MD
->isDeleted())
7130 // Explain why this defaulted function was deleted.
7131 DiagnoseDeletedDefaultedFunction(MD
);
7136 auto CheckForDefaultedFunction
= [&](FunctionDecl
*FD
) -> bool {
7137 if (!FD
|| FD
->isInvalidDecl() || !FD
->isExplicitlyDefaulted())
7140 DefaultedFunctionKind DFK
= getDefaultedFunctionKind(FD
);
7141 if (DFK
.asComparison() == DefaultedComparisonKind::NotEqual
||
7142 DFK
.asComparison() == DefaultedComparisonKind::Relational
) {
7143 DefaultedSecondaryComparisons
.push_back(FD
);
7147 CheckExplicitlyDefaultedFunction(S
, FD
);
7151 auto CompleteMemberFunction
= [&](CXXMethodDecl
*M
) {
7152 // Check whether the explicitly-defaulted members are valid.
7153 bool Incomplete
= CheckForDefaultedFunction(M
);
7155 // Skip the rest of the checks for a member of a dependent class.
7156 if (Record
->isDependentType())
7159 // For an explicitly defaulted or deleted special member, we defer
7160 // determining triviality until the class is complete. That time is now!
7161 CXXSpecialMember CSM
= getSpecialMember(M
);
7162 if (!M
->isImplicit() && !M
->isUserProvided()) {
7163 if (CSM
!= CXXInvalid
) {
7164 M
->setTrivial(SpecialMemberIsTrivial(M
, CSM
));
7165 // Inform the class that we've finished declaring this member.
7166 Record
->finishedDefaultedOrDeletedMember(M
);
7167 M
->setTrivialForCall(
7169 SpecialMemberIsTrivial(M
, CSM
, TAH_ConsiderTrivialABI
));
7170 Record
->setTrivialForCallFlags(M
);
7174 // Set triviality for the purpose of calls if this is a user-provided
7175 // copy/move constructor or destructor.
7176 if ((CSM
== CXXCopyConstructor
|| CSM
== CXXMoveConstructor
||
7177 CSM
== CXXDestructor
) && M
->isUserProvided()) {
7178 M
->setTrivialForCall(HasTrivialABI
);
7179 Record
->setTrivialForCallFlags(M
);
7182 if (!M
->isInvalidDecl() && M
->isExplicitlyDefaulted() &&
7183 M
->hasAttr
<DLLExportAttr
>()) {
7184 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015
) &&
7186 (CSM
== CXXDefaultConstructor
|| CSM
== CXXCopyConstructor
||
7187 CSM
== CXXDestructor
))
7188 M
->dropAttr
<DLLExportAttr
>();
7190 if (M
->hasAttr
<DLLExportAttr
>()) {
7191 // Define after any fields with in-class initializers have been parsed.
7192 DelayedDllExportMemberFunctions
.push_back(M
);
7196 // Define defaulted constexpr virtual functions that override a base class
7197 // function right away.
7198 // FIXME: We can defer doing this until the vtable is marked as used.
7199 if (CSM
!= CXXInvalid
&& !M
->isDeleted() && M
->isDefaulted() &&
7200 M
->isConstexpr() && M
->size_overridden_methods())
7201 DefineDefaultedFunction(*this, M
, M
->getLocation());
7204 CheckCompletedMemberFunction(M
);
7207 // Check the destructor before any other member function. We need to
7208 // determine whether it's trivial in order to determine whether the claas
7209 // type is a literal type, which is a prerequisite for determining whether
7210 // other special member functions are valid and whether they're implicitly
7212 if (CXXDestructorDecl
*Dtor
= Record
->getDestructor())
7213 CompleteMemberFunction(Dtor
);
7215 bool HasMethodWithOverrideControl
= false,
7216 HasOverridingMethodWithoutOverrideControl
= false;
7217 for (auto *D
: Record
->decls()) {
7218 if (auto *M
= dyn_cast
<CXXMethodDecl
>(D
)) {
7219 // FIXME: We could do this check for dependent types with non-dependent
7221 if (!Record
->isDependentType()) {
7222 // See if a method overloads virtual methods in a base
7223 // class without overriding any.
7225 DiagnoseHiddenVirtualMethods(M
);
7226 if (M
->hasAttr
<OverrideAttr
>())
7227 HasMethodWithOverrideControl
= true;
7228 else if (M
->size_overridden_methods() > 0)
7229 HasOverridingMethodWithoutOverrideControl
= true;
7232 if (!isa
<CXXDestructorDecl
>(M
))
7233 CompleteMemberFunction(M
);
7234 } else if (auto *F
= dyn_cast
<FriendDecl
>(D
)) {
7235 CheckForDefaultedFunction(
7236 dyn_cast_or_null
<FunctionDecl
>(F
->getFriendDecl()));
7240 if (HasOverridingMethodWithoutOverrideControl
) {
7241 bool HasInconsistentOverrideControl
= HasMethodWithOverrideControl
;
7242 for (auto *M
: Record
->methods())
7243 DiagnoseAbsenceOfOverrideControl(M
, HasInconsistentOverrideControl
);
7246 // Check the defaulted secondary comparisons after any other member functions.
7247 for (FunctionDecl
*FD
: DefaultedSecondaryComparisons
) {
7248 CheckExplicitlyDefaultedFunction(S
, FD
);
7250 // If this is a member function, we deferred checking it until now.
7251 if (auto *MD
= dyn_cast
<CXXMethodDecl
>(FD
))
7252 CheckCompletedMemberFunction(MD
);
7255 // ms_struct is a request to use the same ABI rules as MSVC. Check
7256 // whether this class uses any C++ features that are implemented
7257 // completely differently in MSVC, and if so, emit a diagnostic.
7258 // That diagnostic defaults to an error, but we allow projects to
7259 // map it down to a warning (or ignore it). It's a fairly common
7260 // practice among users of the ms_struct pragma to mass-annotate
7261 // headers, sweeping up a bunch of types that the project doesn't
7262 // really rely on MSVC-compatible layout for. We must therefore
7263 // support "ms_struct except for C++ stuff" as a secondary ABI.
7264 // Don't emit this diagnostic if the feature was enabled as a
7265 // language option (as opposed to via a pragma or attribute), as
7266 // the option -mms-bitfields otherwise essentially makes it impossible
7267 // to build C++ code, unless this diagnostic is turned off.
7268 if (Record
->isMsStruct(Context
) && !Context
.getLangOpts().MSBitfields
&&
7269 (Record
->isPolymorphic() || Record
->getNumBases())) {
7270 Diag(Record
->getLocation(), diag::warn_cxx_ms_struct
);
7273 checkClassLevelDLLAttribute(Record
);
7274 checkClassLevelCodeSegAttribute(Record
);
7276 bool ClangABICompat4
=
7277 Context
.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4
;
7278 TargetInfo::CallingConvKind CCK
=
7279 Context
.getTargetInfo().getCallingConvKind(ClangABICompat4
);
7280 bool CanPass
= canPassInRegisters(*this, Record
, CCK
);
7282 // Do not change ArgPassingRestrictions if it has already been set to
7283 // ArgPassingKind::CanNeverPassInRegs.
7284 if (Record
->getArgPassingRestrictions() !=
7285 RecordArgPassingKind::CanNeverPassInRegs
)
7286 Record
->setArgPassingRestrictions(
7287 CanPass
? RecordArgPassingKind::CanPassInRegs
7288 : RecordArgPassingKind::CannotPassInRegs
);
7290 // If canPassInRegisters returns true despite the record having a non-trivial
7291 // destructor, the record is destructed in the callee. This happens only when
7292 // the record or one of its subobjects has a field annotated with trivial_abi
7293 // or a field qualified with ObjC __strong/__weak.
7294 if (Context
.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
7295 Record
->setParamDestroyedInCallee(true);
7296 else if (Record
->hasNonTrivialDestructor())
7297 Record
->setParamDestroyedInCallee(CanPass
);
7299 if (getLangOpts().ForceEmitVTables
) {
7300 // If we want to emit all the vtables, we need to mark it as used. This
7301 // is especially required for cases like vtable assumption loads.
7302 MarkVTableUsed(Record
->getInnerLocStart(), Record
);
7305 if (getLangOpts().CUDA
) {
7306 if (Record
->hasAttr
<CUDADeviceBuiltinSurfaceTypeAttr
>())
7307 checkCUDADeviceBuiltinSurfaceClassTemplate(*this, Record
);
7308 else if (Record
->hasAttr
<CUDADeviceBuiltinTextureTypeAttr
>())
7309 checkCUDADeviceBuiltinTextureClassTemplate(*this, Record
);
7313 /// Look up the special member function that would be called by a special
7314 /// member function for a subobject of class type.
7316 /// \param Class The class type of the subobject.
7317 /// \param CSM The kind of special member function.
7318 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
7319 /// \param ConstRHS True if this is a copy operation with a const object
7320 /// on its RHS, that is, if the argument to the outer special member
7321 /// function is 'const' and this is not a field marked 'mutable'.
7322 static Sema::SpecialMemberOverloadResult
lookupCallFromSpecialMember(
7323 Sema
&S
, CXXRecordDecl
*Class
, Sema::CXXSpecialMember CSM
,
7324 unsigned FieldQuals
, bool ConstRHS
) {
7325 unsigned LHSQuals
= 0;
7326 if (CSM
== Sema::CXXCopyAssignment
|| CSM
== Sema::CXXMoveAssignment
)
7327 LHSQuals
= FieldQuals
;
7329 unsigned RHSQuals
= FieldQuals
;
7330 if (CSM
== Sema::CXXDefaultConstructor
|| CSM
== Sema::CXXDestructor
)
7333 RHSQuals
|= Qualifiers::Const
;
7335 return S
.LookupSpecialMember(Class
, CSM
,
7336 RHSQuals
& Qualifiers::Const
,
7337 RHSQuals
& Qualifiers::Volatile
,
7339 LHSQuals
& Qualifiers::Const
,
7340 LHSQuals
& Qualifiers::Volatile
);
7343 class Sema::InheritedConstructorInfo
{
7345 SourceLocation UseLoc
;
7347 /// A mapping from the base classes through which the constructor was
7348 /// inherited to the using shadow declaration in that base class (or a null
7349 /// pointer if the constructor was declared in that base class).
7350 llvm::DenseMap
<CXXRecordDecl
*, ConstructorUsingShadowDecl
*>
7354 InheritedConstructorInfo(Sema
&S
, SourceLocation UseLoc
,
7355 ConstructorUsingShadowDecl
*Shadow
)
7356 : S(S
), UseLoc(UseLoc
) {
7357 bool DiagnosedMultipleConstructedBases
= false;
7358 CXXRecordDecl
*ConstructedBase
= nullptr;
7359 BaseUsingDecl
*ConstructedBaseIntroducer
= nullptr;
7361 // Find the set of such base class subobjects and check that there's a
7362 // unique constructed subobject.
7363 for (auto *D
: Shadow
->redecls()) {
7364 auto *DShadow
= cast
<ConstructorUsingShadowDecl
>(D
);
7365 auto *DNominatedBase
= DShadow
->getNominatedBaseClass();
7366 auto *DConstructedBase
= DShadow
->getConstructedBaseClass();
7368 InheritedFromBases
.insert(
7369 std::make_pair(DNominatedBase
->getCanonicalDecl(),
7370 DShadow
->getNominatedBaseClassShadowDecl()));
7371 if (DShadow
->constructsVirtualBase())
7372 InheritedFromBases
.insert(
7373 std::make_pair(DConstructedBase
->getCanonicalDecl(),
7374 DShadow
->getConstructedBaseClassShadowDecl()));
7376 assert(DNominatedBase
== DConstructedBase
);
7378 // [class.inhctor.init]p2:
7379 // If the constructor was inherited from multiple base class subobjects
7380 // of type B, the program is ill-formed.
7381 if (!ConstructedBase
) {
7382 ConstructedBase
= DConstructedBase
;
7383 ConstructedBaseIntroducer
= D
->getIntroducer();
7384 } else if (ConstructedBase
!= DConstructedBase
&&
7385 !Shadow
->isInvalidDecl()) {
7386 if (!DiagnosedMultipleConstructedBases
) {
7387 S
.Diag(UseLoc
, diag::err_ambiguous_inherited_constructor
)
7388 << Shadow
->getTargetDecl();
7389 S
.Diag(ConstructedBaseIntroducer
->getLocation(),
7390 diag::note_ambiguous_inherited_constructor_using
)
7392 DiagnosedMultipleConstructedBases
= true;
7394 S
.Diag(D
->getIntroducer()->getLocation(),
7395 diag::note_ambiguous_inherited_constructor_using
)
7396 << DConstructedBase
;
7400 if (DiagnosedMultipleConstructedBases
)
7401 Shadow
->setInvalidDecl();
7404 /// Find the constructor to use for inherited construction of a base class,
7405 /// and whether that base class constructor inherits the constructor from a
7406 /// virtual base class (in which case it won't actually invoke it).
7407 std::pair
<CXXConstructorDecl
*, bool>
7408 findConstructorForBase(CXXRecordDecl
*Base
, CXXConstructorDecl
*Ctor
) const {
7409 auto It
= InheritedFromBases
.find(Base
->getCanonicalDecl());
7410 if (It
== InheritedFromBases
.end())
7411 return std::make_pair(nullptr, false);
7413 // This is an intermediary class.
7415 return std::make_pair(
7416 S
.findInheritingConstructor(UseLoc
, Ctor
, It
->second
),
7417 It
->second
->constructsVirtualBase());
7419 // This is the base class from which the constructor was inherited.
7420 return std::make_pair(Ctor
, false);
7424 /// Is the special member function which would be selected to perform the
7425 /// specified operation on the specified class type a constexpr constructor?
7427 specialMemberIsConstexpr(Sema
&S
, CXXRecordDecl
*ClassDecl
,
7428 Sema::CXXSpecialMember CSM
, unsigned Quals
,
7430 CXXConstructorDecl
*InheritedCtor
= nullptr,
7431 Sema::InheritedConstructorInfo
*Inherited
= nullptr) {
7432 // Suppress duplicate constraint checking here, in case a constraint check
7433 // caused us to decide to do this. Any truely recursive checks will get
7434 // caught during these checks anyway.
7435 Sema::SatisfactionStackResetRAII SSRAII
{S
};
7437 // If we're inheriting a constructor, see if we need to call it for this base
7439 if (InheritedCtor
) {
7440 assert(CSM
== Sema::CXXDefaultConstructor
);
7442 Inherited
->findConstructorForBase(ClassDecl
, InheritedCtor
).first
;
7444 return BaseCtor
->isConstexpr();
7447 if (CSM
== Sema::CXXDefaultConstructor
)
7448 return ClassDecl
->hasConstexprDefaultConstructor();
7449 if (CSM
== Sema::CXXDestructor
)
7450 return ClassDecl
->hasConstexprDestructor();
7452 Sema::SpecialMemberOverloadResult SMOR
=
7453 lookupCallFromSpecialMember(S
, ClassDecl
, CSM
, Quals
, ConstRHS
);
7454 if (!SMOR
.getMethod())
7455 // A constructor we wouldn't select can't be "involved in initializing"
7458 return SMOR
.getMethod()->isConstexpr();
7461 /// Determine whether the specified special member function would be constexpr
7462 /// if it were implicitly defined.
7463 static bool defaultedSpecialMemberIsConstexpr(
7464 Sema
&S
, CXXRecordDecl
*ClassDecl
, Sema::CXXSpecialMember CSM
,
7465 bool ConstArg
, CXXConstructorDecl
*InheritedCtor
= nullptr,
7466 Sema::InheritedConstructorInfo
*Inherited
= nullptr) {
7467 if (!S
.getLangOpts().CPlusPlus11
)
7470 // C++11 [dcl.constexpr]p4:
7471 // In the definition of a constexpr constructor [...]
7474 case Sema::CXXDefaultConstructor
:
7477 // Since default constructor lookup is essentially trivial (and cannot
7478 // involve, for instance, template instantiation), we compute whether a
7479 // defaulted default constructor is constexpr directly within CXXRecordDecl.
7481 // This is important for performance; we need to know whether the default
7482 // constructor is constexpr to determine whether the type is a literal type.
7483 return ClassDecl
->defaultedDefaultConstructorIsConstexpr();
7485 case Sema::CXXCopyConstructor
:
7486 case Sema::CXXMoveConstructor
:
7487 // For copy or move constructors, we need to perform overload resolution.
7490 case Sema::CXXCopyAssignment
:
7491 case Sema::CXXMoveAssignment
:
7492 if (!S
.getLangOpts().CPlusPlus14
)
7494 // In C++1y, we need to perform overload resolution.
7498 case Sema::CXXDestructor
:
7499 return ClassDecl
->defaultedDestructorIsConstexpr();
7501 case Sema::CXXInvalid
:
7505 // -- if the class is a non-empty union, or for each non-empty anonymous
7506 // union member of a non-union class, exactly one non-static data member
7507 // shall be initialized; [DR1359]
7509 // If we squint, this is guaranteed, since exactly one non-static data member
7510 // will be initialized (if the constructor isn't deleted), we just don't know
7512 if (Ctor
&& ClassDecl
->isUnion())
7513 return CSM
== Sema::CXXDefaultConstructor
7514 ? ClassDecl
->hasInClassInitializer() ||
7515 !ClassDecl
->hasVariantMembers()
7518 // -- the class shall not have any virtual base classes;
7519 if (Ctor
&& ClassDecl
->getNumVBases())
7522 // C++1y [class.copy]p26:
7523 // -- [the class] is a literal type, and
7524 if (!Ctor
&& !ClassDecl
->isLiteral())
7527 // -- every constructor involved in initializing [...] base class
7528 // sub-objects shall be a constexpr constructor;
7529 // -- the assignment operator selected to copy/move each direct base
7530 // class is a constexpr function, and
7531 for (const auto &B
: ClassDecl
->bases()) {
7532 const RecordType
*BaseType
= B
.getType()->getAs
<RecordType
>();
7535 CXXRecordDecl
*BaseClassDecl
= cast
<CXXRecordDecl
>(BaseType
->getDecl());
7536 if (!specialMemberIsConstexpr(S
, BaseClassDecl
, CSM
, 0, ConstArg
,
7537 InheritedCtor
, Inherited
))
7541 // -- every constructor involved in initializing non-static data members
7542 // [...] shall be a constexpr constructor;
7543 // -- every non-static data member and base class sub-object shall be
7545 // -- for each non-static data member of X that is of class type (or array
7546 // thereof), the assignment operator selected to copy/move that member is
7547 // a constexpr function
7548 for (const auto *F
: ClassDecl
->fields()) {
7549 if (F
->isInvalidDecl())
7551 if (CSM
== Sema::CXXDefaultConstructor
&& F
->hasInClassInitializer())
7553 QualType BaseType
= S
.Context
.getBaseElementType(F
->getType());
7554 if (const RecordType
*RecordTy
= BaseType
->getAs
<RecordType
>()) {
7555 CXXRecordDecl
*FieldRecDecl
= cast
<CXXRecordDecl
>(RecordTy
->getDecl());
7556 if (!specialMemberIsConstexpr(S
, FieldRecDecl
, CSM
,
7557 BaseType
.getCVRQualifiers(),
7558 ConstArg
&& !F
->isMutable()))
7560 } else if (CSM
== Sema::CXXDefaultConstructor
) {
7565 // All OK, it's constexpr!
7570 /// RAII object to register a defaulted function as having its exception
7571 /// specification computed.
7572 struct ComputingExceptionSpec
{
7575 ComputingExceptionSpec(Sema
&S
, FunctionDecl
*FD
, SourceLocation Loc
)
7577 Sema::CodeSynthesisContext Ctx
;
7578 Ctx
.Kind
= Sema::CodeSynthesisContext::ExceptionSpecEvaluation
;
7579 Ctx
.PointOfInstantiation
= Loc
;
7581 S
.pushCodeSynthesisContext(Ctx
);
7583 ~ComputingExceptionSpec() {
7584 S
.popCodeSynthesisContext();
7589 static Sema::ImplicitExceptionSpecification
7590 ComputeDefaultedSpecialMemberExceptionSpec(
7591 Sema
&S
, SourceLocation Loc
, CXXMethodDecl
*MD
, Sema::CXXSpecialMember CSM
,
7592 Sema::InheritedConstructorInfo
*ICI
);
7594 static Sema::ImplicitExceptionSpecification
7595 ComputeDefaultedComparisonExceptionSpec(Sema
&S
, SourceLocation Loc
,
7597 Sema::DefaultedComparisonKind DCK
);
7599 static Sema::ImplicitExceptionSpecification
7600 computeImplicitExceptionSpec(Sema
&S
, SourceLocation Loc
, FunctionDecl
*FD
) {
7601 auto DFK
= S
.getDefaultedFunctionKind(FD
);
7602 if (DFK
.isSpecialMember())
7603 return ComputeDefaultedSpecialMemberExceptionSpec(
7604 S
, Loc
, cast
<CXXMethodDecl
>(FD
), DFK
.asSpecialMember(), nullptr);
7605 if (DFK
.isComparison())
7606 return ComputeDefaultedComparisonExceptionSpec(S
, Loc
, FD
,
7607 DFK
.asComparison());
7609 auto *CD
= cast
<CXXConstructorDecl
>(FD
);
7610 assert(CD
->getInheritedConstructor() &&
7611 "only defaulted functions and inherited constructors have implicit "
7613 Sema::InheritedConstructorInfo
ICI(
7614 S
, Loc
, CD
->getInheritedConstructor().getShadowDecl());
7615 return ComputeDefaultedSpecialMemberExceptionSpec(
7616 S
, Loc
, CD
, Sema::CXXDefaultConstructor
, &ICI
);
7619 static FunctionProtoType::ExtProtoInfo
getImplicitMethodEPI(Sema
&S
,
7620 CXXMethodDecl
*MD
) {
7621 FunctionProtoType::ExtProtoInfo EPI
;
7623 // Build an exception specification pointing back at this member.
7624 EPI
.ExceptionSpec
.Type
= EST_Unevaluated
;
7625 EPI
.ExceptionSpec
.SourceDecl
= MD
;
7627 // Set the calling convention to the default for C++ instance methods.
7628 EPI
.ExtInfo
= EPI
.ExtInfo
.withCallingConv(
7629 S
.Context
.getDefaultCallingConvention(/*IsVariadic=*/false,
7630 /*IsCXXMethod=*/true));
7634 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc
, FunctionDecl
*FD
) {
7635 const FunctionProtoType
*FPT
= FD
->getType()->castAs
<FunctionProtoType
>();
7636 if (FPT
->getExceptionSpecType() != EST_Unevaluated
)
7639 // Evaluate the exception specification.
7640 auto IES
= computeImplicitExceptionSpec(*this, Loc
, FD
);
7641 auto ESI
= IES
.getExceptionSpec();
7643 // Update the type of the special member to use it.
7644 UpdateExceptionSpec(FD
, ESI
);
7647 void Sema::CheckExplicitlyDefaultedFunction(Scope
*S
, FunctionDecl
*FD
) {
7648 assert(FD
->isExplicitlyDefaulted() && "not explicitly-defaulted");
7650 DefaultedFunctionKind DefKind
= getDefaultedFunctionKind(FD
);
7652 assert(FD
->getDeclContext()->isDependentContext());
7656 if (DefKind
.isComparison())
7657 UnusedPrivateFields
.clear();
7659 if (DefKind
.isSpecialMember()
7660 ? CheckExplicitlyDefaultedSpecialMember(cast
<CXXMethodDecl
>(FD
),
7661 DefKind
.asSpecialMember(),
7662 FD
->getDefaultLoc())
7663 : CheckExplicitlyDefaultedComparison(S
, FD
, DefKind
.asComparison()))
7664 FD
->setInvalidDecl();
7667 bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl
*MD
,
7668 CXXSpecialMember CSM
,
7669 SourceLocation DefaultLoc
) {
7670 CXXRecordDecl
*RD
= MD
->getParent();
7672 assert(MD
->isExplicitlyDefaulted() && CSM
!= CXXInvalid
&&
7673 "not an explicitly-defaulted special member");
7675 // Defer all checking for special members of a dependent type.
7676 if (RD
->isDependentType())
7679 // Whether this was the first-declared instance of the constructor.
7680 // This affects whether we implicitly add an exception spec and constexpr.
7681 bool First
= MD
== MD
->getCanonicalDecl();
7683 bool HadError
= false;
7685 // C++11 [dcl.fct.def.default]p1:
7686 // A function that is explicitly defaulted shall
7687 // -- be a special member function [...] (checked elsewhere),
7688 // -- have the same type (except for ref-qualifiers, and except that a
7689 // copy operation can take a non-const reference) as an implicit
7691 // -- not have default arguments.
7692 // C++2a changes the second bullet to instead delete the function if it's
7693 // defaulted on its first declaration, unless it's "an assignment operator,
7694 // and its return type differs or its parameter type is not a reference".
7695 bool DeleteOnTypeMismatch
= getLangOpts().CPlusPlus20
&& First
;
7696 bool ShouldDeleteForTypeMismatch
= false;
7697 unsigned ExpectedParams
= 1;
7698 if (CSM
== CXXDefaultConstructor
|| CSM
== CXXDestructor
)
7700 if (MD
->getNumExplicitParams() != ExpectedParams
) {
7701 // This checks for default arguments: a copy or move constructor with a
7702 // default argument is classified as a default constructor, and assignment
7703 // operations and destructors can't have default arguments.
7704 Diag(MD
->getLocation(), diag::err_defaulted_special_member_params
)
7705 << CSM
<< MD
->getSourceRange();
7707 } else if (MD
->isVariadic()) {
7708 if (DeleteOnTypeMismatch
)
7709 ShouldDeleteForTypeMismatch
= true;
7711 Diag(MD
->getLocation(), diag::err_defaulted_special_member_variadic
)
7712 << CSM
<< MD
->getSourceRange();
7717 const FunctionProtoType
*Type
= MD
->getType()->castAs
<FunctionProtoType
>();
7719 bool CanHaveConstParam
= false;
7720 if (CSM
== CXXCopyConstructor
)
7721 CanHaveConstParam
= RD
->implicitCopyConstructorHasConstParam();
7722 else if (CSM
== CXXCopyAssignment
)
7723 CanHaveConstParam
= RD
->implicitCopyAssignmentHasConstParam();
7725 QualType ReturnType
= Context
.VoidTy
;
7726 if (CSM
== CXXCopyAssignment
|| CSM
== CXXMoveAssignment
) {
7727 // Check for return type matching.
7728 ReturnType
= Type
->getReturnType();
7729 QualType ThisType
= MD
->getFunctionObjectParameterType();
7731 QualType DeclType
= Context
.getTypeDeclType(RD
);
7732 DeclType
= Context
.getElaboratedType(ElaboratedTypeKeyword::None
, nullptr,
7734 DeclType
= Context
.getAddrSpaceQualType(
7735 DeclType
, ThisType
.getQualifiers().getAddressSpace());
7736 QualType ExpectedReturnType
= Context
.getLValueReferenceType(DeclType
);
7738 if (!Context
.hasSameType(ReturnType
, ExpectedReturnType
)) {
7739 Diag(MD
->getLocation(), diag::err_defaulted_special_member_return_type
)
7740 << (CSM
== CXXMoveAssignment
) << ExpectedReturnType
;
7744 // A defaulted special member cannot have cv-qualifiers.
7745 if (ThisType
.isConstQualified() || ThisType
.isVolatileQualified()) {
7746 if (DeleteOnTypeMismatch
)
7747 ShouldDeleteForTypeMismatch
= true;
7749 Diag(MD
->getLocation(), diag::err_defaulted_special_member_quals
)
7750 << (CSM
== CXXMoveAssignment
) << getLangOpts().CPlusPlus14
;
7754 // [C++23][dcl.fct.def.default]/p2.2
7755 // if F2 has an implicit object parameter of type “reference to C”,
7756 // F1 may be an explicit object member function whose explicit object
7757 // parameter is of (possibly different) type “reference to C”,
7758 // in which case the type of F1 would differ from the type of F2
7759 // in that the type of F1 has an additional parameter;
7760 if (!Context
.hasSameType(
7761 ThisType
.getNonReferenceType().getUnqualifiedType(),
7762 Context
.getRecordType(RD
))) {
7763 if (DeleteOnTypeMismatch
)
7764 ShouldDeleteForTypeMismatch
= true;
7766 Diag(MD
->getLocation(),
7767 diag::err_defaulted_special_member_explicit_object_mismatch
)
7768 << (CSM
== CXXMoveAssignment
) << RD
<< MD
->getSourceRange();
7774 // Check for parameter type matching.
7777 ? Type
->getParamType(MD
->isExplicitObjectMemberFunction() ? 1 : 0)
7779 bool HasConstParam
= false;
7780 if (ExpectedParams
&& ArgType
->isReferenceType()) {
7781 // Argument must be reference to possibly-const T.
7782 QualType ReferentType
= ArgType
->getPointeeType();
7783 HasConstParam
= ReferentType
.isConstQualified();
7785 if (ReferentType
.isVolatileQualified()) {
7786 if (DeleteOnTypeMismatch
)
7787 ShouldDeleteForTypeMismatch
= true;
7789 Diag(MD
->getLocation(),
7790 diag::err_defaulted_special_member_volatile_param
) << CSM
;
7795 if (HasConstParam
&& !CanHaveConstParam
) {
7796 if (DeleteOnTypeMismatch
)
7797 ShouldDeleteForTypeMismatch
= true;
7798 else if (CSM
== CXXCopyConstructor
|| CSM
== CXXCopyAssignment
) {
7799 Diag(MD
->getLocation(),
7800 diag::err_defaulted_special_member_copy_const_param
)
7801 << (CSM
== CXXCopyAssignment
);
7802 // FIXME: Explain why this special member can't be const.
7805 Diag(MD
->getLocation(),
7806 diag::err_defaulted_special_member_move_const_param
)
7807 << (CSM
== CXXMoveAssignment
);
7811 } else if (ExpectedParams
) {
7812 // A copy assignment operator can take its argument by value, but a
7813 // defaulted one cannot.
7814 assert(CSM
== CXXCopyAssignment
&& "unexpected non-ref argument");
7815 Diag(MD
->getLocation(), diag::err_defaulted_copy_assign_not_ref
);
7819 // C++11 [dcl.fct.def.default]p2:
7820 // An explicitly-defaulted function may be declared constexpr only if it
7821 // would have been implicitly declared as constexpr,
7822 // Do not apply this rule to members of class templates, since core issue 1358
7823 // makes such functions always instantiate to constexpr functions. For
7824 // functions which cannot be constexpr (for non-constructors in C++11 and for
7825 // destructors in C++14 and C++17), this is checked elsewhere.
7827 // FIXME: This should not apply if the member is deleted.
7828 bool Constexpr
= defaultedSpecialMemberIsConstexpr(*this, RD
, CSM
,
7831 // C++14 [dcl.constexpr]p6 (CWG DR647/CWG DR1358):
7832 // If the instantiated template specialization of a constexpr function
7833 // template or member function of a class template would fail to satisfy
7834 // the requirements for a constexpr function or constexpr constructor, that
7835 // specialization is still a constexpr function or constexpr constructor,
7836 // even though a call to such a function cannot appear in a constant
7838 if (MD
->isTemplateInstantiation() && MD
->isConstexpr())
7841 if ((getLangOpts().CPlusPlus20
||
7842 (getLangOpts().CPlusPlus14
? !isa
<CXXDestructorDecl
>(MD
)
7843 : isa
<CXXConstructorDecl
>(MD
))) &&
7844 MD
->isConstexpr() && !Constexpr
&&
7845 MD
->getTemplatedKind() == FunctionDecl::TK_NonTemplate
) {
7846 if (!MD
->isConsteval() && RD
->getNumVBases()) {
7847 Diag(MD
->getBeginLoc(), diag::err_incorrect_defaulted_constexpr_with_vb
)
7849 for (const auto &I
: RD
->vbases())
7850 Diag(I
.getBeginLoc(), diag::note_constexpr_virtual_base_here
);
7852 Diag(MD
->getBeginLoc(), MD
->isConsteval()
7853 ? diag::err_incorrect_defaulted_consteval
7854 : diag::err_incorrect_defaulted_constexpr
)
7857 // FIXME: Explain why the special member can't be constexpr.
7862 // C++2a [dcl.fct.def.default]p3:
7863 // If a function is explicitly defaulted on its first declaration, it is
7864 // implicitly considered to be constexpr if the implicit declaration
7866 MD
->setConstexprKind(Constexpr
? (MD
->isConsteval()
7867 ? ConstexprSpecKind::Consteval
7868 : ConstexprSpecKind::Constexpr
)
7869 : ConstexprSpecKind::Unspecified
);
7871 if (!Type
->hasExceptionSpec()) {
7872 // C++2a [except.spec]p3:
7873 // If a declaration of a function does not have a noexcept-specifier
7874 // [and] is defaulted on its first declaration, [...] the exception
7875 // specification is as specified below
7876 FunctionProtoType::ExtProtoInfo EPI
= Type
->getExtProtoInfo();
7877 EPI
.ExceptionSpec
.Type
= EST_Unevaluated
;
7878 EPI
.ExceptionSpec
.SourceDecl
= MD
;
7880 Context
.getFunctionType(ReturnType
, Type
->getParamTypes(), EPI
));
7884 if (ShouldDeleteForTypeMismatch
|| ShouldDeleteSpecialMember(MD
, CSM
)) {
7886 SetDeclDeleted(MD
, MD
->getLocation());
7887 if (!inTemplateInstantiation() && !HadError
) {
7888 Diag(MD
->getLocation(), diag::warn_defaulted_method_deleted
) << CSM
;
7889 if (ShouldDeleteForTypeMismatch
) {
7890 Diag(MD
->getLocation(), diag::note_deleted_type_mismatch
) << CSM
;
7891 } else if (ShouldDeleteSpecialMember(MD
, CSM
, nullptr,
7892 /*Diagnose*/ true) &&
7893 DefaultLoc
.isValid()) {
7894 Diag(DefaultLoc
, diag::note_replace_equals_default_to_delete
)
7895 << FixItHint::CreateReplacement(DefaultLoc
, "delete");
7898 if (ShouldDeleteForTypeMismatch
&& !HadError
) {
7899 Diag(MD
->getLocation(),
7900 diag::warn_cxx17_compat_defaulted_method_type_mismatch
) << CSM
;
7903 // C++11 [dcl.fct.def.default]p4:
7904 // [For a] user-provided explicitly-defaulted function [...] if such a
7905 // function is implicitly defined as deleted, the program is ill-formed.
7906 Diag(MD
->getLocation(), diag::err_out_of_line_default_deletes
) << CSM
;
7907 assert(!ShouldDeleteForTypeMismatch
&& "deleted non-first decl");
7908 ShouldDeleteSpecialMember(MD
, CSM
, nullptr, /*Diagnose*/true);
7917 /// Helper class for building and checking a defaulted comparison.
7919 /// Defaulted functions are built in two phases:
7921 /// * First, the set of operations that the function will perform are
7922 /// identified, and some of them are checked. If any of the checked
7923 /// operations is invalid in certain ways, the comparison function is
7924 /// defined as deleted and no body is built.
7925 /// * Then, if the function is not defined as deleted, the body is built.
7927 /// This is accomplished by performing two visitation steps over the eventual
7928 /// body of the function.
7929 template<typename Derived
, typename ResultList
, typename Result
,
7931 class DefaultedComparisonVisitor
{
7933 using DefaultedComparisonKind
= Sema::DefaultedComparisonKind
;
7935 DefaultedComparisonVisitor(Sema
&S
, CXXRecordDecl
*RD
, FunctionDecl
*FD
,
7936 DefaultedComparisonKind DCK
)
7937 : S(S
), RD(RD
), FD(FD
), DCK(DCK
) {
7938 if (auto *Info
= FD
->getDefaultedFunctionInfo()) {
7939 // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an
7940 // UnresolvedSet to avoid this copy.
7941 Fns
.assign(Info
->getUnqualifiedLookups().begin(),
7942 Info
->getUnqualifiedLookups().end());
7946 ResultList
visit() {
7947 // The type of an lvalue naming a parameter of this function.
7948 QualType ParamLvalType
=
7949 FD
->getParamDecl(0)->getType().getNonReferenceType();
7954 case DefaultedComparisonKind::None
:
7955 llvm_unreachable("not a defaulted comparison");
7957 case DefaultedComparisonKind::Equal
:
7958 case DefaultedComparisonKind::ThreeWay
:
7959 getDerived().visitSubobjects(Results
, RD
, ParamLvalType
.getQualifiers());
7962 case DefaultedComparisonKind::NotEqual
:
7963 case DefaultedComparisonKind::Relational
:
7964 Results
.add(getDerived().visitExpandedSubobject(
7965 ParamLvalType
, getDerived().getCompleteObject()));
7968 llvm_unreachable("");
7972 Derived
&getDerived() { return static_cast<Derived
&>(*this); }
7974 /// Visit the expanded list of subobjects of the given type, as specified in
7975 /// C++2a [class.compare.default].
7977 /// \return \c true if the ResultList object said we're done, \c false if not.
7978 bool visitSubobjects(ResultList
&Results
, CXXRecordDecl
*Record
,
7980 // C++2a [class.compare.default]p4:
7981 // The direct base class subobjects of C
7982 for (CXXBaseSpecifier
&Base
: Record
->bases())
7983 if (Results
.add(getDerived().visitSubobject(
7984 S
.Context
.getQualifiedType(Base
.getType(), Quals
),
7985 getDerived().getBase(&Base
))))
7988 // followed by the non-static data members of C
7989 for (FieldDecl
*Field
: Record
->fields()) {
7990 // C++23 [class.bit]p2:
7991 // Unnamed bit-fields are not members ...
7992 if (Field
->isUnnamedBitfield())
7994 // Recursively expand anonymous structs.
7995 if (Field
->isAnonymousStructOrUnion()) {
7996 if (visitSubobjects(Results
, Field
->getType()->getAsCXXRecordDecl(),
8002 // Figure out the type of an lvalue denoting this field.
8003 Qualifiers FieldQuals
= Quals
;
8004 if (Field
->isMutable())
8005 FieldQuals
.removeConst();
8006 QualType FieldType
=
8007 S
.Context
.getQualifiedType(Field
->getType(), FieldQuals
);
8009 if (Results
.add(getDerived().visitSubobject(
8010 FieldType
, getDerived().getField(Field
))))
8014 // form a list of subobjects.
8018 Result
visitSubobject(QualType Type
, Subobject Subobj
) {
8019 // In that list, any subobject of array type is recursively expanded
8020 const ArrayType
*AT
= S
.Context
.getAsArrayType(Type
);
8021 if (auto *CAT
= dyn_cast_or_null
<ConstantArrayType
>(AT
))
8022 return getDerived().visitSubobjectArray(CAT
->getElementType(),
8023 CAT
->getSize(), Subobj
);
8024 return getDerived().visitExpandedSubobject(Type
, Subobj
);
8027 Result
visitSubobjectArray(QualType Type
, const llvm::APInt
&Size
,
8029 return getDerived().visitSubobject(Type
, Subobj
);
8036 DefaultedComparisonKind DCK
;
8037 UnresolvedSet
<16> Fns
;
8040 /// Information about a defaulted comparison, as determined by
8041 /// DefaultedComparisonAnalyzer.
8042 struct DefaultedComparisonInfo
{
8043 bool Deleted
= false;
8044 bool Constexpr
= true;
8045 ComparisonCategoryType Category
= ComparisonCategoryType::StrongOrdering
;
8047 static DefaultedComparisonInfo
deleted() {
8048 DefaultedComparisonInfo Deleted
;
8049 Deleted
.Deleted
= true;
8053 bool add(const DefaultedComparisonInfo
&R
) {
8054 Deleted
|= R
.Deleted
;
8055 Constexpr
&= R
.Constexpr
;
8056 Category
= commonComparisonType(Category
, R
.Category
);
8061 /// An element in the expanded list of subobjects of a defaulted comparison, as
8062 /// specified in C++2a [class.compare.default]p4.
8063 struct DefaultedComparisonSubobject
{
8064 enum { CompleteObject
, Member
, Base
} Kind
;
8069 /// A visitor over the notional body of a defaulted comparison that determines
8070 /// whether that body would be deleted or constexpr.
8071 class DefaultedComparisonAnalyzer
8072 : public DefaultedComparisonVisitor
<DefaultedComparisonAnalyzer
,
8073 DefaultedComparisonInfo
,
8074 DefaultedComparisonInfo
,
8075 DefaultedComparisonSubobject
> {
8077 enum DiagnosticKind
{ NoDiagnostics
, ExplainDeleted
, ExplainConstexpr
};
8080 DiagnosticKind Diagnose
;
8083 using Base
= DefaultedComparisonVisitor
;
8084 using Result
= DefaultedComparisonInfo
;
8085 using Subobject
= DefaultedComparisonSubobject
;
8089 DefaultedComparisonAnalyzer(Sema
&S
, CXXRecordDecl
*RD
, FunctionDecl
*FD
,
8090 DefaultedComparisonKind DCK
,
8091 DiagnosticKind Diagnose
= NoDiagnostics
)
8092 : Base(S
, RD
, FD
, DCK
), Diagnose(Diagnose
) {}
8095 if ((DCK
== DefaultedComparisonKind::Equal
||
8096 DCK
== DefaultedComparisonKind::ThreeWay
) &&
8097 RD
->hasVariantMembers()) {
8098 // C++2a [class.compare.default]p2 [P2002R0]:
8099 // A defaulted comparison operator function for class C is defined as
8100 // deleted if [...] C has variant members.
8101 if (Diagnose
== ExplainDeleted
) {
8102 S
.Diag(FD
->getLocation(), diag::note_defaulted_comparison_union
)
8103 << FD
<< RD
->isUnion() << RD
;
8105 return Result::deleted();
8108 return Base::visit();
8112 Subobject
getCompleteObject() {
8113 return Subobject
{Subobject::CompleteObject
, RD
, FD
->getLocation()};
8116 Subobject
getBase(CXXBaseSpecifier
*Base
) {
8117 return Subobject
{Subobject::Base
, Base
->getType()->getAsCXXRecordDecl(),
8118 Base
->getBaseTypeLoc()};
8121 Subobject
getField(FieldDecl
*Field
) {
8122 return Subobject
{Subobject::Member
, Field
, Field
->getLocation()};
8125 Result
visitExpandedSubobject(QualType Type
, Subobject Subobj
) {
8126 // C++2a [class.compare.default]p2 [P2002R0]:
8127 // A defaulted <=> or == operator function for class C is defined as
8128 // deleted if any non-static data member of C is of reference type
8129 if (Type
->isReferenceType()) {
8130 if (Diagnose
== ExplainDeleted
) {
8131 S
.Diag(Subobj
.Loc
, diag::note_defaulted_comparison_reference_member
)
8134 return Result::deleted();
8137 // [...] Let xi be an lvalue denoting the ith element [...]
8138 OpaqueValueExpr
Xi(FD
->getLocation(), Type
, VK_LValue
);
8139 Expr
*Args
[] = {&Xi
, &Xi
};
8141 // All operators start by trying to apply that same operator recursively.
8142 OverloadedOperatorKind OO
= FD
->getOverloadedOperator();
8143 assert(OO
!= OO_None
&& "not an overloaded operator!");
8144 return visitBinaryOperator(OO
, Args
, Subobj
);
8148 visitBinaryOperator(OverloadedOperatorKind OO
, ArrayRef
<Expr
*> Args
,
8150 OverloadCandidateSet
*SpaceshipCandidates
= nullptr) {
8151 // Note that there is no need to consider rewritten candidates here if
8152 // we've already found there is no viable 'operator<=>' candidate (and are
8153 // considering synthesizing a '<=>' from '==' and '<').
8154 OverloadCandidateSet
CandidateSet(
8155 FD
->getLocation(), OverloadCandidateSet::CSK_Operator
,
8156 OverloadCandidateSet::OperatorRewriteInfo(
8157 OO
, FD
->getLocation(),
8158 /*AllowRewrittenCandidates=*/!SpaceshipCandidates
));
8160 /// C++2a [class.compare.default]p1 [P2002R0]:
8161 /// [...] the defaulted function itself is never a candidate for overload
8162 /// resolution [...]
8163 CandidateSet
.exclude(FD
);
8165 if (Args
[0]->getType()->isOverloadableType())
8166 S
.LookupOverloadedBinOp(CandidateSet
, OO
, Fns
, Args
);
8168 // FIXME: We determine whether this is a valid expression by checking to
8169 // see if there's a viable builtin operator candidate for it. That isn't
8170 // really what the rules ask us to do, but should give the right results.
8171 S
.AddBuiltinOperatorCandidates(OO
, FD
->getLocation(), Args
, CandidateSet
);
8175 OverloadCandidateSet::iterator Best
;
8176 switch (CandidateSet
.BestViableFunction(S
, FD
->getLocation(), Best
)) {
8178 // C++2a [class.compare.secondary]p2 [P2002R0]:
8179 // The operator function [...] is defined as deleted if [...] the
8180 // candidate selected by overload resolution is not a rewritten
8182 if ((DCK
== DefaultedComparisonKind::NotEqual
||
8183 DCK
== DefaultedComparisonKind::Relational
) &&
8184 !Best
->RewriteKind
) {
8185 if (Diagnose
== ExplainDeleted
) {
8186 if (Best
->Function
) {
8187 S
.Diag(Best
->Function
->getLocation(),
8188 diag::note_defaulted_comparison_not_rewritten_callee
)
8191 assert(Best
->Conversions
.size() == 2 &&
8192 Best
->Conversions
[0].isUserDefined() &&
8193 "non-user-defined conversion from class to built-in "
8195 S
.Diag(Best
->Conversions
[0]
8196 .UserDefined
.FoundConversionFunction
.getDecl()
8198 diag::note_defaulted_comparison_not_rewritten_conversion
)
8202 return Result::deleted();
8205 // Throughout C++2a [class.compare]: if overload resolution does not
8206 // result in a usable function, the candidate function is defined as
8207 // deleted. This requires that we selected an accessible function.
8209 // Note that this only considers the access of the function when named
8210 // within the type of the subobject, and not the access path for any
8211 // derived-to-base conversion.
8212 CXXRecordDecl
*ArgClass
= Args
[0]->getType()->getAsCXXRecordDecl();
8213 if (ArgClass
&& Best
->FoundDecl
.getDecl() &&
8214 Best
->FoundDecl
.getDecl()->isCXXClassMember()) {
8215 QualType ObjectType
= Subobj
.Kind
== Subobject::Member
8216 ? Args
[0]->getType()
8217 : S
.Context
.getRecordType(RD
);
8218 if (!S
.isMemberAccessibleForDeletion(
8219 ArgClass
, Best
->FoundDecl
, ObjectType
, Subobj
.Loc
,
8220 Diagnose
== ExplainDeleted
8221 ? S
.PDiag(diag::note_defaulted_comparison_inaccessible
)
8222 << FD
<< Subobj
.Kind
<< Subobj
.Decl
8224 return Result::deleted();
8227 bool NeedsDeducing
=
8228 OO
== OO_Spaceship
&& FD
->getReturnType()->isUndeducedAutoType();
8230 if (FunctionDecl
*BestFD
= Best
->Function
) {
8231 // C++2a [class.compare.default]p3 [P2002R0]:
8232 // A defaulted comparison function is constexpr-compatible if
8233 // [...] no overlod resolution performed [...] results in a
8234 // non-constexpr function.
8235 assert(!BestFD
->isDeleted() && "wrong overload resolution result");
8236 // If it's not constexpr, explain why not.
8237 if (Diagnose
== ExplainConstexpr
&& !BestFD
->isConstexpr()) {
8238 if (Subobj
.Kind
!= Subobject::CompleteObject
)
8239 S
.Diag(Subobj
.Loc
, diag::note_defaulted_comparison_not_constexpr
)
8240 << Subobj
.Kind
<< Subobj
.Decl
;
8241 S
.Diag(BestFD
->getLocation(),
8242 diag::note_defaulted_comparison_not_constexpr_here
);
8243 // Bail out after explaining; we don't want any more notes.
8244 return Result::deleted();
8246 R
.Constexpr
&= BestFD
->isConstexpr();
8248 if (NeedsDeducing
) {
8249 // If any callee has an undeduced return type, deduce it now.
8250 // FIXME: It's not clear how a failure here should be handled. For
8251 // now, we produce an eager diagnostic, because that is forward
8252 // compatible with most (all?) other reasonable options.
8253 if (BestFD
->getReturnType()->isUndeducedType() &&
8254 S
.DeduceReturnType(BestFD
, FD
->getLocation(),
8255 /*Diagnose=*/false)) {
8256 // Don't produce a duplicate error when asked to explain why the
8257 // comparison is deleted: we diagnosed that when initially checking
8258 // the defaulted operator.
8259 if (Diagnose
== NoDiagnostics
) {
8262 diag::err_defaulted_comparison_cannot_deduce_undeduced_auto
)
8263 << Subobj
.Kind
<< Subobj
.Decl
;
8266 diag::note_defaulted_comparison_cannot_deduce_undeduced_auto
)
8267 << Subobj
.Kind
<< Subobj
.Decl
;
8268 S
.Diag(BestFD
->getLocation(),
8269 diag::note_defaulted_comparison_cannot_deduce_callee
)
8270 << Subobj
.Kind
<< Subobj
.Decl
;
8272 return Result::deleted();
8274 auto *Info
= S
.Context
.CompCategories
.lookupInfoForType(
8275 BestFD
->getCallResultType());
8277 if (Diagnose
== ExplainDeleted
) {
8278 S
.Diag(Subobj
.Loc
, diag::note_defaulted_comparison_cannot_deduce
)
8279 << Subobj
.Kind
<< Subobj
.Decl
8280 << BestFD
->getCallResultType().withoutLocalFastQualifiers();
8281 S
.Diag(BestFD
->getLocation(),
8282 diag::note_defaulted_comparison_cannot_deduce_callee
)
8283 << Subobj
.Kind
<< Subobj
.Decl
;
8285 return Result::deleted();
8287 R
.Category
= Info
->Kind
;
8290 QualType T
= Best
->BuiltinParamTypes
[0];
8291 assert(T
== Best
->BuiltinParamTypes
[1] &&
8292 "builtin comparison for different types?");
8293 assert(Best
->BuiltinParamTypes
[2].isNull() &&
8294 "invalid builtin comparison");
8296 if (NeedsDeducing
) {
8297 std::optional
<ComparisonCategoryType
> Cat
=
8298 getComparisonCategoryForBuiltinCmp(T
);
8299 assert(Cat
&& "no category for builtin comparison?");
8304 // Note that we might be rewriting to a different operator. That call is
8305 // not considered until we come to actually build the comparison function.
8310 if (Diagnose
== ExplainDeleted
) {
8312 if (FD
->getOverloadedOperator() == OO_Spaceship
&& OO
!= OO_Spaceship
)
8313 Kind
= OO
== OO_EqualEqual
? 1 : 2;
8314 CandidateSet
.NoteCandidates(
8315 PartialDiagnosticAt(
8316 Subobj
.Loc
, S
.PDiag(diag::note_defaulted_comparison_ambiguous
)
8317 << FD
<< Kind
<< Subobj
.Kind
<< Subobj
.Decl
),
8318 S
, OCD_AmbiguousCandidates
, Args
);
8320 R
= Result::deleted();
8324 if (Diagnose
== ExplainDeleted
) {
8325 if ((DCK
== DefaultedComparisonKind::NotEqual
||
8326 DCK
== DefaultedComparisonKind::Relational
) &&
8327 !Best
->RewriteKind
) {
8328 S
.Diag(Best
->Function
->getLocation(),
8329 diag::note_defaulted_comparison_not_rewritten_callee
)
8333 diag::note_defaulted_comparison_calls_deleted
)
8334 << FD
<< Subobj
.Kind
<< Subobj
.Decl
;
8335 S
.NoteDeletedFunction(Best
->Function
);
8338 R
= Result::deleted();
8341 case OR_No_Viable_Function
:
8342 // If there's no usable candidate, we're done unless we can rewrite a
8343 // '<=>' in terms of '==' and '<'.
8344 if (OO
== OO_Spaceship
&&
8345 S
.Context
.CompCategories
.lookupInfoForType(FD
->getReturnType())) {
8346 // For any kind of comparison category return type, we need a usable
8347 // '==' and a usable '<'.
8348 if (!R
.add(visitBinaryOperator(OO_EqualEqual
, Args
, Subobj
,
8350 R
.add(visitBinaryOperator(OO_Less
, Args
, Subobj
, &CandidateSet
));
8354 if (Diagnose
== ExplainDeleted
) {
8355 S
.Diag(Subobj
.Loc
, diag::note_defaulted_comparison_no_viable_function
)
8356 << FD
<< (OO
== OO_EqualEqual
|| OO
== OO_ExclaimEqual
)
8357 << Subobj
.Kind
<< Subobj
.Decl
;
8359 // For a three-way comparison, list both the candidates for the
8360 // original operator and the candidates for the synthesized operator.
8361 if (SpaceshipCandidates
) {
8362 SpaceshipCandidates
->NoteCandidates(
8364 SpaceshipCandidates
->CompleteCandidates(S
, OCD_AllCandidates
,
8365 Args
, FD
->getLocation()));
8367 diag::note_defaulted_comparison_no_viable_function_synthesized
)
8368 << (OO
== OO_EqualEqual
? 0 : 1);
8371 CandidateSet
.NoteCandidates(
8373 CandidateSet
.CompleteCandidates(S
, OCD_AllCandidates
, Args
,
8374 FD
->getLocation()));
8376 R
= Result::deleted();
8384 /// A list of statements.
8385 struct StmtListResult
{
8386 bool IsInvalid
= false;
8387 llvm::SmallVector
<Stmt
*, 16> Stmts
;
8389 bool add(const StmtResult
&S
) {
8390 IsInvalid
|= S
.isInvalid();
8393 Stmts
.push_back(S
.get());
8398 /// A visitor over the notional body of a defaulted comparison that synthesizes
8399 /// the actual body.
8400 class DefaultedComparisonSynthesizer
8401 : public DefaultedComparisonVisitor
<DefaultedComparisonSynthesizer
,
8402 StmtListResult
, StmtResult
,
8403 std::pair
<ExprResult
, ExprResult
>> {
8405 unsigned ArrayDepth
= 0;
8408 using Base
= DefaultedComparisonVisitor
;
8409 using ExprPair
= std::pair
<ExprResult
, ExprResult
>;
8413 DefaultedComparisonSynthesizer(Sema
&S
, CXXRecordDecl
*RD
, FunctionDecl
*FD
,
8414 DefaultedComparisonKind DCK
,
8415 SourceLocation BodyLoc
)
8416 : Base(S
, RD
, FD
, DCK
), Loc(BodyLoc
) {}
8418 /// Build a suitable function body for this defaulted comparison operator.
8419 StmtResult
build() {
8420 Sema::CompoundScopeRAII
CompoundScope(S
);
8422 StmtListResult Stmts
= visit();
8423 if (Stmts
.IsInvalid
)
8428 case DefaultedComparisonKind::None
:
8429 llvm_unreachable("not a defaulted comparison");
8431 case DefaultedComparisonKind::Equal
: {
8432 // C++2a [class.eq]p3:
8433 // [...] compar[e] the corresponding elements [...] until the first
8434 // index i where xi == yi yields [...] false. If no such index exists,
8435 // V is true. Otherwise, V is false.
8437 // Join the comparisons with '&&'s and return the result. Use a right
8438 // fold (traversing the conditions right-to-left), because that
8439 // short-circuits more naturally.
8440 auto OldStmts
= std::move(Stmts
.Stmts
);
8441 Stmts
.Stmts
.clear();
8442 ExprResult CmpSoFar
;
8443 // Finish a particular comparison chain.
8444 auto FinishCmp
= [&] {
8445 if (Expr
*Prior
= CmpSoFar
.get()) {
8446 // Convert the last expression to 'return ...;'
8447 if (RetVal
.isUnset() && Stmts
.Stmts
.empty())
8449 // Convert any prior comparison to 'if (!(...)) return false;'
8450 else if (Stmts
.add(buildIfNotCondReturnFalse(Prior
)))
8452 CmpSoFar
= ExprResult();
8456 for (Stmt
*EAsStmt
: llvm::reverse(OldStmts
)) {
8457 Expr
*E
= dyn_cast
<Expr
>(EAsStmt
);
8459 // Found an array comparison.
8460 if (FinishCmp() || Stmts
.add(EAsStmt
))
8465 if (CmpSoFar
.isUnset()) {
8469 CmpSoFar
= S
.CreateBuiltinBinOp(Loc
, BO_LAnd
, E
, CmpSoFar
.get());
8470 if (CmpSoFar
.isInvalid())
8475 std::reverse(Stmts
.Stmts
.begin(), Stmts
.Stmts
.end());
8476 // If no such index exists, V is true.
8477 if (RetVal
.isUnset())
8478 RetVal
= S
.ActOnCXXBoolLiteral(Loc
, tok::kw_true
);
8482 case DefaultedComparisonKind::ThreeWay
: {
8483 // Per C++2a [class.spaceship]p3, as a fallback add:
8484 // return static_cast<R>(std::strong_ordering::equal);
8485 QualType StrongOrdering
= S
.CheckComparisonCategoryType(
8486 ComparisonCategoryType::StrongOrdering
, Loc
,
8487 Sema::ComparisonCategoryUsage::DefaultedOperator
);
8488 if (StrongOrdering
.isNull())
8490 VarDecl
*EqualVD
= S
.Context
.CompCategories
.getInfoForType(StrongOrdering
)
8491 .getValueInfo(ComparisonCategoryResult::Equal
)
8493 RetVal
= getDecl(EqualVD
);
8494 if (RetVal
.isInvalid())
8496 RetVal
= buildStaticCastToR(RetVal
.get());
8500 case DefaultedComparisonKind::NotEqual
:
8501 case DefaultedComparisonKind::Relational
:
8502 RetVal
= cast
<Expr
>(Stmts
.Stmts
.pop_back_val());
8506 // Build the final return statement.
8507 if (RetVal
.isInvalid())
8509 StmtResult ReturnStmt
= S
.BuildReturnStmt(Loc
, RetVal
.get());
8510 if (ReturnStmt
.isInvalid())
8512 Stmts
.Stmts
.push_back(ReturnStmt
.get());
8514 return S
.ActOnCompoundStmt(Loc
, Loc
, Stmts
.Stmts
, /*IsStmtExpr=*/false);
8518 ExprResult
getDecl(ValueDecl
*VD
) {
8519 return S
.BuildDeclarationNameExpr(
8520 CXXScopeSpec(), DeclarationNameInfo(VD
->getDeclName(), Loc
), VD
);
8523 ExprResult
getParam(unsigned I
) {
8524 ParmVarDecl
*PD
= FD
->getParamDecl(I
);
8528 ExprPair
getCompleteObject() {
8531 if (const auto *MD
= dyn_cast
<CXXMethodDecl
>(FD
);
8532 MD
&& MD
->isImplicitObjectMemberFunction()) {
8534 LHS
= S
.ActOnCXXThis(Loc
);
8535 if (!LHS
.isInvalid())
8536 LHS
= S
.CreateBuiltinUnaryOp(Loc
, UO_Deref
, LHS
.get());
8538 LHS
= getParam(Param
++);
8540 ExprResult RHS
= getParam(Param
++);
8541 assert(Param
== FD
->getNumParams());
8545 ExprPair
getBase(CXXBaseSpecifier
*Base
) {
8546 ExprPair Obj
= getCompleteObject();
8547 if (Obj
.first
.isInvalid() || Obj
.second
.isInvalid())
8548 return {ExprError(), ExprError()};
8549 CXXCastPath Path
= {Base
};
8550 return {S
.ImpCastExprToType(Obj
.first
.get(), Base
->getType(),
8551 CK_DerivedToBase
, VK_LValue
, &Path
),
8552 S
.ImpCastExprToType(Obj
.second
.get(), Base
->getType(),
8553 CK_DerivedToBase
, VK_LValue
, &Path
)};
8556 ExprPair
getField(FieldDecl
*Field
) {
8557 ExprPair Obj
= getCompleteObject();
8558 if (Obj
.first
.isInvalid() || Obj
.second
.isInvalid())
8559 return {ExprError(), ExprError()};
8561 DeclAccessPair Found
= DeclAccessPair::make(Field
, Field
->getAccess());
8562 DeclarationNameInfo
NameInfo(Field
->getDeclName(), Loc
);
8563 return {S
.BuildFieldReferenceExpr(Obj
.first
.get(), /*IsArrow=*/false, Loc
,
8564 CXXScopeSpec(), Field
, Found
, NameInfo
),
8565 S
.BuildFieldReferenceExpr(Obj
.second
.get(), /*IsArrow=*/false, Loc
,
8566 CXXScopeSpec(), Field
, Found
, NameInfo
)};
8569 // FIXME: When expanding a subobject, register a note in the code synthesis
8570 // stack to say which subobject we're comparing.
8572 StmtResult
buildIfNotCondReturnFalse(ExprResult Cond
) {
8573 if (Cond
.isInvalid())
8576 ExprResult NotCond
= S
.CreateBuiltinUnaryOp(Loc
, UO_LNot
, Cond
.get());
8577 if (NotCond
.isInvalid())
8580 ExprResult False
= S
.ActOnCXXBoolLiteral(Loc
, tok::kw_false
);
8581 assert(!False
.isInvalid() && "should never fail");
8582 StmtResult ReturnFalse
= S
.BuildReturnStmt(Loc
, False
.get());
8583 if (ReturnFalse
.isInvalid())
8586 return S
.ActOnIfStmt(Loc
, IfStatementKind::Ordinary
, Loc
, nullptr,
8587 S
.ActOnCondition(nullptr, Loc
, NotCond
.get(),
8588 Sema::ConditionKind::Boolean
),
8589 Loc
, ReturnFalse
.get(), SourceLocation(), nullptr);
8592 StmtResult
visitSubobjectArray(QualType Type
, llvm::APInt Size
,
8594 QualType SizeType
= S
.Context
.getSizeType();
8595 Size
= Size
.zextOrTrunc(S
.Context
.getTypeSize(SizeType
));
8597 // Build 'size_t i$n = 0'.
8598 IdentifierInfo
*IterationVarName
= nullptr;
8601 llvm::raw_svector_ostream
OS(Str
);
8602 OS
<< "i" << ArrayDepth
;
8603 IterationVarName
= &S
.Context
.Idents
.get(OS
.str());
8605 VarDecl
*IterationVar
= VarDecl::Create(
8606 S
.Context
, S
.CurContext
, Loc
, Loc
, IterationVarName
, SizeType
,
8607 S
.Context
.getTrivialTypeSourceInfo(SizeType
, Loc
), SC_None
);
8608 llvm::APInt
Zero(S
.Context
.getTypeSize(SizeType
), 0);
8609 IterationVar
->setInit(
8610 IntegerLiteral::Create(S
.Context
, Zero
, SizeType
, Loc
));
8611 Stmt
*Init
= new (S
.Context
) DeclStmt(DeclGroupRef(IterationVar
), Loc
, Loc
);
8613 auto IterRef
= [&] {
8614 ExprResult Ref
= S
.BuildDeclarationNameExpr(
8615 CXXScopeSpec(), DeclarationNameInfo(IterationVarName
, Loc
),
8617 assert(!Ref
.isInvalid() && "can't reference our own variable?");
8621 // Build 'i$n != Size'.
8622 ExprResult Cond
= S
.CreateBuiltinBinOp(
8623 Loc
, BO_NE
, IterRef(),
8624 IntegerLiteral::Create(S
.Context
, Size
, SizeType
, Loc
));
8625 assert(!Cond
.isInvalid() && "should never fail");
8628 ExprResult Inc
= S
.CreateBuiltinUnaryOp(Loc
, UO_PreInc
, IterRef());
8629 assert(!Inc
.isInvalid() && "should never fail");
8631 // Build 'a[i$n]' and 'b[i$n]'.
8632 auto Index
= [&](ExprResult E
) {
8635 return S
.CreateBuiltinArraySubscriptExpr(E
.get(), Loc
, IterRef(), Loc
);
8637 Subobj
.first
= Index(Subobj
.first
);
8638 Subobj
.second
= Index(Subobj
.second
);
8640 // Compare the array elements.
8642 StmtResult Substmt
= visitSubobject(Type
, Subobj
);
8645 if (Substmt
.isInvalid())
8648 // For the inner level of an 'operator==', build 'if (!cmp) return false;'.
8649 // For outer levels or for an 'operator<=>' we already have a suitable
8650 // statement that returns as necessary.
8651 if (Expr
*ElemCmp
= dyn_cast
<Expr
>(Substmt
.get())) {
8652 assert(DCK
== DefaultedComparisonKind::Equal
&&
8653 "should have non-expression statement");
8654 Substmt
= buildIfNotCondReturnFalse(ElemCmp
);
8655 if (Substmt
.isInvalid())
8659 // Build 'for (...) ...'
8660 return S
.ActOnForStmt(Loc
, Loc
, Init
,
8661 S
.ActOnCondition(nullptr, Loc
, Cond
.get(),
8662 Sema::ConditionKind::Boolean
),
8663 S
.MakeFullDiscardedValueExpr(Inc
.get()), Loc
,
8667 StmtResult
visitExpandedSubobject(QualType Type
, ExprPair Obj
) {
8668 if (Obj
.first
.isInvalid() || Obj
.second
.isInvalid())
8671 OverloadedOperatorKind OO
= FD
->getOverloadedOperator();
8672 BinaryOperatorKind Opc
= BinaryOperator::getOverloadedOpcode(OO
);
8674 if (Type
->isOverloadableType())
8675 Op
= S
.CreateOverloadedBinOp(Loc
, Opc
, Fns
, Obj
.first
.get(),
8676 Obj
.second
.get(), /*PerformADL=*/true,
8677 /*AllowRewrittenCandidates=*/true, FD
);
8679 Op
= S
.CreateBuiltinBinOp(Loc
, Opc
, Obj
.first
.get(), Obj
.second
.get());
8684 case DefaultedComparisonKind::None
:
8685 llvm_unreachable("not a defaulted comparison");
8687 case DefaultedComparisonKind::Equal
:
8688 // Per C++2a [class.eq]p2, each comparison is individually contextually
8689 // converted to bool.
8690 Op
= S
.PerformContextuallyConvertToBool(Op
.get());
8695 case DefaultedComparisonKind::ThreeWay
: {
8696 // Per C++2a [class.spaceship]p3, form:
8697 // if (R cmp = static_cast<R>(op); cmp != 0)
8699 QualType R
= FD
->getReturnType();
8700 Op
= buildStaticCastToR(Op
.get());
8705 IdentifierInfo
*Name
= &S
.Context
.Idents
.get("cmp");
8707 VarDecl::Create(S
.Context
, S
.CurContext
, Loc
, Loc
, Name
, R
,
8708 S
.Context
.getTrivialTypeSourceInfo(R
, Loc
), SC_None
);
8709 S
.AddInitializerToDecl(VD
, Op
.get(), /*DirectInit=*/false);
8710 Stmt
*InitStmt
= new (S
.Context
) DeclStmt(DeclGroupRef(VD
), Loc
, Loc
);
8713 ExprResult VDRef
= getDecl(VD
);
8714 if (VDRef
.isInvalid())
8716 llvm::APInt
ZeroVal(S
.Context
.getIntWidth(S
.Context
.IntTy
), 0);
8718 IntegerLiteral::Create(S
.Context
, ZeroVal
, S
.Context
.IntTy
, Loc
);
8720 if (VDRef
.get()->getType()->isOverloadableType())
8721 Comp
= S
.CreateOverloadedBinOp(Loc
, BO_NE
, Fns
, VDRef
.get(), Zero
, true,
8724 Comp
= S
.CreateBuiltinBinOp(Loc
, BO_NE
, VDRef
.get(), Zero
);
8725 if (Comp
.isInvalid())
8727 Sema::ConditionResult Cond
= S
.ActOnCondition(
8728 nullptr, Loc
, Comp
.get(), Sema::ConditionKind::Boolean
);
8729 if (Cond
.isInvalid())
8733 VDRef
= getDecl(VD
);
8734 if (VDRef
.isInvalid())
8736 StmtResult ReturnStmt
= S
.BuildReturnStmt(Loc
, VDRef
.get());
8737 if (ReturnStmt
.isInvalid())
8741 return S
.ActOnIfStmt(Loc
, IfStatementKind::Ordinary
, Loc
, InitStmt
, Cond
,
8742 Loc
, ReturnStmt
.get(),
8743 /*ElseLoc=*/SourceLocation(), /*Else=*/nullptr);
8746 case DefaultedComparisonKind::NotEqual
:
8747 case DefaultedComparisonKind::Relational
:
8748 // C++2a [class.compare.secondary]p2:
8749 // Otherwise, the operator function yields x @ y.
8752 llvm_unreachable("");
8755 /// Build "static_cast<R>(E)".
8756 ExprResult
buildStaticCastToR(Expr
*E
) {
8757 QualType R
= FD
->getReturnType();
8758 assert(!R
->isUndeducedType() && "type should have been deduced already");
8760 // Don't bother forming a no-op cast in the common case.
8761 if (E
->isPRValue() && S
.Context
.hasSameType(E
->getType(), R
))
8763 return S
.BuildCXXNamedCast(Loc
, tok::kw_static_cast
,
8764 S
.Context
.getTrivialTypeSourceInfo(R
, Loc
), E
,
8765 SourceRange(Loc
, Loc
), SourceRange(Loc
, Loc
));
8770 /// Perform the unqualified lookups that might be needed to form a defaulted
8771 /// comparison function for the given operator.
8772 static void lookupOperatorsForDefaultedComparison(Sema
&Self
, Scope
*S
,
8773 UnresolvedSetImpl
&Operators
,
8774 OverloadedOperatorKind Op
) {
8775 auto Lookup
= [&](OverloadedOperatorKind OO
) {
8776 Self
.LookupOverloadedOperatorName(OO
, S
, Operators
);
8779 // Every defaulted operator looks up itself.
8781 // ... and the rewritten form of itself, if any.
8782 if (OverloadedOperatorKind ExtraOp
= getRewrittenOverloadedOperator(Op
))
8785 // For 'operator<=>', we also form a 'cmp != 0' expression, and might
8786 // synthesize a three-way comparison from '<' and '=='. In a dependent
8787 // context, we also need to look up '==' in case we implicitly declare a
8788 // defaulted 'operator=='.
8789 if (Op
== OO_Spaceship
) {
8790 Lookup(OO_ExclaimEqual
);
8792 Lookup(OO_EqualEqual
);
8796 bool Sema::CheckExplicitlyDefaultedComparison(Scope
*S
, FunctionDecl
*FD
,
8797 DefaultedComparisonKind DCK
) {
8798 assert(DCK
!= DefaultedComparisonKind::None
&& "not a defaulted comparison");
8800 // Perform any unqualified lookups we're going to need to default this
8803 UnresolvedSet
<32> Operators
;
8804 lookupOperatorsForDefaultedComparison(*this, S
, Operators
,
8805 FD
->getOverloadedOperator());
8806 FD
->setDefaultedFunctionInfo(FunctionDecl::DefaultedFunctionInfo::Create(
8807 Context
, Operators
.pairs()));
8810 // C++2a [class.compare.default]p1:
8811 // A defaulted comparison operator function for some class C shall be a
8812 // non-template function declared in the member-specification of C that is
8813 // -- a non-static const non-volatile member of C having one parameter of
8814 // type const C& and either no ref-qualifier or the ref-qualifier &, or
8815 // -- a friend of C having two parameters of type const C& or two
8816 // parameters of type C.
8818 CXXRecordDecl
*RD
= dyn_cast
<CXXRecordDecl
>(FD
->getLexicalDeclContext());
8819 bool IsMethod
= isa
<CXXMethodDecl
>(FD
);
8821 auto *MD
= cast
<CXXMethodDecl
>(FD
);
8822 assert(!MD
->isStatic() && "comparison function cannot be a static member");
8824 if (MD
->getRefQualifier() == RQ_RValue
) {
8825 Diag(MD
->getLocation(), diag::err_ref_qualifier_comparison_operator
);
8827 // Remove the ref qualifier to recover.
8828 const auto *FPT
= MD
->getType()->castAs
<FunctionProtoType
>();
8829 FunctionProtoType::ExtProtoInfo EPI
= FPT
->getExtProtoInfo();
8830 EPI
.RefQualifier
= RQ_None
;
8831 MD
->setType(Context
.getFunctionType(FPT
->getReturnType(),
8832 FPT
->getParamTypes(), EPI
));
8835 // If we're out-of-class, this is the class we're comparing.
8837 RD
= MD
->getParent();
8838 QualType T
= MD
->getFunctionObjectParameterType();
8839 if (!T
.isConstQualified()) {
8840 SourceLocation Loc
, InsertLoc
;
8841 if (MD
->isExplicitObjectMemberFunction()) {
8842 Loc
= MD
->getParamDecl(0)->getBeginLoc();
8843 InsertLoc
= getLocForEndOfToken(
8844 MD
->getParamDecl(0)->getExplicitObjectParamThisLoc());
8846 Loc
= MD
->getLocation();
8847 if (FunctionTypeLoc Loc
= MD
->getFunctionTypeLoc())
8848 InsertLoc
= Loc
.getRParenLoc();
8850 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8851 // corresponding defaulted 'operator<=>' already.
8852 if (!MD
->isImplicit()) {
8853 Diag(Loc
, diag::err_defaulted_comparison_non_const
)
8854 << (int)DCK
<< FixItHint::CreateInsertion(InsertLoc
, " const");
8857 // Add the 'const' to the type to recover.
8858 const auto *FPT
= MD
->getType()->castAs
<FunctionProtoType
>();
8859 FunctionProtoType::ExtProtoInfo EPI
= FPT
->getExtProtoInfo();
8860 EPI
.TypeQuals
.addConst();
8861 MD
->setType(Context
.getFunctionType(FPT
->getReturnType(),
8862 FPT
->getParamTypes(), EPI
));
8865 if (MD
->isVolatile()) {
8866 Diag(MD
->getLocation(), diag::err_volatile_comparison_operator
);
8868 // Remove the 'volatile' from the type to recover.
8869 const auto *FPT
= MD
->getType()->castAs
<FunctionProtoType
>();
8870 FunctionProtoType::ExtProtoInfo EPI
= FPT
->getExtProtoInfo();
8871 EPI
.TypeQuals
.removeVolatile();
8872 MD
->setType(Context
.getFunctionType(FPT
->getReturnType(),
8873 FPT
->getParamTypes(), EPI
));
8877 if ((FD
->getNumParams() -
8878 (unsigned)FD
->hasCXXExplicitFunctionObjectParameter()) !=
8879 (IsMethod
? 1 : 2)) {
8880 // Let's not worry about using a variadic template pack here -- who would do
8882 Diag(FD
->getLocation(), diag::err_defaulted_comparison_num_args
)
8883 << int(IsMethod
) << int(DCK
);
8887 const ParmVarDecl
*KnownParm
= nullptr;
8888 for (const ParmVarDecl
*Param
: FD
->parameters()) {
8889 if (Param
->isExplicitObjectParameter())
8891 QualType ParmTy
= Param
->getType();
8895 // Is it `T const &`?
8896 bool Ok
= !IsMethod
;
8897 QualType ExpectedTy
;
8899 ExpectedTy
= Context
.getRecordType(RD
);
8900 if (auto *Ref
= CTy
->getAs
<ReferenceType
>()) {
8901 CTy
= Ref
->getPointeeType();
8903 ExpectedTy
.addConst();
8910 if (!RD
->isDependentType() && !Context
.hasSameType(CTy
, ExpectedTy
))
8912 } else if (auto *CRD
= CTy
->getAsRecordDecl()) {
8913 RD
= cast
<CXXRecordDecl
>(CRD
);
8921 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8922 // corresponding defaulted 'operator<=>' already.
8923 if (!FD
->isImplicit()) {
8925 QualType PlainTy
= Context
.getRecordType(RD
);
8927 Context
.getLValueReferenceType(PlainTy
.withConst());
8928 Diag(FD
->getLocation(), diag::err_defaulted_comparison_param
)
8929 << int(DCK
) << ParmTy
<< RefTy
<< int(!IsMethod
) << PlainTy
8930 << Param
->getSourceRange();
8932 assert(!IsMethod
&& "should know expected type for method");
8933 Diag(FD
->getLocation(),
8934 diag::err_defaulted_comparison_param_unknown
)
8935 << int(DCK
) << ParmTy
<< Param
->getSourceRange();
8940 } else if (!Context
.hasSameType(KnownParm
->getType(), ParmTy
)) {
8941 Diag(FD
->getLocation(), diag::err_defaulted_comparison_param_mismatch
)
8942 << int(DCK
) << KnownParm
->getType() << KnownParm
->getSourceRange()
8943 << ParmTy
<< Param
->getSourceRange();
8948 assert(RD
&& "must have determined class");
8950 } else if (isa
<CXXRecordDecl
>(FD
->getLexicalDeclContext())) {
8951 // In-class, must be a friend decl.
8952 assert(FD
->getFriendObjectKind() && "expected a friend declaration");
8954 // Out of class, require the defaulted comparison to be a friend (of a
8956 if (RequireCompleteType(FD
->getLocation(), Context
.getRecordType(RD
),
8957 diag::err_defaulted_comparison_not_friend
, int(DCK
),
8961 if (llvm::none_of(RD
->friends(), [&](const FriendDecl
*F
) {
8962 return FD
->getCanonicalDecl() ==
8963 F
->getFriendDecl()->getCanonicalDecl();
8965 Diag(FD
->getLocation(), diag::err_defaulted_comparison_not_friend
)
8966 << int(DCK
) << int(0) << RD
;
8967 Diag(RD
->getCanonicalDecl()->getLocation(), diag::note_declared_at
);
8972 // C++2a [class.eq]p1, [class.rel]p1:
8973 // A [defaulted comparison other than <=>] shall have a declared return
8975 if (DCK
!= DefaultedComparisonKind::ThreeWay
&&
8976 !FD
->getDeclaredReturnType()->isDependentType() &&
8977 !Context
.hasSameType(FD
->getDeclaredReturnType(), Context
.BoolTy
)) {
8978 Diag(FD
->getLocation(), diag::err_defaulted_comparison_return_type_not_bool
)
8979 << (int)DCK
<< FD
->getDeclaredReturnType() << Context
.BoolTy
8980 << FD
->getReturnTypeSourceRange();
8983 // C++2a [class.spaceship]p2 [P2002R0]:
8984 // Let R be the declared return type [...]. If R is auto, [...]. Otherwise,
8985 // R shall not contain a placeholder type.
8986 if (QualType RT
= FD
->getDeclaredReturnType();
8987 DCK
== DefaultedComparisonKind::ThreeWay
&&
8988 RT
->getContainedDeducedType() &&
8989 (!Context
.hasSameType(RT
, Context
.getAutoDeductType()) ||
8990 RT
->getContainedAutoType()->isConstrained())) {
8991 Diag(FD
->getLocation(),
8992 diag::err_defaulted_comparison_deduced_return_type_not_auto
)
8993 << (int)DCK
<< FD
->getDeclaredReturnType() << Context
.AutoDeductTy
8994 << FD
->getReturnTypeSourceRange();
8998 // For a defaulted function in a dependent class, defer all remaining checks
8999 // until instantiation.
9000 if (RD
->isDependentType())
9003 // Determine whether the function should be defined as deleted.
9004 DefaultedComparisonInfo Info
=
9005 DefaultedComparisonAnalyzer(*this, RD
, FD
, DCK
).visit();
9007 bool First
= FD
== FD
->getCanonicalDecl();
9011 // C++11 [dcl.fct.def.default]p4:
9012 // [For a] user-provided explicitly-defaulted function [...] if such a
9013 // function is implicitly defined as deleted, the program is ill-formed.
9015 // This is really just a consequence of the general rule that you can
9016 // only delete a function on its first declaration.
9017 Diag(FD
->getLocation(), diag::err_non_first_default_compare_deletes
)
9018 << FD
->isImplicit() << (int)DCK
;
9019 DefaultedComparisonAnalyzer(*this, RD
, FD
, DCK
,
9020 DefaultedComparisonAnalyzer::ExplainDeleted
)
9024 if (isa
<CXXRecordDecl
>(FD
->getLexicalDeclContext())) {
9025 // C++20 [class.compare.default]p1:
9026 // [...] A definition of a comparison operator as defaulted that appears
9027 // in a class shall be the first declaration of that function.
9028 Diag(FD
->getLocation(), diag::err_non_first_default_compare_in_class
)
9030 Diag(FD
->getCanonicalDecl()->getLocation(),
9031 diag::note_previous_declaration
);
9036 // If we want to delete the function, then do so; there's nothing else to
9037 // check in that case.
9039 SetDeclDeleted(FD
, FD
->getLocation());
9040 if (!inTemplateInstantiation() && !FD
->isImplicit()) {
9041 Diag(FD
->getLocation(), diag::warn_defaulted_comparison_deleted
)
9043 DefaultedComparisonAnalyzer(*this, RD
, FD
, DCK
,
9044 DefaultedComparisonAnalyzer::ExplainDeleted
)
9046 if (FD
->getDefaultLoc().isValid())
9047 Diag(FD
->getDefaultLoc(), diag::note_replace_equals_default_to_delete
)
9048 << FixItHint::CreateReplacement(FD
->getDefaultLoc(), "delete");
9053 // C++2a [class.spaceship]p2:
9054 // The return type is deduced as the common comparison type of R0, R1, ...
9055 if (DCK
== DefaultedComparisonKind::ThreeWay
&&
9056 FD
->getDeclaredReturnType()->isUndeducedAutoType()) {
9057 SourceLocation RetLoc
= FD
->getReturnTypeSourceRange().getBegin();
9058 if (RetLoc
.isInvalid())
9059 RetLoc
= FD
->getBeginLoc();
9060 // FIXME: Should we really care whether we have the complete type and the
9061 // 'enumerator' constants here? A forward declaration seems sufficient.
9062 QualType Cat
= CheckComparisonCategoryType(
9063 Info
.Category
, RetLoc
, ComparisonCategoryUsage::DefaultedOperator
);
9066 Context
.adjustDeducedFunctionResultType(
9067 FD
, SubstAutoType(FD
->getDeclaredReturnType(), Cat
));
9070 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
9071 // An explicitly-defaulted function that is not defined as deleted may be
9072 // declared constexpr or consteval only if it is constexpr-compatible.
9073 // C++2a [class.compare.default]p3 [P2002R0]:
9074 // A defaulted comparison function is constexpr-compatible if it satisfies
9075 // the requirements for a constexpr function [...]
9076 // The only relevant requirements are that the parameter and return types are
9077 // literal types. The remaining conditions are checked by the analyzer.
9079 // We support P2448R2 in language modes earlier than C++23 as an extension.
9080 // The concept of constexpr-compatible was removed.
9081 // C++23 [dcl.fct.def.default]p3 [P2448R2]
9082 // A function explicitly defaulted on its first declaration is implicitly
9083 // inline, and is implicitly constexpr if it is constexpr-suitable.
9084 // C++23 [dcl.constexpr]p3
9085 // A function is constexpr-suitable if
9086 // - it is not a coroutine, and
9087 // - if the function is a constructor or destructor, its class does not
9088 // have any virtual base classes.
9089 if (FD
->isConstexpr()) {
9090 if (CheckConstexprReturnType(*this, FD
, CheckConstexprKind::Diagnose
) &&
9091 CheckConstexprParameterTypes(*this, FD
, CheckConstexprKind::Diagnose
) &&
9093 Diag(FD
->getBeginLoc(),
9094 getLangOpts().CPlusPlus23
9095 ? diag::warn_cxx23_compat_defaulted_comparison_constexpr_mismatch
9096 : diag::ext_defaulted_comparison_constexpr_mismatch
)
9097 << FD
->isImplicit() << (int)DCK
<< FD
->isConsteval();
9098 DefaultedComparisonAnalyzer(*this, RD
, FD
, DCK
,
9099 DefaultedComparisonAnalyzer::ExplainConstexpr
)
9104 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
9105 // If a constexpr-compatible function is explicitly defaulted on its first
9106 // declaration, it is implicitly considered to be constexpr.
9107 // FIXME: Only applying this to the first declaration seems problematic, as
9108 // simple reorderings can affect the meaning of the program.
9109 if (First
&& !FD
->isConstexpr() && Info
.Constexpr
)
9110 FD
->setConstexprKind(ConstexprSpecKind::Constexpr
);
9112 // C++2a [except.spec]p3:
9113 // If a declaration of a function does not have a noexcept-specifier
9114 // [and] is defaulted on its first declaration, [...] the exception
9115 // specification is as specified below
9116 if (FD
->getExceptionSpecType() == EST_None
) {
9117 auto *FPT
= FD
->getType()->castAs
<FunctionProtoType
>();
9118 FunctionProtoType::ExtProtoInfo EPI
= FPT
->getExtProtoInfo();
9119 EPI
.ExceptionSpec
.Type
= EST_Unevaluated
;
9120 EPI
.ExceptionSpec
.SourceDecl
= FD
;
9121 FD
->setType(Context
.getFunctionType(FPT
->getReturnType(),
9122 FPT
->getParamTypes(), EPI
));
9128 void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl
*RD
,
9129 FunctionDecl
*Spaceship
) {
9130 Sema::CodeSynthesisContext Ctx
;
9131 Ctx
.Kind
= Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison
;
9132 Ctx
.PointOfInstantiation
= Spaceship
->getEndLoc();
9133 Ctx
.Entity
= Spaceship
;
9134 pushCodeSynthesisContext(Ctx
);
9136 if (FunctionDecl
*EqualEqual
= SubstSpaceshipAsEqualEqual(RD
, Spaceship
))
9137 EqualEqual
->setImplicit();
9139 popCodeSynthesisContext();
9142 void Sema::DefineDefaultedComparison(SourceLocation UseLoc
, FunctionDecl
*FD
,
9143 DefaultedComparisonKind DCK
) {
9144 assert(FD
->isDefaulted() && !FD
->isDeleted() &&
9145 !FD
->doesThisDeclarationHaveABody());
9146 if (FD
->willHaveBody() || FD
->isInvalidDecl())
9149 SynthesizedFunctionScope
Scope(*this, FD
);
9151 // Add a context note for diagnostics produced after this point.
9152 Scope
.addContextNote(UseLoc
);
9155 // Build and set up the function body.
9156 // The first parameter has type maybe-ref-to maybe-const T, use that to get
9157 // the type of the class being compared.
9158 auto PT
= FD
->getParamDecl(0)->getType();
9159 CXXRecordDecl
*RD
= PT
.getNonReferenceType()->getAsCXXRecordDecl();
9160 SourceLocation BodyLoc
=
9161 FD
->getEndLoc().isValid() ? FD
->getEndLoc() : FD
->getLocation();
9163 DefaultedComparisonSynthesizer(*this, RD
, FD
, DCK
, BodyLoc
).build();
9164 if (Body
.isInvalid()) {
9165 FD
->setInvalidDecl();
9168 FD
->setBody(Body
.get());
9169 FD
->markUsed(Context
);
9172 // The exception specification is needed because we are defining the
9173 // function. Note that this will reuse the body we just built.
9174 ResolveExceptionSpec(UseLoc
, FD
->getType()->castAs
<FunctionProtoType
>());
9176 if (ASTMutationListener
*L
= getASTMutationListener())
9177 L
->CompletedImplicitDefinition(FD
);
9180 static Sema::ImplicitExceptionSpecification
9181 ComputeDefaultedComparisonExceptionSpec(Sema
&S
, SourceLocation Loc
,
9183 Sema::DefaultedComparisonKind DCK
) {
9184 ComputingExceptionSpec
CES(S
, FD
, Loc
);
9185 Sema::ImplicitExceptionSpecification
ExceptSpec(S
);
9187 if (FD
->isInvalidDecl())
9190 // The common case is that we just defined the comparison function. In that
9191 // case, just look at whether the body can throw.
9192 if (FD
->hasBody()) {
9193 ExceptSpec
.CalledStmt(FD
->getBody());
9195 // Otherwise, build a body so we can check it. This should ideally only
9196 // happen when we're not actually marking the function referenced. (This is
9197 // only really important for efficiency: we don't want to build and throw
9198 // away bodies for comparison functions more than we strictly need to.)
9200 // Pretend to synthesize the function body in an unevaluated context.
9201 // Note that we can't actually just go ahead and define the function here:
9202 // we are not permitted to mark its callees as referenced.
9203 Sema::SynthesizedFunctionScope
Scope(S
, FD
);
9204 EnterExpressionEvaluationContext
Context(
9205 S
, Sema::ExpressionEvaluationContext::Unevaluated
);
9207 CXXRecordDecl
*RD
= cast
<CXXRecordDecl
>(FD
->getLexicalParent());
9208 SourceLocation BodyLoc
=
9209 FD
->getEndLoc().isValid() ? FD
->getEndLoc() : FD
->getLocation();
9211 DefaultedComparisonSynthesizer(S
, RD
, FD
, DCK
, BodyLoc
).build();
9212 if (!Body
.isInvalid())
9213 ExceptSpec
.CalledStmt(Body
.get());
9215 // FIXME: Can we hold onto this body and just transform it to potentially
9216 // evaluated when we're asked to define the function rather than rebuilding
9217 // it? Either that, or we should only build the bits of the body that we
9218 // need (the expressions, not the statements).
9224 void Sema::CheckDelayedMemberExceptionSpecs() {
9225 decltype(DelayedOverridingExceptionSpecChecks
) Overriding
;
9226 decltype(DelayedEquivalentExceptionSpecChecks
) Equivalent
;
9228 std::swap(Overriding
, DelayedOverridingExceptionSpecChecks
);
9229 std::swap(Equivalent
, DelayedEquivalentExceptionSpecChecks
);
9231 // Perform any deferred checking of exception specifications for virtual
9233 for (auto &Check
: Overriding
)
9234 CheckOverridingFunctionExceptionSpec(Check
.first
, Check
.second
);
9236 // Perform any deferred checking of exception specifications for befriended
9238 for (auto &Check
: Equivalent
)
9239 CheckEquivalentExceptionSpec(Check
.second
, Check
.first
);
9243 /// CRTP base class for visiting operations performed by a special member
9244 /// function (or inherited constructor).
9245 template<typename Derived
>
9246 struct SpecialMemberVisitor
{
9249 Sema::CXXSpecialMember CSM
;
9250 Sema::InheritedConstructorInfo
*ICI
;
9252 // Properties of the special member, computed for convenience.
9253 bool IsConstructor
= false, IsAssignment
= false, ConstArg
= false;
9255 SpecialMemberVisitor(Sema
&S
, CXXMethodDecl
*MD
, Sema::CXXSpecialMember CSM
,
9256 Sema::InheritedConstructorInfo
*ICI
)
9257 : S(S
), MD(MD
), CSM(CSM
), ICI(ICI
) {
9259 case Sema::CXXDefaultConstructor
:
9260 case Sema::CXXCopyConstructor
:
9261 case Sema::CXXMoveConstructor
:
9262 IsConstructor
= true;
9264 case Sema::CXXCopyAssignment
:
9265 case Sema::CXXMoveAssignment
:
9266 IsAssignment
= true;
9268 case Sema::CXXDestructor
:
9270 case Sema::CXXInvalid
:
9271 llvm_unreachable("invalid special member kind");
9274 if (MD
->getNumExplicitParams()) {
9275 if (const ReferenceType
*RT
=
9276 MD
->getNonObjectParameter(0)->getType()->getAs
<ReferenceType
>())
9277 ConstArg
= RT
->getPointeeType().isConstQualified();
9281 Derived
&getDerived() { return static_cast<Derived
&>(*this); }
9283 /// Is this a "move" special member?
9284 bool isMove() const {
9285 return CSM
== Sema::CXXMoveConstructor
|| CSM
== Sema::CXXMoveAssignment
;
9288 /// Look up the corresponding special member in the given class.
9289 Sema::SpecialMemberOverloadResult
lookupIn(CXXRecordDecl
*Class
,
9290 unsigned Quals
, bool IsMutable
) {
9291 return lookupCallFromSpecialMember(S
, Class
, CSM
, Quals
,
9292 ConstArg
&& !IsMutable
);
9295 /// Look up the constructor for the specified base class to see if it's
9296 /// overridden due to this being an inherited constructor.
9297 Sema::SpecialMemberOverloadResult
lookupInheritedCtor(CXXRecordDecl
*Class
) {
9300 assert(CSM
== Sema::CXXDefaultConstructor
);
9302 cast
<CXXConstructorDecl
>(MD
)->getInheritedConstructor().getConstructor();
9303 if (auto *MD
= ICI
->findConstructorForBase(Class
, BaseCtor
).first
)
9308 /// A base or member subobject.
9309 typedef llvm::PointerUnion
<CXXBaseSpecifier
*, FieldDecl
*> Subobject
;
9311 /// Get the location to use for a subobject in diagnostics.
9312 static SourceLocation
getSubobjectLoc(Subobject Subobj
) {
9313 // FIXME: For an indirect virtual base, the direct base leading to
9314 // the indirect virtual base would be a more useful choice.
9315 if (auto *B
= Subobj
.dyn_cast
<CXXBaseSpecifier
*>())
9316 return B
->getBaseTypeLoc();
9318 return Subobj
.get
<FieldDecl
*>()->getLocation();
9322 /// Visit all non-virtual (direct) bases.
9323 VisitNonVirtualBases
,
9324 /// Visit all direct bases, virtual or not.
9326 /// Visit all non-virtual bases, and all virtual bases if the class
9327 /// is not abstract.
9328 VisitPotentiallyConstructedBases
,
9329 /// Visit all direct or virtual bases.
9333 // Visit the bases and members of the class.
9334 bool visit(BasesToVisit Bases
) {
9335 CXXRecordDecl
*RD
= MD
->getParent();
9337 if (Bases
== VisitPotentiallyConstructedBases
)
9338 Bases
= RD
->isAbstract() ? VisitNonVirtualBases
: VisitAllBases
;
9340 for (auto &B
: RD
->bases())
9341 if ((Bases
== VisitDirectBases
|| !B
.isVirtual()) &&
9342 getDerived().visitBase(&B
))
9345 if (Bases
== VisitAllBases
)
9346 for (auto &B
: RD
->vbases())
9347 if (getDerived().visitBase(&B
))
9350 for (auto *F
: RD
->fields())
9351 if (!F
->isInvalidDecl() && !F
->isUnnamedBitfield() &&
9352 getDerived().visitField(F
))
9361 struct SpecialMemberDeletionInfo
9362 : SpecialMemberVisitor
<SpecialMemberDeletionInfo
> {
9367 bool AllFieldsAreConst
;
9369 SpecialMemberDeletionInfo(Sema
&S
, CXXMethodDecl
*MD
,
9370 Sema::CXXSpecialMember CSM
,
9371 Sema::InheritedConstructorInfo
*ICI
, bool Diagnose
)
9372 : SpecialMemberVisitor(S
, MD
, CSM
, ICI
), Diagnose(Diagnose
),
9373 Loc(MD
->getLocation()), AllFieldsAreConst(true) {}
9375 bool inUnion() const { return MD
->getParent()->isUnion(); }
9377 Sema::CXXSpecialMember
getEffectiveCSM() {
9378 return ICI
? Sema::CXXInvalid
: CSM
;
9381 bool shouldDeleteForVariantObjCPtrMember(FieldDecl
*FD
, QualType FieldType
);
9383 bool visitBase(CXXBaseSpecifier
*Base
) { return shouldDeleteForBase(Base
); }
9384 bool visitField(FieldDecl
*Field
) { return shouldDeleteForField(Field
); }
9386 bool shouldDeleteForBase(CXXBaseSpecifier
*Base
);
9387 bool shouldDeleteForField(FieldDecl
*FD
);
9388 bool shouldDeleteForAllConstMembers();
9390 bool shouldDeleteForClassSubobject(CXXRecordDecl
*Class
, Subobject Subobj
,
9392 bool shouldDeleteForSubobjectCall(Subobject Subobj
,
9393 Sema::SpecialMemberOverloadResult SMOR
,
9394 bool IsDtorCallInCtor
);
9396 bool isAccessible(Subobject Subobj
, CXXMethodDecl
*D
);
9400 /// Is the given special member inaccessible when used on the given
9402 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj
,
9403 CXXMethodDecl
*target
) {
9404 /// If we're operating on a base class, the object type is the
9405 /// type of this special member.
9407 AccessSpecifier access
= target
->getAccess();
9408 if (CXXBaseSpecifier
*base
= Subobj
.dyn_cast
<CXXBaseSpecifier
*>()) {
9409 objectTy
= S
.Context
.getTypeDeclType(MD
->getParent());
9410 access
= CXXRecordDecl::MergeAccess(base
->getAccessSpecifier(), access
);
9412 // If we're operating on a field, the object type is the type of the field.
9414 objectTy
= S
.Context
.getTypeDeclType(target
->getParent());
9417 return S
.isMemberAccessibleForDeletion(
9418 target
->getParent(), DeclAccessPair::make(target
, access
), objectTy
);
9421 /// Check whether we should delete a special member due to the implicit
9422 /// definition containing a call to a special member of a subobject.
9423 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
9424 Subobject Subobj
, Sema::SpecialMemberOverloadResult SMOR
,
9425 bool IsDtorCallInCtor
) {
9426 CXXMethodDecl
*Decl
= SMOR
.getMethod();
9427 FieldDecl
*Field
= Subobj
.dyn_cast
<FieldDecl
*>();
9431 if (SMOR
.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted
)
9432 DiagKind
= !Decl
? 0 : 1;
9433 else if (SMOR
.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous
)
9435 else if (!isAccessible(Subobj
, Decl
))
9437 else if (!IsDtorCallInCtor
&& Field
&& Field
->getParent()->isUnion() &&
9438 !Decl
->isTrivial()) {
9439 // A member of a union must have a trivial corresponding special member.
9440 // As a weird special case, a destructor call from a union's constructor
9441 // must be accessible and non-deleted, but need not be trivial. Such a
9442 // destructor is never actually called, but is semantically checked as
9444 if (CSM
== Sema::CXXDefaultConstructor
) {
9445 // [class.default.ctor]p2:
9446 // A defaulted default constructor for class X is defined as deleted if
9447 // - X is a union that has a variant member with a non-trivial default
9448 // constructor and no variant member of X has a default member
9450 const auto *RD
= cast
<CXXRecordDecl
>(Field
->getParent());
9451 if (!RD
->hasInClassInitializer())
9463 S
.Diag(Field
->getLocation(),
9464 diag::note_deleted_special_member_class_subobject
)
9465 << getEffectiveCSM() << MD
->getParent() << /*IsField*/true
9466 << Field
<< DiagKind
<< IsDtorCallInCtor
<< /*IsObjCPtr*/false;
9468 CXXBaseSpecifier
*Base
= Subobj
.get
<CXXBaseSpecifier
*>();
9469 S
.Diag(Base
->getBeginLoc(),
9470 diag::note_deleted_special_member_class_subobject
)
9471 << getEffectiveCSM() << MD
->getParent() << /*IsField*/ false
9472 << Base
->getType() << DiagKind
<< IsDtorCallInCtor
9473 << /*IsObjCPtr*/false;
9477 S
.NoteDeletedFunction(Decl
);
9478 // FIXME: Explain inaccessibility if DiagKind == 3.
9484 /// Check whether we should delete a special member function due to having a
9485 /// direct or virtual base class or non-static data member of class type M.
9486 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
9487 CXXRecordDecl
*Class
, Subobject Subobj
, unsigned Quals
) {
9488 FieldDecl
*Field
= Subobj
.dyn_cast
<FieldDecl
*>();
9489 bool IsMutable
= Field
&& Field
->isMutable();
9491 // C++11 [class.ctor]p5:
9492 // -- any direct or virtual base class, or non-static data member with no
9493 // brace-or-equal-initializer, has class type M (or array thereof) and
9494 // either M has no default constructor or overload resolution as applied
9495 // to M's default constructor results in an ambiguity or in a function
9496 // that is deleted or inaccessible
9497 // C++11 [class.copy]p11, C++11 [class.copy]p23:
9498 // -- a direct or virtual base class B that cannot be copied/moved because
9499 // overload resolution, as applied to B's corresponding special member,
9500 // results in an ambiguity or a function that is deleted or inaccessible
9501 // from the defaulted special member
9502 // C++11 [class.dtor]p5:
9503 // -- any direct or virtual base class [...] has a type with a destructor
9504 // that is deleted or inaccessible
9505 if (!(CSM
== Sema::CXXDefaultConstructor
&&
9506 Field
&& Field
->hasInClassInitializer()) &&
9507 shouldDeleteForSubobjectCall(Subobj
, lookupIn(Class
, Quals
, IsMutable
),
9511 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
9512 // -- any direct or virtual base class or non-static data member has a
9513 // type with a destructor that is deleted or inaccessible
9514 if (IsConstructor
) {
9515 Sema::SpecialMemberOverloadResult SMOR
=
9516 S
.LookupSpecialMember(Class
, Sema::CXXDestructor
,
9517 false, false, false, false, false);
9518 if (shouldDeleteForSubobjectCall(Subobj
, SMOR
, true))
9525 bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
9526 FieldDecl
*FD
, QualType FieldType
) {
9527 // The defaulted special functions are defined as deleted if this is a variant
9528 // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
9530 if (!FieldType
.hasNonTrivialObjCLifetime())
9533 // Don't make the defaulted default constructor defined as deleted if the
9534 // member has an in-class initializer.
9535 if (CSM
== Sema::CXXDefaultConstructor
&& FD
->hasInClassInitializer())
9539 auto *ParentClass
= cast
<CXXRecordDecl
>(FD
->getParent());
9540 S
.Diag(FD
->getLocation(),
9541 diag::note_deleted_special_member_class_subobject
)
9542 << getEffectiveCSM() << ParentClass
<< /*IsField*/true
9543 << FD
<< 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true;
9549 /// Check whether we should delete a special member function due to the class
9550 /// having a particular direct or virtual base class.
9551 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier
*Base
) {
9552 CXXRecordDecl
*BaseClass
= Base
->getType()->getAsCXXRecordDecl();
9553 // If program is correct, BaseClass cannot be null, but if it is, the error
9554 // must be reported elsewhere.
9557 // If we have an inheriting constructor, check whether we're calling an
9558 // inherited constructor instead of a default constructor.
9559 Sema::SpecialMemberOverloadResult SMOR
= lookupInheritedCtor(BaseClass
);
9560 if (auto *BaseCtor
= SMOR
.getMethod()) {
9561 // Note that we do not check access along this path; other than that,
9562 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
9563 // FIXME: Check that the base has a usable destructor! Sink this into
9564 // shouldDeleteForClassSubobject.
9565 if (BaseCtor
->isDeleted() && Diagnose
) {
9566 S
.Diag(Base
->getBeginLoc(),
9567 diag::note_deleted_special_member_class_subobject
)
9568 << getEffectiveCSM() << MD
->getParent() << /*IsField*/ false
9569 << Base
->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
9570 << /*IsObjCPtr*/false;
9571 S
.NoteDeletedFunction(BaseCtor
);
9573 return BaseCtor
->isDeleted();
9575 return shouldDeleteForClassSubobject(BaseClass
, Base
, 0);
9578 /// Check whether we should delete a special member function due to the class
9579 /// having a particular non-static data member.
9580 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl
*FD
) {
9581 QualType FieldType
= S
.Context
.getBaseElementType(FD
->getType());
9582 CXXRecordDecl
*FieldRecord
= FieldType
->getAsCXXRecordDecl();
9584 if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD
, FieldType
))
9587 if (CSM
== Sema::CXXDefaultConstructor
) {
9588 // For a default constructor, all references must be initialized in-class
9589 // and, if a union, it must have a non-const member.
9590 if (FieldType
->isReferenceType() && !FD
->hasInClassInitializer()) {
9592 S
.Diag(FD
->getLocation(), diag::note_deleted_default_ctor_uninit_field
)
9593 << !!ICI
<< MD
->getParent() << FD
<< FieldType
<< /*Reference*/0;
9596 // C++11 [class.ctor]p5 (modified by DR2394): any non-variant non-static
9597 // data member of const-qualified type (or array thereof) with no
9598 // brace-or-equal-initializer is not const-default-constructible.
9599 if (!inUnion() && FieldType
.isConstQualified() &&
9600 !FD
->hasInClassInitializer() &&
9601 (!FieldRecord
|| !FieldRecord
->allowConstDefaultInit())) {
9603 S
.Diag(FD
->getLocation(), diag::note_deleted_default_ctor_uninit_field
)
9604 << !!ICI
<< MD
->getParent() << FD
<< FD
->getType() << /*Const*/1;
9608 if (inUnion() && !FieldType
.isConstQualified())
9609 AllFieldsAreConst
= false;
9610 } else if (CSM
== Sema::CXXCopyConstructor
) {
9611 // For a copy constructor, data members must not be of rvalue reference
9613 if (FieldType
->isRValueReferenceType()) {
9615 S
.Diag(FD
->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference
)
9616 << MD
->getParent() << FD
<< FieldType
;
9619 } else if (IsAssignment
) {
9620 // For an assignment operator, data members must not be of reference type.
9621 if (FieldType
->isReferenceType()) {
9623 S
.Diag(FD
->getLocation(), diag::note_deleted_assign_field
)
9624 << isMove() << MD
->getParent() << FD
<< FieldType
<< /*Reference*/0;
9627 if (!FieldRecord
&& FieldType
.isConstQualified()) {
9628 // C++11 [class.copy]p23:
9629 // -- a non-static data member of const non-class type (or array thereof)
9631 S
.Diag(FD
->getLocation(), diag::note_deleted_assign_field
)
9632 << isMove() << MD
->getParent() << FD
<< FD
->getType() << /*Const*/1;
9638 // Some additional restrictions exist on the variant members.
9639 if (!inUnion() && FieldRecord
->isUnion() &&
9640 FieldRecord
->isAnonymousStructOrUnion()) {
9641 bool AllVariantFieldsAreConst
= true;
9643 // FIXME: Handle anonymous unions declared within anonymous unions.
9644 for (auto *UI
: FieldRecord
->fields()) {
9645 QualType UnionFieldType
= S
.Context
.getBaseElementType(UI
->getType());
9647 if (shouldDeleteForVariantObjCPtrMember(&*UI
, UnionFieldType
))
9650 if (!UnionFieldType
.isConstQualified())
9651 AllVariantFieldsAreConst
= false;
9653 CXXRecordDecl
*UnionFieldRecord
= UnionFieldType
->getAsCXXRecordDecl();
9654 if (UnionFieldRecord
&&
9655 shouldDeleteForClassSubobject(UnionFieldRecord
, UI
,
9656 UnionFieldType
.getCVRQualifiers()))
9660 // At least one member in each anonymous union must be non-const
9661 if (CSM
== Sema::CXXDefaultConstructor
&& AllVariantFieldsAreConst
&&
9662 !FieldRecord
->field_empty()) {
9664 S
.Diag(FieldRecord
->getLocation(),
9665 diag::note_deleted_default_ctor_all_const
)
9666 << !!ICI
<< MD
->getParent() << /*anonymous union*/1;
9670 // Don't check the implicit member of the anonymous union type.
9671 // This is technically non-conformant but supported, and we have a
9672 // diagnostic for this elsewhere.
9676 if (shouldDeleteForClassSubobject(FieldRecord
, FD
,
9677 FieldType
.getCVRQualifiers()))
9684 /// C++11 [class.ctor] p5:
9685 /// A defaulted default constructor for a class X is defined as deleted if
9686 /// X is a union and all of its variant members are of const-qualified type.
9687 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
9688 // This is a silly definition, because it gives an empty union a deleted
9689 // default constructor. Don't do that.
9690 if (CSM
== Sema::CXXDefaultConstructor
&& inUnion() && AllFieldsAreConst
) {
9691 bool AnyFields
= false;
9692 for (auto *F
: MD
->getParent()->fields())
9693 if ((AnyFields
= !F
->isUnnamedBitfield()))
9698 S
.Diag(MD
->getParent()->getLocation(),
9699 diag::note_deleted_default_ctor_all_const
)
9700 << !!ICI
<< MD
->getParent() << /*not anonymous union*/0;
9706 /// Determine whether a defaulted special member function should be defined as
9707 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
9708 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
9709 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl
*MD
, CXXSpecialMember CSM
,
9710 InheritedConstructorInfo
*ICI
,
9712 if (MD
->isInvalidDecl())
9714 CXXRecordDecl
*RD
= MD
->getParent();
9715 assert(!RD
->isDependentType() && "do deletion after instantiation");
9716 if (!LangOpts
.CPlusPlus11
|| RD
->isInvalidDecl())
9719 // C++11 [expr.lambda.prim]p19:
9720 // The closure type associated with a lambda-expression has a
9721 // deleted (8.4.3) default constructor and a deleted copy
9722 // assignment operator.
9723 // C++2a adds back these operators if the lambda has no lambda-capture.
9724 if (RD
->isLambda() && !RD
->lambdaIsDefaultConstructibleAndAssignable() &&
9725 (CSM
== CXXDefaultConstructor
|| CSM
== CXXCopyAssignment
)) {
9727 Diag(RD
->getLocation(), diag::note_lambda_decl
);
9731 // For an anonymous struct or union, the copy and assignment special members
9732 // will never be used, so skip the check. For an anonymous union declared at
9733 // namespace scope, the constructor and destructor are used.
9734 if (CSM
!= CXXDefaultConstructor
&& CSM
!= CXXDestructor
&&
9735 RD
->isAnonymousStructOrUnion())
9738 // C++11 [class.copy]p7, p18:
9739 // If the class definition declares a move constructor or move assignment
9740 // operator, an implicitly declared copy constructor or copy assignment
9741 // operator is defined as deleted.
9742 if (MD
->isImplicit() &&
9743 (CSM
== CXXCopyConstructor
|| CSM
== CXXCopyAssignment
)) {
9744 CXXMethodDecl
*UserDeclaredMove
= nullptr;
9746 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
9747 // deletion of the corresponding copy operation, not both copy operations.
9748 // MSVC 2015 has adopted the standards conforming behavior.
9749 bool DeletesOnlyMatchingCopy
=
9750 getLangOpts().MSVCCompat
&&
9751 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015
);
9753 if (RD
->hasUserDeclaredMoveConstructor() &&
9754 (!DeletesOnlyMatchingCopy
|| CSM
== CXXCopyConstructor
)) {
9755 if (!Diagnose
) return true;
9757 // Find any user-declared move constructor.
9758 for (auto *I
: RD
->ctors()) {
9759 if (I
->isMoveConstructor()) {
9760 UserDeclaredMove
= I
;
9764 assert(UserDeclaredMove
);
9765 } else if (RD
->hasUserDeclaredMoveAssignment() &&
9766 (!DeletesOnlyMatchingCopy
|| CSM
== CXXCopyAssignment
)) {
9767 if (!Diagnose
) return true;
9769 // Find any user-declared move assignment operator.
9770 for (auto *I
: RD
->methods()) {
9771 if (I
->isMoveAssignmentOperator()) {
9772 UserDeclaredMove
= I
;
9776 assert(UserDeclaredMove
);
9779 if (UserDeclaredMove
) {
9780 Diag(UserDeclaredMove
->getLocation(),
9781 diag::note_deleted_copy_user_declared_move
)
9782 << (CSM
== CXXCopyAssignment
) << RD
9783 << UserDeclaredMove
->isMoveAssignmentOperator();
9788 // Do access control from the special member function
9789 ContextRAII
MethodContext(*this, MD
);
9791 // C++11 [class.dtor]p5:
9792 // -- for a virtual destructor, lookup of the non-array deallocation function
9793 // results in an ambiguity or in a function that is deleted or inaccessible
9794 if (CSM
== CXXDestructor
&& MD
->isVirtual()) {
9795 FunctionDecl
*OperatorDelete
= nullptr;
9796 DeclarationName Name
=
9797 Context
.DeclarationNames
.getCXXOperatorName(OO_Delete
);
9798 if (FindDeallocationFunction(MD
->getLocation(), MD
->getParent(), Name
,
9799 OperatorDelete
, /*Diagnose*/false)) {
9801 Diag(RD
->getLocation(), diag::note_deleted_dtor_no_operator_delete
);
9806 SpecialMemberDeletionInfo
SMI(*this, MD
, CSM
, ICI
, Diagnose
);
9808 // Per DR1611, do not consider virtual bases of constructors of abstract
9809 // classes, since we are not going to construct them.
9810 // Per DR1658, do not consider virtual bases of destructors of abstract
9812 // Per DR2180, for assignment operators we only assign (and thus only
9813 // consider) direct bases.
9814 if (SMI
.visit(SMI
.IsAssignment
? SMI
.VisitDirectBases
9815 : SMI
.VisitPotentiallyConstructedBases
))
9818 if (SMI
.shouldDeleteForAllConstMembers())
9821 if (getLangOpts().CUDA
) {
9822 // We should delete the special member in CUDA mode if target inference
9824 // For inherited constructors (non-null ICI), CSM may be passed so that MD
9825 // is treated as certain special member, which may not reflect what special
9826 // member MD really is. However inferCUDATargetForImplicitSpecialMember
9827 // expects CSM to match MD, therefore recalculate CSM.
9828 assert(ICI
|| CSM
== getSpecialMember(MD
));
9831 RealCSM
= getSpecialMember(MD
);
9833 return inferCUDATargetForImplicitSpecialMember(RD
, RealCSM
, MD
,
9834 SMI
.ConstArg
, Diagnose
);
9840 void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl
*FD
) {
9841 DefaultedFunctionKind DFK
= getDefaultedFunctionKind(FD
);
9842 assert(DFK
&& "not a defaultable function");
9843 assert(FD
->isDefaulted() && FD
->isDeleted() && "not defaulted and deleted");
9845 if (DFK
.isSpecialMember()) {
9846 ShouldDeleteSpecialMember(cast
<CXXMethodDecl
>(FD
), DFK
.asSpecialMember(),
9847 nullptr, /*Diagnose=*/true);
9849 DefaultedComparisonAnalyzer(
9850 *this, cast
<CXXRecordDecl
>(FD
->getLexicalDeclContext()), FD
,
9851 DFK
.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted
)
9856 /// Perform lookup for a special member of the specified kind, and determine
9857 /// whether it is trivial. If the triviality can be determined without the
9858 /// lookup, skip it. This is intended for use when determining whether a
9859 /// special member of a containing object is trivial, and thus does not ever
9860 /// perform overload resolution for default constructors.
9862 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
9863 /// member that was most likely to be intended to be trivial, if any.
9865 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
9866 /// determine whether the special member is trivial.
9867 static bool findTrivialSpecialMember(Sema
&S
, CXXRecordDecl
*RD
,
9868 Sema::CXXSpecialMember CSM
, unsigned Quals
,
9870 Sema::TrivialABIHandling TAH
,
9871 CXXMethodDecl
**Selected
) {
9873 *Selected
= nullptr;
9876 case Sema::CXXInvalid
:
9877 llvm_unreachable("not a special member");
9879 case Sema::CXXDefaultConstructor
:
9880 // C++11 [class.ctor]p5:
9881 // A default constructor is trivial if:
9882 // - all the [direct subobjects] have trivial default constructors
9884 // Note, no overload resolution is performed in this case.
9885 if (RD
->hasTrivialDefaultConstructor())
9889 // If there's a default constructor which could have been trivial, dig it
9890 // out. Otherwise, if there's any user-provided default constructor, point
9891 // to that as an example of why there's not a trivial one.
9892 CXXConstructorDecl
*DefCtor
= nullptr;
9893 if (RD
->needsImplicitDefaultConstructor())
9894 S
.DeclareImplicitDefaultConstructor(RD
);
9895 for (auto *CI
: RD
->ctors()) {
9896 if (!CI
->isDefaultConstructor())
9899 if (!DefCtor
->isUserProvided())
9903 *Selected
= DefCtor
;
9908 case Sema::CXXDestructor
:
9909 // C++11 [class.dtor]p5:
9910 // A destructor is trivial if:
9911 // - all the direct [subobjects] have trivial destructors
9912 if (RD
->hasTrivialDestructor() ||
9913 (TAH
== Sema::TAH_ConsiderTrivialABI
&&
9914 RD
->hasTrivialDestructorForCall()))
9918 if (RD
->needsImplicitDestructor())
9919 S
.DeclareImplicitDestructor(RD
);
9920 *Selected
= RD
->getDestructor();
9925 case Sema::CXXCopyConstructor
:
9926 // C++11 [class.copy]p12:
9927 // A copy constructor is trivial if:
9928 // - the constructor selected to copy each direct [subobject] is trivial
9929 if (RD
->hasTrivialCopyConstructor() ||
9930 (TAH
== Sema::TAH_ConsiderTrivialABI
&&
9931 RD
->hasTrivialCopyConstructorForCall())) {
9932 if (Quals
== Qualifiers::Const
)
9933 // We must either select the trivial copy constructor or reach an
9934 // ambiguity; no need to actually perform overload resolution.
9936 } else if (!Selected
) {
9939 // In C++98, we are not supposed to perform overload resolution here, but we
9940 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
9941 // cases like B as having a non-trivial copy constructor:
9942 // struct A { template<typename T> A(T&); };
9943 // struct B { mutable A a; };
9944 goto NeedOverloadResolution
;
9946 case Sema::CXXCopyAssignment
:
9947 // C++11 [class.copy]p25:
9948 // A copy assignment operator is trivial if:
9949 // - the assignment operator selected to copy each direct [subobject] is
9951 if (RD
->hasTrivialCopyAssignment()) {
9952 if (Quals
== Qualifiers::Const
)
9954 } else if (!Selected
) {
9957 // In C++98, we are not supposed to perform overload resolution here, but we
9958 // treat that as a language defect.
9959 goto NeedOverloadResolution
;
9961 case Sema::CXXMoveConstructor
:
9962 case Sema::CXXMoveAssignment
:
9963 NeedOverloadResolution
:
9964 Sema::SpecialMemberOverloadResult SMOR
=
9965 lookupCallFromSpecialMember(S
, RD
, CSM
, Quals
, ConstRHS
);
9967 // The standard doesn't describe how to behave if the lookup is ambiguous.
9968 // We treat it as not making the member non-trivial, just like the standard
9969 // mandates for the default constructor. This should rarely matter, because
9970 // the member will also be deleted.
9971 if (SMOR
.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous
)
9974 if (!SMOR
.getMethod()) {
9975 assert(SMOR
.getKind() ==
9976 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted
);
9980 // We deliberately don't check if we found a deleted special member. We're
9983 *Selected
= SMOR
.getMethod();
9985 if (TAH
== Sema::TAH_ConsiderTrivialABI
&&
9986 (CSM
== Sema::CXXCopyConstructor
|| CSM
== Sema::CXXMoveConstructor
))
9987 return SMOR
.getMethod()->isTrivialForCall();
9988 return SMOR
.getMethod()->isTrivial();
9991 llvm_unreachable("unknown special method kind");
9994 static CXXConstructorDecl
*findUserDeclaredCtor(CXXRecordDecl
*RD
) {
9995 for (auto *CI
: RD
->ctors())
9996 if (!CI
->isImplicit())
9999 // Look for constructor templates.
10000 typedef CXXRecordDecl::specific_decl_iterator
<FunctionTemplateDecl
> tmpl_iter
;
10001 for (tmpl_iter
TI(RD
->decls_begin()), TE(RD
->decls_end()); TI
!= TE
; ++TI
) {
10002 if (CXXConstructorDecl
*CD
=
10003 dyn_cast
<CXXConstructorDecl
>(TI
->getTemplatedDecl()))
10010 /// The kind of subobject we are checking for triviality. The values of this
10011 /// enumeration are used in diagnostics.
10012 enum TrivialSubobjectKind
{
10013 /// The subobject is a base class.
10015 /// The subobject is a non-static data member.
10017 /// The object is actually the complete object.
10021 /// Check whether the special member selected for a given type would be trivial.
10022 static bool checkTrivialSubobjectCall(Sema
&S
, SourceLocation SubobjLoc
,
10023 QualType SubType
, bool ConstRHS
,
10024 Sema::CXXSpecialMember CSM
,
10025 TrivialSubobjectKind Kind
,
10026 Sema::TrivialABIHandling TAH
, bool Diagnose
) {
10027 CXXRecordDecl
*SubRD
= SubType
->getAsCXXRecordDecl();
10031 CXXMethodDecl
*Selected
;
10032 if (findTrivialSpecialMember(S
, SubRD
, CSM
, SubType
.getCVRQualifiers(),
10033 ConstRHS
, TAH
, Diagnose
? &Selected
: nullptr))
10038 SubType
.addConst();
10040 if (!Selected
&& CSM
== Sema::CXXDefaultConstructor
) {
10041 S
.Diag(SubobjLoc
, diag::note_nontrivial_no_def_ctor
)
10042 << Kind
<< SubType
.getUnqualifiedType();
10043 if (CXXConstructorDecl
*CD
= findUserDeclaredCtor(SubRD
))
10044 S
.Diag(CD
->getLocation(), diag::note_user_declared_ctor
);
10045 } else if (!Selected
)
10046 S
.Diag(SubobjLoc
, diag::note_nontrivial_no_copy
)
10047 << Kind
<< SubType
.getUnqualifiedType() << CSM
<< SubType
;
10048 else if (Selected
->isUserProvided()) {
10049 if (Kind
== TSK_CompleteObject
)
10050 S
.Diag(Selected
->getLocation(), diag::note_nontrivial_user_provided
)
10051 << Kind
<< SubType
.getUnqualifiedType() << CSM
;
10053 S
.Diag(SubobjLoc
, diag::note_nontrivial_user_provided
)
10054 << Kind
<< SubType
.getUnqualifiedType() << CSM
;
10055 S
.Diag(Selected
->getLocation(), diag::note_declared_at
);
10058 if (Kind
!= TSK_CompleteObject
)
10059 S
.Diag(SubobjLoc
, diag::note_nontrivial_subobject
)
10060 << Kind
<< SubType
.getUnqualifiedType() << CSM
;
10062 // Explain why the defaulted or deleted special member isn't trivial.
10063 S
.SpecialMemberIsTrivial(Selected
, CSM
, Sema::TAH_IgnoreTrivialABI
,
10071 /// Check whether the members of a class type allow a special member to be
10073 static bool checkTrivialClassMembers(Sema
&S
, CXXRecordDecl
*RD
,
10074 Sema::CXXSpecialMember CSM
,
10076 Sema::TrivialABIHandling TAH
,
10078 for (const auto *FI
: RD
->fields()) {
10079 if (FI
->isInvalidDecl() || FI
->isUnnamedBitfield())
10082 QualType FieldType
= S
.Context
.getBaseElementType(FI
->getType());
10084 // Pretend anonymous struct or union members are members of this class.
10085 if (FI
->isAnonymousStructOrUnion()) {
10086 if (!checkTrivialClassMembers(S
, FieldType
->getAsCXXRecordDecl(),
10087 CSM
, ConstArg
, TAH
, Diagnose
))
10092 // C++11 [class.ctor]p5:
10093 // A default constructor is trivial if [...]
10094 // -- no non-static data member of its class has a
10095 // brace-or-equal-initializer
10096 if (CSM
== Sema::CXXDefaultConstructor
&& FI
->hasInClassInitializer()) {
10098 S
.Diag(FI
->getLocation(), diag::note_nontrivial_default_member_init
)
10103 // Objective C ARC 4.3.5:
10104 // [...] nontrivally ownership-qualified types are [...] not trivially
10105 // default constructible, copy constructible, move constructible, copy
10106 // assignable, move assignable, or destructible [...]
10107 if (FieldType
.hasNonTrivialObjCLifetime()) {
10109 S
.Diag(FI
->getLocation(), diag::note_nontrivial_objc_ownership
)
10110 << RD
<< FieldType
.getObjCLifetime();
10114 bool ConstRHS
= ConstArg
&& !FI
->isMutable();
10115 if (!checkTrivialSubobjectCall(S
, FI
->getLocation(), FieldType
, ConstRHS
,
10116 CSM
, TSK_Field
, TAH
, Diagnose
))
10123 /// Diagnose why the specified class does not have a trivial special member of
10124 /// the given kind.
10125 void Sema::DiagnoseNontrivial(const CXXRecordDecl
*RD
, CXXSpecialMember CSM
) {
10126 QualType Ty
= Context
.getRecordType(RD
);
10128 bool ConstArg
= (CSM
== CXXCopyConstructor
|| CSM
== CXXCopyAssignment
);
10129 checkTrivialSubobjectCall(*this, RD
->getLocation(), Ty
, ConstArg
, CSM
,
10130 TSK_CompleteObject
, TAH_IgnoreTrivialABI
,
10134 /// Determine whether a defaulted or deleted special member function is trivial,
10135 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
10136 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
10137 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl
*MD
, CXXSpecialMember CSM
,
10138 TrivialABIHandling TAH
, bool Diagnose
) {
10139 assert(!MD
->isUserProvided() && CSM
!= CXXInvalid
&& "not special enough");
10141 CXXRecordDecl
*RD
= MD
->getParent();
10143 bool ConstArg
= false;
10145 // C++11 [class.copy]p12, p25: [DR1593]
10146 // A [special member] is trivial if [...] its parameter-type-list is
10147 // equivalent to the parameter-type-list of an implicit declaration [...]
10149 case CXXDefaultConstructor
:
10150 case CXXDestructor
:
10151 // Trivial default constructors and destructors cannot have parameters.
10154 case CXXCopyConstructor
:
10155 case CXXCopyAssignment
: {
10156 const ParmVarDecl
*Param0
= MD
->getNonObjectParameter(0);
10157 const ReferenceType
*RT
= Param0
->getType()->getAs
<ReferenceType
>();
10159 // When ClangABICompat14 is true, CXX copy constructors will only be trivial
10160 // if they are not user-provided and their parameter-type-list is equivalent
10161 // to the parameter-type-list of an implicit declaration. This maintains the
10162 // behavior before dr2171 was implemented.
10164 // Otherwise, if ClangABICompat14 is false, All copy constructors can be
10165 // trivial, if they are not user-provided, regardless of the qualifiers on
10166 // the reference type.
10167 const bool ClangABICompat14
= Context
.getLangOpts().getClangABICompat() <=
10168 LangOptions::ClangABI::Ver14
;
10170 ((RT
->getPointeeType().getCVRQualifiers() != Qualifiers::Const
) &&
10171 ClangABICompat14
)) {
10173 Diag(Param0
->getLocation(), diag::note_nontrivial_param_type
)
10174 << Param0
->getSourceRange() << Param0
->getType()
10175 << Context
.getLValueReferenceType(
10176 Context
.getRecordType(RD
).withConst());
10180 ConstArg
= RT
->getPointeeType().isConstQualified();
10184 case CXXMoveConstructor
:
10185 case CXXMoveAssignment
: {
10186 // Trivial move operations always have non-cv-qualified parameters.
10187 const ParmVarDecl
*Param0
= MD
->getNonObjectParameter(0);
10188 const RValueReferenceType
*RT
=
10189 Param0
->getType()->getAs
<RValueReferenceType
>();
10190 if (!RT
|| RT
->getPointeeType().getCVRQualifiers()) {
10192 Diag(Param0
->getLocation(), diag::note_nontrivial_param_type
)
10193 << Param0
->getSourceRange() << Param0
->getType()
10194 << Context
.getRValueReferenceType(Context
.getRecordType(RD
));
10201 llvm_unreachable("not a special member");
10204 if (MD
->getMinRequiredArguments() < MD
->getNumParams()) {
10206 Diag(MD
->getParamDecl(MD
->getMinRequiredArguments())->getLocation(),
10207 diag::note_nontrivial_default_arg
)
10208 << MD
->getParamDecl(MD
->getMinRequiredArguments())->getSourceRange();
10211 if (MD
->isVariadic()) {
10213 Diag(MD
->getLocation(), diag::note_nontrivial_variadic
);
10217 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
10218 // A copy/move [constructor or assignment operator] is trivial if
10219 // -- the [member] selected to copy/move each direct base class subobject
10222 // C++11 [class.copy]p12, C++11 [class.copy]p25:
10223 // A [default constructor or destructor] is trivial if
10224 // -- all the direct base classes have trivial [default constructors or
10226 for (const auto &BI
: RD
->bases())
10227 if (!checkTrivialSubobjectCall(*this, BI
.getBeginLoc(), BI
.getType(),
10228 ConstArg
, CSM
, TSK_BaseClass
, TAH
, Diagnose
))
10231 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
10232 // A copy/move [constructor or assignment operator] for a class X is
10234 // -- for each non-static data member of X that is of class type (or array
10235 // thereof), the constructor selected to copy/move that member is
10238 // C++11 [class.copy]p12, C++11 [class.copy]p25:
10239 // A [default constructor or destructor] is trivial if
10240 // -- for all of the non-static data members of its class that are of class
10241 // type (or array thereof), each such class has a trivial [default
10242 // constructor or destructor]
10243 if (!checkTrivialClassMembers(*this, RD
, CSM
, ConstArg
, TAH
, Diagnose
))
10246 // C++11 [class.dtor]p5:
10247 // A destructor is trivial if [...]
10248 // -- the destructor is not virtual
10249 if (CSM
== CXXDestructor
&& MD
->isVirtual()) {
10251 Diag(MD
->getLocation(), diag::note_nontrivial_virtual_dtor
) << RD
;
10255 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
10256 // A [special member] for class X is trivial if [...]
10257 // -- class X has no virtual functions and no virtual base classes
10258 if (CSM
!= CXXDestructor
&& MD
->getParent()->isDynamicClass()) {
10262 if (RD
->getNumVBases()) {
10263 // Check for virtual bases. We already know that the corresponding
10264 // member in all bases is trivial, so vbases must all be direct.
10265 CXXBaseSpecifier
&BS
= *RD
->vbases_begin();
10266 assert(BS
.isVirtual());
10267 Diag(BS
.getBeginLoc(), diag::note_nontrivial_has_virtual
) << RD
<< 1;
10271 // Must have a virtual method.
10272 for (const auto *MI
: RD
->methods()) {
10273 if (MI
->isVirtual()) {
10274 SourceLocation MLoc
= MI
->getBeginLoc();
10275 Diag(MLoc
, diag::note_nontrivial_has_virtual
) << RD
<< 0;
10280 llvm_unreachable("dynamic class with no vbases and no virtual functions");
10283 // Looks like it's trivial!
10288 struct FindHiddenVirtualMethod
{
10290 CXXMethodDecl
*Method
;
10291 llvm::SmallPtrSet
<const CXXMethodDecl
*, 8> OverridenAndUsingBaseMethods
;
10292 SmallVector
<CXXMethodDecl
*, 8> OverloadedMethods
;
10295 /// Check whether any most overridden method from MD in Methods
10296 static bool CheckMostOverridenMethods(
10297 const CXXMethodDecl
*MD
,
10298 const llvm::SmallPtrSetImpl
<const CXXMethodDecl
*> &Methods
) {
10299 if (MD
->size_overridden_methods() == 0)
10300 return Methods
.count(MD
->getCanonicalDecl());
10301 for (const CXXMethodDecl
*O
: MD
->overridden_methods())
10302 if (CheckMostOverridenMethods(O
, Methods
))
10308 /// Member lookup function that determines whether a given C++
10309 /// method overloads virtual methods in a base class without overriding any,
10310 /// to be used with CXXRecordDecl::lookupInBases().
10311 bool operator()(const CXXBaseSpecifier
*Specifier
, CXXBasePath
&Path
) {
10312 RecordDecl
*BaseRecord
=
10313 Specifier
->getType()->castAs
<RecordType
>()->getDecl();
10315 DeclarationName Name
= Method
->getDeclName();
10316 assert(Name
.getNameKind() == DeclarationName::Identifier
);
10318 bool foundSameNameMethod
= false;
10319 SmallVector
<CXXMethodDecl
*, 8> overloadedMethods
;
10320 for (Path
.Decls
= BaseRecord
->lookup(Name
).begin();
10321 Path
.Decls
!= DeclContext::lookup_iterator(); ++Path
.Decls
) {
10322 NamedDecl
*D
= *Path
.Decls
;
10323 if (CXXMethodDecl
*MD
= dyn_cast
<CXXMethodDecl
>(D
)) {
10324 MD
= MD
->getCanonicalDecl();
10325 foundSameNameMethod
= true;
10326 // Interested only in hidden virtual methods.
10327 if (!MD
->isVirtual())
10329 // If the method we are checking overrides a method from its base
10330 // don't warn about the other overloaded methods. Clang deviates from
10331 // GCC by only diagnosing overloads of inherited virtual functions that
10332 // do not override any other virtual functions in the base. GCC's
10333 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
10334 // function from a base class. These cases may be better served by a
10335 // warning (not specific to virtual functions) on call sites when the
10336 // call would select a different function from the base class, were it
10338 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
10339 if (!S
->IsOverload(Method
, MD
, false))
10341 // Collect the overload only if its hidden.
10342 if (!CheckMostOverridenMethods(MD
, OverridenAndUsingBaseMethods
))
10343 overloadedMethods
.push_back(MD
);
10347 if (foundSameNameMethod
)
10348 OverloadedMethods
.append(overloadedMethods
.begin(),
10349 overloadedMethods
.end());
10350 return foundSameNameMethod
;
10353 } // end anonymous namespace
10355 /// Add the most overridden methods from MD to Methods
10356 static void AddMostOverridenMethods(const CXXMethodDecl
*MD
,
10357 llvm::SmallPtrSetImpl
<const CXXMethodDecl
*>& Methods
) {
10358 if (MD
->size_overridden_methods() == 0)
10359 Methods
.insert(MD
->getCanonicalDecl());
10361 for (const CXXMethodDecl
*O
: MD
->overridden_methods())
10362 AddMostOverridenMethods(O
, Methods
);
10365 /// Check if a method overloads virtual methods in a base class without
10366 /// overriding any.
10367 void Sema::FindHiddenVirtualMethods(CXXMethodDecl
*MD
,
10368 SmallVectorImpl
<CXXMethodDecl
*> &OverloadedMethods
) {
10369 if (!MD
->getDeclName().isIdentifier())
10372 CXXBasePaths
Paths(/*FindAmbiguities=*/true, // true to look in all bases.
10373 /*bool RecordPaths=*/false,
10374 /*bool DetectVirtual=*/false);
10375 FindHiddenVirtualMethod FHVM
;
10379 // Keep the base methods that were overridden or introduced in the subclass
10380 // by 'using' in a set. A base method not in this set is hidden.
10381 CXXRecordDecl
*DC
= MD
->getParent();
10382 DeclContext::lookup_result R
= DC
->lookup(MD
->getDeclName());
10383 for (DeclContext::lookup_iterator I
= R
.begin(), E
= R
.end(); I
!= E
; ++I
) {
10384 NamedDecl
*ND
= *I
;
10385 if (UsingShadowDecl
*shad
= dyn_cast
<UsingShadowDecl
>(*I
))
10386 ND
= shad
->getTargetDecl();
10387 if (CXXMethodDecl
*MD
= dyn_cast
<CXXMethodDecl
>(ND
))
10388 AddMostOverridenMethods(MD
, FHVM
.OverridenAndUsingBaseMethods
);
10391 if (DC
->lookupInBases(FHVM
, Paths
))
10392 OverloadedMethods
= FHVM
.OverloadedMethods
;
10395 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl
*MD
,
10396 SmallVectorImpl
<CXXMethodDecl
*> &OverloadedMethods
) {
10397 for (unsigned i
= 0, e
= OverloadedMethods
.size(); i
!= e
; ++i
) {
10398 CXXMethodDecl
*overloadedMD
= OverloadedMethods
[i
];
10399 PartialDiagnostic PD
= PDiag(
10400 diag::note_hidden_overloaded_virtual_declared_here
) << overloadedMD
;
10401 HandleFunctionTypeMismatch(PD
, MD
->getType(), overloadedMD
->getType());
10402 Diag(overloadedMD
->getLocation(), PD
);
10406 /// Diagnose methods which overload virtual methods in a base class
10407 /// without overriding any.
10408 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl
*MD
) {
10409 if (MD
->isInvalidDecl())
10412 if (Diags
.isIgnored(diag::warn_overloaded_virtual
, MD
->getLocation()))
10415 SmallVector
<CXXMethodDecl
*, 8> OverloadedMethods
;
10416 FindHiddenVirtualMethods(MD
, OverloadedMethods
);
10417 if (!OverloadedMethods
.empty()) {
10418 Diag(MD
->getLocation(), diag::warn_overloaded_virtual
)
10419 << MD
<< (OverloadedMethods
.size() > 1);
10421 NoteHiddenVirtualMethods(MD
, OverloadedMethods
);
10425 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl
&RD
) {
10426 auto PrintDiagAndRemoveAttr
= [&](unsigned N
) {
10427 // No diagnostics if this is a template instantiation.
10428 if (!isTemplateInstantiation(RD
.getTemplateSpecializationKind())) {
10429 Diag(RD
.getAttr
<TrivialABIAttr
>()->getLocation(),
10430 diag::ext_cannot_use_trivial_abi
) << &RD
;
10431 Diag(RD
.getAttr
<TrivialABIAttr
>()->getLocation(),
10432 diag::note_cannot_use_trivial_abi_reason
) << &RD
<< N
;
10434 RD
.dropAttr
<TrivialABIAttr
>();
10437 // Ill-formed if the copy and move constructors are deleted.
10438 auto HasNonDeletedCopyOrMoveConstructor
= [&]() {
10439 // If the type is dependent, then assume it might have
10440 // implicit copy or move ctor because we won't know yet at this point.
10441 if (RD
.isDependentType())
10443 if (RD
.needsImplicitCopyConstructor() &&
10444 !RD
.defaultedCopyConstructorIsDeleted())
10446 if (RD
.needsImplicitMoveConstructor() &&
10447 !RD
.defaultedMoveConstructorIsDeleted())
10449 for (const CXXConstructorDecl
*CD
: RD
.ctors())
10450 if (CD
->isCopyOrMoveConstructor() && !CD
->isDeleted())
10455 if (!HasNonDeletedCopyOrMoveConstructor()) {
10456 PrintDiagAndRemoveAttr(0);
10460 // Ill-formed if the struct has virtual functions.
10461 if (RD
.isPolymorphic()) {
10462 PrintDiagAndRemoveAttr(1);
10466 for (const auto &B
: RD
.bases()) {
10467 // Ill-formed if the base class is non-trivial for the purpose of calls or a
10469 if (!B
.getType()->isDependentType() &&
10470 !B
.getType()->getAsCXXRecordDecl()->canPassInRegisters()) {
10471 PrintDiagAndRemoveAttr(2);
10475 if (B
.isVirtual()) {
10476 PrintDiagAndRemoveAttr(3);
10481 for (const auto *FD
: RD
.fields()) {
10482 // Ill-formed if the field is an ObjectiveC pointer or of a type that is
10483 // non-trivial for the purpose of calls.
10484 QualType FT
= FD
->getType();
10485 if (FT
.getObjCLifetime() == Qualifiers::OCL_Weak
) {
10486 PrintDiagAndRemoveAttr(4);
10490 if (const auto *RT
= FT
->getBaseElementTypeUnsafe()->getAs
<RecordType
>())
10491 if (!RT
->isDependentType() &&
10492 !cast
<CXXRecordDecl
>(RT
->getDecl())->canPassInRegisters()) {
10493 PrintDiagAndRemoveAttr(5);
10499 void Sema::ActOnFinishCXXMemberSpecification(
10500 Scope
*S
, SourceLocation RLoc
, Decl
*TagDecl
, SourceLocation LBrac
,
10501 SourceLocation RBrac
, const ParsedAttributesView
&AttrList
) {
10505 AdjustDeclIfTemplate(TagDecl
);
10507 for (const ParsedAttr
&AL
: AttrList
) {
10508 if (AL
.getKind() != ParsedAttr::AT_Visibility
)
10511 Diag(AL
.getLoc(), diag::warn_attribute_after_definition_ignored
) << AL
;
10514 ActOnFields(S
, RLoc
, TagDecl
,
10516 // strict aliasing violation!
10517 reinterpret_cast<Decl
**>(FieldCollector
->getCurFields()),
10518 FieldCollector
->getCurNumFields()),
10519 LBrac
, RBrac
, AttrList
);
10521 CheckCompletedCXXClass(S
, cast
<CXXRecordDecl
>(TagDecl
));
10524 /// Find the equality comparison functions that should be implicitly declared
10525 /// in a given class definition, per C++2a [class.compare.default]p3.
10526 static void findImplicitlyDeclaredEqualityComparisons(
10527 ASTContext
&Ctx
, CXXRecordDecl
*RD
,
10528 llvm::SmallVectorImpl
<FunctionDecl
*> &Spaceships
) {
10529 DeclarationName EqEq
= Ctx
.DeclarationNames
.getCXXOperatorName(OO_EqualEqual
);
10530 if (!RD
->lookup(EqEq
).empty())
10531 // Member operator== explicitly declared: no implicit operator==s.
10534 // Traverse friends looking for an '==' or a '<=>'.
10535 for (FriendDecl
*Friend
: RD
->friends()) {
10536 FunctionDecl
*FD
= dyn_cast_or_null
<FunctionDecl
>(Friend
->getFriendDecl());
10539 if (FD
->getOverloadedOperator() == OO_EqualEqual
) {
10540 // Friend operator== explicitly declared: no implicit operator==s.
10541 Spaceships
.clear();
10545 if (FD
->getOverloadedOperator() == OO_Spaceship
&&
10546 FD
->isExplicitlyDefaulted())
10547 Spaceships
.push_back(FD
);
10550 // Look for members named 'operator<=>'.
10551 DeclarationName Cmp
= Ctx
.DeclarationNames
.getCXXOperatorName(OO_Spaceship
);
10552 for (NamedDecl
*ND
: RD
->lookup(Cmp
)) {
10553 // Note that we could find a non-function here (either a function template
10554 // or a using-declaration). Neither case results in an implicit
10556 if (auto *FD
= dyn_cast
<FunctionDecl
>(ND
))
10557 if (FD
->isExplicitlyDefaulted())
10558 Spaceships
.push_back(FD
);
10562 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
10563 /// special functions, such as the default constructor, copy
10564 /// constructor, or destructor, to the given C++ class (C++
10565 /// [special]p1). This routine can only be executed just before the
10566 /// definition of the class is complete.
10567 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl
*ClassDecl
) {
10568 // Don't add implicit special members to templated classes.
10569 // FIXME: This means unqualified lookups for 'operator=' within a class
10570 // template don't work properly.
10571 if (!ClassDecl
->isDependentType()) {
10572 if (ClassDecl
->needsImplicitDefaultConstructor()) {
10573 ++getASTContext().NumImplicitDefaultConstructors
;
10575 if (ClassDecl
->hasInheritedConstructor())
10576 DeclareImplicitDefaultConstructor(ClassDecl
);
10579 if (ClassDecl
->needsImplicitCopyConstructor()) {
10580 ++getASTContext().NumImplicitCopyConstructors
;
10582 // If the properties or semantics of the copy constructor couldn't be
10583 // determined while the class was being declared, force a declaration
10585 if (ClassDecl
->needsOverloadResolutionForCopyConstructor() ||
10586 ClassDecl
->hasInheritedConstructor())
10587 DeclareImplicitCopyConstructor(ClassDecl
);
10588 // For the MS ABI we need to know whether the copy ctor is deleted. A
10589 // prerequisite for deleting the implicit copy ctor is that the class has
10590 // a move ctor or move assignment that is either user-declared or whose
10591 // semantics are inherited from a subobject. FIXME: We should provide a
10592 // more direct way for CodeGen to ask whether the constructor was deleted.
10593 else if (Context
.getTargetInfo().getCXXABI().isMicrosoft() &&
10594 (ClassDecl
->hasUserDeclaredMoveConstructor() ||
10595 ClassDecl
->needsOverloadResolutionForMoveConstructor() ||
10596 ClassDecl
->hasUserDeclaredMoveAssignment() ||
10597 ClassDecl
->needsOverloadResolutionForMoveAssignment()))
10598 DeclareImplicitCopyConstructor(ClassDecl
);
10601 if (getLangOpts().CPlusPlus11
&&
10602 ClassDecl
->needsImplicitMoveConstructor()) {
10603 ++getASTContext().NumImplicitMoveConstructors
;
10605 if (ClassDecl
->needsOverloadResolutionForMoveConstructor() ||
10606 ClassDecl
->hasInheritedConstructor())
10607 DeclareImplicitMoveConstructor(ClassDecl
);
10610 if (ClassDecl
->needsImplicitCopyAssignment()) {
10611 ++getASTContext().NumImplicitCopyAssignmentOperators
;
10613 // If we have a dynamic class, then the copy assignment operator may be
10614 // virtual, so we have to declare it immediately. This ensures that, e.g.,
10615 // it shows up in the right place in the vtable and that we diagnose
10616 // problems with the implicit exception specification.
10617 if (ClassDecl
->isDynamicClass() ||
10618 ClassDecl
->needsOverloadResolutionForCopyAssignment() ||
10619 ClassDecl
->hasInheritedAssignment())
10620 DeclareImplicitCopyAssignment(ClassDecl
);
10623 if (getLangOpts().CPlusPlus11
&& ClassDecl
->needsImplicitMoveAssignment()) {
10624 ++getASTContext().NumImplicitMoveAssignmentOperators
;
10626 // Likewise for the move assignment operator.
10627 if (ClassDecl
->isDynamicClass() ||
10628 ClassDecl
->needsOverloadResolutionForMoveAssignment() ||
10629 ClassDecl
->hasInheritedAssignment())
10630 DeclareImplicitMoveAssignment(ClassDecl
);
10633 if (ClassDecl
->needsImplicitDestructor()) {
10634 ++getASTContext().NumImplicitDestructors
;
10636 // If we have a dynamic class, then the destructor may be virtual, so we
10637 // have to declare the destructor immediately. This ensures that, e.g., it
10638 // shows up in the right place in the vtable and that we diagnose problems
10639 // with the implicit exception specification.
10640 if (ClassDecl
->isDynamicClass() ||
10641 ClassDecl
->needsOverloadResolutionForDestructor())
10642 DeclareImplicitDestructor(ClassDecl
);
10646 // C++2a [class.compare.default]p3:
10647 // If the member-specification does not explicitly declare any member or
10648 // friend named operator==, an == operator function is declared implicitly
10649 // for each defaulted three-way comparison operator function defined in
10650 // the member-specification
10651 // FIXME: Consider doing this lazily.
10652 // We do this during the initial parse for a class template, not during
10653 // instantiation, so that we can handle unqualified lookups for 'operator=='
10654 // when parsing the template.
10655 if (getLangOpts().CPlusPlus20
&& !inTemplateInstantiation()) {
10656 llvm::SmallVector
<FunctionDecl
*, 4> DefaultedSpaceships
;
10657 findImplicitlyDeclaredEqualityComparisons(Context
, ClassDecl
,
10658 DefaultedSpaceships
);
10659 for (auto *FD
: DefaultedSpaceships
)
10660 DeclareImplicitEqualityComparison(ClassDecl
, FD
);
10665 Sema::ActOnReenterTemplateScope(Decl
*D
,
10666 llvm::function_ref
<Scope
*()> EnterScope
) {
10669 AdjustDeclIfTemplate(D
);
10671 // In order to get name lookup right, reenter template scopes in order from
10672 // outermost to innermost.
10673 SmallVector
<TemplateParameterList
*, 4> ParameterLists
;
10674 DeclContext
*LookupDC
= dyn_cast
<DeclContext
>(D
);
10676 if (DeclaratorDecl
*DD
= dyn_cast
<DeclaratorDecl
>(D
)) {
10677 for (unsigned i
= 0; i
< DD
->getNumTemplateParameterLists(); ++i
)
10678 ParameterLists
.push_back(DD
->getTemplateParameterList(i
));
10680 if (FunctionDecl
*FD
= dyn_cast
<FunctionDecl
>(D
)) {
10681 if (FunctionTemplateDecl
*FTD
= FD
->getDescribedFunctionTemplate())
10682 ParameterLists
.push_back(FTD
->getTemplateParameters());
10683 } else if (VarDecl
*VD
= dyn_cast
<VarDecl
>(D
)) {
10684 LookupDC
= VD
->getDeclContext();
10686 if (VarTemplateDecl
*VTD
= VD
->getDescribedVarTemplate())
10687 ParameterLists
.push_back(VTD
->getTemplateParameters());
10688 else if (auto *PSD
= dyn_cast
<VarTemplatePartialSpecializationDecl
>(D
))
10689 ParameterLists
.push_back(PSD
->getTemplateParameters());
10691 } else if (TagDecl
*TD
= dyn_cast
<TagDecl
>(D
)) {
10692 for (unsigned i
= 0; i
< TD
->getNumTemplateParameterLists(); ++i
)
10693 ParameterLists
.push_back(TD
->getTemplateParameterList(i
));
10695 if (CXXRecordDecl
*RD
= dyn_cast
<CXXRecordDecl
>(TD
)) {
10696 if (ClassTemplateDecl
*CTD
= RD
->getDescribedClassTemplate())
10697 ParameterLists
.push_back(CTD
->getTemplateParameters());
10698 else if (auto *PSD
= dyn_cast
<ClassTemplatePartialSpecializationDecl
>(D
))
10699 ParameterLists
.push_back(PSD
->getTemplateParameters());
10702 // FIXME: Alias declarations and concepts.
10704 unsigned Count
= 0;
10705 Scope
*InnermostTemplateScope
= nullptr;
10706 for (TemplateParameterList
*Params
: ParameterLists
) {
10707 // Ignore explicit specializations; they don't contribute to the template
10709 if (Params
->size() == 0)
10712 InnermostTemplateScope
= EnterScope();
10713 for (NamedDecl
*Param
: *Params
) {
10714 if (Param
->getDeclName()) {
10715 InnermostTemplateScope
->AddDecl(Param
);
10716 IdResolver
.AddDecl(Param
);
10722 // Associate the new template scopes with the corresponding entities.
10723 if (InnermostTemplateScope
) {
10724 assert(LookupDC
&& "no enclosing DeclContext for template lookup");
10725 EnterTemplatedContext(InnermostTemplateScope
, LookupDC
);
10731 void Sema::ActOnStartDelayedMemberDeclarations(Scope
*S
, Decl
*RecordD
) {
10732 if (!RecordD
) return;
10733 AdjustDeclIfTemplate(RecordD
);
10734 CXXRecordDecl
*Record
= cast
<CXXRecordDecl
>(RecordD
);
10735 PushDeclContext(S
, Record
);
10738 void Sema::ActOnFinishDelayedMemberDeclarations(Scope
*S
, Decl
*RecordD
) {
10739 if (!RecordD
) return;
10743 /// This is used to implement the constant expression evaluation part of the
10744 /// attribute enable_if extension. There is nothing in standard C++ which would
10745 /// require reentering parameters.
10746 void Sema::ActOnReenterCXXMethodParameter(Scope
*S
, ParmVarDecl
*Param
) {
10751 if (Param
->getDeclName())
10752 IdResolver
.AddDecl(Param
);
10755 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
10756 /// parsing a top-level (non-nested) C++ class, and we are now
10757 /// parsing those parts of the given Method declaration that could
10758 /// not be parsed earlier (C++ [class.mem]p2), such as default
10759 /// arguments. This action should enter the scope of the given
10760 /// Method declaration as if we had just parsed the qualified method
10761 /// name. However, it should not bring the parameters into scope;
10762 /// that will be performed by ActOnDelayedCXXMethodParameter.
10763 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope
*S
, Decl
*MethodD
) {
10766 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
10767 /// C++ method declaration. We're (re-)introducing the given
10768 /// function parameter into scope for use in parsing later parts of
10769 /// the method declaration. For example, we could see an
10770 /// ActOnParamDefaultArgument event for this parameter.
10771 void Sema::ActOnDelayedCXXMethodParameter(Scope
*S
, Decl
*ParamD
) {
10775 ParmVarDecl
*Param
= cast
<ParmVarDecl
>(ParamD
);
10778 if (Param
->getDeclName())
10779 IdResolver
.AddDecl(Param
);
10782 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
10783 /// processing the delayed method declaration for Method. The method
10784 /// declaration is now considered finished. There may be a separate
10785 /// ActOnStartOfFunctionDef action later (not necessarily
10786 /// immediately!) for this method, if it was also defined inside the
10788 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope
*S
, Decl
*MethodD
) {
10792 AdjustDeclIfTemplate(MethodD
);
10794 FunctionDecl
*Method
= cast
<FunctionDecl
>(MethodD
);
10796 // Now that we have our default arguments, check the constructor
10797 // again. It could produce additional diagnostics or affect whether
10798 // the class has implicitly-declared destructors, among other
10800 if (CXXConstructorDecl
*Constructor
= dyn_cast
<CXXConstructorDecl
>(Method
))
10801 CheckConstructor(Constructor
);
10803 // Check the default arguments, which we may have added.
10804 if (!Method
->isInvalidDecl())
10805 CheckCXXDefaultArguments(Method
);
10808 // Emit the given diagnostic for each non-address-space qualifier.
10809 // Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
10810 static void checkMethodTypeQualifiers(Sema
&S
, Declarator
&D
, unsigned DiagID
) {
10811 const DeclaratorChunk::FunctionTypeInfo
&FTI
= D
.getFunctionTypeInfo();
10812 if (FTI
.hasMethodTypeQualifiers() && !D
.isInvalidType()) {
10813 bool DiagOccured
= false;
10814 FTI
.MethodQualifiers
->forEachQualifier(
10815 [DiagID
, &S
, &DiagOccured
](DeclSpec::TQ
, StringRef QualName
,
10816 SourceLocation SL
) {
10817 // This diagnostic should be emitted on any qualifier except an addr
10818 // space qualifier. However, forEachQualifier currently doesn't visit
10819 // addr space qualifiers, so there's no way to write this condition
10820 // right now; we just diagnose on everything.
10821 S
.Diag(SL
, DiagID
) << QualName
<< SourceRange(SL
);
10822 DiagOccured
= true;
10825 D
.setInvalidType();
10829 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
10830 /// the well-formedness of the constructor declarator @p D with type @p
10831 /// R. If there are any errors in the declarator, this routine will
10832 /// emit diagnostics and set the invalid bit to true. In any case, the type
10833 /// will be updated to reflect a well-formed type for the constructor and
10835 QualType
Sema::CheckConstructorDeclarator(Declarator
&D
, QualType R
,
10836 StorageClass
&SC
) {
10837 bool isVirtual
= D
.getDeclSpec().isVirtualSpecified();
10839 // C++ [class.ctor]p3:
10840 // A constructor shall not be virtual (10.3) or static (9.4). A
10841 // constructor can be invoked for a const, volatile or const
10842 // volatile object. A constructor shall not be declared const,
10843 // volatile, or const volatile (9.3.2).
10845 if (!D
.isInvalidType())
10846 Diag(D
.getIdentifierLoc(), diag::err_constructor_cannot_be
)
10847 << "virtual" << SourceRange(D
.getDeclSpec().getVirtualSpecLoc())
10848 << SourceRange(D
.getIdentifierLoc());
10849 D
.setInvalidType();
10851 if (SC
== SC_Static
) {
10852 if (!D
.isInvalidType())
10853 Diag(D
.getIdentifierLoc(), diag::err_constructor_cannot_be
)
10854 << "static" << SourceRange(D
.getDeclSpec().getStorageClassSpecLoc())
10855 << SourceRange(D
.getIdentifierLoc());
10856 D
.setInvalidType();
10860 if (unsigned TypeQuals
= D
.getDeclSpec().getTypeQualifiers()) {
10861 diagnoseIgnoredQualifiers(
10862 diag::err_constructor_return_type
, TypeQuals
, SourceLocation(),
10863 D
.getDeclSpec().getConstSpecLoc(), D
.getDeclSpec().getVolatileSpecLoc(),
10864 D
.getDeclSpec().getRestrictSpecLoc(),
10865 D
.getDeclSpec().getAtomicSpecLoc());
10866 D
.setInvalidType();
10869 checkMethodTypeQualifiers(*this, D
, diag::err_invalid_qualified_constructor
);
10871 // C++0x [class.ctor]p4:
10872 // A constructor shall not be declared with a ref-qualifier.
10873 DeclaratorChunk::FunctionTypeInfo
&FTI
= D
.getFunctionTypeInfo();
10874 if (FTI
.hasRefQualifier()) {
10875 Diag(FTI
.getRefQualifierLoc(), diag::err_ref_qualifier_constructor
)
10876 << FTI
.RefQualifierIsLValueRef
10877 << FixItHint::CreateRemoval(FTI
.getRefQualifierLoc());
10878 D
.setInvalidType();
10881 // Rebuild the function type "R" without any type qualifiers (in
10882 // case any of the errors above fired) and with "void" as the
10883 // return type, since constructors don't have return types.
10884 const FunctionProtoType
*Proto
= R
->castAs
<FunctionProtoType
>();
10885 if (Proto
->getReturnType() == Context
.VoidTy
&& !D
.isInvalidType())
10888 FunctionProtoType::ExtProtoInfo EPI
= Proto
->getExtProtoInfo();
10889 EPI
.TypeQuals
= Qualifiers();
10890 EPI
.RefQualifier
= RQ_None
;
10892 return Context
.getFunctionType(Context
.VoidTy
, Proto
->getParamTypes(), EPI
);
10895 /// CheckConstructor - Checks a fully-formed constructor for
10896 /// well-formedness, issuing any diagnostics required. Returns true if
10897 /// the constructor declarator is invalid.
10898 void Sema::CheckConstructor(CXXConstructorDecl
*Constructor
) {
10899 CXXRecordDecl
*ClassDecl
10900 = dyn_cast
<CXXRecordDecl
>(Constructor
->getDeclContext());
10902 return Constructor
->setInvalidDecl();
10904 // C++ [class.copy]p3:
10905 // A declaration of a constructor for a class X is ill-formed if
10906 // its first parameter is of type (optionally cv-qualified) X and
10907 // either there are no other parameters or else all other
10908 // parameters have default arguments.
10909 if (!Constructor
->isInvalidDecl() &&
10910 Constructor
->hasOneParamOrDefaultArgs() &&
10911 Constructor
->getTemplateSpecializationKind() !=
10912 TSK_ImplicitInstantiation
) {
10913 QualType ParamType
= Constructor
->getParamDecl(0)->getType();
10914 QualType ClassTy
= Context
.getTagDeclType(ClassDecl
);
10915 if (Context
.getCanonicalType(ParamType
).getUnqualifiedType() == ClassTy
) {
10916 SourceLocation ParamLoc
= Constructor
->getParamDecl(0)->getLocation();
10917 const char *ConstRef
10918 = Constructor
->getParamDecl(0)->getIdentifier() ? "const &"
10920 Diag(ParamLoc
, diag::err_constructor_byvalue_arg
)
10921 << FixItHint::CreateInsertion(ParamLoc
, ConstRef
);
10923 // FIXME: Rather that making the constructor invalid, we should endeavor
10924 // to fix the type.
10925 Constructor
->setInvalidDecl();
10930 /// CheckDestructor - Checks a fully-formed destructor definition for
10931 /// well-formedness, issuing any diagnostics required. Returns true
10933 bool Sema::CheckDestructor(CXXDestructorDecl
*Destructor
) {
10934 CXXRecordDecl
*RD
= Destructor
->getParent();
10936 if (!Destructor
->getOperatorDelete() && Destructor
->isVirtual()) {
10937 SourceLocation Loc
;
10939 if (!Destructor
->isImplicit())
10940 Loc
= Destructor
->getLocation();
10942 Loc
= RD
->getLocation();
10944 // If we have a virtual destructor, look up the deallocation function
10945 if (FunctionDecl
*OperatorDelete
=
10946 FindDeallocationFunctionForDestructor(Loc
, RD
)) {
10947 Expr
*ThisArg
= nullptr;
10949 // If the notional 'delete this' expression requires a non-trivial
10950 // conversion from 'this' to the type of a destroying operator delete's
10951 // first parameter, perform that conversion now.
10952 if (OperatorDelete
->isDestroyingOperatorDelete()) {
10953 QualType ParamType
= OperatorDelete
->getParamDecl(0)->getType();
10954 if (!declaresSameEntity(ParamType
->getAsCXXRecordDecl(), RD
)) {
10955 // C++ [class.dtor]p13:
10956 // ... as if for the expression 'delete this' appearing in a
10957 // non-virtual destructor of the destructor's class.
10958 ContextRAII
SwitchContext(*this, Destructor
);
10960 ActOnCXXThis(OperatorDelete
->getParamDecl(0)->getLocation());
10961 assert(!This
.isInvalid() && "couldn't form 'this' expr in dtor?");
10962 This
= PerformImplicitConversion(This
.get(), ParamType
, AA_Passing
);
10963 if (This
.isInvalid()) {
10964 // FIXME: Register this as a context note so that it comes out
10965 // in the right order.
10966 Diag(Loc
, diag::note_implicit_delete_this_in_destructor_here
);
10969 ThisArg
= This
.get();
10973 DiagnoseUseOfDecl(OperatorDelete
, Loc
);
10974 MarkFunctionReferenced(Loc
, OperatorDelete
);
10975 Destructor
->setOperatorDelete(OperatorDelete
, ThisArg
);
10982 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
10983 /// the well-formednes of the destructor declarator @p D with type @p
10984 /// R. If there are any errors in the declarator, this routine will
10985 /// emit diagnostics and set the declarator to invalid. Even if this happens,
10986 /// will be updated to reflect a well-formed type for the destructor and
10988 QualType
Sema::CheckDestructorDeclarator(Declarator
&D
, QualType R
,
10989 StorageClass
& SC
) {
10990 // C++ [class.dtor]p1:
10991 // [...] A typedef-name that names a class is a class-name
10992 // (7.1.3); however, a typedef-name that names a class shall not
10993 // be used as the identifier in the declarator for a destructor
10995 QualType DeclaratorType
= GetTypeFromParser(D
.getName().DestructorName
);
10996 if (const TypedefType
*TT
= DeclaratorType
->getAs
<TypedefType
>())
10997 Diag(D
.getIdentifierLoc(), diag::ext_destructor_typedef_name
)
10998 << DeclaratorType
<< isa
<TypeAliasDecl
>(TT
->getDecl());
10999 else if (const TemplateSpecializationType
*TST
=
11000 DeclaratorType
->getAs
<TemplateSpecializationType
>())
11001 if (TST
->isTypeAlias())
11002 Diag(D
.getIdentifierLoc(), diag::ext_destructor_typedef_name
)
11003 << DeclaratorType
<< 1;
11005 // C++ [class.dtor]p2:
11006 // A destructor is used to destroy objects of its class type. A
11007 // destructor takes no parameters, and no return type can be
11008 // specified for it (not even void). The address of a destructor
11009 // shall not be taken. A destructor shall not be static. A
11010 // destructor can be invoked for a const, volatile or const
11011 // volatile object. A destructor shall not be declared const,
11012 // volatile or const volatile (9.3.2).
11013 if (SC
== SC_Static
) {
11014 if (!D
.isInvalidType())
11015 Diag(D
.getIdentifierLoc(), diag::err_destructor_cannot_be
)
11016 << "static" << SourceRange(D
.getDeclSpec().getStorageClassSpecLoc())
11017 << SourceRange(D
.getIdentifierLoc())
11018 << FixItHint::CreateRemoval(D
.getDeclSpec().getStorageClassSpecLoc());
11022 if (!D
.isInvalidType()) {
11023 // Destructors don't have return types, but the parser will
11024 // happily parse something like:
11030 // The return type will be eliminated later.
11031 if (D
.getDeclSpec().hasTypeSpecifier())
11032 Diag(D
.getIdentifierLoc(), diag::err_destructor_return_type
)
11033 << SourceRange(D
.getDeclSpec().getTypeSpecTypeLoc())
11034 << SourceRange(D
.getIdentifierLoc());
11035 else if (unsigned TypeQuals
= D
.getDeclSpec().getTypeQualifiers()) {
11036 diagnoseIgnoredQualifiers(diag::err_destructor_return_type
, TypeQuals
,
11038 D
.getDeclSpec().getConstSpecLoc(),
11039 D
.getDeclSpec().getVolatileSpecLoc(),
11040 D
.getDeclSpec().getRestrictSpecLoc(),
11041 D
.getDeclSpec().getAtomicSpecLoc());
11042 D
.setInvalidType();
11046 checkMethodTypeQualifiers(*this, D
, diag::err_invalid_qualified_destructor
);
11048 // C++0x [class.dtor]p2:
11049 // A destructor shall not be declared with a ref-qualifier.
11050 DeclaratorChunk::FunctionTypeInfo
&FTI
= D
.getFunctionTypeInfo();
11051 if (FTI
.hasRefQualifier()) {
11052 Diag(FTI
.getRefQualifierLoc(), diag::err_ref_qualifier_destructor
)
11053 << FTI
.RefQualifierIsLValueRef
11054 << FixItHint::CreateRemoval(FTI
.getRefQualifierLoc());
11055 D
.setInvalidType();
11058 // Make sure we don't have any parameters.
11059 if (FTIHasNonVoidParameters(FTI
)) {
11060 Diag(D
.getIdentifierLoc(), diag::err_destructor_with_params
);
11062 // Delete the parameters.
11064 D
.setInvalidType();
11067 // Make sure the destructor isn't variadic.
11068 if (FTI
.isVariadic
) {
11069 Diag(D
.getIdentifierLoc(), diag::err_destructor_variadic
);
11070 D
.setInvalidType();
11073 // Rebuild the function type "R" without any type qualifiers or
11074 // parameters (in case any of the errors above fired) and with
11075 // "void" as the return type, since destructors don't have return
11077 if (!D
.isInvalidType())
11080 const FunctionProtoType
*Proto
= R
->castAs
<FunctionProtoType
>();
11081 FunctionProtoType::ExtProtoInfo EPI
= Proto
->getExtProtoInfo();
11082 EPI
.Variadic
= false;
11083 EPI
.TypeQuals
= Qualifiers();
11084 EPI
.RefQualifier
= RQ_None
;
11085 return Context
.getFunctionType(Context
.VoidTy
, std::nullopt
, EPI
);
11088 static void extendLeft(SourceRange
&R
, SourceRange Before
) {
11089 if (Before
.isInvalid())
11091 R
.setBegin(Before
.getBegin());
11092 if (R
.getEnd().isInvalid())
11093 R
.setEnd(Before
.getEnd());
11096 static void extendRight(SourceRange
&R
, SourceRange After
) {
11097 if (After
.isInvalid())
11099 if (R
.getBegin().isInvalid())
11100 R
.setBegin(After
.getBegin());
11101 R
.setEnd(After
.getEnd());
11104 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
11105 /// well-formednes of the conversion function declarator @p D with
11106 /// type @p R. If there are any errors in the declarator, this routine
11107 /// will emit diagnostics and return true. Otherwise, it will return
11108 /// false. Either way, the type @p R will be updated to reflect a
11109 /// well-formed type for the conversion operator.
11110 void Sema::CheckConversionDeclarator(Declarator
&D
, QualType
&R
,
11111 StorageClass
& SC
) {
11112 // C++ [class.conv.fct]p1:
11113 // Neither parameter types nor return type can be specified. The
11114 // type of a conversion function (8.3.5) is "function taking no
11115 // parameter returning conversion-type-id."
11116 if (SC
== SC_Static
) {
11117 if (!D
.isInvalidType())
11118 Diag(D
.getIdentifierLoc(), diag::err_conv_function_not_member
)
11119 << SourceRange(D
.getDeclSpec().getStorageClassSpecLoc())
11120 << D
.getName().getSourceRange();
11121 D
.setInvalidType();
11125 TypeSourceInfo
*ConvTSI
= nullptr;
11126 QualType ConvType
=
11127 GetTypeFromParser(D
.getName().ConversionFunctionId
, &ConvTSI
);
11129 const DeclSpec
&DS
= D
.getDeclSpec();
11130 if (DS
.hasTypeSpecifier() && !D
.isInvalidType()) {
11131 // Conversion functions don't have return types, but the parser will
11132 // happily parse something like:
11135 // float operator bool();
11138 // The return type will be changed later anyway.
11139 Diag(D
.getIdentifierLoc(), diag::err_conv_function_return_type
)
11140 << SourceRange(DS
.getTypeSpecTypeLoc())
11141 << SourceRange(D
.getIdentifierLoc());
11142 D
.setInvalidType();
11143 } else if (DS
.getTypeQualifiers() && !D
.isInvalidType()) {
11144 // It's also plausible that the user writes type qualifiers in the wrong
11146 // struct S { const operator int(); };
11147 // FIXME: we could provide a fixit to move the qualifiers onto the
11148 // conversion type.
11149 Diag(D
.getIdentifierLoc(), diag::err_conv_function_with_complex_decl
)
11150 << SourceRange(D
.getIdentifierLoc()) << 0;
11151 D
.setInvalidType();
11153 const auto *Proto
= R
->castAs
<FunctionProtoType
>();
11154 // Make sure we don't have any parameters.
11155 DeclaratorChunk::FunctionTypeInfo
&FTI
= D
.getFunctionTypeInfo();
11156 unsigned NumParam
= Proto
->getNumParams();
11159 // A conversion function shall have no non-object parameters.
11160 if (NumParam
== 1) {
11161 DeclaratorChunk::FunctionTypeInfo
&FTI
= D
.getFunctionTypeInfo();
11162 if (const auto *First
=
11163 dyn_cast_if_present
<ParmVarDecl
>(FTI
.Params
[0].Param
);
11164 First
&& First
->isExplicitObjectParameter())
11168 if (NumParam
!= 0) {
11169 Diag(D
.getIdentifierLoc(), diag::err_conv_function_with_params
);
11170 // Delete the parameters.
11172 D
.setInvalidType();
11173 } else if (Proto
->isVariadic()) {
11174 Diag(D
.getIdentifierLoc(), diag::err_conv_function_variadic
);
11175 D
.setInvalidType();
11178 // Diagnose "&operator bool()" and other such nonsense. This
11179 // is actually a gcc extension which we don't support.
11180 if (Proto
->getReturnType() != ConvType
) {
11181 bool NeedsTypedef
= false;
11182 SourceRange Before
, After
;
11184 // Walk the chunks and extract information on them for our diagnostic.
11185 bool PastFunctionChunk
= false;
11186 for (auto &Chunk
: D
.type_objects()) {
11187 switch (Chunk
.Kind
) {
11188 case DeclaratorChunk::Function
:
11189 if (!PastFunctionChunk
) {
11190 if (Chunk
.Fun
.HasTrailingReturnType
) {
11191 TypeSourceInfo
*TRT
= nullptr;
11192 GetTypeFromParser(Chunk
.Fun
.getTrailingReturnType(), &TRT
);
11193 if (TRT
) extendRight(After
, TRT
->getTypeLoc().getSourceRange());
11195 PastFunctionChunk
= true;
11199 case DeclaratorChunk::Array
:
11200 NeedsTypedef
= true;
11201 extendRight(After
, Chunk
.getSourceRange());
11204 case DeclaratorChunk::Pointer
:
11205 case DeclaratorChunk::BlockPointer
:
11206 case DeclaratorChunk::Reference
:
11207 case DeclaratorChunk::MemberPointer
:
11208 case DeclaratorChunk::Pipe
:
11209 extendLeft(Before
, Chunk
.getSourceRange());
11212 case DeclaratorChunk::Paren
:
11213 extendLeft(Before
, Chunk
.Loc
);
11214 extendRight(After
, Chunk
.EndLoc
);
11219 SourceLocation Loc
= Before
.isValid() ? Before
.getBegin() :
11220 After
.isValid() ? After
.getBegin() :
11221 D
.getIdentifierLoc();
11222 auto &&DB
= Diag(Loc
, diag::err_conv_function_with_complex_decl
);
11223 DB
<< Before
<< After
;
11225 if (!NeedsTypedef
) {
11226 DB
<< /*don't need a typedef*/0;
11228 // If we can provide a correct fix-it hint, do so.
11229 if (After
.isInvalid() && ConvTSI
) {
11230 SourceLocation InsertLoc
=
11231 getLocForEndOfToken(ConvTSI
->getTypeLoc().getEndLoc());
11232 DB
<< FixItHint::CreateInsertion(InsertLoc
, " ")
11233 << FixItHint::CreateInsertionFromRange(
11234 InsertLoc
, CharSourceRange::getTokenRange(Before
))
11235 << FixItHint::CreateRemoval(Before
);
11237 } else if (!Proto
->getReturnType()->isDependentType()) {
11238 DB
<< /*typedef*/1 << Proto
->getReturnType();
11239 } else if (getLangOpts().CPlusPlus11
) {
11240 DB
<< /*alias template*/2 << Proto
->getReturnType();
11242 DB
<< /*might not be fixable*/3;
11245 // Recover by incorporating the other type chunks into the result type.
11246 // Note, this does *not* change the name of the function. This is compatible
11247 // with the GCC extension:
11248 // struct S { &operator int(); } s;
11249 // int &r = s.operator int(); // ok in GCC
11250 // S::operator int&() {} // error in GCC, function name is 'operator int'.
11251 ConvType
= Proto
->getReturnType();
11254 // C++ [class.conv.fct]p4:
11255 // The conversion-type-id shall not represent a function type nor
11257 if (ConvType
->isArrayType()) {
11258 Diag(D
.getIdentifierLoc(), diag::err_conv_function_to_array
);
11259 ConvType
= Context
.getPointerType(ConvType
);
11260 D
.setInvalidType();
11261 } else if (ConvType
->isFunctionType()) {
11262 Diag(D
.getIdentifierLoc(), diag::err_conv_function_to_function
);
11263 ConvType
= Context
.getPointerType(ConvType
);
11264 D
.setInvalidType();
11267 // Rebuild the function type "R" without any parameters (in case any
11268 // of the errors above fired) and with the conversion type as the
11270 if (D
.isInvalidType())
11271 R
= Context
.getFunctionType(ConvType
, std::nullopt
,
11272 Proto
->getExtProtoInfo());
11274 // C++0x explicit conversion operators.
11275 if (DS
.hasExplicitSpecifier() && !getLangOpts().CPlusPlus20
)
11276 Diag(DS
.getExplicitSpecLoc(),
11277 getLangOpts().CPlusPlus11
11278 ? diag::warn_cxx98_compat_explicit_conversion_functions
11279 : diag::ext_explicit_conversion_functions
)
11280 << SourceRange(DS
.getExplicitSpecRange());
11283 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
11284 /// the declaration of the given C++ conversion function. This routine
11285 /// is responsible for recording the conversion function in the C++
11286 /// class, if possible.
11287 Decl
*Sema::ActOnConversionDeclarator(CXXConversionDecl
*Conversion
) {
11288 assert(Conversion
&& "Expected to receive a conversion function declaration");
11290 CXXRecordDecl
*ClassDecl
= cast
<CXXRecordDecl
>(Conversion
->getDeclContext());
11292 // Make sure we aren't redeclaring the conversion function.
11293 QualType ConvType
= Context
.getCanonicalType(Conversion
->getConversionType());
11294 // C++ [class.conv.fct]p1:
11295 // [...] A conversion function is never used to convert a
11296 // (possibly cv-qualified) object to the (possibly cv-qualified)
11297 // same object type (or a reference to it), to a (possibly
11298 // cv-qualified) base class of that type (or a reference to it),
11299 // or to (possibly cv-qualified) void.
11301 = Context
.getCanonicalType(Context
.getTypeDeclType(ClassDecl
));
11302 if (const ReferenceType
*ConvTypeRef
= ConvType
->getAs
<ReferenceType
>())
11303 ConvType
= ConvTypeRef
->getPointeeType();
11304 if (Conversion
->getTemplateSpecializationKind() != TSK_Undeclared
&&
11305 Conversion
->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
)
11306 /* Suppress diagnostics for instantiations. */;
11307 else if (Conversion
->size_overridden_methods() != 0)
11308 /* Suppress diagnostics for overriding virtual function in a base class. */;
11309 else if (ConvType
->isRecordType()) {
11310 ConvType
= Context
.getCanonicalType(ConvType
).getUnqualifiedType();
11311 if (ConvType
== ClassType
)
11312 Diag(Conversion
->getLocation(), diag::warn_conv_to_self_not_used
)
11314 else if (IsDerivedFrom(Conversion
->getLocation(), ClassType
, ConvType
))
11315 Diag(Conversion
->getLocation(), diag::warn_conv_to_base_not_used
)
11316 << ClassType
<< ConvType
;
11317 } else if (ConvType
->isVoidType()) {
11318 Diag(Conversion
->getLocation(), diag::warn_conv_to_void_not_used
)
11319 << ClassType
<< ConvType
;
11322 if (FunctionTemplateDecl
*ConversionTemplate
11323 = Conversion
->getDescribedFunctionTemplate())
11324 return ConversionTemplate
;
11329 void Sema::CheckExplicitObjectMemberFunction(DeclContext
*DC
, Declarator
&D
,
11330 DeclarationName Name
, QualType R
) {
11331 CheckExplicitObjectMemberFunction(D
, Name
, R
, false, DC
);
11334 void Sema::CheckExplicitObjectLambda(Declarator
&D
) {
11335 CheckExplicitObjectMemberFunction(D
, {}, {}, true);
11338 void Sema::CheckExplicitObjectMemberFunction(Declarator
&D
,
11339 DeclarationName Name
, QualType R
,
11340 bool IsLambda
, DeclContext
*DC
) {
11341 if (!D
.isFunctionDeclarator())
11344 DeclaratorChunk::FunctionTypeInfo
&FTI
= D
.getFunctionTypeInfo();
11345 if (FTI
.NumParams
== 0)
11347 ParmVarDecl
*ExplicitObjectParam
= nullptr;
11348 for (unsigned Idx
= 0; Idx
< FTI
.NumParams
; Idx
++) {
11349 const auto &ParamInfo
= FTI
.Params
[Idx
];
11350 if (!ParamInfo
.Param
)
11352 ParmVarDecl
*Param
= cast
<ParmVarDecl
>(ParamInfo
.Param
);
11353 if (!Param
->isExplicitObjectParameter())
11356 ExplicitObjectParam
= Param
;
11359 Diag(Param
->getLocation(),
11360 diag::err_explicit_object_parameter_must_be_first
)
11361 << IsLambda
<< Param
->getSourceRange();
11364 if (!ExplicitObjectParam
)
11367 if (ExplicitObjectParam
->hasDefaultArg()) {
11368 Diag(ExplicitObjectParam
->getLocation(),
11369 diag::err_explicit_object_default_arg
)
11370 << ExplicitObjectParam
->getSourceRange();
11373 if (D
.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static
) {
11374 Diag(ExplicitObjectParam
->getBeginLoc(),
11375 diag::err_explicit_object_parameter_nonmember
)
11376 << D
.getSourceRange() << /*static=*/0 << IsLambda
;
11377 D
.setInvalidType();
11380 if (D
.getDeclSpec().isVirtualSpecified()) {
11381 Diag(ExplicitObjectParam
->getBeginLoc(),
11382 diag::err_explicit_object_parameter_nonmember
)
11383 << D
.getSourceRange() << /*virtual=*/1 << IsLambda
;
11384 D
.setInvalidType();
11387 if (IsLambda
&& FTI
.hasMutableQualifier()) {
11388 Diag(ExplicitObjectParam
->getBeginLoc(),
11389 diag::err_explicit_object_parameter_mutable
)
11390 << D
.getSourceRange();
11396 if (!DC
|| !DC
->isRecord()) {
11397 Diag(ExplicitObjectParam
->getLocation(),
11398 diag::err_explicit_object_parameter_nonmember
)
11399 << D
.getSourceRange() << /*non-member=*/2 << IsLambda
;
11400 D
.setInvalidType();
11404 // CWG2674: constructors and destructors cannot have explicit parameters.
11405 if (Name
.getNameKind() == DeclarationName::CXXConstructorName
||
11406 Name
.getNameKind() == DeclarationName::CXXDestructorName
) {
11407 Diag(ExplicitObjectParam
->getBeginLoc(),
11408 diag::err_explicit_object_parameter_constructor
)
11409 << (Name
.getNameKind() == DeclarationName::CXXDestructorName
)
11410 << D
.getSourceRange();
11411 D
.setInvalidType();
11416 /// Utility class to accumulate and print a diagnostic listing the invalid
11417 /// specifier(s) on a declaration.
11418 struct BadSpecifierDiagnoser
{
11419 BadSpecifierDiagnoser(Sema
&S
, SourceLocation Loc
, unsigned DiagID
)
11420 : S(S
), Diagnostic(S
.Diag(Loc
, DiagID
)) {}
11421 ~BadSpecifierDiagnoser() {
11422 Diagnostic
<< Specifiers
;
11425 template<typename T
> void check(SourceLocation SpecLoc
, T Spec
) {
11426 return check(SpecLoc
, DeclSpec::getSpecifierName(Spec
));
11428 void check(SourceLocation SpecLoc
, DeclSpec::TST Spec
) {
11429 return check(SpecLoc
,
11430 DeclSpec::getSpecifierName(Spec
, S
.getPrintingPolicy()));
11432 void check(SourceLocation SpecLoc
, const char *Spec
) {
11433 if (SpecLoc
.isInvalid()) return;
11434 Diagnostic
<< SourceRange(SpecLoc
, SpecLoc
);
11435 if (!Specifiers
.empty()) Specifiers
+= " ";
11436 Specifiers
+= Spec
;
11440 Sema::SemaDiagnosticBuilder Diagnostic
;
11441 std::string Specifiers
;
11445 /// Check the validity of a declarator that we parsed for a deduction-guide.
11446 /// These aren't actually declarators in the grammar, so we need to check that
11447 /// the user didn't specify any pieces that are not part of the deduction-guide
11448 /// grammar. Return true on invalid deduction-guide.
11449 bool Sema::CheckDeductionGuideDeclarator(Declarator
&D
, QualType
&R
,
11450 StorageClass
&SC
) {
11451 TemplateName GuidedTemplate
= D
.getName().TemplateName
.get().get();
11452 TemplateDecl
*GuidedTemplateDecl
= GuidedTemplate
.getAsTemplateDecl();
11453 assert(GuidedTemplateDecl
&& "missing template decl for deduction guide");
11455 // C++ [temp.deduct.guide]p3:
11456 // A deduction-gide shall be declared in the same scope as the
11457 // corresponding class template.
11458 if (!CurContext
->getRedeclContext()->Equals(
11459 GuidedTemplateDecl
->getDeclContext()->getRedeclContext())) {
11460 Diag(D
.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope
)
11461 << GuidedTemplateDecl
;
11462 Diag(GuidedTemplateDecl
->getLocation(), diag::note_template_decl_here
);
11465 auto &DS
= D
.getMutableDeclSpec();
11466 // We leave 'friend' and 'virtual' to be rejected in the normal way.
11467 if (DS
.hasTypeSpecifier() || DS
.getTypeQualifiers() ||
11468 DS
.getStorageClassSpecLoc().isValid() || DS
.isInlineSpecified() ||
11469 DS
.isNoreturnSpecified() || DS
.hasConstexprSpecifier()) {
11470 BadSpecifierDiagnoser
Diagnoser(
11471 *this, D
.getIdentifierLoc(),
11472 diag::err_deduction_guide_invalid_specifier
);
11474 Diagnoser
.check(DS
.getStorageClassSpecLoc(), DS
.getStorageClassSpec());
11475 DS
.ClearStorageClassSpecs();
11478 // 'explicit' is permitted.
11479 Diagnoser
.check(DS
.getInlineSpecLoc(), "inline");
11480 Diagnoser
.check(DS
.getNoreturnSpecLoc(), "_Noreturn");
11481 Diagnoser
.check(DS
.getConstexprSpecLoc(), "constexpr");
11482 DS
.ClearConstexprSpec();
11484 Diagnoser
.check(DS
.getConstSpecLoc(), "const");
11485 Diagnoser
.check(DS
.getRestrictSpecLoc(), "__restrict");
11486 Diagnoser
.check(DS
.getVolatileSpecLoc(), "volatile");
11487 Diagnoser
.check(DS
.getAtomicSpecLoc(), "_Atomic");
11488 Diagnoser
.check(DS
.getUnalignedSpecLoc(), "__unaligned");
11489 DS
.ClearTypeQualifiers();
11491 Diagnoser
.check(DS
.getTypeSpecComplexLoc(), DS
.getTypeSpecComplex());
11492 Diagnoser
.check(DS
.getTypeSpecSignLoc(), DS
.getTypeSpecSign());
11493 Diagnoser
.check(DS
.getTypeSpecWidthLoc(), DS
.getTypeSpecWidth());
11494 Diagnoser
.check(DS
.getTypeSpecTypeLoc(), DS
.getTypeSpecType());
11495 DS
.ClearTypeSpecType();
11498 if (D
.isInvalidType())
11501 // Check the declarator is simple enough.
11502 bool FoundFunction
= false;
11503 for (const DeclaratorChunk
&Chunk
: llvm::reverse(D
.type_objects())) {
11504 if (Chunk
.Kind
== DeclaratorChunk::Paren
)
11506 if (Chunk
.Kind
!= DeclaratorChunk::Function
|| FoundFunction
) {
11507 Diag(D
.getDeclSpec().getBeginLoc(),
11508 diag::err_deduction_guide_with_complex_decl
)
11509 << D
.getSourceRange();
11512 if (!Chunk
.Fun
.hasTrailingReturnType())
11513 return Diag(D
.getName().getBeginLoc(),
11514 diag::err_deduction_guide_no_trailing_return_type
);
11516 // Check that the return type is written as a specialization of
11517 // the template specified as the deduction-guide's name.
11518 // The template name may not be qualified. [temp.deduct.guide]
11519 ParsedType TrailingReturnType
= Chunk
.Fun
.getTrailingReturnType();
11520 TypeSourceInfo
*TSI
= nullptr;
11521 QualType RetTy
= GetTypeFromParser(TrailingReturnType
, &TSI
);
11522 assert(TSI
&& "deduction guide has valid type but invalid return type?");
11523 bool AcceptableReturnType
= false;
11524 bool MightInstantiateToSpecialization
= false;
11526 TSI
->getTypeLoc().getAsAdjusted
<TemplateSpecializationTypeLoc
>()) {
11527 TemplateName SpecifiedName
= RetTST
.getTypePtr()->getTemplateName();
11528 bool TemplateMatches
=
11529 Context
.hasSameTemplateName(SpecifiedName
, GuidedTemplate
);
11530 auto TKind
= SpecifiedName
.getKind();
11531 // A Using TemplateName can't actually be valid (either it's qualified, or
11532 // we're in the wrong scope). But we have diagnosed these problems
11534 bool SimplyWritten
= TKind
== TemplateName::Template
||
11535 TKind
== TemplateName::UsingTemplate
;
11536 if (SimplyWritten
&& TemplateMatches
)
11537 AcceptableReturnType
= true;
11539 // This could still instantiate to the right type, unless we know it
11540 // names the wrong class template.
11541 auto *TD
= SpecifiedName
.getAsTemplateDecl();
11542 MightInstantiateToSpecialization
= !(TD
&& isa
<ClassTemplateDecl
>(TD
) &&
11545 } else if (!RetTy
.hasQualifiers() && RetTy
->isDependentType()) {
11546 MightInstantiateToSpecialization
= true;
11549 if (!AcceptableReturnType
)
11550 return Diag(TSI
->getTypeLoc().getBeginLoc(),
11551 diag::err_deduction_guide_bad_trailing_return_type
)
11552 << GuidedTemplate
<< TSI
->getType()
11553 << MightInstantiateToSpecialization
11554 << TSI
->getTypeLoc().getSourceRange();
11556 // Keep going to check that we don't have any inner declarator pieces (we
11557 // could still have a function returning a pointer to a function).
11558 FoundFunction
= true;
11561 if (D
.isFunctionDefinition())
11562 // we can still create a valid deduction guide here.
11563 Diag(D
.getIdentifierLoc(), diag::err_deduction_guide_defines_function
);
11567 //===----------------------------------------------------------------------===//
11568 // Namespace Handling
11569 //===----------------------------------------------------------------------===//
11571 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is
11573 static void DiagnoseNamespaceInlineMismatch(Sema
&S
, SourceLocation KeywordLoc
,
11574 SourceLocation Loc
,
11575 IdentifierInfo
*II
, bool *IsInline
,
11576 NamespaceDecl
*PrevNS
) {
11577 assert(*IsInline
!= PrevNS
->isInline());
11579 // 'inline' must appear on the original definition, but not necessarily
11580 // on all extension definitions, so the note should point to the first
11581 // definition to avoid confusion.
11582 PrevNS
= PrevNS
->getFirstDecl();
11584 if (PrevNS
->isInline())
11585 // The user probably just forgot the 'inline', so suggest that it
11587 S
.Diag(Loc
, diag::warn_inline_namespace_reopened_noninline
)
11588 << FixItHint::CreateInsertion(KeywordLoc
, "inline ");
11590 S
.Diag(Loc
, diag::err_inline_namespace_mismatch
);
11592 S
.Diag(PrevNS
->getLocation(), diag::note_previous_definition
);
11593 *IsInline
= PrevNS
->isInline();
11596 /// ActOnStartNamespaceDef - This is called at the start of a namespace
11598 Decl
*Sema::ActOnStartNamespaceDef(Scope
*NamespcScope
,
11599 SourceLocation InlineLoc
,
11600 SourceLocation NamespaceLoc
,
11601 SourceLocation IdentLoc
, IdentifierInfo
*II
,
11602 SourceLocation LBrace
,
11603 const ParsedAttributesView
&AttrList
,
11604 UsingDirectiveDecl
*&UD
, bool IsNested
) {
11605 SourceLocation StartLoc
= InlineLoc
.isValid() ? InlineLoc
: NamespaceLoc
;
11606 // For anonymous namespace, take the location of the left brace.
11607 SourceLocation Loc
= II
? IdentLoc
: LBrace
;
11608 bool IsInline
= InlineLoc
.isValid();
11609 bool IsInvalid
= false;
11610 bool IsStd
= false;
11611 bool AddToKnown
= false;
11612 Scope
*DeclRegionScope
= NamespcScope
->getParent();
11614 NamespaceDecl
*PrevNS
= nullptr;
11616 // C++ [namespace.std]p7:
11617 // A translation unit shall not declare namespace std to be an inline
11618 // namespace (9.8.2).
11620 // Precondition: the std namespace is in the file scope and is declared to
11622 auto DiagnoseInlineStdNS
= [&]() {
11623 assert(IsInline
&& II
->isStr("std") &&
11624 CurContext
->getRedeclContext()->isTranslationUnit() &&
11625 "Precondition of DiagnoseInlineStdNS not met");
11626 Diag(InlineLoc
, diag::err_inline_namespace_std
)
11627 << SourceRange(InlineLoc
, InlineLoc
.getLocWithOffset(6));
11630 // C++ [namespace.def]p2:
11631 // The identifier in an original-namespace-definition shall not
11632 // have been previously defined in the declarative region in
11633 // which the original-namespace-definition appears. The
11634 // identifier in an original-namespace-definition is the name of
11635 // the namespace. Subsequently in that declarative region, it is
11636 // treated as an original-namespace-name.
11638 // Since namespace names are unique in their scope, and we don't
11639 // look through using directives, just look for any ordinary names
11640 // as if by qualified name lookup.
11641 LookupResult
R(*this, II
, IdentLoc
, LookupOrdinaryName
,
11642 ForExternalRedeclaration
);
11643 LookupQualifiedName(R
, CurContext
->getRedeclContext());
11644 NamedDecl
*PrevDecl
=
11645 R
.isSingleResult() ? R
.getRepresentativeDecl() : nullptr;
11646 PrevNS
= dyn_cast_or_null
<NamespaceDecl
>(PrevDecl
);
11649 // This is an extended namespace definition.
11650 if (IsInline
&& II
->isStr("std") &&
11651 CurContext
->getRedeclContext()->isTranslationUnit())
11652 DiagnoseInlineStdNS();
11653 else if (IsInline
!= PrevNS
->isInline())
11654 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc
, Loc
, II
,
11655 &IsInline
, PrevNS
);
11656 } else if (PrevDecl
) {
11657 // This is an invalid name redefinition.
11658 Diag(Loc
, diag::err_redefinition_different_kind
)
11660 Diag(PrevDecl
->getLocation(), diag::note_previous_definition
);
11662 // Continue on to push Namespc as current DeclContext and return it.
11663 } else if (II
->isStr("std") &&
11664 CurContext
->getRedeclContext()->isTranslationUnit()) {
11666 DiagnoseInlineStdNS();
11667 // This is the first "real" definition of the namespace "std", so update
11668 // our cache of the "std" namespace to point at this definition.
11669 PrevNS
= getStdNamespace();
11671 AddToKnown
= !IsInline
;
11673 // We've seen this namespace for the first time.
11674 AddToKnown
= !IsInline
;
11677 // Anonymous namespaces.
11679 // Determine whether the parent already has an anonymous namespace.
11680 DeclContext
*Parent
= CurContext
->getRedeclContext();
11681 if (TranslationUnitDecl
*TU
= dyn_cast
<TranslationUnitDecl
>(Parent
)) {
11682 PrevNS
= TU
->getAnonymousNamespace();
11684 NamespaceDecl
*ND
= cast
<NamespaceDecl
>(Parent
);
11685 PrevNS
= ND
->getAnonymousNamespace();
11688 if (PrevNS
&& IsInline
!= PrevNS
->isInline())
11689 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc
, NamespaceLoc
, II
,
11690 &IsInline
, PrevNS
);
11693 NamespaceDecl
*Namespc
= NamespaceDecl::Create(
11694 Context
, CurContext
, IsInline
, StartLoc
, Loc
, II
, PrevNS
, IsNested
);
11696 Namespc
->setInvalidDecl();
11698 ProcessDeclAttributeList(DeclRegionScope
, Namespc
, AttrList
);
11699 AddPragmaAttributes(DeclRegionScope
, Namespc
);
11701 // FIXME: Should we be merging attributes?
11702 if (const VisibilityAttr
*Attr
= Namespc
->getAttr
<VisibilityAttr
>())
11703 PushNamespaceVisibilityAttr(Attr
, Loc
);
11706 StdNamespace
= Namespc
;
11708 KnownNamespaces
[Namespc
] = false;
11711 PushOnScopeChains(Namespc
, DeclRegionScope
);
11713 // Link the anonymous namespace into its parent.
11714 DeclContext
*Parent
= CurContext
->getRedeclContext();
11715 if (TranslationUnitDecl
*TU
= dyn_cast
<TranslationUnitDecl
>(Parent
)) {
11716 TU
->setAnonymousNamespace(Namespc
);
11718 cast
<NamespaceDecl
>(Parent
)->setAnonymousNamespace(Namespc
);
11721 CurContext
->addDecl(Namespc
);
11723 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
11724 // behaves as if it were replaced by
11725 // namespace unique { /* empty body */ }
11726 // using namespace unique;
11727 // namespace unique { namespace-body }
11728 // where all occurrences of 'unique' in a translation unit are
11729 // replaced by the same identifier and this identifier differs
11730 // from all other identifiers in the entire program.
11732 // We just create the namespace with an empty name and then add an
11733 // implicit using declaration, just like the standard suggests.
11735 // CodeGen enforces the "universally unique" aspect by giving all
11736 // declarations semantically contained within an anonymous
11737 // namespace internal linkage.
11740 UD
= UsingDirectiveDecl::Create(Context
, Parent
,
11741 /* 'using' */ LBrace
,
11742 /* 'namespace' */ SourceLocation(),
11743 /* qualifier */ NestedNameSpecifierLoc(),
11744 /* identifier */ SourceLocation(),
11746 /* Ancestor */ Parent
);
11748 Parent
->addDecl(UD
);
11752 ActOnDocumentableDecl(Namespc
);
11754 // Although we could have an invalid decl (i.e. the namespace name is a
11755 // redefinition), push it as current DeclContext and try to continue parsing.
11756 // FIXME: We should be able to push Namespc here, so that the each DeclContext
11757 // for the namespace has the declarations that showed up in that particular
11758 // namespace definition.
11759 PushDeclContext(NamespcScope
, Namespc
);
11763 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
11764 /// is a namespace alias, returns the namespace it points to.
11765 static inline NamespaceDecl
*getNamespaceDecl(NamedDecl
*D
) {
11766 if (NamespaceAliasDecl
*AD
= dyn_cast_or_null
<NamespaceAliasDecl
>(D
))
11767 return AD
->getNamespace();
11768 return dyn_cast_or_null
<NamespaceDecl
>(D
);
11771 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
11772 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
11773 void Sema::ActOnFinishNamespaceDef(Decl
*Dcl
, SourceLocation RBrace
) {
11774 NamespaceDecl
*Namespc
= dyn_cast_or_null
<NamespaceDecl
>(Dcl
);
11775 assert(Namespc
&& "Invalid parameter, expected NamespaceDecl");
11776 Namespc
->setRBraceLoc(RBrace
);
11778 if (Namespc
->hasAttr
<VisibilityAttr
>())
11779 PopPragmaVisibility(true, RBrace
);
11780 // If this namespace contains an export-declaration, export it now.
11781 if (DeferredExportedNamespaces
.erase(Namespc
))
11782 Dcl
->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported
);
11785 CXXRecordDecl
*Sema::getStdBadAlloc() const {
11786 return cast_or_null
<CXXRecordDecl
>(
11787 StdBadAlloc
.get(Context
.getExternalSource()));
11790 EnumDecl
*Sema::getStdAlignValT() const {
11791 return cast_or_null
<EnumDecl
>(StdAlignValT
.get(Context
.getExternalSource()));
11794 NamespaceDecl
*Sema::getStdNamespace() const {
11795 return cast_or_null
<NamespaceDecl
>(
11796 StdNamespace
.get(Context
.getExternalSource()));
11800 enum UnsupportedSTLSelect
{
11807 struct InvalidSTLDiagnoser
{
11809 SourceLocation Loc
;
11810 QualType TyForDiags
;
11812 QualType
operator()(UnsupportedSTLSelect Sel
= USS_Other
, StringRef Name
= "",
11813 const VarDecl
*VD
= nullptr) {
11815 auto D
= S
.Diag(Loc
, diag::err_std_compare_type_not_supported
)
11816 << TyForDiags
<< ((int)Sel
);
11817 if (Sel
== USS_InvalidMember
|| Sel
== USS_MissingMember
) {
11818 assert(!Name
.empty());
11822 if (Sel
== USS_InvalidMember
) {
11823 S
.Diag(VD
->getLocation(), diag::note_var_declared_here
)
11824 << VD
<< VD
->getSourceRange();
11831 QualType
Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind
,
11832 SourceLocation Loc
,
11833 ComparisonCategoryUsage Usage
) {
11834 assert(getLangOpts().CPlusPlus
&&
11835 "Looking for comparison category type outside of C++.");
11837 // Use an elaborated type for diagnostics which has a name containing the
11838 // prepended 'std' namespace but not any inline namespace names.
11839 auto TyForDiags
= [&](ComparisonCategoryInfo
*Info
) {
11841 NestedNameSpecifier::Create(Context
, nullptr, getStdNamespace());
11842 return Context
.getElaboratedType(ElaboratedTypeKeyword::None
, NNS
,
11846 // Check if we've already successfully checked the comparison category type
11847 // before. If so, skip checking it again.
11848 ComparisonCategoryInfo
*Info
= Context
.CompCategories
.lookupInfo(Kind
);
11849 if (Info
&& FullyCheckedComparisonCategories
[static_cast<unsigned>(Kind
)]) {
11850 // The only thing we need to check is that the type has a reachable
11851 // definition in the current context.
11852 if (RequireCompleteType(Loc
, TyForDiags(Info
), diag::err_incomplete_type
))
11855 return Info
->getType();
11858 // If lookup failed
11860 std::string NameForDiags
= "std::";
11861 NameForDiags
+= ComparisonCategories::getCategoryString(Kind
);
11862 Diag(Loc
, diag::err_implied_comparison_category_type_not_found
)
11863 << NameForDiags
<< (int)Usage
;
11867 assert(Info
->Kind
== Kind
);
11868 assert(Info
->Record
);
11870 // Update the Record decl in case we encountered a forward declaration on our
11871 // first pass. FIXME: This is a bit of a hack.
11872 if (Info
->Record
->hasDefinition())
11873 Info
->Record
= Info
->Record
->getDefinition();
11875 if (RequireCompleteType(Loc
, TyForDiags(Info
), diag::err_incomplete_type
))
11878 InvalidSTLDiagnoser UnsupportedSTLError
{*this, Loc
, TyForDiags(Info
)};
11880 if (!Info
->Record
->isTriviallyCopyable())
11881 return UnsupportedSTLError(USS_NonTrivial
);
11883 for (const CXXBaseSpecifier
&BaseSpec
: Info
->Record
->bases()) {
11884 CXXRecordDecl
*Base
= BaseSpec
.getType()->getAsCXXRecordDecl();
11885 // Tolerate empty base classes.
11886 if (Base
->isEmpty())
11888 // Reject STL implementations which have at least one non-empty base.
11889 return UnsupportedSTLError();
11892 // Check that the STL has implemented the types using a single integer field.
11893 // This expectation allows better codegen for builtin operators. We require:
11894 // (1) The class has exactly one field.
11895 // (2) The field is an integral or enumeration type.
11896 auto FIt
= Info
->Record
->field_begin(), FEnd
= Info
->Record
->field_end();
11897 if (std::distance(FIt
, FEnd
) != 1 ||
11898 !FIt
->getType()->isIntegralOrEnumerationType()) {
11899 return UnsupportedSTLError();
11902 // Build each of the require values and store them in Info.
11903 for (ComparisonCategoryResult CCR
:
11904 ComparisonCategories::getPossibleResultsForType(Kind
)) {
11905 StringRef MemName
= ComparisonCategories::getResultString(CCR
);
11906 ComparisonCategoryInfo::ValueInfo
*ValInfo
= Info
->lookupValueInfo(CCR
);
11909 return UnsupportedSTLError(USS_MissingMember
, MemName
);
11911 VarDecl
*VD
= ValInfo
->VD
;
11912 assert(VD
&& "should not be null!");
11914 // Attempt to diagnose reasons why the STL definition of this type
11915 // might be foobar, including it failing to be a constant expression.
11916 // TODO Handle more ways the lookup or result can be invalid.
11917 if (!VD
->isStaticDataMember() ||
11918 !VD
->isUsableInConstantExpressions(Context
))
11919 return UnsupportedSTLError(USS_InvalidMember
, MemName
, VD
);
11921 // Attempt to evaluate the var decl as a constant expression and extract
11922 // the value of its first field as a ICE. If this fails, the STL
11923 // implementation is not supported.
11924 if (!ValInfo
->hasValidIntValue())
11925 return UnsupportedSTLError();
11927 MarkVariableReferenced(Loc
, VD
);
11930 // We've successfully built the required types and expressions. Update
11931 // the cache and return the newly cached value.
11932 FullyCheckedComparisonCategories
[static_cast<unsigned>(Kind
)] = true;
11933 return Info
->getType();
11936 /// Retrieve the special "std" namespace, which may require us to
11937 /// implicitly define the namespace.
11938 NamespaceDecl
*Sema::getOrCreateStdNamespace() {
11939 if (!StdNamespace
) {
11940 // The "std" namespace has not yet been defined, so build one implicitly.
11941 StdNamespace
= NamespaceDecl::Create(
11942 Context
, Context
.getTranslationUnitDecl(),
11943 /*Inline=*/false, SourceLocation(), SourceLocation(),
11944 &PP
.getIdentifierTable().get("std"),
11945 /*PrevDecl=*/nullptr, /*Nested=*/false);
11946 getStdNamespace()->setImplicit(true);
11947 // We want the created NamespaceDecl to be available for redeclaration
11948 // lookups, but not for regular name lookups.
11949 Context
.getTranslationUnitDecl()->addDecl(getStdNamespace());
11950 getStdNamespace()->clearIdentifierNamespace();
11953 return getStdNamespace();
11956 bool Sema::isStdInitializerList(QualType Ty
, QualType
*Element
) {
11957 assert(getLangOpts().CPlusPlus
&&
11958 "Looking for std::initializer_list outside of C++.");
11960 // We're looking for implicit instantiations of
11961 // template <typename E> class std::initializer_list.
11963 if (!StdNamespace
) // If we haven't seen namespace std yet, this can't be it.
11966 ClassTemplateDecl
*Template
= nullptr;
11967 const TemplateArgument
*Arguments
= nullptr;
11969 if (const RecordType
*RT
= Ty
->getAs
<RecordType
>()) {
11971 ClassTemplateSpecializationDecl
*Specialization
=
11972 dyn_cast
<ClassTemplateSpecializationDecl
>(RT
->getDecl());
11973 if (!Specialization
)
11976 Template
= Specialization
->getSpecializedTemplate();
11977 Arguments
= Specialization
->getTemplateArgs().data();
11978 } else if (const TemplateSpecializationType
*TST
=
11979 Ty
->getAs
<TemplateSpecializationType
>()) {
11980 Template
= dyn_cast_or_null
<ClassTemplateDecl
>(
11981 TST
->getTemplateName().getAsTemplateDecl());
11982 Arguments
= TST
->template_arguments().begin();
11987 if (!StdInitializerList
) {
11988 // Haven't recognized std::initializer_list yet, maybe this is it.
11989 CXXRecordDecl
*TemplateClass
= Template
->getTemplatedDecl();
11990 if (TemplateClass
->getIdentifier() !=
11991 &PP
.getIdentifierTable().get("initializer_list") ||
11992 !getStdNamespace()->InEnclosingNamespaceSetOf(
11993 TemplateClass
->getDeclContext()))
11995 // This is a template called std::initializer_list, but is it the right
11997 TemplateParameterList
*Params
= Template
->getTemplateParameters();
11998 if (Params
->getMinRequiredArguments() != 1)
12000 if (!isa
<TemplateTypeParmDecl
>(Params
->getParam(0)))
12003 // It's the right template.
12004 StdInitializerList
= Template
;
12007 if (Template
->getCanonicalDecl() != StdInitializerList
->getCanonicalDecl())
12010 // This is an instance of std::initializer_list. Find the argument type.
12012 *Element
= Arguments
[0].getAsType();
12016 static ClassTemplateDecl
*LookupStdInitializerList(Sema
&S
, SourceLocation Loc
){
12017 NamespaceDecl
*Std
= S
.getStdNamespace();
12019 S
.Diag(Loc
, diag::err_implied_std_initializer_list_not_found
);
12023 LookupResult
Result(S
, &S
.PP
.getIdentifierTable().get("initializer_list"),
12024 Loc
, Sema::LookupOrdinaryName
);
12025 if (!S
.LookupQualifiedName(Result
, Std
)) {
12026 S
.Diag(Loc
, diag::err_implied_std_initializer_list_not_found
);
12029 ClassTemplateDecl
*Template
= Result
.getAsSingle
<ClassTemplateDecl
>();
12031 Result
.suppressDiagnostics();
12032 // We found something weird. Complain about the first thing we found.
12033 NamedDecl
*Found
= *Result
.begin();
12034 S
.Diag(Found
->getLocation(), diag::err_malformed_std_initializer_list
);
12038 // We found some template called std::initializer_list. Now verify that it's
12040 TemplateParameterList
*Params
= Template
->getTemplateParameters();
12041 if (Params
->getMinRequiredArguments() != 1 ||
12042 !isa
<TemplateTypeParmDecl
>(Params
->getParam(0))) {
12043 S
.Diag(Template
->getLocation(), diag::err_malformed_std_initializer_list
);
12050 QualType
Sema::BuildStdInitializerList(QualType Element
, SourceLocation Loc
) {
12051 if (!StdInitializerList
) {
12052 StdInitializerList
= LookupStdInitializerList(*this, Loc
);
12053 if (!StdInitializerList
)
12057 TemplateArgumentListInfo
Args(Loc
, Loc
);
12058 Args
.addArgument(TemplateArgumentLoc(TemplateArgument(Element
),
12059 Context
.getTrivialTypeSourceInfo(Element
,
12061 return Context
.getElaboratedType(
12062 ElaboratedTypeKeyword::None
,
12063 NestedNameSpecifier::Create(Context
, nullptr, getStdNamespace()),
12064 CheckTemplateIdType(TemplateName(StdInitializerList
), Loc
, Args
));
12067 bool Sema::isInitListConstructor(const FunctionDecl
*Ctor
) {
12068 // C++ [dcl.init.list]p2:
12069 // A constructor is an initializer-list constructor if its first parameter
12070 // is of type std::initializer_list<E> or reference to possibly cv-qualified
12071 // std::initializer_list<E> for some type E, and either there are no other
12072 // parameters or else all other parameters have default arguments.
12073 if (!Ctor
->hasOneParamOrDefaultArgs())
12076 QualType ArgType
= Ctor
->getParamDecl(0)->getType();
12077 if (const ReferenceType
*RT
= ArgType
->getAs
<ReferenceType
>())
12078 ArgType
= RT
->getPointeeType().getUnqualifiedType();
12080 return isStdInitializerList(ArgType
, nullptr);
12083 /// Determine whether a using statement is in a context where it will be
12084 /// apply in all contexts.
12085 static bool IsUsingDirectiveInToplevelContext(DeclContext
*CurContext
) {
12086 switch (CurContext
->getDeclKind()) {
12087 case Decl::TranslationUnit
:
12089 case Decl::LinkageSpec
:
12090 return IsUsingDirectiveInToplevelContext(CurContext
->getParent());
12098 // Callback to only accept typo corrections that are namespaces.
12099 class NamespaceValidatorCCC final
: public CorrectionCandidateCallback
{
12101 bool ValidateCandidate(const TypoCorrection
&candidate
) override
{
12102 if (NamedDecl
*ND
= candidate
.getCorrectionDecl())
12103 return isa
<NamespaceDecl
>(ND
) || isa
<NamespaceAliasDecl
>(ND
);
12107 std::unique_ptr
<CorrectionCandidateCallback
> clone() override
{
12108 return std::make_unique
<NamespaceValidatorCCC
>(*this);
12114 static bool TryNamespaceTypoCorrection(Sema
&S
, LookupResult
&R
, Scope
*Sc
,
12116 SourceLocation IdentLoc
,
12117 IdentifierInfo
*Ident
) {
12119 NamespaceValidatorCCC CCC
{};
12120 if (TypoCorrection Corrected
=
12121 S
.CorrectTypo(R
.getLookupNameInfo(), R
.getLookupKind(), Sc
, &SS
, CCC
,
12122 Sema::CTK_ErrorRecovery
)) {
12123 if (DeclContext
*DC
= S
.computeDeclContext(SS
, false)) {
12124 std::string
CorrectedStr(Corrected
.getAsString(S
.getLangOpts()));
12125 bool DroppedSpecifier
= Corrected
.WillReplaceSpecifier() &&
12126 Ident
->getName().equals(CorrectedStr
);
12127 S
.diagnoseTypo(Corrected
,
12128 S
.PDiag(diag::err_using_directive_member_suggest
)
12129 << Ident
<< DC
<< DroppedSpecifier
<< SS
.getRange(),
12130 S
.PDiag(diag::note_namespace_defined_here
));
12132 S
.diagnoseTypo(Corrected
,
12133 S
.PDiag(diag::err_using_directive_suggest
) << Ident
,
12134 S
.PDiag(diag::note_namespace_defined_here
));
12136 R
.addDecl(Corrected
.getFoundDecl());
12142 Decl
*Sema::ActOnUsingDirective(Scope
*S
, SourceLocation UsingLoc
,
12143 SourceLocation NamespcLoc
, CXXScopeSpec
&SS
,
12144 SourceLocation IdentLoc
,
12145 IdentifierInfo
*NamespcName
,
12146 const ParsedAttributesView
&AttrList
) {
12147 assert(!SS
.isInvalid() && "Invalid CXXScopeSpec.");
12148 assert(NamespcName
&& "Invalid NamespcName.");
12149 assert(IdentLoc
.isValid() && "Invalid NamespceName location.");
12151 // This can only happen along a recovery path.
12152 while (S
->isTemplateParamScope())
12153 S
= S
->getParent();
12154 assert(S
->getFlags() & Scope::DeclScope
&& "Invalid Scope.");
12156 UsingDirectiveDecl
*UDir
= nullptr;
12157 NestedNameSpecifier
*Qualifier
= nullptr;
12159 Qualifier
= SS
.getScopeRep();
12161 // Lookup namespace name.
12162 LookupResult
R(*this, NamespcName
, IdentLoc
, LookupNamespaceName
);
12163 LookupParsedName(R
, S
, &SS
);
12164 if (R
.isAmbiguous())
12169 // Allow "using namespace std;" or "using namespace ::std;" even if
12170 // "std" hasn't been defined yet, for GCC compatibility.
12171 if ((!Qualifier
|| Qualifier
->getKind() == NestedNameSpecifier::Global
) &&
12172 NamespcName
->isStr("std")) {
12173 Diag(IdentLoc
, diag::ext_using_undefined_std
);
12174 R
.addDecl(getOrCreateStdNamespace());
12177 // Otherwise, attempt typo correction.
12178 else TryNamespaceTypoCorrection(*this, R
, S
, SS
, IdentLoc
, NamespcName
);
12182 NamedDecl
*Named
= R
.getRepresentativeDecl();
12183 NamespaceDecl
*NS
= R
.getAsSingle
<NamespaceDecl
>();
12184 assert(NS
&& "expected namespace decl");
12186 // The use of a nested name specifier may trigger deprecation warnings.
12187 DiagnoseUseOfDecl(Named
, IdentLoc
);
12189 // C++ [namespace.udir]p1:
12190 // A using-directive specifies that the names in the nominated
12191 // namespace can be used in the scope in which the
12192 // using-directive appears after the using-directive. During
12193 // unqualified name lookup (3.4.1), the names appear as if they
12194 // were declared in the nearest enclosing namespace which
12195 // contains both the using-directive and the nominated
12196 // namespace. [Note: in this context, "contains" means "contains
12197 // directly or indirectly". ]
12199 // Find enclosing context containing both using-directive and
12200 // nominated namespace.
12201 DeclContext
*CommonAncestor
= NS
;
12202 while (CommonAncestor
&& !CommonAncestor
->Encloses(CurContext
))
12203 CommonAncestor
= CommonAncestor
->getParent();
12205 UDir
= UsingDirectiveDecl::Create(Context
, CurContext
, UsingLoc
, NamespcLoc
,
12206 SS
.getWithLocInContext(Context
),
12207 IdentLoc
, Named
, CommonAncestor
);
12209 if (IsUsingDirectiveInToplevelContext(CurContext
) &&
12210 !SourceMgr
.isInMainFile(SourceMgr
.getExpansionLoc(IdentLoc
))) {
12211 Diag(IdentLoc
, diag::warn_using_directive_in_header
);
12214 PushUsingDirective(S
, UDir
);
12216 Diag(IdentLoc
, diag::err_expected_namespace_name
) << SS
.getRange();
12220 ProcessDeclAttributeList(S
, UDir
, AttrList
);
12225 void Sema::PushUsingDirective(Scope
*S
, UsingDirectiveDecl
*UDir
) {
12226 // If the scope has an associated entity and the using directive is at
12227 // namespace or translation unit scope, add the UsingDirectiveDecl into
12228 // its lookup structure so qualified name lookup can find it.
12229 DeclContext
*Ctx
= S
->getEntity();
12230 if (Ctx
&& !Ctx
->isFunctionOrMethod())
12231 Ctx
->addDecl(UDir
);
12233 // Otherwise, it is at block scope. The using-directives will affect lookup
12234 // only to the end of the scope.
12235 S
->PushUsingDirective(UDir
);
12238 Decl
*Sema::ActOnUsingDeclaration(Scope
*S
, AccessSpecifier AS
,
12239 SourceLocation UsingLoc
,
12240 SourceLocation TypenameLoc
, CXXScopeSpec
&SS
,
12241 UnqualifiedId
&Name
,
12242 SourceLocation EllipsisLoc
,
12243 const ParsedAttributesView
&AttrList
) {
12244 assert(S
->getFlags() & Scope::DeclScope
&& "Invalid Scope.");
12246 if (SS
.isEmpty()) {
12247 Diag(Name
.getBeginLoc(), diag::err_using_requires_qualname
);
12251 switch (Name
.getKind()) {
12252 case UnqualifiedIdKind::IK_ImplicitSelfParam
:
12253 case UnqualifiedIdKind::IK_Identifier
:
12254 case UnqualifiedIdKind::IK_OperatorFunctionId
:
12255 case UnqualifiedIdKind::IK_LiteralOperatorId
:
12256 case UnqualifiedIdKind::IK_ConversionFunctionId
:
12259 case UnqualifiedIdKind::IK_ConstructorName
:
12260 case UnqualifiedIdKind::IK_ConstructorTemplateId
:
12261 // C++11 inheriting constructors.
12262 Diag(Name
.getBeginLoc(),
12263 getLangOpts().CPlusPlus11
12264 ? diag::warn_cxx98_compat_using_decl_constructor
12265 : diag::err_using_decl_constructor
)
12268 if (getLangOpts().CPlusPlus11
) break;
12272 case UnqualifiedIdKind::IK_DestructorName
:
12273 Diag(Name
.getBeginLoc(), diag::err_using_decl_destructor
) << SS
.getRange();
12276 case UnqualifiedIdKind::IK_TemplateId
:
12277 Diag(Name
.getBeginLoc(), diag::err_using_decl_template_id
)
12278 << SourceRange(Name
.TemplateId
->LAngleLoc
, Name
.TemplateId
->RAngleLoc
);
12281 case UnqualifiedIdKind::IK_DeductionGuideName
:
12282 llvm_unreachable("cannot parse qualified deduction guide name");
12285 DeclarationNameInfo TargetNameInfo
= GetNameFromUnqualifiedId(Name
);
12286 DeclarationName TargetName
= TargetNameInfo
.getName();
12290 // Warn about access declarations.
12291 if (UsingLoc
.isInvalid()) {
12292 Diag(Name
.getBeginLoc(), getLangOpts().CPlusPlus11
12293 ? diag::err_access_decl
12294 : diag::warn_access_decl_deprecated
)
12295 << FixItHint::CreateInsertion(SS
.getRange().getBegin(), "using ");
12298 if (EllipsisLoc
.isInvalid()) {
12299 if (DiagnoseUnexpandedParameterPack(SS
, UPPC_UsingDeclaration
) ||
12300 DiagnoseUnexpandedParameterPack(TargetNameInfo
, UPPC_UsingDeclaration
))
12303 if (!SS
.getScopeRep()->containsUnexpandedParameterPack() &&
12304 !TargetNameInfo
.containsUnexpandedParameterPack()) {
12305 Diag(EllipsisLoc
, diag::err_pack_expansion_without_parameter_packs
)
12306 << SourceRange(SS
.getBeginLoc(), TargetNameInfo
.getEndLoc());
12307 EllipsisLoc
= SourceLocation();
12312 BuildUsingDeclaration(S
, AS
, UsingLoc
, TypenameLoc
.isValid(), TypenameLoc
,
12313 SS
, TargetNameInfo
, EllipsisLoc
, AttrList
,
12314 /*IsInstantiation*/ false,
12315 AttrList
.hasAttribute(ParsedAttr::AT_UsingIfExists
));
12317 PushOnScopeChains(UD
, S
, /*AddToContext*/ false);
12322 Decl
*Sema::ActOnUsingEnumDeclaration(Scope
*S
, AccessSpecifier AS
,
12323 SourceLocation UsingLoc
,
12324 SourceLocation EnumLoc
,
12325 SourceLocation IdentLoc
,
12326 IdentifierInfo
&II
, CXXScopeSpec
*SS
) {
12327 assert(!SS
->isInvalid() && "ScopeSpec is invalid");
12328 TypeSourceInfo
*TSI
= nullptr;
12329 QualType EnumTy
= GetTypeFromParser(
12330 getTypeName(II
, IdentLoc
, S
, SS
, /*isClassName=*/false,
12331 /*HasTrailingDot=*/false,
12332 /*ObjectType=*/nullptr, /*IsCtorOrDtorName=*/false,
12333 /*WantNontrivialTypeSourceInfo=*/true),
12335 if (EnumTy
.isNull()) {
12336 Diag(IdentLoc
, SS
&& isDependentScopeSpecifier(*SS
)
12337 ? diag::err_using_enum_is_dependent
12338 : diag::err_unknown_typename
)
12340 << SourceRange(SS
? SS
->getBeginLoc() : IdentLoc
, IdentLoc
);
12344 auto *Enum
= dyn_cast_if_present
<EnumDecl
>(EnumTy
->getAsTagDecl());
12346 Diag(IdentLoc
, diag::err_using_enum_not_enum
) << EnumTy
;
12350 if (auto *Def
= Enum
->getDefinition())
12353 if (TSI
== nullptr)
12354 TSI
= Context
.getTrivialTypeSourceInfo(EnumTy
, IdentLoc
);
12357 BuildUsingEnumDeclaration(S
, AS
, UsingLoc
, EnumLoc
, IdentLoc
, TSI
, Enum
);
12360 PushOnScopeChains(UD
, S
, /*AddToContext*/ false);
12365 /// Determine whether a using declaration considers the given
12366 /// declarations as "equivalent", e.g., if they are redeclarations of
12367 /// the same entity or are both typedefs of the same type.
12369 IsEquivalentForUsingDecl(ASTContext
&Context
, NamedDecl
*D1
, NamedDecl
*D2
) {
12370 if (D1
->getCanonicalDecl() == D2
->getCanonicalDecl())
12373 if (TypedefNameDecl
*TD1
= dyn_cast
<TypedefNameDecl
>(D1
))
12374 if (TypedefNameDecl
*TD2
= dyn_cast
<TypedefNameDecl
>(D2
))
12375 return Context
.hasSameType(TD1
->getUnderlyingType(),
12376 TD2
->getUnderlyingType());
12378 // Two using_if_exists using-declarations are equivalent if both are
12380 if (isa
<UnresolvedUsingIfExistsDecl
>(D1
) &&
12381 isa
<UnresolvedUsingIfExistsDecl
>(D2
))
12388 /// Determines whether to create a using shadow decl for a particular
12389 /// decl, given the set of decls existing prior to this using lookup.
12390 bool Sema::CheckUsingShadowDecl(BaseUsingDecl
*BUD
, NamedDecl
*Orig
,
12391 const LookupResult
&Previous
,
12392 UsingShadowDecl
*&PrevShadow
) {
12393 // Diagnose finding a decl which is not from a base class of the
12394 // current class. We do this now because there are cases where this
12395 // function will silently decide not to build a shadow decl, which
12396 // will pre-empt further diagnostics.
12398 // We don't need to do this in C++11 because we do the check once on
12401 // FIXME: diagnose the following if we care enough:
12402 // struct A { int foo; };
12403 // struct B : A { using A::foo; };
12404 // template <class T> struct C : A {};
12405 // template <class T> struct D : C<T> { using B::foo; } // <---
12406 // This is invalid (during instantiation) in C++03 because B::foo
12407 // resolves to the using decl in B, which is not a base class of D<T>.
12408 // We can't diagnose it immediately because C<T> is an unknown
12409 // specialization. The UsingShadowDecl in D<T> then points directly
12410 // to A::foo, which will look well-formed when we instantiate.
12411 // The right solution is to not collapse the shadow-decl chain.
12412 if (!getLangOpts().CPlusPlus11
&& CurContext
->isRecord())
12413 if (auto *Using
= dyn_cast
<UsingDecl
>(BUD
)) {
12414 DeclContext
*OrigDC
= Orig
->getDeclContext();
12416 // Handle enums and anonymous structs.
12417 if (isa
<EnumDecl
>(OrigDC
))
12418 OrigDC
= OrigDC
->getParent();
12419 CXXRecordDecl
*OrigRec
= cast
<CXXRecordDecl
>(OrigDC
);
12420 while (OrigRec
->isAnonymousStructOrUnion())
12421 OrigRec
= cast
<CXXRecordDecl
>(OrigRec
->getDeclContext());
12423 if (cast
<CXXRecordDecl
>(CurContext
)->isProvablyNotDerivedFrom(OrigRec
)) {
12424 if (OrigDC
== CurContext
) {
12425 Diag(Using
->getLocation(),
12426 diag::err_using_decl_nested_name_specifier_is_current_class
)
12427 << Using
->getQualifierLoc().getSourceRange();
12428 Diag(Orig
->getLocation(), diag::note_using_decl_target
);
12429 Using
->setInvalidDecl();
12433 Diag(Using
->getQualifierLoc().getBeginLoc(),
12434 diag::err_using_decl_nested_name_specifier_is_not_base_class
)
12435 << Using
->getQualifier() << cast
<CXXRecordDecl
>(CurContext
)
12436 << Using
->getQualifierLoc().getSourceRange();
12437 Diag(Orig
->getLocation(), diag::note_using_decl_target
);
12438 Using
->setInvalidDecl();
12443 if (Previous
.empty()) return false;
12445 NamedDecl
*Target
= Orig
;
12446 if (isa
<UsingShadowDecl
>(Target
))
12447 Target
= cast
<UsingShadowDecl
>(Target
)->getTargetDecl();
12449 // If the target happens to be one of the previous declarations, we
12450 // don't have a conflict.
12452 // FIXME: but we might be increasing its access, in which case we
12453 // should redeclare it.
12454 NamedDecl
*NonTag
= nullptr, *Tag
= nullptr;
12455 bool FoundEquivalentDecl
= false;
12456 for (LookupResult::iterator I
= Previous
.begin(), E
= Previous
.end();
12458 NamedDecl
*D
= (*I
)->getUnderlyingDecl();
12459 // We can have UsingDecls in our Previous results because we use the same
12460 // LookupResult for checking whether the UsingDecl itself is a valid
12462 if (isa
<UsingDecl
>(D
) || isa
<UsingPackDecl
>(D
) || isa
<UsingEnumDecl
>(D
))
12465 if (auto *RD
= dyn_cast
<CXXRecordDecl
>(D
)) {
12466 // C++ [class.mem]p19:
12467 // If T is the name of a class, then [every named member other than
12468 // a non-static data member] shall have a name different from T
12469 if (RD
->isInjectedClassName() && !isa
<FieldDecl
>(Target
) &&
12470 !isa
<IndirectFieldDecl
>(Target
) &&
12471 !isa
<UnresolvedUsingValueDecl
>(Target
) &&
12472 DiagnoseClassNameShadow(
12474 DeclarationNameInfo(BUD
->getDeclName(), BUD
->getLocation())))
12478 if (IsEquivalentForUsingDecl(Context
, D
, Target
)) {
12479 if (UsingShadowDecl
*Shadow
= dyn_cast
<UsingShadowDecl
>(*I
))
12480 PrevShadow
= Shadow
;
12481 FoundEquivalentDecl
= true;
12482 } else if (isEquivalentInternalLinkageDeclaration(D
, Target
)) {
12483 // We don't conflict with an existing using shadow decl of an equivalent
12484 // declaration, but we're not a redeclaration of it.
12485 FoundEquivalentDecl
= true;
12489 (isa
<TagDecl
>(D
) ? Tag
: NonTag
) = D
;
12492 if (FoundEquivalentDecl
)
12495 // Always emit a diagnostic for a mismatch between an unresolved
12496 // using_if_exists and a resolved using declaration in either direction.
12497 if (isa
<UnresolvedUsingIfExistsDecl
>(Target
) !=
12498 (isa_and_nonnull
<UnresolvedUsingIfExistsDecl
>(NonTag
))) {
12499 if (!NonTag
&& !Tag
)
12501 Diag(BUD
->getLocation(), diag::err_using_decl_conflict
);
12502 Diag(Target
->getLocation(), diag::note_using_decl_target
);
12503 Diag((NonTag
? NonTag
: Tag
)->getLocation(),
12504 diag::note_using_decl_conflict
);
12505 BUD
->setInvalidDecl();
12509 if (FunctionDecl
*FD
= Target
->getAsFunction()) {
12510 NamedDecl
*OldDecl
= nullptr;
12511 switch (CheckOverload(nullptr, FD
, Previous
, OldDecl
,
12512 /*IsForUsingDecl*/ true)) {
12516 case Ovl_NonFunction
:
12517 Diag(BUD
->getLocation(), diag::err_using_decl_conflict
);
12520 // We found a decl with the exact signature.
12522 // If we're in a record, we want to hide the target, so we
12523 // return true (without a diagnostic) to tell the caller not to
12524 // build a shadow decl.
12525 if (CurContext
->isRecord())
12528 // If we're not in a record, this is an error.
12529 Diag(BUD
->getLocation(), diag::err_using_decl_conflict
);
12533 Diag(Target
->getLocation(), diag::note_using_decl_target
);
12534 Diag(OldDecl
->getLocation(), diag::note_using_decl_conflict
);
12535 BUD
->setInvalidDecl();
12539 // Target is not a function.
12541 if (isa
<TagDecl
>(Target
)) {
12542 // No conflict between a tag and a non-tag.
12543 if (!Tag
) return false;
12545 Diag(BUD
->getLocation(), diag::err_using_decl_conflict
);
12546 Diag(Target
->getLocation(), diag::note_using_decl_target
);
12547 Diag(Tag
->getLocation(), diag::note_using_decl_conflict
);
12548 BUD
->setInvalidDecl();
12552 // No conflict between a tag and a non-tag.
12553 if (!NonTag
) return false;
12555 Diag(BUD
->getLocation(), diag::err_using_decl_conflict
);
12556 Diag(Target
->getLocation(), diag::note_using_decl_target
);
12557 Diag(NonTag
->getLocation(), diag::note_using_decl_conflict
);
12558 BUD
->setInvalidDecl();
12562 /// Determine whether a direct base class is a virtual base class.
12563 static bool isVirtualDirectBase(CXXRecordDecl
*Derived
, CXXRecordDecl
*Base
) {
12564 if (!Derived
->getNumVBases())
12566 for (auto &B
: Derived
->bases())
12567 if (B
.getType()->getAsCXXRecordDecl() == Base
)
12568 return B
.isVirtual();
12569 llvm_unreachable("not a direct base class");
12572 /// Builds a shadow declaration corresponding to a 'using' declaration.
12573 UsingShadowDecl
*Sema::BuildUsingShadowDecl(Scope
*S
, BaseUsingDecl
*BUD
,
12575 UsingShadowDecl
*PrevDecl
) {
12576 // If we resolved to another shadow declaration, just coalesce them.
12577 NamedDecl
*Target
= Orig
;
12578 if (isa
<UsingShadowDecl
>(Target
)) {
12579 Target
= cast
<UsingShadowDecl
>(Target
)->getTargetDecl();
12580 assert(!isa
<UsingShadowDecl
>(Target
) && "nested shadow declaration");
12583 NamedDecl
*NonTemplateTarget
= Target
;
12584 if (auto *TargetTD
= dyn_cast
<TemplateDecl
>(Target
))
12585 NonTemplateTarget
= TargetTD
->getTemplatedDecl();
12587 UsingShadowDecl
*Shadow
;
12588 if (NonTemplateTarget
&& isa
<CXXConstructorDecl
>(NonTemplateTarget
)) {
12589 UsingDecl
*Using
= cast
<UsingDecl
>(BUD
);
12590 bool IsVirtualBase
=
12591 isVirtualDirectBase(cast
<CXXRecordDecl
>(CurContext
),
12592 Using
->getQualifier()->getAsRecordDecl());
12593 Shadow
= ConstructorUsingShadowDecl::Create(
12594 Context
, CurContext
, Using
->getLocation(), Using
, Orig
, IsVirtualBase
);
12596 Shadow
= UsingShadowDecl::Create(Context
, CurContext
, BUD
->getLocation(),
12597 Target
->getDeclName(), BUD
, Target
);
12599 BUD
->addShadowDecl(Shadow
);
12601 Shadow
->setAccess(BUD
->getAccess());
12602 if (Orig
->isInvalidDecl() || BUD
->isInvalidDecl())
12603 Shadow
->setInvalidDecl();
12605 Shadow
->setPreviousDecl(PrevDecl
);
12608 PushOnScopeChains(Shadow
, S
);
12610 CurContext
->addDecl(Shadow
);
12616 /// Hides a using shadow declaration. This is required by the current
12617 /// using-decl implementation when a resolvable using declaration in a
12618 /// class is followed by a declaration which would hide or override
12619 /// one or more of the using decl's targets; for example:
12621 /// struct Base { void foo(int); };
12622 /// struct Derived : Base {
12623 /// using Base::foo;
12627 /// The governing language is C++03 [namespace.udecl]p12:
12629 /// When a using-declaration brings names from a base class into a
12630 /// derived class scope, member functions in the derived class
12631 /// override and/or hide member functions with the same name and
12632 /// parameter types in a base class (rather than conflicting).
12634 /// There are two ways to implement this:
12635 /// (1) optimistically create shadow decls when they're not hidden
12636 /// by existing declarations, or
12637 /// (2) don't create any shadow decls (or at least don't make them
12638 /// visible) until we've fully parsed/instantiated the class.
12639 /// The problem with (1) is that we might have to retroactively remove
12640 /// a shadow decl, which requires several O(n) operations because the
12641 /// decl structures are (very reasonably) not designed for removal.
12642 /// (2) avoids this but is very fiddly and phase-dependent.
12643 void Sema::HideUsingShadowDecl(Scope
*S
, UsingShadowDecl
*Shadow
) {
12644 if (Shadow
->getDeclName().getNameKind() ==
12645 DeclarationName::CXXConversionFunctionName
)
12646 cast
<CXXRecordDecl
>(Shadow
->getDeclContext())->removeConversion(Shadow
);
12648 // Remove it from the DeclContext...
12649 Shadow
->getDeclContext()->removeDecl(Shadow
);
12651 // ...and the scope, if applicable...
12653 S
->RemoveDecl(Shadow
);
12654 IdResolver
.RemoveDecl(Shadow
);
12657 // ...and the using decl.
12658 Shadow
->getIntroducer()->removeShadowDecl(Shadow
);
12660 // TODO: complain somehow if Shadow was used. It shouldn't
12661 // be possible for this to happen, because...?
12664 /// Find the base specifier for a base class with the given type.
12665 static CXXBaseSpecifier
*findDirectBaseWithType(CXXRecordDecl
*Derived
,
12666 QualType DesiredBase
,
12667 bool &AnyDependentBases
) {
12668 // Check whether the named type is a direct base class.
12669 CanQualType CanonicalDesiredBase
= DesiredBase
->getCanonicalTypeUnqualified()
12670 .getUnqualifiedType();
12671 for (auto &Base
: Derived
->bases()) {
12672 CanQualType BaseType
= Base
.getType()->getCanonicalTypeUnqualified();
12673 if (CanonicalDesiredBase
== BaseType
)
12675 if (BaseType
->isDependentType())
12676 AnyDependentBases
= true;
12682 class UsingValidatorCCC final
: public CorrectionCandidateCallback
{
12684 UsingValidatorCCC(bool HasTypenameKeyword
, bool IsInstantiation
,
12685 NestedNameSpecifier
*NNS
, CXXRecordDecl
*RequireMemberOf
)
12686 : HasTypenameKeyword(HasTypenameKeyword
),
12687 IsInstantiation(IsInstantiation
), OldNNS(NNS
),
12688 RequireMemberOf(RequireMemberOf
) {}
12690 bool ValidateCandidate(const TypoCorrection
&Candidate
) override
{
12691 NamedDecl
*ND
= Candidate
.getCorrectionDecl();
12693 // Keywords are not valid here.
12694 if (!ND
|| isa
<NamespaceDecl
>(ND
))
12697 // Completely unqualified names are invalid for a 'using' declaration.
12698 if (Candidate
.WillReplaceSpecifier() && !Candidate
.getCorrectionSpecifier())
12701 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
12704 if (RequireMemberOf
) {
12705 auto *FoundRecord
= dyn_cast
<CXXRecordDecl
>(ND
);
12706 if (FoundRecord
&& FoundRecord
->isInjectedClassName()) {
12707 // No-one ever wants a using-declaration to name an injected-class-name
12708 // of a base class, unless they're declaring an inheriting constructor.
12709 ASTContext
&Ctx
= ND
->getASTContext();
12710 if (!Ctx
.getLangOpts().CPlusPlus11
)
12712 QualType FoundType
= Ctx
.getRecordType(FoundRecord
);
12714 // Check that the injected-class-name is named as a member of its own
12715 // type; we don't want to suggest 'using Derived::Base;', since that
12716 // means something else.
12717 NestedNameSpecifier
*Specifier
=
12718 Candidate
.WillReplaceSpecifier()
12719 ? Candidate
.getCorrectionSpecifier()
12721 if (!Specifier
->getAsType() ||
12722 !Ctx
.hasSameType(QualType(Specifier
->getAsType(), 0), FoundType
))
12725 // Check that this inheriting constructor declaration actually names a
12726 // direct base class of the current class.
12727 bool AnyDependentBases
= false;
12728 if (!findDirectBaseWithType(RequireMemberOf
,
12729 Ctx
.getRecordType(FoundRecord
),
12730 AnyDependentBases
) &&
12731 !AnyDependentBases
)
12734 auto *RD
= dyn_cast
<CXXRecordDecl
>(ND
->getDeclContext());
12735 if (!RD
|| RequireMemberOf
->isProvablyNotDerivedFrom(RD
))
12738 // FIXME: Check that the base class member is accessible?
12741 auto *FoundRecord
= dyn_cast
<CXXRecordDecl
>(ND
);
12742 if (FoundRecord
&& FoundRecord
->isInjectedClassName())
12746 if (isa
<TypeDecl
>(ND
))
12747 return HasTypenameKeyword
|| !IsInstantiation
;
12749 return !HasTypenameKeyword
;
12752 std::unique_ptr
<CorrectionCandidateCallback
> clone() override
{
12753 return std::make_unique
<UsingValidatorCCC
>(*this);
12757 bool HasTypenameKeyword
;
12758 bool IsInstantiation
;
12759 NestedNameSpecifier
*OldNNS
;
12760 CXXRecordDecl
*RequireMemberOf
;
12762 } // end anonymous namespace
12764 /// Remove decls we can't actually see from a lookup being used to declare
12765 /// shadow using decls.
12767 /// \param S - The scope of the potential shadow decl
12768 /// \param Previous - The lookup of a potential shadow decl's name.
12769 void Sema::FilterUsingLookup(Scope
*S
, LookupResult
&Previous
) {
12770 // It is really dumb that we have to do this.
12771 LookupResult::Filter F
= Previous
.makeFilter();
12772 while (F
.hasNext()) {
12773 NamedDecl
*D
= F
.next();
12774 if (!isDeclInScope(D
, CurContext
, S
))
12776 // If we found a local extern declaration that's not ordinarily visible,
12777 // and this declaration is being added to a non-block scope, ignore it.
12778 // We're only checking for scope conflicts here, not also for violations
12779 // of the linkage rules.
12780 else if (!CurContext
->isFunctionOrMethod() && D
->isLocalExternDecl() &&
12781 !(D
->getIdentifierNamespace() & Decl::IDNS_Ordinary
))
12787 /// Builds a using declaration.
12789 /// \param IsInstantiation - Whether this call arises from an
12790 /// instantiation of an unresolved using declaration. We treat
12791 /// the lookup differently for these declarations.
12792 NamedDecl
*Sema::BuildUsingDeclaration(
12793 Scope
*S
, AccessSpecifier AS
, SourceLocation UsingLoc
,
12794 bool HasTypenameKeyword
, SourceLocation TypenameLoc
, CXXScopeSpec
&SS
,
12795 DeclarationNameInfo NameInfo
, SourceLocation EllipsisLoc
,
12796 const ParsedAttributesView
&AttrList
, bool IsInstantiation
,
12797 bool IsUsingIfExists
) {
12798 assert(!SS
.isInvalid() && "Invalid CXXScopeSpec.");
12799 SourceLocation IdentLoc
= NameInfo
.getLoc();
12800 assert(IdentLoc
.isValid() && "Invalid TargetName location.");
12802 // FIXME: We ignore attributes for now.
12804 // For an inheriting constructor declaration, the name of the using
12805 // declaration is the name of a constructor in this class, not in the
12807 DeclarationNameInfo UsingName
= NameInfo
;
12808 if (UsingName
.getName().getNameKind() == DeclarationName::CXXConstructorName
)
12809 if (auto *RD
= dyn_cast
<CXXRecordDecl
>(CurContext
))
12810 UsingName
.setName(Context
.DeclarationNames
.getCXXConstructorName(
12811 Context
.getCanonicalType(Context
.getRecordType(RD
))));
12813 // Do the redeclaration lookup in the current scope.
12814 LookupResult
Previous(*this, UsingName
, LookupUsingDeclName
,
12815 ForVisibleRedeclaration
);
12816 Previous
.setHideTags(false);
12818 LookupName(Previous
, S
);
12820 FilterUsingLookup(S
, Previous
);
12822 assert(IsInstantiation
&& "no scope in non-instantiation");
12823 if (CurContext
->isRecord())
12824 LookupQualifiedName(Previous
, CurContext
);
12826 // No redeclaration check is needed here; in non-member contexts we
12827 // diagnosed all possible conflicts with other using-declarations when
12828 // building the template:
12830 // For a dependent non-type using declaration, the only valid case is
12831 // if we instantiate to a single enumerator. We check for conflicts
12832 // between shadow declarations we introduce, and we check in the template
12833 // definition for conflicts between a non-type using declaration and any
12834 // other declaration, which together covers all cases.
12836 // A dependent typename using declaration will never successfully
12837 // instantiate, since it will always name a class member, so we reject
12838 // that in the template definition.
12842 // Check for invalid redeclarations.
12843 if (CheckUsingDeclRedeclaration(UsingLoc
, HasTypenameKeyword
,
12844 SS
, IdentLoc
, Previous
))
12847 // 'using_if_exists' doesn't make sense on an inherited constructor.
12848 if (IsUsingIfExists
&& UsingName
.getName().getNameKind() ==
12849 DeclarationName::CXXConstructorName
) {
12850 Diag(UsingLoc
, diag::err_using_if_exists_on_ctor
);
12854 DeclContext
*LookupContext
= computeDeclContext(SS
);
12855 NestedNameSpecifierLoc QualifierLoc
= SS
.getWithLocInContext(Context
);
12856 if (!LookupContext
|| EllipsisLoc
.isValid()) {
12858 // Dependent scope, or an unexpanded pack
12859 if (!LookupContext
&& CheckUsingDeclQualifier(UsingLoc
, HasTypenameKeyword
,
12860 SS
, NameInfo
, IdentLoc
))
12863 if (HasTypenameKeyword
) {
12864 // FIXME: not all declaration name kinds are legal here
12865 D
= UnresolvedUsingTypenameDecl::Create(Context
, CurContext
,
12866 UsingLoc
, TypenameLoc
,
12868 IdentLoc
, NameInfo
.getName(),
12871 D
= UnresolvedUsingValueDecl::Create(Context
, CurContext
, UsingLoc
,
12872 QualifierLoc
, NameInfo
, EllipsisLoc
);
12875 CurContext
->addDecl(D
);
12876 ProcessDeclAttributeList(S
, D
, AttrList
);
12880 auto Build
= [&](bool Invalid
) {
12882 UsingDecl::Create(Context
, CurContext
, UsingLoc
, QualifierLoc
,
12883 UsingName
, HasTypenameKeyword
);
12885 CurContext
->addDecl(UD
);
12886 ProcessDeclAttributeList(S
, UD
, AttrList
);
12887 UD
->setInvalidDecl(Invalid
);
12890 auto BuildInvalid
= [&]{ return Build(true); };
12891 auto BuildValid
= [&]{ return Build(false); };
12893 if (RequireCompleteDeclContext(SS
, LookupContext
))
12894 return BuildInvalid();
12896 // Look up the target name.
12897 LookupResult
R(*this, NameInfo
, LookupOrdinaryName
);
12899 // Unlike most lookups, we don't always want to hide tag
12900 // declarations: tag names are visible through the using declaration
12901 // even if hidden by ordinary names, *except* in a dependent context
12902 // where they may be used by two-phase lookup.
12903 if (!IsInstantiation
)
12904 R
.setHideTags(false);
12906 // For the purposes of this lookup, we have a base object type
12907 // equal to that of the current context.
12908 if (CurContext
->isRecord()) {
12909 R
.setBaseObjectType(
12910 Context
.getTypeDeclType(cast
<CXXRecordDecl
>(CurContext
)));
12913 LookupQualifiedName(R
, LookupContext
);
12915 // Validate the context, now we have a lookup
12916 if (CheckUsingDeclQualifier(UsingLoc
, HasTypenameKeyword
, SS
, NameInfo
,
12920 if (R
.empty() && IsUsingIfExists
)
12921 R
.addDecl(UnresolvedUsingIfExistsDecl::Create(Context
, CurContext
, UsingLoc
,
12922 UsingName
.getName()),
12925 // Try to correct typos if possible. If constructor name lookup finds no
12926 // results, that means the named class has no explicit constructors, and we
12927 // suppressed declaring implicit ones (probably because it's dependent or
12930 NameInfo
.getName().getNameKind() != DeclarationName::CXXConstructorName
) {
12931 // HACK 2017-01-08: Work around an issue with libstdc++'s detection of
12932 // ::gets. Sometimes it believes that glibc provides a ::gets in cases where
12933 // it does not. The issue was fixed in libstdc++ 6.3 (2016-12-21) and later.
12934 auto *II
= NameInfo
.getName().getAsIdentifierInfo();
12935 if (getLangOpts().CPlusPlus14
&& II
&& II
->isStr("gets") &&
12936 CurContext
->isStdNamespace() &&
12937 isa
<TranslationUnitDecl
>(LookupContext
) &&
12938 getSourceManager().isInSystemHeader(UsingLoc
))
12940 UsingValidatorCCC
CCC(HasTypenameKeyword
, IsInstantiation
, SS
.getScopeRep(),
12941 dyn_cast
<CXXRecordDecl
>(CurContext
));
12942 if (TypoCorrection Corrected
=
12943 CorrectTypo(R
.getLookupNameInfo(), R
.getLookupKind(), S
, &SS
, CCC
,
12944 CTK_ErrorRecovery
)) {
12945 // We reject candidates where DroppedSpecifier == true, hence the
12946 // literal '0' below.
12947 diagnoseTypo(Corrected
, PDiag(diag::err_no_member_suggest
)
12948 << NameInfo
.getName() << LookupContext
<< 0
12951 // If we picked a correction with no attached Decl we can't do anything
12952 // useful with it, bail out.
12953 NamedDecl
*ND
= Corrected
.getCorrectionDecl();
12955 return BuildInvalid();
12957 // If we corrected to an inheriting constructor, handle it as one.
12958 auto *RD
= dyn_cast
<CXXRecordDecl
>(ND
);
12959 if (RD
&& RD
->isInjectedClassName()) {
12960 // The parent of the injected class name is the class itself.
12961 RD
= cast
<CXXRecordDecl
>(RD
->getParent());
12963 // Fix up the information we'll use to build the using declaration.
12964 if (Corrected
.WillReplaceSpecifier()) {
12965 NestedNameSpecifierLocBuilder Builder
;
12966 Builder
.MakeTrivial(Context
, Corrected
.getCorrectionSpecifier(),
12967 QualifierLoc
.getSourceRange());
12968 QualifierLoc
= Builder
.getWithLocInContext(Context
);
12971 // In this case, the name we introduce is the name of a derived class
12973 auto *CurClass
= cast
<CXXRecordDecl
>(CurContext
);
12974 UsingName
.setName(Context
.DeclarationNames
.getCXXConstructorName(
12975 Context
.getCanonicalType(Context
.getRecordType(CurClass
))));
12976 UsingName
.setNamedTypeInfo(nullptr);
12977 for (auto *Ctor
: LookupConstructors(RD
))
12981 // FIXME: Pick up all the declarations if we found an overloaded
12983 UsingName
.setName(ND
->getDeclName());
12987 Diag(IdentLoc
, diag::err_no_member
)
12988 << NameInfo
.getName() << LookupContext
<< SS
.getRange();
12989 return BuildInvalid();
12993 if (R
.isAmbiguous())
12994 return BuildInvalid();
12996 if (HasTypenameKeyword
) {
12997 // If we asked for a typename and got a non-type decl, error out.
12998 if (!R
.getAsSingle
<TypeDecl
>() &&
12999 !R
.getAsSingle
<UnresolvedUsingIfExistsDecl
>()) {
13000 Diag(IdentLoc
, diag::err_using_typename_non_type
);
13001 for (LookupResult::iterator I
= R
.begin(), E
= R
.end(); I
!= E
; ++I
)
13002 Diag((*I
)->getUnderlyingDecl()->getLocation(),
13003 diag::note_using_decl_target
);
13004 return BuildInvalid();
13007 // If we asked for a non-typename and we got a type, error out,
13008 // but only if this is an instantiation of an unresolved using
13009 // decl. Otherwise just silently find the type name.
13010 if (IsInstantiation
&& R
.getAsSingle
<TypeDecl
>()) {
13011 Diag(IdentLoc
, diag::err_using_dependent_value_is_type
);
13012 Diag(R
.getFoundDecl()->getLocation(), diag::note_using_decl_target
);
13013 return BuildInvalid();
13017 // C++14 [namespace.udecl]p6:
13018 // A using-declaration shall not name a namespace.
13019 if (R
.getAsSingle
<NamespaceDecl
>()) {
13020 Diag(IdentLoc
, diag::err_using_decl_can_not_refer_to_namespace
)
13022 return BuildInvalid();
13025 UsingDecl
*UD
= BuildValid();
13027 // Some additional rules apply to inheriting constructors.
13028 if (UsingName
.getName().getNameKind() ==
13029 DeclarationName::CXXConstructorName
) {
13030 // Suppress access diagnostics; the access check is instead performed at the
13031 // point of use for an inheriting constructor.
13032 R
.suppressDiagnostics();
13033 if (CheckInheritingConstructorUsingDecl(UD
))
13037 for (LookupResult::iterator I
= R
.begin(), E
= R
.end(); I
!= E
; ++I
) {
13038 UsingShadowDecl
*PrevDecl
= nullptr;
13039 if (!CheckUsingShadowDecl(UD
, *I
, Previous
, PrevDecl
))
13040 BuildUsingShadowDecl(S
, UD
, *I
, PrevDecl
);
13046 NamedDecl
*Sema::BuildUsingEnumDeclaration(Scope
*S
, AccessSpecifier AS
,
13047 SourceLocation UsingLoc
,
13048 SourceLocation EnumLoc
,
13049 SourceLocation NameLoc
,
13050 TypeSourceInfo
*EnumType
,
13052 bool Invalid
= false;
13054 if (CurContext
->getRedeclContext()->isRecord()) {
13055 /// In class scope, check if this is a duplicate, for better a diagnostic.
13056 DeclarationNameInfo
UsingEnumName(ED
->getDeclName(), NameLoc
);
13057 LookupResult
Previous(*this, UsingEnumName
, LookupUsingDeclName
,
13058 ForVisibleRedeclaration
);
13060 LookupName(Previous
, S
);
13062 for (NamedDecl
*D
: Previous
)
13063 if (UsingEnumDecl
*UED
= dyn_cast
<UsingEnumDecl
>(D
))
13064 if (UED
->getEnumDecl() == ED
) {
13065 Diag(UsingLoc
, diag::err_using_enum_decl_redeclaration
)
13066 << SourceRange(EnumLoc
, NameLoc
);
13067 Diag(D
->getLocation(), diag::note_using_enum_decl
) << 1;
13073 if (RequireCompleteEnumDecl(ED
, NameLoc
))
13076 UsingEnumDecl
*UD
= UsingEnumDecl::Create(Context
, CurContext
, UsingLoc
,
13077 EnumLoc
, NameLoc
, EnumType
);
13079 CurContext
->addDecl(UD
);
13082 UD
->setInvalidDecl();
13086 // Create the shadow decls for each enumerator
13087 for (EnumConstantDecl
*EC
: ED
->enumerators()) {
13088 UsingShadowDecl
*PrevDecl
= nullptr;
13089 DeclarationNameInfo
DNI(EC
->getDeclName(), EC
->getLocation());
13090 LookupResult
Previous(*this, DNI
, LookupOrdinaryName
,
13091 ForVisibleRedeclaration
);
13092 LookupName(Previous
, S
);
13093 FilterUsingLookup(S
, Previous
);
13095 if (!CheckUsingShadowDecl(UD
, EC
, Previous
, PrevDecl
))
13096 BuildUsingShadowDecl(S
, UD
, EC
, PrevDecl
);
13102 NamedDecl
*Sema::BuildUsingPackDecl(NamedDecl
*InstantiatedFrom
,
13103 ArrayRef
<NamedDecl
*> Expansions
) {
13104 assert(isa
<UnresolvedUsingValueDecl
>(InstantiatedFrom
) ||
13105 isa
<UnresolvedUsingTypenameDecl
>(InstantiatedFrom
) ||
13106 isa
<UsingPackDecl
>(InstantiatedFrom
));
13109 UsingPackDecl::Create(Context
, CurContext
, InstantiatedFrom
, Expansions
);
13110 UPD
->setAccess(InstantiatedFrom
->getAccess());
13111 CurContext
->addDecl(UPD
);
13115 /// Additional checks for a using declaration referring to a constructor name.
13116 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl
*UD
) {
13117 assert(!UD
->hasTypename() && "expecting a constructor name");
13119 const Type
*SourceType
= UD
->getQualifier()->getAsType();
13120 assert(SourceType
&&
13121 "Using decl naming constructor doesn't have type in scope spec.");
13122 CXXRecordDecl
*TargetClass
= cast
<CXXRecordDecl
>(CurContext
);
13124 // Check whether the named type is a direct base class.
13125 bool AnyDependentBases
= false;
13126 auto *Base
= findDirectBaseWithType(TargetClass
, QualType(SourceType
, 0),
13127 AnyDependentBases
);
13128 if (!Base
&& !AnyDependentBases
) {
13129 Diag(UD
->getUsingLoc(),
13130 diag::err_using_decl_constructor_not_in_direct_base
)
13131 << UD
->getNameInfo().getSourceRange()
13132 << QualType(SourceType
, 0) << TargetClass
;
13133 UD
->setInvalidDecl();
13138 Base
->setInheritConstructors();
13143 /// Checks that the given using declaration is not an invalid
13144 /// redeclaration. Note that this is checking only for the using decl
13145 /// itself, not for any ill-formedness among the UsingShadowDecls.
13146 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc
,
13147 bool HasTypenameKeyword
,
13148 const CXXScopeSpec
&SS
,
13149 SourceLocation NameLoc
,
13150 const LookupResult
&Prev
) {
13151 NestedNameSpecifier
*Qual
= SS
.getScopeRep();
13153 // C++03 [namespace.udecl]p8:
13154 // C++0x [namespace.udecl]p10:
13155 // A using-declaration is a declaration and can therefore be used
13156 // repeatedly where (and only where) multiple declarations are
13159 // That's in non-member contexts.
13160 if (!CurContext
->getRedeclContext()->isRecord()) {
13161 // A dependent qualifier outside a class can only ever resolve to an
13162 // enumeration type. Therefore it conflicts with any other non-type
13163 // declaration in the same scope.
13164 // FIXME: How should we check for dependent type-type conflicts at block
13166 if (Qual
->isDependent() && !HasTypenameKeyword
) {
13167 for (auto *D
: Prev
) {
13168 if (!isa
<TypeDecl
>(D
) && !isa
<UsingDecl
>(D
) && !isa
<UsingPackDecl
>(D
)) {
13169 bool OldCouldBeEnumerator
=
13170 isa
<UnresolvedUsingValueDecl
>(D
) || isa
<EnumConstantDecl
>(D
);
13172 OldCouldBeEnumerator
? diag::err_redefinition
13173 : diag::err_redefinition_different_kind
)
13174 << Prev
.getLookupName();
13175 Diag(D
->getLocation(), diag::note_previous_definition
);
13183 const NestedNameSpecifier
*CNNS
=
13184 Context
.getCanonicalNestedNameSpecifier(Qual
);
13185 for (LookupResult::iterator I
= Prev
.begin(), E
= Prev
.end(); I
!= E
; ++I
) {
13189 NestedNameSpecifier
*DQual
;
13190 if (UsingDecl
*UD
= dyn_cast
<UsingDecl
>(D
)) {
13191 DTypename
= UD
->hasTypename();
13192 DQual
= UD
->getQualifier();
13193 } else if (UnresolvedUsingValueDecl
*UD
13194 = dyn_cast
<UnresolvedUsingValueDecl
>(D
)) {
13196 DQual
= UD
->getQualifier();
13197 } else if (UnresolvedUsingTypenameDecl
*UD
13198 = dyn_cast
<UnresolvedUsingTypenameDecl
>(D
)) {
13200 DQual
= UD
->getQualifier();
13203 // using decls differ if one says 'typename' and the other doesn't.
13204 // FIXME: non-dependent using decls?
13205 if (HasTypenameKeyword
!= DTypename
) continue;
13207 // using decls differ if they name different scopes (but note that
13208 // template instantiation can cause this check to trigger when it
13209 // didn't before instantiation).
13210 if (CNNS
!= Context
.getCanonicalNestedNameSpecifier(DQual
))
13213 Diag(NameLoc
, diag::err_using_decl_redeclaration
) << SS
.getRange();
13214 Diag(D
->getLocation(), diag::note_using_decl
) << 1;
13221 /// Checks that the given nested-name qualifier used in a using decl
13222 /// in the current context is appropriately related to the current
13223 /// scope. If an error is found, diagnoses it and returns true.
13224 /// R is nullptr, if the caller has not (yet) done a lookup, otherwise it's the
13225 /// result of that lookup. UD is likewise nullptr, except when we have an
13226 /// already-populated UsingDecl whose shadow decls contain the same information
13227 /// (i.e. we're instantiating a UsingDecl with non-dependent scope).
13228 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc
, bool HasTypename
,
13229 const CXXScopeSpec
&SS
,
13230 const DeclarationNameInfo
&NameInfo
,
13231 SourceLocation NameLoc
,
13232 const LookupResult
*R
, const UsingDecl
*UD
) {
13233 DeclContext
*NamedContext
= computeDeclContext(SS
);
13234 assert(bool(NamedContext
) == (R
|| UD
) && !(R
&& UD
) &&
13235 "resolvable context must have exactly one set of decls");
13237 // C++ 20 permits using an enumerator that does not have a class-hierarchy
13239 bool Cxx20Enumerator
= false;
13240 if (NamedContext
) {
13241 EnumConstantDecl
*EC
= nullptr;
13243 EC
= R
->getAsSingle
<EnumConstantDecl
>();
13244 else if (UD
&& UD
->shadow_size() == 1)
13245 EC
= dyn_cast
<EnumConstantDecl
>(UD
->shadow_begin()->getTargetDecl());
13247 Cxx20Enumerator
= getLangOpts().CPlusPlus20
;
13249 if (auto *ED
= dyn_cast
<EnumDecl
>(NamedContext
)) {
13250 // C++14 [namespace.udecl]p7:
13251 // A using-declaration shall not name a scoped enumerator.
13252 // C++20 p1099 permits enumerators.
13253 if (EC
&& R
&& ED
->isScoped())
13254 Diag(SS
.getBeginLoc(),
13255 getLangOpts().CPlusPlus20
13256 ? diag::warn_cxx17_compat_using_decl_scoped_enumerator
13257 : diag::ext_using_decl_scoped_enumerator
)
13260 // We want to consider the scope of the enumerator
13261 NamedContext
= ED
->getDeclContext();
13265 if (!CurContext
->isRecord()) {
13266 // C++03 [namespace.udecl]p3:
13267 // C++0x [namespace.udecl]p8:
13268 // A using-declaration for a class member shall be a member-declaration.
13269 // C++20 [namespace.udecl]p7
13270 // ... other than an enumerator ...
13272 // If we weren't able to compute a valid scope, it might validly be a
13273 // dependent class or enumeration scope. If we have a 'typename' keyword,
13274 // the scope must resolve to a class type.
13275 if (NamedContext
? !NamedContext
->getRedeclContext()->isRecord()
13277 return false; // OK
13281 ? diag::warn_cxx17_compat_using_decl_class_member_enumerator
13282 : diag::err_using_decl_can_not_refer_to_class_member
)
13285 if (Cxx20Enumerator
)
13286 return false; // OK
13288 auto *RD
= NamedContext
13289 ? cast
<CXXRecordDecl
>(NamedContext
->getRedeclContext())
13291 if (RD
&& !RequireCompleteDeclContext(const_cast<CXXScopeSpec
&>(SS
), RD
)) {
13292 // See if there's a helpful fixit
13295 // We will have already diagnosed the problem on the template
13296 // definition, Maybe we should do so again?
13297 } else if (R
->getAsSingle
<TypeDecl
>()) {
13298 if (getLangOpts().CPlusPlus11
) {
13299 // Convert 'using X::Y;' to 'using Y = X::Y;'.
13300 Diag(SS
.getBeginLoc(), diag::note_using_decl_class_member_workaround
)
13301 << 0 // alias declaration
13302 << FixItHint::CreateInsertion(SS
.getBeginLoc(),
13303 NameInfo
.getName().getAsString() +
13306 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
13307 SourceLocation InsertLoc
= getLocForEndOfToken(NameInfo
.getEndLoc());
13308 Diag(InsertLoc
, diag::note_using_decl_class_member_workaround
)
13309 << 1 // typedef declaration
13310 << FixItHint::CreateReplacement(UsingLoc
, "typedef")
13311 << FixItHint::CreateInsertion(
13312 InsertLoc
, " " + NameInfo
.getName().getAsString());
13314 } else if (R
->getAsSingle
<VarDecl
>()) {
13315 // Don't provide a fixit outside C++11 mode; we don't want to suggest
13316 // repeating the type of the static data member here.
13318 if (getLangOpts().CPlusPlus11
) {
13319 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
13320 FixIt
= FixItHint::CreateReplacement(
13321 UsingLoc
, "auto &" + NameInfo
.getName().getAsString() + " = ");
13324 Diag(UsingLoc
, diag::note_using_decl_class_member_workaround
)
13325 << 2 // reference declaration
13327 } else if (R
->getAsSingle
<EnumConstantDecl
>()) {
13328 // Don't provide a fixit outside C++11 mode; we don't want to suggest
13329 // repeating the type of the enumeration here, and we can't do so if
13330 // the type is anonymous.
13332 if (getLangOpts().CPlusPlus11
) {
13333 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
13334 FixIt
= FixItHint::CreateReplacement(
13336 "constexpr auto " + NameInfo
.getName().getAsString() + " = ");
13339 Diag(UsingLoc
, diag::note_using_decl_class_member_workaround
)
13340 << (getLangOpts().CPlusPlus11
? 4 : 3) // const[expr] variable
13345 return true; // Fail
13348 // If the named context is dependent, we can't decide much.
13349 if (!NamedContext
) {
13350 // FIXME: in C++0x, we can diagnose if we can prove that the
13351 // nested-name-specifier does not refer to a base class, which is
13352 // still possible in some cases.
13354 // Otherwise we have to conservatively report that things might be
13359 // The current scope is a record.
13360 if (!NamedContext
->isRecord()) {
13361 // Ideally this would point at the last name in the specifier,
13362 // but we don't have that level of source info.
13363 Diag(SS
.getBeginLoc(),
13365 ? diag::warn_cxx17_compat_using_decl_non_member_enumerator
13366 : diag::err_using_decl_nested_name_specifier_is_not_class
)
13367 << SS
.getScopeRep() << SS
.getRange();
13369 if (Cxx20Enumerator
)
13370 return false; // OK
13375 if (!NamedContext
->isDependentContext() &&
13376 RequireCompleteDeclContext(const_cast<CXXScopeSpec
&>(SS
), NamedContext
))
13379 if (getLangOpts().CPlusPlus11
) {
13380 // C++11 [namespace.udecl]p3:
13381 // In a using-declaration used as a member-declaration, the
13382 // nested-name-specifier shall name a base class of the class
13385 if (cast
<CXXRecordDecl
>(CurContext
)->isProvablyNotDerivedFrom(
13386 cast
<CXXRecordDecl
>(NamedContext
))) {
13388 if (Cxx20Enumerator
) {
13389 Diag(NameLoc
, diag::warn_cxx17_compat_using_decl_non_member_enumerator
)
13394 if (CurContext
== NamedContext
) {
13395 Diag(SS
.getBeginLoc(),
13396 diag::err_using_decl_nested_name_specifier_is_current_class
)
13398 return !getLangOpts().CPlusPlus20
;
13401 if (!cast
<CXXRecordDecl
>(NamedContext
)->isInvalidDecl()) {
13402 Diag(SS
.getBeginLoc(),
13403 diag::err_using_decl_nested_name_specifier_is_not_base_class
)
13404 << SS
.getScopeRep() << cast
<CXXRecordDecl
>(CurContext
)
13413 // C++03 [namespace.udecl]p4:
13414 // A using-declaration used as a member-declaration shall refer
13415 // to a member of a base class of the class being defined [etc.].
13417 // Salient point: SS doesn't have to name a base class as long as
13418 // lookup only finds members from base classes. Therefore we can
13419 // diagnose here only if we can prove that can't happen,
13420 // i.e. if the class hierarchies provably don't intersect.
13422 // TODO: it would be nice if "definitely valid" results were cached
13423 // in the UsingDecl and UsingShadowDecl so that these checks didn't
13424 // need to be repeated.
13426 llvm::SmallPtrSet
<const CXXRecordDecl
*, 4> Bases
;
13427 auto Collect
= [&Bases
](const CXXRecordDecl
*Base
) {
13428 Bases
.insert(Base
);
13432 // Collect all bases. Return false if we find a dependent base.
13433 if (!cast
<CXXRecordDecl
>(CurContext
)->forallBases(Collect
))
13436 // Returns true if the base is dependent or is one of the accumulated base
13438 auto IsNotBase
= [&Bases
](const CXXRecordDecl
*Base
) {
13439 return !Bases
.count(Base
);
13442 // Return false if the class has a dependent base or if it or one
13443 // of its bases is present in the base set of the current context.
13444 if (Bases
.count(cast
<CXXRecordDecl
>(NamedContext
)) ||
13445 !cast
<CXXRecordDecl
>(NamedContext
)->forallBases(IsNotBase
))
13448 Diag(SS
.getRange().getBegin(),
13449 diag::err_using_decl_nested_name_specifier_is_not_base_class
)
13450 << SS
.getScopeRep()
13451 << cast
<CXXRecordDecl
>(CurContext
)
13457 Decl
*Sema::ActOnAliasDeclaration(Scope
*S
, AccessSpecifier AS
,
13458 MultiTemplateParamsArg TemplateParamLists
,
13459 SourceLocation UsingLoc
, UnqualifiedId
&Name
,
13460 const ParsedAttributesView
&AttrList
,
13461 TypeResult Type
, Decl
*DeclFromDeclSpec
) {
13462 // Skip up to the relevant declaration scope.
13463 while (S
->isTemplateParamScope())
13464 S
= S
->getParent();
13465 assert((S
->getFlags() & Scope::DeclScope
) &&
13466 "got alias-declaration outside of declaration scope");
13468 if (Type
.isInvalid())
13471 bool Invalid
= false;
13472 DeclarationNameInfo NameInfo
= GetNameFromUnqualifiedId(Name
);
13473 TypeSourceInfo
*TInfo
= nullptr;
13474 GetTypeFromParser(Type
.get(), &TInfo
);
13476 if (DiagnoseClassNameShadow(CurContext
, NameInfo
))
13479 if (DiagnoseUnexpandedParameterPack(Name
.StartLocation
, TInfo
,
13480 UPPC_DeclarationType
)) {
13482 TInfo
= Context
.getTrivialTypeSourceInfo(Context
.IntTy
,
13483 TInfo
->getTypeLoc().getBeginLoc());
13486 LookupResult
Previous(*this, NameInfo
, LookupOrdinaryName
,
13487 TemplateParamLists
.size()
13488 ? forRedeclarationInCurContext()
13489 : ForVisibleRedeclaration
);
13490 LookupName(Previous
, S
);
13492 // Warn about shadowing the name of a template parameter.
13493 if (Previous
.isSingleResult() &&
13494 Previous
.getFoundDecl()->isTemplateParameter()) {
13495 DiagnoseTemplateParameterShadow(Name
.StartLocation
,Previous
.getFoundDecl());
13499 assert(Name
.getKind() == UnqualifiedIdKind::IK_Identifier
&&
13500 "name in alias declaration must be an identifier");
13501 TypeAliasDecl
*NewTD
= TypeAliasDecl::Create(Context
, CurContext
, UsingLoc
,
13502 Name
.StartLocation
,
13503 Name
.Identifier
, TInfo
);
13505 NewTD
->setAccess(AS
);
13508 NewTD
->setInvalidDecl();
13510 ProcessDeclAttributeList(S
, NewTD
, AttrList
);
13511 AddPragmaAttributes(S
, NewTD
);
13513 CheckTypedefForVariablyModifiedType(S
, NewTD
);
13514 Invalid
|= NewTD
->isInvalidDecl();
13516 bool Redeclaration
= false;
13519 if (TemplateParamLists
.size()) {
13520 TypeAliasTemplateDecl
*OldDecl
= nullptr;
13521 TemplateParameterList
*OldTemplateParams
= nullptr;
13523 if (TemplateParamLists
.size() != 1) {
13524 Diag(UsingLoc
, diag::err_alias_template_extra_headers
)
13525 << SourceRange(TemplateParamLists
[1]->getTemplateLoc(),
13526 TemplateParamLists
[TemplateParamLists
.size()-1]->getRAngleLoc());
13528 TemplateParameterList
*TemplateParams
= TemplateParamLists
[0];
13530 // Check that we can declare a template here.
13531 if (CheckTemplateDeclScope(S
, TemplateParams
))
13534 // Only consider previous declarations in the same scope.
13535 FilterLookupForScope(Previous
, CurContext
, S
, /*ConsiderLinkage*/false,
13536 /*ExplicitInstantiationOrSpecialization*/false);
13537 if (!Previous
.empty()) {
13538 Redeclaration
= true;
13540 OldDecl
= Previous
.getAsSingle
<TypeAliasTemplateDecl
>();
13541 if (!OldDecl
&& !Invalid
) {
13542 Diag(UsingLoc
, diag::err_redefinition_different_kind
)
13543 << Name
.Identifier
;
13545 NamedDecl
*OldD
= Previous
.getRepresentativeDecl();
13546 if (OldD
->getLocation().isValid())
13547 Diag(OldD
->getLocation(), diag::note_previous_definition
);
13552 if (!Invalid
&& OldDecl
&& !OldDecl
->isInvalidDecl()) {
13553 if (TemplateParameterListsAreEqual(TemplateParams
,
13554 OldDecl
->getTemplateParameters(),
13556 TPL_TemplateMatch
))
13557 OldTemplateParams
=
13558 OldDecl
->getMostRecentDecl()->getTemplateParameters();
13562 TypeAliasDecl
*OldTD
= OldDecl
->getTemplatedDecl();
13564 !Context
.hasSameType(OldTD
->getUnderlyingType(),
13565 NewTD
->getUnderlyingType())) {
13566 // FIXME: The C++0x standard does not clearly say this is ill-formed,
13567 // but we can't reasonably accept it.
13568 Diag(NewTD
->getLocation(), diag::err_redefinition_different_typedef
)
13569 << 2 << NewTD
->getUnderlyingType() << OldTD
->getUnderlyingType();
13570 if (OldTD
->getLocation().isValid())
13571 Diag(OldTD
->getLocation(), diag::note_previous_definition
);
13577 // Merge any previous default template arguments into our parameters,
13578 // and check the parameter list.
13579 if (CheckTemplateParameterList(TemplateParams
, OldTemplateParams
,
13580 TPC_TypeAliasTemplate
))
13583 TypeAliasTemplateDecl
*NewDecl
=
13584 TypeAliasTemplateDecl::Create(Context
, CurContext
, UsingLoc
,
13585 Name
.Identifier
, TemplateParams
,
13587 NewTD
->setDescribedAliasTemplate(NewDecl
);
13589 NewDecl
->setAccess(AS
);
13592 NewDecl
->setInvalidDecl();
13593 else if (OldDecl
) {
13594 NewDecl
->setPreviousDecl(OldDecl
);
13595 CheckRedeclarationInModule(NewDecl
, OldDecl
);
13600 if (auto *TD
= dyn_cast_or_null
<TagDecl
>(DeclFromDeclSpec
)) {
13601 setTagNameForLinkagePurposes(TD
, NewTD
);
13602 handleTagNumbering(TD
, S
);
13604 ActOnTypedefNameDecl(S
, CurContext
, NewTD
, Previous
, Redeclaration
);
13608 PushOnScopeChains(NewND
, S
);
13609 ActOnDocumentableDecl(NewND
);
13613 Decl
*Sema::ActOnNamespaceAliasDef(Scope
*S
, SourceLocation NamespaceLoc
,
13614 SourceLocation AliasLoc
,
13615 IdentifierInfo
*Alias
, CXXScopeSpec
&SS
,
13616 SourceLocation IdentLoc
,
13617 IdentifierInfo
*Ident
) {
13619 // Lookup the namespace name.
13620 LookupResult
R(*this, Ident
, IdentLoc
, LookupNamespaceName
);
13621 LookupParsedName(R
, S
, &SS
);
13623 if (R
.isAmbiguous())
13627 if (!TryNamespaceTypoCorrection(*this, R
, S
, SS
, IdentLoc
, Ident
)) {
13628 Diag(IdentLoc
, diag::err_expected_namespace_name
) << SS
.getRange();
13632 assert(!R
.isAmbiguous() && !R
.empty());
13633 NamedDecl
*ND
= R
.getRepresentativeDecl();
13635 // Check if we have a previous declaration with the same name.
13636 LookupResult
PrevR(*this, Alias
, AliasLoc
, LookupOrdinaryName
,
13637 ForVisibleRedeclaration
);
13638 LookupName(PrevR
, S
);
13640 // Check we're not shadowing a template parameter.
13641 if (PrevR
.isSingleResult() && PrevR
.getFoundDecl()->isTemplateParameter()) {
13642 DiagnoseTemplateParameterShadow(AliasLoc
, PrevR
.getFoundDecl());
13646 // Filter out any other lookup result from an enclosing scope.
13647 FilterLookupForScope(PrevR
, CurContext
, S
, /*ConsiderLinkage*/false,
13648 /*AllowInlineNamespace*/false);
13650 // Find the previous declaration and check that we can redeclare it.
13651 NamespaceAliasDecl
*Prev
= nullptr;
13652 if (PrevR
.isSingleResult()) {
13653 NamedDecl
*PrevDecl
= PrevR
.getRepresentativeDecl();
13654 if (NamespaceAliasDecl
*AD
= dyn_cast
<NamespaceAliasDecl
>(PrevDecl
)) {
13655 // We already have an alias with the same name that points to the same
13656 // namespace; check that it matches.
13657 if (AD
->getNamespace()->Equals(getNamespaceDecl(ND
))) {
13659 } else if (isVisible(PrevDecl
)) {
13660 Diag(AliasLoc
, diag::err_redefinition_different_namespace_alias
)
13662 Diag(AD
->getLocation(), diag::note_previous_namespace_alias
)
13663 << AD
->getNamespace();
13666 } else if (isVisible(PrevDecl
)) {
13667 unsigned DiagID
= isa
<NamespaceDecl
>(PrevDecl
->getUnderlyingDecl())
13668 ? diag::err_redefinition
13669 : diag::err_redefinition_different_kind
;
13670 Diag(AliasLoc
, DiagID
) << Alias
;
13671 Diag(PrevDecl
->getLocation(), diag::note_previous_definition
);
13676 // The use of a nested name specifier may trigger deprecation warnings.
13677 DiagnoseUseOfDecl(ND
, IdentLoc
);
13679 NamespaceAliasDecl
*AliasDecl
=
13680 NamespaceAliasDecl::Create(Context
, CurContext
, NamespaceLoc
, AliasLoc
,
13681 Alias
, SS
.getWithLocInContext(Context
),
13684 AliasDecl
->setPreviousDecl(Prev
);
13686 PushOnScopeChains(AliasDecl
, S
);
13691 struct SpecialMemberExceptionSpecInfo
13692 : SpecialMemberVisitor
<SpecialMemberExceptionSpecInfo
> {
13693 SourceLocation Loc
;
13694 Sema::ImplicitExceptionSpecification ExceptSpec
;
13696 SpecialMemberExceptionSpecInfo(Sema
&S
, CXXMethodDecl
*MD
,
13697 Sema::CXXSpecialMember CSM
,
13698 Sema::InheritedConstructorInfo
*ICI
,
13699 SourceLocation Loc
)
13700 : SpecialMemberVisitor(S
, MD
, CSM
, ICI
), Loc(Loc
), ExceptSpec(S
) {}
13702 bool visitBase(CXXBaseSpecifier
*Base
);
13703 bool visitField(FieldDecl
*FD
);
13705 void visitClassSubobject(CXXRecordDecl
*Class
, Subobject Subobj
,
13708 void visitSubobjectCall(Subobject Subobj
,
13709 Sema::SpecialMemberOverloadResult SMOR
);
13713 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier
*Base
) {
13714 auto *RT
= Base
->getType()->getAs
<RecordType
>();
13718 auto *BaseClass
= cast
<CXXRecordDecl
>(RT
->getDecl());
13719 Sema::SpecialMemberOverloadResult SMOR
= lookupInheritedCtor(BaseClass
);
13720 if (auto *BaseCtor
= SMOR
.getMethod()) {
13721 visitSubobjectCall(Base
, BaseCtor
);
13725 visitClassSubobject(BaseClass
, Base
, 0);
13729 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl
*FD
) {
13730 if (CSM
== Sema::CXXDefaultConstructor
&& FD
->hasInClassInitializer()) {
13731 Expr
*E
= FD
->getInClassInitializer();
13733 // FIXME: It's a little wasteful to build and throw away a
13734 // CXXDefaultInitExpr here.
13735 // FIXME: We should have a single context note pointing at Loc, and
13736 // this location should be MD->getLocation() instead, since that's
13737 // the location where we actually use the default init expression.
13738 E
= S
.BuildCXXDefaultInitExpr(Loc
, FD
).get();
13740 ExceptSpec
.CalledExpr(E
);
13741 } else if (auto *RT
= S
.Context
.getBaseElementType(FD
->getType())
13742 ->getAs
<RecordType
>()) {
13743 visitClassSubobject(cast
<CXXRecordDecl
>(RT
->getDecl()), FD
,
13744 FD
->getType().getCVRQualifiers());
13749 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl
*Class
,
13752 FieldDecl
*Field
= Subobj
.dyn_cast
<FieldDecl
*>();
13753 bool IsMutable
= Field
&& Field
->isMutable();
13754 visitSubobjectCall(Subobj
, lookupIn(Class
, Quals
, IsMutable
));
13757 void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
13758 Subobject Subobj
, Sema::SpecialMemberOverloadResult SMOR
) {
13759 // Note, if lookup fails, it doesn't matter what exception specification we
13760 // choose because the special member will be deleted.
13761 if (CXXMethodDecl
*MD
= SMOR
.getMethod())
13762 ExceptSpec
.CalledDecl(getSubobjectLoc(Subobj
), MD
);
13765 bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier
&ExplicitSpec
) {
13766 llvm::APSInt Result
;
13767 ExprResult Converted
= CheckConvertedConstantExpression(
13768 ExplicitSpec
.getExpr(), Context
.BoolTy
, Result
, CCEK_ExplicitBool
);
13769 ExplicitSpec
.setExpr(Converted
.get());
13770 if (Converted
.isUsable() && !Converted
.get()->isValueDependent()) {
13771 ExplicitSpec
.setKind(Result
.getBoolValue()
13772 ? ExplicitSpecKind::ResolvedTrue
13773 : ExplicitSpecKind::ResolvedFalse
);
13776 ExplicitSpec
.setKind(ExplicitSpecKind::Unresolved
);
13780 ExplicitSpecifier
Sema::ActOnExplicitBoolSpecifier(Expr
*ExplicitExpr
) {
13781 ExplicitSpecifier
ES(ExplicitExpr
, ExplicitSpecKind::Unresolved
);
13782 if (!ExplicitExpr
->isTypeDependent())
13783 tryResolveExplicitSpecifier(ES
);
13787 static Sema::ImplicitExceptionSpecification
13788 ComputeDefaultedSpecialMemberExceptionSpec(
13789 Sema
&S
, SourceLocation Loc
, CXXMethodDecl
*MD
, Sema::CXXSpecialMember CSM
,
13790 Sema::InheritedConstructorInfo
*ICI
) {
13791 ComputingExceptionSpec
CES(S
, MD
, Loc
);
13793 CXXRecordDecl
*ClassDecl
= MD
->getParent();
13795 // C++ [except.spec]p14:
13796 // An implicitly declared special member function (Clause 12) shall have an
13797 // exception-specification. [...]
13798 SpecialMemberExceptionSpecInfo
Info(S
, MD
, CSM
, ICI
, MD
->getLocation());
13799 if (ClassDecl
->isInvalidDecl())
13800 return Info
.ExceptSpec
;
13802 // FIXME: If this diagnostic fires, we're probably missing a check for
13803 // attempting to resolve an exception specification before it's known
13804 // at a higher level.
13805 if (S
.RequireCompleteType(MD
->getLocation(),
13806 S
.Context
.getRecordType(ClassDecl
),
13807 diag::err_exception_spec_incomplete_type
))
13808 return Info
.ExceptSpec
;
13810 // C++1z [except.spec]p7:
13811 // [Look for exceptions thrown by] a constructor selected [...] to
13812 // initialize a potentially constructed subobject,
13813 // C++1z [except.spec]p8:
13814 // The exception specification for an implicitly-declared destructor, or a
13815 // destructor without a noexcept-specifier, is potentially-throwing if and
13816 // only if any of the destructors for any of its potentially constructed
13817 // subojects is potentially throwing.
13818 // FIXME: We respect the first rule but ignore the "potentially constructed"
13819 // in the second rule to resolve a core issue (no number yet) that would have
13821 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
13822 // struct B : A {};
13823 // struct C : B { void f(); };
13824 // ... due to giving B::~B() a non-throwing exception specification.
13825 Info
.visit(Info
.IsConstructor
? Info
.VisitPotentiallyConstructedBases
13826 : Info
.VisitAllBases
);
13828 return Info
.ExceptSpec
;
13832 /// RAII object to register a special member as being currently declared.
13833 struct DeclaringSpecialMember
{
13835 Sema::SpecialMemberDecl D
;
13836 Sema::ContextRAII SavedContext
;
13837 bool WasAlreadyBeingDeclared
;
13839 DeclaringSpecialMember(Sema
&S
, CXXRecordDecl
*RD
, Sema::CXXSpecialMember CSM
)
13840 : S(S
), D(RD
, CSM
), SavedContext(S
, RD
) {
13841 WasAlreadyBeingDeclared
= !S
.SpecialMembersBeingDeclared
.insert(D
).second
;
13842 if (WasAlreadyBeingDeclared
)
13843 // This almost never happens, but if it does, ensure that our cache
13844 // doesn't contain a stale result.
13845 S
.SpecialMemberCache
.clear();
13847 // Register a note to be produced if we encounter an error while
13848 // declaring the special member.
13849 Sema::CodeSynthesisContext Ctx
;
13850 Ctx
.Kind
= Sema::CodeSynthesisContext::DeclaringSpecialMember
;
13851 // FIXME: We don't have a location to use here. Using the class's
13852 // location maintains the fiction that we declare all special members
13853 // with the class, but (1) it's not clear that lying about that helps our
13854 // users understand what's going on, and (2) there may be outer contexts
13855 // on the stack (some of which are relevant) and printing them exposes
13857 Ctx
.PointOfInstantiation
= RD
->getLocation();
13859 Ctx
.SpecialMember
= CSM
;
13860 S
.pushCodeSynthesisContext(Ctx
);
13863 ~DeclaringSpecialMember() {
13864 if (!WasAlreadyBeingDeclared
) {
13865 S
.SpecialMembersBeingDeclared
.erase(D
);
13866 S
.popCodeSynthesisContext();
13870 /// Are we already trying to declare this special member?
13871 bool isAlreadyBeingDeclared() const {
13872 return WasAlreadyBeingDeclared
;
13877 void Sema::CheckImplicitSpecialMemberDeclaration(Scope
*S
, FunctionDecl
*FD
) {
13878 // Look up any existing declarations, but don't trigger declaration of all
13879 // implicit special members with this name.
13880 DeclarationName Name
= FD
->getDeclName();
13881 LookupResult
R(*this, Name
, SourceLocation(), LookupOrdinaryName
,
13882 ForExternalRedeclaration
);
13883 for (auto *D
: FD
->getParent()->lookup(Name
))
13884 if (auto *Acceptable
= R
.getAcceptableDecl(D
))
13885 R
.addDecl(Acceptable
);
13887 R
.suppressDiagnostics();
13889 CheckFunctionDeclaration(S
, FD
, R
, /*IsMemberSpecialization*/ false,
13890 FD
->isThisDeclarationADefinition());
13893 void Sema::setupImplicitSpecialMemberType(CXXMethodDecl
*SpecialMem
,
13895 ArrayRef
<QualType
> Args
) {
13896 // Build an exception specification pointing back at this constructor.
13897 FunctionProtoType::ExtProtoInfo EPI
= getImplicitMethodEPI(*this, SpecialMem
);
13899 LangAS AS
= getDefaultCXXMethodAddrSpace();
13900 if (AS
!= LangAS::Default
) {
13901 EPI
.TypeQuals
.addAddressSpace(AS
);
13904 auto QT
= Context
.getFunctionType(ResultTy
, Args
, EPI
);
13905 SpecialMem
->setType(QT
);
13907 // During template instantiation of implicit special member functions we need
13908 // a reliable TypeSourceInfo for the function prototype in order to allow
13909 // functions to be substituted.
13910 if (inTemplateInstantiation() &&
13911 cast
<CXXRecordDecl
>(SpecialMem
->getParent())->isLambda()) {
13912 TypeSourceInfo
*TSI
=
13913 Context
.getTrivialTypeSourceInfo(SpecialMem
->getType());
13914 SpecialMem
->setTypeSourceInfo(TSI
);
13918 CXXConstructorDecl
*Sema::DeclareImplicitDefaultConstructor(
13919 CXXRecordDecl
*ClassDecl
) {
13920 // C++ [class.ctor]p5:
13921 // A default constructor for a class X is a constructor of class X
13922 // that can be called without an argument. If there is no
13923 // user-declared constructor for class X, a default constructor is
13924 // implicitly declared. An implicitly-declared default constructor
13925 // is an inline public member of its class.
13926 assert(ClassDecl
->needsImplicitDefaultConstructor() &&
13927 "Should not build implicit default constructor!");
13929 DeclaringSpecialMember
DSM(*this, ClassDecl
, CXXDefaultConstructor
);
13930 if (DSM
.isAlreadyBeingDeclared())
13933 bool Constexpr
= defaultedSpecialMemberIsConstexpr(*this, ClassDecl
,
13934 CXXDefaultConstructor
,
13937 // Create the actual constructor declaration.
13938 CanQualType ClassType
13939 = Context
.getCanonicalType(Context
.getTypeDeclType(ClassDecl
));
13940 SourceLocation ClassLoc
= ClassDecl
->getLocation();
13941 DeclarationName Name
13942 = Context
.DeclarationNames
.getCXXConstructorName(ClassType
);
13943 DeclarationNameInfo
NameInfo(Name
, ClassLoc
);
13944 CXXConstructorDecl
*DefaultCon
= CXXConstructorDecl::Create(
13945 Context
, ClassDecl
, ClassLoc
, NameInfo
, /*Type*/ QualType(),
13946 /*TInfo=*/nullptr, ExplicitSpecifier(),
13947 getCurFPFeatures().isFPConstrained(),
13948 /*isInline=*/true, /*isImplicitlyDeclared=*/true,
13949 Constexpr
? ConstexprSpecKind::Constexpr
13950 : ConstexprSpecKind::Unspecified
);
13951 DefaultCon
->setAccess(AS_public
);
13952 DefaultCon
->setDefaulted();
13954 setupImplicitSpecialMemberType(DefaultCon
, Context
.VoidTy
, std::nullopt
);
13956 if (getLangOpts().CUDA
)
13957 inferCUDATargetForImplicitSpecialMember(ClassDecl
, CXXDefaultConstructor
,
13959 /* ConstRHS */ false,
13960 /* Diagnose */ false);
13962 // We don't need to use SpecialMemberIsTrivial here; triviality for default
13963 // constructors is easy to compute.
13964 DefaultCon
->setTrivial(ClassDecl
->hasTrivialDefaultConstructor());
13966 // Note that we have declared this constructor.
13967 ++getASTContext().NumImplicitDefaultConstructorsDeclared
;
13969 Scope
*S
= getScopeForContext(ClassDecl
);
13970 CheckImplicitSpecialMemberDeclaration(S
, DefaultCon
);
13972 if (ShouldDeleteSpecialMember(DefaultCon
, CXXDefaultConstructor
))
13973 SetDeclDeleted(DefaultCon
, ClassLoc
);
13976 PushOnScopeChains(DefaultCon
, S
, false);
13977 ClassDecl
->addDecl(DefaultCon
);
13982 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation
,
13983 CXXConstructorDecl
*Constructor
) {
13984 assert((Constructor
->isDefaulted() && Constructor
->isDefaultConstructor() &&
13985 !Constructor
->doesThisDeclarationHaveABody() &&
13986 !Constructor
->isDeleted()) &&
13987 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
13988 if (Constructor
->willHaveBody() || Constructor
->isInvalidDecl())
13991 CXXRecordDecl
*ClassDecl
= Constructor
->getParent();
13992 assert(ClassDecl
&& "DefineImplicitDefaultConstructor - invalid constructor");
13994 SynthesizedFunctionScope
Scope(*this, Constructor
);
13996 // The exception specification is needed because we are defining the
13998 ResolveExceptionSpec(CurrentLocation
,
13999 Constructor
->getType()->castAs
<FunctionProtoType
>());
14000 MarkVTableUsed(CurrentLocation
, ClassDecl
);
14002 // Add a context note for diagnostics produced after this point.
14003 Scope
.addContextNote(CurrentLocation
);
14005 if (SetCtorInitializers(Constructor
, /*AnyErrors=*/false)) {
14006 Constructor
->setInvalidDecl();
14010 SourceLocation Loc
= Constructor
->getEndLoc().isValid()
14011 ? Constructor
->getEndLoc()
14012 : Constructor
->getLocation();
14013 Constructor
->setBody(new (Context
) CompoundStmt(Loc
));
14014 Constructor
->markUsed(Context
);
14016 if (ASTMutationListener
*L
= getASTMutationListener()) {
14017 L
->CompletedImplicitDefinition(Constructor
);
14020 DiagnoseUninitializedFields(*this, Constructor
);
14023 void Sema::ActOnFinishDelayedMemberInitializers(Decl
*D
) {
14024 // Perform any delayed checks on exception specifications.
14025 CheckDelayedMemberExceptionSpecs();
14028 /// Find or create the fake constructor we synthesize to model constructing an
14029 /// object of a derived class via a constructor of a base class.
14030 CXXConstructorDecl
*
14031 Sema::findInheritingConstructor(SourceLocation Loc
,
14032 CXXConstructorDecl
*BaseCtor
,
14033 ConstructorUsingShadowDecl
*Shadow
) {
14034 CXXRecordDecl
*Derived
= Shadow
->getParent();
14035 SourceLocation UsingLoc
= Shadow
->getLocation();
14037 // FIXME: Add a new kind of DeclarationName for an inherited constructor.
14038 // For now we use the name of the base class constructor as a member of the
14039 // derived class to indicate a (fake) inherited constructor name.
14040 DeclarationName Name
= BaseCtor
->getDeclName();
14042 // Check to see if we already have a fake constructor for this inherited
14043 // constructor call.
14044 for (NamedDecl
*Ctor
: Derived
->lookup(Name
))
14045 if (declaresSameEntity(cast
<CXXConstructorDecl
>(Ctor
)
14046 ->getInheritedConstructor()
14049 return cast
<CXXConstructorDecl
>(Ctor
);
14051 DeclarationNameInfo
NameInfo(Name
, UsingLoc
);
14052 TypeSourceInfo
*TInfo
=
14053 Context
.getTrivialTypeSourceInfo(BaseCtor
->getType(), UsingLoc
);
14054 FunctionProtoTypeLoc ProtoLoc
=
14055 TInfo
->getTypeLoc().IgnoreParens().castAs
<FunctionProtoTypeLoc
>();
14057 // Check the inherited constructor is valid and find the list of base classes
14058 // from which it was inherited.
14059 InheritedConstructorInfo
ICI(*this, Loc
, Shadow
);
14062 BaseCtor
->isConstexpr() &&
14063 defaultedSpecialMemberIsConstexpr(*this, Derived
, CXXDefaultConstructor
,
14064 false, BaseCtor
, &ICI
);
14066 CXXConstructorDecl
*DerivedCtor
= CXXConstructorDecl::Create(
14067 Context
, Derived
, UsingLoc
, NameInfo
, TInfo
->getType(), TInfo
,
14068 BaseCtor
->getExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
14070 /*isImplicitlyDeclared=*/true,
14071 Constexpr
? BaseCtor
->getConstexprKind() : ConstexprSpecKind::Unspecified
,
14072 InheritedConstructor(Shadow
, BaseCtor
),
14073 BaseCtor
->getTrailingRequiresClause());
14074 if (Shadow
->isInvalidDecl())
14075 DerivedCtor
->setInvalidDecl();
14077 // Build an unevaluated exception specification for this fake constructor.
14078 const FunctionProtoType
*FPT
= TInfo
->getType()->castAs
<FunctionProtoType
>();
14079 FunctionProtoType::ExtProtoInfo EPI
= FPT
->getExtProtoInfo();
14080 EPI
.ExceptionSpec
.Type
= EST_Unevaluated
;
14081 EPI
.ExceptionSpec
.SourceDecl
= DerivedCtor
;
14082 DerivedCtor
->setType(Context
.getFunctionType(FPT
->getReturnType(),
14083 FPT
->getParamTypes(), EPI
));
14085 // Build the parameter declarations.
14086 SmallVector
<ParmVarDecl
*, 16> ParamDecls
;
14087 for (unsigned I
= 0, N
= FPT
->getNumParams(); I
!= N
; ++I
) {
14088 TypeSourceInfo
*TInfo
=
14089 Context
.getTrivialTypeSourceInfo(FPT
->getParamType(I
), UsingLoc
);
14090 ParmVarDecl
*PD
= ParmVarDecl::Create(
14091 Context
, DerivedCtor
, UsingLoc
, UsingLoc
, /*IdentifierInfo=*/nullptr,
14092 FPT
->getParamType(I
), TInfo
, SC_None
, /*DefArg=*/nullptr);
14093 PD
->setScopeInfo(0, I
);
14095 // Ensure attributes are propagated onto parameters (this matters for
14096 // format, pass_object_size, ...).
14097 mergeDeclAttributes(PD
, BaseCtor
->getParamDecl(I
));
14098 ParamDecls
.push_back(PD
);
14099 ProtoLoc
.setParam(I
, PD
);
14102 // Set up the new constructor.
14103 assert(!BaseCtor
->isDeleted() && "should not use deleted constructor");
14104 DerivedCtor
->setAccess(BaseCtor
->getAccess());
14105 DerivedCtor
->setParams(ParamDecls
);
14106 Derived
->addDecl(DerivedCtor
);
14108 if (ShouldDeleteSpecialMember(DerivedCtor
, CXXDefaultConstructor
, &ICI
))
14109 SetDeclDeleted(DerivedCtor
, UsingLoc
);
14111 return DerivedCtor
;
14114 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl
*Ctor
) {
14115 InheritedConstructorInfo
ICI(*this, Ctor
->getLocation(),
14116 Ctor
->getInheritedConstructor().getShadowDecl());
14117 ShouldDeleteSpecialMember(Ctor
, CXXDefaultConstructor
, &ICI
,
14121 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation
,
14122 CXXConstructorDecl
*Constructor
) {
14123 CXXRecordDecl
*ClassDecl
= Constructor
->getParent();
14124 assert(Constructor
->getInheritedConstructor() &&
14125 !Constructor
->doesThisDeclarationHaveABody() &&
14126 !Constructor
->isDeleted());
14127 if (Constructor
->willHaveBody() || Constructor
->isInvalidDecl())
14130 // Initializations are performed "as if by a defaulted default constructor",
14131 // so enter the appropriate scope.
14132 SynthesizedFunctionScope
Scope(*this, Constructor
);
14134 // The exception specification is needed because we are defining the
14136 ResolveExceptionSpec(CurrentLocation
,
14137 Constructor
->getType()->castAs
<FunctionProtoType
>());
14138 MarkVTableUsed(CurrentLocation
, ClassDecl
);
14140 // Add a context note for diagnostics produced after this point.
14141 Scope
.addContextNote(CurrentLocation
);
14143 ConstructorUsingShadowDecl
*Shadow
=
14144 Constructor
->getInheritedConstructor().getShadowDecl();
14145 CXXConstructorDecl
*InheritedCtor
=
14146 Constructor
->getInheritedConstructor().getConstructor();
14148 // [class.inhctor.init]p1:
14149 // initialization proceeds as if a defaulted default constructor is used to
14150 // initialize the D object and each base class subobject from which the
14151 // constructor was inherited
14153 InheritedConstructorInfo
ICI(*this, CurrentLocation
, Shadow
);
14154 CXXRecordDecl
*RD
= Shadow
->getParent();
14155 SourceLocation InitLoc
= Shadow
->getLocation();
14157 // Build explicit initializers for all base classes from which the
14158 // constructor was inherited.
14159 SmallVector
<CXXCtorInitializer
*, 8> Inits
;
14160 for (bool VBase
: {false, true}) {
14161 for (CXXBaseSpecifier
&B
: VBase
? RD
->vbases() : RD
->bases()) {
14162 if (B
.isVirtual() != VBase
)
14165 auto *BaseRD
= B
.getType()->getAsCXXRecordDecl();
14169 auto BaseCtor
= ICI
.findConstructorForBase(BaseRD
, InheritedCtor
);
14170 if (!BaseCtor
.first
)
14173 MarkFunctionReferenced(CurrentLocation
, BaseCtor
.first
);
14174 ExprResult Init
= new (Context
) CXXInheritedCtorInitExpr(
14175 InitLoc
, B
.getType(), BaseCtor
.first
, VBase
, BaseCtor
.second
);
14177 auto *TInfo
= Context
.getTrivialTypeSourceInfo(B
.getType(), InitLoc
);
14178 Inits
.push_back(new (Context
) CXXCtorInitializer(
14179 Context
, TInfo
, VBase
, InitLoc
, Init
.get(), InitLoc
,
14180 SourceLocation()));
14184 // We now proceed as if for a defaulted default constructor, with the relevant
14185 // initializers replaced.
14187 if (SetCtorInitializers(Constructor
, /*AnyErrors*/false, Inits
)) {
14188 Constructor
->setInvalidDecl();
14192 Constructor
->setBody(new (Context
) CompoundStmt(InitLoc
));
14193 Constructor
->markUsed(Context
);
14195 if (ASTMutationListener
*L
= getASTMutationListener()) {
14196 L
->CompletedImplicitDefinition(Constructor
);
14199 DiagnoseUninitializedFields(*this, Constructor
);
14202 CXXDestructorDecl
*Sema::DeclareImplicitDestructor(CXXRecordDecl
*ClassDecl
) {
14203 // C++ [class.dtor]p2:
14204 // If a class has no user-declared destructor, a destructor is
14205 // declared implicitly. An implicitly-declared destructor is an
14206 // inline public member of its class.
14207 assert(ClassDecl
->needsImplicitDestructor());
14209 DeclaringSpecialMember
DSM(*this, ClassDecl
, CXXDestructor
);
14210 if (DSM
.isAlreadyBeingDeclared())
14213 bool Constexpr
= defaultedSpecialMemberIsConstexpr(*this, ClassDecl
,
14217 // Create the actual destructor declaration.
14218 CanQualType ClassType
14219 = Context
.getCanonicalType(Context
.getTypeDeclType(ClassDecl
));
14220 SourceLocation ClassLoc
= ClassDecl
->getLocation();
14221 DeclarationName Name
14222 = Context
.DeclarationNames
.getCXXDestructorName(ClassType
);
14223 DeclarationNameInfo
NameInfo(Name
, ClassLoc
);
14224 CXXDestructorDecl
*Destructor
= CXXDestructorDecl::Create(
14225 Context
, ClassDecl
, ClassLoc
, NameInfo
, QualType(), nullptr,
14226 getCurFPFeatures().isFPConstrained(),
14228 /*isImplicitlyDeclared=*/true,
14229 Constexpr
? ConstexprSpecKind::Constexpr
14230 : ConstexprSpecKind::Unspecified
);
14231 Destructor
->setAccess(AS_public
);
14232 Destructor
->setDefaulted();
14234 setupImplicitSpecialMemberType(Destructor
, Context
.VoidTy
, std::nullopt
);
14236 if (getLangOpts().CUDA
)
14237 inferCUDATargetForImplicitSpecialMember(ClassDecl
, CXXDestructor
,
14239 /* ConstRHS */ false,
14240 /* Diagnose */ false);
14242 // We don't need to use SpecialMemberIsTrivial here; triviality for
14243 // destructors is easy to compute.
14244 Destructor
->setTrivial(ClassDecl
->hasTrivialDestructor());
14245 Destructor
->setTrivialForCall(ClassDecl
->hasAttr
<TrivialABIAttr
>() ||
14246 ClassDecl
->hasTrivialDestructorForCall());
14248 // Note that we have declared this destructor.
14249 ++getASTContext().NumImplicitDestructorsDeclared
;
14251 Scope
*S
= getScopeForContext(ClassDecl
);
14252 CheckImplicitSpecialMemberDeclaration(S
, Destructor
);
14254 // We can't check whether an implicit destructor is deleted before we complete
14255 // the definition of the class, because its validity depends on the alignment
14256 // of the class. We'll check this from ActOnFields once the class is complete.
14257 if (ClassDecl
->isCompleteDefinition() &&
14258 ShouldDeleteSpecialMember(Destructor
, CXXDestructor
))
14259 SetDeclDeleted(Destructor
, ClassLoc
);
14261 // Introduce this destructor into its scope.
14263 PushOnScopeChains(Destructor
, S
, false);
14264 ClassDecl
->addDecl(Destructor
);
14269 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation
,
14270 CXXDestructorDecl
*Destructor
) {
14271 assert((Destructor
->isDefaulted() &&
14272 !Destructor
->doesThisDeclarationHaveABody() &&
14273 !Destructor
->isDeleted()) &&
14274 "DefineImplicitDestructor - call it for implicit default dtor");
14275 if (Destructor
->willHaveBody() || Destructor
->isInvalidDecl())
14278 CXXRecordDecl
*ClassDecl
= Destructor
->getParent();
14279 assert(ClassDecl
&& "DefineImplicitDestructor - invalid destructor");
14281 SynthesizedFunctionScope
Scope(*this, Destructor
);
14283 // The exception specification is needed because we are defining the
14285 ResolveExceptionSpec(CurrentLocation
,
14286 Destructor
->getType()->castAs
<FunctionProtoType
>());
14287 MarkVTableUsed(CurrentLocation
, ClassDecl
);
14289 // Add a context note for diagnostics produced after this point.
14290 Scope
.addContextNote(CurrentLocation
);
14292 MarkBaseAndMemberDestructorsReferenced(Destructor
->getLocation(),
14293 Destructor
->getParent());
14295 if (CheckDestructor(Destructor
)) {
14296 Destructor
->setInvalidDecl();
14300 SourceLocation Loc
= Destructor
->getEndLoc().isValid()
14301 ? Destructor
->getEndLoc()
14302 : Destructor
->getLocation();
14303 Destructor
->setBody(new (Context
) CompoundStmt(Loc
));
14304 Destructor
->markUsed(Context
);
14306 if (ASTMutationListener
*L
= getASTMutationListener()) {
14307 L
->CompletedImplicitDefinition(Destructor
);
14311 void Sema::CheckCompleteDestructorVariant(SourceLocation CurrentLocation
,
14312 CXXDestructorDecl
*Destructor
) {
14313 if (Destructor
->isInvalidDecl())
14316 CXXRecordDecl
*ClassDecl
= Destructor
->getParent();
14317 assert(Context
.getTargetInfo().getCXXABI().isMicrosoft() &&
14318 "implicit complete dtors unneeded outside MS ABI");
14319 assert(ClassDecl
->getNumVBases() > 0 &&
14320 "complete dtor only exists for classes with vbases");
14322 SynthesizedFunctionScope
Scope(*this, Destructor
);
14324 // Add a context note for diagnostics produced after this point.
14325 Scope
.addContextNote(CurrentLocation
);
14327 MarkVirtualBaseDestructorsReferenced(Destructor
->getLocation(), ClassDecl
);
14330 /// Perform any semantic analysis which needs to be delayed until all
14331 /// pending class member declarations have been parsed.
14332 void Sema::ActOnFinishCXXMemberDecls() {
14333 // If the context is an invalid C++ class, just suppress these checks.
14334 if (CXXRecordDecl
*Record
= dyn_cast
<CXXRecordDecl
>(CurContext
)) {
14335 if (Record
->isInvalidDecl()) {
14336 DelayedOverridingExceptionSpecChecks
.clear();
14337 DelayedEquivalentExceptionSpecChecks
.clear();
14340 checkForMultipleExportedDefaultConstructors(*this, Record
);
14344 void Sema::ActOnFinishCXXNonNestedClass() {
14345 referenceDLLExportedClassMethods();
14347 if (!DelayedDllExportMemberFunctions
.empty()) {
14348 SmallVector
<CXXMethodDecl
*, 4> WorkList
;
14349 std::swap(DelayedDllExportMemberFunctions
, WorkList
);
14350 for (CXXMethodDecl
*M
: WorkList
) {
14351 DefineDefaultedFunction(*this, M
, M
->getLocation());
14353 // Pass the method to the consumer to get emitted. This is not necessary
14354 // for explicit instantiation definitions, as they will get emitted
14356 if (M
->getParent()->getTemplateSpecializationKind() !=
14357 TSK_ExplicitInstantiationDefinition
)
14358 ActOnFinishInlineFunctionDef(M
);
14363 void Sema::referenceDLLExportedClassMethods() {
14364 if (!DelayedDllExportClasses
.empty()) {
14365 // Calling ReferenceDllExportedMembers might cause the current function to
14366 // be called again, so use a local copy of DelayedDllExportClasses.
14367 SmallVector
<CXXRecordDecl
*, 4> WorkList
;
14368 std::swap(DelayedDllExportClasses
, WorkList
);
14369 for (CXXRecordDecl
*Class
: WorkList
)
14370 ReferenceDllExportedMembers(*this, Class
);
14374 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl
*Destructor
) {
14375 assert(getLangOpts().CPlusPlus11
&&
14376 "adjusting dtor exception specs was introduced in c++11");
14378 if (Destructor
->isDependentContext())
14381 // C++11 [class.dtor]p3:
14382 // A declaration of a destructor that does not have an exception-
14383 // specification is implicitly considered to have the same exception-
14384 // specification as an implicit declaration.
14385 const auto *DtorType
= Destructor
->getType()->castAs
<FunctionProtoType
>();
14386 if (DtorType
->hasExceptionSpec())
14389 // Replace the destructor's type, building off the existing one. Fortunately,
14390 // the only thing of interest in the destructor type is its extended info.
14391 // The return and arguments are fixed.
14392 FunctionProtoType::ExtProtoInfo EPI
= DtorType
->getExtProtoInfo();
14393 EPI
.ExceptionSpec
.Type
= EST_Unevaluated
;
14394 EPI
.ExceptionSpec
.SourceDecl
= Destructor
;
14395 Destructor
->setType(
14396 Context
.getFunctionType(Context
.VoidTy
, std::nullopt
, EPI
));
14398 // FIXME: If the destructor has a body that could throw, and the newly created
14399 // spec doesn't allow exceptions, we should emit a warning, because this
14400 // change in behavior can break conforming C++03 programs at runtime.
14401 // However, we don't have a body or an exception specification yet, so it
14402 // needs to be done somewhere else.
14406 /// An abstract base class for all helper classes used in building the
14407 // copy/move operators. These classes serve as factory functions and help us
14408 // avoid using the same Expr* in the AST twice.
14409 class ExprBuilder
{
14410 ExprBuilder(const ExprBuilder
&) = delete;
14411 ExprBuilder
&operator=(const ExprBuilder
&) = delete;
14414 static Expr
*assertNotNull(Expr
*E
) {
14415 assert(E
&& "Expression construction must not fail.");
14421 virtual ~ExprBuilder() {}
14423 virtual Expr
*build(Sema
&S
, SourceLocation Loc
) const = 0;
14426 class RefBuilder
: public ExprBuilder
{
14431 Expr
*build(Sema
&S
, SourceLocation Loc
) const override
{
14432 return assertNotNull(S
.BuildDeclRefExpr(Var
, VarType
, VK_LValue
, Loc
));
14435 RefBuilder(VarDecl
*Var
, QualType VarType
)
14436 : Var(Var
), VarType(VarType
) {}
14439 class ThisBuilder
: public ExprBuilder
{
14441 Expr
*build(Sema
&S
, SourceLocation Loc
) const override
{
14442 return assertNotNull(S
.ActOnCXXThis(Loc
).getAs
<Expr
>());
14446 class CastBuilder
: public ExprBuilder
{
14447 const ExprBuilder
&Builder
;
14449 ExprValueKind Kind
;
14450 const CXXCastPath
&Path
;
14453 Expr
*build(Sema
&S
, SourceLocation Loc
) const override
{
14454 return assertNotNull(S
.ImpCastExprToType(Builder
.build(S
, Loc
), Type
,
14455 CK_UncheckedDerivedToBase
, Kind
,
14459 CastBuilder(const ExprBuilder
&Builder
, QualType Type
, ExprValueKind Kind
,
14460 const CXXCastPath
&Path
)
14461 : Builder(Builder
), Type(Type
), Kind(Kind
), Path(Path
) {}
14464 class DerefBuilder
: public ExprBuilder
{
14465 const ExprBuilder
&Builder
;
14468 Expr
*build(Sema
&S
, SourceLocation Loc
) const override
{
14469 return assertNotNull(
14470 S
.CreateBuiltinUnaryOp(Loc
, UO_Deref
, Builder
.build(S
, Loc
)).get());
14473 DerefBuilder(const ExprBuilder
&Builder
) : Builder(Builder
) {}
14476 class MemberBuilder
: public ExprBuilder
{
14477 const ExprBuilder
&Builder
;
14481 LookupResult
&MemberLookup
;
14484 Expr
*build(Sema
&S
, SourceLocation Loc
) const override
{
14485 return assertNotNull(S
.BuildMemberReferenceExpr(
14486 Builder
.build(S
, Loc
), Type
, Loc
, IsArrow
, SS
, SourceLocation(),
14487 nullptr, MemberLookup
, nullptr, nullptr).get());
14490 MemberBuilder(const ExprBuilder
&Builder
, QualType Type
, bool IsArrow
,
14491 LookupResult
&MemberLookup
)
14492 : Builder(Builder
), Type(Type
), IsArrow(IsArrow
),
14493 MemberLookup(MemberLookup
) {}
14496 class MoveCastBuilder
: public ExprBuilder
{
14497 const ExprBuilder
&Builder
;
14500 Expr
*build(Sema
&S
, SourceLocation Loc
) const override
{
14501 return assertNotNull(CastForMoving(S
, Builder
.build(S
, Loc
)));
14504 MoveCastBuilder(const ExprBuilder
&Builder
) : Builder(Builder
) {}
14507 class LvalueConvBuilder
: public ExprBuilder
{
14508 const ExprBuilder
&Builder
;
14511 Expr
*build(Sema
&S
, SourceLocation Loc
) const override
{
14512 return assertNotNull(
14513 S
.DefaultLvalueConversion(Builder
.build(S
, Loc
)).get());
14516 LvalueConvBuilder(const ExprBuilder
&Builder
) : Builder(Builder
) {}
14519 class SubscriptBuilder
: public ExprBuilder
{
14520 const ExprBuilder
&Base
;
14521 const ExprBuilder
&Index
;
14524 Expr
*build(Sema
&S
, SourceLocation Loc
) const override
{
14525 return assertNotNull(S
.CreateBuiltinArraySubscriptExpr(
14526 Base
.build(S
, Loc
), Loc
, Index
.build(S
, Loc
), Loc
).get());
14529 SubscriptBuilder(const ExprBuilder
&Base
, const ExprBuilder
&Index
)
14530 : Base(Base
), Index(Index
) {}
14533 } // end anonymous namespace
14535 /// When generating a defaulted copy or move assignment operator, if a field
14536 /// should be copied with __builtin_memcpy rather than via explicit assignments,
14537 /// do so. This optimization only applies for arrays of scalars, and for arrays
14538 /// of class type where the selected copy/move-assignment operator is trivial.
14540 buildMemcpyForAssignmentOp(Sema
&S
, SourceLocation Loc
, QualType T
,
14541 const ExprBuilder
&ToB
, const ExprBuilder
&FromB
) {
14542 // Compute the size of the memory buffer to be copied.
14543 QualType SizeType
= S
.Context
.getSizeType();
14544 llvm::APInt
Size(S
.Context
.getTypeSize(SizeType
),
14545 S
.Context
.getTypeSizeInChars(T
).getQuantity());
14547 // Take the address of the field references for "from" and "to". We
14548 // directly construct UnaryOperators here because semantic analysis
14549 // does not permit us to take the address of an xvalue.
14550 Expr
*From
= FromB
.build(S
, Loc
);
14551 From
= UnaryOperator::Create(
14552 S
.Context
, From
, UO_AddrOf
, S
.Context
.getPointerType(From
->getType()),
14553 VK_PRValue
, OK_Ordinary
, Loc
, false, S
.CurFPFeatureOverrides());
14554 Expr
*To
= ToB
.build(S
, Loc
);
14555 To
= UnaryOperator::Create(
14556 S
.Context
, To
, UO_AddrOf
, S
.Context
.getPointerType(To
->getType()),
14557 VK_PRValue
, OK_Ordinary
, Loc
, false, S
.CurFPFeatureOverrides());
14559 const Type
*E
= T
->getBaseElementTypeUnsafe();
14560 bool NeedsCollectableMemCpy
=
14561 E
->isRecordType() &&
14562 E
->castAs
<RecordType
>()->getDecl()->hasObjectMember();
14564 // Create a reference to the __builtin_objc_memmove_collectable function
14565 StringRef MemCpyName
= NeedsCollectableMemCpy
?
14566 "__builtin_objc_memmove_collectable" :
14567 "__builtin_memcpy";
14568 LookupResult
R(S
, &S
.Context
.Idents
.get(MemCpyName
), Loc
,
14569 Sema::LookupOrdinaryName
);
14570 S
.LookupName(R
, S
.TUScope
, true);
14572 FunctionDecl
*MemCpy
= R
.getAsSingle
<FunctionDecl
>();
14574 // Something went horribly wrong earlier, and we will have complained
14576 return StmtError();
14578 ExprResult MemCpyRef
= S
.BuildDeclRefExpr(MemCpy
, S
.Context
.BuiltinFnTy
,
14579 VK_PRValue
, Loc
, nullptr);
14580 assert(MemCpyRef
.isUsable() && "Builtin reference cannot fail");
14582 Expr
*CallArgs
[] = {
14583 To
, From
, IntegerLiteral::Create(S
.Context
, Size
, SizeType
, Loc
)
14585 ExprResult Call
= S
.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef
.get(),
14586 Loc
, CallArgs
, Loc
);
14588 assert(!Call
.isInvalid() && "Call to __builtin_memcpy cannot fail!");
14589 return Call
.getAs
<Stmt
>();
14592 /// Builds a statement that copies/moves the given entity from \p From to
14595 /// This routine is used to copy/move the members of a class with an
14596 /// implicitly-declared copy/move assignment operator. When the entities being
14597 /// copied are arrays, this routine builds for loops to copy them.
14599 /// \param S The Sema object used for type-checking.
14601 /// \param Loc The location where the implicit copy/move is being generated.
14603 /// \param T The type of the expressions being copied/moved. Both expressions
14604 /// must have this type.
14606 /// \param To The expression we are copying/moving to.
14608 /// \param From The expression we are copying/moving from.
14610 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
14611 /// Otherwise, it's a non-static member subobject.
14613 /// \param Copying Whether we're copying or moving.
14615 /// \param Depth Internal parameter recording the depth of the recursion.
14617 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
14618 /// if a memcpy should be used instead.
14620 buildSingleCopyAssignRecursively(Sema
&S
, SourceLocation Loc
, QualType T
,
14621 const ExprBuilder
&To
, const ExprBuilder
&From
,
14622 bool CopyingBaseSubobject
, bool Copying
,
14623 unsigned Depth
= 0) {
14624 // C++11 [class.copy]p28:
14625 // Each subobject is assigned in the manner appropriate to its type:
14627 // - if the subobject is of class type, as if by a call to operator= with
14628 // the subobject as the object expression and the corresponding
14629 // subobject of x as a single function argument (as if by explicit
14630 // qualification; that is, ignoring any possible virtual overriding
14631 // functions in more derived classes);
14633 // C++03 [class.copy]p13:
14634 // - if the subobject is of class type, the copy assignment operator for
14635 // the class is used (as if by explicit qualification; that is,
14636 // ignoring any possible virtual overriding functions in more derived
14638 if (const RecordType
*RecordTy
= T
->getAs
<RecordType
>()) {
14639 CXXRecordDecl
*ClassDecl
= cast
<CXXRecordDecl
>(RecordTy
->getDecl());
14641 // Look for operator=.
14642 DeclarationName Name
14643 = S
.Context
.DeclarationNames
.getCXXOperatorName(OO_Equal
);
14644 LookupResult
OpLookup(S
, Name
, Loc
, Sema::LookupOrdinaryName
);
14645 S
.LookupQualifiedName(OpLookup
, ClassDecl
, false);
14647 // Prior to C++11, filter out any result that isn't a copy/move-assignment
14649 if (!S
.getLangOpts().CPlusPlus11
) {
14650 LookupResult::Filter F
= OpLookup
.makeFilter();
14651 while (F
.hasNext()) {
14652 NamedDecl
*D
= F
.next();
14653 if (CXXMethodDecl
*Method
= dyn_cast
<CXXMethodDecl
>(D
))
14654 if (Method
->isCopyAssignmentOperator() ||
14655 (!Copying
&& Method
->isMoveAssignmentOperator()))
14663 // Suppress the protected check (C++ [class.protected]) for each of the
14664 // assignment operators we found. This strange dance is required when
14665 // we're assigning via a base classes's copy-assignment operator. To
14666 // ensure that we're getting the right base class subobject (without
14667 // ambiguities), we need to cast "this" to that subobject type; to
14668 // ensure that we don't go through the virtual call mechanism, we need
14669 // to qualify the operator= name with the base class (see below). However,
14670 // this means that if the base class has a protected copy assignment
14671 // operator, the protected member access check will fail. So, we
14672 // rewrite "protected" access to "public" access in this case, since we
14673 // know by construction that we're calling from a derived class.
14674 if (CopyingBaseSubobject
) {
14675 for (LookupResult::iterator L
= OpLookup
.begin(), LEnd
= OpLookup
.end();
14677 if (L
.getAccess() == AS_protected
)
14678 L
.setAccess(AS_public
);
14682 // Create the nested-name-specifier that will be used to qualify the
14683 // reference to operator=; this is required to suppress the virtual
14686 const Type
*CanonicalT
= S
.Context
.getCanonicalType(T
.getTypePtr());
14687 SS
.MakeTrivial(S
.Context
,
14688 NestedNameSpecifier::Create(S
.Context
, nullptr, false,
14692 // Create the reference to operator=.
14693 ExprResult OpEqualRef
14694 = S
.BuildMemberReferenceExpr(To
.build(S
, Loc
), T
, Loc
, /*IsArrow=*/false,
14695 SS
, /*TemplateKWLoc=*/SourceLocation(),
14696 /*FirstQualifierInScope=*/nullptr,
14698 /*TemplateArgs=*/nullptr, /*S*/nullptr,
14699 /*SuppressQualifierCheck=*/true);
14700 if (OpEqualRef
.isInvalid())
14701 return StmtError();
14703 // Build the call to the assignment operator.
14705 Expr
*FromInst
= From
.build(S
, Loc
);
14706 ExprResult Call
= S
.BuildCallToMemberFunction(/*Scope=*/nullptr,
14707 OpEqualRef
.getAs
<Expr
>(),
14708 Loc
, FromInst
, Loc
);
14709 if (Call
.isInvalid())
14710 return StmtError();
14712 // If we built a call to a trivial 'operator=' while copying an array,
14713 // bail out. We'll replace the whole shebang with a memcpy.
14714 CXXMemberCallExpr
*CE
= dyn_cast
<CXXMemberCallExpr
>(Call
.get());
14715 if (CE
&& CE
->getMethodDecl()->isTrivial() && Depth
)
14716 return StmtResult((Stmt
*)nullptr);
14718 // Convert to an expression-statement, and clean up any produced
14720 return S
.ActOnExprStmt(Call
);
14723 // - if the subobject is of scalar type, the built-in assignment
14724 // operator is used.
14725 const ConstantArrayType
*ArrayTy
= S
.Context
.getAsConstantArrayType(T
);
14727 ExprResult Assignment
= S
.CreateBuiltinBinOp(
14728 Loc
, BO_Assign
, To
.build(S
, Loc
), From
.build(S
, Loc
));
14729 if (Assignment
.isInvalid())
14730 return StmtError();
14731 return S
.ActOnExprStmt(Assignment
);
14734 // - if the subobject is an array, each element is assigned, in the
14735 // manner appropriate to the element type;
14737 // Construct a loop over the array bounds, e.g.,
14739 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
14741 // that will copy each of the array elements.
14742 QualType SizeType
= S
.Context
.getSizeType();
14744 // Create the iteration variable.
14745 IdentifierInfo
*IterationVarName
= nullptr;
14747 SmallString
<8> Str
;
14748 llvm::raw_svector_ostream
OS(Str
);
14749 OS
<< "__i" << Depth
;
14750 IterationVarName
= &S
.Context
.Idents
.get(OS
.str());
14752 VarDecl
*IterationVar
= VarDecl::Create(S
.Context
, S
.CurContext
, Loc
, Loc
,
14753 IterationVarName
, SizeType
,
14754 S
.Context
.getTrivialTypeSourceInfo(SizeType
, Loc
),
14757 // Initialize the iteration variable to zero.
14758 llvm::APInt
Zero(S
.Context
.getTypeSize(SizeType
), 0);
14759 IterationVar
->setInit(IntegerLiteral::Create(S
.Context
, Zero
, SizeType
, Loc
));
14761 // Creates a reference to the iteration variable.
14762 RefBuilder
IterationVarRef(IterationVar
, SizeType
);
14763 LvalueConvBuilder
IterationVarRefRVal(IterationVarRef
);
14765 // Create the DeclStmt that holds the iteration variable.
14766 Stmt
*InitStmt
= new (S
.Context
) DeclStmt(DeclGroupRef(IterationVar
),Loc
,Loc
);
14768 // Subscript the "from" and "to" expressions with the iteration variable.
14769 SubscriptBuilder
FromIndexCopy(From
, IterationVarRefRVal
);
14770 MoveCastBuilder
FromIndexMove(FromIndexCopy
);
14771 const ExprBuilder
*FromIndex
;
14773 FromIndex
= &FromIndexCopy
;
14775 FromIndex
= &FromIndexMove
;
14777 SubscriptBuilder
ToIndex(To
, IterationVarRefRVal
);
14779 // Build the copy/move for an individual element of the array.
14781 buildSingleCopyAssignRecursively(S
, Loc
, ArrayTy
->getElementType(),
14782 ToIndex
, *FromIndex
, CopyingBaseSubobject
,
14783 Copying
, Depth
+ 1);
14784 // Bail out if copying fails or if we determined that we should use memcpy.
14785 if (Copy
.isInvalid() || !Copy
.get())
14788 // Create the comparison against the array bound.
14790 = ArrayTy
->getSize().zextOrTrunc(S
.Context
.getTypeSize(SizeType
));
14791 Expr
*Comparison
= BinaryOperator::Create(
14792 S
.Context
, IterationVarRefRVal
.build(S
, Loc
),
14793 IntegerLiteral::Create(S
.Context
, Upper
, SizeType
, Loc
), BO_NE
,
14794 S
.Context
.BoolTy
, VK_PRValue
, OK_Ordinary
, Loc
,
14795 S
.CurFPFeatureOverrides());
14797 // Create the pre-increment of the iteration variable. We can determine
14798 // whether the increment will overflow based on the value of the array
14800 Expr
*Increment
= UnaryOperator::Create(
14801 S
.Context
, IterationVarRef
.build(S
, Loc
), UO_PreInc
, SizeType
, VK_LValue
,
14802 OK_Ordinary
, Loc
, Upper
.isMaxValue(), S
.CurFPFeatureOverrides());
14804 // Construct the loop that copies all elements of this array.
14805 return S
.ActOnForStmt(
14806 Loc
, Loc
, InitStmt
,
14807 S
.ActOnCondition(nullptr, Loc
, Comparison
, Sema::ConditionKind::Boolean
),
14808 S
.MakeFullDiscardedValueExpr(Increment
), Loc
, Copy
.get());
14812 buildSingleCopyAssign(Sema
&S
, SourceLocation Loc
, QualType T
,
14813 const ExprBuilder
&To
, const ExprBuilder
&From
,
14814 bool CopyingBaseSubobject
, bool Copying
) {
14815 // Maybe we should use a memcpy?
14816 if (T
->isArrayType() && !T
.isConstQualified() && !T
.isVolatileQualified() &&
14817 T
.isTriviallyCopyableType(S
.Context
))
14818 return buildMemcpyForAssignmentOp(S
, Loc
, T
, To
, From
);
14820 StmtResult
Result(buildSingleCopyAssignRecursively(S
, Loc
, T
, To
, From
,
14821 CopyingBaseSubobject
,
14824 // If we ended up picking a trivial assignment operator for an array of a
14825 // non-trivially-copyable class type, just emit a memcpy.
14826 if (!Result
.isInvalid() && !Result
.get())
14827 return buildMemcpyForAssignmentOp(S
, Loc
, T
, To
, From
);
14832 CXXMethodDecl
*Sema::DeclareImplicitCopyAssignment(CXXRecordDecl
*ClassDecl
) {
14833 // Note: The following rules are largely analoguous to the copy
14834 // constructor rules. Note that virtual bases are not taken into account
14835 // for determining the argument type of the operator. Note also that
14836 // operators taking an object instead of a reference are allowed.
14837 assert(ClassDecl
->needsImplicitCopyAssignment());
14839 DeclaringSpecialMember
DSM(*this, ClassDecl
, CXXCopyAssignment
);
14840 if (DSM
.isAlreadyBeingDeclared())
14843 QualType ArgType
= Context
.getTypeDeclType(ClassDecl
);
14844 ArgType
= Context
.getElaboratedType(ElaboratedTypeKeyword::None
, nullptr,
14846 LangAS AS
= getDefaultCXXMethodAddrSpace();
14847 if (AS
!= LangAS::Default
)
14848 ArgType
= Context
.getAddrSpaceQualType(ArgType
, AS
);
14849 QualType RetType
= Context
.getLValueReferenceType(ArgType
);
14850 bool Const
= ClassDecl
->implicitCopyAssignmentHasConstParam();
14852 ArgType
= ArgType
.withConst();
14854 ArgType
= Context
.getLValueReferenceType(ArgType
);
14856 bool Constexpr
= defaultedSpecialMemberIsConstexpr(*this, ClassDecl
,
14860 // An implicitly-declared copy assignment operator is an inline public
14861 // member of its class.
14862 DeclarationName Name
= Context
.DeclarationNames
.getCXXOperatorName(OO_Equal
);
14863 SourceLocation ClassLoc
= ClassDecl
->getLocation();
14864 DeclarationNameInfo
NameInfo(Name
, ClassLoc
);
14865 CXXMethodDecl
*CopyAssignment
= CXXMethodDecl::Create(
14866 Context
, ClassDecl
, ClassLoc
, NameInfo
, QualType(),
14867 /*TInfo=*/nullptr, /*StorageClass=*/SC_None
,
14868 getCurFPFeatures().isFPConstrained(),
14870 Constexpr
? ConstexprSpecKind::Constexpr
: ConstexprSpecKind::Unspecified
,
14872 CopyAssignment
->setAccess(AS_public
);
14873 CopyAssignment
->setDefaulted();
14874 CopyAssignment
->setImplicit();
14876 setupImplicitSpecialMemberType(CopyAssignment
, RetType
, ArgType
);
14878 if (getLangOpts().CUDA
)
14879 inferCUDATargetForImplicitSpecialMember(ClassDecl
, CXXCopyAssignment
,
14881 /* ConstRHS */ Const
,
14882 /* Diagnose */ false);
14884 // Add the parameter to the operator.
14885 ParmVarDecl
*FromParam
= ParmVarDecl::Create(Context
, CopyAssignment
,
14886 ClassLoc
, ClassLoc
,
14887 /*Id=*/nullptr, ArgType
,
14888 /*TInfo=*/nullptr, SC_None
,
14890 CopyAssignment
->setParams(FromParam
);
14892 CopyAssignment
->setTrivial(
14893 ClassDecl
->needsOverloadResolutionForCopyAssignment()
14894 ? SpecialMemberIsTrivial(CopyAssignment
, CXXCopyAssignment
)
14895 : ClassDecl
->hasTrivialCopyAssignment());
14897 // Note that we have added this copy-assignment operator.
14898 ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared
;
14900 Scope
*S
= getScopeForContext(ClassDecl
);
14901 CheckImplicitSpecialMemberDeclaration(S
, CopyAssignment
);
14903 if (ShouldDeleteSpecialMember(CopyAssignment
, CXXCopyAssignment
)) {
14904 ClassDecl
->setImplicitCopyAssignmentIsDeleted();
14905 SetDeclDeleted(CopyAssignment
, ClassLoc
);
14909 PushOnScopeChains(CopyAssignment
, S
, false);
14910 ClassDecl
->addDecl(CopyAssignment
);
14912 return CopyAssignment
;
14915 /// Diagnose an implicit copy operation for a class which is odr-used, but
14916 /// which is deprecated because the class has a user-declared copy constructor,
14917 /// copy assignment operator, or destructor.
14918 static void diagnoseDeprecatedCopyOperation(Sema
&S
, CXXMethodDecl
*CopyOp
) {
14919 assert(CopyOp
->isImplicit());
14921 CXXRecordDecl
*RD
= CopyOp
->getParent();
14922 CXXMethodDecl
*UserDeclaredOperation
= nullptr;
14924 if (RD
->hasUserDeclaredDestructor()) {
14925 UserDeclaredOperation
= RD
->getDestructor();
14926 } else if (!isa
<CXXConstructorDecl
>(CopyOp
) &&
14927 RD
->hasUserDeclaredCopyConstructor()) {
14928 // Find any user-declared copy constructor.
14929 for (auto *I
: RD
->ctors()) {
14930 if (I
->isCopyConstructor()) {
14931 UserDeclaredOperation
= I
;
14935 assert(UserDeclaredOperation
);
14936 } else if (isa
<CXXConstructorDecl
>(CopyOp
) &&
14937 RD
->hasUserDeclaredCopyAssignment()) {
14938 // Find any user-declared move assignment operator.
14939 for (auto *I
: RD
->methods()) {
14940 if (I
->isCopyAssignmentOperator()) {
14941 UserDeclaredOperation
= I
;
14945 assert(UserDeclaredOperation
);
14948 if (UserDeclaredOperation
) {
14949 bool UDOIsUserProvided
= UserDeclaredOperation
->isUserProvided();
14950 bool UDOIsDestructor
= isa
<CXXDestructorDecl
>(UserDeclaredOperation
);
14951 bool IsCopyAssignment
= !isa
<CXXConstructorDecl
>(CopyOp
);
14953 (UDOIsUserProvided
&& UDOIsDestructor
)
14954 ? diag::warn_deprecated_copy_with_user_provided_dtor
14955 : (UDOIsUserProvided
&& !UDOIsDestructor
)
14956 ? diag::warn_deprecated_copy_with_user_provided_copy
14957 : (!UDOIsUserProvided
&& UDOIsDestructor
)
14958 ? diag::warn_deprecated_copy_with_dtor
14959 : diag::warn_deprecated_copy
;
14960 S
.Diag(UserDeclaredOperation
->getLocation(), DiagID
)
14961 << RD
<< IsCopyAssignment
;
14965 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation
,
14966 CXXMethodDecl
*CopyAssignOperator
) {
14967 assert((CopyAssignOperator
->isDefaulted() &&
14968 CopyAssignOperator
->isOverloadedOperator() &&
14969 CopyAssignOperator
->getOverloadedOperator() == OO_Equal
&&
14970 !CopyAssignOperator
->doesThisDeclarationHaveABody() &&
14971 !CopyAssignOperator
->isDeleted()) &&
14972 "DefineImplicitCopyAssignment called for wrong function");
14973 if (CopyAssignOperator
->willHaveBody() || CopyAssignOperator
->isInvalidDecl())
14976 CXXRecordDecl
*ClassDecl
= CopyAssignOperator
->getParent();
14977 if (ClassDecl
->isInvalidDecl()) {
14978 CopyAssignOperator
->setInvalidDecl();
14982 SynthesizedFunctionScope
Scope(*this, CopyAssignOperator
);
14984 // The exception specification is needed because we are defining the
14986 ResolveExceptionSpec(CurrentLocation
,
14987 CopyAssignOperator
->getType()->castAs
<FunctionProtoType
>());
14989 // Add a context note for diagnostics produced after this point.
14990 Scope
.addContextNote(CurrentLocation
);
14992 // C++11 [class.copy]p18:
14993 // The [definition of an implicitly declared copy assignment operator] is
14994 // deprecated if the class has a user-declared copy constructor or a
14995 // user-declared destructor.
14996 if (getLangOpts().CPlusPlus11
&& CopyAssignOperator
->isImplicit())
14997 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator
);
14999 // C++0x [class.copy]p30:
15000 // The implicitly-defined or explicitly-defaulted copy assignment operator
15001 // for a non-union class X performs memberwise copy assignment of its
15002 // subobjects. The direct base classes of X are assigned first, in the
15003 // order of their declaration in the base-specifier-list, and then the
15004 // immediate non-static data members of X are assigned, in the order in
15005 // which they were declared in the class definition.
15007 // The statements that form the synthesized function body.
15008 SmallVector
<Stmt
*, 8> Statements
;
15010 // The parameter for the "other" object, which we are copying from.
15011 ParmVarDecl
*Other
= CopyAssignOperator
->getNonObjectParameter(0);
15012 Qualifiers OtherQuals
= Other
->getType().getQualifiers();
15013 QualType OtherRefType
= Other
->getType();
15014 if (OtherRefType
->isLValueReferenceType()) {
15015 OtherRefType
= OtherRefType
->getPointeeType();
15016 OtherQuals
= OtherRefType
.getQualifiers();
15019 // Our location for everything implicitly-generated.
15020 SourceLocation Loc
= CopyAssignOperator
->getEndLoc().isValid()
15021 ? CopyAssignOperator
->getEndLoc()
15022 : CopyAssignOperator
->getLocation();
15024 // Builds a DeclRefExpr for the "other" object.
15025 RefBuilder
OtherRef(Other
, OtherRefType
);
15027 // Builds the function object parameter.
15028 std::optional
<ThisBuilder
> This
;
15029 std::optional
<DerefBuilder
> DerefThis
;
15030 std::optional
<RefBuilder
> ExplicitObject
;
15031 bool IsArrow
= false;
15032 QualType ObjectType
;
15033 if (CopyAssignOperator
->isExplicitObjectMemberFunction()) {
15034 ObjectType
= CopyAssignOperator
->getParamDecl(0)->getType();
15035 if (ObjectType
->isReferenceType())
15036 ObjectType
= ObjectType
->getPointeeType();
15037 ExplicitObject
.emplace(CopyAssignOperator
->getParamDecl(0), ObjectType
);
15039 ObjectType
= getCurrentThisType();
15041 DerefThis
.emplace(*This
);
15042 IsArrow
= !LangOpts
.HLSL
;
15044 ExprBuilder
&ObjectParameter
=
15045 ExplicitObject
? static_cast<ExprBuilder
&>(*ExplicitObject
)
15046 : static_cast<ExprBuilder
&>(*This
);
15048 // Assign base classes.
15049 bool Invalid
= false;
15050 for (auto &Base
: ClassDecl
->bases()) {
15051 // Form the assignment:
15052 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
15053 QualType BaseType
= Base
.getType().getUnqualifiedType();
15054 if (!BaseType
->isRecordType()) {
15059 CXXCastPath BasePath
;
15060 BasePath
.push_back(&Base
);
15062 // Construct the "from" expression, which is an implicit cast to the
15063 // appropriately-qualified base type.
15064 CastBuilder
From(OtherRef
, Context
.getQualifiedType(BaseType
, OtherQuals
),
15065 VK_LValue
, BasePath
);
15067 // Dereference "this".
15069 ExplicitObject
? static_cast<ExprBuilder
&>(*ExplicitObject
)
15070 : static_cast<ExprBuilder
&>(*DerefThis
),
15071 Context
.getQualifiedType(BaseType
, ObjectType
.getQualifiers()),
15072 VK_LValue
, BasePath
);
15075 StmtResult Copy
= buildSingleCopyAssign(*this, Loc
, BaseType
,
15077 /*CopyingBaseSubobject=*/true,
15079 if (Copy
.isInvalid()) {
15080 CopyAssignOperator
->setInvalidDecl();
15084 // Success! Record the copy.
15085 Statements
.push_back(Copy
.getAs
<Expr
>());
15088 // Assign non-static members.
15089 for (auto *Field
: ClassDecl
->fields()) {
15090 // FIXME: We should form some kind of AST representation for the implied
15091 // memcpy in a union copy operation.
15092 if (Field
->isUnnamedBitfield() || Field
->getParent()->isUnion())
15095 if (Field
->isInvalidDecl()) {
15100 // Check for members of reference type; we can't copy those.
15101 if (Field
->getType()->isReferenceType()) {
15102 Diag(ClassDecl
->getLocation(), diag::err_uninitialized_member_for_assign
)
15103 << Context
.getTagDeclType(ClassDecl
) << 0 << Field
->getDeclName();
15104 Diag(Field
->getLocation(), diag::note_declared_at
);
15109 // Check for members of const-qualified, non-class type.
15110 QualType BaseType
= Context
.getBaseElementType(Field
->getType());
15111 if (!BaseType
->getAs
<RecordType
>() && BaseType
.isConstQualified()) {
15112 Diag(ClassDecl
->getLocation(), diag::err_uninitialized_member_for_assign
)
15113 << Context
.getTagDeclType(ClassDecl
) << 1 << Field
->getDeclName();
15114 Diag(Field
->getLocation(), diag::note_declared_at
);
15119 // Suppress assigning zero-width bitfields.
15120 if (Field
->isZeroLengthBitField(Context
))
15123 QualType FieldType
= Field
->getType().getNonReferenceType();
15124 if (FieldType
->isIncompleteArrayType()) {
15125 assert(ClassDecl
->hasFlexibleArrayMember() &&
15126 "Incomplete array type is not valid");
15130 // Build references to the field in the object we're copying from and to.
15131 CXXScopeSpec SS
; // Intentionally empty
15132 LookupResult
MemberLookup(*this, Field
->getDeclName(), Loc
,
15134 MemberLookup
.addDecl(Field
);
15135 MemberLookup
.resolveKind();
15137 MemberBuilder
From(OtherRef
, OtherRefType
, /*IsArrow=*/false, MemberLookup
);
15138 MemberBuilder
To(ObjectParameter
, ObjectType
, IsArrow
, MemberLookup
);
15139 // Build the copy of this field.
15140 StmtResult Copy
= buildSingleCopyAssign(*this, Loc
, FieldType
,
15142 /*CopyingBaseSubobject=*/false,
15144 if (Copy
.isInvalid()) {
15145 CopyAssignOperator
->setInvalidDecl();
15149 // Success! Record the copy.
15150 Statements
.push_back(Copy
.getAs
<Stmt
>());
15154 // Add a "return *this;"
15156 (ExplicitObject
? static_cast<ExprBuilder
&>(*ExplicitObject
)
15157 : LangOpts
.HLSL
? static_cast<ExprBuilder
&>(*This
)
15158 : static_cast<ExprBuilder
&>(*DerefThis
))
15159 .build(*this, Loc
);
15160 StmtResult Return
= BuildReturnStmt(Loc
, ThisExpr
);
15161 if (Return
.isInvalid())
15164 Statements
.push_back(Return
.getAs
<Stmt
>());
15168 CopyAssignOperator
->setInvalidDecl();
15174 CompoundScopeRAII
CompoundScope(*this);
15175 Body
= ActOnCompoundStmt(Loc
, Loc
, Statements
,
15176 /*isStmtExpr=*/false);
15177 assert(!Body
.isInvalid() && "Compound statement creation cannot fail");
15179 CopyAssignOperator
->setBody(Body
.getAs
<Stmt
>());
15180 CopyAssignOperator
->markUsed(Context
);
15182 if (ASTMutationListener
*L
= getASTMutationListener()) {
15183 L
->CompletedImplicitDefinition(CopyAssignOperator
);
15187 CXXMethodDecl
*Sema::DeclareImplicitMoveAssignment(CXXRecordDecl
*ClassDecl
) {
15188 assert(ClassDecl
->needsImplicitMoveAssignment());
15190 DeclaringSpecialMember
DSM(*this, ClassDecl
, CXXMoveAssignment
);
15191 if (DSM
.isAlreadyBeingDeclared())
15194 // Note: The following rules are largely analoguous to the move
15195 // constructor rules.
15197 QualType ArgType
= Context
.getTypeDeclType(ClassDecl
);
15198 ArgType
= Context
.getElaboratedType(ElaboratedTypeKeyword::None
, nullptr,
15200 LangAS AS
= getDefaultCXXMethodAddrSpace();
15201 if (AS
!= LangAS::Default
)
15202 ArgType
= Context
.getAddrSpaceQualType(ArgType
, AS
);
15203 QualType RetType
= Context
.getLValueReferenceType(ArgType
);
15204 ArgType
= Context
.getRValueReferenceType(ArgType
);
15206 bool Constexpr
= defaultedSpecialMemberIsConstexpr(*this, ClassDecl
,
15210 // An implicitly-declared move assignment operator is an inline public
15211 // member of its class.
15212 DeclarationName Name
= Context
.DeclarationNames
.getCXXOperatorName(OO_Equal
);
15213 SourceLocation ClassLoc
= ClassDecl
->getLocation();
15214 DeclarationNameInfo
NameInfo(Name
, ClassLoc
);
15215 CXXMethodDecl
*MoveAssignment
= CXXMethodDecl::Create(
15216 Context
, ClassDecl
, ClassLoc
, NameInfo
, QualType(),
15217 /*TInfo=*/nullptr, /*StorageClass=*/SC_None
,
15218 getCurFPFeatures().isFPConstrained(),
15220 Constexpr
? ConstexprSpecKind::Constexpr
: ConstexprSpecKind::Unspecified
,
15222 MoveAssignment
->setAccess(AS_public
);
15223 MoveAssignment
->setDefaulted();
15224 MoveAssignment
->setImplicit();
15226 setupImplicitSpecialMemberType(MoveAssignment
, RetType
, ArgType
);
15228 if (getLangOpts().CUDA
)
15229 inferCUDATargetForImplicitSpecialMember(ClassDecl
, CXXMoveAssignment
,
15231 /* ConstRHS */ false,
15232 /* Diagnose */ false);
15234 // Add the parameter to the operator.
15235 ParmVarDecl
*FromParam
= ParmVarDecl::Create(Context
, MoveAssignment
,
15236 ClassLoc
, ClassLoc
,
15237 /*Id=*/nullptr, ArgType
,
15238 /*TInfo=*/nullptr, SC_None
,
15240 MoveAssignment
->setParams(FromParam
);
15242 MoveAssignment
->setTrivial(
15243 ClassDecl
->needsOverloadResolutionForMoveAssignment()
15244 ? SpecialMemberIsTrivial(MoveAssignment
, CXXMoveAssignment
)
15245 : ClassDecl
->hasTrivialMoveAssignment());
15247 // Note that we have added this copy-assignment operator.
15248 ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared
;
15250 Scope
*S
= getScopeForContext(ClassDecl
);
15251 CheckImplicitSpecialMemberDeclaration(S
, MoveAssignment
);
15253 if (ShouldDeleteSpecialMember(MoveAssignment
, CXXMoveAssignment
)) {
15254 ClassDecl
->setImplicitMoveAssignmentIsDeleted();
15255 SetDeclDeleted(MoveAssignment
, ClassLoc
);
15259 PushOnScopeChains(MoveAssignment
, S
, false);
15260 ClassDecl
->addDecl(MoveAssignment
);
15262 return MoveAssignment
;
15265 /// Check if we're implicitly defining a move assignment operator for a class
15266 /// with virtual bases. Such a move assignment might move-assign the virtual
15267 /// base multiple times.
15268 static void checkMoveAssignmentForRepeatedMove(Sema
&S
, CXXRecordDecl
*Class
,
15269 SourceLocation CurrentLocation
) {
15270 assert(!Class
->isDependentContext() && "should not define dependent move");
15272 // Only a virtual base could get implicitly move-assigned multiple times.
15273 // Only a non-trivial move assignment can observe this. We only want to
15274 // diagnose if we implicitly define an assignment operator that assigns
15275 // two base classes, both of which move-assign the same virtual base.
15276 if (Class
->getNumVBases() == 0 || Class
->hasTrivialMoveAssignment() ||
15277 Class
->getNumBases() < 2)
15280 llvm::SmallVector
<CXXBaseSpecifier
*, 16> Worklist
;
15281 typedef llvm::DenseMap
<CXXRecordDecl
*, CXXBaseSpecifier
*> VBaseMap
;
15284 for (auto &BI
: Class
->bases()) {
15285 Worklist
.push_back(&BI
);
15286 while (!Worklist
.empty()) {
15287 CXXBaseSpecifier
*BaseSpec
= Worklist
.pop_back_val();
15288 CXXRecordDecl
*Base
= BaseSpec
->getType()->getAsCXXRecordDecl();
15290 // If the base has no non-trivial move assignment operators,
15291 // we don't care about moves from it.
15292 if (!Base
->hasNonTrivialMoveAssignment())
15295 // If there's nothing virtual here, skip it.
15296 if (!BaseSpec
->isVirtual() && !Base
->getNumVBases())
15299 // If we're not actually going to call a move assignment for this base,
15300 // or the selected move assignment is trivial, skip it.
15301 Sema::SpecialMemberOverloadResult SMOR
=
15302 S
.LookupSpecialMember(Base
, Sema::CXXMoveAssignment
,
15303 /*ConstArg*/false, /*VolatileArg*/false,
15304 /*RValueThis*/true, /*ConstThis*/false,
15305 /*VolatileThis*/false);
15306 if (!SMOR
.getMethod() || SMOR
.getMethod()->isTrivial() ||
15307 !SMOR
.getMethod()->isMoveAssignmentOperator())
15310 if (BaseSpec
->isVirtual()) {
15311 // We're going to move-assign this virtual base, and its move
15312 // assignment operator is not trivial. If this can happen for
15313 // multiple distinct direct bases of Class, diagnose it. (If it
15314 // only happens in one base, we'll diagnose it when synthesizing
15315 // that base class's move assignment operator.)
15316 CXXBaseSpecifier
*&Existing
=
15317 VBases
.insert(std::make_pair(Base
->getCanonicalDecl(), &BI
))
15319 if (Existing
&& Existing
!= &BI
) {
15320 S
.Diag(CurrentLocation
, diag::warn_vbase_moved_multiple_times
)
15322 S
.Diag(Existing
->getBeginLoc(), diag::note_vbase_moved_here
)
15323 << (Base
->getCanonicalDecl() ==
15324 Existing
->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
15325 << Base
<< Existing
->getType() << Existing
->getSourceRange();
15326 S
.Diag(BI
.getBeginLoc(), diag::note_vbase_moved_here
)
15327 << (Base
->getCanonicalDecl() ==
15328 BI
.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
15329 << Base
<< BI
.getType() << BaseSpec
->getSourceRange();
15331 // Only diagnose each vbase once.
15332 Existing
= nullptr;
15335 // Only walk over bases that have defaulted move assignment operators.
15336 // We assume that any user-provided move assignment operator handles
15337 // the multiple-moves-of-vbase case itself somehow.
15338 if (!SMOR
.getMethod()->isDefaulted())
15341 // We're going to move the base classes of Base. Add them to the list.
15342 llvm::append_range(Worklist
, llvm::make_pointer_range(Base
->bases()));
15348 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation
,
15349 CXXMethodDecl
*MoveAssignOperator
) {
15350 assert((MoveAssignOperator
->isDefaulted() &&
15351 MoveAssignOperator
->isOverloadedOperator() &&
15352 MoveAssignOperator
->getOverloadedOperator() == OO_Equal
&&
15353 !MoveAssignOperator
->doesThisDeclarationHaveABody() &&
15354 !MoveAssignOperator
->isDeleted()) &&
15355 "DefineImplicitMoveAssignment called for wrong function");
15356 if (MoveAssignOperator
->willHaveBody() || MoveAssignOperator
->isInvalidDecl())
15359 CXXRecordDecl
*ClassDecl
= MoveAssignOperator
->getParent();
15360 if (ClassDecl
->isInvalidDecl()) {
15361 MoveAssignOperator
->setInvalidDecl();
15365 // C++0x [class.copy]p28:
15366 // The implicitly-defined or move assignment operator for a non-union class
15367 // X performs memberwise move assignment of its subobjects. The direct base
15368 // classes of X are assigned first, in the order of their declaration in the
15369 // base-specifier-list, and then the immediate non-static data members of X
15370 // are assigned, in the order in which they were declared in the class
15373 // Issue a warning if our implicit move assignment operator will move
15374 // from a virtual base more than once.
15375 checkMoveAssignmentForRepeatedMove(*this, ClassDecl
, CurrentLocation
);
15377 SynthesizedFunctionScope
Scope(*this, MoveAssignOperator
);
15379 // The exception specification is needed because we are defining the
15381 ResolveExceptionSpec(CurrentLocation
,
15382 MoveAssignOperator
->getType()->castAs
<FunctionProtoType
>());
15384 // Add a context note for diagnostics produced after this point.
15385 Scope
.addContextNote(CurrentLocation
);
15387 // The statements that form the synthesized function body.
15388 SmallVector
<Stmt
*, 8> Statements
;
15390 // The parameter for the "other" object, which we are move from.
15391 ParmVarDecl
*Other
= MoveAssignOperator
->getNonObjectParameter(0);
15392 QualType OtherRefType
=
15393 Other
->getType()->castAs
<RValueReferenceType
>()->getPointeeType();
15395 // Our location for everything implicitly-generated.
15396 SourceLocation Loc
= MoveAssignOperator
->getEndLoc().isValid()
15397 ? MoveAssignOperator
->getEndLoc()
15398 : MoveAssignOperator
->getLocation();
15400 // Builds a reference to the "other" object.
15401 RefBuilder
OtherRef(Other
, OtherRefType
);
15403 MoveCastBuilder
MoveOther(OtherRef
);
15405 // Builds the function object parameter.
15406 std::optional
<ThisBuilder
> This
;
15407 std::optional
<DerefBuilder
> DerefThis
;
15408 std::optional
<RefBuilder
> ExplicitObject
;
15409 QualType ObjectType
;
15410 if (MoveAssignOperator
->isExplicitObjectMemberFunction()) {
15411 ObjectType
= MoveAssignOperator
->getParamDecl(0)->getType();
15412 if (ObjectType
->isReferenceType())
15413 ObjectType
= ObjectType
->getPointeeType();
15414 ExplicitObject
.emplace(MoveAssignOperator
->getParamDecl(0), ObjectType
);
15416 ObjectType
= getCurrentThisType();
15418 DerefThis
.emplace(*This
);
15420 ExprBuilder
&ObjectParameter
=
15421 ExplicitObject
? *ExplicitObject
: static_cast<ExprBuilder
&>(*This
);
15423 // Assign base classes.
15424 bool Invalid
= false;
15425 for (auto &Base
: ClassDecl
->bases()) {
15426 // C++11 [class.copy]p28:
15427 // It is unspecified whether subobjects representing virtual base classes
15428 // are assigned more than once by the implicitly-defined copy assignment
15430 // FIXME: Do not assign to a vbase that will be assigned by some other base
15431 // class. For a move-assignment, this can result in the vbase being moved
15434 // Form the assignment:
15435 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
15436 QualType BaseType
= Base
.getType().getUnqualifiedType();
15437 if (!BaseType
->isRecordType()) {
15442 CXXCastPath BasePath
;
15443 BasePath
.push_back(&Base
);
15445 // Construct the "from" expression, which is an implicit cast to the
15446 // appropriately-qualified base type.
15447 CastBuilder
From(OtherRef
, BaseType
, VK_XValue
, BasePath
);
15449 // Implicitly cast "this" to the appropriately-qualified base type.
15450 // Dereference "this".
15452 ExplicitObject
? static_cast<ExprBuilder
&>(*ExplicitObject
)
15453 : static_cast<ExprBuilder
&>(*DerefThis
),
15454 Context
.getQualifiedType(BaseType
, ObjectType
.getQualifiers()),
15455 VK_LValue
, BasePath
);
15458 StmtResult Move
= buildSingleCopyAssign(*this, Loc
, BaseType
,
15460 /*CopyingBaseSubobject=*/true,
15461 /*Copying=*/false);
15462 if (Move
.isInvalid()) {
15463 MoveAssignOperator
->setInvalidDecl();
15467 // Success! Record the move.
15468 Statements
.push_back(Move
.getAs
<Expr
>());
15471 // Assign non-static members.
15472 for (auto *Field
: ClassDecl
->fields()) {
15473 // FIXME: We should form some kind of AST representation for the implied
15474 // memcpy in a union copy operation.
15475 if (Field
->isUnnamedBitfield() || Field
->getParent()->isUnion())
15478 if (Field
->isInvalidDecl()) {
15483 // Check for members of reference type; we can't move those.
15484 if (Field
->getType()->isReferenceType()) {
15485 Diag(ClassDecl
->getLocation(), diag::err_uninitialized_member_for_assign
)
15486 << Context
.getTagDeclType(ClassDecl
) << 0 << Field
->getDeclName();
15487 Diag(Field
->getLocation(), diag::note_declared_at
);
15492 // Check for members of const-qualified, non-class type.
15493 QualType BaseType
= Context
.getBaseElementType(Field
->getType());
15494 if (!BaseType
->getAs
<RecordType
>() && BaseType
.isConstQualified()) {
15495 Diag(ClassDecl
->getLocation(), diag::err_uninitialized_member_for_assign
)
15496 << Context
.getTagDeclType(ClassDecl
) << 1 << Field
->getDeclName();
15497 Diag(Field
->getLocation(), diag::note_declared_at
);
15502 // Suppress assigning zero-width bitfields.
15503 if (Field
->isZeroLengthBitField(Context
))
15506 QualType FieldType
= Field
->getType().getNonReferenceType();
15507 if (FieldType
->isIncompleteArrayType()) {
15508 assert(ClassDecl
->hasFlexibleArrayMember() &&
15509 "Incomplete array type is not valid");
15513 // Build references to the field in the object we're copying from and to.
15514 LookupResult
MemberLookup(*this, Field
->getDeclName(), Loc
,
15516 MemberLookup
.addDecl(Field
);
15517 MemberLookup
.resolveKind();
15518 MemberBuilder
From(MoveOther
, OtherRefType
,
15519 /*IsArrow=*/false, MemberLookup
);
15520 MemberBuilder
To(ObjectParameter
, ObjectType
, /*IsArrow=*/!ExplicitObject
,
15523 assert(!From
.build(*this, Loc
)->isLValue() && // could be xvalue or prvalue
15524 "Member reference with rvalue base must be rvalue except for reference "
15525 "members, which aren't allowed for move assignment.");
15527 // Build the move of this field.
15528 StmtResult Move
= buildSingleCopyAssign(*this, Loc
, FieldType
,
15530 /*CopyingBaseSubobject=*/false,
15531 /*Copying=*/false);
15532 if (Move
.isInvalid()) {
15533 MoveAssignOperator
->setInvalidDecl();
15537 // Success! Record the copy.
15538 Statements
.push_back(Move
.getAs
<Stmt
>());
15542 // Add a "return *this;"
15544 (ExplicitObject
? static_cast<ExprBuilder
&>(*ExplicitObject
)
15545 : static_cast<ExprBuilder
&>(*DerefThis
))
15546 .build(*this, Loc
);
15548 StmtResult Return
= BuildReturnStmt(Loc
, ThisExpr
);
15549 if (Return
.isInvalid())
15552 Statements
.push_back(Return
.getAs
<Stmt
>());
15556 MoveAssignOperator
->setInvalidDecl();
15562 CompoundScopeRAII
CompoundScope(*this);
15563 Body
= ActOnCompoundStmt(Loc
, Loc
, Statements
,
15564 /*isStmtExpr=*/false);
15565 assert(!Body
.isInvalid() && "Compound statement creation cannot fail");
15567 MoveAssignOperator
->setBody(Body
.getAs
<Stmt
>());
15568 MoveAssignOperator
->markUsed(Context
);
15570 if (ASTMutationListener
*L
= getASTMutationListener()) {
15571 L
->CompletedImplicitDefinition(MoveAssignOperator
);
15575 CXXConstructorDecl
*Sema::DeclareImplicitCopyConstructor(
15576 CXXRecordDecl
*ClassDecl
) {
15577 // C++ [class.copy]p4:
15578 // If the class definition does not explicitly declare a copy
15579 // constructor, one is declared implicitly.
15580 assert(ClassDecl
->needsImplicitCopyConstructor());
15582 DeclaringSpecialMember
DSM(*this, ClassDecl
, CXXCopyConstructor
);
15583 if (DSM
.isAlreadyBeingDeclared())
15586 QualType ClassType
= Context
.getTypeDeclType(ClassDecl
);
15587 QualType ArgType
= ClassType
;
15588 ArgType
= Context
.getElaboratedType(ElaboratedTypeKeyword::None
, nullptr,
15590 bool Const
= ClassDecl
->implicitCopyConstructorHasConstParam();
15592 ArgType
= ArgType
.withConst();
15594 LangAS AS
= getDefaultCXXMethodAddrSpace();
15595 if (AS
!= LangAS::Default
)
15596 ArgType
= Context
.getAddrSpaceQualType(ArgType
, AS
);
15598 ArgType
= Context
.getLValueReferenceType(ArgType
);
15600 bool Constexpr
= defaultedSpecialMemberIsConstexpr(*this, ClassDecl
,
15601 CXXCopyConstructor
,
15604 DeclarationName Name
15605 = Context
.DeclarationNames
.getCXXConstructorName(
15606 Context
.getCanonicalType(ClassType
));
15607 SourceLocation ClassLoc
= ClassDecl
->getLocation();
15608 DeclarationNameInfo
NameInfo(Name
, ClassLoc
);
15610 // An implicitly-declared copy constructor is an inline public
15611 // member of its class.
15612 CXXConstructorDecl
*CopyConstructor
= CXXConstructorDecl::Create(
15613 Context
, ClassDecl
, ClassLoc
, NameInfo
, QualType(), /*TInfo=*/nullptr,
15614 ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
15616 /*isImplicitlyDeclared=*/true,
15617 Constexpr
? ConstexprSpecKind::Constexpr
15618 : ConstexprSpecKind::Unspecified
);
15619 CopyConstructor
->setAccess(AS_public
);
15620 CopyConstructor
->setDefaulted();
15622 setupImplicitSpecialMemberType(CopyConstructor
, Context
.VoidTy
, ArgType
);
15624 if (getLangOpts().CUDA
)
15625 inferCUDATargetForImplicitSpecialMember(ClassDecl
, CXXCopyConstructor
,
15627 /* ConstRHS */ Const
,
15628 /* Diagnose */ false);
15630 // During template instantiation of special member functions we need a
15631 // reliable TypeSourceInfo for the parameter types in order to allow functions
15632 // to be substituted.
15633 TypeSourceInfo
*TSI
= nullptr;
15634 if (inTemplateInstantiation() && ClassDecl
->isLambda())
15635 TSI
= Context
.getTrivialTypeSourceInfo(ArgType
);
15637 // Add the parameter to the constructor.
15638 ParmVarDecl
*FromParam
=
15639 ParmVarDecl::Create(Context
, CopyConstructor
, ClassLoc
, ClassLoc
,
15640 /*IdentifierInfo=*/nullptr, ArgType
,
15641 /*TInfo=*/TSI
, SC_None
, nullptr);
15642 CopyConstructor
->setParams(FromParam
);
15644 CopyConstructor
->setTrivial(
15645 ClassDecl
->needsOverloadResolutionForCopyConstructor()
15646 ? SpecialMemberIsTrivial(CopyConstructor
, CXXCopyConstructor
)
15647 : ClassDecl
->hasTrivialCopyConstructor());
15649 CopyConstructor
->setTrivialForCall(
15650 ClassDecl
->hasAttr
<TrivialABIAttr
>() ||
15651 (ClassDecl
->needsOverloadResolutionForCopyConstructor()
15652 ? SpecialMemberIsTrivial(CopyConstructor
, CXXCopyConstructor
,
15653 TAH_ConsiderTrivialABI
)
15654 : ClassDecl
->hasTrivialCopyConstructorForCall()));
15656 // Note that we have declared this constructor.
15657 ++getASTContext().NumImplicitCopyConstructorsDeclared
;
15659 Scope
*S
= getScopeForContext(ClassDecl
);
15660 CheckImplicitSpecialMemberDeclaration(S
, CopyConstructor
);
15662 if (ShouldDeleteSpecialMember(CopyConstructor
, CXXCopyConstructor
)) {
15663 ClassDecl
->setImplicitCopyConstructorIsDeleted();
15664 SetDeclDeleted(CopyConstructor
, ClassLoc
);
15668 PushOnScopeChains(CopyConstructor
, S
, false);
15669 ClassDecl
->addDecl(CopyConstructor
);
15671 return CopyConstructor
;
15674 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation
,
15675 CXXConstructorDecl
*CopyConstructor
) {
15676 assert((CopyConstructor
->isDefaulted() &&
15677 CopyConstructor
->isCopyConstructor() &&
15678 !CopyConstructor
->doesThisDeclarationHaveABody() &&
15679 !CopyConstructor
->isDeleted()) &&
15680 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
15681 if (CopyConstructor
->willHaveBody() || CopyConstructor
->isInvalidDecl())
15684 CXXRecordDecl
*ClassDecl
= CopyConstructor
->getParent();
15685 assert(ClassDecl
&& "DefineImplicitCopyConstructor - invalid constructor");
15687 SynthesizedFunctionScope
Scope(*this, CopyConstructor
);
15689 // The exception specification is needed because we are defining the
15691 ResolveExceptionSpec(CurrentLocation
,
15692 CopyConstructor
->getType()->castAs
<FunctionProtoType
>());
15693 MarkVTableUsed(CurrentLocation
, ClassDecl
);
15695 // Add a context note for diagnostics produced after this point.
15696 Scope
.addContextNote(CurrentLocation
);
15698 // C++11 [class.copy]p7:
15699 // The [definition of an implicitly declared copy constructor] is
15700 // deprecated if the class has a user-declared copy assignment operator
15701 // or a user-declared destructor.
15702 if (getLangOpts().CPlusPlus11
&& CopyConstructor
->isImplicit())
15703 diagnoseDeprecatedCopyOperation(*this, CopyConstructor
);
15705 if (SetCtorInitializers(CopyConstructor
, /*AnyErrors=*/false)) {
15706 CopyConstructor
->setInvalidDecl();
15708 SourceLocation Loc
= CopyConstructor
->getEndLoc().isValid()
15709 ? CopyConstructor
->getEndLoc()
15710 : CopyConstructor
->getLocation();
15711 Sema::CompoundScopeRAII
CompoundScope(*this);
15712 CopyConstructor
->setBody(
15713 ActOnCompoundStmt(Loc
, Loc
, std::nullopt
, /*isStmtExpr=*/false)
15715 CopyConstructor
->markUsed(Context
);
15718 if (ASTMutationListener
*L
= getASTMutationListener()) {
15719 L
->CompletedImplicitDefinition(CopyConstructor
);
15723 CXXConstructorDecl
*Sema::DeclareImplicitMoveConstructor(
15724 CXXRecordDecl
*ClassDecl
) {
15725 assert(ClassDecl
->needsImplicitMoveConstructor());
15727 DeclaringSpecialMember
DSM(*this, ClassDecl
, CXXMoveConstructor
);
15728 if (DSM
.isAlreadyBeingDeclared())
15731 QualType ClassType
= Context
.getTypeDeclType(ClassDecl
);
15733 QualType ArgType
= ClassType
;
15734 ArgType
= Context
.getElaboratedType(ElaboratedTypeKeyword::None
, nullptr,
15736 LangAS AS
= getDefaultCXXMethodAddrSpace();
15737 if (AS
!= LangAS::Default
)
15738 ArgType
= Context
.getAddrSpaceQualType(ClassType
, AS
);
15739 ArgType
= Context
.getRValueReferenceType(ArgType
);
15741 bool Constexpr
= defaultedSpecialMemberIsConstexpr(*this, ClassDecl
,
15742 CXXMoveConstructor
,
15745 DeclarationName Name
15746 = Context
.DeclarationNames
.getCXXConstructorName(
15747 Context
.getCanonicalType(ClassType
));
15748 SourceLocation ClassLoc
= ClassDecl
->getLocation();
15749 DeclarationNameInfo
NameInfo(Name
, ClassLoc
);
15751 // C++11 [class.copy]p11:
15752 // An implicitly-declared copy/move constructor is an inline public
15753 // member of its class.
15754 CXXConstructorDecl
*MoveConstructor
= CXXConstructorDecl::Create(
15755 Context
, ClassDecl
, ClassLoc
, NameInfo
, QualType(), /*TInfo=*/nullptr,
15756 ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
15758 /*isImplicitlyDeclared=*/true,
15759 Constexpr
? ConstexprSpecKind::Constexpr
15760 : ConstexprSpecKind::Unspecified
);
15761 MoveConstructor
->setAccess(AS_public
);
15762 MoveConstructor
->setDefaulted();
15764 setupImplicitSpecialMemberType(MoveConstructor
, Context
.VoidTy
, ArgType
);
15766 if (getLangOpts().CUDA
)
15767 inferCUDATargetForImplicitSpecialMember(ClassDecl
, CXXMoveConstructor
,
15769 /* ConstRHS */ false,
15770 /* Diagnose */ false);
15772 // Add the parameter to the constructor.
15773 ParmVarDecl
*FromParam
= ParmVarDecl::Create(Context
, MoveConstructor
,
15774 ClassLoc
, ClassLoc
,
15775 /*IdentifierInfo=*/nullptr,
15776 ArgType
, /*TInfo=*/nullptr,
15778 MoveConstructor
->setParams(FromParam
);
15780 MoveConstructor
->setTrivial(
15781 ClassDecl
->needsOverloadResolutionForMoveConstructor()
15782 ? SpecialMemberIsTrivial(MoveConstructor
, CXXMoveConstructor
)
15783 : ClassDecl
->hasTrivialMoveConstructor());
15785 MoveConstructor
->setTrivialForCall(
15786 ClassDecl
->hasAttr
<TrivialABIAttr
>() ||
15787 (ClassDecl
->needsOverloadResolutionForMoveConstructor()
15788 ? SpecialMemberIsTrivial(MoveConstructor
, CXXMoveConstructor
,
15789 TAH_ConsiderTrivialABI
)
15790 : ClassDecl
->hasTrivialMoveConstructorForCall()));
15792 // Note that we have declared this constructor.
15793 ++getASTContext().NumImplicitMoveConstructorsDeclared
;
15795 Scope
*S
= getScopeForContext(ClassDecl
);
15796 CheckImplicitSpecialMemberDeclaration(S
, MoveConstructor
);
15798 if (ShouldDeleteSpecialMember(MoveConstructor
, CXXMoveConstructor
)) {
15799 ClassDecl
->setImplicitMoveConstructorIsDeleted();
15800 SetDeclDeleted(MoveConstructor
, ClassLoc
);
15804 PushOnScopeChains(MoveConstructor
, S
, false);
15805 ClassDecl
->addDecl(MoveConstructor
);
15807 return MoveConstructor
;
15810 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation
,
15811 CXXConstructorDecl
*MoveConstructor
) {
15812 assert((MoveConstructor
->isDefaulted() &&
15813 MoveConstructor
->isMoveConstructor() &&
15814 !MoveConstructor
->doesThisDeclarationHaveABody() &&
15815 !MoveConstructor
->isDeleted()) &&
15816 "DefineImplicitMoveConstructor - call it for implicit move ctor");
15817 if (MoveConstructor
->willHaveBody() || MoveConstructor
->isInvalidDecl())
15820 CXXRecordDecl
*ClassDecl
= MoveConstructor
->getParent();
15821 assert(ClassDecl
&& "DefineImplicitMoveConstructor - invalid constructor");
15823 SynthesizedFunctionScope
Scope(*this, MoveConstructor
);
15825 // The exception specification is needed because we are defining the
15827 ResolveExceptionSpec(CurrentLocation
,
15828 MoveConstructor
->getType()->castAs
<FunctionProtoType
>());
15829 MarkVTableUsed(CurrentLocation
, ClassDecl
);
15831 // Add a context note for diagnostics produced after this point.
15832 Scope
.addContextNote(CurrentLocation
);
15834 if (SetCtorInitializers(MoveConstructor
, /*AnyErrors=*/false)) {
15835 MoveConstructor
->setInvalidDecl();
15837 SourceLocation Loc
= MoveConstructor
->getEndLoc().isValid()
15838 ? MoveConstructor
->getEndLoc()
15839 : MoveConstructor
->getLocation();
15840 Sema::CompoundScopeRAII
CompoundScope(*this);
15841 MoveConstructor
->setBody(
15842 ActOnCompoundStmt(Loc
, Loc
, std::nullopt
, /*isStmtExpr=*/false)
15844 MoveConstructor
->markUsed(Context
);
15847 if (ASTMutationListener
*L
= getASTMutationListener()) {
15848 L
->CompletedImplicitDefinition(MoveConstructor
);
15852 bool Sema::isImplicitlyDeleted(FunctionDecl
*FD
) {
15853 return FD
->isDeleted() && FD
->isDefaulted() && isa
<CXXMethodDecl
>(FD
);
15856 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
15857 SourceLocation CurrentLocation
,
15858 CXXConversionDecl
*Conv
) {
15859 SynthesizedFunctionScope
Scope(*this, Conv
);
15860 assert(!Conv
->getReturnType()->isUndeducedType());
15862 QualType ConvRT
= Conv
->getType()->castAs
<FunctionType
>()->getReturnType();
15864 ConvRT
->getPointeeType()->castAs
<FunctionType
>()->getCallConv();
15866 CXXRecordDecl
*Lambda
= Conv
->getParent();
15867 FunctionDecl
*CallOp
= Lambda
->getLambdaCallOperator();
15868 FunctionDecl
*Invoker
=
15869 CallOp
->hasCXXExplicitFunctionObjectParameter() || CallOp
->isStatic()
15871 : Lambda
->getLambdaStaticInvoker(CC
);
15873 if (auto *TemplateArgs
= Conv
->getTemplateSpecializationArgs()) {
15874 CallOp
= InstantiateFunctionDeclaration(
15875 CallOp
->getDescribedFunctionTemplate(), TemplateArgs
, CurrentLocation
);
15879 if (CallOp
!= Invoker
) {
15880 Invoker
= InstantiateFunctionDeclaration(
15881 Invoker
->getDescribedFunctionTemplate(), TemplateArgs
,
15888 if (CallOp
->isInvalidDecl())
15891 // Mark the call operator referenced (and add to pending instantiations
15893 // For both the conversion and static-invoker template specializations
15894 // we construct their body's in this function, so no need to add them
15895 // to the PendingInstantiations.
15896 MarkFunctionReferenced(CurrentLocation
, CallOp
);
15898 if (Invoker
!= CallOp
) {
15899 // Fill in the __invoke function with a dummy implementation. IR generation
15900 // will fill in the actual details. Update its type in case it contained
15902 Invoker
->markUsed(Context
);
15903 Invoker
->setReferenced();
15904 Invoker
->setType(Conv
->getReturnType()->getPointeeType());
15905 Invoker
->setBody(new (Context
) CompoundStmt(Conv
->getLocation()));
15908 // Construct the body of the conversion function { return __invoke; }.
15909 Expr
*FunctionRef
= BuildDeclRefExpr(Invoker
, Invoker
->getType(), VK_LValue
,
15910 Conv
->getLocation());
15911 assert(FunctionRef
&& "Can't refer to __invoke function?");
15912 Stmt
*Return
= BuildReturnStmt(Conv
->getLocation(), FunctionRef
).get();
15913 Conv
->setBody(CompoundStmt::Create(Context
, Return
, FPOptionsOverride(),
15914 Conv
->getLocation(), Conv
->getLocation()));
15915 Conv
->markUsed(Context
);
15916 Conv
->setReferenced();
15918 if (ASTMutationListener
*L
= getASTMutationListener()) {
15919 L
->CompletedImplicitDefinition(Conv
);
15920 if (Invoker
!= CallOp
)
15921 L
->CompletedImplicitDefinition(Invoker
);
15925 void Sema::DefineImplicitLambdaToBlockPointerConversion(
15926 SourceLocation CurrentLocation
, CXXConversionDecl
*Conv
) {
15927 assert(!Conv
->getParent()->isGenericLambda());
15929 SynthesizedFunctionScope
Scope(*this, Conv
);
15931 // Copy-initialize the lambda object as needed to capture it.
15932 Expr
*This
= ActOnCXXThis(CurrentLocation
).get();
15933 Expr
*DerefThis
=CreateBuiltinUnaryOp(CurrentLocation
, UO_Deref
, This
).get();
15935 ExprResult BuildBlock
= BuildBlockForLambdaConversion(CurrentLocation
,
15936 Conv
->getLocation(),
15939 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
15940 // behavior. Note that only the general conversion function does this
15941 // (since it's unusable otherwise); in the case where we inline the
15942 // block literal, it has block literal lifetime semantics.
15943 if (!BuildBlock
.isInvalid() && !getLangOpts().ObjCAutoRefCount
)
15944 BuildBlock
= ImplicitCastExpr::Create(
15945 Context
, BuildBlock
.get()->getType(), CK_CopyAndAutoreleaseBlockObject
,
15946 BuildBlock
.get(), nullptr, VK_PRValue
, FPOptionsOverride());
15948 if (BuildBlock
.isInvalid()) {
15949 Diag(CurrentLocation
, diag::note_lambda_to_block_conv
);
15950 Conv
->setInvalidDecl();
15954 // Create the return statement that returns the block from the conversion
15956 StmtResult Return
= BuildReturnStmt(Conv
->getLocation(), BuildBlock
.get());
15957 if (Return
.isInvalid()) {
15958 Diag(CurrentLocation
, diag::note_lambda_to_block_conv
);
15959 Conv
->setInvalidDecl();
15963 // Set the body of the conversion function.
15964 Stmt
*ReturnS
= Return
.get();
15965 Conv
->setBody(CompoundStmt::Create(Context
, ReturnS
, FPOptionsOverride(),
15966 Conv
->getLocation(), Conv
->getLocation()));
15967 Conv
->markUsed(Context
);
15969 // We're done; notify the mutation listener, if any.
15970 if (ASTMutationListener
*L
= getASTMutationListener()) {
15971 L
->CompletedImplicitDefinition(Conv
);
15975 /// Determine whether the given list arguments contains exactly one
15976 /// "real" (non-default) argument.
15977 static bool hasOneRealArgument(MultiExprArg Args
) {
15978 switch (Args
.size()) {
15983 if (!Args
[1]->isDefaultArgument())
15988 return !Args
[0]->isDefaultArgument();
15995 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc
, QualType DeclInitType
,
15996 NamedDecl
*FoundDecl
,
15997 CXXConstructorDecl
*Constructor
,
15998 MultiExprArg ExprArgs
,
15999 bool HadMultipleCandidates
,
16000 bool IsListInitialization
,
16001 bool IsStdInitListInitialization
,
16002 bool RequiresZeroInit
,
16003 unsigned ConstructKind
,
16004 SourceRange ParenRange
) {
16005 bool Elidable
= false;
16007 // C++0x [class.copy]p34:
16008 // When certain criteria are met, an implementation is allowed to
16009 // omit the copy/move construction of a class object, even if the
16010 // copy/move constructor and/or destructor for the object have
16011 // side effects. [...]
16012 // - when a temporary class object that has not been bound to a
16013 // reference (12.2) would be copied/moved to a class object
16014 // with the same cv-unqualified type, the copy/move operation
16015 // can be omitted by constructing the temporary object
16016 // directly into the target of the omitted copy/move
16017 if (ConstructKind
== CXXConstructExpr::CK_Complete
&& Constructor
&&
16018 // FIXME: Converting constructors should also be accepted.
16019 // But to fix this, the logic that digs down into a CXXConstructExpr
16020 // to find the source object needs to handle it.
16021 // Right now it assumes the source object is passed directly as the
16023 Constructor
->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs
)) {
16024 Expr
*SubExpr
= ExprArgs
[0];
16025 // FIXME: Per above, this is also incorrect if we want to accept
16026 // converting constructors, as isTemporaryObject will
16027 // reject temporaries with different type from the
16028 // CXXRecord itself.
16029 Elidable
= SubExpr
->isTemporaryObject(
16030 Context
, cast
<CXXRecordDecl
>(FoundDecl
->getDeclContext()));
16033 return BuildCXXConstructExpr(ConstructLoc
, DeclInitType
,
16034 FoundDecl
, Constructor
,
16035 Elidable
, ExprArgs
, HadMultipleCandidates
,
16036 IsListInitialization
,
16037 IsStdInitListInitialization
, RequiresZeroInit
,
16038 ConstructKind
, ParenRange
);
16042 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc
, QualType DeclInitType
,
16043 NamedDecl
*FoundDecl
,
16044 CXXConstructorDecl
*Constructor
,
16046 MultiExprArg ExprArgs
,
16047 bool HadMultipleCandidates
,
16048 bool IsListInitialization
,
16049 bool IsStdInitListInitialization
,
16050 bool RequiresZeroInit
,
16051 unsigned ConstructKind
,
16052 SourceRange ParenRange
) {
16053 if (auto *Shadow
= dyn_cast
<ConstructorUsingShadowDecl
>(FoundDecl
)) {
16054 Constructor
= findInheritingConstructor(ConstructLoc
, Constructor
, Shadow
);
16055 // The only way to get here is if we did overlaod resolution to find the
16056 // shadow decl, so we don't need to worry about re-checking the trailing
16057 // requires clause.
16058 if (DiagnoseUseOfOverloadedDecl(Constructor
, ConstructLoc
))
16059 return ExprError();
16062 return BuildCXXConstructExpr(
16063 ConstructLoc
, DeclInitType
, Constructor
, Elidable
, ExprArgs
,
16064 HadMultipleCandidates
, IsListInitialization
, IsStdInitListInitialization
,
16065 RequiresZeroInit
, ConstructKind
, ParenRange
);
16068 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
16069 /// including handling of its default argument expressions.
16071 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc
, QualType DeclInitType
,
16072 CXXConstructorDecl
*Constructor
,
16074 MultiExprArg ExprArgs
,
16075 bool HadMultipleCandidates
,
16076 bool IsListInitialization
,
16077 bool IsStdInitListInitialization
,
16078 bool RequiresZeroInit
,
16079 unsigned ConstructKind
,
16080 SourceRange ParenRange
) {
16081 assert(declaresSameEntity(
16082 Constructor
->getParent(),
16083 DeclInitType
->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
16084 "given constructor for wrong type");
16085 MarkFunctionReferenced(ConstructLoc
, Constructor
);
16086 if (getLangOpts().CUDA
&& !CheckCUDACall(ConstructLoc
, Constructor
))
16087 return ExprError();
16089 return CheckForImmediateInvocation(
16090 CXXConstructExpr::Create(
16091 Context
, DeclInitType
, ConstructLoc
, Constructor
, Elidable
, ExprArgs
,
16092 HadMultipleCandidates
, IsListInitialization
,
16093 IsStdInitListInitialization
, RequiresZeroInit
,
16094 static_cast<CXXConstructExpr::ConstructionKind
>(ConstructKind
),
16099 void Sema::FinalizeVarWithDestructor(VarDecl
*VD
, const RecordType
*Record
) {
16100 if (VD
->isInvalidDecl()) return;
16101 // If initializing the variable failed, don't also diagnose problems with
16102 // the destructor, they're likely related.
16103 if (VD
->getInit() && VD
->getInit()->containsErrors())
16106 CXXRecordDecl
*ClassDecl
= cast
<CXXRecordDecl
>(Record
->getDecl());
16107 if (ClassDecl
->isInvalidDecl()) return;
16108 if (ClassDecl
->hasIrrelevantDestructor()) return;
16109 if (ClassDecl
->isDependentContext()) return;
16111 if (VD
->isNoDestroy(getASTContext()))
16114 CXXDestructorDecl
*Destructor
= LookupDestructor(ClassDecl
);
16115 // The result of `LookupDestructor` might be nullptr if the destructor is
16116 // invalid, in which case it is marked as `IneligibleOrNotSelected` and
16117 // will not be selected by `CXXRecordDecl::getDestructor()`.
16120 // If this is an array, we'll require the destructor during initialization, so
16121 // we can skip over this. We still want to emit exit-time destructor warnings
16123 if (!VD
->getType()->isArrayType()) {
16124 MarkFunctionReferenced(VD
->getLocation(), Destructor
);
16125 CheckDestructorAccess(VD
->getLocation(), Destructor
,
16126 PDiag(diag::err_access_dtor_var
)
16127 << VD
->getDeclName() << VD
->getType());
16128 DiagnoseUseOfDecl(Destructor
, VD
->getLocation());
16131 if (Destructor
->isTrivial()) return;
16133 // If the destructor is constexpr, check whether the variable has constant
16134 // destruction now.
16135 if (Destructor
->isConstexpr()) {
16136 bool HasConstantInit
= false;
16137 if (VD
->getInit() && !VD
->getInit()->isValueDependent())
16138 HasConstantInit
= VD
->evaluateValue();
16139 SmallVector
<PartialDiagnosticAt
, 8> Notes
;
16140 if (!VD
->evaluateDestruction(Notes
) && VD
->isConstexpr() &&
16142 Diag(VD
->getLocation(),
16143 diag::err_constexpr_var_requires_const_destruction
) << VD
;
16144 for (unsigned I
= 0, N
= Notes
.size(); I
!= N
; ++I
)
16145 Diag(Notes
[I
].first
, Notes
[I
].second
);
16149 if (!VD
->hasGlobalStorage() || !VD
->needsDestruction(Context
))
16152 // Emit warning for non-trivial dtor in global scope (a real global,
16153 // class-static, function-static).
16154 Diag(VD
->getLocation(), diag::warn_exit_time_destructor
);
16156 // TODO: this should be re-enabled for static locals by !CXAAtExit
16157 if (!VD
->isStaticLocal())
16158 Diag(VD
->getLocation(), diag::warn_global_destructor
);
16161 /// Given a constructor and the set of arguments provided for the
16162 /// constructor, convert the arguments and add any required default arguments
16163 /// to form a proper call to this constructor.
16165 /// \returns true if an error occurred, false otherwise.
16166 bool Sema::CompleteConstructorCall(CXXConstructorDecl
*Constructor
,
16167 QualType DeclInitType
, MultiExprArg ArgsPtr
,
16168 SourceLocation Loc
,
16169 SmallVectorImpl
<Expr
*> &ConvertedArgs
,
16170 bool AllowExplicit
,
16171 bool IsListInitialization
) {
16172 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
16173 unsigned NumArgs
= ArgsPtr
.size();
16174 Expr
**Args
= ArgsPtr
.data();
16176 const auto *Proto
= Constructor
->getType()->castAs
<FunctionProtoType
>();
16177 unsigned NumParams
= Proto
->getNumParams();
16179 // If too few arguments are available, we'll fill in the rest with defaults.
16180 if (NumArgs
< NumParams
)
16181 ConvertedArgs
.reserve(NumParams
);
16183 ConvertedArgs
.reserve(NumArgs
);
16185 VariadicCallType CallType
=
16186 Proto
->isVariadic() ? VariadicConstructor
: VariadicDoesNotApply
;
16187 SmallVector
<Expr
*, 8> AllArgs
;
16188 bool Invalid
= GatherArgumentsForCall(
16189 Loc
, Constructor
, Proto
, 0, llvm::ArrayRef(Args
, NumArgs
), AllArgs
,
16190 CallType
, AllowExplicit
, IsListInitialization
);
16191 ConvertedArgs
.append(AllArgs
.begin(), AllArgs
.end());
16193 DiagnoseSentinelCalls(Constructor
, Loc
, AllArgs
);
16195 CheckConstructorCall(Constructor
, DeclInitType
,
16196 llvm::ArrayRef(AllArgs
.data(), AllArgs
.size()), Proto
,
16203 CheckOperatorNewDeleteDeclarationScope(Sema
&SemaRef
,
16204 const FunctionDecl
*FnDecl
) {
16205 const DeclContext
*DC
= FnDecl
->getDeclContext()->getRedeclContext();
16206 if (isa
<NamespaceDecl
>(DC
)) {
16207 return SemaRef
.Diag(FnDecl
->getLocation(),
16208 diag::err_operator_new_delete_declared_in_namespace
)
16209 << FnDecl
->getDeclName();
16212 if (isa
<TranslationUnitDecl
>(DC
) &&
16213 FnDecl
->getStorageClass() == SC_Static
) {
16214 return SemaRef
.Diag(FnDecl
->getLocation(),
16215 diag::err_operator_new_delete_declared_static
)
16216 << FnDecl
->getDeclName();
16222 static CanQualType
RemoveAddressSpaceFromPtr(Sema
&SemaRef
,
16223 const PointerType
*PtrTy
) {
16224 auto &Ctx
= SemaRef
.Context
;
16225 Qualifiers PtrQuals
= PtrTy
->getPointeeType().getQualifiers();
16226 PtrQuals
.removeAddressSpace();
16227 return Ctx
.getPointerType(Ctx
.getCanonicalType(Ctx
.getQualifiedType(
16228 PtrTy
->getPointeeType().getUnqualifiedType(), PtrQuals
)));
16232 CheckOperatorNewDeleteTypes(Sema
&SemaRef
, const FunctionDecl
*FnDecl
,
16233 CanQualType ExpectedResultType
,
16234 CanQualType ExpectedFirstParamType
,
16235 unsigned DependentParamTypeDiag
,
16236 unsigned InvalidParamTypeDiag
) {
16237 QualType ResultType
=
16238 FnDecl
->getType()->castAs
<FunctionType
>()->getReturnType();
16240 if (SemaRef
.getLangOpts().OpenCLCPlusPlus
) {
16241 // The operator is valid on any address space for OpenCL.
16242 // Drop address space from actual and expected result types.
16243 if (const auto *PtrTy
= ResultType
->getAs
<PointerType
>())
16244 ResultType
= RemoveAddressSpaceFromPtr(SemaRef
, PtrTy
);
16246 if (auto ExpectedPtrTy
= ExpectedResultType
->getAs
<PointerType
>())
16247 ExpectedResultType
= RemoveAddressSpaceFromPtr(SemaRef
, ExpectedPtrTy
);
16250 // Check that the result type is what we expect.
16251 if (SemaRef
.Context
.getCanonicalType(ResultType
) != ExpectedResultType
) {
16252 // Reject even if the type is dependent; an operator delete function is
16253 // required to have a non-dependent result type.
16254 return SemaRef
.Diag(
16255 FnDecl
->getLocation(),
16256 ResultType
->isDependentType()
16257 ? diag::err_operator_new_delete_dependent_result_type
16258 : diag::err_operator_new_delete_invalid_result_type
)
16259 << FnDecl
->getDeclName() << ExpectedResultType
;
16262 // A function template must have at least 2 parameters.
16263 if (FnDecl
->getDescribedFunctionTemplate() && FnDecl
->getNumParams() < 2)
16264 return SemaRef
.Diag(FnDecl
->getLocation(),
16265 diag::err_operator_new_delete_template_too_few_parameters
)
16266 << FnDecl
->getDeclName();
16268 // The function decl must have at least 1 parameter.
16269 if (FnDecl
->getNumParams() == 0)
16270 return SemaRef
.Diag(FnDecl
->getLocation(),
16271 diag::err_operator_new_delete_too_few_parameters
)
16272 << FnDecl
->getDeclName();
16274 QualType FirstParamType
= FnDecl
->getParamDecl(0)->getType();
16275 if (SemaRef
.getLangOpts().OpenCLCPlusPlus
) {
16276 // The operator is valid on any address space for OpenCL.
16277 // Drop address space from actual and expected first parameter types.
16278 if (const auto *PtrTy
=
16279 FnDecl
->getParamDecl(0)->getType()->getAs
<PointerType
>())
16280 FirstParamType
= RemoveAddressSpaceFromPtr(SemaRef
, PtrTy
);
16282 if (auto ExpectedPtrTy
= ExpectedFirstParamType
->getAs
<PointerType
>())
16283 ExpectedFirstParamType
=
16284 RemoveAddressSpaceFromPtr(SemaRef
, ExpectedPtrTy
);
16287 // Check that the first parameter type is what we expect.
16288 if (SemaRef
.Context
.getCanonicalType(FirstParamType
).getUnqualifiedType() !=
16289 ExpectedFirstParamType
) {
16290 // The first parameter type is not allowed to be dependent. As a tentative
16291 // DR resolution, we allow a dependent parameter type if it is the right
16292 // type anyway, to allow destroying operator delete in class templates.
16293 return SemaRef
.Diag(FnDecl
->getLocation(), FirstParamType
->isDependentType()
16294 ? DependentParamTypeDiag
16295 : InvalidParamTypeDiag
)
16296 << FnDecl
->getDeclName() << ExpectedFirstParamType
;
16303 CheckOperatorNewDeclaration(Sema
&SemaRef
, const FunctionDecl
*FnDecl
) {
16304 // C++ [basic.stc.dynamic.allocation]p1:
16305 // A program is ill-formed if an allocation function is declared in a
16306 // namespace scope other than global scope or declared static in global
16308 if (CheckOperatorNewDeleteDeclarationScope(SemaRef
, FnDecl
))
16311 CanQualType SizeTy
=
16312 SemaRef
.Context
.getCanonicalType(SemaRef
.Context
.getSizeType());
16314 // C++ [basic.stc.dynamic.allocation]p1:
16315 // The return type shall be void*. The first parameter shall have type
16317 if (CheckOperatorNewDeleteTypes(SemaRef
, FnDecl
, SemaRef
.Context
.VoidPtrTy
,
16319 diag::err_operator_new_dependent_param_type
,
16320 diag::err_operator_new_param_type
))
16323 // C++ [basic.stc.dynamic.allocation]p1:
16324 // The first parameter shall not have an associated default argument.
16325 if (FnDecl
->getParamDecl(0)->hasDefaultArg())
16326 return SemaRef
.Diag(FnDecl
->getLocation(),
16327 diag::err_operator_new_default_arg
)
16328 << FnDecl
->getDeclName() << FnDecl
->getParamDecl(0)->getDefaultArgRange();
16334 CheckOperatorDeleteDeclaration(Sema
&SemaRef
, FunctionDecl
*FnDecl
) {
16335 // C++ [basic.stc.dynamic.deallocation]p1:
16336 // A program is ill-formed if deallocation functions are declared in a
16337 // namespace scope other than global scope or declared static in global
16339 if (CheckOperatorNewDeleteDeclarationScope(SemaRef
, FnDecl
))
16342 auto *MD
= dyn_cast
<CXXMethodDecl
>(FnDecl
);
16345 // Within a class C, the first parameter of a destroying operator delete
16346 // shall be of type C *. The first parameter of any other deallocation
16347 // function shall be of type void *.
16348 CanQualType ExpectedFirstParamType
=
16349 MD
&& MD
->isDestroyingOperatorDelete()
16350 ? SemaRef
.Context
.getCanonicalType(SemaRef
.Context
.getPointerType(
16351 SemaRef
.Context
.getRecordType(MD
->getParent())))
16352 : SemaRef
.Context
.VoidPtrTy
;
16354 // C++ [basic.stc.dynamic.deallocation]p2:
16355 // Each deallocation function shall return void
16356 if (CheckOperatorNewDeleteTypes(
16357 SemaRef
, FnDecl
, SemaRef
.Context
.VoidTy
, ExpectedFirstParamType
,
16358 diag::err_operator_delete_dependent_param_type
,
16359 diag::err_operator_delete_param_type
))
16363 // A destroying operator delete shall be a usual deallocation function.
16364 if (MD
&& !MD
->getParent()->isDependentContext() &&
16365 MD
->isDestroyingOperatorDelete() &&
16366 !SemaRef
.isUsualDeallocationFunction(MD
)) {
16367 SemaRef
.Diag(MD
->getLocation(),
16368 diag::err_destroying_operator_delete_not_usual
);
16375 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
16376 /// of this overloaded operator is well-formed. If so, returns false;
16377 /// otherwise, emits appropriate diagnostics and returns true.
16378 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl
*FnDecl
) {
16379 assert(FnDecl
&& FnDecl
->isOverloadedOperator() &&
16380 "Expected an overloaded operator declaration");
16382 OverloadedOperatorKind Op
= FnDecl
->getOverloadedOperator();
16384 // C++ [over.oper]p5:
16385 // The allocation and deallocation functions, operator new,
16386 // operator new[], operator delete and operator delete[], are
16387 // described completely in 3.7.3. The attributes and restrictions
16388 // found in the rest of this subclause do not apply to them unless
16389 // explicitly stated in 3.7.3.
16390 if (Op
== OO_Delete
|| Op
== OO_Array_Delete
)
16391 return CheckOperatorDeleteDeclaration(*this, FnDecl
);
16393 if (Op
== OO_New
|| Op
== OO_Array_New
)
16394 return CheckOperatorNewDeclaration(*this, FnDecl
);
16396 // C++ [over.oper]p7:
16397 // An operator function shall either be a member function or
16398 // be a non-member function and have at least one parameter
16399 // whose type is a class, a reference to a class, an enumeration,
16400 // or a reference to an enumeration.
16401 // Note: Before C++23, a member function could not be static. The only member
16402 // function allowed to be static is the call operator function.
16403 if (CXXMethodDecl
*MethodDecl
= dyn_cast
<CXXMethodDecl
>(FnDecl
)) {
16404 if (MethodDecl
->isStatic()) {
16405 if (Op
== OO_Call
|| Op
== OO_Subscript
)
16406 Diag(FnDecl
->getLocation(),
16407 (LangOpts
.CPlusPlus23
16408 ? diag::warn_cxx20_compat_operator_overload_static
16409 : diag::ext_operator_overload_static
))
16412 return Diag(FnDecl
->getLocation(), diag::err_operator_overload_static
)
16416 bool ClassOrEnumParam
= false;
16417 for (auto *Param
: FnDecl
->parameters()) {
16418 QualType ParamType
= Param
->getType().getNonReferenceType();
16419 if (ParamType
->isDependentType() || ParamType
->isRecordType() ||
16420 ParamType
->isEnumeralType()) {
16421 ClassOrEnumParam
= true;
16426 if (!ClassOrEnumParam
)
16427 return Diag(FnDecl
->getLocation(),
16428 diag::err_operator_overload_needs_class_or_enum
)
16429 << FnDecl
->getDeclName();
16432 // C++ [over.oper]p8:
16433 // An operator function cannot have default arguments (8.3.6),
16434 // except where explicitly stated below.
16436 // Only the function-call operator (C++ [over.call]p1) and the subscript
16437 // operator (CWG2507) allow default arguments.
16438 if (Op
!= OO_Call
) {
16439 ParmVarDecl
*FirstDefaultedParam
= nullptr;
16440 for (auto *Param
: FnDecl
->parameters()) {
16441 if (Param
->hasDefaultArg()) {
16442 FirstDefaultedParam
= Param
;
16446 if (FirstDefaultedParam
) {
16447 if (Op
== OO_Subscript
) {
16448 Diag(FnDecl
->getLocation(), LangOpts
.CPlusPlus23
16449 ? diag::ext_subscript_overload
16450 : diag::error_subscript_overload
)
16451 << FnDecl
->getDeclName() << 1
16452 << FirstDefaultedParam
->getDefaultArgRange();
16454 return Diag(FirstDefaultedParam
->getLocation(),
16455 diag::err_operator_overload_default_arg
)
16456 << FnDecl
->getDeclName()
16457 << FirstDefaultedParam
->getDefaultArgRange();
16462 static const bool OperatorUses
[NUM_OVERLOADED_OPERATORS
][3] = {
16463 { false, false, false }
16464 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
16465 , { Unary, Binary, MemberOnly }
16466 #include "clang/Basic/OperatorKinds.def"
16469 bool CanBeUnaryOperator
= OperatorUses
[Op
][0];
16470 bool CanBeBinaryOperator
= OperatorUses
[Op
][1];
16471 bool MustBeMemberOperator
= OperatorUses
[Op
][2];
16473 // C++ [over.oper]p8:
16474 // [...] Operator functions cannot have more or fewer parameters
16475 // than the number required for the corresponding operator, as
16476 // described in the rest of this subclause.
16477 unsigned NumParams
= FnDecl
->getNumParams() +
16478 (isa
<CXXMethodDecl
>(FnDecl
) &&
16479 !FnDecl
->hasCXXExplicitFunctionObjectParameter()
16482 if (Op
!= OO_Call
&& Op
!= OO_Subscript
&&
16483 ((NumParams
== 1 && !CanBeUnaryOperator
) ||
16484 (NumParams
== 2 && !CanBeBinaryOperator
) || (NumParams
< 1) ||
16485 (NumParams
> 2))) {
16486 // We have the wrong number of parameters.
16487 unsigned ErrorKind
;
16488 if (CanBeUnaryOperator
&& CanBeBinaryOperator
) {
16489 ErrorKind
= 2; // 2 -> unary or binary.
16490 } else if (CanBeUnaryOperator
) {
16491 ErrorKind
= 0; // 0 -> unary
16493 assert(CanBeBinaryOperator
&&
16494 "All non-call overloaded operators are unary or binary!");
16495 ErrorKind
= 1; // 1 -> binary
16497 return Diag(FnDecl
->getLocation(), diag::err_operator_overload_must_be
)
16498 << FnDecl
->getDeclName() << NumParams
<< ErrorKind
;
16501 if (Op
== OO_Subscript
&& NumParams
!= 2) {
16502 Diag(FnDecl
->getLocation(), LangOpts
.CPlusPlus23
16503 ? diag::ext_subscript_overload
16504 : diag::error_subscript_overload
)
16505 << FnDecl
->getDeclName() << (NumParams
== 1 ? 0 : 2);
16508 // Overloaded operators other than operator() and operator[] cannot be
16510 if (Op
!= OO_Call
&&
16511 FnDecl
->getType()->castAs
<FunctionProtoType
>()->isVariadic()) {
16512 return Diag(FnDecl
->getLocation(), diag::err_operator_overload_variadic
)
16513 << FnDecl
->getDeclName();
16516 // Some operators must be member functions.
16517 if (MustBeMemberOperator
&& !isa
<CXXMethodDecl
>(FnDecl
)) {
16518 return Diag(FnDecl
->getLocation(),
16519 diag::err_operator_overload_must_be_member
)
16520 << FnDecl
->getDeclName();
16523 // C++ [over.inc]p1:
16524 // The user-defined function called operator++ implements the
16525 // prefix and postfix ++ operator. If this function is a member
16526 // function with no parameters, or a non-member function with one
16527 // parameter of class or enumeration type, it defines the prefix
16528 // increment operator ++ for objects of that type. If the function
16529 // is a member function with one parameter (which shall be of type
16530 // int) or a non-member function with two parameters (the second
16531 // of which shall be of type int), it defines the postfix
16532 // increment operator ++ for objects of that type.
16533 if ((Op
== OO_PlusPlus
|| Op
== OO_MinusMinus
) && NumParams
== 2) {
16534 ParmVarDecl
*LastParam
= FnDecl
->getParamDecl(FnDecl
->getNumParams() - 1);
16535 QualType ParamType
= LastParam
->getType();
16537 if (!ParamType
->isSpecificBuiltinType(BuiltinType::Int
) &&
16538 !ParamType
->isDependentType())
16539 return Diag(LastParam
->getLocation(),
16540 diag::err_operator_overload_post_incdec_must_be_int
)
16541 << LastParam
->getType() << (Op
== OO_MinusMinus
);
16548 checkLiteralOperatorTemplateParameterList(Sema
&SemaRef
,
16549 FunctionTemplateDecl
*TpDecl
) {
16550 TemplateParameterList
*TemplateParams
= TpDecl
->getTemplateParameters();
16552 // Must have one or two template parameters.
16553 if (TemplateParams
->size() == 1) {
16554 NonTypeTemplateParmDecl
*PmDecl
=
16555 dyn_cast
<NonTypeTemplateParmDecl
>(TemplateParams
->getParam(0));
16557 // The template parameter must be a char parameter pack.
16558 if (PmDecl
&& PmDecl
->isTemplateParameterPack() &&
16559 SemaRef
.Context
.hasSameType(PmDecl
->getType(), SemaRef
.Context
.CharTy
))
16562 // C++20 [over.literal]p5:
16563 // A string literal operator template is a literal operator template
16564 // whose template-parameter-list comprises a single non-type
16565 // template-parameter of class type.
16567 // As a DR resolution, we also allow placeholders for deduced class
16568 // template specializations.
16569 if (SemaRef
.getLangOpts().CPlusPlus20
&& PmDecl
&&
16570 !PmDecl
->isTemplateParameterPack() &&
16571 (PmDecl
->getType()->isRecordType() ||
16572 PmDecl
->getType()->getAs
<DeducedTemplateSpecializationType
>()))
16574 } else if (TemplateParams
->size() == 2) {
16575 TemplateTypeParmDecl
*PmType
=
16576 dyn_cast
<TemplateTypeParmDecl
>(TemplateParams
->getParam(0));
16577 NonTypeTemplateParmDecl
*PmArgs
=
16578 dyn_cast
<NonTypeTemplateParmDecl
>(TemplateParams
->getParam(1));
16580 // The second template parameter must be a parameter pack with the
16581 // first template parameter as its type.
16582 if (PmType
&& PmArgs
&& !PmType
->isTemplateParameterPack() &&
16583 PmArgs
->isTemplateParameterPack()) {
16584 const TemplateTypeParmType
*TArgs
=
16585 PmArgs
->getType()->getAs
<TemplateTypeParmType
>();
16586 if (TArgs
&& TArgs
->getDepth() == PmType
->getDepth() &&
16587 TArgs
->getIndex() == PmType
->getIndex()) {
16588 if (!SemaRef
.inTemplateInstantiation())
16589 SemaRef
.Diag(TpDecl
->getLocation(),
16590 diag::ext_string_literal_operator_template
);
16596 SemaRef
.Diag(TpDecl
->getTemplateParameters()->getSourceRange().getBegin(),
16597 diag::err_literal_operator_template
)
16598 << TpDecl
->getTemplateParameters()->getSourceRange();
16602 /// CheckLiteralOperatorDeclaration - Check whether the declaration
16603 /// of this literal operator function is well-formed. If so, returns
16604 /// false; otherwise, emits appropriate diagnostics and returns true.
16605 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl
*FnDecl
) {
16606 if (isa
<CXXMethodDecl
>(FnDecl
)) {
16607 Diag(FnDecl
->getLocation(), diag::err_literal_operator_outside_namespace
)
16608 << FnDecl
->getDeclName();
16612 if (FnDecl
->isExternC()) {
16613 Diag(FnDecl
->getLocation(), diag::err_literal_operator_extern_c
);
16614 if (const LinkageSpecDecl
*LSD
=
16615 FnDecl
->getDeclContext()->getExternCContext())
16616 Diag(LSD
->getExternLoc(), diag::note_extern_c_begins_here
);
16620 // This might be the definition of a literal operator template.
16621 FunctionTemplateDecl
*TpDecl
= FnDecl
->getDescribedFunctionTemplate();
16623 // This might be a specialization of a literal operator template.
16625 TpDecl
= FnDecl
->getPrimaryTemplate();
16627 // template <char...> type operator "" name() and
16628 // template <class T, T...> type operator "" name() are the only valid
16629 // template signatures, and the only valid signatures with no parameters.
16631 // C++20 also allows template <SomeClass T> type operator "" name().
16633 if (FnDecl
->param_size() != 0) {
16634 Diag(FnDecl
->getLocation(),
16635 diag::err_literal_operator_template_with_params
);
16639 if (checkLiteralOperatorTemplateParameterList(*this, TpDecl
))
16642 } else if (FnDecl
->param_size() == 1) {
16643 const ParmVarDecl
*Param
= FnDecl
->getParamDecl(0);
16645 QualType ParamType
= Param
->getType().getUnqualifiedType();
16647 // Only unsigned long long int, long double, any character type, and const
16648 // char * are allowed as the only parameters.
16649 if (ParamType
->isSpecificBuiltinType(BuiltinType::ULongLong
) ||
16650 ParamType
->isSpecificBuiltinType(BuiltinType::LongDouble
) ||
16651 Context
.hasSameType(ParamType
, Context
.CharTy
) ||
16652 Context
.hasSameType(ParamType
, Context
.WideCharTy
) ||
16653 Context
.hasSameType(ParamType
, Context
.Char8Ty
) ||
16654 Context
.hasSameType(ParamType
, Context
.Char16Ty
) ||
16655 Context
.hasSameType(ParamType
, Context
.Char32Ty
)) {
16656 } else if (const PointerType
*Ptr
= ParamType
->getAs
<PointerType
>()) {
16657 QualType InnerType
= Ptr
->getPointeeType();
16659 // Pointer parameter must be a const char *.
16660 if (!(Context
.hasSameType(InnerType
.getUnqualifiedType(),
16662 InnerType
.isConstQualified() && !InnerType
.isVolatileQualified())) {
16663 Diag(Param
->getSourceRange().getBegin(),
16664 diag::err_literal_operator_param
)
16665 << ParamType
<< "'const char *'" << Param
->getSourceRange();
16669 } else if (ParamType
->isRealFloatingType()) {
16670 Diag(Param
->getSourceRange().getBegin(), diag::err_literal_operator_param
)
16671 << ParamType
<< Context
.LongDoubleTy
<< Param
->getSourceRange();
16674 } else if (ParamType
->isIntegerType()) {
16675 Diag(Param
->getSourceRange().getBegin(), diag::err_literal_operator_param
)
16676 << ParamType
<< Context
.UnsignedLongLongTy
<< Param
->getSourceRange();
16680 Diag(Param
->getSourceRange().getBegin(),
16681 diag::err_literal_operator_invalid_param
)
16682 << ParamType
<< Param
->getSourceRange();
16686 } else if (FnDecl
->param_size() == 2) {
16687 FunctionDecl::param_iterator Param
= FnDecl
->param_begin();
16689 // First, verify that the first parameter is correct.
16691 QualType FirstParamType
= (*Param
)->getType().getUnqualifiedType();
16693 // Two parameter function must have a pointer to const as a
16694 // first parameter; let's strip those qualifiers.
16695 const PointerType
*PT
= FirstParamType
->getAs
<PointerType
>();
16698 Diag((*Param
)->getSourceRange().getBegin(),
16699 diag::err_literal_operator_param
)
16700 << FirstParamType
<< "'const char *'" << (*Param
)->getSourceRange();
16704 QualType PointeeType
= PT
->getPointeeType();
16705 // First parameter must be const
16706 if (!PointeeType
.isConstQualified() || PointeeType
.isVolatileQualified()) {
16707 Diag((*Param
)->getSourceRange().getBegin(),
16708 diag::err_literal_operator_param
)
16709 << FirstParamType
<< "'const char *'" << (*Param
)->getSourceRange();
16713 QualType InnerType
= PointeeType
.getUnqualifiedType();
16714 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
16715 // const char32_t* are allowed as the first parameter to a two-parameter
16717 if (!(Context
.hasSameType(InnerType
, Context
.CharTy
) ||
16718 Context
.hasSameType(InnerType
, Context
.WideCharTy
) ||
16719 Context
.hasSameType(InnerType
, Context
.Char8Ty
) ||
16720 Context
.hasSameType(InnerType
, Context
.Char16Ty
) ||
16721 Context
.hasSameType(InnerType
, Context
.Char32Ty
))) {
16722 Diag((*Param
)->getSourceRange().getBegin(),
16723 diag::err_literal_operator_param
)
16724 << FirstParamType
<< "'const char *'" << (*Param
)->getSourceRange();
16728 // Move on to the second and final parameter.
16731 // The second parameter must be a std::size_t.
16732 QualType SecondParamType
= (*Param
)->getType().getUnqualifiedType();
16733 if (!Context
.hasSameType(SecondParamType
, Context
.getSizeType())) {
16734 Diag((*Param
)->getSourceRange().getBegin(),
16735 diag::err_literal_operator_param
)
16736 << SecondParamType
<< Context
.getSizeType()
16737 << (*Param
)->getSourceRange();
16741 Diag(FnDecl
->getLocation(), diag::err_literal_operator_bad_param_count
);
16745 // Parameters are good.
16747 // A parameter-declaration-clause containing a default argument is not
16748 // equivalent to any of the permitted forms.
16749 for (auto *Param
: FnDecl
->parameters()) {
16750 if (Param
->hasDefaultArg()) {
16751 Diag(Param
->getDefaultArgRange().getBegin(),
16752 diag::err_literal_operator_default_argument
)
16753 << Param
->getDefaultArgRange();
16758 const IdentifierInfo
*II
= FnDecl
->getDeclName().getCXXLiteralIdentifier();
16759 ReservedLiteralSuffixIdStatus Status
= II
->isReservedLiteralSuffixId();
16760 if (Status
!= ReservedLiteralSuffixIdStatus::NotReserved
&&
16761 !getSourceManager().isInSystemHeader(FnDecl
->getLocation())) {
16762 // C++23 [usrlit.suffix]p1:
16763 // Literal suffix identifiers that do not start with an underscore are
16764 // reserved for future standardization. Literal suffix identifiers that
16765 // contain a double underscore __ are reserved for use by C++
16766 // implementations.
16767 Diag(FnDecl
->getLocation(), diag::warn_user_literal_reserved
)
16768 << static_cast<int>(Status
)
16769 << StringLiteralParser::isValidUDSuffix(getLangOpts(), II
->getName());
16775 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
16776 /// linkage specification, including the language and (if present)
16777 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
16778 /// language string literal. LBraceLoc, if valid, provides the location of
16779 /// the '{' brace. Otherwise, this linkage specification does not
16780 /// have any braces.
16781 Decl
*Sema::ActOnStartLinkageSpecification(Scope
*S
, SourceLocation ExternLoc
,
16783 SourceLocation LBraceLoc
) {
16784 StringLiteral
*Lit
= cast
<StringLiteral
>(LangStr
);
16785 assert(Lit
->isUnevaluated() && "Unexpected string literal kind");
16787 StringRef Lang
= Lit
->getString();
16788 LinkageSpecLanguageIDs Language
;
16790 Language
= LinkageSpecLanguageIDs::C
;
16791 else if (Lang
== "C++")
16792 Language
= LinkageSpecLanguageIDs::CXX
;
16794 Diag(LangStr
->getExprLoc(), diag::err_language_linkage_spec_unknown
)
16795 << LangStr
->getSourceRange();
16799 // FIXME: Add all the various semantics of linkage specifications
16801 LinkageSpecDecl
*D
= LinkageSpecDecl::Create(Context
, CurContext
, ExternLoc
,
16802 LangStr
->getExprLoc(), Language
,
16803 LBraceLoc
.isValid());
16805 /// C++ [module.unit]p7.2.3
16806 /// - Otherwise, if the declaration
16809 /// - appears within a linkage-specification,
16810 /// it is attached to the global module.
16812 /// If the declaration is already in global module fragment, we don't
16813 /// need to attach it again.
16814 if (getLangOpts().CPlusPlusModules
&& isCurrentModulePurview()) {
16815 Module
*GlobalModule
= PushImplicitGlobalModuleFragment(
16816 ExternLoc
, /*IsExported=*/D
->isInExportDeclContext());
16817 D
->setLocalOwningModule(GlobalModule
);
16820 CurContext
->addDecl(D
);
16821 PushDeclContext(S
, D
);
16825 /// ActOnFinishLinkageSpecification - Complete the definition of
16826 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
16827 /// valid, it's the position of the closing '}' brace in a linkage
16828 /// specification that uses braces.
16829 Decl
*Sema::ActOnFinishLinkageSpecification(Scope
*S
,
16831 SourceLocation RBraceLoc
) {
16832 if (RBraceLoc
.isValid()) {
16833 LinkageSpecDecl
* LSDecl
= cast
<LinkageSpecDecl
>(LinkageSpec
);
16834 LSDecl
->setRBraceLoc(RBraceLoc
);
16837 // If the current module doesn't has Parent, it implies that the
16838 // LinkageSpec isn't in the module created by itself. So we don't
16840 if (getLangOpts().CPlusPlusModules
&& getCurrentModule() &&
16841 getCurrentModule()->isImplicitGlobalModule() &&
16842 getCurrentModule()->Parent
)
16843 PopImplicitGlobalModuleFragment();
16846 return LinkageSpec
;
16849 Decl
*Sema::ActOnEmptyDeclaration(Scope
*S
,
16850 const ParsedAttributesView
&AttrList
,
16851 SourceLocation SemiLoc
) {
16852 Decl
*ED
= EmptyDecl::Create(Context
, CurContext
, SemiLoc
);
16853 // Attribute declarations appertain to empty declaration so we handle
16855 ProcessDeclAttributeList(S
, ED
, AttrList
);
16857 CurContext
->addDecl(ED
);
16861 /// Perform semantic analysis for the variable declaration that
16862 /// occurs within a C++ catch clause, returning the newly-created
16864 VarDecl
*Sema::BuildExceptionDeclaration(Scope
*S
,
16865 TypeSourceInfo
*TInfo
,
16866 SourceLocation StartLoc
,
16867 SourceLocation Loc
,
16868 IdentifierInfo
*Name
) {
16869 bool Invalid
= false;
16870 QualType ExDeclType
= TInfo
->getType();
16872 // Arrays and functions decay.
16873 if (ExDeclType
->isArrayType())
16874 ExDeclType
= Context
.getArrayDecayedType(ExDeclType
);
16875 else if (ExDeclType
->isFunctionType())
16876 ExDeclType
= Context
.getPointerType(ExDeclType
);
16878 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
16879 // The exception-declaration shall not denote a pointer or reference to an
16880 // incomplete type, other than [cv] void*.
16881 // N2844 forbids rvalue references.
16882 if (!ExDeclType
->isDependentType() && ExDeclType
->isRValueReferenceType()) {
16883 Diag(Loc
, diag::err_catch_rvalue_ref
);
16887 if (ExDeclType
->isVariablyModifiedType()) {
16888 Diag(Loc
, diag::err_catch_variably_modified
) << ExDeclType
;
16892 QualType BaseType
= ExDeclType
;
16893 int Mode
= 0; // 0 for direct type, 1 for pointer, 2 for reference
16894 unsigned DK
= diag::err_catch_incomplete
;
16895 if (const PointerType
*Ptr
= BaseType
->getAs
<PointerType
>()) {
16896 BaseType
= Ptr
->getPointeeType();
16898 DK
= diag::err_catch_incomplete_ptr
;
16899 } else if (const ReferenceType
*Ref
= BaseType
->getAs
<ReferenceType
>()) {
16900 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
16901 BaseType
= Ref
->getPointeeType();
16903 DK
= diag::err_catch_incomplete_ref
;
16905 if (!Invalid
&& (Mode
== 0 || !BaseType
->isVoidType()) &&
16906 !BaseType
->isDependentType() && RequireCompleteType(Loc
, BaseType
, DK
))
16909 if (!Invalid
&& BaseType
.isWebAssemblyReferenceType()) {
16910 Diag(Loc
, diag::err_wasm_reftype_tc
) << 1;
16914 if (!Invalid
&& Mode
!= 1 && BaseType
->isSizelessType()) {
16915 Diag(Loc
, diag::err_catch_sizeless
) << (Mode
== 2 ? 1 : 0) << BaseType
;
16919 if (!Invalid
&& !ExDeclType
->isDependentType() &&
16920 RequireNonAbstractType(Loc
, ExDeclType
,
16921 diag::err_abstract_type_in_decl
,
16922 AbstractVariableType
))
16925 // Only the non-fragile NeXT runtime currently supports C++ catches
16926 // of ObjC types, and no runtime supports catching ObjC types by value.
16927 if (!Invalid
&& getLangOpts().ObjC
) {
16928 QualType T
= ExDeclType
;
16929 if (const ReferenceType
*RT
= T
->getAs
<ReferenceType
>())
16930 T
= RT
->getPointeeType();
16932 if (T
->isObjCObjectType()) {
16933 Diag(Loc
, diag::err_objc_object_catch
);
16935 } else if (T
->isObjCObjectPointerType()) {
16936 // FIXME: should this be a test for macosx-fragile specifically?
16937 if (getLangOpts().ObjCRuntime
.isFragile())
16938 Diag(Loc
, diag::warn_objc_pointer_cxx_catch_fragile
);
16942 VarDecl
*ExDecl
= VarDecl::Create(Context
, CurContext
, StartLoc
, Loc
, Name
,
16943 ExDeclType
, TInfo
, SC_None
);
16944 ExDecl
->setExceptionVariable(true);
16946 // In ARC, infer 'retaining' for variables of retainable type.
16947 if (getLangOpts().ObjCAutoRefCount
&& inferObjCARCLifetime(ExDecl
))
16950 if (!Invalid
&& !ExDeclType
->isDependentType()) {
16951 if (const RecordType
*recordType
= ExDeclType
->getAs
<RecordType
>()) {
16952 // Insulate this from anything else we might currently be parsing.
16953 EnterExpressionEvaluationContext
scope(
16954 *this, ExpressionEvaluationContext::PotentiallyEvaluated
);
16956 // C++ [except.handle]p16:
16957 // The object declared in an exception-declaration or, if the
16958 // exception-declaration does not specify a name, a temporary (12.2) is
16959 // copy-initialized (8.5) from the exception object. [...]
16960 // The object is destroyed when the handler exits, after the destruction
16961 // of any automatic objects initialized within the handler.
16963 // We just pretend to initialize the object with itself, then make sure
16964 // it can be destroyed later.
16965 QualType initType
= Context
.getExceptionObjectType(ExDeclType
);
16967 InitializedEntity entity
=
16968 InitializedEntity::InitializeVariable(ExDecl
);
16969 InitializationKind initKind
=
16970 InitializationKind::CreateCopy(Loc
, SourceLocation());
16972 Expr
*opaqueValue
=
16973 new (Context
) OpaqueValueExpr(Loc
, initType
, VK_LValue
, OK_Ordinary
);
16974 InitializationSequence
sequence(*this, entity
, initKind
, opaqueValue
);
16975 ExprResult result
= sequence
.Perform(*this, entity
, initKind
, opaqueValue
);
16976 if (result
.isInvalid())
16979 // If the constructor used was non-trivial, set this as the
16981 CXXConstructExpr
*construct
= result
.getAs
<CXXConstructExpr
>();
16982 if (!construct
->getConstructor()->isTrivial()) {
16983 Expr
*init
= MaybeCreateExprWithCleanups(construct
);
16984 ExDecl
->setInit(init
);
16987 // And make sure it's destructable.
16988 FinalizeVarWithDestructor(ExDecl
, recordType
);
16994 ExDecl
->setInvalidDecl();
16999 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
17001 Decl
*Sema::ActOnExceptionDeclarator(Scope
*S
, Declarator
&D
) {
17002 TypeSourceInfo
*TInfo
= GetTypeForDeclarator(D
, S
);
17003 bool Invalid
= D
.isInvalidType();
17005 // Check for unexpanded parameter packs.
17006 if (DiagnoseUnexpandedParameterPack(D
.getIdentifierLoc(), TInfo
,
17007 UPPC_ExceptionType
)) {
17008 TInfo
= Context
.getTrivialTypeSourceInfo(Context
.IntTy
,
17009 D
.getIdentifierLoc());
17013 IdentifierInfo
*II
= D
.getIdentifier();
17014 if (NamedDecl
*PrevDecl
= LookupSingleName(S
, II
, D
.getIdentifierLoc(),
17015 LookupOrdinaryName
,
17016 ForVisibleRedeclaration
)) {
17017 // The scope should be freshly made just for us. There is just no way
17018 // it contains any previous declaration, except for function parameters in
17019 // a function-try-block's catch statement.
17020 assert(!S
->isDeclScope(PrevDecl
));
17021 if (isDeclInScope(PrevDecl
, CurContext
, S
)) {
17022 Diag(D
.getIdentifierLoc(), diag::err_redefinition
)
17023 << D
.getIdentifier();
17024 Diag(PrevDecl
->getLocation(), diag::note_previous_definition
);
17026 } else if (PrevDecl
->isTemplateParameter())
17027 // Maybe we will complain about the shadowed template parameter.
17028 DiagnoseTemplateParameterShadow(D
.getIdentifierLoc(), PrevDecl
);
17031 if (D
.getCXXScopeSpec().isSet() && !Invalid
) {
17032 Diag(D
.getIdentifierLoc(), diag::err_qualified_catch_declarator
)
17033 << D
.getCXXScopeSpec().getRange();
17037 VarDecl
*ExDecl
= BuildExceptionDeclaration(
17038 S
, TInfo
, D
.getBeginLoc(), D
.getIdentifierLoc(), D
.getIdentifier());
17040 ExDecl
->setInvalidDecl();
17042 // Add the exception declaration into this scope.
17044 PushOnScopeChains(ExDecl
, S
);
17046 CurContext
->addDecl(ExDecl
);
17048 ProcessDeclAttributes(S
, ExDecl
, D
);
17052 Decl
*Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc
,
17054 Expr
*AssertMessageExpr
,
17055 SourceLocation RParenLoc
) {
17056 if (DiagnoseUnexpandedParameterPack(AssertExpr
, UPPC_StaticAssertExpression
))
17059 return BuildStaticAssertDeclaration(StaticAssertLoc
, AssertExpr
,
17060 AssertMessageExpr
, RParenLoc
, false);
17063 static void WriteCharTypePrefix(BuiltinType::Kind BTK
, llvm::raw_ostream
&OS
) {
17065 case BuiltinType::Char_S
:
17066 case BuiltinType::Char_U
:
17068 case BuiltinType::Char8
:
17071 case BuiltinType::Char16
:
17074 case BuiltinType::Char32
:
17077 case BuiltinType::WChar_S
:
17078 case BuiltinType::WChar_U
:
17082 llvm_unreachable("Non-character type");
17086 /// Convert character's value, interpreted as a code unit, to a string.
17087 /// The value needs to be zero-extended to 32-bits.
17088 /// FIXME: This assumes Unicode literal encodings
17089 static void WriteCharValueForDiagnostic(uint32_t Value
, const BuiltinType
*BTy
,
17091 SmallVectorImpl
<char> &Str
) {
17092 char Arr
[UNI_MAX_UTF8_BYTES_PER_CODE_POINT
];
17094 BuiltinType::Kind K
= BTy
->getKind();
17095 llvm::raw_svector_ostream
OS(Str
);
17097 // This should catch Char_S, Char_U, Char8, and use of escaped characters in
17099 if (K
== BuiltinType::Char_S
|| K
== BuiltinType::Char_U
||
17100 K
== BuiltinType::Char8
|| Value
<= 0x7F) {
17101 StringRef Escaped
= escapeCStyle
<EscapeChar::Single
>(Value
);
17102 if (!Escaped
.empty())
17103 EscapeStringForDiagnostic(Escaped
, Str
);
17105 OS
<< static_cast<char>(Value
);
17110 case BuiltinType::Char16
:
17111 case BuiltinType::Char32
:
17112 case BuiltinType::WChar_S
:
17113 case BuiltinType::WChar_U
: {
17114 if (llvm::ConvertCodePointToUTF8(Value
, Ptr
))
17115 EscapeStringForDiagnostic(StringRef(Arr
, Ptr
- Arr
), Str
);
17118 << llvm::format_hex_no_prefix(Value
, TyWidth
/ 4, /*Upper=*/true);
17122 llvm_unreachable("Non-character type is passed");
17126 /// Convert \V to a string we can present to the user in a diagnostic
17127 /// \T is the type of the expression that has been evaluated into \V
17128 static bool ConvertAPValueToString(const APValue
&V
, QualType T
,
17129 SmallVectorImpl
<char> &Str
,
17130 ASTContext
&Context
) {
17134 switch (V
.getKind()) {
17135 case APValue::ValueKind::Int
:
17136 if (T
->isBooleanType()) {
17137 // Bools are reduced to ints during evaluation, but for
17138 // diagnostic purposes we want to print them as
17140 int64_t BoolValue
= V
.getInt().getExtValue();
17141 assert((BoolValue
== 0 || BoolValue
== 1) &&
17142 "Bool type, but value is not 0 or 1");
17143 llvm::raw_svector_ostream
OS(Str
);
17144 OS
<< (BoolValue
? "true" : "false");
17146 llvm::raw_svector_ostream
OS(Str
);
17147 // Same is true for chars.
17148 // We want to print the character representation for textual types
17149 const auto *BTy
= T
->getAs
<BuiltinType
>();
17151 switch (BTy
->getKind()) {
17152 case BuiltinType::Char_S
:
17153 case BuiltinType::Char_U
:
17154 case BuiltinType::Char8
:
17155 case BuiltinType::Char16
:
17156 case BuiltinType::Char32
:
17157 case BuiltinType::WChar_S
:
17158 case BuiltinType::WChar_U
: {
17159 unsigned TyWidth
= Context
.getIntWidth(T
);
17160 assert(8 <= TyWidth
&& TyWidth
<= 32 && "Unexpected integer width");
17161 uint32_t CodeUnit
= static_cast<uint32_t>(V
.getInt().getZExtValue());
17162 WriteCharTypePrefix(BTy
->getKind(), OS
);
17164 WriteCharValueForDiagnostic(CodeUnit
, BTy
, TyWidth
, Str
);
17166 << llvm::format_hex_no_prefix(CodeUnit
, /*Width=*/2,
17168 << ", " << V
.getInt() << ')';
17175 V
.getInt().toString(Str
);
17180 case APValue::ValueKind::Float
:
17181 V
.getFloat().toString(Str
);
17184 case APValue::ValueKind::LValue
:
17185 if (V
.isNullPointer()) {
17186 llvm::raw_svector_ostream
OS(Str
);
17192 case APValue::ValueKind::ComplexFloat
: {
17193 llvm::raw_svector_ostream
OS(Str
);
17195 V
.getComplexFloatReal().toString(Str
);
17197 V
.getComplexFloatImag().toString(Str
);
17201 case APValue::ValueKind::ComplexInt
: {
17202 llvm::raw_svector_ostream
OS(Str
);
17204 V
.getComplexIntReal().toString(Str
);
17206 V
.getComplexIntImag().toString(Str
);
17217 /// Some Expression types are not useful to print notes about,
17218 /// e.g. literals and values that have already been expanded
17219 /// before such as int-valued template parameters.
17220 static bool UsefulToPrintExpr(const Expr
*E
) {
17221 E
= E
->IgnoreParenImpCasts();
17222 // Literals are pretty easy for humans to understand.
17223 if (isa
<IntegerLiteral
, FloatingLiteral
, CharacterLiteral
, CXXBoolLiteralExpr
,
17224 CXXNullPtrLiteralExpr
, FixedPointLiteral
, ImaginaryLiteral
>(E
))
17227 // These have been substituted from template parameters
17228 // and appear as literals in the static assert error.
17229 if (isa
<SubstNonTypeTemplateParmExpr
>(E
))
17232 // -5 is also simple to understand.
17233 if (const auto *UnaryOp
= dyn_cast
<UnaryOperator
>(E
))
17234 return UsefulToPrintExpr(UnaryOp
->getSubExpr());
17236 // Ignore nested binary operators. This could be a FIXME for improvements
17237 // to the diagnostics in the future.
17238 if (isa
<BinaryOperator
>(E
))
17244 /// Try to print more useful information about a failed static_assert
17245 /// with expression \E
17246 void Sema::DiagnoseStaticAssertDetails(const Expr
*E
) {
17247 if (const auto *Op
= dyn_cast
<BinaryOperator
>(E
);
17248 Op
&& Op
->getOpcode() != BO_LOr
) {
17249 const Expr
*LHS
= Op
->getLHS()->IgnoreParenImpCasts();
17250 const Expr
*RHS
= Op
->getRHS()->IgnoreParenImpCasts();
17252 // Ignore comparisons of boolean expressions with a boolean literal.
17253 if ((isa
<CXXBoolLiteralExpr
>(LHS
) && RHS
->getType()->isBooleanType()) ||
17254 (isa
<CXXBoolLiteralExpr
>(RHS
) && LHS
->getType()->isBooleanType()))
17257 // Don't print obvious expressions.
17258 if (!UsefulToPrintExpr(LHS
) && !UsefulToPrintExpr(RHS
))
17262 const clang::Expr
*Cond
;
17263 Expr::EvalResult Result
;
17264 SmallString
<12> ValueString
;
17266 } DiagSide
[2] = {{LHS
, Expr::EvalResult(), {}, false},
17267 {RHS
, Expr::EvalResult(), {}, false}};
17268 for (unsigned I
= 0; I
< 2; I
++) {
17269 const Expr
*Side
= DiagSide
[I
].Cond
;
17271 Side
->EvaluateAsRValue(DiagSide
[I
].Result
, Context
, true);
17273 DiagSide
[I
].Print
=
17274 ConvertAPValueToString(DiagSide
[I
].Result
.Val
, Side
->getType(),
17275 DiagSide
[I
].ValueString
, Context
);
17277 if (DiagSide
[0].Print
&& DiagSide
[1].Print
) {
17278 Diag(Op
->getExprLoc(), diag::note_expr_evaluates_to
)
17279 << DiagSide
[0].ValueString
<< Op
->getOpcodeStr()
17280 << DiagSide
[1].ValueString
<< Op
->getSourceRange();
17285 bool Sema::EvaluateStaticAssertMessageAsString(Expr
*Message
,
17286 std::string
&Result
,
17288 bool ErrorOnInvalidMessage
) {
17290 assert(!Message
->isTypeDependent() && !Message
->isValueDependent() &&
17291 "can't evaluate a dependant static assert message");
17293 if (const auto *SL
= dyn_cast
<StringLiteral
>(Message
)) {
17294 assert(SL
->isUnevaluated() && "expected an unevaluated string");
17295 Result
.assign(SL
->getString().begin(), SL
->getString().end());
17299 SourceLocation Loc
= Message
->getBeginLoc();
17300 QualType T
= Message
->getType().getNonReferenceType();
17301 auto *RD
= T
->getAsCXXRecordDecl();
17303 Diag(Loc
, diag::err_static_assert_invalid_message
);
17307 auto FindMember
= [&](StringRef Member
, bool &Empty
,
17308 bool Diag
= false) -> std::optional
<LookupResult
> {
17309 QualType ObjectType
= Message
->getType();
17310 Expr::Classification ObjectClassification
=
17311 Message
->Classify(getASTContext());
17313 DeclarationName DN
= PP
.getIdentifierInfo(Member
);
17314 LookupResult
MemberLookup(*this, DN
, Loc
, Sema::LookupMemberName
);
17315 LookupQualifiedName(MemberLookup
, RD
);
17316 Empty
= MemberLookup
.empty();
17317 OverloadCandidateSet
Candidates(MemberLookup
.getNameLoc(),
17318 OverloadCandidateSet::CSK_Normal
);
17319 for (NamedDecl
*D
: MemberLookup
) {
17320 AddMethodCandidate(DeclAccessPair::make(D
, D
->getAccess()), ObjectType
,
17321 ObjectClassification
, /*Args=*/{}, Candidates
);
17323 OverloadCandidateSet::iterator Best
;
17324 switch (Candidates
.BestViableFunction(*this, Loc
, Best
)) {
17326 return std::move(MemberLookup
);
17329 Candidates
.NoteCandidates(
17330 PartialDiagnosticAt(
17331 Loc
, PDiag(diag::err_static_assert_invalid_mem_fn_ret_ty
)
17332 << (Member
== "data")),
17333 *this, OCD_AllCandidates
, /*Args=*/{});
17335 return std::nullopt
;
17338 bool SizeNotFound
, DataNotFound
;
17339 std::optional
<LookupResult
> SizeMember
= FindMember("size", SizeNotFound
);
17340 std::optional
<LookupResult
> DataMember
= FindMember("data", DataNotFound
);
17341 if (SizeNotFound
|| DataNotFound
) {
17342 Diag(Loc
, diag::err_static_assert_missing_member_function
)
17343 << ((SizeNotFound
&& DataNotFound
) ? 2
17349 if (!SizeMember
|| !DataMember
) {
17351 FindMember("size", SizeNotFound
, /*Diag=*/true);
17353 FindMember("data", DataNotFound
, /*Diag=*/true);
17357 auto BuildExpr
= [&](LookupResult
&LR
) {
17358 ExprResult Res
= BuildMemberReferenceExpr(
17359 Message
, Message
->getType(), Message
->getBeginLoc(), false,
17360 CXXScopeSpec(), SourceLocation(), nullptr, LR
, nullptr, nullptr);
17361 if (Res
.isInvalid())
17362 return ExprError();
17363 Res
= BuildCallExpr(nullptr, Res
.get(), Loc
, std::nullopt
, Loc
, nullptr,
17365 if (Res
.isInvalid())
17366 return ExprError();
17367 if (Res
.get()->isTypeDependent() || Res
.get()->isValueDependent())
17368 return ExprError();
17369 return TemporaryMaterializationConversion(Res
.get());
17372 ExprResult SizeE
= BuildExpr(*SizeMember
);
17373 ExprResult DataE
= BuildExpr(*DataMember
);
17375 QualType SizeT
= Context
.getSizeType();
17376 QualType ConstCharPtr
=
17377 Context
.getPointerType(Context
.getConstType(Context
.CharTy
));
17379 ExprResult EvaluatedSize
=
17380 SizeE
.isInvalid() ? ExprError()
17381 : BuildConvertedConstantExpression(
17382 SizeE
.get(), SizeT
, CCEK_StaticAssertMessageSize
);
17383 if (EvaluatedSize
.isInvalid()) {
17384 Diag(Loc
, diag::err_static_assert_invalid_mem_fn_ret_ty
) << /*size*/ 0;
17388 ExprResult EvaluatedData
=
17391 : BuildConvertedConstantExpression(DataE
.get(), ConstCharPtr
,
17392 CCEK_StaticAssertMessageData
);
17393 if (EvaluatedData
.isInvalid()) {
17394 Diag(Loc
, diag::err_static_assert_invalid_mem_fn_ret_ty
) << /*data*/ 1;
17398 if (!ErrorOnInvalidMessage
&&
17399 Diags
.isIgnored(diag::warn_static_assert_message_constexpr
, Loc
))
17402 Expr::EvalResult Status
;
17403 SmallVector
<PartialDiagnosticAt
, 8> Notes
;
17404 Status
.Diag
= &Notes
;
17405 if (!Message
->EvaluateCharRangeAsString(Result
, EvaluatedSize
.get(),
17406 EvaluatedData
.get(), Ctx
, Status
) ||
17408 Diag(Message
->getBeginLoc(),
17409 ErrorOnInvalidMessage
? diag::err_static_assert_message_constexpr
17410 : diag::warn_static_assert_message_constexpr
);
17411 for (const auto &Note
: Notes
)
17412 Diag(Note
.first
, Note
.second
);
17413 return !ErrorOnInvalidMessage
;
17418 Decl
*Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc
,
17419 Expr
*AssertExpr
, Expr
*AssertMessage
,
17420 SourceLocation RParenLoc
,
17422 assert(AssertExpr
!= nullptr && "Expected non-null condition");
17423 if (!AssertExpr
->isTypeDependent() && !AssertExpr
->isValueDependent() &&
17424 (!AssertMessage
|| (!AssertMessage
->isTypeDependent() &&
17425 !AssertMessage
->isValueDependent())) &&
17427 // In a static_assert-declaration, the constant-expression shall be a
17428 // constant expression that can be contextually converted to bool.
17429 ExprResult Converted
= PerformContextuallyConvertToBool(AssertExpr
);
17430 if (Converted
.isInvalid())
17433 ExprResult FullAssertExpr
=
17434 ActOnFinishFullExpr(Converted
.get(), StaticAssertLoc
,
17435 /*DiscardedValue*/ false,
17436 /*IsConstexpr*/ true);
17437 if (FullAssertExpr
.isInvalid())
17440 AssertExpr
= FullAssertExpr
.get();
17443 Expr
*BaseExpr
= AssertExpr
;
17444 AllowFoldKind FoldKind
= NoFold
;
17446 if (!getLangOpts().CPlusPlus
) {
17447 // In C mode, allow folding as an extension for better compatibility with
17448 // C++ in terms of expressions like static_assert("test") or
17449 // static_assert(nullptr).
17450 FoldKind
= AllowFold
;
17453 if (!Failed
&& VerifyIntegerConstantExpression(
17455 diag::err_static_assert_expression_is_not_constant
,
17456 FoldKind
).isInvalid())
17459 // If the static_assert passes, only verify that
17460 // the message is grammatically valid without evaluating it.
17461 if (!Failed
&& AssertMessage
&& Cond
.getBoolValue()) {
17463 EvaluateStaticAssertMessageAsString(AssertMessage
, Str
, Context
,
17464 /*ErrorOnInvalidMessage=*/false);
17468 // [dcl.pre]/p10 If [...] the expression is evaluated in the context of a
17469 // template definition, the declaration has no effect.
17470 bool InTemplateDefinition
=
17471 getLangOpts().CPlusPlus
&& CurContext
->isDependentContext();
17473 if (!Failed
&& !Cond
&& !InTemplateDefinition
) {
17474 SmallString
<256> MsgBuffer
;
17475 llvm::raw_svector_ostream
Msg(MsgBuffer
);
17476 bool HasMessage
= AssertMessage
;
17477 if (AssertMessage
) {
17480 EvaluateStaticAssertMessageAsString(
17481 AssertMessage
, Str
, Context
, /*ErrorOnInvalidMessage=*/true) ||
17485 Expr
*InnerCond
= nullptr;
17486 std::string InnerCondDescription
;
17487 std::tie(InnerCond
, InnerCondDescription
) =
17488 findFailedBooleanCondition(Converted
.get());
17489 if (InnerCond
&& isa
<ConceptSpecializationExpr
>(InnerCond
)) {
17490 // Drill down into concept specialization expressions to see why they
17491 // weren't satisfied.
17492 Diag(AssertExpr
->getBeginLoc(), diag::err_static_assert_failed
)
17493 << !HasMessage
<< Msg
.str() << AssertExpr
->getSourceRange();
17494 ConstraintSatisfaction Satisfaction
;
17495 if (!CheckConstraintSatisfaction(InnerCond
, Satisfaction
))
17496 DiagnoseUnsatisfiedConstraint(Satisfaction
);
17497 } else if (InnerCond
&& !isa
<CXXBoolLiteralExpr
>(InnerCond
)
17498 && !isa
<IntegerLiteral
>(InnerCond
)) {
17499 Diag(InnerCond
->getBeginLoc(),
17500 diag::err_static_assert_requirement_failed
)
17501 << InnerCondDescription
<< !HasMessage
<< Msg
.str()
17502 << InnerCond
->getSourceRange();
17503 DiagnoseStaticAssertDetails(InnerCond
);
17505 Diag(AssertExpr
->getBeginLoc(), diag::err_static_assert_failed
)
17506 << !HasMessage
<< Msg
.str() << AssertExpr
->getSourceRange();
17507 PrintContextStack();
17512 ExprResult FullAssertExpr
= ActOnFinishFullExpr(AssertExpr
, StaticAssertLoc
,
17513 /*DiscardedValue*/false,
17514 /*IsConstexpr*/true);
17515 if (FullAssertExpr
.isInvalid())
17518 AssertExpr
= FullAssertExpr
.get();
17521 Decl
*Decl
= StaticAssertDecl::Create(Context
, CurContext
, StaticAssertLoc
,
17522 AssertExpr
, AssertMessage
, RParenLoc
,
17525 CurContext
->addDecl(Decl
);
17529 /// Perform semantic analysis of the given friend type declaration.
17531 /// \returns A friend declaration that.
17532 FriendDecl
*Sema::CheckFriendTypeDecl(SourceLocation LocStart
,
17533 SourceLocation FriendLoc
,
17534 TypeSourceInfo
*TSInfo
) {
17535 assert(TSInfo
&& "NULL TypeSourceInfo for friend type declaration");
17537 QualType T
= TSInfo
->getType();
17538 SourceRange TypeRange
= TSInfo
->getTypeLoc().getSourceRange();
17540 // C++03 [class.friend]p2:
17541 // An elaborated-type-specifier shall be used in a friend declaration
17544 // * The class-key of the elaborated-type-specifier is required.
17545 if (!CodeSynthesisContexts
.empty()) {
17546 // Do not complain about the form of friend template types during any kind
17547 // of code synthesis. For template instantiation, we will have complained
17548 // when the template was defined.
17550 if (!T
->isElaboratedTypeSpecifier()) {
17551 // If we evaluated the type to a record type, suggest putting
17553 if (const RecordType
*RT
= T
->getAs
<RecordType
>()) {
17554 RecordDecl
*RD
= RT
->getDecl();
17556 SmallString
<16> InsertionText(" ");
17557 InsertionText
+= RD
->getKindName();
17559 Diag(TypeRange
.getBegin(),
17560 getLangOpts().CPlusPlus11
?
17561 diag::warn_cxx98_compat_unelaborated_friend_type
:
17562 diag::ext_unelaborated_friend_type
)
17563 << (unsigned) RD
->getTagKind()
17565 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc
),
17569 getLangOpts().CPlusPlus11
?
17570 diag::warn_cxx98_compat_nonclass_type_friend
:
17571 diag::ext_nonclass_type_friend
)
17575 } else if (T
->getAs
<EnumType
>()) {
17577 getLangOpts().CPlusPlus11
?
17578 diag::warn_cxx98_compat_enum_friend
:
17579 diag::ext_enum_friend
)
17584 // C++11 [class.friend]p3:
17585 // A friend declaration that does not declare a function shall have one
17586 // of the following forms:
17587 // friend elaborated-type-specifier ;
17588 // friend simple-type-specifier ;
17589 // friend typename-specifier ;
17590 if (getLangOpts().CPlusPlus11
&& LocStart
!= FriendLoc
)
17591 Diag(FriendLoc
, diag::err_friend_not_first_in_declaration
) << T
;
17594 // If the type specifier in a friend declaration designates a (possibly
17595 // cv-qualified) class type, that class is declared as a friend; otherwise,
17596 // the friend declaration is ignored.
17597 return FriendDecl::Create(Context
, CurContext
,
17598 TSInfo
->getTypeLoc().getBeginLoc(), TSInfo
,
17602 /// Handle a friend tag declaration where the scope specifier was
17604 DeclResult
Sema::ActOnTemplatedFriendTag(
17605 Scope
*S
, SourceLocation FriendLoc
, unsigned TagSpec
, SourceLocation TagLoc
,
17606 CXXScopeSpec
&SS
, IdentifierInfo
*Name
, SourceLocation NameLoc
,
17607 const ParsedAttributesView
&Attr
, MultiTemplateParamsArg TempParamLists
) {
17608 TagTypeKind Kind
= TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec
);
17610 bool IsMemberSpecialization
= false;
17611 bool Invalid
= false;
17613 if (TemplateParameterList
*TemplateParams
=
17614 MatchTemplateParametersToScopeSpecifier(
17615 TagLoc
, NameLoc
, SS
, nullptr, TempParamLists
, /*friend*/ true,
17616 IsMemberSpecialization
, Invalid
)) {
17617 if (TemplateParams
->size() > 0) {
17618 // This is a declaration of a class template.
17622 return CheckClassTemplate(S
, TagSpec
, TUK_Friend
, TagLoc
, SS
, Name
,
17623 NameLoc
, Attr
, TemplateParams
, AS_public
,
17624 /*ModulePrivateLoc=*/SourceLocation(),
17625 FriendLoc
, TempParamLists
.size() - 1,
17626 TempParamLists
.data()).get();
17628 // The "template<>" header is extraneous.
17629 Diag(TemplateParams
->getTemplateLoc(), diag::err_template_tag_noparams
)
17630 << TypeWithKeyword::getTagTypeKindName(Kind
) << Name
;
17631 IsMemberSpecialization
= true;
17635 if (Invalid
) return true;
17637 bool isAllExplicitSpecializations
= true;
17638 for (unsigned I
= TempParamLists
.size(); I
-- > 0; ) {
17639 if (TempParamLists
[I
]->size()) {
17640 isAllExplicitSpecializations
= false;
17645 // FIXME: don't ignore attributes.
17647 // If it's explicit specializations all the way down, just forget
17648 // about the template header and build an appropriate non-templated
17649 // friend. TODO: for source fidelity, remember the headers.
17650 if (isAllExplicitSpecializations
) {
17651 if (SS
.isEmpty()) {
17652 bool Owned
= false;
17653 bool IsDependent
= false;
17654 return ActOnTag(S
, TagSpec
, TUK_Friend
, TagLoc
, SS
, Name
, NameLoc
, Attr
,
17656 /*ModulePrivateLoc=*/SourceLocation(),
17657 MultiTemplateParamsArg(), Owned
, IsDependent
,
17658 /*ScopedEnumKWLoc=*/SourceLocation(),
17659 /*ScopedEnumUsesClassTag=*/false,
17660 /*UnderlyingType=*/TypeResult(),
17661 /*IsTypeSpecifier=*/false,
17662 /*IsTemplateParamOrArg=*/false, /*OOK=*/OOK_Outside
);
17665 NestedNameSpecifierLoc QualifierLoc
= SS
.getWithLocInContext(Context
);
17666 ElaboratedTypeKeyword Keyword
17667 = TypeWithKeyword::getKeywordForTagTypeKind(Kind
);
17668 QualType T
= CheckTypenameType(Keyword
, TagLoc
, QualifierLoc
,
17673 TypeSourceInfo
*TSI
= Context
.CreateTypeSourceInfo(T
);
17674 if (isa
<DependentNameType
>(T
)) {
17675 DependentNameTypeLoc TL
=
17676 TSI
->getTypeLoc().castAs
<DependentNameTypeLoc
>();
17677 TL
.setElaboratedKeywordLoc(TagLoc
);
17678 TL
.setQualifierLoc(QualifierLoc
);
17679 TL
.setNameLoc(NameLoc
);
17681 ElaboratedTypeLoc TL
= TSI
->getTypeLoc().castAs
<ElaboratedTypeLoc
>();
17682 TL
.setElaboratedKeywordLoc(TagLoc
);
17683 TL
.setQualifierLoc(QualifierLoc
);
17684 TL
.getNamedTypeLoc().castAs
<TypeSpecTypeLoc
>().setNameLoc(NameLoc
);
17687 FriendDecl
*Friend
= FriendDecl::Create(Context
, CurContext
, NameLoc
,
17688 TSI
, FriendLoc
, TempParamLists
);
17689 Friend
->setAccess(AS_public
);
17690 CurContext
->addDecl(Friend
);
17694 assert(SS
.isNotEmpty() && "valid templated tag with no SS and no direct?");
17698 // Handle the case of a templated-scope friend class. e.g.
17699 // template <class T> class A<T>::B;
17700 // FIXME: we don't support these right now.
17701 Diag(NameLoc
, diag::warn_template_qualified_friend_unsupported
)
17702 << SS
.getScopeRep() << SS
.getRange() << cast
<CXXRecordDecl
>(CurContext
);
17703 ElaboratedTypeKeyword ETK
= TypeWithKeyword::getKeywordForTagTypeKind(Kind
);
17704 QualType T
= Context
.getDependentNameType(ETK
, SS
.getScopeRep(), Name
);
17705 TypeSourceInfo
*TSI
= Context
.CreateTypeSourceInfo(T
);
17706 DependentNameTypeLoc TL
= TSI
->getTypeLoc().castAs
<DependentNameTypeLoc
>();
17707 TL
.setElaboratedKeywordLoc(TagLoc
);
17708 TL
.setQualifierLoc(SS
.getWithLocInContext(Context
));
17709 TL
.setNameLoc(NameLoc
);
17711 FriendDecl
*Friend
= FriendDecl::Create(Context
, CurContext
, NameLoc
,
17712 TSI
, FriendLoc
, TempParamLists
);
17713 Friend
->setAccess(AS_public
);
17714 Friend
->setUnsupportedFriend(true);
17715 CurContext
->addDecl(Friend
);
17719 /// Handle a friend type declaration. This works in tandem with
17722 /// Notes on friend class templates:
17724 /// We generally treat friend class declarations as if they were
17725 /// declaring a class. So, for example, the elaborated type specifier
17726 /// in a friend declaration is required to obey the restrictions of a
17727 /// class-head (i.e. no typedefs in the scope chain), template
17728 /// parameters are required to match up with simple template-ids, &c.
17729 /// However, unlike when declaring a template specialization, it's
17730 /// okay to refer to a template specialization without an empty
17731 /// template parameter declaration, e.g.
17732 /// friend class A<T>::B<unsigned>;
17733 /// We permit this as a special case; if there are any template
17734 /// parameters present at all, require proper matching, i.e.
17735 /// template <> template \<class T> friend class A<int>::B;
17736 Decl
*Sema::ActOnFriendTypeDecl(Scope
*S
, const DeclSpec
&DS
,
17737 MultiTemplateParamsArg TempParams
) {
17738 SourceLocation Loc
= DS
.getBeginLoc();
17740 assert(DS
.isFriendSpecified());
17741 assert(DS
.getStorageClassSpec() == DeclSpec::SCS_unspecified
);
17743 // C++ [class.friend]p3:
17744 // A friend declaration that does not declare a function shall have one of
17745 // the following forms:
17746 // friend elaborated-type-specifier ;
17747 // friend simple-type-specifier ;
17748 // friend typename-specifier ;
17750 // Any declaration with a type qualifier does not have that form. (It's
17751 // legal to specify a qualified type as a friend, you just can't write the
17753 if (DS
.getTypeQualifiers()) {
17754 if (DS
.getTypeQualifiers() & DeclSpec::TQ_const
)
17755 Diag(DS
.getConstSpecLoc(), diag::err_friend_decl_spec
) << "const";
17756 if (DS
.getTypeQualifiers() & DeclSpec::TQ_volatile
)
17757 Diag(DS
.getVolatileSpecLoc(), diag::err_friend_decl_spec
) << "volatile";
17758 if (DS
.getTypeQualifiers() & DeclSpec::TQ_restrict
)
17759 Diag(DS
.getRestrictSpecLoc(), diag::err_friend_decl_spec
) << "restrict";
17760 if (DS
.getTypeQualifiers() & DeclSpec::TQ_atomic
)
17761 Diag(DS
.getAtomicSpecLoc(), diag::err_friend_decl_spec
) << "_Atomic";
17762 if (DS
.getTypeQualifiers() & DeclSpec::TQ_unaligned
)
17763 Diag(DS
.getUnalignedSpecLoc(), diag::err_friend_decl_spec
) << "__unaligned";
17766 // Try to convert the decl specifier to a type. This works for
17767 // friend templates because ActOnTag never produces a ClassTemplateDecl
17768 // for a TUK_Friend.
17769 Declarator
TheDeclarator(DS
, ParsedAttributesView::none(),
17770 DeclaratorContext::Member
);
17771 TypeSourceInfo
*TSI
= GetTypeForDeclarator(TheDeclarator
, S
);
17772 QualType T
= TSI
->getType();
17773 if (TheDeclarator
.isInvalidType())
17776 if (DiagnoseUnexpandedParameterPack(Loc
, TSI
, UPPC_FriendDeclaration
))
17779 // This is definitely an error in C++98. It's probably meant to
17780 // be forbidden in C++0x, too, but the specification is just
17783 // The problem is with declarations like the following:
17784 // template <T> friend A<T>::foo;
17785 // where deciding whether a class C is a friend or not now hinges
17786 // on whether there exists an instantiation of A that causes
17787 // 'foo' to equal C. There are restrictions on class-heads
17788 // (which we declare (by fiat) elaborated friend declarations to
17789 // be) that makes this tractable.
17791 // FIXME: handle "template <> friend class A<T>;", which
17792 // is possibly well-formed? Who even knows?
17793 if (TempParams
.size() && !T
->isElaboratedTypeSpecifier()) {
17794 Diag(Loc
, diag::err_tagless_friend_type_template
)
17795 << DS
.getSourceRange();
17799 // C++98 [class.friend]p1: A friend of a class is a function
17800 // or class that is not a member of the class . . .
17801 // This is fixed in DR77, which just barely didn't make the C++03
17802 // deadline. It's also a very silly restriction that seriously
17803 // affects inner classes and which nobody else seems to implement;
17804 // thus we never diagnose it, not even in -pedantic.
17806 // But note that we could warn about it: it's always useless to
17807 // friend one of your own members (it's not, however, worthless to
17808 // friend a member of an arbitrary specialization of your template).
17811 if (!TempParams
.empty())
17812 D
= FriendTemplateDecl::Create(Context
, CurContext
, Loc
,
17815 DS
.getFriendSpecLoc());
17817 D
= CheckFriendTypeDecl(Loc
, DS
.getFriendSpecLoc(), TSI
);
17822 D
->setAccess(AS_public
);
17823 CurContext
->addDecl(D
);
17828 NamedDecl
*Sema::ActOnFriendFunctionDecl(Scope
*S
, Declarator
&D
,
17829 MultiTemplateParamsArg TemplateParams
) {
17830 const DeclSpec
&DS
= D
.getDeclSpec();
17832 assert(DS
.isFriendSpecified());
17833 assert(DS
.getStorageClassSpec() == DeclSpec::SCS_unspecified
);
17835 SourceLocation Loc
= D
.getIdentifierLoc();
17836 TypeSourceInfo
*TInfo
= GetTypeForDeclarator(D
, S
);
17838 // C++ [class.friend]p1
17839 // A friend of a class is a function or class....
17840 // Note that this sees through typedefs, which is intended.
17841 // It *doesn't* see through dependent types, which is correct
17842 // according to [temp.arg.type]p3:
17843 // If a declaration acquires a function type through a
17844 // type dependent on a template-parameter and this causes
17845 // a declaration that does not use the syntactic form of a
17846 // function declarator to have a function type, the program
17848 if (!TInfo
->getType()->isFunctionType()) {
17849 Diag(Loc
, diag::err_unexpected_friend
);
17851 // It might be worthwhile to try to recover by creating an
17852 // appropriate declaration.
17856 // C++ [namespace.memdef]p3
17857 // - If a friend declaration in a non-local class first declares a
17858 // class or function, the friend class or function is a member
17859 // of the innermost enclosing namespace.
17860 // - The name of the friend is not found by simple name lookup
17861 // until a matching declaration is provided in that namespace
17862 // scope (either before or after the class declaration granting
17864 // - If a friend function is called, its name may be found by the
17865 // name lookup that considers functions from namespaces and
17866 // classes associated with the types of the function arguments.
17867 // - When looking for a prior declaration of a class or a function
17868 // declared as a friend, scopes outside the innermost enclosing
17869 // namespace scope are not considered.
17871 CXXScopeSpec
&SS
= D
.getCXXScopeSpec();
17872 DeclarationNameInfo NameInfo
= GetNameForDeclarator(D
);
17873 assert(NameInfo
.getName());
17875 // Check for unexpanded parameter packs.
17876 if (DiagnoseUnexpandedParameterPack(Loc
, TInfo
, UPPC_FriendDeclaration
) ||
17877 DiagnoseUnexpandedParameterPack(NameInfo
, UPPC_FriendDeclaration
) ||
17878 DiagnoseUnexpandedParameterPack(SS
, UPPC_FriendDeclaration
))
17881 // The context we found the declaration in, or in which we should
17882 // create the declaration.
17884 Scope
*DCScope
= S
;
17885 LookupResult
Previous(*this, NameInfo
, LookupOrdinaryName
,
17886 ForExternalRedeclaration
);
17888 // There are five cases here.
17889 // - There's no scope specifier and we're in a local class. Only look
17890 // for functions declared in the immediately-enclosing block scope.
17891 // We recover from invalid scope qualifiers as if they just weren't there.
17892 FunctionDecl
*FunctionContainingLocalClass
= nullptr;
17893 if ((SS
.isInvalid() || !SS
.isSet()) &&
17894 (FunctionContainingLocalClass
=
17895 cast
<CXXRecordDecl
>(CurContext
)->isLocalClass())) {
17896 // C++11 [class.friend]p11:
17897 // If a friend declaration appears in a local class and the name
17898 // specified is an unqualified name, a prior declaration is
17899 // looked up without considering scopes that are outside the
17900 // innermost enclosing non-class scope. For a friend function
17901 // declaration, if there is no prior declaration, the program is
17904 // Find the innermost enclosing non-class scope. This is the block
17905 // scope containing the local class definition (or for a nested class,
17906 // the outer local class).
17907 DCScope
= S
->getFnParent();
17909 // Look up the function name in the scope.
17910 Previous
.clear(LookupLocalFriendName
);
17911 LookupName(Previous
, S
, /*AllowBuiltinCreation*/false);
17913 if (!Previous
.empty()) {
17914 // All possible previous declarations must have the same context:
17915 // either they were declared at block scope or they are members of
17916 // one of the enclosing local classes.
17917 DC
= Previous
.getRepresentativeDecl()->getDeclContext();
17919 // This is ill-formed, but provide the context that we would have
17920 // declared the function in, if we were permitted to, for error recovery.
17921 DC
= FunctionContainingLocalClass
;
17923 adjustContextForLocalExternDecl(DC
);
17925 // C++ [class.friend]p6:
17926 // A function can be defined in a friend declaration of a class if and
17927 // only if the class is a non-local class (9.8), the function name is
17928 // unqualified, and the function has namespace scope.
17929 if (D
.isFunctionDefinition()) {
17930 Diag(NameInfo
.getBeginLoc(), diag::err_friend_def_in_local_class
);
17933 // - There's no scope specifier, in which case we just go to the
17934 // appropriate scope and look for a function or function template
17935 // there as appropriate.
17936 } else if (SS
.isInvalid() || !SS
.isSet()) {
17937 // C++11 [namespace.memdef]p3:
17938 // If the name in a friend declaration is neither qualified nor
17939 // a template-id and the declaration is a function or an
17940 // elaborated-type-specifier, the lookup to determine whether
17941 // the entity has been previously declared shall not consider
17942 // any scopes outside the innermost enclosing namespace.
17943 bool isTemplateId
=
17944 D
.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
;
17946 // Find the appropriate context according to the above.
17949 // Skip class contexts. If someone can cite chapter and verse
17950 // for this behavior, that would be nice --- it's what GCC and
17951 // EDG do, and it seems like a reasonable intent, but the spec
17952 // really only says that checks for unqualified existing
17953 // declarations should stop at the nearest enclosing namespace,
17954 // not that they should only consider the nearest enclosing
17956 while (DC
->isRecord())
17957 DC
= DC
->getParent();
17959 DeclContext
*LookupDC
= DC
->getNonTransparentContext();
17961 LookupQualifiedName(Previous
, LookupDC
);
17963 if (!Previous
.empty()) {
17968 if (isTemplateId
) {
17969 if (isa
<TranslationUnitDecl
>(LookupDC
)) break;
17971 if (LookupDC
->isFileContext()) break;
17973 LookupDC
= LookupDC
->getParent();
17976 DCScope
= getScopeForDeclContext(S
, DC
);
17978 // - There's a non-dependent scope specifier, in which case we
17979 // compute it and do a previous lookup there for a function
17980 // or function template.
17981 } else if (!SS
.getScopeRep()->isDependent()) {
17982 DC
= computeDeclContext(SS
);
17983 if (!DC
) return nullptr;
17985 if (RequireCompleteDeclContext(SS
, DC
)) return nullptr;
17987 LookupQualifiedName(Previous
, DC
);
17989 // C++ [class.friend]p1: A friend of a class is a function or
17990 // class that is not a member of the class . . .
17991 if (DC
->Equals(CurContext
))
17992 Diag(DS
.getFriendSpecLoc(),
17993 getLangOpts().CPlusPlus11
?
17994 diag::warn_cxx98_compat_friend_is_member
:
17995 diag::err_friend_is_member
);
17997 if (D
.isFunctionDefinition()) {
17998 // C++ [class.friend]p6:
17999 // A function can be defined in a friend declaration of a class if and
18000 // only if the class is a non-local class (9.8), the function name is
18001 // unqualified, and the function has namespace scope.
18003 // FIXME: We should only do this if the scope specifier names the
18004 // innermost enclosing namespace; otherwise the fixit changes the
18005 // meaning of the code.
18006 SemaDiagnosticBuilder DB
18007 = Diag(SS
.getRange().getBegin(), diag::err_qualified_friend_def
);
18009 DB
<< SS
.getScopeRep();
18010 if (DC
->isFileContext())
18011 DB
<< FixItHint::CreateRemoval(SS
.getRange());
18015 // - There's a scope specifier that does not match any template
18016 // parameter lists, in which case we use some arbitrary context,
18017 // create a method or method template, and wait for instantiation.
18018 // - There's a scope specifier that does match some template
18019 // parameter lists, which we don't handle right now.
18021 if (D
.isFunctionDefinition()) {
18022 // C++ [class.friend]p6:
18023 // A function can be defined in a friend declaration of a class if and
18024 // only if the class is a non-local class (9.8), the function name is
18025 // unqualified, and the function has namespace scope.
18026 Diag(SS
.getRange().getBegin(), diag::err_qualified_friend_def
)
18027 << SS
.getScopeRep();
18031 assert(isa
<CXXRecordDecl
>(DC
) && "friend declaration not in class?");
18034 if (!DC
->isRecord()) {
18036 switch (D
.getName().getKind()) {
18037 case UnqualifiedIdKind::IK_ConstructorTemplateId
:
18038 case UnqualifiedIdKind::IK_ConstructorName
:
18041 case UnqualifiedIdKind::IK_DestructorName
:
18044 case UnqualifiedIdKind::IK_ConversionFunctionId
:
18047 case UnqualifiedIdKind::IK_DeductionGuideName
:
18050 case UnqualifiedIdKind::IK_Identifier
:
18051 case UnqualifiedIdKind::IK_ImplicitSelfParam
:
18052 case UnqualifiedIdKind::IK_LiteralOperatorId
:
18053 case UnqualifiedIdKind::IK_OperatorFunctionId
:
18054 case UnqualifiedIdKind::IK_TemplateId
:
18057 // This implies that it has to be an operator or function.
18058 if (DiagArg
>= 0) {
18059 Diag(Loc
, diag::err_introducing_special_friend
) << DiagArg
;
18064 // FIXME: This is an egregious hack to cope with cases where the scope stack
18065 // does not contain the declaration context, i.e., in an out-of-line
18066 // definition of a class.
18067 Scope
FakeDCScope(S
, Scope::DeclScope
, Diags
);
18069 FakeDCScope
.setEntity(DC
);
18070 DCScope
= &FakeDCScope
;
18073 bool AddToScope
= true;
18074 NamedDecl
*ND
= ActOnFunctionDeclarator(DCScope
, D
, DC
, TInfo
, Previous
,
18075 TemplateParams
, AddToScope
);
18076 if (!ND
) return nullptr;
18078 assert(ND
->getLexicalDeclContext() == CurContext
);
18080 // If we performed typo correction, we might have added a scope specifier
18081 // and changed the decl context.
18082 DC
= ND
->getDeclContext();
18084 // Add the function declaration to the appropriate lookup tables,
18085 // adjusting the redeclarations list as necessary. We don't
18086 // want to do this yet if the friending class is dependent.
18088 // Also update the scope-based lookup if the target context's
18089 // lookup context is in lexical scope.
18090 if (!CurContext
->isDependentContext()) {
18091 DC
= DC
->getRedeclContext();
18092 DC
->makeDeclVisibleInContext(ND
);
18093 if (Scope
*EnclosingScope
= getScopeForDeclContext(S
, DC
))
18094 PushOnScopeChains(ND
, EnclosingScope
, /*AddToContext=*/ false);
18097 FriendDecl
*FrD
= FriendDecl::Create(Context
, CurContext
,
18098 D
.getIdentifierLoc(), ND
,
18099 DS
.getFriendSpecLoc());
18100 FrD
->setAccess(AS_public
);
18101 CurContext
->addDecl(FrD
);
18103 if (ND
->isInvalidDecl()) {
18104 FrD
->setInvalidDecl();
18106 if (DC
->isRecord()) CheckFriendAccess(ND
);
18109 if (FunctionTemplateDecl
*FTD
= dyn_cast
<FunctionTemplateDecl
>(ND
))
18110 FD
= FTD
->getTemplatedDecl();
18112 FD
= cast
<FunctionDecl
>(ND
);
18114 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
18115 // default argument expression, that declaration shall be a definition
18116 // and shall be the only declaration of the function or function
18117 // template in the translation unit.
18118 if (functionDeclHasDefaultArgument(FD
)) {
18119 // We can't look at FD->getPreviousDecl() because it may not have been set
18120 // if we're in a dependent context. If the function is known to be a
18121 // redeclaration, we will have narrowed Previous down to the right decl.
18122 if (D
.isRedeclaration()) {
18123 Diag(FD
->getLocation(), diag::err_friend_decl_with_def_arg_redeclared
);
18124 Diag(Previous
.getRepresentativeDecl()->getLocation(),
18125 diag::note_previous_declaration
);
18126 } else if (!D
.isFunctionDefinition())
18127 Diag(FD
->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def
);
18130 // Mark templated-scope function declarations as unsupported.
18131 if (FD
->getNumTemplateParameterLists() && SS
.isValid()) {
18132 Diag(FD
->getLocation(), diag::warn_template_qualified_friend_unsupported
)
18133 << SS
.getScopeRep() << SS
.getRange()
18134 << cast
<CXXRecordDecl
>(CurContext
);
18135 FrD
->setUnsupportedFriend(true);
18139 warnOnReservedIdentifier(ND
);
18144 void Sema::SetDeclDeleted(Decl
*Dcl
, SourceLocation DelLoc
) {
18145 AdjustDeclIfTemplate(Dcl
);
18147 FunctionDecl
*Fn
= dyn_cast_or_null
<FunctionDecl
>(Dcl
);
18149 Diag(DelLoc
, diag::err_deleted_non_function
);
18153 // Deleted function does not have a body.
18154 Fn
->setWillHaveBody(false);
18156 if (const FunctionDecl
*Prev
= Fn
->getPreviousDecl()) {
18157 // Don't consider the implicit declaration we generate for explicit
18158 // specializations. FIXME: Do not generate these implicit declarations.
18159 if ((Prev
->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
||
18160 Prev
->getPreviousDecl()) &&
18161 !Prev
->isDefined()) {
18162 Diag(DelLoc
, diag::err_deleted_decl_not_first
);
18163 Diag(Prev
->getLocation().isInvalid() ? DelLoc
: Prev
->getLocation(),
18164 Prev
->isImplicit() ? diag::note_previous_implicit_declaration
18165 : diag::note_previous_declaration
);
18166 // We can't recover from this; the declaration might have already
18168 Fn
->setInvalidDecl();
18172 // To maintain the invariant that functions are only deleted on their first
18173 // declaration, mark the implicitly-instantiated declaration of the
18174 // explicitly-specialized function as deleted instead of marking the
18175 // instantiated redeclaration.
18176 Fn
= Fn
->getCanonicalDecl();
18179 // dllimport/dllexport cannot be deleted.
18180 if (const InheritableAttr
*DLLAttr
= getDLLAttr(Fn
)) {
18181 Diag(Fn
->getLocation(), diag::err_attribute_dll_deleted
) << DLLAttr
;
18182 Fn
->setInvalidDecl();
18185 // C++11 [basic.start.main]p3:
18186 // A program that defines main as deleted [...] is ill-formed.
18188 Diag(DelLoc
, diag::err_deleted_main
);
18190 // C++11 [dcl.fct.def.delete]p4:
18191 // A deleted function is implicitly inline.
18192 Fn
->setImplicitlyInline();
18193 Fn
->setDeletedAsWritten();
18196 void Sema::SetDeclDefaulted(Decl
*Dcl
, SourceLocation DefaultLoc
) {
18197 if (!Dcl
|| Dcl
->isInvalidDecl())
18200 auto *FD
= dyn_cast
<FunctionDecl
>(Dcl
);
18202 if (auto *FTD
= dyn_cast
<FunctionTemplateDecl
>(Dcl
)) {
18203 if (getDefaultedFunctionKind(FTD
->getTemplatedDecl()).isComparison()) {
18204 Diag(DefaultLoc
, diag::err_defaulted_comparison_template
);
18209 Diag(DefaultLoc
, diag::err_default_special_members
)
18210 << getLangOpts().CPlusPlus20
;
18214 // Reject if this can't possibly be a defaultable function.
18215 DefaultedFunctionKind DefKind
= getDefaultedFunctionKind(FD
);
18217 // A dependent function that doesn't locally look defaultable can
18218 // still instantiate to a defaultable function if it's a constructor
18219 // or assignment operator.
18220 (!FD
->isDependentContext() ||
18221 (!isa
<CXXConstructorDecl
>(FD
) &&
18222 FD
->getDeclName().getCXXOverloadedOperator() != OO_Equal
))) {
18223 Diag(DefaultLoc
, diag::err_default_special_members
)
18224 << getLangOpts().CPlusPlus20
;
18228 // Issue compatibility warning. We already warned if the operator is
18229 // 'operator<=>' when parsing the '<=>' token.
18230 if (DefKind
.isComparison() &&
18231 DefKind
.asComparison() != DefaultedComparisonKind::ThreeWay
) {
18232 Diag(DefaultLoc
, getLangOpts().CPlusPlus20
18233 ? diag::warn_cxx17_compat_defaulted_comparison
18234 : diag::ext_defaulted_comparison
);
18237 FD
->setDefaulted();
18238 FD
->setExplicitlyDefaulted();
18239 FD
->setDefaultLoc(DefaultLoc
);
18241 // Defer checking functions that are defaulted in a dependent context.
18242 if (FD
->isDependentContext())
18245 // Unset that we will have a body for this function. We might not,
18246 // if it turns out to be trivial, and we don't need this marking now
18247 // that we've marked it as defaulted.
18248 FD
->setWillHaveBody(false);
18250 if (DefKind
.isComparison()) {
18251 // If this comparison's defaulting occurs within the definition of its
18252 // lexical class context, we have to do the checking when complete.
18253 if (auto const *RD
= dyn_cast
<CXXRecordDecl
>(FD
->getLexicalDeclContext()))
18254 if (!RD
->isCompleteDefinition())
18258 // If this member fn was defaulted on its first declaration, we will have
18259 // already performed the checking in CheckCompletedCXXClass. Such a
18260 // declaration doesn't trigger an implicit definition.
18261 if (isa
<CXXMethodDecl
>(FD
)) {
18262 const FunctionDecl
*Primary
= FD
;
18263 if (const FunctionDecl
*Pattern
= FD
->getTemplateInstantiationPattern())
18264 // Ask the template instantiation pattern that actually had the
18265 // '= default' on it.
18267 if (Primary
->getCanonicalDecl()->isDefaulted())
18271 if (DefKind
.isComparison()) {
18272 if (CheckExplicitlyDefaultedComparison(nullptr, FD
, DefKind
.asComparison()))
18273 FD
->setInvalidDecl();
18275 DefineDefaultedComparison(DefaultLoc
, FD
, DefKind
.asComparison());
18277 auto *MD
= cast
<CXXMethodDecl
>(FD
);
18279 if (CheckExplicitlyDefaultedSpecialMember(MD
, DefKind
.asSpecialMember(),
18281 MD
->setInvalidDecl();
18283 DefineDefaultedFunction(*this, MD
, DefaultLoc
);
18287 static void SearchForReturnInStmt(Sema
&Self
, Stmt
*S
) {
18288 for (Stmt
*SubStmt
: S
->children()) {
18291 if (isa
<ReturnStmt
>(SubStmt
))
18292 Self
.Diag(SubStmt
->getBeginLoc(),
18293 diag::err_return_in_constructor_handler
);
18294 if (!isa
<Expr
>(SubStmt
))
18295 SearchForReturnInStmt(Self
, SubStmt
);
18299 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt
*TryBlock
) {
18300 for (unsigned I
= 0, E
= TryBlock
->getNumHandlers(); I
!= E
; ++I
) {
18301 CXXCatchStmt
*Handler
= TryBlock
->getHandler(I
);
18302 SearchForReturnInStmt(*this, Handler
);
18306 void Sema::SetFunctionBodyKind(Decl
*D
, SourceLocation Loc
,
18307 FnBodyKind BodyKind
) {
18308 switch (BodyKind
) {
18309 case FnBodyKind::Delete
:
18310 SetDeclDeleted(D
, Loc
);
18312 case FnBodyKind::Default
:
18313 SetDeclDefaulted(D
, Loc
);
18315 case FnBodyKind::Other
:
18317 "Parsed function body should be '= delete;' or '= default;'");
18321 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl
*New
,
18322 const CXXMethodDecl
*Old
) {
18323 const auto *NewFT
= New
->getType()->castAs
<FunctionProtoType
>();
18324 const auto *OldFT
= Old
->getType()->castAs
<FunctionProtoType
>();
18326 if (OldFT
->hasExtParameterInfos()) {
18327 for (unsigned I
= 0, E
= OldFT
->getNumParams(); I
!= E
; ++I
)
18328 // A parameter of the overriding method should be annotated with noescape
18329 // if the corresponding parameter of the overridden method is annotated.
18330 if (OldFT
->getExtParameterInfo(I
).isNoEscape() &&
18331 !NewFT
->getExtParameterInfo(I
).isNoEscape()) {
18332 Diag(New
->getParamDecl(I
)->getLocation(),
18333 diag::warn_overriding_method_missing_noescape
);
18334 Diag(Old
->getParamDecl(I
)->getLocation(),
18335 diag::note_overridden_marked_noescape
);
18339 // SME attributes must match when overriding a function declaration.
18340 if (IsInvalidSMECallConversion(
18341 Old
->getType(), New
->getType(),
18342 AArch64SMECallConversionKind::MayAddPreservesZA
)) {
18343 Diag(New
->getLocation(), diag::err_conflicting_overriding_attributes
)
18344 << New
<< New
->getType() << Old
->getType();
18345 Diag(Old
->getLocation(), diag::note_overridden_virtual_function
);
18349 // Virtual overrides must have the same code_seg.
18350 const auto *OldCSA
= Old
->getAttr
<CodeSegAttr
>();
18351 const auto *NewCSA
= New
->getAttr
<CodeSegAttr
>();
18352 if ((NewCSA
|| OldCSA
) &&
18353 (!OldCSA
|| !NewCSA
|| NewCSA
->getName() != OldCSA
->getName())) {
18354 Diag(New
->getLocation(), diag::err_mismatched_code_seg_override
);
18355 Diag(Old
->getLocation(), diag::note_previous_declaration
);
18359 CallingConv NewCC
= NewFT
->getCallConv(), OldCC
= OldFT
->getCallConv();
18361 // If the calling conventions match, everything is fine
18362 if (NewCC
== OldCC
)
18365 // If the calling conventions mismatch because the new function is static,
18366 // suppress the calling convention mismatch error; the error about static
18367 // function override (err_static_overrides_virtual from
18368 // Sema::CheckFunctionDeclaration) is more clear.
18369 if (New
->getStorageClass() == SC_Static
)
18372 Diag(New
->getLocation(),
18373 diag::err_conflicting_overriding_cc_attributes
)
18374 << New
->getDeclName() << New
->getType() << Old
->getType();
18375 Diag(Old
->getLocation(), diag::note_overridden_virtual_function
);
18379 bool Sema::CheckExplicitObjectOverride(CXXMethodDecl
*New
,
18380 const CXXMethodDecl
*Old
) {
18382 // A virtual function shall not be an explicit object member function.
18383 if (!New
->isExplicitObjectMemberFunction())
18385 Diag(New
->getParamDecl(0)->getBeginLoc(),
18386 diag::err_explicit_object_parameter_nonmember
)
18387 << New
->getSourceRange() << /*virtual*/ 1 << /*IsLambda*/ false;
18388 Diag(Old
->getLocation(), diag::note_overridden_virtual_function
);
18389 New
->setInvalidDecl();
18393 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl
*New
,
18394 const CXXMethodDecl
*Old
) {
18395 QualType NewTy
= New
->getType()->castAs
<FunctionType
>()->getReturnType();
18396 QualType OldTy
= Old
->getType()->castAs
<FunctionType
>()->getReturnType();
18398 if (Context
.hasSameType(NewTy
, OldTy
) ||
18399 NewTy
->isDependentType() || OldTy
->isDependentType())
18402 // Check if the return types are covariant
18403 QualType NewClassTy
, OldClassTy
;
18405 /// Both types must be pointers or references to classes.
18406 if (const PointerType
*NewPT
= NewTy
->getAs
<PointerType
>()) {
18407 if (const PointerType
*OldPT
= OldTy
->getAs
<PointerType
>()) {
18408 NewClassTy
= NewPT
->getPointeeType();
18409 OldClassTy
= OldPT
->getPointeeType();
18411 } else if (const ReferenceType
*NewRT
= NewTy
->getAs
<ReferenceType
>()) {
18412 if (const ReferenceType
*OldRT
= OldTy
->getAs
<ReferenceType
>()) {
18413 if (NewRT
->getTypeClass() == OldRT
->getTypeClass()) {
18414 NewClassTy
= NewRT
->getPointeeType();
18415 OldClassTy
= OldRT
->getPointeeType();
18420 // The return types aren't either both pointers or references to a class type.
18421 if (NewClassTy
.isNull()) {
18422 Diag(New
->getLocation(),
18423 diag::err_different_return_type_for_overriding_virtual_function
)
18424 << New
->getDeclName() << NewTy
<< OldTy
18425 << New
->getReturnTypeSourceRange();
18426 Diag(Old
->getLocation(), diag::note_overridden_virtual_function
)
18427 << Old
->getReturnTypeSourceRange();
18432 if (!Context
.hasSameUnqualifiedType(NewClassTy
, OldClassTy
)) {
18433 // C++14 [class.virtual]p8:
18434 // If the class type in the covariant return type of D::f differs from
18435 // that of B::f, the class type in the return type of D::f shall be
18436 // complete at the point of declaration of D::f or shall be the class
18438 if (const RecordType
*RT
= NewClassTy
->getAs
<RecordType
>()) {
18439 if (!RT
->isBeingDefined() &&
18440 RequireCompleteType(New
->getLocation(), NewClassTy
,
18441 diag::err_covariant_return_incomplete
,
18442 New
->getDeclName()))
18446 // Check if the new class derives from the old class.
18447 if (!IsDerivedFrom(New
->getLocation(), NewClassTy
, OldClassTy
)) {
18448 Diag(New
->getLocation(), diag::err_covariant_return_not_derived
)
18449 << New
->getDeclName() << NewTy
<< OldTy
18450 << New
->getReturnTypeSourceRange();
18451 Diag(Old
->getLocation(), diag::note_overridden_virtual_function
)
18452 << Old
->getReturnTypeSourceRange();
18456 // Check if we the conversion from derived to base is valid.
18457 if (CheckDerivedToBaseConversion(
18458 NewClassTy
, OldClassTy
,
18459 diag::err_covariant_return_inaccessible_base
,
18460 diag::err_covariant_return_ambiguous_derived_to_base_conv
,
18461 New
->getLocation(), New
->getReturnTypeSourceRange(),
18462 New
->getDeclName(), nullptr)) {
18463 // FIXME: this note won't trigger for delayed access control
18464 // diagnostics, and it's impossible to get an undelayed error
18465 // here from access control during the original parse because
18466 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
18467 Diag(Old
->getLocation(), diag::note_overridden_virtual_function
)
18468 << Old
->getReturnTypeSourceRange();
18473 // The qualifiers of the return types must be the same.
18474 if (NewTy
.getLocalCVRQualifiers() != OldTy
.getLocalCVRQualifiers()) {
18475 Diag(New
->getLocation(),
18476 diag::err_covariant_return_type_different_qualifications
)
18477 << New
->getDeclName() << NewTy
<< OldTy
18478 << New
->getReturnTypeSourceRange();
18479 Diag(Old
->getLocation(), diag::note_overridden_virtual_function
)
18480 << Old
->getReturnTypeSourceRange();
18485 // The new class type must have the same or less qualifiers as the old type.
18486 if (NewClassTy
.isMoreQualifiedThan(OldClassTy
)) {
18487 Diag(New
->getLocation(),
18488 diag::err_covariant_return_type_class_type_more_qualified
)
18489 << New
->getDeclName() << NewTy
<< OldTy
18490 << New
->getReturnTypeSourceRange();
18491 Diag(Old
->getLocation(), diag::note_overridden_virtual_function
)
18492 << Old
->getReturnTypeSourceRange();
18499 /// Mark the given method pure.
18501 /// \param Method the method to be marked pure.
18503 /// \param InitRange the source range that covers the "0" initializer.
18504 bool Sema::CheckPureMethod(CXXMethodDecl
*Method
, SourceRange InitRange
) {
18505 SourceLocation EndLoc
= InitRange
.getEnd();
18506 if (EndLoc
.isValid())
18507 Method
->setRangeEnd(EndLoc
);
18509 if (Method
->isVirtual() || Method
->getParent()->isDependentContext()) {
18514 if (!Method
->isInvalidDecl())
18515 Diag(Method
->getLocation(), diag::err_non_virtual_pure
)
18516 << Method
->getDeclName() << InitRange
;
18520 void Sema::ActOnPureSpecifier(Decl
*D
, SourceLocation ZeroLoc
) {
18521 if (D
->getFriendObjectKind())
18522 Diag(D
->getLocation(), diag::err_pure_friend
);
18523 else if (auto *M
= dyn_cast
<CXXMethodDecl
>(D
))
18524 CheckPureMethod(M
, ZeroLoc
);
18526 Diag(D
->getLocation(), diag::err_illegal_initializer
);
18529 /// Determine whether the given declaration is a global variable or
18530 /// static data member.
18531 static bool isNonlocalVariable(const Decl
*D
) {
18532 if (const VarDecl
*Var
= dyn_cast_or_null
<VarDecl
>(D
))
18533 return Var
->hasGlobalStorage();
18538 /// Invoked when we are about to parse an initializer for the declaration
18541 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
18542 /// static data member of class X, names should be looked up in the scope of
18543 /// class X. If the declaration had a scope specifier, a scope will have
18544 /// been created and passed in for this purpose. Otherwise, S will be null.
18545 void Sema::ActOnCXXEnterDeclInitializer(Scope
*S
, Decl
*D
) {
18546 // If there is no declaration, there was an error parsing it.
18547 if (!D
|| D
->isInvalidDecl())
18550 // We will always have a nested name specifier here, but this declaration
18551 // might not be out of line if the specifier names the current namespace:
18554 if (S
&& D
->isOutOfLine())
18555 EnterDeclaratorContext(S
, D
->getDeclContext());
18557 // If we are parsing the initializer for a static data member, push a
18558 // new expression evaluation context that is associated with this static
18560 if (isNonlocalVariable(D
))
18561 PushExpressionEvaluationContext(
18562 ExpressionEvaluationContext::PotentiallyEvaluated
, D
);
18565 /// Invoked after we are finished parsing an initializer for the declaration D.
18566 void Sema::ActOnCXXExitDeclInitializer(Scope
*S
, Decl
*D
) {
18567 // If there is no declaration, there was an error parsing it.
18568 if (!D
|| D
->isInvalidDecl())
18571 if (isNonlocalVariable(D
))
18572 PopExpressionEvaluationContext();
18574 if (S
&& D
->isOutOfLine())
18575 ExitDeclaratorContext(S
);
18578 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
18579 /// C++ if/switch/while/for statement.
18580 /// e.g: "if (int x = f()) {...}"
18581 DeclResult
Sema::ActOnCXXConditionDeclaration(Scope
*S
, Declarator
&D
) {
18583 // The declarator shall not specify a function or an array.
18584 // The type-specifier-seq shall not contain typedef and shall not declare a
18585 // new class or enumeration.
18586 assert(D
.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef
&&
18587 "Parser allowed 'typedef' as storage class of condition decl.");
18589 Decl
*Dcl
= ActOnDeclarator(S
, D
);
18593 if (isa
<FunctionDecl
>(Dcl
)) { // The declarator shall not specify a function.
18594 Diag(Dcl
->getLocation(), diag::err_invalid_use_of_function_type
)
18595 << D
.getSourceRange();
18602 void Sema::LoadExternalVTableUses() {
18603 if (!ExternalSource
)
18606 SmallVector
<ExternalVTableUse
, 4> VTables
;
18607 ExternalSource
->ReadUsedVTables(VTables
);
18608 SmallVector
<VTableUse
, 4> NewUses
;
18609 for (unsigned I
= 0, N
= VTables
.size(); I
!= N
; ++I
) {
18610 llvm::DenseMap
<CXXRecordDecl
*, bool>::iterator Pos
18611 = VTablesUsed
.find(VTables
[I
].Record
);
18612 // Even if a definition wasn't required before, it may be required now.
18613 if (Pos
!= VTablesUsed
.end()) {
18614 if (!Pos
->second
&& VTables
[I
].DefinitionRequired
)
18615 Pos
->second
= true;
18619 VTablesUsed
[VTables
[I
].Record
] = VTables
[I
].DefinitionRequired
;
18620 NewUses
.push_back(VTableUse(VTables
[I
].Record
, VTables
[I
].Location
));
18623 VTableUses
.insert(VTableUses
.begin(), NewUses
.begin(), NewUses
.end());
18626 void Sema::MarkVTableUsed(SourceLocation Loc
, CXXRecordDecl
*Class
,
18627 bool DefinitionRequired
) {
18628 // Ignore any vtable uses in unevaluated operands or for classes that do
18629 // not have a vtable.
18630 if (!Class
->isDynamicClass() || Class
->isDependentContext() ||
18631 CurContext
->isDependentContext() || isUnevaluatedContext())
18633 // Do not mark as used if compiling for the device outside of the target
18635 if (TUKind
!= TU_Prefix
&& LangOpts
.OpenMP
&& LangOpts
.OpenMPIsTargetDevice
&&
18636 !isInOpenMPDeclareTargetContext() &&
18637 !isInOpenMPTargetExecutionDirective()) {
18638 if (!DefinitionRequired
)
18639 MarkVirtualMembersReferenced(Loc
, Class
);
18643 // Try to insert this class into the map.
18644 LoadExternalVTableUses();
18645 Class
= Class
->getCanonicalDecl();
18646 std::pair
<llvm::DenseMap
<CXXRecordDecl
*, bool>::iterator
, bool>
18647 Pos
= VTablesUsed
.insert(std::make_pair(Class
, DefinitionRequired
));
18649 // If we already had an entry, check to see if we are promoting this vtable
18650 // to require a definition. If so, we need to reappend to the VTableUses
18651 // list, since we may have already processed the first entry.
18652 if (DefinitionRequired
&& !Pos
.first
->second
) {
18653 Pos
.first
->second
= true;
18655 // Otherwise, we can early exit.
18659 // The Microsoft ABI requires that we perform the destructor body
18660 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
18661 // the deleting destructor is emitted with the vtable, not with the
18662 // destructor definition as in the Itanium ABI.
18663 if (Context
.getTargetInfo().getCXXABI().isMicrosoft()) {
18664 CXXDestructorDecl
*DD
= Class
->getDestructor();
18665 if (DD
&& DD
->isVirtual() && !DD
->isDeleted()) {
18666 if (Class
->hasUserDeclaredDestructor() && !DD
->isDefined()) {
18667 // If this is an out-of-line declaration, marking it referenced will
18668 // not do anything. Manually call CheckDestructor to look up operator
18670 ContextRAII
SavedContext(*this, DD
);
18671 CheckDestructor(DD
);
18673 MarkFunctionReferenced(Loc
, Class
->getDestructor());
18679 // Local classes need to have their virtual members marked
18680 // immediately. For all other classes, we mark their virtual members
18681 // at the end of the translation unit.
18682 if (Class
->isLocalClass())
18683 MarkVirtualMembersReferenced(Loc
, Class
->getDefinition());
18685 VTableUses
.push_back(std::make_pair(Class
, Loc
));
18688 bool Sema::DefineUsedVTables() {
18689 LoadExternalVTableUses();
18690 if (VTableUses
.empty())
18693 // Note: The VTableUses vector could grow as a result of marking
18694 // the members of a class as "used", so we check the size each
18695 // time through the loop and prefer indices (which are stable) to
18696 // iterators (which are not).
18697 bool DefinedAnything
= false;
18698 for (unsigned I
= 0; I
!= VTableUses
.size(); ++I
) {
18699 CXXRecordDecl
*Class
= VTableUses
[I
].first
->getDefinition();
18702 TemplateSpecializationKind ClassTSK
=
18703 Class
->getTemplateSpecializationKind();
18705 SourceLocation Loc
= VTableUses
[I
].second
;
18707 bool DefineVTable
= true;
18709 // If this class has a key function, but that key function is
18710 // defined in another translation unit, we don't need to emit the
18711 // vtable even though we're using it.
18712 const CXXMethodDecl
*KeyFunction
= Context
.getCurrentKeyFunction(Class
);
18713 if (KeyFunction
&& !KeyFunction
->hasBody()) {
18714 // The key function is in another translation unit.
18715 DefineVTable
= false;
18716 TemplateSpecializationKind TSK
=
18717 KeyFunction
->getTemplateSpecializationKind();
18718 assert(TSK
!= TSK_ExplicitInstantiationDefinition
&&
18719 TSK
!= TSK_ImplicitInstantiation
&&
18720 "Instantiations don't have key functions");
18722 } else if (!KeyFunction
) {
18723 // If we have a class with no key function that is the subject
18724 // of an explicit instantiation declaration, suppress the
18725 // vtable; it will live with the explicit instantiation
18727 bool IsExplicitInstantiationDeclaration
=
18728 ClassTSK
== TSK_ExplicitInstantiationDeclaration
;
18729 for (auto *R
: Class
->redecls()) {
18730 TemplateSpecializationKind TSK
18731 = cast
<CXXRecordDecl
>(R
)->getTemplateSpecializationKind();
18732 if (TSK
== TSK_ExplicitInstantiationDeclaration
)
18733 IsExplicitInstantiationDeclaration
= true;
18734 else if (TSK
== TSK_ExplicitInstantiationDefinition
) {
18735 IsExplicitInstantiationDeclaration
= false;
18740 if (IsExplicitInstantiationDeclaration
)
18741 DefineVTable
= false;
18744 // The exception specifications for all virtual members may be needed even
18745 // if we are not providing an authoritative form of the vtable in this TU.
18746 // We may choose to emit it available_externally anyway.
18747 if (!DefineVTable
) {
18748 MarkVirtualMemberExceptionSpecsNeeded(Loc
, Class
);
18752 // Mark all of the virtual members of this class as referenced, so
18753 // that we can build a vtable. Then, tell the AST consumer that a
18754 // vtable for this class is required.
18755 DefinedAnything
= true;
18756 MarkVirtualMembersReferenced(Loc
, Class
);
18757 CXXRecordDecl
*Canonical
= Class
->getCanonicalDecl();
18758 if (VTablesUsed
[Canonical
])
18759 Consumer
.HandleVTable(Class
);
18761 // Warn if we're emitting a weak vtable. The vtable will be weak if there is
18762 // no key function or the key function is inlined. Don't warn in C++ ABIs
18763 // that lack key functions, since the user won't be able to make one.
18764 if (Context
.getTargetInfo().getCXXABI().hasKeyFunctions() &&
18765 Class
->isExternallyVisible() && ClassTSK
!= TSK_ImplicitInstantiation
&&
18766 ClassTSK
!= TSK_ExplicitInstantiationDefinition
) {
18767 const FunctionDecl
*KeyFunctionDef
= nullptr;
18768 if (!KeyFunction
|| (KeyFunction
->hasBody(KeyFunctionDef
) &&
18769 KeyFunctionDef
->isInlined()))
18770 Diag(Class
->getLocation(), diag::warn_weak_vtable
) << Class
;
18773 VTableUses
.clear();
18775 return DefinedAnything
;
18778 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc
,
18779 const CXXRecordDecl
*RD
) {
18780 for (const auto *I
: RD
->methods())
18781 if (I
->isVirtual() && !I
->isPure())
18782 ResolveExceptionSpec(Loc
, I
->getType()->castAs
<FunctionProtoType
>());
18785 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc
,
18786 const CXXRecordDecl
*RD
,
18787 bool ConstexprOnly
) {
18788 // Mark all functions which will appear in RD's vtable as used.
18789 CXXFinalOverriderMap FinalOverriders
;
18790 RD
->getFinalOverriders(FinalOverriders
);
18791 for (CXXFinalOverriderMap::const_iterator I
= FinalOverriders
.begin(),
18792 E
= FinalOverriders
.end();
18794 for (OverridingMethods::const_iterator OI
= I
->second
.begin(),
18795 OE
= I
->second
.end();
18797 assert(OI
->second
.size() > 0 && "no final overrider");
18798 CXXMethodDecl
*Overrider
= OI
->second
.front().Method
;
18800 // C++ [basic.def.odr]p2:
18801 // [...] A virtual member function is used if it is not pure. [...]
18802 if (!Overrider
->isPure() && (!ConstexprOnly
|| Overrider
->isConstexpr()))
18803 MarkFunctionReferenced(Loc
, Overrider
);
18807 // Only classes that have virtual bases need a VTT.
18808 if (RD
->getNumVBases() == 0)
18811 for (const auto &I
: RD
->bases()) {
18813 cast
<CXXRecordDecl
>(I
.getType()->castAs
<RecordType
>()->getDecl());
18814 if (Base
->getNumVBases() == 0)
18816 MarkVirtualMembersReferenced(Loc
, Base
);
18820 /// SetIvarInitializers - This routine builds initialization ASTs for the
18821 /// Objective-C implementation whose ivars need be initialized.
18822 void Sema::SetIvarInitializers(ObjCImplementationDecl
*ObjCImplementation
) {
18823 if (!getLangOpts().CPlusPlus
)
18825 if (ObjCInterfaceDecl
*OID
= ObjCImplementation
->getClassInterface()) {
18826 SmallVector
<ObjCIvarDecl
*, 8> ivars
;
18827 CollectIvarsToConstructOrDestruct(OID
, ivars
);
18830 SmallVector
<CXXCtorInitializer
*, 32> AllToInit
;
18831 for (unsigned i
= 0; i
< ivars
.size(); i
++) {
18832 FieldDecl
*Field
= ivars
[i
];
18833 if (Field
->isInvalidDecl())
18836 CXXCtorInitializer
*Member
;
18837 InitializedEntity InitEntity
= InitializedEntity::InitializeMember(Field
);
18838 InitializationKind InitKind
=
18839 InitializationKind::CreateDefault(ObjCImplementation
->getLocation());
18841 InitializationSequence
InitSeq(*this, InitEntity
, InitKind
, std::nullopt
);
18842 ExprResult MemberInit
=
18843 InitSeq
.Perform(*this, InitEntity
, InitKind
, std::nullopt
);
18844 MemberInit
= MaybeCreateExprWithCleanups(MemberInit
);
18845 // Note, MemberInit could actually come back empty if no initialization
18846 // is required (e.g., because it would call a trivial default constructor)
18847 if (!MemberInit
.get() || MemberInit
.isInvalid())
18851 new (Context
) CXXCtorInitializer(Context
, Field
, SourceLocation(),
18853 MemberInit
.getAs
<Expr
>(),
18855 AllToInit
.push_back(Member
);
18857 // Be sure that the destructor is accessible and is marked as referenced.
18858 if (const RecordType
*RecordTy
=
18859 Context
.getBaseElementType(Field
->getType())
18860 ->getAs
<RecordType
>()) {
18861 CXXRecordDecl
*RD
= cast
<CXXRecordDecl
>(RecordTy
->getDecl());
18862 if (CXXDestructorDecl
*Destructor
= LookupDestructor(RD
)) {
18863 MarkFunctionReferenced(Field
->getLocation(), Destructor
);
18864 CheckDestructorAccess(Field
->getLocation(), Destructor
,
18865 PDiag(diag::err_access_dtor_ivar
)
18866 << Context
.getBaseElementType(Field
->getType()));
18870 ObjCImplementation
->setIvarInitializers(Context
,
18871 AllToInit
.data(), AllToInit
.size());
18876 void DelegatingCycleHelper(CXXConstructorDecl
* Ctor
,
18877 llvm::SmallPtrSet
<CXXConstructorDecl
*, 4> &Valid
,
18878 llvm::SmallPtrSet
<CXXConstructorDecl
*, 4> &Invalid
,
18879 llvm::SmallPtrSet
<CXXConstructorDecl
*, 4> &Current
,
18881 if (Ctor
->isInvalidDecl())
18884 CXXConstructorDecl
*Target
= Ctor
->getTargetConstructor();
18886 // Target may not be determinable yet, for instance if this is a dependent
18887 // call in an uninstantiated template.
18889 const FunctionDecl
*FNTarget
= nullptr;
18890 (void)Target
->hasBody(FNTarget
);
18891 Target
= const_cast<CXXConstructorDecl
*>(
18892 cast_or_null
<CXXConstructorDecl
>(FNTarget
));
18895 CXXConstructorDecl
*Canonical
= Ctor
->getCanonicalDecl(),
18896 // Avoid dereferencing a null pointer here.
18897 *TCanonical
= Target
? Target
->getCanonicalDecl() : nullptr;
18899 if (!Current
.insert(Canonical
).second
)
18902 // We know that beyond here, we aren't chaining into a cycle.
18903 if (!Target
|| !Target
->isDelegatingConstructor() ||
18904 Target
->isInvalidDecl() || Valid
.count(TCanonical
)) {
18905 Valid
.insert(Current
.begin(), Current
.end());
18907 // We've hit a cycle.
18908 } else if (TCanonical
== Canonical
|| Invalid
.count(TCanonical
) ||
18909 Current
.count(TCanonical
)) {
18910 // If we haven't diagnosed this cycle yet, do so now.
18911 if (!Invalid
.count(TCanonical
)) {
18912 S
.Diag((*Ctor
->init_begin())->getSourceLocation(),
18913 diag::warn_delegating_ctor_cycle
)
18916 // Don't add a note for a function delegating directly to itself.
18917 if (TCanonical
!= Canonical
)
18918 S
.Diag(Target
->getLocation(), diag::note_it_delegates_to
);
18920 CXXConstructorDecl
*C
= Target
;
18921 while (C
->getCanonicalDecl() != Canonical
) {
18922 const FunctionDecl
*FNTarget
= nullptr;
18923 (void)C
->getTargetConstructor()->hasBody(FNTarget
);
18924 assert(FNTarget
&& "Ctor cycle through bodiless function");
18926 C
= const_cast<CXXConstructorDecl
*>(
18927 cast
<CXXConstructorDecl
>(FNTarget
));
18928 S
.Diag(C
->getLocation(), diag::note_which_delegates_to
);
18932 Invalid
.insert(Current
.begin(), Current
.end());
18935 DelegatingCycleHelper(Target
, Valid
, Invalid
, Current
, S
);
18940 void Sema::CheckDelegatingCtorCycles() {
18941 llvm::SmallPtrSet
<CXXConstructorDecl
*, 4> Valid
, Invalid
, Current
;
18943 for (DelegatingCtorDeclsType::iterator
18944 I
= DelegatingCtorDecls
.begin(ExternalSource
.get()),
18945 E
= DelegatingCtorDecls
.end();
18947 DelegatingCycleHelper(*I
, Valid
, Invalid
, Current
, *this);
18949 for (auto CI
= Invalid
.begin(), CE
= Invalid
.end(); CI
!= CE
; ++CI
)
18950 (*CI
)->setInvalidDecl();
18954 /// AST visitor that finds references to the 'this' expression.
18955 class FindCXXThisExpr
: public RecursiveASTVisitor
<FindCXXThisExpr
> {
18959 explicit FindCXXThisExpr(Sema
&S
) : S(S
) { }
18961 bool VisitCXXThisExpr(CXXThisExpr
*E
) {
18962 S
.Diag(E
->getLocation(), diag::err_this_static_member_func
)
18963 << E
->isImplicit();
18969 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl
*Method
) {
18970 TypeSourceInfo
*TSInfo
= Method
->getTypeSourceInfo();
18974 TypeLoc TL
= TSInfo
->getTypeLoc();
18975 FunctionProtoTypeLoc ProtoTL
= TL
.getAs
<FunctionProtoTypeLoc
>();
18979 // C++11 [expr.prim.general]p3:
18980 // [The expression this] shall not appear before the optional
18981 // cv-qualifier-seq and it shall not appear within the declaration of a
18982 // static member function (although its type and value category are defined
18983 // within a static member function as they are within a non-static member
18984 // function). [ Note: this is because declaration matching does not occur
18985 // until the complete declarator is known. - end note ]
18986 const FunctionProtoType
*Proto
= ProtoTL
.getTypePtr();
18987 FindCXXThisExpr
Finder(*this);
18989 // If the return type came after the cv-qualifier-seq, check it now.
18990 if (Proto
->hasTrailingReturn() &&
18991 !Finder
.TraverseTypeLoc(ProtoTL
.getReturnLoc()))
18994 // Check the exception specification.
18995 if (checkThisInStaticMemberFunctionExceptionSpec(Method
))
18998 // Check the trailing requires clause
18999 if (Expr
*E
= Method
->getTrailingRequiresClause())
19000 if (!Finder
.TraverseStmt(E
))
19003 return checkThisInStaticMemberFunctionAttributes(Method
);
19006 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl
*Method
) {
19007 TypeSourceInfo
*TSInfo
= Method
->getTypeSourceInfo();
19011 TypeLoc TL
= TSInfo
->getTypeLoc();
19012 FunctionProtoTypeLoc ProtoTL
= TL
.getAs
<FunctionProtoTypeLoc
>();
19016 const FunctionProtoType
*Proto
= ProtoTL
.getTypePtr();
19017 FindCXXThisExpr
Finder(*this);
19019 switch (Proto
->getExceptionSpecType()) {
19021 case EST_Uninstantiated
:
19022 case EST_Unevaluated
:
19023 case EST_BasicNoexcept
:
19025 case EST_DynamicNone
:
19030 case EST_DependentNoexcept
:
19031 case EST_NoexceptFalse
:
19032 case EST_NoexceptTrue
:
19033 if (!Finder
.TraverseStmt(Proto
->getNoexceptExpr()))
19038 for (const auto &E
: Proto
->exceptions()) {
19039 if (!Finder
.TraverseType(E
))
19048 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl
*Method
) {
19049 FindCXXThisExpr
Finder(*this);
19051 // Check attributes.
19052 for (const auto *A
: Method
->attrs()) {
19053 // FIXME: This should be emitted by tblgen.
19054 Expr
*Arg
= nullptr;
19055 ArrayRef
<Expr
*> Args
;
19056 if (const auto *G
= dyn_cast
<GuardedByAttr
>(A
))
19058 else if (const auto *G
= dyn_cast
<PtGuardedByAttr
>(A
))
19060 else if (const auto *AA
= dyn_cast
<AcquiredAfterAttr
>(A
))
19061 Args
= llvm::ArrayRef(AA
->args_begin(), AA
->args_size());
19062 else if (const auto *AB
= dyn_cast
<AcquiredBeforeAttr
>(A
))
19063 Args
= llvm::ArrayRef(AB
->args_begin(), AB
->args_size());
19064 else if (const auto *ETLF
= dyn_cast
<ExclusiveTrylockFunctionAttr
>(A
)) {
19065 Arg
= ETLF
->getSuccessValue();
19066 Args
= llvm::ArrayRef(ETLF
->args_begin(), ETLF
->args_size());
19067 } else if (const auto *STLF
= dyn_cast
<SharedTrylockFunctionAttr
>(A
)) {
19068 Arg
= STLF
->getSuccessValue();
19069 Args
= llvm::ArrayRef(STLF
->args_begin(), STLF
->args_size());
19070 } else if (const auto *LR
= dyn_cast
<LockReturnedAttr
>(A
))
19071 Arg
= LR
->getArg();
19072 else if (const auto *LE
= dyn_cast
<LocksExcludedAttr
>(A
))
19073 Args
= llvm::ArrayRef(LE
->args_begin(), LE
->args_size());
19074 else if (const auto *RC
= dyn_cast
<RequiresCapabilityAttr
>(A
))
19075 Args
= llvm::ArrayRef(RC
->args_begin(), RC
->args_size());
19076 else if (const auto *AC
= dyn_cast
<AcquireCapabilityAttr
>(A
))
19077 Args
= llvm::ArrayRef(AC
->args_begin(), AC
->args_size());
19078 else if (const auto *AC
= dyn_cast
<TryAcquireCapabilityAttr
>(A
))
19079 Args
= llvm::ArrayRef(AC
->args_begin(), AC
->args_size());
19080 else if (const auto *RC
= dyn_cast
<ReleaseCapabilityAttr
>(A
))
19081 Args
= llvm::ArrayRef(RC
->args_begin(), RC
->args_size());
19083 if (Arg
&& !Finder
.TraverseStmt(Arg
))
19086 for (unsigned I
= 0, N
= Args
.size(); I
!= N
; ++I
) {
19087 if (!Finder
.TraverseStmt(Args
[I
]))
19095 void Sema::checkExceptionSpecification(
19096 bool IsTopLevel
, ExceptionSpecificationType EST
,
19097 ArrayRef
<ParsedType
> DynamicExceptions
,
19098 ArrayRef
<SourceRange
> DynamicExceptionRanges
, Expr
*NoexceptExpr
,
19099 SmallVectorImpl
<QualType
> &Exceptions
,
19100 FunctionProtoType::ExceptionSpecInfo
&ESI
) {
19101 Exceptions
.clear();
19103 if (EST
== EST_Dynamic
) {
19104 Exceptions
.reserve(DynamicExceptions
.size());
19105 for (unsigned ei
= 0, ee
= DynamicExceptions
.size(); ei
!= ee
; ++ei
) {
19106 // FIXME: Preserve type source info.
19107 QualType ET
= GetTypeFromParser(DynamicExceptions
[ei
]);
19110 SmallVector
<UnexpandedParameterPack
, 2> Unexpanded
;
19111 collectUnexpandedParameterPacks(ET
, Unexpanded
);
19112 if (!Unexpanded
.empty()) {
19113 DiagnoseUnexpandedParameterPacks(
19114 DynamicExceptionRanges
[ei
].getBegin(), UPPC_ExceptionType
,
19120 // Check that the type is valid for an exception spec, and
19122 if (!CheckSpecifiedExceptionType(ET
, DynamicExceptionRanges
[ei
]))
19123 Exceptions
.push_back(ET
);
19125 ESI
.Exceptions
= Exceptions
;
19129 if (isComputedNoexcept(EST
)) {
19130 assert((NoexceptExpr
->isTypeDependent() ||
19131 NoexceptExpr
->getType()->getCanonicalTypeUnqualified() ==
19133 "Parser should have made sure that the expression is boolean");
19134 if (IsTopLevel
&& DiagnoseUnexpandedParameterPack(NoexceptExpr
)) {
19135 ESI
.Type
= EST_BasicNoexcept
;
19139 ESI
.NoexceptExpr
= NoexceptExpr
;
19144 void Sema::actOnDelayedExceptionSpecification(Decl
*MethodD
,
19145 ExceptionSpecificationType EST
,
19146 SourceRange SpecificationRange
,
19147 ArrayRef
<ParsedType
> DynamicExceptions
,
19148 ArrayRef
<SourceRange
> DynamicExceptionRanges
,
19149 Expr
*NoexceptExpr
) {
19153 // Dig out the method we're referring to.
19154 if (FunctionTemplateDecl
*FunTmpl
= dyn_cast
<FunctionTemplateDecl
>(MethodD
))
19155 MethodD
= FunTmpl
->getTemplatedDecl();
19157 CXXMethodDecl
*Method
= dyn_cast
<CXXMethodDecl
>(MethodD
);
19161 // Check the exception specification.
19162 llvm::SmallVector
<QualType
, 4> Exceptions
;
19163 FunctionProtoType::ExceptionSpecInfo ESI
;
19164 checkExceptionSpecification(/*IsTopLevel*/true, EST
, DynamicExceptions
,
19165 DynamicExceptionRanges
, NoexceptExpr
, Exceptions
,
19168 // Update the exception specification on the function type.
19169 Context
.adjustExceptionSpec(Method
, ESI
, /*AsWritten*/true);
19171 if (Method
->isStatic())
19172 checkThisInStaticMemberFunctionExceptionSpec(Method
);
19174 if (Method
->isVirtual()) {
19175 // Check overrides, which we previously had to delay.
19176 for (const CXXMethodDecl
*O
: Method
->overridden_methods())
19177 CheckOverridingFunctionExceptionSpec(Method
, O
);
19181 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
19183 MSPropertyDecl
*Sema::HandleMSProperty(Scope
*S
, RecordDecl
*Record
,
19184 SourceLocation DeclStart
, Declarator
&D
,
19186 InClassInitStyle InitStyle
,
19187 AccessSpecifier AS
,
19188 const ParsedAttr
&MSPropertyAttr
) {
19189 IdentifierInfo
*II
= D
.getIdentifier();
19191 Diag(DeclStart
, diag::err_anonymous_property
);
19194 SourceLocation Loc
= D
.getIdentifierLoc();
19196 TypeSourceInfo
*TInfo
= GetTypeForDeclarator(D
, S
);
19197 QualType T
= TInfo
->getType();
19198 if (getLangOpts().CPlusPlus
) {
19199 CheckExtraCXXDefaultArguments(D
);
19201 if (DiagnoseUnexpandedParameterPack(D
.getIdentifierLoc(), TInfo
,
19202 UPPC_DataMemberType
)) {
19203 D
.setInvalidType();
19205 TInfo
= Context
.getTrivialTypeSourceInfo(T
, Loc
);
19209 DiagnoseFunctionSpecifiers(D
.getDeclSpec());
19211 if (D
.getDeclSpec().isInlineSpecified())
19212 Diag(D
.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function
)
19213 << getLangOpts().CPlusPlus17
;
19214 if (DeclSpec::TSCS TSCS
= D
.getDeclSpec().getThreadStorageClassSpec())
19215 Diag(D
.getDeclSpec().getThreadStorageClassSpecLoc(),
19216 diag::err_invalid_thread
)
19217 << DeclSpec::getSpecifierName(TSCS
);
19219 // Check to see if this name was declared as a member previously
19220 NamedDecl
*PrevDecl
= nullptr;
19221 LookupResult
Previous(*this, II
, Loc
, LookupMemberName
,
19222 ForVisibleRedeclaration
);
19223 LookupName(Previous
, S
);
19224 switch (Previous
.getResultKind()) {
19225 case LookupResult::Found
:
19226 case LookupResult::FoundUnresolvedValue
:
19227 PrevDecl
= Previous
.getAsSingle
<NamedDecl
>();
19230 case LookupResult::FoundOverloaded
:
19231 PrevDecl
= Previous
.getRepresentativeDecl();
19234 case LookupResult::NotFound
:
19235 case LookupResult::NotFoundInCurrentInstantiation
:
19236 case LookupResult::Ambiguous
:
19240 if (PrevDecl
&& PrevDecl
->isTemplateParameter()) {
19241 // Maybe we will complain about the shadowed template parameter.
19242 DiagnoseTemplateParameterShadow(D
.getIdentifierLoc(), PrevDecl
);
19243 // Just pretend that we didn't see the previous declaration.
19244 PrevDecl
= nullptr;
19247 if (PrevDecl
&& !isDeclInScope(PrevDecl
, Record
, S
))
19248 PrevDecl
= nullptr;
19250 SourceLocation TSSL
= D
.getBeginLoc();
19251 MSPropertyDecl
*NewPD
=
19252 MSPropertyDecl::Create(Context
, Record
, Loc
, II
, T
, TInfo
, TSSL
,
19253 MSPropertyAttr
.getPropertyDataGetter(),
19254 MSPropertyAttr
.getPropertyDataSetter());
19255 ProcessDeclAttributes(TUScope
, NewPD
, D
);
19256 NewPD
->setAccess(AS
);
19258 if (NewPD
->isInvalidDecl())
19259 Record
->setInvalidDecl();
19261 if (D
.getDeclSpec().isModulePrivateSpecified())
19262 NewPD
->setModulePrivate();
19264 if (NewPD
->isInvalidDecl() && PrevDecl
) {
19265 // Don't introduce NewFD into scope; there's already something
19266 // with the same name in the same scope.
19268 PushOnScopeChains(NewPD
, S
);
19270 Record
->addDecl(NewPD
);
19275 void Sema::ActOnStartFunctionDeclarationDeclarator(
19276 Declarator
&Declarator
, unsigned TemplateParameterDepth
) {
19277 auto &Info
= InventedParameterInfos
.emplace_back();
19278 TemplateParameterList
*ExplicitParams
= nullptr;
19279 ArrayRef
<TemplateParameterList
*> ExplicitLists
=
19280 Declarator
.getTemplateParameterLists();
19281 if (!ExplicitLists
.empty()) {
19282 bool IsMemberSpecialization
, IsInvalid
;
19283 ExplicitParams
= MatchTemplateParametersToScopeSpecifier(
19284 Declarator
.getBeginLoc(), Declarator
.getIdentifierLoc(),
19285 Declarator
.getCXXScopeSpec(), /*TemplateId=*/nullptr,
19286 ExplicitLists
, /*IsFriend=*/false, IsMemberSpecialization
, IsInvalid
,
19287 /*SuppressDiagnostic=*/true);
19289 if (ExplicitParams
) {
19290 Info
.AutoTemplateParameterDepth
= ExplicitParams
->getDepth();
19291 llvm::append_range(Info
.TemplateParams
, *ExplicitParams
);
19292 Info
.NumExplicitTemplateParams
= ExplicitParams
->size();
19294 Info
.AutoTemplateParameterDepth
= TemplateParameterDepth
;
19295 Info
.NumExplicitTemplateParams
= 0;
19299 void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator
&Declarator
) {
19300 auto &FSI
= InventedParameterInfos
.back();
19301 if (FSI
.TemplateParams
.size() > FSI
.NumExplicitTemplateParams
) {
19302 if (FSI
.NumExplicitTemplateParams
!= 0) {
19303 TemplateParameterList
*ExplicitParams
=
19304 Declarator
.getTemplateParameterLists().back();
19305 Declarator
.setInventedTemplateParameterList(
19306 TemplateParameterList::Create(
19307 Context
, ExplicitParams
->getTemplateLoc(),
19308 ExplicitParams
->getLAngleLoc(), FSI
.TemplateParams
,
19309 ExplicitParams
->getRAngleLoc(),
19310 ExplicitParams
->getRequiresClause()));
19312 Declarator
.setInventedTemplateParameterList(
19313 TemplateParameterList::Create(
19314 Context
, SourceLocation(), SourceLocation(), FSI
.TemplateParams
,
19315 SourceLocation(), /*RequiresClause=*/nullptr));
19318 InventedParameterInfos
.pop_back();