clang 19.0.0git
SemaDeclCXX.cpp
Go to the documentation of this file.
1//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for C++ declarations.
10//
11//===----------------------------------------------------------------------===//
12
15#include "clang/AST/ASTLambda.h"
18#include "clang/AST/CharUnits.h"
20#include "clang/AST/DeclCXX.h"
23#include "clang/AST/Expr.h"
24#include "clang/AST/ExprCXX.h"
28#include "clang/AST/TypeLoc.h"
37#include "clang/Sema/DeclSpec.h"
40#include "clang/Sema/Lookup.h"
43#include "clang/Sema/Scope.h"
45#include "clang/Sema/SemaCUDA.h"
47#include "clang/Sema/SemaObjC.h"
49#include "clang/Sema/Template.h"
50#include "llvm/ADT/ArrayRef.h"
51#include "llvm/ADT/STLExtras.h"
52#include "llvm/ADT/STLForwardCompat.h"
53#include "llvm/ADT/ScopeExit.h"
54#include "llvm/ADT/SmallString.h"
55#include "llvm/ADT/StringExtras.h"
56#include "llvm/Support/ConvertUTF.h"
57#include "llvm/Support/SaveAndRestore.h"
58#include <map>
59#include <optional>
60#include <set>
61
62using namespace clang;
63
64//===----------------------------------------------------------------------===//
65// CheckDefaultArgumentVisitor
66//===----------------------------------------------------------------------===//
67
68namespace {
69/// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
70/// the default argument of a parameter to determine whether it
71/// contains any ill-formed subexpressions. For example, this will
72/// diagnose the use of local variables or parameters within the
73/// default argument expression.
74class CheckDefaultArgumentVisitor
75 : public ConstStmtVisitor<CheckDefaultArgumentVisitor, bool> {
76 Sema &S;
77 const Expr *DefaultArg;
78
79public:
80 CheckDefaultArgumentVisitor(Sema &S, const Expr *DefaultArg)
81 : S(S), DefaultArg(DefaultArg) {}
82
83 bool VisitExpr(const Expr *Node);
84 bool VisitDeclRefExpr(const DeclRefExpr *DRE);
85 bool VisitCXXThisExpr(const CXXThisExpr *ThisE);
86 bool VisitLambdaExpr(const LambdaExpr *Lambda);
87 bool VisitPseudoObjectExpr(const PseudoObjectExpr *POE);
88};
89
90/// VisitExpr - Visit all of the children of this expression.
91bool CheckDefaultArgumentVisitor::VisitExpr(const Expr *Node) {
92 bool IsInvalid = false;
93 for (const Stmt *SubStmt : Node->children())
94 if (SubStmt)
95 IsInvalid |= Visit(SubStmt);
96 return IsInvalid;
97}
98
99/// VisitDeclRefExpr - Visit a reference to a declaration, to
100/// determine whether this declaration can be used in the default
101/// argument expression.
102bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(const DeclRefExpr *DRE) {
103 const ValueDecl *Decl = dyn_cast<ValueDecl>(DRE->getDecl());
104
105 if (!isa<VarDecl, BindingDecl>(Decl))
106 return false;
107
108 if (const auto *Param = dyn_cast<ParmVarDecl>(Decl)) {
109 // C++ [dcl.fct.default]p9:
110 // [...] parameters of a function shall not be used in default
111 // argument expressions, even if they are not evaluated. [...]
112 //
113 // C++17 [dcl.fct.default]p9 (by CWG 2082):
114 // [...] A parameter shall not appear as a potentially-evaluated
115 // expression in a default argument. [...]
116 //
117 if (DRE->isNonOdrUse() != NOUR_Unevaluated)
118 return S.Diag(DRE->getBeginLoc(),
119 diag::err_param_default_argument_references_param)
120 << Param->getDeclName() << DefaultArg->getSourceRange();
121 } else if (auto *VD = Decl->getPotentiallyDecomposedVarDecl()) {
122 // C++ [dcl.fct.default]p7:
123 // Local variables shall not be used in default argument
124 // expressions.
125 //
126 // C++17 [dcl.fct.default]p7 (by CWG 2082):
127 // A local variable shall not appear as a potentially-evaluated
128 // expression in a default argument.
129 //
130 // C++20 [dcl.fct.default]p7 (DR as part of P0588R1, see also CWG 2346):
131 // Note: A local variable cannot be odr-used (6.3) in a default
132 // argument.
133 //
134 if (VD->isLocalVarDecl() && !DRE->isNonOdrUse())
135 return S.Diag(DRE->getBeginLoc(),
136 diag::err_param_default_argument_references_local)
137 << Decl << DefaultArg->getSourceRange();
138 }
139 return false;
140}
141
142/// VisitCXXThisExpr - Visit a C++ "this" expression.
143bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(const CXXThisExpr *ThisE) {
144 // C++ [dcl.fct.default]p8:
145 // The keyword this shall not be used in a default argument of a
146 // member function.
147 return S.Diag(ThisE->getBeginLoc(),
148 diag::err_param_default_argument_references_this)
149 << ThisE->getSourceRange();
150}
151
152bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(
153 const PseudoObjectExpr *POE) {
154 bool Invalid = false;
155 for (const Expr *E : POE->semantics()) {
156 // Look through bindings.
157 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) {
158 E = OVE->getSourceExpr();
159 assert(E && "pseudo-object binding without source expression?");
160 }
161
162 Invalid |= Visit(E);
163 }
164 return Invalid;
165}
166
167bool CheckDefaultArgumentVisitor::VisitLambdaExpr(const LambdaExpr *Lambda) {
168 // [expr.prim.lambda.capture]p9
169 // a lambda-expression appearing in a default argument cannot implicitly or
170 // explicitly capture any local entity. Such a lambda-expression can still
171 // have an init-capture if any full-expression in its initializer satisfies
172 // the constraints of an expression appearing in a default argument.
173 bool Invalid = false;
174 for (const LambdaCapture &LC : Lambda->captures()) {
175 if (!Lambda->isInitCapture(&LC))
176 return S.Diag(LC.getLocation(), diag::err_lambda_capture_default_arg);
177 // Init captures are always VarDecl.
178 auto *D = cast<VarDecl>(LC.getCapturedVar());
179 Invalid |= Visit(D->getInit());
180 }
181 return Invalid;
182}
183} // namespace
184
185void
187 const CXXMethodDecl *Method) {
188 // If we have an MSAny spec already, don't bother.
189 if (!Method || ComputedEST == EST_MSAny)
190 return;
191
192 const FunctionProtoType *Proto
193 = Method->getType()->getAs<FunctionProtoType>();
194 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
195 if (!Proto)
196 return;
197
199
200 // If we have a throw-all spec at this point, ignore the function.
201 if (ComputedEST == EST_None)
202 return;
203
204 if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
205 EST = EST_BasicNoexcept;
206
207 switch (EST) {
208 case EST_Unparsed:
210 case EST_Unevaluated:
211 llvm_unreachable("should not see unresolved exception specs here");
212
213 // If this function can throw any exceptions, make a note of that.
214 case EST_MSAny:
215 case EST_None:
216 // FIXME: Whichever we see last of MSAny and None determines our result.
217 // We should make a consistent, order-independent choice here.
218 ClearExceptions();
219 ComputedEST = EST;
220 return;
222 ClearExceptions();
223 ComputedEST = EST_None;
224 return;
225 // FIXME: If the call to this decl is using any of its default arguments, we
226 // need to search them for potentially-throwing calls.
227 // If this function has a basic noexcept, it doesn't affect the outcome.
229 case EST_NoexceptTrue:
230 case EST_NoThrow:
231 return;
232 // If we're still at noexcept(true) and there's a throw() callee,
233 // change to that specification.
234 case EST_DynamicNone:
235 if (ComputedEST == EST_BasicNoexcept)
236 ComputedEST = EST_DynamicNone;
237 return;
239 llvm_unreachable(
240 "should not generate implicit declarations for dependent cases");
241 case EST_Dynamic:
242 break;
243 }
244 assert(EST == EST_Dynamic && "EST case not considered earlier.");
245 assert(ComputedEST != EST_None &&
246 "Shouldn't collect exceptions when throw-all is guaranteed.");
247 ComputedEST = EST_Dynamic;
248 // Record the exceptions in this function's exception specification.
249 for (const auto &E : Proto->exceptions())
250 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
251 Exceptions.push_back(E);
252}
253
255 if (!S || ComputedEST == EST_MSAny)
256 return;
257
258 // FIXME:
259 //
260 // C++0x [except.spec]p14:
261 // [An] implicit exception-specification specifies the type-id T if and
262 // only if T is allowed by the exception-specification of a function directly
263 // invoked by f's implicit definition; f shall allow all exceptions if any
264 // function it directly invokes allows all exceptions, and f shall allow no
265 // exceptions if every function it directly invokes allows no exceptions.
266 //
267 // Note in particular that if an implicit exception-specification is generated
268 // for a function containing a throw-expression, that specification can still
269 // be noexcept(true).
270 //
271 // Note also that 'directly invoked' is not defined in the standard, and there
272 // is no indication that we should only consider potentially-evaluated calls.
273 //
274 // Ultimately we should implement the intent of the standard: the exception
275 // specification should be the set of exceptions which can be thrown by the
276 // implicit definition. For now, we assume that any non-nothrow expression can
277 // throw any exception.
278
279 if (Self->canThrow(S))
280 ComputedEST = EST_None;
281}
282
284 SourceLocation EqualLoc) {
285 if (RequireCompleteType(Param->getLocation(), Param->getType(),
286 diag::err_typecheck_decl_incomplete_type))
287 return true;
288
289 // C++ [dcl.fct.default]p5
290 // A default argument expression is implicitly converted (clause
291 // 4) to the parameter type. The default argument expression has
292 // the same semantic constraints as the initializer expression in
293 // a declaration of a variable of the parameter type, using the
294 // copy-initialization semantics (8.5).
296 Param);
298 EqualLoc);
299 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
300 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
301 if (Result.isInvalid())
302 return true;
303 Arg = Result.getAs<Expr>();
304
305 CheckCompletedExpr(Arg, EqualLoc);
307
308 return Arg;
309}
310
312 SourceLocation EqualLoc) {
313 // Add the default argument to the parameter
314 Param->setDefaultArg(Arg);
315
316 // We have already instantiated this parameter; provide each of the
317 // instantiations with the uninstantiated default argument.
318 UnparsedDefaultArgInstantiationsMap::iterator InstPos
320 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
321 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
322 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
323
324 // We're done tracking this parameter's instantiations.
326 }
327}
328
329void
331 Expr *DefaultArg) {
332 if (!param || !DefaultArg)
333 return;
334
335 ParmVarDecl *Param = cast<ParmVarDecl>(param);
336 UnparsedDefaultArgLocs.erase(Param);
337
338 // Default arguments are only permitted in C++
339 if (!getLangOpts().CPlusPlus) {
340 Diag(EqualLoc, diag::err_param_default_argument)
341 << DefaultArg->getSourceRange();
342 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
343 }
344
345 // Check for unexpanded parameter packs.
347 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
348
349 // C++11 [dcl.fct.default]p3
350 // A default argument expression [...] shall not be specified for a
351 // parameter pack.
352 if (Param->isParameterPack()) {
353 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
354 << DefaultArg->getSourceRange();
355 // Recover by discarding the default argument.
356 Param->setDefaultArg(nullptr);
357 return;
358 }
359
360 ExprResult Result = ConvertParamDefaultArgument(Param, DefaultArg, EqualLoc);
361 if (Result.isInvalid())
362 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
363
364 DefaultArg = Result.getAs<Expr>();
365
366 // Check that the default argument is well-formed
367 CheckDefaultArgumentVisitor DefaultArgChecker(*this, DefaultArg);
368 if (DefaultArgChecker.Visit(DefaultArg))
369 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
370
371 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
372}
373
375 SourceLocation EqualLoc,
376 SourceLocation ArgLoc) {
377 if (!param)
378 return;
379
380 ParmVarDecl *Param = cast<ParmVarDecl>(param);
381 Param->setUnparsedDefaultArg();
382 UnparsedDefaultArgLocs[Param] = ArgLoc;
383}
384
386 Expr *DefaultArg) {
387 if (!param)
388 return;
389
390 ParmVarDecl *Param = cast<ParmVarDecl>(param);
391 Param->setInvalidDecl();
392 UnparsedDefaultArgLocs.erase(Param);
393 ExprResult RE;
394 if (DefaultArg) {
395 RE = CreateRecoveryExpr(EqualLoc, DefaultArg->getEndLoc(), {DefaultArg},
396 Param->getType().getNonReferenceType());
397 } else {
398 RE = CreateRecoveryExpr(EqualLoc, EqualLoc, {},
399 Param->getType().getNonReferenceType());
400 }
401 Param->setDefaultArg(RE.get());
402}
403
405 // C++ [dcl.fct.default]p3
406 // A default argument expression shall be specified only in the
407 // parameter-declaration-clause of a function declaration or in a
408 // template-parameter (14.1). It shall not be specified for a
409 // parameter pack. If it is specified in a
410 // parameter-declaration-clause, it shall not occur within a
411 // declarator or abstract-declarator of a parameter-declaration.
412 bool MightBeFunction = D.isFunctionDeclarationContext();
413 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
414 DeclaratorChunk &chunk = D.getTypeObject(i);
415 if (chunk.Kind == DeclaratorChunk::Function) {
416 if (MightBeFunction) {
417 // This is a function declaration. It can have default arguments, but
418 // keep looking in case its return type is a function type with default
419 // arguments.
420 MightBeFunction = false;
421 continue;
422 }
423 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
424 ++argIdx) {
425 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
426 if (Param->hasUnparsedDefaultArg()) {
427 std::unique_ptr<CachedTokens> Toks =
428 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
429 SourceRange SR;
430 if (Toks->size() > 1)
431 SR = SourceRange((*Toks)[1].getLocation(),
432 Toks->back().getLocation());
433 else
434 SR = UnparsedDefaultArgLocs[Param];
435 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
436 << SR;
437 } else if (Param->getDefaultArg()) {
438 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
439 << Param->getDefaultArg()->getSourceRange();
440 Param->setDefaultArg(nullptr);
441 }
442 }
443 } else if (chunk.Kind != DeclaratorChunk::Paren) {
444 MightBeFunction = false;
445 }
446 }
447}
448
450 return llvm::any_of(FD->parameters(), [](ParmVarDecl *P) {
451 return P->hasDefaultArg() && !P->hasInheritedDefaultArg();
452 });
453}
454
456 Scope *S) {
457 bool Invalid = false;
458
459 // The declaration context corresponding to the scope is the semantic
460 // parent, unless this is a local function declaration, in which case
461 // it is that surrounding function.
462 DeclContext *ScopeDC = New->isLocalExternDecl()
463 ? New->getLexicalDeclContext()
464 : New->getDeclContext();
465
466 // Find the previous declaration for the purpose of default arguments.
467 FunctionDecl *PrevForDefaultArgs = Old;
468 for (/**/; PrevForDefaultArgs;
469 // Don't bother looking back past the latest decl if this is a local
470 // extern declaration; nothing else could work.
471 PrevForDefaultArgs = New->isLocalExternDecl()
472 ? nullptr
473 : PrevForDefaultArgs->getPreviousDecl()) {
474 // Ignore hidden declarations.
475 if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
476 continue;
477
478 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
479 !New->isCXXClassMember()) {
480 // Ignore default arguments of old decl if they are not in
481 // the same scope and this is not an out-of-line definition of
482 // a member function.
483 continue;
484 }
485
486 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
487 // If only one of these is a local function declaration, then they are
488 // declared in different scopes, even though isDeclInScope may think
489 // they're in the same scope. (If both are local, the scope check is
490 // sufficient, and if neither is local, then they are in the same scope.)
491 continue;
492 }
493
494 // We found the right previous declaration.
495 break;
496 }
497
498 // C++ [dcl.fct.default]p4:
499 // For non-template functions, default arguments can be added in
500 // later declarations of a function in the same
501 // scope. Declarations in different scopes have completely
502 // distinct sets of default arguments. That is, declarations in
503 // inner scopes do not acquire default arguments from
504 // declarations in outer scopes, and vice versa. In a given
505 // function declaration, all parameters subsequent to a
506 // parameter with a default argument shall have default
507 // arguments supplied in this or previous declarations. A
508 // default argument shall not be redefined by a later
509 // declaration (not even to the same value).
510 //
511 // C++ [dcl.fct.default]p6:
512 // Except for member functions of class templates, the default arguments
513 // in a member function definition that appears outside of the class
514 // definition are added to the set of default arguments provided by the
515 // member function declaration in the class definition.
516 for (unsigned p = 0, NumParams = PrevForDefaultArgs
517 ? PrevForDefaultArgs->getNumParams()
518 : 0;
519 p < NumParams; ++p) {
520 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
521 ParmVarDecl *NewParam = New->getParamDecl(p);
522
523 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
524 bool NewParamHasDfl = NewParam->hasDefaultArg();
525
526 if (OldParamHasDfl && NewParamHasDfl) {
527 unsigned DiagDefaultParamID =
528 diag::err_param_default_argument_redefinition;
529
530 // MSVC accepts that default parameters be redefined for member functions
531 // of template class. The new default parameter's value is ignored.
532 Invalid = true;
533 if (getLangOpts().MicrosoftExt) {
534 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
535 if (MD && MD->getParent()->getDescribedClassTemplate()) {
536 // Merge the old default argument into the new parameter.
537 NewParam->setHasInheritedDefaultArg();
538 if (OldParam->hasUninstantiatedDefaultArg())
540 OldParam->getUninstantiatedDefaultArg());
541 else
542 NewParam->setDefaultArg(OldParam->getInit());
543 DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
544 Invalid = false;
545 }
546 }
547
548 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
549 // hint here. Alternatively, we could walk the type-source information
550 // for NewParam to find the last source location in the type... but it
551 // isn't worth the effort right now. This is the kind of test case that
552 // is hard to get right:
553 // int f(int);
554 // void g(int (*fp)(int) = f);
555 // void g(int (*fp)(int) = &f);
556 Diag(NewParam->getLocation(), DiagDefaultParamID)
557 << NewParam->getDefaultArgRange();
558
559 // Look for the function declaration where the default argument was
560 // actually written, which may be a declaration prior to Old.
561 for (auto Older = PrevForDefaultArgs;
562 OldParam->hasInheritedDefaultArg(); /**/) {
563 Older = Older->getPreviousDecl();
564 OldParam = Older->getParamDecl(p);
565 }
566
567 Diag(OldParam->getLocation(), diag::note_previous_definition)
568 << OldParam->getDefaultArgRange();
569 } else if (OldParamHasDfl) {
570 // Merge the old default argument into the new parameter unless the new
571 // function is a friend declaration in a template class. In the latter
572 // case the default arguments will be inherited when the friend
573 // declaration will be instantiated.
574 if (New->getFriendObjectKind() == Decl::FOK_None ||
576 // It's important to use getInit() here; getDefaultArg()
577 // strips off any top-level ExprWithCleanups.
578 NewParam->setHasInheritedDefaultArg();
579 if (OldParam->hasUnparsedDefaultArg())
580 NewParam->setUnparsedDefaultArg();
581 else if (OldParam->hasUninstantiatedDefaultArg())
583 OldParam->getUninstantiatedDefaultArg());
584 else
585 NewParam->setDefaultArg(OldParam->getInit());
586 }
587 } else if (NewParamHasDfl) {
588 if (New->getDescribedFunctionTemplate()) {
589 // Paragraph 4, quoted above, only applies to non-template functions.
590 Diag(NewParam->getLocation(),
591 diag::err_param_default_argument_template_redecl)
592 << NewParam->getDefaultArgRange();
593 Diag(PrevForDefaultArgs->getLocation(),
594 diag::note_template_prev_declaration)
595 << false;
596 } else if (New->getTemplateSpecializationKind()
599 // C++ [temp.expr.spec]p21:
600 // Default function arguments shall not be specified in a declaration
601 // or a definition for one of the following explicit specializations:
602 // - the explicit specialization of a function template;
603 // - the explicit specialization of a member function template;
604 // - the explicit specialization of a member function of a class
605 // template where the class template specialization to which the
606 // member function specialization belongs is implicitly
607 // instantiated.
608 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
610 << New->getDeclName()
611 << NewParam->getDefaultArgRange();
612 } else if (New->getDeclContext()->isDependentContext()) {
613 // C++ [dcl.fct.default]p6 (DR217):
614 // Default arguments for a member function of a class template shall
615 // be specified on the initial declaration of the member function
616 // within the class template.
617 //
618 // Reading the tea leaves a bit in DR217 and its reference to DR205
619 // leads me to the conclusion that one cannot add default function
620 // arguments for an out-of-line definition of a member function of a
621 // dependent type.
622 int WhichKind = 2;
624 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
625 if (Record->getDescribedClassTemplate())
626 WhichKind = 0;
627 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
628 WhichKind = 1;
629 else
630 WhichKind = 2;
631 }
632
633 Diag(NewParam->getLocation(),
634 diag::err_param_default_argument_member_template_redecl)
635 << WhichKind
636 << NewParam->getDefaultArgRange();
637 }
638 }
639 }
640
641 // DR1344: If a default argument is added outside a class definition and that
642 // default argument makes the function a special member function, the program
643 // is ill-formed. This can only happen for constructors.
644 if (isa<CXXConstructorDecl>(New) &&
646 CXXSpecialMemberKind NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
647 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
648 if (NewSM != OldSM) {
649 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
650 assert(NewParam->hasDefaultArg());
651 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
652 << NewParam->getDefaultArgRange() << llvm::to_underlying(NewSM);
653 Diag(Old->getLocation(), diag::note_previous_declaration);
654 }
655 }
656
657 const FunctionDecl *Def;
658 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
659 // template has a constexpr specifier then all its declarations shall
660 // contain the constexpr specifier.
661 if (New->getConstexprKind() != Old->getConstexprKind()) {
662 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
663 << New << static_cast<int>(New->getConstexprKind())
664 << static_cast<int>(Old->getConstexprKind());
665 Diag(Old->getLocation(), diag::note_previous_declaration);
666 Invalid = true;
667 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
668 Old->isDefined(Def) &&
669 // If a friend function is inlined but does not have 'inline'
670 // specifier, it is a definition. Do not report attribute conflict
671 // in this case, redefinition will be diagnosed later.
672 (New->isInlineSpecified() ||
674 // C++11 [dcl.fcn.spec]p4:
675 // If the definition of a function appears in a translation unit before its
676 // first declaration as inline, the program is ill-formed.
677 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
678 Diag(Def->getLocation(), diag::note_previous_definition);
679 Invalid = true;
680 }
681
682 // C++17 [temp.deduct.guide]p3:
683 // Two deduction guide declarations in the same translation unit
684 // for the same class template shall not have equivalent
685 // parameter-declaration-clauses.
686 if (isa<CXXDeductionGuideDecl>(New) &&
688 Diag(New->getLocation(), diag::err_deduction_guide_redeclared);
689 Diag(Old->getLocation(), diag::note_previous_declaration);
690 }
691
692 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
693 // argument expression, that declaration shall be a definition and shall be
694 // the only declaration of the function or function template in the
695 // translation unit.
698 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
699 Diag(Old->getLocation(), diag::note_previous_declaration);
700 Invalid = true;
701 }
702
703 // C++11 [temp.friend]p4 (DR329):
704 // When a function is defined in a friend function declaration in a class
705 // template, the function is instantiated when the function is odr-used.
706 // The same restrictions on multiple declarations and definitions that
707 // apply to non-template function declarations and definitions also apply
708 // to these implicit definitions.
709 const FunctionDecl *OldDefinition = nullptr;
711 Old->isDefined(OldDefinition, true))
712 CheckForFunctionRedefinition(New, OldDefinition);
713
714 return Invalid;
715}
716
719 ? diag::warn_cxx23_placeholder_var_definition
720 : diag::ext_placeholder_var_definition);
721}
722
723NamedDecl *
725 MultiTemplateParamsArg TemplateParamLists) {
726 assert(D.isDecompositionDeclarator());
727 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
728
729 // The syntax only allows a decomposition declarator as a simple-declaration,
730 // a for-range-declaration, or a condition in Clang, but we parse it in more
731 // cases than that.
732 if (!D.mayHaveDecompositionDeclarator()) {
733 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
734 << Decomp.getSourceRange();
735 return nullptr;
736 }
737
738 if (!TemplateParamLists.empty()) {
739 // FIXME: There's no rule against this, but there are also no rules that
740 // would actually make it usable, so we reject it for now.
741 Diag(TemplateParamLists.front()->getTemplateLoc(),
742 diag::err_decomp_decl_template);
743 return nullptr;
744 }
745
746 Diag(Decomp.getLSquareLoc(),
748 ? diag::ext_decomp_decl
749 : D.getContext() == DeclaratorContext::Condition
750 ? diag::ext_decomp_decl_cond
751 : diag::warn_cxx14_compat_decomp_decl)
752 << Decomp.getSourceRange();
753
754 // The semantic context is always just the current context.
755 DeclContext *const DC = CurContext;
756
757 // C++17 [dcl.dcl]/8:
758 // The decl-specifier-seq shall contain only the type-specifier auto
759 // and cv-qualifiers.
760 // C++20 [dcl.dcl]/8:
761 // If decl-specifier-seq contains any decl-specifier other than static,
762 // thread_local, auto, or cv-qualifiers, the program is ill-formed.
763 // C++23 [dcl.pre]/6:
764 // Each decl-specifier in the decl-specifier-seq shall be static,
765 // thread_local, auto (9.2.9.6 [dcl.spec.auto]), or a cv-qualifier.
766 auto &DS = D.getDeclSpec();
767 {
768 // Note: While constrained-auto needs to be checked, we do so separately so
769 // we can emit a better diagnostic.
770 SmallVector<StringRef, 8> BadSpecifiers;
771 SmallVector<SourceLocation, 8> BadSpecifierLocs;
772 SmallVector<StringRef, 8> CPlusPlus20Specifiers;
773 SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs;
774 if (auto SCS = DS.getStorageClassSpec()) {
775 if (SCS == DeclSpec::SCS_static) {
776 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS));
777 CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc());
778 } else {
779 BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
780 BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
781 }
782 }
783 if (auto TSCS = DS.getThreadStorageClassSpec()) {
784 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS));
785 CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
786 }
787 if (DS.hasConstexprSpecifier()) {
788 BadSpecifiers.push_back(
789 DeclSpec::getSpecifierName(DS.getConstexprSpecifier()));
790 BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
791 }
792 if (DS.isInlineSpecified()) {
793 BadSpecifiers.push_back("inline");
794 BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
795 }
796
797 if (!BadSpecifiers.empty()) {
798 auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
799 Err << (int)BadSpecifiers.size()
800 << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
801 // Don't add FixItHints to remove the specifiers; we do still respect
802 // them when building the underlying variable.
803 for (auto Loc : BadSpecifierLocs)
804 Err << SourceRange(Loc, Loc);
805 } else if (!CPlusPlus20Specifiers.empty()) {
806 auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(),
808 ? diag::warn_cxx17_compat_decomp_decl_spec
809 : diag::ext_decomp_decl_spec);
810 Warn << (int)CPlusPlus20Specifiers.size()
811 << llvm::join(CPlusPlus20Specifiers.begin(),
812 CPlusPlus20Specifiers.end(), " ");
813 for (auto Loc : CPlusPlus20SpecifierLocs)
814 Warn << SourceRange(Loc, Loc);
815 }
816 // We can't recover from it being declared as a typedef.
817 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
818 return nullptr;
819 }
820
821 // C++2a [dcl.struct.bind]p1:
822 // A cv that includes volatile is deprecated
823 if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) &&
825 Diag(DS.getVolatileSpecLoc(),
826 diag::warn_deprecated_volatile_structured_binding);
827
829 QualType R = TInfo->getType();
830
831 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
833 D.setInvalidType();
834
835 // The syntax only allows a single ref-qualifier prior to the decomposition
836 // declarator. No other declarator chunks are permitted. Also check the type
837 // specifier here.
838 if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
839 D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
840 (D.getNumTypeObjects() == 1 &&
841 D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
842 Diag(Decomp.getLSquareLoc(),
843 (D.hasGroupingParens() ||
844 (D.getNumTypeObjects() &&
845 D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
846 ? diag::err_decomp_decl_parens
847 : diag::err_decomp_decl_type)
848 << R;
849
850 // In most cases, there's no actual problem with an explicitly-specified
851 // type, but a function type won't work here, and ActOnVariableDeclarator
852 // shouldn't be called for such a type.
853 if (R->isFunctionType())
854 D.setInvalidType();
855 }
856
857 // Constrained auto is prohibited by [decl.pre]p6, so check that here.
858 if (DS.isConstrainedAuto()) {
859 TemplateIdAnnotation *TemplRep = DS.getRepAsTemplateId();
860 assert(TemplRep->Kind == TNK_Concept_template &&
861 "No other template kind should be possible for a constrained auto");
862
863 SourceRange TemplRange{TemplRep->TemplateNameLoc,
864 TemplRep->RAngleLoc.isValid()
865 ? TemplRep->RAngleLoc
866 : TemplRep->TemplateNameLoc};
867 Diag(TemplRep->TemplateNameLoc, diag::err_decomp_decl_constraint)
868 << TemplRange << FixItHint::CreateRemoval(TemplRange);
869 }
870
871 // Build the BindingDecls.
873
874 // Build the BindingDecls.
875 for (auto &B : D.getDecompositionDeclarator().bindings()) {
876 // Check for name conflicts.
877 DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
878 IdentifierInfo *VarName = B.Name;
879 assert(VarName && "Cannot have an unnamed binding declaration");
880
882 RedeclarationKind::ForVisibleRedeclaration);
884 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
885
886 // It's not permitted to shadow a template parameter name.
887 if (Previous.isSingleResult() &&
888 Previous.getFoundDecl()->isTemplateParameter()) {
889 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
890 Previous.getFoundDecl());
891 Previous.clear();
892 }
893
894 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, VarName);
895
896 ProcessDeclAttributeList(S, BD, *B.Attrs);
897
898 // Find the shadowed declaration before filtering for scope.
899 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
901 : nullptr;
902
903 bool ConsiderLinkage = DC->isFunctionOrMethod() &&
904 DS.getStorageClassSpec() == DeclSpec::SCS_extern;
905 FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
906 /*AllowInlineNamespace*/false);
907
908 bool IsPlaceholder = DS.getStorageClassSpec() != DeclSpec::SCS_static &&
909 DC->isFunctionOrMethod() && VarName->isPlaceholder();
910 if (!Previous.empty()) {
911 if (IsPlaceholder) {
912 bool sameDC = (Previous.end() - 1)
913 ->getDeclContext()
914 ->getRedeclContext()
915 ->Equals(DC->getRedeclContext());
916 if (sameDC &&
917 isDeclInScope(*(Previous.end() - 1), CurContext, S, false)) {
918 Previous.clear();
920 }
921 } else {
922 auto *Old = Previous.getRepresentativeDecl();
923 Diag(B.NameLoc, diag::err_redefinition) << B.Name;
924 Diag(Old->getLocation(), diag::note_previous_definition);
925 }
926 } else if (ShadowedDecl && !D.isRedeclaration()) {
927 CheckShadow(BD, ShadowedDecl, Previous);
928 }
929 PushOnScopeChains(BD, S, true);
930 Bindings.push_back(BD);
931 ParsingInitForAutoVars.insert(BD);
932 }
933
934 // There are no prior lookup results for the variable itself, because it
935 // is unnamed.
936 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
937 Decomp.getLSquareLoc());
939 RedeclarationKind::ForVisibleRedeclaration);
940
941 // Build the variable that holds the non-decomposed object.
942 bool AddToScope = true;
943 NamedDecl *New =
944 ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
945 MultiTemplateParamsArg(), AddToScope, Bindings);
946 if (AddToScope) {
947 S->AddDecl(New);
949 }
950
951 if (OpenMP().isInOpenMPDeclareTargetContext())
953
954 return New;
955}
956
959 QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
960 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
961 if ((int64_t)Bindings.size() != NumElems) {
962 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
963 << DecompType << (unsigned)Bindings.size()
964 << (unsigned)NumElems.getLimitedValue(UINT_MAX)
965 << toString(NumElems, 10) << (NumElems < Bindings.size());
966 return true;
967 }
968
969 unsigned I = 0;
970 for (auto *B : Bindings) {
971 SourceLocation Loc = B->getLocation();
972 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
973 if (E.isInvalid())
974 return true;
975 E = GetInit(Loc, E.get(), I++);
976 if (E.isInvalid())
977 return true;
978 B->setBinding(ElemType, E.get());
979 }
980
981 return false;
982}
983
986 ValueDecl *Src, QualType DecompType,
987 const llvm::APSInt &NumElems,
988 QualType ElemType) {
990 S, Bindings, Src, DecompType, NumElems, ElemType,
991 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
993 if (E.isInvalid())
994 return ExprError();
995 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
996 });
997}
998
1000 ValueDecl *Src, QualType DecompType,
1001 const ConstantArrayType *CAT) {
1002 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
1003 llvm::APSInt(CAT->getSize()),
1004 CAT->getElementType());
1005}
1006
1008 ValueDecl *Src, QualType DecompType,
1009 const VectorType *VT) {
1011 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
1013 DecompType.getQualifiers()));
1014}
1015
1018 ValueDecl *Src, QualType DecompType,
1019 const ComplexType *CT) {
1021 S, Bindings, Src, DecompType, llvm::APSInt::get(2),
1023 DecompType.getQualifiers()),
1024 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
1025 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
1026 });
1027}
1028
1031 const TemplateParameterList *Params) {
1033 llvm::raw_svector_ostream OS(SS);
1034 bool First = true;
1035 unsigned I = 0;
1036 for (auto &Arg : Args.arguments()) {
1037 if (!First)
1038 OS << ", ";
1039 Arg.getArgument().print(PrintingPolicy, OS,
1041 PrintingPolicy, Params, I));
1042 First = false;
1043 I++;
1044 }
1045 return std::string(OS.str());
1046}
1047
1048static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
1049 SourceLocation Loc, StringRef Trait,
1051 unsigned DiagID) {
1052 auto DiagnoseMissing = [&] {
1053 if (DiagID)
1055 Args, /*Params*/ nullptr);
1056 return true;
1057 };
1058
1059 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
1061 if (!Std)
1062 return DiagnoseMissing();
1063
1064 // Look up the trait itself, within namespace std. We can diagnose various
1065 // problems with this lookup even if we've been asked to not diagnose a
1066 // missing specialization, because this can only fail if the user has been
1067 // declaring their own names in namespace std or we don't support the
1068 // standard library implementation in use.
1072 return DiagnoseMissing();
1073 if (Result.isAmbiguous())
1074 return true;
1075
1076 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
1077 if (!TraitTD) {
1078 Result.suppressDiagnostics();
1079 NamedDecl *Found = *Result.begin();
1080 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
1081 S.Diag(Found->getLocation(), diag::note_declared_at);
1082 return true;
1083 }
1084
1085 // Build the template-id.
1086 QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
1087 if (TraitTy.isNull())
1088 return true;
1089 if (!S.isCompleteType(Loc, TraitTy)) {
1090 if (DiagID)
1092 Loc, TraitTy, DiagID,
1094 TraitTD->getTemplateParameters()));
1095 return true;
1096 }
1097
1098 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
1099 assert(RD && "specialization of class template is not a class?");
1100
1101 // Look up the member of the trait type.
1102 S.LookupQualifiedName(TraitMemberLookup, RD);
1103 return TraitMemberLookup.isAmbiguous();
1104}
1105
1108 uint64_t I) {
1110 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
1111}
1112
1116}
1117
1118namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1119
1121 llvm::APSInt &Size) {
1124
1127
1128 // Form template argument list for tuple_size<T>.
1131
1132 // If there's no tuple_size specialization or the lookup of 'value' is empty,
1133 // it's not tuple-like.
1134 if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) ||
1135 R.empty())
1136 return IsTupleLike::NotTupleLike;
1137
1138 // If we get this far, we've committed to the tuple interpretation, but
1139 // we can still fail if there actually isn't a usable ::value.
1140
1141 struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1142 LookupResult &R;
1144 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1145 : R(R), Args(Args) {}
1146 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
1147 SourceLocation Loc) override {
1148 return S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1150 /*Params*/ nullptr);
1151 }
1152 } Diagnoser(R, Args);
1153
1154 ExprResult E =
1155 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1156 if (E.isInvalid())
1157 return IsTupleLike::Error;
1158
1159 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser);
1160 if (E.isInvalid())
1161 return IsTupleLike::Error;
1162
1163 return IsTupleLike::TupleLike;
1164}
1165
1166/// \return std::tuple_element<I, T>::type.
1168 unsigned I, QualType T) {
1169 // Form template argument list for tuple_element<I, T>.
1171 Args.addArgument(
1174
1175 DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1178 S, R, Loc, "tuple_element", Args,
1179 diag::err_decomp_decl_std_tuple_element_not_specialized))
1180 return QualType();
1181
1182 auto *TD = R.getAsSingle<TypeDecl>();
1183 if (!TD) {
1185 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1187 /*Params*/ nullptr);
1188 if (!R.empty())
1189 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1190 return QualType();
1191 }
1192
1193 return S.Context.getTypeDeclType(TD);
1194}
1195
1196namespace {
1197struct InitializingBinding {
1198 Sema &S;
1199 InitializingBinding(Sema &S, BindingDecl *BD) : S(S) {
1203 Ctx.Entity = BD;
1205 }
1206 ~InitializingBinding() {
1208 }
1209};
1210}
1211
1214 VarDecl *Src, QualType DecompType,
1215 const llvm::APSInt &TupleSize) {
1216 if ((int64_t)Bindings.size() != TupleSize) {
1217 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1218 << DecompType << (unsigned)Bindings.size()
1219 << (unsigned)TupleSize.getLimitedValue(UINT_MAX)
1220 << toString(TupleSize, 10) << (TupleSize < Bindings.size());
1221 return true;
1222 }
1223
1224 if (Bindings.empty())
1225 return false;
1226
1227 DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1228
1229 // [dcl.decomp]p3:
1230 // The unqualified-id get is looked up in the scope of E by class member
1231 // access lookup ...
1232 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1233 bool UseMemberGet = false;
1234 if (S.isCompleteType(Src->getLocation(), DecompType)) {
1235 if (auto *RD = DecompType->getAsCXXRecordDecl())
1236 S.LookupQualifiedName(MemberGet, RD);
1237 if (MemberGet.isAmbiguous())
1238 return true;
1239 // ... and if that finds at least one declaration that is a function
1240 // template whose first template parameter is a non-type parameter ...
1241 for (NamedDecl *D : MemberGet) {
1242 if (FunctionTemplateDecl *FTD =
1243 dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
1244 TemplateParameterList *TPL = FTD->getTemplateParameters();
1245 if (TPL->size() != 0 &&
1246 isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) {
1247 // ... the initializer is e.get<i>().
1248 UseMemberGet = true;
1249 break;
1250 }
1251 }
1252 }
1253 }
1254
1255 unsigned I = 0;
1256 for (auto *B : Bindings) {
1257 InitializingBinding InitContext(S, B);
1258 SourceLocation Loc = B->getLocation();
1259
1260 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1261 if (E.isInvalid())
1262 return true;
1263
1264 // e is an lvalue if the type of the entity is an lvalue reference and
1265 // an xvalue otherwise
1266 if (!Src->getType()->isLValueReferenceType())
1267 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1268 E.get(), nullptr, VK_XValue,
1270
1272 Args.addArgument(
1274
1275 if (UseMemberGet) {
1276 // if [lookup of member get] finds at least one declaration, the
1277 // initializer is e.get<i-1>().
1278 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1279 CXXScopeSpec(), SourceLocation(), nullptr,
1280 MemberGet, &Args, nullptr);
1281 if (E.isInvalid())
1282 return true;
1283
1284 E = S.BuildCallExpr(nullptr, E.get(), Loc, std::nullopt, Loc);
1285 } else {
1286 // Otherwise, the initializer is get<i-1>(e), where get is looked up
1287 // in the associated namespaces.
1290 DeclarationNameInfo(GetDN, Loc), /*RequiresADL=*/true, &Args,
1292 /*KnownDependent=*/false);
1293
1294 Expr *Arg = E.get();
1295 E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc);
1296 }
1297 if (E.isInvalid())
1298 return true;
1299 Expr *Init = E.get();
1300
1301 // Given the type T designated by std::tuple_element<i - 1, E>::type,
1302 QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1303 if (T.isNull())
1304 return true;
1305
1306 // each vi is a variable of type "reference to T" initialized with the
1307 // initializer, where the reference is an lvalue reference if the
1308 // initializer is an lvalue and an rvalue reference otherwise
1309 QualType RefType =
1310 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1311 if (RefType.isNull())
1312 return true;
1313 auto *RefVD = VarDecl::Create(
1314 S.Context, Src->getDeclContext(), Loc, Loc,
1315 B->getDeclName().getAsIdentifierInfo(), RefType,
1317 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1318 RefVD->setTSCSpec(Src->getTSCSpec());
1319 RefVD->setImplicit();
1320 if (Src->isInlineSpecified())
1321 RefVD->setInlineSpecified();
1322 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1323
1326 InitializationSequence Seq(S, Entity, Kind, Init);
1327 E = Seq.Perform(S, Entity, Kind, Init);
1328 if (E.isInvalid())
1329 return true;
1330 E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
1331 if (E.isInvalid())
1332 return true;
1333 RefVD->setInit(E.get());
1335
1337 DeclarationNameInfo(B->getDeclName(), Loc),
1338 RefVD);
1339 if (E.isInvalid())
1340 return true;
1341
1342 B->setBinding(T, E.get());
1343 I++;
1344 }
1345
1346 return false;
1347}
1348
1349/// Find the base class to decompose in a built-in decomposition of a class type.
1350/// This base class search is, unfortunately, not quite like any other that we
1351/// perform anywhere else in C++.
1353 const CXXRecordDecl *RD,
1354 CXXCastPath &BasePath) {
1355 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1356 CXXBasePath &Path) {
1357 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1358 };
1359
1360 const CXXRecordDecl *ClassWithFields = nullptr;
1362 if (RD->hasDirectFields())
1363 // [dcl.decomp]p4:
1364 // Otherwise, all of E's non-static data members shall be public direct
1365 // members of E ...
1366 ClassWithFields = RD;
1367 else {
1368 // ... or of ...
1369 CXXBasePaths Paths;
1370 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1371 if (!RD->lookupInBases(BaseHasFields, Paths)) {
1372 // If no classes have fields, just decompose RD itself. (This will work
1373 // if and only if zero bindings were provided.)
1374 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
1375 }
1376
1377 CXXBasePath *BestPath = nullptr;
1378 for (auto &P : Paths) {
1379 if (!BestPath)
1380 BestPath = &P;
1381 else if (!S.Context.hasSameType(P.back().Base->getType(),
1382 BestPath->back().Base->getType())) {
1383 // ... the same ...
1384 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1385 << false << RD << BestPath->back().Base->getType()
1386 << P.back().Base->getType();
1387 return DeclAccessPair();
1388 } else if (P.Access < BestPath->Access) {
1389 BestPath = &P;
1390 }
1391 }
1392
1393 // ... unambiguous ...
1394 QualType BaseType = BestPath->back().Base->getType();
1395 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1396 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1397 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1398 return DeclAccessPair();
1399 }
1400
1401 // ... [accessible, implied by other rules] base class of E.
1402 S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD),
1403 *BestPath, diag::err_decomp_decl_inaccessible_base);
1404 AS = BestPath->Access;
1405
1406 ClassWithFields = BaseType->getAsCXXRecordDecl();
1407 S.BuildBasePathArray(Paths, BasePath);
1408 }
1409
1410 // The above search did not check whether the selected class itself has base
1411 // classes with fields, so check that now.
1412 CXXBasePaths Paths;
1413 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1414 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1415 << (ClassWithFields == RD) << RD << ClassWithFields
1416 << Paths.front().back().Base->getType();
1417 return DeclAccessPair();
1418 }
1419
1420 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1421}
1422
1424 ValueDecl *Src, QualType DecompType,
1425 const CXXRecordDecl *OrigRD) {
1426 if (S.RequireCompleteType(Src->getLocation(), DecompType,
1427 diag::err_incomplete_type))
1428 return true;
1429
1430 CXXCastPath BasePath;
1431 DeclAccessPair BasePair =
1432 findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1433 const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1434 if (!RD)
1435 return true;
1437 DecompType.getQualifiers());
1438
1439 auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1440 unsigned NumFields = llvm::count_if(
1441 RD->fields(), [](FieldDecl *FD) { return !FD->isUnnamedBitField(); });
1442 assert(Bindings.size() != NumFields);
1443 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1444 << DecompType << (unsigned)Bindings.size() << NumFields << NumFields
1445 << (NumFields < Bindings.size());
1446 return true;
1447 };
1448
1449 // all of E's non-static data members shall be [...] well-formed
1450 // when named as e.name in the context of the structured binding,
1451 // E shall not have an anonymous union member, ...
1452 unsigned I = 0;
1453 for (auto *FD : RD->fields()) {
1454 if (FD->isUnnamedBitField())
1455 continue;
1456
1457 // All the non-static data members are required to be nameable, so they
1458 // must all have names.
1459 if (!FD->getDeclName()) {
1460 if (RD->isLambda()) {
1461 S.Diag(Src->getLocation(), diag::err_decomp_decl_lambda);
1462 S.Diag(RD->getLocation(), diag::note_lambda_decl);
1463 return true;
1464 }
1465
1466 if (FD->isAnonymousStructOrUnion()) {
1467 S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1468 << DecompType << FD->getType()->isUnionType();
1469 S.Diag(FD->getLocation(), diag::note_declared_at);
1470 return true;
1471 }
1472
1473 // FIXME: Are there any other ways we could have an anonymous member?
1474 }
1475
1476 // We have a real field to bind.
1477 if (I >= Bindings.size())
1478 return DiagnoseBadNumberOfBindings();
1479 auto *B = Bindings[I++];
1480 SourceLocation Loc = B->getLocation();
1481
1482 // The field must be accessible in the context of the structured binding.
1483 // We already checked that the base class is accessible.
1484 // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1485 // const_cast here.
1487 Loc, const_cast<CXXRecordDecl *>(OrigRD),
1489 BasePair.getAccess(), FD->getAccess())));
1490
1491 // Initialize the binding to Src.FD.
1492 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1493 if (E.isInvalid())
1494 return true;
1495 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1496 VK_LValue, &BasePath);
1497 if (E.isInvalid())
1498 return true;
1499 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1500 CXXScopeSpec(), FD,
1501 DeclAccessPair::make(FD, FD->getAccess()),
1502 DeclarationNameInfo(FD->getDeclName(), Loc));
1503 if (E.isInvalid())
1504 return true;
1505
1506 // If the type of the member is T, the referenced type is cv T, where cv is
1507 // the cv-qualification of the decomposition expression.
1508 //
1509 // FIXME: We resolve a defect here: if the field is mutable, we do not add
1510 // 'const' to the type of the field.
1511 Qualifiers Q = DecompType.getQualifiers();
1512 if (FD->isMutable())
1513 Q.removeConst();
1514 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1515 }
1516
1517 if (I != Bindings.size())
1518 return DiagnoseBadNumberOfBindings();
1519
1520 return false;
1521}
1522
1524 QualType DecompType = DD->getType();
1525
1526 // If the type of the decomposition is dependent, then so is the type of
1527 // each binding.
1528 if (DecompType->isDependentType()) {
1529 for (auto *B : DD->bindings())
1530 B->setType(Context.DependentTy);
1531 return;
1532 }
1533
1534 DecompType = DecompType.getNonReferenceType();
1536
1537 // C++1z [dcl.decomp]/2:
1538 // If E is an array type [...]
1539 // As an extension, we also support decomposition of built-in complex and
1540 // vector types.
1541 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1542 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1543 DD->setInvalidDecl();
1544 return;
1545 }
1546 if (auto *VT = DecompType->getAs<VectorType>()) {
1547 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1548 DD->setInvalidDecl();
1549 return;
1550 }
1551 if (auto *CT = DecompType->getAs<ComplexType>()) {
1552 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1553 DD->setInvalidDecl();
1554 return;
1555 }
1556
1557 // C++1z [dcl.decomp]/3:
1558 // if the expression std::tuple_size<E>::value is a well-formed integral
1559 // constant expression, [...]
1560 llvm::APSInt TupleSize(32);
1561 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1562 case IsTupleLike::Error:
1563 DD->setInvalidDecl();
1564 return;
1565
1566 case IsTupleLike::TupleLike:
1567 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1568 DD->setInvalidDecl();
1569 return;
1570
1571 case IsTupleLike::NotTupleLike:
1572 break;
1573 }
1574
1575 // C++1z [dcl.dcl]/8:
1576 // [E shall be of array or non-union class type]
1577 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1578 if (!RD || RD->isUnion()) {
1579 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1580 << DD << !RD << DecompType;
1581 DD->setInvalidDecl();
1582 return;
1583 }
1584
1585 // C++1z [dcl.decomp]/4:
1586 // all of E's non-static data members shall be [...] direct members of
1587 // E or of the same unambiguous public base class of E, ...
1588 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1589 DD->setInvalidDecl();
1590}
1591
1593 // Shortcut if exceptions are disabled.
1594 if (!getLangOpts().CXXExceptions)
1595 return;
1596
1597 assert(Context.hasSameType(New->getType(), Old->getType()) &&
1598 "Should only be called if types are otherwise the same.");
1599
1600 QualType NewType = New->getType();
1601 QualType OldType = Old->getType();
1602
1603 // We're only interested in pointers and references to functions, as well
1604 // as pointers to member functions.
1605 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1606 NewType = R->getPointeeType();
1607 OldType = OldType->castAs<ReferenceType>()->getPointeeType();
1608 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1609 NewType = P->getPointeeType();
1610 OldType = OldType->castAs<PointerType>()->getPointeeType();
1611 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1612 NewType = M->getPointeeType();
1613 OldType = OldType->castAs<MemberPointerType>()->getPointeeType();
1614 }
1615
1616 if (!NewType->isFunctionProtoType())
1617 return;
1618
1619 // There's lots of special cases for functions. For function pointers, system
1620 // libraries are hopefully not as broken so that we don't need these
1621 // workarounds.
1623 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1624 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1625 New->setInvalidDecl();
1626 }
1627}
1628
1629/// CheckCXXDefaultArguments - Verify that the default arguments for a
1630/// function declaration are well-formed according to C++
1631/// [dcl.fct.default].
1633 // This checking doesn't make sense for explicit specializations; their
1634 // default arguments are determined by the declaration we're specializing,
1635 // not by FD.
1637 return;
1638 if (auto *FTD = FD->getDescribedFunctionTemplate())
1639 if (FTD->isMemberSpecialization())
1640 return;
1641
1642 unsigned NumParams = FD->getNumParams();
1643 unsigned ParamIdx = 0;
1644
1645 // Find first parameter with a default argument
1646 for (; ParamIdx < NumParams; ++ParamIdx) {
1647 ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1648 if (Param->hasDefaultArg())
1649 break;
1650 }
1651
1652 // C++20 [dcl.fct.default]p4:
1653 // In a given function declaration, each parameter subsequent to a parameter
1654 // with a default argument shall have a default argument supplied in this or
1655 // a previous declaration, unless the parameter was expanded from a
1656 // parameter pack, or shall be a function parameter pack.
1657 for (++ParamIdx; ParamIdx < NumParams; ++ParamIdx) {
1658 ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1659 if (Param->hasDefaultArg() || Param->isParameterPack() ||
1662 continue;
1663 if (Param->isInvalidDecl())
1664 /* We already complained about this parameter. */;
1665 else if (Param->getIdentifier())
1666 Diag(Param->getLocation(), diag::err_param_default_argument_missing_name)
1667 << Param->getIdentifier();
1668 else
1669 Diag(Param->getLocation(), diag::err_param_default_argument_missing);
1670 }
1671}
1672
1673/// Check that the given type is a literal type. Issue a diagnostic if not,
1674/// if Kind is Diagnose.
1675/// \return \c true if a problem has been found (and optionally diagnosed).
1676template <typename... Ts>
1678 SourceLocation Loc, QualType T, unsigned DiagID,
1679 Ts &&...DiagArgs) {
1680 if (T->isDependentType())
1681 return false;
1682
1683 switch (Kind) {
1685 return SemaRef.RequireLiteralType(Loc, T, DiagID,
1686 std::forward<Ts>(DiagArgs)...);
1687
1689 return !T->isLiteralType(SemaRef.Context);
1690 }
1691
1692 llvm_unreachable("unknown CheckConstexprKind");
1693}
1694
1695/// Determine whether a destructor cannot be constexpr due to
1697 const CXXDestructorDecl *DD,
1699 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1700 "this check is obsolete for C++23");
1701 auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) {
1702 const CXXRecordDecl *RD =
1704 if (!RD || RD->hasConstexprDestructor())
1705 return true;
1706
1708 SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject)
1709 << static_cast<int>(DD->getConstexprKind()) << !FD
1710 << (FD ? FD->getDeclName() : DeclarationName()) << T;
1711 SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject)
1712 << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T;
1713 }
1714 return false;
1715 };
1716
1717 const CXXRecordDecl *RD = DD->getParent();
1718 for (const CXXBaseSpecifier &B : RD->bases())
1719 if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr))
1720 return false;
1721 for (const FieldDecl *FD : RD->fields())
1722 if (!Check(FD->getLocation(), FD->getType(), FD))
1723 return false;
1724 return true;
1725}
1726
1727/// Check whether a function's parameter types are all literal types. If so,
1728/// return true. If not, produce a suitable diagnostic and return false.
1730 const FunctionDecl *FD,
1732 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1733 "this check is obsolete for C++23");
1734 unsigned ArgIndex = 0;
1735 const auto *FT = FD->getType()->castAs<FunctionProtoType>();
1736 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1737 e = FT->param_type_end();
1738 i != e; ++i, ++ArgIndex) {
1739 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1740 assert(PD && "null in a parameter list");
1741 SourceLocation ParamLoc = PD->getLocation();
1742 if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i,
1743 diag::err_constexpr_non_literal_param, ArgIndex + 1,
1744 PD->getSourceRange(), isa<CXXConstructorDecl>(FD),
1745 FD->isConsteval()))
1746 return false;
1747 }
1748 return true;
1749}
1750
1751/// Check whether a function's return type is a literal type. If so, return
1752/// true. If not, produce a suitable diagnostic and return false.
1755 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1756 "this check is obsolete for C++23");
1757 if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(),
1758 diag::err_constexpr_non_literal_return,
1759 FD->isConsteval()))
1760 return false;
1761 return true;
1762}
1763
1764/// Get diagnostic %select index for tag kind for
1765/// record diagnostic message.
1766/// WARNING: Indexes apply to particular diagnostics only!
1767///
1768/// \returns diagnostic %select index.
1770 switch (Tag) {
1772 return 0;
1774 return 1;
1775 case TagTypeKind::Class:
1776 return 2;
1777 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1778 }
1779}
1780
1781static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
1782 Stmt *Body,
1784static bool CheckConstexprMissingReturn(Sema &SemaRef, const FunctionDecl *Dcl);
1785
1787 CheckConstexprKind Kind) {
1788 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1789 if (MD && MD->isInstance()) {
1790 // C++11 [dcl.constexpr]p4:
1791 // The definition of a constexpr constructor shall satisfy the following
1792 // constraints:
1793 // - the class shall not have any virtual base classes;
1794 //
1795 // FIXME: This only applies to constructors and destructors, not arbitrary
1796 // member functions.
1797 const CXXRecordDecl *RD = MD->getParent();
1798 if (RD->getNumVBases()) {
1800 return false;
1801
1802 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1803 << isa<CXXConstructorDecl>(NewFD)
1805 for (const auto &I : RD->vbases())
1806 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1807 << I.getSourceRange();
1808 return false;
1809 }
1810 }
1811
1812 if (!isa<CXXConstructorDecl>(NewFD)) {
1813 // C++11 [dcl.constexpr]p3:
1814 // The definition of a constexpr function shall satisfy the following
1815 // constraints:
1816 // - it shall not be virtual; (removed in C++20)
1817 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1818 if (Method && Method->isVirtual()) {
1819 if (getLangOpts().CPlusPlus20) {
1820 if (Kind == CheckConstexprKind::Diagnose)
1821 Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
1822 } else {
1824 return false;
1825
1826 Method = Method->getCanonicalDecl();
1827 Diag(Method->getLocation(), diag::err_constexpr_virtual);
1828
1829 // If it's not obvious why this function is virtual, find an overridden
1830 // function which uses the 'virtual' keyword.
1831 const CXXMethodDecl *WrittenVirtual = Method;
1832 while (!WrittenVirtual->isVirtualAsWritten())
1833 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1834 if (WrittenVirtual != Method)
1835 Diag(WrittenVirtual->getLocation(),
1836 diag::note_overridden_virtual_function);
1837 return false;
1838 }
1839 }
1840
1841 // - its return type shall be a literal type; (removed in C++23)
1842 if (!getLangOpts().CPlusPlus23 &&
1843 !CheckConstexprReturnType(*this, NewFD, Kind))
1844 return false;
1845 }
1846
1847 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) {
1848 // A destructor can be constexpr only if the defaulted destructor could be;
1849 // we don't need to check the members and bases if we already know they all
1850 // have constexpr destructors. (removed in C++23)
1851 if (!getLangOpts().CPlusPlus23 &&
1852 !Dtor->getParent()->defaultedDestructorIsConstexpr()) {
1854 return false;
1855 if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind))
1856 return false;
1857 }
1858 }
1859
1860 // - each of its parameter types shall be a literal type; (removed in C++23)
1861 if (!getLangOpts().CPlusPlus23 &&
1862 !CheckConstexprParameterTypes(*this, NewFD, Kind))
1863 return false;
1864
1865 Stmt *Body = NewFD->getBody();
1866 assert(Body &&
1867 "CheckConstexprFunctionDefinition called on function with no body");
1868 return CheckConstexprFunctionBody(*this, NewFD, Body, Kind);
1869}
1870
1871/// Check the given declaration statement is legal within a constexpr function
1872/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1873///
1874/// \return true if the body is OK (maybe only as an extension), false if we
1875/// have diagnosed a problem.
1877 DeclStmt *DS, SourceLocation &Cxx1yLoc,
1879 // C++11 [dcl.constexpr]p3 and p4:
1880 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
1881 // contain only
1882 for (const auto *DclIt : DS->decls()) {
1883 switch (DclIt->getKind()) {
1884 case Decl::StaticAssert:
1885 case Decl::Using:
1886 case Decl::UsingShadow:
1887 case Decl::UsingDirective:
1888 case Decl::UnresolvedUsingTypename:
1889 case Decl::UnresolvedUsingValue:
1890 case Decl::UsingEnum:
1891 // - static_assert-declarations
1892 // - using-declarations,
1893 // - using-directives,
1894 // - using-enum-declaration
1895 continue;
1896
1897 case Decl::Typedef:
1898 case Decl::TypeAlias: {
1899 // - typedef declarations and alias-declarations that do not define
1900 // classes or enumerations,
1901 const auto *TN = cast<TypedefNameDecl>(DclIt);
1902 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1903 // Don't allow variably-modified types in constexpr functions.
1905 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1906 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1907 << TL.getSourceRange() << TL.getType()
1908 << isa<CXXConstructorDecl>(Dcl);
1909 }
1910 return false;
1911 }
1912 continue;
1913 }
1914
1915 case Decl::Enum:
1916 case Decl::CXXRecord:
1917 // C++1y allows types to be defined, not just declared.
1918 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) {
1920 SemaRef.Diag(DS->getBeginLoc(),
1921 SemaRef.getLangOpts().CPlusPlus14
1922 ? diag::warn_cxx11_compat_constexpr_type_definition
1923 : diag::ext_constexpr_type_definition)
1924 << isa<CXXConstructorDecl>(Dcl);
1925 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1926 return false;
1927 }
1928 }
1929 continue;
1930
1931 case Decl::EnumConstant:
1932 case Decl::IndirectField:
1933 case Decl::ParmVar:
1934 // These can only appear with other declarations which are banned in
1935 // C++11 and permitted in C++1y, so ignore them.
1936 continue;
1937
1938 case Decl::Var:
1939 case Decl::Decomposition: {
1940 // C++1y [dcl.constexpr]p3 allows anything except:
1941 // a definition of a variable of non-literal type or of static or
1942 // thread storage duration or [before C++2a] for which no
1943 // initialization is performed.
1944 const auto *VD = cast<VarDecl>(DclIt);
1945 if (VD->isThisDeclarationADefinition()) {
1946 if (VD->isStaticLocal()) {
1948 SemaRef.Diag(VD->getLocation(),
1949 SemaRef.getLangOpts().CPlusPlus23
1950 ? diag::warn_cxx20_compat_constexpr_var
1951 : diag::ext_constexpr_static_var)
1952 << isa<CXXConstructorDecl>(Dcl)
1953 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1954 } else if (!SemaRef.getLangOpts().CPlusPlus23) {
1955 return false;
1956 }
1957 }
1958 if (SemaRef.LangOpts.CPlusPlus23) {
1959 CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(),
1960 diag::warn_cxx20_compat_constexpr_var,
1961 isa<CXXConstructorDecl>(Dcl),
1962 /*variable of non-literal type*/ 2);
1963 } else if (CheckLiteralType(
1964 SemaRef, Kind, VD->getLocation(), VD->getType(),
1965 diag::err_constexpr_local_var_non_literal_type,
1966 isa<CXXConstructorDecl>(Dcl))) {
1967 return false;
1968 }
1969 if (!VD->getType()->isDependentType() &&
1970 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1972 SemaRef.Diag(
1973 VD->getLocation(),
1974 SemaRef.getLangOpts().CPlusPlus20
1975 ? diag::warn_cxx17_compat_constexpr_local_var_no_init
1976 : diag::ext_constexpr_local_var_no_init)
1977 << isa<CXXConstructorDecl>(Dcl);
1978 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
1979 return false;
1980 }
1981 continue;
1982 }
1983 }
1985 SemaRef.Diag(VD->getLocation(),
1986 SemaRef.getLangOpts().CPlusPlus14
1987 ? diag::warn_cxx11_compat_constexpr_local_var
1988 : diag::ext_constexpr_local_var)
1989 << isa<CXXConstructorDecl>(Dcl);
1990 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1991 return false;
1992 }
1993 continue;
1994 }
1995
1996 case Decl::NamespaceAlias:
1997 case Decl::Function:
1998 // These are disallowed in C++11 and permitted in C++1y. Allow them
1999 // everywhere as an extension.
2000 if (!Cxx1yLoc.isValid())
2001 Cxx1yLoc = DS->getBeginLoc();
2002 continue;
2003
2004 default:
2006 SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2007 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2008 }
2009 return false;
2010 }
2011 }
2012
2013 return true;
2014}
2015
2016/// Check that the given field is initialized within a constexpr constructor.
2017///
2018/// \param Dcl The constexpr constructor being checked.
2019/// \param Field The field being checked. This may be a member of an anonymous
2020/// struct or union nested within the class being checked.
2021/// \param Inits All declarations, including anonymous struct/union members and
2022/// indirect members, for which any initialization was provided.
2023/// \param Diagnosed Whether we've emitted the error message yet. Used to attach
2024/// multiple notes for different members to the same error.
2025/// \param Kind Whether we're diagnosing a constructor as written or determining
2026/// whether the formal requirements are satisfied.
2027/// \return \c false if we're checking for validity and the constructor does
2028/// not satisfy the requirements on a constexpr constructor.
2030 const FunctionDecl *Dcl,
2031 FieldDecl *Field,
2032 llvm::SmallSet<Decl*, 16> &Inits,
2033 bool &Diagnosed,
2035 // In C++20 onwards, there's nothing to check for validity.
2037 SemaRef.getLangOpts().CPlusPlus20)
2038 return true;
2039
2040 if (Field->isInvalidDecl())
2041 return true;
2042
2043 if (Field->isUnnamedBitField())
2044 return true;
2045
2046 // Anonymous unions with no variant members and empty anonymous structs do not
2047 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
2048 // indirect fields don't need initializing.
2049 if (Field->isAnonymousStructOrUnion() &&
2050 (Field->getType()->isUnionType()
2051 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
2052 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
2053 return true;
2054
2055 if (!Inits.count(Field)) {
2057 if (!Diagnosed) {
2058 SemaRef.Diag(Dcl->getLocation(),
2059 SemaRef.getLangOpts().CPlusPlus20
2060 ? diag::warn_cxx17_compat_constexpr_ctor_missing_init
2061 : diag::ext_constexpr_ctor_missing_init);
2062 Diagnosed = true;
2063 }
2064 SemaRef.Diag(Field->getLocation(),
2065 diag::note_constexpr_ctor_missing_init);
2066 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2067 return false;
2068 }
2069 } else if (Field->isAnonymousStructOrUnion()) {
2070 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
2071 for (auto *I : RD->fields())
2072 // If an anonymous union contains an anonymous struct of which any member
2073 // is initialized, all members must be initialized.
2074 if (!RD->isUnion() || Inits.count(I))
2075 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2076 Kind))
2077 return false;
2078 }
2079 return true;
2080}
2081
2082/// Check the provided statement is allowed in a constexpr function
2083/// definition.
2084static bool
2087 SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
2088 SourceLocation &Cxx2bLoc,
2090 // - its function-body shall be [...] a compound-statement that contains only
2091 switch (S->getStmtClass()) {
2092 case Stmt::NullStmtClass:
2093 // - null statements,
2094 return true;
2095
2096 case Stmt::DeclStmtClass:
2097 // - static_assert-declarations
2098 // - using-declarations,
2099 // - using-directives,
2100 // - typedef declarations and alias-declarations that do not define
2101 // classes or enumerations,
2102 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind))
2103 return false;
2104 return true;
2105
2106 case Stmt::ReturnStmtClass:
2107 // - and exactly one return statement;
2108 if (isa<CXXConstructorDecl>(Dcl)) {
2109 // C++1y allows return statements in constexpr constructors.
2110 if (!Cxx1yLoc.isValid())
2111 Cxx1yLoc = S->getBeginLoc();
2112 return true;
2113 }
2114
2115 ReturnStmts.push_back(S->getBeginLoc());
2116 return true;
2117
2118 case Stmt::AttributedStmtClass:
2119 // Attributes on a statement don't affect its formal kind and hence don't
2120 // affect its validity in a constexpr function.
2122 SemaRef, Dcl, cast<AttributedStmt>(S)->getSubStmt(), ReturnStmts,
2123 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind);
2124
2125 case Stmt::CompoundStmtClass: {
2126 // C++1y allows compound-statements.
2127 if (!Cxx1yLoc.isValid())
2128 Cxx1yLoc = S->getBeginLoc();
2129
2130 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
2131 for (auto *BodyIt : CompStmt->body()) {
2132 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
2133 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2134 return false;
2135 }
2136 return true;
2137 }
2138
2139 case Stmt::IfStmtClass: {
2140 // C++1y allows if-statements.
2141 if (!Cxx1yLoc.isValid())
2142 Cxx1yLoc = S->getBeginLoc();
2143
2144 IfStmt *If = cast<IfStmt>(S);
2145 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
2146 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2147 return false;
2148 if (If->getElse() &&
2149 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
2150 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2151 return false;
2152 return true;
2153 }
2154
2155 case Stmt::WhileStmtClass:
2156 case Stmt::DoStmtClass:
2157 case Stmt::ForStmtClass:
2158 case Stmt::CXXForRangeStmtClass:
2159 case Stmt::ContinueStmtClass:
2160 // C++1y allows all of these. We don't allow them as extensions in C++11,
2161 // because they don't make sense without variable mutation.
2162 if (!SemaRef.getLangOpts().CPlusPlus14)
2163 break;
2164 if (!Cxx1yLoc.isValid())
2165 Cxx1yLoc = S->getBeginLoc();
2166 for (Stmt *SubStmt : S->children()) {
2167 if (SubStmt &&
2168 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2169 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2170 return false;
2171 }
2172 return true;
2173
2174 case Stmt::SwitchStmtClass:
2175 case Stmt::CaseStmtClass:
2176 case Stmt::DefaultStmtClass:
2177 case Stmt::BreakStmtClass:
2178 // C++1y allows switch-statements, and since they don't need variable
2179 // mutation, we can reasonably allow them in C++11 as an extension.
2180 if (!Cxx1yLoc.isValid())
2181 Cxx1yLoc = S->getBeginLoc();
2182 for (Stmt *SubStmt : S->children()) {
2183 if (SubStmt &&
2184 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2185 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2186 return false;
2187 }
2188 return true;
2189
2190 case Stmt::LabelStmtClass:
2191 case Stmt::GotoStmtClass:
2192 if (Cxx2bLoc.isInvalid())
2193 Cxx2bLoc = S->getBeginLoc();
2194 for (Stmt *SubStmt : S->children()) {
2195 if (SubStmt &&
2196 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2197 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2198 return false;
2199 }
2200 return true;
2201
2202 case Stmt::GCCAsmStmtClass:
2203 case Stmt::MSAsmStmtClass:
2204 // C++2a allows inline assembly statements.
2205 case Stmt::CXXTryStmtClass:
2206 if (Cxx2aLoc.isInvalid())
2207 Cxx2aLoc = S->getBeginLoc();
2208 for (Stmt *SubStmt : S->children()) {
2209 if (SubStmt &&
2210 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2211 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2212 return false;
2213 }
2214 return true;
2215
2216 case Stmt::CXXCatchStmtClass:
2217 // Do not bother checking the language mode (already covered by the
2218 // try block check).
2220 SemaRef, Dcl, cast<CXXCatchStmt>(S)->getHandlerBlock(), ReturnStmts,
2221 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2222 return false;
2223 return true;
2224
2225 default:
2226 if (!isa<Expr>(S))
2227 break;
2228
2229 // C++1y allows expression-statements.
2230 if (!Cxx1yLoc.isValid())
2231 Cxx1yLoc = S->getBeginLoc();
2232 return true;
2233 }
2234
2236 SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2237 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2238 }
2239 return false;
2240}
2241
2242/// Check the body for the given constexpr function declaration only contains
2243/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
2244///
2245/// \return true if the body is OK, false if we have found or diagnosed a
2246/// problem.
2248 Stmt *Body,
2251
2252 if (isa<CXXTryStmt>(Body)) {
2253 // C++11 [dcl.constexpr]p3:
2254 // The definition of a constexpr function shall satisfy the following
2255 // constraints: [...]
2256 // - its function-body shall be = delete, = default, or a
2257 // compound-statement
2258 //
2259 // C++11 [dcl.constexpr]p4:
2260 // In the definition of a constexpr constructor, [...]
2261 // - its function-body shall not be a function-try-block;
2262 //
2263 // This restriction is lifted in C++2a, as long as inner statements also
2264 // apply the general constexpr rules.
2265 switch (Kind) {
2267 if (!SemaRef.getLangOpts().CPlusPlus20)
2268 return false;
2269 break;
2270
2272 SemaRef.Diag(Body->getBeginLoc(),
2273 !SemaRef.getLangOpts().CPlusPlus20
2274 ? diag::ext_constexpr_function_try_block_cxx20
2275 : diag::warn_cxx17_compat_constexpr_function_try_block)
2276 << isa<CXXConstructorDecl>(Dcl);
2277 break;
2278 }
2279 }
2280
2281 // - its function-body shall be [...] a compound-statement that contains only
2282 // [... list of cases ...]
2283 //
2284 // Note that walking the children here is enough to properly check for
2285 // CompoundStmt and CXXTryStmt body.
2286 SourceLocation Cxx1yLoc, Cxx2aLoc, Cxx2bLoc;
2287 for (Stmt *SubStmt : Body->children()) {
2288 if (SubStmt &&
2289 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2290 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2291 return false;
2292 }
2293
2295 // If this is only valid as an extension, report that we don't satisfy the
2296 // constraints of the current language.
2297 if ((Cxx2bLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus23) ||
2298 (Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) ||
2299 (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
2300 return false;
2301 } else if (Cxx2bLoc.isValid()) {
2302 SemaRef.Diag(Cxx2bLoc,
2303 SemaRef.getLangOpts().CPlusPlus23
2304 ? diag::warn_cxx20_compat_constexpr_body_invalid_stmt
2305 : diag::ext_constexpr_body_invalid_stmt_cxx23)
2306 << isa<CXXConstructorDecl>(Dcl);
2307 } else if (Cxx2aLoc.isValid()) {
2308 SemaRef.Diag(Cxx2aLoc,
2309 SemaRef.getLangOpts().CPlusPlus20
2310 ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
2311 : diag::ext_constexpr_body_invalid_stmt_cxx20)
2312 << isa<CXXConstructorDecl>(Dcl);
2313 } else if (Cxx1yLoc.isValid()) {
2314 SemaRef.Diag(Cxx1yLoc,
2315 SemaRef.getLangOpts().CPlusPlus14
2316 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
2317 : diag::ext_constexpr_body_invalid_stmt)
2318 << isa<CXXConstructorDecl>(Dcl);
2319 }
2320
2321 if (const CXXConstructorDecl *Constructor
2322 = dyn_cast<CXXConstructorDecl>(Dcl)) {
2323 const CXXRecordDecl *RD = Constructor->getParent();
2324 // DR1359:
2325 // - every non-variant non-static data member and base class sub-object
2326 // shall be initialized;
2327 // DR1460:
2328 // - if the class is a union having variant members, exactly one of them
2329 // shall be initialized;
2330 if (RD->isUnion()) {
2331 if (Constructor->getNumCtorInitializers() == 0 &&
2332 RD->hasVariantMembers()) {
2334 SemaRef.Diag(
2335 Dcl->getLocation(),
2336 SemaRef.getLangOpts().CPlusPlus20
2337 ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init
2338 : diag::ext_constexpr_union_ctor_no_init);
2339 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2340 return false;
2341 }
2342 }
2343 } else if (!Constructor->isDependentContext() &&
2344 !Constructor->isDelegatingConstructor()) {
2345 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
2346
2347 // Skip detailed checking if we have enough initializers, and we would
2348 // allow at most one initializer per member.
2349 bool AnyAnonStructUnionMembers = false;
2350 unsigned Fields = 0;
2352 E = RD->field_end(); I != E; ++I, ++Fields) {
2353 if (I->isAnonymousStructOrUnion()) {
2354 AnyAnonStructUnionMembers = true;
2355 break;
2356 }
2357 }
2358 // DR1460:
2359 // - if the class is a union-like class, but is not a union, for each of
2360 // its anonymous union members having variant members, exactly one of
2361 // them shall be initialized;
2362 if (AnyAnonStructUnionMembers ||
2363 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2364 // Check initialization of non-static data members. Base classes are
2365 // always initialized so do not need to be checked. Dependent bases
2366 // might not have initializers in the member initializer list.
2367 llvm::SmallSet<Decl*, 16> Inits;
2368 for (const auto *I: Constructor->inits()) {
2369 if (FieldDecl *FD = I->getMember())
2370 Inits.insert(FD);
2371 else if (IndirectFieldDecl *ID = I->getIndirectMember())
2372 Inits.insert(ID->chain_begin(), ID->chain_end());
2373 }
2374
2375 bool Diagnosed = false;
2376 for (auto *I : RD->fields())
2377 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2378 Kind))
2379 return false;
2380 }
2381 }
2382 } else {
2383 if (ReturnStmts.empty()) {
2384 switch (Kind) {
2387 return false;
2388 break;
2389
2391 // The formal requirements don't include this rule in C++14, even
2392 // though the "must be able to produce a constant expression" rules
2393 // still imply it in some cases.
2394 if (!SemaRef.getLangOpts().CPlusPlus14)
2395 return false;
2396 break;
2397 }
2398 } else if (ReturnStmts.size() > 1) {
2399 switch (Kind) {
2401 SemaRef.Diag(
2402 ReturnStmts.back(),
2403 SemaRef.getLangOpts().CPlusPlus14
2404 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2405 : diag::ext_constexpr_body_multiple_return);
2406 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2407 SemaRef.Diag(ReturnStmts[I],
2408 diag::note_constexpr_body_previous_return);
2409 break;
2410
2412 if (!SemaRef.getLangOpts().CPlusPlus14)
2413 return false;
2414 break;
2415 }
2416 }
2417 }
2418
2419 // C++11 [dcl.constexpr]p5:
2420 // if no function argument values exist such that the function invocation
2421 // substitution would produce a constant expression, the program is
2422 // ill-formed; no diagnostic required.
2423 // C++11 [dcl.constexpr]p3:
2424 // - every constructor call and implicit conversion used in initializing the
2425 // return value shall be one of those allowed in a constant expression.
2426 // C++11 [dcl.constexpr]p4:
2427 // - every constructor involved in initializing non-static data members and
2428 // base class sub-objects shall be a constexpr constructor.
2429 //
2430 // Note that this rule is distinct from the "requirements for a constexpr
2431 // function", so is not checked in CheckValid mode. Because the check for
2432 // constexpr potential is expensive, skip the check if the diagnostic is
2433 // disabled, the function is declared in a system header, or we're in C++23
2434 // or later mode (see https://wg21.link/P2448).
2435 bool SkipCheck =
2436 !SemaRef.getLangOpts().CheckConstexprFunctionBodies ||
2439 diag::ext_constexpr_function_never_constant_expr, Dcl->getLocation());
2441 if (Kind == Sema::CheckConstexprKind::Diagnose && !SkipCheck &&
2443 SemaRef.Diag(Dcl->getLocation(),
2444 diag::ext_constexpr_function_never_constant_expr)
2445 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval()
2446 << Dcl->getNameInfo().getSourceRange();
2447 for (size_t I = 0, N = Diags.size(); I != N; ++I)
2448 SemaRef.Diag(Diags[I].first, Diags[I].second);
2449 // Don't return false here: we allow this for compatibility in
2450 // system headers.
2451 }
2452
2453 return true;
2454}
2455
2457 const FunctionDecl *Dcl) {
2458 bool IsVoidOrDependentType = Dcl->getReturnType()->isVoidType() ||
2460 // Skip emitting a missing return error diagnostic for non-void functions
2461 // since C++23 no longer mandates constexpr functions to yield constant
2462 // expressions.
2463 if (SemaRef.getLangOpts().CPlusPlus23 && !IsVoidOrDependentType)
2464 return true;
2465
2466 // C++14 doesn't require constexpr functions to contain a 'return'
2467 // statement. We still do, unless the return type might be void, because
2468 // otherwise if there's no return statement, the function cannot
2469 // be used in a core constant expression.
2470 bool OK = SemaRef.getLangOpts().CPlusPlus14 && IsVoidOrDependentType;
2471 SemaRef.Diag(Dcl->getLocation(),
2472 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2473 : diag::err_constexpr_body_no_return)
2474 << Dcl->isConsteval();
2475 return OK;
2476}
2477
2479 FunctionDecl *FD, const sema::FunctionScopeInfo *FSI) {
2481 return true;
2485 auto it = UndefinedButUsed.find(FD->getCanonicalDecl());
2486 if (it != UndefinedButUsed.end()) {
2487 Diag(it->second, diag::err_immediate_function_used_before_definition)
2488 << it->first;
2489 Diag(FD->getLocation(), diag::note_defined_here) << FD;
2490 if (FD->isImmediateFunction() && !FD->isConsteval())
2492 return false;
2493 }
2494 }
2495 return true;
2496}
2497
2499 assert(FD->isImmediateEscalating() && !FD->isConsteval() &&
2500 "expected an immediate function");
2501 assert(FD->hasBody() && "expected the function to have a body");
2502 struct ImmediateEscalatingExpressionsVisitor
2503 : public RecursiveASTVisitor<ImmediateEscalatingExpressionsVisitor> {
2504
2506 Sema &SemaRef;
2507
2508 const FunctionDecl *ImmediateFn;
2509 bool ImmediateFnIsConstructor;
2510 CXXConstructorDecl *CurrentConstructor = nullptr;
2511 CXXCtorInitializer *CurrentInit = nullptr;
2512
2513 ImmediateEscalatingExpressionsVisitor(Sema &SemaRef, FunctionDecl *FD)
2514 : SemaRef(SemaRef), ImmediateFn(FD),
2515 ImmediateFnIsConstructor(isa<CXXConstructorDecl>(FD)) {}
2516
2517 bool shouldVisitImplicitCode() const { return true; }
2518 bool shouldVisitLambdaBody() const { return false; }
2519
2520 void Diag(const Expr *E, const FunctionDecl *Fn, bool IsCall) {
2523 if (CurrentConstructor && CurrentInit) {
2524 Loc = CurrentConstructor->getLocation();
2525 Range = CurrentInit->isWritten() ? CurrentInit->getSourceRange()
2526 : SourceRange();
2527 }
2528
2529 FieldDecl* InitializedField = CurrentInit ? CurrentInit->getAnyMember() : nullptr;
2530
2531 SemaRef.Diag(Loc, diag::note_immediate_function_reason)
2532 << ImmediateFn << Fn << Fn->isConsteval() << IsCall
2533 << isa<CXXConstructorDecl>(Fn) << ImmediateFnIsConstructor
2534 << (InitializedField != nullptr)
2535 << (CurrentInit && !CurrentInit->isWritten())
2536 << InitializedField << Range;
2537 }
2538 bool TraverseCallExpr(CallExpr *E) {
2539 if (const auto *DR =
2540 dyn_cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit());
2541 DR && DR->isImmediateEscalating()) {
2542 Diag(E, E->getDirectCallee(), /*IsCall=*/true);
2543 return false;
2544 }
2545
2546 for (Expr *A : E->arguments())
2547 if (!getDerived().TraverseStmt(A))
2548 return false;
2549
2550 return true;
2551 }
2552
2553 bool VisitDeclRefExpr(DeclRefExpr *E) {
2554 if (const auto *ReferencedFn = dyn_cast<FunctionDecl>(E->getDecl());
2555 ReferencedFn && E->isImmediateEscalating()) {
2556 Diag(E, ReferencedFn, /*IsCall=*/false);
2557 return false;
2558 }
2559
2560 return true;
2561 }
2562
2563 bool VisitCXXConstructExpr(CXXConstructExpr *E) {
2564 CXXConstructorDecl *D = E->getConstructor();
2565 if (E->isImmediateEscalating()) {
2566 Diag(E, D, /*IsCall=*/true);
2567 return false;
2568 }
2569 return true;
2570 }
2571
2572 bool TraverseConstructorInitializer(CXXCtorInitializer *Init) {
2573 llvm::SaveAndRestore RAII(CurrentInit, Init);
2574 return Base::TraverseConstructorInitializer(Init);
2575 }
2576
2577 bool TraverseCXXConstructorDecl(CXXConstructorDecl *Ctr) {
2578 llvm::SaveAndRestore RAII(CurrentConstructor, Ctr);
2579 return Base::TraverseCXXConstructorDecl(Ctr);
2580 }
2581
2582 bool TraverseType(QualType T) { return true; }
2583 bool VisitBlockExpr(BlockExpr *T) { return true; }
2584
2585 } Visitor(*this, FD);
2586 Visitor.TraverseDecl(FD);
2587}
2588
2590 assert(getLangOpts().CPlusPlus && "No class names in C!");
2591
2592 if (SS && SS->isInvalid())
2593 return nullptr;
2594
2595 if (SS && SS->isNotEmpty()) {
2596 DeclContext *DC = computeDeclContext(*SS, true);
2597 return dyn_cast_or_null<CXXRecordDecl>(DC);
2598 }
2599
2600 return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2601}
2602
2604 const CXXScopeSpec *SS) {
2605 CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2606 return CurDecl && &II == CurDecl->getIdentifier();
2607}
2608
2610 assert(getLangOpts().CPlusPlus && "No class names in C!");
2611
2612 if (!getLangOpts().SpellChecking)
2613 return false;
2614
2615 CXXRecordDecl *CurDecl;
2616 if (SS && SS->isSet() && !SS->isInvalid()) {
2617 DeclContext *DC = computeDeclContext(*SS, true);
2618 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2619 } else
2620 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2621
2622 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2623 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2624 < II->getLength()) {
2625 II = CurDecl->getIdentifier();
2626 return true;
2627 }
2628
2629 return false;
2630}
2631
2633 SourceRange SpecifierRange,
2634 bool Virtual, AccessSpecifier Access,
2635 TypeSourceInfo *TInfo,
2636 SourceLocation EllipsisLoc) {
2637 QualType BaseType = TInfo->getType();
2638 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2639 if (BaseType->containsErrors()) {
2640 // Already emitted a diagnostic when parsing the error type.
2641 return nullptr;
2642 }
2643
2644 if (EllipsisLoc.isValid() && !BaseType->containsUnexpandedParameterPack()) {
2645 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2646 << TInfo->getTypeLoc().getSourceRange();
2647 EllipsisLoc = SourceLocation();
2648 }
2649
2650 auto *BaseDecl =
2651 dyn_cast_if_present<CXXRecordDecl>(computeDeclContext(BaseType));
2652 // C++ [class.derived.general]p2:
2653 // A class-or-decltype shall denote a (possibly cv-qualified) class type
2654 // that is not an incompletely defined class; any cv-qualifiers are
2655 // ignored.
2656 if (BaseDecl) {
2657 // C++ [class.union.general]p4:
2658 // [...] A union shall not be used as a base class.
2659 if (BaseDecl->isUnion()) {
2660 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2661 return nullptr;
2662 }
2663
2664 // For the MS ABI, propagate DLL attributes to base class templates.
2666 Context.getTargetInfo().getTriple().isPS()) {
2667 if (Attr *ClassAttr = getDLLAttr(Class)) {
2668 if (auto *BaseSpec =
2669 dyn_cast<ClassTemplateSpecializationDecl>(BaseDecl)) {
2670 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseSpec,
2671 BaseLoc);
2672 }
2673 }
2674 }
2675
2676 if (RequireCompleteType(BaseLoc, BaseType, diag::err_incomplete_base_class,
2677 SpecifierRange)) {
2678 Class->setInvalidDecl();
2679 return nullptr;
2680 }
2681
2682 BaseDecl = BaseDecl->getDefinition();
2683 assert(BaseDecl && "Base type is not incomplete, but has no definition");
2684
2685 // Microsoft docs say:
2686 // "If a base-class has a code_seg attribute, derived classes must have the
2687 // same attribute."
2688 const auto *BaseCSA = BaseDecl->getAttr<CodeSegAttr>();
2689 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2690 if ((DerivedCSA || BaseCSA) &&
2691 (!BaseCSA || !DerivedCSA ||
2692 BaseCSA->getName() != DerivedCSA->getName())) {
2693 Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2694 Diag(BaseDecl->getLocation(), diag::note_base_class_specified_here)
2695 << BaseDecl;
2696 return nullptr;
2697 }
2698
2699 // A class which contains a flexible array member is not suitable for use as
2700 // a base class:
2701 // - If the layout determines that a base comes before another base,
2702 // the flexible array member would index into the subsequent base.
2703 // - If the layout determines that base comes before the derived class,
2704 // the flexible array member would index into the derived class.
2705 if (BaseDecl->hasFlexibleArrayMember()) {
2706 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2707 << BaseDecl->getDeclName();
2708 return nullptr;
2709 }
2710
2711 // C++ [class]p3:
2712 // If a class is marked final and it appears as a base-type-specifier in
2713 // base-clause, the program is ill-formed.
2714 if (FinalAttr *FA = BaseDecl->getAttr<FinalAttr>()) {
2715 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2716 << BaseDecl->getDeclName() << FA->isSpelledAsSealed();
2717 Diag(BaseDecl->getLocation(), diag::note_entity_declared_at)
2718 << BaseDecl->getDeclName() << FA->getRange();
2719 return nullptr;
2720 }
2721
2722 // If the base class is invalid the derived class is as well.
2723 if (BaseDecl->isInvalidDecl())
2724 Class->setInvalidDecl();
2725 } else if (BaseType->isDependentType()) {
2726 // Make sure that we don't make an ill-formed AST where the type of the
2727 // Class is non-dependent and its attached base class specifier is an
2728 // dependent type, which violates invariants in many clang code paths (e.g.
2729 // constexpr evaluator). If this case happens (in errory-recovery mode), we
2730 // explicitly mark the Class decl invalid. The diagnostic was already
2731 // emitted.
2732 if (!Class->isDependentContext())
2733 Class->setInvalidDecl();
2734 } else {
2735 // The base class is some non-dependent non-class type.
2736 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2737 return nullptr;
2738 }
2739
2740 // In HLSL, unspecified class access is public rather than private.
2741 if (getLangOpts().HLSL && Class->getTagKind() == TagTypeKind::Class &&
2742 Access == AS_none)
2743 Access = AS_public;
2744
2745 // Create the base specifier.
2746 return new (Context) CXXBaseSpecifier(
2747 SpecifierRange, Virtual, Class->getTagKind() == TagTypeKind::Class,
2748 Access, TInfo, EllipsisLoc);
2749}
2750
2752 const ParsedAttributesView &Attributes,
2753 bool Virtual, AccessSpecifier Access,
2754 ParsedType basetype, SourceLocation BaseLoc,
2755 SourceLocation EllipsisLoc) {
2756 if (!classdecl)
2757 return true;
2758
2759 AdjustDeclIfTemplate(classdecl);
2760 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2761 if (!Class)
2762 return true;
2763
2764 // We haven't yet attached the base specifiers.
2765 Class->setIsParsingBaseSpecifiers();
2766
2767 // We do not support any C++11 attributes on base-specifiers yet.
2768 // Diagnose any attributes we see.
2769 for (const ParsedAttr &AL : Attributes) {
2770 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2771 continue;
2772 if (AL.getKind() == ParsedAttr::UnknownAttribute)
2773 Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored)
2774 << AL << AL.getRange();
2775 else
2776 Diag(AL.getLoc(), diag::err_base_specifier_attribute)
2777 << AL << AL.isRegularKeywordAttribute() << AL.getRange();
2778 }
2779
2780 TypeSourceInfo *TInfo = nullptr;
2781 GetTypeFromParser(basetype, &TInfo);
2782
2783 if (EllipsisLoc.isInvalid() &&
2784 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2786 return true;
2787
2788 // C++ [class.union.general]p4:
2789 // [...] A union shall not have base classes.
2790 if (Class->isUnion()) {
2791 Diag(Class->getLocation(), diag::err_base_clause_on_union)
2792 << SpecifierRange;
2793 return true;
2794 }
2795
2796 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2797 Virtual, Access, TInfo,
2798 EllipsisLoc))
2799 return BaseSpec;
2800
2801 Class->setInvalidDecl();
2802 return true;
2803}
2804
2805/// Use small set to collect indirect bases. As this is only used
2806/// locally, there's no need to abstract the small size parameter.
2808
2809/// Recursively add the bases of Type. Don't add Type itself.
2810static void
2812 const QualType &Type)
2813{
2814 // Even though the incoming type is a base, it might not be
2815 // a class -- it could be a template parm, for instance.
2816 if (auto Rec = Type->getAs<RecordType>()) {
2817 auto Decl = Rec->getAsCXXRecordDecl();
2818
2819 // Iterate over its bases.
2820 for (const auto &BaseSpec : Decl->bases()) {
2821 QualType Base = Context.getCanonicalType(BaseSpec.getType())
2823 if (Set.insert(Base).second)
2824 // If we've not already seen it, recurse.
2826 }
2827 }
2828}
2829
2832 if (Bases.empty())
2833 return false;
2834
2835 // Used to keep track of which base types we have already seen, so
2836 // that we can properly diagnose redundant direct base types. Note
2837 // that the key is always the unqualified canonical type of the base
2838 // class.
2839 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2840
2841 // Used to track indirect bases so we can see if a direct base is
2842 // ambiguous.
2843 IndirectBaseSet IndirectBaseTypes;
2844
2845 // Copy non-redundant base specifiers into permanent storage.
2846 unsigned NumGoodBases = 0;
2847 bool Invalid = false;
2848 for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2849 QualType NewBaseType
2850 = Context.getCanonicalType(Bases[idx]->getType());
2851 NewBaseType = NewBaseType.getLocalUnqualifiedType();
2852
2853 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2854 if (KnownBase) {
2855 // C++ [class.mi]p3:
2856 // A class shall not be specified as a direct base class of a
2857 // derived class more than once.
2858 Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2859 << KnownBase->getType() << Bases[idx]->getSourceRange();
2860
2861 // Delete the duplicate base class specifier; we're going to
2862 // overwrite its pointer later.
2863 Context.Deallocate(Bases[idx]);
2864
2865 Invalid = true;
2866 } else {
2867 // Okay, add this new base class.
2868 KnownBase = Bases[idx];
2869 Bases[NumGoodBases++] = Bases[idx];
2870
2871 if (NewBaseType->isDependentType())
2872 continue;
2873 // Note this base's direct & indirect bases, if there could be ambiguity.
2874 if (Bases.size() > 1)
2875 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2876
2877 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2878 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2879 if (Class->isInterface() &&
2880 (!RD->isInterfaceLike() ||
2881 KnownBase->getAccessSpecifier() != AS_public)) {
2882 // The Microsoft extension __interface does not permit bases that
2883 // are not themselves public interfaces.
2884 Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
2885 << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2886 << RD->getSourceRange();
2887 Invalid = true;
2888 }
2889 if (RD->hasAttr<WeakAttr>())
2890 Class->addAttr(WeakAttr::CreateImplicit(Context));
2891 }
2892 }
2893 }
2894
2895 // Attach the remaining base class specifiers to the derived class.
2896 Class->setBases(Bases.data(), NumGoodBases);
2897
2898 // Check that the only base classes that are duplicate are virtual.
2899 for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2900 // Check whether this direct base is inaccessible due to ambiguity.
2901 QualType BaseType = Bases[idx]->getType();
2902
2903 // Skip all dependent types in templates being used as base specifiers.
2904 // Checks below assume that the base specifier is a CXXRecord.
2905 if (BaseType->isDependentType())
2906 continue;
2907
2908 CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2910
2911 if (IndirectBaseTypes.count(CanonicalBase)) {
2912 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2913 /*DetectVirtual=*/true);
2914 bool found
2915 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2916 assert(found);
2917 (void)found;
2918
2919 if (Paths.isAmbiguous(CanonicalBase))
2920 Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
2921 << BaseType << getAmbiguousPathsDisplayString(Paths)
2922 << Bases[idx]->getSourceRange();
2923 else
2924 assert(Bases[idx]->isVirtual());
2925 }
2926
2927 // Delete the base class specifier, since its data has been copied
2928 // into the CXXRecordDecl.
2929 Context.Deallocate(Bases[idx]);
2930 }
2931
2932 return Invalid;
2933}
2934
2937 if (!ClassDecl || Bases.empty())
2938 return;
2939
2940 AdjustDeclIfTemplate(ClassDecl);
2941 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2942}
2943
2945 if (!getLangOpts().CPlusPlus)
2946 return false;
2947
2948 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2949 if (!DerivedRD)
2950 return false;
2951
2952 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2953 if (!BaseRD)
2954 return false;
2955
2956 // If either the base or the derived type is invalid, don't try to
2957 // check whether one is derived from the other.
2958 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2959 return false;
2960
2961 // FIXME: In a modules build, do we need the entire path to be visible for us
2962 // to be able to use the inheritance relationship?
2963 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2964 return false;
2965
2966 return DerivedRD->isDerivedFrom(BaseRD);
2967}
2968
2970 CXXBasePaths &Paths) {
2971 if (!getLangOpts().CPlusPlus)
2972 return false;
2973
2974 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2975 if (!DerivedRD)
2976 return false;
2977
2978 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2979 if (!BaseRD)
2980 return false;
2981
2982 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2983 return false;
2984
2985 return DerivedRD->isDerivedFrom(BaseRD, Paths);
2986}
2987
2989 CXXCastPath &BasePathArray) {
2990 // We first go backward and check if we have a virtual base.
2991 // FIXME: It would be better if CXXBasePath had the base specifier for
2992 // the nearest virtual base.
2993 unsigned Start = 0;
2994 for (unsigned I = Path.size(); I != 0; --I) {
2995 if (Path[I - 1].Base->isVirtual()) {
2996 Start = I - 1;
2997 break;
2998 }
2999 }
3000
3001 // Now add all bases.
3002 for (unsigned I = Start, E = Path.size(); I != E; ++I)
3003 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
3004}
3005
3006
3008 CXXCastPath &BasePathArray) {
3009 assert(BasePathArray.empty() && "Base path array must be empty!");
3010 assert(Paths.isRecordingPaths() && "Must record paths!");
3011 return ::BuildBasePathArray(Paths.front(), BasePathArray);
3012}
3013
3014bool
3016 unsigned InaccessibleBaseID,
3017 unsigned AmbiguousBaseConvID,
3019 DeclarationName Name,
3020 CXXCastPath *BasePath,
3021 bool IgnoreAccess) {
3022 // First, determine whether the path from Derived to Base is
3023 // ambiguous. This is slightly more expensive than checking whether
3024 // the Derived to Base conversion exists, because here we need to
3025 // explore multiple paths to determine if there is an ambiguity.
3026 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3027 /*DetectVirtual=*/false);
3028 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
3029 if (!DerivationOkay)
3030 return true;
3031
3032 const CXXBasePath *Path = nullptr;
3033 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
3034 Path = &Paths.front();
3035
3036 // For MSVC compatibility, check if Derived directly inherits from Base. Clang
3037 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
3038 // user to access such bases.
3039 if (!Path && getLangOpts().MSVCCompat) {
3040 for (const CXXBasePath &PossiblePath : Paths) {
3041 if (PossiblePath.size() == 1) {
3042 Path = &PossiblePath;
3043 if (AmbiguousBaseConvID)
3044 Diag(Loc, diag::ext_ms_ambiguous_direct_base)
3045 << Base << Derived << Range;
3046 break;
3047 }
3048 }
3049 }
3050
3051 if (Path) {
3052 if (!IgnoreAccess) {
3053 // Check that the base class can be accessed.
3054 switch (
3055 CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
3056 case AR_inaccessible:
3057 return true;
3058 case AR_accessible:
3059 case AR_dependent:
3060 case AR_delayed:
3061 break;
3062 }
3063 }
3064
3065 // Build a base path if necessary.
3066 if (BasePath)
3067 ::BuildBasePathArray(*Path, *BasePath);
3068 return false;
3069 }
3070
3071 if (AmbiguousBaseConvID) {
3072 // We know that the derived-to-base conversion is ambiguous, and
3073 // we're going to produce a diagnostic. Perform the derived-to-base
3074 // search just one more time to compute all of the possible paths so
3075 // that we can print them out. This is more expensive than any of
3076 // the previous derived-to-base checks we've done, but at this point
3077 // performance isn't as much of an issue.
3078 Paths.clear();
3079 Paths.setRecordingPaths(true);
3080 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
3081 assert(StillOkay && "Can only be used with a derived-to-base conversion");
3082 (void)StillOkay;
3083
3084 // Build up a textual representation of the ambiguous paths, e.g.,
3085 // D -> B -> A, that will be used to illustrate the ambiguous
3086 // conversions in the diagnostic. We only print one of the paths
3087 // to each base class subobject.
3088 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3089
3090 Diag(Loc, AmbiguousBaseConvID)
3091 << Derived << Base << PathDisplayStr << Range << Name;
3092 }
3093 return true;
3094}
3095
3096bool
3099 CXXCastPath *BasePath,
3100 bool IgnoreAccess) {
3102 Derived, Base, diag::err_upcast_to_inaccessible_base,
3103 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
3104 BasePath, IgnoreAccess);
3105}
3106
3108 std::string PathDisplayStr;
3109 std::set<unsigned> DisplayedPaths;
3110 for (CXXBasePaths::paths_iterator Path = Paths.begin();
3111 Path != Paths.end(); ++Path) {
3112 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
3113 // We haven't displayed a path to this particular base
3114 // class subobject yet.
3115 PathDisplayStr += "\n ";
3116 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
3117 for (CXXBasePath::const_iterator Element = Path->begin();
3118 Element != Path->end(); ++Element)
3119 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
3120 }
3121 }
3122
3123 return PathDisplayStr;
3124}
3125
3126//===----------------------------------------------------------------------===//
3127// C++ class member Handling
3128//===----------------------------------------------------------------------===//
3129
3131 SourceLocation ColonLoc,
3132 const ParsedAttributesView &Attrs) {
3133 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
3135 ASLoc, ColonLoc);
3136 CurContext->addHiddenDecl(ASDecl);
3137 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
3138}
3139
3141 if (D->isInvalidDecl())
3142 return;
3143
3144 // We only care about "override" and "final" declarations.
3145 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
3146 return;
3147
3148 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3149
3150 // We can't check dependent instance methods.
3151 if (MD && MD->isInstance() &&
3152 (MD->getParent()->hasAnyDependentBases() ||
3153 MD->getType()->isDependentType()))
3154 return;
3155
3156 if (MD && !MD->isVirtual()) {
3157 // If we have a non-virtual method, check if it hides a virtual method.
3158 // (In that case, it's most likely the method has the wrong type.)
3159 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3160 FindHiddenVirtualMethods(MD, OverloadedMethods);
3161
3162 if (!OverloadedMethods.empty()) {
3163 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3164 Diag(OA->getLocation(),
3165 diag::override_keyword_hides_virtual_member_function)
3166 << "override" << (OverloadedMethods.size() > 1);
3167 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3168 Diag(FA->getLocation(),
3169 diag::override_keyword_hides_virtual_member_function)
3170 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3171 << (OverloadedMethods.size() > 1);
3172 }
3173 NoteHiddenVirtualMethods(MD, OverloadedMethods);
3174 MD->setInvalidDecl();
3175 return;
3176 }
3177 // Fall through into the general case diagnostic.
3178 // FIXME: We might want to attempt typo correction here.
3179 }
3180
3181 if (!MD || !MD->isVirtual()) {
3182 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3183 Diag(OA->getLocation(),
3184 diag::override_keyword_only_allowed_on_virtual_member_functions)
3185 << "override" << FixItHint::CreateRemoval(OA->getLocation());
3186 D->dropAttr<OverrideAttr>();
3187 }
3188 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3189 Diag(FA->getLocation(),
3190 diag::override_keyword_only_allowed_on_virtual_member_functions)
3191 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3192 << FixItHint::CreateRemoval(FA->getLocation());
3193 D->dropAttr<FinalAttr>();
3194 }
3195 return;
3196 }
3197
3198 // C++11 [class.virtual]p5:
3199 // If a function is marked with the virt-specifier override and
3200 // does not override a member function of a base class, the program is
3201 // ill-formed.
3202 bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
3203 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
3204 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
3205 << MD->getDeclName();
3206}
3207
3209 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
3210 return;
3211 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3212 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
3213 return;
3214
3216 SourceLocation SpellingLoc = Loc;
3217 if (getSourceManager().isMacroArgExpansion(Loc))
3219 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
3220 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
3221 return;
3222
3223 if (MD->size_overridden_methods() > 0) {
3224 auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) {
3225 unsigned DiagID =
3226 Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation())
3227 ? DiagInconsistent
3228 : DiagSuggest;
3229 Diag(MD->getLocation(), DiagID) << MD->getDeclName();
3230 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
3231 Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
3232 };
3233 if (isa<CXXDestructorDecl>(MD))
3234 EmitDiag(
3235 diag::warn_inconsistent_destructor_marked_not_override_overriding,
3236 diag::warn_suggest_destructor_marked_not_override_overriding);
3237 else
3238 EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding,
3239 diag::warn_suggest_function_marked_not_override_overriding);
3240 }
3241}
3242
3244 const CXXMethodDecl *Old) {
3245 FinalAttr *FA = Old->getAttr<FinalAttr>();
3246 if (!FA)
3247 return false;
3248
3249 Diag(New->getLocation(), diag::err_final_function_overridden)
3250 << New->getDeclName()
3251 << FA->isSpelledAsSealed();
3252 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3253 return true;
3254}
3255
3257 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
3258 // FIXME: Destruction of ObjC lifetime types has side-effects.
3259 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3260 return !RD->isCompleteDefinition() ||
3261 !RD->hasTrivialDefaultConstructor() ||
3262 !RD->hasTrivialDestructor();
3263 return false;
3264}
3265
3266void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
3267 DeclarationName FieldName,
3268 const CXXRecordDecl *RD,
3269 bool DeclIsField) {
3270 if (Diags.isIgnored(diag::warn_shadow_field, Loc))
3271 return;
3272
3273 // To record a shadowed field in a base
3274 std::map<CXXRecordDecl*, NamedDecl*> Bases;
3275 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
3276 CXXBasePath &Path) {
3277 const auto Base = Specifier->getType()->getAsCXXRecordDecl();
3278 // Record an ambiguous path directly
3279 if (Bases.find(Base) != Bases.end())
3280 return true;
3281 for (const auto Field : Base->lookup(FieldName)) {
3282 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
3283 Field->getAccess() != AS_private) {
3284 assert(Field->getAccess() != AS_none);
3285 assert(Bases.find(Base) == Bases.end());
3286 Bases[Base] = Field;
3287 return true;
3288 }
3289 }
3290 return false;
3291 };
3292
3293 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3294 /*DetectVirtual=*/true);
3295 if (!RD->lookupInBases(FieldShadowed, Paths))
3296 return;
3297
3298 for (const auto &P : Paths) {
3299 auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
3300 auto It = Bases.find(Base);
3301 // Skip duplicated bases
3302 if (It == Bases.end())
3303 continue;
3304 auto BaseField = It->second;
3305 assert(BaseField->getAccess() != AS_private);
3306 if (AS_none !=
3307 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
3308 Diag(Loc, diag::warn_shadow_field)
3309 << FieldName << RD << Base << DeclIsField;
3310 Diag(BaseField->getLocation(), diag::note_shadow_field);
3311 Bases.erase(It);
3312 }
3313 }
3314}
3315
3316NamedDecl *
3318 MultiTemplateParamsArg TemplateParameterLists,
3319 Expr *BW, const VirtSpecifiers &VS,
3320 InClassInitStyle InitStyle) {
3321 const DeclSpec &DS = D.getDeclSpec();
3323 DeclarationName Name = NameInfo.getName();
3324 SourceLocation Loc = NameInfo.getLoc();
3325
3326 // For anonymous bitfields, the location should point to the type.
3327 if (Loc.isInvalid())
3328 Loc = D.getBeginLoc();
3329
3330 Expr *BitWidth = static_cast<Expr*>(BW);
3331
3332 assert(isa<CXXRecordDecl>(CurContext));
3333 assert(!DS.isFriendSpecified());
3334
3335 bool isFunc = D.isDeclarationOfFunction();
3336 const ParsedAttr *MSPropertyAttr =
3337 D.getDeclSpec().getAttributes().getMSPropertyAttr();
3338
3339 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
3340 // The Microsoft extension __interface only permits public member functions
3341 // and prohibits constructors, destructors, operators, non-public member
3342 // functions, static methods and data members.
3343 unsigned InvalidDecl;
3344 bool ShowDeclName = true;
3345 if (!isFunc &&
3346 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
3347 InvalidDecl = 0;
3348 else if (!isFunc)
3349 InvalidDecl = 1;
3350 else if (AS != AS_public)
3351 InvalidDecl = 2;
3353 InvalidDecl = 3;
3354 else switch (Name.getNameKind()) {
3356 InvalidDecl = 4;
3357 ShowDeclName = false;
3358 break;
3359
3361 InvalidDecl = 5;
3362 ShowDeclName = false;
3363 break;
3364
3367 InvalidDecl = 6;
3368 break;
3369
3370 default:
3371 InvalidDecl = 0;
3372 break;
3373 }
3374
3375 if (InvalidDecl) {
3376 if (ShowDeclName)
3377 Diag(Loc, diag::err_invalid_member_in_interface)
3378 << (InvalidDecl-1) << Name;
3379 else
3380 Diag(Loc, diag::err_invalid_member_in_interface)
3381 << (InvalidDecl-1) << "";
3382 return nullptr;
3383 }
3384 }
3385
3386 // C++ 9.2p6: A member shall not be declared to have automatic storage
3387 // duration (auto, register) or with the extern storage-class-specifier.
3388 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3389 // data members and cannot be applied to names declared const or static,
3390 // and cannot be applied to reference members.
3391 switch (DS.getStorageClassSpec()) {
3395 break;
3397 if (isFunc) {
3398 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3399
3400 // FIXME: It would be nicer if the keyword was ignored only for this
3401 // declarator. Otherwise we could get follow-up errors.
3402 D.getMutableDeclSpec().ClearStorageClassSpecs();
3403 }
3404 break;
3405 default:
3407 diag::err_storageclass_invalid_for_member);
3408 D.getMutableDeclSpec().ClearStorageClassSpecs();
3409 break;
3410 }
3411
3412 bool isInstField = (DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3414 !isFunc && TemplateParameterLists.empty();
3415
3416 if (DS.hasConstexprSpecifier() && isInstField) {
3418 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3419 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3420 if (InitStyle == ICIS_NoInit) {
3421 B << 0 << 0;
3422 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
3423 B << FixItHint::CreateRemoval(ConstexprLoc);
3424 else {
3425 B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3426 D.getMutableDeclSpec().ClearConstexprSpec();
3427 const char *PrevSpec;
3428 unsigned DiagID;
3429 bool Failed = D.getMutableDeclSpec().SetTypeQual(
3430 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3431 (void)Failed;
3432 assert(!Failed && "Making a constexpr member const shouldn't fail");
3433 }
3434 } else {
3435 B << 1;
3436 const char *PrevSpec;
3437 unsigned DiagID;
3438 if (D.getMutableDeclSpec().SetStorageClassSpec(
3439 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3442 "This is the only DeclSpec that should fail to be applied");
3443 B << 1;
3444 } else {
3445 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3446 isInstField = false;
3447 }
3448 }
3449 }
3450
3452 if (isInstField) {
3453 CXXScopeSpec &SS = D.getCXXScopeSpec();
3454
3455 // Data members must have identifiers for names.
3456 if (!Name.isIdentifier()) {
3457 Diag(Loc, diag::err_bad_variable_name)
3458 << Name;
3459 return nullptr;
3460 }
3461
3462 IdentifierInfo *II = Name.getAsIdentifierInfo();
3463 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
3464 Diag(D.getIdentifierLoc(), diag::err_member_with_template_arguments)
3465 << II
3466 << SourceRange(D.getName().TemplateId->LAngleLoc,
3467 D.getName().TemplateId->RAngleLoc)
3468 << D.getName().TemplateId->LAngleLoc;
3469 D.SetIdentifier(II, Loc);
3470 }
3471
3472 if (SS.isSet() && !SS.isInvalid()) {
3473 // The user provided a superfluous scope specifier inside a class
3474 // definition:
3475 //
3476 // class X {
3477 // int X::member;
3478 // };
3479 if (DeclContext *DC = computeDeclContext(SS, false)) {
3480 TemplateIdAnnotation *TemplateId =
3482 ? D.getName().TemplateId
3483 : nullptr;
3484 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
3485 TemplateId,
3486 /*IsMemberSpecialization=*/false);
3487 } else {
3488 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3489 << Name << SS.getRange();
3490 }
3491 SS.clear();
3492 }
3493
3494 if (MSPropertyAttr) {
3495 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3496 BitWidth, InitStyle, AS, *MSPropertyAttr);
3497 if (!Member)
3498 return nullptr;
3499 isInstField = false;
3500 } else {
3501 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3502 BitWidth, InitStyle, AS);
3503 if (!Member)
3504 return nullptr;
3505 }
3506
3507 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3508 } else {
3509 Member = HandleDeclarator(S, D, TemplateParameterLists);
3510 if (!Member)
3511 return nullptr;
3512
3513 // Non-instance-fields can't have a bitfield.
3514 if (BitWidth) {
3515 if (Member->isInvalidDecl()) {
3516 // don't emit another diagnostic.
3517 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3518 // C++ 9.6p3: A bit-field shall not be a static member.
3519 // "static member 'A' cannot be a bit-field"
3520 Diag(Loc, diag::err_static_not_bitfield)
3521 << Name << BitWidth->getSourceRange();
3522 } else if (isa<TypedefDecl>(Member)) {
3523 // "typedef member 'x' cannot be a bit-field"
3524 Diag(Loc, diag::err_typedef_not_bitfield)
3525 << Name << BitWidth->getSourceRange();
3526 } else {
3527 // A function typedef ("typedef int f(); f a;").
3528 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3529 Diag(Loc, diag::err_not_integral_type_bitfield)
3530 << Name << cast<ValueDecl>(Member)->getType()
3531 << BitWidth->getSourceRange();
3532 }
3533
3534 BitWidth = nullptr;
3535 Member->setInvalidDecl();
3536 }
3537
3538 NamedDecl *NonTemplateMember = Member;
3539 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3540 NonTemplateMember = FunTmpl->getTemplatedDecl();
3541 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3542 NonTemplateMember = VarTmpl->getTemplatedDecl();
3543
3544 Member->setAccess(AS);
3545
3546 // If we have declared a member function template or static data member
3547 // template, set the access of the templated declaration as well.
3548 if (NonTemplateMember != Member)
3549 NonTemplateMember->setAccess(AS);
3550
3551 // C++ [temp.deduct.guide]p3:
3552 // A deduction guide [...] for a member class template [shall be
3553 // declared] with the same access [as the template].
3554 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3555 auto *TD = DG->getDeducedTemplate();
3556 // Access specifiers are only meaningful if both the template and the
3557 // deduction guide are from the same scope.
3558 if (AS != TD->getAccess() &&
3559 TD->getDeclContext()->getRedeclContext()->Equals(
3560 DG->getDeclContext()->getRedeclContext())) {
3561 Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3562 Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3563 << TD->getAccess();
3564 const AccessSpecDecl *LastAccessSpec = nullptr;
3565 for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3566 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3567 LastAccessSpec = AccessSpec;
3568 }
3569 assert(LastAccessSpec && "differing access with no access specifier");
3570 Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3571 << AS;
3572 }
3573 }
3574 }
3575
3576 if (VS.isOverrideSpecified())
3577 Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc()));
3578 if (VS.isFinalSpecified())
3579 Member->addAttr(FinalAttr::Create(Context, VS.getFinalLoc(),
3581 ? FinalAttr::Keyword_sealed
3582 : FinalAttr::Keyword_final));
3583
3584 if (VS.getLastLocation().isValid()) {
3585 // Update the end location of a method that has a virt-specifiers.
3586 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3587 MD->setRangeEnd(VS.getLastLocation());
3588 }
3589
3591
3592 assert((Name || isInstField) && "No identifier for non-field ?");
3593
3594 if (isInstField) {
3595 FieldDecl *FD = cast<FieldDecl>(Member);
3596 FieldCollector->Add(FD);
3597
3598 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3599 // Remember all explicit private FieldDecls that have a name, no side
3600 // effects and are not part of a dependent type declaration.
3601
3602 auto DeclHasUnusedAttr = [](const QualType &T) {
3603 if (const TagDecl *TD = T->getAsTagDecl())
3604 return TD->hasAttr<UnusedAttr>();
3605 if (const TypedefType *TDT = T->getAs<TypedefType>())
3606 return TDT->getDecl()->hasAttr<UnusedAttr>();
3607 return false;
3608 };
3609
3610 if (!FD->isImplicit() && FD->getDeclName() &&
3611 FD->getAccess() == AS_private &&
3612 !FD->hasAttr<UnusedAttr>() &&
3613 !FD->getParent()->isDependentContext() &&
3614 !DeclHasUnusedAttr(FD->getType()) &&
3616 UnusedPrivateFields.insert(FD);
3617 }
3618 }
3619
3620 return Member;
3621}
3622
3623namespace {
3624 class UninitializedFieldVisitor
3625 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3626 Sema &S;
3627 // List of Decls to generate a warning on. Also remove Decls that become
3628 // initialized.
3629 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3630 // List of base classes of the record. Classes are removed after their
3631 // initializers.
3632 llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3633 // Vector of decls to be removed from the Decl set prior to visiting the
3634 // nodes. These Decls may have been initialized in the prior initializer.
3636 // If non-null, add a note to the warning pointing back to the constructor.
3637 const CXXConstructorDecl *Constructor;
3638 // Variables to hold state when processing an initializer list. When
3639 // InitList is true, special case initialization of FieldDecls matching
3640 // InitListFieldDecl.
3641 bool InitList;
3642 FieldDecl *InitListFieldDecl;
3643 llvm::SmallVector<unsigned, 4> InitFieldIndex;
3644
3645 public:
3647 UninitializedFieldVisitor(Sema &S,
3648 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3649 llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3650 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3651 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3652
3653 // Returns true if the use of ME is not an uninitialized use.
3654 bool IsInitListMemberExprInitialized(MemberExpr *ME,
3655 bool CheckReferenceOnly) {
3657 bool ReferenceField = false;
3658 while (ME) {
3659 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3660 if (!FD)
3661 return false;
3662 Fields.push_back(FD);
3663 if (FD->getType()->isReferenceType())
3664 ReferenceField = true;
3665 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3666 }
3667
3668 // Binding a reference to an uninitialized field is not an
3669 // uninitialized use.
3670 if (CheckReferenceOnly && !ReferenceField)
3671 return true;
3672
3673 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3674 // Discard the first field since it is the field decl that is being
3675 // initialized.
3676 for (const FieldDecl *FD : llvm::drop_begin(llvm::reverse(Fields)))
3677 UsedFieldIndex.push_back(FD->getFieldIndex());
3678
3679 for (auto UsedIter = UsedFieldIndex.begin(),
3680 UsedEnd = UsedFieldIndex.end(),
3681 OrigIter = InitFieldIndex.begin(),
3682 OrigEnd = InitFieldIndex.end();
3683 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3684 if (*UsedIter < *OrigIter)
3685 return true;
3686 if (*UsedIter > *OrigIter)
3687 break;
3688 }
3689
3690 return false;
3691 }
3692
3693 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3694 bool AddressOf) {
3695 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3696 return;
3697
3698 // FieldME is the inner-most MemberExpr that is not an anonymous struct
3699 // or union.
3700 MemberExpr *FieldME = ME;
3701
3702 bool AllPODFields = FieldME->getType().isPODType(S.Context);
3703
3704 Expr *Base = ME;
3705 while (MemberExpr *SubME =
3706 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3707
3708 if (isa<VarDecl>(SubME->getMemberDecl()))
3709 return;
3710
3711 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3712 if (!FD->isAnonymousStructOrUnion())
3713 FieldME = SubME;
3714
3715 if (!FieldME->getType().isPODType(S.Context))
3716 AllPODFields = false;
3717
3718 Base = SubME->getBase();
3719 }
3720
3721 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) {
3722 Visit(Base);
3723 return;
3724 }
3725
3726 if (AddressOf && AllPODFields)
3727 return;
3728
3729 ValueDecl* FoundVD = FieldME->getMemberDecl();
3730
3731 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3732 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3733 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3734 }
3735
3736 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3737 QualType T = BaseCast->getType();
3738 if (T->isPointerType() &&
3739 BaseClasses.count(T->getPointeeType())) {
3740 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3741 << T->getPointeeType() << FoundVD;
3742 }
3743 }
3744 }
3745
3746 if (!Decls.count(FoundVD))
3747 return;
3748
3749 const bool IsReference = FoundVD->getType()->isReferenceType();
3750
3751 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3752 // Special checking for initializer lists.
3753 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3754 return;
3755 }
3756 } else {
3757 // Prevent double warnings on use of unbounded references.
3758 if (CheckReferenceOnly && !IsReference)
3759 return;
3760 }
3761
3762 unsigned diag = IsReference
3763 ? diag::warn_reference_field_is_uninit
3764 : diag::warn_field_is_uninit;
3765 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3766 if (Constructor)
3767 S.Diag(Constructor->getLocation(),
3768 diag::note_uninit_in_this_constructor)
3769 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3770
3771 }
3772
3773 void HandleValue(Expr *E, bool AddressOf) {
3774 E = E->IgnoreParens();
3775
3776 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3777 HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3778 AddressOf /*AddressOf*/);
3779 return;
3780 }
3781
3782 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3783 Visit(CO->getCond());
3784 HandleValue(CO->getTrueExpr(), AddressOf);
3785 HandleValue(CO->getFalseExpr(), AddressOf);
3786 return;
3787 }
3788
3789 if (BinaryConditionalOperator *BCO =
3790 dyn_cast<BinaryConditionalOperator>(E)) {
3791 Visit(BCO->getCond());
3792 HandleValue(BCO->getFalseExpr(), AddressOf);
3793 return;
3794 }
3795
3796 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3797 HandleValue(OVE->getSourceExpr(), AddressOf);
3798 return;
3799 }
3800
3801 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3802 switch (BO->getOpcode()) {
3803 default:
3804 break;
3805 case(BO_PtrMemD):
3806 case(BO_PtrMemI):
3807 HandleValue(BO->getLHS(), AddressOf);
3808 Visit(BO->getRHS());
3809 return;
3810 case(BO_Comma):
3811 Visit(BO->getLHS());
3812 HandleValue(BO->getRHS(), AddressOf);
3813 return;
3814 }
3815 }
3816
3817 Visit(E);
3818 }
3819
3820 void CheckInitListExpr(InitListExpr *ILE) {
3821 InitFieldIndex.push_back(0);
3822 for (auto *Child : ILE->children()) {
3823 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3824 CheckInitListExpr(SubList);
3825 } else {
3826 Visit(Child);
3827 }
3828 ++InitFieldIndex.back();
3829 }
3830 InitFieldIndex.pop_back();
3831 }
3832
3833 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3834 FieldDecl *Field, const Type *BaseClass) {
3835 // Remove Decls that may have been initialized in the previous
3836 // initializer.
3837 for (ValueDecl* VD : DeclsToRemove)
3838 Decls.erase(VD);
3839 DeclsToRemove.clear();
3840
3841 Constructor = FieldConstructor;
3842 InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3843
3844 if (ILE && Field) {
3845 InitList = true;
3846 InitListFieldDecl = Field;
3847 InitFieldIndex.clear();
3848 CheckInitListExpr(ILE);
3849 } else {
3850 InitList = false;
3851 Visit(E);
3852 }
3853
3854 if (Field)
3855 Decls.erase(Field);
3856 if (BaseClass)
3857 BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3858 }
3859
3860 void VisitMemberExpr(MemberExpr *ME) {
3861 // All uses of unbounded reference fields will warn.
3862 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3863 }
3864
3865 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3866 if (E->getCastKind() == CK_LValueToRValue) {
3867 HandleValue(E->getSubExpr(), false /*AddressOf*/);
3868 return;
3869 }
3870
3871 Inherited::VisitImplicitCastExpr(E);
3872 }
3873
3874 void VisitCXXConstructExpr(CXXConstructExpr *E) {
3875 if (E->getConstructor()->isCopyConstructor()) {
3876 Expr *ArgExpr = E->getArg(0);
3877 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3878 if (ILE->getNumInits() == 1)
3879 ArgExpr = ILE->getInit(0);
3880 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3881 if (ICE->getCastKind() == CK_NoOp)
3882 ArgExpr = ICE->getSubExpr();
3883 HandleValue(ArgExpr, false /*AddressOf*/);
3884 return;
3885 }
3886 Inherited::VisitCXXConstructExpr(E);
3887 }
3888
3889 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3890 Expr *Callee = E->getCallee();
3891 if (isa<MemberExpr>(Callee)) {
3892 HandleValue(Callee, false /*AddressOf*/);
3893 for (auto *Arg : E->arguments())
3894 Visit(Arg);
3895 return;
3896 }
3897
3898 Inherited::VisitCXXMemberCallExpr(E);
3899 }
3900
3901 void VisitCallExpr(CallExpr *E) {
3902 // Treat std::move as a use.
3903 if (E->isCallToStdMove()) {
3904 HandleValue(E->getArg(0), /*AddressOf=*/false);
3905 return;
3906 }
3907
3908 Inherited::VisitCallExpr(E);
3909 }
3910
3911 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3912 Expr *Callee = E->getCallee();
3913
3914 if (isa<UnresolvedLookupExpr>(Callee))
3915 return Inherited::VisitCXXOperatorCallExpr(E);
3916
3917 Visit(Callee);
3918 for (auto *Arg : E->arguments())
3919 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3920 }
3921
3922 void VisitBinaryOperator(BinaryOperator *E) {
3923 // If a field assignment is detected, remove the field from the
3924 // uninitiailized field set.
3925 if (E->getOpcode() == BO_Assign)
3926 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3927 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3928 if (!FD->getType()->isReferenceType())
3929 DeclsToRemove.push_back(FD);
3930
3931 if (E->isCompoundAssignmentOp()) {
3932 HandleValue(E->getLHS(), false /*AddressOf*/);
3933 Visit(E->getRHS());
3934 return;
3935 }
3936
3937 Inherited::VisitBinaryOperator(E);
3938 }
3939
3940 void VisitUnaryOperator(UnaryOperator *E) {
3941 if (E->isIncrementDecrementOp()) {
3942 HandleValue(E->getSubExpr(), false /*AddressOf*/);
3943 return;
3944 }
3945 if (E->getOpcode() == UO_AddrOf) {
3946 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3947 HandleValue(ME->getBase(), true /*AddressOf*/);
3948 return;
3949 }
3950 }
3951
3952 Inherited::VisitUnaryOperator(E);
3953 }
3954 };
3955
3956 // Diagnose value-uses of fields to initialize themselves, e.g.
3957 // foo(foo)
3958 // where foo is not also a parameter to the constructor.
3959 // Also diagnose across field uninitialized use such as
3960 // x(y), y(x)
3961 // TODO: implement -Wuninitialized and fold this into that framework.
3962 static void DiagnoseUninitializedFields(
3963 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3964
3965 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3966 Constructor->getLocation())) {
3967 return;
3968 }
3969
3970 if (Constructor->isInvalidDecl())
3971 return;
3972
3973 const CXXRecordDecl *RD = Constructor->getParent();
3974
3975 if (RD->isDependentContext())
3976 return;
3977
3978 // Holds fields that are uninitialized.
3979 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3980
3981 // At the beginning, all fields are uninitialized.
3982 for (auto *I : RD->decls()) {
3983 if (auto *FD = dyn_cast<FieldDecl>(I)) {
3984 UninitializedFields.insert(FD);
3985 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3986 UninitializedFields.insert(IFD->getAnonField());
3987 }
3988 }
3989
3990 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3991 for (const auto &I : RD->bases())
3992 UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3993
3994 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3995 return;
3996
3997 UninitializedFieldVisitor UninitializedChecker(SemaRef,
3998 UninitializedFields,
3999 UninitializedBaseClasses);
4000
4001 for (const auto *FieldInit : Constructor->inits()) {
4002 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
4003 break;
4004
4005 Expr *InitExpr = FieldInit->getInit();
4006 if (!InitExpr)
4007 continue;
4008
4010 dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
4011 InitExpr = Default->getExpr();
4012 if (!InitExpr)
4013 continue;
4014 // In class initializers will point to the constructor.
4015 UninitializedChecker.CheckInitializer(InitExpr, Constructor,
4016 FieldInit->getAnyMember(),
4017 FieldInit->getBaseClass());
4018 } else {
4019 UninitializedChecker.CheckInitializer(InitExpr, nullptr,
4020 FieldInit->getAnyMember(),
4021 FieldInit->getBaseClass());
4022 }
4023 }
4024 }
4025} // namespace
4026
4028 // Create a synthetic function scope to represent the call to the constructor
4029 // that notionally surrounds a use of this initializer.
4031}
4032
4034 if (!D.isFunctionDeclarator())
4035 return;
4036 auto &FTI = D.getFunctionTypeInfo();
4037 if (!FTI.Params)
4038 return;
4039 for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params,
4040 FTI.NumParams)) {
4041 auto *ParamDecl = cast<NamedDecl>(Param.Param);
4042 if (ParamDecl->getDeclName())
4043 PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false);
4044 }
4045}
4046
4048 return ActOnRequiresClause(ConstraintExpr);
4049}
4050
4052 if (ConstraintExpr.isInvalid())
4053 return ExprError();
4054
4055 ConstraintExpr = CorrectDelayedTyposInExpr(ConstraintExpr);
4056 if (ConstraintExpr.isInvalid())
4057 return ExprError();
4058
4059 if (DiagnoseUnexpandedParameterPack(ConstraintExpr.get(),
4061 return ExprError();
4062
4063 return ConstraintExpr;
4064}
4065
4067 Expr *InitExpr,
4068 SourceLocation InitLoc) {
4069 InitializedEntity Entity =
4071 InitializationKind Kind =
4074 InitExpr->getBeginLoc(),
4075 InitExpr->getEndLoc())
4076 : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
4077 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
4078 return Seq.Perform(*this, Entity, Kind, InitExpr);
4079}
4080
4082 SourceLocation InitLoc,
4083 Expr *InitExpr) {
4084 // Pop the notional constructor scope we created earlier.
4085 PopFunctionScopeInfo(nullptr, D);
4086
4087 FieldDecl *FD = dyn_cast<FieldDecl>(D);
4088 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
4089 "must set init style when field is created");
4090
4091 if (!InitExpr) {
4092 D->setInvalidDecl();
4093 if (FD)
4095 return;
4096 }
4097
4099 FD->setInvalidDecl();
4101 return;
4102 }
4103
4104 ExprResult Init = CorrectDelayedTyposInExpr(InitExpr, /*InitDecl=*/nullptr,
4105 /*RecoverUncorrectedTypos=*/true);
4106 assert(Init.isUsable() && "Init should at least have a RecoveryExpr");
4107 if (!FD->getType()->isDependentType() && !Init.get()->isTypeDependent()) {
4108 Init = ConvertMemberDefaultInitExpression(FD, Init.get(), InitLoc);
4109 // C++11 [class.base.init]p7:
4110 // The initialization of each base and member constitutes a
4111 // full-expression.
4112 if (!Init.isInvalid())
4113 Init = ActOnFinishFullExpr(Init.get(), /*DiscarededValue=*/false);
4114 if (Init.isInvalid()) {
4115 FD->setInvalidDecl();
4116 return;
4117 }
4118 }
4119
4120 FD->setInClassInitializer(Init.get());
4121}
4122
4123/// Find the direct and/or virtual base specifiers that
4124/// correspond to the given base type, for use in base initialization
4125/// within a constructor.
4127 CXXRecordDecl *ClassDecl,
4128 QualType BaseType,
4129 const CXXBaseSpecifier *&DirectBaseSpec,
4130 const CXXBaseSpecifier *&VirtualBaseSpec) {
4131 // First, check for a direct base class.
4132 DirectBaseSpec = nullptr;
4133 for (const auto &Base : ClassDecl->bases()) {
4134 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
4135 // We found a direct base of this type. That's what we're
4136 // initializing.
4137 DirectBaseSpec = &Base;
4138 break;
4139 }
4140 }
4141
4142 // Check for a virtual base class.
4143 // FIXME: We might be able to short-circuit this if we know in advance that
4144 // there are no virtual bases.
4145 VirtualBaseSpec = nullptr;
4146 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
4147 // We haven't found a base yet; search the class hierarchy for a
4148 // virtual base class.
4149 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
4150 /*DetectVirtual=*/false);
4151 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
4152 SemaRef.Context.getTypeDeclType(ClassDecl),
4153 BaseType, Paths)) {
4154 for (CXXBasePaths::paths_iterator Path = Paths.begin();
4155 Path != Paths.end(); ++Path) {
4156 if (Path->back().Base->isVirtual()) {
4157 VirtualBaseSpec = Path->back().Base;
4158 break;
4159 }
4160 }
4161 }
4162 }
4163
4164 return DirectBaseSpec || VirtualBaseSpec;
4165}
4166
4169 Scope *S,
4170 CXXScopeSpec &SS,
4171 IdentifierInfo *MemberOrBase,
4172 ParsedType TemplateTypeTy,
4173 const DeclSpec &DS,
4174 SourceLocation IdLoc,
4175 Expr *InitList,
4176 SourceLocation EllipsisLoc) {
4177 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4178 DS, IdLoc, InitList,
4179 EllipsisLoc);
4180}
4181
4184 Scope *S,
4185 CXXScopeSpec &SS,
4186 IdentifierInfo *MemberOrBase,
4187 ParsedType TemplateTypeTy,
4188 const DeclSpec &DS,
4189 SourceLocation IdLoc,
4190 SourceLocation LParenLoc,
4191 ArrayRef<Expr *> Args,
4192 SourceLocation RParenLoc,
4193 SourceLocation EllipsisLoc) {
4194 Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
4195 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4196 DS, IdLoc, List, EllipsisLoc);
4197}
4198
4199namespace {
4200
4201// Callback to only accept typo corrections that can be a valid C++ member
4202// initializer: either a non-static field member or a base class.
4203class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
4204public:
4205 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
4206 : ClassDecl(ClassDecl) {}
4207
4208 bool ValidateCandidate(const TypoCorrection &candidate) override {
4209 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
4210 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
4211 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
4212 return isa<TypeDecl>(ND);
4213 }
4214 return false;
4215 }
4216
4217 std::unique_ptr<CorrectionCandidateCallback> clone() override {
4218 return std::make_unique<MemInitializerValidatorCCC>(*this);
4219 }
4220
4221private:
4222 CXXRecordDecl *ClassDecl;
4223};
4224
4225}
4226
4228 RecordDecl *ClassDecl,
4229 const IdentifierInfo *Name) {
4230 DeclContextLookupResult Result = ClassDecl->lookup(Name);
4232 llvm::find_if(Result, [this](const NamedDecl *Elem) {
4233 return isa<FieldDecl, IndirectFieldDecl>(Elem) &&
4235 });
4236 // We did not find a placeholder variable
4237 if (Found == Result.end())
4238 return false;
4239 Diag(Loc, diag::err_using_placeholder_variable) << Name;
4240 for (DeclContextLookupResult::iterator It = Found; It != Result.end(); It++) {
4241 const NamedDecl *ND = *It;
4242 if (ND->getDeclContext() != ND->getDeclContext())
4243 break;
4244 if (isa<FieldDecl, IndirectFieldDecl>(ND) &&
4246 Diag(ND->getLocation(), diag::note_reference_placeholder) << ND;
4247 }
4248 return true;
4249}
4250
4251ValueDecl *
4253 const IdentifierInfo *MemberOrBase) {
4254 ValueDecl *ND = nullptr;
4255 for (auto *D : ClassDecl->lookup(MemberOrBase)) {
4256 if (isa<FieldDecl, IndirectFieldDecl>(D)) {
4257 bool IsPlaceholder = D->isPlaceholderVar(getLangOpts());
4258 if (ND) {
4259 if (IsPlaceholder && D->getDeclContext() == ND->getDeclContext())
4260 return nullptr;
4261 break;
4262 }
4263 if (!IsPlaceholder)
4264 return cast<ValueDecl>(D);
4265 ND = cast<ValueDecl>(D);
4266 }
4267 }
4268 return ND;
4269}
4270
4272 CXXScopeSpec &SS,
4273 ParsedType TemplateTypeTy,
4274 IdentifierInfo *MemberOrBase) {
4275 if (SS.getScopeRep() || TemplateTypeTy)
4276 return nullptr;
4277 return tryLookupUnambiguousFieldDecl(ClassDecl, MemberOrBase);
4278}
4279
4282 Scope *S,
4283 CXXScopeSpec &SS,
4284 IdentifierInfo *MemberOrBase,
4285 ParsedType TemplateTypeTy,
4286 const DeclSpec &DS,
4287 SourceLocation IdLoc,
4288 Expr *Init,
4289 SourceLocation EllipsisLoc) {
4290 ExprResult Res = CorrectDelayedTyposInExpr(Init, /*InitDecl=*/nullptr,
4291 /*RecoverUncorrectedTypos=*/true);
4292 if (!Res.isUsable())
4293 return true;
4294 Init = Res.get();
4295
4296 if (!ConstructorD)
4297 return true;
4298
4299 AdjustDeclIfTemplate(ConstructorD);
4300
4301 CXXConstructorDecl *Constructor
4302 = dyn_cast<CXXConstructorDecl>(ConstructorD);
4303 if (!Constructor) {
4304 // The user wrote a constructor initializer on a function that is
4305 // not a C++ constructor. Ignore the error for now, because we may
4306 // have more member initializers coming; we'll diagnose it just
4307 // once in ActOnMemInitializers.
4308 return true;
4309 }
4310
4311 CXXRecordDecl *ClassDecl = Constructor->getParent();
4312
4313 // C++ [class.base.init]p2:
4314 // Names in a mem-initializer-id are looked up in the scope of the
4315 // constructor's class and, if not found in that scope, are looked
4316 // up in the scope containing the constructor's definition.
4317 // [Note: if the constructor's class contains a member with the
4318 // same name as a direct or virtual base class of the class, a
4319 // mem-initializer-id naming the member or base class and composed
4320 // of a single identifier refers to the class member. A
4321 // mem-initializer-id for the hidden base class may be specified
4322 // using a qualified name. ]
4323
4324 // Look for a member, first.
4326 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
4327 if (EllipsisLoc.isValid())
4328 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
4329 << MemberOrBase
4330 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4331
4332 return BuildMemberInitializer(Member, Init, IdLoc);
4333 }
4334 // It didn't name a member, so see if it names a class.
4335 QualType BaseType;
4336 TypeSourceInfo *TInfo = nullptr;
4337
4338 if (TemplateTypeTy) {
4339 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
4340 if (BaseType.isNull())
4341 return true;
4342 } else if (DS.getTypeSpecType() == TST_decltype) {
4343 BaseType = BuildDecltypeType(DS.getRepAsExpr());
4344 } else if (DS.getTypeSpecType() == TST_decltype_auto) {
4345 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
4346 return true;
4347 } else if (DS.getTypeSpecType() == TST_typename_pack_indexing) {
4348 BaseType =
4350 DS.getBeginLoc(), DS.getEllipsisLoc());
4351 } else {
4352 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
4353 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
4354
4355 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
4356 if (!TyD) {
4357 if (R.isAmbiguous()) return true;
4358
4359 // We don't want access-control diagnostics here.
4361
4362 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
4363 bool NotUnknownSpecialization = false;
4364 DeclContext *DC = computeDeclContext(SS, false);
4365 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
4366 NotUnknownSpecialization = !Record->hasAnyDependentBases();
4367
4368 if (!NotUnknownSpecialization) {
4369 // When the scope specifier can refer to a member of an unknown
4370 // specialization, we take it as a type name.
4371 BaseType = CheckTypenameType(
4373 SS.getWithLocInContext(Context), *MemberOrBase, IdLoc);
4374 if (BaseType.isNull())
4375 return true;
4376
4377 TInfo = Context.CreateTypeSourceInfo(BaseType);
4380 if (!TL.isNull()) {
4381 TL.setNameLoc(IdLoc);
4384 }
4385
4386 R.clear();
4387 R.setLookupName(MemberOrBase);
4388 }
4389 }
4390
4391 if (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus20) {
4392 if (auto UnqualifiedBase = R.getAsSingle<ClassTemplateDecl>()) {
4393 auto *TempSpec = cast<TemplateSpecializationType>(
4394 UnqualifiedBase->getInjectedClassNameSpecialization());
4395 TemplateName TN = TempSpec->getTemplateName();
4396 for (auto const &Base : ClassDecl->bases()) {
4397 auto BaseTemplate =
4398 Base.getType()->getAs<TemplateSpecializationType>();
4399 if (BaseTemplate && Context.hasSameTemplateName(
4400 BaseTemplate->getTemplateName(), TN)) {
4401 Diag(IdLoc, diag::ext_unqualified_base_class)
4402 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4403 BaseType = Base.getType();
4404 break;
4405 }
4406 }
4407 }
4408 }
4409
4410 // If no results were found, try to correct typos.
4411 TypoCorrection Corr;
4412 MemInitializerValidatorCCC CCC(ClassDecl);
4413 if (R.empty() && BaseType.isNull() &&
4414 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
4415 CCC, CTK_ErrorRecovery, ClassDecl))) {
4417 // We have found a non-static data member with a similar
4418 // name to what was typed; complain and initialize that
4419 // member.
4420 diagnoseTypo(Corr,
4421 PDiag(diag::err_mem_init_not_member_or_class_suggest)
4422 << MemberOrBase << true);
4423 return BuildMemberInitializer(Member, Init, IdLoc);
4424 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
4425 const CXXBaseSpecifier *DirectBaseSpec;
4426 const CXXBaseSpecifier *VirtualBaseSpec;
4427 if (FindBaseInitializer(*this, ClassDecl,
4429 DirectBaseSpec, VirtualBaseSpec)) {
4430 // We have found a direct or virtual base class with a
4431 // similar name to what was typed; complain and initialize
4432 // that base class.
4433 diagnoseTypo(Corr,
4434 PDiag(diag::err_mem_init_not_member_or_class_suggest)
4435 << MemberOrBase << false,
4436 PDiag() /*Suppress note, we provide our own.*/);
4437
4438 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
4439 : VirtualBaseSpec;
4440 Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
4441 << BaseSpec->getType() << BaseSpec->getSourceRange();
4442
4443 TyD = Type;
4444 }
4445 }
4446 }
4447
4448 if (!TyD && BaseType.isNull()) {
4449 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
4450 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4451 return true;
4452 }
4453 }
4454
4455 if (BaseType.isNull()) {
4458 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
4459 TInfo = Context.CreateTypeSourceInfo(BaseType);
4461 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
4464 }
4465 }
4466
4467 if (!TInfo)
4468 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
4469
4470 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
4471}
4472
4475 SourceLocation IdLoc) {
4476 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
4477 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
4478 assert((DirectMember || IndirectMember) &&
4479 "Member must be a FieldDecl or IndirectFieldDecl");
4480
4482 return true;
4483
4484 if (Member->isInvalidDecl())
4485 return true;
4486
4487 MultiExprArg Args;
4488 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4489 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4490 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4491 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4492 } else {
4493 // Template instantiation doesn't reconstruct ParenListExprs for us.
4494 Args = Init;
4495 }
4496
4497 SourceRange InitRange = Init->getSourceRange();
4498
4499 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4500 // Can't check initialization for a member of dependent type or when
4501 // any of the arguments are type-dependent expressions.
4503 } else {
4504 bool InitList = false;
4505 if (isa<InitListExpr>(Init)) {
4506 InitList = true;
4507 Args = Init;
4508 }
4509
4510 // Initialize the member.
4511 InitializedEntity MemberEntity =
4512 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4513 : InitializedEntity::InitializeMember(IndirectMember,
4514 nullptr);
4515 InitializationKind Kind =
4517 IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4518 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4519 InitRange.getEnd());
4520
4521 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4522 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4523 nullptr);
4524 if (!MemberInit.isInvalid()) {
4525 // C++11 [class.base.init]p7:
4526 // The initialization of each base and member constitutes a
4527 // full-expression.
4528 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
4529 /*DiscardedValue*/ false);
4530 }
4531
4532 if (MemberInit.isInvalid()) {
4533 // Args were sensible expressions but we couldn't initialize the member
4534 // from them. Preserve them in a RecoveryExpr instead.
4535 Init = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,
4536 Member->getType())
4537 .get();
4538 if (!Init)
4539 return true;
4540 } else {
4541 Init = MemberInit.get();
4542 }
4543 }
4544
4545 if (DirectMember) {
4546 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4547 InitRange.getBegin(), Init,
4548 InitRange.getEnd());
4549 } else {
4550 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4551 InitRange.getBegin(), Init,
4552 InitRange.getEnd());
4553 }
4554}
4555
4558 CXXRecordDecl *ClassDecl) {
4559 SourceLocation NameLoc = TInfo->getTypeLoc().getSourceRange().getBegin();
4560 if (!LangOpts.CPlusPlus11)
4561 return Diag(NameLoc, diag::err_delegating_ctor)
4562 << TInfo->getTypeLoc().getSourceRange();
4563 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4564
4565 bool InitList = true;
4566 MultiExprArg Args = Init;
4567 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4568 InitList = false;
4569 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4570 }
4571
4572 SourceRange InitRange = Init->getSourceRange();
4573 // Initialize the object.
4575 QualType(ClassDecl->getTypeForDecl(), 0));
4576 InitializationKind Kind =
4578 NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4579 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4580 InitRange.getEnd());
4581 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4582 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4583 Args, nullptr);
4584 if (!DelegationInit.isInvalid()) {
4585 assert((DelegationInit.get()->containsErrors() ||
4586 cast<CXXConstructExpr>(DelegationInit.get())->getConstructor()) &&
4587 "Delegating constructor with no target?");
4588
4589 // C++11 [class.base.init]p7:
4590 // The initialization of each base and member constitutes a
4591 // full-expression.
4592 DelegationInit = ActOnFinishFullExpr(
4593 DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
4594 }
4595
4596 if (DelegationInit.isInvalid()) {
4597 DelegationInit =
4598 CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,
4599 QualType(ClassDecl->getTypeForDecl(), 0));
4600 if (DelegationInit.isInvalid())
4601 return true;
4602 } else {
4603 // If we are in a dependent context, template instantiation will
4604 // perform this type-checking again. Just save the arguments that we
4605 // received in a ParenListExpr.
4606 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4607 // of the information that we have about the base
4608 // initializer. However, deconstructing the ASTs is a dicey process,
4609 // and this approach is far more likely to get the corner cases right.
4611 DelegationInit = Init;
4612 }
4613
4614 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4615 DelegationInit.getAs<Expr>(),
4616 InitRange.getEnd());
4617}
4618
4621 Expr *Init, CXXRecordDecl *ClassDecl,
4622 SourceLocation EllipsisLoc) {
4623 SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getBeginLoc();
4624
4625 if (!BaseType->isDependentType() && !BaseType->isRecordType())
4626 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4627 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
4628
4629 // C++ [class.base.init]p2:
4630 // [...] Unless the mem-initializer-id names a nonstatic data
4631 // member of the constructor's class or a direct or virtual base
4632 // of that class, the mem-initializer is ill-formed. A
4633 // mem-initializer-list can initialize a base class using any
4634 // name that denotes that base class type.
4635
4636 // We can store the initializers in "as-written" form and delay analysis until
4637 // instantiation if the constructor is dependent. But not for dependent
4638 // (broken) code in a non-template! SetCtorInitializers does not expect this.
4640 (BaseType->isDependentType() || Init->isTypeDependent());
4641
4642 SourceRange InitRange = Init->getSourceRange();
4643 if (EllipsisLoc.isValid()) {
4644 // This is a pack expansion.
4645 if (!BaseType->containsUnexpandedParameterPack()) {
4646 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4647 << SourceRange(BaseLoc, InitRange.getEnd());
4648
4649 EllipsisLoc = SourceLocation();
4650 }
4651 } else {
4652 // Check for any unexpanded parameter packs.
4653 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4654 return true;
4655
4657 return true;
4658 }
4659
4660 // Check for direct and virtual base classes.
4661 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4662 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4663 if (!Dependent) {
4665 BaseType))
4666 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4667
4668 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4669 VirtualBaseSpec);
4670
4671 // C++ [base.class.init]p2:
4672 // Unless the mem-initializer-id names a nonstatic data member of the
4673 // constructor's class or a direct or virtual base of that class, the
4674 // mem-initializer is ill-formed.
4675 if (!DirectBaseSpec && !VirtualBaseSpec) {
4676 // If the class has any dependent bases, then it's possible that
4677 // one of those types will resolve to the same type as
4678 // BaseType. Therefore, just treat this as a dependent base
4679 // class initialization. FIXME: Should we try to check the
4680 // initialization anyway? It seems odd.
4681 if (ClassDecl->hasAnyDependentBases())
4682 Dependent = true;
4683 else
4684 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4685 << BaseType << Context.getTypeDeclType(ClassDecl)
4686 << BaseTInfo->getTypeLoc().getSourceRange();
4687 }
4688 }
4689
4690 if (Dependent) {
4692
4693 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4694 /*IsVirtual=*/false,
4695 InitRange.getBegin(), Init,
4696 InitRange.getEnd(), EllipsisLoc);
4697 }
4698
4699 // C++ [base.class.init]p2:
4700 // If a mem-initializer-id is ambiguous because it designates both
4701 // a direct non-virtual base class and an inherited virtual base
4702 // class, the mem-initializer is ill-formed.
4703 if (DirectBaseSpec && VirtualBaseSpec)
4704 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4705 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4706
4707 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4708 if (!BaseSpec)
4709 BaseSpec = VirtualBaseSpec;
4710
4711 // Initialize the base.
4712 bool InitList = true;
4713 MultiExprArg Args = Init;
4714 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4715 InitList = false;
4716 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4717 }
4718
4719 InitializedEntity BaseEntity =
4720 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4721 InitializationKind Kind =
4722 InitList ? InitializationKind::CreateDirectList(BaseLoc)
4723 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4724 InitRange.getEnd());
4725 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4726 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4727 if (!BaseInit.isInvalid()) {
4728 // C++11 [class.base.init]p7:
4729 // The initialization of each base and member constitutes a
4730 // full-expression.
4731 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
4732 /*DiscardedValue*/ false);
4733 }
4734
4735 if (BaseInit.isInvalid()) {
4736 BaseInit = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(),
4737 Args, BaseType);
4738 if (BaseInit.isInvalid())
4739 return true;
4740 } else {
4741 // If we are in a dependent context, template instantiation will
4742 // perform this type-checking again. Just save the arguments that we
4743 // received in a ParenListExpr.
4744 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4745 // of the information that we have about the base
4746 // initializer. However, deconstructing the ASTs is a dicey process,
4747 // and this approach is far more likely to get the corner cases right.
4749 BaseInit = Init;
4750 }
4751
4752 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4753 BaseSpec->isVirtual(),
4754 InitRange.getBegin(),
4755 BaseInit.getAs<Expr>(),
4756 InitRange.getEnd(), EllipsisLoc);
4757}
4758
4759// Create a static_cast<T&&>(expr).
4761 QualType TargetType =
4762 SemaRef.BuildReferenceType(E->getType(), /*SpelledAsLValue*/ false,
4764 SourceLocation ExprLoc = E->getBeginLoc();
4766 TargetType, ExprLoc);
4767
4768 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4769 SourceRange(ExprLoc, ExprLoc),
4770 E->getSourceRange()).get();
4771}
4772
4773/// ImplicitInitializerKind - How an implicit base or member initializer should
4774/// initialize its base or member.
4781
4782static bool
4784 ImplicitInitializerKind ImplicitInitKind,
4785 CXXBaseSpecifier *BaseSpec,
4786 bool IsInheritedVirtualBase,
4787 CXXCtorInitializer *&CXXBaseInit) {
4788 InitializedEntity InitEntity
4790 IsInheritedVirtualBase);
4791
4792 ExprResult BaseInit;
4793
4794 switch (ImplicitInitKind) {
4795 case IIK_Inherit:
4796 case IIK_Default: {
4797 InitializationKind InitKind
4798 = InitializationKind::CreateDefault(Constructor->getLocation());
4799 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, std::nullopt);
4800 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, std::nullopt);
4801 break;
4802 }
4803
4804 case IIK_Move:
4805 case IIK_Copy: {
4806 bool Moving = ImplicitInitKind == IIK_Move;
4807 ParmVarDecl *Param = Constructor->getParamDecl(0);
4808 QualType ParamType = Param->getType().getNonReferenceType();
4809
4810 Expr *CopyCtorArg =
4812 SourceLocation(), Param, false,
4813 Constructor->getLocation(), ParamType,
4814 VK_LValue, nullptr);
4815
4816 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4817
4818 // Cast to the base class to avoid ambiguities.
4819 QualType ArgTy =
4821 ParamType.getQualifiers());
4822
4823 if (Moving) {
4824 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4825 }
4826
4827 CXXCastPath BasePath;
4828 BasePath.push_back(BaseSpec);
4829 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4830 CK_UncheckedDerivedToBase,
4831 Moving ? VK_XValue : VK_LValue,
4832 &BasePath).get();
4833
4834 InitializationKind InitKind
4835 = InitializationKind::CreateDirect(Constructor->getLocation(),
4837 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4838 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4839 break;
4840 }
4841 }
4842
4843 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4844 if (BaseInit.isInvalid())
4845 return true;
484