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 TagTypeKind::Struct
:
1786 case TagTypeKind::Interface
:
1788 case TagTypeKind::Class
:
1790 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1794 static bool CheckConstexprFunctionBody(Sema
&SemaRef
, const FunctionDecl
*Dcl
,
1796 Sema::CheckConstexprKind Kind
);
1798 // Check whether a function declaration satisfies the requirements of a
1799 // constexpr function definition or a constexpr constructor definition. If so,
1800 // return true. If not, produce appropriate diagnostics (unless asked not to by
1801 // Kind) and return false.
1803 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1804 bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl
*NewFD
,
1805 CheckConstexprKind Kind
) {
1806 const CXXMethodDecl
*MD
= dyn_cast
<CXXMethodDecl
>(NewFD
);
1807 if (MD
&& MD
->isInstance()) {
1808 // C++11 [dcl.constexpr]p4:
1809 // The definition of a constexpr constructor shall satisfy the following
1811 // - the class shall not have any virtual base classes;
1813 // FIXME: This only applies to constructors and destructors, not arbitrary
1814 // member functions.
1815 const CXXRecordDecl
*RD
= MD
->getParent();
1816 if (RD
->getNumVBases()) {
1817 if (Kind
== CheckConstexprKind::CheckValid
)
1820 Diag(NewFD
->getLocation(), diag::err_constexpr_virtual_base
)
1821 << isa
<CXXConstructorDecl
>(NewFD
)
1822 << getRecordDiagFromTagKind(RD
->getTagKind()) << RD
->getNumVBases();
1823 for (const auto &I
: RD
->vbases())
1824 Diag(I
.getBeginLoc(), diag::note_constexpr_virtual_base_here
)
1825 << I
.getSourceRange();
1830 if (!isa
<CXXConstructorDecl
>(NewFD
)) {
1831 // C++11 [dcl.constexpr]p3:
1832 // The definition of a constexpr function shall satisfy the following
1834 // - it shall not be virtual; (removed in C++20)
1835 const CXXMethodDecl
*Method
= dyn_cast
<CXXMethodDecl
>(NewFD
);
1836 if (Method
&& Method
->isVirtual()) {
1837 if (getLangOpts().CPlusPlus20
) {
1838 if (Kind
== CheckConstexprKind::Diagnose
)
1839 Diag(Method
->getLocation(), diag::warn_cxx17_compat_constexpr_virtual
);
1841 if (Kind
== CheckConstexprKind::CheckValid
)
1844 Method
= Method
->getCanonicalDecl();
1845 Diag(Method
->getLocation(), diag::err_constexpr_virtual
);
1847 // If it's not obvious why this function is virtual, find an overridden
1848 // function which uses the 'virtual' keyword.
1849 const CXXMethodDecl
*WrittenVirtual
= Method
;
1850 while (!WrittenVirtual
->isVirtualAsWritten())
1851 WrittenVirtual
= *WrittenVirtual
->begin_overridden_methods();
1852 if (WrittenVirtual
!= Method
)
1853 Diag(WrittenVirtual
->getLocation(),
1854 diag::note_overridden_virtual_function
);
1859 // - its return type shall be a literal type;
1860 if (!CheckConstexprReturnType(*this, NewFD
, Kind
))
1864 if (auto *Dtor
= dyn_cast
<CXXDestructorDecl
>(NewFD
)) {
1865 // A destructor can be constexpr only if the defaulted destructor could be;
1866 // we don't need to check the members and bases if we already know they all
1867 // have constexpr destructors.
1868 if (!Dtor
->getParent()->defaultedDestructorIsConstexpr()) {
1869 if (Kind
== CheckConstexprKind::CheckValid
)
1871 if (!CheckConstexprDestructorSubobjects(*this, Dtor
, Kind
))
1876 // - each of its parameter types shall be a literal type;
1877 if (!CheckConstexprParameterTypes(*this, NewFD
, Kind
))
1880 Stmt
*Body
= NewFD
->getBody();
1882 "CheckConstexprFunctionDefinition called on function with no body");
1883 return CheckConstexprFunctionBody(*this, NewFD
, Body
, Kind
);
1886 /// Check the given declaration statement is legal within a constexpr function
1887 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1889 /// \return true if the body is OK (maybe only as an extension), false if we
1890 /// have diagnosed a problem.
1891 static bool CheckConstexprDeclStmt(Sema
&SemaRef
, const FunctionDecl
*Dcl
,
1892 DeclStmt
*DS
, SourceLocation
&Cxx1yLoc
,
1893 Sema::CheckConstexprKind Kind
) {
1894 // C++11 [dcl.constexpr]p3 and p4:
1895 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
1897 for (const auto *DclIt
: DS
->decls()) {
1898 switch (DclIt
->getKind()) {
1899 case Decl::StaticAssert
:
1901 case Decl::UsingShadow
:
1902 case Decl::UsingDirective
:
1903 case Decl::UnresolvedUsingTypename
:
1904 case Decl::UnresolvedUsingValue
:
1905 case Decl::UsingEnum
:
1906 // - static_assert-declarations
1907 // - using-declarations,
1908 // - using-directives,
1909 // - using-enum-declaration
1913 case Decl::TypeAlias
: {
1914 // - typedef declarations and alias-declarations that do not define
1915 // classes or enumerations,
1916 const auto *TN
= cast
<TypedefNameDecl
>(DclIt
);
1917 if (TN
->getUnderlyingType()->isVariablyModifiedType()) {
1918 // Don't allow variably-modified types in constexpr functions.
1919 if (Kind
== Sema::CheckConstexprKind::Diagnose
) {
1920 TypeLoc TL
= TN
->getTypeSourceInfo()->getTypeLoc();
1921 SemaRef
.Diag(TL
.getBeginLoc(), diag::err_constexpr_vla
)
1922 << TL
.getSourceRange() << TL
.getType()
1923 << isa
<CXXConstructorDecl
>(Dcl
);
1931 case Decl::CXXRecord
:
1932 // C++1y allows types to be defined, not just declared.
1933 if (cast
<TagDecl
>(DclIt
)->isThisDeclarationADefinition()) {
1934 if (Kind
== Sema::CheckConstexprKind::Diagnose
) {
1935 SemaRef
.Diag(DS
->getBeginLoc(),
1936 SemaRef
.getLangOpts().CPlusPlus14
1937 ? diag::warn_cxx11_compat_constexpr_type_definition
1938 : diag::ext_constexpr_type_definition
)
1939 << isa
<CXXConstructorDecl
>(Dcl
);
1940 } else if (!SemaRef
.getLangOpts().CPlusPlus14
) {
1946 case Decl::EnumConstant
:
1947 case Decl::IndirectField
:
1949 // These can only appear with other declarations which are banned in
1950 // C++11 and permitted in C++1y, so ignore them.
1954 case Decl::Decomposition
: {
1955 // C++1y [dcl.constexpr]p3 allows anything except:
1956 // a definition of a variable of non-literal type or of static or
1957 // thread storage duration or [before C++2a] for which no
1958 // initialization is performed.
1959 const auto *VD
= cast
<VarDecl
>(DclIt
);
1960 if (VD
->isThisDeclarationADefinition()) {
1961 if (VD
->isStaticLocal()) {
1962 if (Kind
== Sema::CheckConstexprKind::Diagnose
) {
1963 SemaRef
.Diag(VD
->getLocation(),
1964 SemaRef
.getLangOpts().CPlusPlus23
1965 ? diag::warn_cxx20_compat_constexpr_var
1966 : diag::ext_constexpr_static_var
)
1967 << isa
<CXXConstructorDecl
>(Dcl
)
1968 << (VD
->getTLSKind() == VarDecl::TLS_Dynamic
);
1969 } else if (!SemaRef
.getLangOpts().CPlusPlus23
) {
1973 if (SemaRef
.LangOpts
.CPlusPlus23
) {
1974 CheckLiteralType(SemaRef
, Kind
, VD
->getLocation(), VD
->getType(),
1975 diag::warn_cxx20_compat_constexpr_var
,
1976 isa
<CXXConstructorDecl
>(Dcl
),
1977 /*variable of non-literal type*/ 2);
1978 } else if (CheckLiteralType(
1979 SemaRef
, Kind
, VD
->getLocation(), VD
->getType(),
1980 diag::err_constexpr_local_var_non_literal_type
,
1981 isa
<CXXConstructorDecl
>(Dcl
))) {
1984 if (!VD
->getType()->isDependentType() &&
1985 !VD
->hasInit() && !VD
->isCXXForRangeDecl()) {
1986 if (Kind
== Sema::CheckConstexprKind::Diagnose
) {
1989 SemaRef
.getLangOpts().CPlusPlus20
1990 ? diag::warn_cxx17_compat_constexpr_local_var_no_init
1991 : diag::ext_constexpr_local_var_no_init
)
1992 << isa
<CXXConstructorDecl
>(Dcl
);
1993 } else if (!SemaRef
.getLangOpts().CPlusPlus20
) {
1999 if (Kind
== Sema::CheckConstexprKind::Diagnose
) {
2000 SemaRef
.Diag(VD
->getLocation(),
2001 SemaRef
.getLangOpts().CPlusPlus14
2002 ? diag::warn_cxx11_compat_constexpr_local_var
2003 : diag::ext_constexpr_local_var
)
2004 << isa
<CXXConstructorDecl
>(Dcl
);
2005 } else if (!SemaRef
.getLangOpts().CPlusPlus14
) {
2011 case Decl::NamespaceAlias
:
2012 case Decl::Function
:
2013 // These are disallowed in C++11 and permitted in C++1y. Allow them
2014 // everywhere as an extension.
2015 if (!Cxx1yLoc
.isValid())
2016 Cxx1yLoc
= DS
->getBeginLoc();
2020 if (Kind
== Sema::CheckConstexprKind::Diagnose
) {
2021 SemaRef
.Diag(DS
->getBeginLoc(), diag::err_constexpr_body_invalid_stmt
)
2022 << isa
<CXXConstructorDecl
>(Dcl
) << Dcl
->isConsteval();
2031 /// Check that the given field is initialized within a constexpr constructor.
2033 /// \param Dcl The constexpr constructor being checked.
2034 /// \param Field The field being checked. This may be a member of an anonymous
2035 /// struct or union nested within the class being checked.
2036 /// \param Inits All declarations, including anonymous struct/union members and
2037 /// indirect members, for which any initialization was provided.
2038 /// \param Diagnosed Whether we've emitted the error message yet. Used to attach
2039 /// multiple notes for different members to the same error.
2040 /// \param Kind Whether we're diagnosing a constructor as written or determining
2041 /// whether the formal requirements are satisfied.
2042 /// \return \c false if we're checking for validity and the constructor does
2043 /// not satisfy the requirements on a constexpr constructor.
2044 static bool CheckConstexprCtorInitializer(Sema
&SemaRef
,
2045 const FunctionDecl
*Dcl
,
2047 llvm::SmallSet
<Decl
*, 16> &Inits
,
2049 Sema::CheckConstexprKind Kind
) {
2050 // In C++20 onwards, there's nothing to check for validity.
2051 if (Kind
== Sema::CheckConstexprKind::CheckValid
&&
2052 SemaRef
.getLangOpts().CPlusPlus20
)
2055 if (Field
->isInvalidDecl())
2058 if (Field
->isUnnamedBitfield())
2061 // Anonymous unions with no variant members and empty anonymous structs do not
2062 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
2063 // indirect fields don't need initializing.
2064 if (Field
->isAnonymousStructOrUnion() &&
2065 (Field
->getType()->isUnionType()
2066 ? !Field
->getType()->getAsCXXRecordDecl()->hasVariantMembers()
2067 : Field
->getType()->getAsCXXRecordDecl()->isEmpty()))
2070 if (!Inits
.count(Field
)) {
2071 if (Kind
== Sema::CheckConstexprKind::Diagnose
) {
2073 SemaRef
.Diag(Dcl
->getLocation(),
2074 SemaRef
.getLangOpts().CPlusPlus20
2075 ? diag::warn_cxx17_compat_constexpr_ctor_missing_init
2076 : diag::ext_constexpr_ctor_missing_init
);
2079 SemaRef
.Diag(Field
->getLocation(),
2080 diag::note_constexpr_ctor_missing_init
);
2081 } else if (!SemaRef
.getLangOpts().CPlusPlus20
) {
2084 } else if (Field
->isAnonymousStructOrUnion()) {
2085 const RecordDecl
*RD
= Field
->getType()->castAs
<RecordType
>()->getDecl();
2086 for (auto *I
: RD
->fields())
2087 // If an anonymous union contains an anonymous struct of which any member
2088 // is initialized, all members must be initialized.
2089 if (!RD
->isUnion() || Inits
.count(I
))
2090 if (!CheckConstexprCtorInitializer(SemaRef
, Dcl
, I
, Inits
, Diagnosed
,
2097 /// Check the provided statement is allowed in a constexpr function
2100 CheckConstexprFunctionStmt(Sema
&SemaRef
, const FunctionDecl
*Dcl
, Stmt
*S
,
2101 SmallVectorImpl
<SourceLocation
> &ReturnStmts
,
2102 SourceLocation
&Cxx1yLoc
, SourceLocation
&Cxx2aLoc
,
2103 SourceLocation
&Cxx2bLoc
,
2104 Sema::CheckConstexprKind Kind
) {
2105 // - its function-body shall be [...] a compound-statement that contains only
2106 switch (S
->getStmtClass()) {
2107 case Stmt::NullStmtClass
:
2108 // - null statements,
2111 case Stmt::DeclStmtClass
:
2112 // - static_assert-declarations
2113 // - using-declarations,
2114 // - using-directives,
2115 // - typedef declarations and alias-declarations that do not define
2116 // classes or enumerations,
2117 if (!CheckConstexprDeclStmt(SemaRef
, Dcl
, cast
<DeclStmt
>(S
), Cxx1yLoc
, Kind
))
2121 case Stmt::ReturnStmtClass
:
2122 // - and exactly one return statement;
2123 if (isa
<CXXConstructorDecl
>(Dcl
)) {
2124 // C++1y allows return statements in constexpr constructors.
2125 if (!Cxx1yLoc
.isValid())
2126 Cxx1yLoc
= S
->getBeginLoc();
2130 ReturnStmts
.push_back(S
->getBeginLoc());
2133 case Stmt::AttributedStmtClass
:
2134 // Attributes on a statement don't affect its formal kind and hence don't
2135 // affect its validity in a constexpr function.
2136 return CheckConstexprFunctionStmt(
2137 SemaRef
, Dcl
, cast
<AttributedStmt
>(S
)->getSubStmt(), ReturnStmts
,
2138 Cxx1yLoc
, Cxx2aLoc
, Cxx2bLoc
, Kind
);
2140 case Stmt::CompoundStmtClass
: {
2141 // C++1y allows compound-statements.
2142 if (!Cxx1yLoc
.isValid())
2143 Cxx1yLoc
= S
->getBeginLoc();
2145 CompoundStmt
*CompStmt
= cast
<CompoundStmt
>(S
);
2146 for (auto *BodyIt
: CompStmt
->body()) {
2147 if (!CheckConstexprFunctionStmt(SemaRef
, Dcl
, BodyIt
, ReturnStmts
,
2148 Cxx1yLoc
, Cxx2aLoc
, Cxx2bLoc
, Kind
))
2154 case Stmt::IfStmtClass
: {
2155 // C++1y allows if-statements.
2156 if (!Cxx1yLoc
.isValid())
2157 Cxx1yLoc
= S
->getBeginLoc();
2159 IfStmt
*If
= cast
<IfStmt
>(S
);
2160 if (!CheckConstexprFunctionStmt(SemaRef
, Dcl
, If
->getThen(), ReturnStmts
,
2161 Cxx1yLoc
, Cxx2aLoc
, Cxx2bLoc
, Kind
))
2163 if (If
->getElse() &&
2164 !CheckConstexprFunctionStmt(SemaRef
, Dcl
, If
->getElse(), ReturnStmts
,
2165 Cxx1yLoc
, Cxx2aLoc
, Cxx2bLoc
, Kind
))
2170 case Stmt::WhileStmtClass
:
2171 case Stmt::DoStmtClass
:
2172 case Stmt::ForStmtClass
:
2173 case Stmt::CXXForRangeStmtClass
:
2174 case Stmt::ContinueStmtClass
:
2175 // C++1y allows all of these. We don't allow them as extensions in C++11,
2176 // because they don't make sense without variable mutation.
2177 if (!SemaRef
.getLangOpts().CPlusPlus14
)
2179 if (!Cxx1yLoc
.isValid())
2180 Cxx1yLoc
= S
->getBeginLoc();
2181 for (Stmt
*SubStmt
: S
->children()) {
2183 !CheckConstexprFunctionStmt(SemaRef
, Dcl
, SubStmt
, ReturnStmts
,
2184 Cxx1yLoc
, Cxx2aLoc
, Cxx2bLoc
, Kind
))
2189 case Stmt::SwitchStmtClass
:
2190 case Stmt::CaseStmtClass
:
2191 case Stmt::DefaultStmtClass
:
2192 case Stmt::BreakStmtClass
:
2193 // C++1y allows switch-statements, and since they don't need variable
2194 // mutation, we can reasonably allow them in C++11 as an extension.
2195 if (!Cxx1yLoc
.isValid())
2196 Cxx1yLoc
= S
->getBeginLoc();
2197 for (Stmt
*SubStmt
: S
->children()) {
2199 !CheckConstexprFunctionStmt(SemaRef
, Dcl
, SubStmt
, ReturnStmts
,
2200 Cxx1yLoc
, Cxx2aLoc
, Cxx2bLoc
, Kind
))
2205 case Stmt::LabelStmtClass
:
2206 case Stmt::GotoStmtClass
:
2207 if (Cxx2bLoc
.isInvalid())
2208 Cxx2bLoc
= S
->getBeginLoc();
2209 for (Stmt
*SubStmt
: S
->children()) {
2211 !CheckConstexprFunctionStmt(SemaRef
, Dcl
, SubStmt
, ReturnStmts
,
2212 Cxx1yLoc
, Cxx2aLoc
, Cxx2bLoc
, Kind
))
2217 case Stmt::GCCAsmStmtClass
:
2218 case Stmt::MSAsmStmtClass
:
2219 // C++2a allows inline assembly statements.
2220 case Stmt::CXXTryStmtClass
:
2221 if (Cxx2aLoc
.isInvalid())
2222 Cxx2aLoc
= S
->getBeginLoc();
2223 for (Stmt
*SubStmt
: S
->children()) {
2225 !CheckConstexprFunctionStmt(SemaRef
, Dcl
, SubStmt
, ReturnStmts
,
2226 Cxx1yLoc
, Cxx2aLoc
, Cxx2bLoc
, Kind
))
2231 case Stmt::CXXCatchStmtClass
:
2232 // Do not bother checking the language mode (already covered by the
2233 // try block check).
2234 if (!CheckConstexprFunctionStmt(
2235 SemaRef
, Dcl
, cast
<CXXCatchStmt
>(S
)->getHandlerBlock(), ReturnStmts
,
2236 Cxx1yLoc
, Cxx2aLoc
, Cxx2bLoc
, Kind
))
2244 // C++1y allows expression-statements.
2245 if (!Cxx1yLoc
.isValid())
2246 Cxx1yLoc
= S
->getBeginLoc();
2250 if (Kind
== Sema::CheckConstexprKind::Diagnose
) {
2251 SemaRef
.Diag(S
->getBeginLoc(), diag::err_constexpr_body_invalid_stmt
)
2252 << isa
<CXXConstructorDecl
>(Dcl
) << Dcl
->isConsteval();
2257 /// Check the body for the given constexpr function declaration only contains
2258 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
2260 /// \return true if the body is OK, false if we have found or diagnosed a
2262 static bool CheckConstexprFunctionBody(Sema
&SemaRef
, const FunctionDecl
*Dcl
,
2264 Sema::CheckConstexprKind Kind
) {
2265 SmallVector
<SourceLocation
, 4> ReturnStmts
;
2267 if (isa
<CXXTryStmt
>(Body
)) {
2268 // C++11 [dcl.constexpr]p3:
2269 // The definition of a constexpr function shall satisfy the following
2270 // constraints: [...]
2271 // - its function-body shall be = delete, = default, or a
2272 // compound-statement
2274 // C++11 [dcl.constexpr]p4:
2275 // In the definition of a constexpr constructor, [...]
2276 // - its function-body shall not be a function-try-block;
2278 // This restriction is lifted in C++2a, as long as inner statements also
2279 // apply the general constexpr rules.
2281 case Sema::CheckConstexprKind::CheckValid
:
2282 if (!SemaRef
.getLangOpts().CPlusPlus20
)
2286 case Sema::CheckConstexprKind::Diagnose
:
2287 SemaRef
.Diag(Body
->getBeginLoc(),
2288 !SemaRef
.getLangOpts().CPlusPlus20
2289 ? diag::ext_constexpr_function_try_block_cxx20
2290 : diag::warn_cxx17_compat_constexpr_function_try_block
)
2291 << isa
<CXXConstructorDecl
>(Dcl
);
2296 // - its function-body shall be [...] a compound-statement that contains only
2297 // [... list of cases ...]
2299 // Note that walking the children here is enough to properly check for
2300 // CompoundStmt and CXXTryStmt body.
2301 SourceLocation Cxx1yLoc
, Cxx2aLoc
, Cxx2bLoc
;
2302 for (Stmt
*SubStmt
: Body
->children()) {
2304 !CheckConstexprFunctionStmt(SemaRef
, Dcl
, SubStmt
, ReturnStmts
,
2305 Cxx1yLoc
, Cxx2aLoc
, Cxx2bLoc
, Kind
))
2309 if (Kind
== Sema::CheckConstexprKind::CheckValid
) {
2310 // If this is only valid as an extension, report that we don't satisfy the
2311 // constraints of the current language.
2312 if ((Cxx2bLoc
.isValid() && !SemaRef
.getLangOpts().CPlusPlus23
) ||
2313 (Cxx2aLoc
.isValid() && !SemaRef
.getLangOpts().CPlusPlus20
) ||
2314 (Cxx1yLoc
.isValid() && !SemaRef
.getLangOpts().CPlusPlus17
))
2316 } else if (Cxx2bLoc
.isValid()) {
2317 SemaRef
.Diag(Cxx2bLoc
,
2318 SemaRef
.getLangOpts().CPlusPlus23
2319 ? diag::warn_cxx20_compat_constexpr_body_invalid_stmt
2320 : diag::ext_constexpr_body_invalid_stmt_cxx23
)
2321 << isa
<CXXConstructorDecl
>(Dcl
);
2322 } else if (Cxx2aLoc
.isValid()) {
2323 SemaRef
.Diag(Cxx2aLoc
,
2324 SemaRef
.getLangOpts().CPlusPlus20
2325 ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
2326 : diag::ext_constexpr_body_invalid_stmt_cxx20
)
2327 << isa
<CXXConstructorDecl
>(Dcl
);
2328 } else if (Cxx1yLoc
.isValid()) {
2329 SemaRef
.Diag(Cxx1yLoc
,
2330 SemaRef
.getLangOpts().CPlusPlus14
2331 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
2332 : diag::ext_constexpr_body_invalid_stmt
)
2333 << isa
<CXXConstructorDecl
>(Dcl
);
2336 if (const CXXConstructorDecl
*Constructor
2337 = dyn_cast
<CXXConstructorDecl
>(Dcl
)) {
2338 const CXXRecordDecl
*RD
= Constructor
->getParent();
2340 // - every non-variant non-static data member and base class sub-object
2341 // shall be initialized;
2343 // - if the class is a union having variant members, exactly one of them
2344 // shall be initialized;
2345 if (RD
->isUnion()) {
2346 if (Constructor
->getNumCtorInitializers() == 0 &&
2347 RD
->hasVariantMembers()) {
2348 if (Kind
== Sema::CheckConstexprKind::Diagnose
) {
2351 SemaRef
.getLangOpts().CPlusPlus20
2352 ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init
2353 : diag::ext_constexpr_union_ctor_no_init
);
2354 } else if (!SemaRef
.getLangOpts().CPlusPlus20
) {
2358 } else if (!Constructor
->isDependentContext() &&
2359 !Constructor
->isDelegatingConstructor()) {
2360 assert(RD
->getNumVBases() == 0 && "constexpr ctor with virtual bases");
2362 // Skip detailed checking if we have enough initializers, and we would
2363 // allow at most one initializer per member.
2364 bool AnyAnonStructUnionMembers
= false;
2365 unsigned Fields
= 0;
2366 for (CXXRecordDecl::field_iterator I
= RD
->field_begin(),
2367 E
= RD
->field_end(); I
!= E
; ++I
, ++Fields
) {
2368 if (I
->isAnonymousStructOrUnion()) {
2369 AnyAnonStructUnionMembers
= true;
2374 // - if the class is a union-like class, but is not a union, for each of
2375 // its anonymous union members having variant members, exactly one of
2376 // them shall be initialized;
2377 if (AnyAnonStructUnionMembers
||
2378 Constructor
->getNumCtorInitializers() != RD
->getNumBases() + Fields
) {
2379 // Check initialization of non-static data members. Base classes are
2380 // always initialized so do not need to be checked. Dependent bases
2381 // might not have initializers in the member initializer list.
2382 llvm::SmallSet
<Decl
*, 16> Inits
;
2383 for (const auto *I
: Constructor
->inits()) {
2384 if (FieldDecl
*FD
= I
->getMember())
2386 else if (IndirectFieldDecl
*ID
= I
->getIndirectMember())
2387 Inits
.insert(ID
->chain_begin(), ID
->chain_end());
2390 bool Diagnosed
= false;
2391 for (auto *I
: RD
->fields())
2392 if (!CheckConstexprCtorInitializer(SemaRef
, Dcl
, I
, Inits
, Diagnosed
,
2398 if (ReturnStmts
.empty()) {
2399 // C++1y doesn't require constexpr functions to contain a 'return'
2400 // statement. We still do, unless the return type might be void, because
2401 // otherwise if there's no return statement, the function cannot
2402 // be used in a core constant expression.
2403 bool OK
= SemaRef
.getLangOpts().CPlusPlus14
&&
2404 (Dcl
->getReturnType()->isVoidType() ||
2405 Dcl
->getReturnType()->isDependentType());
2407 case Sema::CheckConstexprKind::Diagnose
:
2408 SemaRef
.Diag(Dcl
->getLocation(),
2409 OK
? diag::warn_cxx11_compat_constexpr_body_no_return
2410 : diag::err_constexpr_body_no_return
)
2411 << Dcl
->isConsteval();
2416 case Sema::CheckConstexprKind::CheckValid
:
2417 // The formal requirements don't include this rule in C++14, even
2418 // though the "must be able to produce a constant expression" rules
2419 // still imply it in some cases.
2420 if (!SemaRef
.getLangOpts().CPlusPlus14
)
2424 } else if (ReturnStmts
.size() > 1) {
2426 case Sema::CheckConstexprKind::Diagnose
:
2429 SemaRef
.getLangOpts().CPlusPlus14
2430 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2431 : diag::ext_constexpr_body_multiple_return
);
2432 for (unsigned I
= 0; I
< ReturnStmts
.size() - 1; ++I
)
2433 SemaRef
.Diag(ReturnStmts
[I
],
2434 diag::note_constexpr_body_previous_return
);
2437 case Sema::CheckConstexprKind::CheckValid
:
2438 if (!SemaRef
.getLangOpts().CPlusPlus14
)
2445 // C++11 [dcl.constexpr]p5:
2446 // if no function argument values exist such that the function invocation
2447 // substitution would produce a constant expression, the program is
2448 // ill-formed; no diagnostic required.
2449 // C++11 [dcl.constexpr]p3:
2450 // - every constructor call and implicit conversion used in initializing the
2451 // return value shall be one of those allowed in a constant expression.
2452 // C++11 [dcl.constexpr]p4:
2453 // - every constructor involved in initializing non-static data members and
2454 // base class sub-objects shall be a constexpr constructor.
2456 // Note that this rule is distinct from the "requirements for a constexpr
2457 // function", so is not checked in CheckValid mode.
2458 SmallVector
<PartialDiagnosticAt
, 8> Diags
;
2459 if (Kind
== Sema::CheckConstexprKind::Diagnose
&&
2460 !Expr::isPotentialConstantExpr(Dcl
, Diags
)) {
2461 SemaRef
.Diag(Dcl
->getLocation(),
2462 diag::ext_constexpr_function_never_constant_expr
)
2463 << isa
<CXXConstructorDecl
>(Dcl
) << Dcl
->isConsteval()
2464 << Dcl
->getNameInfo().getSourceRange();
2465 for (size_t I
= 0, N
= Diags
.size(); I
!= N
; ++I
)
2466 SemaRef
.Diag(Diags
[I
].first
, Diags
[I
].second
);
2467 // Don't return false here: we allow this for compatibility in
2474 bool Sema::CheckImmediateEscalatingFunctionDefinition(
2475 FunctionDecl
*FD
, const sema::FunctionScopeInfo
*FSI
) {
2476 if (!getLangOpts().CPlusPlus20
|| !FD
->isImmediateEscalating())
2478 FD
->setBodyContainsImmediateEscalatingExpressions(
2479 FSI
->FoundImmediateEscalatingExpression
);
2480 if (FSI
->FoundImmediateEscalatingExpression
) {
2481 auto it
= UndefinedButUsed
.find(FD
->getCanonicalDecl());
2482 if (it
!= UndefinedButUsed
.end()) {
2483 Diag(it
->second
, diag::err_immediate_function_used_before_definition
)
2485 Diag(FD
->getLocation(), diag::note_defined_here
) << FD
;
2486 if (FD
->isImmediateFunction() && !FD
->isConsteval())
2487 DiagnoseImmediateEscalatingReason(FD
);
2494 void Sema::DiagnoseImmediateEscalatingReason(FunctionDecl
*FD
) {
2495 assert(FD
->isImmediateEscalating() && !FD
->isConsteval() &&
2496 "expected an immediate function");
2497 assert(FD
->hasBody() && "expected the function to have a body");
2498 struct ImmediateEscalatingExpressionsVisitor
2499 : public RecursiveASTVisitor
<ImmediateEscalatingExpressionsVisitor
> {
2501 using Base
= RecursiveASTVisitor
<ImmediateEscalatingExpressionsVisitor
>;
2504 const FunctionDecl
*ImmediateFn
;
2505 bool ImmediateFnIsConstructor
;
2506 CXXConstructorDecl
*CurrentConstructor
= nullptr;
2507 CXXCtorInitializer
*CurrentInit
= nullptr;
2509 ImmediateEscalatingExpressionsVisitor(Sema
&SemaRef
, FunctionDecl
*FD
)
2510 : SemaRef(SemaRef
), ImmediateFn(FD
),
2511 ImmediateFnIsConstructor(isa
<CXXConstructorDecl
>(FD
)) {}
2513 bool shouldVisitImplicitCode() const { return true; }
2514 bool shouldVisitLambdaBody() const { return false; }
2516 void Diag(const Expr
*E
, const FunctionDecl
*Fn
, bool IsCall
) {
2517 SourceLocation Loc
= E
->getBeginLoc();
2518 SourceRange Range
= E
->getSourceRange();
2519 if (CurrentConstructor
&& CurrentInit
) {
2520 Loc
= CurrentConstructor
->getLocation();
2521 Range
= CurrentInit
->isWritten() ? CurrentInit
->getSourceRange()
2525 FieldDecl
* InitializedField
= CurrentInit
? CurrentInit
->getAnyMember() : nullptr;
2527 SemaRef
.Diag(Loc
, diag::note_immediate_function_reason
)
2528 << ImmediateFn
<< Fn
<< Fn
->isConsteval() << IsCall
2529 << isa
<CXXConstructorDecl
>(Fn
) << ImmediateFnIsConstructor
2530 << (InitializedField
!= nullptr)
2531 << (CurrentInit
&& !CurrentInit
->isWritten())
2532 << InitializedField
<< Range
;
2534 bool TraverseCallExpr(CallExpr
*E
) {
2535 if (const auto *DR
=
2536 dyn_cast
<DeclRefExpr
>(E
->getCallee()->IgnoreImplicit());
2537 DR
&& DR
->isImmediateEscalating()) {
2538 Diag(E
, E
->getDirectCallee(), /*IsCall=*/true);
2542 for (Expr
*A
: E
->arguments())
2543 if (!getDerived().TraverseStmt(A
))
2549 bool VisitDeclRefExpr(DeclRefExpr
*E
) {
2550 if (const auto *ReferencedFn
= dyn_cast
<FunctionDecl
>(E
->getDecl());
2551 ReferencedFn
&& E
->isImmediateEscalating()) {
2552 Diag(E
, ReferencedFn
, /*IsCall=*/false);
2559 bool VisitCXXConstructExpr(CXXConstructExpr
*E
) {
2560 CXXConstructorDecl
*D
= E
->getConstructor();
2561 if (E
->isImmediateEscalating()) {
2562 Diag(E
, D
, /*IsCall=*/true);
2568 bool TraverseConstructorInitializer(CXXCtorInitializer
*Init
) {
2569 llvm::SaveAndRestore
RAII(CurrentInit
, Init
);
2570 return Base::TraverseConstructorInitializer(Init
);
2573 bool TraverseCXXConstructorDecl(CXXConstructorDecl
*Ctr
) {
2574 llvm::SaveAndRestore
RAII(CurrentConstructor
, Ctr
);
2575 return Base::TraverseCXXConstructorDecl(Ctr
);
2578 bool TraverseType(QualType T
) { return true; }
2579 bool VisitBlockExpr(BlockExpr
*T
) { return true; }
2581 } Visitor(*this, FD
);
2582 Visitor
.TraverseDecl(FD
);
2585 /// Get the class that is directly named by the current context. This is the
2586 /// class for which an unqualified-id in this scope could name a constructor
2589 /// If the scope specifier denotes a class, this will be that class.
2590 /// If the scope specifier is empty, this will be the class whose
2591 /// member-specification we are currently within. Otherwise, there
2592 /// is no such class.
2593 CXXRecordDecl
*Sema::getCurrentClass(Scope
*, const CXXScopeSpec
*SS
) {
2594 assert(getLangOpts().CPlusPlus
&& "No class names in C!");
2596 if (SS
&& SS
->isInvalid())
2599 if (SS
&& SS
->isNotEmpty()) {
2600 DeclContext
*DC
= computeDeclContext(*SS
, true);
2601 return dyn_cast_or_null
<CXXRecordDecl
>(DC
);
2604 return dyn_cast_or_null
<CXXRecordDecl
>(CurContext
);
2607 /// isCurrentClassName - Determine whether the identifier II is the
2608 /// name of the class type currently being defined. In the case of
2609 /// nested classes, this will only return true if II is the name of
2610 /// the innermost class.
2611 bool Sema::isCurrentClassName(const IdentifierInfo
&II
, Scope
*S
,
2612 const CXXScopeSpec
*SS
) {
2613 CXXRecordDecl
*CurDecl
= getCurrentClass(S
, SS
);
2614 return CurDecl
&& &II
== CurDecl
->getIdentifier();
2617 /// Determine whether the identifier II is a typo for the name of
2618 /// the class type currently being defined. If so, update it to the identifier
2619 /// that should have been used.
2620 bool Sema::isCurrentClassNameTypo(IdentifierInfo
*&II
, const CXXScopeSpec
*SS
) {
2621 assert(getLangOpts().CPlusPlus
&& "No class names in C!");
2623 if (!getLangOpts().SpellChecking
)
2626 CXXRecordDecl
*CurDecl
;
2627 if (SS
&& SS
->isSet() && !SS
->isInvalid()) {
2628 DeclContext
*DC
= computeDeclContext(*SS
, true);
2629 CurDecl
= dyn_cast_or_null
<CXXRecordDecl
>(DC
);
2631 CurDecl
= dyn_cast_or_null
<CXXRecordDecl
>(CurContext
);
2633 if (CurDecl
&& CurDecl
->getIdentifier() && II
!= CurDecl
->getIdentifier() &&
2634 3 * II
->getName().edit_distance(CurDecl
->getIdentifier()->getName())
2635 < II
->getLength()) {
2636 II
= CurDecl
->getIdentifier();
2643 /// Determine whether the given class is a base class of the given
2644 /// class, including looking at dependent bases.
2645 static bool findCircularInheritance(const CXXRecordDecl
*Class
,
2646 const CXXRecordDecl
*Current
) {
2647 SmallVector
<const CXXRecordDecl
*, 8> Queue
;
2649 Class
= Class
->getCanonicalDecl();
2651 for (const auto &I
: Current
->bases()) {
2652 CXXRecordDecl
*Base
= I
.getType()->getAsCXXRecordDecl();
2656 Base
= Base
->getDefinition();
2660 if (Base
->getCanonicalDecl() == Class
)
2663 Queue
.push_back(Base
);
2669 Current
= Queue
.pop_back_val();
2675 /// Check the validity of a C++ base class specifier.
2677 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2678 /// and returns NULL otherwise.
2680 Sema::CheckBaseSpecifier(CXXRecordDecl
*Class
,
2681 SourceRange SpecifierRange
,
2682 bool Virtual
, AccessSpecifier Access
,
2683 TypeSourceInfo
*TInfo
,
2684 SourceLocation EllipsisLoc
) {
2685 // In HLSL, unspecified class access is public rather than private.
2686 if (getLangOpts().HLSL
&& Class
->getTagKind() == TagTypeKind::Class
&&
2690 QualType BaseType
= TInfo
->getType();
2691 if (BaseType
->containsErrors()) {
2692 // Already emitted a diagnostic when parsing the error type.
2695 // C++ [class.union]p1:
2696 // A union shall not have base classes.
2697 if (Class
->isUnion()) {
2698 Diag(Class
->getLocation(), diag::err_base_clause_on_union
)
2703 if (EllipsisLoc
.isValid() &&
2704 !TInfo
->getType()->containsUnexpandedParameterPack()) {
2705 Diag(EllipsisLoc
, diag::err_pack_expansion_without_parameter_packs
)
2706 << TInfo
->getTypeLoc().getSourceRange();
2707 EllipsisLoc
= SourceLocation();
2710 SourceLocation BaseLoc
= TInfo
->getTypeLoc().getBeginLoc();
2712 if (BaseType
->isDependentType()) {
2713 // Make sure that we don't have circular inheritance among our dependent
2714 // bases. For non-dependent bases, the check for completeness below handles
2716 if (CXXRecordDecl
*BaseDecl
= BaseType
->getAsCXXRecordDecl()) {
2717 if (BaseDecl
->getCanonicalDecl() == Class
->getCanonicalDecl() ||
2718 ((BaseDecl
= BaseDecl
->getDefinition()) &&
2719 findCircularInheritance(Class
, BaseDecl
))) {
2720 Diag(BaseLoc
, diag::err_circular_inheritance
)
2721 << BaseType
<< Context
.getTypeDeclType(Class
);
2723 if (BaseDecl
->getCanonicalDecl() != Class
->getCanonicalDecl())
2724 Diag(BaseDecl
->getLocation(), diag::note_previous_decl
)
2731 // Make sure that we don't make an ill-formed AST where the type of the
2732 // Class is non-dependent and its attached base class specifier is an
2733 // dependent type, which violates invariants in many clang code paths (e.g.
2734 // constexpr evaluator). If this case happens (in errory-recovery mode), we
2735 // explicitly mark the Class decl invalid. The diagnostic was already
2737 if (!Class
->getTypeForDecl()->isDependentType())
2738 Class
->setInvalidDecl();
2739 return new (Context
) CXXBaseSpecifier(
2740 SpecifierRange
, Virtual
, Class
->getTagKind() == TagTypeKind::Class
,
2741 Access
, TInfo
, EllipsisLoc
);
2744 // Base specifiers must be record types.
2745 if (!BaseType
->isRecordType()) {
2746 Diag(BaseLoc
, diag::err_base_must_be_class
) << SpecifierRange
;
2750 // C++ [class.union]p1:
2751 // A union shall not be used as a base class.
2752 if (BaseType
->isUnionType()) {
2753 Diag(BaseLoc
, diag::err_union_as_base_class
) << SpecifierRange
;
2757 // For the MS ABI, propagate DLL attributes to base class templates.
2758 if (Context
.getTargetInfo().getCXXABI().isMicrosoft() ||
2759 Context
.getTargetInfo().getTriple().isPS()) {
2760 if (Attr
*ClassAttr
= getDLLAttr(Class
)) {
2761 if (auto *BaseTemplate
= dyn_cast_or_null
<ClassTemplateSpecializationDecl
>(
2762 BaseType
->getAsCXXRecordDecl())) {
2763 propagateDLLAttrToBaseClassTemplate(Class
, ClassAttr
, BaseTemplate
,
2769 // C++ [class.derived]p2:
2770 // The class-name in a base-specifier shall not be an incompletely
2772 if (RequireCompleteType(BaseLoc
, BaseType
,
2773 diag::err_incomplete_base_class
, SpecifierRange
)) {
2774 Class
->setInvalidDecl();
2778 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2779 RecordDecl
*BaseDecl
= BaseType
->castAs
<RecordType
>()->getDecl();
2780 assert(BaseDecl
&& "Record type has no declaration");
2781 BaseDecl
= BaseDecl
->getDefinition();
2782 assert(BaseDecl
&& "Base type is not incomplete, but has no definition");
2783 CXXRecordDecl
*CXXBaseDecl
= cast
<CXXRecordDecl
>(BaseDecl
);
2784 assert(CXXBaseDecl
&& "Base type is not a C++ type");
2786 // Microsoft docs say:
2787 // "If a base-class has a code_seg attribute, derived classes must have the
2789 const auto *BaseCSA
= CXXBaseDecl
->getAttr
<CodeSegAttr
>();
2790 const auto *DerivedCSA
= Class
->getAttr
<CodeSegAttr
>();
2791 if ((DerivedCSA
|| BaseCSA
) &&
2792 (!BaseCSA
|| !DerivedCSA
|| BaseCSA
->getName() != DerivedCSA
->getName())) {
2793 Diag(Class
->getLocation(), diag::err_mismatched_code_seg_base
);
2794 Diag(CXXBaseDecl
->getLocation(), diag::note_base_class_specified_here
)
2799 // A class which contains a flexible array member is not suitable for use as a
2801 // - If the layout determines that a base comes before another base,
2802 // the flexible array member would index into the subsequent base.
2803 // - If the layout determines that base comes before the derived class,
2804 // the flexible array member would index into the derived class.
2805 if (CXXBaseDecl
->hasFlexibleArrayMember()) {
2806 Diag(BaseLoc
, diag::err_base_class_has_flexible_array_member
)
2807 << CXXBaseDecl
->getDeclName();
2812 // If a class is marked final and it appears as a base-type-specifier in
2813 // base-clause, the program is ill-formed.
2814 if (FinalAttr
*FA
= CXXBaseDecl
->getAttr
<FinalAttr
>()) {
2815 Diag(BaseLoc
, diag::err_class_marked_final_used_as_base
)
2816 << CXXBaseDecl
->getDeclName()
2817 << FA
->isSpelledAsSealed();
2818 Diag(CXXBaseDecl
->getLocation(), diag::note_entity_declared_at
)
2819 << CXXBaseDecl
->getDeclName() << FA
->getRange();
2823 if (BaseDecl
->isInvalidDecl())
2824 Class
->setInvalidDecl();
2826 // Create the base specifier.
2827 return new (Context
) CXXBaseSpecifier(
2828 SpecifierRange
, Virtual
, Class
->getTagKind() == TagTypeKind::Class
,
2829 Access
, TInfo
, EllipsisLoc
);
2832 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2833 /// one entry in the base class list of a class specifier, for
2835 /// class foo : public bar, virtual private baz {
2836 /// 'public bar' and 'virtual private baz' are each base-specifiers.
2837 BaseResult
Sema::ActOnBaseSpecifier(Decl
*classdecl
, SourceRange SpecifierRange
,
2838 const ParsedAttributesView
&Attributes
,
2839 bool Virtual
, AccessSpecifier Access
,
2840 ParsedType basetype
, SourceLocation BaseLoc
,
2841 SourceLocation EllipsisLoc
) {
2845 AdjustDeclIfTemplate(classdecl
);
2846 CXXRecordDecl
*Class
= dyn_cast
<CXXRecordDecl
>(classdecl
);
2850 // We haven't yet attached the base specifiers.
2851 Class
->setIsParsingBaseSpecifiers();
2853 // We do not support any C++11 attributes on base-specifiers yet.
2854 // Diagnose any attributes we see.
2855 for (const ParsedAttr
&AL
: Attributes
) {
2856 if (AL
.isInvalid() || AL
.getKind() == ParsedAttr::IgnoredAttribute
)
2858 if (AL
.getKind() == ParsedAttr::UnknownAttribute
)
2859 Diag(AL
.getLoc(), diag::warn_unknown_attribute_ignored
)
2860 << AL
<< AL
.getRange();
2862 Diag(AL
.getLoc(), diag::err_base_specifier_attribute
)
2863 << AL
<< AL
.isRegularKeywordAttribute() << AL
.getRange();
2866 TypeSourceInfo
*TInfo
= nullptr;
2867 GetTypeFromParser(basetype
, &TInfo
);
2869 if (EllipsisLoc
.isInvalid() &&
2870 DiagnoseUnexpandedParameterPack(SpecifierRange
.getBegin(), TInfo
,
2874 if (CXXBaseSpecifier
*BaseSpec
= CheckBaseSpecifier(Class
, SpecifierRange
,
2875 Virtual
, Access
, TInfo
,
2879 Class
->setInvalidDecl();
2884 /// Use small set to collect indirect bases. As this is only used
2885 /// locally, there's no need to abstract the small size parameter.
2886 typedef llvm::SmallPtrSet
<QualType
, 4> IndirectBaseSet
;
2888 /// Recursively add the bases of Type. Don't add Type itself.
2890 NoteIndirectBases(ASTContext
&Context
, IndirectBaseSet
&Set
,
2891 const QualType
&Type
)
2893 // Even though the incoming type is a base, it might not be
2894 // a class -- it could be a template parm, for instance.
2895 if (auto Rec
= Type
->getAs
<RecordType
>()) {
2896 auto Decl
= Rec
->getAsCXXRecordDecl();
2898 // Iterate over its bases.
2899 for (const auto &BaseSpec
: Decl
->bases()) {
2900 QualType Base
= Context
.getCanonicalType(BaseSpec
.getType())
2901 .getUnqualifiedType();
2902 if (Set
.insert(Base
).second
)
2903 // If we've not already seen it, recurse.
2904 NoteIndirectBases(Context
, Set
, Base
);
2909 /// Performs the actual work of attaching the given base class
2910 /// specifiers to a C++ class.
2911 bool Sema::AttachBaseSpecifiers(CXXRecordDecl
*Class
,
2912 MutableArrayRef
<CXXBaseSpecifier
*> Bases
) {
2916 // Used to keep track of which base types we have already seen, so
2917 // that we can properly diagnose redundant direct base types. Note
2918 // that the key is always the unqualified canonical type of the base
2920 std::map
<QualType
, CXXBaseSpecifier
*, QualTypeOrdering
> KnownBaseTypes
;
2922 // Used to track indirect bases so we can see if a direct base is
2924 IndirectBaseSet IndirectBaseTypes
;
2926 // Copy non-redundant base specifiers into permanent storage.
2927 unsigned NumGoodBases
= 0;
2928 bool Invalid
= false;
2929 for (unsigned idx
= 0; idx
< Bases
.size(); ++idx
) {
2930 QualType NewBaseType
2931 = Context
.getCanonicalType(Bases
[idx
]->getType());
2932 NewBaseType
= NewBaseType
.getLocalUnqualifiedType();
2934 CXXBaseSpecifier
*&KnownBase
= KnownBaseTypes
[NewBaseType
];
2936 // C++ [class.mi]p3:
2937 // A class shall not be specified as a direct base class of a
2938 // derived class more than once.
2939 Diag(Bases
[idx
]->getBeginLoc(), diag::err_duplicate_base_class
)
2940 << KnownBase
->getType() << Bases
[idx
]->getSourceRange();
2942 // Delete the duplicate base class specifier; we're going to
2943 // overwrite its pointer later.
2944 Context
.Deallocate(Bases
[idx
]);
2948 // Okay, add this new base class.
2949 KnownBase
= Bases
[idx
];
2950 Bases
[NumGoodBases
++] = Bases
[idx
];
2952 if (NewBaseType
->isDependentType())
2954 // Note this base's direct & indirect bases, if there could be ambiguity.
2955 if (Bases
.size() > 1)
2956 NoteIndirectBases(Context
, IndirectBaseTypes
, NewBaseType
);
2958 if (const RecordType
*Record
= NewBaseType
->getAs
<RecordType
>()) {
2959 const CXXRecordDecl
*RD
= cast
<CXXRecordDecl
>(Record
->getDecl());
2960 if (Class
->isInterface() &&
2961 (!RD
->isInterfaceLike() ||
2962 KnownBase
->getAccessSpecifier() != AS_public
)) {
2963 // The Microsoft extension __interface does not permit bases that
2964 // are not themselves public interfaces.
2965 Diag(KnownBase
->getBeginLoc(), diag::err_invalid_base_in_interface
)
2966 << getRecordDiagFromTagKind(RD
->getTagKind()) << RD
2967 << RD
->getSourceRange();
2970 if (RD
->hasAttr
<WeakAttr
>())
2971 Class
->addAttr(WeakAttr::CreateImplicit(Context
));
2976 // Attach the remaining base class specifiers to the derived class.
2977 Class
->setBases(Bases
.data(), NumGoodBases
);
2979 // Check that the only base classes that are duplicate are virtual.
2980 for (unsigned idx
= 0; idx
< NumGoodBases
; ++idx
) {
2981 // Check whether this direct base is inaccessible due to ambiguity.
2982 QualType BaseType
= Bases
[idx
]->getType();
2984 // Skip all dependent types in templates being used as base specifiers.
2985 // Checks below assume that the base specifier is a CXXRecord.
2986 if (BaseType
->isDependentType())
2989 CanQualType CanonicalBase
= Context
.getCanonicalType(BaseType
)
2990 .getUnqualifiedType();
2992 if (IndirectBaseTypes
.count(CanonicalBase
)) {
2993 CXXBasePaths
Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2994 /*DetectVirtual=*/true);
2996 = Class
->isDerivedFrom(CanonicalBase
->getAsCXXRecordDecl(), Paths
);
3000 if (Paths
.isAmbiguous(CanonicalBase
))
3001 Diag(Bases
[idx
]->getBeginLoc(), diag::warn_inaccessible_base_class
)
3002 << BaseType
<< getAmbiguousPathsDisplayString(Paths
)
3003 << Bases
[idx
]->getSourceRange();
3005 assert(Bases
[idx
]->isVirtual());
3008 // Delete the base class specifier, since its data has been copied
3009 // into the CXXRecordDecl.
3010 Context
.Deallocate(Bases
[idx
]);
3016 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
3017 /// class, after checking whether there are any duplicate base
3019 void Sema::ActOnBaseSpecifiers(Decl
*ClassDecl
,
3020 MutableArrayRef
<CXXBaseSpecifier
*> Bases
) {
3021 if (!ClassDecl
|| Bases
.empty())
3024 AdjustDeclIfTemplate(ClassDecl
);
3025 AttachBaseSpecifiers(cast
<CXXRecordDecl
>(ClassDecl
), Bases
);
3028 /// Determine whether the type \p Derived is a C++ class that is
3029 /// derived from the type \p Base.
3030 bool Sema::IsDerivedFrom(SourceLocation Loc
, QualType Derived
, QualType Base
) {
3031 if (!getLangOpts().CPlusPlus
)
3034 CXXRecordDecl
*DerivedRD
= Derived
->getAsCXXRecordDecl();
3038 CXXRecordDecl
*BaseRD
= Base
->getAsCXXRecordDecl();
3042 // If either the base or the derived type is invalid, don't try to
3043 // check whether one is derived from the other.
3044 if (BaseRD
->isInvalidDecl() || DerivedRD
->isInvalidDecl())
3047 // FIXME: In a modules build, do we need the entire path to be visible for us
3048 // to be able to use the inheritance relationship?
3049 if (!isCompleteType(Loc
, Derived
) && !DerivedRD
->isBeingDefined())
3052 return DerivedRD
->isDerivedFrom(BaseRD
);
3055 /// Determine whether the type \p Derived is a C++ class that is
3056 /// derived from the type \p Base.
3057 bool Sema::IsDerivedFrom(SourceLocation Loc
, QualType Derived
, QualType Base
,
3058 CXXBasePaths
&Paths
) {
3059 if (!getLangOpts().CPlusPlus
)
3062 CXXRecordDecl
*DerivedRD
= Derived
->getAsCXXRecordDecl();
3066 CXXRecordDecl
*BaseRD
= Base
->getAsCXXRecordDecl();
3070 if (!isCompleteType(Loc
, Derived
) && !DerivedRD
->isBeingDefined())
3073 return DerivedRD
->isDerivedFrom(BaseRD
, Paths
);
3076 static void BuildBasePathArray(const CXXBasePath
&Path
,
3077 CXXCastPath
&BasePathArray
) {
3078 // We first go backward and check if we have a virtual base.
3079 // FIXME: It would be better if CXXBasePath had the base specifier for
3080 // the nearest virtual base.
3082 for (unsigned I
= Path
.size(); I
!= 0; --I
) {
3083 if (Path
[I
- 1].Base
->isVirtual()) {
3089 // Now add all bases.
3090 for (unsigned I
= Start
, E
= Path
.size(); I
!= E
; ++I
)
3091 BasePathArray
.push_back(const_cast<CXXBaseSpecifier
*>(Path
[I
].Base
));
3095 void Sema::BuildBasePathArray(const CXXBasePaths
&Paths
,
3096 CXXCastPath
&BasePathArray
) {
3097 assert(BasePathArray
.empty() && "Base path array must be empty!");
3098 assert(Paths
.isRecordingPaths() && "Must record paths!");
3099 return ::BuildBasePathArray(Paths
.front(), BasePathArray
);
3101 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
3102 /// conversion (where Derived and Base are class types) is
3103 /// well-formed, meaning that the conversion is unambiguous (and
3104 /// that all of the base classes are accessible). Returns true
3105 /// and emits a diagnostic if the code is ill-formed, returns false
3106 /// otherwise. Loc is the location where this routine should point to
3107 /// if there is an error, and Range is the source range to highlight
3108 /// if there is an error.
3110 /// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the
3111 /// diagnostic for the respective type of error will be suppressed, but the
3112 /// check for ill-formed code will still be performed.
3114 Sema::CheckDerivedToBaseConversion(QualType Derived
, QualType Base
,
3115 unsigned InaccessibleBaseID
,
3116 unsigned AmbiguousBaseConvID
,
3117 SourceLocation Loc
, SourceRange Range
,
3118 DeclarationName Name
,
3119 CXXCastPath
*BasePath
,
3120 bool IgnoreAccess
) {
3121 // First, determine whether the path from Derived to Base is
3122 // ambiguous. This is slightly more expensive than checking whether
3123 // the Derived to Base conversion exists, because here we need to
3124 // explore multiple paths to determine if there is an ambiguity.
3125 CXXBasePaths
Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3126 /*DetectVirtual=*/false);
3127 bool DerivationOkay
= IsDerivedFrom(Loc
, Derived
, Base
, Paths
);
3128 if (!DerivationOkay
)
3131 const CXXBasePath
*Path
= nullptr;
3132 if (!Paths
.isAmbiguous(Context
.getCanonicalType(Base
).getUnqualifiedType()))
3133 Path
= &Paths
.front();
3135 // For MSVC compatibility, check if Derived directly inherits from Base. Clang
3136 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
3137 // user to access such bases.
3138 if (!Path
&& getLangOpts().MSVCCompat
) {
3139 for (const CXXBasePath
&PossiblePath
: Paths
) {
3140 if (PossiblePath
.size() == 1) {
3141 Path
= &PossiblePath
;
3142 if (AmbiguousBaseConvID
)
3143 Diag(Loc
, diag::ext_ms_ambiguous_direct_base
)
3144 << Base
<< Derived
<< Range
;
3151 if (!IgnoreAccess
) {
3152 // Check that the base class can be accessed.
3154 CheckBaseClassAccess(Loc
, Base
, Derived
, *Path
, InaccessibleBaseID
)) {
3155 case AR_inaccessible
:
3164 // Build a base path if necessary.
3166 ::BuildBasePathArray(*Path
, *BasePath
);
3170 if (AmbiguousBaseConvID
) {
3171 // We know that the derived-to-base conversion is ambiguous, and
3172 // we're going to produce a diagnostic. Perform the derived-to-base
3173 // search just one more time to compute all of the possible paths so
3174 // that we can print them out. This is more expensive than any of
3175 // the previous derived-to-base checks we've done, but at this point
3176 // performance isn't as much of an issue.
3178 Paths
.setRecordingPaths(true);
3179 bool StillOkay
= IsDerivedFrom(Loc
, Derived
, Base
, Paths
);
3180 assert(StillOkay
&& "Can only be used with a derived-to-base conversion");
3183 // Build up a textual representation of the ambiguous paths, e.g.,
3184 // D -> B -> A, that will be used to illustrate the ambiguous
3185 // conversions in the diagnostic. We only print one of the paths
3186 // to each base class subobject.
3187 std::string PathDisplayStr
= getAmbiguousPathsDisplayString(Paths
);
3189 Diag(Loc
, AmbiguousBaseConvID
)
3190 << Derived
<< Base
<< PathDisplayStr
<< Range
<< Name
;
3196 Sema::CheckDerivedToBaseConversion(QualType Derived
, QualType Base
,
3197 SourceLocation Loc
, SourceRange Range
,
3198 CXXCastPath
*BasePath
,
3199 bool IgnoreAccess
) {
3200 return CheckDerivedToBaseConversion(
3201 Derived
, Base
, diag::err_upcast_to_inaccessible_base
,
3202 diag::err_ambiguous_derived_to_base_conv
, Loc
, Range
, DeclarationName(),
3203 BasePath
, IgnoreAccess
);
3207 /// Builds a string representing ambiguous paths from a
3208 /// specific derived class to different subobjects of the same base
3211 /// This function builds a string that can be used in error messages
3212 /// to show the different paths that one can take through the
3213 /// inheritance hierarchy to go from the derived class to different
3214 /// subobjects of a base class. The result looks something like this:
3216 /// struct D -> struct B -> struct A
3217 /// struct D -> struct C -> struct A
3219 std::string
Sema::getAmbiguousPathsDisplayString(CXXBasePaths
&Paths
) {
3220 std::string PathDisplayStr
;
3221 std::set
<unsigned> DisplayedPaths
;
3222 for (CXXBasePaths::paths_iterator Path
= Paths
.begin();
3223 Path
!= Paths
.end(); ++Path
) {
3224 if (DisplayedPaths
.insert(Path
->back().SubobjectNumber
).second
) {
3225 // We haven't displayed a path to this particular base
3226 // class subobject yet.
3227 PathDisplayStr
+= "\n ";
3228 PathDisplayStr
+= Context
.getTypeDeclType(Paths
.getOrigin()).getAsString();
3229 for (CXXBasePath::const_iterator Element
= Path
->begin();
3230 Element
!= Path
->end(); ++Element
)
3231 PathDisplayStr
+= " -> " + Element
->Base
->getType().getAsString();
3235 return PathDisplayStr
;
3238 //===----------------------------------------------------------------------===//
3239 // C++ class member Handling
3240 //===----------------------------------------------------------------------===//
3242 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
3243 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access
, SourceLocation ASLoc
,
3244 SourceLocation ColonLoc
,
3245 const ParsedAttributesView
&Attrs
) {
3246 assert(Access
!= AS_none
&& "Invalid kind for syntactic access specifier!");
3247 AccessSpecDecl
*ASDecl
= AccessSpecDecl::Create(Context
, Access
, CurContext
,
3249 CurContext
->addHiddenDecl(ASDecl
);
3250 return ProcessAccessDeclAttributeList(ASDecl
, Attrs
);
3253 /// CheckOverrideControl - Check C++11 override control semantics.
3254 void Sema::CheckOverrideControl(NamedDecl
*D
) {
3255 if (D
->isInvalidDecl())
3258 // We only care about "override" and "final" declarations.
3259 if (!D
->hasAttr
<OverrideAttr
>() && !D
->hasAttr
<FinalAttr
>())
3262 CXXMethodDecl
*MD
= dyn_cast
<CXXMethodDecl
>(D
);
3264 // We can't check dependent instance methods.
3265 if (MD
&& MD
->isInstance() &&
3266 (MD
->getParent()->hasAnyDependentBases() ||
3267 MD
->getType()->isDependentType()))
3270 if (MD
&& !MD
->isVirtual()) {
3271 // If we have a non-virtual method, check if it hides a virtual method.
3272 // (In that case, it's most likely the method has the wrong type.)
3273 SmallVector
<CXXMethodDecl
*, 8> OverloadedMethods
;
3274 FindHiddenVirtualMethods(MD
, OverloadedMethods
);
3276 if (!OverloadedMethods
.empty()) {
3277 if (OverrideAttr
*OA
= D
->getAttr
<OverrideAttr
>()) {
3278 Diag(OA
->getLocation(),
3279 diag::override_keyword_hides_virtual_member_function
)
3280 << "override" << (OverloadedMethods
.size() > 1);
3281 } else if (FinalAttr
*FA
= D
->getAttr
<FinalAttr
>()) {
3282 Diag(FA
->getLocation(),
3283 diag::override_keyword_hides_virtual_member_function
)
3284 << (FA
->isSpelledAsSealed() ? "sealed" : "final")
3285 << (OverloadedMethods
.size() > 1);
3287 NoteHiddenVirtualMethods(MD
, OverloadedMethods
);
3288 MD
->setInvalidDecl();
3291 // Fall through into the general case diagnostic.
3292 // FIXME: We might want to attempt typo correction here.
3295 if (!MD
|| !MD
->isVirtual()) {
3296 if (OverrideAttr
*OA
= D
->getAttr
<OverrideAttr
>()) {
3297 Diag(OA
->getLocation(),
3298 diag::override_keyword_only_allowed_on_virtual_member_functions
)
3299 << "override" << FixItHint::CreateRemoval(OA
->getLocation());
3300 D
->dropAttr
<OverrideAttr
>();
3302 if (FinalAttr
*FA
= D
->getAttr
<FinalAttr
>()) {
3303 Diag(FA
->getLocation(),
3304 diag::override_keyword_only_allowed_on_virtual_member_functions
)
3305 << (FA
->isSpelledAsSealed() ? "sealed" : "final")
3306 << FixItHint::CreateRemoval(FA
->getLocation());
3307 D
->dropAttr
<FinalAttr
>();
3312 // C++11 [class.virtual]p5:
3313 // If a function is marked with the virt-specifier override and
3314 // does not override a member function of a base class, the program is
3316 bool HasOverriddenMethods
= MD
->size_overridden_methods() != 0;
3317 if (MD
->hasAttr
<OverrideAttr
>() && !HasOverriddenMethods
)
3318 Diag(MD
->getLocation(), diag::err_function_marked_override_not_overriding
)
3319 << MD
->getDeclName();
3322 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl
*D
, bool Inconsistent
) {
3323 if (D
->isInvalidDecl() || D
->hasAttr
<OverrideAttr
>())
3325 CXXMethodDecl
*MD
= dyn_cast
<CXXMethodDecl
>(D
);
3326 if (!MD
|| MD
->isImplicit() || MD
->hasAttr
<FinalAttr
>())
3329 SourceLocation Loc
= MD
->getLocation();
3330 SourceLocation SpellingLoc
= Loc
;
3331 if (getSourceManager().isMacroArgExpansion(Loc
))
3332 SpellingLoc
= getSourceManager().getImmediateExpansionRange(Loc
).getBegin();
3333 SpellingLoc
= getSourceManager().getSpellingLoc(SpellingLoc
);
3334 if (SpellingLoc
.isValid() && getSourceManager().isInSystemHeader(SpellingLoc
))
3337 if (MD
->size_overridden_methods() > 0) {
3338 auto EmitDiag
= [&](unsigned DiagInconsistent
, unsigned DiagSuggest
) {
3340 Inconsistent
&& !Diags
.isIgnored(DiagInconsistent
, MD
->getLocation())
3343 Diag(MD
->getLocation(), DiagID
) << MD
->getDeclName();
3344 const CXXMethodDecl
*OMD
= *MD
->begin_overridden_methods();
3345 Diag(OMD
->getLocation(), diag::note_overridden_virtual_function
);
3347 if (isa
<CXXDestructorDecl
>(MD
))
3349 diag::warn_inconsistent_destructor_marked_not_override_overriding
,
3350 diag::warn_suggest_destructor_marked_not_override_overriding
);
3352 EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding
,
3353 diag::warn_suggest_function_marked_not_override_overriding
);
3357 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
3358 /// function overrides a virtual member function marked 'final', according to
3359 /// C++11 [class.virtual]p4.
3360 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl
*New
,
3361 const CXXMethodDecl
*Old
) {
3362 FinalAttr
*FA
= Old
->getAttr
<FinalAttr
>();
3366 Diag(New
->getLocation(), diag::err_final_function_overridden
)
3367 << New
->getDeclName()
3368 << FA
->isSpelledAsSealed();
3369 Diag(Old
->getLocation(), diag::note_overridden_virtual_function
);
3373 static bool InitializationHasSideEffects(const FieldDecl
&FD
) {
3374 const Type
*T
= FD
.getType()->getBaseElementTypeUnsafe();
3375 // FIXME: Destruction of ObjC lifetime types has side-effects.
3376 if (const CXXRecordDecl
*RD
= T
->getAsCXXRecordDecl())
3377 return !RD
->isCompleteDefinition() ||
3378 !RD
->hasTrivialDefaultConstructor() ||
3379 !RD
->hasTrivialDestructor();
3383 // Check if there is a field shadowing.
3384 void Sema::CheckShadowInheritedFields(const SourceLocation
&Loc
,
3385 DeclarationName FieldName
,
3386 const CXXRecordDecl
*RD
,
3388 if (Diags
.isIgnored(diag::warn_shadow_field
, Loc
))
3391 // To record a shadowed field in a base
3392 std::map
<CXXRecordDecl
*, NamedDecl
*> Bases
;
3393 auto FieldShadowed
= [&](const CXXBaseSpecifier
*Specifier
,
3394 CXXBasePath
&Path
) {
3395 const auto Base
= Specifier
->getType()->getAsCXXRecordDecl();
3396 // Record an ambiguous path directly
3397 if (Bases
.find(Base
) != Bases
.end())
3399 for (const auto Field
: Base
->lookup(FieldName
)) {
3400 if ((isa
<FieldDecl
>(Field
) || isa
<IndirectFieldDecl
>(Field
)) &&
3401 Field
->getAccess() != AS_private
) {
3402 assert(Field
->getAccess() != AS_none
);
3403 assert(Bases
.find(Base
) == Bases
.end());
3404 Bases
[Base
] = Field
;
3411 CXXBasePaths
Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3412 /*DetectVirtual=*/true);
3413 if (!RD
->lookupInBases(FieldShadowed
, Paths
))
3416 for (const auto &P
: Paths
) {
3417 auto Base
= P
.back().Base
->getType()->getAsCXXRecordDecl();
3418 auto It
= Bases
.find(Base
);
3419 // Skip duplicated bases
3420 if (It
== Bases
.end())
3422 auto BaseField
= It
->second
;
3423 assert(BaseField
->getAccess() != AS_private
);
3425 CXXRecordDecl::MergeAccess(P
.Access
, BaseField
->getAccess())) {
3426 Diag(Loc
, diag::warn_shadow_field
)
3427 << FieldName
<< RD
<< Base
<< DeclIsField
;
3428 Diag(BaseField
->getLocation(), diag::note_shadow_field
);
3434 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
3435 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
3436 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
3437 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
3438 /// present (but parsing it has been deferred).
3440 Sema::ActOnCXXMemberDeclarator(Scope
*S
, AccessSpecifier AS
, Declarator
&D
,
3441 MultiTemplateParamsArg TemplateParameterLists
,
3442 Expr
*BW
, const VirtSpecifiers
&VS
,
3443 InClassInitStyle InitStyle
) {
3444 const DeclSpec
&DS
= D
.getDeclSpec();
3445 DeclarationNameInfo NameInfo
= GetNameForDeclarator(D
);
3446 DeclarationName Name
= NameInfo
.getName();
3447 SourceLocation Loc
= NameInfo
.getLoc();
3449 // For anonymous bitfields, the location should point to the type.
3450 if (Loc
.isInvalid())
3451 Loc
= D
.getBeginLoc();
3453 Expr
*BitWidth
= static_cast<Expr
*>(BW
);
3455 assert(isa
<CXXRecordDecl
>(CurContext
));
3456 assert(!DS
.isFriendSpecified());
3458 bool isFunc
= D
.isDeclarationOfFunction();
3459 const ParsedAttr
*MSPropertyAttr
=
3460 D
.getDeclSpec().getAttributes().getMSPropertyAttr();
3462 if (cast
<CXXRecordDecl
>(CurContext
)->isInterface()) {
3463 // The Microsoft extension __interface only permits public member functions
3464 // and prohibits constructors, destructors, operators, non-public member
3465 // functions, static methods and data members.
3466 unsigned InvalidDecl
;
3467 bool ShowDeclName
= true;
3469 (DS
.getStorageClassSpec() == DeclSpec::SCS_typedef
|| MSPropertyAttr
))
3473 else if (AS
!= AS_public
)
3475 else if (DS
.getStorageClassSpec() == DeclSpec::SCS_static
)
3477 else switch (Name
.getNameKind()) {
3478 case DeclarationName::CXXConstructorName
:
3480 ShowDeclName
= false;
3483 case DeclarationName::CXXDestructorName
:
3485 ShowDeclName
= false;
3488 case DeclarationName::CXXOperatorName
:
3489 case DeclarationName::CXXConversionFunctionName
:
3500 Diag(Loc
, diag::err_invalid_member_in_interface
)
3501 << (InvalidDecl
-1) << Name
;
3503 Diag(Loc
, diag::err_invalid_member_in_interface
)
3504 << (InvalidDecl
-1) << "";
3509 // C++ 9.2p6: A member shall not be declared to have automatic storage
3510 // duration (auto, register) or with the extern storage-class-specifier.
3511 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3512 // data members and cannot be applied to names declared const or static,
3513 // and cannot be applied to reference members.
3514 switch (DS
.getStorageClassSpec()) {
3515 case DeclSpec::SCS_unspecified
:
3516 case DeclSpec::SCS_typedef
:
3517 case DeclSpec::SCS_static
:
3519 case DeclSpec::SCS_mutable
:
3521 Diag(DS
.getStorageClassSpecLoc(), diag::err_mutable_function
);
3523 // FIXME: It would be nicer if the keyword was ignored only for this
3524 // declarator. Otherwise we could get follow-up errors.
3525 D
.getMutableDeclSpec().ClearStorageClassSpecs();
3529 Diag(DS
.getStorageClassSpecLoc(),
3530 diag::err_storageclass_invalid_for_member
);
3531 D
.getMutableDeclSpec().ClearStorageClassSpecs();
3535 bool isInstField
= ((DS
.getStorageClassSpec() == DeclSpec::SCS_unspecified
||
3536 DS
.getStorageClassSpec() == DeclSpec::SCS_mutable
) &&
3539 if (DS
.hasConstexprSpecifier() && isInstField
) {
3540 SemaDiagnosticBuilder B
=
3541 Diag(DS
.getConstexprSpecLoc(), diag::err_invalid_constexpr_member
);
3542 SourceLocation ConstexprLoc
= DS
.getConstexprSpecLoc();
3543 if (InitStyle
== ICIS_NoInit
) {
3545 if (D
.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const
)
3546 B
<< FixItHint::CreateRemoval(ConstexprLoc
);
3548 B
<< FixItHint::CreateReplacement(ConstexprLoc
, "const");
3549 D
.getMutableDeclSpec().ClearConstexprSpec();
3550 const char *PrevSpec
;
3552 bool Failed
= D
.getMutableDeclSpec().SetTypeQual(
3553 DeclSpec::TQ_const
, ConstexprLoc
, PrevSpec
, DiagID
, getLangOpts());
3555 assert(!Failed
&& "Making a constexpr member const shouldn't fail");
3559 const char *PrevSpec
;
3561 if (D
.getMutableDeclSpec().SetStorageClassSpec(
3562 *this, DeclSpec::SCS_static
, ConstexprLoc
, PrevSpec
, DiagID
,
3563 Context
.getPrintingPolicy())) {
3564 assert(DS
.getStorageClassSpec() == DeclSpec::SCS_mutable
&&
3565 "This is the only DeclSpec that should fail to be applied");
3568 B
<< 0 << FixItHint::CreateInsertion(ConstexprLoc
, "static ");
3569 isInstField
= false;
3576 CXXScopeSpec
&SS
= D
.getCXXScopeSpec();
3578 // Data members must have identifiers for names.
3579 if (!Name
.isIdentifier()) {
3580 Diag(Loc
, diag::err_bad_variable_name
)
3585 IdentifierInfo
*II
= Name
.getAsIdentifierInfo();
3587 // Member field could not be with "template" keyword.
3588 // So TemplateParameterLists should be empty in this case.
3589 if (TemplateParameterLists
.size()) {
3590 TemplateParameterList
* TemplateParams
= TemplateParameterLists
[0];
3591 if (TemplateParams
->size()) {
3592 // There is no such thing as a member field template.
3593 Diag(D
.getIdentifierLoc(), diag::err_template_member
)
3595 << SourceRange(TemplateParams
->getTemplateLoc(),
3596 TemplateParams
->getRAngleLoc());
3598 // There is an extraneous 'template<>' for this member.
3599 Diag(TemplateParams
->getTemplateLoc(),
3600 diag::err_template_member_noparams
)
3602 << SourceRange(TemplateParams
->getTemplateLoc(),
3603 TemplateParams
->getRAngleLoc());
3608 if (D
.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
) {
3609 Diag(D
.getIdentifierLoc(), diag::err_member_with_template_arguments
)
3611 << SourceRange(D
.getName().TemplateId
->LAngleLoc
,
3612 D
.getName().TemplateId
->RAngleLoc
)
3613 << D
.getName().TemplateId
->LAngleLoc
;
3614 D
.SetIdentifier(II
, Loc
);
3617 if (SS
.isSet() && !SS
.isInvalid()) {
3618 // The user provided a superfluous scope specifier inside a class
3624 if (DeclContext
*DC
= computeDeclContext(SS
, false))
3625 diagnoseQualifiedDeclaration(SS
, DC
, Name
, D
.getIdentifierLoc(),
3626 D
.getName().getKind() ==
3627 UnqualifiedIdKind::IK_TemplateId
);
3629 Diag(D
.getIdentifierLoc(), diag::err_member_qualification
)
3630 << Name
<< SS
.getRange();
3635 if (MSPropertyAttr
) {
3636 Member
= HandleMSProperty(S
, cast
<CXXRecordDecl
>(CurContext
), Loc
, D
,
3637 BitWidth
, InitStyle
, AS
, *MSPropertyAttr
);
3640 isInstField
= false;
3642 Member
= HandleField(S
, cast
<CXXRecordDecl
>(CurContext
), Loc
, D
,
3643 BitWidth
, InitStyle
, AS
);
3648 CheckShadowInheritedFields(Loc
, Name
, cast
<CXXRecordDecl
>(CurContext
));
3650 Member
= HandleDeclarator(S
, D
, TemplateParameterLists
);
3654 // Non-instance-fields can't have a bitfield.
3656 if (Member
->isInvalidDecl()) {
3657 // don't emit another diagnostic.
3658 } else if (isa
<VarDecl
>(Member
) || isa
<VarTemplateDecl
>(Member
)) {
3659 // C++ 9.6p3: A bit-field shall not be a static member.
3660 // "static member 'A' cannot be a bit-field"
3661 Diag(Loc
, diag::err_static_not_bitfield
)
3662 << Name
<< BitWidth
->getSourceRange();
3663 } else if (isa
<TypedefDecl
>(Member
)) {
3664 // "typedef member 'x' cannot be a bit-field"
3665 Diag(Loc
, diag::err_typedef_not_bitfield
)
3666 << Name
<< BitWidth
->getSourceRange();
3668 // A function typedef ("typedef int f(); f a;").
3669 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3670 Diag(Loc
, diag::err_not_integral_type_bitfield
)
3671 << Name
<< cast
<ValueDecl
>(Member
)->getType()
3672 << BitWidth
->getSourceRange();
3676 Member
->setInvalidDecl();
3679 NamedDecl
*NonTemplateMember
= Member
;
3680 if (FunctionTemplateDecl
*FunTmpl
= dyn_cast
<FunctionTemplateDecl
>(Member
))
3681 NonTemplateMember
= FunTmpl
->getTemplatedDecl();
3682 else if (VarTemplateDecl
*VarTmpl
= dyn_cast
<VarTemplateDecl
>(Member
))
3683 NonTemplateMember
= VarTmpl
->getTemplatedDecl();
3685 Member
->setAccess(AS
);
3687 // If we have declared a member function template or static data member
3688 // template, set the access of the templated declaration as well.
3689 if (NonTemplateMember
!= Member
)
3690 NonTemplateMember
->setAccess(AS
);
3692 // C++ [temp.deduct.guide]p3:
3693 // A deduction guide [...] for a member class template [shall be
3694 // declared] with the same access [as the template].
3695 if (auto *DG
= dyn_cast
<CXXDeductionGuideDecl
>(NonTemplateMember
)) {
3696 auto *TD
= DG
->getDeducedTemplate();
3697 // Access specifiers are only meaningful if both the template and the
3698 // deduction guide are from the same scope.
3699 if (AS
!= TD
->getAccess() &&
3700 TD
->getDeclContext()->getRedeclContext()->Equals(
3701 DG
->getDeclContext()->getRedeclContext())) {
3702 Diag(DG
->getBeginLoc(), diag::err_deduction_guide_wrong_access
);
3703 Diag(TD
->getBeginLoc(), diag::note_deduction_guide_template_access
)
3705 const AccessSpecDecl
*LastAccessSpec
= nullptr;
3706 for (const auto *D
: cast
<CXXRecordDecl
>(CurContext
)->decls()) {
3707 if (const auto *AccessSpec
= dyn_cast
<AccessSpecDecl
>(D
))
3708 LastAccessSpec
= AccessSpec
;
3710 assert(LastAccessSpec
&& "differing access with no access specifier");
3711 Diag(LastAccessSpec
->getBeginLoc(), diag::note_deduction_guide_access
)
3717 if (VS
.isOverrideSpecified())
3718 Member
->addAttr(OverrideAttr::Create(Context
, VS
.getOverrideLoc()));
3719 if (VS
.isFinalSpecified())
3720 Member
->addAttr(FinalAttr::Create(Context
, VS
.getFinalLoc(),
3721 VS
.isFinalSpelledSealed()
3722 ? FinalAttr::Keyword_sealed
3723 : FinalAttr::Keyword_final
));
3725 if (VS
.getLastLocation().isValid()) {
3726 // Update the end location of a method that has a virt-specifiers.
3727 if (CXXMethodDecl
*MD
= dyn_cast_or_null
<CXXMethodDecl
>(Member
))
3728 MD
->setRangeEnd(VS
.getLastLocation());
3731 CheckOverrideControl(Member
);
3733 assert((Name
|| isInstField
) && "No identifier for non-field ?");
3736 FieldDecl
*FD
= cast
<FieldDecl
>(Member
);
3737 FieldCollector
->Add(FD
);
3739 if (!Diags
.isIgnored(diag::warn_unused_private_field
, FD
->getLocation())) {
3740 // Remember all explicit private FieldDecls that have a name, no side
3741 // effects and are not part of a dependent type declaration.
3743 auto DeclHasUnusedAttr
= [](const QualType
&T
) {
3744 if (const TagDecl
*TD
= T
->getAsTagDecl())
3745 return TD
->hasAttr
<UnusedAttr
>();
3746 if (const TypedefType
*TDT
= T
->getAs
<TypedefType
>())
3747 return TDT
->getDecl()->hasAttr
<UnusedAttr
>();
3751 if (!FD
->isImplicit() && FD
->getDeclName() &&
3752 FD
->getAccess() == AS_private
&&
3753 !FD
->hasAttr
<UnusedAttr
>() &&
3754 !FD
->getParent()->isDependentContext() &&
3755 !DeclHasUnusedAttr(FD
->getType()) &&
3756 !InitializationHasSideEffects(*FD
))
3757 UnusedPrivateFields
.insert(FD
);
3765 class UninitializedFieldVisitor
3766 : public EvaluatedExprVisitor
<UninitializedFieldVisitor
> {
3768 // List of Decls to generate a warning on. Also remove Decls that become
3770 llvm::SmallPtrSetImpl
<ValueDecl
*> &Decls
;
3771 // List of base classes of the record. Classes are removed after their
3773 llvm::SmallPtrSetImpl
<QualType
> &BaseClasses
;
3774 // Vector of decls to be removed from the Decl set prior to visiting the
3775 // nodes. These Decls may have been initialized in the prior initializer.
3776 llvm::SmallVector
<ValueDecl
*, 4> DeclsToRemove
;
3777 // If non-null, add a note to the warning pointing back to the constructor.
3778 const CXXConstructorDecl
*Constructor
;
3779 // Variables to hold state when processing an initializer list. When
3780 // InitList is true, special case initialization of FieldDecls matching
3781 // InitListFieldDecl.
3783 FieldDecl
*InitListFieldDecl
;
3784 llvm::SmallVector
<unsigned, 4> InitFieldIndex
;
3787 typedef EvaluatedExprVisitor
<UninitializedFieldVisitor
> Inherited
;
3788 UninitializedFieldVisitor(Sema
&S
,
3789 llvm::SmallPtrSetImpl
<ValueDecl
*> &Decls
,
3790 llvm::SmallPtrSetImpl
<QualType
> &BaseClasses
)
3791 : Inherited(S
.Context
), S(S
), Decls(Decls
), BaseClasses(BaseClasses
),
3792 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3794 // Returns true if the use of ME is not an uninitialized use.
3795 bool IsInitListMemberExprInitialized(MemberExpr
*ME
,
3796 bool CheckReferenceOnly
) {
3797 llvm::SmallVector
<FieldDecl
*, 4> Fields
;
3798 bool ReferenceField
= false;
3800 FieldDecl
*FD
= dyn_cast
<FieldDecl
>(ME
->getMemberDecl());
3803 Fields
.push_back(FD
);
3804 if (FD
->getType()->isReferenceType())
3805 ReferenceField
= true;
3806 ME
= dyn_cast
<MemberExpr
>(ME
->getBase()->IgnoreParenImpCasts());
3809 // Binding a reference to an uninitialized field is not an
3810 // uninitialized use.
3811 if (CheckReferenceOnly
&& !ReferenceField
)
3814 llvm::SmallVector
<unsigned, 4> UsedFieldIndex
;
3815 // Discard the first field since it is the field decl that is being
3817 for (const FieldDecl
*FD
: llvm::drop_begin(llvm::reverse(Fields
)))
3818 UsedFieldIndex
.push_back(FD
->getFieldIndex());
3820 for (auto UsedIter
= UsedFieldIndex
.begin(),
3821 UsedEnd
= UsedFieldIndex
.end(),
3822 OrigIter
= InitFieldIndex
.begin(),
3823 OrigEnd
= InitFieldIndex
.end();
3824 UsedIter
!= UsedEnd
&& OrigIter
!= OrigEnd
; ++UsedIter
, ++OrigIter
) {
3825 if (*UsedIter
< *OrigIter
)
3827 if (*UsedIter
> *OrigIter
)
3834 void HandleMemberExpr(MemberExpr
*ME
, bool CheckReferenceOnly
,
3836 if (isa
<EnumConstantDecl
>(ME
->getMemberDecl()))
3839 // FieldME is the inner-most MemberExpr that is not an anonymous struct
3841 MemberExpr
*FieldME
= ME
;
3843 bool AllPODFields
= FieldME
->getType().isPODType(S
.Context
);
3846 while (MemberExpr
*SubME
=
3847 dyn_cast
<MemberExpr
>(Base
->IgnoreParenImpCasts())) {
3849 if (isa
<VarDecl
>(SubME
->getMemberDecl()))
3852 if (FieldDecl
*FD
= dyn_cast
<FieldDecl
>(SubME
->getMemberDecl()))
3853 if (!FD
->isAnonymousStructOrUnion())
3856 if (!FieldME
->getType().isPODType(S
.Context
))
3857 AllPODFields
= false;
3859 Base
= SubME
->getBase();
3862 if (!isa
<CXXThisExpr
>(Base
->IgnoreParenImpCasts())) {
3867 if (AddressOf
&& AllPODFields
)
3870 ValueDecl
* FoundVD
= FieldME
->getMemberDecl();
3872 if (ImplicitCastExpr
*BaseCast
= dyn_cast
<ImplicitCastExpr
>(Base
)) {
3873 while (isa
<ImplicitCastExpr
>(BaseCast
->getSubExpr())) {
3874 BaseCast
= cast
<ImplicitCastExpr
>(BaseCast
->getSubExpr());
3877 if (BaseCast
->getCastKind() == CK_UncheckedDerivedToBase
) {
3878 QualType T
= BaseCast
->getType();
3879 if (T
->isPointerType() &&
3880 BaseClasses
.count(T
->getPointeeType())) {
3881 S
.Diag(FieldME
->getExprLoc(), diag::warn_base_class_is_uninit
)
3882 << T
->getPointeeType() << FoundVD
;
3887 if (!Decls
.count(FoundVD
))
3890 const bool IsReference
= FoundVD
->getType()->isReferenceType();
3892 if (InitList
&& !AddressOf
&& FoundVD
== InitListFieldDecl
) {
3893 // Special checking for initializer lists.
3894 if (IsInitListMemberExprInitialized(ME
, CheckReferenceOnly
)) {
3898 // Prevent double warnings on use of unbounded references.
3899 if (CheckReferenceOnly
&& !IsReference
)
3903 unsigned diag
= IsReference
3904 ? diag::warn_reference_field_is_uninit
3905 : diag::warn_field_is_uninit
;
3906 S
.Diag(FieldME
->getExprLoc(), diag
) << FoundVD
;
3908 S
.Diag(Constructor
->getLocation(),
3909 diag::note_uninit_in_this_constructor
)
3910 << (Constructor
->isDefaultConstructor() && Constructor
->isImplicit());
3914 void HandleValue(Expr
*E
, bool AddressOf
) {
3915 E
= E
->IgnoreParens();
3917 if (MemberExpr
*ME
= dyn_cast
<MemberExpr
>(E
)) {
3918 HandleMemberExpr(ME
, false /*CheckReferenceOnly*/,
3919 AddressOf
/*AddressOf*/);
3923 if (ConditionalOperator
*CO
= dyn_cast
<ConditionalOperator
>(E
)) {
3924 Visit(CO
->getCond());
3925 HandleValue(CO
->getTrueExpr(), AddressOf
);
3926 HandleValue(CO
->getFalseExpr(), AddressOf
);
3930 if (BinaryConditionalOperator
*BCO
=
3931 dyn_cast
<BinaryConditionalOperator
>(E
)) {
3932 Visit(BCO
->getCond());
3933 HandleValue(BCO
->getFalseExpr(), AddressOf
);
3937 if (OpaqueValueExpr
*OVE
= dyn_cast
<OpaqueValueExpr
>(E
)) {
3938 HandleValue(OVE
->getSourceExpr(), AddressOf
);
3942 if (BinaryOperator
*BO
= dyn_cast
<BinaryOperator
>(E
)) {
3943 switch (BO
->getOpcode()) {
3948 HandleValue(BO
->getLHS(), AddressOf
);
3949 Visit(BO
->getRHS());
3952 Visit(BO
->getLHS());
3953 HandleValue(BO
->getRHS(), AddressOf
);
3961 void CheckInitListExpr(InitListExpr
*ILE
) {
3962 InitFieldIndex
.push_back(0);
3963 for (auto *Child
: ILE
->children()) {
3964 if (InitListExpr
*SubList
= dyn_cast
<InitListExpr
>(Child
)) {
3965 CheckInitListExpr(SubList
);
3969 ++InitFieldIndex
.back();
3971 InitFieldIndex
.pop_back();
3974 void CheckInitializer(Expr
*E
, const CXXConstructorDecl
*FieldConstructor
,
3975 FieldDecl
*Field
, const Type
*BaseClass
) {
3976 // Remove Decls that may have been initialized in the previous
3978 for (ValueDecl
* VD
: DeclsToRemove
)
3980 DeclsToRemove
.clear();
3982 Constructor
= FieldConstructor
;
3983 InitListExpr
*ILE
= dyn_cast
<InitListExpr
>(E
);
3987 InitListFieldDecl
= Field
;
3988 InitFieldIndex
.clear();
3989 CheckInitListExpr(ILE
);
3998 BaseClasses
.erase(BaseClass
->getCanonicalTypeInternal());
4001 void VisitMemberExpr(MemberExpr
*ME
) {
4002 // All uses of unbounded reference fields will warn.
4003 HandleMemberExpr(ME
, true /*CheckReferenceOnly*/, false /*AddressOf*/);
4006 void VisitImplicitCastExpr(ImplicitCastExpr
*E
) {
4007 if (E
->getCastKind() == CK_LValueToRValue
) {
4008 HandleValue(E
->getSubExpr(), false /*AddressOf*/);
4012 Inherited::VisitImplicitCastExpr(E
);
4015 void VisitCXXConstructExpr(CXXConstructExpr
*E
) {
4016 if (E
->getConstructor()->isCopyConstructor()) {
4017 Expr
*ArgExpr
= E
->getArg(0);
4018 if (InitListExpr
*ILE
= dyn_cast
<InitListExpr
>(ArgExpr
))
4019 if (ILE
->getNumInits() == 1)
4020 ArgExpr
= ILE
->getInit(0);
4021 if (ImplicitCastExpr
*ICE
= dyn_cast
<ImplicitCastExpr
>(ArgExpr
))
4022 if (ICE
->getCastKind() == CK_NoOp
)
4023 ArgExpr
= ICE
->getSubExpr();
4024 HandleValue(ArgExpr
, false /*AddressOf*/);
4027 Inherited::VisitCXXConstructExpr(E
);
4030 void VisitCXXMemberCallExpr(CXXMemberCallExpr
*E
) {
4031 Expr
*Callee
= E
->getCallee();
4032 if (isa
<MemberExpr
>(Callee
)) {
4033 HandleValue(Callee
, false /*AddressOf*/);
4034 for (auto *Arg
: E
->arguments())
4039 Inherited::VisitCXXMemberCallExpr(E
);
4042 void VisitCallExpr(CallExpr
*E
) {
4043 // Treat std::move as a use.
4044 if (E
->isCallToStdMove()) {
4045 HandleValue(E
->getArg(0), /*AddressOf=*/false);
4049 Inherited::VisitCallExpr(E
);
4052 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr
*E
) {
4053 Expr
*Callee
= E
->getCallee();
4055 if (isa
<UnresolvedLookupExpr
>(Callee
))
4056 return Inherited::VisitCXXOperatorCallExpr(E
);
4059 for (auto *Arg
: E
->arguments())
4060 HandleValue(Arg
->IgnoreParenImpCasts(), false /*AddressOf*/);
4063 void VisitBinaryOperator(BinaryOperator
*E
) {
4064 // If a field assignment is detected, remove the field from the
4065 // uninitiailized field set.
4066 if (E
->getOpcode() == BO_Assign
)
4067 if (MemberExpr
*ME
= dyn_cast
<MemberExpr
>(E
->getLHS()))
4068 if (FieldDecl
*FD
= dyn_cast
<FieldDecl
>(ME
->getMemberDecl()))
4069 if (!FD
->getType()->isReferenceType())
4070 DeclsToRemove
.push_back(FD
);
4072 if (E
->isCompoundAssignmentOp()) {
4073 HandleValue(E
->getLHS(), false /*AddressOf*/);
4078 Inherited::VisitBinaryOperator(E
);
4081 void VisitUnaryOperator(UnaryOperator
*E
) {
4082 if (E
->isIncrementDecrementOp()) {
4083 HandleValue(E
->getSubExpr(), false /*AddressOf*/);
4086 if (E
->getOpcode() == UO_AddrOf
) {
4087 if (MemberExpr
*ME
= dyn_cast
<MemberExpr
>(E
->getSubExpr())) {
4088 HandleValue(ME
->getBase(), true /*AddressOf*/);
4093 Inherited::VisitUnaryOperator(E
);
4097 // Diagnose value-uses of fields to initialize themselves, e.g.
4099 // where foo is not also a parameter to the constructor.
4100 // Also diagnose across field uninitialized use such as
4102 // TODO: implement -Wuninitialized and fold this into that framework.
4103 static void DiagnoseUninitializedFields(
4104 Sema
&SemaRef
, const CXXConstructorDecl
*Constructor
) {
4106 if (SemaRef
.getDiagnostics().isIgnored(diag::warn_field_is_uninit
,
4107 Constructor
->getLocation())) {
4111 if (Constructor
->isInvalidDecl())
4114 const CXXRecordDecl
*RD
= Constructor
->getParent();
4116 if (RD
->isDependentContext())
4119 // Holds fields that are uninitialized.
4120 llvm::SmallPtrSet
<ValueDecl
*, 4> UninitializedFields
;
4122 // At the beginning, all fields are uninitialized.
4123 for (auto *I
: RD
->decls()) {
4124 if (auto *FD
= dyn_cast
<FieldDecl
>(I
)) {
4125 UninitializedFields
.insert(FD
);
4126 } else if (auto *IFD
= dyn_cast
<IndirectFieldDecl
>(I
)) {
4127 UninitializedFields
.insert(IFD
->getAnonField());
4131 llvm::SmallPtrSet
<QualType
, 4> UninitializedBaseClasses
;
4132 for (const auto &I
: RD
->bases())
4133 UninitializedBaseClasses
.insert(I
.getType().getCanonicalType());
4135 if (UninitializedFields
.empty() && UninitializedBaseClasses
.empty())
4138 UninitializedFieldVisitor
UninitializedChecker(SemaRef
,
4139 UninitializedFields
,
4140 UninitializedBaseClasses
);
4142 for (const auto *FieldInit
: Constructor
->inits()) {
4143 if (UninitializedFields
.empty() && UninitializedBaseClasses
.empty())
4146 Expr
*InitExpr
= FieldInit
->getInit();
4150 if (CXXDefaultInitExpr
*Default
=
4151 dyn_cast
<CXXDefaultInitExpr
>(InitExpr
)) {
4152 InitExpr
= Default
->getExpr();
4155 // In class initializers will point to the constructor.
4156 UninitializedChecker
.CheckInitializer(InitExpr
, Constructor
,
4157 FieldInit
->getAnyMember(),
4158 FieldInit
->getBaseClass());
4160 UninitializedChecker
.CheckInitializer(InitExpr
, nullptr,
4161 FieldInit
->getAnyMember(),
4162 FieldInit
->getBaseClass());
4168 /// Enter a new C++ default initializer scope. After calling this, the
4169 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
4170 /// parsing or instantiating the initializer failed.
4171 void Sema::ActOnStartCXXInClassMemberInitializer() {
4172 // Create a synthetic function scope to represent the call to the constructor
4173 // that notionally surrounds a use of this initializer.
4174 PushFunctionScope();
4177 void Sema::ActOnStartTrailingRequiresClause(Scope
*S
, Declarator
&D
) {
4178 if (!D
.isFunctionDeclarator())
4180 auto &FTI
= D
.getFunctionTypeInfo();
4183 for (auto &Param
: ArrayRef
<DeclaratorChunk::ParamInfo
>(FTI
.Params
,
4185 auto *ParamDecl
= cast
<NamedDecl
>(Param
.Param
);
4186 if (ParamDecl
->getDeclName())
4187 PushOnScopeChains(ParamDecl
, S
, /*AddToContext=*/false);
4191 ExprResult
Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr
) {
4192 return ActOnRequiresClause(ConstraintExpr
);
4195 ExprResult
Sema::ActOnRequiresClause(ExprResult ConstraintExpr
) {
4196 if (ConstraintExpr
.isInvalid())
4199 ConstraintExpr
= CorrectDelayedTyposInExpr(ConstraintExpr
);
4200 if (ConstraintExpr
.isInvalid())
4203 if (DiagnoseUnexpandedParameterPack(ConstraintExpr
.get(),
4204 UPPC_RequiresClause
))
4207 return ConstraintExpr
;
4210 ExprResult
Sema::ConvertMemberDefaultInitExpression(FieldDecl
*FD
,
4212 SourceLocation InitLoc
) {
4213 InitializedEntity Entity
=
4214 InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD
);
4215 InitializationKind Kind
=
4216 FD
->getInClassInitStyle() == ICIS_ListInit
4217 ? InitializationKind::CreateDirectList(InitExpr
->getBeginLoc(),
4218 InitExpr
->getBeginLoc(),
4219 InitExpr
->getEndLoc())
4220 : InitializationKind::CreateCopy(InitExpr
->getBeginLoc(), InitLoc
);
4221 InitializationSequence
Seq(*this, Entity
, Kind
, InitExpr
);
4222 return Seq
.Perform(*this, Entity
, Kind
, InitExpr
);
4225 /// This is invoked after parsing an in-class initializer for a
4226 /// non-static C++ class member, and after instantiating an in-class initializer
4227 /// in a class template. Such actions are deferred until the class is complete.
4228 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl
*D
,
4229 SourceLocation InitLoc
,
4231 // Pop the notional constructor scope we created earlier.
4232 PopFunctionScopeInfo(nullptr, D
);
4234 FieldDecl
*FD
= dyn_cast
<FieldDecl
>(D
);
4235 assert((isa
<MSPropertyDecl
>(D
) || FD
->getInClassInitStyle() != ICIS_NoInit
) &&
4236 "must set init style when field is created");
4239 D
->setInvalidDecl();
4241 FD
->removeInClassInitializer();
4245 if (DiagnoseUnexpandedParameterPack(InitExpr
, UPPC_Initializer
)) {
4246 FD
->setInvalidDecl();
4247 FD
->removeInClassInitializer();
4251 ExprResult Init
= CorrectDelayedTyposInExpr(InitExpr
, /*InitDecl=*/nullptr,
4252 /*RecoverUncorrectedTypos=*/true);
4253 assert(Init
.isUsable() && "Init should at least have a RecoveryExpr");
4254 if (!FD
->getType()->isDependentType() && !Init
.get()->isTypeDependent()) {
4255 Init
= ConvertMemberDefaultInitExpression(FD
, Init
.get(), InitLoc
);
4256 // C++11 [class.base.init]p7:
4257 // The initialization of each base and member constitutes a
4259 if (!Init
.isInvalid())
4260 Init
= ActOnFinishFullExpr(Init
.get(), /*DiscarededValue=*/false);
4261 if (Init
.isInvalid()) {
4262 FD
->setInvalidDecl();
4267 FD
->setInClassInitializer(Init
.get());
4270 /// Find the direct and/or virtual base specifiers that
4271 /// correspond to the given base type, for use in base initialization
4272 /// within a constructor.
4273 static bool FindBaseInitializer(Sema
&SemaRef
,
4274 CXXRecordDecl
*ClassDecl
,
4276 const CXXBaseSpecifier
*&DirectBaseSpec
,
4277 const CXXBaseSpecifier
*&VirtualBaseSpec
) {
4278 // First, check for a direct base class.
4279 DirectBaseSpec
= nullptr;
4280 for (const auto &Base
: ClassDecl
->bases()) {
4281 if (SemaRef
.Context
.hasSameUnqualifiedType(BaseType
, Base
.getType())) {
4282 // We found a direct base of this type. That's what we're
4284 DirectBaseSpec
= &Base
;
4289 // Check for a virtual base class.
4290 // FIXME: We might be able to short-circuit this if we know in advance that
4291 // there are no virtual bases.
4292 VirtualBaseSpec
= nullptr;
4293 if (!DirectBaseSpec
|| !DirectBaseSpec
->isVirtual()) {
4294 // We haven't found a base yet; search the class hierarchy for a
4295 // virtual base class.
4296 CXXBasePaths
Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
4297 /*DetectVirtual=*/false);
4298 if (SemaRef
.IsDerivedFrom(ClassDecl
->getLocation(),
4299 SemaRef
.Context
.getTypeDeclType(ClassDecl
),
4301 for (CXXBasePaths::paths_iterator Path
= Paths
.begin();
4302 Path
!= Paths
.end(); ++Path
) {
4303 if (Path
->back().Base
->isVirtual()) {
4304 VirtualBaseSpec
= Path
->back().Base
;
4311 return DirectBaseSpec
|| VirtualBaseSpec
;
4314 /// Handle a C++ member initializer using braced-init-list syntax.
4316 Sema::ActOnMemInitializer(Decl
*ConstructorD
,
4319 IdentifierInfo
*MemberOrBase
,
4320 ParsedType TemplateTypeTy
,
4322 SourceLocation IdLoc
,
4324 SourceLocation EllipsisLoc
) {
4325 return BuildMemInitializer(ConstructorD
, S
, SS
, MemberOrBase
, TemplateTypeTy
,
4326 DS
, IdLoc
, InitList
,
4330 /// Handle a C++ member initializer using parentheses syntax.
4332 Sema::ActOnMemInitializer(Decl
*ConstructorD
,
4335 IdentifierInfo
*MemberOrBase
,
4336 ParsedType TemplateTypeTy
,
4338 SourceLocation IdLoc
,
4339 SourceLocation LParenLoc
,
4340 ArrayRef
<Expr
*> Args
,
4341 SourceLocation RParenLoc
,
4342 SourceLocation EllipsisLoc
) {
4343 Expr
*List
= ParenListExpr::Create(Context
, LParenLoc
, Args
, RParenLoc
);
4344 return BuildMemInitializer(ConstructorD
, S
, SS
, MemberOrBase
, TemplateTypeTy
,
4345 DS
, IdLoc
, List
, EllipsisLoc
);
4350 // Callback to only accept typo corrections that can be a valid C++ member
4351 // initializer: either a non-static field member or a base class.
4352 class MemInitializerValidatorCCC final
: public CorrectionCandidateCallback
{
4354 explicit MemInitializerValidatorCCC(CXXRecordDecl
*ClassDecl
)
4355 : ClassDecl(ClassDecl
) {}
4357 bool ValidateCandidate(const TypoCorrection
&candidate
) override
{
4358 if (NamedDecl
*ND
= candidate
.getCorrectionDecl()) {
4359 if (FieldDecl
*Member
= dyn_cast
<FieldDecl
>(ND
))
4360 return Member
->getDeclContext()->getRedeclContext()->Equals(ClassDecl
);
4361 return isa
<TypeDecl
>(ND
);
4366 std::unique_ptr
<CorrectionCandidateCallback
> clone() override
{
4367 return std::make_unique
<MemInitializerValidatorCCC
>(*this);
4371 CXXRecordDecl
*ClassDecl
;
4376 bool Sema::DiagRedefinedPlaceholderFieldDecl(SourceLocation Loc
,
4377 RecordDecl
*ClassDecl
,
4378 const IdentifierInfo
*Name
) {
4379 DeclContextLookupResult Result
= ClassDecl
->lookup(Name
);
4380 DeclContextLookupResult::iterator Found
=
4381 llvm::find_if(Result
, [this](const NamedDecl
*Elem
) {
4382 return isa
<FieldDecl
, IndirectFieldDecl
>(Elem
) &&
4383 Elem
->isPlaceholderVar(getLangOpts());
4385 // We did not find a placeholder variable
4386 if (Found
== Result
.end())
4388 Diag(Loc
, diag::err_using_placeholder_variable
) << Name
;
4389 for (DeclContextLookupResult::iterator It
= Found
; It
!= Result
.end(); It
++) {
4390 const NamedDecl
*ND
= *It
;
4391 if (ND
->getDeclContext() != ND
->getDeclContext())
4393 if (isa
<FieldDecl
, IndirectFieldDecl
>(ND
) &&
4394 ND
->isPlaceholderVar(getLangOpts()))
4395 Diag(ND
->getLocation(), diag::note_reference_placeholder
) << ND
;
4401 Sema::tryLookupUnambiguousFieldDecl(RecordDecl
*ClassDecl
,
4402 const IdentifierInfo
*MemberOrBase
) {
4403 ValueDecl
*ND
= nullptr;
4404 for (auto *D
: ClassDecl
->lookup(MemberOrBase
)) {
4405 if (isa
<FieldDecl
, IndirectFieldDecl
>(D
)) {
4406 bool IsPlaceholder
= D
->isPlaceholderVar(getLangOpts());
4408 if (IsPlaceholder
&& D
->getDeclContext() == ND
->getDeclContext())
4413 return cast
<ValueDecl
>(D
);
4414 ND
= cast
<ValueDecl
>(D
);
4420 ValueDecl
*Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl
*ClassDecl
,
4422 ParsedType TemplateTypeTy
,
4423 IdentifierInfo
*MemberOrBase
) {
4424 if (SS
.getScopeRep() || TemplateTypeTy
)
4426 return tryLookupUnambiguousFieldDecl(ClassDecl
, MemberOrBase
);
4429 /// Handle a C++ member initializer.
4431 Sema::BuildMemInitializer(Decl
*ConstructorD
,
4434 IdentifierInfo
*MemberOrBase
,
4435 ParsedType TemplateTypeTy
,
4437 SourceLocation IdLoc
,
4439 SourceLocation EllipsisLoc
) {
4440 ExprResult Res
= CorrectDelayedTyposInExpr(Init
, /*InitDecl=*/nullptr,
4441 /*RecoverUncorrectedTypos=*/true);
4442 if (!Res
.isUsable())
4449 AdjustDeclIfTemplate(ConstructorD
);
4451 CXXConstructorDecl
*Constructor
4452 = dyn_cast
<CXXConstructorDecl
>(ConstructorD
);
4454 // The user wrote a constructor initializer on a function that is
4455 // not a C++ constructor. Ignore the error for now, because we may
4456 // have more member initializers coming; we'll diagnose it just
4457 // once in ActOnMemInitializers.
4461 CXXRecordDecl
*ClassDecl
= Constructor
->getParent();
4463 // C++ [class.base.init]p2:
4464 // Names in a mem-initializer-id are looked up in the scope of the
4465 // constructor's class and, if not found in that scope, are looked
4466 // up in the scope containing the constructor's definition.
4467 // [Note: if the constructor's class contains a member with the
4468 // same name as a direct or virtual base class of the class, a
4469 // mem-initializer-id naming the member or base class and composed
4470 // of a single identifier refers to the class member. A
4471 // mem-initializer-id for the hidden base class may be specified
4472 // using a qualified name. ]
4474 // Look for a member, first.
4475 if (ValueDecl
*Member
= tryLookupCtorInitMemberDecl(
4476 ClassDecl
, SS
, TemplateTypeTy
, MemberOrBase
)) {
4477 if (EllipsisLoc
.isValid())
4478 Diag(EllipsisLoc
, diag::err_pack_expansion_member_init
)
4480 << SourceRange(IdLoc
, Init
->getSourceRange().getEnd());
4482 return BuildMemberInitializer(Member
, Init
, IdLoc
);
4484 // It didn't name a member, so see if it names a class.
4486 TypeSourceInfo
*TInfo
= nullptr;
4488 if (TemplateTypeTy
) {
4489 BaseType
= GetTypeFromParser(TemplateTypeTy
, &TInfo
);
4490 if (BaseType
.isNull())
4492 } else if (DS
.getTypeSpecType() == TST_decltype
) {
4493 BaseType
= BuildDecltypeType(DS
.getRepAsExpr());
4494 } else if (DS
.getTypeSpecType() == TST_decltype_auto
) {
4495 Diag(DS
.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid
);
4498 LookupResult
R(*this, MemberOrBase
, IdLoc
, LookupOrdinaryName
);
4499 LookupParsedName(R
, S
, &SS
);
4501 TypeDecl
*TyD
= R
.getAsSingle
<TypeDecl
>();
4503 if (R
.isAmbiguous()) return true;
4505 // We don't want access-control diagnostics here.
4506 R
.suppressDiagnostics();
4508 if (SS
.isSet() && isDependentScopeSpecifier(SS
)) {
4509 bool NotUnknownSpecialization
= false;
4510 DeclContext
*DC
= computeDeclContext(SS
, false);
4511 if (CXXRecordDecl
*Record
= dyn_cast_or_null
<CXXRecordDecl
>(DC
))
4512 NotUnknownSpecialization
= !Record
->hasAnyDependentBases();
4514 if (!NotUnknownSpecialization
) {
4515 // When the scope specifier can refer to a member of an unknown
4516 // specialization, we take it as a type name.
4517 BaseType
= CheckTypenameType(
4518 ElaboratedTypeKeyword::None
, SourceLocation(),
4519 SS
.getWithLocInContext(Context
), *MemberOrBase
, IdLoc
);
4520 if (BaseType
.isNull())
4523 TInfo
= Context
.CreateTypeSourceInfo(BaseType
);
4524 DependentNameTypeLoc TL
=
4525 TInfo
->getTypeLoc().castAs
<DependentNameTypeLoc
>();
4527 TL
.setNameLoc(IdLoc
);
4528 TL
.setElaboratedKeywordLoc(SourceLocation());
4529 TL
.setQualifierLoc(SS
.getWithLocInContext(Context
));
4533 R
.setLookupName(MemberOrBase
);
4537 if (getLangOpts().MSVCCompat
&& !getLangOpts().CPlusPlus20
) {
4538 if (auto UnqualifiedBase
= R
.getAsSingle
<ClassTemplateDecl
>()) {
4539 auto *TempSpec
= cast
<TemplateSpecializationType
>(
4540 UnqualifiedBase
->getInjectedClassNameSpecialization());
4541 TemplateName TN
= TempSpec
->getTemplateName();
4542 for (auto const &Base
: ClassDecl
->bases()) {
4544 Base
.getType()->getAs
<TemplateSpecializationType
>();
4545 if (BaseTemplate
&& Context
.hasSameTemplateName(
4546 BaseTemplate
->getTemplateName(), TN
)) {
4547 Diag(IdLoc
, diag::ext_unqualified_base_class
)
4548 << SourceRange(IdLoc
, Init
->getSourceRange().getEnd());
4549 BaseType
= Base
.getType();
4556 // If no results were found, try to correct typos.
4557 TypoCorrection Corr
;
4558 MemInitializerValidatorCCC
CCC(ClassDecl
);
4559 if (R
.empty() && BaseType
.isNull() &&
4560 (Corr
= CorrectTypo(R
.getLookupNameInfo(), R
.getLookupKind(), S
, &SS
,
4561 CCC
, CTK_ErrorRecovery
, ClassDecl
))) {
4562 if (FieldDecl
*Member
= Corr
.getCorrectionDeclAs
<FieldDecl
>()) {
4563 // We have found a non-static data member with a similar
4564 // name to what was typed; complain and initialize that
4567 PDiag(diag::err_mem_init_not_member_or_class_suggest
)
4568 << MemberOrBase
<< true);
4569 return BuildMemberInitializer(Member
, Init
, IdLoc
);
4570 } else if (TypeDecl
*Type
= Corr
.getCorrectionDeclAs
<TypeDecl
>()) {
4571 const CXXBaseSpecifier
*DirectBaseSpec
;
4572 const CXXBaseSpecifier
*VirtualBaseSpec
;
4573 if (FindBaseInitializer(*this, ClassDecl
,
4574 Context
.getTypeDeclType(Type
),
4575 DirectBaseSpec
, VirtualBaseSpec
)) {
4576 // We have found a direct or virtual base class with a
4577 // similar name to what was typed; complain and initialize
4580 PDiag(diag::err_mem_init_not_member_or_class_suggest
)
4581 << MemberOrBase
<< false,
4582 PDiag() /*Suppress note, we provide our own.*/);
4584 const CXXBaseSpecifier
*BaseSpec
= DirectBaseSpec
? DirectBaseSpec
4586 Diag(BaseSpec
->getBeginLoc(), diag::note_base_class_specified_here
)
4587 << BaseSpec
->getType() << BaseSpec
->getSourceRange();
4594 if (!TyD
&& BaseType
.isNull()) {
4595 Diag(IdLoc
, diag::err_mem_init_not_member_or_class
)
4596 << MemberOrBase
<< SourceRange(IdLoc
,Init
->getSourceRange().getEnd());
4601 if (BaseType
.isNull()) {
4602 BaseType
= getElaboratedType(ElaboratedTypeKeyword::None
, SS
,
4603 Context
.getTypeDeclType(TyD
));
4604 MarkAnyDeclReferenced(TyD
->getLocation(), TyD
, /*OdrUse=*/false);
4605 TInfo
= Context
.CreateTypeSourceInfo(BaseType
);
4606 ElaboratedTypeLoc TL
= TInfo
->getTypeLoc().castAs
<ElaboratedTypeLoc
>();
4607 TL
.getNamedTypeLoc().castAs
<TypeSpecTypeLoc
>().setNameLoc(IdLoc
);
4608 TL
.setElaboratedKeywordLoc(SourceLocation());
4609 TL
.setQualifierLoc(SS
.getWithLocInContext(Context
));
4614 TInfo
= Context
.getTrivialTypeSourceInfo(BaseType
, IdLoc
);
4616 return BuildBaseInitializer(BaseType
, TInfo
, Init
, ClassDecl
, EllipsisLoc
);
4620 Sema::BuildMemberInitializer(ValueDecl
*Member
, Expr
*Init
,
4621 SourceLocation IdLoc
) {
4622 FieldDecl
*DirectMember
= dyn_cast
<FieldDecl
>(Member
);
4623 IndirectFieldDecl
*IndirectMember
= dyn_cast
<IndirectFieldDecl
>(Member
);
4624 assert((DirectMember
|| IndirectMember
) &&
4625 "Member must be a FieldDecl or IndirectFieldDecl");
4627 if (DiagnoseUnexpandedParameterPack(Init
, UPPC_Initializer
))
4630 if (Member
->isInvalidDecl())
4634 if (ParenListExpr
*ParenList
= dyn_cast
<ParenListExpr
>(Init
)) {
4635 Args
= MultiExprArg(ParenList
->getExprs(), ParenList
->getNumExprs());
4636 } else if (InitListExpr
*InitList
= dyn_cast
<InitListExpr
>(Init
)) {
4637 Args
= MultiExprArg(InitList
->getInits(), InitList
->getNumInits());
4639 // Template instantiation doesn't reconstruct ParenListExprs for us.
4643 SourceRange InitRange
= Init
->getSourceRange();
4645 if (Member
->getType()->isDependentType() || Init
->isTypeDependent()) {
4646 // Can't check initialization for a member of dependent type or when
4647 // any of the arguments are type-dependent expressions.
4648 DiscardCleanupsInEvaluationContext();
4650 bool InitList
= false;
4651 if (isa
<InitListExpr
>(Init
)) {
4656 // Initialize the member.
4657 InitializedEntity MemberEntity
=
4658 DirectMember
? InitializedEntity::InitializeMember(DirectMember
, nullptr)
4659 : InitializedEntity::InitializeMember(IndirectMember
,
4661 InitializationKind Kind
=
4662 InitList
? InitializationKind::CreateDirectList(
4663 IdLoc
, Init
->getBeginLoc(), Init
->getEndLoc())
4664 : InitializationKind::CreateDirect(IdLoc
, InitRange
.getBegin(),
4665 InitRange
.getEnd());
4667 InitializationSequence
InitSeq(*this, MemberEntity
, Kind
, Args
);
4668 ExprResult MemberInit
= InitSeq
.Perform(*this, MemberEntity
, Kind
, Args
,
4670 if (!MemberInit
.isInvalid()) {
4671 // C++11 [class.base.init]p7:
4672 // The initialization of each base and member constitutes a
4674 MemberInit
= ActOnFinishFullExpr(MemberInit
.get(), InitRange
.getBegin(),
4675 /*DiscardedValue*/ false);
4678 if (MemberInit
.isInvalid()) {
4679 // Args were sensible expressions but we couldn't initialize the member
4680 // from them. Preserve them in a RecoveryExpr instead.
4681 Init
= CreateRecoveryExpr(InitRange
.getBegin(), InitRange
.getEnd(), Args
,
4687 Init
= MemberInit
.get();
4692 return new (Context
) CXXCtorInitializer(Context
, DirectMember
, IdLoc
,
4693 InitRange
.getBegin(), Init
,
4694 InitRange
.getEnd());
4696 return new (Context
) CXXCtorInitializer(Context
, IndirectMember
, IdLoc
,
4697 InitRange
.getBegin(), Init
,
4698 InitRange
.getEnd());
4703 Sema::BuildDelegatingInitializer(TypeSourceInfo
*TInfo
, Expr
*Init
,
4704 CXXRecordDecl
*ClassDecl
) {
4705 SourceLocation NameLoc
= TInfo
->getTypeLoc().getSourceRange().getBegin();
4706 if (!LangOpts
.CPlusPlus11
)
4707 return Diag(NameLoc
, diag::err_delegating_ctor
)
4708 << TInfo
->getTypeLoc().getSourceRange();
4709 Diag(NameLoc
, diag::warn_cxx98_compat_delegating_ctor
);
4711 bool InitList
= true;
4712 MultiExprArg Args
= Init
;
4713 if (ParenListExpr
*ParenList
= dyn_cast
<ParenListExpr
>(Init
)) {
4715 Args
= MultiExprArg(ParenList
->getExprs(), ParenList
->getNumExprs());
4718 SourceRange InitRange
= Init
->getSourceRange();
4719 // Initialize the object.
4720 InitializedEntity DelegationEntity
= InitializedEntity::InitializeDelegation(
4721 QualType(ClassDecl
->getTypeForDecl(), 0));
4722 InitializationKind Kind
=
4723 InitList
? InitializationKind::CreateDirectList(
4724 NameLoc
, Init
->getBeginLoc(), Init
->getEndLoc())
4725 : InitializationKind::CreateDirect(NameLoc
, InitRange
.getBegin(),
4726 InitRange
.getEnd());
4727 InitializationSequence
InitSeq(*this, DelegationEntity
, Kind
, Args
);
4728 ExprResult DelegationInit
= InitSeq
.Perform(*this, DelegationEntity
, Kind
,
4730 if (!DelegationInit
.isInvalid()) {
4731 assert((DelegationInit
.get()->containsErrors() ||
4732 cast
<CXXConstructExpr
>(DelegationInit
.get())->getConstructor()) &&
4733 "Delegating constructor with no target?");
4735 // C++11 [class.base.init]p7:
4736 // The initialization of each base and member constitutes a
4738 DelegationInit
= ActOnFinishFullExpr(
4739 DelegationInit
.get(), InitRange
.getBegin(), /*DiscardedValue*/ false);
4742 if (DelegationInit
.isInvalid()) {
4744 CreateRecoveryExpr(InitRange
.getBegin(), InitRange
.getEnd(), Args
,
4745 QualType(ClassDecl
->getTypeForDecl(), 0));
4746 if (DelegationInit
.isInvalid())
4749 // If we are in a dependent context, template instantiation will
4750 // perform this type-checking again. Just save the arguments that we
4751 // received in a ParenListExpr.
4752 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4753 // of the information that we have about the base
4754 // initializer. However, deconstructing the ASTs is a dicey process,
4755 // and this approach is far more likely to get the corner cases right.
4756 if (CurContext
->isDependentContext())
4757 DelegationInit
= Init
;
4760 return new (Context
) CXXCtorInitializer(Context
, TInfo
, InitRange
.getBegin(),
4761 DelegationInit
.getAs
<Expr
>(),
4762 InitRange
.getEnd());
4766 Sema::BuildBaseInitializer(QualType BaseType
, TypeSourceInfo
*BaseTInfo
,
4767 Expr
*Init
, CXXRecordDecl
*ClassDecl
,
4768 SourceLocation EllipsisLoc
) {
4769 SourceLocation BaseLoc
= BaseTInfo
->getTypeLoc().getBeginLoc();
4771 if (!BaseType
->isDependentType() && !BaseType
->isRecordType())
4772 return Diag(BaseLoc
, diag::err_base_init_does_not_name_class
)
4773 << BaseType
<< BaseTInfo
->getTypeLoc().getSourceRange();
4775 // C++ [class.base.init]p2:
4776 // [...] Unless the mem-initializer-id names a nonstatic data
4777 // member of the constructor's class or a direct or virtual base
4778 // of that class, the mem-initializer is ill-formed. A
4779 // mem-initializer-list can initialize a base class using any
4780 // name that denotes that base class type.
4782 // We can store the initializers in "as-written" form and delay analysis until
4783 // instantiation if the constructor is dependent. But not for dependent
4784 // (broken) code in a non-template! SetCtorInitializers does not expect this.
4785 bool Dependent
= CurContext
->isDependentContext() &&
4786 (BaseType
->isDependentType() || Init
->isTypeDependent());
4788 SourceRange InitRange
= Init
->getSourceRange();
4789 if (EllipsisLoc
.isValid()) {
4790 // This is a pack expansion.
4791 if (!BaseType
->containsUnexpandedParameterPack()) {
4792 Diag(EllipsisLoc
, diag::err_pack_expansion_without_parameter_packs
)
4793 << SourceRange(BaseLoc
, InitRange
.getEnd());
4795 EllipsisLoc
= SourceLocation();
4798 // Check for any unexpanded parameter packs.
4799 if (DiagnoseUnexpandedParameterPack(BaseLoc
, BaseTInfo
, UPPC_Initializer
))
4802 if (DiagnoseUnexpandedParameterPack(Init
, UPPC_Initializer
))
4806 // Check for direct and virtual base classes.
4807 const CXXBaseSpecifier
*DirectBaseSpec
= nullptr;
4808 const CXXBaseSpecifier
*VirtualBaseSpec
= nullptr;
4810 if (Context
.hasSameUnqualifiedType(QualType(ClassDecl
->getTypeForDecl(),0),
4812 return BuildDelegatingInitializer(BaseTInfo
, Init
, ClassDecl
);
4814 FindBaseInitializer(*this, ClassDecl
, BaseType
, DirectBaseSpec
,
4817 // C++ [base.class.init]p2:
4818 // Unless the mem-initializer-id names a nonstatic data member of the
4819 // constructor's class or a direct or virtual base of that class, the
4820 // mem-initializer is ill-formed.
4821 if (!DirectBaseSpec
&& !VirtualBaseSpec
) {
4822 // If the class has any dependent bases, then it's possible that
4823 // one of those types will resolve to the same type as
4824 // BaseType. Therefore, just treat this as a dependent base
4825 // class initialization. FIXME: Should we try to check the
4826 // initialization anyway? It seems odd.
4827 if (ClassDecl
->hasAnyDependentBases())
4830 return Diag(BaseLoc
, diag::err_not_direct_base_or_virtual
)
4831 << BaseType
<< Context
.getTypeDeclType(ClassDecl
)
4832 << BaseTInfo
->getTypeLoc().getSourceRange();
4837 DiscardCleanupsInEvaluationContext();
4839 return new (Context
) CXXCtorInitializer(Context
, BaseTInfo
,
4840 /*IsVirtual=*/false,
4841 InitRange
.getBegin(), Init
,
4842 InitRange
.getEnd(), EllipsisLoc
);
4845 // C++ [base.class.init]p2:
4846 // If a mem-initializer-id is ambiguous because it designates both
4847 // a direct non-virtual base class and an inherited virtual base
4848 // class, the mem-initializer is ill-formed.
4849 if (DirectBaseSpec
&& VirtualBaseSpec
)
4850 return Diag(BaseLoc
, diag::err_base_init_direct_and_virtual
)
4851 << BaseType
<< BaseTInfo
->getTypeLoc().getLocalSourceRange();
4853 const CXXBaseSpecifier
*BaseSpec
= DirectBaseSpec
;
4855 BaseSpec
= VirtualBaseSpec
;
4857 // Initialize the base.
4858 bool InitList
= true;
4859 MultiExprArg Args
= Init
;
4860 if (ParenListExpr
*ParenList
= dyn_cast
<ParenListExpr
>(Init
)) {
4862 Args
= MultiExprArg(ParenList
->getExprs(), ParenList
->getNumExprs());
4865 InitializedEntity BaseEntity
=
4866 InitializedEntity::InitializeBase(Context
, BaseSpec
, VirtualBaseSpec
);
4867 InitializationKind Kind
=
4868 InitList
? InitializationKind::CreateDirectList(BaseLoc
)
4869 : InitializationKind::CreateDirect(BaseLoc
, InitRange
.getBegin(),
4870 InitRange
.getEnd());
4871 InitializationSequence
InitSeq(*this, BaseEntity
, Kind
, Args
);
4872 ExprResult BaseInit
= InitSeq
.Perform(*this, BaseEntity
, Kind
, Args
, nullptr);
4873 if (!BaseInit
.isInvalid()) {
4874 // C++11 [class.base.init]p7:
4875 // The initialization of each base and member constitutes a
4877 BaseInit
= ActOnFinishFullExpr(BaseInit
.get(), InitRange
.getBegin(),
4878 /*DiscardedValue*/ false);
4881 if (BaseInit
.isInvalid()) {
4882 BaseInit
= CreateRecoveryExpr(InitRange
.getBegin(), InitRange
.getEnd(),
4884 if (BaseInit
.isInvalid())
4887 // If we are in a dependent context, template instantiation will
4888 // perform this type-checking again. Just save the arguments that we
4889 // received in a ParenListExpr.
4890 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4891 // of the information that we have about the base
4892 // initializer. However, deconstructing the ASTs is a dicey process,
4893 // and this approach is far more likely to get the corner cases right.
4894 if (CurContext
->isDependentContext())
4898 return new (Context
) CXXCtorInitializer(Context
, BaseTInfo
,
4899 BaseSpec
->isVirtual(),
4900 InitRange
.getBegin(),
4901 BaseInit
.getAs
<Expr
>(),
4902 InitRange
.getEnd(), EllipsisLoc
);
4905 // Create a static_cast\<T&&>(expr).
4906 static Expr
*CastForMoving(Sema
&SemaRef
, Expr
*E
) {
4907 QualType TargetType
=
4908 SemaRef
.BuildReferenceType(E
->getType(), /*SpelledAsLValue*/ false,
4909 SourceLocation(), DeclarationName());
4910 SourceLocation ExprLoc
= E
->getBeginLoc();
4911 TypeSourceInfo
*TargetLoc
= SemaRef
.Context
.getTrivialTypeSourceInfo(
4912 TargetType
, ExprLoc
);
4914 return SemaRef
.BuildCXXNamedCast(ExprLoc
, tok::kw_static_cast
, TargetLoc
, E
,
4915 SourceRange(ExprLoc
, ExprLoc
),
4916 E
->getSourceRange()).get();
4919 /// ImplicitInitializerKind - How an implicit base or member initializer should
4920 /// initialize its base or member.
4921 enum ImplicitInitializerKind
{
4929 BuildImplicitBaseInitializer(Sema
&SemaRef
, CXXConstructorDecl
*Constructor
,
4930 ImplicitInitializerKind ImplicitInitKind
,
4931 CXXBaseSpecifier
*BaseSpec
,
4932 bool IsInheritedVirtualBase
,
4933 CXXCtorInitializer
*&CXXBaseInit
) {
4934 InitializedEntity InitEntity
4935 = InitializedEntity::InitializeBase(SemaRef
.Context
, BaseSpec
,
4936 IsInheritedVirtualBase
);
4938 ExprResult BaseInit
;
4940 switch (ImplicitInitKind
) {
4943 InitializationKind InitKind
4944 = InitializationKind::CreateDefault(Constructor
->getLocation());
4945 InitializationSequence
InitSeq(SemaRef
, InitEntity
, InitKind
, std::nullopt
);
4946 BaseInit
= InitSeq
.Perform(SemaRef
, InitEntity
, InitKind
, std::nullopt
);
4952 bool Moving
= ImplicitInitKind
== IIK_Move
;
4953 ParmVarDecl
*Param
= Constructor
->getParamDecl(0);
4954 QualType ParamType
= Param
->getType().getNonReferenceType();
4957 DeclRefExpr::Create(SemaRef
.Context
, NestedNameSpecifierLoc(),
4958 SourceLocation(), Param
, false,
4959 Constructor
->getLocation(), ParamType
,
4960 VK_LValue
, nullptr);
4962 SemaRef
.MarkDeclRefReferenced(cast
<DeclRefExpr
>(CopyCtorArg
));
4964 // Cast to the base class to avoid ambiguities.
4966 SemaRef
.Context
.getQualifiedType(BaseSpec
->getType().getUnqualifiedType(),
4967 ParamType
.getQualifiers());
4970 CopyCtorArg
= CastForMoving(SemaRef
, CopyCtorArg
);
4973 CXXCastPath BasePath
;
4974 BasePath
.push_back(BaseSpec
);
4975 CopyCtorArg
= SemaRef
.ImpCastExprToType(CopyCtorArg
, ArgTy
,
4976 CK_UncheckedDerivedToBase
,
4977 Moving
? VK_XValue
: VK_LValue
,
4980 InitializationKind InitKind
4981 = InitializationKind::CreateDirect(Constructor
->getLocation(),
4982 SourceLocation(), SourceLocation());
4983 InitializationSequence
InitSeq(SemaRef
, InitEntity
, InitKind
, CopyCtorArg
);
4984 BaseInit
= InitSeq
.Perform(SemaRef
, InitEntity
, InitKind
, CopyCtorArg
);
4989 BaseInit
= SemaRef
.MaybeCreateExprWithCleanups(BaseInit
);
4990 if (BaseInit
.isInvalid())
4994 new (SemaRef
.Context
) CXXCtorInitializer(SemaRef
.Context
,
4995 SemaRef
.Context
.getTrivialTypeSourceInfo(BaseSpec
->getType(),
4997 BaseSpec
->isVirtual(),
4999 BaseInit
.getAs
<Expr
>(),
5006 static bool RefersToRValueRef(Expr
*MemRef
) {
5007 ValueDecl
*Referenced
= cast
<MemberExpr
>(MemRef
)->getMemberDecl();
5008 return Referenced
->getType()->isRValueReferenceType();
5012 BuildImplicitMemberInitializer(Sema
&SemaRef
, CXXConstructorDecl
*Constructor
,
5013 ImplicitInitializerKind ImplicitInitKind
,
5014 FieldDecl
*Field
, IndirectFieldDecl
*Indirect
,
5015 CXXCtorInitializer
*&CXXMemberInit
) {
5016 if (Field
->isInvalidDecl())
5019 SourceLocation Loc
= Constructor
->getLocation();
5021 if (ImplicitInitKind
== IIK_Copy
|| ImplicitInitKind
== IIK_Move
) {
5022 bool Moving
= ImplicitInitKind
== IIK_Move
;
5023 ParmVarDecl
*Param
= Constructor
->getParamDecl(0);
5024 QualType ParamType
= Param
->getType().getNonReferenceType();
5026 // Suppress copying zero-width bitfields.
5027 if (Field
->isZeroLengthBitField(SemaRef
.Context
))
5030 Expr
*MemberExprBase
=
5031 DeclRefExpr::Create(SemaRef
.Context
, NestedNameSpecifierLoc(),
5032 SourceLocation(), Param
, false,
5033 Loc
, ParamType
, VK_LValue
, nullptr);
5035 SemaRef
.MarkDeclRefReferenced(cast
<DeclRefExpr
>(MemberExprBase
));
5038 MemberExprBase
= CastForMoving(SemaRef
, MemberExprBase
);
5041 // Build a reference to this field within the parameter.
5043 LookupResult
MemberLookup(SemaRef
, Field
->getDeclName(), Loc
,
5044 Sema::LookupMemberName
);
5045 MemberLookup
.addDecl(Indirect
? cast
<ValueDecl
>(Indirect
)
5046 : cast
<ValueDecl
>(Field
), AS_public
);
5047 MemberLookup
.resolveKind();
5049 = SemaRef
.BuildMemberReferenceExpr(MemberExprBase
,
5053 /*TemplateKWLoc=*/SourceLocation(),
5054 /*FirstQualifierInScope=*/nullptr,
5056 /*TemplateArgs=*/nullptr,
5058 if (CtorArg
.isInvalid())
5061 // C++11 [class.copy]p15:
5062 // - if a member m has rvalue reference type T&&, it is direct-initialized
5063 // with static_cast<T&&>(x.m);
5064 if (RefersToRValueRef(CtorArg
.get())) {
5065 CtorArg
= CastForMoving(SemaRef
, CtorArg
.get());
5068 InitializedEntity Entity
=
5069 Indirect
? InitializedEntity::InitializeMember(Indirect
, nullptr,
5071 : InitializedEntity::InitializeMember(Field
, nullptr,
5074 // Direct-initialize to use the copy constructor.
5075 InitializationKind InitKind
=
5076 InitializationKind::CreateDirect(Loc
, SourceLocation(), SourceLocation());
5078 Expr
*CtorArgE
= CtorArg
.getAs
<Expr
>();
5079 InitializationSequence
InitSeq(SemaRef
, Entity
, InitKind
, CtorArgE
);
5080 ExprResult MemberInit
=
5081 InitSeq
.Perform(SemaRef
, Entity
, InitKind
, MultiExprArg(&CtorArgE
, 1));
5082 MemberInit
= SemaRef
.MaybeCreateExprWithCleanups(MemberInit
);
5083 if (MemberInit
.isInvalid())
5087 CXXMemberInit
= new (SemaRef
.Context
) CXXCtorInitializer(
5088 SemaRef
.Context
, Indirect
, Loc
, Loc
, MemberInit
.getAs
<Expr
>(), Loc
);
5090 CXXMemberInit
= new (SemaRef
.Context
) CXXCtorInitializer(
5091 SemaRef
.Context
, Field
, Loc
, Loc
, MemberInit
.getAs
<Expr
>(), Loc
);
5095 assert((ImplicitInitKind
== IIK_Default
|| ImplicitInitKind
== IIK_Inherit
) &&
5096 "Unhandled implicit init kind!");
5098 QualType FieldBaseElementType
=
5099 SemaRef
.Context
.getBaseElementType(Field
->getType());
5101 if (FieldBaseElementType
->isRecordType()) {
5102 InitializedEntity InitEntity
=
5103 Indirect
? InitializedEntity::InitializeMember(Indirect
, nullptr,
5105 : InitializedEntity::InitializeMember(Field
, nullptr,
5107 InitializationKind InitKind
=
5108 InitializationKind::CreateDefault(Loc
);
5110 InitializationSequence
InitSeq(SemaRef
, InitEntity
, InitKind
, std::nullopt
);
5111 ExprResult MemberInit
=
5112 InitSeq
.Perform(SemaRef
, InitEntity
, InitKind
, std::nullopt
);
5114 MemberInit
= SemaRef
.MaybeCreateExprWithCleanups(MemberInit
);
5115 if (MemberInit
.isInvalid())
5119 CXXMemberInit
= new (SemaRef
.Context
) CXXCtorInitializer(SemaRef
.Context
,
5125 CXXMemberInit
= new (SemaRef
.Context
) CXXCtorInitializer(SemaRef
.Context
,
5132 if (!Field
->getParent()->isUnion()) {
5133 if (FieldBaseElementType
->isReferenceType()) {
5134 SemaRef
.Diag(Constructor
->getLocation(),
5135 diag::err_uninitialized_member_in_ctor
)
5136 << (int)Constructor
->isImplicit()
5137 << SemaRef
.Context
.getTagDeclType(Constructor
->getParent())
5138 << 0 << Field
->getDeclName();
5139 SemaRef
.Diag(Field
->getLocation(), diag::note_declared_at
);
5143 if (FieldBaseElementType
.isConstQualified()) {
5144 SemaRef
.Diag(Constructor
->getLocation(),
5145 diag::err_uninitialized_member_in_ctor
)
5146 << (int)Constructor
->isImplicit()
5147 << SemaRef
.Context
.getTagDeclType(Constructor
->getParent())
5148 << 1 << Field
->getDeclName();
5149 SemaRef
.Diag(Field
->getLocation(), diag::note_declared_at
);
5154 if (FieldBaseElementType
.hasNonTrivialObjCLifetime()) {
5156 // Default-initialize Objective-C pointers to NULL.
5158 = new (SemaRef
.Context
) CXXCtorInitializer(SemaRef
.Context
, Field
,
5160 new (SemaRef
.Context
) ImplicitValueInitExpr(Field
->getType()),
5165 // Nothing to initialize.
5166 CXXMemberInit
= nullptr;
5171 struct BaseAndFieldInfo
{
5173 CXXConstructorDecl
*Ctor
;
5174 bool AnyErrorsInInits
;
5175 ImplicitInitializerKind IIK
;
5176 llvm::DenseMap
<const void *, CXXCtorInitializer
*> AllBaseFields
;
5177 SmallVector
<CXXCtorInitializer
*, 8> AllToInit
;
5178 llvm::DenseMap
<TagDecl
*, FieldDecl
*> ActiveUnionMember
;
5180 BaseAndFieldInfo(Sema
&S
, CXXConstructorDecl
*Ctor
, bool ErrorsInInits
)
5181 : S(S
), Ctor(Ctor
), AnyErrorsInInits(ErrorsInInits
) {
5182 bool Generated
= Ctor
->isImplicit() || Ctor
->isDefaulted();
5183 if (Ctor
->getInheritedConstructor())
5185 else if (Generated
&& Ctor
->isCopyConstructor())
5187 else if (Generated
&& Ctor
->isMoveConstructor())
5193 bool isImplicitCopyOrMove() const {
5204 llvm_unreachable("Invalid ImplicitInitializerKind!");
5207 bool addFieldInitializer(CXXCtorInitializer
*Init
) {
5208 AllToInit
.push_back(Init
);
5210 // Check whether this initializer makes the field "used".
5211 if (Init
->getInit()->HasSideEffects(S
.Context
))
5212 S
.UnusedPrivateFields
.remove(Init
->getAnyMember());
5217 bool isInactiveUnionMember(FieldDecl
*Field
) {
5218 RecordDecl
*Record
= Field
->getParent();
5219 if (!Record
->isUnion())
5222 if (FieldDecl
*Active
=
5223 ActiveUnionMember
.lookup(Record
->getCanonicalDecl()))
5224 return Active
!= Field
->getCanonicalDecl();
5226 // In an implicit copy or move constructor, ignore any in-class initializer.
5227 if (isImplicitCopyOrMove())
5230 // If there's no explicit initialization, the field is active only if it
5231 // has an in-class initializer...
5232 if (Field
->hasInClassInitializer())
5234 // ... or it's an anonymous struct or union whose class has an in-class
5236 if (!Field
->isAnonymousStructOrUnion())
5238 CXXRecordDecl
*FieldRD
= Field
->getType()->getAsCXXRecordDecl();
5239 return !FieldRD
->hasInClassInitializer();
5242 /// Determine whether the given field is, or is within, a union member
5243 /// that is inactive (because there was an initializer given for a different
5244 /// member of the union, or because the union was not initialized at all).
5245 bool isWithinInactiveUnionMember(FieldDecl
*Field
,
5246 IndirectFieldDecl
*Indirect
) {
5248 return isInactiveUnionMember(Field
);
5250 for (auto *C
: Indirect
->chain()) {
5251 FieldDecl
*Field
= dyn_cast
<FieldDecl
>(C
);
5252 if (Field
&& isInactiveUnionMember(Field
))
5260 /// Determine whether the given type is an incomplete or zero-lenfgth
5262 static bool isIncompleteOrZeroLengthArrayType(ASTContext
&Context
, QualType T
) {
5263 if (T
->isIncompleteArrayType())
5266 while (const ConstantArrayType
*ArrayT
= Context
.getAsConstantArrayType(T
)) {
5267 if (!ArrayT
->getSize())
5270 T
= ArrayT
->getElementType();
5276 static bool CollectFieldInitializer(Sema
&SemaRef
, BaseAndFieldInfo
&Info
,
5278 IndirectFieldDecl
*Indirect
= nullptr) {
5279 if (Field
->isInvalidDecl())
5282 // Overwhelmingly common case: we have a direct initializer for this field.
5283 if (CXXCtorInitializer
*Init
=
5284 Info
.AllBaseFields
.lookup(Field
->getCanonicalDecl()))
5285 return Info
.addFieldInitializer(Init
);
5287 // C++11 [class.base.init]p8:
5288 // if the entity is a non-static data member that has a
5289 // brace-or-equal-initializer and either
5290 // -- the constructor's class is a union and no other variant member of that
5291 // union is designated by a mem-initializer-id or
5292 // -- the constructor's class is not a union, and, if the entity is a member
5293 // of an anonymous union, no other member of that union is designated by
5294 // a mem-initializer-id,
5295 // the entity is initialized as specified in [dcl.init].
5297 // We also apply the same rules to handle anonymous structs within anonymous
5299 if (Info
.isWithinInactiveUnionMember(Field
, Indirect
))
5302 if (Field
->hasInClassInitializer() && !Info
.isImplicitCopyOrMove()) {
5304 SemaRef
.BuildCXXDefaultInitExpr(Info
.Ctor
->getLocation(), Field
);
5305 if (DIE
.isInvalid())
5308 auto Entity
= InitializedEntity::InitializeMember(Field
, nullptr, true);
5309 SemaRef
.checkInitializerLifetime(Entity
, DIE
.get());
5311 CXXCtorInitializer
*Init
;
5313 Init
= new (SemaRef
.Context
)
5314 CXXCtorInitializer(SemaRef
.Context
, Indirect
, SourceLocation(),
5315 SourceLocation(), DIE
.get(), SourceLocation());
5317 Init
= new (SemaRef
.Context
)
5318 CXXCtorInitializer(SemaRef
.Context
, Field
, SourceLocation(),
5319 SourceLocation(), DIE
.get(), SourceLocation());
5320 return Info
.addFieldInitializer(Init
);
5323 // Don't initialize incomplete or zero-length arrays.
5324 if (isIncompleteOrZeroLengthArrayType(SemaRef
.Context
, Field
->getType()))
5327 // Don't try to build an implicit initializer if there were semantic
5328 // errors in any of the initializers (and therefore we might be
5329 // missing some that the user actually wrote).
5330 if (Info
.AnyErrorsInInits
)
5333 CXXCtorInitializer
*Init
= nullptr;
5334 if (BuildImplicitMemberInitializer(Info
.S
, Info
.Ctor
, Info
.IIK
, Field
,
5341 return Info
.addFieldInitializer(Init
);
5345 Sema::SetDelegatingInitializer(CXXConstructorDecl
*Constructor
,
5346 CXXCtorInitializer
*Initializer
) {
5347 assert(Initializer
->isDelegatingInitializer());
5348 Constructor
->setNumCtorInitializers(1);
5349 CXXCtorInitializer
**initializer
=
5350 new (Context
) CXXCtorInitializer
*[1];
5351 memcpy(initializer
, &Initializer
, sizeof (CXXCtorInitializer
*));
5352 Constructor
->setCtorInitializers(initializer
);
5354 if (CXXDestructorDecl
*Dtor
= LookupDestructor(Constructor
->getParent())) {
5355 MarkFunctionReferenced(Initializer
->getSourceLocation(), Dtor
);
5356 DiagnoseUseOfDecl(Dtor
, Initializer
->getSourceLocation());
5359 DelegatingCtorDecls
.push_back(Constructor
);
5361 DiagnoseUninitializedFields(*this, Constructor
);
5366 bool Sema::SetCtorInitializers(CXXConstructorDecl
*Constructor
, bool AnyErrors
,
5367 ArrayRef
<CXXCtorInitializer
*> Initializers
) {
5368 if (Constructor
->isDependentContext()) {
5369 // Just store the initializers as written, they will be checked during
5371 if (!Initializers
.empty()) {
5372 Constructor
->setNumCtorInitializers(Initializers
.size());
5373 CXXCtorInitializer
**baseOrMemberInitializers
=
5374 new (Context
) CXXCtorInitializer
*[Initializers
.size()];
5375 memcpy(baseOrMemberInitializers
, Initializers
.data(),
5376 Initializers
.size() * sizeof(CXXCtorInitializer
*));
5377 Constructor
->setCtorInitializers(baseOrMemberInitializers
);
5380 // Let template instantiation know whether we had errors.
5382 Constructor
->setInvalidDecl();
5387 BaseAndFieldInfo
Info(*this, Constructor
, AnyErrors
);
5389 // We need to build the initializer AST according to order of construction
5390 // and not what user specified in the Initializers list.
5391 CXXRecordDecl
*ClassDecl
= Constructor
->getParent()->getDefinition();
5395 bool HadError
= false;
5397 for (unsigned i
= 0; i
< Initializers
.size(); i
++) {
5398 CXXCtorInitializer
*Member
= Initializers
[i
];
5400 if (Member
->isBaseInitializer())
5401 Info
.AllBaseFields
[Member
->getBaseClass()->getAs
<RecordType
>()] = Member
;
5403 Info
.AllBaseFields
[Member
->getAnyMember()->getCanonicalDecl()] = Member
;
5405 if (IndirectFieldDecl
*F
= Member
->getIndirectMember()) {
5406 for (auto *C
: F
->chain()) {
5407 FieldDecl
*FD
= dyn_cast
<FieldDecl
>(C
);
5408 if (FD
&& FD
->getParent()->isUnion())
5409 Info
.ActiveUnionMember
.insert(std::make_pair(
5410 FD
->getParent()->getCanonicalDecl(), FD
->getCanonicalDecl()));
5412 } else if (FieldDecl
*FD
= Member
->getMember()) {
5413 if (FD
->getParent()->isUnion())
5414 Info
.ActiveUnionMember
.insert(std::make_pair(
5415 FD
->getParent()->getCanonicalDecl(), FD
->getCanonicalDecl()));
5420 // Keep track of the direct virtual bases.
5421 llvm::SmallPtrSet
<CXXBaseSpecifier
*, 16> DirectVBases
;
5422 for (auto &I
: ClassDecl
->bases()) {
5424 DirectVBases
.insert(&I
);
5427 // Push virtual bases before others.
5428 for (auto &VBase
: ClassDecl
->vbases()) {
5429 if (CXXCtorInitializer
*Value
5430 = Info
.AllBaseFields
.lookup(VBase
.getType()->getAs
<RecordType
>())) {
5431 // [class.base.init]p7, per DR257:
5432 // A mem-initializer where the mem-initializer-id names a virtual base
5433 // class is ignored during execution of a constructor of any class that
5434 // is not the most derived class.
5435 if (ClassDecl
->isAbstract()) {
5436 // FIXME: Provide a fixit to remove the base specifier. This requires
5437 // tracking the location of the associated comma for a base specifier.
5438 Diag(Value
->getSourceLocation(), diag::warn_abstract_vbase_init_ignored
)
5439 << VBase
.getType() << ClassDecl
;
5440 DiagnoseAbstractType(ClassDecl
);
5443 Info
.AllToInit
.push_back(Value
);
5444 } else if (!AnyErrors
&& !ClassDecl
->isAbstract()) {
5445 // [class.base.init]p8, per DR257:
5446 // If a given [...] base class is not named by a mem-initializer-id
5447 // [...] and the entity is not a virtual base class of an abstract
5448 // class, then [...] the entity is default-initialized.
5449 bool IsInheritedVirtualBase
= !DirectVBases
.count(&VBase
);
5450 CXXCtorInitializer
*CXXBaseInit
;
5451 if (BuildImplicitBaseInitializer(*this, Constructor
, Info
.IIK
,
5452 &VBase
, IsInheritedVirtualBase
,
5458 Info
.AllToInit
.push_back(CXXBaseInit
);
5462 // Non-virtual bases.
5463 for (auto &Base
: ClassDecl
->bases()) {
5464 // Virtuals are in the virtual base list and already constructed.
5465 if (Base
.isVirtual())
5468 if (CXXCtorInitializer
*Value
5469 = Info
.AllBaseFields
.lookup(Base
.getType()->getAs
<RecordType
>())) {
5470 Info
.AllToInit
.push_back(Value
);
5471 } else if (!AnyErrors
) {
5472 CXXCtorInitializer
*CXXBaseInit
;
5473 if (BuildImplicitBaseInitializer(*this, Constructor
, Info
.IIK
,
5474 &Base
, /*IsInheritedVirtualBase=*/false,
5480 Info
.AllToInit
.push_back(CXXBaseInit
);
5485 for (auto *Mem
: ClassDecl
->decls()) {
5486 if (auto *F
= dyn_cast
<FieldDecl
>(Mem
)) {
5487 // C++ [class.bit]p2:
5488 // A declaration for a bit-field that omits the identifier declares an
5489 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
5491 if (F
->isUnnamedBitfield())
5494 // If we're not generating the implicit copy/move constructor, then we'll
5495 // handle anonymous struct/union fields based on their individual
5497 if (F
->isAnonymousStructOrUnion() && !Info
.isImplicitCopyOrMove())
5500 if (CollectFieldInitializer(*this, Info
, F
))
5505 // Beyond this point, we only consider default initialization.
5506 if (Info
.isImplicitCopyOrMove())
5509 if (auto *F
= dyn_cast
<IndirectFieldDecl
>(Mem
)) {
5510 if (F
->getType()->isIncompleteArrayType()) {
5511 assert(ClassDecl
->hasFlexibleArrayMember() &&
5512 "Incomplete array type is not valid");
5516 // Initialize each field of an anonymous struct individually.
5517 if (CollectFieldInitializer(*this, Info
, F
->getAnonField(), F
))
5524 unsigned NumInitializers
= Info
.AllToInit
.size();
5525 if (NumInitializers
> 0) {
5526 Constructor
->setNumCtorInitializers(NumInitializers
);
5527 CXXCtorInitializer
**baseOrMemberInitializers
=
5528 new (Context
) CXXCtorInitializer
*[NumInitializers
];
5529 memcpy(baseOrMemberInitializers
, Info
.AllToInit
.data(),
5530 NumInitializers
* sizeof(CXXCtorInitializer
*));
5531 Constructor
->setCtorInitializers(baseOrMemberInitializers
);
5533 // Constructors implicitly reference the base and member
5535 MarkBaseAndMemberDestructorsReferenced(Constructor
->getLocation(),
5536 Constructor
->getParent());
5542 static void PopulateKeysForFields(FieldDecl
*Field
, SmallVectorImpl
<const void*> &IdealInits
) {
5543 if (const RecordType
*RT
= Field
->getType()->getAs
<RecordType
>()) {
5544 const RecordDecl
*RD
= RT
->getDecl();
5545 if (RD
->isAnonymousStructOrUnion()) {
5546 for (auto *Field
: RD
->fields())
5547 PopulateKeysForFields(Field
, IdealInits
);
5551 IdealInits
.push_back(Field
->getCanonicalDecl());
5554 static const void *GetKeyForBase(ASTContext
&Context
, QualType BaseType
) {
5555 return Context
.getCanonicalType(BaseType
).getTypePtr();
5558 static const void *GetKeyForMember(ASTContext
&Context
,
5559 CXXCtorInitializer
*Member
) {
5560 if (!Member
->isAnyMemberInitializer())
5561 return GetKeyForBase(Context
, QualType(Member
->getBaseClass(), 0));
5563 return Member
->getAnyMember()->getCanonicalDecl();
5566 static void AddInitializerToDiag(const Sema::SemaDiagnosticBuilder
&Diag
,
5567 const CXXCtorInitializer
*Previous
,
5568 const CXXCtorInitializer
*Current
) {
5569 if (Previous
->isAnyMemberInitializer())
5570 Diag
<< 0 << Previous
->getAnyMember();
5572 Diag
<< 1 << Previous
->getTypeSourceInfo()->getType();
5574 if (Current
->isAnyMemberInitializer())
5575 Diag
<< 0 << Current
->getAnyMember();
5577 Diag
<< 1 << Current
->getTypeSourceInfo()->getType();
5580 static void DiagnoseBaseOrMemInitializerOrder(
5581 Sema
&SemaRef
, const CXXConstructorDecl
*Constructor
,
5582 ArrayRef
<CXXCtorInitializer
*> Inits
) {
5583 if (Constructor
->getDeclContext()->isDependentContext())
5586 // Don't check initializers order unless the warning is enabled at the
5587 // location of at least one initializer.
5588 bool ShouldCheckOrder
= false;
5589 for (unsigned InitIndex
= 0; InitIndex
!= Inits
.size(); ++InitIndex
) {
5590 CXXCtorInitializer
*Init
= Inits
[InitIndex
];
5591 if (!SemaRef
.Diags
.isIgnored(diag::warn_initializer_out_of_order
,
5592 Init
->getSourceLocation())) {
5593 ShouldCheckOrder
= true;
5597 if (!ShouldCheckOrder
)
5600 // Build the list of bases and members in the order that they'll
5601 // actually be initialized. The explicit initializers should be in
5602 // this same order but may be missing things.
5603 SmallVector
<const void*, 32> IdealInitKeys
;
5605 const CXXRecordDecl
*ClassDecl
= Constructor
->getParent();
5607 // 1. Virtual bases.
5608 for (const auto &VBase
: ClassDecl
->vbases())
5609 IdealInitKeys
.push_back(GetKeyForBase(SemaRef
.Context
, VBase
.getType()));
5611 // 2. Non-virtual bases.
5612 for (const auto &Base
: ClassDecl
->bases()) {
5613 if (Base
.isVirtual())
5615 IdealInitKeys
.push_back(GetKeyForBase(SemaRef
.Context
, Base
.getType()));
5618 // 3. Direct fields.
5619 for (auto *Field
: ClassDecl
->fields()) {
5620 if (Field
->isUnnamedBitfield())
5623 PopulateKeysForFields(Field
, IdealInitKeys
);
5626 unsigned NumIdealInits
= IdealInitKeys
.size();
5627 unsigned IdealIndex
= 0;
5629 // Track initializers that are in an incorrect order for either a warning or
5630 // note if multiple ones occur.
5631 SmallVector
<unsigned> WarnIndexes
;
5632 // Correlates the index of an initializer in the init-list to the index of
5633 // the field/base in the class.
5634 SmallVector
<std::pair
<unsigned, unsigned>, 32> CorrelatedInitOrder
;
5636 for (unsigned InitIndex
= 0; InitIndex
!= Inits
.size(); ++InitIndex
) {
5637 const void *InitKey
= GetKeyForMember(SemaRef
.Context
, Inits
[InitIndex
]);
5639 // Scan forward to try to find this initializer in the idealized
5640 // initializers list.
5641 for (; IdealIndex
!= NumIdealInits
; ++IdealIndex
)
5642 if (InitKey
== IdealInitKeys
[IdealIndex
])
5645 // If we didn't find this initializer, it must be because we
5646 // scanned past it on a previous iteration. That can only
5647 // happen if we're out of order; emit a warning.
5648 if (IdealIndex
== NumIdealInits
&& InitIndex
) {
5649 WarnIndexes
.push_back(InitIndex
);
5651 // Move back to the initializer's location in the ideal list.
5652 for (IdealIndex
= 0; IdealIndex
!= NumIdealInits
; ++IdealIndex
)
5653 if (InitKey
== IdealInitKeys
[IdealIndex
])
5656 assert(IdealIndex
< NumIdealInits
&&
5657 "initializer not found in initializer list");
5659 CorrelatedInitOrder
.emplace_back(IdealIndex
, InitIndex
);
5662 if (WarnIndexes
.empty())
5665 // Sort based on the ideal order, first in the pair.
5666 llvm::sort(CorrelatedInitOrder
, llvm::less_first());
5668 // Introduce a new scope as SemaDiagnosticBuilder needs to be destroyed to
5669 // emit the diagnostic before we can try adding notes.
5671 Sema::SemaDiagnosticBuilder D
= SemaRef
.Diag(
5672 Inits
[WarnIndexes
.front() - 1]->getSourceLocation(),
5673 WarnIndexes
.size() == 1 ? diag::warn_initializer_out_of_order
5674 : diag::warn_some_initializers_out_of_order
);
5676 for (unsigned I
= 0; I
< CorrelatedInitOrder
.size(); ++I
) {
5677 if (CorrelatedInitOrder
[I
].second
== I
)
5679 // Ideally we would be using InsertFromRange here, but clang doesn't
5680 // appear to handle InsertFromRange correctly when the source range is
5681 // modified by another fix-it.
5682 D
<< FixItHint::CreateReplacement(
5683 Inits
[I
]->getSourceRange(),
5684 Lexer::getSourceText(
5685 CharSourceRange::getTokenRange(
5686 Inits
[CorrelatedInitOrder
[I
].second
]->getSourceRange()),
5687 SemaRef
.getSourceManager(), SemaRef
.getLangOpts()));
5690 // If there is only 1 item out of order, the warning expects the name and
5691 // type of each being added to it.
5692 if (WarnIndexes
.size() == 1) {
5693 AddInitializerToDiag(D
, Inits
[WarnIndexes
.front() - 1],
5694 Inits
[WarnIndexes
.front()]);
5698 // More than 1 item to warn, create notes letting the user know which ones
5700 for (unsigned WarnIndex
: WarnIndexes
) {
5701 const clang::CXXCtorInitializer
*PrevInit
= Inits
[WarnIndex
- 1];
5702 auto D
= SemaRef
.Diag(PrevInit
->getSourceLocation(),
5703 diag::note_initializer_out_of_order
);
5704 AddInitializerToDiag(D
, PrevInit
, Inits
[WarnIndex
]);
5705 D
<< PrevInit
->getSourceRange();
5710 bool CheckRedundantInit(Sema
&S
,
5711 CXXCtorInitializer
*Init
,
5712 CXXCtorInitializer
*&PrevInit
) {
5718 if (FieldDecl
*Field
= Init
->getAnyMember())
5719 S
.Diag(Init
->getSourceLocation(),
5720 diag::err_multiple_mem_initialization
)
5721 << Field
->getDeclName()
5722 << Init
->getSourceRange();
5724 const Type
*BaseClass
= Init
->getBaseClass();
5725 assert(BaseClass
&& "neither field nor base");
5726 S
.Diag(Init
->getSourceLocation(),
5727 diag::err_multiple_base_initialization
)
5728 << QualType(BaseClass
, 0)
5729 << Init
->getSourceRange();
5731 S
.Diag(PrevInit
->getSourceLocation(), diag::note_previous_initializer
)
5732 << 0 << PrevInit
->getSourceRange();
5737 typedef std::pair
<NamedDecl
*, CXXCtorInitializer
*> UnionEntry
;
5738 typedef llvm::DenseMap
<RecordDecl
*, UnionEntry
> RedundantUnionMap
;
5740 bool CheckRedundantUnionInit(Sema
&S
,
5741 CXXCtorInitializer
*Init
,
5742 RedundantUnionMap
&Unions
) {
5743 FieldDecl
*Field
= Init
->getAnyMember();
5744 RecordDecl
*Parent
= Field
->getParent();
5745 NamedDecl
*Child
= Field
;
5747 while (Parent
->isAnonymousStructOrUnion() || Parent
->isUnion()) {
5748 if (Parent
->isUnion()) {
5749 UnionEntry
&En
= Unions
[Parent
];
5750 if (En
.first
&& En
.first
!= Child
) {
5751 S
.Diag(Init
->getSourceLocation(),
5752 diag::err_multiple_mem_union_initialization
)
5753 << Field
->getDeclName()
5754 << Init
->getSourceRange();
5755 S
.Diag(En
.second
->getSourceLocation(), diag::note_previous_initializer
)
5756 << 0 << En
.second
->getSourceRange();
5763 if (!Parent
->isAnonymousStructOrUnion())
5768 Parent
= cast
<RecordDecl
>(Parent
->getDeclContext());
5775 /// ActOnMemInitializers - Handle the member initializers for a constructor.
5776 void Sema::ActOnMemInitializers(Decl
*ConstructorDecl
,
5777 SourceLocation ColonLoc
,
5778 ArrayRef
<CXXCtorInitializer
*> MemInits
,
5780 if (!ConstructorDecl
)
5783 AdjustDeclIfTemplate(ConstructorDecl
);
5785 CXXConstructorDecl
*Constructor
5786 = dyn_cast
<CXXConstructorDecl
>(ConstructorDecl
);
5789 Diag(ColonLoc
, diag::err_only_constructors_take_base_inits
);
5793 // Mapping for the duplicate initializers check.
5794 // For member initializers, this is keyed with a FieldDecl*.
5795 // For base initializers, this is keyed with a Type*.
5796 llvm::DenseMap
<const void *, CXXCtorInitializer
*> Members
;
5798 // Mapping for the inconsistent anonymous-union initializers check.
5799 RedundantUnionMap MemberUnions
;
5801 bool HadError
= false;
5802 for (unsigned i
= 0; i
< MemInits
.size(); i
++) {
5803 CXXCtorInitializer
*Init
= MemInits
[i
];
5805 // Set the source order index.
5806 Init
->setSourceOrder(i
);
5808 if (Init
->isAnyMemberInitializer()) {
5809 const void *Key
= GetKeyForMember(Context
, Init
);
5810 if (CheckRedundantInit(*this, Init
, Members
[Key
]) ||
5811 CheckRedundantUnionInit(*this, Init
, MemberUnions
))
5813 } else if (Init
->isBaseInitializer()) {
5814 const void *Key
= GetKeyForMember(Context
, Init
);
5815 if (CheckRedundantInit(*this, Init
, Members
[Key
]))
5818 assert(Init
->isDelegatingInitializer());
5819 // This must be the only initializer
5820 if (MemInits
.size() != 1) {
5821 Diag(Init
->getSourceLocation(),
5822 diag::err_delegating_initializer_alone
)
5823 << Init
->getSourceRange() << MemInits
[i
? 0 : 1]->getSourceRange();
5824 // We will treat this as being the only initializer.
5826 SetDelegatingInitializer(Constructor
, MemInits
[i
]);
5827 // Return immediately as the initializer is set.
5835 DiagnoseBaseOrMemInitializerOrder(*this, Constructor
, MemInits
);
5837 SetCtorInitializers(Constructor
, AnyErrors
, MemInits
);
5839 DiagnoseUninitializedFields(*this, Constructor
);
5843 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location
,
5844 CXXRecordDecl
*ClassDecl
) {
5845 // Ignore dependent contexts. Also ignore unions, since their members never
5846 // have destructors implicitly called.
5847 if (ClassDecl
->isDependentContext() || ClassDecl
->isUnion())
5850 // FIXME: all the access-control diagnostics are positioned on the
5851 // field/base declaration. That's probably good; that said, the
5852 // user might reasonably want to know why the destructor is being
5853 // emitted, and we currently don't say.
5855 // Non-static data members.
5856 for (auto *Field
: ClassDecl
->fields()) {
5857 if (Field
->isInvalidDecl())
5860 // Don't destroy incomplete or zero-length arrays.
5861 if (isIncompleteOrZeroLengthArrayType(Context
, Field
->getType()))
5864 QualType FieldType
= Context
.getBaseElementType(Field
->getType());
5866 const RecordType
* RT
= FieldType
->getAs
<RecordType
>();
5870 CXXRecordDecl
*FieldClassDecl
= cast
<CXXRecordDecl
>(RT
->getDecl());
5871 if (FieldClassDecl
->isInvalidDecl())
5873 if (FieldClassDecl
->hasIrrelevantDestructor())
5875 // The destructor for an implicit anonymous union member is never invoked.
5876 if (FieldClassDecl
->isUnion() && FieldClassDecl
->isAnonymousStructOrUnion())
5879 CXXDestructorDecl
*Dtor
= LookupDestructor(FieldClassDecl
);
5880 // Dtor might still be missing, e.g because it's invalid.
5883 CheckDestructorAccess(Field
->getLocation(), Dtor
,
5884 PDiag(diag::err_access_dtor_field
)
5885 << Field
->getDeclName()
5888 MarkFunctionReferenced(Location
, Dtor
);
5889 DiagnoseUseOfDecl(Dtor
, Location
);
5892 // We only potentially invoke the destructors of potentially constructed
5894 bool VisitVirtualBases
= !ClassDecl
->isAbstract();
5896 // If the destructor exists and has already been marked used in the MS ABI,
5897 // then virtual base destructors have already been checked and marked used.
5898 // Skip checking them again to avoid duplicate diagnostics.
5899 if (Context
.getTargetInfo().getCXXABI().isMicrosoft()) {
5900 CXXDestructorDecl
*Dtor
= ClassDecl
->getDestructor();
5901 if (Dtor
&& Dtor
->isUsed())
5902 VisitVirtualBases
= false;
5905 llvm::SmallPtrSet
<const RecordType
*, 8> DirectVirtualBases
;
5908 for (const auto &Base
: ClassDecl
->bases()) {
5909 const RecordType
*RT
= Base
.getType()->getAs
<RecordType
>();
5913 // Remember direct virtual bases.
5914 if (Base
.isVirtual()) {
5915 if (!VisitVirtualBases
)
5917 DirectVirtualBases
.insert(RT
);
5920 CXXRecordDecl
*BaseClassDecl
= cast
<CXXRecordDecl
>(RT
->getDecl());
5921 // If our base class is invalid, we probably can't get its dtor anyway.
5922 if (BaseClassDecl
->isInvalidDecl())
5924 if (BaseClassDecl
->hasIrrelevantDestructor())
5927 CXXDestructorDecl
*Dtor
= LookupDestructor(BaseClassDecl
);
5928 // Dtor might still be missing, e.g because it's invalid.
5932 // FIXME: caret should be on the start of the class name
5933 CheckDestructorAccess(Base
.getBeginLoc(), Dtor
,
5934 PDiag(diag::err_access_dtor_base
)
5935 << Base
.getType() << Base
.getSourceRange(),
5936 Context
.getTypeDeclType(ClassDecl
));
5938 MarkFunctionReferenced(Location
, Dtor
);
5939 DiagnoseUseOfDecl(Dtor
, Location
);
5942 if (VisitVirtualBases
)
5943 MarkVirtualBaseDestructorsReferenced(Location
, ClassDecl
,
5944 &DirectVirtualBases
);
5947 void Sema::MarkVirtualBaseDestructorsReferenced(
5948 SourceLocation Location
, CXXRecordDecl
*ClassDecl
,
5949 llvm::SmallPtrSetImpl
<const RecordType
*> *DirectVirtualBases
) {
5951 for (const auto &VBase
: ClassDecl
->vbases()) {
5952 // Bases are always records in a well-formed non-dependent class.
5953 const RecordType
*RT
= VBase
.getType()->castAs
<RecordType
>();
5955 // Ignore already visited direct virtual bases.
5956 if (DirectVirtualBases
&& DirectVirtualBases
->count(RT
))
5959 CXXRecordDecl
*BaseClassDecl
= cast
<CXXRecordDecl
>(RT
->getDecl());
5960 // If our base class is invalid, we probably can't get its dtor anyway.
5961 if (BaseClassDecl
->isInvalidDecl())
5963 if (BaseClassDecl
->hasIrrelevantDestructor())
5966 CXXDestructorDecl
*Dtor
= LookupDestructor(BaseClassDecl
);
5967 // Dtor might still be missing, e.g because it's invalid.
5970 if (CheckDestructorAccess(
5971 ClassDecl
->getLocation(), Dtor
,
5972 PDiag(diag::err_access_dtor_vbase
)
5973 << Context
.getTypeDeclType(ClassDecl
) << VBase
.getType(),
5974 Context
.getTypeDeclType(ClassDecl
)) ==
5976 CheckDerivedToBaseConversion(
5977 Context
.getTypeDeclType(ClassDecl
), VBase
.getType(),
5978 diag::err_access_dtor_vbase
, 0, ClassDecl
->getLocation(),
5979 SourceRange(), DeclarationName(), nullptr);
5982 MarkFunctionReferenced(Location
, Dtor
);
5983 DiagnoseUseOfDecl(Dtor
, Location
);
5987 void Sema::ActOnDefaultCtorInitializers(Decl
*CDtorDecl
) {
5991 if (CXXConstructorDecl
*Constructor
5992 = dyn_cast
<CXXConstructorDecl
>(CDtorDecl
)) {
5993 SetCtorInitializers(Constructor
, /*AnyErrors=*/false);
5994 DiagnoseUninitializedFields(*this, Constructor
);
5998 bool Sema::isAbstractType(SourceLocation Loc
, QualType T
) {
5999 if (!getLangOpts().CPlusPlus
)
6002 const auto *RD
= Context
.getBaseElementType(T
)->getAsCXXRecordDecl();
6006 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
6007 // class template specialization here, but doing so breaks a lot of code.
6009 // We can't answer whether something is abstract until it has a
6010 // definition. If it's currently being defined, we'll walk back
6011 // over all the declarations when we have a full definition.
6012 const CXXRecordDecl
*Def
= RD
->getDefinition();
6013 if (!Def
|| Def
->isBeingDefined())
6016 return RD
->isAbstract();
6019 bool Sema::RequireNonAbstractType(SourceLocation Loc
, QualType T
,
6020 TypeDiagnoser
&Diagnoser
) {
6021 if (!isAbstractType(Loc
, T
))
6024 T
= Context
.getBaseElementType(T
);
6025 Diagnoser
.diagnose(*this, Loc
, T
);
6026 DiagnoseAbstractType(T
->getAsCXXRecordDecl());
6030 void Sema::DiagnoseAbstractType(const CXXRecordDecl
*RD
) {
6031 // Check if we've already emitted the list of pure virtual functions
6033 if (PureVirtualClassDiagSet
&& PureVirtualClassDiagSet
->count(RD
))
6036 // If the diagnostic is suppressed, don't emit the notes. We're only
6037 // going to emit them once, so try to attach them to a diagnostic we're
6038 // actually going to show.
6039 if (Diags
.isLastDiagnosticIgnored())
6042 CXXFinalOverriderMap FinalOverriders
;
6043 RD
->getFinalOverriders(FinalOverriders
);
6045 // Keep a set of seen pure methods so we won't diagnose the same method
6047 llvm::SmallPtrSet
<const CXXMethodDecl
*, 8> SeenPureMethods
;
6049 for (CXXFinalOverriderMap::iterator M
= FinalOverriders
.begin(),
6050 MEnd
= FinalOverriders
.end();
6053 for (OverridingMethods::iterator SO
= M
->second
.begin(),
6054 SOEnd
= M
->second
.end();
6055 SO
!= SOEnd
; ++SO
) {
6056 // C++ [class.abstract]p4:
6057 // A class is abstract if it contains or inherits at least one
6058 // pure virtual function for which the final overrider is pure
6062 if (SO
->second
.size() != 1)
6065 if (!SO
->second
.front().Method
->isPure())
6068 if (!SeenPureMethods
.insert(SO
->second
.front().Method
).second
)
6071 Diag(SO
->second
.front().Method
->getLocation(),
6072 diag::note_pure_virtual_function
)
6073 << SO
->second
.front().Method
->getDeclName() << RD
->getDeclName();
6077 if (!PureVirtualClassDiagSet
)
6078 PureVirtualClassDiagSet
.reset(new RecordDeclSetTy
);
6079 PureVirtualClassDiagSet
->insert(RD
);
6083 struct AbstractUsageInfo
{
6085 CXXRecordDecl
*Record
;
6086 CanQualType AbstractType
;
6089 AbstractUsageInfo(Sema
&S
, CXXRecordDecl
*Record
)
6090 : S(S
), Record(Record
),
6091 AbstractType(S
.Context
.getCanonicalType(
6092 S
.Context
.getTypeDeclType(Record
))),
6095 void DiagnoseAbstractType() {
6096 if (Invalid
) return;
6097 S
.DiagnoseAbstractType(Record
);
6101 void CheckType(const NamedDecl
*D
, TypeLoc TL
, Sema::AbstractDiagSelID Sel
);
6104 struct CheckAbstractUsage
{
6105 AbstractUsageInfo
&Info
;
6106 const NamedDecl
*Ctx
;
6108 CheckAbstractUsage(AbstractUsageInfo
&Info
, const NamedDecl
*Ctx
)
6109 : Info(Info
), Ctx(Ctx
) {}
6111 void Visit(TypeLoc TL
, Sema::AbstractDiagSelID Sel
) {
6112 switch (TL
.getTypeLocClass()) {
6113 #define ABSTRACT_TYPELOC(CLASS, PARENT)
6114 #define TYPELOC(CLASS, PARENT) \
6115 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
6116 #include "clang/AST/TypeLocNodes.def"
6120 void Check(FunctionProtoTypeLoc TL
, Sema::AbstractDiagSelID Sel
) {
6121 Visit(TL
.getReturnLoc(), Sema::AbstractReturnType
);
6122 for (unsigned I
= 0, E
= TL
.getNumParams(); I
!= E
; ++I
) {
6123 if (!TL
.getParam(I
))
6126 TypeSourceInfo
*TSI
= TL
.getParam(I
)->getTypeSourceInfo();
6127 if (TSI
) Visit(TSI
->getTypeLoc(), Sema::AbstractParamType
);
6131 void Check(ArrayTypeLoc TL
, Sema::AbstractDiagSelID Sel
) {
6132 Visit(TL
.getElementLoc(), Sema::AbstractArrayType
);
6135 void Check(TemplateSpecializationTypeLoc TL
, Sema::AbstractDiagSelID Sel
) {
6136 // Visit the type parameters from a permissive context.
6137 for (unsigned I
= 0, E
= TL
.getNumArgs(); I
!= E
; ++I
) {
6138 TemplateArgumentLoc TAL
= TL
.getArgLoc(I
);
6139 if (TAL
.getArgument().getKind() == TemplateArgument::Type
)
6140 if (TypeSourceInfo
*TSI
= TAL
.getTypeSourceInfo())
6141 Visit(TSI
->getTypeLoc(), Sema::AbstractNone
);
6142 // TODO: other template argument types?
6146 // Visit pointee types from a permissive context.
6147 #define CheckPolymorphic(Type) \
6148 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
6149 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
6151 CheckPolymorphic(PointerTypeLoc
)
6152 CheckPolymorphic(ReferenceTypeLoc
)
6153 CheckPolymorphic(MemberPointerTypeLoc
)
6154 CheckPolymorphic(BlockPointerTypeLoc
)
6155 CheckPolymorphic(AtomicTypeLoc
)
6157 /// Handle all the types we haven't given a more specific
6158 /// implementation for above.
6159 void Check(TypeLoc TL
, Sema::AbstractDiagSelID Sel
) {
6160 // Every other kind of type that we haven't called out already
6161 // that has an inner type is either (1) sugar or (2) contains that
6162 // inner type in some way as a subobject.
6163 if (TypeLoc Next
= TL
.getNextTypeLoc())
6164 return Visit(Next
, Sel
);
6166 // If there's no inner type and we're in a permissive context,
6168 if (Sel
== Sema::AbstractNone
) return;
6170 // Check whether the type matches the abstract type.
6171 QualType T
= TL
.getType();
6172 if (T
->isArrayType()) {
6173 Sel
= Sema::AbstractArrayType
;
6174 T
= Info
.S
.Context
.getBaseElementType(T
);
6176 CanQualType CT
= T
->getCanonicalTypeUnqualified().getUnqualifiedType();
6177 if (CT
!= Info
.AbstractType
) return;
6179 // It matched; do some magic.
6180 // FIXME: These should be at most warnings. See P0929R2, CWG1640, CWG1646.
6181 if (Sel
== Sema::AbstractArrayType
) {
6182 Info
.S
.Diag(Ctx
->getLocation(), diag::err_array_of_abstract_type
)
6183 << T
<< TL
.getSourceRange();
6185 Info
.S
.Diag(Ctx
->getLocation(), diag::err_abstract_type_in_decl
)
6186 << Sel
<< T
<< TL
.getSourceRange();
6188 Info
.DiagnoseAbstractType();
6192 void AbstractUsageInfo::CheckType(const NamedDecl
*D
, TypeLoc TL
,
6193 Sema::AbstractDiagSelID Sel
) {
6194 CheckAbstractUsage(*this, D
).Visit(TL
, Sel
);
6199 /// Check for invalid uses of an abstract type in a function declaration.
6200 static void CheckAbstractClassUsage(AbstractUsageInfo
&Info
,
6202 // Only definitions are required to refer to complete and
6203 // non-abstract types.
6204 if (!FD
->doesThisDeclarationHaveABody())
6207 // For safety's sake, just ignore it if we don't have type source
6208 // information. This should never happen for non-implicit methods,
6210 if (TypeSourceInfo
*TSI
= FD
->getTypeSourceInfo())
6211 Info
.CheckType(FD
, TSI
->getTypeLoc(), Sema::AbstractNone
);
6214 /// Check for invalid uses of an abstract type in a variable0 declaration.
6215 static void CheckAbstractClassUsage(AbstractUsageInfo
&Info
,
6217 // No need to do the check on definitions, which require that
6218 // the type is complete.
6219 if (VD
->isThisDeclarationADefinition())
6222 Info
.CheckType(VD
, VD
->getTypeSourceInfo()->getTypeLoc(),
6223 Sema::AbstractVariableType
);
6226 /// Check for invalid uses of an abstract type within a class definition.
6227 static void CheckAbstractClassUsage(AbstractUsageInfo
&Info
,
6228 CXXRecordDecl
*RD
) {
6229 for (auto *D
: RD
->decls()) {
6230 if (D
->isImplicit()) continue;
6232 // Step through friends to the befriended declaration.
6233 if (auto *FD
= dyn_cast
<FriendDecl
>(D
)) {
6234 D
= FD
->getFriendDecl();
6238 // Functions and function templates.
6239 if (auto *FD
= dyn_cast
<FunctionDecl
>(D
)) {
6240 CheckAbstractClassUsage(Info
, FD
);
6241 } else if (auto *FTD
= dyn_cast
<FunctionTemplateDecl
>(D
)) {
6242 CheckAbstractClassUsage(Info
, FTD
->getTemplatedDecl());
6244 // Fields and static variables.
6245 } else if (auto *FD
= dyn_cast
<FieldDecl
>(D
)) {
6246 if (TypeSourceInfo
*TSI
= FD
->getTypeSourceInfo())
6247 Info
.CheckType(FD
, TSI
->getTypeLoc(), Sema::AbstractFieldType
);
6248 } else if (auto *VD
= dyn_cast
<VarDecl
>(D
)) {
6249 CheckAbstractClassUsage(Info
, VD
);
6250 } else if (auto *VTD
= dyn_cast
<VarTemplateDecl
>(D
)) {
6251 CheckAbstractClassUsage(Info
, VTD
->getTemplatedDecl());
6253 // Nested classes and class templates.
6254 } else if (auto *RD
= dyn_cast
<CXXRecordDecl
>(D
)) {
6255 CheckAbstractClassUsage(Info
, RD
);
6256 } else if (auto *CTD
= dyn_cast
<ClassTemplateDecl
>(D
)) {
6257 CheckAbstractClassUsage(Info
, CTD
->getTemplatedDecl());
6262 static void ReferenceDllExportedMembers(Sema
&S
, CXXRecordDecl
*Class
) {
6263 Attr
*ClassAttr
= getDLLAttr(Class
);
6267 assert(ClassAttr
->getKind() == attr::DLLExport
);
6269 TemplateSpecializationKind TSK
= Class
->getTemplateSpecializationKind();
6271 if (TSK
== TSK_ExplicitInstantiationDeclaration
)
6272 // Don't go any further if this is just an explicit instantiation
6276 // Add a context note to explain how we got to any diagnostics produced below.
6277 struct MarkingClassDllexported
{
6279 MarkingClassDllexported(Sema
&S
, CXXRecordDecl
*Class
,
6280 SourceLocation AttrLoc
)
6282 Sema::CodeSynthesisContext Ctx
;
6283 Ctx
.Kind
= Sema::CodeSynthesisContext::MarkingClassDllexported
;
6284 Ctx
.PointOfInstantiation
= AttrLoc
;
6286 S
.pushCodeSynthesisContext(Ctx
);
6288 ~MarkingClassDllexported() {
6289 S
.popCodeSynthesisContext();
6291 } MarkingDllexportedContext(S
, Class
, ClassAttr
->getLocation());
6293 if (S
.Context
.getTargetInfo().getTriple().isWindowsGNUEnvironment())
6294 S
.MarkVTableUsed(Class
->getLocation(), Class
, true);
6296 for (Decl
*Member
: Class
->decls()) {
6297 // Skip members that were not marked exported.
6298 if (!Member
->hasAttr
<DLLExportAttr
>())
6301 // Defined static variables that are members of an exported base
6302 // class must be marked export too.
6303 auto *VD
= dyn_cast
<VarDecl
>(Member
);
6304 if (VD
&& VD
->getStorageClass() == SC_Static
&&
6305 TSK
== TSK_ImplicitInstantiation
)
6306 S
.MarkVariableReferenced(VD
->getLocation(), VD
);
6308 auto *MD
= dyn_cast
<CXXMethodDecl
>(Member
);
6312 if (MD
->isUserProvided()) {
6313 // Instantiate non-default class member functions ...
6315 // .. except for certain kinds of template specializations.
6316 if (TSK
== TSK_ImplicitInstantiation
&& !ClassAttr
->isInherited())
6319 // If this is an MS ABI dllexport default constructor, instantiate any
6320 // default arguments.
6321 if (S
.Context
.getTargetInfo().getCXXABI().isMicrosoft()) {
6322 auto *CD
= dyn_cast
<CXXConstructorDecl
>(MD
);
6323 if (CD
&& CD
->isDefaultConstructor() && TSK
== TSK_Undeclared
) {
6324 S
.InstantiateDefaultCtorDefaultArgs(CD
);
6328 S
.MarkFunctionReferenced(Class
->getLocation(), MD
);
6330 // The function will be passed to the consumer when its definition is
6332 } else if (MD
->isExplicitlyDefaulted()) {
6333 // Synthesize and instantiate explicitly defaulted methods.
6334 S
.MarkFunctionReferenced(Class
->getLocation(), MD
);
6336 if (TSK
!= TSK_ExplicitInstantiationDefinition
) {
6337 // Except for explicit instantiation defs, we will not see the
6338 // definition again later, so pass it to the consumer now.
6339 S
.Consumer
.HandleTopLevelDecl(DeclGroupRef(MD
));
6341 } else if (!MD
->isTrivial() ||
6342 MD
->isCopyAssignmentOperator() ||
6343 MD
->isMoveAssignmentOperator()) {
6344 // Synthesize and instantiate non-trivial implicit methods, and the copy
6345 // and move assignment operators. The latter are exported even if they
6346 // are trivial, because the address of an operator can be taken and
6347 // should compare equal across libraries.
6348 S
.MarkFunctionReferenced(Class
->getLocation(), MD
);
6350 // There is no later point when we will see the definition of this
6351 // function, so pass it to the consumer now.
6352 S
.Consumer
.HandleTopLevelDecl(DeclGroupRef(MD
));
6357 static void checkForMultipleExportedDefaultConstructors(Sema
&S
,
6358 CXXRecordDecl
*Class
) {
6359 // Only the MS ABI has default constructor closures, so we don't need to do
6360 // this semantic checking anywhere else.
6361 if (!S
.Context
.getTargetInfo().getCXXABI().isMicrosoft())
6364 CXXConstructorDecl
*LastExportedDefaultCtor
= nullptr;
6365 for (Decl
*Member
: Class
->decls()) {
6366 // Look for exported default constructors.
6367 auto *CD
= dyn_cast
<CXXConstructorDecl
>(Member
);
6368 if (!CD
|| !CD
->isDefaultConstructor())
6370 auto *Attr
= CD
->getAttr
<DLLExportAttr
>();
6374 // If the class is non-dependent, mark the default arguments as ODR-used so
6375 // that we can properly codegen the constructor closure.
6376 if (!Class
->isDependentContext()) {
6377 for (ParmVarDecl
*PD
: CD
->parameters()) {
6378 (void)S
.CheckCXXDefaultArgExpr(Attr
->getLocation(), CD
, PD
);
6379 S
.DiscardCleanupsInEvaluationContext();
6383 if (LastExportedDefaultCtor
) {
6384 S
.Diag(LastExportedDefaultCtor
->getLocation(),
6385 diag::err_attribute_dll_ambiguous_default_ctor
)
6387 S
.Diag(CD
->getLocation(), diag::note_entity_declared_at
)
6388 << CD
->getDeclName();
6391 LastExportedDefaultCtor
= CD
;
6395 static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema
&S
,
6396 CXXRecordDecl
*Class
) {
6397 bool ErrorReported
= false;
6398 auto reportIllegalClassTemplate
= [&ErrorReported
](Sema
&S
,
6399 ClassTemplateDecl
*TD
) {
6402 S
.Diag(TD
->getLocation(),
6403 diag::err_cuda_device_builtin_surftex_cls_template
)
6404 << /*surface*/ 0 << TD
;
6405 ErrorReported
= true;
6408 ClassTemplateDecl
*TD
= Class
->getDescribedClassTemplate();
6410 auto *SD
= dyn_cast
<ClassTemplateSpecializationDecl
>(Class
);
6412 S
.Diag(Class
->getLocation(),
6413 diag::err_cuda_device_builtin_surftex_ref_decl
)
6414 << /*surface*/ 0 << Class
;
6415 S
.Diag(Class
->getLocation(),
6416 diag::note_cuda_device_builtin_surftex_should_be_template_class
)
6420 TD
= SD
->getSpecializedTemplate();
6423 TemplateParameterList
*Params
= TD
->getTemplateParameters();
6424 unsigned N
= Params
->size();
6427 reportIllegalClassTemplate(S
, TD
);
6428 S
.Diag(TD
->getLocation(),
6429 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args
)
6432 if (N
> 0 && !isa
<TemplateTypeParmDecl
>(Params
->getParam(0))) {
6433 reportIllegalClassTemplate(S
, TD
);
6434 S
.Diag(TD
->getLocation(),
6435 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg
)
6436 << TD
<< /*1st*/ 0 << /*type*/ 0;
6439 auto *NTTP
= dyn_cast
<NonTypeTemplateParmDecl
>(Params
->getParam(1));
6440 if (!NTTP
|| !NTTP
->getType()->isIntegralOrEnumerationType()) {
6441 reportIllegalClassTemplate(S
, TD
);
6442 S
.Diag(TD
->getLocation(),
6443 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg
)
6444 << TD
<< /*2nd*/ 1 << /*integer*/ 1;
6449 static void checkCUDADeviceBuiltinTextureClassTemplate(Sema
&S
,
6450 CXXRecordDecl
*Class
) {
6451 bool ErrorReported
= false;
6452 auto reportIllegalClassTemplate
= [&ErrorReported
](Sema
&S
,
6453 ClassTemplateDecl
*TD
) {
6456 S
.Diag(TD
->getLocation(),
6457 diag::err_cuda_device_builtin_surftex_cls_template
)
6458 << /*texture*/ 1 << TD
;
6459 ErrorReported
= true;
6462 ClassTemplateDecl
*TD
= Class
->getDescribedClassTemplate();
6464 auto *SD
= dyn_cast
<ClassTemplateSpecializationDecl
>(Class
);
6466 S
.Diag(Class
->getLocation(),
6467 diag::err_cuda_device_builtin_surftex_ref_decl
)
6468 << /*texture*/ 1 << Class
;
6469 S
.Diag(Class
->getLocation(),
6470 diag::note_cuda_device_builtin_surftex_should_be_template_class
)
6474 TD
= SD
->getSpecializedTemplate();
6477 TemplateParameterList
*Params
= TD
->getTemplateParameters();
6478 unsigned N
= Params
->size();
6481 reportIllegalClassTemplate(S
, TD
);
6482 S
.Diag(TD
->getLocation(),
6483 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args
)
6486 if (N
> 0 && !isa
<TemplateTypeParmDecl
>(Params
->getParam(0))) {
6487 reportIllegalClassTemplate(S
, TD
);
6488 S
.Diag(TD
->getLocation(),
6489 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg
)
6490 << TD
<< /*1st*/ 0 << /*type*/ 0;
6493 auto *NTTP
= dyn_cast
<NonTypeTemplateParmDecl
>(Params
->getParam(1));
6494 if (!NTTP
|| !NTTP
->getType()->isIntegralOrEnumerationType()) {
6495 reportIllegalClassTemplate(S
, TD
);
6496 S
.Diag(TD
->getLocation(),
6497 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg
)
6498 << TD
<< /*2nd*/ 1 << /*integer*/ 1;
6502 auto *NTTP
= dyn_cast
<NonTypeTemplateParmDecl
>(Params
->getParam(2));
6503 if (!NTTP
|| !NTTP
->getType()->isIntegralOrEnumerationType()) {
6504 reportIllegalClassTemplate(S
, TD
);
6505 S
.Diag(TD
->getLocation(),
6506 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg
)
6507 << TD
<< /*3rd*/ 2 << /*integer*/ 1;
6512 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl
*Class
) {
6513 // Mark any compiler-generated routines with the implicit code_seg attribute.
6514 for (auto *Method
: Class
->methods()) {
6515 if (Method
->isUserProvided())
6517 if (Attr
*A
= getImplicitCodeSegOrSectionAttrForFunction(Method
, /*IsDefinition=*/true))
6522 /// Check class-level dllimport/dllexport attribute.
6523 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl
*Class
) {
6524 Attr
*ClassAttr
= getDLLAttr(Class
);
6526 // MSVC inherits DLL attributes to partial class template specializations.
6527 if (Context
.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr
) {
6528 if (auto *Spec
= dyn_cast
<ClassTemplatePartialSpecializationDecl
>(Class
)) {
6529 if (Attr
*TemplateAttr
=
6530 getDLLAttr(Spec
->getSpecializedTemplate()->getTemplatedDecl())) {
6531 auto *A
= cast
<InheritableAttr
>(TemplateAttr
->clone(getASTContext()));
6532 A
->setInherited(true);
6541 // MSVC allows imported or exported template classes that have UniqueExternal
6542 // linkage. This occurs when the template class has been instantiated with
6543 // a template parameter which itself has internal linkage.
6544 // We drop the attribute to avoid exporting or importing any members.
6545 if ((Context
.getTargetInfo().getCXXABI().isMicrosoft() ||
6546 Context
.getTargetInfo().getTriple().isPS()) &&
6547 (!Class
->isExternallyVisible() && Class
->hasExternalFormalLinkage())) {
6548 Class
->dropAttr
<DLLExportAttr
>();
6549 Class
->dropAttr
<DLLImportAttr
>();
6553 if (!Class
->isExternallyVisible()) {
6554 Diag(Class
->getLocation(), diag::err_attribute_dll_not_extern
)
6555 << Class
<< ClassAttr
;
6559 if (Context
.getTargetInfo().shouldDLLImportComdatSymbols() &&
6560 !ClassAttr
->isInherited()) {
6561 // Diagnose dll attributes on members of class with dll attribute.
6562 for (Decl
*Member
: Class
->decls()) {
6563 if (!isa
<VarDecl
>(Member
) && !isa
<CXXMethodDecl
>(Member
))
6565 InheritableAttr
*MemberAttr
= getDLLAttr(Member
);
6566 if (!MemberAttr
|| MemberAttr
->isInherited() || Member
->isInvalidDecl())
6569 Diag(MemberAttr
->getLocation(),
6570 diag::err_attribute_dll_member_of_dll_class
)
6571 << MemberAttr
<< ClassAttr
;
6572 Diag(ClassAttr
->getLocation(), diag::note_previous_attribute
);
6573 Member
->setInvalidDecl();
6577 if (Class
->getDescribedClassTemplate())
6578 // Don't inherit dll attribute until the template is instantiated.
6581 // The class is either imported or exported.
6582 const bool ClassExported
= ClassAttr
->getKind() == attr::DLLExport
;
6584 // Check if this was a dllimport attribute propagated from a derived class to
6585 // a base class template specialization. We don't apply these attributes to
6586 // static data members.
6587 const bool PropagatedImport
=
6589 cast
<DLLImportAttr
>(ClassAttr
)->wasPropagatedToBaseTemplate();
6591 TemplateSpecializationKind TSK
= Class
->getTemplateSpecializationKind();
6593 // Ignore explicit dllexport on explicit class template instantiation
6594 // declarations, except in MinGW mode.
6595 if (ClassExported
&& !ClassAttr
->isInherited() &&
6596 TSK
== TSK_ExplicitInstantiationDeclaration
&&
6597 !Context
.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
6598 Class
->dropAttr
<DLLExportAttr
>();
6602 // Force declaration of implicit members so they can inherit the attribute.
6603 ForceDeclarationOfImplicitMembers(Class
);
6605 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
6606 // seem to be true in practice?
6608 for (Decl
*Member
: Class
->decls()) {
6609 VarDecl
*VD
= dyn_cast
<VarDecl
>(Member
);
6610 CXXMethodDecl
*MD
= dyn_cast
<CXXMethodDecl
>(Member
);
6612 // Only methods and static fields inherit the attributes.
6617 // Don't process deleted methods.
6618 if (MD
->isDeleted())
6621 if (MD
->isInlined()) {
6622 // MinGW does not import or export inline methods. But do it for
6623 // template instantiations.
6624 if (!Context
.getTargetInfo().shouldDLLImportComdatSymbols() &&
6625 TSK
!= TSK_ExplicitInstantiationDeclaration
&&
6626 TSK
!= TSK_ExplicitInstantiationDefinition
)
6629 // MSVC versions before 2015 don't export the move assignment operators
6630 // and move constructor, so don't attempt to import/export them if
6631 // we have a definition.
6632 auto *Ctor
= dyn_cast
<CXXConstructorDecl
>(MD
);
6633 if ((MD
->isMoveAssignmentOperator() ||
6634 (Ctor
&& Ctor
->isMoveConstructor())) &&
6635 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015
))
6638 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
6639 // operator is exported anyway.
6640 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015
) &&
6641 (Ctor
|| isa
<CXXDestructorDecl
>(MD
)) && MD
->isTrivial())
6646 // Don't apply dllimport attributes to static data members of class template
6647 // instantiations when the attribute is propagated from a derived class.
6648 if (VD
&& PropagatedImport
)
6651 if (!cast
<NamedDecl
>(Member
)->isExternallyVisible())
6654 if (!getDLLAttr(Member
)) {
6655 InheritableAttr
*NewAttr
= nullptr;
6657 // Do not export/import inline function when -fno-dllexport-inlines is
6658 // passed. But add attribute for later local static var check.
6659 if (!getLangOpts().DllExportInlines
&& MD
&& MD
->isInlined() &&
6660 TSK
!= TSK_ExplicitInstantiationDeclaration
&&
6661 TSK
!= TSK_ExplicitInstantiationDefinition
) {
6662 if (ClassExported
) {
6663 NewAttr
= ::new (getASTContext())
6664 DLLExportStaticLocalAttr(getASTContext(), *ClassAttr
);
6666 NewAttr
= ::new (getASTContext())
6667 DLLImportStaticLocalAttr(getASTContext(), *ClassAttr
);
6670 NewAttr
= cast
<InheritableAttr
>(ClassAttr
->clone(getASTContext()));
6673 NewAttr
->setInherited(true);
6674 Member
->addAttr(NewAttr
);
6677 // Propagate DLLAttr to friend re-declarations of MD that have already
6678 // been constructed.
6679 for (FunctionDecl
*FD
= MD
->getMostRecentDecl(); FD
;
6680 FD
= FD
->getPreviousDecl()) {
6681 if (FD
->getFriendObjectKind() == Decl::FOK_None
)
6683 assert(!getDLLAttr(FD
) &&
6684 "friend re-decl should not already have a DLLAttr");
6685 NewAttr
= cast
<InheritableAttr
>(ClassAttr
->clone(getASTContext()));
6686 NewAttr
->setInherited(true);
6687 FD
->addAttr(NewAttr
);
6694 DelayedDllExportClasses
.push_back(Class
);
6697 /// Perform propagation of DLL attributes from a derived class to a
6698 /// templated base class for MS compatibility.
6699 void Sema::propagateDLLAttrToBaseClassTemplate(
6700 CXXRecordDecl
*Class
, Attr
*ClassAttr
,
6701 ClassTemplateSpecializationDecl
*BaseTemplateSpec
, SourceLocation BaseLoc
) {
6703 BaseTemplateSpec
->getSpecializedTemplate()->getTemplatedDecl())) {
6704 // If the base class template has a DLL attribute, don't try to change it.
6708 auto TSK
= BaseTemplateSpec
->getSpecializationKind();
6709 if (!getDLLAttr(BaseTemplateSpec
) &&
6710 (TSK
== TSK_Undeclared
|| TSK
== TSK_ExplicitInstantiationDeclaration
||
6711 TSK
== TSK_ImplicitInstantiation
)) {
6712 // The template hasn't been instantiated yet (or it has, but only as an
6713 // explicit instantiation declaration or implicit instantiation, which means
6714 // we haven't codegenned any members yet), so propagate the attribute.
6715 auto *NewAttr
= cast
<InheritableAttr
>(ClassAttr
->clone(getASTContext()));
6716 NewAttr
->setInherited(true);
6717 BaseTemplateSpec
->addAttr(NewAttr
);
6719 // If this was an import, mark that we propagated it from a derived class to
6720 // a base class template specialization.
6721 if (auto *ImportAttr
= dyn_cast
<DLLImportAttr
>(NewAttr
))
6722 ImportAttr
->setPropagatedToBaseTemplate();
6724 // If the template is already instantiated, checkDLLAttributeRedeclaration()
6725 // needs to be run again to work see the new attribute. Otherwise this will
6726 // get run whenever the template is instantiated.
6727 if (TSK
!= TSK_Undeclared
)
6728 checkClassLevelDLLAttribute(BaseTemplateSpec
);
6733 if (getDLLAttr(BaseTemplateSpec
)) {
6734 // The template has already been specialized or instantiated with an
6735 // attribute, explicitly or through propagation. We should not try to change
6740 // The template was previously instantiated or explicitly specialized without
6741 // a dll attribute, It's too late for us to add an attribute, so warn that
6742 // this is unsupported.
6743 Diag(BaseLoc
, diag::warn_attribute_dll_instantiated_base_class
)
6744 << BaseTemplateSpec
->isExplicitSpecialization();
6745 Diag(ClassAttr
->getLocation(), diag::note_attribute
);
6746 if (BaseTemplateSpec
->isExplicitSpecialization()) {
6747 Diag(BaseTemplateSpec
->getLocation(),
6748 diag::note_template_class_explicit_specialization_was_here
)
6749 << BaseTemplateSpec
;
6751 Diag(BaseTemplateSpec
->getPointOfInstantiation(),
6752 diag::note_template_class_instantiation_was_here
)
6753 << BaseTemplateSpec
;
6757 /// Determine the kind of defaulting that would be done for a given function.
6759 /// If the function is both a default constructor and a copy / move constructor
6760 /// (due to having a default argument for the first parameter), this picks
6761 /// CXXDefaultConstructor.
6763 /// FIXME: Check that case is properly handled by all callers.
6764 Sema::DefaultedFunctionKind
6765 Sema::getDefaultedFunctionKind(const FunctionDecl
*FD
) {
6766 if (auto *MD
= dyn_cast
<CXXMethodDecl
>(FD
)) {
6767 if (const CXXConstructorDecl
*Ctor
= dyn_cast
<CXXConstructorDecl
>(FD
)) {
6768 if (Ctor
->isDefaultConstructor())
6769 return Sema::CXXDefaultConstructor
;
6771 if (Ctor
->isCopyConstructor())
6772 return Sema::CXXCopyConstructor
;
6774 if (Ctor
->isMoveConstructor())
6775 return Sema::CXXMoveConstructor
;
6778 if (MD
->isCopyAssignmentOperator())
6779 return Sema::CXXCopyAssignment
;
6781 if (MD
->isMoveAssignmentOperator())
6782 return Sema::CXXMoveAssignment
;
6784 if (isa
<CXXDestructorDecl
>(FD
))
6785 return Sema::CXXDestructor
;
6788 switch (FD
->getDeclName().getCXXOverloadedOperator()) {
6790 return DefaultedComparisonKind::Equal
;
6792 case OO_ExclaimEqual
:
6793 return DefaultedComparisonKind::NotEqual
;
6796 // No point allowing this if <=> doesn't exist in the current language mode.
6797 if (!getLangOpts().CPlusPlus20
)
6799 return DefaultedComparisonKind::ThreeWay
;
6804 case OO_GreaterEqual
:
6805 // No point allowing this if <=> doesn't exist in the current language mode.
6806 if (!getLangOpts().CPlusPlus20
)
6808 return DefaultedComparisonKind::Relational
;
6815 return DefaultedFunctionKind();
6818 static void DefineDefaultedFunction(Sema
&S
, FunctionDecl
*FD
,
6819 SourceLocation DefaultLoc
) {
6820 Sema::DefaultedFunctionKind DFK
= S
.getDefaultedFunctionKind(FD
);
6821 if (DFK
.isComparison())
6822 return S
.DefineDefaultedComparison(DefaultLoc
, FD
, DFK
.asComparison());
6824 switch (DFK
.asSpecialMember()) {
6825 case Sema::CXXDefaultConstructor
:
6826 S
.DefineImplicitDefaultConstructor(DefaultLoc
,
6827 cast
<CXXConstructorDecl
>(FD
));
6829 case Sema::CXXCopyConstructor
:
6830 S
.DefineImplicitCopyConstructor(DefaultLoc
, cast
<CXXConstructorDecl
>(FD
));
6832 case Sema::CXXCopyAssignment
:
6833 S
.DefineImplicitCopyAssignment(DefaultLoc
, cast
<CXXMethodDecl
>(FD
));
6835 case Sema::CXXDestructor
:
6836 S
.DefineImplicitDestructor(DefaultLoc
, cast
<CXXDestructorDecl
>(FD
));
6838 case Sema::CXXMoveConstructor
:
6839 S
.DefineImplicitMoveConstructor(DefaultLoc
, cast
<CXXConstructorDecl
>(FD
));
6841 case Sema::CXXMoveAssignment
:
6842 S
.DefineImplicitMoveAssignment(DefaultLoc
, cast
<CXXMethodDecl
>(FD
));
6844 case Sema::CXXInvalid
:
6845 llvm_unreachable("Invalid special member.");
6849 /// Determine whether a type is permitted to be passed or returned in
6850 /// registers, per C++ [class.temporary]p3.
6851 static bool canPassInRegisters(Sema
&S
, CXXRecordDecl
*D
,
6852 TargetInfo::CallingConvKind CCK
) {
6853 if (D
->isDependentType() || D
->isInvalidDecl())
6856 // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
6857 // The PS4 platform ABI follows the behavior of Clang 3.2.
6858 if (CCK
== TargetInfo::CCK_ClangABI4OrPS4
)
6859 return !D
->hasNonTrivialDestructorForCall() &&
6860 !D
->hasNonTrivialCopyConstructorForCall();
6862 if (CCK
== TargetInfo::CCK_MicrosoftWin64
) {
6863 bool CopyCtorIsTrivial
= false, CopyCtorIsTrivialForCall
= false;
6864 bool DtorIsTrivialForCall
= false;
6866 // If a class has at least one eligible, trivial copy constructor, it
6867 // is passed according to the C ABI. Otherwise, it is passed indirectly.
6869 // Note: This permits classes with non-trivial copy or move ctors to be
6870 // passed in registers, so long as they *also* have a trivial copy ctor,
6871 // which is non-conforming.
6872 if (D
->needsImplicitCopyConstructor()) {
6873 if (!D
->defaultedCopyConstructorIsDeleted()) {
6874 if (D
->hasTrivialCopyConstructor())
6875 CopyCtorIsTrivial
= true;
6876 if (D
->hasTrivialCopyConstructorForCall())
6877 CopyCtorIsTrivialForCall
= true;
6880 for (const CXXConstructorDecl
*CD
: D
->ctors()) {
6881 if (CD
->isCopyConstructor() && !CD
->isDeleted() &&
6882 !CD
->isIneligibleOrNotSelected()) {
6883 if (CD
->isTrivial())
6884 CopyCtorIsTrivial
= true;
6885 if (CD
->isTrivialForCall())
6886 CopyCtorIsTrivialForCall
= true;
6891 if (D
->needsImplicitDestructor()) {
6892 if (!D
->defaultedDestructorIsDeleted() &&
6893 D
->hasTrivialDestructorForCall())
6894 DtorIsTrivialForCall
= true;
6895 } else if (const auto *DD
= D
->getDestructor()) {
6896 if (!DD
->isDeleted() && DD
->isTrivialForCall())
6897 DtorIsTrivialForCall
= true;
6900 // If the copy ctor and dtor are both trivial-for-calls, pass direct.
6901 if (CopyCtorIsTrivialForCall
&& DtorIsTrivialForCall
)
6904 // If a class has a destructor, we'd really like to pass it indirectly
6905 // because it allows us to elide copies. Unfortunately, MSVC makes that
6906 // impossible for small types, which it will pass in a single register or
6907 // stack slot. Most objects with dtors are large-ish, so handle that early.
6908 // We can't call out all large objects as being indirect because there are
6909 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
6910 // how we pass large POD types.
6912 // Note: This permits small classes with nontrivial destructors to be
6913 // passed in registers, which is non-conforming.
6914 bool isAArch64
= S
.Context
.getTargetInfo().getTriple().isAArch64();
6915 uint64_t TypeSize
= isAArch64
? 128 : 64;
6917 if (CopyCtorIsTrivial
&&
6918 S
.getASTContext().getTypeSize(D
->getTypeForDecl()) <= TypeSize
)
6923 // Per C++ [class.temporary]p3, the relevant condition is:
6924 // each copy constructor, move constructor, and destructor of X is
6925 // either trivial or deleted, and X has at least one non-deleted copy
6926 // or move constructor
6927 bool HasNonDeletedCopyOrMove
= false;
6929 if (D
->needsImplicitCopyConstructor() &&
6930 !D
->defaultedCopyConstructorIsDeleted()) {
6931 if (!D
->hasTrivialCopyConstructorForCall())
6933 HasNonDeletedCopyOrMove
= true;
6936 if (S
.getLangOpts().CPlusPlus11
&& D
->needsImplicitMoveConstructor() &&
6937 !D
->defaultedMoveConstructorIsDeleted()) {
6938 if (!D
->hasTrivialMoveConstructorForCall())
6940 HasNonDeletedCopyOrMove
= true;
6943 if (D
->needsImplicitDestructor() && !D
->defaultedDestructorIsDeleted() &&
6944 !D
->hasTrivialDestructorForCall())
6947 for (const CXXMethodDecl
*MD
: D
->methods()) {
6948 if (MD
->isDeleted() || MD
->isIneligibleOrNotSelected())
6951 auto *CD
= dyn_cast
<CXXConstructorDecl
>(MD
);
6952 if (CD
&& CD
->isCopyOrMoveConstructor())
6953 HasNonDeletedCopyOrMove
= true;
6954 else if (!isa
<CXXDestructorDecl
>(MD
))
6957 if (!MD
->isTrivialForCall())
6961 return HasNonDeletedCopyOrMove
;
6964 /// Report an error regarding overriding, along with any relevant
6965 /// overridden methods.
6967 /// \param DiagID the primary error to report.
6968 /// \param MD the overriding method.
6970 ReportOverrides(Sema
&S
, unsigned DiagID
, const CXXMethodDecl
*MD
,
6971 llvm::function_ref
<bool(const CXXMethodDecl
*)> Report
) {
6972 bool IssuedDiagnostic
= false;
6973 for (const CXXMethodDecl
*O
: MD
->overridden_methods()) {
6975 if (!IssuedDiagnostic
) {
6976 S
.Diag(MD
->getLocation(), DiagID
) << MD
->getDeclName();
6977 IssuedDiagnostic
= true;
6979 S
.Diag(O
->getLocation(), diag::note_overridden_virtual_function
);
6982 return IssuedDiagnostic
;
6985 /// Perform semantic checks on a class definition that has been
6986 /// completing, introducing implicitly-declared members, checking for
6987 /// abstract types, etc.
6989 /// \param S The scope in which the class was parsed. Null if we didn't just
6990 /// parse a class definition.
6991 /// \param Record The completed class.
6992 void Sema::CheckCompletedCXXClass(Scope
*S
, CXXRecordDecl
*Record
) {
6996 if (Record
->isAbstract() && !Record
->isInvalidDecl()) {
6997 AbstractUsageInfo
Info(*this, Record
);
6998 CheckAbstractClassUsage(Info
, Record
);
7001 // If this is not an aggregate type and has no user-declared constructor,
7002 // complain about any non-static data members of reference or const scalar
7003 // type, since they will never get initializers.
7004 if (!Record
->isInvalidDecl() && !Record
->isDependentType() &&
7005 !Record
->isAggregate() && !Record
->hasUserDeclaredConstructor() &&
7006 !Record
->isLambda()) {
7007 bool Complained
= false;
7008 for (const auto *F
: Record
->fields()) {
7009 if (F
->hasInClassInitializer() || F
->isUnnamedBitfield())
7012 if (F
->getType()->isReferenceType() ||
7013 (F
->getType().isConstQualified() && F
->getType()->isScalarType())) {
7015 Diag(Record
->getLocation(), diag::warn_no_constructor_for_refconst
)
7016 << llvm::to_underlying(Record
->getTagKind()) << Record
;
7020 Diag(F
->getLocation(), diag::note_refconst_member_not_initialized
)
7021 << F
->getType()->isReferenceType()
7022 << F
->getDeclName();
7027 if (Record
->getIdentifier()) {
7028 // C++ [class.mem]p13:
7029 // If T is the name of a class, then each of the following shall have a
7030 // name different from T:
7031 // - every member of every anonymous union that is a member of class T.
7033 // C++ [class.mem]p14:
7034 // In addition, if class T has a user-declared constructor (12.1), every
7035 // non-static data member of class T shall have a name different from T.
7036 DeclContext::lookup_result R
= Record
->lookup(Record
->getDeclName());
7037 for (DeclContext::lookup_iterator I
= R
.begin(), E
= R
.end(); I
!= E
;
7039 NamedDecl
*D
= (*I
)->getUnderlyingDecl();
7040 if (((isa
<FieldDecl
>(D
) || isa
<UnresolvedUsingValueDecl
>(D
)) &&
7041 Record
->hasUserDeclaredConstructor()) ||
7042 isa
<IndirectFieldDecl
>(D
)) {
7043 Diag((*I
)->getLocation(), diag::err_member_name_of_class
)
7044 << D
->getDeclName();
7050 // Warn if the class has virtual methods but non-virtual public destructor.
7051 if (Record
->isPolymorphic() && !Record
->isDependentType()) {
7052 CXXDestructorDecl
*dtor
= Record
->getDestructor();
7053 if ((!dtor
|| (!dtor
->isVirtual() && dtor
->getAccess() == AS_public
)) &&
7054 !Record
->hasAttr
<FinalAttr
>())
7055 Diag(dtor
? dtor
->getLocation() : Record
->getLocation(),
7056 diag::warn_non_virtual_dtor
) << Context
.getRecordType(Record
);
7059 if (Record
->isAbstract()) {
7060 if (FinalAttr
*FA
= Record
->getAttr
<FinalAttr
>()) {
7061 Diag(Record
->getLocation(), diag::warn_abstract_final_class
)
7062 << FA
->isSpelledAsSealed();
7063 DiagnoseAbstractType(Record
);
7067 // Warn if the class has a final destructor but is not itself marked final.
7068 if (!Record
->hasAttr
<FinalAttr
>()) {
7069 if (const CXXDestructorDecl
*dtor
= Record
->getDestructor()) {
7070 if (const FinalAttr
*FA
= dtor
->getAttr
<FinalAttr
>()) {
7071 Diag(FA
->getLocation(), diag::warn_final_dtor_non_final_class
)
7072 << FA
->isSpelledAsSealed()
7073 << FixItHint::CreateInsertion(
7074 getLocForEndOfToken(Record
->getLocation()),
7075 (FA
->isSpelledAsSealed() ? " sealed" : " final"));
7076 Diag(Record
->getLocation(),
7077 diag::note_final_dtor_non_final_class_silence
)
7078 << Context
.getRecordType(Record
) << FA
->isSpelledAsSealed();
7083 // See if trivial_abi has to be dropped.
7084 if (Record
->hasAttr
<TrivialABIAttr
>())
7085 checkIllFormedTrivialABIStruct(*Record
);
7087 // Set HasTrivialSpecialMemberForCall if the record has attribute
7089 bool HasTrivialABI
= Record
->hasAttr
<TrivialABIAttr
>();
7092 Record
->setHasTrivialSpecialMemberForCall();
7094 // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=).
7095 // We check these last because they can depend on the properties of the
7096 // primary comparison functions (==, <=>).
7097 llvm::SmallVector
<FunctionDecl
*, 5> DefaultedSecondaryComparisons
;
7099 // Perform checks that can't be done until we know all the properties of a
7100 // member function (whether it's defaulted, deleted, virtual, overriding,
7102 auto CheckCompletedMemberFunction
= [&](CXXMethodDecl
*MD
) {
7103 // A static function cannot override anything.
7104 if (MD
->getStorageClass() == SC_Static
) {
7105 if (ReportOverrides(*this, diag::err_static_overrides_virtual
, MD
,
7106 [](const CXXMethodDecl
*) { return true; }))
7110 // A deleted function cannot override a non-deleted function and vice
7112 if (ReportOverrides(*this,
7113 MD
->isDeleted() ? diag::err_deleted_override
7114 : diag::err_non_deleted_override
,
7115 MD
, [&](const CXXMethodDecl
*V
) {
7116 return MD
->isDeleted() != V
->isDeleted();
7118 if (MD
->isDefaulted() && MD
->isDeleted())
7119 // Explain why this defaulted function was deleted.
7120 DiagnoseDeletedDefaultedFunction(MD
);
7124 // A consteval function cannot override a non-consteval function and vice
7126 if (ReportOverrides(*this,
7127 MD
->isConsteval() ? diag::err_consteval_override
7128 : diag::err_non_consteval_override
,
7129 MD
, [&](const CXXMethodDecl
*V
) {
7130 return MD
->isConsteval() != V
->isConsteval();
7132 if (MD
->isDefaulted() && MD
->isDeleted())
7133 // Explain why this defaulted function was deleted.
7134 DiagnoseDeletedDefaultedFunction(MD
);
7139 auto CheckForDefaultedFunction
= [&](FunctionDecl
*FD
) -> bool {
7140 if (!FD
|| FD
->isInvalidDecl() || !FD
->isExplicitlyDefaulted())
7143 DefaultedFunctionKind DFK
= getDefaultedFunctionKind(FD
);
7144 if (DFK
.asComparison() == DefaultedComparisonKind::NotEqual
||
7145 DFK
.asComparison() == DefaultedComparisonKind::Relational
) {
7146 DefaultedSecondaryComparisons
.push_back(FD
);
7150 CheckExplicitlyDefaultedFunction(S
, FD
);
7154 auto CompleteMemberFunction
= [&](CXXMethodDecl
*M
) {
7155 // Check whether the explicitly-defaulted members are valid.
7156 bool Incomplete
= CheckForDefaultedFunction(M
);
7158 // Skip the rest of the checks for a member of a dependent class.
7159 if (Record
->isDependentType())
7162 // For an explicitly defaulted or deleted special member, we defer
7163 // determining triviality until the class is complete. That time is now!
7164 CXXSpecialMember CSM
= getSpecialMember(M
);
7165 if (!M
->isImplicit() && !M
->isUserProvided()) {
7166 if (CSM
!= CXXInvalid
) {
7167 M
->setTrivial(SpecialMemberIsTrivial(M
, CSM
));
7168 // Inform the class that we've finished declaring this member.
7169 Record
->finishedDefaultedOrDeletedMember(M
);
7170 M
->setTrivialForCall(
7172 SpecialMemberIsTrivial(M
, CSM
, TAH_ConsiderTrivialABI
));
7173 Record
->setTrivialForCallFlags(M
);
7177 // Set triviality for the purpose of calls if this is a user-provided
7178 // copy/move constructor or destructor.
7179 if ((CSM
== CXXCopyConstructor
|| CSM
== CXXMoveConstructor
||
7180 CSM
== CXXDestructor
) && M
->isUserProvided()) {
7181 M
->setTrivialForCall(HasTrivialABI
);
7182 Record
->setTrivialForCallFlags(M
);
7185 if (!M
->isInvalidDecl() && M
->isExplicitlyDefaulted() &&
7186 M
->hasAttr
<DLLExportAttr
>()) {
7187 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015
) &&
7189 (CSM
== CXXDefaultConstructor
|| CSM
== CXXCopyConstructor
||
7190 CSM
== CXXDestructor
))
7191 M
->dropAttr
<DLLExportAttr
>();
7193 if (M
->hasAttr
<DLLExportAttr
>()) {
7194 // Define after any fields with in-class initializers have been parsed.
7195 DelayedDllExportMemberFunctions
.push_back(M
);
7199 // Define defaulted constexpr virtual functions that override a base class
7200 // function right away.
7201 // FIXME: We can defer doing this until the vtable is marked as used.
7202 if (CSM
!= CXXInvalid
&& !M
->isDeleted() && M
->isDefaulted() &&
7203 M
->isConstexpr() && M
->size_overridden_methods())
7204 DefineDefaultedFunction(*this, M
, M
->getLocation());
7207 CheckCompletedMemberFunction(M
);
7210 // Check the destructor before any other member function. We need to
7211 // determine whether it's trivial in order to determine whether the claas
7212 // type is a literal type, which is a prerequisite for determining whether
7213 // other special member functions are valid and whether they're implicitly
7215 if (CXXDestructorDecl
*Dtor
= Record
->getDestructor())
7216 CompleteMemberFunction(Dtor
);
7218 bool HasMethodWithOverrideControl
= false,
7219 HasOverridingMethodWithoutOverrideControl
= false;
7220 for (auto *D
: Record
->decls()) {
7221 if (auto *M
= dyn_cast
<CXXMethodDecl
>(D
)) {
7222 // FIXME: We could do this check for dependent types with non-dependent
7224 if (!Record
->isDependentType()) {
7225 // See if a method overloads virtual methods in a base
7226 // class without overriding any.
7228 DiagnoseHiddenVirtualMethods(M
);
7229 if (M
->hasAttr
<OverrideAttr
>())
7230 HasMethodWithOverrideControl
= true;
7231 else if (M
->size_overridden_methods() > 0)
7232 HasOverridingMethodWithoutOverrideControl
= true;
7235 if (!isa
<CXXDestructorDecl
>(M
))
7236 CompleteMemberFunction(M
);
7237 } else if (auto *F
= dyn_cast
<FriendDecl
>(D
)) {
7238 CheckForDefaultedFunction(
7239 dyn_cast_or_null
<FunctionDecl
>(F
->getFriendDecl()));
7243 if (HasOverridingMethodWithoutOverrideControl
) {
7244 bool HasInconsistentOverrideControl
= HasMethodWithOverrideControl
;
7245 for (auto *M
: Record
->methods())
7246 DiagnoseAbsenceOfOverrideControl(M
, HasInconsistentOverrideControl
);
7249 // Check the defaulted secondary comparisons after any other member functions.
7250 for (FunctionDecl
*FD
: DefaultedSecondaryComparisons
) {
7251 CheckExplicitlyDefaultedFunction(S
, FD
);
7253 // If this is a member function, we deferred checking it until now.
7254 if (auto *MD
= dyn_cast
<CXXMethodDecl
>(FD
))
7255 CheckCompletedMemberFunction(MD
);
7258 // ms_struct is a request to use the same ABI rules as MSVC. Check
7259 // whether this class uses any C++ features that are implemented
7260 // completely differently in MSVC, and if so, emit a diagnostic.
7261 // That diagnostic defaults to an error, but we allow projects to
7262 // map it down to a warning (or ignore it). It's a fairly common
7263 // practice among users of the ms_struct pragma to mass-annotate
7264 // headers, sweeping up a bunch of types that the project doesn't
7265 // really rely on MSVC-compatible layout for. We must therefore
7266 // support "ms_struct except for C++ stuff" as a secondary ABI.
7267 // Don't emit this diagnostic if the feature was enabled as a
7268 // language option (as opposed to via a pragma or attribute), as
7269 // the option -mms-bitfields otherwise essentially makes it impossible
7270 // to build C++ code, unless this diagnostic is turned off.
7271 if (Record
->isMsStruct(Context
) && !Context
.getLangOpts().MSBitfields
&&
7272 (Record
->isPolymorphic() || Record
->getNumBases())) {
7273 Diag(Record
->getLocation(), diag::warn_cxx_ms_struct
);
7276 checkClassLevelDLLAttribute(Record
);
7277 checkClassLevelCodeSegAttribute(Record
);
7279 bool ClangABICompat4
=
7280 Context
.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4
;
7281 TargetInfo::CallingConvKind CCK
=
7282 Context
.getTargetInfo().getCallingConvKind(ClangABICompat4
);
7283 bool CanPass
= canPassInRegisters(*this, Record
, CCK
);
7285 // Do not change ArgPassingRestrictions if it has already been set to
7286 // ArgPassingKind::CanNeverPassInRegs.
7287 if (Record
->getArgPassingRestrictions() !=
7288 RecordArgPassingKind::CanNeverPassInRegs
)
7289 Record
->setArgPassingRestrictions(
7290 CanPass
? RecordArgPassingKind::CanPassInRegs
7291 : RecordArgPassingKind::CannotPassInRegs
);
7293 // If canPassInRegisters returns true despite the record having a non-trivial
7294 // destructor, the record is destructed in the callee. This happens only when
7295 // the record or one of its subobjects has a field annotated with trivial_abi
7296 // or a field qualified with ObjC __strong/__weak.
7297 if (Context
.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
7298 Record
->setParamDestroyedInCallee(true);
7299 else if (Record
->hasNonTrivialDestructor())
7300 Record
->setParamDestroyedInCallee(CanPass
);
7302 if (getLangOpts().ForceEmitVTables
) {
7303 // If we want to emit all the vtables, we need to mark it as used. This
7304 // is especially required for cases like vtable assumption loads.
7305 MarkVTableUsed(Record
->getInnerLocStart(), Record
);
7308 if (getLangOpts().CUDA
) {
7309 if (Record
->hasAttr
<CUDADeviceBuiltinSurfaceTypeAttr
>())
7310 checkCUDADeviceBuiltinSurfaceClassTemplate(*this, Record
);
7311 else if (Record
->hasAttr
<CUDADeviceBuiltinTextureTypeAttr
>())
7312 checkCUDADeviceBuiltinTextureClassTemplate(*this, Record
);
7316 /// Look up the special member function that would be called by a special
7317 /// member function for a subobject of class type.
7319 /// \param Class The class type of the subobject.
7320 /// \param CSM The kind of special member function.
7321 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
7322 /// \param ConstRHS True if this is a copy operation with a const object
7323 /// on its RHS, that is, if the argument to the outer special member
7324 /// function is 'const' and this is not a field marked 'mutable'.
7325 static Sema::SpecialMemberOverloadResult
lookupCallFromSpecialMember(
7326 Sema
&S
, CXXRecordDecl
*Class
, Sema::CXXSpecialMember CSM
,
7327 unsigned FieldQuals
, bool ConstRHS
) {
7328 unsigned LHSQuals
= 0;
7329 if (CSM
== Sema::CXXCopyAssignment
|| CSM
== Sema::CXXMoveAssignment
)
7330 LHSQuals
= FieldQuals
;
7332 unsigned RHSQuals
= FieldQuals
;
7333 if (CSM
== Sema::CXXDefaultConstructor
|| CSM
== Sema::CXXDestructor
)
7336 RHSQuals
|= Qualifiers::Const
;
7338 return S
.LookupSpecialMember(Class
, CSM
,
7339 RHSQuals
& Qualifiers::Const
,
7340 RHSQuals
& Qualifiers::Volatile
,
7342 LHSQuals
& Qualifiers::Const
,
7343 LHSQuals
& Qualifiers::Volatile
);
7346 class Sema::InheritedConstructorInfo
{
7348 SourceLocation UseLoc
;
7350 /// A mapping from the base classes through which the constructor was
7351 /// inherited to the using shadow declaration in that base class (or a null
7352 /// pointer if the constructor was declared in that base class).
7353 llvm::DenseMap
<CXXRecordDecl
*, ConstructorUsingShadowDecl
*>
7357 InheritedConstructorInfo(Sema
&S
, SourceLocation UseLoc
,
7358 ConstructorUsingShadowDecl
*Shadow
)
7359 : S(S
), UseLoc(UseLoc
) {
7360 bool DiagnosedMultipleConstructedBases
= false;
7361 CXXRecordDecl
*ConstructedBase
= nullptr;
7362 BaseUsingDecl
*ConstructedBaseIntroducer
= nullptr;
7364 // Find the set of such base class subobjects and check that there's a
7365 // unique constructed subobject.
7366 for (auto *D
: Shadow
->redecls()) {
7367 auto *DShadow
= cast
<ConstructorUsingShadowDecl
>(D
);
7368 auto *DNominatedBase
= DShadow
->getNominatedBaseClass();
7369 auto *DConstructedBase
= DShadow
->getConstructedBaseClass();
7371 InheritedFromBases
.insert(
7372 std::make_pair(DNominatedBase
->getCanonicalDecl(),
7373 DShadow
->getNominatedBaseClassShadowDecl()));
7374 if (DShadow
->constructsVirtualBase())
7375 InheritedFromBases
.insert(
7376 std::make_pair(DConstructedBase
->getCanonicalDecl(),
7377 DShadow
->getConstructedBaseClassShadowDecl()));
7379 assert(DNominatedBase
== DConstructedBase
);
7381 // [class.inhctor.init]p2:
7382 // If the constructor was inherited from multiple base class subobjects
7383 // of type B, the program is ill-formed.
7384 if (!ConstructedBase
) {
7385 ConstructedBase
= DConstructedBase
;
7386 ConstructedBaseIntroducer
= D
->getIntroducer();
7387 } else if (ConstructedBase
!= DConstructedBase
&&
7388 !Shadow
->isInvalidDecl()) {
7389 if (!DiagnosedMultipleConstructedBases
) {
7390 S
.Diag(UseLoc
, diag::err_ambiguous_inherited_constructor
)
7391 << Shadow
->getTargetDecl();
7392 S
.Diag(ConstructedBaseIntroducer
->getLocation(),
7393 diag::note_ambiguous_inherited_constructor_using
)
7395 DiagnosedMultipleConstructedBases
= true;
7397 S
.Diag(D
->getIntroducer()->getLocation(),
7398 diag::note_ambiguous_inherited_constructor_using
)
7399 << DConstructedBase
;
7403 if (DiagnosedMultipleConstructedBases
)
7404 Shadow
->setInvalidDecl();
7407 /// Find the constructor to use for inherited construction of a base class,
7408 /// and whether that base class constructor inherits the constructor from a
7409 /// virtual base class (in which case it won't actually invoke it).
7410 std::pair
<CXXConstructorDecl
*, bool>
7411 findConstructorForBase(CXXRecordDecl
*Base
, CXXConstructorDecl
*Ctor
) const {
7412 auto It
= InheritedFromBases
.find(Base
->getCanonicalDecl());
7413 if (It
== InheritedFromBases
.end())
7414 return std::make_pair(nullptr, false);
7416 // This is an intermediary class.
7418 return std::make_pair(
7419 S
.findInheritingConstructor(UseLoc
, Ctor
, It
->second
),
7420 It
->second
->constructsVirtualBase());
7422 // This is the base class from which the constructor was inherited.
7423 return std::make_pair(Ctor
, false);
7427 /// Is the special member function which would be selected to perform the
7428 /// specified operation on the specified class type a constexpr constructor?
7430 specialMemberIsConstexpr(Sema
&S
, CXXRecordDecl
*ClassDecl
,
7431 Sema::CXXSpecialMember CSM
, unsigned Quals
,
7433 CXXConstructorDecl
*InheritedCtor
= nullptr,
7434 Sema::InheritedConstructorInfo
*Inherited
= nullptr) {
7435 // Suppress duplicate constraint checking here, in case a constraint check
7436 // caused us to decide to do this. Any truely recursive checks will get
7437 // caught during these checks anyway.
7438 Sema::SatisfactionStackResetRAII SSRAII
{S
};
7440 // If we're inheriting a constructor, see if we need to call it for this base
7442 if (InheritedCtor
) {
7443 assert(CSM
== Sema::CXXDefaultConstructor
);
7445 Inherited
->findConstructorForBase(ClassDecl
, InheritedCtor
).first
;
7447 return BaseCtor
->isConstexpr();
7450 if (CSM
== Sema::CXXDefaultConstructor
)
7451 return ClassDecl
->hasConstexprDefaultConstructor();
7452 if (CSM
== Sema::CXXDestructor
)
7453 return ClassDecl
->hasConstexprDestructor();
7455 Sema::SpecialMemberOverloadResult SMOR
=
7456 lookupCallFromSpecialMember(S
, ClassDecl
, CSM
, Quals
, ConstRHS
);
7457 if (!SMOR
.getMethod())
7458 // A constructor we wouldn't select can't be "involved in initializing"
7461 return SMOR
.getMethod()->isConstexpr();
7464 /// Determine whether the specified special member function would be constexpr
7465 /// if it were implicitly defined.
7466 static bool defaultedSpecialMemberIsConstexpr(
7467 Sema
&S
, CXXRecordDecl
*ClassDecl
, Sema::CXXSpecialMember CSM
,
7468 bool ConstArg
, CXXConstructorDecl
*InheritedCtor
= nullptr,
7469 Sema::InheritedConstructorInfo
*Inherited
= nullptr) {
7470 if (!S
.getLangOpts().CPlusPlus11
)
7473 // C++11 [dcl.constexpr]p4:
7474 // In the definition of a constexpr constructor [...]
7477 case Sema::CXXDefaultConstructor
:
7480 // Since default constructor lookup is essentially trivial (and cannot
7481 // involve, for instance, template instantiation), we compute whether a
7482 // defaulted default constructor is constexpr directly within CXXRecordDecl.
7484 // This is important for performance; we need to know whether the default
7485 // constructor is constexpr to determine whether the type is a literal type.
7486 return ClassDecl
->defaultedDefaultConstructorIsConstexpr();
7488 case Sema::CXXCopyConstructor
:
7489 case Sema::CXXMoveConstructor
:
7490 // For copy or move constructors, we need to perform overload resolution.
7493 case Sema::CXXCopyAssignment
:
7494 case Sema::CXXMoveAssignment
:
7495 if (!S
.getLangOpts().CPlusPlus14
)
7497 // In C++1y, we need to perform overload resolution.
7501 case Sema::CXXDestructor
:
7502 return ClassDecl
->defaultedDestructorIsConstexpr();
7504 case Sema::CXXInvalid
:
7508 // -- if the class is a non-empty union, or for each non-empty anonymous
7509 // union member of a non-union class, exactly one non-static data member
7510 // shall be initialized; [DR1359]
7512 // If we squint, this is guaranteed, since exactly one non-static data member
7513 // will be initialized (if the constructor isn't deleted), we just don't know
7515 if (Ctor
&& ClassDecl
->isUnion())
7516 return CSM
== Sema::CXXDefaultConstructor
7517 ? ClassDecl
->hasInClassInitializer() ||
7518 !ClassDecl
->hasVariantMembers()
7521 // -- the class shall not have any virtual base classes;
7522 if (Ctor
&& ClassDecl
->getNumVBases())
7525 // C++1y [class.copy]p26:
7526 // -- [the class] is a literal type, and
7527 if (!Ctor
&& !ClassDecl
->isLiteral())
7530 // -- every constructor involved in initializing [...] base class
7531 // sub-objects shall be a constexpr constructor;
7532 // -- the assignment operator selected to copy/move each direct base
7533 // class is a constexpr function, and
7534 for (const auto &B
: ClassDecl
->bases()) {
7535 const RecordType
*BaseType
= B
.getType()->getAs
<RecordType
>();
7538 CXXRecordDecl
*BaseClassDecl
= cast
<CXXRecordDecl
>(BaseType
->getDecl());
7539 if (!specialMemberIsConstexpr(S
, BaseClassDecl
, CSM
, 0, ConstArg
,
7540 InheritedCtor
, Inherited
))
7544 // -- every constructor involved in initializing non-static data members
7545 // [...] shall be a constexpr constructor;
7546 // -- every non-static data member and base class sub-object shall be
7548 // -- for each non-static data member of X that is of class type (or array
7549 // thereof), the assignment operator selected to copy/move that member is
7550 // a constexpr function
7551 for (const auto *F
: ClassDecl
->fields()) {
7552 if (F
->isInvalidDecl())
7554 if (CSM
== Sema::CXXDefaultConstructor
&& F
->hasInClassInitializer())
7556 QualType BaseType
= S
.Context
.getBaseElementType(F
->getType());
7557 if (const RecordType
*RecordTy
= BaseType
->getAs
<RecordType
>()) {
7558 CXXRecordDecl
*FieldRecDecl
= cast
<CXXRecordDecl
>(RecordTy
->getDecl());
7559 if (!specialMemberIsConstexpr(S
, FieldRecDecl
, CSM
,
7560 BaseType
.getCVRQualifiers(),
7561 ConstArg
&& !F
->isMutable()))
7563 } else if (CSM
== Sema::CXXDefaultConstructor
) {
7568 // All OK, it's constexpr!
7573 /// RAII object to register a defaulted function as having its exception
7574 /// specification computed.
7575 struct ComputingExceptionSpec
{
7578 ComputingExceptionSpec(Sema
&S
, FunctionDecl
*FD
, SourceLocation Loc
)
7580 Sema::CodeSynthesisContext Ctx
;
7581 Ctx
.Kind
= Sema::CodeSynthesisContext::ExceptionSpecEvaluation
;
7582 Ctx
.PointOfInstantiation
= Loc
;
7584 S
.pushCodeSynthesisContext(Ctx
);
7586 ~ComputingExceptionSpec() {
7587 S
.popCodeSynthesisContext();
7592 static Sema::ImplicitExceptionSpecification
7593 ComputeDefaultedSpecialMemberExceptionSpec(
7594 Sema
&S
, SourceLocation Loc
, CXXMethodDecl
*MD
, Sema::CXXSpecialMember CSM
,
7595 Sema::InheritedConstructorInfo
*ICI
);
7597 static Sema::ImplicitExceptionSpecification
7598 ComputeDefaultedComparisonExceptionSpec(Sema
&S
, SourceLocation Loc
,
7600 Sema::DefaultedComparisonKind DCK
);
7602 static Sema::ImplicitExceptionSpecification
7603 computeImplicitExceptionSpec(Sema
&S
, SourceLocation Loc
, FunctionDecl
*FD
) {
7604 auto DFK
= S
.getDefaultedFunctionKind(FD
);
7605 if (DFK
.isSpecialMember())
7606 return ComputeDefaultedSpecialMemberExceptionSpec(
7607 S
, Loc
, cast
<CXXMethodDecl
>(FD
), DFK
.asSpecialMember(), nullptr);
7608 if (DFK
.isComparison())
7609 return ComputeDefaultedComparisonExceptionSpec(S
, Loc
, FD
,
7610 DFK
.asComparison());
7612 auto *CD
= cast
<CXXConstructorDecl
>(FD
);
7613 assert(CD
->getInheritedConstructor() &&
7614 "only defaulted functions and inherited constructors have implicit "
7616 Sema::InheritedConstructorInfo
ICI(
7617 S
, Loc
, CD
->getInheritedConstructor().getShadowDecl());
7618 return ComputeDefaultedSpecialMemberExceptionSpec(
7619 S
, Loc
, CD
, Sema::CXXDefaultConstructor
, &ICI
);
7622 static FunctionProtoType::ExtProtoInfo
getImplicitMethodEPI(Sema
&S
,
7623 CXXMethodDecl
*MD
) {
7624 FunctionProtoType::ExtProtoInfo EPI
;
7626 // Build an exception specification pointing back at this member.
7627 EPI
.ExceptionSpec
.Type
= EST_Unevaluated
;
7628 EPI
.ExceptionSpec
.SourceDecl
= MD
;
7630 // Set the calling convention to the default for C++ instance methods.
7631 EPI
.ExtInfo
= EPI
.ExtInfo
.withCallingConv(
7632 S
.Context
.getDefaultCallingConvention(/*IsVariadic=*/false,
7633 /*IsCXXMethod=*/true));
7637 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc
, FunctionDecl
*FD
) {
7638 const FunctionProtoType
*FPT
= FD
->getType()->castAs
<FunctionProtoType
>();
7639 if (FPT
->getExceptionSpecType() != EST_Unevaluated
)
7642 // Evaluate the exception specification.
7643 auto IES
= computeImplicitExceptionSpec(*this, Loc
, FD
);
7644 auto ESI
= IES
.getExceptionSpec();
7646 // Update the type of the special member to use it.
7647 UpdateExceptionSpec(FD
, ESI
);
7650 void Sema::CheckExplicitlyDefaultedFunction(Scope
*S
, FunctionDecl
*FD
) {
7651 assert(FD
->isExplicitlyDefaulted() && "not explicitly-defaulted");
7653 DefaultedFunctionKind DefKind
= getDefaultedFunctionKind(FD
);
7655 assert(FD
->getDeclContext()->isDependentContext());
7659 if (DefKind
.isComparison())
7660 UnusedPrivateFields
.clear();
7662 if (DefKind
.isSpecialMember()
7663 ? CheckExplicitlyDefaultedSpecialMember(cast
<CXXMethodDecl
>(FD
),
7664 DefKind
.asSpecialMember(),
7665 FD
->getDefaultLoc())
7666 : CheckExplicitlyDefaultedComparison(S
, FD
, DefKind
.asComparison()))
7667 FD
->setInvalidDecl();
7670 bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl
*MD
,
7671 CXXSpecialMember CSM
,
7672 SourceLocation DefaultLoc
) {
7673 CXXRecordDecl
*RD
= MD
->getParent();
7675 assert(MD
->isExplicitlyDefaulted() && CSM
!= CXXInvalid
&&
7676 "not an explicitly-defaulted special member");
7678 // Defer all checking for special members of a dependent type.
7679 if (RD
->isDependentType())
7682 // Whether this was the first-declared instance of the constructor.
7683 // This affects whether we implicitly add an exception spec and constexpr.
7684 bool First
= MD
== MD
->getCanonicalDecl();
7686 bool HadError
= false;
7688 // C++11 [dcl.fct.def.default]p1:
7689 // A function that is explicitly defaulted shall
7690 // -- be a special member function [...] (checked elsewhere),
7691 // -- have the same type (except for ref-qualifiers, and except that a
7692 // copy operation can take a non-const reference) as an implicit
7694 // -- not have default arguments.
7695 // C++2a changes the second bullet to instead delete the function if it's
7696 // defaulted on its first declaration, unless it's "an assignment operator,
7697 // and its return type differs or its parameter type is not a reference".
7698 bool DeleteOnTypeMismatch
= getLangOpts().CPlusPlus20
&& First
;
7699 bool ShouldDeleteForTypeMismatch
= false;
7700 unsigned ExpectedParams
= 1;
7701 if (CSM
== CXXDefaultConstructor
|| CSM
== CXXDestructor
)
7703 if (MD
->getNumExplicitParams() != ExpectedParams
) {
7704 // This checks for default arguments: a copy or move constructor with a
7705 // default argument is classified as a default constructor, and assignment
7706 // operations and destructors can't have default arguments.
7707 Diag(MD
->getLocation(), diag::err_defaulted_special_member_params
)
7708 << CSM
<< MD
->getSourceRange();
7710 } else if (MD
->isVariadic()) {
7711 if (DeleteOnTypeMismatch
)
7712 ShouldDeleteForTypeMismatch
= true;
7714 Diag(MD
->getLocation(), diag::err_defaulted_special_member_variadic
)
7715 << CSM
<< MD
->getSourceRange();
7720 const FunctionProtoType
*Type
= MD
->getType()->castAs
<FunctionProtoType
>();
7722 bool CanHaveConstParam
= false;
7723 if (CSM
== CXXCopyConstructor
)
7724 CanHaveConstParam
= RD
->implicitCopyConstructorHasConstParam();
7725 else if (CSM
== CXXCopyAssignment
)
7726 CanHaveConstParam
= RD
->implicitCopyAssignmentHasConstParam();
7728 QualType ReturnType
= Context
.VoidTy
;
7729 if (CSM
== CXXCopyAssignment
|| CSM
== CXXMoveAssignment
) {
7730 // Check for return type matching.
7731 ReturnType
= Type
->getReturnType();
7732 QualType ThisType
= MD
->getFunctionObjectParameterType();
7734 QualType DeclType
= Context
.getTypeDeclType(RD
);
7735 DeclType
= Context
.getElaboratedType(ElaboratedTypeKeyword::None
, nullptr,
7737 DeclType
= Context
.getAddrSpaceQualType(
7738 DeclType
, ThisType
.getQualifiers().getAddressSpace());
7739 QualType ExpectedReturnType
= Context
.getLValueReferenceType(DeclType
);
7741 if (!Context
.hasSameType(ReturnType
, ExpectedReturnType
)) {
7742 Diag(MD
->getLocation(), diag::err_defaulted_special_member_return_type
)
7743 << (CSM
== CXXMoveAssignment
) << ExpectedReturnType
;
7747 // A defaulted special member cannot have cv-qualifiers.
7748 if (ThisType
.isConstQualified() || ThisType
.isVolatileQualified()) {
7749 if (DeleteOnTypeMismatch
)
7750 ShouldDeleteForTypeMismatch
= true;
7752 Diag(MD
->getLocation(), diag::err_defaulted_special_member_quals
)
7753 << (CSM
== CXXMoveAssignment
) << getLangOpts().CPlusPlus14
;
7757 // [C++23][dcl.fct.def.default]/p2.2
7758 // if F2 has an implicit object parameter of type “reference to C”,
7759 // F1 may be an explicit object member function whose explicit object
7760 // parameter is of (possibly different) type “reference to C”,
7761 // in which case the type of F1 would differ from the type of F2
7762 // in that the type of F1 has an additional parameter;
7763 if (!Context
.hasSameType(
7764 ThisType
.getNonReferenceType().getUnqualifiedType(),
7765 Context
.getRecordType(RD
))) {
7766 if (DeleteOnTypeMismatch
)
7767 ShouldDeleteForTypeMismatch
= true;
7769 Diag(MD
->getLocation(),
7770 diag::err_defaulted_special_member_explicit_object_mismatch
)
7771 << (CSM
== CXXMoveAssignment
) << RD
<< MD
->getSourceRange();
7777 // Check for parameter type matching.
7780 ? Type
->getParamType(MD
->isExplicitObjectMemberFunction() ? 1 : 0)
7782 bool HasConstParam
= false;
7783 if (ExpectedParams
&& ArgType
->isReferenceType()) {
7784 // Argument must be reference to possibly-const T.
7785 QualType ReferentType
= ArgType
->getPointeeType();
7786 HasConstParam
= ReferentType
.isConstQualified();
7788 if (ReferentType
.isVolatileQualified()) {
7789 if (DeleteOnTypeMismatch
)
7790 ShouldDeleteForTypeMismatch
= true;
7792 Diag(MD
->getLocation(),
7793 diag::err_defaulted_special_member_volatile_param
) << CSM
;
7798 if (HasConstParam
&& !CanHaveConstParam
) {
7799 if (DeleteOnTypeMismatch
)
7800 ShouldDeleteForTypeMismatch
= true;
7801 else if (CSM
== CXXCopyConstructor
|| CSM
== CXXCopyAssignment
) {
7802 Diag(MD
->getLocation(),
7803 diag::err_defaulted_special_member_copy_const_param
)
7804 << (CSM
== CXXCopyAssignment
);
7805 // FIXME: Explain why this special member can't be const.
7808 Diag(MD
->getLocation(),
7809 diag::err_defaulted_special_member_move_const_param
)
7810 << (CSM
== CXXMoveAssignment
);
7814 } else if (ExpectedParams
) {
7815 // A copy assignment operator can take its argument by value, but a
7816 // defaulted one cannot.
7817 assert(CSM
== CXXCopyAssignment
&& "unexpected non-ref argument");
7818 Diag(MD
->getLocation(), diag::err_defaulted_copy_assign_not_ref
);
7822 // C++11 [dcl.fct.def.default]p2:
7823 // An explicitly-defaulted function may be declared constexpr only if it
7824 // would have been implicitly declared as constexpr,
7825 // Do not apply this rule to members of class templates, since core issue 1358
7826 // makes such functions always instantiate to constexpr functions. For
7827 // functions which cannot be constexpr (for non-constructors in C++11 and for
7828 // destructors in C++14 and C++17), this is checked elsewhere.
7830 // FIXME: This should not apply if the member is deleted.
7831 bool Constexpr
= defaultedSpecialMemberIsConstexpr(*this, RD
, CSM
,
7834 // C++14 [dcl.constexpr]p6 (CWG DR647/CWG DR1358):
7835 // If the instantiated template specialization of a constexpr function
7836 // template or member function of a class template would fail to satisfy
7837 // the requirements for a constexpr function or constexpr constructor, that
7838 // specialization is still a constexpr function or constexpr constructor,
7839 // even though a call to such a function cannot appear in a constant
7841 if (MD
->isTemplateInstantiation() && MD
->isConstexpr())
7844 if ((getLangOpts().CPlusPlus20
||
7845 (getLangOpts().CPlusPlus14
? !isa
<CXXDestructorDecl
>(MD
)
7846 : isa
<CXXConstructorDecl
>(MD
))) &&
7847 MD
->isConstexpr() && !Constexpr
&&
7848 MD
->getTemplatedKind() == FunctionDecl::TK_NonTemplate
) {
7849 if (!MD
->isConsteval() && RD
->getNumVBases()) {
7850 Diag(MD
->getBeginLoc(), diag::err_incorrect_defaulted_constexpr_with_vb
)
7852 for (const auto &I
: RD
->vbases())
7853 Diag(I
.getBeginLoc(), diag::note_constexpr_virtual_base_here
);
7855 Diag(MD
->getBeginLoc(), MD
->isConsteval()
7856 ? diag::err_incorrect_defaulted_consteval
7857 : diag::err_incorrect_defaulted_constexpr
)
7860 // FIXME: Explain why the special member can't be constexpr.
7865 // C++2a [dcl.fct.def.default]p3:
7866 // If a function is explicitly defaulted on its first declaration, it is
7867 // implicitly considered to be constexpr if the implicit declaration
7869 MD
->setConstexprKind(Constexpr
? (MD
->isConsteval()
7870 ? ConstexprSpecKind::Consteval
7871 : ConstexprSpecKind::Constexpr
)
7872 : ConstexprSpecKind::Unspecified
);
7874 if (!Type
->hasExceptionSpec()) {
7875 // C++2a [except.spec]p3:
7876 // If a declaration of a function does not have a noexcept-specifier
7877 // [and] is defaulted on its first declaration, [...] the exception
7878 // specification is as specified below
7879 FunctionProtoType::ExtProtoInfo EPI
= Type
->getExtProtoInfo();
7880 EPI
.ExceptionSpec
.Type
= EST_Unevaluated
;
7881 EPI
.ExceptionSpec
.SourceDecl
= MD
;
7883 Context
.getFunctionType(ReturnType
, Type
->getParamTypes(), EPI
));
7887 if (ShouldDeleteForTypeMismatch
|| ShouldDeleteSpecialMember(MD
, CSM
)) {
7889 SetDeclDeleted(MD
, MD
->getLocation());
7890 if (!inTemplateInstantiation() && !HadError
) {
7891 Diag(MD
->getLocation(), diag::warn_defaulted_method_deleted
) << CSM
;
7892 if (ShouldDeleteForTypeMismatch
) {
7893 Diag(MD
->getLocation(), diag::note_deleted_type_mismatch
) << CSM
;
7894 } else if (ShouldDeleteSpecialMember(MD
, CSM
, nullptr,
7895 /*Diagnose*/ true) &&
7896 DefaultLoc
.isValid()) {
7897 Diag(DefaultLoc
, diag::note_replace_equals_default_to_delete
)
7898 << FixItHint::CreateReplacement(DefaultLoc
, "delete");
7901 if (ShouldDeleteForTypeMismatch
&& !HadError
) {
7902 Diag(MD
->getLocation(),
7903 diag::warn_cxx17_compat_defaulted_method_type_mismatch
) << CSM
;
7906 // C++11 [dcl.fct.def.default]p4:
7907 // [For a] user-provided explicitly-defaulted function [...] if such a
7908 // function is implicitly defined as deleted, the program is ill-formed.
7909 Diag(MD
->getLocation(), diag::err_out_of_line_default_deletes
) << CSM
;
7910 assert(!ShouldDeleteForTypeMismatch
&& "deleted non-first decl");
7911 ShouldDeleteSpecialMember(MD
, CSM
, nullptr, /*Diagnose*/true);
7920 /// Helper class for building and checking a defaulted comparison.
7922 /// Defaulted functions are built in two phases:
7924 /// * First, the set of operations that the function will perform are
7925 /// identified, and some of them are checked. If any of the checked
7926 /// operations is invalid in certain ways, the comparison function is
7927 /// defined as deleted and no body is built.
7928 /// * Then, if the function is not defined as deleted, the body is built.
7930 /// This is accomplished by performing two visitation steps over the eventual
7931 /// body of the function.
7932 template<typename Derived
, typename ResultList
, typename Result
,
7934 class DefaultedComparisonVisitor
{
7936 using DefaultedComparisonKind
= Sema::DefaultedComparisonKind
;
7938 DefaultedComparisonVisitor(Sema
&S
, CXXRecordDecl
*RD
, FunctionDecl
*FD
,
7939 DefaultedComparisonKind DCK
)
7940 : S(S
), RD(RD
), FD(FD
), DCK(DCK
) {
7941 if (auto *Info
= FD
->getDefaultedFunctionInfo()) {
7942 // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an
7943 // UnresolvedSet to avoid this copy.
7944 Fns
.assign(Info
->getUnqualifiedLookups().begin(),
7945 Info
->getUnqualifiedLookups().end());
7949 ResultList
visit() {
7950 // The type of an lvalue naming a parameter of this function.
7951 QualType ParamLvalType
=
7952 FD
->getParamDecl(0)->getType().getNonReferenceType();
7957 case DefaultedComparisonKind::None
:
7958 llvm_unreachable("not a defaulted comparison");
7960 case DefaultedComparisonKind::Equal
:
7961 case DefaultedComparisonKind::ThreeWay
:
7962 getDerived().visitSubobjects(Results
, RD
, ParamLvalType
.getQualifiers());
7965 case DefaultedComparisonKind::NotEqual
:
7966 case DefaultedComparisonKind::Relational
:
7967 Results
.add(getDerived().visitExpandedSubobject(
7968 ParamLvalType
, getDerived().getCompleteObject()));
7971 llvm_unreachable("");
7975 Derived
&getDerived() { return static_cast<Derived
&>(*this); }
7977 /// Visit the expanded list of subobjects of the given type, as specified in
7978 /// C++2a [class.compare.default].
7980 /// \return \c true if the ResultList object said we're done, \c false if not.
7981 bool visitSubobjects(ResultList
&Results
, CXXRecordDecl
*Record
,
7983 // C++2a [class.compare.default]p4:
7984 // The direct base class subobjects of C
7985 for (CXXBaseSpecifier
&Base
: Record
->bases())
7986 if (Results
.add(getDerived().visitSubobject(
7987 S
.Context
.getQualifiedType(Base
.getType(), Quals
),
7988 getDerived().getBase(&Base
))))
7991 // followed by the non-static data members of C
7992 for (FieldDecl
*Field
: Record
->fields()) {
7993 // C++23 [class.bit]p2:
7994 // Unnamed bit-fields are not members ...
7995 if (Field
->isUnnamedBitfield())
7997 // Recursively expand anonymous structs.
7998 if (Field
->isAnonymousStructOrUnion()) {
7999 if (visitSubobjects(Results
, Field
->getType()->getAsCXXRecordDecl(),
8005 // Figure out the type of an lvalue denoting this field.
8006 Qualifiers FieldQuals
= Quals
;
8007 if (Field
->isMutable())
8008 FieldQuals
.removeConst();
8009 QualType FieldType
=
8010 S
.Context
.getQualifiedType(Field
->getType(), FieldQuals
);
8012 if (Results
.add(getDerived().visitSubobject(
8013 FieldType
, getDerived().getField(Field
))))
8017 // form a list of subobjects.
8021 Result
visitSubobject(QualType Type
, Subobject Subobj
) {
8022 // In that list, any subobject of array type is recursively expanded
8023 const ArrayType
*AT
= S
.Context
.getAsArrayType(Type
);
8024 if (auto *CAT
= dyn_cast_or_null
<ConstantArrayType
>(AT
))
8025 return getDerived().visitSubobjectArray(CAT
->getElementType(),
8026 CAT
->getSize(), Subobj
);
8027 return getDerived().visitExpandedSubobject(Type
, Subobj
);
8030 Result
visitSubobjectArray(QualType Type
, const llvm::APInt
&Size
,
8032 return getDerived().visitSubobject(Type
, Subobj
);
8039 DefaultedComparisonKind DCK
;
8040 UnresolvedSet
<16> Fns
;
8043 /// Information about a defaulted comparison, as determined by
8044 /// DefaultedComparisonAnalyzer.
8045 struct DefaultedComparisonInfo
{
8046 bool Deleted
= false;
8047 bool Constexpr
= true;
8048 ComparisonCategoryType Category
= ComparisonCategoryType::StrongOrdering
;
8050 static DefaultedComparisonInfo
deleted() {
8051 DefaultedComparisonInfo Deleted
;
8052 Deleted
.Deleted
= true;
8056 bool add(const DefaultedComparisonInfo
&R
) {
8057 Deleted
|= R
.Deleted
;
8058 Constexpr
&= R
.Constexpr
;
8059 Category
= commonComparisonType(Category
, R
.Category
);
8064 /// An element in the expanded list of subobjects of a defaulted comparison, as
8065 /// specified in C++2a [class.compare.default]p4.
8066 struct DefaultedComparisonSubobject
{
8067 enum { CompleteObject
, Member
, Base
} Kind
;
8072 /// A visitor over the notional body of a defaulted comparison that determines
8073 /// whether that body would be deleted or constexpr.
8074 class DefaultedComparisonAnalyzer
8075 : public DefaultedComparisonVisitor
<DefaultedComparisonAnalyzer
,
8076 DefaultedComparisonInfo
,
8077 DefaultedComparisonInfo
,
8078 DefaultedComparisonSubobject
> {
8080 enum DiagnosticKind
{ NoDiagnostics
, ExplainDeleted
, ExplainConstexpr
};
8083 DiagnosticKind Diagnose
;
8086 using Base
= DefaultedComparisonVisitor
;
8087 using Result
= DefaultedComparisonInfo
;
8088 using Subobject
= DefaultedComparisonSubobject
;
8092 DefaultedComparisonAnalyzer(Sema
&S
, CXXRecordDecl
*RD
, FunctionDecl
*FD
,
8093 DefaultedComparisonKind DCK
,
8094 DiagnosticKind Diagnose
= NoDiagnostics
)
8095 : Base(S
, RD
, FD
, DCK
), Diagnose(Diagnose
) {}
8098 if ((DCK
== DefaultedComparisonKind::Equal
||
8099 DCK
== DefaultedComparisonKind::ThreeWay
) &&
8100 RD
->hasVariantMembers()) {
8101 // C++2a [class.compare.default]p2 [P2002R0]:
8102 // A defaulted comparison operator function for class C is defined as
8103 // deleted if [...] C has variant members.
8104 if (Diagnose
== ExplainDeleted
) {
8105 S
.Diag(FD
->getLocation(), diag::note_defaulted_comparison_union
)
8106 << FD
<< RD
->isUnion() << RD
;
8108 return Result::deleted();
8111 return Base::visit();
8115 Subobject
getCompleteObject() {
8116 return Subobject
{Subobject::CompleteObject
, RD
, FD
->getLocation()};
8119 Subobject
getBase(CXXBaseSpecifier
*Base
) {
8120 return Subobject
{Subobject::Base
, Base
->getType()->getAsCXXRecordDecl(),
8121 Base
->getBaseTypeLoc()};
8124 Subobject
getField(FieldDecl
*Field
) {
8125 return Subobject
{Subobject::Member
, Field
, Field
->getLocation()};
8128 Result
visitExpandedSubobject(QualType Type
, Subobject Subobj
) {
8129 // C++2a [class.compare.default]p2 [P2002R0]:
8130 // A defaulted <=> or == operator function for class C is defined as
8131 // deleted if any non-static data member of C is of reference type
8132 if (Type
->isReferenceType()) {
8133 if (Diagnose
== ExplainDeleted
) {
8134 S
.Diag(Subobj
.Loc
, diag::note_defaulted_comparison_reference_member
)
8137 return Result::deleted();
8140 // [...] Let xi be an lvalue denoting the ith element [...]
8141 OpaqueValueExpr
Xi(FD
->getLocation(), Type
, VK_LValue
);
8142 Expr
*Args
[] = {&Xi
, &Xi
};
8144 // All operators start by trying to apply that same operator recursively.
8145 OverloadedOperatorKind OO
= FD
->getOverloadedOperator();
8146 assert(OO
!= OO_None
&& "not an overloaded operator!");
8147 return visitBinaryOperator(OO
, Args
, Subobj
);
8151 visitBinaryOperator(OverloadedOperatorKind OO
, ArrayRef
<Expr
*> Args
,
8153 OverloadCandidateSet
*SpaceshipCandidates
= nullptr) {
8154 // Note that there is no need to consider rewritten candidates here if
8155 // we've already found there is no viable 'operator<=>' candidate (and are
8156 // considering synthesizing a '<=>' from '==' and '<').
8157 OverloadCandidateSet
CandidateSet(
8158 FD
->getLocation(), OverloadCandidateSet::CSK_Operator
,
8159 OverloadCandidateSet::OperatorRewriteInfo(
8160 OO
, FD
->getLocation(),
8161 /*AllowRewrittenCandidates=*/!SpaceshipCandidates
));
8163 /// C++2a [class.compare.default]p1 [P2002R0]:
8164 /// [...] the defaulted function itself is never a candidate for overload
8165 /// resolution [...]
8166 CandidateSet
.exclude(FD
);
8168 if (Args
[0]->getType()->isOverloadableType())
8169 S
.LookupOverloadedBinOp(CandidateSet
, OO
, Fns
, Args
);
8171 // FIXME: We determine whether this is a valid expression by checking to
8172 // see if there's a viable builtin operator candidate for it. That isn't
8173 // really what the rules ask us to do, but should give the right results.
8174 S
.AddBuiltinOperatorCandidates(OO
, FD
->getLocation(), Args
, CandidateSet
);
8178 OverloadCandidateSet::iterator Best
;
8179 switch (CandidateSet
.BestViableFunction(S
, FD
->getLocation(), Best
)) {
8181 // C++2a [class.compare.secondary]p2 [P2002R0]:
8182 // The operator function [...] is defined as deleted if [...] the
8183 // candidate selected by overload resolution is not a rewritten
8185 if ((DCK
== DefaultedComparisonKind::NotEqual
||
8186 DCK
== DefaultedComparisonKind::Relational
) &&
8187 !Best
->RewriteKind
) {
8188 if (Diagnose
== ExplainDeleted
) {
8189 if (Best
->Function
) {
8190 S
.Diag(Best
->Function
->getLocation(),
8191 diag::note_defaulted_comparison_not_rewritten_callee
)
8194 assert(Best
->Conversions
.size() == 2 &&
8195 Best
->Conversions
[0].isUserDefined() &&
8196 "non-user-defined conversion from class to built-in "
8198 S
.Diag(Best
->Conversions
[0]
8199 .UserDefined
.FoundConversionFunction
.getDecl()
8201 diag::note_defaulted_comparison_not_rewritten_conversion
)
8205 return Result::deleted();
8208 // Throughout C++2a [class.compare]: if overload resolution does not
8209 // result in a usable function, the candidate function is defined as
8210 // deleted. This requires that we selected an accessible function.
8212 // Note that this only considers the access of the function when named
8213 // within the type of the subobject, and not the access path for any
8214 // derived-to-base conversion.
8215 CXXRecordDecl
*ArgClass
= Args
[0]->getType()->getAsCXXRecordDecl();
8216 if (ArgClass
&& Best
->FoundDecl
.getDecl() &&
8217 Best
->FoundDecl
.getDecl()->isCXXClassMember()) {
8218 QualType ObjectType
= Subobj
.Kind
== Subobject::Member
8219 ? Args
[0]->getType()
8220 : S
.Context
.getRecordType(RD
);
8221 if (!S
.isMemberAccessibleForDeletion(
8222 ArgClass
, Best
->FoundDecl
, ObjectType
, Subobj
.Loc
,
8223 Diagnose
== ExplainDeleted
8224 ? S
.PDiag(diag::note_defaulted_comparison_inaccessible
)
8225 << FD
<< Subobj
.Kind
<< Subobj
.Decl
8227 return Result::deleted();
8230 bool NeedsDeducing
=
8231 OO
== OO_Spaceship
&& FD
->getReturnType()->isUndeducedAutoType();
8233 if (FunctionDecl
*BestFD
= Best
->Function
) {
8234 // C++2a [class.compare.default]p3 [P2002R0]:
8235 // A defaulted comparison function is constexpr-compatible if
8236 // [...] no overlod resolution performed [...] results in a
8237 // non-constexpr function.
8238 assert(!BestFD
->isDeleted() && "wrong overload resolution result");
8239 // If it's not constexpr, explain why not.
8240 if (Diagnose
== ExplainConstexpr
&& !BestFD
->isConstexpr()) {
8241 if (Subobj
.Kind
!= Subobject::CompleteObject
)
8242 S
.Diag(Subobj
.Loc
, diag::note_defaulted_comparison_not_constexpr
)
8243 << Subobj
.Kind
<< Subobj
.Decl
;
8244 S
.Diag(BestFD
->getLocation(),
8245 diag::note_defaulted_comparison_not_constexpr_here
);
8246 // Bail out after explaining; we don't want any more notes.
8247 return Result::deleted();
8249 R
.Constexpr
&= BestFD
->isConstexpr();
8251 if (NeedsDeducing
) {
8252 // If any callee has an undeduced return type, deduce it now.
8253 // FIXME: It's not clear how a failure here should be handled. For
8254 // now, we produce an eager diagnostic, because that is forward
8255 // compatible with most (all?) other reasonable options.
8256 if (BestFD
->getReturnType()->isUndeducedType() &&
8257 S
.DeduceReturnType(BestFD
, FD
->getLocation(),
8258 /*Diagnose=*/false)) {
8259 // Don't produce a duplicate error when asked to explain why the
8260 // comparison is deleted: we diagnosed that when initially checking
8261 // the defaulted operator.
8262 if (Diagnose
== NoDiagnostics
) {
8265 diag::err_defaulted_comparison_cannot_deduce_undeduced_auto
)
8266 << Subobj
.Kind
<< Subobj
.Decl
;
8269 diag::note_defaulted_comparison_cannot_deduce_undeduced_auto
)
8270 << Subobj
.Kind
<< Subobj
.Decl
;
8271 S
.Diag(BestFD
->getLocation(),
8272 diag::note_defaulted_comparison_cannot_deduce_callee
)
8273 << Subobj
.Kind
<< Subobj
.Decl
;
8275 return Result::deleted();
8277 auto *Info
= S
.Context
.CompCategories
.lookupInfoForType(
8278 BestFD
->getCallResultType());
8280 if (Diagnose
== ExplainDeleted
) {
8281 S
.Diag(Subobj
.Loc
, diag::note_defaulted_comparison_cannot_deduce
)
8282 << Subobj
.Kind
<< Subobj
.Decl
8283 << BestFD
->getCallResultType().withoutLocalFastQualifiers();
8284 S
.Diag(BestFD
->getLocation(),
8285 diag::note_defaulted_comparison_cannot_deduce_callee
)
8286 << Subobj
.Kind
<< Subobj
.Decl
;
8288 return Result::deleted();
8290 R
.Category
= Info
->Kind
;
8293 QualType T
= Best
->BuiltinParamTypes
[0];
8294 assert(T
== Best
->BuiltinParamTypes
[1] &&
8295 "builtin comparison for different types?");
8296 assert(Best
->BuiltinParamTypes
[2].isNull() &&
8297 "invalid builtin comparison");
8299 if (NeedsDeducing
) {
8300 std::optional
<ComparisonCategoryType
> Cat
=
8301 getComparisonCategoryForBuiltinCmp(T
);
8302 assert(Cat
&& "no category for builtin comparison?");
8307 // Note that we might be rewriting to a different operator. That call is
8308 // not considered until we come to actually build the comparison function.
8313 if (Diagnose
== ExplainDeleted
) {
8315 if (FD
->getOverloadedOperator() == OO_Spaceship
&& OO
!= OO_Spaceship
)
8316 Kind
= OO
== OO_EqualEqual
? 1 : 2;
8317 CandidateSet
.NoteCandidates(
8318 PartialDiagnosticAt(
8319 Subobj
.Loc
, S
.PDiag(diag::note_defaulted_comparison_ambiguous
)
8320 << FD
<< Kind
<< Subobj
.Kind
<< Subobj
.Decl
),
8321 S
, OCD_AmbiguousCandidates
, Args
);
8323 R
= Result::deleted();
8327 if (Diagnose
== ExplainDeleted
) {
8328 if ((DCK
== DefaultedComparisonKind::NotEqual
||
8329 DCK
== DefaultedComparisonKind::Relational
) &&
8330 !Best
->RewriteKind
) {
8331 S
.Diag(Best
->Function
->getLocation(),
8332 diag::note_defaulted_comparison_not_rewritten_callee
)
8336 diag::note_defaulted_comparison_calls_deleted
)
8337 << FD
<< Subobj
.Kind
<< Subobj
.Decl
;
8338 S
.NoteDeletedFunction(Best
->Function
);
8341 R
= Result::deleted();
8344 case OR_No_Viable_Function
:
8345 // If there's no usable candidate, we're done unless we can rewrite a
8346 // '<=>' in terms of '==' and '<'.
8347 if (OO
== OO_Spaceship
&&
8348 S
.Context
.CompCategories
.lookupInfoForType(FD
->getReturnType())) {
8349 // For any kind of comparison category return type, we need a usable
8350 // '==' and a usable '<'.
8351 if (!R
.add(visitBinaryOperator(OO_EqualEqual
, Args
, Subobj
,
8353 R
.add(visitBinaryOperator(OO_Less
, Args
, Subobj
, &CandidateSet
));
8357 if (Diagnose
== ExplainDeleted
) {
8358 S
.Diag(Subobj
.Loc
, diag::note_defaulted_comparison_no_viable_function
)
8359 << FD
<< (OO
== OO_EqualEqual
|| OO
== OO_ExclaimEqual
)
8360 << Subobj
.Kind
<< Subobj
.Decl
;
8362 // For a three-way comparison, list both the candidates for the
8363 // original operator and the candidates for the synthesized operator.
8364 if (SpaceshipCandidates
) {
8365 SpaceshipCandidates
->NoteCandidates(
8367 SpaceshipCandidates
->CompleteCandidates(S
, OCD_AllCandidates
,
8368 Args
, FD
->getLocation()));
8370 diag::note_defaulted_comparison_no_viable_function_synthesized
)
8371 << (OO
== OO_EqualEqual
? 0 : 1);
8374 CandidateSet
.NoteCandidates(
8376 CandidateSet
.CompleteCandidates(S
, OCD_AllCandidates
, Args
,
8377 FD
->getLocation()));
8379 R
= Result::deleted();
8387 /// A list of statements.
8388 struct StmtListResult
{
8389 bool IsInvalid
= false;
8390 llvm::SmallVector
<Stmt
*, 16> Stmts
;
8392 bool add(const StmtResult
&S
) {
8393 IsInvalid
|= S
.isInvalid();
8396 Stmts
.push_back(S
.get());
8401 /// A visitor over the notional body of a defaulted comparison that synthesizes
8402 /// the actual body.
8403 class DefaultedComparisonSynthesizer
8404 : public DefaultedComparisonVisitor
<DefaultedComparisonSynthesizer
,
8405 StmtListResult
, StmtResult
,
8406 std::pair
<ExprResult
, ExprResult
>> {
8408 unsigned ArrayDepth
= 0;
8411 using Base
= DefaultedComparisonVisitor
;
8412 using ExprPair
= std::pair
<ExprResult
, ExprResult
>;
8416 DefaultedComparisonSynthesizer(Sema
&S
, CXXRecordDecl
*RD
, FunctionDecl
*FD
,
8417 DefaultedComparisonKind DCK
,
8418 SourceLocation BodyLoc
)
8419 : Base(S
, RD
, FD
, DCK
), Loc(BodyLoc
) {}
8421 /// Build a suitable function body for this defaulted comparison operator.
8422 StmtResult
build() {
8423 Sema::CompoundScopeRAII
CompoundScope(S
);
8425 StmtListResult Stmts
= visit();
8426 if (Stmts
.IsInvalid
)
8431 case DefaultedComparisonKind::None
:
8432 llvm_unreachable("not a defaulted comparison");
8434 case DefaultedComparisonKind::Equal
: {
8435 // C++2a [class.eq]p3:
8436 // [...] compar[e] the corresponding elements [...] until the first
8437 // index i where xi == yi yields [...] false. If no such index exists,
8438 // V is true. Otherwise, V is false.
8440 // Join the comparisons with '&&'s and return the result. Use a right
8441 // fold (traversing the conditions right-to-left), because that
8442 // short-circuits more naturally.
8443 auto OldStmts
= std::move(Stmts
.Stmts
);
8444 Stmts
.Stmts
.clear();
8445 ExprResult CmpSoFar
;
8446 // Finish a particular comparison chain.
8447 auto FinishCmp
= [&] {
8448 if (Expr
*Prior
= CmpSoFar
.get()) {
8449 // Convert the last expression to 'return ...;'
8450 if (RetVal
.isUnset() && Stmts
.Stmts
.empty())
8452 // Convert any prior comparison to 'if (!(...)) return false;'
8453 else if (Stmts
.add(buildIfNotCondReturnFalse(Prior
)))
8455 CmpSoFar
= ExprResult();
8459 for (Stmt
*EAsStmt
: llvm::reverse(OldStmts
)) {
8460 Expr
*E
= dyn_cast
<Expr
>(EAsStmt
);
8462 // Found an array comparison.
8463 if (FinishCmp() || Stmts
.add(EAsStmt
))
8468 if (CmpSoFar
.isUnset()) {
8472 CmpSoFar
= S
.CreateBuiltinBinOp(Loc
, BO_LAnd
, E
, CmpSoFar
.get());
8473 if (CmpSoFar
.isInvalid())
8478 std::reverse(Stmts
.Stmts
.begin(), Stmts
.Stmts
.end());
8479 // If no such index exists, V is true.
8480 if (RetVal
.isUnset())
8481 RetVal
= S
.ActOnCXXBoolLiteral(Loc
, tok::kw_true
);
8485 case DefaultedComparisonKind::ThreeWay
: {
8486 // Per C++2a [class.spaceship]p3, as a fallback add:
8487 // return static_cast<R>(std::strong_ordering::equal);
8488 QualType StrongOrdering
= S
.CheckComparisonCategoryType(
8489 ComparisonCategoryType::StrongOrdering
, Loc
,
8490 Sema::ComparisonCategoryUsage::DefaultedOperator
);
8491 if (StrongOrdering
.isNull())
8493 VarDecl
*EqualVD
= S
.Context
.CompCategories
.getInfoForType(StrongOrdering
)
8494 .getValueInfo(ComparisonCategoryResult::Equal
)
8496 RetVal
= getDecl(EqualVD
);
8497 if (RetVal
.isInvalid())
8499 RetVal
= buildStaticCastToR(RetVal
.get());
8503 case DefaultedComparisonKind::NotEqual
:
8504 case DefaultedComparisonKind::Relational
:
8505 RetVal
= cast
<Expr
>(Stmts
.Stmts
.pop_back_val());
8509 // Build the final return statement.
8510 if (RetVal
.isInvalid())
8512 StmtResult ReturnStmt
= S
.BuildReturnStmt(Loc
, RetVal
.get());
8513 if (ReturnStmt
.isInvalid())
8515 Stmts
.Stmts
.push_back(ReturnStmt
.get());
8517 return S
.ActOnCompoundStmt(Loc
, Loc
, Stmts
.Stmts
, /*IsStmtExpr=*/false);
8521 ExprResult
getDecl(ValueDecl
*VD
) {
8522 return S
.BuildDeclarationNameExpr(
8523 CXXScopeSpec(), DeclarationNameInfo(VD
->getDeclName(), Loc
), VD
);
8526 ExprResult
getParam(unsigned I
) {
8527 ParmVarDecl
*PD
= FD
->getParamDecl(I
);
8531 ExprPair
getCompleteObject() {
8534 if (const auto *MD
= dyn_cast
<CXXMethodDecl
>(FD
);
8535 MD
&& MD
->isImplicitObjectMemberFunction()) {
8537 LHS
= S
.ActOnCXXThis(Loc
);
8538 if (!LHS
.isInvalid())
8539 LHS
= S
.CreateBuiltinUnaryOp(Loc
, UO_Deref
, LHS
.get());
8541 LHS
= getParam(Param
++);
8543 ExprResult RHS
= getParam(Param
++);
8544 assert(Param
== FD
->getNumParams());
8548 ExprPair
getBase(CXXBaseSpecifier
*Base
) {
8549 ExprPair Obj
= getCompleteObject();
8550 if (Obj
.first
.isInvalid() || Obj
.second
.isInvalid())
8551 return {ExprError(), ExprError()};
8552 CXXCastPath Path
= {Base
};
8553 return {S
.ImpCastExprToType(Obj
.first
.get(), Base
->getType(),
8554 CK_DerivedToBase
, VK_LValue
, &Path
),
8555 S
.ImpCastExprToType(Obj
.second
.get(), Base
->getType(),
8556 CK_DerivedToBase
, VK_LValue
, &Path
)};
8559 ExprPair
getField(FieldDecl
*Field
) {
8560 ExprPair Obj
= getCompleteObject();
8561 if (Obj
.first
.isInvalid() || Obj
.second
.isInvalid())
8562 return {ExprError(), ExprError()};
8564 DeclAccessPair Found
= DeclAccessPair::make(Field
, Field
->getAccess());
8565 DeclarationNameInfo
NameInfo(Field
->getDeclName(), Loc
);
8566 return {S
.BuildFieldReferenceExpr(Obj
.first
.get(), /*IsArrow=*/false, Loc
,
8567 CXXScopeSpec(), Field
, Found
, NameInfo
),
8568 S
.BuildFieldReferenceExpr(Obj
.second
.get(), /*IsArrow=*/false, Loc
,
8569 CXXScopeSpec(), Field
, Found
, NameInfo
)};
8572 // FIXME: When expanding a subobject, register a note in the code synthesis
8573 // stack to say which subobject we're comparing.
8575 StmtResult
buildIfNotCondReturnFalse(ExprResult Cond
) {
8576 if (Cond
.isInvalid())
8579 ExprResult NotCond
= S
.CreateBuiltinUnaryOp(Loc
, UO_LNot
, Cond
.get());
8580 if (NotCond
.isInvalid())
8583 ExprResult False
= S
.ActOnCXXBoolLiteral(Loc
, tok::kw_false
);
8584 assert(!False
.isInvalid() && "should never fail");
8585 StmtResult ReturnFalse
= S
.BuildReturnStmt(Loc
, False
.get());
8586 if (ReturnFalse
.isInvalid())
8589 return S
.ActOnIfStmt(Loc
, IfStatementKind::Ordinary
, Loc
, nullptr,
8590 S
.ActOnCondition(nullptr, Loc
, NotCond
.get(),
8591 Sema::ConditionKind::Boolean
),
8592 Loc
, ReturnFalse
.get(), SourceLocation(), nullptr);
8595 StmtResult
visitSubobjectArray(QualType Type
, llvm::APInt Size
,
8597 QualType SizeType
= S
.Context
.getSizeType();
8598 Size
= Size
.zextOrTrunc(S
.Context
.getTypeSize(SizeType
));
8600 // Build 'size_t i$n = 0'.
8601 IdentifierInfo
*IterationVarName
= nullptr;
8604 llvm::raw_svector_ostream
OS(Str
);
8605 OS
<< "i" << ArrayDepth
;
8606 IterationVarName
= &S
.Context
.Idents
.get(OS
.str());
8608 VarDecl
*IterationVar
= VarDecl::Create(
8609 S
.Context
, S
.CurContext
, Loc
, Loc
, IterationVarName
, SizeType
,
8610 S
.Context
.getTrivialTypeSourceInfo(SizeType
, Loc
), SC_None
);
8611 llvm::APInt
Zero(S
.Context
.getTypeSize(SizeType
), 0);
8612 IterationVar
->setInit(
8613 IntegerLiteral::Create(S
.Context
, Zero
, SizeType
, Loc
));
8614 Stmt
*Init
= new (S
.Context
) DeclStmt(DeclGroupRef(IterationVar
), Loc
, Loc
);
8616 auto IterRef
= [&] {
8617 ExprResult Ref
= S
.BuildDeclarationNameExpr(
8618 CXXScopeSpec(), DeclarationNameInfo(IterationVarName
, Loc
),
8620 assert(!Ref
.isInvalid() && "can't reference our own variable?");
8624 // Build 'i$n != Size'.
8625 ExprResult Cond
= S
.CreateBuiltinBinOp(
8626 Loc
, BO_NE
, IterRef(),
8627 IntegerLiteral::Create(S
.Context
, Size
, SizeType
, Loc
));
8628 assert(!Cond
.isInvalid() && "should never fail");
8631 ExprResult Inc
= S
.CreateBuiltinUnaryOp(Loc
, UO_PreInc
, IterRef());
8632 assert(!Inc
.isInvalid() && "should never fail");
8634 // Build 'a[i$n]' and 'b[i$n]'.
8635 auto Index
= [&](ExprResult E
) {
8638 return S
.CreateBuiltinArraySubscriptExpr(E
.get(), Loc
, IterRef(), Loc
);
8640 Subobj
.first
= Index(Subobj
.first
);
8641 Subobj
.second
= Index(Subobj
.second
);
8643 // Compare the array elements.
8645 StmtResult Substmt
= visitSubobject(Type
, Subobj
);
8648 if (Substmt
.isInvalid())
8651 // For the inner level of an 'operator==', build 'if (!cmp) return false;'.
8652 // For outer levels or for an 'operator<=>' we already have a suitable
8653 // statement that returns as necessary.
8654 if (Expr
*ElemCmp
= dyn_cast
<Expr
>(Substmt
.get())) {
8655 assert(DCK
== DefaultedComparisonKind::Equal
&&
8656 "should have non-expression statement");
8657 Substmt
= buildIfNotCondReturnFalse(ElemCmp
);
8658 if (Substmt
.isInvalid())
8662 // Build 'for (...) ...'
8663 return S
.ActOnForStmt(Loc
, Loc
, Init
,
8664 S
.ActOnCondition(nullptr, Loc
, Cond
.get(),
8665 Sema::ConditionKind::Boolean
),
8666 S
.MakeFullDiscardedValueExpr(Inc
.get()), Loc
,
8670 StmtResult
visitExpandedSubobject(QualType Type
, ExprPair Obj
) {
8671 if (Obj
.first
.isInvalid() || Obj
.second
.isInvalid())
8674 OverloadedOperatorKind OO
= FD
->getOverloadedOperator();
8675 BinaryOperatorKind Opc
= BinaryOperator::getOverloadedOpcode(OO
);
8677 if (Type
->isOverloadableType())
8678 Op
= S
.CreateOverloadedBinOp(Loc
, Opc
, Fns
, Obj
.first
.get(),
8679 Obj
.second
.get(), /*PerformADL=*/true,
8680 /*AllowRewrittenCandidates=*/true, FD
);
8682 Op
= S
.CreateBuiltinBinOp(Loc
, Opc
, Obj
.first
.get(), Obj
.second
.get());
8687 case DefaultedComparisonKind::None
:
8688 llvm_unreachable("not a defaulted comparison");
8690 case DefaultedComparisonKind::Equal
:
8691 // Per C++2a [class.eq]p2, each comparison is individually contextually
8692 // converted to bool.
8693 Op
= S
.PerformContextuallyConvertToBool(Op
.get());
8698 case DefaultedComparisonKind::ThreeWay
: {
8699 // Per C++2a [class.spaceship]p3, form:
8700 // if (R cmp = static_cast<R>(op); cmp != 0)
8702 QualType R
= FD
->getReturnType();
8703 Op
= buildStaticCastToR(Op
.get());
8708 IdentifierInfo
*Name
= &S
.Context
.Idents
.get("cmp");
8710 VarDecl::Create(S
.Context
, S
.CurContext
, Loc
, Loc
, Name
, R
,
8711 S
.Context
.getTrivialTypeSourceInfo(R
, Loc
), SC_None
);
8712 S
.AddInitializerToDecl(VD
, Op
.get(), /*DirectInit=*/false);
8713 Stmt
*InitStmt
= new (S
.Context
) DeclStmt(DeclGroupRef(VD
), Loc
, Loc
);
8716 ExprResult VDRef
= getDecl(VD
);
8717 if (VDRef
.isInvalid())
8719 llvm::APInt
ZeroVal(S
.Context
.getIntWidth(S
.Context
.IntTy
), 0);
8721 IntegerLiteral::Create(S
.Context
, ZeroVal
, S
.Context
.IntTy
, Loc
);
8723 if (VDRef
.get()->getType()->isOverloadableType())
8724 Comp
= S
.CreateOverloadedBinOp(Loc
, BO_NE
, Fns
, VDRef
.get(), Zero
, true,
8727 Comp
= S
.CreateBuiltinBinOp(Loc
, BO_NE
, VDRef
.get(), Zero
);
8728 if (Comp
.isInvalid())
8730 Sema::ConditionResult Cond
= S
.ActOnCondition(
8731 nullptr, Loc
, Comp
.get(), Sema::ConditionKind::Boolean
);
8732 if (Cond
.isInvalid())
8736 VDRef
= getDecl(VD
);
8737 if (VDRef
.isInvalid())
8739 StmtResult ReturnStmt
= S
.BuildReturnStmt(Loc
, VDRef
.get());
8740 if (ReturnStmt
.isInvalid())
8744 return S
.ActOnIfStmt(Loc
, IfStatementKind::Ordinary
, Loc
, InitStmt
, Cond
,
8745 Loc
, ReturnStmt
.get(),
8746 /*ElseLoc=*/SourceLocation(), /*Else=*/nullptr);
8749 case DefaultedComparisonKind::NotEqual
:
8750 case DefaultedComparisonKind::Relational
:
8751 // C++2a [class.compare.secondary]p2:
8752 // Otherwise, the operator function yields x @ y.
8755 llvm_unreachable("");
8758 /// Build "static_cast<R>(E)".
8759 ExprResult
buildStaticCastToR(Expr
*E
) {
8760 QualType R
= FD
->getReturnType();
8761 assert(!R
->isUndeducedType() && "type should have been deduced already");
8763 // Don't bother forming a no-op cast in the common case.
8764 if (E
->isPRValue() && S
.Context
.hasSameType(E
->getType(), R
))
8766 return S
.BuildCXXNamedCast(Loc
, tok::kw_static_cast
,
8767 S
.Context
.getTrivialTypeSourceInfo(R
, Loc
), E
,
8768 SourceRange(Loc
, Loc
), SourceRange(Loc
, Loc
));
8773 /// Perform the unqualified lookups that might be needed to form a defaulted
8774 /// comparison function for the given operator.
8775 static void lookupOperatorsForDefaultedComparison(Sema
&Self
, Scope
*S
,
8776 UnresolvedSetImpl
&Operators
,
8777 OverloadedOperatorKind Op
) {
8778 auto Lookup
= [&](OverloadedOperatorKind OO
) {
8779 Self
.LookupOverloadedOperatorName(OO
, S
, Operators
);
8782 // Every defaulted operator looks up itself.
8784 // ... and the rewritten form of itself, if any.
8785 if (OverloadedOperatorKind ExtraOp
= getRewrittenOverloadedOperator(Op
))
8788 // For 'operator<=>', we also form a 'cmp != 0' expression, and might
8789 // synthesize a three-way comparison from '<' and '=='. In a dependent
8790 // context, we also need to look up '==' in case we implicitly declare a
8791 // defaulted 'operator=='.
8792 if (Op
== OO_Spaceship
) {
8793 Lookup(OO_ExclaimEqual
);
8795 Lookup(OO_EqualEqual
);
8799 bool Sema::CheckExplicitlyDefaultedComparison(Scope
*S
, FunctionDecl
*FD
,
8800 DefaultedComparisonKind DCK
) {
8801 assert(DCK
!= DefaultedComparisonKind::None
&& "not a defaulted comparison");
8803 // Perform any unqualified lookups we're going to need to default this
8806 UnresolvedSet
<32> Operators
;
8807 lookupOperatorsForDefaultedComparison(*this, S
, Operators
,
8808 FD
->getOverloadedOperator());
8809 FD
->setDefaultedFunctionInfo(FunctionDecl::DefaultedFunctionInfo::Create(
8810 Context
, Operators
.pairs()));
8813 // C++2a [class.compare.default]p1:
8814 // A defaulted comparison operator function for some class C shall be a
8815 // non-template function declared in the member-specification of C that is
8816 // -- a non-static const non-volatile member of C having one parameter of
8817 // type const C& and either no ref-qualifier or the ref-qualifier &, or
8818 // -- a friend of C having two parameters of type const C& or two
8819 // parameters of type C.
8821 CXXRecordDecl
*RD
= dyn_cast
<CXXRecordDecl
>(FD
->getLexicalDeclContext());
8822 bool IsMethod
= isa
<CXXMethodDecl
>(FD
);
8824 auto *MD
= cast
<CXXMethodDecl
>(FD
);
8825 assert(!MD
->isStatic() && "comparison function cannot be a static member");
8827 if (MD
->getRefQualifier() == RQ_RValue
) {
8828 Diag(MD
->getLocation(), diag::err_ref_qualifier_comparison_operator
);
8830 // Remove the ref qualifier to recover.
8831 const auto *FPT
= MD
->getType()->castAs
<FunctionProtoType
>();
8832 FunctionProtoType::ExtProtoInfo EPI
= FPT
->getExtProtoInfo();
8833 EPI
.RefQualifier
= RQ_None
;
8834 MD
->setType(Context
.getFunctionType(FPT
->getReturnType(),
8835 FPT
->getParamTypes(), EPI
));
8838 // If we're out-of-class, this is the class we're comparing.
8840 RD
= MD
->getParent();
8841 QualType T
= MD
->getFunctionObjectParameterType();
8842 if (!T
.isConstQualified()) {
8843 SourceLocation Loc
, InsertLoc
;
8844 if (MD
->isExplicitObjectMemberFunction()) {
8845 Loc
= MD
->getParamDecl(0)->getBeginLoc();
8846 InsertLoc
= getLocForEndOfToken(
8847 MD
->getParamDecl(0)->getExplicitObjectParamThisLoc());
8849 Loc
= MD
->getLocation();
8850 if (FunctionTypeLoc Loc
= MD
->getFunctionTypeLoc())
8851 InsertLoc
= Loc
.getRParenLoc();
8853 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8854 // corresponding defaulted 'operator<=>' already.
8855 if (!MD
->isImplicit()) {
8856 Diag(Loc
, diag::err_defaulted_comparison_non_const
)
8857 << (int)DCK
<< FixItHint::CreateInsertion(InsertLoc
, " const");
8860 // Add the 'const' to the type to recover.
8861 const auto *FPT
= MD
->getType()->castAs
<FunctionProtoType
>();
8862 FunctionProtoType::ExtProtoInfo EPI
= FPT
->getExtProtoInfo();
8863 EPI
.TypeQuals
.addConst();
8864 MD
->setType(Context
.getFunctionType(FPT
->getReturnType(),
8865 FPT
->getParamTypes(), EPI
));
8868 if (MD
->isVolatile()) {
8869 Diag(MD
->getLocation(), diag::err_volatile_comparison_operator
);
8871 // Remove the 'volatile' from the type to recover.
8872 const auto *FPT
= MD
->getType()->castAs
<FunctionProtoType
>();
8873 FunctionProtoType::ExtProtoInfo EPI
= FPT
->getExtProtoInfo();
8874 EPI
.TypeQuals
.removeVolatile();
8875 MD
->setType(Context
.getFunctionType(FPT
->getReturnType(),
8876 FPT
->getParamTypes(), EPI
));
8880 if ((FD
->getNumParams() -
8881 (unsigned)FD
->hasCXXExplicitFunctionObjectParameter()) !=
8882 (IsMethod
? 1 : 2)) {
8883 // Let's not worry about using a variadic template pack here -- who would do
8885 Diag(FD
->getLocation(), diag::err_defaulted_comparison_num_args
)
8886 << int(IsMethod
) << int(DCK
);
8890 const ParmVarDecl
*KnownParm
= nullptr;
8891 for (const ParmVarDecl
*Param
: FD
->parameters()) {
8892 if (Param
->isExplicitObjectParameter())
8894 QualType ParmTy
= Param
->getType();
8898 // Is it `T const &`?
8899 bool Ok
= !IsMethod
;
8900 QualType ExpectedTy
;
8902 ExpectedTy
= Context
.getRecordType(RD
);
8903 if (auto *Ref
= CTy
->getAs
<ReferenceType
>()) {
8904 CTy
= Ref
->getPointeeType();
8906 ExpectedTy
.addConst();
8913 if (!RD
->isDependentType() && !Context
.hasSameType(CTy
, ExpectedTy
))
8915 } else if (auto *CRD
= CTy
->getAsRecordDecl()) {
8916 RD
= cast
<CXXRecordDecl
>(CRD
);
8924 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8925 // corresponding defaulted 'operator<=>' already.
8926 if (!FD
->isImplicit()) {
8928 QualType PlainTy
= Context
.getRecordType(RD
);
8930 Context
.getLValueReferenceType(PlainTy
.withConst());
8931 Diag(FD
->getLocation(), diag::err_defaulted_comparison_param
)
8932 << int(DCK
) << ParmTy
<< RefTy
<< int(!IsMethod
) << PlainTy
8933 << Param
->getSourceRange();
8935 assert(!IsMethod
&& "should know expected type for method");
8936 Diag(FD
->getLocation(),
8937 diag::err_defaulted_comparison_param_unknown
)
8938 << int(DCK
) << ParmTy
<< Param
->getSourceRange();
8943 } else if (!Context
.hasSameType(KnownParm
->getType(), ParmTy
)) {
8944 Diag(FD
->getLocation(), diag::err_defaulted_comparison_param_mismatch
)
8945 << int(DCK
) << KnownParm
->getType() << KnownParm
->getSourceRange()
8946 << ParmTy
<< Param
->getSourceRange();
8951 assert(RD
&& "must have determined class");
8953 } else if (isa
<CXXRecordDecl
>(FD
->getLexicalDeclContext())) {
8954 // In-class, must be a friend decl.
8955 assert(FD
->getFriendObjectKind() && "expected a friend declaration");
8957 // Out of class, require the defaulted comparison to be a friend (of a
8959 if (RequireCompleteType(FD
->getLocation(), Context
.getRecordType(RD
),
8960 diag::err_defaulted_comparison_not_friend
, int(DCK
),
8964 if (llvm::none_of(RD
->friends(), [&](const FriendDecl
*F
) {
8965 return FD
->getCanonicalDecl() ==
8966 F
->getFriendDecl()->getCanonicalDecl();
8968 Diag(FD
->getLocation(), diag::err_defaulted_comparison_not_friend
)
8969 << int(DCK
) << int(0) << RD
;
8970 Diag(RD
->getCanonicalDecl()->getLocation(), diag::note_declared_at
);
8975 // C++2a [class.eq]p1, [class.rel]p1:
8976 // A [defaulted comparison other than <=>] shall have a declared return
8978 if (DCK
!= DefaultedComparisonKind::ThreeWay
&&
8979 !FD
->getDeclaredReturnType()->isDependentType() &&
8980 !Context
.hasSameType(FD
->getDeclaredReturnType(), Context
.BoolTy
)) {
8981 Diag(FD
->getLocation(), diag::err_defaulted_comparison_return_type_not_bool
)
8982 << (int)DCK
<< FD
->getDeclaredReturnType() << Context
.BoolTy
8983 << FD
->getReturnTypeSourceRange();
8986 // C++2a [class.spaceship]p2 [P2002R0]:
8987 // Let R be the declared return type [...]. If R is auto, [...]. Otherwise,
8988 // R shall not contain a placeholder type.
8989 if (QualType RT
= FD
->getDeclaredReturnType();
8990 DCK
== DefaultedComparisonKind::ThreeWay
&&
8991 RT
->getContainedDeducedType() &&
8992 (!Context
.hasSameType(RT
, Context
.getAutoDeductType()) ||
8993 RT
->getContainedAutoType()->isConstrained())) {
8994 Diag(FD
->getLocation(),
8995 diag::err_defaulted_comparison_deduced_return_type_not_auto
)
8996 << (int)DCK
<< FD
->getDeclaredReturnType() << Context
.AutoDeductTy
8997 << FD
->getReturnTypeSourceRange();
9001 // For a defaulted function in a dependent class, defer all remaining checks
9002 // until instantiation.
9003 if (RD
->isDependentType())
9006 // Determine whether the function should be defined as deleted.
9007 DefaultedComparisonInfo Info
=
9008 DefaultedComparisonAnalyzer(*this, RD
, FD
, DCK
).visit();
9010 bool First
= FD
== FD
->getCanonicalDecl();
9014 // C++11 [dcl.fct.def.default]p4:
9015 // [For a] user-provided explicitly-defaulted function [...] if such a
9016 // function is implicitly defined as deleted, the program is ill-formed.
9018 // This is really just a consequence of the general rule that you can
9019 // only delete a function on its first declaration.
9020 Diag(FD
->getLocation(), diag::err_non_first_default_compare_deletes
)
9021 << FD
->isImplicit() << (int)DCK
;
9022 DefaultedComparisonAnalyzer(*this, RD
, FD
, DCK
,
9023 DefaultedComparisonAnalyzer::ExplainDeleted
)
9027 if (isa
<CXXRecordDecl
>(FD
->getLexicalDeclContext())) {
9028 // C++20 [class.compare.default]p1:
9029 // [...] A definition of a comparison operator as defaulted that appears
9030 // in a class shall be the first declaration of that function.
9031 Diag(FD
->getLocation(), diag::err_non_first_default_compare_in_class
)
9033 Diag(FD
->getCanonicalDecl()->getLocation(),
9034 diag::note_previous_declaration
);
9039 // If we want to delete the function, then do so; there's nothing else to
9040 // check in that case.
9042 SetDeclDeleted(FD
, FD
->getLocation());
9043 if (!inTemplateInstantiation() && !FD
->isImplicit()) {
9044 Diag(FD
->getLocation(), diag::warn_defaulted_comparison_deleted
)
9046 DefaultedComparisonAnalyzer(*this, RD
, FD
, DCK
,
9047 DefaultedComparisonAnalyzer::ExplainDeleted
)
9049 if (FD
->getDefaultLoc().isValid())
9050 Diag(FD
->getDefaultLoc(), diag::note_replace_equals_default_to_delete
)
9051 << FixItHint::CreateReplacement(FD
->getDefaultLoc(), "delete");
9056 // C++2a [class.spaceship]p2:
9057 // The return type is deduced as the common comparison type of R0, R1, ...
9058 if (DCK
== DefaultedComparisonKind::ThreeWay
&&
9059 FD
->getDeclaredReturnType()->isUndeducedAutoType()) {
9060 SourceLocation RetLoc
= FD
->getReturnTypeSourceRange().getBegin();
9061 if (RetLoc
.isInvalid())
9062 RetLoc
= FD
->getBeginLoc();
9063 // FIXME: Should we really care whether we have the complete type and the
9064 // 'enumerator' constants here? A forward declaration seems sufficient.
9065 QualType Cat
= CheckComparisonCategoryType(
9066 Info
.Category
, RetLoc
, ComparisonCategoryUsage::DefaultedOperator
);
9069 Context
.adjustDeducedFunctionResultType(
9070 FD
, SubstAutoType(FD
->getDeclaredReturnType(), Cat
));
9073 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
9074 // An explicitly-defaulted function that is not defined as deleted may be
9075 // declared constexpr or consteval only if it is constexpr-compatible.
9076 // C++2a [class.compare.default]p3 [P2002R0]:
9077 // A defaulted comparison function is constexpr-compatible if it satisfies
9078 // the requirements for a constexpr function [...]
9079 // The only relevant requirements are that the parameter and return types are
9080 // literal types. The remaining conditions are checked by the analyzer.
9082 // We support P2448R2 in language modes earlier than C++23 as an extension.
9083 // The concept of constexpr-compatible was removed.
9084 // C++23 [dcl.fct.def.default]p3 [P2448R2]
9085 // A function explicitly defaulted on its first declaration is implicitly
9086 // inline, and is implicitly constexpr if it is constexpr-suitable.
9087 // C++23 [dcl.constexpr]p3
9088 // A function is constexpr-suitable if
9089 // - it is not a coroutine, and
9090 // - if the function is a constructor or destructor, its class does not
9091 // have any virtual base classes.
9092 if (FD
->isConstexpr()) {
9093 if (CheckConstexprReturnType(*this, FD
, CheckConstexprKind::Diagnose
) &&
9094 CheckConstexprParameterTypes(*this, FD
, CheckConstexprKind::Diagnose
) &&
9096 Diag(FD
->getBeginLoc(),
9097 getLangOpts().CPlusPlus23
9098 ? diag::warn_cxx23_compat_defaulted_comparison_constexpr_mismatch
9099 : diag::ext_defaulted_comparison_constexpr_mismatch
)
9100 << FD
->isImplicit() << (int)DCK
<< FD
->isConsteval();
9101 DefaultedComparisonAnalyzer(*this, RD
, FD
, DCK
,
9102 DefaultedComparisonAnalyzer::ExplainConstexpr
)
9107 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
9108 // If a constexpr-compatible function is explicitly defaulted on its first
9109 // declaration, it is implicitly considered to be constexpr.
9110 // FIXME: Only applying this to the first declaration seems problematic, as
9111 // simple reorderings can affect the meaning of the program.
9112 if (First
&& !FD
->isConstexpr() && Info
.Constexpr
)
9113 FD
->setConstexprKind(ConstexprSpecKind::Constexpr
);
9115 // C++2a [except.spec]p3:
9116 // If a declaration of a function does not have a noexcept-specifier
9117 // [and] is defaulted on its first declaration, [...] the exception
9118 // specification is as specified below
9119 if (FD
->getExceptionSpecType() == EST_None
) {
9120 auto *FPT
= FD
->getType()->castAs
<FunctionProtoType
>();
9121 FunctionProtoType::ExtProtoInfo EPI
= FPT
->getExtProtoInfo();
9122 EPI
.ExceptionSpec
.Type
= EST_Unevaluated
;
9123 EPI
.ExceptionSpec
.SourceDecl
= FD
;
9124 FD
->setType(Context
.getFunctionType(FPT
->getReturnType(),
9125 FPT
->getParamTypes(), EPI
));
9131 void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl
*RD
,
9132 FunctionDecl
*Spaceship
) {
9133 Sema::CodeSynthesisContext Ctx
;
9134 Ctx
.Kind
= Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison
;
9135 Ctx
.PointOfInstantiation
= Spaceship
->getEndLoc();
9136 Ctx
.Entity
= Spaceship
;
9137 pushCodeSynthesisContext(Ctx
);
9139 if (FunctionDecl
*EqualEqual
= SubstSpaceshipAsEqualEqual(RD
, Spaceship
))
9140 EqualEqual
->setImplicit();
9142 popCodeSynthesisContext();
9145 void Sema::DefineDefaultedComparison(SourceLocation UseLoc
, FunctionDecl
*FD
,
9146 DefaultedComparisonKind DCK
) {
9147 assert(FD
->isDefaulted() && !FD
->isDeleted() &&
9148 !FD
->doesThisDeclarationHaveABody());
9149 if (FD
->willHaveBody() || FD
->isInvalidDecl())
9152 SynthesizedFunctionScope
Scope(*this, FD
);
9154 // Add a context note for diagnostics produced after this point.
9155 Scope
.addContextNote(UseLoc
);
9158 // Build and set up the function body.
9159 // The first parameter has type maybe-ref-to maybe-const T, use that to get
9160 // the type of the class being compared.
9161 auto PT
= FD
->getParamDecl(0)->getType();
9162 CXXRecordDecl
*RD
= PT
.getNonReferenceType()->getAsCXXRecordDecl();
9163 SourceLocation BodyLoc
=
9164 FD
->getEndLoc().isValid() ? FD
->getEndLoc() : FD
->getLocation();
9166 DefaultedComparisonSynthesizer(*this, RD
, FD
, DCK
, BodyLoc
).build();
9167 if (Body
.isInvalid()) {
9168 FD
->setInvalidDecl();
9171 FD
->setBody(Body
.get());
9172 FD
->markUsed(Context
);
9175 // The exception specification is needed because we are defining the
9176 // function. Note that this will reuse the body we just built.
9177 ResolveExceptionSpec(UseLoc
, FD
->getType()->castAs
<FunctionProtoType
>());
9179 if (ASTMutationListener
*L
= getASTMutationListener())
9180 L
->CompletedImplicitDefinition(FD
);
9183 static Sema::ImplicitExceptionSpecification
9184 ComputeDefaultedComparisonExceptionSpec(Sema
&S
, SourceLocation Loc
,
9186 Sema::DefaultedComparisonKind DCK
) {
9187 ComputingExceptionSpec
CES(S
, FD
, Loc
);
9188 Sema::ImplicitExceptionSpecification
ExceptSpec(S
);
9190 if (FD
->isInvalidDecl())
9193 // The common case is that we just defined the comparison function. In that
9194 // case, just look at whether the body can throw.
9195 if (FD
->hasBody()) {
9196 ExceptSpec
.CalledStmt(FD
->getBody());
9198 // Otherwise, build a body so we can check it. This should ideally only
9199 // happen when we're not actually marking the function referenced. (This is
9200 // only really important for efficiency: we don't want to build and throw
9201 // away bodies for comparison functions more than we strictly need to.)
9203 // Pretend to synthesize the function body in an unevaluated context.
9204 // Note that we can't actually just go ahead and define the function here:
9205 // we are not permitted to mark its callees as referenced.
9206 Sema::SynthesizedFunctionScope
Scope(S
, FD
);
9207 EnterExpressionEvaluationContext
Context(
9208 S
, Sema::ExpressionEvaluationContext::Unevaluated
);
9210 CXXRecordDecl
*RD
= cast
<CXXRecordDecl
>(FD
->getLexicalParent());
9211 SourceLocation BodyLoc
=
9212 FD
->getEndLoc().isValid() ? FD
->getEndLoc() : FD
->getLocation();
9214 DefaultedComparisonSynthesizer(S
, RD
, FD
, DCK
, BodyLoc
).build();
9215 if (!Body
.isInvalid())
9216 ExceptSpec
.CalledStmt(Body
.get());
9218 // FIXME: Can we hold onto this body and just transform it to potentially
9219 // evaluated when we're asked to define the function rather than rebuilding
9220 // it? Either that, or we should only build the bits of the body that we
9221 // need (the expressions, not the statements).
9227 void Sema::CheckDelayedMemberExceptionSpecs() {
9228 decltype(DelayedOverridingExceptionSpecChecks
) Overriding
;
9229 decltype(DelayedEquivalentExceptionSpecChecks
) Equivalent
;
9231 std::swap(Overriding
, DelayedOverridingExceptionSpecChecks
);
9232 std::swap(Equivalent
, DelayedEquivalentExceptionSpecChecks
);
9234 // Perform any deferred checking of exception specifications for virtual
9236 for (auto &Check
: Overriding
)
9237 CheckOverridingFunctionExceptionSpec(Check
.first
, Check
.second
);
9239 // Perform any deferred checking of exception specifications for befriended
9241 for (auto &Check
: Equivalent
)
9242 CheckEquivalentExceptionSpec(Check
.second
, Check
.first
);
9246 /// CRTP base class for visiting operations performed by a special member
9247 /// function (or inherited constructor).
9248 template<typename Derived
>
9249 struct SpecialMemberVisitor
{
9252 Sema::CXXSpecialMember CSM
;
9253 Sema::InheritedConstructorInfo
*ICI
;
9255 // Properties of the special member, computed for convenience.
9256 bool IsConstructor
= false, IsAssignment
= false, ConstArg
= false;
9258 SpecialMemberVisitor(Sema
&S
, CXXMethodDecl
*MD
, Sema::CXXSpecialMember CSM
,
9259 Sema::InheritedConstructorInfo
*ICI
)
9260 : S(S
), MD(MD
), CSM(CSM
), ICI(ICI
) {
9262 case Sema::CXXDefaultConstructor
:
9263 case Sema::CXXCopyConstructor
:
9264 case Sema::CXXMoveConstructor
:
9265 IsConstructor
= true;
9267 case Sema::CXXCopyAssignment
:
9268 case Sema::CXXMoveAssignment
:
9269 IsAssignment
= true;
9271 case Sema::CXXDestructor
:
9273 case Sema::CXXInvalid
:
9274 llvm_unreachable("invalid special member kind");
9277 if (MD
->getNumExplicitParams()) {
9278 if (const ReferenceType
*RT
=
9279 MD
->getNonObjectParameter(0)->getType()->getAs
<ReferenceType
>())
9280 ConstArg
= RT
->getPointeeType().isConstQualified();
9284 Derived
&getDerived() { return static_cast<Derived
&>(*this); }
9286 /// Is this a "move" special member?
9287 bool isMove() const {
9288 return CSM
== Sema::CXXMoveConstructor
|| CSM
== Sema::CXXMoveAssignment
;
9291 /// Look up the corresponding special member in the given class.
9292 Sema::SpecialMemberOverloadResult
lookupIn(CXXRecordDecl
*Class
,
9293 unsigned Quals
, bool IsMutable
) {
9294 return lookupCallFromSpecialMember(S
, Class
, CSM
, Quals
,
9295 ConstArg
&& !IsMutable
);
9298 /// Look up the constructor for the specified base class to see if it's
9299 /// overridden due to this being an inherited constructor.
9300 Sema::SpecialMemberOverloadResult
lookupInheritedCtor(CXXRecordDecl
*Class
) {
9303 assert(CSM
== Sema::CXXDefaultConstructor
);
9305 cast
<CXXConstructorDecl
>(MD
)->getInheritedConstructor().getConstructor();
9306 if (auto *MD
= ICI
->findConstructorForBase(Class
, BaseCtor
).first
)
9311 /// A base or member subobject.
9312 typedef llvm::PointerUnion
<CXXBaseSpecifier
*, FieldDecl
*> Subobject
;
9314 /// Get the location to use for a subobject in diagnostics.
9315 static SourceLocation
getSubobjectLoc(Subobject Subobj
) {
9316 // FIXME: For an indirect virtual base, the direct base leading to
9317 // the indirect virtual base would be a more useful choice.
9318 if (auto *B
= Subobj
.dyn_cast
<CXXBaseSpecifier
*>())
9319 return B
->getBaseTypeLoc();
9321 return Subobj
.get
<FieldDecl
*>()->getLocation();
9325 /// Visit all non-virtual (direct) bases.
9326 VisitNonVirtualBases
,
9327 /// Visit all direct bases, virtual or not.
9329 /// Visit all non-virtual bases, and all virtual bases if the class
9330 /// is not abstract.
9331 VisitPotentiallyConstructedBases
,
9332 /// Visit all direct or virtual bases.
9336 // Visit the bases and members of the class.
9337 bool visit(BasesToVisit Bases
) {
9338 CXXRecordDecl
*RD
= MD
->getParent();
9340 if (Bases
== VisitPotentiallyConstructedBases
)
9341 Bases
= RD
->isAbstract() ? VisitNonVirtualBases
: VisitAllBases
;
9343 for (auto &B
: RD
->bases())
9344 if ((Bases
== VisitDirectBases
|| !B
.isVirtual()) &&
9345 getDerived().visitBase(&B
))
9348 if (Bases
== VisitAllBases
)
9349 for (auto &B
: RD
->vbases())
9350 if (getDerived().visitBase(&B
))
9353 for (auto *F
: RD
->fields())
9354 if (!F
->isInvalidDecl() && !F
->isUnnamedBitfield() &&
9355 getDerived().visitField(F
))
9364 struct SpecialMemberDeletionInfo
9365 : SpecialMemberVisitor
<SpecialMemberDeletionInfo
> {
9370 bool AllFieldsAreConst
;
9372 SpecialMemberDeletionInfo(Sema
&S
, CXXMethodDecl
*MD
,
9373 Sema::CXXSpecialMember CSM
,
9374 Sema::InheritedConstructorInfo
*ICI
, bool Diagnose
)
9375 : SpecialMemberVisitor(S
, MD
, CSM
, ICI
), Diagnose(Diagnose
),
9376 Loc(MD
->getLocation()), AllFieldsAreConst(true) {}
9378 bool inUnion() const { return MD
->getParent()->isUnion(); }
9380 Sema::CXXSpecialMember
getEffectiveCSM() {
9381 return ICI
? Sema::CXXInvalid
: CSM
;
9384 bool shouldDeleteForVariantObjCPtrMember(FieldDecl
*FD
, QualType FieldType
);
9386 bool visitBase(CXXBaseSpecifier
*Base
) { return shouldDeleteForBase(Base
); }
9387 bool visitField(FieldDecl
*Field
) { return shouldDeleteForField(Field
); }
9389 bool shouldDeleteForBase(CXXBaseSpecifier
*Base
);
9390 bool shouldDeleteForField(FieldDecl
*FD
);
9391 bool shouldDeleteForAllConstMembers();
9393 bool shouldDeleteForClassSubobject(CXXRecordDecl
*Class
, Subobject Subobj
,
9395 bool shouldDeleteForSubobjectCall(Subobject Subobj
,
9396 Sema::SpecialMemberOverloadResult SMOR
,
9397 bool IsDtorCallInCtor
);
9399 bool isAccessible(Subobject Subobj
, CXXMethodDecl
*D
);
9403 /// Is the given special member inaccessible when used on the given
9405 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj
,
9406 CXXMethodDecl
*target
) {
9407 /// If we're operating on a base class, the object type is the
9408 /// type of this special member.
9410 AccessSpecifier access
= target
->getAccess();
9411 if (CXXBaseSpecifier
*base
= Subobj
.dyn_cast
<CXXBaseSpecifier
*>()) {
9412 objectTy
= S
.Context
.getTypeDeclType(MD
->getParent());
9413 access
= CXXRecordDecl::MergeAccess(base
->getAccessSpecifier(), access
);
9415 // If we're operating on a field, the object type is the type of the field.
9417 objectTy
= S
.Context
.getTypeDeclType(target
->getParent());
9420 return S
.isMemberAccessibleForDeletion(
9421 target
->getParent(), DeclAccessPair::make(target
, access
), objectTy
);
9424 /// Check whether we should delete a special member due to the implicit
9425 /// definition containing a call to a special member of a subobject.
9426 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
9427 Subobject Subobj
, Sema::SpecialMemberOverloadResult SMOR
,
9428 bool IsDtorCallInCtor
) {
9429 CXXMethodDecl
*Decl
= SMOR
.getMethod();
9430 FieldDecl
*Field
= Subobj
.dyn_cast
<FieldDecl
*>();
9434 if (SMOR
.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted
)
9435 DiagKind
= !Decl
? 0 : 1;
9436 else if (SMOR
.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous
)
9438 else if (!isAccessible(Subobj
, Decl
))
9440 else if (!IsDtorCallInCtor
&& Field
&& Field
->getParent()->isUnion() &&
9441 !Decl
->isTrivial()) {
9442 // A member of a union must have a trivial corresponding special member.
9443 // As a weird special case, a destructor call from a union's constructor
9444 // must be accessible and non-deleted, but need not be trivial. Such a
9445 // destructor is never actually called, but is semantically checked as
9447 if (CSM
== Sema::CXXDefaultConstructor
) {
9448 // [class.default.ctor]p2:
9449 // A defaulted default constructor for class X is defined as deleted if
9450 // - X is a union that has a variant member with a non-trivial default
9451 // constructor and no variant member of X has a default member
9453 const auto *RD
= cast
<CXXRecordDecl
>(Field
->getParent());
9454 if (!RD
->hasInClassInitializer())
9466 S
.Diag(Field
->getLocation(),
9467 diag::note_deleted_special_member_class_subobject
)
9468 << getEffectiveCSM() << MD
->getParent() << /*IsField*/true
9469 << Field
<< DiagKind
<< IsDtorCallInCtor
<< /*IsObjCPtr*/false;
9471 CXXBaseSpecifier
*Base
= Subobj
.get
<CXXBaseSpecifier
*>();
9472 S
.Diag(Base
->getBeginLoc(),
9473 diag::note_deleted_special_member_class_subobject
)
9474 << getEffectiveCSM() << MD
->getParent() << /*IsField*/ false
9475 << Base
->getType() << DiagKind
<< IsDtorCallInCtor
9476 << /*IsObjCPtr*/false;
9480 S
.NoteDeletedFunction(Decl
);
9481 // FIXME: Explain inaccessibility if DiagKind == 3.
9487 /// Check whether we should delete a special member function due to having a
9488 /// direct or virtual base class or non-static data member of class type M.
9489 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
9490 CXXRecordDecl
*Class
, Subobject Subobj
, unsigned Quals
) {
9491 FieldDecl
*Field
= Subobj
.dyn_cast
<FieldDecl
*>();
9492 bool IsMutable
= Field
&& Field
->isMutable();
9494 // C++11 [class.ctor]p5:
9495 // -- any direct or virtual base class, or non-static data member with no
9496 // brace-or-equal-initializer, has class type M (or array thereof) and
9497 // either M has no default constructor or overload resolution as applied
9498 // to M's default constructor results in an ambiguity or in a function
9499 // that is deleted or inaccessible
9500 // C++11 [class.copy]p11, C++11 [class.copy]p23:
9501 // -- a direct or virtual base class B that cannot be copied/moved because
9502 // overload resolution, as applied to B's corresponding special member,
9503 // results in an ambiguity or a function that is deleted or inaccessible
9504 // from the defaulted special member
9505 // C++11 [class.dtor]p5:
9506 // -- any direct or virtual base class [...] has a type with a destructor
9507 // that is deleted or inaccessible
9508 if (!(CSM
== Sema::CXXDefaultConstructor
&&
9509 Field
&& Field
->hasInClassInitializer()) &&
9510 shouldDeleteForSubobjectCall(Subobj
, lookupIn(Class
, Quals
, IsMutable
),
9514 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
9515 // -- any direct or virtual base class or non-static data member has a
9516 // type with a destructor that is deleted or inaccessible
9517 if (IsConstructor
) {
9518 Sema::SpecialMemberOverloadResult SMOR
=
9519 S
.LookupSpecialMember(Class
, Sema::CXXDestructor
,
9520 false, false, false, false, false);
9521 if (shouldDeleteForSubobjectCall(Subobj
, SMOR
, true))
9528 bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
9529 FieldDecl
*FD
, QualType FieldType
) {
9530 // The defaulted special functions are defined as deleted if this is a variant
9531 // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
9533 if (!FieldType
.hasNonTrivialObjCLifetime())
9536 // Don't make the defaulted default constructor defined as deleted if the
9537 // member has an in-class initializer.
9538 if (CSM
== Sema::CXXDefaultConstructor
&& FD
->hasInClassInitializer())
9542 auto *ParentClass
= cast
<CXXRecordDecl
>(FD
->getParent());
9543 S
.Diag(FD
->getLocation(),
9544 diag::note_deleted_special_member_class_subobject
)
9545 << getEffectiveCSM() << ParentClass
<< /*IsField*/true
9546 << FD
<< 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true;
9552 /// Check whether we should delete a special member function due to the class
9553 /// having a particular direct or virtual base class.
9554 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier
*Base
) {
9555 CXXRecordDecl
*BaseClass
= Base
->getType()->getAsCXXRecordDecl();
9556 // If program is correct, BaseClass cannot be null, but if it is, the error
9557 // must be reported elsewhere.
9560 // If we have an inheriting constructor, check whether we're calling an
9561 // inherited constructor instead of a default constructor.
9562 Sema::SpecialMemberOverloadResult SMOR
= lookupInheritedCtor(BaseClass
);
9563 if (auto *BaseCtor
= SMOR
.getMethod()) {
9564 // Note that we do not check access along this path; other than that,
9565 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
9566 // FIXME: Check that the base has a usable destructor! Sink this into
9567 // shouldDeleteForClassSubobject.
9568 if (BaseCtor
->isDeleted() && Diagnose
) {
9569 S
.Diag(Base
->getBeginLoc(),
9570 diag::note_deleted_special_member_class_subobject
)
9571 << getEffectiveCSM() << MD
->getParent() << /*IsField*/ false
9572 << Base
->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
9573 << /*IsObjCPtr*/false;
9574 S
.NoteDeletedFunction(BaseCtor
);
9576 return BaseCtor
->isDeleted();
9578 return shouldDeleteForClassSubobject(BaseClass
, Base
, 0);
9581 /// Check whether we should delete a special member function due to the class
9582 /// having a particular non-static data member.
9583 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl
*FD
) {
9584 QualType FieldType
= S
.Context
.getBaseElementType(FD
->getType());
9585 CXXRecordDecl
*FieldRecord
= FieldType
->getAsCXXRecordDecl();
9587 if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD
, FieldType
))
9590 if (CSM
== Sema::CXXDefaultConstructor
) {
9591 // For a default constructor, all references must be initialized in-class
9592 // and, if a union, it must have a non-const member.
9593 if (FieldType
->isReferenceType() && !FD
->hasInClassInitializer()) {
9595 S
.Diag(FD
->getLocation(), diag::note_deleted_default_ctor_uninit_field
)
9596 << !!ICI
<< MD
->getParent() << FD
<< FieldType
<< /*Reference*/0;
9599 // C++11 [class.ctor]p5 (modified by DR2394): any non-variant non-static
9600 // data member of const-qualified type (or array thereof) with no
9601 // brace-or-equal-initializer is not const-default-constructible.
9602 if (!inUnion() && FieldType
.isConstQualified() &&
9603 !FD
->hasInClassInitializer() &&
9604 (!FieldRecord
|| !FieldRecord
->allowConstDefaultInit())) {
9606 S
.Diag(FD
->getLocation(), diag::note_deleted_default_ctor_uninit_field
)
9607 << !!ICI
<< MD
->getParent() << FD
<< FD
->getType() << /*Const*/1;
9611 if (inUnion() && !FieldType
.isConstQualified())
9612 AllFieldsAreConst
= false;
9613 } else if (CSM
== Sema::CXXCopyConstructor
) {
9614 // For a copy constructor, data members must not be of rvalue reference
9616 if (FieldType
->isRValueReferenceType()) {
9618 S
.Diag(FD
->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference
)
9619 << MD
->getParent() << FD
<< FieldType
;
9622 } else if (IsAssignment
) {
9623 // For an assignment operator, data members must not be of reference type.
9624 if (FieldType
->isReferenceType()) {
9626 S
.Diag(FD
->getLocation(), diag::note_deleted_assign_field
)
9627 << isMove() << MD
->getParent() << FD
<< FieldType
<< /*Reference*/0;
9630 if (!FieldRecord
&& FieldType
.isConstQualified()) {
9631 // C++11 [class.copy]p23:
9632 // -- a non-static data member of const non-class type (or array thereof)
9634 S
.Diag(FD
->getLocation(), diag::note_deleted_assign_field
)
9635 << isMove() << MD
->getParent() << FD
<< FD
->getType() << /*Const*/1;
9641 // Some additional restrictions exist on the variant members.
9642 if (!inUnion() && FieldRecord
->isUnion() &&
9643 FieldRecord
->isAnonymousStructOrUnion()) {
9644 bool AllVariantFieldsAreConst
= true;
9646 // FIXME: Handle anonymous unions declared within anonymous unions.
9647 for (auto *UI
: FieldRecord
->fields()) {
9648 QualType UnionFieldType
= S
.Context
.getBaseElementType(UI
->getType());
9650 if (shouldDeleteForVariantObjCPtrMember(&*UI
, UnionFieldType
))
9653 if (!UnionFieldType
.isConstQualified())
9654 AllVariantFieldsAreConst
= false;
9656 CXXRecordDecl
*UnionFieldRecord
= UnionFieldType
->getAsCXXRecordDecl();
9657 if (UnionFieldRecord
&&
9658 shouldDeleteForClassSubobject(UnionFieldRecord
, UI
,
9659 UnionFieldType
.getCVRQualifiers()))
9663 // At least one member in each anonymous union must be non-const
9664 if (CSM
== Sema::CXXDefaultConstructor
&& AllVariantFieldsAreConst
&&
9665 !FieldRecord
->field_empty()) {
9667 S
.Diag(FieldRecord
->getLocation(),
9668 diag::note_deleted_default_ctor_all_const
)
9669 << !!ICI
<< MD
->getParent() << /*anonymous union*/1;
9673 // Don't check the implicit member of the anonymous union type.
9674 // This is technically non-conformant but supported, and we have a
9675 // diagnostic for this elsewhere.
9679 if (shouldDeleteForClassSubobject(FieldRecord
, FD
,
9680 FieldType
.getCVRQualifiers()))
9687 /// C++11 [class.ctor] p5:
9688 /// A defaulted default constructor for a class X is defined as deleted if
9689 /// X is a union and all of its variant members are of const-qualified type.
9690 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
9691 // This is a silly definition, because it gives an empty union a deleted
9692 // default constructor. Don't do that.
9693 if (CSM
== Sema::CXXDefaultConstructor
&& inUnion() && AllFieldsAreConst
) {
9694 bool AnyFields
= false;
9695 for (auto *F
: MD
->getParent()->fields())
9696 if ((AnyFields
= !F
->isUnnamedBitfield()))
9701 S
.Diag(MD
->getParent()->getLocation(),
9702 diag::note_deleted_default_ctor_all_const
)
9703 << !!ICI
<< MD
->getParent() << /*not anonymous union*/0;
9709 /// Determine whether a defaulted special member function should be defined as
9710 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
9711 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
9712 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl
*MD
, CXXSpecialMember CSM
,
9713 InheritedConstructorInfo
*ICI
,
9715 if (MD
->isInvalidDecl())
9717 CXXRecordDecl
*RD
= MD
->getParent();
9718 assert(!RD
->isDependentType() && "do deletion after instantiation");
9719 if (!LangOpts
.CPlusPlus11
|| RD
->isInvalidDecl())
9722 // C++11 [expr.lambda.prim]p19:
9723 // The closure type associated with a lambda-expression has a
9724 // deleted (8.4.3) default constructor and a deleted copy
9725 // assignment operator.
9726 // C++2a adds back these operators if the lambda has no lambda-capture.
9727 if (RD
->isLambda() && !RD
->lambdaIsDefaultConstructibleAndAssignable() &&
9728 (CSM
== CXXDefaultConstructor
|| CSM
== CXXCopyAssignment
)) {
9730 Diag(RD
->getLocation(), diag::note_lambda_decl
);
9734 // For an anonymous struct or union, the copy and assignment special members
9735 // will never be used, so skip the check. For an anonymous union declared at
9736 // namespace scope, the constructor and destructor are used.
9737 if (CSM
!= CXXDefaultConstructor
&& CSM
!= CXXDestructor
&&
9738 RD
->isAnonymousStructOrUnion())
9741 // C++11 [class.copy]p7, p18:
9742 // If the class definition declares a move constructor or move assignment
9743 // operator, an implicitly declared copy constructor or copy assignment
9744 // operator is defined as deleted.
9745 if (MD
->isImplicit() &&
9746 (CSM
== CXXCopyConstructor
|| CSM
== CXXCopyAssignment
)) {
9747 CXXMethodDecl
*UserDeclaredMove
= nullptr;
9749 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
9750 // deletion of the corresponding copy operation, not both copy operations.
9751 // MSVC 2015 has adopted the standards conforming behavior.
9752 bool DeletesOnlyMatchingCopy
=
9753 getLangOpts().MSVCCompat
&&
9754 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015
);
9756 if (RD
->hasUserDeclaredMoveConstructor() &&
9757 (!DeletesOnlyMatchingCopy
|| CSM
== CXXCopyConstructor
)) {
9758 if (!Diagnose
) return true;
9760 // Find any user-declared move constructor.
9761 for (auto *I
: RD
->ctors()) {
9762 if (I
->isMoveConstructor()) {
9763 UserDeclaredMove
= I
;
9767 assert(UserDeclaredMove
);
9768 } else if (RD
->hasUserDeclaredMoveAssignment() &&
9769 (!DeletesOnlyMatchingCopy
|| CSM
== CXXCopyAssignment
)) {
9770 if (!Diagnose
) return true;
9772 // Find any user-declared move assignment operator.
9773 for (auto *I
: RD
->methods()) {
9774 if (I
->isMoveAssignmentOperator()) {
9775 UserDeclaredMove
= I
;
9779 assert(UserDeclaredMove
);
9782 if (UserDeclaredMove
) {
9783 Diag(UserDeclaredMove
->getLocation(),
9784 diag::note_deleted_copy_user_declared_move
)
9785 << (CSM
== CXXCopyAssignment
) << RD
9786 << UserDeclaredMove
->isMoveAssignmentOperator();
9791 // Do access control from the special member function
9792 ContextRAII
MethodContext(*this, MD
);
9794 // C++11 [class.dtor]p5:
9795 // -- for a virtual destructor, lookup of the non-array deallocation function
9796 // results in an ambiguity or in a function that is deleted or inaccessible
9797 if (CSM
== CXXDestructor
&& MD
->isVirtual()) {
9798 FunctionDecl
*OperatorDelete
= nullptr;
9799 DeclarationName Name
=
9800 Context
.DeclarationNames
.getCXXOperatorName(OO_Delete
);
9801 if (FindDeallocationFunction(MD
->getLocation(), MD
->getParent(), Name
,
9802 OperatorDelete
, /*Diagnose*/false)) {
9804 Diag(RD
->getLocation(), diag::note_deleted_dtor_no_operator_delete
);
9809 SpecialMemberDeletionInfo
SMI(*this, MD
, CSM
, ICI
, Diagnose
);
9811 // Per DR1611, do not consider virtual bases of constructors of abstract
9812 // classes, since we are not going to construct them.
9813 // Per DR1658, do not consider virtual bases of destructors of abstract
9815 // Per DR2180, for assignment operators we only assign (and thus only
9816 // consider) direct bases.
9817 if (SMI
.visit(SMI
.IsAssignment
? SMI
.VisitDirectBases
9818 : SMI
.VisitPotentiallyConstructedBases
))
9821 if (SMI
.shouldDeleteForAllConstMembers())
9824 if (getLangOpts().CUDA
) {
9825 // We should delete the special member in CUDA mode if target inference
9827 // For inherited constructors (non-null ICI), CSM may be passed so that MD
9828 // is treated as certain special member, which may not reflect what special
9829 // member MD really is. However inferCUDATargetForImplicitSpecialMember
9830 // expects CSM to match MD, therefore recalculate CSM.
9831 assert(ICI
|| CSM
== getSpecialMember(MD
));
9834 RealCSM
= getSpecialMember(MD
);
9836 return inferCUDATargetForImplicitSpecialMember(RD
, RealCSM
, MD
,
9837 SMI
.ConstArg
, Diagnose
);
9843 void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl
*FD
) {
9844 DefaultedFunctionKind DFK
= getDefaultedFunctionKind(FD
);
9845 assert(DFK
&& "not a defaultable function");
9846 assert(FD
->isDefaulted() && FD
->isDeleted() && "not defaulted and deleted");
9848 if (DFK
.isSpecialMember()) {
9849 ShouldDeleteSpecialMember(cast
<CXXMethodDecl
>(FD
), DFK
.asSpecialMember(),
9850 nullptr, /*Diagnose=*/true);
9852 DefaultedComparisonAnalyzer(
9853 *this, cast
<CXXRecordDecl
>(FD
->getLexicalDeclContext()), FD
,
9854 DFK
.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted
)
9859 /// Perform lookup for a special member of the specified kind, and determine
9860 /// whether it is trivial. If the triviality can be determined without the
9861 /// lookup, skip it. This is intended for use when determining whether a
9862 /// special member of a containing object is trivial, and thus does not ever
9863 /// perform overload resolution for default constructors.
9865 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
9866 /// member that was most likely to be intended to be trivial, if any.
9868 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
9869 /// determine whether the special member is trivial.
9870 static bool findTrivialSpecialMember(Sema
&S
, CXXRecordDecl
*RD
,
9871 Sema::CXXSpecialMember CSM
, unsigned Quals
,
9873 Sema::TrivialABIHandling TAH
,
9874 CXXMethodDecl
**Selected
) {
9876 *Selected
= nullptr;
9879 case Sema::CXXInvalid
:
9880 llvm_unreachable("not a special member");
9882 case Sema::CXXDefaultConstructor
:
9883 // C++11 [class.ctor]p5:
9884 // A default constructor is trivial if:
9885 // - all the [direct subobjects] have trivial default constructors
9887 // Note, no overload resolution is performed in this case.
9888 if (RD
->hasTrivialDefaultConstructor())
9892 // If there's a default constructor which could have been trivial, dig it
9893 // out. Otherwise, if there's any user-provided default constructor, point
9894 // to that as an example of why there's not a trivial one.
9895 CXXConstructorDecl
*DefCtor
= nullptr;
9896 if (RD
->needsImplicitDefaultConstructor())
9897 S
.DeclareImplicitDefaultConstructor(RD
);
9898 for (auto *CI
: RD
->ctors()) {
9899 if (!CI
->isDefaultConstructor())
9902 if (!DefCtor
->isUserProvided())
9906 *Selected
= DefCtor
;
9911 case Sema::CXXDestructor
:
9912 // C++11 [class.dtor]p5:
9913 // A destructor is trivial if:
9914 // - all the direct [subobjects] have trivial destructors
9915 if (RD
->hasTrivialDestructor() ||
9916 (TAH
== Sema::TAH_ConsiderTrivialABI
&&
9917 RD
->hasTrivialDestructorForCall()))
9921 if (RD
->needsImplicitDestructor())
9922 S
.DeclareImplicitDestructor(RD
);
9923 *Selected
= RD
->getDestructor();
9928 case Sema::CXXCopyConstructor
:
9929 // C++11 [class.copy]p12:
9930 // A copy constructor is trivial if:
9931 // - the constructor selected to copy each direct [subobject] is trivial
9932 if (RD
->hasTrivialCopyConstructor() ||
9933 (TAH
== Sema::TAH_ConsiderTrivialABI
&&
9934 RD
->hasTrivialCopyConstructorForCall())) {
9935 if (Quals
== Qualifiers::Const
)
9936 // We must either select the trivial copy constructor or reach an
9937 // ambiguity; no need to actually perform overload resolution.
9939 } else if (!Selected
) {
9942 // In C++98, we are not supposed to perform overload resolution here, but we
9943 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
9944 // cases like B as having a non-trivial copy constructor:
9945 // struct A { template<typename T> A(T&); };
9946 // struct B { mutable A a; };
9947 goto NeedOverloadResolution
;
9949 case Sema::CXXCopyAssignment
:
9950 // C++11 [class.copy]p25:
9951 // A copy assignment operator is trivial if:
9952 // - the assignment operator selected to copy each direct [subobject] is
9954 if (RD
->hasTrivialCopyAssignment()) {
9955 if (Quals
== Qualifiers::Const
)
9957 } else if (!Selected
) {
9960 // In C++98, we are not supposed to perform overload resolution here, but we
9961 // treat that as a language defect.
9962 goto NeedOverloadResolution
;
9964 case Sema::CXXMoveConstructor
:
9965 case Sema::CXXMoveAssignment
:
9966 NeedOverloadResolution
:
9967 Sema::SpecialMemberOverloadResult SMOR
=
9968 lookupCallFromSpecialMember(S
, RD
, CSM
, Quals
, ConstRHS
);
9970 // The standard doesn't describe how to behave if the lookup is ambiguous.
9971 // We treat it as not making the member non-trivial, just like the standard
9972 // mandates for the default constructor. This should rarely matter, because
9973 // the member will also be deleted.
9974 if (SMOR
.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous
)
9977 if (!SMOR
.getMethod()) {
9978 assert(SMOR
.getKind() ==
9979 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted
);
9983 // We deliberately don't check if we found a deleted special member. We're
9986 *Selected
= SMOR
.getMethod();
9988 if (TAH
== Sema::TAH_ConsiderTrivialABI
&&
9989 (CSM
== Sema::CXXCopyConstructor
|| CSM
== Sema::CXXMoveConstructor
))
9990 return SMOR
.getMethod()->isTrivialForCall();
9991 return SMOR
.getMethod()->isTrivial();
9994 llvm_unreachable("unknown special method kind");
9997 static CXXConstructorDecl
*findUserDeclaredCtor(CXXRecordDecl
*RD
) {
9998 for (auto *CI
: RD
->ctors())
9999 if (!CI
->isImplicit())
10002 // Look for constructor templates.
10003 typedef CXXRecordDecl::specific_decl_iterator
<FunctionTemplateDecl
> tmpl_iter
;
10004 for (tmpl_iter
TI(RD
->decls_begin()), TE(RD
->decls_end()); TI
!= TE
; ++TI
) {
10005 if (CXXConstructorDecl
*CD
=
10006 dyn_cast
<CXXConstructorDecl
>(TI
->getTemplatedDecl()))
10013 /// The kind of subobject we are checking for triviality. The values of this
10014 /// enumeration are used in diagnostics.
10015 enum TrivialSubobjectKind
{
10016 /// The subobject is a base class.
10018 /// The subobject is a non-static data member.
10020 /// The object is actually the complete object.
10024 /// Check whether the special member selected for a given type would be trivial.
10025 static bool checkTrivialSubobjectCall(Sema
&S
, SourceLocation SubobjLoc
,
10026 QualType SubType
, bool ConstRHS
,
10027 Sema::CXXSpecialMember CSM
,
10028 TrivialSubobjectKind Kind
,
10029 Sema::TrivialABIHandling TAH
, bool Diagnose
) {
10030 CXXRecordDecl
*SubRD
= SubType
->getAsCXXRecordDecl();
10034 CXXMethodDecl
*Selected
;
10035 if (findTrivialSpecialMember(S
, SubRD
, CSM
, SubType
.getCVRQualifiers(),
10036 ConstRHS
, TAH
, Diagnose
? &Selected
: nullptr))
10041 SubType
.addConst();
10043 if (!Selected
&& CSM
== Sema::CXXDefaultConstructor
) {
10044 S
.Diag(SubobjLoc
, diag::note_nontrivial_no_def_ctor
)
10045 << Kind
<< SubType
.getUnqualifiedType();
10046 if (CXXConstructorDecl
*CD
= findUserDeclaredCtor(SubRD
))
10047 S
.Diag(CD
->getLocation(), diag::note_user_declared_ctor
);
10048 } else if (!Selected
)
10049 S
.Diag(SubobjLoc
, diag::note_nontrivial_no_copy
)
10050 << Kind
<< SubType
.getUnqualifiedType() << CSM
<< SubType
;
10051 else if (Selected
->isUserProvided()) {
10052 if (Kind
== TSK_CompleteObject
)
10053 S
.Diag(Selected
->getLocation(), diag::note_nontrivial_user_provided
)
10054 << Kind
<< SubType
.getUnqualifiedType() << CSM
;
10056 S
.Diag(SubobjLoc
, diag::note_nontrivial_user_provided
)
10057 << Kind
<< SubType
.getUnqualifiedType() << CSM
;
10058 S
.Diag(Selected
->getLocation(), diag::note_declared_at
);
10061 if (Kind
!= TSK_CompleteObject
)
10062 S
.Diag(SubobjLoc
, diag::note_nontrivial_subobject
)
10063 << Kind
<< SubType
.getUnqualifiedType() << CSM
;
10065 // Explain why the defaulted or deleted special member isn't trivial.
10066 S
.SpecialMemberIsTrivial(Selected
, CSM
, Sema::TAH_IgnoreTrivialABI
,
10074 /// Check whether the members of a class type allow a special member to be
10076 static bool checkTrivialClassMembers(Sema
&S
, CXXRecordDecl
*RD
,
10077 Sema::CXXSpecialMember CSM
,
10079 Sema::TrivialABIHandling TAH
,
10081 for (const auto *FI
: RD
->fields()) {
10082 if (FI
->isInvalidDecl() || FI
->isUnnamedBitfield())
10085 QualType FieldType
= S
.Context
.getBaseElementType(FI
->getType());
10087 // Pretend anonymous struct or union members are members of this class.
10088 if (FI
->isAnonymousStructOrUnion()) {
10089 if (!checkTrivialClassMembers(S
, FieldType
->getAsCXXRecordDecl(),
10090 CSM
, ConstArg
, TAH
, Diagnose
))
10095 // C++11 [class.ctor]p5:
10096 // A default constructor is trivial if [...]
10097 // -- no non-static data member of its class has a
10098 // brace-or-equal-initializer
10099 if (CSM
== Sema::CXXDefaultConstructor
&& FI
->hasInClassInitializer()) {
10101 S
.Diag(FI
->getLocation(), diag::note_nontrivial_default_member_init
)
10106 // Objective C ARC 4.3.5:
10107 // [...] nontrivally ownership-qualified types are [...] not trivially
10108 // default constructible, copy constructible, move constructible, copy
10109 // assignable, move assignable, or destructible [...]
10110 if (FieldType
.hasNonTrivialObjCLifetime()) {
10112 S
.Diag(FI
->getLocation(), diag::note_nontrivial_objc_ownership
)
10113 << RD
<< FieldType
.getObjCLifetime();
10117 bool ConstRHS
= ConstArg
&& !FI
->isMutable();
10118 if (!checkTrivialSubobjectCall(S
, FI
->getLocation(), FieldType
, ConstRHS
,
10119 CSM
, TSK_Field
, TAH
, Diagnose
))
10126 /// Diagnose why the specified class does not have a trivial special member of
10127 /// the given kind.
10128 void Sema::DiagnoseNontrivial(const CXXRecordDecl
*RD
, CXXSpecialMember CSM
) {
10129 QualType Ty
= Context
.getRecordType(RD
);
10131 bool ConstArg
= (CSM
== CXXCopyConstructor
|| CSM
== CXXCopyAssignment
);
10132 checkTrivialSubobjectCall(*this, RD
->getLocation(), Ty
, ConstArg
, CSM
,
10133 TSK_CompleteObject
, TAH_IgnoreTrivialABI
,
10137 /// Determine whether a defaulted or deleted special member function is trivial,
10138 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
10139 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
10140 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl
*MD
, CXXSpecialMember CSM
,
10141 TrivialABIHandling TAH
, bool Diagnose
) {
10142 assert(!MD
->isUserProvided() && CSM
!= CXXInvalid
&& "not special enough");
10144 CXXRecordDecl
*RD
= MD
->getParent();
10146 bool ConstArg
= false;
10148 // C++11 [class.copy]p12, p25: [DR1593]
10149 // A [special member] is trivial if [...] its parameter-type-list is
10150 // equivalent to the parameter-type-list of an implicit declaration [...]
10152 case CXXDefaultConstructor
:
10153 case CXXDestructor
:
10154 // Trivial default constructors and destructors cannot have parameters.
10157 case CXXCopyConstructor
:
10158 case CXXCopyAssignment
: {
10159 const ParmVarDecl
*Param0
= MD
->getNonObjectParameter(0);
10160 const ReferenceType
*RT
= Param0
->getType()->getAs
<ReferenceType
>();
10162 // When ClangABICompat14 is true, CXX copy constructors will only be trivial
10163 // if they are not user-provided and their parameter-type-list is equivalent
10164 // to the parameter-type-list of an implicit declaration. This maintains the
10165 // behavior before dr2171 was implemented.
10167 // Otherwise, if ClangABICompat14 is false, All copy constructors can be
10168 // trivial, if they are not user-provided, regardless of the qualifiers on
10169 // the reference type.
10170 const bool ClangABICompat14
= Context
.getLangOpts().getClangABICompat() <=
10171 LangOptions::ClangABI::Ver14
;
10173 ((RT
->getPointeeType().getCVRQualifiers() != Qualifiers::Const
) &&
10174 ClangABICompat14
)) {
10176 Diag(Param0
->getLocation(), diag::note_nontrivial_param_type
)
10177 << Param0
->getSourceRange() << Param0
->getType()
10178 << Context
.getLValueReferenceType(
10179 Context
.getRecordType(RD
).withConst());
10183 ConstArg
= RT
->getPointeeType().isConstQualified();
10187 case CXXMoveConstructor
:
10188 case CXXMoveAssignment
: {
10189 // Trivial move operations always have non-cv-qualified parameters.
10190 const ParmVarDecl
*Param0
= MD
->getNonObjectParameter(0);
10191 const RValueReferenceType
*RT
=
10192 Param0
->getType()->getAs
<RValueReferenceType
>();
10193 if (!RT
|| RT
->getPointeeType().getCVRQualifiers()) {
10195 Diag(Param0
->getLocation(), diag::note_nontrivial_param_type
)
10196 << Param0
->getSourceRange() << Param0
->getType()
10197 << Context
.getRValueReferenceType(Context
.getRecordType(RD
));
10204 llvm_unreachable("not a special member");
10207 if (MD
->getMinRequiredArguments() < MD
->getNumParams()) {
10209 Diag(MD
->getParamDecl(MD
->getMinRequiredArguments())->getLocation(),
10210 diag::note_nontrivial_default_arg
)
10211 << MD
->getParamDecl(MD
->getMinRequiredArguments())->getSourceRange();
10214 if (MD
->isVariadic()) {
10216 Diag(MD
->getLocation(), diag::note_nontrivial_variadic
);
10220 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
10221 // A copy/move [constructor or assignment operator] is trivial if
10222 // -- the [member] selected to copy/move each direct base class subobject
10225 // C++11 [class.copy]p12, C++11 [class.copy]p25:
10226 // A [default constructor or destructor] is trivial if
10227 // -- all the direct base classes have trivial [default constructors or
10229 for (const auto &BI
: RD
->bases())
10230 if (!checkTrivialSubobjectCall(*this, BI
.getBeginLoc(), BI
.getType(),
10231 ConstArg
, CSM
, TSK_BaseClass
, TAH
, Diagnose
))
10234 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
10235 // A copy/move [constructor or assignment operator] for a class X is
10237 // -- for each non-static data member of X that is of class type (or array
10238 // thereof), the constructor selected to copy/move that member is
10241 // C++11 [class.copy]p12, C++11 [class.copy]p25:
10242 // A [default constructor or destructor] is trivial if
10243 // -- for all of the non-static data members of its class that are of class
10244 // type (or array thereof), each such class has a trivial [default
10245 // constructor or destructor]
10246 if (!checkTrivialClassMembers(*this, RD
, CSM
, ConstArg
, TAH
, Diagnose
))
10249 // C++11 [class.dtor]p5:
10250 // A destructor is trivial if [...]
10251 // -- the destructor is not virtual
10252 if (CSM
== CXXDestructor
&& MD
->isVirtual()) {
10254 Diag(MD
->getLocation(), diag::note_nontrivial_virtual_dtor
) << RD
;
10258 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
10259 // A [special member] for class X is trivial if [...]
10260 // -- class X has no virtual functions and no virtual base classes
10261 if (CSM
!= CXXDestructor
&& MD
->getParent()->isDynamicClass()) {
10265 if (RD
->getNumVBases()) {
10266 // Check for virtual bases. We already know that the corresponding
10267 // member in all bases is trivial, so vbases must all be direct.
10268 CXXBaseSpecifier
&BS
= *RD
->vbases_begin();
10269 assert(BS
.isVirtual());
10270 Diag(BS
.getBeginLoc(), diag::note_nontrivial_has_virtual
) << RD
<< 1;
10274 // Must have a virtual method.
10275 for (const auto *MI
: RD
->methods()) {
10276 if (MI
->isVirtual()) {
10277 SourceLocation MLoc
= MI
->getBeginLoc();
10278 Diag(MLoc
, diag::note_nontrivial_has_virtual
) << RD
<< 0;
10283 llvm_unreachable("dynamic class with no vbases and no virtual functions");
10286 // Looks like it's trivial!
10291 struct FindHiddenVirtualMethod
{
10293 CXXMethodDecl
*Method
;
10294 llvm::SmallPtrSet
<const CXXMethodDecl
*, 8> OverridenAndUsingBaseMethods
;
10295 SmallVector
<CXXMethodDecl
*, 8> OverloadedMethods
;
10298 /// Check whether any most overridden method from MD in Methods
10299 static bool CheckMostOverridenMethods(
10300 const CXXMethodDecl
*MD
,
10301 const llvm::SmallPtrSetImpl
<const CXXMethodDecl
*> &Methods
) {
10302 if (MD
->size_overridden_methods() == 0)
10303 return Methods
.count(MD
->getCanonicalDecl());
10304 for (const CXXMethodDecl
*O
: MD
->overridden_methods())
10305 if (CheckMostOverridenMethods(O
, Methods
))
10311 /// Member lookup function that determines whether a given C++
10312 /// method overloads virtual methods in a base class without overriding any,
10313 /// to be used with CXXRecordDecl::lookupInBases().
10314 bool operator()(const CXXBaseSpecifier
*Specifier
, CXXBasePath
&Path
) {
10315 RecordDecl
*BaseRecord
=
10316 Specifier
->getType()->castAs
<RecordType
>()->getDecl();
10318 DeclarationName Name
= Method
->getDeclName();
10319 assert(Name
.getNameKind() == DeclarationName::Identifier
);
10321 bool foundSameNameMethod
= false;
10322 SmallVector
<CXXMethodDecl
*, 8> overloadedMethods
;
10323 for (Path
.Decls
= BaseRecord
->lookup(Name
).begin();
10324 Path
.Decls
!= DeclContext::lookup_iterator(); ++Path
.Decls
) {
10325 NamedDecl
*D
= *Path
.Decls
;
10326 if (CXXMethodDecl
*MD
= dyn_cast
<CXXMethodDecl
>(D
)) {
10327 MD
= MD
->getCanonicalDecl();
10328 foundSameNameMethod
= true;
10329 // Interested only in hidden virtual methods.
10330 if (!MD
->isVirtual())
10332 // If the method we are checking overrides a method from its base
10333 // don't warn about the other overloaded methods. Clang deviates from
10334 // GCC by only diagnosing overloads of inherited virtual functions that
10335 // do not override any other virtual functions in the base. GCC's
10336 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
10337 // function from a base class. These cases may be better served by a
10338 // warning (not specific to virtual functions) on call sites when the
10339 // call would select a different function from the base class, were it
10341 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
10342 if (!S
->IsOverload(Method
, MD
, false))
10344 // Collect the overload only if its hidden.
10345 if (!CheckMostOverridenMethods(MD
, OverridenAndUsingBaseMethods
))
10346 overloadedMethods
.push_back(MD
);
10350 if (foundSameNameMethod
)
10351 OverloadedMethods
.append(overloadedMethods
.begin(),
10352 overloadedMethods
.end());
10353 return foundSameNameMethod
;
10356 } // end anonymous namespace
10358 /// Add the most overridden methods from MD to Methods
10359 static void AddMostOverridenMethods(const CXXMethodDecl
*MD
,
10360 llvm::SmallPtrSetImpl
<const CXXMethodDecl
*>& Methods
) {
10361 if (MD
->size_overridden_methods() == 0)
10362 Methods
.insert(MD
->getCanonicalDecl());
10364 for (const CXXMethodDecl
*O
: MD
->overridden_methods())
10365 AddMostOverridenMethods(O
, Methods
);
10368 /// Check if a method overloads virtual methods in a base class without
10369 /// overriding any.
10370 void Sema::FindHiddenVirtualMethods(CXXMethodDecl
*MD
,
10371 SmallVectorImpl
<CXXMethodDecl
*> &OverloadedMethods
) {
10372 if (!MD
->getDeclName().isIdentifier())
10375 CXXBasePaths
Paths(/*FindAmbiguities=*/true, // true to look in all bases.
10376 /*bool RecordPaths=*/false,
10377 /*bool DetectVirtual=*/false);
10378 FindHiddenVirtualMethod FHVM
;
10382 // Keep the base methods that were overridden or introduced in the subclass
10383 // by 'using' in a set. A base method not in this set is hidden.
10384 CXXRecordDecl
*DC
= MD
->getParent();
10385 DeclContext::lookup_result R
= DC
->lookup(MD
->getDeclName());
10386 for (DeclContext::lookup_iterator I
= R
.begin(), E
= R
.end(); I
!= E
; ++I
) {
10387 NamedDecl
*ND
= *I
;
10388 if (UsingShadowDecl
*shad
= dyn_cast
<UsingShadowDecl
>(*I
))
10389 ND
= shad
->getTargetDecl();
10390 if (CXXMethodDecl
*MD
= dyn_cast
<CXXMethodDecl
>(ND
))
10391 AddMostOverridenMethods(MD
, FHVM
.OverridenAndUsingBaseMethods
);
10394 if (DC
->lookupInBases(FHVM
, Paths
))
10395 OverloadedMethods
= FHVM
.OverloadedMethods
;
10398 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl
*MD
,
10399 SmallVectorImpl
<CXXMethodDecl
*> &OverloadedMethods
) {
10400 for (unsigned i
= 0, e
= OverloadedMethods
.size(); i
!= e
; ++i
) {
10401 CXXMethodDecl
*overloadedMD
= OverloadedMethods
[i
];
10402 PartialDiagnostic PD
= PDiag(
10403 diag::note_hidden_overloaded_virtual_declared_here
) << overloadedMD
;
10404 HandleFunctionTypeMismatch(PD
, MD
->getType(), overloadedMD
->getType());
10405 Diag(overloadedMD
->getLocation(), PD
);
10409 /// Diagnose methods which overload virtual methods in a base class
10410 /// without overriding any.
10411 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl
*MD
) {
10412 if (MD
->isInvalidDecl())
10415 if (Diags
.isIgnored(diag::warn_overloaded_virtual
, MD
->getLocation()))
10418 SmallVector
<CXXMethodDecl
*, 8> OverloadedMethods
;
10419 FindHiddenVirtualMethods(MD
, OverloadedMethods
);
10420 if (!OverloadedMethods
.empty()) {
10421 Diag(MD
->getLocation(), diag::warn_overloaded_virtual
)
10422 << MD
<< (OverloadedMethods
.size() > 1);
10424 NoteHiddenVirtualMethods(MD
, OverloadedMethods
);
10428 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl
&RD
) {
10429 auto PrintDiagAndRemoveAttr
= [&](unsigned N
) {
10430 // No diagnostics if this is a template instantiation.
10431 if (!isTemplateInstantiation(RD
.getTemplateSpecializationKind())) {
10432 Diag(RD
.getAttr
<TrivialABIAttr
>()->getLocation(),
10433 diag::ext_cannot_use_trivial_abi
) << &RD
;
10434 Diag(RD
.getAttr
<TrivialABIAttr
>()->getLocation(),
10435 diag::note_cannot_use_trivial_abi_reason
) << &RD
<< N
;
10437 RD
.dropAttr
<TrivialABIAttr
>();
10440 // Ill-formed if the copy and move constructors are deleted.
10441 auto HasNonDeletedCopyOrMoveConstructor
= [&]() {
10442 // If the type is dependent, then assume it might have
10443 // implicit copy or move ctor because we won't know yet at this point.
10444 if (RD
.isDependentType())
10446 if (RD
.needsImplicitCopyConstructor() &&
10447 !RD
.defaultedCopyConstructorIsDeleted())
10449 if (RD
.needsImplicitMoveConstructor() &&
10450 !RD
.defaultedMoveConstructorIsDeleted())
10452 for (const CXXConstructorDecl
*CD
: RD
.ctors())
10453 if (CD
->isCopyOrMoveConstructor() && !CD
->isDeleted())
10458 if (!HasNonDeletedCopyOrMoveConstructor()) {
10459 PrintDiagAndRemoveAttr(0);
10463 // Ill-formed if the struct has virtual functions.
10464 if (RD
.isPolymorphic()) {
10465 PrintDiagAndRemoveAttr(1);
10469 for (const auto &B
: RD
.bases()) {
10470 // Ill-formed if the base class is non-trivial for the purpose of calls or a
10472 if (!B
.getType()->isDependentType() &&
10473 !B
.getType()->getAsCXXRecordDecl()->canPassInRegisters()) {
10474 PrintDiagAndRemoveAttr(2);
10478 if (B
.isVirtual()) {
10479 PrintDiagAndRemoveAttr(3);
10484 for (const auto *FD
: RD
.fields()) {
10485 // Ill-formed if the field is an ObjectiveC pointer or of a type that is
10486 // non-trivial for the purpose of calls.
10487 QualType FT
= FD
->getType();
10488 if (FT
.getObjCLifetime() == Qualifiers::OCL_Weak
) {
10489 PrintDiagAndRemoveAttr(4);
10493 if (const auto *RT
= FT
->getBaseElementTypeUnsafe()->getAs
<RecordType
>())
10494 if (!RT
->isDependentType() &&
10495 !cast
<CXXRecordDecl
>(RT
->getDecl())->canPassInRegisters()) {
10496 PrintDiagAndRemoveAttr(5);
10502 void Sema::ActOnFinishCXXMemberSpecification(
10503 Scope
*S
, SourceLocation RLoc
, Decl
*TagDecl
, SourceLocation LBrac
,
10504 SourceLocation RBrac
, const ParsedAttributesView
&AttrList
) {
10508 AdjustDeclIfTemplate(TagDecl
);
10510 for (const ParsedAttr
&AL
: AttrList
) {
10511 if (AL
.getKind() != ParsedAttr::AT_Visibility
)
10514 Diag(AL
.getLoc(), diag::warn_attribute_after_definition_ignored
) << AL
;
10517 ActOnFields(S
, RLoc
, TagDecl
,
10519 // strict aliasing violation!
10520 reinterpret_cast<Decl
**>(FieldCollector
->getCurFields()),
10521 FieldCollector
->getCurNumFields()),
10522 LBrac
, RBrac
, AttrList
);
10524 CheckCompletedCXXClass(S
, cast
<CXXRecordDecl
>(TagDecl
));
10527 /// Find the equality comparison functions that should be implicitly declared
10528 /// in a given class definition, per C++2a [class.compare.default]p3.
10529 static void findImplicitlyDeclaredEqualityComparisons(
10530 ASTContext
&Ctx
, CXXRecordDecl
*RD
,
10531 llvm::SmallVectorImpl
<FunctionDecl
*> &Spaceships
) {
10532 DeclarationName EqEq
= Ctx
.DeclarationNames
.getCXXOperatorName(OO_EqualEqual
);
10533 if (!RD
->lookup(EqEq
).empty())
10534 // Member operator== explicitly declared: no implicit operator==s.
10537 // Traverse friends looking for an '==' or a '<=>'.
10538 for (FriendDecl
*Friend
: RD
->friends()) {
10539 FunctionDecl
*FD
= dyn_cast_or_null
<FunctionDecl
>(Friend
->getFriendDecl());
10542 if (FD
->getOverloadedOperator() == OO_EqualEqual
) {
10543 // Friend operator== explicitly declared: no implicit operator==s.
10544 Spaceships
.clear();
10548 if (FD
->getOverloadedOperator() == OO_Spaceship
&&
10549 FD
->isExplicitlyDefaulted())
10550 Spaceships
.push_back(FD
);
10553 // Look for members named 'operator<=>'.
10554 DeclarationName Cmp
= Ctx
.DeclarationNames
.getCXXOperatorName(OO_Spaceship
);
10555 for (NamedDecl
*ND
: RD
->lookup(Cmp
)) {
10556 // Note that we could find a non-function here (either a function template
10557 // or a using-declaration). Neither case results in an implicit
10559 if (auto *FD
= dyn_cast
<FunctionDecl
>(ND
))
10560 if (FD
->isExplicitlyDefaulted())
10561 Spaceships
.push_back(FD
);
10565 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
10566 /// special functions, such as the default constructor, copy
10567 /// constructor, or destructor, to the given C++ class (C++
10568 /// [special]p1). This routine can only be executed just before the
10569 /// definition of the class is complete.
10570 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl
*ClassDecl
) {
10571 // Don't add implicit special members to templated classes.
10572 // FIXME: This means unqualified lookups for 'operator=' within a class
10573 // template don't work properly.
10574 if (!ClassDecl
->isDependentType()) {
10575 if (ClassDecl
->needsImplicitDefaultConstructor()) {
10576 ++getASTContext().NumImplicitDefaultConstructors
;
10578 if (ClassDecl
->hasInheritedConstructor())
10579 DeclareImplicitDefaultConstructor(ClassDecl
);
10582 if (ClassDecl
->needsImplicitCopyConstructor()) {
10583 ++getASTContext().NumImplicitCopyConstructors
;
10585 // If the properties or semantics of the copy constructor couldn't be
10586 // determined while the class was being declared, force a declaration
10588 if (ClassDecl
->needsOverloadResolutionForCopyConstructor() ||
10589 ClassDecl
->hasInheritedConstructor())
10590 DeclareImplicitCopyConstructor(ClassDecl
);
10591 // For the MS ABI we need to know whether the copy ctor is deleted. A
10592 // prerequisite for deleting the implicit copy ctor is that the class has
10593 // a move ctor or move assignment that is either user-declared or whose
10594 // semantics are inherited from a subobject. FIXME: We should provide a
10595 // more direct way for CodeGen to ask whether the constructor was deleted.
10596 else if (Context
.getTargetInfo().getCXXABI().isMicrosoft() &&
10597 (ClassDecl
->hasUserDeclaredMoveConstructor() ||
10598 ClassDecl
->needsOverloadResolutionForMoveConstructor() ||
10599 ClassDecl
->hasUserDeclaredMoveAssignment() ||
10600 ClassDecl
->needsOverloadResolutionForMoveAssignment()))
10601 DeclareImplicitCopyConstructor(ClassDecl
);
10604 if (getLangOpts().CPlusPlus11
&&
10605 ClassDecl
->needsImplicitMoveConstructor()) {
10606 ++getASTContext().NumImplicitMoveConstructors
;
10608 if (ClassDecl
->needsOverloadResolutionForMoveConstructor() ||
10609 ClassDecl
->hasInheritedConstructor())
10610 DeclareImplicitMoveConstructor(ClassDecl
);
10613 if (ClassDecl
->needsImplicitCopyAssignment()) {
10614 ++getASTContext().NumImplicitCopyAssignmentOperators
;
10616 // If we have a dynamic class, then the copy assignment operator may be
10617 // virtual, so we have to declare it immediately. This ensures that, e.g.,
10618 // it shows up in the right place in the vtable and that we diagnose
10619 // problems with the implicit exception specification.
10620 if (ClassDecl
->isDynamicClass() ||
10621 ClassDecl
->needsOverloadResolutionForCopyAssignment() ||
10622 ClassDecl
->hasInheritedAssignment())
10623 DeclareImplicitCopyAssignment(ClassDecl
);
10626 if (getLangOpts().CPlusPlus11
&& ClassDecl
->needsImplicitMoveAssignment()) {
10627 ++getASTContext().NumImplicitMoveAssignmentOperators
;
10629 // Likewise for the move assignment operator.
10630 if (ClassDecl
->isDynamicClass() ||
10631 ClassDecl
->needsOverloadResolutionForMoveAssignment() ||
10632 ClassDecl
->hasInheritedAssignment())
10633 DeclareImplicitMoveAssignment(ClassDecl
);
10636 if (ClassDecl
->needsImplicitDestructor()) {
10637 ++getASTContext().NumImplicitDestructors
;
10639 // If we have a dynamic class, then the destructor may be virtual, so we
10640 // have to declare the destructor immediately. This ensures that, e.g., it
10641 // shows up in the right place in the vtable and that we diagnose problems
10642 // with the implicit exception specification.
10643 if (ClassDecl
->isDynamicClass() ||
10644 ClassDecl
->needsOverloadResolutionForDestructor())
10645 DeclareImplicitDestructor(ClassDecl
);
10649 // C++2a [class.compare.default]p3:
10650 // If the member-specification does not explicitly declare any member or
10651 // friend named operator==, an == operator function is declared implicitly
10652 // for each defaulted three-way comparison operator function defined in
10653 // the member-specification
10654 // FIXME: Consider doing this lazily.
10655 // We do this during the initial parse for a class template, not during
10656 // instantiation, so that we can handle unqualified lookups for 'operator=='
10657 // when parsing the template.
10658 if (getLangOpts().CPlusPlus20
&& !inTemplateInstantiation()) {
10659 llvm::SmallVector
<FunctionDecl
*, 4> DefaultedSpaceships
;
10660 findImplicitlyDeclaredEqualityComparisons(Context
, ClassDecl
,
10661 DefaultedSpaceships
);
10662 for (auto *FD
: DefaultedSpaceships
)
10663 DeclareImplicitEqualityComparison(ClassDecl
, FD
);
10668 Sema::ActOnReenterTemplateScope(Decl
*D
,
10669 llvm::function_ref
<Scope
*()> EnterScope
) {
10672 AdjustDeclIfTemplate(D
);
10674 // In order to get name lookup right, reenter template scopes in order from
10675 // outermost to innermost.
10676 SmallVector
<TemplateParameterList
*, 4> ParameterLists
;
10677 DeclContext
*LookupDC
= dyn_cast
<DeclContext
>(D
);
10679 if (DeclaratorDecl
*DD
= dyn_cast
<DeclaratorDecl
>(D
)) {
10680 for (unsigned i
= 0; i
< DD
->getNumTemplateParameterLists(); ++i
)
10681 ParameterLists
.push_back(DD
->getTemplateParameterList(i
));
10683 if (FunctionDecl
*FD
= dyn_cast
<FunctionDecl
>(D
)) {
10684 if (FunctionTemplateDecl
*FTD
= FD
->getDescribedFunctionTemplate())
10685 ParameterLists
.push_back(FTD
->getTemplateParameters());
10686 } else if (VarDecl
*VD
= dyn_cast
<VarDecl
>(D
)) {
10687 LookupDC
= VD
->getDeclContext();
10689 if (VarTemplateDecl
*VTD
= VD
->getDescribedVarTemplate())
10690 ParameterLists
.push_back(VTD
->getTemplateParameters());
10691 else if (auto *PSD
= dyn_cast
<VarTemplatePartialSpecializationDecl
>(D
))
10692 ParameterLists
.push_back(PSD
->getTemplateParameters());
10694 } else if (TagDecl
*TD
= dyn_cast
<TagDecl
>(D
)) {
10695 for (unsigned i
= 0; i
< TD
->getNumTemplateParameterLists(); ++i
)
10696 ParameterLists
.push_back(TD
->getTemplateParameterList(i
));
10698 if (CXXRecordDecl
*RD
= dyn_cast
<CXXRecordDecl
>(TD
)) {
10699 if (ClassTemplateDecl
*CTD
= RD
->getDescribedClassTemplate())
10700 ParameterLists
.push_back(CTD
->getTemplateParameters());
10701 else if (auto *PSD
= dyn_cast
<ClassTemplatePartialSpecializationDecl
>(D
))
10702 ParameterLists
.push_back(PSD
->getTemplateParameters());
10705 // FIXME: Alias declarations and concepts.
10707 unsigned Count
= 0;
10708 Scope
*InnermostTemplateScope
= nullptr;
10709 for (TemplateParameterList
*Params
: ParameterLists
) {
10710 // Ignore explicit specializations; they don't contribute to the template
10712 if (Params
->size() == 0)
10715 InnermostTemplateScope
= EnterScope();
10716 for (NamedDecl
*Param
: *Params
) {
10717 if (Param
->getDeclName()) {
10718 InnermostTemplateScope
->AddDecl(Param
);
10719 IdResolver
.AddDecl(Param
);
10725 // Associate the new template scopes with the corresponding entities.
10726 if (InnermostTemplateScope
) {
10727 assert(LookupDC
&& "no enclosing DeclContext for template lookup");
10728 EnterTemplatedContext(InnermostTemplateScope
, LookupDC
);
10734 void Sema::ActOnStartDelayedMemberDeclarations(Scope
*S
, Decl
*RecordD
) {
10735 if (!RecordD
) return;
10736 AdjustDeclIfTemplate(RecordD
);
10737 CXXRecordDecl
*Record
= cast
<CXXRecordDecl
>(RecordD
);
10738 PushDeclContext(S
, Record
);
10741 void Sema::ActOnFinishDelayedMemberDeclarations(Scope
*S
, Decl
*RecordD
) {
10742 if (!RecordD
) return;
10746 /// This is used to implement the constant expression evaluation part of the
10747 /// attribute enable_if extension. There is nothing in standard C++ which would
10748 /// require reentering parameters.
10749 void Sema::ActOnReenterCXXMethodParameter(Scope
*S
, ParmVarDecl
*Param
) {
10754 if (Param
->getDeclName())
10755 IdResolver
.AddDecl(Param
);
10758 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
10759 /// parsing a top-level (non-nested) C++ class, and we are now
10760 /// parsing those parts of the given Method declaration that could
10761 /// not be parsed earlier (C++ [class.mem]p2), such as default
10762 /// arguments. This action should enter the scope of the given
10763 /// Method declaration as if we had just parsed the qualified method
10764 /// name. However, it should not bring the parameters into scope;
10765 /// that will be performed by ActOnDelayedCXXMethodParameter.
10766 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope
*S
, Decl
*MethodD
) {
10769 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
10770 /// C++ method declaration. We're (re-)introducing the given
10771 /// function parameter into scope for use in parsing later parts of
10772 /// the method declaration. For example, we could see an
10773 /// ActOnParamDefaultArgument event for this parameter.
10774 void Sema::ActOnDelayedCXXMethodParameter(Scope
*S
, Decl
*ParamD
) {
10778 ParmVarDecl
*Param
= cast
<ParmVarDecl
>(ParamD
);
10781 if (Param
->getDeclName())
10782 IdResolver
.AddDecl(Param
);
10785 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
10786 /// processing the delayed method declaration for Method. The method
10787 /// declaration is now considered finished. There may be a separate
10788 /// ActOnStartOfFunctionDef action later (not necessarily
10789 /// immediately!) for this method, if it was also defined inside the
10791 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope
*S
, Decl
*MethodD
) {
10795 AdjustDeclIfTemplate(MethodD
);
10797 FunctionDecl
*Method
= cast
<FunctionDecl
>(MethodD
);
10799 // Now that we have our default arguments, check the constructor
10800 // again. It could produce additional diagnostics or affect whether
10801 // the class has implicitly-declared destructors, among other
10803 if (CXXConstructorDecl
*Constructor
= dyn_cast
<CXXConstructorDecl
>(Method
))
10804 CheckConstructor(Constructor
);
10806 // Check the default arguments, which we may have added.
10807 if (!Method
->isInvalidDecl())
10808 CheckCXXDefaultArguments(Method
);
10811 // Emit the given diagnostic for each non-address-space qualifier.
10812 // Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
10813 static void checkMethodTypeQualifiers(Sema
&S
, Declarator
&D
, unsigned DiagID
) {
10814 const DeclaratorChunk::FunctionTypeInfo
&FTI
= D
.getFunctionTypeInfo();
10815 if (FTI
.hasMethodTypeQualifiers() && !D
.isInvalidType()) {
10816 bool DiagOccured
= false;
10817 FTI
.MethodQualifiers
->forEachQualifier(
10818 [DiagID
, &S
, &DiagOccured
](DeclSpec::TQ
, StringRef QualName
,
10819 SourceLocation SL
) {
10820 // This diagnostic should be emitted on any qualifier except an addr
10821 // space qualifier. However, forEachQualifier currently doesn't visit
10822 // addr space qualifiers, so there's no way to write this condition
10823 // right now; we just diagnose on everything.
10824 S
.Diag(SL
, DiagID
) << QualName
<< SourceRange(SL
);
10825 DiagOccured
= true;
10828 D
.setInvalidType();
10832 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
10833 /// the well-formedness of the constructor declarator @p D with type @p
10834 /// R. If there are any errors in the declarator, this routine will
10835 /// emit diagnostics and set the invalid bit to true. In any case, the type
10836 /// will be updated to reflect a well-formed type for the constructor and
10838 QualType
Sema::CheckConstructorDeclarator(Declarator
&D
, QualType R
,
10839 StorageClass
&SC
) {
10840 bool isVirtual
= D
.getDeclSpec().isVirtualSpecified();
10842 // C++ [class.ctor]p3:
10843 // A constructor shall not be virtual (10.3) or static (9.4). A
10844 // constructor can be invoked for a const, volatile or const
10845 // volatile object. A constructor shall not be declared const,
10846 // volatile, or const volatile (9.3.2).
10848 if (!D
.isInvalidType())
10849 Diag(D
.getIdentifierLoc(), diag::err_constructor_cannot_be
)
10850 << "virtual" << SourceRange(D
.getDeclSpec().getVirtualSpecLoc())
10851 << SourceRange(D
.getIdentifierLoc());
10852 D
.setInvalidType();
10854 if (SC
== SC_Static
) {
10855 if (!D
.isInvalidType())
10856 Diag(D
.getIdentifierLoc(), diag::err_constructor_cannot_be
)
10857 << "static" << SourceRange(D
.getDeclSpec().getStorageClassSpecLoc())
10858 << SourceRange(D
.getIdentifierLoc());
10859 D
.setInvalidType();
10863 if (unsigned TypeQuals
= D
.getDeclSpec().getTypeQualifiers()) {
10864 diagnoseIgnoredQualifiers(
10865 diag::err_constructor_return_type
, TypeQuals
, SourceLocation(),
10866 D
.getDeclSpec().getConstSpecLoc(), D
.getDeclSpec().getVolatileSpecLoc(),
10867 D
.getDeclSpec().getRestrictSpecLoc(),
10868 D
.getDeclSpec().getAtomicSpecLoc());
10869 D
.setInvalidType();
10872 checkMethodTypeQualifiers(*this, D
, diag::err_invalid_qualified_constructor
);
10874 // C++0x [class.ctor]p4:
10875 // A constructor shall not be declared with a ref-qualifier.
10876 DeclaratorChunk::FunctionTypeInfo
&FTI
= D
.getFunctionTypeInfo();
10877 if (FTI
.hasRefQualifier()) {
10878 Diag(FTI
.getRefQualifierLoc(), diag::err_ref_qualifier_constructor
)
10879 << FTI
.RefQualifierIsLValueRef
10880 << FixItHint::CreateRemoval(FTI
.getRefQualifierLoc());
10881 D
.setInvalidType();
10884 // Rebuild the function type "R" without any type qualifiers (in
10885 // case any of the errors above fired) and with "void" as the
10886 // return type, since constructors don't have return types.
10887 const FunctionProtoType
*Proto
= R
->castAs
<FunctionProtoType
>();
10888 if (Proto
->getReturnType() == Context
.VoidTy
&& !D
.isInvalidType())
10891 FunctionProtoType::ExtProtoInfo EPI
= Proto
->getExtProtoInfo();
10892 EPI
.TypeQuals
= Qualifiers();
10893 EPI
.RefQualifier
= RQ_None
;
10895 return Context
.getFunctionType(Context
.VoidTy
, Proto
->getParamTypes(), EPI
);
10898 /// CheckConstructor - Checks a fully-formed constructor for
10899 /// well-formedness, issuing any diagnostics required. Returns true if
10900 /// the constructor declarator is invalid.
10901 void Sema::CheckConstructor(CXXConstructorDecl
*Constructor
) {
10902 CXXRecordDecl
*ClassDecl
10903 = dyn_cast
<CXXRecordDecl
>(Constructor
->getDeclContext());
10905 return Constructor
->setInvalidDecl();
10907 // C++ [class.copy]p3:
10908 // A declaration of a constructor for a class X is ill-formed if
10909 // its first parameter is of type (optionally cv-qualified) X and
10910 // either there are no other parameters or else all other
10911 // parameters have default arguments.
10912 if (!Constructor
->isInvalidDecl() &&
10913 Constructor
->hasOneParamOrDefaultArgs() &&
10914 Constructor
->getTemplateSpecializationKind() !=
10915 TSK_ImplicitInstantiation
) {
10916 QualType ParamType
= Constructor
->getParamDecl(0)->getType();
10917 QualType ClassTy
= Context
.getTagDeclType(ClassDecl
);
10918 if (Context
.getCanonicalType(ParamType
).getUnqualifiedType() == ClassTy
) {
10919 SourceLocation ParamLoc
= Constructor
->getParamDecl(0)->getLocation();
10920 const char *ConstRef
10921 = Constructor
->getParamDecl(0)->getIdentifier() ? "const &"
10923 Diag(ParamLoc
, diag::err_constructor_byvalue_arg
)
10924 << FixItHint::CreateInsertion(ParamLoc
, ConstRef
);
10926 // FIXME: Rather that making the constructor invalid, we should endeavor
10927 // to fix the type.
10928 Constructor
->setInvalidDecl();
10933 /// CheckDestructor - Checks a fully-formed destructor definition for
10934 /// well-formedness, issuing any diagnostics required. Returns true
10936 bool Sema::CheckDestructor(CXXDestructorDecl
*Destructor
) {
10937 CXXRecordDecl
*RD
= Destructor
->getParent();
10939 if (!Destructor
->getOperatorDelete() && Destructor
->isVirtual()) {
10940 SourceLocation Loc
;
10942 if (!Destructor
->isImplicit())
10943 Loc
= Destructor
->getLocation();
10945 Loc
= RD
->getLocation();
10947 // If we have a virtual destructor, look up the deallocation function
10948 if (FunctionDecl
*OperatorDelete
=
10949 FindDeallocationFunctionForDestructor(Loc
, RD
)) {
10950 Expr
*ThisArg
= nullptr;
10952 // If the notional 'delete this' expression requires a non-trivial
10953 // conversion from 'this' to the type of a destroying operator delete's
10954 // first parameter, perform that conversion now.
10955 if (OperatorDelete
->isDestroyingOperatorDelete()) {
10956 QualType ParamType
= OperatorDelete
->getParamDecl(0)->getType();
10957 if (!declaresSameEntity(ParamType
->getAsCXXRecordDecl(), RD
)) {
10958 // C++ [class.dtor]p13:
10959 // ... as if for the expression 'delete this' appearing in a
10960 // non-virtual destructor of the destructor's class.
10961 ContextRAII
SwitchContext(*this, Destructor
);
10963 ActOnCXXThis(OperatorDelete
->getParamDecl(0)->getLocation());
10964 assert(!This
.isInvalid() && "couldn't form 'this' expr in dtor?");
10965 This
= PerformImplicitConversion(This
.get(), ParamType
, AA_Passing
);
10966 if (This
.isInvalid()) {
10967 // FIXME: Register this as a context note so that it comes out
10968 // in the right order.
10969 Diag(Loc
, diag::note_implicit_delete_this_in_destructor_here
);
10972 ThisArg
= This
.get();
10976 DiagnoseUseOfDecl(OperatorDelete
, Loc
);
10977 MarkFunctionReferenced(Loc
, OperatorDelete
);
10978 Destructor
->setOperatorDelete(OperatorDelete
, ThisArg
);
10985 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
10986 /// the well-formednes of the destructor declarator @p D with type @p
10987 /// R. If there are any errors in the declarator, this routine will
10988 /// emit diagnostics and set the declarator to invalid. Even if this happens,
10989 /// will be updated to reflect a well-formed type for the destructor and
10991 QualType
Sema::CheckDestructorDeclarator(Declarator
&D
, QualType R
,
10992 StorageClass
& SC
) {
10993 // C++ [class.dtor]p1:
10994 // [...] A typedef-name that names a class is a class-name
10995 // (7.1.3); however, a typedef-name that names a class shall not
10996 // be used as the identifier in the declarator for a destructor
10998 QualType DeclaratorType
= GetTypeFromParser(D
.getName().DestructorName
);
10999 if (const TypedefType
*TT
= DeclaratorType
->getAs
<TypedefType
>())
11000 Diag(D
.getIdentifierLoc(), diag::ext_destructor_typedef_name
)
11001 << DeclaratorType
<< isa
<TypeAliasDecl
>(TT
->getDecl());
11002 else if (const TemplateSpecializationType
*TST
=
11003 DeclaratorType
->getAs
<TemplateSpecializationType
>())
11004 if (TST
->isTypeAlias())
11005 Diag(D
.getIdentifierLoc(), diag::ext_destructor_typedef_name
)
11006 << DeclaratorType
<< 1;
11008 // C++ [class.dtor]p2:
11009 // A destructor is used to destroy objects of its class type. A
11010 // destructor takes no parameters, and no return type can be
11011 // specified for it (not even void). The address of a destructor
11012 // shall not be taken. A destructor shall not be static. A
11013 // destructor can be invoked for a const, volatile or const
11014 // volatile object. A destructor shall not be declared const,
11015 // volatile or const volatile (9.3.2).
11016 if (SC
== SC_Static
) {
11017 if (!D
.isInvalidType())
11018 Diag(D
.getIdentifierLoc(), diag::err_destructor_cannot_be
)
11019 << "static" << SourceRange(D
.getDeclSpec().getStorageClassSpecLoc())
11020 << SourceRange(D
.getIdentifierLoc())
11021 << FixItHint::CreateRemoval(D
.getDeclSpec().getStorageClassSpecLoc());
11025 if (!D
.isInvalidType()) {
11026 // Destructors don't have return types, but the parser will
11027 // happily parse something like:
11033 // The return type will be eliminated later.
11034 if (D
.getDeclSpec().hasTypeSpecifier())
11035 Diag(D
.getIdentifierLoc(), diag::err_destructor_return_type
)
11036 << SourceRange(D
.getDeclSpec().getTypeSpecTypeLoc())
11037 << SourceRange(D
.getIdentifierLoc());
11038 else if (unsigned TypeQuals
= D
.getDeclSpec().getTypeQualifiers()) {
11039 diagnoseIgnoredQualifiers(diag::err_destructor_return_type
, TypeQuals
,
11041 D
.getDeclSpec().getConstSpecLoc(),
11042 D
.getDeclSpec().getVolatileSpecLoc(),
11043 D
.getDeclSpec().getRestrictSpecLoc(),
11044 D
.getDeclSpec().getAtomicSpecLoc());
11045 D
.setInvalidType();
11049 checkMethodTypeQualifiers(*this, D
, diag::err_invalid_qualified_destructor
);
11051 // C++0x [class.dtor]p2:
11052 // A destructor shall not be declared with a ref-qualifier.
11053 DeclaratorChunk::FunctionTypeInfo
&FTI
= D
.getFunctionTypeInfo();
11054 if (FTI
.hasRefQualifier()) {
11055 Diag(FTI
.getRefQualifierLoc(), diag::err_ref_qualifier_destructor
)
11056 << FTI
.RefQualifierIsLValueRef
11057 << FixItHint::CreateRemoval(FTI
.getRefQualifierLoc());
11058 D
.setInvalidType();
11061 // Make sure we don't have any parameters.
11062 if (FTIHasNonVoidParameters(FTI
)) {
11063 Diag(D
.getIdentifierLoc(), diag::err_destructor_with_params
);
11065 // Delete the parameters.
11067 D
.setInvalidType();
11070 // Make sure the destructor isn't variadic.
11071 if (FTI
.isVariadic
) {
11072 Diag(D
.getIdentifierLoc(), diag::err_destructor_variadic
);
11073 D
.setInvalidType();
11076 // Rebuild the function type "R" without any type qualifiers or
11077 // parameters (in case any of the errors above fired) and with
11078 // "void" as the return type, since destructors don't have return
11080 if (!D
.isInvalidType())
11083 const FunctionProtoType
*Proto
= R
->castAs
<FunctionProtoType
>();
11084 FunctionProtoType::ExtProtoInfo EPI
= Proto
->getExtProtoInfo();
11085 EPI
.Variadic
= false;
11086 EPI
.TypeQuals
= Qualifiers();
11087 EPI
.RefQualifier
= RQ_None
;
11088 return Context
.getFunctionType(Context
.VoidTy
, std::nullopt
, EPI
);
11091 static void extendLeft(SourceRange
&R
, SourceRange Before
) {
11092 if (Before
.isInvalid())
11094 R
.setBegin(Before
.getBegin());
11095 if (R
.getEnd().isInvalid())
11096 R
.setEnd(Before
.getEnd());
11099 static void extendRight(SourceRange
&R
, SourceRange After
) {
11100 if (After
.isInvalid())
11102 if (R
.getBegin().isInvalid())
11103 R
.setBegin(After
.getBegin());
11104 R
.setEnd(After
.getEnd());
11107 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
11108 /// well-formednes of the conversion function declarator @p D with
11109 /// type @p R. If there are any errors in the declarator, this routine
11110 /// will emit diagnostics and return true. Otherwise, it will return
11111 /// false. Either way, the type @p R will be updated to reflect a
11112 /// well-formed type for the conversion operator.
11113 void Sema::CheckConversionDeclarator(Declarator
&D
, QualType
&R
,
11114 StorageClass
& SC
) {
11115 // C++ [class.conv.fct]p1:
11116 // Neither parameter types nor return type can be specified. The
11117 // type of a conversion function (8.3.5) is "function taking no
11118 // parameter returning conversion-type-id."
11119 if (SC
== SC_Static
) {
11120 if (!D
.isInvalidType())
11121 Diag(D
.getIdentifierLoc(), diag::err_conv_function_not_member
)
11122 << SourceRange(D
.getDeclSpec().getStorageClassSpecLoc())
11123 << D
.getName().getSourceRange();
11124 D
.setInvalidType();
11128 TypeSourceInfo
*ConvTSI
= nullptr;
11129 QualType ConvType
=
11130 GetTypeFromParser(D
.getName().ConversionFunctionId
, &ConvTSI
);
11132 const DeclSpec
&DS
= D
.getDeclSpec();
11133 if (DS
.hasTypeSpecifier() && !D
.isInvalidType()) {
11134 // Conversion functions don't have return types, but the parser will
11135 // happily parse something like:
11138 // float operator bool();
11141 // The return type will be changed later anyway.
11142 Diag(D
.getIdentifierLoc(), diag::err_conv_function_return_type
)
11143 << SourceRange(DS
.getTypeSpecTypeLoc())
11144 << SourceRange(D
.getIdentifierLoc());
11145 D
.setInvalidType();
11146 } else if (DS
.getTypeQualifiers() && !D
.isInvalidType()) {
11147 // It's also plausible that the user writes type qualifiers in the wrong
11149 // struct S { const operator int(); };
11150 // FIXME: we could provide a fixit to move the qualifiers onto the
11151 // conversion type.
11152 Diag(D
.getIdentifierLoc(), diag::err_conv_function_with_complex_decl
)
11153 << SourceRange(D
.getIdentifierLoc()) << 0;
11154 D
.setInvalidType();
11156 const auto *Proto
= R
->castAs
<FunctionProtoType
>();
11157 // Make sure we don't have any parameters.
11158 DeclaratorChunk::FunctionTypeInfo
&FTI
= D
.getFunctionTypeInfo();
11159 unsigned NumParam
= Proto
->getNumParams();
11162 // A conversion function shall have no non-object parameters.
11163 if (NumParam
== 1) {
11164 DeclaratorChunk::FunctionTypeInfo
&FTI
= D
.getFunctionTypeInfo();
11165 if (const auto *First
=
11166 dyn_cast_if_present
<ParmVarDecl
>(FTI
.Params
[0].Param
);
11167 First
&& First
->isExplicitObjectParameter())
11171 if (NumParam
!= 0) {
11172 Diag(D
.getIdentifierLoc(), diag::err_conv_function_with_params
);
11173 // Delete the parameters.
11175 D
.setInvalidType();
11176 } else if (Proto
->isVariadic()) {
11177 Diag(D
.getIdentifierLoc(), diag::err_conv_function_variadic
);
11178 D
.setInvalidType();
11181 // Diagnose "&operator bool()" and other such nonsense. This
11182 // is actually a gcc extension which we don't support.
11183 if (Proto
->getReturnType() != ConvType
) {
11184 bool NeedsTypedef
= false;
11185 SourceRange Before
, After
;
11187 // Walk the chunks and extract information on them for our diagnostic.
11188 bool PastFunctionChunk
= false;
11189 for (auto &Chunk
: D
.type_objects()) {
11190 switch (Chunk
.Kind
) {
11191 case DeclaratorChunk::Function
:
11192 if (!PastFunctionChunk
) {
11193 if (Chunk
.Fun
.HasTrailingReturnType
) {
11194 TypeSourceInfo
*TRT
= nullptr;
11195 GetTypeFromParser(Chunk
.Fun
.getTrailingReturnType(), &TRT
);
11196 if (TRT
) extendRight(After
, TRT
->getTypeLoc().getSourceRange());
11198 PastFunctionChunk
= true;
11202 case DeclaratorChunk::Array
:
11203 NeedsTypedef
= true;
11204 extendRight(After
, Chunk
.getSourceRange());
11207 case DeclaratorChunk::Pointer
:
11208 case DeclaratorChunk::BlockPointer
:
11209 case DeclaratorChunk::Reference
:
11210 case DeclaratorChunk::MemberPointer
:
11211 case DeclaratorChunk::Pipe
:
11212 extendLeft(Before
, Chunk
.getSourceRange());
11215 case DeclaratorChunk::Paren
:
11216 extendLeft(Before
, Chunk
.Loc
);
11217 extendRight(After
, Chunk
.EndLoc
);
11222 SourceLocation Loc
= Before
.isValid() ? Before
.getBegin() :
11223 After
.isValid() ? After
.getBegin() :
11224 D
.getIdentifierLoc();
11225 auto &&DB
= Diag(Loc
, diag::err_conv_function_with_complex_decl
);
11226 DB
<< Before
<< After
;
11228 if (!NeedsTypedef
) {
11229 DB
<< /*don't need a typedef*/0;
11231 // If we can provide a correct fix-it hint, do so.
11232 if (After
.isInvalid() && ConvTSI
) {
11233 SourceLocation InsertLoc
=
11234 getLocForEndOfToken(ConvTSI
->getTypeLoc().getEndLoc());
11235 DB
<< FixItHint::CreateInsertion(InsertLoc
, " ")
11236 << FixItHint::CreateInsertionFromRange(
11237 InsertLoc
, CharSourceRange::getTokenRange(Before
))
11238 << FixItHint::CreateRemoval(Before
);
11240 } else if (!Proto
->getReturnType()->isDependentType()) {
11241 DB
<< /*typedef*/1 << Proto
->getReturnType();
11242 } else if (getLangOpts().CPlusPlus11
) {
11243 DB
<< /*alias template*/2 << Proto
->getReturnType();
11245 DB
<< /*might not be fixable*/3;
11248 // Recover by incorporating the other type chunks into the result type.
11249 // Note, this does *not* change the name of the function. This is compatible
11250 // with the GCC extension:
11251 // struct S { &operator int(); } s;
11252 // int &r = s.operator int(); // ok in GCC
11253 // S::operator int&() {} // error in GCC, function name is 'operator int'.
11254 ConvType
= Proto
->getReturnType();
11257 // C++ [class.conv.fct]p4:
11258 // The conversion-type-id shall not represent a function type nor
11260 if (ConvType
->isArrayType()) {
11261 Diag(D
.getIdentifierLoc(), diag::err_conv_function_to_array
);
11262 ConvType
= Context
.getPointerType(ConvType
);
11263 D
.setInvalidType();
11264 } else if (ConvType
->isFunctionType()) {
11265 Diag(D
.getIdentifierLoc(), diag::err_conv_function_to_function
);
11266 ConvType
= Context
.getPointerType(ConvType
);
11267 D
.setInvalidType();
11270 // Rebuild the function type "R" without any parameters (in case any
11271 // of the errors above fired) and with the conversion type as the
11273 if (D
.isInvalidType())
11274 R
= Context
.getFunctionType(ConvType
, std::nullopt
,
11275 Proto
->getExtProtoInfo());
11277 // C++0x explicit conversion operators.
11278 if (DS
.hasExplicitSpecifier() && !getLangOpts().CPlusPlus20
)
11279 Diag(DS
.getExplicitSpecLoc(),
11280 getLangOpts().CPlusPlus11
11281 ? diag::warn_cxx98_compat_explicit_conversion_functions
11282 : diag::ext_explicit_conversion_functions
)
11283 << SourceRange(DS
.getExplicitSpecRange());
11286 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
11287 /// the declaration of the given C++ conversion function. This routine
11288 /// is responsible for recording the conversion function in the C++
11289 /// class, if possible.
11290 Decl
*Sema::ActOnConversionDeclarator(CXXConversionDecl
*Conversion
) {
11291 assert(Conversion
&& "Expected to receive a conversion function declaration");
11293 CXXRecordDecl
*ClassDecl
= cast
<CXXRecordDecl
>(Conversion
->getDeclContext());
11295 // Make sure we aren't redeclaring the conversion function.
11296 QualType ConvType
= Context
.getCanonicalType(Conversion
->getConversionType());
11297 // C++ [class.conv.fct]p1:
11298 // [...] A conversion function is never used to convert a
11299 // (possibly cv-qualified) object to the (possibly cv-qualified)
11300 // same object type (or a reference to it), to a (possibly
11301 // cv-qualified) base class of that type (or a reference to it),
11302 // or to (possibly cv-qualified) void.
11304 = Context
.getCanonicalType(Context
.getTypeDeclType(ClassDecl
));
11305 if (const ReferenceType
*ConvTypeRef
= ConvType
->getAs
<ReferenceType
>())
11306 ConvType
= ConvTypeRef
->getPointeeType();
11307 if (Conversion
->getTemplateSpecializationKind() != TSK_Undeclared
&&
11308 Conversion
->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
)
11309 /* Suppress diagnostics for instantiations. */;
11310 else if (Conversion
->size_overridden_methods() != 0)
11311 /* Suppress diagnostics for overriding virtual function in a base class. */;
11312 else if (ConvType
->isRecordType()) {
11313 ConvType
= Context
.getCanonicalType(ConvType
).getUnqualifiedType();
11314 if (ConvType
== ClassType
)
11315 Diag(Conversion
->getLocation(), diag::warn_conv_to_self_not_used
)
11317 else if (IsDerivedFrom(Conversion
->getLocation(), ClassType
, ConvType
))
11318 Diag(Conversion
->getLocation(), diag::warn_conv_to_base_not_used
)
11319 << ClassType
<< ConvType
;
11320 } else if (ConvType
->isVoidType()) {
11321 Diag(Conversion
->getLocation(), diag::warn_conv_to_void_not_used
)
11322 << ClassType
<< ConvType
;
11325 if (FunctionTemplateDecl
*ConversionTemplate
11326 = Conversion
->getDescribedFunctionTemplate())
11327 return ConversionTemplate
;
11332 void Sema::CheckExplicitObjectMemberFunction(DeclContext
*DC
, Declarator
&D
,
11333 DeclarationName Name
, QualType R
) {
11334 CheckExplicitObjectMemberFunction(D
, Name
, R
, false, DC
);
11337 void Sema::CheckExplicitObjectLambda(Declarator
&D
) {
11338 CheckExplicitObjectMemberFunction(D
, {}, {}, true);
11341 void Sema::CheckExplicitObjectMemberFunction(Declarator
&D
,
11342 DeclarationName Name
, QualType R
,
11343 bool IsLambda
, DeclContext
*DC
) {
11344 if (!D
.isFunctionDeclarator())
11347 DeclaratorChunk::FunctionTypeInfo
&FTI
= D
.getFunctionTypeInfo();
11348 if (FTI
.NumParams
== 0)
11350 ParmVarDecl
*ExplicitObjectParam
= nullptr;
11351 for (unsigned Idx
= 0; Idx
< FTI
.NumParams
; Idx
++) {
11352 const auto &ParamInfo
= FTI
.Params
[Idx
];
11353 if (!ParamInfo
.Param
)
11355 ParmVarDecl
*Param
= cast
<ParmVarDecl
>(ParamInfo
.Param
);
11356 if (!Param
->isExplicitObjectParameter())
11359 ExplicitObjectParam
= Param
;
11362 Diag(Param
->getLocation(),
11363 diag::err_explicit_object_parameter_must_be_first
)
11364 << IsLambda
<< Param
->getSourceRange();
11367 if (!ExplicitObjectParam
)
11370 if (ExplicitObjectParam
->hasDefaultArg()) {
11371 Diag(ExplicitObjectParam
->getLocation(),
11372 diag::err_explicit_object_default_arg
)
11373 << ExplicitObjectParam
->getSourceRange();
11376 if (D
.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static
) {
11377 Diag(ExplicitObjectParam
->getBeginLoc(),
11378 diag::err_explicit_object_parameter_nonmember
)
11379 << D
.getSourceRange() << /*static=*/0 << IsLambda
;
11380 D
.setInvalidType();
11383 if (D
.getDeclSpec().isVirtualSpecified()) {
11384 Diag(ExplicitObjectParam
->getBeginLoc(),
11385 diag::err_explicit_object_parameter_nonmember
)
11386 << D
.getSourceRange() << /*virtual=*/1 << IsLambda
;
11387 D
.setInvalidType();
11390 if (IsLambda
&& FTI
.hasMutableQualifier()) {
11391 Diag(ExplicitObjectParam
->getBeginLoc(),
11392 diag::err_explicit_object_parameter_mutable
)
11393 << D
.getSourceRange();
11399 if (!DC
|| !DC
->isRecord()) {
11400 Diag(ExplicitObjectParam
->getLocation(),
11401 diag::err_explicit_object_parameter_nonmember
)
11402 << D
.getSourceRange() << /*non-member=*/2 << IsLambda
;
11403 D
.setInvalidType();
11407 // CWG2674: constructors and destructors cannot have explicit parameters.
11408 if (Name
.getNameKind() == DeclarationName::CXXConstructorName
||
11409 Name
.getNameKind() == DeclarationName::CXXDestructorName
) {
11410 Diag(ExplicitObjectParam
->getBeginLoc(),
11411 diag::err_explicit_object_parameter_constructor
)
11412 << (Name
.getNameKind() == DeclarationName::CXXDestructorName
)
11413 << D
.getSourceRange();
11414 D
.setInvalidType();
11419 /// Utility class to accumulate and print a diagnostic listing the invalid
11420 /// specifier(s) on a declaration.
11421 struct BadSpecifierDiagnoser
{
11422 BadSpecifierDiagnoser(Sema
&S
, SourceLocation Loc
, unsigned DiagID
)
11423 : S(S
), Diagnostic(S
.Diag(Loc
, DiagID
)) {}
11424 ~BadSpecifierDiagnoser() {
11425 Diagnostic
<< Specifiers
;
11428 template<typename T
> void check(SourceLocation SpecLoc
, T Spec
) {
11429 return check(SpecLoc
, DeclSpec::getSpecifierName(Spec
));
11431 void check(SourceLocation SpecLoc
, DeclSpec::TST Spec
) {
11432 return check(SpecLoc
,
11433 DeclSpec::getSpecifierName(Spec
, S
.getPrintingPolicy()));
11435 void check(SourceLocation SpecLoc
, const char *Spec
) {
11436 if (SpecLoc
.isInvalid()) return;
11437 Diagnostic
<< SourceRange(SpecLoc
, SpecLoc
);
11438 if (!Specifiers
.empty()) Specifiers
+= " ";
11439 Specifiers
+= Spec
;
11443 Sema::SemaDiagnosticBuilder Diagnostic
;
11444 std::string Specifiers
;
11448 /// Check the validity of a declarator that we parsed for a deduction-guide.
11449 /// These aren't actually declarators in the grammar, so we need to check that
11450 /// the user didn't specify any pieces that are not part of the deduction-guide
11451 /// grammar. Return true on invalid deduction-guide.
11452 bool Sema::CheckDeductionGuideDeclarator(Declarator
&D
, QualType
&R
,
11453 StorageClass
&SC
) {
11454 TemplateName GuidedTemplate
= D
.getName().TemplateName
.get().get();
11455 TemplateDecl
*GuidedTemplateDecl
= GuidedTemplate
.getAsTemplateDecl();
11456 assert(GuidedTemplateDecl
&& "missing template decl for deduction guide");
11458 // C++ [temp.deduct.guide]p3:
11459 // A deduction-gide shall be declared in the same scope as the
11460 // corresponding class template.
11461 if (!CurContext
->getRedeclContext()->Equals(
11462 GuidedTemplateDecl
->getDeclContext()->getRedeclContext())) {
11463 Diag(D
.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope
)
11464 << GuidedTemplateDecl
;
11465 Diag(GuidedTemplateDecl
->getLocation(), diag::note_template_decl_here
);
11468 auto &DS
= D
.getMutableDeclSpec();
11469 // We leave 'friend' and 'virtual' to be rejected in the normal way.
11470 if (DS
.hasTypeSpecifier() || DS
.getTypeQualifiers() ||
11471 DS
.getStorageClassSpecLoc().isValid() || DS
.isInlineSpecified() ||
11472 DS
.isNoreturnSpecified() || DS
.hasConstexprSpecifier()) {
11473 BadSpecifierDiagnoser
Diagnoser(
11474 *this, D
.getIdentifierLoc(),
11475 diag::err_deduction_guide_invalid_specifier
);
11477 Diagnoser
.check(DS
.getStorageClassSpecLoc(), DS
.getStorageClassSpec());
11478 DS
.ClearStorageClassSpecs();
11481 // 'explicit' is permitted.
11482 Diagnoser
.check(DS
.getInlineSpecLoc(), "inline");
11483 Diagnoser
.check(DS
.getNoreturnSpecLoc(), "_Noreturn");
11484 Diagnoser
.check(DS
.getConstexprSpecLoc(), "constexpr");
11485 DS
.ClearConstexprSpec();
11487 Diagnoser
.check(DS
.getConstSpecLoc(), "const");
11488 Diagnoser
.check(DS
.getRestrictSpecLoc(), "__restrict");
11489 Diagnoser
.check(DS
.getVolatileSpecLoc(), "volatile");
11490 Diagnoser
.check(DS
.getAtomicSpecLoc(), "_Atomic");
11491 Diagnoser
.check(DS
.getUnalignedSpecLoc(), "__unaligned");
11492 DS
.ClearTypeQualifiers();
11494 Diagnoser
.check(DS
.getTypeSpecComplexLoc(), DS
.getTypeSpecComplex());
11495 Diagnoser
.check(DS
.getTypeSpecSignLoc(), DS
.getTypeSpecSign());
11496 Diagnoser
.check(DS
.getTypeSpecWidthLoc(), DS
.getTypeSpecWidth());
11497 Diagnoser
.check(DS
.getTypeSpecTypeLoc(), DS
.getTypeSpecType());
11498 DS
.ClearTypeSpecType();
11501 if (D
.isInvalidType())
11504 // Check the declarator is simple enough.
11505 bool FoundFunction
= false;
11506 for (const DeclaratorChunk
&Chunk
: llvm::reverse(D
.type_objects())) {
11507 if (Chunk
.Kind
== DeclaratorChunk::Paren
)
11509 if (Chunk
.Kind
!= DeclaratorChunk::Function
|| FoundFunction
) {
11510 Diag(D
.getDeclSpec().getBeginLoc(),
11511 diag::err_deduction_guide_with_complex_decl
)
11512 << D
.getSourceRange();
11515 if (!Chunk
.Fun
.hasTrailingReturnType())
11516 return Diag(D
.getName().getBeginLoc(),
11517 diag::err_deduction_guide_no_trailing_return_type
);
11519 // Check that the return type is written as a specialization of
11520 // the template specified as the deduction-guide's name.
11521 // The template name may not be qualified. [temp.deduct.guide]
11522 ParsedType TrailingReturnType
= Chunk
.Fun
.getTrailingReturnType();
11523 TypeSourceInfo
*TSI
= nullptr;
11524 QualType RetTy
= GetTypeFromParser(TrailingReturnType
, &TSI
);
11525 assert(TSI
&& "deduction guide has valid type but invalid return type?");
11526 bool AcceptableReturnType
= false;
11527 bool MightInstantiateToSpecialization
= false;
11529 TSI
->getTypeLoc().getAsAdjusted
<TemplateSpecializationTypeLoc
>()) {
11530 TemplateName SpecifiedName
= RetTST
.getTypePtr()->getTemplateName();
11531 bool TemplateMatches
=
11532 Context
.hasSameTemplateName(SpecifiedName
, GuidedTemplate
);
11533 auto TKind
= SpecifiedName
.getKind();
11534 // A Using TemplateName can't actually be valid (either it's qualified, or
11535 // we're in the wrong scope). But we have diagnosed these problems
11537 bool SimplyWritten
= TKind
== TemplateName::Template
||
11538 TKind
== TemplateName::UsingTemplate
;
11539 if (SimplyWritten
&& TemplateMatches
)
11540 AcceptableReturnType
= true;
11542 // This could still instantiate to the right type, unless we know it
11543 // names the wrong class template.
11544 auto *TD
= SpecifiedName
.getAsTemplateDecl();
11545 MightInstantiateToSpecialization
= !(TD
&& isa
<ClassTemplateDecl
>(TD
) &&
11548 } else if (!RetTy
.hasQualifiers() && RetTy
->isDependentType()) {
11549 MightInstantiateToSpecialization
= true;
11552 if (!AcceptableReturnType
)
11553 return Diag(TSI
->getTypeLoc().getBeginLoc(),
11554 diag::err_deduction_guide_bad_trailing_return_type
)
11555 << GuidedTemplate
<< TSI
->getType()
11556 << MightInstantiateToSpecialization
11557 << TSI
->getTypeLoc().getSourceRange();
11559 // Keep going to check that we don't have any inner declarator pieces (we
11560 // could still have a function returning a pointer to a function).
11561 FoundFunction
= true;
11564 if (D
.isFunctionDefinition())
11565 // we can still create a valid deduction guide here.
11566 Diag(D
.getIdentifierLoc(), diag::err_deduction_guide_defines_function
);
11570 //===----------------------------------------------------------------------===//
11571 // Namespace Handling
11572 //===----------------------------------------------------------------------===//
11574 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is
11576 static void DiagnoseNamespaceInlineMismatch(Sema
&S
, SourceLocation KeywordLoc
,
11577 SourceLocation Loc
,
11578 IdentifierInfo
*II
, bool *IsInline
,
11579 NamespaceDecl
*PrevNS
) {
11580 assert(*IsInline
!= PrevNS
->isInline());
11582 // 'inline' must appear on the original definition, but not necessarily
11583 // on all extension definitions, so the note should point to the first
11584 // definition to avoid confusion.
11585 PrevNS
= PrevNS
->getFirstDecl();
11587 if (PrevNS
->isInline())
11588 // The user probably just forgot the 'inline', so suggest that it
11590 S
.Diag(Loc
, diag::warn_inline_namespace_reopened_noninline
)
11591 << FixItHint::CreateInsertion(KeywordLoc
, "inline ");
11593 S
.Diag(Loc
, diag::err_inline_namespace_mismatch
);
11595 S
.Diag(PrevNS
->getLocation(), diag::note_previous_definition
);
11596 *IsInline
= PrevNS
->isInline();
11599 /// ActOnStartNamespaceDef - This is called at the start of a namespace
11601 Decl
*Sema::ActOnStartNamespaceDef(Scope
*NamespcScope
,
11602 SourceLocation InlineLoc
,
11603 SourceLocation NamespaceLoc
,
11604 SourceLocation IdentLoc
, IdentifierInfo
*II
,
11605 SourceLocation LBrace
,
11606 const ParsedAttributesView
&AttrList
,
11607 UsingDirectiveDecl
*&UD
, bool IsNested
) {
11608 SourceLocation StartLoc
= InlineLoc
.isValid() ? InlineLoc
: NamespaceLoc
;
11609 // For anonymous namespace, take the location of the left brace.
11610 SourceLocation Loc
= II
? IdentLoc
: LBrace
;
11611 bool IsInline
= InlineLoc
.isValid();
11612 bool IsInvalid
= false;
11613 bool IsStd
= false;
11614 bool AddToKnown
= false;
11615 Scope
*DeclRegionScope
= NamespcScope
->getParent();
11617 NamespaceDecl
*PrevNS
= nullptr;
11619 // C++ [namespace.std]p7:
11620 // A translation unit shall not declare namespace std to be an inline
11621 // namespace (9.8.2).
11623 // Precondition: the std namespace is in the file scope and is declared to
11625 auto DiagnoseInlineStdNS
= [&]() {
11626 assert(IsInline
&& II
->isStr("std") &&
11627 CurContext
->getRedeclContext()->isTranslationUnit() &&
11628 "Precondition of DiagnoseInlineStdNS not met");
11629 Diag(InlineLoc
, diag::err_inline_namespace_std
)
11630 << SourceRange(InlineLoc
, InlineLoc
.getLocWithOffset(6));
11633 // C++ [namespace.def]p2:
11634 // The identifier in an original-namespace-definition shall not
11635 // have been previously defined in the declarative region in
11636 // which the original-namespace-definition appears. The
11637 // identifier in an original-namespace-definition is the name of
11638 // the namespace. Subsequently in that declarative region, it is
11639 // treated as an original-namespace-name.
11641 // Since namespace names are unique in their scope, and we don't
11642 // look through using directives, just look for any ordinary names
11643 // as if by qualified name lookup.
11644 LookupResult
R(*this, II
, IdentLoc
, LookupOrdinaryName
,
11645 ForExternalRedeclaration
);
11646 LookupQualifiedName(R
, CurContext
->getRedeclContext());
11647 NamedDecl
*PrevDecl
=
11648 R
.isSingleResult() ? R
.getRepresentativeDecl() : nullptr;
11649 PrevNS
= dyn_cast_or_null
<NamespaceDecl
>(PrevDecl
);
11652 // This is an extended namespace definition.
11653 if (IsInline
&& II
->isStr("std") &&
11654 CurContext
->getRedeclContext()->isTranslationUnit())
11655 DiagnoseInlineStdNS();
11656 else if (IsInline
!= PrevNS
->isInline())
11657 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc
, Loc
, II
,
11658 &IsInline
, PrevNS
);
11659 } else if (PrevDecl
) {
11660 // This is an invalid name redefinition.
11661 Diag(Loc
, diag::err_redefinition_different_kind
)
11663 Diag(PrevDecl
->getLocation(), diag::note_previous_definition
);
11665 // Continue on to push Namespc as current DeclContext and return it.
11666 } else if (II
->isStr("std") &&
11667 CurContext
->getRedeclContext()->isTranslationUnit()) {
11669 DiagnoseInlineStdNS();
11670 // This is the first "real" definition of the namespace "std", so update
11671 // our cache of the "std" namespace to point at this definition.
11672 PrevNS
= getStdNamespace();
11674 AddToKnown
= !IsInline
;
11676 // We've seen this namespace for the first time.
11677 AddToKnown
= !IsInline
;
11680 // Anonymous namespaces.
11682 // Determine whether the parent already has an anonymous namespace.
11683 DeclContext
*Parent
= CurContext
->getRedeclContext();
11684 if (TranslationUnitDecl
*TU
= dyn_cast
<TranslationUnitDecl
>(Parent
)) {
11685 PrevNS
= TU
->getAnonymousNamespace();
11687 NamespaceDecl
*ND
= cast
<NamespaceDecl
>(Parent
);
11688 PrevNS
= ND
->getAnonymousNamespace();
11691 if (PrevNS
&& IsInline
!= PrevNS
->isInline())
11692 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc
, NamespaceLoc
, II
,
11693 &IsInline
, PrevNS
);
11696 NamespaceDecl
*Namespc
= NamespaceDecl::Create(
11697 Context
, CurContext
, IsInline
, StartLoc
, Loc
, II
, PrevNS
, IsNested
);
11699 Namespc
->setInvalidDecl();
11701 ProcessDeclAttributeList(DeclRegionScope
, Namespc
, AttrList
);
11702 AddPragmaAttributes(DeclRegionScope
, Namespc
);
11704 // FIXME: Should we be merging attributes?
11705 if (const VisibilityAttr
*Attr
= Namespc
->getAttr
<VisibilityAttr
>())
11706 PushNamespaceVisibilityAttr(Attr
, Loc
);
11709 StdNamespace
= Namespc
;
11711 KnownNamespaces
[Namespc
] = false;
11714 PushOnScopeChains(Namespc
, DeclRegionScope
);
11716 // Link the anonymous namespace into its parent.
11717 DeclContext
*Parent
= CurContext
->getRedeclContext();
11718 if (TranslationUnitDecl
*TU
= dyn_cast
<TranslationUnitDecl
>(Parent
)) {
11719 TU
->setAnonymousNamespace(Namespc
);
11721 cast
<NamespaceDecl
>(Parent
)->setAnonymousNamespace(Namespc
);
11724 CurContext
->addDecl(Namespc
);
11726 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
11727 // behaves as if it were replaced by
11728 // namespace unique { /* empty body */ }
11729 // using namespace unique;
11730 // namespace unique { namespace-body }
11731 // where all occurrences of 'unique' in a translation unit are
11732 // replaced by the same identifier and this identifier differs
11733 // from all other identifiers in the entire program.
11735 // We just create the namespace with an empty name and then add an
11736 // implicit using declaration, just like the standard suggests.
11738 // CodeGen enforces the "universally unique" aspect by giving all
11739 // declarations semantically contained within an anonymous
11740 // namespace internal linkage.
11743 UD
= UsingDirectiveDecl::Create(Context
, Parent
,
11744 /* 'using' */ LBrace
,
11745 /* 'namespace' */ SourceLocation(),
11746 /* qualifier */ NestedNameSpecifierLoc(),
11747 /* identifier */ SourceLocation(),
11749 /* Ancestor */ Parent
);
11751 Parent
->addDecl(UD
);
11755 ActOnDocumentableDecl(Namespc
);
11757 // Although we could have an invalid decl (i.e. the namespace name is a
11758 // redefinition), push it as current DeclContext and try to continue parsing.
11759 // FIXME: We should be able to push Namespc here, so that the each DeclContext
11760 // for the namespace has the declarations that showed up in that particular
11761 // namespace definition.
11762 PushDeclContext(NamespcScope
, Namespc
);
11766 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
11767 /// is a namespace alias, returns the namespace it points to.
11768 static inline NamespaceDecl
*getNamespaceDecl(NamedDecl
*D
) {
11769 if (NamespaceAliasDecl
*AD
= dyn_cast_or_null
<NamespaceAliasDecl
>(D
))
11770 return AD
->getNamespace();
11771 return dyn_cast_or_null
<NamespaceDecl
>(D
);
11774 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
11775 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
11776 void Sema::ActOnFinishNamespaceDef(Decl
*Dcl
, SourceLocation RBrace
) {
11777 NamespaceDecl
*Namespc
= dyn_cast_or_null
<NamespaceDecl
>(Dcl
);
11778 assert(Namespc
&& "Invalid parameter, expected NamespaceDecl");
11779 Namespc
->setRBraceLoc(RBrace
);
11781 if (Namespc
->hasAttr
<VisibilityAttr
>())
11782 PopPragmaVisibility(true, RBrace
);
11783 // If this namespace contains an export-declaration, export it now.
11784 if (DeferredExportedNamespaces
.erase(Namespc
))
11785 Dcl
->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported
);
11788 CXXRecordDecl
*Sema::getStdBadAlloc() const {
11789 return cast_or_null
<CXXRecordDecl
>(
11790 StdBadAlloc
.get(Context
.getExternalSource()));
11793 EnumDecl
*Sema::getStdAlignValT() const {
11794 return cast_or_null
<EnumDecl
>(StdAlignValT
.get(Context
.getExternalSource()));
11797 NamespaceDecl
*Sema::getStdNamespace() const {
11798 return cast_or_null
<NamespaceDecl
>(
11799 StdNamespace
.get(Context
.getExternalSource()));
11803 enum UnsupportedSTLSelect
{
11810 struct InvalidSTLDiagnoser
{
11812 SourceLocation Loc
;
11813 QualType TyForDiags
;
11815 QualType
operator()(UnsupportedSTLSelect Sel
= USS_Other
, StringRef Name
= "",
11816 const VarDecl
*VD
= nullptr) {
11818 auto D
= S
.Diag(Loc
, diag::err_std_compare_type_not_supported
)
11819 << TyForDiags
<< ((int)Sel
);
11820 if (Sel
== USS_InvalidMember
|| Sel
== USS_MissingMember
) {
11821 assert(!Name
.empty());
11825 if (Sel
== USS_InvalidMember
) {
11826 S
.Diag(VD
->getLocation(), diag::note_var_declared_here
)
11827 << VD
<< VD
->getSourceRange();
11834 QualType
Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind
,
11835 SourceLocation Loc
,
11836 ComparisonCategoryUsage Usage
) {
11837 assert(getLangOpts().CPlusPlus
&&
11838 "Looking for comparison category type outside of C++.");
11840 // Use an elaborated type for diagnostics which has a name containing the
11841 // prepended 'std' namespace but not any inline namespace names.
11842 auto TyForDiags
= [&](ComparisonCategoryInfo
*Info
) {
11844 NestedNameSpecifier::Create(Context
, nullptr, getStdNamespace());
11845 return Context
.getElaboratedType(ElaboratedTypeKeyword::None
, NNS
,
11849 // Check if we've already successfully checked the comparison category type
11850 // before. If so, skip checking it again.
11851 ComparisonCategoryInfo
*Info
= Context
.CompCategories
.lookupInfo(Kind
);
11852 if (Info
&& FullyCheckedComparisonCategories
[static_cast<unsigned>(Kind
)]) {
11853 // The only thing we need to check is that the type has a reachable
11854 // definition in the current context.
11855 if (RequireCompleteType(Loc
, TyForDiags(Info
), diag::err_incomplete_type
))
11858 return Info
->getType();
11861 // If lookup failed
11863 std::string NameForDiags
= "std::";
11864 NameForDiags
+= ComparisonCategories::getCategoryString(Kind
);
11865 Diag(Loc
, diag::err_implied_comparison_category_type_not_found
)
11866 << NameForDiags
<< (int)Usage
;
11870 assert(Info
->Kind
== Kind
);
11871 assert(Info
->Record
);
11873 // Update the Record decl in case we encountered a forward declaration on our
11874 // first pass. FIXME: This is a bit of a hack.
11875 if (Info
->Record
->hasDefinition())
11876 Info
->Record
= Info
->Record
->getDefinition();
11878 if (RequireCompleteType(Loc
, TyForDiags(Info
), diag::err_incomplete_type
))
11881 InvalidSTLDiagnoser UnsupportedSTLError
{*this, Loc
, TyForDiags(Info
)};
11883 if (!Info
->Record
->isTriviallyCopyable())
11884 return UnsupportedSTLError(USS_NonTrivial
);
11886 for (const CXXBaseSpecifier
&BaseSpec
: Info
->Record
->bases()) {
11887 CXXRecordDecl
*Base
= BaseSpec
.getType()->getAsCXXRecordDecl();
11888 // Tolerate empty base classes.
11889 if (Base
->isEmpty())
11891 // Reject STL implementations which have at least one non-empty base.
11892 return UnsupportedSTLError();
11895 // Check that the STL has implemented the types using a single integer field.
11896 // This expectation allows better codegen for builtin operators. We require:
11897 // (1) The class has exactly one field.
11898 // (2) The field is an integral or enumeration type.
11899 auto FIt
= Info
->Record
->field_begin(), FEnd
= Info
->Record
->field_end();
11900 if (std::distance(FIt
, FEnd
) != 1 ||
11901 !FIt
->getType()->isIntegralOrEnumerationType()) {
11902 return UnsupportedSTLError();
11905 // Build each of the require values and store them in Info.
11906 for (ComparisonCategoryResult CCR
:
11907 ComparisonCategories::getPossibleResultsForType(Kind
)) {
11908 StringRef MemName
= ComparisonCategories::getResultString(CCR
);
11909 ComparisonCategoryInfo::ValueInfo
*ValInfo
= Info
->lookupValueInfo(CCR
);
11912 return UnsupportedSTLError(USS_MissingMember
, MemName
);
11914 VarDecl
*VD
= ValInfo
->VD
;
11915 assert(VD
&& "should not be null!");
11917 // Attempt to diagnose reasons why the STL definition of this type
11918 // might be foobar, including it failing to be a constant expression.
11919 // TODO Handle more ways the lookup or result can be invalid.
11920 if (!VD
->isStaticDataMember() ||
11921 !VD
->isUsableInConstantExpressions(Context
))
11922 return UnsupportedSTLError(USS_InvalidMember
, MemName
, VD
);
11924 // Attempt to evaluate the var decl as a constant expression and extract
11925 // the value of its first field as a ICE. If this fails, the STL
11926 // implementation is not supported.
11927 if (!ValInfo
->hasValidIntValue())
11928 return UnsupportedSTLError();
11930 MarkVariableReferenced(Loc
, VD
);
11933 // We've successfully built the required types and expressions. Update
11934 // the cache and return the newly cached value.
11935 FullyCheckedComparisonCategories
[static_cast<unsigned>(Kind
)] = true;
11936 return Info
->getType();
11939 /// Retrieve the special "std" namespace, which may require us to
11940 /// implicitly define the namespace.
11941 NamespaceDecl
*Sema::getOrCreateStdNamespace() {
11942 if (!StdNamespace
) {
11943 // The "std" namespace has not yet been defined, so build one implicitly.
11944 StdNamespace
= NamespaceDecl::Create(
11945 Context
, Context
.getTranslationUnitDecl(),
11946 /*Inline=*/false, SourceLocation(), SourceLocation(),
11947 &PP
.getIdentifierTable().get("std"),
11948 /*PrevDecl=*/nullptr, /*Nested=*/false);
11949 getStdNamespace()->setImplicit(true);
11950 // We want the created NamespaceDecl to be available for redeclaration
11951 // lookups, but not for regular name lookups.
11952 Context
.getTranslationUnitDecl()->addDecl(getStdNamespace());
11953 getStdNamespace()->clearIdentifierNamespace();
11956 return getStdNamespace();
11959 bool Sema::isStdInitializerList(QualType Ty
, QualType
*Element
) {
11960 assert(getLangOpts().CPlusPlus
&&
11961 "Looking for std::initializer_list outside of C++.");
11963 // We're looking for implicit instantiations of
11964 // template <typename E> class std::initializer_list.
11966 if (!StdNamespace
) // If we haven't seen namespace std yet, this can't be it.
11969 ClassTemplateDecl
*Template
= nullptr;
11970 const TemplateArgument
*Arguments
= nullptr;
11972 if (const RecordType
*RT
= Ty
->getAs
<RecordType
>()) {
11974 ClassTemplateSpecializationDecl
*Specialization
=
11975 dyn_cast
<ClassTemplateSpecializationDecl
>(RT
->getDecl());
11976 if (!Specialization
)
11979 Template
= Specialization
->getSpecializedTemplate();
11980 Arguments
= Specialization
->getTemplateArgs().data();
11981 } else if (const TemplateSpecializationType
*TST
=
11982 Ty
->getAs
<TemplateSpecializationType
>()) {
11983 Template
= dyn_cast_or_null
<ClassTemplateDecl
>(
11984 TST
->getTemplateName().getAsTemplateDecl());
11985 Arguments
= TST
->template_arguments().begin();
11990 if (!StdInitializerList
) {
11991 // Haven't recognized std::initializer_list yet, maybe this is it.
11992 CXXRecordDecl
*TemplateClass
= Template
->getTemplatedDecl();
11993 if (TemplateClass
->getIdentifier() !=
11994 &PP
.getIdentifierTable().get("initializer_list") ||
11995 !getStdNamespace()->InEnclosingNamespaceSetOf(
11996 TemplateClass
->getDeclContext()))
11998 // This is a template called std::initializer_list, but is it the right
12000 TemplateParameterList
*Params
= Template
->getTemplateParameters();
12001 if (Params
->getMinRequiredArguments() != 1)
12003 if (!isa
<TemplateTypeParmDecl
>(Params
->getParam(0)))
12006 // It's the right template.
12007 StdInitializerList
= Template
;
12010 if (Template
->getCanonicalDecl() != StdInitializerList
->getCanonicalDecl())
12013 // This is an instance of std::initializer_list. Find the argument type.
12015 *Element
= Arguments
[0].getAsType();
12019 static ClassTemplateDecl
*LookupStdInitializerList(Sema
&S
, SourceLocation Loc
){
12020 NamespaceDecl
*Std
= S
.getStdNamespace();
12022 S
.Diag(Loc
, diag::err_implied_std_initializer_list_not_found
);
12026 LookupResult
Result(S
, &S
.PP
.getIdentifierTable().get("initializer_list"),
12027 Loc
, Sema::LookupOrdinaryName
);
12028 if (!S
.LookupQualifiedName(Result
, Std
)) {
12029 S
.Diag(Loc
, diag::err_implied_std_initializer_list_not_found
);
12032 ClassTemplateDecl
*Template
= Result
.getAsSingle
<ClassTemplateDecl
>();
12034 Result
.suppressDiagnostics();
12035 // We found something weird. Complain about the first thing we found.
12036 NamedDecl
*Found
= *Result
.begin();
12037 S
.Diag(Found
->getLocation(), diag::err_malformed_std_initializer_list
);
12041 // We found some template called std::initializer_list. Now verify that it's
12043 TemplateParameterList
*Params
= Template
->getTemplateParameters();
12044 if (Params
->getMinRequiredArguments() != 1 ||
12045 !isa
<TemplateTypeParmDecl
>(Params
->getParam(0))) {
12046 S
.Diag(Template
->getLocation(), diag::err_malformed_std_initializer_list
);
12053 QualType
Sema::BuildStdInitializerList(QualType Element
, SourceLocation Loc
) {
12054 if (!StdInitializerList
) {
12055 StdInitializerList
= LookupStdInitializerList(*this, Loc
);
12056 if (!StdInitializerList
)
12060 TemplateArgumentListInfo
Args(Loc
, Loc
);
12061 Args
.addArgument(TemplateArgumentLoc(TemplateArgument(Element
),
12062 Context
.getTrivialTypeSourceInfo(Element
,
12064 return Context
.getElaboratedType(
12065 ElaboratedTypeKeyword::None
,
12066 NestedNameSpecifier::Create(Context
, nullptr, getStdNamespace()),
12067 CheckTemplateIdType(TemplateName(StdInitializerList
), Loc
, Args
));
12070 bool Sema::isInitListConstructor(const FunctionDecl
*Ctor
) {
12071 // C++ [dcl.init.list]p2:
12072 // A constructor is an initializer-list constructor if its first parameter
12073 // is of type std::initializer_list<E> or reference to possibly cv-qualified
12074 // std::initializer_list<E> for some type E, and either there are no other
12075 // parameters or else all other parameters have default arguments.
12076 if (!Ctor
->hasOneParamOrDefaultArgs())
12079 QualType ArgType
= Ctor
->getParamDecl(0)->getType();
12080 if (const ReferenceType
*RT
= ArgType
->getAs
<ReferenceType
>())
12081 ArgType
= RT
->getPointeeType().getUnqualifiedType();
12083 return isStdInitializerList(ArgType
, nullptr);
12086 /// Determine whether a using statement is in a context where it will be
12087 /// apply in all contexts.
12088 static bool IsUsingDirectiveInToplevelContext(DeclContext
*CurContext
) {
12089 switch (CurContext
->getDeclKind()) {
12090 case Decl::TranslationUnit
:
12092 case Decl::LinkageSpec
:
12093 return IsUsingDirectiveInToplevelContext(CurContext
->getParent());
12101 // Callback to only accept typo corrections that are namespaces.
12102 class NamespaceValidatorCCC final
: public CorrectionCandidateCallback
{
12104 bool ValidateCandidate(const TypoCorrection
&candidate
) override
{
12105 if (NamedDecl
*ND
= candidate
.getCorrectionDecl())
12106 return isa
<NamespaceDecl
>(ND
) || isa
<NamespaceAliasDecl
>(ND
);
12110 std::unique_ptr
<CorrectionCandidateCallback
> clone() override
{
12111 return std::make_unique
<NamespaceValidatorCCC
>(*this);
12117 static bool TryNamespaceTypoCorrection(Sema
&S
, LookupResult
&R
, Scope
*Sc
,
12119 SourceLocation IdentLoc
,
12120 IdentifierInfo
*Ident
) {
12122 NamespaceValidatorCCC CCC
{};
12123 if (TypoCorrection Corrected
=
12124 S
.CorrectTypo(R
.getLookupNameInfo(), R
.getLookupKind(), Sc
, &SS
, CCC
,
12125 Sema::CTK_ErrorRecovery
)) {
12126 if (DeclContext
*DC
= S
.computeDeclContext(SS
, false)) {
12127 std::string
CorrectedStr(Corrected
.getAsString(S
.getLangOpts()));
12128 bool DroppedSpecifier
= Corrected
.WillReplaceSpecifier() &&
12129 Ident
->getName().equals(CorrectedStr
);
12130 S
.diagnoseTypo(Corrected
,
12131 S
.PDiag(diag::err_using_directive_member_suggest
)
12132 << Ident
<< DC
<< DroppedSpecifier
<< SS
.getRange(),
12133 S
.PDiag(diag::note_namespace_defined_here
));
12135 S
.diagnoseTypo(Corrected
,
12136 S
.PDiag(diag::err_using_directive_suggest
) << Ident
,
12137 S
.PDiag(diag::note_namespace_defined_here
));
12139 R
.addDecl(Corrected
.getFoundDecl());
12145 Decl
*Sema::ActOnUsingDirective(Scope
*S
, SourceLocation UsingLoc
,
12146 SourceLocation NamespcLoc
, CXXScopeSpec
&SS
,
12147 SourceLocation IdentLoc
,
12148 IdentifierInfo
*NamespcName
,
12149 const ParsedAttributesView
&AttrList
) {
12150 assert(!SS
.isInvalid() && "Invalid CXXScopeSpec.");
12151 assert(NamespcName
&& "Invalid NamespcName.");
12152 assert(IdentLoc
.isValid() && "Invalid NamespceName location.");
12154 // This can only happen along a recovery path.
12155 while (S
->isTemplateParamScope())
12156 S
= S
->getParent();
12157 assert(S
->getFlags() & Scope::DeclScope
&& "Invalid Scope.");
12159 UsingDirectiveDecl
*UDir
= nullptr;
12160 NestedNameSpecifier
*Qualifier
= nullptr;
12162 Qualifier
= SS
.getScopeRep();
12164 // Lookup namespace name.
12165 LookupResult
R(*this, NamespcName
, IdentLoc
, LookupNamespaceName
);
12166 LookupParsedName(R
, S
, &SS
);
12167 if (R
.isAmbiguous())
12172 // Allow "using namespace std;" or "using namespace ::std;" even if
12173 // "std" hasn't been defined yet, for GCC compatibility.
12174 if ((!Qualifier
|| Qualifier
->getKind() == NestedNameSpecifier::Global
) &&
12175 NamespcName
->isStr("std")) {
12176 Diag(IdentLoc
, diag::ext_using_undefined_std
);
12177 R
.addDecl(getOrCreateStdNamespace());
12180 // Otherwise, attempt typo correction.
12181 else TryNamespaceTypoCorrection(*this, R
, S
, SS
, IdentLoc
, NamespcName
);
12185 NamedDecl
*Named
= R
.getRepresentativeDecl();
12186 NamespaceDecl
*NS
= R
.getAsSingle
<NamespaceDecl
>();
12187 assert(NS
&& "expected namespace decl");
12189 // The use of a nested name specifier may trigger deprecation warnings.
12190 DiagnoseUseOfDecl(Named
, IdentLoc
);
12192 // C++ [namespace.udir]p1:
12193 // A using-directive specifies that the names in the nominated
12194 // namespace can be used in the scope in which the
12195 // using-directive appears after the using-directive. During
12196 // unqualified name lookup (3.4.1), the names appear as if they
12197 // were declared in the nearest enclosing namespace which
12198 // contains both the using-directive and the nominated
12199 // namespace. [Note: in this context, "contains" means "contains
12200 // directly or indirectly". ]
12202 // Find enclosing context containing both using-directive and
12203 // nominated namespace.
12204 DeclContext
*CommonAncestor
= NS
;
12205 while (CommonAncestor
&& !CommonAncestor
->Encloses(CurContext
))
12206 CommonAncestor
= CommonAncestor
->getParent();
12208 UDir
= UsingDirectiveDecl::Create(Context
, CurContext
, UsingLoc
, NamespcLoc
,
12209 SS
.getWithLocInContext(Context
),
12210 IdentLoc
, Named
, CommonAncestor
);
12212 if (IsUsingDirectiveInToplevelContext(CurContext
) &&
12213 !SourceMgr
.isInMainFile(SourceMgr
.getExpansionLoc(IdentLoc
))) {
12214 Diag(IdentLoc
, diag::warn_using_directive_in_header
);
12217 PushUsingDirective(S
, UDir
);
12219 Diag(IdentLoc
, diag::err_expected_namespace_name
) << SS
.getRange();
12223 ProcessDeclAttributeList(S
, UDir
, AttrList
);
12228 void Sema::PushUsingDirective(Scope
*S
, UsingDirectiveDecl
*UDir
) {
12229 // If the scope has an associated entity and the using directive is at
12230 // namespace or translation unit scope, add the UsingDirectiveDecl into
12231 // its lookup structure so qualified name lookup can find it.
12232 DeclContext
*Ctx
= S
->getEntity();
12233 if (Ctx
&& !Ctx
->isFunctionOrMethod())
12234 Ctx
->addDecl(UDir
);
12236 // Otherwise, it is at block scope. The using-directives will affect lookup
12237 // only to the end of the scope.
12238 S
->PushUsingDirective(UDir
);
12241 Decl
*Sema::ActOnUsingDeclaration(Scope
*S
, AccessSpecifier AS
,
12242 SourceLocation UsingLoc
,
12243 SourceLocation TypenameLoc
, CXXScopeSpec
&SS
,
12244 UnqualifiedId
&Name
,
12245 SourceLocation EllipsisLoc
,
12246 const ParsedAttributesView
&AttrList
) {
12247 assert(S
->getFlags() & Scope::DeclScope
&& "Invalid Scope.");
12249 if (SS
.isEmpty()) {
12250 Diag(Name
.getBeginLoc(), diag::err_using_requires_qualname
);
12254 switch (Name
.getKind()) {
12255 case UnqualifiedIdKind::IK_ImplicitSelfParam
:
12256 case UnqualifiedIdKind::IK_Identifier
:
12257 case UnqualifiedIdKind::IK_OperatorFunctionId
:
12258 case UnqualifiedIdKind::IK_LiteralOperatorId
:
12259 case UnqualifiedIdKind::IK_ConversionFunctionId
:
12262 case UnqualifiedIdKind::IK_ConstructorName
:
12263 case UnqualifiedIdKind::IK_ConstructorTemplateId
:
12264 // C++11 inheriting constructors.
12265 Diag(Name
.getBeginLoc(),
12266 getLangOpts().CPlusPlus11
12267 ? diag::warn_cxx98_compat_using_decl_constructor
12268 : diag::err_using_decl_constructor
)
12271 if (getLangOpts().CPlusPlus11
) break;
12275 case UnqualifiedIdKind::IK_DestructorName
:
12276 Diag(Name
.getBeginLoc(), diag::err_using_decl_destructor
) << SS
.getRange();
12279 case UnqualifiedIdKind::IK_TemplateId
:
12280 Diag(Name
.getBeginLoc(), diag::err_using_decl_template_id
)
12281 << SourceRange(Name
.TemplateId
->LAngleLoc
, Name
.TemplateId
->RAngleLoc
);
12284 case UnqualifiedIdKind::IK_DeductionGuideName
:
12285 llvm_unreachable("cannot parse qualified deduction guide name");
12288 DeclarationNameInfo TargetNameInfo
= GetNameFromUnqualifiedId(Name
);
12289 DeclarationName TargetName
= TargetNameInfo
.getName();
12293 // Warn about access declarations.
12294 if (UsingLoc
.isInvalid()) {
12295 Diag(Name
.getBeginLoc(), getLangOpts().CPlusPlus11
12296 ? diag::err_access_decl
12297 : diag::warn_access_decl_deprecated
)
12298 << FixItHint::CreateInsertion(SS
.getRange().getBegin(), "using ");
12301 if (EllipsisLoc
.isInvalid()) {
12302 if (DiagnoseUnexpandedParameterPack(SS
, UPPC_UsingDeclaration
) ||
12303 DiagnoseUnexpandedParameterPack(TargetNameInfo
, UPPC_UsingDeclaration
))
12306 if (!SS
.getScopeRep()->containsUnexpandedParameterPack() &&
12307 !TargetNameInfo
.containsUnexpandedParameterPack()) {
12308 Diag(EllipsisLoc
, diag::err_pack_expansion_without_parameter_packs
)
12309 << SourceRange(SS
.getBeginLoc(), TargetNameInfo
.getEndLoc());
12310 EllipsisLoc
= SourceLocation();
12315 BuildUsingDeclaration(S
, AS
, UsingLoc
, TypenameLoc
.isValid(), TypenameLoc
,
12316 SS
, TargetNameInfo
, EllipsisLoc
, AttrList
,
12317 /*IsInstantiation*/ false,
12318 AttrList
.hasAttribute(ParsedAttr::AT_UsingIfExists
));
12320 PushOnScopeChains(UD
, S
, /*AddToContext*/ false);
12325 Decl
*Sema::ActOnUsingEnumDeclaration(Scope
*S
, AccessSpecifier AS
,
12326 SourceLocation UsingLoc
,
12327 SourceLocation EnumLoc
,
12328 SourceLocation IdentLoc
,
12329 IdentifierInfo
&II
, CXXScopeSpec
*SS
) {
12330 assert(!SS
->isInvalid() && "ScopeSpec is invalid");
12331 TypeSourceInfo
*TSI
= nullptr;
12332 QualType EnumTy
= GetTypeFromParser(
12333 getTypeName(II
, IdentLoc
, S
, SS
, /*isClassName=*/false,
12334 /*HasTrailingDot=*/false,
12335 /*ObjectType=*/nullptr, /*IsCtorOrDtorName=*/false,
12336 /*WantNontrivialTypeSourceInfo=*/true),
12338 if (EnumTy
.isNull()) {
12339 Diag(IdentLoc
, SS
&& isDependentScopeSpecifier(*SS
)
12340 ? diag::err_using_enum_is_dependent
12341 : diag::err_unknown_typename
)
12343 << SourceRange(SS
? SS
->getBeginLoc() : IdentLoc
, IdentLoc
);
12347 auto *Enum
= dyn_cast_if_present
<EnumDecl
>(EnumTy
->getAsTagDecl());
12349 Diag(IdentLoc
, diag::err_using_enum_not_enum
) << EnumTy
;
12353 if (auto *Def
= Enum
->getDefinition())
12356 if (TSI
== nullptr)
12357 TSI
= Context
.getTrivialTypeSourceInfo(EnumTy
, IdentLoc
);
12360 BuildUsingEnumDeclaration(S
, AS
, UsingLoc
, EnumLoc
, IdentLoc
, TSI
, Enum
);
12363 PushOnScopeChains(UD
, S
, /*AddToContext*/ false);
12368 /// Determine whether a using declaration considers the given
12369 /// declarations as "equivalent", e.g., if they are redeclarations of
12370 /// the same entity or are both typedefs of the same type.
12372 IsEquivalentForUsingDecl(ASTContext
&Context
, NamedDecl
*D1
, NamedDecl
*D2
) {
12373 if (D1
->getCanonicalDecl() == D2
->getCanonicalDecl())
12376 if (TypedefNameDecl
*TD1
= dyn_cast
<TypedefNameDecl
>(D1
))
12377 if (TypedefNameDecl
*TD2
= dyn_cast
<TypedefNameDecl
>(D2
))
12378 return Context
.hasSameType(TD1
->getUnderlyingType(),
12379 TD2
->getUnderlyingType());
12381 // Two using_if_exists using-declarations are equivalent if both are
12383 if (isa
<UnresolvedUsingIfExistsDecl
>(D1
) &&
12384 isa
<UnresolvedUsingIfExistsDecl
>(D2
))
12391 /// Determines whether to create a using shadow decl for a particular
12392 /// decl, given the set of decls existing prior to this using lookup.
12393 bool Sema::CheckUsingShadowDecl(BaseUsingDecl
*BUD
, NamedDecl
*Orig
,
12394 const LookupResult
&Previous
,
12395 UsingShadowDecl
*&PrevShadow
) {
12396 // Diagnose finding a decl which is not from a base class of the
12397 // current class. We do this now because there are cases where this
12398 // function will silently decide not to build a shadow decl, which
12399 // will pre-empt further diagnostics.
12401 // We don't need to do this in C++11 because we do the check once on
12404 // FIXME: diagnose the following if we care enough:
12405 // struct A { int foo; };
12406 // struct B : A { using A::foo; };
12407 // template <class T> struct C : A {};
12408 // template <class T> struct D : C<T> { using B::foo; } // <---
12409 // This is invalid (during instantiation) in C++03 because B::foo
12410 // resolves to the using decl in B, which is not a base class of D<T>.
12411 // We can't diagnose it immediately because C<T> is an unknown
12412 // specialization. The UsingShadowDecl in D<T> then points directly
12413 // to A::foo, which will look well-formed when we instantiate.
12414 // The right solution is to not collapse the shadow-decl chain.
12415 if (!getLangOpts().CPlusPlus11
&& CurContext
->isRecord())
12416 if (auto *Using
= dyn_cast
<UsingDecl
>(BUD
)) {
12417 DeclContext
*OrigDC
= Orig
->getDeclContext();
12419 // Handle enums and anonymous structs.
12420 if (isa
<EnumDecl
>(OrigDC
))
12421 OrigDC
= OrigDC
->getParent();
12422 CXXRecordDecl
*OrigRec
= cast
<CXXRecordDecl
>(OrigDC
);
12423 while (OrigRec
->isAnonymousStructOrUnion())
12424 OrigRec
= cast
<CXXRecordDecl
>(OrigRec
->getDeclContext());
12426 if (cast
<CXXRecordDecl
>(CurContext
)->isProvablyNotDerivedFrom(OrigRec
)) {
12427 if (OrigDC
== CurContext
) {
12428 Diag(Using
->getLocation(),
12429 diag::err_using_decl_nested_name_specifier_is_current_class
)
12430 << Using
->getQualifierLoc().getSourceRange();
12431 Diag(Orig
->getLocation(), diag::note_using_decl_target
);
12432 Using
->setInvalidDecl();
12436 Diag(Using
->getQualifierLoc().getBeginLoc(),
12437 diag::err_using_decl_nested_name_specifier_is_not_base_class
)
12438 << Using
->getQualifier() << cast
<CXXRecordDecl
>(CurContext
)
12439 << Using
->getQualifierLoc().getSourceRange();
12440 Diag(Orig
->getLocation(), diag::note_using_decl_target
);
12441 Using
->setInvalidDecl();
12446 if (Previous
.empty()) return false;
12448 NamedDecl
*Target
= Orig
;
12449 if (isa
<UsingShadowDecl
>(Target
))
12450 Target
= cast
<UsingShadowDecl
>(Target
)->getTargetDecl();
12452 // If the target happens to be one of the previous declarations, we
12453 // don't have a conflict.
12455 // FIXME: but we might be increasing its access, in which case we
12456 // should redeclare it.
12457 NamedDecl
*NonTag
= nullptr, *Tag
= nullptr;
12458 bool FoundEquivalentDecl
= false;
12459 for (LookupResult::iterator I
= Previous
.begin(), E
= Previous
.end();
12461 NamedDecl
*D
= (*I
)->getUnderlyingDecl();
12462 // We can have UsingDecls in our Previous results because we use the same
12463 // LookupResult for checking whether the UsingDecl itself is a valid
12465 if (isa
<UsingDecl
>(D
) || isa
<UsingPackDecl
>(D
) || isa
<UsingEnumDecl
>(D
))
12468 if (auto *RD
= dyn_cast
<CXXRecordDecl
>(D
)) {
12469 // C++ [class.mem]p19:
12470 // If T is the name of a class, then [every named member other than
12471 // a non-static data member] shall have a name different from T
12472 if (RD
->isInjectedClassName() && !isa
<FieldDecl
>(Target
) &&
12473 !isa
<IndirectFieldDecl
>(Target
) &&
12474 !isa
<UnresolvedUsingValueDecl
>(Target
) &&
12475 DiagnoseClassNameShadow(
12477 DeclarationNameInfo(BUD
->getDeclName(), BUD
->getLocation())))
12481 if (IsEquivalentForUsingDecl(Context
, D
, Target
)) {
12482 if (UsingShadowDecl
*Shadow
= dyn_cast
<UsingShadowDecl
>(*I
))
12483 PrevShadow
= Shadow
;
12484 FoundEquivalentDecl
= true;
12485 } else if (isEquivalentInternalLinkageDeclaration(D
, Target
)) {
12486 // We don't conflict with an existing using shadow decl of an equivalent
12487 // declaration, but we're not a redeclaration of it.
12488 FoundEquivalentDecl
= true;
12492 (isa
<TagDecl
>(D
) ? Tag
: NonTag
) = D
;
12495 if (FoundEquivalentDecl
)
12498 // Always emit a diagnostic for a mismatch between an unresolved
12499 // using_if_exists and a resolved using declaration in either direction.
12500 if (isa
<UnresolvedUsingIfExistsDecl
>(Target
) !=
12501 (isa_and_nonnull
<UnresolvedUsingIfExistsDecl
>(NonTag
))) {
12502 if (!NonTag
&& !Tag
)
12504 Diag(BUD
->getLocation(), diag::err_using_decl_conflict
);
12505 Diag(Target
->getLocation(), diag::note_using_decl_target
);
12506 Diag((NonTag
? NonTag
: Tag
)->getLocation(),
12507 diag::note_using_decl_conflict
);
12508 BUD
->setInvalidDecl();
12512 if (FunctionDecl
*FD
= Target
->getAsFunction()) {
12513 NamedDecl
*OldDecl
= nullptr;
12514 switch (CheckOverload(nullptr, FD
, Previous
, OldDecl
,
12515 /*IsForUsingDecl*/ true)) {
12519 case Ovl_NonFunction
:
12520 Diag(BUD
->getLocation(), diag::err_using_decl_conflict
);
12523 // We found a decl with the exact signature.
12525 // If we're in a record, we want to hide the target, so we
12526 // return true (without a diagnostic) to tell the caller not to
12527 // build a shadow decl.
12528 if (CurContext
->isRecord())
12531 // If we're not in a record, this is an error.
12532 Diag(BUD
->getLocation(), diag::err_using_decl_conflict
);
12536 Diag(Target
->getLocation(), diag::note_using_decl_target
);
12537 Diag(OldDecl
->getLocation(), diag::note_using_decl_conflict
);
12538 BUD
->setInvalidDecl();
12542 // Target is not a function.
12544 if (isa
<TagDecl
>(Target
)) {
12545 // No conflict between a tag and a non-tag.
12546 if (!Tag
) return false;
12548 Diag(BUD
->getLocation(), diag::err_using_decl_conflict
);
12549 Diag(Target
->getLocation(), diag::note_using_decl_target
);
12550 Diag(Tag
->getLocation(), diag::note_using_decl_conflict
);
12551 BUD
->setInvalidDecl();
12555 // No conflict between a tag and a non-tag.
12556 if (!NonTag
) return false;
12558 Diag(BUD
->getLocation(), diag::err_using_decl_conflict
);
12559 Diag(Target
->getLocation(), diag::note_using_decl_target
);
12560 Diag(NonTag
->getLocation(), diag::note_using_decl_conflict
);
12561 BUD
->setInvalidDecl();
12565 /// Determine whether a direct base class is a virtual base class.
12566 static bool isVirtualDirectBase(CXXRecordDecl
*Derived
, CXXRecordDecl
*Base
) {
12567 if (!Derived
->getNumVBases())
12569 for (auto &B
: Derived
->bases())
12570 if (B
.getType()->getAsCXXRecordDecl() == Base
)
12571 return B
.isVirtual();
12572 llvm_unreachable("not a direct base class");
12575 /// Builds a shadow declaration corresponding to a 'using' declaration.
12576 UsingShadowDecl
*Sema::BuildUsingShadowDecl(Scope
*S
, BaseUsingDecl
*BUD
,
12578 UsingShadowDecl
*PrevDecl
) {
12579 // If we resolved to another shadow declaration, just coalesce them.
12580 NamedDecl
*Target
= Orig
;
12581 if (isa
<UsingShadowDecl
>(Target
)) {
12582 Target
= cast
<UsingShadowDecl
>(Target
)->getTargetDecl();
12583 assert(!isa
<UsingShadowDecl
>(Target
) && "nested shadow declaration");
12586 NamedDecl
*NonTemplateTarget
= Target
;
12587 if (auto *TargetTD
= dyn_cast
<TemplateDecl
>(Target
))
12588 NonTemplateTarget
= TargetTD
->getTemplatedDecl();
12590 UsingShadowDecl
*Shadow
;
12591 if (NonTemplateTarget
&& isa
<CXXConstructorDecl
>(NonTemplateTarget
)) {
12592 UsingDecl
*Using
= cast
<UsingDecl
>(BUD
);
12593 bool IsVirtualBase
=
12594 isVirtualDirectBase(cast
<CXXRecordDecl
>(CurContext
),
12595 Using
->getQualifier()->getAsRecordDecl());
12596 Shadow
= ConstructorUsingShadowDecl::Create(
12597 Context
, CurContext
, Using
->getLocation(), Using
, Orig
, IsVirtualBase
);
12599 Shadow
= UsingShadowDecl::Create(Context
, CurContext
, BUD
->getLocation(),
12600 Target
->getDeclName(), BUD
, Target
);
12602 BUD
->addShadowDecl(Shadow
);
12604 Shadow
->setAccess(BUD
->getAccess());
12605 if (Orig
->isInvalidDecl() || BUD
->isInvalidDecl())
12606 Shadow
->setInvalidDecl();
12608 Shadow
->setPreviousDecl(PrevDecl
);
12611 PushOnScopeChains(Shadow
, S
);
12613 CurContext
->addDecl(Shadow
);
12619 /// Hides a using shadow declaration. This is required by the current
12620 /// using-decl implementation when a resolvable using declaration in a
12621 /// class is followed by a declaration which would hide or override
12622 /// one or more of the using decl's targets; for example:
12624 /// struct Base { void foo(int); };
12625 /// struct Derived : Base {
12626 /// using Base::foo;
12630 /// The governing language is C++03 [namespace.udecl]p12:
12632 /// When a using-declaration brings names from a base class into a
12633 /// derived class scope, member functions in the derived class
12634 /// override and/or hide member functions with the same name and
12635 /// parameter types in a base class (rather than conflicting).
12637 /// There are two ways to implement this:
12638 /// (1) optimistically create shadow decls when they're not hidden
12639 /// by existing declarations, or
12640 /// (2) don't create any shadow decls (or at least don't make them
12641 /// visible) until we've fully parsed/instantiated the class.
12642 /// The problem with (1) is that we might have to retroactively remove
12643 /// a shadow decl, which requires several O(n) operations because the
12644 /// decl structures are (very reasonably) not designed for removal.
12645 /// (2) avoids this but is very fiddly and phase-dependent.
12646 void Sema::HideUsingShadowDecl(Scope
*S
, UsingShadowDecl
*Shadow
) {
12647 if (Shadow
->getDeclName().getNameKind() ==
12648 DeclarationName::CXXConversionFunctionName
)
12649 cast
<CXXRecordDecl
>(Shadow
->getDeclContext())->removeConversion(Shadow
);
12651 // Remove it from the DeclContext...
12652 Shadow
->getDeclContext()->removeDecl(Shadow
);
12654 // ...and the scope, if applicable...
12656 S
->RemoveDecl(Shadow
);
12657 IdResolver
.RemoveDecl(Shadow
);
12660 // ...and the using decl.
12661 Shadow
->getIntroducer()->removeShadowDecl(Shadow
);
12663 // TODO: complain somehow if Shadow was used. It shouldn't
12664 // be possible for this to happen, because...?
12667 /// Find the base specifier for a base class with the given type.
12668 static CXXBaseSpecifier
*findDirectBaseWithType(CXXRecordDecl
*Derived
,
12669 QualType DesiredBase
,
12670 bool &AnyDependentBases
) {
12671 // Check whether the named type is a direct base class.
12672 CanQualType CanonicalDesiredBase
= DesiredBase
->getCanonicalTypeUnqualified()
12673 .getUnqualifiedType();
12674 for (auto &Base
: Derived
->bases()) {
12675 CanQualType BaseType
= Base
.getType()->getCanonicalTypeUnqualified();
12676 if (CanonicalDesiredBase
== BaseType
)
12678 if (BaseType
->isDependentType())
12679 AnyDependentBases
= true;
12685 class UsingValidatorCCC final
: public CorrectionCandidateCallback
{
12687 UsingValidatorCCC(bool HasTypenameKeyword
, bool IsInstantiation
,
12688 NestedNameSpecifier
*NNS
, CXXRecordDecl
*RequireMemberOf
)
12689 : HasTypenameKeyword(HasTypenameKeyword
),
12690 IsInstantiation(IsInstantiation
), OldNNS(NNS
),
12691 RequireMemberOf(RequireMemberOf
) {}
12693 bool ValidateCandidate(const TypoCorrection
&Candidate
) override
{
12694 NamedDecl
*ND
= Candidate
.getCorrectionDecl();
12696 // Keywords are not valid here.
12697 if (!ND
|| isa
<NamespaceDecl
>(ND
))
12700 // Completely unqualified names are invalid for a 'using' declaration.
12701 if (Candidate
.WillReplaceSpecifier() && !Candidate
.getCorrectionSpecifier())
12704 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
12707 if (RequireMemberOf
) {
12708 auto *FoundRecord
= dyn_cast
<CXXRecordDecl
>(ND
);
12709 if (FoundRecord
&& FoundRecord
->isInjectedClassName()) {
12710 // No-one ever wants a using-declaration to name an injected-class-name
12711 // of a base class, unless they're declaring an inheriting constructor.
12712 ASTContext
&Ctx
= ND
->getASTContext();
12713 if (!Ctx
.getLangOpts().CPlusPlus11
)
12715 QualType FoundType
= Ctx
.getRecordType(FoundRecord
);
12717 // Check that the injected-class-name is named as a member of its own
12718 // type; we don't want to suggest 'using Derived::Base;', since that
12719 // means something else.
12720 NestedNameSpecifier
*Specifier
=
12721 Candidate
.WillReplaceSpecifier()
12722 ? Candidate
.getCorrectionSpecifier()
12724 if (!Specifier
->getAsType() ||
12725 !Ctx
.hasSameType(QualType(Specifier
->getAsType(), 0), FoundType
))
12728 // Check that this inheriting constructor declaration actually names a
12729 // direct base class of the current class.
12730 bool AnyDependentBases
= false;
12731 if (!findDirectBaseWithType(RequireMemberOf
,
12732 Ctx
.getRecordType(FoundRecord
),
12733 AnyDependentBases
) &&
12734 !AnyDependentBases
)
12737 auto *RD
= dyn_cast
<CXXRecordDecl
>(ND
->getDeclContext());
12738 if (!RD
|| RequireMemberOf
->isProvablyNotDerivedFrom(RD
))
12741 // FIXME: Check that the base class member is accessible?
12744 auto *FoundRecord
= dyn_cast
<CXXRecordDecl
>(ND
);
12745 if (FoundRecord
&& FoundRecord
->isInjectedClassName())
12749 if (isa
<TypeDecl
>(ND
))
12750 return HasTypenameKeyword
|| !IsInstantiation
;
12752 return !HasTypenameKeyword
;
12755 std::unique_ptr
<CorrectionCandidateCallback
> clone() override
{
12756 return std::make_unique
<UsingValidatorCCC
>(*this);
12760 bool HasTypenameKeyword
;
12761 bool IsInstantiation
;
12762 NestedNameSpecifier
*OldNNS
;
12763 CXXRecordDecl
*RequireMemberOf
;
12765 } // end anonymous namespace
12767 /// Remove decls we can't actually see from a lookup being used to declare
12768 /// shadow using decls.
12770 /// \param S - The scope of the potential shadow decl
12771 /// \param Previous - The lookup of a potential shadow decl's name.
12772 void Sema::FilterUsingLookup(Scope
*S
, LookupResult
&Previous
) {
12773 // It is really dumb that we have to do this.
12774 LookupResult::Filter F
= Previous
.makeFilter();
12775 while (F
.hasNext()) {
12776 NamedDecl
*D
= F
.next();
12777 if (!isDeclInScope(D
, CurContext
, S
))
12779 // If we found a local extern declaration that's not ordinarily visible,
12780 // and this declaration is being added to a non-block scope, ignore it.
12781 // We're only checking for scope conflicts here, not also for violations
12782 // of the linkage rules.
12783 else if (!CurContext
->isFunctionOrMethod() && D
->isLocalExternDecl() &&
12784 !(D
->getIdentifierNamespace() & Decl::IDNS_Ordinary
))
12790 /// Builds a using declaration.
12792 /// \param IsInstantiation - Whether this call arises from an
12793 /// instantiation of an unresolved using declaration. We treat
12794 /// the lookup differently for these declarations.
12795 NamedDecl
*Sema::BuildUsingDeclaration(
12796 Scope
*S
, AccessSpecifier AS
, SourceLocation UsingLoc
,
12797 bool HasTypenameKeyword
, SourceLocation TypenameLoc
, CXXScopeSpec
&SS
,
12798 DeclarationNameInfo NameInfo
, SourceLocation EllipsisLoc
,
12799 const ParsedAttributesView
&AttrList
, bool IsInstantiation
,
12800 bool IsUsingIfExists
) {
12801 assert(!SS
.isInvalid() && "Invalid CXXScopeSpec.");
12802 SourceLocation IdentLoc
= NameInfo
.getLoc();
12803 assert(IdentLoc
.isValid() && "Invalid TargetName location.");
12805 // FIXME: We ignore attributes for now.
12807 // For an inheriting constructor declaration, the name of the using
12808 // declaration is the name of a constructor in this class, not in the
12810 DeclarationNameInfo UsingName
= NameInfo
;
12811 if (UsingName
.getName().getNameKind() == DeclarationName::CXXConstructorName
)
12812 if (auto *RD
= dyn_cast
<CXXRecordDecl
>(CurContext
))
12813 UsingName
.setName(Context
.DeclarationNames
.getCXXConstructorName(
12814 Context
.getCanonicalType(Context
.getRecordType(RD
))));
12816 // Do the redeclaration lookup in the current scope.
12817 LookupResult
Previous(*this, UsingName
, LookupUsingDeclName
,
12818 ForVisibleRedeclaration
);
12819 Previous
.setHideTags(false);
12821 LookupName(Previous
, S
);
12823 FilterUsingLookup(S
, Previous
);
12825 assert(IsInstantiation
&& "no scope in non-instantiation");
12826 if (CurContext
->isRecord())
12827 LookupQualifiedName(Previous
, CurContext
);
12829 // No redeclaration check is needed here; in non-member contexts we
12830 // diagnosed all possible conflicts with other using-declarations when
12831 // building the template:
12833 // For a dependent non-type using declaration, the only valid case is
12834 // if we instantiate to a single enumerator. We check for conflicts
12835 // between shadow declarations we introduce, and we check in the template
12836 // definition for conflicts between a non-type using declaration and any
12837 // other declaration, which together covers all cases.
12839 // A dependent typename using declaration will never successfully
12840 // instantiate, since it will always name a class member, so we reject
12841 // that in the template definition.
12845 // Check for invalid redeclarations.
12846 if (CheckUsingDeclRedeclaration(UsingLoc
, HasTypenameKeyword
,
12847 SS
, IdentLoc
, Previous
))
12850 // 'using_if_exists' doesn't make sense on an inherited constructor.
12851 if (IsUsingIfExists
&& UsingName
.getName().getNameKind() ==
12852 DeclarationName::CXXConstructorName
) {
12853 Diag(UsingLoc
, diag::err_using_if_exists_on_ctor
);
12857 DeclContext
*LookupContext
= computeDeclContext(SS
);
12858 NestedNameSpecifierLoc QualifierLoc
= SS
.getWithLocInContext(Context
);
12859 if (!LookupContext
|| EllipsisLoc
.isValid()) {
12861 // Dependent scope, or an unexpanded pack
12862 if (!LookupContext
&& CheckUsingDeclQualifier(UsingLoc
, HasTypenameKeyword
,
12863 SS
, NameInfo
, IdentLoc
))
12866 if (HasTypenameKeyword
) {
12867 // FIXME: not all declaration name kinds are legal here
12868 D
= UnresolvedUsingTypenameDecl::Create(Context
, CurContext
,
12869 UsingLoc
, TypenameLoc
,
12871 IdentLoc
, NameInfo
.getName(),
12874 D
= UnresolvedUsingValueDecl::Create(Context
, CurContext
, UsingLoc
,
12875 QualifierLoc
, NameInfo
, EllipsisLoc
);
12878 CurContext
->addDecl(D
);
12879 ProcessDeclAttributeList(S
, D
, AttrList
);
12883 auto Build
= [&](bool Invalid
) {
12885 UsingDecl::Create(Context
, CurContext
, UsingLoc
, QualifierLoc
,
12886 UsingName
, HasTypenameKeyword
);
12888 CurContext
->addDecl(UD
);
12889 ProcessDeclAttributeList(S
, UD
, AttrList
);
12890 UD
->setInvalidDecl(Invalid
);
12893 auto BuildInvalid
= [&]{ return Build(true); };
12894 auto BuildValid
= [&]{ return Build(false); };
12896 if (RequireCompleteDeclContext(SS
, LookupContext
))
12897 return BuildInvalid();
12899 // Look up the target name.
12900 LookupResult
R(*this, NameInfo
, LookupOrdinaryName
);
12902 // Unlike most lookups, we don't always want to hide tag
12903 // declarations: tag names are visible through the using declaration
12904 // even if hidden by ordinary names, *except* in a dependent context
12905 // where they may be used by two-phase lookup.
12906 if (!IsInstantiation
)
12907 R
.setHideTags(false);
12909 // For the purposes of this lookup, we have a base object type
12910 // equal to that of the current context.
12911 if (CurContext
->isRecord()) {
12912 R
.setBaseObjectType(
12913 Context
.getTypeDeclType(cast
<CXXRecordDecl
>(CurContext
)));
12916 LookupQualifiedName(R
, LookupContext
);
12918 // Validate the context, now we have a lookup
12919 if (CheckUsingDeclQualifier(UsingLoc
, HasTypenameKeyword
, SS
, NameInfo
,
12923 if (R
.empty() && IsUsingIfExists
)
12924 R
.addDecl(UnresolvedUsingIfExistsDecl::Create(Context
, CurContext
, UsingLoc
,
12925 UsingName
.getName()),
12928 // Try to correct typos if possible. If constructor name lookup finds no
12929 // results, that means the named class has no explicit constructors, and we
12930 // suppressed declaring implicit ones (probably because it's dependent or
12933 NameInfo
.getName().getNameKind() != DeclarationName::CXXConstructorName
) {
12934 // HACK 2017-01-08: Work around an issue with libstdc++'s detection of
12935 // ::gets. Sometimes it believes that glibc provides a ::gets in cases where
12936 // it does not. The issue was fixed in libstdc++ 6.3 (2016-12-21) and later.
12937 auto *II
= NameInfo
.getName().getAsIdentifierInfo();
12938 if (getLangOpts().CPlusPlus14
&& II
&& II
->isStr("gets") &&
12939 CurContext
->isStdNamespace() &&
12940 isa
<TranslationUnitDecl
>(LookupContext
) &&
12941 getSourceManager().isInSystemHeader(UsingLoc
))
12943 UsingValidatorCCC
CCC(HasTypenameKeyword
, IsInstantiation
, SS
.getScopeRep(),
12944 dyn_cast
<CXXRecordDecl
>(CurContext
));
12945 if (TypoCorrection Corrected
=
12946 CorrectTypo(R
.getLookupNameInfo(), R
.getLookupKind(), S
, &SS
, CCC
,
12947 CTK_ErrorRecovery
)) {
12948 // We reject candidates where DroppedSpecifier == true, hence the
12949 // literal '0' below.
12950 diagnoseTypo(Corrected
, PDiag(diag::err_no_member_suggest
)
12951 << NameInfo
.getName() << LookupContext
<< 0
12954 // If we picked a correction with no attached Decl we can't do anything
12955 // useful with it, bail out.
12956 NamedDecl
*ND
= Corrected
.getCorrectionDecl();
12958 return BuildInvalid();
12960 // If we corrected to an inheriting constructor, handle it as one.
12961 auto *RD
= dyn_cast
<CXXRecordDecl
>(ND
);
12962 if (RD
&& RD
->isInjectedClassName()) {
12963 // The parent of the injected class name is the class itself.
12964 RD
= cast
<CXXRecordDecl
>(RD
->getParent());
12966 // Fix up the information we'll use to build the using declaration.
12967 if (Corrected
.WillReplaceSpecifier()) {
12968 NestedNameSpecifierLocBuilder Builder
;
12969 Builder
.MakeTrivial(Context
, Corrected
.getCorrectionSpecifier(),
12970 QualifierLoc
.getSourceRange());
12971 QualifierLoc
= Builder
.getWithLocInContext(Context
);
12974 // In this case, the name we introduce is the name of a derived class
12976 auto *CurClass
= cast
<CXXRecordDecl
>(CurContext
);
12977 UsingName
.setName(Context
.DeclarationNames
.getCXXConstructorName(
12978 Context
.getCanonicalType(Context
.getRecordType(CurClass
))));
12979 UsingName
.setNamedTypeInfo(nullptr);
12980 for (auto *Ctor
: LookupConstructors(RD
))
12984 // FIXME: Pick up all the declarations if we found an overloaded
12986 UsingName
.setName(ND
->getDeclName());
12990 Diag(IdentLoc
, diag::err_no_member
)
12991 << NameInfo
.getName() << LookupContext
<< SS
.getRange();
12992 return BuildInvalid();
12996 if (R
.isAmbiguous())
12997 return BuildInvalid();
12999 if (HasTypenameKeyword
) {
13000 // If we asked for a typename and got a non-type decl, error out.
13001 if (!R
.getAsSingle
<TypeDecl
>() &&
13002 !R
.getAsSingle
<UnresolvedUsingIfExistsDecl
>()) {
13003 Diag(IdentLoc
, diag::err_using_typename_non_type
);
13004 for (LookupResult::iterator I
= R
.begin(), E
= R
.end(); I
!= E
; ++I
)
13005 Diag((*I
)->getUnderlyingDecl()->getLocation(),
13006 diag::note_using_decl_target
);
13007 return BuildInvalid();
13010 // If we asked for a non-typename and we got a type, error out,
13011 // but only if this is an instantiation of an unresolved using
13012 // decl. Otherwise just silently find the type name.
13013 if (IsInstantiation
&& R
.getAsSingle
<TypeDecl
>()) {
13014 Diag(IdentLoc
, diag::err_using_dependent_value_is_type
);
13015 Diag(R
.getFoundDecl()->getLocation(), diag::note_using_decl_target
);
13016 return BuildInvalid();
13020 // C++14 [namespace.udecl]p6:
13021 // A using-declaration shall not name a namespace.
13022 if (R
.getAsSingle
<NamespaceDecl
>()) {
13023 Diag(IdentLoc
, diag::err_using_decl_can_not_refer_to_namespace
)
13025 return BuildInvalid();
13028 UsingDecl
*UD
= BuildValid();
13030 // Some additional rules apply to inheriting constructors.
13031 if (UsingName
.getName().getNameKind() ==
13032 DeclarationName::CXXConstructorName
) {
13033 // Suppress access diagnostics; the access check is instead performed at the
13034 // point of use for an inheriting constructor.
13035 R
.suppressDiagnostics();
13036 if (CheckInheritingConstructorUsingDecl(UD
))
13040 for (LookupResult::iterator I
= R
.begin(), E
= R
.end(); I
!= E
; ++I
) {
13041 UsingShadowDecl
*PrevDecl
= nullptr;
13042 if (!CheckUsingShadowDecl(UD
, *I
, Previous
, PrevDecl
))
13043 BuildUsingShadowDecl(S
, UD
, *I
, PrevDecl
);
13049 NamedDecl
*Sema::BuildUsingEnumDeclaration(Scope
*S
, AccessSpecifier AS
,
13050 SourceLocation UsingLoc
,
13051 SourceLocation EnumLoc
,
13052 SourceLocation NameLoc
,
13053 TypeSourceInfo
*EnumType
,
13055 bool Invalid
= false;
13057 if (CurContext
->getRedeclContext()->isRecord()) {
13058 /// In class scope, check if this is a duplicate, for better a diagnostic.
13059 DeclarationNameInfo
UsingEnumName(ED
->getDeclName(), NameLoc
);
13060 LookupResult
Previous(*this, UsingEnumName
, LookupUsingDeclName
,
13061 ForVisibleRedeclaration
);
13063 LookupName(Previous
, S
);
13065 for (NamedDecl
*D
: Previous
)
13066 if (UsingEnumDecl
*UED
= dyn_cast
<UsingEnumDecl
>(D
))
13067 if (UED
->getEnumDecl() == ED
) {
13068 Diag(UsingLoc
, diag::err_using_enum_decl_redeclaration
)
13069 << SourceRange(EnumLoc
, NameLoc
);
13070 Diag(D
->getLocation(), diag::note_using_enum_decl
) << 1;
13076 if (RequireCompleteEnumDecl(ED
, NameLoc
))
13079 UsingEnumDecl
*UD
= UsingEnumDecl::Create(Context
, CurContext
, UsingLoc
,
13080 EnumLoc
, NameLoc
, EnumType
);
13082 CurContext
->addDecl(UD
);
13085 UD
->setInvalidDecl();
13089 // Create the shadow decls for each enumerator
13090 for (EnumConstantDecl
*EC
: ED
->enumerators()) {
13091 UsingShadowDecl
*PrevDecl
= nullptr;
13092 DeclarationNameInfo
DNI(EC
->getDeclName(), EC
->getLocation());
13093 LookupResult
Previous(*this, DNI
, LookupOrdinaryName
,
13094 ForVisibleRedeclaration
);
13095 LookupName(Previous
, S
);
13096 FilterUsingLookup(S
, Previous
);
13098 if (!CheckUsingShadowDecl(UD
, EC
, Previous
, PrevDecl
))
13099 BuildUsingShadowDecl(S
, UD
, EC
, PrevDecl
);
13105 NamedDecl
*Sema::BuildUsingPackDecl(NamedDecl
*InstantiatedFrom
,
13106 ArrayRef
<NamedDecl
*> Expansions
) {
13107 assert(isa
<UnresolvedUsingValueDecl
>(InstantiatedFrom
) ||
13108 isa
<UnresolvedUsingTypenameDecl
>(InstantiatedFrom
) ||
13109 isa
<UsingPackDecl
>(InstantiatedFrom
));
13112 UsingPackDecl::Create(Context
, CurContext
, InstantiatedFrom
, Expansions
);
13113 UPD
->setAccess(InstantiatedFrom
->getAccess());
13114 CurContext
->addDecl(UPD
);
13118 /// Additional checks for a using declaration referring to a constructor name.
13119 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl
*UD
) {
13120 assert(!UD
->hasTypename() && "expecting a constructor name");
13122 const Type
*SourceType
= UD
->getQualifier()->getAsType();
13123 assert(SourceType
&&
13124 "Using decl naming constructor doesn't have type in scope spec.");
13125 CXXRecordDecl
*TargetClass
= cast
<CXXRecordDecl
>(CurContext
);
13127 // Check whether the named type is a direct base class.
13128 bool AnyDependentBases
= false;
13129 auto *Base
= findDirectBaseWithType(TargetClass
, QualType(SourceType
, 0),
13130 AnyDependentBases
);
13131 if (!Base
&& !AnyDependentBases
) {
13132 Diag(UD
->getUsingLoc(),
13133 diag::err_using_decl_constructor_not_in_direct_base
)
13134 << UD
->getNameInfo().getSourceRange()
13135 << QualType(SourceType
, 0) << TargetClass
;
13136 UD
->setInvalidDecl();
13141 Base
->setInheritConstructors();
13146 /// Checks that the given using declaration is not an invalid
13147 /// redeclaration. Note that this is checking only for the using decl
13148 /// itself, not for any ill-formedness among the UsingShadowDecls.
13149 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc
,
13150 bool HasTypenameKeyword
,
13151 const CXXScopeSpec
&SS
,
13152 SourceLocation NameLoc
,
13153 const LookupResult
&Prev
) {
13154 NestedNameSpecifier
*Qual
= SS
.getScopeRep();
13156 // C++03 [namespace.udecl]p8:
13157 // C++0x [namespace.udecl]p10:
13158 // A using-declaration is a declaration and can therefore be used
13159 // repeatedly where (and only where) multiple declarations are
13162 // That's in non-member contexts.
13163 if (!CurContext
->getRedeclContext()->isRecord()) {
13164 // A dependent qualifier outside a class can only ever resolve to an
13165 // enumeration type. Therefore it conflicts with any other non-type
13166 // declaration in the same scope.
13167 // FIXME: How should we check for dependent type-type conflicts at block
13169 if (Qual
->isDependent() && !HasTypenameKeyword
) {
13170 for (auto *D
: Prev
) {
13171 if (!isa
<TypeDecl
>(D
) && !isa
<UsingDecl
>(D
) && !isa
<UsingPackDecl
>(D
)) {
13172 bool OldCouldBeEnumerator
=
13173 isa
<UnresolvedUsingValueDecl
>(D
) || isa
<EnumConstantDecl
>(D
);
13175 OldCouldBeEnumerator
? diag::err_redefinition
13176 : diag::err_redefinition_different_kind
)
13177 << Prev
.getLookupName();
13178 Diag(D
->getLocation(), diag::note_previous_definition
);
13186 const NestedNameSpecifier
*CNNS
=
13187 Context
.getCanonicalNestedNameSpecifier(Qual
);
13188 for (LookupResult::iterator I
= Prev
.begin(), E
= Prev
.end(); I
!= E
; ++I
) {
13192 NestedNameSpecifier
*DQual
;
13193 if (UsingDecl
*UD
= dyn_cast
<UsingDecl
>(D
)) {
13194 DTypename
= UD
->hasTypename();
13195 DQual
= UD
->getQualifier();
13196 } else if (UnresolvedUsingValueDecl
*UD
13197 = dyn_cast
<UnresolvedUsingValueDecl
>(D
)) {
13199 DQual
= UD
->getQualifier();
13200 } else if (UnresolvedUsingTypenameDecl
*UD
13201 = dyn_cast
<UnresolvedUsingTypenameDecl
>(D
)) {
13203 DQual
= UD
->getQualifier();
13206 // using decls differ if one says 'typename' and the other doesn't.
13207 // FIXME: non-dependent using decls?
13208 if (HasTypenameKeyword
!= DTypename
) continue;
13210 // using decls differ if they name different scopes (but note that
13211 // template instantiation can cause this check to trigger when it
13212 // didn't before instantiation).
13213 if (CNNS
!= Context
.getCanonicalNestedNameSpecifier(DQual
))
13216 Diag(NameLoc
, diag::err_using_decl_redeclaration
) << SS
.getRange();
13217 Diag(D
->getLocation(), diag::note_using_decl
) << 1;
13224 /// Checks that the given nested-name qualifier used in a using decl
13225 /// in the current context is appropriately related to the current
13226 /// scope. If an error is found, diagnoses it and returns true.
13227 /// R is nullptr, if the caller has not (yet) done a lookup, otherwise it's the
13228 /// result of that lookup. UD is likewise nullptr, except when we have an
13229 /// already-populated UsingDecl whose shadow decls contain the same information
13230 /// (i.e. we're instantiating a UsingDecl with non-dependent scope).
13231 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc
, bool HasTypename
,
13232 const CXXScopeSpec
&SS
,
13233 const DeclarationNameInfo
&NameInfo
,
13234 SourceLocation NameLoc
,
13235 const LookupResult
*R
, const UsingDecl
*UD
) {
13236 DeclContext
*NamedContext
= computeDeclContext(SS
);
13237 assert(bool(NamedContext
) == (R
|| UD
) && !(R
&& UD
) &&
13238 "resolvable context must have exactly one set of decls");
13240 // C++ 20 permits using an enumerator that does not have a class-hierarchy
13242 bool Cxx20Enumerator
= false;
13243 if (NamedContext
) {
13244 EnumConstantDecl
*EC
= nullptr;
13246 EC
= R
->getAsSingle
<EnumConstantDecl
>();
13247 else if (UD
&& UD
->shadow_size() == 1)
13248 EC
= dyn_cast
<EnumConstantDecl
>(UD
->shadow_begin()->getTargetDecl());
13250 Cxx20Enumerator
= getLangOpts().CPlusPlus20
;
13252 if (auto *ED
= dyn_cast
<EnumDecl
>(NamedContext
)) {
13253 // C++14 [namespace.udecl]p7:
13254 // A using-declaration shall not name a scoped enumerator.
13255 // C++20 p1099 permits enumerators.
13256 if (EC
&& R
&& ED
->isScoped())
13257 Diag(SS
.getBeginLoc(),
13258 getLangOpts().CPlusPlus20
13259 ? diag::warn_cxx17_compat_using_decl_scoped_enumerator
13260 : diag::ext_using_decl_scoped_enumerator
)
13263 // We want to consider the scope of the enumerator
13264 NamedContext
= ED
->getDeclContext();
13268 if (!CurContext
->isRecord()) {
13269 // C++03 [namespace.udecl]p3:
13270 // C++0x [namespace.udecl]p8:
13271 // A using-declaration for a class member shall be a member-declaration.
13272 // C++20 [namespace.udecl]p7
13273 // ... other than an enumerator ...
13275 // If we weren't able to compute a valid scope, it might validly be a
13276 // dependent class or enumeration scope. If we have a 'typename' keyword,
13277 // the scope must resolve to a class type.
13278 if (NamedContext
? !NamedContext
->getRedeclContext()->isRecord()
13280 return false; // OK
13284 ? diag::warn_cxx17_compat_using_decl_class_member_enumerator
13285 : diag::err_using_decl_can_not_refer_to_class_member
)
13288 if (Cxx20Enumerator
)
13289 return false; // OK
13291 auto *RD
= NamedContext
13292 ? cast
<CXXRecordDecl
>(NamedContext
->getRedeclContext())
13294 if (RD
&& !RequireCompleteDeclContext(const_cast<CXXScopeSpec
&>(SS
), RD
)) {
13295 // See if there's a helpful fixit
13298 // We will have already diagnosed the problem on the template
13299 // definition, Maybe we should do so again?
13300 } else if (R
->getAsSingle
<TypeDecl
>()) {
13301 if (getLangOpts().CPlusPlus11
) {
13302 // Convert 'using X::Y;' to 'using Y = X::Y;'.
13303 Diag(SS
.getBeginLoc(), diag::note_using_decl_class_member_workaround
)
13304 << 0 // alias declaration
13305 << FixItHint::CreateInsertion(SS
.getBeginLoc(),
13306 NameInfo
.getName().getAsString() +
13309 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
13310 SourceLocation InsertLoc
= getLocForEndOfToken(NameInfo
.getEndLoc());
13311 Diag(InsertLoc
, diag::note_using_decl_class_member_workaround
)
13312 << 1 // typedef declaration
13313 << FixItHint::CreateReplacement(UsingLoc
, "typedef")
13314 << FixItHint::CreateInsertion(
13315 InsertLoc
, " " + NameInfo
.getName().getAsString());
13317 } else if (R
->getAsSingle
<VarDecl
>()) {
13318 // Don't provide a fixit outside C++11 mode; we don't want to suggest
13319 // repeating the type of the static data member here.
13321 if (getLangOpts().CPlusPlus11
) {
13322 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
13323 FixIt
= FixItHint::CreateReplacement(
13324 UsingLoc
, "auto &" + NameInfo
.getName().getAsString() + " = ");
13327 Diag(UsingLoc
, diag::note_using_decl_class_member_workaround
)
13328 << 2 // reference declaration
13330 } else if (R
->getAsSingle
<EnumConstantDecl
>()) {
13331 // Don't provide a fixit outside C++11 mode; we don't want to suggest
13332 // repeating the type of the enumeration here, and we can't do so if
13333 // the type is anonymous.
13335 if (getLangOpts().CPlusPlus11
) {
13336 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
13337 FixIt
= FixItHint::CreateReplacement(
13339 "constexpr auto " + NameInfo
.getName().getAsString() + " = ");
13342 Diag(UsingLoc
, diag::note_using_decl_class_member_workaround
)
13343 << (getLangOpts().CPlusPlus11
? 4 : 3) // const[expr] variable
13348 return true; // Fail
13351 // If the named context is dependent, we can't decide much.
13352 if (!NamedContext
) {
13353 // FIXME: in C++0x, we can diagnose if we can prove that the
13354 // nested-name-specifier does not refer to a base class, which is
13355 // still possible in some cases.
13357 // Otherwise we have to conservatively report that things might be
13362 // The current scope is a record.
13363 if (!NamedContext
->isRecord()) {
13364 // Ideally this would point at the last name in the specifier,
13365 // but we don't have that level of source info.
13366 Diag(SS
.getBeginLoc(),
13368 ? diag::warn_cxx17_compat_using_decl_non_member_enumerator
13369 : diag::err_using_decl_nested_name_specifier_is_not_class
)
13370 << SS
.getScopeRep() << SS
.getRange();
13372 if (Cxx20Enumerator
)
13373 return false; // OK
13378 if (!NamedContext
->isDependentContext() &&
13379 RequireCompleteDeclContext(const_cast<CXXScopeSpec
&>(SS
), NamedContext
))
13382 if (getLangOpts().CPlusPlus11
) {
13383 // C++11 [namespace.udecl]p3:
13384 // In a using-declaration used as a member-declaration, the
13385 // nested-name-specifier shall name a base class of the class
13388 if (cast
<CXXRecordDecl
>(CurContext
)->isProvablyNotDerivedFrom(
13389 cast
<CXXRecordDecl
>(NamedContext
))) {
13391 if (Cxx20Enumerator
) {
13392 Diag(NameLoc
, diag::warn_cxx17_compat_using_decl_non_member_enumerator
)
13397 if (CurContext
== NamedContext
) {
13398 Diag(SS
.getBeginLoc(),
13399 diag::err_using_decl_nested_name_specifier_is_current_class
)
13401 return !getLangOpts().CPlusPlus20
;
13404 if (!cast
<CXXRecordDecl
>(NamedContext
)->isInvalidDecl()) {
13405 Diag(SS
.getBeginLoc(),
13406 diag::err_using_decl_nested_name_specifier_is_not_base_class
)
13407 << SS
.getScopeRep() << cast
<CXXRecordDecl
>(CurContext
)
13416 // C++03 [namespace.udecl]p4:
13417 // A using-declaration used as a member-declaration shall refer
13418 // to a member of a base class of the class being defined [etc.].
13420 // Salient point: SS doesn't have to name a base class as long as
13421 // lookup only finds members from base classes. Therefore we can
13422 // diagnose here only if we can prove that can't happen,
13423 // i.e. if the class hierarchies provably don't intersect.
13425 // TODO: it would be nice if "definitely valid" results were cached
13426 // in the UsingDecl and UsingShadowDecl so that these checks didn't
13427 // need to be repeated.
13429 llvm::SmallPtrSet
<const CXXRecordDecl
*, 4> Bases
;
13430 auto Collect
= [&Bases
](const CXXRecordDecl
*Base
) {
13431 Bases
.insert(Base
);
13435 // Collect all bases. Return false if we find a dependent base.
13436 if (!cast
<CXXRecordDecl
>(CurContext
)->forallBases(Collect
))
13439 // Returns true if the base is dependent or is one of the accumulated base
13441 auto IsNotBase
= [&Bases
](const CXXRecordDecl
*Base
) {
13442 return !Bases
.count(Base
);
13445 // Return false if the class has a dependent base or if it or one
13446 // of its bases is present in the base set of the current context.
13447 if (Bases
.count(cast
<CXXRecordDecl
>(NamedContext
)) ||
13448 !cast
<CXXRecordDecl
>(NamedContext
)->forallBases(IsNotBase
))
13451 Diag(SS
.getRange().getBegin(),
13452 diag::err_using_decl_nested_name_specifier_is_not_base_class
)
13453 << SS
.getScopeRep()
13454 << cast
<CXXRecordDecl
>(CurContext
)
13460 Decl
*Sema::ActOnAliasDeclaration(Scope
*S
, AccessSpecifier AS
,
13461 MultiTemplateParamsArg TemplateParamLists
,
13462 SourceLocation UsingLoc
, UnqualifiedId
&Name
,
13463 const ParsedAttributesView
&AttrList
,
13464 TypeResult Type
, Decl
*DeclFromDeclSpec
) {
13465 // Skip up to the relevant declaration scope.
13466 while (S
->isTemplateParamScope())
13467 S
= S
->getParent();
13468 assert((S
->getFlags() & Scope::DeclScope
) &&
13469 "got alias-declaration outside of declaration scope");
13471 if (Type
.isInvalid())
13474 bool Invalid
= false;
13475 DeclarationNameInfo NameInfo
= GetNameFromUnqualifiedId(Name
);
13476 TypeSourceInfo
*TInfo
= nullptr;
13477 GetTypeFromParser(Type
.get(), &TInfo
);
13479 if (DiagnoseClassNameShadow(CurContext
, NameInfo
))
13482 if (DiagnoseUnexpandedParameterPack(Name
.StartLocation
, TInfo
,
13483 UPPC_DeclarationType
)) {
13485 TInfo
= Context
.getTrivialTypeSourceInfo(Context
.IntTy
,
13486 TInfo
->getTypeLoc().getBeginLoc());
13489 LookupResult
Previous(*this, NameInfo
, LookupOrdinaryName
,
13490 TemplateParamLists
.size()
13491 ? forRedeclarationInCurContext()
13492 : ForVisibleRedeclaration
);
13493 LookupName(Previous
, S
);
13495 // Warn about shadowing the name of a template parameter.
13496 if (Previous
.isSingleResult() &&
13497 Previous
.getFoundDecl()->isTemplateParameter()) {
13498 DiagnoseTemplateParameterShadow(Name
.StartLocation
,Previous
.getFoundDecl());
13502 assert(Name
.getKind() == UnqualifiedIdKind::IK_Identifier
&&
13503 "name in alias declaration must be an identifier");
13504 TypeAliasDecl
*NewTD
= TypeAliasDecl::Create(Context
, CurContext
, UsingLoc
,
13505 Name
.StartLocation
,
13506 Name
.Identifier
, TInfo
);
13508 NewTD
->setAccess(AS
);
13511 NewTD
->setInvalidDecl();
13513 ProcessDeclAttributeList(S
, NewTD
, AttrList
);
13514 AddPragmaAttributes(S
, NewTD
);
13516 CheckTypedefForVariablyModifiedType(S
, NewTD
);
13517 Invalid
|= NewTD
->isInvalidDecl();
13519 bool Redeclaration
= false;
13522 if (TemplateParamLists
.size()) {
13523 TypeAliasTemplateDecl
*OldDecl
= nullptr;
13524 TemplateParameterList
*OldTemplateParams
= nullptr;
13526 if (TemplateParamLists
.size() != 1) {
13527 Diag(UsingLoc
, diag::err_alias_template_extra_headers
)
13528 << SourceRange(TemplateParamLists
[1]->getTemplateLoc(),
13529 TemplateParamLists
[TemplateParamLists
.size()-1]->getRAngleLoc());
13531 TemplateParameterList
*TemplateParams
= TemplateParamLists
[0];
13533 // Check that we can declare a template here.
13534 if (CheckTemplateDeclScope(S
, TemplateParams
))
13537 // Only consider previous declarations in the same scope.
13538 FilterLookupForScope(Previous
, CurContext
, S
, /*ConsiderLinkage*/false,
13539 /*ExplicitInstantiationOrSpecialization*/false);
13540 if (!Previous
.empty()) {
13541 Redeclaration
= true;
13543 OldDecl
= Previous
.getAsSingle
<TypeAliasTemplateDecl
>();
13544 if (!OldDecl
&& !Invalid
) {
13545 Diag(UsingLoc
, diag::err_redefinition_different_kind
)
13546 << Name
.Identifier
;
13548 NamedDecl
*OldD
= Previous
.getRepresentativeDecl();
13549 if (OldD
->getLocation().isValid())
13550 Diag(OldD
->getLocation(), diag::note_previous_definition
);
13555 if (!Invalid
&& OldDecl
&& !OldDecl
->isInvalidDecl()) {
13556 if (TemplateParameterListsAreEqual(TemplateParams
,
13557 OldDecl
->getTemplateParameters(),
13559 TPL_TemplateMatch
))
13560 OldTemplateParams
=
13561 OldDecl
->getMostRecentDecl()->getTemplateParameters();
13565 TypeAliasDecl
*OldTD
= OldDecl
->getTemplatedDecl();
13567 !Context
.hasSameType(OldTD
->getUnderlyingType(),
13568 NewTD
->getUnderlyingType())) {
13569 // FIXME: The C++0x standard does not clearly say this is ill-formed,
13570 // but we can't reasonably accept it.
13571 Diag(NewTD
->getLocation(), diag::err_redefinition_different_typedef
)
13572 << 2 << NewTD
->getUnderlyingType() << OldTD
->getUnderlyingType();
13573 if (OldTD
->getLocation().isValid())
13574 Diag(OldTD
->getLocation(), diag::note_previous_definition
);
13580 // Merge any previous default template arguments into our parameters,
13581 // and check the parameter list.
13582 if (CheckTemplateParameterList(TemplateParams
, OldTemplateParams
,
13583 TPC_TypeAliasTemplate
))
13586 TypeAliasTemplateDecl
*NewDecl
=
13587 TypeAliasTemplateDecl::Create(Context
, CurContext
, UsingLoc
,
13588 Name
.Identifier
, TemplateParams
,
13590 NewTD
->setDescribedAliasTemplate(NewDecl
);
13592 NewDecl
->setAccess(AS
);
13595 NewDecl
->setInvalidDecl();
13596 else if (OldDecl
) {
13597 NewDecl
->setPreviousDecl(OldDecl
);
13598 CheckRedeclarationInModule(NewDecl
, OldDecl
);
13603 if (auto *TD
= dyn_cast_or_null
<TagDecl
>(DeclFromDeclSpec
)) {
13604 setTagNameForLinkagePurposes(TD
, NewTD
);
13605 handleTagNumbering(TD
, S
);
13607 ActOnTypedefNameDecl(S
, CurContext
, NewTD
, Previous
, Redeclaration
);
13611 PushOnScopeChains(NewND
, S
);
13612 ActOnDocumentableDecl(NewND
);
13616 Decl
*Sema::ActOnNamespaceAliasDef(Scope
*S
, SourceLocation NamespaceLoc
,
13617 SourceLocation AliasLoc
,
13618 IdentifierInfo
*Alias
, CXXScopeSpec
&SS
,
13619 SourceLocation IdentLoc
,
13620 IdentifierInfo
*Ident
) {
13622 // Lookup the namespace name.
13623 LookupResult
R(*this, Ident
, IdentLoc
, LookupNamespaceName
);
13624 LookupParsedName(R
, S
, &SS
);
13626 if (R
.isAmbiguous())
13630 if (!TryNamespaceTypoCorrection(*this, R
, S
, SS
, IdentLoc
, Ident
)) {
13631 Diag(IdentLoc
, diag::err_expected_namespace_name
) << SS
.getRange();
13635 assert(!R
.isAmbiguous() && !R
.empty());
13636 NamedDecl
*ND
= R
.getRepresentativeDecl();
13638 // Check if we have a previous declaration with the same name.
13639 LookupResult
PrevR(*this, Alias
, AliasLoc
, LookupOrdinaryName
,
13640 ForVisibleRedeclaration
);
13641 LookupName(PrevR
, S
);
13643 // Check we're not shadowing a template parameter.
13644 if (PrevR
.isSingleResult() && PrevR
.getFoundDecl()->isTemplateParameter()) {
13645 DiagnoseTemplateParameterShadow(AliasLoc
, PrevR
.getFoundDecl());
13649 // Filter out any other lookup result from an enclosing scope.
13650 FilterLookupForScope(PrevR
, CurContext
, S
, /*ConsiderLinkage*/false,
13651 /*AllowInlineNamespace*/false);
13653 // Find the previous declaration and check that we can redeclare it.
13654 NamespaceAliasDecl
*Prev
= nullptr;
13655 if (PrevR
.isSingleResult()) {
13656 NamedDecl
*PrevDecl
= PrevR
.getRepresentativeDecl();
13657 if (NamespaceAliasDecl
*AD
= dyn_cast
<NamespaceAliasDecl
>(PrevDecl
)) {
13658 // We already have an alias with the same name that points to the same
13659 // namespace; check that it matches.
13660 if (AD
->getNamespace()->Equals(getNamespaceDecl(ND
))) {
13662 } else if (isVisible(PrevDecl
)) {
13663 Diag(AliasLoc
, diag::err_redefinition_different_namespace_alias
)
13665 Diag(AD
->getLocation(), diag::note_previous_namespace_alias
)
13666 << AD
->getNamespace();
13669 } else if (isVisible(PrevDecl
)) {
13670 unsigned DiagID
= isa
<NamespaceDecl
>(PrevDecl
->getUnderlyingDecl())
13671 ? diag::err_redefinition
13672 : diag::err_redefinition_different_kind
;
13673 Diag(AliasLoc
, DiagID
) << Alias
;
13674 Diag(PrevDecl
->getLocation(), diag::note_previous_definition
);
13679 // The use of a nested name specifier may trigger deprecation warnings.
13680 DiagnoseUseOfDecl(ND
, IdentLoc
);
13682 NamespaceAliasDecl
*AliasDecl
=
13683 NamespaceAliasDecl::Create(Context
, CurContext
, NamespaceLoc
, AliasLoc
,
13684 Alias
, SS
.getWithLocInContext(Context
),
13687 AliasDecl
->setPreviousDecl(Prev
);
13689 PushOnScopeChains(AliasDecl
, S
);
13694 struct SpecialMemberExceptionSpecInfo
13695 : SpecialMemberVisitor
<SpecialMemberExceptionSpecInfo
> {
13696 SourceLocation Loc
;
13697 Sema::ImplicitExceptionSpecification ExceptSpec
;
13699 SpecialMemberExceptionSpecInfo(Sema
&S
, CXXMethodDecl
*MD
,
13700 Sema::CXXSpecialMember CSM
,
13701 Sema::InheritedConstructorInfo
*ICI
,
13702 SourceLocation Loc
)
13703 : SpecialMemberVisitor(S
, MD
, CSM
, ICI
), Loc(Loc
), ExceptSpec(S
) {}
13705 bool visitBase(CXXBaseSpecifier
*Base
);
13706 bool visitField(FieldDecl
*FD
);
13708 void visitClassSubobject(CXXRecordDecl
*Class
, Subobject Subobj
,
13711 void visitSubobjectCall(Subobject Subobj
,
13712 Sema::SpecialMemberOverloadResult SMOR
);
13716 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier
*Base
) {
13717 auto *RT
= Base
->getType()->getAs
<RecordType
>();
13721 auto *BaseClass
= cast
<CXXRecordDecl
>(RT
->getDecl());
13722 Sema::SpecialMemberOverloadResult SMOR
= lookupInheritedCtor(BaseClass
);
13723 if (auto *BaseCtor
= SMOR
.getMethod()) {
13724 visitSubobjectCall(Base
, BaseCtor
);
13728 visitClassSubobject(BaseClass
, Base
, 0);
13732 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl
*FD
) {
13733 if (CSM
== Sema::CXXDefaultConstructor
&& FD
->hasInClassInitializer()) {
13734 Expr
*E
= FD
->getInClassInitializer();
13736 // FIXME: It's a little wasteful to build and throw away a
13737 // CXXDefaultInitExpr here.
13738 // FIXME: We should have a single context note pointing at Loc, and
13739 // this location should be MD->getLocation() instead, since that's
13740 // the location where we actually use the default init expression.
13741 E
= S
.BuildCXXDefaultInitExpr(Loc
, FD
).get();
13743 ExceptSpec
.CalledExpr(E
);
13744 } else if (auto *RT
= S
.Context
.getBaseElementType(FD
->getType())
13745 ->getAs
<RecordType
>()) {
13746 visitClassSubobject(cast
<CXXRecordDecl
>(RT
->getDecl()), FD
,
13747 FD
->getType().getCVRQualifiers());
13752 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl
*Class
,
13755 FieldDecl
*Field
= Subobj
.dyn_cast
<FieldDecl
*>();
13756 bool IsMutable
= Field
&& Field
->isMutable();
13757 visitSubobjectCall(Subobj
, lookupIn(Class
, Quals
, IsMutable
));
13760 void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
13761 Subobject Subobj
, Sema::SpecialMemberOverloadResult SMOR
) {
13762 // Note, if lookup fails, it doesn't matter what exception specification we
13763 // choose because the special member will be deleted.
13764 if (CXXMethodDecl
*MD
= SMOR
.getMethod())
13765 ExceptSpec
.CalledDecl(getSubobjectLoc(Subobj
), MD
);
13768 bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier
&ExplicitSpec
) {
13769 llvm::APSInt Result
;
13770 ExprResult Converted
= CheckConvertedConstantExpression(
13771 ExplicitSpec
.getExpr(), Context
.BoolTy
, Result
, CCEK_ExplicitBool
);
13772 ExplicitSpec
.setExpr(Converted
.get());
13773 if (Converted
.isUsable() && !Converted
.get()->isValueDependent()) {
13774 ExplicitSpec
.setKind(Result
.getBoolValue()
13775 ? ExplicitSpecKind::ResolvedTrue
13776 : ExplicitSpecKind::ResolvedFalse
);
13779 ExplicitSpec
.setKind(ExplicitSpecKind::Unresolved
);
13783 ExplicitSpecifier
Sema::ActOnExplicitBoolSpecifier(Expr
*ExplicitExpr
) {
13784 ExplicitSpecifier
ES(ExplicitExpr
, ExplicitSpecKind::Unresolved
);
13785 if (!ExplicitExpr
->isTypeDependent())
13786 tryResolveExplicitSpecifier(ES
);
13790 static Sema::ImplicitExceptionSpecification
13791 ComputeDefaultedSpecialMemberExceptionSpec(
13792 Sema
&S
, SourceLocation Loc
, CXXMethodDecl
*MD
, Sema::CXXSpecialMember CSM
,
13793 Sema::InheritedConstructorInfo
*ICI
) {
13794 ComputingExceptionSpec
CES(S
, MD
, Loc
);
13796 CXXRecordDecl
*ClassDecl
= MD
->getParent();
13798 // C++ [except.spec]p14:
13799 // An implicitly declared special member function (Clause 12) shall have an
13800 // exception-specification. [...]
13801 SpecialMemberExceptionSpecInfo
Info(S
, MD
, CSM
, ICI
, MD
->getLocation());
13802 if (ClassDecl
->isInvalidDecl())
13803 return Info
.ExceptSpec
;
13805 // FIXME: If this diagnostic fires, we're probably missing a check for
13806 // attempting to resolve an exception specification before it's known
13807 // at a higher level.
13808 if (S
.RequireCompleteType(MD
->getLocation(),
13809 S
.Context
.getRecordType(ClassDecl
),
13810 diag::err_exception_spec_incomplete_type
))
13811 return Info
.ExceptSpec
;
13813 // C++1z [except.spec]p7:
13814 // [Look for exceptions thrown by] a constructor selected [...] to
13815 // initialize a potentially constructed subobject,
13816 // C++1z [except.spec]p8:
13817 // The exception specification for an implicitly-declared destructor, or a
13818 // destructor without a noexcept-specifier, is potentially-throwing if and
13819 // only if any of the destructors for any of its potentially constructed
13820 // subojects is potentially throwing.
13821 // FIXME: We respect the first rule but ignore the "potentially constructed"
13822 // in the second rule to resolve a core issue (no number yet) that would have
13824 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
13825 // struct B : A {};
13826 // struct C : B { void f(); };
13827 // ... due to giving B::~B() a non-throwing exception specification.
13828 Info
.visit(Info
.IsConstructor
? Info
.VisitPotentiallyConstructedBases
13829 : Info
.VisitAllBases
);
13831 return Info
.ExceptSpec
;
13835 /// RAII object to register a special member as being currently declared.
13836 struct DeclaringSpecialMember
{
13838 Sema::SpecialMemberDecl D
;
13839 Sema::ContextRAII SavedContext
;
13840 bool WasAlreadyBeingDeclared
;
13842 DeclaringSpecialMember(Sema
&S
, CXXRecordDecl
*RD
, Sema::CXXSpecialMember CSM
)
13843 : S(S
), D(RD
, CSM
), SavedContext(S
, RD
) {
13844 WasAlreadyBeingDeclared
= !S
.SpecialMembersBeingDeclared
.insert(D
).second
;
13845 if (WasAlreadyBeingDeclared
)
13846 // This almost never happens, but if it does, ensure that our cache
13847 // doesn't contain a stale result.
13848 S
.SpecialMemberCache
.clear();
13850 // Register a note to be produced if we encounter an error while
13851 // declaring the special member.
13852 Sema::CodeSynthesisContext Ctx
;
13853 Ctx
.Kind
= Sema::CodeSynthesisContext::DeclaringSpecialMember
;
13854 // FIXME: We don't have a location to use here. Using the class's
13855 // location maintains the fiction that we declare all special members
13856 // with the class, but (1) it's not clear that lying about that helps our
13857 // users understand what's going on, and (2) there may be outer contexts
13858 // on the stack (some of which are relevant) and printing them exposes
13860 Ctx
.PointOfInstantiation
= RD
->getLocation();
13862 Ctx
.SpecialMember
= CSM
;
13863 S
.pushCodeSynthesisContext(Ctx
);
13866 ~DeclaringSpecialMember() {
13867 if (!WasAlreadyBeingDeclared
) {
13868 S
.SpecialMembersBeingDeclared
.erase(D
);
13869 S
.popCodeSynthesisContext();
13873 /// Are we already trying to declare this special member?
13874 bool isAlreadyBeingDeclared() const {
13875 return WasAlreadyBeingDeclared
;
13880 void Sema::CheckImplicitSpecialMemberDeclaration(Scope
*S
, FunctionDecl
*FD
) {
13881 // Look up any existing declarations, but don't trigger declaration of all
13882 // implicit special members with this name.
13883 DeclarationName Name
= FD
->getDeclName();
13884 LookupResult
R(*this, Name
, SourceLocation(), LookupOrdinaryName
,
13885 ForExternalRedeclaration
);
13886 for (auto *D
: FD
->getParent()->lookup(Name
))
13887 if (auto *Acceptable
= R
.getAcceptableDecl(D
))
13888 R
.addDecl(Acceptable
);
13890 R
.suppressDiagnostics();
13892 CheckFunctionDeclaration(S
, FD
, R
, /*IsMemberSpecialization*/ false,
13893 FD
->isThisDeclarationADefinition());
13896 void Sema::setupImplicitSpecialMemberType(CXXMethodDecl
*SpecialMem
,
13898 ArrayRef
<QualType
> Args
) {
13899 // Build an exception specification pointing back at this constructor.
13900 FunctionProtoType::ExtProtoInfo EPI
= getImplicitMethodEPI(*this, SpecialMem
);
13902 LangAS AS
= getDefaultCXXMethodAddrSpace();
13903 if (AS
!= LangAS::Default
) {
13904 EPI
.TypeQuals
.addAddressSpace(AS
);
13907 auto QT
= Context
.getFunctionType(ResultTy
, Args
, EPI
);
13908 SpecialMem
->setType(QT
);
13910 // During template instantiation of implicit special member functions we need
13911 // a reliable TypeSourceInfo for the function prototype in order to allow
13912 // functions to be substituted.
13913 if (inTemplateInstantiation() &&
13914 cast
<CXXRecordDecl
>(SpecialMem
->getParent())->isLambda()) {
13915 TypeSourceInfo
*TSI
=
13916 Context
.getTrivialTypeSourceInfo(SpecialMem
->getType());
13917 SpecialMem
->setTypeSourceInfo(TSI
);
13921 CXXConstructorDecl
*Sema::DeclareImplicitDefaultConstructor(
13922 CXXRecordDecl
*ClassDecl
) {
13923 // C++ [class.ctor]p5:
13924 // A default constructor for a class X is a constructor of class X
13925 // that can be called without an argument. If there is no
13926 // user-declared constructor for class X, a default constructor is
13927 // implicitly declared. An implicitly-declared default constructor
13928 // is an inline public member of its class.
13929 assert(ClassDecl
->needsImplicitDefaultConstructor() &&
13930 "Should not build implicit default constructor!");
13932 DeclaringSpecialMember
DSM(*this, ClassDecl
, CXXDefaultConstructor
);
13933 if (DSM
.isAlreadyBeingDeclared())
13936 bool Constexpr
= defaultedSpecialMemberIsConstexpr(*this, ClassDecl
,
13937 CXXDefaultConstructor
,
13940 // Create the actual constructor declaration.
13941 CanQualType ClassType
13942 = Context
.getCanonicalType(Context
.getTypeDeclType(ClassDecl
));
13943 SourceLocation ClassLoc
= ClassDecl
->getLocation();
13944 DeclarationName Name
13945 = Context
.DeclarationNames
.getCXXConstructorName(ClassType
);
13946 DeclarationNameInfo
NameInfo(Name
, ClassLoc
);
13947 CXXConstructorDecl
*DefaultCon
= CXXConstructorDecl::Create(
13948 Context
, ClassDecl
, ClassLoc
, NameInfo
, /*Type*/ QualType(),
13949 /*TInfo=*/nullptr, ExplicitSpecifier(),
13950 getCurFPFeatures().isFPConstrained(),
13951 /*isInline=*/true, /*isImplicitlyDeclared=*/true,
13952 Constexpr
? ConstexprSpecKind::Constexpr
13953 : ConstexprSpecKind::Unspecified
);
13954 DefaultCon
->setAccess(AS_public
);
13955 DefaultCon
->setDefaulted();
13957 setupImplicitSpecialMemberType(DefaultCon
, Context
.VoidTy
, std::nullopt
);
13959 if (getLangOpts().CUDA
)
13960 inferCUDATargetForImplicitSpecialMember(ClassDecl
, CXXDefaultConstructor
,
13962 /* ConstRHS */ false,
13963 /* Diagnose */ false);
13965 // We don't need to use SpecialMemberIsTrivial here; triviality for default
13966 // constructors is easy to compute.
13967 DefaultCon
->setTrivial(ClassDecl
->hasTrivialDefaultConstructor());
13969 // Note that we have declared this constructor.
13970 ++getASTContext().NumImplicitDefaultConstructorsDeclared
;
13972 Scope
*S
= getScopeForContext(ClassDecl
);
13973 CheckImplicitSpecialMemberDeclaration(S
, DefaultCon
);
13975 if (ShouldDeleteSpecialMember(DefaultCon
, CXXDefaultConstructor
))
13976 SetDeclDeleted(DefaultCon
, ClassLoc
);
13979 PushOnScopeChains(DefaultCon
, S
, false);
13980 ClassDecl
->addDecl(DefaultCon
);
13985 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation
,
13986 CXXConstructorDecl
*Constructor
) {
13987 assert((Constructor
->isDefaulted() && Constructor
->isDefaultConstructor() &&
13988 !Constructor
->doesThisDeclarationHaveABody() &&
13989 !Constructor
->isDeleted()) &&
13990 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
13991 if (Constructor
->willHaveBody() || Constructor
->isInvalidDecl())
13994 CXXRecordDecl
*ClassDecl
= Constructor
->getParent();
13995 assert(ClassDecl
&& "DefineImplicitDefaultConstructor - invalid constructor");
13997 SynthesizedFunctionScope
Scope(*this, Constructor
);
13999 // The exception specification is needed because we are defining the
14001 ResolveExceptionSpec(CurrentLocation
,
14002 Constructor
->getType()->castAs
<FunctionProtoType
>());
14003 MarkVTableUsed(CurrentLocation
, ClassDecl
);
14005 // Add a context note for diagnostics produced after this point.
14006 Scope
.addContextNote(CurrentLocation
);
14008 if (SetCtorInitializers(Constructor
, /*AnyErrors=*/false)) {
14009 Constructor
->setInvalidDecl();
14013 SourceLocation Loc
= Constructor
->getEndLoc().isValid()
14014 ? Constructor
->getEndLoc()
14015 : Constructor
->getLocation();
14016 Constructor
->setBody(new (Context
) CompoundStmt(Loc
));
14017 Constructor
->markUsed(Context
);
14019 if (ASTMutationListener
*L
= getASTMutationListener()) {
14020 L
->CompletedImplicitDefinition(Constructor
);
14023 DiagnoseUninitializedFields(*this, Constructor
);
14026 void Sema::ActOnFinishDelayedMemberInitializers(Decl
*D
) {
14027 // Perform any delayed checks on exception specifications.
14028 CheckDelayedMemberExceptionSpecs();
14031 /// Find or create the fake constructor we synthesize to model constructing an
14032 /// object of a derived class via a constructor of a base class.
14033 CXXConstructorDecl
*
14034 Sema::findInheritingConstructor(SourceLocation Loc
,
14035 CXXConstructorDecl
*BaseCtor
,
14036 ConstructorUsingShadowDecl
*Shadow
) {
14037 CXXRecordDecl
*Derived
= Shadow
->getParent();
14038 SourceLocation UsingLoc
= Shadow
->getLocation();
14040 // FIXME: Add a new kind of DeclarationName for an inherited constructor.
14041 // For now we use the name of the base class constructor as a member of the
14042 // derived class to indicate a (fake) inherited constructor name.
14043 DeclarationName Name
= BaseCtor
->getDeclName();
14045 // Check to see if we already have a fake constructor for this inherited
14046 // constructor call.
14047 for (NamedDecl
*Ctor
: Derived
->lookup(Name
))
14048 if (declaresSameEntity(cast
<CXXConstructorDecl
>(Ctor
)
14049 ->getInheritedConstructor()
14052 return cast
<CXXConstructorDecl
>(Ctor
);
14054 DeclarationNameInfo
NameInfo(Name
, UsingLoc
);
14055 TypeSourceInfo
*TInfo
=
14056 Context
.getTrivialTypeSourceInfo(BaseCtor
->getType(), UsingLoc
);
14057 FunctionProtoTypeLoc ProtoLoc
=
14058 TInfo
->getTypeLoc().IgnoreParens().castAs
<FunctionProtoTypeLoc
>();
14060 // Check the inherited constructor is valid and find the list of base classes
14061 // from which it was inherited.
14062 InheritedConstructorInfo
ICI(*this, Loc
, Shadow
);
14065 BaseCtor
->isConstexpr() &&
14066 defaultedSpecialMemberIsConstexpr(*this, Derived
, CXXDefaultConstructor
,
14067 false, BaseCtor
, &ICI
);
14069 CXXConstructorDecl
*DerivedCtor
= CXXConstructorDecl::Create(
14070 Context
, Derived
, UsingLoc
, NameInfo
, TInfo
->getType(), TInfo
,
14071 BaseCtor
->getExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
14073 /*isImplicitlyDeclared=*/true,
14074 Constexpr
? BaseCtor
->getConstexprKind() : ConstexprSpecKind::Unspecified
,
14075 InheritedConstructor(Shadow
, BaseCtor
),
14076 BaseCtor
->getTrailingRequiresClause());
14077 if (Shadow
->isInvalidDecl())
14078 DerivedCtor
->setInvalidDecl();
14080 // Build an unevaluated exception specification for this fake constructor.
14081 const FunctionProtoType
*FPT
= TInfo
->getType()->castAs
<FunctionProtoType
>();
14082 FunctionProtoType::ExtProtoInfo EPI
= FPT
->getExtProtoInfo();
14083 EPI
.ExceptionSpec
.Type
= EST_Unevaluated
;
14084 EPI
.ExceptionSpec
.SourceDecl
= DerivedCtor
;
14085 DerivedCtor
->setType(Context
.getFunctionType(FPT
->getReturnType(),
14086 FPT
->getParamTypes(), EPI
));
14088 // Build the parameter declarations.
14089 SmallVector
<ParmVarDecl
*, 16> ParamDecls
;
14090 for (unsigned I
= 0, N
= FPT
->getNumParams(); I
!= N
; ++I
) {
14091 TypeSourceInfo
*TInfo
=
14092 Context
.getTrivialTypeSourceInfo(FPT
->getParamType(I
), UsingLoc
);
14093 ParmVarDecl
*PD
= ParmVarDecl::Create(
14094 Context
, DerivedCtor
, UsingLoc
, UsingLoc
, /*IdentifierInfo=*/nullptr,
14095 FPT
->getParamType(I
), TInfo
, SC_None
, /*DefArg=*/nullptr);
14096 PD
->setScopeInfo(0, I
);
14098 // Ensure attributes are propagated onto parameters (this matters for
14099 // format, pass_object_size, ...).
14100 mergeDeclAttributes(PD
, BaseCtor
->getParamDecl(I
));
14101 ParamDecls
.push_back(PD
);
14102 ProtoLoc
.setParam(I
, PD
);
14105 // Set up the new constructor.
14106 assert(!BaseCtor
->isDeleted() && "should not use deleted constructor");
14107 DerivedCtor
->setAccess(BaseCtor
->getAccess());
14108 DerivedCtor
->setParams(ParamDecls
);
14109 Derived
->addDecl(DerivedCtor
);
14111 if (ShouldDeleteSpecialMember(DerivedCtor
, CXXDefaultConstructor
, &ICI
))
14112 SetDeclDeleted(DerivedCtor
, UsingLoc
);
14114 return DerivedCtor
;
14117 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl
*Ctor
) {
14118 InheritedConstructorInfo
ICI(*this, Ctor
->getLocation(),
14119 Ctor
->getInheritedConstructor().getShadowDecl());
14120 ShouldDeleteSpecialMember(Ctor
, CXXDefaultConstructor
, &ICI
,
14124 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation
,
14125 CXXConstructorDecl
*Constructor
) {
14126 CXXRecordDecl
*ClassDecl
= Constructor
->getParent();
14127 assert(Constructor
->getInheritedConstructor() &&
14128 !Constructor
->doesThisDeclarationHaveABody() &&
14129 !Constructor
->isDeleted());
14130 if (Constructor
->willHaveBody() || Constructor
->isInvalidDecl())
14133 // Initializations are performed "as if by a defaulted default constructor",
14134 // so enter the appropriate scope.
14135 SynthesizedFunctionScope
Scope(*this, Constructor
);
14137 // The exception specification is needed because we are defining the
14139 ResolveExceptionSpec(CurrentLocation
,
14140 Constructor
->getType()->castAs
<FunctionProtoType
>());
14141 MarkVTableUsed(CurrentLocation
, ClassDecl
);
14143 // Add a context note for diagnostics produced after this point.
14144 Scope
.addContextNote(CurrentLocation
);
14146 ConstructorUsingShadowDecl
*Shadow
=
14147 Constructor
->getInheritedConstructor().getShadowDecl();
14148 CXXConstructorDecl
*InheritedCtor
=
14149 Constructor
->getInheritedConstructor().getConstructor();
14151 // [class.inhctor.init]p1:
14152 // initialization proceeds as if a defaulted default constructor is used to
14153 // initialize the D object and each base class subobject from which the
14154 // constructor was inherited
14156 InheritedConstructorInfo
ICI(*this, CurrentLocation
, Shadow
);
14157 CXXRecordDecl
*RD
= Shadow
->getParent();
14158 SourceLocation InitLoc
= Shadow
->getLocation();
14160 // Build explicit initializers for all base classes from which the
14161 // constructor was inherited.
14162 SmallVector
<CXXCtorInitializer
*, 8> Inits
;
14163 for (bool VBase
: {false, true}) {
14164 for (CXXBaseSpecifier
&B
: VBase
? RD
->vbases() : RD
->bases()) {
14165 if (B
.isVirtual() != VBase
)
14168 auto *BaseRD
= B
.getType()->getAsCXXRecordDecl();
14172 auto BaseCtor
= ICI
.findConstructorForBase(BaseRD
, InheritedCtor
);
14173 if (!BaseCtor
.first
)
14176 MarkFunctionReferenced(CurrentLocation
, BaseCtor
.first
);
14177 ExprResult Init
= new (Context
) CXXInheritedCtorInitExpr(
14178 InitLoc
, B
.getType(), BaseCtor
.first
, VBase
, BaseCtor
.second
);
14180 auto *TInfo
= Context
.getTrivialTypeSourceInfo(B
.getType(), InitLoc
);
14181 Inits
.push_back(new (Context
) CXXCtorInitializer(
14182 Context
, TInfo
, VBase
, InitLoc
, Init
.get(), InitLoc
,
14183 SourceLocation()));
14187 // We now proceed as if for a defaulted default constructor, with the relevant
14188 // initializers replaced.
14190 if (SetCtorInitializers(Constructor
, /*AnyErrors*/false, Inits
)) {
14191 Constructor
->setInvalidDecl();
14195 Constructor
->setBody(new (Context
) CompoundStmt(InitLoc
));
14196 Constructor
->markUsed(Context
);
14198 if (ASTMutationListener
*L
= getASTMutationListener()) {
14199 L
->CompletedImplicitDefinition(Constructor
);
14202 DiagnoseUninitializedFields(*this, Constructor
);
14205 CXXDestructorDecl
*Sema::DeclareImplicitDestructor(CXXRecordDecl
*ClassDecl
) {
14206 // C++ [class.dtor]p2:
14207 // If a class has no user-declared destructor, a destructor is
14208 // declared implicitly. An implicitly-declared destructor is an
14209 // inline public member of its class.
14210 assert(ClassDecl
->needsImplicitDestructor());
14212 DeclaringSpecialMember
DSM(*this, ClassDecl
, CXXDestructor
);
14213 if (DSM
.isAlreadyBeingDeclared())
14216 bool Constexpr
= defaultedSpecialMemberIsConstexpr(*this, ClassDecl
,
14220 // Create the actual destructor declaration.
14221 CanQualType ClassType
14222 = Context
.getCanonicalType(Context
.getTypeDeclType(ClassDecl
));
14223 SourceLocation ClassLoc
= ClassDecl
->getLocation();
14224 DeclarationName Name
14225 = Context
.DeclarationNames
.getCXXDestructorName(ClassType
);
14226 DeclarationNameInfo
NameInfo(Name
, ClassLoc
);
14227 CXXDestructorDecl
*Destructor
= CXXDestructorDecl::Create(
14228 Context
, ClassDecl
, ClassLoc
, NameInfo
, QualType(), nullptr,
14229 getCurFPFeatures().isFPConstrained(),
14231 /*isImplicitlyDeclared=*/true,
14232 Constexpr
? ConstexprSpecKind::Constexpr
14233 : ConstexprSpecKind::Unspecified
);
14234 Destructor
->setAccess(AS_public
);
14235 Destructor
->setDefaulted();
14237 setupImplicitSpecialMemberType(Destructor
, Context
.VoidTy
, std::nullopt
);
14239 if (getLangOpts().CUDA
)
14240 inferCUDATargetForImplicitSpecialMember(ClassDecl
, CXXDestructor
,
14242 /* ConstRHS */ false,
14243 /* Diagnose */ false);
14245 // We don't need to use SpecialMemberIsTrivial here; triviality for
14246 // destructors is easy to compute.
14247 Destructor
->setTrivial(ClassDecl
->hasTrivialDestructor());
14248 Destructor
->setTrivialForCall(ClassDecl
->hasAttr
<TrivialABIAttr
>() ||
14249 ClassDecl
->hasTrivialDestructorForCall());
14251 // Note that we have declared this destructor.
14252 ++getASTContext().NumImplicitDestructorsDeclared
;
14254 Scope
*S
= getScopeForContext(ClassDecl
);
14255 CheckImplicitSpecialMemberDeclaration(S
, Destructor
);
14257 // We can't check whether an implicit destructor is deleted before we complete
14258 // the definition of the class, because its validity depends on the alignment
14259 // of the class. We'll check this from ActOnFields once the class is complete.
14260 if (ClassDecl
->isCompleteDefinition() &&
14261 ShouldDeleteSpecialMember(Destructor
, CXXDestructor
))
14262 SetDeclDeleted(Destructor
, ClassLoc
);
14264 // Introduce this destructor into its scope.
14266 PushOnScopeChains(Destructor
, S
, false);
14267 ClassDecl
->addDecl(Destructor
);
14272 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation
,
14273 CXXDestructorDecl
*Destructor
) {
14274 assert((Destructor
->isDefaulted() &&
14275 !Destructor
->doesThisDeclarationHaveABody() &&
14276 !Destructor
->isDeleted()) &&
14277 "DefineImplicitDestructor - call it for implicit default dtor");
14278 if (Destructor
->willHaveBody() || Destructor
->isInvalidDecl())
14281 CXXRecordDecl
*ClassDecl
= Destructor
->getParent();
14282 assert(ClassDecl
&& "DefineImplicitDestructor - invalid destructor");
14284 SynthesizedFunctionScope
Scope(*this, Destructor
);
14286 // The exception specification is needed because we are defining the
14288 ResolveExceptionSpec(CurrentLocation
,
14289 Destructor
->getType()->castAs
<FunctionProtoType
>());
14290 MarkVTableUsed(CurrentLocation
, ClassDecl
);
14292 // Add a context note for diagnostics produced after this point.
14293 Scope
.addContextNote(CurrentLocation
);
14295 MarkBaseAndMemberDestructorsReferenced(Destructor
->getLocation(),
14296 Destructor
->getParent());
14298 if (CheckDestructor(Destructor
)) {
14299 Destructor
->setInvalidDecl();
14303 SourceLocation Loc
= Destructor
->getEndLoc().isValid()
14304 ? Destructor
->getEndLoc()
14305 : Destructor
->getLocation();
14306 Destructor
->setBody(new (Context
) CompoundStmt(Loc
));
14307 Destructor
->markUsed(Context
);
14309 if (ASTMutationListener
*L
= getASTMutationListener()) {
14310 L
->CompletedImplicitDefinition(Destructor
);
14314 void Sema::CheckCompleteDestructorVariant(SourceLocation CurrentLocation
,
14315 CXXDestructorDecl
*Destructor
) {
14316 if (Destructor
->isInvalidDecl())
14319 CXXRecordDecl
*ClassDecl
= Destructor
->getParent();
14320 assert(Context
.getTargetInfo().getCXXABI().isMicrosoft() &&
14321 "implicit complete dtors unneeded outside MS ABI");
14322 assert(ClassDecl
->getNumVBases() > 0 &&
14323 "complete dtor only exists for classes with vbases");
14325 SynthesizedFunctionScope
Scope(*this, Destructor
);
14327 // Add a context note for diagnostics produced after this point.
14328 Scope
.addContextNote(CurrentLocation
);
14330 MarkVirtualBaseDestructorsReferenced(Destructor
->getLocation(), ClassDecl
);
14333 /// Perform any semantic analysis which needs to be delayed until all
14334 /// pending class member declarations have been parsed.
14335 void Sema::ActOnFinishCXXMemberDecls() {
14336 // If the context is an invalid C++ class, just suppress these checks.
14337 if (CXXRecordDecl
*Record
= dyn_cast
<CXXRecordDecl
>(CurContext
)) {
14338 if (Record
->isInvalidDecl()) {
14339 DelayedOverridingExceptionSpecChecks
.clear();
14340 DelayedEquivalentExceptionSpecChecks
.clear();
14343 checkForMultipleExportedDefaultConstructors(*this, Record
);
14347 void Sema::ActOnFinishCXXNonNestedClass() {
14348 referenceDLLExportedClassMethods();
14350 if (!DelayedDllExportMemberFunctions
.empty()) {
14351 SmallVector
<CXXMethodDecl
*, 4> WorkList
;
14352 std::swap(DelayedDllExportMemberFunctions
, WorkList
);
14353 for (CXXMethodDecl
*M
: WorkList
) {
14354 DefineDefaultedFunction(*this, M
, M
->getLocation());
14356 // Pass the method to the consumer to get emitted. This is not necessary
14357 // for explicit instantiation definitions, as they will get emitted
14359 if (M
->getParent()->getTemplateSpecializationKind() !=
14360 TSK_ExplicitInstantiationDefinition
)
14361 ActOnFinishInlineFunctionDef(M
);
14366 void Sema::referenceDLLExportedClassMethods() {
14367 if (!DelayedDllExportClasses
.empty()) {
14368 // Calling ReferenceDllExportedMembers might cause the current function to
14369 // be called again, so use a local copy of DelayedDllExportClasses.
14370 SmallVector
<CXXRecordDecl
*, 4> WorkList
;
14371 std::swap(DelayedDllExportClasses
, WorkList
);
14372 for (CXXRecordDecl
*Class
: WorkList
)
14373 ReferenceDllExportedMembers(*this, Class
);
14377 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl
*Destructor
) {
14378 assert(getLangOpts().CPlusPlus11
&&
14379 "adjusting dtor exception specs was introduced in c++11");
14381 if (Destructor
->isDependentContext())
14384 // C++11 [class.dtor]p3:
14385 // A declaration of a destructor that does not have an exception-
14386 // specification is implicitly considered to have the same exception-
14387 // specification as an implicit declaration.
14388 const auto *DtorType
= Destructor
->getType()->castAs
<FunctionProtoType
>();
14389 if (DtorType
->hasExceptionSpec())
14392 // Replace the destructor's type, building off the existing one. Fortunately,
14393 // the only thing of interest in the destructor type is its extended info.
14394 // The return and arguments are fixed.
14395 FunctionProtoType::ExtProtoInfo EPI
= DtorType
->getExtProtoInfo();
14396 EPI
.ExceptionSpec
.Type
= EST_Unevaluated
;
14397 EPI
.ExceptionSpec
.SourceDecl
= Destructor
;
14398 Destructor
->setType(
14399 Context
.getFunctionType(Context
.VoidTy
, std::nullopt
, EPI
));
14401 // FIXME: If the destructor has a body that could throw, and the newly created
14402 // spec doesn't allow exceptions, we should emit a warning, because this
14403 // change in behavior can break conforming C++03 programs at runtime.
14404 // However, we don't have a body or an exception specification yet, so it
14405 // needs to be done somewhere else.
14409 /// An abstract base class for all helper classes used in building the
14410 // copy/move operators. These classes serve as factory functions and help us
14411 // avoid using the same Expr* in the AST twice.
14412 class ExprBuilder
{
14413 ExprBuilder(const ExprBuilder
&) = delete;
14414 ExprBuilder
&operator=(const ExprBuilder
&) = delete;
14417 static Expr
*assertNotNull(Expr
*E
) {
14418 assert(E
&& "Expression construction must not fail.");
14424 virtual ~ExprBuilder() {}
14426 virtual Expr
*build(Sema
&S
, SourceLocation Loc
) const = 0;
14429 class RefBuilder
: public ExprBuilder
{
14434 Expr
*build(Sema
&S
, SourceLocation Loc
) const override
{
14435 return assertNotNull(S
.BuildDeclRefExpr(Var
, VarType
, VK_LValue
, Loc
));
14438 RefBuilder(VarDecl
*Var
, QualType VarType
)
14439 : Var(Var
), VarType(VarType
) {}
14442 class ThisBuilder
: public ExprBuilder
{
14444 Expr
*build(Sema
&S
, SourceLocation Loc
) const override
{
14445 return assertNotNull(S
.ActOnCXXThis(Loc
).getAs
<Expr
>());
14449 class CastBuilder
: public ExprBuilder
{
14450 const ExprBuilder
&Builder
;
14452 ExprValueKind Kind
;
14453 const CXXCastPath
&Path
;
14456 Expr
*build(Sema
&S
, SourceLocation Loc
) const override
{
14457 return assertNotNull(S
.ImpCastExprToType(Builder
.build(S
, Loc
), Type
,
14458 CK_UncheckedDerivedToBase
, Kind
,
14462 CastBuilder(const ExprBuilder
&Builder
, QualType Type
, ExprValueKind Kind
,
14463 const CXXCastPath
&Path
)
14464 : Builder(Builder
), Type(Type
), Kind(Kind
), Path(Path
) {}
14467 class DerefBuilder
: public ExprBuilder
{
14468 const ExprBuilder
&Builder
;
14471 Expr
*build(Sema
&S
, SourceLocation Loc
) const override
{
14472 return assertNotNull(
14473 S
.CreateBuiltinUnaryOp(Loc
, UO_Deref
, Builder
.build(S
, Loc
)).get());
14476 DerefBuilder(const ExprBuilder
&Builder
) : Builder(Builder
) {}
14479 class MemberBuilder
: public ExprBuilder
{
14480 const ExprBuilder
&Builder
;
14484 LookupResult
&MemberLookup
;
14487 Expr
*build(Sema
&S
, SourceLocation Loc
) const override
{
14488 return assertNotNull(S
.BuildMemberReferenceExpr(
14489 Builder
.build(S
, Loc
), Type
, Loc
, IsArrow
, SS
, SourceLocation(),
14490 nullptr, MemberLookup
, nullptr, nullptr).get());
14493 MemberBuilder(const ExprBuilder
&Builder
, QualType Type
, bool IsArrow
,
14494 LookupResult
&MemberLookup
)
14495 : Builder(Builder
), Type(Type
), IsArrow(IsArrow
),
14496 MemberLookup(MemberLookup
) {}
14499 class MoveCastBuilder
: public ExprBuilder
{
14500 const ExprBuilder
&Builder
;
14503 Expr
*build(Sema
&S
, SourceLocation Loc
) const override
{
14504 return assertNotNull(CastForMoving(S
, Builder
.build(S
, Loc
)));
14507 MoveCastBuilder(const ExprBuilder
&Builder
) : Builder(Builder
) {}
14510 class LvalueConvBuilder
: public ExprBuilder
{
14511 const ExprBuilder
&Builder
;
14514 Expr
*build(Sema
&S
, SourceLocation Loc
) const override
{
14515 return assertNotNull(
14516 S
.DefaultLvalueConversion(Builder
.build(S
, Loc
)).get());
14519 LvalueConvBuilder(const ExprBuilder
&Builder
) : Builder(Builder
) {}
14522 class SubscriptBuilder
: public ExprBuilder
{
14523 const ExprBuilder
&Base
;
14524 const ExprBuilder
&Index
;
14527 Expr
*build(Sema
&S
, SourceLocation Loc
) const override
{
14528 return assertNotNull(S
.CreateBuiltinArraySubscriptExpr(
14529 Base
.build(S
, Loc
), Loc
, Index
.build(S
, Loc
), Loc
).get());
14532 SubscriptBuilder(const ExprBuilder
&Base
, const ExprBuilder
&Index
)
14533 : Base(Base
), Index(Index
) {}
14536 } // end anonymous namespace
14538 /// When generating a defaulted copy or move assignment operator, if a field
14539 /// should be copied with __builtin_memcpy rather than via explicit assignments,
14540 /// do so. This optimization only applies for arrays of scalars, and for arrays
14541 /// of class type where the selected copy/move-assignment operator is trivial.
14543 buildMemcpyForAssignmentOp(Sema
&S
, SourceLocation Loc
, QualType T
,
14544 const ExprBuilder
&ToB
, const ExprBuilder
&FromB
) {
14545 // Compute the size of the memory buffer to be copied.
14546 QualType SizeType
= S
.Context
.getSizeType();
14547 llvm::APInt
Size(S
.Context
.getTypeSize(SizeType
),
14548 S
.Context
.getTypeSizeInChars(T
).getQuantity());
14550 // Take the address of the field references for "from" and "to". We
14551 // directly construct UnaryOperators here because semantic analysis
14552 // does not permit us to take the address of an xvalue.
14553 Expr
*From
= FromB
.build(S
, Loc
);
14554 From
= UnaryOperator::Create(
14555 S
.Context
, From
, UO_AddrOf
, S
.Context
.getPointerType(From
->getType()),
14556 VK_PRValue
, OK_Ordinary
, Loc
, false, S
.CurFPFeatureOverrides());
14557 Expr
*To
= ToB
.build(S
, Loc
);
14558 To
= UnaryOperator::Create(
14559 S
.Context
, To
, UO_AddrOf
, S
.Context
.getPointerType(To
->getType()),
14560 VK_PRValue
, OK_Ordinary
, Loc
, false, S
.CurFPFeatureOverrides());
14562 const Type
*E
= T
->getBaseElementTypeUnsafe();
14563 bool NeedsCollectableMemCpy
=
14564 E
->isRecordType() &&
14565 E
->castAs
<RecordType
>()->getDecl()->hasObjectMember();
14567 // Create a reference to the __builtin_objc_memmove_collectable function
14568 StringRef MemCpyName
= NeedsCollectableMemCpy
?
14569 "__builtin_objc_memmove_collectable" :
14570 "__builtin_memcpy";
14571 LookupResult
R(S
, &S
.Context
.Idents
.get(MemCpyName
), Loc
,
14572 Sema::LookupOrdinaryName
);
14573 S
.LookupName(R
, S
.TUScope
, true);
14575 FunctionDecl
*MemCpy
= R
.getAsSingle
<FunctionDecl
>();
14577 // Something went horribly wrong earlier, and we will have complained
14579 return StmtError();
14581 ExprResult MemCpyRef
= S
.BuildDeclRefExpr(MemCpy
, S
.Context
.BuiltinFnTy
,
14582 VK_PRValue
, Loc
, nullptr);
14583 assert(MemCpyRef
.isUsable() && "Builtin reference cannot fail");
14585 Expr
*CallArgs
[] = {
14586 To
, From
, IntegerLiteral::Create(S
.Context
, Size
, SizeType
, Loc
)
14588 ExprResult Call
= S
.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef
.get(),
14589 Loc
, CallArgs
, Loc
);
14591 assert(!Call
.isInvalid() && "Call to __builtin_memcpy cannot fail!");
14592 return Call
.getAs
<Stmt
>();
14595 /// Builds a statement that copies/moves the given entity from \p From to
14598 /// This routine is used to copy/move the members of a class with an
14599 /// implicitly-declared copy/move assignment operator. When the entities being
14600 /// copied are arrays, this routine builds for loops to copy them.
14602 /// \param S The Sema object used for type-checking.
14604 /// \param Loc The location where the implicit copy/move is being generated.
14606 /// \param T The type of the expressions being copied/moved. Both expressions
14607 /// must have this type.
14609 /// \param To The expression we are copying/moving to.
14611 /// \param From The expression we are copying/moving from.
14613 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
14614 /// Otherwise, it's a non-static member subobject.
14616 /// \param Copying Whether we're copying or moving.
14618 /// \param Depth Internal parameter recording the depth of the recursion.
14620 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
14621 /// if a memcpy should be used instead.
14623 buildSingleCopyAssignRecursively(Sema
&S
, SourceLocation Loc
, QualType T
,
14624 const ExprBuilder
&To
, const ExprBuilder
&From
,
14625 bool CopyingBaseSubobject
, bool Copying
,
14626 unsigned Depth
= 0) {
14627 // C++11 [class.copy]p28:
14628 // Each subobject is assigned in the manner appropriate to its type:
14630 // - if the subobject is of class type, as if by a call to operator= with
14631 // the subobject as the object expression and the corresponding
14632 // subobject of x as a single function argument (as if by explicit
14633 // qualification; that is, ignoring any possible virtual overriding
14634 // functions in more derived classes);
14636 // C++03 [class.copy]p13:
14637 // - if the subobject is of class type, the copy assignment operator for
14638 // the class is used (as if by explicit qualification; that is,
14639 // ignoring any possible virtual overriding functions in more derived
14641 if (const RecordType
*RecordTy
= T
->getAs
<RecordType
>()) {
14642 CXXRecordDecl
*ClassDecl
= cast
<CXXRecordDecl
>(RecordTy
->getDecl());
14644 // Look for operator=.
14645 DeclarationName Name
14646 = S
.Context
.DeclarationNames
.getCXXOperatorName(OO_Equal
);
14647 LookupResult
OpLookup(S
, Name
, Loc
, Sema::LookupOrdinaryName
);
14648 S
.LookupQualifiedName(OpLookup
, ClassDecl
, false);
14650 // Prior to C++11, filter out any result that isn't a copy/move-assignment
14652 if (!S
.getLangOpts().CPlusPlus11
) {
14653 LookupResult::Filter F
= OpLookup
.makeFilter();
14654 while (F
.hasNext()) {
14655 NamedDecl
*D
= F
.next();
14656 if (CXXMethodDecl
*Method
= dyn_cast
<CXXMethodDecl
>(D
))
14657 if (Method
->isCopyAssignmentOperator() ||
14658 (!Copying
&& Method
->isMoveAssignmentOperator()))
14666 // Suppress the protected check (C++ [class.protected]) for each of the
14667 // assignment operators we found. This strange dance is required when
14668 // we're assigning via a base classes's copy-assignment operator. To
14669 // ensure that we're getting the right base class subobject (without
14670 // ambiguities), we need to cast "this" to that subobject type; to
14671 // ensure that we don't go through the virtual call mechanism, we need
14672 // to qualify the operator= name with the base class (see below). However,
14673 // this means that if the base class has a protected copy assignment
14674 // operator, the protected member access check will fail. So, we
14675 // rewrite "protected" access to "public" access in this case, since we
14676 // know by construction that we're calling from a derived class.
14677 if (CopyingBaseSubobject
) {
14678 for (LookupResult::iterator L
= OpLookup
.begin(), LEnd
= OpLookup
.end();
14680 if (L
.getAccess() == AS_protected
)
14681 L
.setAccess(AS_public
);
14685 // Create the nested-name-specifier that will be used to qualify the
14686 // reference to operator=; this is required to suppress the virtual
14689 const Type
*CanonicalT
= S
.Context
.getCanonicalType(T
.getTypePtr());
14690 SS
.MakeTrivial(S
.Context
,
14691 NestedNameSpecifier::Create(S
.Context
, nullptr, false,
14695 // Create the reference to operator=.
14696 ExprResult OpEqualRef
14697 = S
.BuildMemberReferenceExpr(To
.build(S
, Loc
), T
, Loc
, /*IsArrow=*/false,
14698 SS
, /*TemplateKWLoc=*/SourceLocation(),
14699 /*FirstQualifierInScope=*/nullptr,
14701 /*TemplateArgs=*/nullptr, /*S*/nullptr,
14702 /*SuppressQualifierCheck=*/true);
14703 if (OpEqualRef
.isInvalid())
14704 return StmtError();
14706 // Build the call to the assignment operator.
14708 Expr
*FromInst
= From
.build(S
, Loc
);
14709 ExprResult Call
= S
.BuildCallToMemberFunction(/*Scope=*/nullptr,
14710 OpEqualRef
.getAs
<Expr
>(),
14711 Loc
, FromInst
, Loc
);
14712 if (Call
.isInvalid())
14713 return StmtError();
14715 // If we built a call to a trivial 'operator=' while copying an array,
14716 // bail out. We'll replace the whole shebang with a memcpy.
14717 CXXMemberCallExpr
*CE
= dyn_cast
<CXXMemberCallExpr
>(Call
.get());
14718 if (CE
&& CE
->getMethodDecl()->isTrivial() && Depth
)
14719 return StmtResult((Stmt
*)nullptr);
14721 // Convert to an expression-statement, and clean up any produced
14723 return S
.ActOnExprStmt(Call
);
14726 // - if the subobject is of scalar type, the built-in assignment
14727 // operator is used.
14728 const ConstantArrayType
*ArrayTy
= S
.Context
.getAsConstantArrayType(T
);
14730 ExprResult Assignment
= S
.CreateBuiltinBinOp(
14731 Loc
, BO_Assign
, To
.build(S
, Loc
), From
.build(S
, Loc
));
14732 if (Assignment
.isInvalid())
14733 return StmtError();
14734 return S
.ActOnExprStmt(Assignment
);
14737 // - if the subobject is an array, each element is assigned, in the
14738 // manner appropriate to the element type;
14740 // Construct a loop over the array bounds, e.g.,
14742 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
14744 // that will copy each of the array elements.
14745 QualType SizeType
= S
.Context
.getSizeType();
14747 // Create the iteration variable.
14748 IdentifierInfo
*IterationVarName
= nullptr;
14750 SmallString
<8> Str
;
14751 llvm::raw_svector_ostream
OS(Str
);
14752 OS
<< "__i" << Depth
;
14753 IterationVarName
= &S
.Context
.Idents
.get(OS
.str());
14755 VarDecl
*IterationVar
= VarDecl::Create(S
.Context
, S
.CurContext
, Loc
, Loc
,
14756 IterationVarName
, SizeType
,
14757 S
.Context
.getTrivialTypeSourceInfo(SizeType
, Loc
),
14760 // Initialize the iteration variable to zero.
14761 llvm::APInt
Zero(S
.Context
.getTypeSize(SizeType
), 0);
14762 IterationVar
->setInit(IntegerLiteral::Create(S
.Context
, Zero
, SizeType
, Loc
));
14764 // Creates a reference to the iteration variable.
14765 RefBuilder
IterationVarRef(IterationVar
, SizeType
);
14766 LvalueConvBuilder
IterationVarRefRVal(IterationVarRef
);
14768 // Create the DeclStmt that holds the iteration variable.
14769 Stmt
*InitStmt
= new (S
.Context
) DeclStmt(DeclGroupRef(IterationVar
),Loc
,Loc
);
14771 // Subscript the "from" and "to" expressions with the iteration variable.
14772 SubscriptBuilder
FromIndexCopy(From
, IterationVarRefRVal
);
14773 MoveCastBuilder
FromIndexMove(FromIndexCopy
);
14774 const ExprBuilder
*FromIndex
;
14776 FromIndex
= &FromIndexCopy
;
14778 FromIndex
= &FromIndexMove
;
14780 SubscriptBuilder
ToIndex(To
, IterationVarRefRVal
);
14782 // Build the copy/move for an individual element of the array.
14784 buildSingleCopyAssignRecursively(S
, Loc
, ArrayTy
->getElementType(),
14785 ToIndex
, *FromIndex
, CopyingBaseSubobject
,
14786 Copying
, Depth
+ 1);
14787 // Bail out if copying fails or if we determined that we should use memcpy.
14788 if (Copy
.isInvalid() || !Copy
.get())
14791 // Create the comparison against the array bound.
14793 = ArrayTy
->getSize().zextOrTrunc(S
.Context
.getTypeSize(SizeType
));
14794 Expr
*Comparison
= BinaryOperator::Create(
14795 S
.Context
, IterationVarRefRVal
.build(S
, Loc
),
14796 IntegerLiteral::Create(S
.Context
, Upper
, SizeType
, Loc
), BO_NE
,
14797 S
.Context
.BoolTy
, VK_PRValue
, OK_Ordinary
, Loc
,
14798 S
.CurFPFeatureOverrides());
14800 // Create the pre-increment of the iteration variable. We can determine
14801 // whether the increment will overflow based on the value of the array
14803 Expr
*Increment
= UnaryOperator::Create(
14804 S
.Context
, IterationVarRef
.build(S
, Loc
), UO_PreInc
, SizeType
, VK_LValue
,
14805 OK_Ordinary
, Loc
, Upper
.isMaxValue(), S
.CurFPFeatureOverrides());
14807 // Construct the loop that copies all elements of this array.
14808 return S
.ActOnForStmt(
14809 Loc
, Loc
, InitStmt
,
14810 S
.ActOnCondition(nullptr, Loc
, Comparison
, Sema::ConditionKind::Boolean
),
14811 S
.MakeFullDiscardedValueExpr(Increment
), Loc
, Copy
.get());
14815 buildSingleCopyAssign(Sema
&S
, SourceLocation Loc
, QualType T
,
14816 const ExprBuilder
&To
, const ExprBuilder
&From
,
14817 bool CopyingBaseSubobject
, bool Copying
) {
14818 // Maybe we should use a memcpy?
14819 if (T
->isArrayType() && !T
.isConstQualified() && !T
.isVolatileQualified() &&
14820 T
.isTriviallyCopyableType(S
.Context
))
14821 return buildMemcpyForAssignmentOp(S
, Loc
, T
, To
, From
);
14823 StmtResult
Result(buildSingleCopyAssignRecursively(S
, Loc
, T
, To
, From
,
14824 CopyingBaseSubobject
,
14827 // If we ended up picking a trivial assignment operator for an array of a
14828 // non-trivially-copyable class type, just emit a memcpy.
14829 if (!Result
.isInvalid() && !Result
.get())
14830 return buildMemcpyForAssignmentOp(S
, Loc
, T
, To
, From
);
14835 CXXMethodDecl
*Sema::DeclareImplicitCopyAssignment(CXXRecordDecl
*ClassDecl
) {
14836 // Note: The following rules are largely analoguous to the copy
14837 // constructor rules. Note that virtual bases are not taken into account
14838 // for determining the argument type of the operator. Note also that
14839 // operators taking an object instead of a reference are allowed.
14840 assert(ClassDecl
->needsImplicitCopyAssignment());
14842 DeclaringSpecialMember
DSM(*this, ClassDecl
, CXXCopyAssignment
);
14843 if (DSM
.isAlreadyBeingDeclared())
14846 QualType ArgType
= Context
.getTypeDeclType(ClassDecl
);
14847 ArgType
= Context
.getElaboratedType(ElaboratedTypeKeyword::None
, nullptr,
14849 LangAS AS
= getDefaultCXXMethodAddrSpace();
14850 if (AS
!= LangAS::Default
)
14851 ArgType
= Context
.getAddrSpaceQualType(ArgType
, AS
);
14852 QualType RetType
= Context
.getLValueReferenceType(ArgType
);
14853 bool Const
= ClassDecl
->implicitCopyAssignmentHasConstParam();
14855 ArgType
= ArgType
.withConst();
14857 ArgType
= Context
.getLValueReferenceType(ArgType
);
14859 bool Constexpr
= defaultedSpecialMemberIsConstexpr(*this, ClassDecl
,
14863 // An implicitly-declared copy assignment operator is an inline public
14864 // member of its class.
14865 DeclarationName Name
= Context
.DeclarationNames
.getCXXOperatorName(OO_Equal
);
14866 SourceLocation ClassLoc
= ClassDecl
->getLocation();
14867 DeclarationNameInfo
NameInfo(Name
, ClassLoc
);
14868 CXXMethodDecl
*CopyAssignment
= CXXMethodDecl::Create(
14869 Context
, ClassDecl
, ClassLoc
, NameInfo
, QualType(),
14870 /*TInfo=*/nullptr, /*StorageClass=*/SC_None
,
14871 getCurFPFeatures().isFPConstrained(),
14873 Constexpr
? ConstexprSpecKind::Constexpr
: ConstexprSpecKind::Unspecified
,
14875 CopyAssignment
->setAccess(AS_public
);
14876 CopyAssignment
->setDefaulted();
14877 CopyAssignment
->setImplicit();
14879 setupImplicitSpecialMemberType(CopyAssignment
, RetType
, ArgType
);
14881 if (getLangOpts().CUDA
)
14882 inferCUDATargetForImplicitSpecialMember(ClassDecl
, CXXCopyAssignment
,
14884 /* ConstRHS */ Const
,
14885 /* Diagnose */ false);
14887 // Add the parameter to the operator.
14888 ParmVarDecl
*FromParam
= ParmVarDecl::Create(Context
, CopyAssignment
,
14889 ClassLoc
, ClassLoc
,
14890 /*Id=*/nullptr, ArgType
,
14891 /*TInfo=*/nullptr, SC_None
,
14893 CopyAssignment
->setParams(FromParam
);
14895 CopyAssignment
->setTrivial(
14896 ClassDecl
->needsOverloadResolutionForCopyAssignment()
14897 ? SpecialMemberIsTrivial(CopyAssignment
, CXXCopyAssignment
)
14898 : ClassDecl
->hasTrivialCopyAssignment());
14900 // Note that we have added this copy-assignment operator.
14901 ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared
;
14903 Scope
*S
= getScopeForContext(ClassDecl
);
14904 CheckImplicitSpecialMemberDeclaration(S
, CopyAssignment
);
14906 if (ShouldDeleteSpecialMember(CopyAssignment
, CXXCopyAssignment
)) {
14907 ClassDecl
->setImplicitCopyAssignmentIsDeleted();
14908 SetDeclDeleted(CopyAssignment
, ClassLoc
);
14912 PushOnScopeChains(CopyAssignment
, S
, false);
14913 ClassDecl
->addDecl(CopyAssignment
);
14915 return CopyAssignment
;
14918 /// Diagnose an implicit copy operation for a class which is odr-used, but
14919 /// which is deprecated because the class has a user-declared copy constructor,
14920 /// copy assignment operator, or destructor.
14921 static void diagnoseDeprecatedCopyOperation(Sema
&S
, CXXMethodDecl
*CopyOp
) {
14922 assert(CopyOp
->isImplicit());
14924 CXXRecordDecl
*RD
= CopyOp
->getParent();
14925 CXXMethodDecl
*UserDeclaredOperation
= nullptr;
14927 if (RD
->hasUserDeclaredDestructor()) {
14928 UserDeclaredOperation
= RD
->getDestructor();
14929 } else if (!isa
<CXXConstructorDecl
>(CopyOp
) &&
14930 RD
->hasUserDeclaredCopyConstructor()) {
14931 // Find any user-declared copy constructor.
14932 for (auto *I
: RD
->ctors()) {
14933 if (I
->isCopyConstructor()) {
14934 UserDeclaredOperation
= I
;
14938 assert(UserDeclaredOperation
);
14939 } else if (isa
<CXXConstructorDecl
>(CopyOp
) &&
14940 RD
->hasUserDeclaredCopyAssignment()) {
14941 // Find any user-declared move assignment operator.
14942 for (auto *I
: RD
->methods()) {
14943 if (I
->isCopyAssignmentOperator()) {
14944 UserDeclaredOperation
= I
;
14948 assert(UserDeclaredOperation
);
14951 if (UserDeclaredOperation
) {
14952 bool UDOIsUserProvided
= UserDeclaredOperation
->isUserProvided();
14953 bool UDOIsDestructor
= isa
<CXXDestructorDecl
>(UserDeclaredOperation
);
14954 bool IsCopyAssignment
= !isa
<CXXConstructorDecl
>(CopyOp
);
14956 (UDOIsUserProvided
&& UDOIsDestructor
)
14957 ? diag::warn_deprecated_copy_with_user_provided_dtor
14958 : (UDOIsUserProvided
&& !UDOIsDestructor
)
14959 ? diag::warn_deprecated_copy_with_user_provided_copy
14960 : (!UDOIsUserProvided
&& UDOIsDestructor
)
14961 ? diag::warn_deprecated_copy_with_dtor
14962 : diag::warn_deprecated_copy
;
14963 S
.Diag(UserDeclaredOperation
->getLocation(), DiagID
)
14964 << RD
<< IsCopyAssignment
;
14968 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation
,
14969 CXXMethodDecl
*CopyAssignOperator
) {
14970 assert((CopyAssignOperator
->isDefaulted() &&
14971 CopyAssignOperator
->isOverloadedOperator() &&
14972 CopyAssignOperator
->getOverloadedOperator() == OO_Equal
&&
14973 !CopyAssignOperator
->doesThisDeclarationHaveABody() &&
14974 !CopyAssignOperator
->isDeleted()) &&
14975 "DefineImplicitCopyAssignment called for wrong function");
14976 if (CopyAssignOperator
->willHaveBody() || CopyAssignOperator
->isInvalidDecl())
14979 CXXRecordDecl
*ClassDecl
= CopyAssignOperator
->getParent();
14980 if (ClassDecl
->isInvalidDecl()) {
14981 CopyAssignOperator
->setInvalidDecl();
14985 SynthesizedFunctionScope
Scope(*this, CopyAssignOperator
);
14987 // The exception specification is needed because we are defining the
14989 ResolveExceptionSpec(CurrentLocation
,
14990 CopyAssignOperator
->getType()->castAs
<FunctionProtoType
>());
14992 // Add a context note for diagnostics produced after this point.
14993 Scope
.addContextNote(CurrentLocation
);
14995 // C++11 [class.copy]p18:
14996 // The [definition of an implicitly declared copy assignment operator] is
14997 // deprecated if the class has a user-declared copy constructor or a
14998 // user-declared destructor.
14999 if (getLangOpts().CPlusPlus11
&& CopyAssignOperator
->isImplicit())
15000 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator
);
15002 // C++0x [class.copy]p30:
15003 // The implicitly-defined or explicitly-defaulted copy assignment operator
15004 // for a non-union class X performs memberwise copy assignment of its
15005 // subobjects. The direct base classes of X are assigned first, in the
15006 // order of their declaration in the base-specifier-list, and then the
15007 // immediate non-static data members of X are assigned, in the order in
15008 // which they were declared in the class definition.
15010 // The statements that form the synthesized function body.
15011 SmallVector
<Stmt
*, 8> Statements
;
15013 // The parameter for the "other" object, which we are copying from.
15014 ParmVarDecl
*Other
= CopyAssignOperator
->getNonObjectParameter(0);
15015 Qualifiers OtherQuals
= Other
->getType().getQualifiers();
15016 QualType OtherRefType
= Other
->getType();
15017 if (OtherRefType
->isLValueReferenceType()) {
15018 OtherRefType
= OtherRefType
->getPointeeType();
15019 OtherQuals
= OtherRefType
.getQualifiers();
15022 // Our location for everything implicitly-generated.
15023 SourceLocation Loc
= CopyAssignOperator
->getEndLoc().isValid()
15024 ? CopyAssignOperator
->getEndLoc()
15025 : CopyAssignOperator
->getLocation();
15027 // Builds a DeclRefExpr for the "other" object.
15028 RefBuilder
OtherRef(Other
, OtherRefType
);
15030 // Builds the function object parameter.
15031 std::optional
<ThisBuilder
> This
;
15032 std::optional
<DerefBuilder
> DerefThis
;
15033 std::optional
<RefBuilder
> ExplicitObject
;
15034 bool IsArrow
= false;
15035 QualType ObjectType
;
15036 if (CopyAssignOperator
->isExplicitObjectMemberFunction()) {
15037 ObjectType
= CopyAssignOperator
->getParamDecl(0)->getType();
15038 if (ObjectType
->isReferenceType())
15039 ObjectType
= ObjectType
->getPointeeType();
15040 ExplicitObject
.emplace(CopyAssignOperator
->getParamDecl(0), ObjectType
);
15042 ObjectType
= getCurrentThisType();
15044 DerefThis
.emplace(*This
);
15045 IsArrow
= !LangOpts
.HLSL
;
15047 ExprBuilder
&ObjectParameter
=
15048 ExplicitObject
? static_cast<ExprBuilder
&>(*ExplicitObject
)
15049 : static_cast<ExprBuilder
&>(*This
);
15051 // Assign base classes.
15052 bool Invalid
= false;
15053 for (auto &Base
: ClassDecl
->bases()) {
15054 // Form the assignment:
15055 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
15056 QualType BaseType
= Base
.getType().getUnqualifiedType();
15057 if (!BaseType
->isRecordType()) {
15062 CXXCastPath BasePath
;
15063 BasePath
.push_back(&Base
);
15065 // Construct the "from" expression, which is an implicit cast to the
15066 // appropriately-qualified base type.
15067 CastBuilder
From(OtherRef
, Context
.getQualifiedType(BaseType
, OtherQuals
),
15068 VK_LValue
, BasePath
);
15070 // Dereference "this".
15072 ExplicitObject
? static_cast<ExprBuilder
&>(*ExplicitObject
)
15073 : static_cast<ExprBuilder
&>(*DerefThis
),
15074 Context
.getQualifiedType(BaseType
, ObjectType
.getQualifiers()),
15075 VK_LValue
, BasePath
);
15078 StmtResult Copy
= buildSingleCopyAssign(*this, Loc
, BaseType
,
15080 /*CopyingBaseSubobject=*/true,
15082 if (Copy
.isInvalid()) {
15083 CopyAssignOperator
->setInvalidDecl();
15087 // Success! Record the copy.
15088 Statements
.push_back(Copy
.getAs
<Expr
>());
15091 // Assign non-static members.
15092 for (auto *Field
: ClassDecl
->fields()) {
15093 // FIXME: We should form some kind of AST representation for the implied
15094 // memcpy in a union copy operation.
15095 if (Field
->isUnnamedBitfield() || Field
->getParent()->isUnion())
15098 if (Field
->isInvalidDecl()) {
15103 // Check for members of reference type; we can't copy those.
15104 if (Field
->getType()->isReferenceType()) {
15105 Diag(ClassDecl
->getLocation(), diag::err_uninitialized_member_for_assign
)
15106 << Context
.getTagDeclType(ClassDecl
) << 0 << Field
->getDeclName();
15107 Diag(Field
->getLocation(), diag::note_declared_at
);
15112 // Check for members of const-qualified, non-class type.
15113 QualType BaseType
= Context
.getBaseElementType(Field
->getType());
15114 if (!BaseType
->getAs
<RecordType
>() && BaseType
.isConstQualified()) {
15115 Diag(ClassDecl
->getLocation(), diag::err_uninitialized_member_for_assign
)
15116 << Context
.getTagDeclType(ClassDecl
) << 1 << Field
->getDeclName();
15117 Diag(Field
->getLocation(), diag::note_declared_at
);
15122 // Suppress assigning zero-width bitfields.
15123 if (Field
->isZeroLengthBitField(Context
))
15126 QualType FieldType
= Field
->getType().getNonReferenceType();
15127 if (FieldType
->isIncompleteArrayType()) {
15128 assert(ClassDecl
->hasFlexibleArrayMember() &&
15129 "Incomplete array type is not valid");
15133 // Build references to the field in the object we're copying from and to.
15134 CXXScopeSpec SS
; // Intentionally empty
15135 LookupResult
MemberLookup(*this, Field
->getDeclName(), Loc
,
15137 MemberLookup
.addDecl(Field
);
15138 MemberLookup
.resolveKind();
15140 MemberBuilder
From(OtherRef
, OtherRefType
, /*IsArrow=*/false, MemberLookup
);
15141 MemberBuilder
To(ObjectParameter
, ObjectType
, IsArrow
, MemberLookup
);
15142 // Build the copy of this field.
15143 StmtResult Copy
= buildSingleCopyAssign(*this, Loc
, FieldType
,
15145 /*CopyingBaseSubobject=*/false,
15147 if (Copy
.isInvalid()) {
15148 CopyAssignOperator
->setInvalidDecl();
15152 // Success! Record the copy.
15153 Statements
.push_back(Copy
.getAs
<Stmt
>());
15157 // Add a "return *this;"
15159 (ExplicitObject
? static_cast<ExprBuilder
&>(*ExplicitObject
)
15160 : LangOpts
.HLSL
? static_cast<ExprBuilder
&>(*This
)
15161 : static_cast<ExprBuilder
&>(*DerefThis
))
15162 .build(*this, Loc
);
15163 StmtResult Return
= BuildReturnStmt(Loc
, ThisExpr
);
15164 if (Return
.isInvalid())
15167 Statements
.push_back(Return
.getAs
<Stmt
>());
15171 CopyAssignOperator
->setInvalidDecl();
15177 CompoundScopeRAII
CompoundScope(*this);
15178 Body
= ActOnCompoundStmt(Loc
, Loc
, Statements
,
15179 /*isStmtExpr=*/false);
15180 assert(!Body
.isInvalid() && "Compound statement creation cannot fail");
15182 CopyAssignOperator
->setBody(Body
.getAs
<Stmt
>());
15183 CopyAssignOperator
->markUsed(Context
);
15185 if (ASTMutationListener
*L
= getASTMutationListener()) {
15186 L
->CompletedImplicitDefinition(CopyAssignOperator
);
15190 CXXMethodDecl
*Sema::DeclareImplicitMoveAssignment(CXXRecordDecl
*ClassDecl
) {
15191 assert(ClassDecl
->needsImplicitMoveAssignment());
15193 DeclaringSpecialMember
DSM(*this, ClassDecl
, CXXMoveAssignment
);
15194 if (DSM
.isAlreadyBeingDeclared())
15197 // Note: The following rules are largely analoguous to the move
15198 // constructor rules.
15200 QualType ArgType
= Context
.getTypeDeclType(ClassDecl
);
15201 ArgType
= Context
.getElaboratedType(ElaboratedTypeKeyword::None
, nullptr,
15203 LangAS AS
= getDefaultCXXMethodAddrSpace();
15204 if (AS
!= LangAS::Default
)
15205 ArgType
= Context
.getAddrSpaceQualType(ArgType
, AS
);
15206 QualType RetType
= Context
.getLValueReferenceType(ArgType
);
15207 ArgType
= Context
.getRValueReferenceType(ArgType
);
15209 bool Constexpr
= defaultedSpecialMemberIsConstexpr(*this, ClassDecl
,
15213 // An implicitly-declared move assignment operator is an inline public
15214 // member of its class.
15215 DeclarationName Name
= Context
.DeclarationNames
.getCXXOperatorName(OO_Equal
);
15216 SourceLocation ClassLoc
= ClassDecl
->getLocation();
15217 DeclarationNameInfo
NameInfo(Name
, ClassLoc
);
15218 CXXMethodDecl
*MoveAssignment
= CXXMethodDecl::Create(
15219 Context
, ClassDecl
, ClassLoc
, NameInfo
, QualType(),
15220 /*TInfo=*/nullptr, /*StorageClass=*/SC_None
,
15221 getCurFPFeatures().isFPConstrained(),
15223 Constexpr
? ConstexprSpecKind::Constexpr
: ConstexprSpecKind::Unspecified
,
15225 MoveAssignment
->setAccess(AS_public
);
15226 MoveAssignment
->setDefaulted();
15227 MoveAssignment
->setImplicit();
15229 setupImplicitSpecialMemberType(MoveAssignment
, RetType
, ArgType
);
15231 if (getLangOpts().CUDA
)
15232 inferCUDATargetForImplicitSpecialMember(ClassDecl
, CXXMoveAssignment
,
15234 /* ConstRHS */ false,
15235 /* Diagnose */ false);
15237 // Add the parameter to the operator.
15238 ParmVarDecl
*FromParam
= ParmVarDecl::Create(Context
, MoveAssignment
,
15239 ClassLoc
, ClassLoc
,
15240 /*Id=*/nullptr, ArgType
,
15241 /*TInfo=*/nullptr, SC_None
,
15243 MoveAssignment
->setParams(FromParam
);
15245 MoveAssignment
->setTrivial(
15246 ClassDecl
->needsOverloadResolutionForMoveAssignment()
15247 ? SpecialMemberIsTrivial(MoveAssignment
, CXXMoveAssignment
)
15248 : ClassDecl
->hasTrivialMoveAssignment());
15250 // Note that we have added this copy-assignment operator.
15251 ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared
;
15253 Scope
*S
= getScopeForContext(ClassDecl
);
15254 CheckImplicitSpecialMemberDeclaration(S
, MoveAssignment
);
15256 if (ShouldDeleteSpecialMember(MoveAssignment
, CXXMoveAssignment
)) {
15257 ClassDecl
->setImplicitMoveAssignmentIsDeleted();
15258 SetDeclDeleted(MoveAssignment
, ClassLoc
);
15262 PushOnScopeChains(MoveAssignment
, S
, false);
15263 ClassDecl
->addDecl(MoveAssignment
);
15265 return MoveAssignment
;
15268 /// Check if we're implicitly defining a move assignment operator for a class
15269 /// with virtual bases. Such a move assignment might move-assign the virtual
15270 /// base multiple times.
15271 static void checkMoveAssignmentForRepeatedMove(Sema
&S
, CXXRecordDecl
*Class
,
15272 SourceLocation CurrentLocation
) {
15273 assert(!Class
->isDependentContext() && "should not define dependent move");
15275 // Only a virtual base could get implicitly move-assigned multiple times.
15276 // Only a non-trivial move assignment can observe this. We only want to
15277 // diagnose if we implicitly define an assignment operator that assigns
15278 // two base classes, both of which move-assign the same virtual base.
15279 if (Class
->getNumVBases() == 0 || Class
->hasTrivialMoveAssignment() ||
15280 Class
->getNumBases() < 2)
15283 llvm::SmallVector
<CXXBaseSpecifier
*, 16> Worklist
;
15284 typedef llvm::DenseMap
<CXXRecordDecl
*, CXXBaseSpecifier
*> VBaseMap
;
15287 for (auto &BI
: Class
->bases()) {
15288 Worklist
.push_back(&BI
);
15289 while (!Worklist
.empty()) {
15290 CXXBaseSpecifier
*BaseSpec
= Worklist
.pop_back_val();
15291 CXXRecordDecl
*Base
= BaseSpec
->getType()->getAsCXXRecordDecl();
15293 // If the base has no non-trivial move assignment operators,
15294 // we don't care about moves from it.
15295 if (!Base
->hasNonTrivialMoveAssignment())
15298 // If there's nothing virtual here, skip it.
15299 if (!BaseSpec
->isVirtual() && !Base
->getNumVBases())
15302 // If we're not actually going to call a move assignment for this base,
15303 // or the selected move assignment is trivial, skip it.
15304 Sema::SpecialMemberOverloadResult SMOR
=
15305 S
.LookupSpecialMember(Base
, Sema::CXXMoveAssignment
,
15306 /*ConstArg*/false, /*VolatileArg*/false,
15307 /*RValueThis*/true, /*ConstThis*/false,
15308 /*VolatileThis*/false);
15309 if (!SMOR
.getMethod() || SMOR
.getMethod()->isTrivial() ||
15310 !SMOR
.getMethod()->isMoveAssignmentOperator())
15313 if (BaseSpec
->isVirtual()) {
15314 // We're going to move-assign this virtual base, and its move
15315 // assignment operator is not trivial. If this can happen for
15316 // multiple distinct direct bases of Class, diagnose it. (If it
15317 // only happens in one base, we'll diagnose it when synthesizing
15318 // that base class's move assignment operator.)
15319 CXXBaseSpecifier
*&Existing
=
15320 VBases
.insert(std::make_pair(Base
->getCanonicalDecl(), &BI
))
15322 if (Existing
&& Existing
!= &BI
) {
15323 S
.Diag(CurrentLocation
, diag::warn_vbase_moved_multiple_times
)
15325 S
.Diag(Existing
->getBeginLoc(), diag::note_vbase_moved_here
)
15326 << (Base
->getCanonicalDecl() ==
15327 Existing
->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
15328 << Base
<< Existing
->getType() << Existing
->getSourceRange();
15329 S
.Diag(BI
.getBeginLoc(), diag::note_vbase_moved_here
)
15330 << (Base
->getCanonicalDecl() ==
15331 BI
.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
15332 << Base
<< BI
.getType() << BaseSpec
->getSourceRange();
15334 // Only diagnose each vbase once.
15335 Existing
= nullptr;
15338 // Only walk over bases that have defaulted move assignment operators.
15339 // We assume that any user-provided move assignment operator handles
15340 // the multiple-moves-of-vbase case itself somehow.
15341 if (!SMOR
.getMethod()->isDefaulted())
15344 // We're going to move the base classes of Base. Add them to the list.
15345 llvm::append_range(Worklist
, llvm::make_pointer_range(Base
->bases()));
15351 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation
,
15352 CXXMethodDecl
*MoveAssignOperator
) {
15353 assert((MoveAssignOperator
->isDefaulted() &&
15354 MoveAssignOperator
->isOverloadedOperator() &&
15355 MoveAssignOperator
->getOverloadedOperator() == OO_Equal
&&
15356 !MoveAssignOperator
->doesThisDeclarationHaveABody() &&
15357 !MoveAssignOperator
->isDeleted()) &&
15358 "DefineImplicitMoveAssignment called for wrong function");
15359 if (MoveAssignOperator
->willHaveBody() || MoveAssignOperator
->isInvalidDecl())
15362 CXXRecordDecl
*ClassDecl
= MoveAssignOperator
->getParent();
15363 if (ClassDecl
->isInvalidDecl()) {
15364 MoveAssignOperator
->setInvalidDecl();
15368 // C++0x [class.copy]p28:
15369 // The implicitly-defined or move assignment operator for a non-union class
15370 // X performs memberwise move assignment of its subobjects. The direct base
15371 // classes of X are assigned first, in the order of their declaration in the
15372 // base-specifier-list, and then the immediate non-static data members of X
15373 // are assigned, in the order in which they were declared in the class
15376 // Issue a warning if our implicit move assignment operator will move
15377 // from a virtual base more than once.
15378 checkMoveAssignmentForRepeatedMove(*this, ClassDecl
, CurrentLocation
);
15380 SynthesizedFunctionScope
Scope(*this, MoveAssignOperator
);
15382 // The exception specification is needed because we are defining the
15384 ResolveExceptionSpec(CurrentLocation
,
15385 MoveAssignOperator
->getType()->castAs
<FunctionProtoType
>());
15387 // Add a context note for diagnostics produced after this point.
15388 Scope
.addContextNote(CurrentLocation
);
15390 // The statements that form the synthesized function body.
15391 SmallVector
<Stmt
*, 8> Statements
;
15393 // The parameter for the "other" object, which we are move from.
15394 ParmVarDecl
*Other
= MoveAssignOperator
->getNonObjectParameter(0);
15395 QualType OtherRefType
=
15396 Other
->getType()->castAs
<RValueReferenceType
>()->getPointeeType();
15398 // Our location for everything implicitly-generated.
15399 SourceLocation Loc
= MoveAssignOperator
->getEndLoc().isValid()
15400 ? MoveAssignOperator
->getEndLoc()
15401 : MoveAssignOperator
->getLocation();
15403 // Builds a reference to the "other" object.
15404 RefBuilder
OtherRef(Other
, OtherRefType
);
15406 MoveCastBuilder
MoveOther(OtherRef
);
15408 // Builds the function object parameter.
15409 std::optional
<ThisBuilder
> This
;
15410 std::optional
<DerefBuilder
> DerefThis
;
15411 std::optional
<RefBuilder
> ExplicitObject
;
15412 QualType ObjectType
;
15413 if (MoveAssignOperator
->isExplicitObjectMemberFunction()) {
15414 ObjectType
= MoveAssignOperator
->getParamDecl(0)->getType();
15415 if (ObjectType
->isReferenceType())
15416 ObjectType
= ObjectType
->getPointeeType();
15417 ExplicitObject
.emplace(MoveAssignOperator
->getParamDecl(0), ObjectType
);
15419 ObjectType
= getCurrentThisType();
15421 DerefThis
.emplace(*This
);
15423 ExprBuilder
&ObjectParameter
=
15424 ExplicitObject
? *ExplicitObject
: static_cast<ExprBuilder
&>(*This
);
15426 // Assign base classes.
15427 bool Invalid
= false;
15428 for (auto &Base
: ClassDecl
->bases()) {
15429 // C++11 [class.copy]p28:
15430 // It is unspecified whether subobjects representing virtual base classes
15431 // are assigned more than once by the implicitly-defined copy assignment
15433 // FIXME: Do not assign to a vbase that will be assigned by some other base
15434 // class. For a move-assignment, this can result in the vbase being moved
15437 // Form the assignment:
15438 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
15439 QualType BaseType
= Base
.getType().getUnqualifiedType();
15440 if (!BaseType
->isRecordType()) {
15445 CXXCastPath BasePath
;
15446 BasePath
.push_back(&Base
);
15448 // Construct the "from" expression, which is an implicit cast to the
15449 // appropriately-qualified base type.
15450 CastBuilder
From(OtherRef
, BaseType
, VK_XValue
, BasePath
);
15452 // Implicitly cast "this" to the appropriately-qualified base type.
15453 // Dereference "this".
15455 ExplicitObject
? static_cast<ExprBuilder
&>(*ExplicitObject
)
15456 : static_cast<ExprBuilder
&>(*DerefThis
),
15457 Context
.getQualifiedType(BaseType
, ObjectType
.getQualifiers()),
15458 VK_LValue
, BasePath
);
15461 StmtResult Move
= buildSingleCopyAssign(*this, Loc
, BaseType
,
15463 /*CopyingBaseSubobject=*/true,
15464 /*Copying=*/false);
15465 if (Move
.isInvalid()) {
15466 MoveAssignOperator
->setInvalidDecl();
15470 // Success! Record the move.
15471 Statements
.push_back(Move
.getAs
<Expr
>());
15474 // Assign non-static members.
15475 for (auto *Field
: ClassDecl
->fields()) {
15476 // FIXME: We should form some kind of AST representation for the implied
15477 // memcpy in a union copy operation.
15478 if (Field
->isUnnamedBitfield() || Field
->getParent()->isUnion())
15481 if (Field
->isInvalidDecl()) {
15486 // Check for members of reference type; we can't move those.
15487 if (Field
->getType()->isReferenceType()) {
15488 Diag(ClassDecl
->getLocation(), diag::err_uninitialized_member_for_assign
)
15489 << Context
.getTagDeclType(ClassDecl
) << 0 << Field
->getDeclName();
15490 Diag(Field
->getLocation(), diag::note_declared_at
);
15495 // Check for members of const-qualified, non-class type.
15496 QualType BaseType
= Context
.getBaseElementType(Field
->getType());
15497 if (!BaseType
->getAs
<RecordType
>() && BaseType
.isConstQualified()) {
15498 Diag(ClassDecl
->getLocation(), diag::err_uninitialized_member_for_assign
)
15499 << Context
.getTagDeclType(ClassDecl
) << 1 << Field
->getDeclName();
15500 Diag(Field
->getLocation(), diag::note_declared_at
);
15505 // Suppress assigning zero-width bitfields.
15506 if (Field
->isZeroLengthBitField(Context
))
15509 QualType FieldType
= Field
->getType().getNonReferenceType();
15510 if (FieldType
->isIncompleteArrayType()) {
15511 assert(ClassDecl
->hasFlexibleArrayMember() &&
15512 "Incomplete array type is not valid");
15516 // Build references to the field in the object we're copying from and to.
15517 LookupResult
MemberLookup(*this, Field
->getDeclName(), Loc
,
15519 MemberLookup
.addDecl(Field
);
15520 MemberLookup
.resolveKind();
15521 MemberBuilder
From(MoveOther
, OtherRefType
,
15522 /*IsArrow=*/false, MemberLookup
);
15523 MemberBuilder
To(ObjectParameter
, ObjectType
, /*IsArrow=*/!ExplicitObject
,
15526 assert(!From
.build(*this, Loc
)->isLValue() && // could be xvalue or prvalue
15527 "Member reference with rvalue base must be rvalue except for reference "
15528 "members, which aren't allowed for move assignment.");
15530 // Build the move of this field.
15531 StmtResult Move
= buildSingleCopyAssign(*this, Loc
, FieldType
,
15533 /*CopyingBaseSubobject=*/false,
15534 /*Copying=*/false);
15535 if (Move
.isInvalid()) {
15536 MoveAssignOperator
->setInvalidDecl();
15540 // Success! Record the copy.
15541 Statements
.push_back(Move
.getAs
<Stmt
>());
15545 // Add a "return *this;"
15547 (ExplicitObject
? static_cast<ExprBuilder
&>(*ExplicitObject
)
15548 : static_cast<ExprBuilder
&>(*DerefThis
))
15549 .build(*this, Loc
);
15551 StmtResult Return
= BuildReturnStmt(Loc
, ThisExpr
);
15552 if (Return
.isInvalid())
15555 Statements
.push_back(Return
.getAs
<Stmt
>());
15559 MoveAssignOperator
->setInvalidDecl();
15565 CompoundScopeRAII
CompoundScope(*this);
15566 Body
= ActOnCompoundStmt(Loc
, Loc
, Statements
,
15567 /*isStmtExpr=*/false);
15568 assert(!Body
.isInvalid() && "Compound statement creation cannot fail");
15570 MoveAssignOperator
->setBody(Body
.getAs
<Stmt
>());
15571 MoveAssignOperator
->markUsed(Context
);
15573 if (ASTMutationListener
*L
= getASTMutationListener()) {
15574 L
->CompletedImplicitDefinition(MoveAssignOperator
);
15578 CXXConstructorDecl
*Sema::DeclareImplicitCopyConstructor(
15579 CXXRecordDecl
*ClassDecl
) {
15580 // C++ [class.copy]p4:
15581 // If the class definition does not explicitly declare a copy
15582 // constructor, one is declared implicitly.
15583 assert(ClassDecl
->needsImplicitCopyConstructor());
15585 DeclaringSpecialMember
DSM(*this, ClassDecl
, CXXCopyConstructor
);
15586 if (DSM
.isAlreadyBeingDeclared())
15589 QualType ClassType
= Context
.getTypeDeclType(ClassDecl
);
15590 QualType ArgType
= ClassType
;
15591 ArgType
= Context
.getElaboratedType(ElaboratedTypeKeyword::None
, nullptr,
15593 bool Const
= ClassDecl
->implicitCopyConstructorHasConstParam();
15595 ArgType
= ArgType
.withConst();
15597 LangAS AS
= getDefaultCXXMethodAddrSpace();
15598 if (AS
!= LangAS::Default
)
15599 ArgType
= Context
.getAddrSpaceQualType(ArgType
, AS
);
15601 ArgType
= Context
.getLValueReferenceType(ArgType
);
15603 bool Constexpr
= defaultedSpecialMemberIsConstexpr(*this, ClassDecl
,
15604 CXXCopyConstructor
,
15607 DeclarationName Name
15608 = Context
.DeclarationNames
.getCXXConstructorName(
15609 Context
.getCanonicalType(ClassType
));
15610 SourceLocation ClassLoc
= ClassDecl
->getLocation();
15611 DeclarationNameInfo
NameInfo(Name
, ClassLoc
);
15613 // An implicitly-declared copy constructor is an inline public
15614 // member of its class.
15615 CXXConstructorDecl
*CopyConstructor
= CXXConstructorDecl::Create(
15616 Context
, ClassDecl
, ClassLoc
, NameInfo
, QualType(), /*TInfo=*/nullptr,
15617 ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
15619 /*isImplicitlyDeclared=*/true,
15620 Constexpr
? ConstexprSpecKind::Constexpr
15621 : ConstexprSpecKind::Unspecified
);
15622 CopyConstructor
->setAccess(AS_public
);
15623 CopyConstructor
->setDefaulted();
15625 setupImplicitSpecialMemberType(CopyConstructor
, Context
.VoidTy
, ArgType
);
15627 if (getLangOpts().CUDA
)
15628 inferCUDATargetForImplicitSpecialMember(ClassDecl
, CXXCopyConstructor
,
15630 /* ConstRHS */ Const
,
15631 /* Diagnose */ false);
15633 // During template instantiation of special member functions we need a
15634 // reliable TypeSourceInfo for the parameter types in order to allow functions
15635 // to be substituted.
15636 TypeSourceInfo
*TSI
= nullptr;
15637 if (inTemplateInstantiation() && ClassDecl
->isLambda())
15638 TSI
= Context
.getTrivialTypeSourceInfo(ArgType
);
15640 // Add the parameter to the constructor.
15641 ParmVarDecl
*FromParam
=
15642 ParmVarDecl::Create(Context
, CopyConstructor
, ClassLoc
, ClassLoc
,
15643 /*IdentifierInfo=*/nullptr, ArgType
,
15644 /*TInfo=*/TSI
, SC_None
, nullptr);
15645 CopyConstructor
->setParams(FromParam
);
15647 CopyConstructor
->setTrivial(
15648 ClassDecl
->needsOverloadResolutionForCopyConstructor()
15649 ? SpecialMemberIsTrivial(CopyConstructor
, CXXCopyConstructor
)
15650 : ClassDecl
->hasTrivialCopyConstructor());
15652 CopyConstructor
->setTrivialForCall(
15653 ClassDecl
->hasAttr
<TrivialABIAttr
>() ||
15654 (ClassDecl
->needsOverloadResolutionForCopyConstructor()
15655 ? SpecialMemberIsTrivial(CopyConstructor
, CXXCopyConstructor
,
15656 TAH_ConsiderTrivialABI
)
15657 : ClassDecl
->hasTrivialCopyConstructorForCall()));
15659 // Note that we have declared this constructor.
15660 ++getASTContext().NumImplicitCopyConstructorsDeclared
;
15662 Scope
*S
= getScopeForContext(ClassDecl
);
15663 CheckImplicitSpecialMemberDeclaration(S
, CopyConstructor
);
15665 if (ShouldDeleteSpecialMember(CopyConstructor
, CXXCopyConstructor
)) {
15666 ClassDecl
->setImplicitCopyConstructorIsDeleted();
15667 SetDeclDeleted(CopyConstructor
, ClassLoc
);
15671 PushOnScopeChains(CopyConstructor
, S
, false);
15672 ClassDecl
->addDecl(CopyConstructor
);
15674 return CopyConstructor
;
15677 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation
,
15678 CXXConstructorDecl
*CopyConstructor
) {
15679 assert((CopyConstructor
->isDefaulted() &&
15680 CopyConstructor
->isCopyConstructor() &&
15681 !CopyConstructor
->doesThisDeclarationHaveABody() &&
15682 !CopyConstructor
->isDeleted()) &&
15683 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
15684 if (CopyConstructor
->willHaveBody() || CopyConstructor
->isInvalidDecl())
15687 CXXRecordDecl
*ClassDecl
= CopyConstructor
->getParent();
15688 assert(ClassDecl
&& "DefineImplicitCopyConstructor - invalid constructor");
15690 SynthesizedFunctionScope
Scope(*this, CopyConstructor
);
15692 // The exception specification is needed because we are defining the
15694 ResolveExceptionSpec(CurrentLocation
,
15695 CopyConstructor
->getType()->castAs
<FunctionProtoType
>());
15696 MarkVTableUsed(CurrentLocation
, ClassDecl
);
15698 // Add a context note for diagnostics produced after this point.
15699 Scope
.addContextNote(CurrentLocation
);
15701 // C++11 [class.copy]p7:
15702 // The [definition of an implicitly declared copy constructor] is
15703 // deprecated if the class has a user-declared copy assignment operator
15704 // or a user-declared destructor.
15705 if (getLangOpts().CPlusPlus11
&& CopyConstructor
->isImplicit())
15706 diagnoseDeprecatedCopyOperation(*this, CopyConstructor
);
15708 if (SetCtorInitializers(CopyConstructor
, /*AnyErrors=*/false)) {
15709 CopyConstructor
->setInvalidDecl();
15711 SourceLocation Loc
= CopyConstructor
->getEndLoc().isValid()
15712 ? CopyConstructor
->getEndLoc()
15713 : CopyConstructor
->getLocation();
15714 Sema::CompoundScopeRAII
CompoundScope(*this);
15715 CopyConstructor
->setBody(
15716 ActOnCompoundStmt(Loc
, Loc
, std::nullopt
, /*isStmtExpr=*/false)
15718 CopyConstructor
->markUsed(Context
);
15721 if (ASTMutationListener
*L
= getASTMutationListener()) {
15722 L
->CompletedImplicitDefinition(CopyConstructor
);
15726 CXXConstructorDecl
*Sema::DeclareImplicitMoveConstructor(
15727 CXXRecordDecl
*ClassDecl
) {
15728 assert(ClassDecl
->needsImplicitMoveConstructor());
15730 DeclaringSpecialMember
DSM(*this, ClassDecl
, CXXMoveConstructor
);
15731 if (DSM
.isAlreadyBeingDeclared())
15734 QualType ClassType
= Context
.getTypeDeclType(ClassDecl
);
15736 QualType ArgType
= ClassType
;
15737 ArgType
= Context
.getElaboratedType(ElaboratedTypeKeyword::None
, nullptr,
15739 LangAS AS
= getDefaultCXXMethodAddrSpace();
15740 if (AS
!= LangAS::Default
)
15741 ArgType
= Context
.getAddrSpaceQualType(ClassType
, AS
);
15742 ArgType
= Context
.getRValueReferenceType(ArgType
);
15744 bool Constexpr
= defaultedSpecialMemberIsConstexpr(*this, ClassDecl
,
15745 CXXMoveConstructor
,
15748 DeclarationName Name
15749 = Context
.DeclarationNames
.getCXXConstructorName(
15750 Context
.getCanonicalType(ClassType
));
15751 SourceLocation ClassLoc
= ClassDecl
->getLocation();
15752 DeclarationNameInfo
NameInfo(Name
, ClassLoc
);
15754 // C++11 [class.copy]p11:
15755 // An implicitly-declared copy/move constructor is an inline public
15756 // member of its class.
15757 CXXConstructorDecl
*MoveConstructor
= CXXConstructorDecl::Create(
15758 Context
, ClassDecl
, ClassLoc
, NameInfo
, QualType(), /*TInfo=*/nullptr,
15759 ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
15761 /*isImplicitlyDeclared=*/true,
15762 Constexpr
? ConstexprSpecKind::Constexpr
15763 : ConstexprSpecKind::Unspecified
);
15764 MoveConstructor
->setAccess(AS_public
);
15765 MoveConstructor
->setDefaulted();
15767 setupImplicitSpecialMemberType(MoveConstructor
, Context
.VoidTy
, ArgType
);
15769 if (getLangOpts().CUDA
)
15770 inferCUDATargetForImplicitSpecialMember(ClassDecl
, CXXMoveConstructor
,
15772 /* ConstRHS */ false,
15773 /* Diagnose */ false);
15775 // Add the parameter to the constructor.
15776 ParmVarDecl
*FromParam
= ParmVarDecl::Create(Context
, MoveConstructor
,
15777 ClassLoc
, ClassLoc
,
15778 /*IdentifierInfo=*/nullptr,
15779 ArgType
, /*TInfo=*/nullptr,
15781 MoveConstructor
->setParams(FromParam
);
15783 MoveConstructor
->setTrivial(
15784 ClassDecl
->needsOverloadResolutionForMoveConstructor()
15785 ? SpecialMemberIsTrivial(MoveConstructor
, CXXMoveConstructor
)
15786 : ClassDecl
->hasTrivialMoveConstructor());
15788 MoveConstructor
->setTrivialForCall(
15789 ClassDecl
->hasAttr
<TrivialABIAttr
>() ||
15790 (ClassDecl
->needsOverloadResolutionForMoveConstructor()
15791 ? SpecialMemberIsTrivial(MoveConstructor
, CXXMoveConstructor
,
15792 TAH_ConsiderTrivialABI
)
15793 : ClassDecl
->hasTrivialMoveConstructorForCall()));
15795 // Note that we have declared this constructor.
15796 ++getASTContext().NumImplicitMoveConstructorsDeclared
;
15798 Scope
*S
= getScopeForContext(ClassDecl
);
15799 CheckImplicitSpecialMemberDeclaration(S
, MoveConstructor
);
15801 if (ShouldDeleteSpecialMember(MoveConstructor
, CXXMoveConstructor
)) {
15802 ClassDecl
->setImplicitMoveConstructorIsDeleted();
15803 SetDeclDeleted(MoveConstructor
, ClassLoc
);
15807 PushOnScopeChains(MoveConstructor
, S
, false);
15808 ClassDecl
->addDecl(MoveConstructor
);
15810 return MoveConstructor
;
15813 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation
,
15814 CXXConstructorDecl
*MoveConstructor
) {
15815 assert((MoveConstructor
->isDefaulted() &&
15816 MoveConstructor
->isMoveConstructor() &&
15817 !MoveConstructor
->doesThisDeclarationHaveABody() &&
15818 !MoveConstructor
->isDeleted()) &&
15819 "DefineImplicitMoveConstructor - call it for implicit move ctor");
15820 if (MoveConstructor
->willHaveBody() || MoveConstructor
->isInvalidDecl())
15823 CXXRecordDecl
*ClassDecl
= MoveConstructor
->getParent();
15824 assert(ClassDecl
&& "DefineImplicitMoveConstructor - invalid constructor");
15826 SynthesizedFunctionScope
Scope(*this, MoveConstructor
);
15828 // The exception specification is needed because we are defining the
15830 ResolveExceptionSpec(CurrentLocation
,
15831 MoveConstructor
->getType()->castAs
<FunctionProtoType
>());
15832 MarkVTableUsed(CurrentLocation
, ClassDecl
);
15834 // Add a context note for diagnostics produced after this point.
15835 Scope
.addContextNote(CurrentLocation
);
15837 if (SetCtorInitializers(MoveConstructor
, /*AnyErrors=*/false)) {
15838 MoveConstructor
->setInvalidDecl();
15840 SourceLocation Loc
= MoveConstructor
->getEndLoc().isValid()
15841 ? MoveConstructor
->getEndLoc()
15842 : MoveConstructor
->getLocation();
15843 Sema::CompoundScopeRAII
CompoundScope(*this);
15844 MoveConstructor
->setBody(
15845 ActOnCompoundStmt(Loc
, Loc
, std::nullopt
, /*isStmtExpr=*/false)
15847 MoveConstructor
->markUsed(Context
);
15850 if (ASTMutationListener
*L
= getASTMutationListener()) {
15851 L
->CompletedImplicitDefinition(MoveConstructor
);
15855 bool Sema::isImplicitlyDeleted(FunctionDecl
*FD
) {
15856 return FD
->isDeleted() && FD
->isDefaulted() && isa
<CXXMethodDecl
>(FD
);
15859 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
15860 SourceLocation CurrentLocation
,
15861 CXXConversionDecl
*Conv
) {
15862 SynthesizedFunctionScope
Scope(*this, Conv
);
15863 assert(!Conv
->getReturnType()->isUndeducedType());
15865 QualType ConvRT
= Conv
->getType()->castAs
<FunctionType
>()->getReturnType();
15867 ConvRT
->getPointeeType()->castAs
<FunctionType
>()->getCallConv();
15869 CXXRecordDecl
*Lambda
= Conv
->getParent();
15870 FunctionDecl
*CallOp
= Lambda
->getLambdaCallOperator();
15871 FunctionDecl
*Invoker
=
15872 CallOp
->hasCXXExplicitFunctionObjectParameter() || CallOp
->isStatic()
15874 : Lambda
->getLambdaStaticInvoker(CC
);
15876 if (auto *TemplateArgs
= Conv
->getTemplateSpecializationArgs()) {
15877 CallOp
= InstantiateFunctionDeclaration(
15878 CallOp
->getDescribedFunctionTemplate(), TemplateArgs
, CurrentLocation
);
15882 if (CallOp
!= Invoker
) {
15883 Invoker
= InstantiateFunctionDeclaration(
15884 Invoker
->getDescribedFunctionTemplate(), TemplateArgs
,
15891 if (CallOp
->isInvalidDecl())
15894 // Mark the call operator referenced (and add to pending instantiations
15896 // For both the conversion and static-invoker template specializations
15897 // we construct their body's in this function, so no need to add them
15898 // to the PendingInstantiations.
15899 MarkFunctionReferenced(CurrentLocation
, CallOp
);
15901 if (Invoker
!= CallOp
) {
15902 // Fill in the __invoke function with a dummy implementation. IR generation
15903 // will fill in the actual details. Update its type in case it contained
15905 Invoker
->markUsed(Context
);
15906 Invoker
->setReferenced();
15907 Invoker
->setType(Conv
->getReturnType()->getPointeeType());
15908 Invoker
->setBody(new (Context
) CompoundStmt(Conv
->getLocation()));
15911 // Construct the body of the conversion function { return __invoke; }.
15912 Expr
*FunctionRef
= BuildDeclRefExpr(Invoker
, Invoker
->getType(), VK_LValue
,
15913 Conv
->getLocation());
15914 assert(FunctionRef
&& "Can't refer to __invoke function?");
15915 Stmt
*Return
= BuildReturnStmt(Conv
->getLocation(), FunctionRef
).get();
15916 Conv
->setBody(CompoundStmt::Create(Context
, Return
, FPOptionsOverride(),
15917 Conv
->getLocation(), Conv
->getLocation()));
15918 Conv
->markUsed(Context
);
15919 Conv
->setReferenced();
15921 if (ASTMutationListener
*L
= getASTMutationListener()) {
15922 L
->CompletedImplicitDefinition(Conv
);
15923 if (Invoker
!= CallOp
)
15924 L
->CompletedImplicitDefinition(Invoker
);
15928 void Sema::DefineImplicitLambdaToBlockPointerConversion(
15929 SourceLocation CurrentLocation
, CXXConversionDecl
*Conv
) {
15930 assert(!Conv
->getParent()->isGenericLambda());
15932 SynthesizedFunctionScope
Scope(*this, Conv
);
15934 // Copy-initialize the lambda object as needed to capture it.
15935 Expr
*This
= ActOnCXXThis(CurrentLocation
).get();
15936 Expr
*DerefThis
=CreateBuiltinUnaryOp(CurrentLocation
, UO_Deref
, This
).get();
15938 ExprResult BuildBlock
= BuildBlockForLambdaConversion(CurrentLocation
,
15939 Conv
->getLocation(),
15942 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
15943 // behavior. Note that only the general conversion function does this
15944 // (since it's unusable otherwise); in the case where we inline the
15945 // block literal, it has block literal lifetime semantics.
15946 if (!BuildBlock
.isInvalid() && !getLangOpts().ObjCAutoRefCount
)
15947 BuildBlock
= ImplicitCastExpr::Create(
15948 Context
, BuildBlock
.get()->getType(), CK_CopyAndAutoreleaseBlockObject
,
15949 BuildBlock
.get(), nullptr, VK_PRValue
, FPOptionsOverride());
15951 if (BuildBlock
.isInvalid()) {
15952 Diag(CurrentLocation
, diag::note_lambda_to_block_conv
);
15953 Conv
->setInvalidDecl();
15957 // Create the return statement that returns the block from the conversion
15959 StmtResult Return
= BuildReturnStmt(Conv
->getLocation(), BuildBlock
.get());
15960 if (Return
.isInvalid()) {
15961 Diag(CurrentLocation
, diag::note_lambda_to_block_conv
);
15962 Conv
->setInvalidDecl();
15966 // Set the body of the conversion function.
15967 Stmt
*ReturnS
= Return
.get();
15968 Conv
->setBody(CompoundStmt::Create(Context
, ReturnS
, FPOptionsOverride(),
15969 Conv
->getLocation(), Conv
->getLocation()));
15970 Conv
->markUsed(Context
);
15972 // We're done; notify the mutation listener, if any.
15973 if (ASTMutationListener
*L
= getASTMutationListener()) {
15974 L
->CompletedImplicitDefinition(Conv
);
15978 /// Determine whether the given list arguments contains exactly one
15979 /// "real" (non-default) argument.
15980 static bool hasOneRealArgument(MultiExprArg Args
) {
15981 switch (Args
.size()) {
15986 if (!Args
[1]->isDefaultArgument())
15991 return !Args
[0]->isDefaultArgument();
15998 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc
, QualType DeclInitType
,
15999 NamedDecl
*FoundDecl
,
16000 CXXConstructorDecl
*Constructor
,
16001 MultiExprArg ExprArgs
,
16002 bool HadMultipleCandidates
,
16003 bool IsListInitialization
,
16004 bool IsStdInitListInitialization
,
16005 bool RequiresZeroInit
,
16006 unsigned ConstructKind
,
16007 SourceRange ParenRange
) {
16008 bool Elidable
= false;
16010 // C++0x [class.copy]p34:
16011 // When certain criteria are met, an implementation is allowed to
16012 // omit the copy/move construction of a class object, even if the
16013 // copy/move constructor and/or destructor for the object have
16014 // side effects. [...]
16015 // - when a temporary class object that has not been bound to a
16016 // reference (12.2) would be copied/moved to a class object
16017 // with the same cv-unqualified type, the copy/move operation
16018 // can be omitted by constructing the temporary object
16019 // directly into the target of the omitted copy/move
16020 if (ConstructKind
== CXXConstructExpr::CK_Complete
&& Constructor
&&
16021 // FIXME: Converting constructors should also be accepted.
16022 // But to fix this, the logic that digs down into a CXXConstructExpr
16023 // to find the source object needs to handle it.
16024 // Right now it assumes the source object is passed directly as the
16026 Constructor
->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs
)) {
16027 Expr
*SubExpr
= ExprArgs
[0];
16028 // FIXME: Per above, this is also incorrect if we want to accept
16029 // converting constructors, as isTemporaryObject will
16030 // reject temporaries with different type from the
16031 // CXXRecord itself.
16032 Elidable
= SubExpr
->isTemporaryObject(
16033 Context
, cast
<CXXRecordDecl
>(FoundDecl
->getDeclContext()));
16036 return BuildCXXConstructExpr(ConstructLoc
, DeclInitType
,
16037 FoundDecl
, Constructor
,
16038 Elidable
, ExprArgs
, HadMultipleCandidates
,
16039 IsListInitialization
,
16040 IsStdInitListInitialization
, RequiresZeroInit
,
16041 ConstructKind
, ParenRange
);
16045 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc
, QualType DeclInitType
,
16046 NamedDecl
*FoundDecl
,
16047 CXXConstructorDecl
*Constructor
,
16049 MultiExprArg ExprArgs
,
16050 bool HadMultipleCandidates
,
16051 bool IsListInitialization
,
16052 bool IsStdInitListInitialization
,
16053 bool RequiresZeroInit
,
16054 unsigned ConstructKind
,
16055 SourceRange ParenRange
) {
16056 if (auto *Shadow
= dyn_cast
<ConstructorUsingShadowDecl
>(FoundDecl
)) {
16057 Constructor
= findInheritingConstructor(ConstructLoc
, Constructor
, Shadow
);
16058 // The only way to get here is if we did overlaod resolution to find the
16059 // shadow decl, so we don't need to worry about re-checking the trailing
16060 // requires clause.
16061 if (DiagnoseUseOfOverloadedDecl(Constructor
, ConstructLoc
))
16062 return ExprError();
16065 return BuildCXXConstructExpr(
16066 ConstructLoc
, DeclInitType
, Constructor
, Elidable
, ExprArgs
,
16067 HadMultipleCandidates
, IsListInitialization
, IsStdInitListInitialization
,
16068 RequiresZeroInit
, ConstructKind
, ParenRange
);
16071 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
16072 /// including handling of its default argument expressions.
16074 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc
, QualType DeclInitType
,
16075 CXXConstructorDecl
*Constructor
,
16077 MultiExprArg ExprArgs
,
16078 bool HadMultipleCandidates
,
16079 bool IsListInitialization
,
16080 bool IsStdInitListInitialization
,
16081 bool RequiresZeroInit
,
16082 unsigned ConstructKind
,
16083 SourceRange ParenRange
) {
16084 assert(declaresSameEntity(
16085 Constructor
->getParent(),
16086 DeclInitType
->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
16087 "given constructor for wrong type");
16088 MarkFunctionReferenced(ConstructLoc
, Constructor
);
16089 if (getLangOpts().CUDA
&& !CheckCUDACall(ConstructLoc
, Constructor
))
16090 return ExprError();
16092 return CheckForImmediateInvocation(
16093 CXXConstructExpr::Create(
16094 Context
, DeclInitType
, ConstructLoc
, Constructor
, Elidable
, ExprArgs
,
16095 HadMultipleCandidates
, IsListInitialization
,
16096 IsStdInitListInitialization
, RequiresZeroInit
,
16097 static_cast<CXXConstructExpr::ConstructionKind
>(ConstructKind
),
16102 void Sema::FinalizeVarWithDestructor(VarDecl
*VD
, const RecordType
*Record
) {
16103 if (VD
->isInvalidDecl()) return;
16104 // If initializing the variable failed, don't also diagnose problems with
16105 // the destructor, they're likely related.
16106 if (VD
->getInit() && VD
->getInit()->containsErrors())
16109 CXXRecordDecl
*ClassDecl
= cast
<CXXRecordDecl
>(Record
->getDecl());
16110 if (ClassDecl
->isInvalidDecl()) return;
16111 if (ClassDecl
->hasIrrelevantDestructor()) return;
16112 if (ClassDecl
->isDependentContext()) return;
16114 if (VD
->isNoDestroy(getASTContext()))
16117 CXXDestructorDecl
*Destructor
= LookupDestructor(ClassDecl
);
16118 // The result of `LookupDestructor` might be nullptr if the destructor is
16119 // invalid, in which case it is marked as `IneligibleOrNotSelected` and
16120 // will not be selected by `CXXRecordDecl::getDestructor()`.
16123 // If this is an array, we'll require the destructor during initialization, so
16124 // we can skip over this. We still want to emit exit-time destructor warnings
16126 if (!VD
->getType()->isArrayType()) {
16127 MarkFunctionReferenced(VD
->getLocation(), Destructor
);
16128 CheckDestructorAccess(VD
->getLocation(), Destructor
,
16129 PDiag(diag::err_access_dtor_var
)
16130 << VD
->getDeclName() << VD
->getType());
16131 DiagnoseUseOfDecl(Destructor
, VD
->getLocation());
16134 if (Destructor
->isTrivial()) return;
16136 // If the destructor is constexpr, check whether the variable has constant
16137 // destruction now.
16138 if (Destructor
->isConstexpr()) {
16139 bool HasConstantInit
= false;
16140 if (VD
->getInit() && !VD
->getInit()->isValueDependent())
16141 HasConstantInit
= VD
->evaluateValue();
16142 SmallVector
<PartialDiagnosticAt
, 8> Notes
;
16143 if (!VD
->evaluateDestruction(Notes
) && VD
->isConstexpr() &&
16145 Diag(VD
->getLocation(),
16146 diag::err_constexpr_var_requires_const_destruction
) << VD
;
16147 for (unsigned I
= 0, N
= Notes
.size(); I
!= N
; ++I
)
16148 Diag(Notes
[I
].first
, Notes
[I
].second
);
16152 if (!VD
->hasGlobalStorage() || !VD
->needsDestruction(Context
))
16155 // Emit warning for non-trivial dtor in global scope (a real global,
16156 // class-static, function-static).
16157 Diag(VD
->getLocation(), diag::warn_exit_time_destructor
);
16159 // TODO: this should be re-enabled for static locals by !CXAAtExit
16160 if (!VD
->isStaticLocal())
16161 Diag(VD
->getLocation(), diag::warn_global_destructor
);
16164 /// Given a constructor and the set of arguments provided for the
16165 /// constructor, convert the arguments and add any required default arguments
16166 /// to form a proper call to this constructor.
16168 /// \returns true if an error occurred, false otherwise.
16169 bool Sema::CompleteConstructorCall(CXXConstructorDecl
*Constructor
,
16170 QualType DeclInitType
, MultiExprArg ArgsPtr
,
16171 SourceLocation Loc
,
16172 SmallVectorImpl
<Expr
*> &ConvertedArgs
,
16173 bool AllowExplicit
,
16174 bool IsListInitialization
) {
16175 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
16176 unsigned NumArgs
= ArgsPtr
.size();
16177 Expr
**Args
= ArgsPtr
.data();
16179 const auto *Proto
= Constructor
->getType()->castAs
<FunctionProtoType
>();
16180 unsigned NumParams
= Proto
->getNumParams();
16182 // If too few arguments are available, we'll fill in the rest with defaults.
16183 if (NumArgs
< NumParams
)
16184 ConvertedArgs
.reserve(NumParams
);
16186 ConvertedArgs
.reserve(NumArgs
);
16188 VariadicCallType CallType
=
16189 Proto
->isVariadic() ? VariadicConstructor
: VariadicDoesNotApply
;
16190 SmallVector
<Expr
*, 8> AllArgs
;
16191 bool Invalid
= GatherArgumentsForCall(
16192 Loc
, Constructor
, Proto
, 0, llvm::ArrayRef(Args
, NumArgs
), AllArgs
,
16193 CallType
, AllowExplicit
, IsListInitialization
);
16194 ConvertedArgs
.append(AllArgs
.begin(), AllArgs
.end());
16196 DiagnoseSentinelCalls(Constructor
, Loc
, AllArgs
);
16198 CheckConstructorCall(Constructor
, DeclInitType
,
16199 llvm::ArrayRef(AllArgs
.data(), AllArgs
.size()), Proto
,
16206 CheckOperatorNewDeleteDeclarationScope(Sema
&SemaRef
,
16207 const FunctionDecl
*FnDecl
) {
16208 const DeclContext
*DC
= FnDecl
->getDeclContext()->getRedeclContext();
16209 if (isa
<NamespaceDecl
>(DC
)) {
16210 return SemaRef
.Diag(FnDecl
->getLocation(),
16211 diag::err_operator_new_delete_declared_in_namespace
)
16212 << FnDecl
->getDeclName();
16215 if (isa
<TranslationUnitDecl
>(DC
) &&
16216 FnDecl
->getStorageClass() == SC_Static
) {
16217 return SemaRef
.Diag(FnDecl
->getLocation(),
16218 diag::err_operator_new_delete_declared_static
)
16219 << FnDecl
->getDeclName();
16225 static CanQualType
RemoveAddressSpaceFromPtr(Sema
&SemaRef
,
16226 const PointerType
*PtrTy
) {
16227 auto &Ctx
= SemaRef
.Context
;
16228 Qualifiers PtrQuals
= PtrTy
->getPointeeType().getQualifiers();
16229 PtrQuals
.removeAddressSpace();
16230 return Ctx
.getPointerType(Ctx
.getCanonicalType(Ctx
.getQualifiedType(
16231 PtrTy
->getPointeeType().getUnqualifiedType(), PtrQuals
)));
16235 CheckOperatorNewDeleteTypes(Sema
&SemaRef
, const FunctionDecl
*FnDecl
,
16236 CanQualType ExpectedResultType
,
16237 CanQualType ExpectedFirstParamType
,
16238 unsigned DependentParamTypeDiag
,
16239 unsigned InvalidParamTypeDiag
) {
16240 QualType ResultType
=
16241 FnDecl
->getType()->castAs
<FunctionType
>()->getReturnType();
16243 if (SemaRef
.getLangOpts().OpenCLCPlusPlus
) {
16244 // The operator is valid on any address space for OpenCL.
16245 // Drop address space from actual and expected result types.
16246 if (const auto *PtrTy
= ResultType
->getAs
<PointerType
>())
16247 ResultType
= RemoveAddressSpaceFromPtr(SemaRef
, PtrTy
);
16249 if (auto ExpectedPtrTy
= ExpectedResultType
->getAs
<PointerType
>())
16250 ExpectedResultType
= RemoveAddressSpaceFromPtr(SemaRef
, ExpectedPtrTy
);
16253 // Check that the result type is what we expect.
16254 if (SemaRef
.Context
.getCanonicalType(ResultType
) != ExpectedResultType
) {
16255 // Reject even if the type is dependent; an operator delete function is
16256 // required to have a non-dependent result type.
16257 return SemaRef
.Diag(
16258 FnDecl
->getLocation(),
16259 ResultType
->isDependentType()
16260 ? diag::err_operator_new_delete_dependent_result_type
16261 : diag::err_operator_new_delete_invalid_result_type
)
16262 << FnDecl
->getDeclName() << ExpectedResultType
;
16265 // A function template must have at least 2 parameters.
16266 if (FnDecl
->getDescribedFunctionTemplate() && FnDecl
->getNumParams() < 2)
16267 return SemaRef
.Diag(FnDecl
->getLocation(),
16268 diag::err_operator_new_delete_template_too_few_parameters
)
16269 << FnDecl
->getDeclName();
16271 // The function decl must have at least 1 parameter.
16272 if (FnDecl
->getNumParams() == 0)
16273 return SemaRef
.Diag(FnDecl
->getLocation(),
16274 diag::err_operator_new_delete_too_few_parameters
)
16275 << FnDecl
->getDeclName();
16277 QualType FirstParamType
= FnDecl
->getParamDecl(0)->getType();
16278 if (SemaRef
.getLangOpts().OpenCLCPlusPlus
) {
16279 // The operator is valid on any address space for OpenCL.
16280 // Drop address space from actual and expected first parameter types.
16281 if (const auto *PtrTy
=
16282 FnDecl
->getParamDecl(0)->getType()->getAs
<PointerType
>())
16283 FirstParamType
= RemoveAddressSpaceFromPtr(SemaRef
, PtrTy
);
16285 if (auto ExpectedPtrTy
= ExpectedFirstParamType
->getAs
<PointerType
>())
16286 ExpectedFirstParamType
=
16287 RemoveAddressSpaceFromPtr(SemaRef
, ExpectedPtrTy
);
16290 // Check that the first parameter type is what we expect.
16291 if (SemaRef
.Context
.getCanonicalType(FirstParamType
).getUnqualifiedType() !=
16292 ExpectedFirstParamType
) {
16293 // The first parameter type is not allowed to be dependent. As a tentative
16294 // DR resolution, we allow a dependent parameter type if it is the right
16295 // type anyway, to allow destroying operator delete in class templates.
16296 return SemaRef
.Diag(FnDecl
->getLocation(), FirstParamType
->isDependentType()
16297 ? DependentParamTypeDiag
16298 : InvalidParamTypeDiag
)
16299 << FnDecl
->getDeclName() << ExpectedFirstParamType
;
16306 CheckOperatorNewDeclaration(Sema
&SemaRef
, const FunctionDecl
*FnDecl
) {
16307 // C++ [basic.stc.dynamic.allocation]p1:
16308 // A program is ill-formed if an allocation function is declared in a
16309 // namespace scope other than global scope or declared static in global
16311 if (CheckOperatorNewDeleteDeclarationScope(SemaRef
, FnDecl
))
16314 CanQualType SizeTy
=
16315 SemaRef
.Context
.getCanonicalType(SemaRef
.Context
.getSizeType());
16317 // C++ [basic.stc.dynamic.allocation]p1:
16318 // The return type shall be void*. The first parameter shall have type
16320 if (CheckOperatorNewDeleteTypes(SemaRef
, FnDecl
, SemaRef
.Context
.VoidPtrTy
,
16322 diag::err_operator_new_dependent_param_type
,
16323 diag::err_operator_new_param_type
))
16326 // C++ [basic.stc.dynamic.allocation]p1:
16327 // The first parameter shall not have an associated default argument.
16328 if (FnDecl
->getParamDecl(0)->hasDefaultArg())
16329 return SemaRef
.Diag(FnDecl
->getLocation(),
16330 diag::err_operator_new_default_arg
)
16331 << FnDecl
->getDeclName() << FnDecl
->getParamDecl(0)->getDefaultArgRange();
16337 CheckOperatorDeleteDeclaration(Sema
&SemaRef
, FunctionDecl
*FnDecl
) {
16338 // C++ [basic.stc.dynamic.deallocation]p1:
16339 // A program is ill-formed if deallocation functions are declared in a
16340 // namespace scope other than global scope or declared static in global
16342 if (CheckOperatorNewDeleteDeclarationScope(SemaRef
, FnDecl
))
16345 auto *MD
= dyn_cast
<CXXMethodDecl
>(FnDecl
);
16348 // Within a class C, the first parameter of a destroying operator delete
16349 // shall be of type C *. The first parameter of any other deallocation
16350 // function shall be of type void *.
16351 CanQualType ExpectedFirstParamType
=
16352 MD
&& MD
->isDestroyingOperatorDelete()
16353 ? SemaRef
.Context
.getCanonicalType(SemaRef
.Context
.getPointerType(
16354 SemaRef
.Context
.getRecordType(MD
->getParent())))
16355 : SemaRef
.Context
.VoidPtrTy
;
16357 // C++ [basic.stc.dynamic.deallocation]p2:
16358 // Each deallocation function shall return void
16359 if (CheckOperatorNewDeleteTypes(
16360 SemaRef
, FnDecl
, SemaRef
.Context
.VoidTy
, ExpectedFirstParamType
,
16361 diag::err_operator_delete_dependent_param_type
,
16362 diag::err_operator_delete_param_type
))
16366 // A destroying operator delete shall be a usual deallocation function.
16367 if (MD
&& !MD
->getParent()->isDependentContext() &&
16368 MD
->isDestroyingOperatorDelete() &&
16369 !SemaRef
.isUsualDeallocationFunction(MD
)) {
16370 SemaRef
.Diag(MD
->getLocation(),
16371 diag::err_destroying_operator_delete_not_usual
);
16378 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
16379 /// of this overloaded operator is well-formed. If so, returns false;
16380 /// otherwise, emits appropriate diagnostics and returns true.
16381 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl
*FnDecl
) {
16382 assert(FnDecl
&& FnDecl
->isOverloadedOperator() &&
16383 "Expected an overloaded operator declaration");
16385 OverloadedOperatorKind Op
= FnDecl
->getOverloadedOperator();
16387 // C++ [over.oper]p5:
16388 // The allocation and deallocation functions, operator new,
16389 // operator new[], operator delete and operator delete[], are
16390 // described completely in 3.7.3. The attributes and restrictions
16391 // found in the rest of this subclause do not apply to them unless
16392 // explicitly stated in 3.7.3.
16393 if (Op
== OO_Delete
|| Op
== OO_Array_Delete
)
16394 return CheckOperatorDeleteDeclaration(*this, FnDecl
);
16396 if (Op
== OO_New
|| Op
== OO_Array_New
)
16397 return CheckOperatorNewDeclaration(*this, FnDecl
);
16399 // C++ [over.oper]p7:
16400 // An operator function shall either be a member function or
16401 // be a non-member function and have at least one parameter
16402 // whose type is a class, a reference to a class, an enumeration,
16403 // or a reference to an enumeration.
16404 // Note: Before C++23, a member function could not be static. The only member
16405 // function allowed to be static is the call operator function.
16406 if (CXXMethodDecl
*MethodDecl
= dyn_cast
<CXXMethodDecl
>(FnDecl
)) {
16407 if (MethodDecl
->isStatic()) {
16408 if (Op
== OO_Call
|| Op
== OO_Subscript
)
16409 Diag(FnDecl
->getLocation(),
16410 (LangOpts
.CPlusPlus23
16411 ? diag::warn_cxx20_compat_operator_overload_static
16412 : diag::ext_operator_overload_static
))
16415 return Diag(FnDecl
->getLocation(), diag::err_operator_overload_static
)
16419 bool ClassOrEnumParam
= false;
16420 for (auto *Param
: FnDecl
->parameters()) {
16421 QualType ParamType
= Param
->getType().getNonReferenceType();
16422 if (ParamType
->isDependentType() || ParamType
->isRecordType() ||
16423 ParamType
->isEnumeralType()) {
16424 ClassOrEnumParam
= true;
16429 if (!ClassOrEnumParam
)
16430 return Diag(FnDecl
->getLocation(),
16431 diag::err_operator_overload_needs_class_or_enum
)
16432 << FnDecl
->getDeclName();
16435 // C++ [over.oper]p8:
16436 // An operator function cannot have default arguments (8.3.6),
16437 // except where explicitly stated below.
16439 // Only the function-call operator (C++ [over.call]p1) and the subscript
16440 // operator (CWG2507) allow default arguments.
16441 if (Op
!= OO_Call
) {
16442 ParmVarDecl
*FirstDefaultedParam
= nullptr;
16443 for (auto *Param
: FnDecl
->parameters()) {
16444 if (Param
->hasDefaultArg()) {
16445 FirstDefaultedParam
= Param
;
16449 if (FirstDefaultedParam
) {
16450 if (Op
== OO_Subscript
) {
16451 Diag(FnDecl
->getLocation(), LangOpts
.CPlusPlus23
16452 ? diag::ext_subscript_overload
16453 : diag::error_subscript_overload
)
16454 << FnDecl
->getDeclName() << 1
16455 << FirstDefaultedParam
->getDefaultArgRange();
16457 return Diag(FirstDefaultedParam
->getLocation(),
16458 diag::err_operator_overload_default_arg
)
16459 << FnDecl
->getDeclName()
16460 << FirstDefaultedParam
->getDefaultArgRange();
16465 static const bool OperatorUses
[NUM_OVERLOADED_OPERATORS
][3] = {
16466 { false, false, false }
16467 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
16468 , { Unary, Binary, MemberOnly }
16469 #include "clang/Basic/OperatorKinds.def"
16472 bool CanBeUnaryOperator
= OperatorUses
[Op
][0];
16473 bool CanBeBinaryOperator
= OperatorUses
[Op
][1];
16474 bool MustBeMemberOperator
= OperatorUses
[Op
][2];
16476 // C++ [over.oper]p8:
16477 // [...] Operator functions cannot have more or fewer parameters
16478 // than the number required for the corresponding operator, as
16479 // described in the rest of this subclause.
16480 unsigned NumParams
= FnDecl
->getNumParams() +
16481 (isa
<CXXMethodDecl
>(FnDecl
) &&
16482 !FnDecl
->hasCXXExplicitFunctionObjectParameter()
16485 if (Op
!= OO_Call
&& Op
!= OO_Subscript
&&
16486 ((NumParams
== 1 && !CanBeUnaryOperator
) ||
16487 (NumParams
== 2 && !CanBeBinaryOperator
) || (NumParams
< 1) ||
16488 (NumParams
> 2))) {
16489 // We have the wrong number of parameters.
16490 unsigned ErrorKind
;
16491 if (CanBeUnaryOperator
&& CanBeBinaryOperator
) {
16492 ErrorKind
= 2; // 2 -> unary or binary.
16493 } else if (CanBeUnaryOperator
) {
16494 ErrorKind
= 0; // 0 -> unary
16496 assert(CanBeBinaryOperator
&&
16497 "All non-call overloaded operators are unary or binary!");
16498 ErrorKind
= 1; // 1 -> binary
16500 return Diag(FnDecl
->getLocation(), diag::err_operator_overload_must_be
)
16501 << FnDecl
->getDeclName() << NumParams
<< ErrorKind
;
16504 if (Op
== OO_Subscript
&& NumParams
!= 2) {
16505 Diag(FnDecl
->getLocation(), LangOpts
.CPlusPlus23
16506 ? diag::ext_subscript_overload
16507 : diag::error_subscript_overload
)
16508 << FnDecl
->getDeclName() << (NumParams
== 1 ? 0 : 2);
16511 // Overloaded operators other than operator() and operator[] cannot be
16513 if (Op
!= OO_Call
&&
16514 FnDecl
->getType()->castAs
<FunctionProtoType
>()->isVariadic()) {
16515 return Diag(FnDecl
->getLocation(), diag::err_operator_overload_variadic
)
16516 << FnDecl
->getDeclName();
16519 // Some operators must be member functions.
16520 if (MustBeMemberOperator
&& !isa
<CXXMethodDecl
>(FnDecl
)) {
16521 return Diag(FnDecl
->getLocation(),
16522 diag::err_operator_overload_must_be_member
)
16523 << FnDecl
->getDeclName();
16526 // C++ [over.inc]p1:
16527 // The user-defined function called operator++ implements the
16528 // prefix and postfix ++ operator. If this function is a member
16529 // function with no parameters, or a non-member function with one
16530 // parameter of class or enumeration type, it defines the prefix
16531 // increment operator ++ for objects of that type. If the function
16532 // is a member function with one parameter (which shall be of type
16533 // int) or a non-member function with two parameters (the second
16534 // of which shall be of type int), it defines the postfix
16535 // increment operator ++ for objects of that type.
16536 if ((Op
== OO_PlusPlus
|| Op
== OO_MinusMinus
) && NumParams
== 2) {
16537 ParmVarDecl
*LastParam
= FnDecl
->getParamDecl(FnDecl
->getNumParams() - 1);
16538 QualType ParamType
= LastParam
->getType();
16540 if (!ParamType
->isSpecificBuiltinType(BuiltinType::Int
) &&
16541 !ParamType
->isDependentType())
16542 return Diag(LastParam
->getLocation(),
16543 diag::err_operator_overload_post_incdec_must_be_int
)
16544 << LastParam
->getType() << (Op
== OO_MinusMinus
);
16551 checkLiteralOperatorTemplateParameterList(Sema
&SemaRef
,
16552 FunctionTemplateDecl
*TpDecl
) {
16553 TemplateParameterList
*TemplateParams
= TpDecl
->getTemplateParameters();
16555 // Must have one or two template parameters.
16556 if (TemplateParams
->size() == 1) {
16557 NonTypeTemplateParmDecl
*PmDecl
=
16558 dyn_cast
<NonTypeTemplateParmDecl
>(TemplateParams
->getParam(0));
16560 // The template parameter must be a char parameter pack.
16561 if (PmDecl
&& PmDecl
->isTemplateParameterPack() &&
16562 SemaRef
.Context
.hasSameType(PmDecl
->getType(), SemaRef
.Context
.CharTy
))
16565 // C++20 [over.literal]p5:
16566 // A string literal operator template is a literal operator template
16567 // whose template-parameter-list comprises a single non-type
16568 // template-parameter of class type.
16570 // As a DR resolution, we also allow placeholders for deduced class
16571 // template specializations.
16572 if (SemaRef
.getLangOpts().CPlusPlus20
&& PmDecl
&&
16573 !PmDecl
->isTemplateParameterPack() &&
16574 (PmDecl
->getType()->isRecordType() ||
16575 PmDecl
->getType()->getAs
<DeducedTemplateSpecializationType
>()))
16577 } else if (TemplateParams
->size() == 2) {
16578 TemplateTypeParmDecl
*PmType
=
16579 dyn_cast
<TemplateTypeParmDecl
>(TemplateParams
->getParam(0));
16580 NonTypeTemplateParmDecl
*PmArgs
=
16581 dyn_cast
<NonTypeTemplateParmDecl
>(TemplateParams
->getParam(1));
16583 // The second template parameter must be a parameter pack with the
16584 // first template parameter as its type.
16585 if (PmType
&& PmArgs
&& !PmType
->isTemplateParameterPack() &&
16586 PmArgs
->isTemplateParameterPack()) {
16587 const TemplateTypeParmType
*TArgs
=
16588 PmArgs
->getType()->getAs
<TemplateTypeParmType
>();
16589 if (TArgs
&& TArgs
->getDepth() == PmType
->getDepth() &&
16590 TArgs
->getIndex() == PmType
->getIndex()) {
16591 if (!SemaRef
.inTemplateInstantiation())
16592 SemaRef
.Diag(TpDecl
->getLocation(),
16593 diag::ext_string_literal_operator_template
);
16599 SemaRef
.Diag(TpDecl
->getTemplateParameters()->getSourceRange().getBegin(),
16600 diag::err_literal_operator_template
)
16601 << TpDecl
->getTemplateParameters()->getSourceRange();
16605 /// CheckLiteralOperatorDeclaration - Check whether the declaration
16606 /// of this literal operator function is well-formed. If so, returns
16607 /// false; otherwise, emits appropriate diagnostics and returns true.
16608 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl
*FnDecl
) {
16609 if (isa
<CXXMethodDecl
>(FnDecl
)) {
16610 Diag(FnDecl
->getLocation(), diag::err_literal_operator_outside_namespace
)
16611 << FnDecl
->getDeclName();
16615 if (FnDecl
->isExternC()) {
16616 Diag(FnDecl
->getLocation(), diag::err_literal_operator_extern_c
);
16617 if (const LinkageSpecDecl
*LSD
=
16618 FnDecl
->getDeclContext()->getExternCContext())
16619 Diag(LSD
->getExternLoc(), diag::note_extern_c_begins_here
);
16623 // This might be the definition of a literal operator template.
16624 FunctionTemplateDecl
*TpDecl
= FnDecl
->getDescribedFunctionTemplate();
16626 // This might be a specialization of a literal operator template.
16628 TpDecl
= FnDecl
->getPrimaryTemplate();
16630 // template <char...> type operator "" name() and
16631 // template <class T, T...> type operator "" name() are the only valid
16632 // template signatures, and the only valid signatures with no parameters.
16634 // C++20 also allows template <SomeClass T> type operator "" name().
16636 if (FnDecl
->param_size() != 0) {
16637 Diag(FnDecl
->getLocation(),
16638 diag::err_literal_operator_template_with_params
);
16642 if (checkLiteralOperatorTemplateParameterList(*this, TpDecl
))
16645 } else if (FnDecl
->param_size() == 1) {
16646 const ParmVarDecl
*Param
= FnDecl
->getParamDecl(0);
16648 QualType ParamType
= Param
->getType().getUnqualifiedType();
16650 // Only unsigned long long int, long double, any character type, and const
16651 // char * are allowed as the only parameters.
16652 if (ParamType
->isSpecificBuiltinType(BuiltinType::ULongLong
) ||
16653 ParamType
->isSpecificBuiltinType(BuiltinType::LongDouble
) ||
16654 Context
.hasSameType(ParamType
, Context
.CharTy
) ||
16655 Context
.hasSameType(ParamType
, Context
.WideCharTy
) ||
16656 Context
.hasSameType(ParamType
, Context
.Char8Ty
) ||
16657 Context
.hasSameType(ParamType
, Context
.Char16Ty
) ||
16658 Context
.hasSameType(ParamType
, Context
.Char32Ty
)) {
16659 } else if (const PointerType
*Ptr
= ParamType
->getAs
<PointerType
>()) {
16660 QualType InnerType
= Ptr
->getPointeeType();
16662 // Pointer parameter must be a const char *.
16663 if (!(Context
.hasSameType(InnerType
.getUnqualifiedType(),
16665 InnerType
.isConstQualified() && !InnerType
.isVolatileQualified())) {
16666 Diag(Param
->getSourceRange().getBegin(),
16667 diag::err_literal_operator_param
)
16668 << ParamType
<< "'const char *'" << Param
->getSourceRange();
16672 } else if (ParamType
->isRealFloatingType()) {
16673 Diag(Param
->getSourceRange().getBegin(), diag::err_literal_operator_param
)
16674 << ParamType
<< Context
.LongDoubleTy
<< Param
->getSourceRange();
16677 } else if (ParamType
->isIntegerType()) {
16678 Diag(Param
->getSourceRange().getBegin(), diag::err_literal_operator_param
)
16679 << ParamType
<< Context
.UnsignedLongLongTy
<< Param
->getSourceRange();
16683 Diag(Param
->getSourceRange().getBegin(),
16684 diag::err_literal_operator_invalid_param
)
16685 << ParamType
<< Param
->getSourceRange();
16689 } else if (FnDecl
->param_size() == 2) {
16690 FunctionDecl::param_iterator Param
= FnDecl
->param_begin();
16692 // First, verify that the first parameter is correct.
16694 QualType FirstParamType
= (*Param
)->getType().getUnqualifiedType();
16696 // Two parameter function must have a pointer to const as a
16697 // first parameter; let's strip those qualifiers.
16698 const PointerType
*PT
= FirstParamType
->getAs
<PointerType
>();
16701 Diag((*Param
)->getSourceRange().getBegin(),
16702 diag::err_literal_operator_param
)
16703 << FirstParamType
<< "'const char *'" << (*Param
)->getSourceRange();
16707 QualType PointeeType
= PT
->getPointeeType();
16708 // First parameter must be const
16709 if (!PointeeType
.isConstQualified() || PointeeType
.isVolatileQualified()) {
16710 Diag((*Param
)->getSourceRange().getBegin(),
16711 diag::err_literal_operator_param
)
16712 << FirstParamType
<< "'const char *'" << (*Param
)->getSourceRange();
16716 QualType InnerType
= PointeeType
.getUnqualifiedType();
16717 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
16718 // const char32_t* are allowed as the first parameter to a two-parameter
16720 if (!(Context
.hasSameType(InnerType
, Context
.CharTy
) ||
16721 Context
.hasSameType(InnerType
, Context
.WideCharTy
) ||
16722 Context
.hasSameType(InnerType
, Context
.Char8Ty
) ||
16723 Context
.hasSameType(InnerType
, Context
.Char16Ty
) ||
16724 Context
.hasSameType(InnerType
, Context
.Char32Ty
))) {
16725 Diag((*Param
)->getSourceRange().getBegin(),
16726 diag::err_literal_operator_param
)
16727 << FirstParamType
<< "'const char *'" << (*Param
)->getSourceRange();
16731 // Move on to the second and final parameter.
16734 // The second parameter must be a std::size_t.
16735 QualType SecondParamType
= (*Param
)->getType().getUnqualifiedType();
16736 if (!Context
.hasSameType(SecondParamType
, Context
.getSizeType())) {
16737 Diag((*Param
)->getSourceRange().getBegin(),
16738 diag::err_literal_operator_param
)
16739 << SecondParamType
<< Context
.getSizeType()
16740 << (*Param
)->getSourceRange();
16744 Diag(FnDecl
->getLocation(), diag::err_literal_operator_bad_param_count
);
16748 // Parameters are good.
16750 // A parameter-declaration-clause containing a default argument is not
16751 // equivalent to any of the permitted forms.
16752 for (auto *Param
: FnDecl
->parameters()) {
16753 if (Param
->hasDefaultArg()) {
16754 Diag(Param
->getDefaultArgRange().getBegin(),
16755 diag::err_literal_operator_default_argument
)
16756 << Param
->getDefaultArgRange();
16761 const IdentifierInfo
*II
= FnDecl
->getDeclName().getCXXLiteralIdentifier();
16762 ReservedLiteralSuffixIdStatus Status
= II
->isReservedLiteralSuffixId();
16763 if (Status
!= ReservedLiteralSuffixIdStatus::NotReserved
&&
16764 !getSourceManager().isInSystemHeader(FnDecl
->getLocation())) {
16765 // C++23 [usrlit.suffix]p1:
16766 // Literal suffix identifiers that do not start with an underscore are
16767 // reserved for future standardization. Literal suffix identifiers that
16768 // contain a double underscore __ are reserved for use by C++
16769 // implementations.
16770 Diag(FnDecl
->getLocation(), diag::warn_user_literal_reserved
)
16771 << static_cast<int>(Status
)
16772 << StringLiteralParser::isValidUDSuffix(getLangOpts(), II
->getName());
16778 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
16779 /// linkage specification, including the language and (if present)
16780 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
16781 /// language string literal. LBraceLoc, if valid, provides the location of
16782 /// the '{' brace. Otherwise, this linkage specification does not
16783 /// have any braces.
16784 Decl
*Sema::ActOnStartLinkageSpecification(Scope
*S
, SourceLocation ExternLoc
,
16786 SourceLocation LBraceLoc
) {
16787 StringLiteral
*Lit
= cast
<StringLiteral
>(LangStr
);
16788 assert(Lit
->isUnevaluated() && "Unexpected string literal kind");
16790 StringRef Lang
= Lit
->getString();
16791 LinkageSpecLanguageIDs Language
;
16793 Language
= LinkageSpecLanguageIDs::C
;
16794 else if (Lang
== "C++")
16795 Language
= LinkageSpecLanguageIDs::CXX
;
16797 Diag(LangStr
->getExprLoc(), diag::err_language_linkage_spec_unknown
)
16798 << LangStr
->getSourceRange();
16802 // FIXME: Add all the various semantics of linkage specifications
16804 LinkageSpecDecl
*D
= LinkageSpecDecl::Create(Context
, CurContext
, ExternLoc
,
16805 LangStr
->getExprLoc(), Language
,
16806 LBraceLoc
.isValid());
16808 /// C++ [module.unit]p7.2.3
16809 /// - Otherwise, if the declaration
16812 /// - appears within a linkage-specification,
16813 /// it is attached to the global module.
16815 /// If the declaration is already in global module fragment, we don't
16816 /// need to attach it again.
16817 if (getLangOpts().CPlusPlusModules
&& isCurrentModulePurview()) {
16818 Module
*GlobalModule
= PushImplicitGlobalModuleFragment(
16819 ExternLoc
, /*IsExported=*/D
->isInExportDeclContext());
16820 D
->setLocalOwningModule(GlobalModule
);
16823 CurContext
->addDecl(D
);
16824 PushDeclContext(S
, D
);
16828 /// ActOnFinishLinkageSpecification - Complete the definition of
16829 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
16830 /// valid, it's the position of the closing '}' brace in a linkage
16831 /// specification that uses braces.
16832 Decl
*Sema::ActOnFinishLinkageSpecification(Scope
*S
,
16834 SourceLocation RBraceLoc
) {
16835 if (RBraceLoc
.isValid()) {
16836 LinkageSpecDecl
* LSDecl
= cast
<LinkageSpecDecl
>(LinkageSpec
);
16837 LSDecl
->setRBraceLoc(RBraceLoc
);
16840 // If the current module doesn't has Parent, it implies that the
16841 // LinkageSpec isn't in the module created by itself. So we don't
16843 if (getLangOpts().CPlusPlusModules
&& getCurrentModule() &&
16844 getCurrentModule()->isImplicitGlobalModule() &&
16845 getCurrentModule()->Parent
)
16846 PopImplicitGlobalModuleFragment();
16849 return LinkageSpec
;
16852 Decl
*Sema::ActOnEmptyDeclaration(Scope
*S
,
16853 const ParsedAttributesView
&AttrList
,
16854 SourceLocation SemiLoc
) {
16855 Decl
*ED
= EmptyDecl::Create(Context
, CurContext
, SemiLoc
);
16856 // Attribute declarations appertain to empty declaration so we handle
16858 ProcessDeclAttributeList(S
, ED
, AttrList
);
16860 CurContext
->addDecl(ED
);
16864 /// Perform semantic analysis for the variable declaration that
16865 /// occurs within a C++ catch clause, returning the newly-created
16867 VarDecl
*Sema::BuildExceptionDeclaration(Scope
*S
,
16868 TypeSourceInfo
*TInfo
,
16869 SourceLocation StartLoc
,
16870 SourceLocation Loc
,
16871 IdentifierInfo
*Name
) {
16872 bool Invalid
= false;
16873 QualType ExDeclType
= TInfo
->getType();
16875 // Arrays and functions decay.
16876 if (ExDeclType
->isArrayType())
16877 ExDeclType
= Context
.getArrayDecayedType(ExDeclType
);
16878 else if (ExDeclType
->isFunctionType())
16879 ExDeclType
= Context
.getPointerType(ExDeclType
);
16881 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
16882 // The exception-declaration shall not denote a pointer or reference to an
16883 // incomplete type, other than [cv] void*.
16884 // N2844 forbids rvalue references.
16885 if (!ExDeclType
->isDependentType() && ExDeclType
->isRValueReferenceType()) {
16886 Diag(Loc
, diag::err_catch_rvalue_ref
);
16890 if (ExDeclType
->isVariablyModifiedType()) {
16891 Diag(Loc
, diag::err_catch_variably_modified
) << ExDeclType
;
16895 QualType BaseType
= ExDeclType
;
16896 int Mode
= 0; // 0 for direct type, 1 for pointer, 2 for reference
16897 unsigned DK
= diag::err_catch_incomplete
;
16898 if (const PointerType
*Ptr
= BaseType
->getAs
<PointerType
>()) {
16899 BaseType
= Ptr
->getPointeeType();
16901 DK
= diag::err_catch_incomplete_ptr
;
16902 } else if (const ReferenceType
*Ref
= BaseType
->getAs
<ReferenceType
>()) {
16903 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
16904 BaseType
= Ref
->getPointeeType();
16906 DK
= diag::err_catch_incomplete_ref
;
16908 if (!Invalid
&& (Mode
== 0 || !BaseType
->isVoidType()) &&
16909 !BaseType
->isDependentType() && RequireCompleteType(Loc
, BaseType
, DK
))
16912 if (!Invalid
&& BaseType
.isWebAssemblyReferenceType()) {
16913 Diag(Loc
, diag::err_wasm_reftype_tc
) << 1;
16917 if (!Invalid
&& Mode
!= 1 && BaseType
->isSizelessType()) {
16918 Diag(Loc
, diag::err_catch_sizeless
) << (Mode
== 2 ? 1 : 0) << BaseType
;
16922 if (!Invalid
&& !ExDeclType
->isDependentType() &&
16923 RequireNonAbstractType(Loc
, ExDeclType
,
16924 diag::err_abstract_type_in_decl
,
16925 AbstractVariableType
))
16928 // Only the non-fragile NeXT runtime currently supports C++ catches
16929 // of ObjC types, and no runtime supports catching ObjC types by value.
16930 if (!Invalid
&& getLangOpts().ObjC
) {
16931 QualType T
= ExDeclType
;
16932 if (const ReferenceType
*RT
= T
->getAs
<ReferenceType
>())
16933 T
= RT
->getPointeeType();
16935 if (T
->isObjCObjectType()) {
16936 Diag(Loc
, diag::err_objc_object_catch
);
16938 } else if (T
->isObjCObjectPointerType()) {
16939 // FIXME: should this be a test for macosx-fragile specifically?
16940 if (getLangOpts().ObjCRuntime
.isFragile())
16941 Diag(Loc
, diag::warn_objc_pointer_cxx_catch_fragile
);
16945 VarDecl
*ExDecl
= VarDecl::Create(Context
, CurContext
, StartLoc
, Loc
, Name
,
16946 ExDeclType
, TInfo
, SC_None
);
16947 ExDecl
->setExceptionVariable(true);
16949 // In ARC, infer 'retaining' for variables of retainable type.
16950 if (getLangOpts().ObjCAutoRefCount
&& inferObjCARCLifetime(ExDecl
))
16953 if (!Invalid
&& !ExDeclType
->isDependentType()) {
16954 if (const RecordType
*recordType
= ExDeclType
->getAs
<RecordType
>()) {
16955 // Insulate this from anything else we might currently be parsing.
16956 EnterExpressionEvaluationContext
scope(
16957 *this, ExpressionEvaluationContext::PotentiallyEvaluated
);
16959 // C++ [except.handle]p16:
16960 // The object declared in an exception-declaration or, if the
16961 // exception-declaration does not specify a name, a temporary (12.2) is
16962 // copy-initialized (8.5) from the exception object. [...]
16963 // The object is destroyed when the handler exits, after the destruction
16964 // of any automatic objects initialized within the handler.
16966 // We just pretend to initialize the object with itself, then make sure
16967 // it can be destroyed later.
16968 QualType initType
= Context
.getExceptionObjectType(ExDeclType
);
16970 InitializedEntity entity
=
16971 InitializedEntity::InitializeVariable(ExDecl
);
16972 InitializationKind initKind
=
16973 InitializationKind::CreateCopy(Loc
, SourceLocation());
16975 Expr
*opaqueValue
=
16976 new (Context
) OpaqueValueExpr(Loc
, initType
, VK_LValue
, OK_Ordinary
);
16977 InitializationSequence
sequence(*this, entity
, initKind
, opaqueValue
);
16978 ExprResult result
= sequence
.Perform(*this, entity
, initKind
, opaqueValue
);
16979 if (result
.isInvalid())
16982 // If the constructor used was non-trivial, set this as the
16984 CXXConstructExpr
*construct
= result
.getAs
<CXXConstructExpr
>();
16985 if (!construct
->getConstructor()->isTrivial()) {
16986 Expr
*init
= MaybeCreateExprWithCleanups(construct
);
16987 ExDecl
->setInit(init
);
16990 // And make sure it's destructable.
16991 FinalizeVarWithDestructor(ExDecl
, recordType
);
16997 ExDecl
->setInvalidDecl();
17002 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
17004 Decl
*Sema::ActOnExceptionDeclarator(Scope
*S
, Declarator
&D
) {
17005 TypeSourceInfo
*TInfo
= GetTypeForDeclarator(D
, S
);
17006 bool Invalid
= D
.isInvalidType();
17008 // Check for unexpanded parameter packs.
17009 if (DiagnoseUnexpandedParameterPack(D
.getIdentifierLoc(), TInfo
,
17010 UPPC_ExceptionType
)) {
17011 TInfo
= Context
.getTrivialTypeSourceInfo(Context
.IntTy
,
17012 D
.getIdentifierLoc());
17016 IdentifierInfo
*II
= D
.getIdentifier();
17017 if (NamedDecl
*PrevDecl
= LookupSingleName(S
, II
, D
.getIdentifierLoc(),
17018 LookupOrdinaryName
,
17019 ForVisibleRedeclaration
)) {
17020 // The scope should be freshly made just for us. There is just no way
17021 // it contains any previous declaration, except for function parameters in
17022 // a function-try-block's catch statement.
17023 assert(!S
->isDeclScope(PrevDecl
));
17024 if (isDeclInScope(PrevDecl
, CurContext
, S
)) {
17025 Diag(D
.getIdentifierLoc(), diag::err_redefinition
)
17026 << D
.getIdentifier();
17027 Diag(PrevDecl
->getLocation(), diag::note_previous_definition
);
17029 } else if (PrevDecl
->isTemplateParameter())
17030 // Maybe we will complain about the shadowed template parameter.
17031 DiagnoseTemplateParameterShadow(D
.getIdentifierLoc(), PrevDecl
);
17034 if (D
.getCXXScopeSpec().isSet() && !Invalid
) {
17035 Diag(D
.getIdentifierLoc(), diag::err_qualified_catch_declarator
)
17036 << D
.getCXXScopeSpec().getRange();
17040 VarDecl
*ExDecl
= BuildExceptionDeclaration(
17041 S
, TInfo
, D
.getBeginLoc(), D
.getIdentifierLoc(), D
.getIdentifier());
17043 ExDecl
->setInvalidDecl();
17045 // Add the exception declaration into this scope.
17047 PushOnScopeChains(ExDecl
, S
);
17049 CurContext
->addDecl(ExDecl
);
17051 ProcessDeclAttributes(S
, ExDecl
, D
);
17055 Decl
*Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc
,
17057 Expr
*AssertMessageExpr
,
17058 SourceLocation RParenLoc
) {
17059 if (DiagnoseUnexpandedParameterPack(AssertExpr
, UPPC_StaticAssertExpression
))
17062 return BuildStaticAssertDeclaration(StaticAssertLoc
, AssertExpr
,
17063 AssertMessageExpr
, RParenLoc
, false);
17066 static void WriteCharTypePrefix(BuiltinType::Kind BTK
, llvm::raw_ostream
&OS
) {
17068 case BuiltinType::Char_S
:
17069 case BuiltinType::Char_U
:
17071 case BuiltinType::Char8
:
17074 case BuiltinType::Char16
:
17077 case BuiltinType::Char32
:
17080 case BuiltinType::WChar_S
:
17081 case BuiltinType::WChar_U
:
17085 llvm_unreachable("Non-character type");
17089 /// Convert character's value, interpreted as a code unit, to a string.
17090 /// The value needs to be zero-extended to 32-bits.
17091 /// FIXME: This assumes Unicode literal encodings
17092 static void WriteCharValueForDiagnostic(uint32_t Value
, const BuiltinType
*BTy
,
17094 SmallVectorImpl
<char> &Str
) {
17095 char Arr
[UNI_MAX_UTF8_BYTES_PER_CODE_POINT
];
17097 BuiltinType::Kind K
= BTy
->getKind();
17098 llvm::raw_svector_ostream
OS(Str
);
17100 // This should catch Char_S, Char_U, Char8, and use of escaped characters in
17102 if (K
== BuiltinType::Char_S
|| K
== BuiltinType::Char_U
||
17103 K
== BuiltinType::Char8
|| Value
<= 0x7F) {
17104 StringRef Escaped
= escapeCStyle
<EscapeChar::Single
>(Value
);
17105 if (!Escaped
.empty())
17106 EscapeStringForDiagnostic(Escaped
, Str
);
17108 OS
<< static_cast<char>(Value
);
17113 case BuiltinType::Char16
:
17114 case BuiltinType::Char32
:
17115 case BuiltinType::WChar_S
:
17116 case BuiltinType::WChar_U
: {
17117 if (llvm::ConvertCodePointToUTF8(Value
, Ptr
))
17118 EscapeStringForDiagnostic(StringRef(Arr
, Ptr
- Arr
), Str
);
17121 << llvm::format_hex_no_prefix(Value
, TyWidth
/ 4, /*Upper=*/true);
17125 llvm_unreachable("Non-character type is passed");
17129 /// Convert \V to a string we can present to the user in a diagnostic
17130 /// \T is the type of the expression that has been evaluated into \V
17131 static bool ConvertAPValueToString(const APValue
&V
, QualType T
,
17132 SmallVectorImpl
<char> &Str
,
17133 ASTContext
&Context
) {
17137 switch (V
.getKind()) {
17138 case APValue::ValueKind::Int
:
17139 if (T
->isBooleanType()) {
17140 // Bools are reduced to ints during evaluation, but for
17141 // diagnostic purposes we want to print them as
17143 int64_t BoolValue
= V
.getInt().getExtValue();
17144 assert((BoolValue
== 0 || BoolValue
== 1) &&
17145 "Bool type, but value is not 0 or 1");
17146 llvm::raw_svector_ostream
OS(Str
);
17147 OS
<< (BoolValue
? "true" : "false");
17149 llvm::raw_svector_ostream
OS(Str
);
17150 // Same is true for chars.
17151 // We want to print the character representation for textual types
17152 const auto *BTy
= T
->getAs
<BuiltinType
>();
17154 switch (BTy
->getKind()) {
17155 case BuiltinType::Char_S
:
17156 case BuiltinType::Char_U
:
17157 case BuiltinType::Char8
:
17158 case BuiltinType::Char16
:
17159 case BuiltinType::Char32
:
17160 case BuiltinType::WChar_S
:
17161 case BuiltinType::WChar_U
: {
17162 unsigned TyWidth
= Context
.getIntWidth(T
);
17163 assert(8 <= TyWidth
&& TyWidth
<= 32 && "Unexpected integer width");
17164 uint32_t CodeUnit
= static_cast<uint32_t>(V
.getInt().getZExtValue());
17165 WriteCharTypePrefix(BTy
->getKind(), OS
);
17167 WriteCharValueForDiagnostic(CodeUnit
, BTy
, TyWidth
, Str
);
17169 << llvm::format_hex_no_prefix(CodeUnit
, /*Width=*/2,
17171 << ", " << V
.getInt() << ')';
17178 V
.getInt().toString(Str
);
17183 case APValue::ValueKind::Float
:
17184 V
.getFloat().toString(Str
);
17187 case APValue::ValueKind::LValue
:
17188 if (V
.isNullPointer()) {
17189 llvm::raw_svector_ostream
OS(Str
);
17195 case APValue::ValueKind::ComplexFloat
: {
17196 llvm::raw_svector_ostream
OS(Str
);
17198 V
.getComplexFloatReal().toString(Str
);
17200 V
.getComplexFloatImag().toString(Str
);
17204 case APValue::ValueKind::ComplexInt
: {
17205 llvm::raw_svector_ostream
OS(Str
);
17207 V
.getComplexIntReal().toString(Str
);
17209 V
.getComplexIntImag().toString(Str
);
17220 /// Some Expression types are not useful to print notes about,
17221 /// e.g. literals and values that have already been expanded
17222 /// before such as int-valued template parameters.
17223 static bool UsefulToPrintExpr(const Expr
*E
) {
17224 E
= E
->IgnoreParenImpCasts();
17225 // Literals are pretty easy for humans to understand.
17226 if (isa
<IntegerLiteral
, FloatingLiteral
, CharacterLiteral
, CXXBoolLiteralExpr
,
17227 CXXNullPtrLiteralExpr
, FixedPointLiteral
, ImaginaryLiteral
>(E
))
17230 // These have been substituted from template parameters
17231 // and appear as literals in the static assert error.
17232 if (isa
<SubstNonTypeTemplateParmExpr
>(E
))
17235 // -5 is also simple to understand.
17236 if (const auto *UnaryOp
= dyn_cast
<UnaryOperator
>(E
))
17237 return UsefulToPrintExpr(UnaryOp
->getSubExpr());
17239 // Ignore nested binary operators. This could be a FIXME for improvements
17240 // to the diagnostics in the future.
17241 if (isa
<BinaryOperator
>(E
))
17247 /// Try to print more useful information about a failed static_assert
17248 /// with expression \E
17249 void Sema::DiagnoseStaticAssertDetails(const Expr
*E
) {
17250 if (const auto *Op
= dyn_cast
<BinaryOperator
>(E
);
17251 Op
&& Op
->getOpcode() != BO_LOr
) {
17252 const Expr
*LHS
= Op
->getLHS()->IgnoreParenImpCasts();
17253 const Expr
*RHS
= Op
->getRHS()->IgnoreParenImpCasts();
17255 // Ignore comparisons of boolean expressions with a boolean literal.
17256 if ((isa
<CXXBoolLiteralExpr
>(LHS
) && RHS
->getType()->isBooleanType()) ||
17257 (isa
<CXXBoolLiteralExpr
>(RHS
) && LHS
->getType()->isBooleanType()))
17260 // Don't print obvious expressions.
17261 if (!UsefulToPrintExpr(LHS
) && !UsefulToPrintExpr(RHS
))
17265 const clang::Expr
*Cond
;
17266 Expr::EvalResult Result
;
17267 SmallString
<12> ValueString
;
17269 } DiagSide
[2] = {{LHS
, Expr::EvalResult(), {}, false},
17270 {RHS
, Expr::EvalResult(), {}, false}};
17271 for (unsigned I
= 0; I
< 2; I
++) {
17272 const Expr
*Side
= DiagSide
[I
].Cond
;
17274 Side
->EvaluateAsRValue(DiagSide
[I
].Result
, Context
, true);
17276 DiagSide
[I
].Print
=
17277 ConvertAPValueToString(DiagSide
[I
].Result
.Val
, Side
->getType(),
17278 DiagSide
[I
].ValueString
, Context
);
17280 if (DiagSide
[0].Print
&& DiagSide
[1].Print
) {
17281 Diag(Op
->getExprLoc(), diag::note_expr_evaluates_to
)
17282 << DiagSide
[0].ValueString
<< Op
->getOpcodeStr()
17283 << DiagSide
[1].ValueString
<< Op
->getSourceRange();
17288 bool Sema::EvaluateStaticAssertMessageAsString(Expr
*Message
,
17289 std::string
&Result
,
17291 bool ErrorOnInvalidMessage
) {
17293 assert(!Message
->isTypeDependent() && !Message
->isValueDependent() &&
17294 "can't evaluate a dependant static assert message");
17296 if (const auto *SL
= dyn_cast
<StringLiteral
>(Message
)) {
17297 assert(SL
->isUnevaluated() && "expected an unevaluated string");
17298 Result
.assign(SL
->getString().begin(), SL
->getString().end());
17302 SourceLocation Loc
= Message
->getBeginLoc();
17303 QualType T
= Message
->getType().getNonReferenceType();
17304 auto *RD
= T
->getAsCXXRecordDecl();
17306 Diag(Loc
, diag::err_static_assert_invalid_message
);
17310 auto FindMember
= [&](StringRef Member
, bool &Empty
,
17311 bool Diag
= false) -> std::optional
<LookupResult
> {
17312 QualType ObjectType
= Message
->getType();
17313 Expr::Classification ObjectClassification
=
17314 Message
->Classify(getASTContext());
17316 DeclarationName DN
= PP
.getIdentifierInfo(Member
);
17317 LookupResult
MemberLookup(*this, DN
, Loc
, Sema::LookupMemberName
);
17318 LookupQualifiedName(MemberLookup
, RD
);
17319 Empty
= MemberLookup
.empty();
17320 OverloadCandidateSet
Candidates(MemberLookup
.getNameLoc(),
17321 OverloadCandidateSet::CSK_Normal
);
17322 for (NamedDecl
*D
: MemberLookup
) {
17323 AddMethodCandidate(DeclAccessPair::make(D
, D
->getAccess()), ObjectType
,
17324 ObjectClassification
, /*Args=*/{}, Candidates
);
17326 OverloadCandidateSet::iterator Best
;
17327 switch (Candidates
.BestViableFunction(*this, Loc
, Best
)) {
17329 return std::move(MemberLookup
);
17332 Candidates
.NoteCandidates(
17333 PartialDiagnosticAt(
17334 Loc
, PDiag(diag::err_static_assert_invalid_mem_fn_ret_ty
)
17335 << (Member
== "data")),
17336 *this, OCD_AllCandidates
, /*Args=*/{});
17338 return std::nullopt
;
17341 bool SizeNotFound
, DataNotFound
;
17342 std::optional
<LookupResult
> SizeMember
= FindMember("size", SizeNotFound
);
17343 std::optional
<LookupResult
> DataMember
= FindMember("data", DataNotFound
);
17344 if (SizeNotFound
|| DataNotFound
) {
17345 Diag(Loc
, diag::err_static_assert_missing_member_function
)
17346 << ((SizeNotFound
&& DataNotFound
) ? 2
17352 if (!SizeMember
|| !DataMember
) {
17354 FindMember("size", SizeNotFound
, /*Diag=*/true);
17356 FindMember("data", DataNotFound
, /*Diag=*/true);
17360 auto BuildExpr
= [&](LookupResult
&LR
) {
17361 ExprResult Res
= BuildMemberReferenceExpr(
17362 Message
, Message
->getType(), Message
->getBeginLoc(), false,
17363 CXXScopeSpec(), SourceLocation(), nullptr, LR
, nullptr, nullptr);
17364 if (Res
.isInvalid())
17365 return ExprError();
17366 Res
= BuildCallExpr(nullptr, Res
.get(), Loc
, std::nullopt
, Loc
, nullptr,
17368 if (Res
.isInvalid())
17369 return ExprError();
17370 if (Res
.get()->isTypeDependent() || Res
.get()->isValueDependent())
17371 return ExprError();
17372 return TemporaryMaterializationConversion(Res
.get());
17375 ExprResult SizeE
= BuildExpr(*SizeMember
);
17376 ExprResult DataE
= BuildExpr(*DataMember
);
17378 QualType SizeT
= Context
.getSizeType();
17379 QualType ConstCharPtr
=
17380 Context
.getPointerType(Context
.getConstType(Context
.CharTy
));
17382 ExprResult EvaluatedSize
=
17383 SizeE
.isInvalid() ? ExprError()
17384 : BuildConvertedConstantExpression(
17385 SizeE
.get(), SizeT
, CCEK_StaticAssertMessageSize
);
17386 if (EvaluatedSize
.isInvalid()) {
17387 Diag(Loc
, diag::err_static_assert_invalid_mem_fn_ret_ty
) << /*size*/ 0;
17391 ExprResult EvaluatedData
=
17394 : BuildConvertedConstantExpression(DataE
.get(), ConstCharPtr
,
17395 CCEK_StaticAssertMessageData
);
17396 if (EvaluatedData
.isInvalid()) {
17397 Diag(Loc
, diag::err_static_assert_invalid_mem_fn_ret_ty
) << /*data*/ 1;
17401 if (!ErrorOnInvalidMessage
&&
17402 Diags
.isIgnored(diag::warn_static_assert_message_constexpr
, Loc
))
17405 Expr::EvalResult Status
;
17406 SmallVector
<PartialDiagnosticAt
, 8> Notes
;
17407 Status
.Diag
= &Notes
;
17408 if (!Message
->EvaluateCharRangeAsString(Result
, EvaluatedSize
.get(),
17409 EvaluatedData
.get(), Ctx
, Status
) ||
17411 Diag(Message
->getBeginLoc(),
17412 ErrorOnInvalidMessage
? diag::err_static_assert_message_constexpr
17413 : diag::warn_static_assert_message_constexpr
);
17414 for (const auto &Note
: Notes
)
17415 Diag(Note
.first
, Note
.second
);
17416 return !ErrorOnInvalidMessage
;
17421 Decl
*Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc
,
17422 Expr
*AssertExpr
, Expr
*AssertMessage
,
17423 SourceLocation RParenLoc
,
17425 assert(AssertExpr
!= nullptr && "Expected non-null condition");
17426 if (!AssertExpr
->isTypeDependent() && !AssertExpr
->isValueDependent() &&
17427 (!AssertMessage
|| (!AssertMessage
->isTypeDependent() &&
17428 !AssertMessage
->isValueDependent())) &&
17430 // In a static_assert-declaration, the constant-expression shall be a
17431 // constant expression that can be contextually converted to bool.
17432 ExprResult Converted
= PerformContextuallyConvertToBool(AssertExpr
);
17433 if (Converted
.isInvalid())
17436 ExprResult FullAssertExpr
=
17437 ActOnFinishFullExpr(Converted
.get(), StaticAssertLoc
,
17438 /*DiscardedValue*/ false,
17439 /*IsConstexpr*/ true);
17440 if (FullAssertExpr
.isInvalid())
17443 AssertExpr
= FullAssertExpr
.get();
17446 Expr
*BaseExpr
= AssertExpr
;
17447 AllowFoldKind FoldKind
= NoFold
;
17449 if (!getLangOpts().CPlusPlus
) {
17450 // In C mode, allow folding as an extension for better compatibility with
17451 // C++ in terms of expressions like static_assert("test") or
17452 // static_assert(nullptr).
17453 FoldKind
= AllowFold
;
17456 if (!Failed
&& VerifyIntegerConstantExpression(
17458 diag::err_static_assert_expression_is_not_constant
,
17459 FoldKind
).isInvalid())
17462 // If the static_assert passes, only verify that
17463 // the message is grammatically valid without evaluating it.
17464 if (!Failed
&& AssertMessage
&& Cond
.getBoolValue()) {
17466 EvaluateStaticAssertMessageAsString(AssertMessage
, Str
, Context
,
17467 /*ErrorOnInvalidMessage=*/false);
17471 // [dcl.pre]/p10 If [...] the expression is evaluated in the context of a
17472 // template definition, the declaration has no effect.
17473 bool InTemplateDefinition
=
17474 getLangOpts().CPlusPlus
&& CurContext
->isDependentContext();
17476 if (!Failed
&& !Cond
&& !InTemplateDefinition
) {
17477 SmallString
<256> MsgBuffer
;
17478 llvm::raw_svector_ostream
Msg(MsgBuffer
);
17479 bool HasMessage
= AssertMessage
;
17480 if (AssertMessage
) {
17483 EvaluateStaticAssertMessageAsString(
17484 AssertMessage
, Str
, Context
, /*ErrorOnInvalidMessage=*/true) ||
17488 Expr
*InnerCond
= nullptr;
17489 std::string InnerCondDescription
;
17490 std::tie(InnerCond
, InnerCondDescription
) =
17491 findFailedBooleanCondition(Converted
.get());
17492 if (InnerCond
&& isa
<ConceptSpecializationExpr
>(InnerCond
)) {
17493 // Drill down into concept specialization expressions to see why they
17494 // weren't satisfied.
17495 Diag(AssertExpr
->getBeginLoc(), diag::err_static_assert_failed
)
17496 << !HasMessage
<< Msg
.str() << AssertExpr
->getSourceRange();
17497 ConstraintSatisfaction Satisfaction
;
17498 if (!CheckConstraintSatisfaction(InnerCond
, Satisfaction
))
17499 DiagnoseUnsatisfiedConstraint(Satisfaction
);
17500 } else if (InnerCond
&& !isa
<CXXBoolLiteralExpr
>(InnerCond
)
17501 && !isa
<IntegerLiteral
>(InnerCond
)) {
17502 Diag(InnerCond
->getBeginLoc(),
17503 diag::err_static_assert_requirement_failed
)
17504 << InnerCondDescription
<< !HasMessage
<< Msg
.str()
17505 << InnerCond
->getSourceRange();
17506 DiagnoseStaticAssertDetails(InnerCond
);
17508 Diag(AssertExpr
->getBeginLoc(), diag::err_static_assert_failed
)
17509 << !HasMessage
<< Msg
.str() << AssertExpr
->getSourceRange();
17510 PrintContextStack();
17515 ExprResult FullAssertExpr
= ActOnFinishFullExpr(AssertExpr
, StaticAssertLoc
,
17516 /*DiscardedValue*/false,
17517 /*IsConstexpr*/true);
17518 if (FullAssertExpr
.isInvalid())
17521 AssertExpr
= FullAssertExpr
.get();
17524 Decl
*Decl
= StaticAssertDecl::Create(Context
, CurContext
, StaticAssertLoc
,
17525 AssertExpr
, AssertMessage
, RParenLoc
,
17528 CurContext
->addDecl(Decl
);
17532 /// Perform semantic analysis of the given friend type declaration.
17534 /// \returns A friend declaration that.
17535 FriendDecl
*Sema::CheckFriendTypeDecl(SourceLocation LocStart
,
17536 SourceLocation FriendLoc
,
17537 TypeSourceInfo
*TSInfo
) {
17538 assert(TSInfo
&& "NULL TypeSourceInfo for friend type declaration");
17540 QualType T
= TSInfo
->getType();
17541 SourceRange TypeRange
= TSInfo
->getTypeLoc().getSourceRange();
17543 // C++03 [class.friend]p2:
17544 // An elaborated-type-specifier shall be used in a friend declaration
17547 // * The class-key of the elaborated-type-specifier is required.
17548 if (!CodeSynthesisContexts
.empty()) {
17549 // Do not complain about the form of friend template types during any kind
17550 // of code synthesis. For template instantiation, we will have complained
17551 // when the template was defined.
17553 if (!T
->isElaboratedTypeSpecifier()) {
17554 // If we evaluated the type to a record type, suggest putting
17556 if (const RecordType
*RT
= T
->getAs
<RecordType
>()) {
17557 RecordDecl
*RD
= RT
->getDecl();
17559 SmallString
<16> InsertionText(" ");
17560 InsertionText
+= RD
->getKindName();
17562 Diag(TypeRange
.getBegin(),
17563 getLangOpts().CPlusPlus11
?
17564 diag::warn_cxx98_compat_unelaborated_friend_type
:
17565 diag::ext_unelaborated_friend_type
)
17566 << (unsigned) RD
->getTagKind()
17568 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc
),
17572 getLangOpts().CPlusPlus11
?
17573 diag::warn_cxx98_compat_nonclass_type_friend
:
17574 diag::ext_nonclass_type_friend
)
17578 } else if (T
->getAs
<EnumType
>()) {
17580 getLangOpts().CPlusPlus11
?
17581 diag::warn_cxx98_compat_enum_friend
:
17582 diag::ext_enum_friend
)
17587 // C++11 [class.friend]p3:
17588 // A friend declaration that does not declare a function shall have one
17589 // of the following forms:
17590 // friend elaborated-type-specifier ;
17591 // friend simple-type-specifier ;
17592 // friend typename-specifier ;
17593 if (getLangOpts().CPlusPlus11
&& LocStart
!= FriendLoc
)
17594 Diag(FriendLoc
, diag::err_friend_not_first_in_declaration
) << T
;
17597 // If the type specifier in a friend declaration designates a (possibly
17598 // cv-qualified) class type, that class is declared as a friend; otherwise,
17599 // the friend declaration is ignored.
17600 return FriendDecl::Create(Context
, CurContext
,
17601 TSInfo
->getTypeLoc().getBeginLoc(), TSInfo
,
17605 /// Handle a friend tag declaration where the scope specifier was
17607 DeclResult
Sema::ActOnTemplatedFriendTag(
17608 Scope
*S
, SourceLocation FriendLoc
, unsigned TagSpec
, SourceLocation TagLoc
,
17609 CXXScopeSpec
&SS
, IdentifierInfo
*Name
, SourceLocation NameLoc
,
17610 const ParsedAttributesView
&Attr
, MultiTemplateParamsArg TempParamLists
) {
17611 TagTypeKind Kind
= TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec
);
17613 bool IsMemberSpecialization
= false;
17614 bool Invalid
= false;
17616 if (TemplateParameterList
*TemplateParams
=
17617 MatchTemplateParametersToScopeSpecifier(
17618 TagLoc
, NameLoc
, SS
, nullptr, TempParamLists
, /*friend*/ true,
17619 IsMemberSpecialization
, Invalid
)) {
17620 if (TemplateParams
->size() > 0) {
17621 // This is a declaration of a class template.
17625 return CheckClassTemplate(S
, TagSpec
, TUK_Friend
, TagLoc
, SS
, Name
,
17626 NameLoc
, Attr
, TemplateParams
, AS_public
,
17627 /*ModulePrivateLoc=*/SourceLocation(),
17628 FriendLoc
, TempParamLists
.size() - 1,
17629 TempParamLists
.data()).get();
17631 // The "template<>" header is extraneous.
17632 Diag(TemplateParams
->getTemplateLoc(), diag::err_template_tag_noparams
)
17633 << TypeWithKeyword::getTagTypeKindName(Kind
) << Name
;
17634 IsMemberSpecialization
= true;
17638 if (Invalid
) return true;
17640 bool isAllExplicitSpecializations
= true;
17641 for (unsigned I
= TempParamLists
.size(); I
-- > 0; ) {
17642 if (TempParamLists
[I
]->size()) {
17643 isAllExplicitSpecializations
= false;
17648 // FIXME: don't ignore attributes.
17650 // If it's explicit specializations all the way down, just forget
17651 // about the template header and build an appropriate non-templated
17652 // friend. TODO: for source fidelity, remember the headers.
17653 if (isAllExplicitSpecializations
) {
17654 if (SS
.isEmpty()) {
17655 bool Owned
= false;
17656 bool IsDependent
= false;
17657 return ActOnTag(S
, TagSpec
, TUK_Friend
, TagLoc
, SS
, Name
, NameLoc
, Attr
,
17659 /*ModulePrivateLoc=*/SourceLocation(),
17660 MultiTemplateParamsArg(), Owned
, IsDependent
,
17661 /*ScopedEnumKWLoc=*/SourceLocation(),
17662 /*ScopedEnumUsesClassTag=*/false,
17663 /*UnderlyingType=*/TypeResult(),
17664 /*IsTypeSpecifier=*/false,
17665 /*IsTemplateParamOrArg=*/false, /*OOK=*/OOK_Outside
);
17668 NestedNameSpecifierLoc QualifierLoc
= SS
.getWithLocInContext(Context
);
17669 ElaboratedTypeKeyword Keyword
17670 = TypeWithKeyword::getKeywordForTagTypeKind(Kind
);
17671 QualType T
= CheckTypenameType(Keyword
, TagLoc
, QualifierLoc
,
17676 TypeSourceInfo
*TSI
= Context
.CreateTypeSourceInfo(T
);
17677 if (isa
<DependentNameType
>(T
)) {
17678 DependentNameTypeLoc TL
=
17679 TSI
->getTypeLoc().castAs
<DependentNameTypeLoc
>();
17680 TL
.setElaboratedKeywordLoc(TagLoc
);
17681 TL
.setQualifierLoc(QualifierLoc
);
17682 TL
.setNameLoc(NameLoc
);
17684 ElaboratedTypeLoc TL
= TSI
->getTypeLoc().castAs
<ElaboratedTypeLoc
>();
17685 TL
.setElaboratedKeywordLoc(TagLoc
);
17686 TL
.setQualifierLoc(QualifierLoc
);
17687 TL
.getNamedTypeLoc().castAs
<TypeSpecTypeLoc
>().setNameLoc(NameLoc
);
17690 FriendDecl
*Friend
= FriendDecl::Create(Context
, CurContext
, NameLoc
,
17691 TSI
, FriendLoc
, TempParamLists
);
17692 Friend
->setAccess(AS_public
);
17693 CurContext
->addDecl(Friend
);
17697 assert(SS
.isNotEmpty() && "valid templated tag with no SS and no direct?");
17701 // Handle the case of a templated-scope friend class. e.g.
17702 // template <class T> class A<T>::B;
17703 // FIXME: we don't support these right now.
17704 Diag(NameLoc
, diag::warn_template_qualified_friend_unsupported
)
17705 << SS
.getScopeRep() << SS
.getRange() << cast
<CXXRecordDecl
>(CurContext
);
17706 ElaboratedTypeKeyword ETK
= TypeWithKeyword::getKeywordForTagTypeKind(Kind
);
17707 QualType T
= Context
.getDependentNameType(ETK
, SS
.getScopeRep(), Name
);
17708 TypeSourceInfo
*TSI
= Context
.CreateTypeSourceInfo(T
);
17709 DependentNameTypeLoc TL
= TSI
->getTypeLoc().castAs
<DependentNameTypeLoc
>();
17710 TL
.setElaboratedKeywordLoc(TagLoc
);
17711 TL
.setQualifierLoc(SS
.getWithLocInContext(Context
));
17712 TL
.setNameLoc(NameLoc
);
17714 FriendDecl
*Friend
= FriendDecl::Create(Context
, CurContext
, NameLoc
,
17715 TSI
, FriendLoc
, TempParamLists
);
17716 Friend
->setAccess(AS_public
);
17717 Friend
->setUnsupportedFriend(true);
17718 CurContext
->addDecl(Friend
);
17722 /// Handle a friend type declaration. This works in tandem with
17725 /// Notes on friend class templates:
17727 /// We generally treat friend class declarations as if they were
17728 /// declaring a class. So, for example, the elaborated type specifier
17729 /// in a friend declaration is required to obey the restrictions of a
17730 /// class-head (i.e. no typedefs in the scope chain), template
17731 /// parameters are required to match up with simple template-ids, &c.
17732 /// However, unlike when declaring a template specialization, it's
17733 /// okay to refer to a template specialization without an empty
17734 /// template parameter declaration, e.g.
17735 /// friend class A<T>::B<unsigned>;
17736 /// We permit this as a special case; if there are any template
17737 /// parameters present at all, require proper matching, i.e.
17738 /// template <> template \<class T> friend class A<int>::B;
17739 Decl
*Sema::ActOnFriendTypeDecl(Scope
*S
, const DeclSpec
&DS
,
17740 MultiTemplateParamsArg TempParams
) {
17741 SourceLocation Loc
= DS
.getBeginLoc();
17743 assert(DS
.isFriendSpecified());
17744 assert(DS
.getStorageClassSpec() == DeclSpec::SCS_unspecified
);
17746 // C++ [class.friend]p3:
17747 // A friend declaration that does not declare a function shall have one of
17748 // the following forms:
17749 // friend elaborated-type-specifier ;
17750 // friend simple-type-specifier ;
17751 // friend typename-specifier ;
17753 // Any declaration with a type qualifier does not have that form. (It's
17754 // legal to specify a qualified type as a friend, you just can't write the
17756 if (DS
.getTypeQualifiers()) {
17757 if (DS
.getTypeQualifiers() & DeclSpec::TQ_const
)
17758 Diag(DS
.getConstSpecLoc(), diag::err_friend_decl_spec
) << "const";
17759 if (DS
.getTypeQualifiers() & DeclSpec::TQ_volatile
)
17760 Diag(DS
.getVolatileSpecLoc(), diag::err_friend_decl_spec
) << "volatile";
17761 if (DS
.getTypeQualifiers() & DeclSpec::TQ_restrict
)
17762 Diag(DS
.getRestrictSpecLoc(), diag::err_friend_decl_spec
) << "restrict";
17763 if (DS
.getTypeQualifiers() & DeclSpec::TQ_atomic
)
17764 Diag(DS
.getAtomicSpecLoc(), diag::err_friend_decl_spec
) << "_Atomic";
17765 if (DS
.getTypeQualifiers() & DeclSpec::TQ_unaligned
)
17766 Diag(DS
.getUnalignedSpecLoc(), diag::err_friend_decl_spec
) << "__unaligned";
17769 // Try to convert the decl specifier to a type. This works for
17770 // friend templates because ActOnTag never produces a ClassTemplateDecl
17771 // for a TUK_Friend.
17772 Declarator
TheDeclarator(DS
, ParsedAttributesView::none(),
17773 DeclaratorContext::Member
);
17774 TypeSourceInfo
*TSI
= GetTypeForDeclarator(TheDeclarator
, S
);
17775 QualType T
= TSI
->getType();
17776 if (TheDeclarator
.isInvalidType())
17779 if (DiagnoseUnexpandedParameterPack(Loc
, TSI
, UPPC_FriendDeclaration
))
17782 // This is definitely an error in C++98. It's probably meant to
17783 // be forbidden in C++0x, too, but the specification is just
17786 // The problem is with declarations like the following:
17787 // template <T> friend A<T>::foo;
17788 // where deciding whether a class C is a friend or not now hinges
17789 // on whether there exists an instantiation of A that causes
17790 // 'foo' to equal C. There are restrictions on class-heads
17791 // (which we declare (by fiat) elaborated friend declarations to
17792 // be) that makes this tractable.
17794 // FIXME: handle "template <> friend class A<T>;", which
17795 // is possibly well-formed? Who even knows?
17796 if (TempParams
.size() && !T
->isElaboratedTypeSpecifier()) {
17797 Diag(Loc
, diag::err_tagless_friend_type_template
)
17798 << DS
.getSourceRange();
17802 // C++98 [class.friend]p1: A friend of a class is a function
17803 // or class that is not a member of the class . . .
17804 // This is fixed in DR77, which just barely didn't make the C++03
17805 // deadline. It's also a very silly restriction that seriously
17806 // affects inner classes and which nobody else seems to implement;
17807 // thus we never diagnose it, not even in -pedantic.
17809 // But note that we could warn about it: it's always useless to
17810 // friend one of your own members (it's not, however, worthless to
17811 // friend a member of an arbitrary specialization of your template).
17814 if (!TempParams
.empty())
17815 D
= FriendTemplateDecl::Create(Context
, CurContext
, Loc
,
17818 DS
.getFriendSpecLoc());
17820 D
= CheckFriendTypeDecl(Loc
, DS
.getFriendSpecLoc(), TSI
);
17825 D
->setAccess(AS_public
);
17826 CurContext
->addDecl(D
);
17831 NamedDecl
*Sema::ActOnFriendFunctionDecl(Scope
*S
, Declarator
&D
,
17832 MultiTemplateParamsArg TemplateParams
) {
17833 const DeclSpec
&DS
= D
.getDeclSpec();
17835 assert(DS
.isFriendSpecified());
17836 assert(DS
.getStorageClassSpec() == DeclSpec::SCS_unspecified
);
17838 SourceLocation Loc
= D
.getIdentifierLoc();
17839 TypeSourceInfo
*TInfo
= GetTypeForDeclarator(D
, S
);
17841 // C++ [class.friend]p1
17842 // A friend of a class is a function or class....
17843 // Note that this sees through typedefs, which is intended.
17844 // It *doesn't* see through dependent types, which is correct
17845 // according to [temp.arg.type]p3:
17846 // If a declaration acquires a function type through a
17847 // type dependent on a template-parameter and this causes
17848 // a declaration that does not use the syntactic form of a
17849 // function declarator to have a function type, the program
17851 if (!TInfo
->getType()->isFunctionType()) {
17852 Diag(Loc
, diag::err_unexpected_friend
);
17854 // It might be worthwhile to try to recover by creating an
17855 // appropriate declaration.
17859 // C++ [namespace.memdef]p3
17860 // - If a friend declaration in a non-local class first declares a
17861 // class or function, the friend class or function is a member
17862 // of the innermost enclosing namespace.
17863 // - The name of the friend is not found by simple name lookup
17864 // until a matching declaration is provided in that namespace
17865 // scope (either before or after the class declaration granting
17867 // - If a friend function is called, its name may be found by the
17868 // name lookup that considers functions from namespaces and
17869 // classes associated with the types of the function arguments.
17870 // - When looking for a prior declaration of a class or a function
17871 // declared as a friend, scopes outside the innermost enclosing
17872 // namespace scope are not considered.
17874 CXXScopeSpec
&SS
= D
.getCXXScopeSpec();
17875 DeclarationNameInfo NameInfo
= GetNameForDeclarator(D
);
17876 assert(NameInfo
.getName());
17878 // Check for unexpanded parameter packs.
17879 if (DiagnoseUnexpandedParameterPack(Loc
, TInfo
, UPPC_FriendDeclaration
) ||
17880 DiagnoseUnexpandedParameterPack(NameInfo
, UPPC_FriendDeclaration
) ||
17881 DiagnoseUnexpandedParameterPack(SS
, UPPC_FriendDeclaration
))
17884 // The context we found the declaration in, or in which we should
17885 // create the declaration.
17887 Scope
*DCScope
= S
;
17888 LookupResult
Previous(*this, NameInfo
, LookupOrdinaryName
,
17889 ForExternalRedeclaration
);
17891 // There are five cases here.
17892 // - There's no scope specifier and we're in a local class. Only look
17893 // for functions declared in the immediately-enclosing block scope.
17894 // We recover from invalid scope qualifiers as if they just weren't there.
17895 FunctionDecl
*FunctionContainingLocalClass
= nullptr;
17896 if ((SS
.isInvalid() || !SS
.isSet()) &&
17897 (FunctionContainingLocalClass
=
17898 cast
<CXXRecordDecl
>(CurContext
)->isLocalClass())) {
17899 // C++11 [class.friend]p11:
17900 // If a friend declaration appears in a local class and the name
17901 // specified is an unqualified name, a prior declaration is
17902 // looked up without considering scopes that are outside the
17903 // innermost enclosing non-class scope. For a friend function
17904 // declaration, if there is no prior declaration, the program is
17907 // Find the innermost enclosing non-class scope. This is the block
17908 // scope containing the local class definition (or for a nested class,
17909 // the outer local class).
17910 DCScope
= S
->getFnParent();
17912 // Look up the function name in the scope.
17913 Previous
.clear(LookupLocalFriendName
);
17914 LookupName(Previous
, S
, /*AllowBuiltinCreation*/false);
17916 if (!Previous
.empty()) {
17917 // All possible previous declarations must have the same context:
17918 // either they were declared at block scope or they are members of
17919 // one of the enclosing local classes.
17920 DC
= Previous
.getRepresentativeDecl()->getDeclContext();
17922 // This is ill-formed, but provide the context that we would have
17923 // declared the function in, if we were permitted to, for error recovery.
17924 DC
= FunctionContainingLocalClass
;
17926 adjustContextForLocalExternDecl(DC
);
17928 // C++ [class.friend]p6:
17929 // A function can be defined in a friend declaration of a class if and
17930 // only if the class is a non-local class (9.8), the function name is
17931 // unqualified, and the function has namespace scope.
17932 if (D
.isFunctionDefinition()) {
17933 Diag(NameInfo
.getBeginLoc(), diag::err_friend_def_in_local_class
);
17936 // - There's no scope specifier, in which case we just go to the
17937 // appropriate scope and look for a function or function template
17938 // there as appropriate.
17939 } else if (SS
.isInvalid() || !SS
.isSet()) {
17940 // C++11 [namespace.memdef]p3:
17941 // If the name in a friend declaration is neither qualified nor
17942 // a template-id and the declaration is a function or an
17943 // elaborated-type-specifier, the lookup to determine whether
17944 // the entity has been previously declared shall not consider
17945 // any scopes outside the innermost enclosing namespace.
17946 bool isTemplateId
=
17947 D
.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
;
17949 // Find the appropriate context according to the above.
17952 // Skip class contexts. If someone can cite chapter and verse
17953 // for this behavior, that would be nice --- it's what GCC and
17954 // EDG do, and it seems like a reasonable intent, but the spec
17955 // really only says that checks for unqualified existing
17956 // declarations should stop at the nearest enclosing namespace,
17957 // not that they should only consider the nearest enclosing
17959 while (DC
->isRecord())
17960 DC
= DC
->getParent();
17962 DeclContext
*LookupDC
= DC
->getNonTransparentContext();
17964 LookupQualifiedName(Previous
, LookupDC
);
17966 if (!Previous
.empty()) {
17971 if (isTemplateId
) {
17972 if (isa
<TranslationUnitDecl
>(LookupDC
)) break;
17974 if (LookupDC
->isFileContext()) break;
17976 LookupDC
= LookupDC
->getParent();
17979 DCScope
= getScopeForDeclContext(S
, DC
);
17981 // - There's a non-dependent scope specifier, in which case we
17982 // compute it and do a previous lookup there for a function
17983 // or function template.
17984 } else if (!SS
.getScopeRep()->isDependent()) {
17985 DC
= computeDeclContext(SS
);
17986 if (!DC
) return nullptr;
17988 if (RequireCompleteDeclContext(SS
, DC
)) return nullptr;
17990 LookupQualifiedName(Previous
, DC
);
17992 // C++ [class.friend]p1: A friend of a class is a function or
17993 // class that is not a member of the class . . .
17994 if (DC
->Equals(CurContext
))
17995 Diag(DS
.getFriendSpecLoc(),
17996 getLangOpts().CPlusPlus11
?
17997 diag::warn_cxx98_compat_friend_is_member
:
17998 diag::err_friend_is_member
);
18000 if (D
.isFunctionDefinition()) {
18001 // C++ [class.friend]p6:
18002 // A function can be defined in a friend declaration of a class if and
18003 // only if the class is a non-local class (9.8), the function name is
18004 // unqualified, and the function has namespace scope.
18006 // FIXME: We should only do this if the scope specifier names the
18007 // innermost enclosing namespace; otherwise the fixit changes the
18008 // meaning of the code.
18009 SemaDiagnosticBuilder DB
18010 = Diag(SS
.getRange().getBegin(), diag::err_qualified_friend_def
);
18012 DB
<< SS
.getScopeRep();
18013 if (DC
->isFileContext())
18014 DB
<< FixItHint::CreateRemoval(SS
.getRange());
18018 // - There's a scope specifier that does not match any template
18019 // parameter lists, in which case we use some arbitrary context,
18020 // create a method or method template, and wait for instantiation.
18021 // - There's a scope specifier that does match some template
18022 // parameter lists, which we don't handle right now.
18024 if (D
.isFunctionDefinition()) {
18025 // C++ [class.friend]p6:
18026 // A function can be defined in a friend declaration of a class if and
18027 // only if the class is a non-local class (9.8), the function name is
18028 // unqualified, and the function has namespace scope.
18029 Diag(SS
.getRange().getBegin(), diag::err_qualified_friend_def
)
18030 << SS
.getScopeRep();
18034 assert(isa
<CXXRecordDecl
>(DC
) && "friend declaration not in class?");
18037 if (!DC
->isRecord()) {
18039 switch (D
.getName().getKind()) {
18040 case UnqualifiedIdKind::IK_ConstructorTemplateId
:
18041 case UnqualifiedIdKind::IK_ConstructorName
:
18044 case UnqualifiedIdKind::IK_DestructorName
:
18047 case UnqualifiedIdKind::IK_ConversionFunctionId
:
18050 case UnqualifiedIdKind::IK_DeductionGuideName
:
18053 case UnqualifiedIdKind::IK_Identifier
:
18054 case UnqualifiedIdKind::IK_ImplicitSelfParam
:
18055 case UnqualifiedIdKind::IK_LiteralOperatorId
:
18056 case UnqualifiedIdKind::IK_OperatorFunctionId
:
18057 case UnqualifiedIdKind::IK_TemplateId
:
18060 // This implies that it has to be an operator or function.
18061 if (DiagArg
>= 0) {
18062 Diag(Loc
, diag::err_introducing_special_friend
) << DiagArg
;
18067 // FIXME: This is an egregious hack to cope with cases where the scope stack
18068 // does not contain the declaration context, i.e., in an out-of-line
18069 // definition of a class.
18070 Scope
FakeDCScope(S
, Scope::DeclScope
, Diags
);
18072 FakeDCScope
.setEntity(DC
);
18073 DCScope
= &FakeDCScope
;
18076 bool AddToScope
= true;
18077 NamedDecl
*ND
= ActOnFunctionDeclarator(DCScope
, D
, DC
, TInfo
, Previous
,
18078 TemplateParams
, AddToScope
);
18079 if (!ND
) return nullptr;
18081 assert(ND
->getLexicalDeclContext() == CurContext
);
18083 // If we performed typo correction, we might have added a scope specifier
18084 // and changed the decl context.
18085 DC
= ND
->getDeclContext();
18087 // Add the function declaration to the appropriate lookup tables,
18088 // adjusting the redeclarations list as necessary. We don't
18089 // want to do this yet if the friending class is dependent.
18091 // Also update the scope-based lookup if the target context's
18092 // lookup context is in lexical scope.
18093 if (!CurContext
->isDependentContext()) {
18094 DC
= DC
->getRedeclContext();
18095 DC
->makeDeclVisibleInContext(ND
);
18096 if (Scope
*EnclosingScope
= getScopeForDeclContext(S
, DC
))
18097 PushOnScopeChains(ND
, EnclosingScope
, /*AddToContext=*/ false);
18100 FriendDecl
*FrD
= FriendDecl::Create(Context
, CurContext
,
18101 D
.getIdentifierLoc(), ND
,
18102 DS
.getFriendSpecLoc());
18103 FrD
->setAccess(AS_public
);
18104 CurContext
->addDecl(FrD
);
18106 if (ND
->isInvalidDecl()) {
18107 FrD
->setInvalidDecl();
18109 if (DC
->isRecord()) CheckFriendAccess(ND
);
18112 if (FunctionTemplateDecl
*FTD
= dyn_cast
<FunctionTemplateDecl
>(ND
))
18113 FD
= FTD
->getTemplatedDecl();
18115 FD
= cast
<FunctionDecl
>(ND
);
18117 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
18118 // default argument expression, that declaration shall be a definition
18119 // and shall be the only declaration of the function or function
18120 // template in the translation unit.
18121 if (functionDeclHasDefaultArgument(FD
)) {
18122 // We can't look at FD->getPreviousDecl() because it may not have been set
18123 // if we're in a dependent context. If the function is known to be a
18124 // redeclaration, we will have narrowed Previous down to the right decl.
18125 if (D
.isRedeclaration()) {
18126 Diag(FD
->getLocation(), diag::err_friend_decl_with_def_arg_redeclared
);
18127 Diag(Previous
.getRepresentativeDecl()->getLocation(),
18128 diag::note_previous_declaration
);
18129 } else if (!D
.isFunctionDefinition())
18130 Diag(FD
->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def
);
18133 // Mark templated-scope function declarations as unsupported.
18134 if (FD
->getNumTemplateParameterLists() && SS
.isValid()) {
18135 Diag(FD
->getLocation(), diag::warn_template_qualified_friend_unsupported
)
18136 << SS
.getScopeRep() << SS
.getRange()
18137 << cast
<CXXRecordDecl
>(CurContext
);
18138 FrD
->setUnsupportedFriend(true);
18142 warnOnReservedIdentifier(ND
);
18147 void Sema::SetDeclDeleted(Decl
*Dcl
, SourceLocation DelLoc
) {
18148 AdjustDeclIfTemplate(Dcl
);
18150 FunctionDecl
*Fn
= dyn_cast_or_null
<FunctionDecl
>(Dcl
);
18152 Diag(DelLoc
, diag::err_deleted_non_function
);
18156 // Deleted function does not have a body.
18157 Fn
->setWillHaveBody(false);
18159 if (const FunctionDecl
*Prev
= Fn
->getPreviousDecl()) {
18160 // Don't consider the implicit declaration we generate for explicit
18161 // specializations. FIXME: Do not generate these implicit declarations.
18162 if ((Prev
->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
||
18163 Prev
->getPreviousDecl()) &&
18164 !Prev
->isDefined()) {
18165 Diag(DelLoc
, diag::err_deleted_decl_not_first
);
18166 Diag(Prev
->getLocation().isInvalid() ? DelLoc
: Prev
->getLocation(),
18167 Prev
->isImplicit() ? diag::note_previous_implicit_declaration
18168 : diag::note_previous_declaration
);
18169 // We can't recover from this; the declaration might have already
18171 Fn
->setInvalidDecl();
18175 // To maintain the invariant that functions are only deleted on their first
18176 // declaration, mark the implicitly-instantiated declaration of the
18177 // explicitly-specialized function as deleted instead of marking the
18178 // instantiated redeclaration.
18179 Fn
= Fn
->getCanonicalDecl();
18182 // dllimport/dllexport cannot be deleted.
18183 if (const InheritableAttr
*DLLAttr
= getDLLAttr(Fn
)) {
18184 Diag(Fn
->getLocation(), diag::err_attribute_dll_deleted
) << DLLAttr
;
18185 Fn
->setInvalidDecl();
18188 // C++11 [basic.start.main]p3:
18189 // A program that defines main as deleted [...] is ill-formed.
18191 Diag(DelLoc
, diag::err_deleted_main
);
18193 // C++11 [dcl.fct.def.delete]p4:
18194 // A deleted function is implicitly inline.
18195 Fn
->setImplicitlyInline();
18196 Fn
->setDeletedAsWritten();
18199 void Sema::SetDeclDefaulted(Decl
*Dcl
, SourceLocation DefaultLoc
) {
18200 if (!Dcl
|| Dcl
->isInvalidDecl())
18203 auto *FD
= dyn_cast
<FunctionDecl
>(Dcl
);
18205 if (auto *FTD
= dyn_cast
<FunctionTemplateDecl
>(Dcl
)) {
18206 if (getDefaultedFunctionKind(FTD
->getTemplatedDecl()).isComparison()) {
18207 Diag(DefaultLoc
, diag::err_defaulted_comparison_template
);
18212 Diag(DefaultLoc
, diag::err_default_special_members
)
18213 << getLangOpts().CPlusPlus20
;
18217 // Reject if this can't possibly be a defaultable function.
18218 DefaultedFunctionKind DefKind
= getDefaultedFunctionKind(FD
);
18220 // A dependent function that doesn't locally look defaultable can
18221 // still instantiate to a defaultable function if it's a constructor
18222 // or assignment operator.
18223 (!FD
->isDependentContext() ||
18224 (!isa
<CXXConstructorDecl
>(FD
) &&
18225 FD
->getDeclName().getCXXOverloadedOperator() != OO_Equal
))) {
18226 Diag(DefaultLoc
, diag::err_default_special_members
)
18227 << getLangOpts().CPlusPlus20
;
18231 // Issue compatibility warning. We already warned if the operator is
18232 // 'operator<=>' when parsing the '<=>' token.
18233 if (DefKind
.isComparison() &&
18234 DefKind
.asComparison() != DefaultedComparisonKind::ThreeWay
) {
18235 Diag(DefaultLoc
, getLangOpts().CPlusPlus20
18236 ? diag::warn_cxx17_compat_defaulted_comparison
18237 : diag::ext_defaulted_comparison
);
18240 FD
->setDefaulted();
18241 FD
->setExplicitlyDefaulted();
18242 FD
->setDefaultLoc(DefaultLoc
);
18244 // Defer checking functions that are defaulted in a dependent context.
18245 if (FD
->isDependentContext())
18248 // Unset that we will have a body for this function. We might not,
18249 // if it turns out to be trivial, and we don't need this marking now
18250 // that we've marked it as defaulted.
18251 FD
->setWillHaveBody(false);
18253 if (DefKind
.isComparison()) {
18254 // If this comparison's defaulting occurs within the definition of its
18255 // lexical class context, we have to do the checking when complete.
18256 if (auto const *RD
= dyn_cast
<CXXRecordDecl
>(FD
->getLexicalDeclContext()))
18257 if (!RD
->isCompleteDefinition())
18261 // If this member fn was defaulted on its first declaration, we will have
18262 // already performed the checking in CheckCompletedCXXClass. Such a
18263 // declaration doesn't trigger an implicit definition.
18264 if (isa
<CXXMethodDecl
>(FD
)) {
18265 const FunctionDecl
*Primary
= FD
;
18266 if (const FunctionDecl
*Pattern
= FD
->getTemplateInstantiationPattern())
18267 // Ask the template instantiation pattern that actually had the
18268 // '= default' on it.
18270 if (Primary
->getCanonicalDecl()->isDefaulted())
18274 if (DefKind
.isComparison()) {
18275 if (CheckExplicitlyDefaultedComparison(nullptr, FD
, DefKind
.asComparison()))
18276 FD
->setInvalidDecl();
18278 DefineDefaultedComparison(DefaultLoc
, FD
, DefKind
.asComparison());
18280 auto *MD
= cast
<CXXMethodDecl
>(FD
);
18282 if (CheckExplicitlyDefaultedSpecialMember(MD
, DefKind
.asSpecialMember(),
18284 MD
->setInvalidDecl();
18286 DefineDefaultedFunction(*this, MD
, DefaultLoc
);
18290 static void SearchForReturnInStmt(Sema
&Self
, Stmt
*S
) {
18291 for (Stmt
*SubStmt
: S
->children()) {
18294 if (isa
<ReturnStmt
>(SubStmt
))
18295 Self
.Diag(SubStmt
->getBeginLoc(),
18296 diag::err_return_in_constructor_handler
);
18297 if (!isa
<Expr
>(SubStmt
))
18298 SearchForReturnInStmt(Self
, SubStmt
);
18302 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt
*TryBlock
) {
18303 for (unsigned I
= 0, E
= TryBlock
->getNumHandlers(); I
!= E
; ++I
) {
18304 CXXCatchStmt
*Handler
= TryBlock
->getHandler(I
);
18305 SearchForReturnInStmt(*this, Handler
);
18309 void Sema::SetFunctionBodyKind(Decl
*D
, SourceLocation Loc
,
18310 FnBodyKind BodyKind
) {
18311 switch (BodyKind
) {
18312 case FnBodyKind::Delete
:
18313 SetDeclDeleted(D
, Loc
);
18315 case FnBodyKind::Default
:
18316 SetDeclDefaulted(D
, Loc
);
18318 case FnBodyKind::Other
:
18320 "Parsed function body should be '= delete;' or '= default;'");
18324 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl
*New
,
18325 const CXXMethodDecl
*Old
) {
18326 const auto *NewFT
= New
->getType()->castAs
<FunctionProtoType
>();
18327 const auto *OldFT
= Old
->getType()->castAs
<FunctionProtoType
>();
18329 if (OldFT
->hasExtParameterInfos()) {
18330 for (unsigned I
= 0, E
= OldFT
->getNumParams(); I
!= E
; ++I
)
18331 // A parameter of the overriding method should be annotated with noescape
18332 // if the corresponding parameter of the overridden method is annotated.
18333 if (OldFT
->getExtParameterInfo(I
).isNoEscape() &&
18334 !NewFT
->getExtParameterInfo(I
).isNoEscape()) {
18335 Diag(New
->getParamDecl(I
)->getLocation(),
18336 diag::warn_overriding_method_missing_noescape
);
18337 Diag(Old
->getParamDecl(I
)->getLocation(),
18338 diag::note_overridden_marked_noescape
);
18342 // SME attributes must match when overriding a function declaration.
18343 if (IsInvalidSMECallConversion(
18344 Old
->getType(), New
->getType(),
18345 AArch64SMECallConversionKind::MayAddPreservesZA
)) {
18346 Diag(New
->getLocation(), diag::err_conflicting_overriding_attributes
)
18347 << New
<< New
->getType() << Old
->getType();
18348 Diag(Old
->getLocation(), diag::note_overridden_virtual_function
);
18352 // Virtual overrides must have the same code_seg.
18353 const auto *OldCSA
= Old
->getAttr
<CodeSegAttr
>();
18354 const auto *NewCSA
= New
->getAttr
<CodeSegAttr
>();
18355 if ((NewCSA
|| OldCSA
) &&
18356 (!OldCSA
|| !NewCSA
|| NewCSA
->getName() != OldCSA
->getName())) {
18357 Diag(New
->getLocation(), diag::err_mismatched_code_seg_override
);
18358 Diag(Old
->getLocation(), diag::note_previous_declaration
);
18362 CallingConv NewCC
= NewFT
->getCallConv(), OldCC
= OldFT
->getCallConv();
18364 // If the calling conventions match, everything is fine
18365 if (NewCC
== OldCC
)
18368 // If the calling conventions mismatch because the new function is static,
18369 // suppress the calling convention mismatch error; the error about static
18370 // function override (err_static_overrides_virtual from
18371 // Sema::CheckFunctionDeclaration) is more clear.
18372 if (New
->getStorageClass() == SC_Static
)
18375 Diag(New
->getLocation(),
18376 diag::err_conflicting_overriding_cc_attributes
)
18377 << New
->getDeclName() << New
->getType() << Old
->getType();
18378 Diag(Old
->getLocation(), diag::note_overridden_virtual_function
);
18382 bool Sema::CheckExplicitObjectOverride(CXXMethodDecl
*New
,
18383 const CXXMethodDecl
*Old
) {
18385 // A virtual function shall not be an explicit object member function.
18386 if (!New
->isExplicitObjectMemberFunction())
18388 Diag(New
->getParamDecl(0)->getBeginLoc(),
18389 diag::err_explicit_object_parameter_nonmember
)
18390 << New
->getSourceRange() << /*virtual*/ 1 << /*IsLambda*/ false;
18391 Diag(Old
->getLocation(), diag::note_overridden_virtual_function
);
18392 New
->setInvalidDecl();
18396 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl
*New
,
18397 const CXXMethodDecl
*Old
) {
18398 QualType NewTy
= New
->getType()->castAs
<FunctionType
>()->getReturnType();
18399 QualType OldTy
= Old
->getType()->castAs
<FunctionType
>()->getReturnType();
18401 if (Context
.hasSameType(NewTy
, OldTy
) ||
18402 NewTy
->isDependentType() || OldTy
->isDependentType())
18405 // Check if the return types are covariant
18406 QualType NewClassTy
, OldClassTy
;
18408 /// Both types must be pointers or references to classes.
18409 if (const PointerType
*NewPT
= NewTy
->getAs
<PointerType
>()) {
18410 if (const PointerType
*OldPT
= OldTy
->getAs
<PointerType
>()) {
18411 NewClassTy
= NewPT
->getPointeeType();
18412 OldClassTy
= OldPT
->getPointeeType();
18414 } else if (const ReferenceType
*NewRT
= NewTy
->getAs
<ReferenceType
>()) {
18415 if (const ReferenceType
*OldRT
= OldTy
->getAs
<ReferenceType
>()) {
18416 if (NewRT
->getTypeClass() == OldRT
->getTypeClass()) {
18417 NewClassTy
= NewRT
->getPointeeType();
18418 OldClassTy
= OldRT
->getPointeeType();
18423 // The return types aren't either both pointers or references to a class type.
18424 if (NewClassTy
.isNull()) {
18425 Diag(New
->getLocation(),
18426 diag::err_different_return_type_for_overriding_virtual_function
)
18427 << New
->getDeclName() << NewTy
<< OldTy
18428 << New
->getReturnTypeSourceRange();
18429 Diag(Old
->getLocation(), diag::note_overridden_virtual_function
)
18430 << Old
->getReturnTypeSourceRange();
18435 if (!Context
.hasSameUnqualifiedType(NewClassTy
, OldClassTy
)) {
18436 // C++14 [class.virtual]p8:
18437 // If the class type in the covariant return type of D::f differs from
18438 // that of B::f, the class type in the return type of D::f shall be
18439 // complete at the point of declaration of D::f or shall be the class
18441 if (const RecordType
*RT
= NewClassTy
->getAs
<RecordType
>()) {
18442 if (!RT
->isBeingDefined() &&
18443 RequireCompleteType(New
->getLocation(), NewClassTy
,
18444 diag::err_covariant_return_incomplete
,
18445 New
->getDeclName()))
18449 // Check if the new class derives from the old class.
18450 if (!IsDerivedFrom(New
->getLocation(), NewClassTy
, OldClassTy
)) {
18451 Diag(New
->getLocation(), diag::err_covariant_return_not_derived
)
18452 << New
->getDeclName() << NewTy
<< OldTy
18453 << New
->getReturnTypeSourceRange();
18454 Diag(Old
->getLocation(), diag::note_overridden_virtual_function
)
18455 << Old
->getReturnTypeSourceRange();
18459 // Check if we the conversion from derived to base is valid.
18460 if (CheckDerivedToBaseConversion(
18461 NewClassTy
, OldClassTy
,
18462 diag::err_covariant_return_inaccessible_base
,
18463 diag::err_covariant_return_ambiguous_derived_to_base_conv
,
18464 New
->getLocation(), New
->getReturnTypeSourceRange(),
18465 New
->getDeclName(), nullptr)) {
18466 // FIXME: this note won't trigger for delayed access control
18467 // diagnostics, and it's impossible to get an undelayed error
18468 // here from access control during the original parse because
18469 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
18470 Diag(Old
->getLocation(), diag::note_overridden_virtual_function
)
18471 << Old
->getReturnTypeSourceRange();
18476 // The qualifiers of the return types must be the same.
18477 if (NewTy
.getLocalCVRQualifiers() != OldTy
.getLocalCVRQualifiers()) {
18478 Diag(New
->getLocation(),
18479 diag::err_covariant_return_type_different_qualifications
)
18480 << New
->getDeclName() << NewTy
<< OldTy
18481 << New
->getReturnTypeSourceRange();
18482 Diag(Old
->getLocation(), diag::note_overridden_virtual_function
)
18483 << Old
->getReturnTypeSourceRange();
18488 // The new class type must have the same or less qualifiers as the old type.
18489 if (NewClassTy
.isMoreQualifiedThan(OldClassTy
)) {
18490 Diag(New
->getLocation(),
18491 diag::err_covariant_return_type_class_type_more_qualified
)
18492 << New
->getDeclName() << NewTy
<< OldTy
18493 << New
->getReturnTypeSourceRange();
18494 Diag(Old
->getLocation(), diag::note_overridden_virtual_function
)
18495 << Old
->getReturnTypeSourceRange();
18502 /// Mark the given method pure.
18504 /// \param Method the method to be marked pure.
18506 /// \param InitRange the source range that covers the "0" initializer.
18507 bool Sema::CheckPureMethod(CXXMethodDecl
*Method
, SourceRange InitRange
) {
18508 SourceLocation EndLoc
= InitRange
.getEnd();
18509 if (EndLoc
.isValid())
18510 Method
->setRangeEnd(EndLoc
);
18512 if (Method
->isVirtual() || Method
->getParent()->isDependentContext()) {
18517 if (!Method
->isInvalidDecl())
18518 Diag(Method
->getLocation(), diag::err_non_virtual_pure
)
18519 << Method
->getDeclName() << InitRange
;
18523 void Sema::ActOnPureSpecifier(Decl
*D
, SourceLocation ZeroLoc
) {
18524 if (D
->getFriendObjectKind())
18525 Diag(D
->getLocation(), diag::err_pure_friend
);
18526 else if (auto *M
= dyn_cast
<CXXMethodDecl
>(D
))
18527 CheckPureMethod(M
, ZeroLoc
);
18529 Diag(D
->getLocation(), diag::err_illegal_initializer
);
18532 /// Determine whether the given declaration is a global variable or
18533 /// static data member.
18534 static bool isNonlocalVariable(const Decl
*D
) {
18535 if (const VarDecl
*Var
= dyn_cast_or_null
<VarDecl
>(D
))
18536 return Var
->hasGlobalStorage();
18541 /// Invoked when we are about to parse an initializer for the declaration
18544 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
18545 /// static data member of class X, names should be looked up in the scope of
18546 /// class X. If the declaration had a scope specifier, a scope will have
18547 /// been created and passed in for this purpose. Otherwise, S will be null.
18548 void Sema::ActOnCXXEnterDeclInitializer(Scope
*S
, Decl
*D
) {
18549 // If there is no declaration, there was an error parsing it.
18550 if (!D
|| D
->isInvalidDecl())
18553 // We will always have a nested name specifier here, but this declaration
18554 // might not be out of line if the specifier names the current namespace:
18557 if (S
&& D
->isOutOfLine())
18558 EnterDeclaratorContext(S
, D
->getDeclContext());
18560 // If we are parsing the initializer for a static data member, push a
18561 // new expression evaluation context that is associated with this static
18563 if (isNonlocalVariable(D
))
18564 PushExpressionEvaluationContext(
18565 ExpressionEvaluationContext::PotentiallyEvaluated
, D
);
18568 /// Invoked after we are finished parsing an initializer for the declaration D.
18569 void Sema::ActOnCXXExitDeclInitializer(Scope
*S
, Decl
*D
) {
18570 // If there is no declaration, there was an error parsing it.
18571 if (!D
|| D
->isInvalidDecl())
18574 if (isNonlocalVariable(D
))
18575 PopExpressionEvaluationContext();
18577 if (S
&& D
->isOutOfLine())
18578 ExitDeclaratorContext(S
);
18581 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
18582 /// C++ if/switch/while/for statement.
18583 /// e.g: "if (int x = f()) {...}"
18584 DeclResult
Sema::ActOnCXXConditionDeclaration(Scope
*S
, Declarator
&D
) {
18586 // The declarator shall not specify a function or an array.
18587 // The type-specifier-seq shall not contain typedef and shall not declare a
18588 // new class or enumeration.
18589 assert(D
.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef
&&
18590 "Parser allowed 'typedef' as storage class of condition decl.");
18592 Decl
*Dcl
= ActOnDeclarator(S
, D
);
18596 if (isa
<FunctionDecl
>(Dcl
)) { // The declarator shall not specify a function.
18597 Diag(Dcl
->getLocation(), diag::err_invalid_use_of_function_type
)
18598 << D
.getSourceRange();
18605 void Sema::LoadExternalVTableUses() {
18606 if (!ExternalSource
)
18609 SmallVector
<ExternalVTableUse
, 4> VTables
;
18610 ExternalSource
->ReadUsedVTables(VTables
);
18611 SmallVector
<VTableUse
, 4> NewUses
;
18612 for (unsigned I
= 0, N
= VTables
.size(); I
!= N
; ++I
) {
18613 llvm::DenseMap
<CXXRecordDecl
*, bool>::iterator Pos
18614 = VTablesUsed
.find(VTables
[I
].Record
);
18615 // Even if a definition wasn't required before, it may be required now.
18616 if (Pos
!= VTablesUsed
.end()) {
18617 if (!Pos
->second
&& VTables
[I
].DefinitionRequired
)
18618 Pos
->second
= true;
18622 VTablesUsed
[VTables
[I
].Record
] = VTables
[I
].DefinitionRequired
;
18623 NewUses
.push_back(VTableUse(VTables
[I
].Record
, VTables
[I
].Location
));
18626 VTableUses
.insert(VTableUses
.begin(), NewUses
.begin(), NewUses
.end());
18629 void Sema::MarkVTableUsed(SourceLocation Loc
, CXXRecordDecl
*Class
,
18630 bool DefinitionRequired
) {
18631 // Ignore any vtable uses in unevaluated operands or for classes that do
18632 // not have a vtable.
18633 if (!Class
->isDynamicClass() || Class
->isDependentContext() ||
18634 CurContext
->isDependentContext() || isUnevaluatedContext())
18636 // Do not mark as used if compiling for the device outside of the target
18638 if (TUKind
!= TU_Prefix
&& LangOpts
.OpenMP
&& LangOpts
.OpenMPIsTargetDevice
&&
18639 !isInOpenMPDeclareTargetContext() &&
18640 !isInOpenMPTargetExecutionDirective()) {
18641 if (!DefinitionRequired
)
18642 MarkVirtualMembersReferenced(Loc
, Class
);
18646 // Try to insert this class into the map.
18647 LoadExternalVTableUses();
18648 Class
= Class
->getCanonicalDecl();
18649 std::pair
<llvm::DenseMap
<CXXRecordDecl
*, bool>::iterator
, bool>
18650 Pos
= VTablesUsed
.insert(std::make_pair(Class
, DefinitionRequired
));
18652 // If we already had an entry, check to see if we are promoting this vtable
18653 // to require a definition. If so, we need to reappend to the VTableUses
18654 // list, since we may have already processed the first entry.
18655 if (DefinitionRequired
&& !Pos
.first
->second
) {
18656 Pos
.first
->second
= true;
18658 // Otherwise, we can early exit.
18662 // The Microsoft ABI requires that we perform the destructor body
18663 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
18664 // the deleting destructor is emitted with the vtable, not with the
18665 // destructor definition as in the Itanium ABI.
18666 if (Context
.getTargetInfo().getCXXABI().isMicrosoft()) {
18667 CXXDestructorDecl
*DD
= Class
->getDestructor();
18668 if (DD
&& DD
->isVirtual() && !DD
->isDeleted()) {
18669 if (Class
->hasUserDeclaredDestructor() && !DD
->isDefined()) {
18670 // If this is an out-of-line declaration, marking it referenced will
18671 // not do anything. Manually call CheckDestructor to look up operator
18673 ContextRAII
SavedContext(*this, DD
);
18674 CheckDestructor(DD
);
18676 MarkFunctionReferenced(Loc
, Class
->getDestructor());
18682 // Local classes need to have their virtual members marked
18683 // immediately. For all other classes, we mark their virtual members
18684 // at the end of the translation unit.
18685 if (Class
->isLocalClass())
18686 MarkVirtualMembersReferenced(Loc
, Class
->getDefinition());
18688 VTableUses
.push_back(std::make_pair(Class
, Loc
));
18691 bool Sema::DefineUsedVTables() {
18692 LoadExternalVTableUses();
18693 if (VTableUses
.empty())
18696 // Note: The VTableUses vector could grow as a result of marking
18697 // the members of a class as "used", so we check the size each
18698 // time through the loop and prefer indices (which are stable) to
18699 // iterators (which are not).
18700 bool DefinedAnything
= false;
18701 for (unsigned I
= 0; I
!= VTableUses
.size(); ++I
) {
18702 CXXRecordDecl
*Class
= VTableUses
[I
].first
->getDefinition();
18705 TemplateSpecializationKind ClassTSK
=
18706 Class
->getTemplateSpecializationKind();
18708 SourceLocation Loc
= VTableUses
[I
].second
;
18710 bool DefineVTable
= true;
18712 // If this class has a key function, but that key function is
18713 // defined in another translation unit, we don't need to emit the
18714 // vtable even though we're using it.
18715 const CXXMethodDecl
*KeyFunction
= Context
.getCurrentKeyFunction(Class
);
18716 if (KeyFunction
&& !KeyFunction
->hasBody()) {
18717 // The key function is in another translation unit.
18718 DefineVTable
= false;
18719 TemplateSpecializationKind TSK
=
18720 KeyFunction
->getTemplateSpecializationKind();
18721 assert(TSK
!= TSK_ExplicitInstantiationDefinition
&&
18722 TSK
!= TSK_ImplicitInstantiation
&&
18723 "Instantiations don't have key functions");
18725 } else if (!KeyFunction
) {
18726 // If we have a class with no key function that is the subject
18727 // of an explicit instantiation declaration, suppress the
18728 // vtable; it will live with the explicit instantiation
18730 bool IsExplicitInstantiationDeclaration
=
18731 ClassTSK
== TSK_ExplicitInstantiationDeclaration
;
18732 for (auto *R
: Class
->redecls()) {
18733 TemplateSpecializationKind TSK
18734 = cast
<CXXRecordDecl
>(R
)->getTemplateSpecializationKind();
18735 if (TSK
== TSK_ExplicitInstantiationDeclaration
)
18736 IsExplicitInstantiationDeclaration
= true;
18737 else if (TSK
== TSK_ExplicitInstantiationDefinition
) {
18738 IsExplicitInstantiationDeclaration
= false;
18743 if (IsExplicitInstantiationDeclaration
)
18744 DefineVTable
= false;
18747 // The exception specifications for all virtual members may be needed even
18748 // if we are not providing an authoritative form of the vtable in this TU.
18749 // We may choose to emit it available_externally anyway.
18750 if (!DefineVTable
) {
18751 MarkVirtualMemberExceptionSpecsNeeded(Loc
, Class
);
18755 // Mark all of the virtual members of this class as referenced, so
18756 // that we can build a vtable. Then, tell the AST consumer that a
18757 // vtable for this class is required.
18758 DefinedAnything
= true;
18759 MarkVirtualMembersReferenced(Loc
, Class
);
18760 CXXRecordDecl
*Canonical
= Class
->getCanonicalDecl();
18761 if (VTablesUsed
[Canonical
])
18762 Consumer
.HandleVTable(Class
);
18764 // Warn if we're emitting a weak vtable. The vtable will be weak if there is
18765 // no key function or the key function is inlined. Don't warn in C++ ABIs
18766 // that lack key functions, since the user won't be able to make one.
18767 if (Context
.getTargetInfo().getCXXABI().hasKeyFunctions() &&
18768 Class
->isExternallyVisible() && ClassTSK
!= TSK_ImplicitInstantiation
&&
18769 ClassTSK
!= TSK_ExplicitInstantiationDefinition
) {
18770 const FunctionDecl
*KeyFunctionDef
= nullptr;
18771 if (!KeyFunction
|| (KeyFunction
->hasBody(KeyFunctionDef
) &&
18772 KeyFunctionDef
->isInlined()))
18773 Diag(Class
->getLocation(), diag::warn_weak_vtable
) << Class
;
18776 VTableUses
.clear();
18778 return DefinedAnything
;
18781 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc
,
18782 const CXXRecordDecl
*RD
) {
18783 for (const auto *I
: RD
->methods())
18784 if (I
->isVirtual() && !I
->isPure())
18785 ResolveExceptionSpec(Loc
, I
->getType()->castAs
<FunctionProtoType
>());
18788 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc
,
18789 const CXXRecordDecl
*RD
,
18790 bool ConstexprOnly
) {
18791 // Mark all functions which will appear in RD's vtable as used.
18792 CXXFinalOverriderMap FinalOverriders
;
18793 RD
->getFinalOverriders(FinalOverriders
);
18794 for (CXXFinalOverriderMap::const_iterator I
= FinalOverriders
.begin(),
18795 E
= FinalOverriders
.end();
18797 for (OverridingMethods::const_iterator OI
= I
->second
.begin(),
18798 OE
= I
->second
.end();
18800 assert(OI
->second
.size() > 0 && "no final overrider");
18801 CXXMethodDecl
*Overrider
= OI
->second
.front().Method
;
18803 // C++ [basic.def.odr]p2:
18804 // [...] A virtual member function is used if it is not pure. [...]
18805 if (!Overrider
->isPure() && (!ConstexprOnly
|| Overrider
->isConstexpr()))
18806 MarkFunctionReferenced(Loc
, Overrider
);
18810 // Only classes that have virtual bases need a VTT.
18811 if (RD
->getNumVBases() == 0)
18814 for (const auto &I
: RD
->bases()) {
18816 cast
<CXXRecordDecl
>(I
.getType()->castAs
<RecordType
>()->getDecl());
18817 if (Base
->getNumVBases() == 0)
18819 MarkVirtualMembersReferenced(Loc
, Base
);
18823 /// SetIvarInitializers - This routine builds initialization ASTs for the
18824 /// Objective-C implementation whose ivars need be initialized.
18825 void Sema::SetIvarInitializers(ObjCImplementationDecl
*ObjCImplementation
) {
18826 if (!getLangOpts().CPlusPlus
)
18828 if (ObjCInterfaceDecl
*OID
= ObjCImplementation
->getClassInterface()) {
18829 SmallVector
<ObjCIvarDecl
*, 8> ivars
;
18830 CollectIvarsToConstructOrDestruct(OID
, ivars
);
18833 SmallVector
<CXXCtorInitializer
*, 32> AllToInit
;
18834 for (unsigned i
= 0; i
< ivars
.size(); i
++) {
18835 FieldDecl
*Field
= ivars
[i
];
18836 if (Field
->isInvalidDecl())
18839 CXXCtorInitializer
*Member
;
18840 InitializedEntity InitEntity
= InitializedEntity::InitializeMember(Field
);
18841 InitializationKind InitKind
=
18842 InitializationKind::CreateDefault(ObjCImplementation
->getLocation());
18844 InitializationSequence
InitSeq(*this, InitEntity
, InitKind
, std::nullopt
);
18845 ExprResult MemberInit
=
18846 InitSeq
.Perform(*this, InitEntity
, InitKind
, std::nullopt
);
18847 MemberInit
= MaybeCreateExprWithCleanups(MemberInit
);
18848 // Note, MemberInit could actually come back empty if no initialization
18849 // is required (e.g., because it would call a trivial default constructor)
18850 if (!MemberInit
.get() || MemberInit
.isInvalid())
18854 new (Context
) CXXCtorInitializer(Context
, Field
, SourceLocation(),
18856 MemberInit
.getAs
<Expr
>(),
18858 AllToInit
.push_back(Member
);
18860 // Be sure that the destructor is accessible and is marked as referenced.
18861 if (const RecordType
*RecordTy
=
18862 Context
.getBaseElementType(Field
->getType())
18863 ->getAs
<RecordType
>()) {
18864 CXXRecordDecl
*RD
= cast
<CXXRecordDecl
>(RecordTy
->getDecl());
18865 if (CXXDestructorDecl
*Destructor
= LookupDestructor(RD
)) {
18866 MarkFunctionReferenced(Field
->getLocation(), Destructor
);
18867 CheckDestructorAccess(Field
->getLocation(), Destructor
,
18868 PDiag(diag::err_access_dtor_ivar
)
18869 << Context
.getBaseElementType(Field
->getType()));
18873 ObjCImplementation
->setIvarInitializers(Context
,
18874 AllToInit
.data(), AllToInit
.size());
18879 void DelegatingCycleHelper(CXXConstructorDecl
* Ctor
,
18880 llvm::SmallPtrSet
<CXXConstructorDecl
*, 4> &Valid
,
18881 llvm::SmallPtrSet
<CXXConstructorDecl
*, 4> &Invalid
,
18882 llvm::SmallPtrSet
<CXXConstructorDecl
*, 4> &Current
,
18884 if (Ctor
->isInvalidDecl())
18887 CXXConstructorDecl
*Target
= Ctor
->getTargetConstructor();
18889 // Target may not be determinable yet, for instance if this is a dependent
18890 // call in an uninstantiated template.
18892 const FunctionDecl
*FNTarget
= nullptr;
18893 (void)Target
->hasBody(FNTarget
);
18894 Target
= const_cast<CXXConstructorDecl
*>(
18895 cast_or_null
<CXXConstructorDecl
>(FNTarget
));
18898 CXXConstructorDecl
*Canonical
= Ctor
->getCanonicalDecl(),
18899 // Avoid dereferencing a null pointer here.
18900 *TCanonical
= Target
? Target
->getCanonicalDecl() : nullptr;
18902 if (!Current
.insert(Canonical
).second
)
18905 // We know that beyond here, we aren't chaining into a cycle.
18906 if (!Target
|| !Target
->isDelegatingConstructor() ||
18907 Target
->isInvalidDecl() || Valid
.count(TCanonical
)) {
18908 Valid
.insert(Current
.begin(), Current
.end());
18910 // We've hit a cycle.
18911 } else if (TCanonical
== Canonical
|| Invalid
.count(TCanonical
) ||
18912 Current
.count(TCanonical
)) {
18913 // If we haven't diagnosed this cycle yet, do so now.
18914 if (!Invalid
.count(TCanonical
)) {
18915 S
.Diag((*Ctor
->init_begin())->getSourceLocation(),
18916 diag::warn_delegating_ctor_cycle
)
18919 // Don't add a note for a function delegating directly to itself.
18920 if (TCanonical
!= Canonical
)
18921 S
.Diag(Target
->getLocation(), diag::note_it_delegates_to
);
18923 CXXConstructorDecl
*C
= Target
;
18924 while (C
->getCanonicalDecl() != Canonical
) {
18925 const FunctionDecl
*FNTarget
= nullptr;
18926 (void)C
->getTargetConstructor()->hasBody(FNTarget
);
18927 assert(FNTarget
&& "Ctor cycle through bodiless function");
18929 C
= const_cast<CXXConstructorDecl
*>(
18930 cast
<CXXConstructorDecl
>(FNTarget
));
18931 S
.Diag(C
->getLocation(), diag::note_which_delegates_to
);
18935 Invalid
.insert(Current
.begin(), Current
.end());
18938 DelegatingCycleHelper(Target
, Valid
, Invalid
, Current
, S
);
18943 void Sema::CheckDelegatingCtorCycles() {
18944 llvm::SmallPtrSet
<CXXConstructorDecl
*, 4> Valid
, Invalid
, Current
;
18946 for (DelegatingCtorDeclsType::iterator
18947 I
= DelegatingCtorDecls
.begin(ExternalSource
.get()),
18948 E
= DelegatingCtorDecls
.end();
18950 DelegatingCycleHelper(*I
, Valid
, Invalid
, Current
, *this);
18952 for (auto CI
= Invalid
.begin(), CE
= Invalid
.end(); CI
!= CE
; ++CI
)
18953 (*CI
)->setInvalidDecl();
18957 /// AST visitor that finds references to the 'this' expression.
18958 class FindCXXThisExpr
: public RecursiveASTVisitor
<FindCXXThisExpr
> {
18962 explicit FindCXXThisExpr(Sema
&S
) : S(S
) { }
18964 bool VisitCXXThisExpr(CXXThisExpr
*E
) {
18965 S
.Diag(E
->getLocation(), diag::err_this_static_member_func
)
18966 << E
->isImplicit();
18972 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl
*Method
) {
18973 TypeSourceInfo
*TSInfo
= Method
->getTypeSourceInfo();
18977 TypeLoc TL
= TSInfo
->getTypeLoc();
18978 FunctionProtoTypeLoc ProtoTL
= TL
.getAs
<FunctionProtoTypeLoc
>();
18982 // C++11 [expr.prim.general]p3:
18983 // [The expression this] shall not appear before the optional
18984 // cv-qualifier-seq and it shall not appear within the declaration of a
18985 // static member function (although its type and value category are defined
18986 // within a static member function as they are within a non-static member
18987 // function). [ Note: this is because declaration matching does not occur
18988 // until the complete declarator is known. - end note ]
18989 const FunctionProtoType
*Proto
= ProtoTL
.getTypePtr();
18990 FindCXXThisExpr
Finder(*this);
18992 // If the return type came after the cv-qualifier-seq, check it now.
18993 if (Proto
->hasTrailingReturn() &&
18994 !Finder
.TraverseTypeLoc(ProtoTL
.getReturnLoc()))
18997 // Check the exception specification.
18998 if (checkThisInStaticMemberFunctionExceptionSpec(Method
))
19001 // Check the trailing requires clause
19002 if (Expr
*E
= Method
->getTrailingRequiresClause())
19003 if (!Finder
.TraverseStmt(E
))
19006 return checkThisInStaticMemberFunctionAttributes(Method
);
19009 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl
*Method
) {
19010 TypeSourceInfo
*TSInfo
= Method
->getTypeSourceInfo();
19014 TypeLoc TL
= TSInfo
->getTypeLoc();
19015 FunctionProtoTypeLoc ProtoTL
= TL
.getAs
<FunctionProtoTypeLoc
>();
19019 const FunctionProtoType
*Proto
= ProtoTL
.getTypePtr();
19020 FindCXXThisExpr
Finder(*this);
19022 switch (Proto
->getExceptionSpecType()) {
19024 case EST_Uninstantiated
:
19025 case EST_Unevaluated
:
19026 case EST_BasicNoexcept
:
19028 case EST_DynamicNone
:
19033 case EST_DependentNoexcept
:
19034 case EST_NoexceptFalse
:
19035 case EST_NoexceptTrue
:
19036 if (!Finder
.TraverseStmt(Proto
->getNoexceptExpr()))
19041 for (const auto &E
: Proto
->exceptions()) {
19042 if (!Finder
.TraverseType(E
))
19051 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl
*Method
) {
19052 FindCXXThisExpr
Finder(*this);
19054 // Check attributes.
19055 for (const auto *A
: Method
->attrs()) {
19056 // FIXME: This should be emitted by tblgen.
19057 Expr
*Arg
= nullptr;
19058 ArrayRef
<Expr
*> Args
;
19059 if (const auto *G
= dyn_cast
<GuardedByAttr
>(A
))
19061 else if (const auto *G
= dyn_cast
<PtGuardedByAttr
>(A
))
19063 else if (const auto *AA
= dyn_cast
<AcquiredAfterAttr
>(A
))
19064 Args
= llvm::ArrayRef(AA
->args_begin(), AA
->args_size());
19065 else if (const auto *AB
= dyn_cast
<AcquiredBeforeAttr
>(A
))
19066 Args
= llvm::ArrayRef(AB
->args_begin(), AB
->args_size());
19067 else if (const auto *ETLF
= dyn_cast
<ExclusiveTrylockFunctionAttr
>(A
)) {
19068 Arg
= ETLF
->getSuccessValue();
19069 Args
= llvm::ArrayRef(ETLF
->args_begin(), ETLF
->args_size());
19070 } else if (const auto *STLF
= dyn_cast
<SharedTrylockFunctionAttr
>(A
)) {
19071 Arg
= STLF
->getSuccessValue();
19072 Args
= llvm::ArrayRef(STLF
->args_begin(), STLF
->args_size());
19073 } else if (const auto *LR
= dyn_cast
<LockReturnedAttr
>(A
))
19074 Arg
= LR
->getArg();
19075 else if (const auto *LE
= dyn_cast
<LocksExcludedAttr
>(A
))
19076 Args
= llvm::ArrayRef(LE
->args_begin(), LE
->args_size());
19077 else if (const auto *RC
= dyn_cast
<RequiresCapabilityAttr
>(A
))
19078 Args
= llvm::ArrayRef(RC
->args_begin(), RC
->args_size());
19079 else if (const auto *AC
= dyn_cast
<AcquireCapabilityAttr
>(A
))
19080 Args
= llvm::ArrayRef(AC
->args_begin(), AC
->args_size());
19081 else if (const auto *AC
= dyn_cast
<TryAcquireCapabilityAttr
>(A
))
19082 Args
= llvm::ArrayRef(AC
->args_begin(), AC
->args_size());
19083 else if (const auto *RC
= dyn_cast
<ReleaseCapabilityAttr
>(A
))
19084 Args
= llvm::ArrayRef(RC
->args_begin(), RC
->args_size());
19086 if (Arg
&& !Finder
.TraverseStmt(Arg
))
19089 for (unsigned I
= 0, N
= Args
.size(); I
!= N
; ++I
) {
19090 if (!Finder
.TraverseStmt(Args
[I
]))
19098 void Sema::checkExceptionSpecification(
19099 bool IsTopLevel
, ExceptionSpecificationType EST
,
19100 ArrayRef
<ParsedType
> DynamicExceptions
,
19101 ArrayRef
<SourceRange
> DynamicExceptionRanges
, Expr
*NoexceptExpr
,
19102 SmallVectorImpl
<QualType
> &Exceptions
,
19103 FunctionProtoType::ExceptionSpecInfo
&ESI
) {
19104 Exceptions
.clear();
19106 if (EST
== EST_Dynamic
) {
19107 Exceptions
.reserve(DynamicExceptions
.size());
19108 for (unsigned ei
= 0, ee
= DynamicExceptions
.size(); ei
!= ee
; ++ei
) {
19109 // FIXME: Preserve type source info.
19110 QualType ET
= GetTypeFromParser(DynamicExceptions
[ei
]);
19113 SmallVector
<UnexpandedParameterPack
, 2> Unexpanded
;
19114 collectUnexpandedParameterPacks(ET
, Unexpanded
);
19115 if (!Unexpanded
.empty()) {
19116 DiagnoseUnexpandedParameterPacks(
19117 DynamicExceptionRanges
[ei
].getBegin(), UPPC_ExceptionType
,
19123 // Check that the type is valid for an exception spec, and
19125 if (!CheckSpecifiedExceptionType(ET
, DynamicExceptionRanges
[ei
]))
19126 Exceptions
.push_back(ET
);
19128 ESI
.Exceptions
= Exceptions
;
19132 if (isComputedNoexcept(EST
)) {
19133 assert((NoexceptExpr
->isTypeDependent() ||
19134 NoexceptExpr
->getType()->getCanonicalTypeUnqualified() ==
19136 "Parser should have made sure that the expression is boolean");
19137 if (IsTopLevel
&& DiagnoseUnexpandedParameterPack(NoexceptExpr
)) {
19138 ESI
.Type
= EST_BasicNoexcept
;
19142 ESI
.NoexceptExpr
= NoexceptExpr
;
19147 void Sema::actOnDelayedExceptionSpecification(Decl
*MethodD
,
19148 ExceptionSpecificationType EST
,
19149 SourceRange SpecificationRange
,
19150 ArrayRef
<ParsedType
> DynamicExceptions
,
19151 ArrayRef
<SourceRange
> DynamicExceptionRanges
,
19152 Expr
*NoexceptExpr
) {
19156 // Dig out the method we're referring to.
19157 if (FunctionTemplateDecl
*FunTmpl
= dyn_cast
<FunctionTemplateDecl
>(MethodD
))
19158 MethodD
= FunTmpl
->getTemplatedDecl();
19160 CXXMethodDecl
*Method
= dyn_cast
<CXXMethodDecl
>(MethodD
);
19164 // Check the exception specification.
19165 llvm::SmallVector
<QualType
, 4> Exceptions
;
19166 FunctionProtoType::ExceptionSpecInfo ESI
;
19167 checkExceptionSpecification(/*IsTopLevel*/true, EST
, DynamicExceptions
,
19168 DynamicExceptionRanges
, NoexceptExpr
, Exceptions
,
19171 // Update the exception specification on the function type.
19172 Context
.adjustExceptionSpec(Method
, ESI
, /*AsWritten*/true);
19174 if (Method
->isStatic())
19175 checkThisInStaticMemberFunctionExceptionSpec(Method
);
19177 if (Method
->isVirtual()) {
19178 // Check overrides, which we previously had to delay.
19179 for (const CXXMethodDecl
*O
: Method
->overridden_methods())
19180 CheckOverridingFunctionExceptionSpec(Method
, O
);
19184 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
19186 MSPropertyDecl
*Sema::HandleMSProperty(Scope
*S
, RecordDecl
*Record
,
19187 SourceLocation DeclStart
, Declarator
&D
,
19189 InClassInitStyle InitStyle
,
19190 AccessSpecifier AS
,
19191 const ParsedAttr
&MSPropertyAttr
) {
19192 IdentifierInfo
*II
= D
.getIdentifier();
19194 Diag(DeclStart
, diag::err_anonymous_property
);
19197 SourceLocation Loc
= D
.getIdentifierLoc();
19199 TypeSourceInfo
*TInfo
= GetTypeForDeclarator(D
, S
);
19200 QualType T
= TInfo
->getType();
19201 if (getLangOpts().CPlusPlus
) {
19202 CheckExtraCXXDefaultArguments(D
);
19204 if (DiagnoseUnexpandedParameterPack(D
.getIdentifierLoc(), TInfo
,
19205 UPPC_DataMemberType
)) {
19206 D
.setInvalidType();
19208 TInfo
= Context
.getTrivialTypeSourceInfo(T
, Loc
);
19212 DiagnoseFunctionSpecifiers(D
.getDeclSpec());
19214 if (D
.getDeclSpec().isInlineSpecified())
19215 Diag(D
.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function
)
19216 << getLangOpts().CPlusPlus17
;
19217 if (DeclSpec::TSCS TSCS
= D
.getDeclSpec().getThreadStorageClassSpec())
19218 Diag(D
.getDeclSpec().getThreadStorageClassSpecLoc(),
19219 diag::err_invalid_thread
)
19220 << DeclSpec::getSpecifierName(TSCS
);
19222 // Check to see if this name was declared as a member previously
19223 NamedDecl
*PrevDecl
= nullptr;
19224 LookupResult
Previous(*this, II
, Loc
, LookupMemberName
,
19225 ForVisibleRedeclaration
);
19226 LookupName(Previous
, S
);
19227 switch (Previous
.getResultKind()) {
19228 case LookupResult::Found
:
19229 case LookupResult::FoundUnresolvedValue
:
19230 PrevDecl
= Previous
.getAsSingle
<NamedDecl
>();
19233 case LookupResult::FoundOverloaded
:
19234 PrevDecl
= Previous
.getRepresentativeDecl();
19237 case LookupResult::NotFound
:
19238 case LookupResult::NotFoundInCurrentInstantiation
:
19239 case LookupResult::Ambiguous
:
19243 if (PrevDecl
&& PrevDecl
->isTemplateParameter()) {
19244 // Maybe we will complain about the shadowed template parameter.
19245 DiagnoseTemplateParameterShadow(D
.getIdentifierLoc(), PrevDecl
);
19246 // Just pretend that we didn't see the previous declaration.
19247 PrevDecl
= nullptr;
19250 if (PrevDecl
&& !isDeclInScope(PrevDecl
, Record
, S
))
19251 PrevDecl
= nullptr;
19253 SourceLocation TSSL
= D
.getBeginLoc();
19254 MSPropertyDecl
*NewPD
=
19255 MSPropertyDecl::Create(Context
, Record
, Loc
, II
, T
, TInfo
, TSSL
,
19256 MSPropertyAttr
.getPropertyDataGetter(),
19257 MSPropertyAttr
.getPropertyDataSetter());
19258 ProcessDeclAttributes(TUScope
, NewPD
, D
);
19259 NewPD
->setAccess(AS
);
19261 if (NewPD
->isInvalidDecl())
19262 Record
->setInvalidDecl();
19264 if (D
.getDeclSpec().isModulePrivateSpecified())
19265 NewPD
->setModulePrivate();
19267 if (NewPD
->isInvalidDecl() && PrevDecl
) {
19268 // Don't introduce NewFD into scope; there's already something
19269 // with the same name in the same scope.
19271 PushOnScopeChains(NewPD
, S
);
19273 Record
->addDecl(NewPD
);
19278 void Sema::ActOnStartFunctionDeclarationDeclarator(
19279 Declarator
&Declarator
, unsigned TemplateParameterDepth
) {
19280 auto &Info
= InventedParameterInfos
.emplace_back();
19281 TemplateParameterList
*ExplicitParams
= nullptr;
19282 ArrayRef
<TemplateParameterList
*> ExplicitLists
=
19283 Declarator
.getTemplateParameterLists();
19284 if (!ExplicitLists
.empty()) {
19285 bool IsMemberSpecialization
, IsInvalid
;
19286 ExplicitParams
= MatchTemplateParametersToScopeSpecifier(
19287 Declarator
.getBeginLoc(), Declarator
.getIdentifierLoc(),
19288 Declarator
.getCXXScopeSpec(), /*TemplateId=*/nullptr,
19289 ExplicitLists
, /*IsFriend=*/false, IsMemberSpecialization
, IsInvalid
,
19290 /*SuppressDiagnostic=*/true);
19292 if (ExplicitParams
) {
19293 Info
.AutoTemplateParameterDepth
= ExplicitParams
->getDepth();
19294 llvm::append_range(Info
.TemplateParams
, *ExplicitParams
);
19295 Info
.NumExplicitTemplateParams
= ExplicitParams
->size();
19297 Info
.AutoTemplateParameterDepth
= TemplateParameterDepth
;
19298 Info
.NumExplicitTemplateParams
= 0;
19302 void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator
&Declarator
) {
19303 auto &FSI
= InventedParameterInfos
.back();
19304 if (FSI
.TemplateParams
.size() > FSI
.NumExplicitTemplateParams
) {
19305 if (FSI
.NumExplicitTemplateParams
!= 0) {
19306 TemplateParameterList
*ExplicitParams
=
19307 Declarator
.getTemplateParameterLists().back();
19308 Declarator
.setInventedTemplateParameterList(
19309 TemplateParameterList::Create(
19310 Context
, ExplicitParams
->getTemplateLoc(),
19311 ExplicitParams
->getLAngleLoc(), FSI
.TemplateParams
,
19312 ExplicitParams
->getRAngleLoc(),
19313 ExplicitParams
->getRequiresClause()));
19315 Declarator
.setInventedTemplateParameterList(
19316 TemplateParameterList::Create(
19317 Context
, SourceLocation(), SourceLocation(), FSI
.TemplateParams
,
19318 SourceLocation(), /*RequiresClause=*/nullptr));
19321 InventedParameterInfos
.pop_back();