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