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
13#include "TypeLocBuilder.h"
14#include "clang/AST/ASTConsumer.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/ASTMutationListener.h"
17#include "clang/AST/CXXInheritance.h"
18#include "clang/AST/CharUnits.h"
19#include "clang/AST/ComparisonCategories.h"
20#include "clang/AST/DeclCXX.h"
21#include "clang/AST/DeclTemplate.h"
22#include "clang/AST/DynamicRecursiveASTVisitor.h"
23#include "clang/AST/EvaluatedExprVisitor.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/ExprCXX.h"
26#include "clang/AST/RecordLayout.h"
27#include "clang/AST/StmtVisitor.h"
28#include "clang/AST/TypeLoc.h"
29#include "clang/AST/TypeOrdering.h"
30#include "clang/Basic/AttributeCommonInfo.h"
31#include "clang/Basic/PartialDiagnostic.h"
32#include "clang/Basic/Specifiers.h"
33#include "clang/Basic/TargetInfo.h"
34#include "clang/Lex/LiteralSupport.h"
35#include "clang/Lex/Preprocessor.h"
36#include "clang/Sema/CXXFieldCollector.h"
37#include "clang/Sema/DeclSpec.h"
38#include "clang/Sema/EnterExpressionEvaluationContext.h"
39#include "clang/Sema/Initialization.h"
40#include "clang/Sema/Lookup.h"
41#include "clang/Sema/Ownership.h"
42#include "clang/Sema/ParsedTemplate.h"
43#include "clang/Sema/Scope.h"
44#include "clang/Sema/ScopeInfo.h"
45#include "clang/Sema/SemaCUDA.h"
46#include "clang/Sema/SemaInternal.h"
47#include "clang/Sema/SemaObjC.h"
48#include "clang/Sema/SemaOpenMP.h"
49#include "clang/Sema/Template.h"
50#include "clang/Sema/TemplateDeduction.h"
51#include "llvm/ADT/ArrayRef.h"
52#include "llvm/ADT/STLExtras.h"
53#include "llvm/ADT/StringExtras.h"
54#include "llvm/Support/ConvertUTF.h"
55#include "llvm/Support/SaveAndRestore.h"
56#include <map>
57#include <optional>
58#include <set>
59
60using namespace clang;
61
62//===----------------------------------------------------------------------===//
63// CheckDefaultArgumentVisitor
64//===----------------------------------------------------------------------===//
65
66namespace {
67/// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
68/// the default argument of a parameter to determine whether it
69/// contains any ill-formed subexpressions. For example, this will
70/// diagnose the use of local variables or parameters within the
71/// default argument expression.
72class CheckDefaultArgumentVisitor
73 : public ConstStmtVisitor<CheckDefaultArgumentVisitor, bool> {
74 Sema &S;
75 const Expr *DefaultArg;
76
77public:
78 CheckDefaultArgumentVisitor(Sema &S, const Expr *DefaultArg)
79 : S(S), DefaultArg(DefaultArg) {}
80
81 bool VisitExpr(const Expr *Node);
82 bool VisitDeclRefExpr(const DeclRefExpr *DRE);
83 bool VisitCXXThisExpr(const CXXThisExpr *ThisE);
84 bool VisitLambdaExpr(const LambdaExpr *Lambda);
85 bool VisitPseudoObjectExpr(const PseudoObjectExpr *POE);
86 bool VisitCoawaitExpr(const CoawaitExpr *E);
87 bool VisitCoyieldExpr(const CoyieldExpr *E);
88};
89
90/// VisitExpr - Visit all of the children of this expression.
91bool CheckDefaultArgumentVisitor::VisitExpr(const Expr *Node) {
92 bool IsInvalid = false;
93 for (const Stmt *SubStmt : Node->children())
94 if (SubStmt)
95 IsInvalid |= Visit(S: SubStmt);
96 return IsInvalid;
97}
98
99/// VisitDeclRefExpr - Visit a reference to a declaration, to
100/// determine whether this declaration can be used in the default
101/// argument expression.
102bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(const DeclRefExpr *DRE) {
103 const ValueDecl *Decl = DRE->getDecl();
104
105 if (!isa<VarDecl, BindingDecl>(Val: Decl))
106 return false;
107
108 if (const auto *Param = dyn_cast<ParmVarDecl>(Val: Decl)) {
109 // C++ [dcl.fct.default]p9:
110 // [...] parameters of a function shall not be used in default
111 // argument expressions, even if they are not evaluated. [...]
112 //
113 // C++17 [dcl.fct.default]p9 (by CWG 2082):
114 // [...] A parameter shall not appear as a potentially-evaluated
115 // expression in a default argument. [...]
116 //
117 if (DRE->isNonOdrUse() != NOUR_Unevaluated)
118 return S.Diag(Loc: DRE->getBeginLoc(),
119 DiagID: diag::err_param_default_argument_references_param)
120 << Param->getDeclName() << DefaultArg->getSourceRange();
121 } else if (auto *VD = Decl->getPotentiallyDecomposedVarDecl()) {
122 // C++ [dcl.fct.default]p7:
123 // Local variables shall not be used in default argument
124 // expressions.
125 //
126 // C++17 [dcl.fct.default]p7 (by CWG 2082):
127 // A local variable shall not appear as a potentially-evaluated
128 // expression in a default argument.
129 //
130 // C++20 [dcl.fct.default]p7 (DR as part of P0588R1, see also CWG 2346):
131 // Note: A local variable cannot be odr-used (6.3) in a default
132 // argument.
133 //
134 if (VD->isLocalVarDecl() && !DRE->isNonOdrUse())
135 return S.Diag(Loc: DRE->getBeginLoc(),
136 DiagID: diag::err_param_default_argument_references_local)
137 << Decl << DefaultArg->getSourceRange();
138 }
139 return false;
140}
141
142/// VisitCXXThisExpr - Visit a C++ "this" expression.
143bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(const CXXThisExpr *ThisE) {
144 // C++ [dcl.fct.default]p8:
145 // The keyword this shall not be used in a default argument of a
146 // member function.
147 return S.Diag(Loc: ThisE->getBeginLoc(),
148 DiagID: diag::err_param_default_argument_references_this)
149 << ThisE->getSourceRange();
150}
151
152bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(
153 const PseudoObjectExpr *POE) {
154 bool Invalid = false;
155 for (const Expr *E : POE->semantics()) {
156 // Look through bindings.
157 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Val: E)) {
158 E = OVE->getSourceExpr();
159 assert(E && "pseudo-object binding without source expression?");
160 }
161
162 Invalid |= Visit(S: E);
163 }
164 return Invalid;
165}
166
167bool CheckDefaultArgumentVisitor::VisitLambdaExpr(const LambdaExpr *Lambda) {
168 // [expr.prim.lambda.capture]p9
169 // a lambda-expression appearing in a default argument cannot implicitly or
170 // explicitly capture any local entity. Such a lambda-expression can still
171 // have an init-capture if any full-expression in its initializer satisfies
172 // the constraints of an expression appearing in a default argument.
173 bool Invalid = false;
174 for (const LambdaCapture &LC : Lambda->captures()) {
175 if (!Lambda->isInitCapture(Capture: &LC))
176 return S.Diag(Loc: LC.getLocation(), DiagID: diag::err_lambda_capture_default_arg);
177 // Init captures are always VarDecl.
178 auto *D = cast<VarDecl>(Val: LC.getCapturedVar());
179 Invalid |= Visit(S: D->getInit());
180 }
181 return Invalid;
182}
183
184bool CheckDefaultArgumentVisitor::VisitCoawaitExpr(const CoawaitExpr *E) {
185 // [expr.await] An await-expression shall not appear in a default argument.
186 // Note that this is generally diagnosed by isValidCoroutineContext,
187 // however isValidCoroutineContext misses default argument in nested
188 // function declarations.
189 S.Diag(Loc: E->getBeginLoc(), DiagID: diag::err_coroutine_outside_function)
190 << "co_await" << E->getSourceRange();
191 return true;
192}
193
194bool CheckDefaultArgumentVisitor::VisitCoyieldExpr(const CoyieldExpr *E) {
195 S.Diag(Loc: E->getBeginLoc(), DiagID: diag::err_coroutine_outside_function)
196 << "co_yield" << E->getSourceRange();
197 return true;
198}
199
200} // namespace
201
202void
203Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
204 const CXXMethodDecl *Method) {
205 // If we have an MSAny spec already, don't bother.
206 if (!Method || ComputedEST == EST_MSAny)
207 return;
208
209 const FunctionProtoType *Proto
210 = Method->getType()->getAs<FunctionProtoType>();
211 Proto = Self->ResolveExceptionSpec(Loc: CallLoc, FPT: Proto);
212 if (!Proto)
213 return;
214
215 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
216
217 // If we have a throw-all spec at this point, ignore the function.
218 if (ComputedEST == EST_None)
219 return;
220
221 if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
222 EST = EST_BasicNoexcept;
223
224 switch (EST) {
225 case EST_Unparsed:
226 case EST_Uninstantiated:
227 case EST_Unevaluated:
228 llvm_unreachable("should not see unresolved exception specs here");
229
230 // If this function can throw any exceptions, make a note of that.
231 case EST_MSAny:
232 case EST_None:
233 // FIXME: Whichever we see last of MSAny and None determines our result.
234 // We should make a consistent, order-independent choice here.
235 ClearExceptions();
236 ComputedEST = EST;
237 return;
238 case EST_NoexceptFalse:
239 ClearExceptions();
240 ComputedEST = EST_None;
241 return;
242 // FIXME: If the call to this decl is using any of its default arguments, we
243 // need to search them for potentially-throwing calls.
244 // If this function has a basic noexcept, it doesn't affect the outcome.
245 case EST_BasicNoexcept:
246 case EST_NoexceptTrue:
247 case EST_NoThrow:
248 return;
249 // If we're still at noexcept(true) and there's a throw() callee,
250 // change to that specification.
251 case EST_DynamicNone:
252 if (ComputedEST == EST_BasicNoexcept)
253 ComputedEST = EST_DynamicNone;
254 return;
255 case EST_DependentNoexcept:
256 llvm_unreachable(
257 "should not generate implicit declarations for dependent cases");
258 case EST_Dynamic:
259 break;
260 }
261 assert(EST == EST_Dynamic && "EST case not considered earlier.");
262 assert(ComputedEST != EST_None &&
263 "Shouldn't collect exceptions when throw-all is guaranteed.");
264 ComputedEST = EST_Dynamic;
265 // Record the exceptions in this function's exception specification.
266 for (const auto &E : Proto->exceptions())
267 if (ExceptionsSeen.insert(Ptr: Self->Context.getCanonicalType(T: E)).second)
268 Exceptions.push_back(Elt: E);
269}
270
271void Sema::ImplicitExceptionSpecification::CalledStmt(Stmt *S) {
272 if (!S || ComputedEST == EST_MSAny)
273 return;
274
275 // FIXME:
276 //
277 // C++0x [except.spec]p14:
278 // [An] implicit exception-specification specifies the type-id T if and
279 // only if T is allowed by the exception-specification of a function directly
280 // invoked by f's implicit definition; f shall allow all exceptions if any
281 // function it directly invokes allows all exceptions, and f shall allow no
282 // exceptions if every function it directly invokes allows no exceptions.
283 //
284 // Note in particular that if an implicit exception-specification is generated
285 // for a function containing a throw-expression, that specification can still
286 // be noexcept(true).
287 //
288 // Note also that 'directly invoked' is not defined in the standard, and there
289 // is no indication that we should only consider potentially-evaluated calls.
290 //
291 // Ultimately we should implement the intent of the standard: the exception
292 // specification should be the set of exceptions which can be thrown by the
293 // implicit definition. For now, we assume that any non-nothrow expression can
294 // throw any exception.
295
296 if (Self->canThrow(E: S))
297 ComputedEST = EST_None;
298}
299
300ExprResult Sema::ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
301 SourceLocation EqualLoc) {
302 if (RequireCompleteType(Loc: Param->getLocation(), T: Param->getType(),
303 DiagID: diag::err_typecheck_decl_incomplete_type))
304 return true;
305
306 // C++ [dcl.fct.default]p5
307 // A default argument expression is implicitly converted (clause
308 // 4) to the parameter type. The default argument expression has
309 // the same semantic constraints as the initializer expression in
310 // a declaration of a variable of the parameter type, using the
311 // copy-initialization semantics (8.5).
312 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
313 Parm: Param);
314 InitializationKind Kind = InitializationKind::CreateCopy(InitLoc: Param->getLocation(),
315 EqualLoc);
316 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
317 ExprResult Result = InitSeq.Perform(S&: *this, Entity, Kind, Args: Arg);
318 if (Result.isInvalid())
319 return true;
320 Arg = Result.getAs<Expr>();
321
322 CheckCompletedExpr(E: Arg, CheckLoc: EqualLoc);
323 Arg = MaybeCreateExprWithCleanups(SubExpr: Arg);
324
325 return Arg;
326}
327
328void Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
329 SourceLocation EqualLoc) {
330 // Add the default argument to the parameter
331 Param->setDefaultArg(Arg);
332
333 // We have already instantiated this parameter; provide each of the
334 // instantiations with the uninstantiated default argument.
335 UnparsedDefaultArgInstantiationsMap::iterator InstPos
336 = UnparsedDefaultArgInstantiations.find(Val: Param);
337 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
338 for (auto &Instantiation : InstPos->second)
339 Instantiation->setUninstantiatedDefaultArg(Arg);
340
341 // We're done tracking this parameter's instantiations.
342 UnparsedDefaultArgInstantiations.erase(I: InstPos);
343 }
344}
345
346void
347Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
348 Expr *DefaultArg) {
349 if (!param || !DefaultArg)
350 return;
351
352 ParmVarDecl *Param = cast<ParmVarDecl>(Val: param);
353 UnparsedDefaultArgLocs.erase(Val: Param);
354
355 // Default arguments are only permitted in C++
356 if (!getLangOpts().CPlusPlus) {
357 Diag(Loc: EqualLoc, DiagID: diag::err_param_default_argument)
358 << DefaultArg->getSourceRange();
359 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
360 }
361
362 // C++11 [dcl.fct.default]p3
363 // A default argument expression [...] shall not be specified for a
364 // parameter pack.
365 //
366 // Check this before looking for unexpanded parameter packs in DefaultArg:
367 // if DefaultArg references a pack from an enclosing lambda/block, that
368 // check would (incorrectly) mark the lambda as containing an unexpanded
369 // pack that never actually appears in the final AST once we discard
370 // DefaultArg below.
371 if (Param->isParameterPack()) {
372 Diag(Loc: EqualLoc, DiagID: diag::err_param_default_argument_on_parameter_pack)
373 << DefaultArg->getSourceRange();
374 // Recover by discarding the default argument.
375 Param->setDefaultArg(nullptr);
376 return;
377 }
378
379 // Check for unexpanded parameter packs.
380 if (DiagnoseUnexpandedParameterPack(E: DefaultArg, UPPC: UPPC_DefaultArgument))
381 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
382
383 ExprResult Result = ConvertParamDefaultArgument(Param, Arg: DefaultArg, EqualLoc);
384 if (Result.isInvalid())
385 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
386
387 DefaultArg = Result.getAs<Expr>();
388
389 // Check that the default argument is well-formed
390 CheckDefaultArgumentVisitor DefaultArgChecker(*this, DefaultArg);
391 if (DefaultArgChecker.Visit(S: DefaultArg))
392 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
393
394 SetParamDefaultArgument(Param, Arg: DefaultArg, EqualLoc);
395}
396
397void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
398 SourceLocation EqualLoc,
399 SourceLocation ArgLoc) {
400 if (!param)
401 return;
402
403 ParmVarDecl *Param = cast<ParmVarDecl>(Val: param);
404 Param->setUnparsedDefaultArg();
405 UnparsedDefaultArgLocs[Param] = ArgLoc;
406}
407
408void Sema::ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc,
409 Expr *DefaultArg) {
410 if (!param)
411 return;
412
413 ParmVarDecl *Param = cast<ParmVarDecl>(Val: param);
414 Param->setInvalidDecl();
415 UnparsedDefaultArgLocs.erase(Val: Param);
416 ExprResult RE;
417 if (DefaultArg) {
418 RE = CreateRecoveryExpr(Begin: EqualLoc, End: DefaultArg->getEndLoc(), SubExprs: {DefaultArg},
419 T: Param->getType().getNonReferenceType());
420 } else {
421 RE = CreateRecoveryExpr(Begin: EqualLoc, End: EqualLoc, SubExprs: {},
422 T: Param->getType().getNonReferenceType());
423 }
424 Param->setDefaultArg(RE.get());
425}
426
427void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
428 // C++ [dcl.fct.default]p3
429 // A default argument expression shall be specified only in the
430 // parameter-declaration-clause of a function declaration or in a
431 // template-parameter (14.1). It shall not be specified for a
432 // parameter pack. If it is specified in a
433 // parameter-declaration-clause, it shall not occur within a
434 // declarator or abstract-declarator of a parameter-declaration.
435 bool MightBeFunction = D.isFunctionDeclarationContext();
436 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
437 DeclaratorChunk &chunk = D.getTypeObject(i);
438 if (chunk.Kind == DeclaratorChunk::Function) {
439 if (MightBeFunction) {
440 // This is a function declaration. It can have default arguments, but
441 // keep looking in case its return type is a function type with default
442 // arguments.
443 MightBeFunction = false;
444 continue;
445 }
446 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
447 ++argIdx) {
448 ParmVarDecl *Param = cast<ParmVarDecl>(Val: chunk.Fun.Params[argIdx].Param);
449 if (Param->hasUnparsedDefaultArg()) {
450 std::unique_ptr<CachedTokens> Toks =
451 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
452 SourceRange SR;
453 if (Toks->size() > 1)
454 SR = SourceRange((*Toks)[1].getLocation(),
455 Toks->back().getLocation());
456 else
457 SR = UnparsedDefaultArgLocs[Param];
458 Diag(Loc: Param->getLocation(), DiagID: diag::err_param_default_argument_nonfunc)
459 << SR;
460 } else if (Param->getDefaultArg()) {
461 Diag(Loc: Param->getLocation(), DiagID: diag::err_param_default_argument_nonfunc)
462 << Param->getDefaultArg()->getSourceRange();
463 Param->setDefaultArg(nullptr);
464 }
465 }
466 } else if (chunk.Kind != DeclaratorChunk::Paren) {
467 MightBeFunction = false;
468 }
469 }
470}
471
472static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
473 return llvm::any_of(Range: FD->parameters(), P: [](ParmVarDecl *P) {
474 return P->hasDefaultArg() && !P->hasInheritedDefaultArg();
475 });
476}
477
478bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
479 Scope *S) {
480 bool Invalid = false;
481
482 // The declaration context corresponding to the scope is the semantic
483 // parent, unless this is a local function declaration, in which case
484 // it is that surrounding function.
485 DeclContext *ScopeDC = New->isLocalExternDecl()
486 ? New->getLexicalDeclContext()
487 : New->getDeclContext();
488
489 // Find the previous declaration for the purpose of default arguments.
490 FunctionDecl *PrevForDefaultArgs = Old;
491 for (/**/; PrevForDefaultArgs;
492 // Don't bother looking back past the latest decl if this is a local
493 // extern declaration; nothing else could work.
494 PrevForDefaultArgs = New->isLocalExternDecl()
495 ? nullptr
496 : PrevForDefaultArgs->getPreviousDecl()) {
497 // Ignore hidden declarations.
498 if (!LookupResult::isVisible(SemaRef&: *this, D: PrevForDefaultArgs))
499 continue;
500
501 if (S && !isDeclInScope(D: PrevForDefaultArgs, Ctx: ScopeDC, S) &&
502 !New->isCXXClassMember()) {
503 // Ignore default arguments of old decl if they are not in
504 // the same scope and this is not an out-of-line definition of
505 // a member function.
506 continue;
507 }
508
509 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
510 // If only one of these is a local function declaration, then they are
511 // declared in different scopes, even though isDeclInScope may think
512 // they're in the same scope. (If both are local, the scope check is
513 // sufficient, and if neither is local, then they are in the same scope.)
514 continue;
515 }
516
517 if (PrevForDefaultArgs->getFriendObjectKind()) {
518 // Don't inherit default arguments from a friend declaration. It's invalid
519 // to redeclare such a function at all if it owns the default arguments;
520 // we check for that later. Otherwise, it's not the declaration that we're
521 // inheriting them from.
522 continue;
523 }
524
525 // We found the right previous declaration.
526 break;
527 }
528
529 // C++ [dcl.fct.default]p4:
530 // For non-template functions, default arguments can be added in
531 // later declarations of a function in the same
532 // scope. Declarations in different scopes have completely
533 // distinct sets of default arguments. That is, declarations in
534 // inner scopes do not acquire default arguments from
535 // declarations in outer scopes, and vice versa. In a given
536 // function declaration, all parameters subsequent to a
537 // parameter with a default argument shall have default
538 // arguments supplied in this or previous declarations. A
539 // default argument shall not be redefined by a later
540 // declaration (not even to the same value).
541 //
542 // C++ [dcl.fct.default]p6:
543 // Except for member functions of class templates, the default arguments
544 // in a member function definition that appears outside of the class
545 // definition are added to the set of default arguments provided by the
546 // member function declaration in the class definition.
547 for (unsigned p = 0, NumParams = PrevForDefaultArgs
548 ? PrevForDefaultArgs->getNumParams()
549 : 0;
550 p < NumParams; ++p) {
551 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(i: p);
552 ParmVarDecl *NewParam = New->getParamDecl(i: p);
553
554 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
555 bool NewParamHasDfl = NewParam->hasDefaultArg();
556
557 if (OldParamHasDfl && NewParamHasDfl) {
558 unsigned DiagDefaultParamID =
559 diag::err_param_default_argument_redefinition;
560
561 // MSVC accepts that default parameters be redefined for member functions
562 // of template class. The new default parameter's value is ignored.
563 Invalid = true;
564 if (getLangOpts().MicrosoftExt) {
565 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: New);
566 if (MD && MD->getParent()->getDescribedClassTemplate()) {
567 // Merge the old default argument into the new parameter.
568 NewParam->setHasInheritedDefaultArg();
569 if (OldParam->hasUninstantiatedDefaultArg())
570 NewParam->setUninstantiatedDefaultArg(
571 OldParam->getUninstantiatedDefaultArg());
572 else
573 NewParam->setDefaultArg(OldParam->getInit());
574 DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
575 Invalid = false;
576 }
577 }
578
579 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
580 // hint here. Alternatively, we could walk the type-source information
581 // for NewParam to find the last source location in the type... but it
582 // isn't worth the effort right now. This is the kind of test case that
583 // is hard to get right:
584 // int f(int);
585 // void g(int (*fp)(int) = f);
586 // void g(int (*fp)(int) = &f);
587 Diag(Loc: NewParam->getLocation(), DiagID: DiagDefaultParamID)
588 << NewParam->getDefaultArgRange();
589
590 // Look for the function declaration where the default argument was
591 // actually written, which may be a declaration prior to Old.
592 for (auto Older = PrevForDefaultArgs;
593 OldParam->hasInheritedDefaultArg(); /**/) {
594 Older = Older->getPreviousDecl();
595 OldParam = Older->getParamDecl(i: p);
596 }
597
598 Diag(Loc: OldParam->getLocation(), DiagID: diag::note_previous_definition)
599 << OldParam->getDefaultArgRange();
600 } else if (OldParamHasDfl) {
601 // Merge the old default argument into the new parameter unless the new
602 // function is a friend declaration in a template class. In the latter
603 // case the default arguments will be inherited when the friend
604 // declaration will be instantiated.
605 if (New->getFriendObjectKind() == Decl::FOK_None ||
606 !New->getLexicalDeclContext()->isDependentContext()) {
607 // It's important to use getInit() here; getDefaultArg()
608 // strips off any top-level ExprWithCleanups.
609 NewParam->setHasInheritedDefaultArg();
610 if (OldParam->hasUnparsedDefaultArg())
611 NewParam->setUnparsedDefaultArg();
612 else if (OldParam->hasUninstantiatedDefaultArg())
613 NewParam->setUninstantiatedDefaultArg(
614 OldParam->getUninstantiatedDefaultArg());
615 else
616 NewParam->setDefaultArg(OldParam->getInit());
617 }
618 } else if (NewParamHasDfl) {
619 if (New->getDescribedFunctionTemplate()) {
620 // Paragraph 4, quoted above, only applies to non-template functions.
621 Diag(Loc: NewParam->getLocation(),
622 DiagID: diag::err_param_default_argument_template_redecl)
623 << NewParam->getDefaultArgRange();
624 Diag(Loc: PrevForDefaultArgs->getLocation(),
625 DiagID: diag::note_template_prev_declaration)
626 << false;
627 } else if (New->getTemplateSpecializationKind()
628 != TSK_ImplicitInstantiation &&
629 New->getTemplateSpecializationKind() != TSK_Undeclared) {
630 // C++ [temp.expr.spec]p21:
631 // Default function arguments shall not be specified in a declaration
632 // or a definition for one of the following explicit specializations:
633 // - the explicit specialization of a function template;
634 // - the explicit specialization of a member function template;
635 // - the explicit specialization of a member function of a class
636 // template where the class template specialization to which the
637 // member function specialization belongs is implicitly
638 // instantiated.
639 Diag(Loc: NewParam->getLocation(), DiagID: diag::err_template_spec_default_arg)
640 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
641 << New->getDeclName()
642 << NewParam->getDefaultArgRange();
643 } else if (New->getDeclContext()->isDependentContext()) {
644 // C++ [dcl.fct.default]p6 (DR217):
645 // Default arguments for a member function of a class template shall
646 // be specified on the initial declaration of the member function
647 // within the class template.
648 //
649 // Reading the tea leaves a bit in DR217 and its reference to DR205
650 // leads me to the conclusion that one cannot add default function
651 // arguments for an out-of-line definition of a member function of a
652 // dependent type.
653 int WhichKind = 2;
654 if (CXXRecordDecl *Record
655 = dyn_cast<CXXRecordDecl>(Val: New->getDeclContext())) {
656 if (Record->getDescribedClassTemplate())
657 WhichKind = 0;
658 else if (isa<ClassTemplatePartialSpecializationDecl>(Val: Record))
659 WhichKind = 1;
660 else
661 WhichKind = 2;
662 }
663
664 Diag(Loc: NewParam->getLocation(),
665 DiagID: diag::err_param_default_argument_member_template_redecl)
666 << WhichKind
667 << NewParam->getDefaultArgRange();
668 }
669 }
670 }
671
672 // DR1344: If a default argument is added outside a class definition and that
673 // default argument makes the function a special member function, the program
674 // is ill-formed. This can only happen for constructors.
675 if (isa<CXXConstructorDecl>(Val: New) &&
676 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
677 CXXSpecialMemberKind NewSM =
678 cast<CXXMethodDecl>(Val: New)->getSpecialMemberKind(),
679 OldSM =
680 cast<CXXMethodDecl>(Val: Old)->getSpecialMemberKind();
681 if (NewSM != OldSM) {
682 auto It = llvm::find_if(Range: New->parameters(), P: [](const ParmVarDecl *P) {
683 return P->hasDefaultArg();
684 });
685 assert(It != New->param_end());
686 ParmVarDecl *NewParam = *It;
687 Diag(Loc: NewParam->getLocation(), DiagID: diag::err_default_arg_makes_ctor_special)
688 << NewParam->getDefaultArgRange() << NewSM;
689 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
690 }
691 }
692
693 const FunctionDecl *Def;
694 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
695 // template has a constexpr specifier then all its declarations shall
696 // contain the constexpr specifier.
697 if (New->getConstexprKind() != Old->getConstexprKind()) {
698 Diag(Loc: New->getLocation(), DiagID: diag::err_constexpr_redecl_mismatch)
699 << New << static_cast<int>(New->getConstexprKind())
700 << static_cast<int>(Old->getConstexprKind());
701 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
702 Invalid = true;
703 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
704 Old->isDefined(Definition&: Def) &&
705 // If a friend function is inlined but does not have 'inline'
706 // specifier, it is a definition. Do not report attribute conflict
707 // in this case, redefinition will be diagnosed later.
708 (New->isInlineSpecified() ||
709 New->getFriendObjectKind() == Decl::FOK_None)) {
710 // C++11 [dcl.fcn.spec]p4:
711 // If the definition of a function appears in a translation unit before its
712 // first declaration as inline, the program is ill-formed.
713 Diag(Loc: New->getLocation(), DiagID: diag::err_inline_decl_follows_def) << New;
714 Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
715 Invalid = true;
716 }
717
718 // C++17 [temp.deduct.guide]p3:
719 // Two deduction guide declarations in the same translation unit
720 // for the same class template shall not have equivalent
721 // parameter-declaration-clauses.
722 if (isa<CXXDeductionGuideDecl>(Val: New) &&
723 !New->isFunctionTemplateSpecialization() && isVisible(D: Old)) {
724 Diag(Loc: New->getLocation(), DiagID: diag::err_deduction_guide_redeclared);
725 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
726 }
727
728 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
729 // argument expression, that declaration shall be a definition and shall be
730 // the only declaration of the function or function template in the
731 // translation unit.
732 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
733 functionDeclHasDefaultArgument(FD: Old)) {
734 Diag(Loc: New->getLocation(), DiagID: diag::err_friend_decl_with_def_arg_redeclared);
735 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
736 Invalid = true;
737 }
738
739 // C++11 [temp.friend]p4 (DR329):
740 // When a function is defined in a friend function declaration in a class
741 // template, the function is instantiated when the function is odr-used.
742 // The same restrictions on multiple declarations and definitions that
743 // apply to non-template function declarations and definitions also apply
744 // to these implicit definitions.
745 const FunctionDecl *OldDefinition = nullptr;
746 if (New->isThisDeclarationInstantiatedFromAFriendDefinition() &&
747 Old->isDefined(Definition&: OldDefinition, CheckForPendingFriendDefinition: true))
748 CheckForFunctionRedefinition(FD: New, EffectiveDefinition: OldDefinition);
749
750 return Invalid;
751}
752
753void Sema::DiagPlaceholderVariableDefinition(SourceLocation Loc) {
754 Diag(Loc, DiagID: getLangOpts().CPlusPlus26
755 ? diag::warn_cxx23_placeholder_var_definition
756 : diag::ext_placeholder_var_definition);
757}
758
759NamedDecl *
760Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
761 MultiTemplateParamsArg TemplateParamLists) {
762 assert(D.isDecompositionDeclarator());
763 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
764
765 // The syntax only allows a decomposition declarator as a simple-declaration,
766 // a for-range-declaration, or a condition in Clang, but we parse it in more
767 // cases than that.
768 if (!D.mayHaveDecompositionDeclarator()) {
769 Diag(Loc: Decomp.getLSquareLoc(), DiagID: diag::err_decomp_decl_context)
770 << Decomp.getSourceRange();
771 return nullptr;
772 }
773
774 if (!TemplateParamLists.empty()) {
775 // C++17 [temp]/1:
776 // A template defines a family of class, functions, or variables, or an
777 // alias for a family of types.
778 //
779 // Structured bindings are not included.
780 Diag(Loc: TemplateParamLists.front()->getTemplateLoc(),
781 DiagID: diag::err_decomp_decl_template);
782 return nullptr;
783 }
784
785 unsigned DiagID;
786 if (!getLangOpts().CPlusPlus17)
787 DiagID = diag::compat_pre_cxx17_decomp_decl;
788 else if (D.getContext() == DeclaratorContext::Condition)
789 DiagID = getLangOpts().CPlusPlus26
790 ? diag::compat_cxx26_decomp_decl_cond
791 : diag::compat_pre_cxx26_decomp_decl_cond;
792 else
793 DiagID = diag::compat_cxx17_decomp_decl;
794
795 Diag(Loc: Decomp.getLSquareLoc(), DiagID) << Decomp.getSourceRange();
796
797 // The semantic context is always just the current context.
798 DeclContext *const DC = CurContext;
799
800 // C++17 [dcl.dcl]/8:
801 // The decl-specifier-seq shall contain only the type-specifier auto
802 // and cv-qualifiers.
803 // C++20 [dcl.dcl]/8:
804 // If decl-specifier-seq contains any decl-specifier other than static,
805 // thread_local, auto, or cv-qualifiers, the program is ill-formed.
806 // C++23 [dcl.pre]/6:
807 // Each decl-specifier in the decl-specifier-seq shall be static,
808 // thread_local, auto (9.2.9.6 [dcl.spec.auto]), or a cv-qualifier.
809 // C++23 [dcl.pre]/7:
810 // Each decl-specifier in the decl-specifier-seq shall be constexpr,
811 // constinit, static, thread_local, auto, or a cv-qualifier
812 auto &DS = D.getDeclSpec();
813 auto DiagBadSpecifier = [&](StringRef Name, SourceLocation Loc) {
814 Diag(Loc, DiagID: diag::err_decomp_decl_spec) << Name;
815 };
816
817 auto DiagCpp20Specifier = [&](StringRef Name, SourceLocation Loc) {
818 DiagCompat(Loc, CompatDiagId: diag_compat::decomp_decl_spec) << Name;
819 };
820
821 if (auto SCS = DS.getStorageClassSpec()) {
822 if (SCS == DeclSpec::SCS_static)
823 DiagCpp20Specifier(DeclSpec::getSpecifierName(S: SCS),
824 DS.getStorageClassSpecLoc());
825 else
826 DiagBadSpecifier(DeclSpec::getSpecifierName(S: SCS),
827 DS.getStorageClassSpecLoc());
828 }
829 if (auto TSCS = DS.getThreadStorageClassSpec())
830 DiagCpp20Specifier(DeclSpec::getSpecifierName(S: TSCS),
831 DS.getThreadStorageClassSpecLoc());
832
833 if (DS.isInlineSpecified())
834 DiagBadSpecifier("inline", DS.getInlineSpecLoc());
835
836 if (ConstexprSpecKind ConstexprSpec = DS.getConstexprSpecifier();
837 ConstexprSpec != ConstexprSpecKind::Unspecified) {
838 if (ConstexprSpec == ConstexprSpecKind::Consteval ||
839 !getLangOpts().CPlusPlus26)
840 DiagBadSpecifier(DeclSpec::getSpecifierName(C: ConstexprSpec),
841 DS.getConstexprSpecLoc());
842 }
843
844 // We can't recover from it being declared as a typedef.
845 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
846 return nullptr;
847
848 // C++2a [dcl.struct.bind]p1:
849 // A cv that includes volatile is deprecated
850 if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) &&
851 getLangOpts().CPlusPlus20)
852 Diag(Loc: DS.getVolatileSpecLoc(),
853 DiagID: diag::warn_deprecated_volatile_structured_binding);
854
855 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
856 QualType R = TInfo->getType();
857
858 if (DiagnoseUnexpandedParameterPack(Loc: D.getIdentifierLoc(), T: TInfo,
859 UPPC: UPPC_DeclarationType))
860 D.setInvalidType();
861
862 // The syntax only allows a single ref-qualifier prior to the decomposition
863 // declarator. No other declarator chunks are permitted. Also check the type
864 // specifier here.
865 if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
866 D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
867 (D.getNumTypeObjects() == 1 &&
868 D.getTypeObject(i: 0).Kind != DeclaratorChunk::Reference)) {
869 Diag(Loc: Decomp.getLSquareLoc(),
870 DiagID: (D.hasGroupingParens() ||
871 (D.getNumTypeObjects() &&
872 D.getTypeObject(i: 0).Kind == DeclaratorChunk::Paren))
873 ? diag::err_decomp_decl_parens
874 : diag::err_decomp_decl_type)
875 << R;
876
877 // In most cases, there's no actual problem with an explicitly-specified
878 // type, but a function type won't work here, and ActOnVariableDeclarator
879 // shouldn't be called for such a type.
880 if (R->isFunctionType())
881 D.setInvalidType();
882 }
883
884 // Constrained auto is prohibited by [decl.pre]p6, so check that here.
885 if (DS.isConstrainedAuto()) {
886 TemplateIdAnnotation *TemplRep = DS.getRepAsTemplateId();
887 assert(TemplRep->Kind == TNK_Concept_template &&
888 "No other template kind should be possible for a constrained auto");
889
890 SourceRange TemplRange{TemplRep->TemplateNameLoc,
891 TemplRep->RAngleLoc.isValid()
892 ? TemplRep->RAngleLoc
893 : TemplRep->TemplateNameLoc};
894 Diag(Loc: TemplRep->TemplateNameLoc, DiagID: diag::err_decomp_decl_constraint)
895 << TemplRange << FixItHint::CreateRemoval(RemoveRange: TemplRange);
896 }
897
898 // Build the BindingDecls.
899 SmallVector<BindingDecl*, 8> Bindings;
900
901 // Build the BindingDecls.
902 for (auto &B : D.getDecompositionDeclarator().bindings()) {
903 // Check for name conflicts.
904 DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
905 IdentifierInfo *VarName = B.Name;
906 assert(VarName && "Cannot have an unnamed binding declaration");
907
908 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
909 RedeclarationKind::ForVisibleRedeclaration);
910 LookupName(R&: Previous, S,
911 /*CreateBuiltins*/AllowBuiltinCreation: DC->getRedeclContext()->isTranslationUnit());
912
913 // It's not permitted to shadow a template parameter name.
914 if (Previous.isSingleResult() &&
915 Previous.getFoundDecl()->isTemplateParameter()) {
916 DiagnoseTemplateParameterShadow(Loc: B.NameLoc, PrevDecl: Previous.getFoundDecl());
917 Previous.clear();
918 }
919
920 QualType QT;
921 if (B.EllipsisLoc.isValid()) {
922 if (!cast<Decl>(Val: DC)->isTemplated())
923 Diag(Loc: B.EllipsisLoc, DiagID: diag::err_pack_outside_template);
924 QT = Context.getPackExpansionType(Pattern: Context.DependentTy, NumExpansions: std::nullopt,
925 /*ExpectsPackInType=*/ExpectPackInType: false);
926 }
927
928 auto *BD = BindingDecl::Create(C&: Context, DC, IdLoc: B.NameLoc, Id: B.Name, T: QT);
929
930 if (BD->isParameterPack()) {
931 if (sema::CapturingScopeInfo *CSI = getEnclosingLambdaOrBlock())
932 CSI->LocalPacks.push_back(Elt: BD);
933 }
934
935 ProcessDeclAttributeList(S, D: BD, AttrList: *B.Attrs);
936
937 // Find the shadowed declaration before filtering for scope.
938 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
939 ? getShadowedDeclaration(D: BD, R: Previous)
940 : nullptr;
941
942 bool ConsiderLinkage = DC->isFunctionOrMethod() &&
943 DS.getStorageClassSpec() == DeclSpec::SCS_extern;
944 FilterLookupForScope(R&: Previous, Ctx: DC, S, ConsiderLinkage,
945 /*AllowInlineNamespace*/false);
946
947 bool IsPlaceholder = DS.getStorageClassSpec() != DeclSpec::SCS_static &&
948 DC->isFunctionOrMethod() && VarName->isPlaceholder();
949 if (!Previous.empty()) {
950 if (IsPlaceholder) {
951 bool sameDC = (Previous.end() - 1)
952 ->getDeclContext()
953 ->getRedeclContext()
954 ->Equals(DC: DC->getRedeclContext());
955 if (sameDC &&
956 isDeclInScope(D: *(Previous.end() - 1), Ctx: CurContext, S, AllowInlineNamespace: false)) {
957 Previous.clear();
958 DiagPlaceholderVariableDefinition(Loc: B.NameLoc);
959 }
960 } else {
961 auto *Old = Previous.getRepresentativeDecl();
962 Diag(Loc: B.NameLoc, DiagID: diag::err_redefinition) << B.Name;
963 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_definition);
964 }
965 } else if (ShadowedDecl && !D.isRedeclaration()) {
966 CheckShadow(D: BD, ShadowedDecl, R: Previous);
967 }
968 PushOnScopeChains(D: BD, S, AddToContext: true);
969 Bindings.push_back(Elt: BD);
970 ParsingInitForAutoVars.insert(Ptr: BD);
971 }
972
973 // There are no prior lookup results for the variable itself, because it
974 // is unnamed.
975 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
976 Decomp.getLSquareLoc());
977 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
978 RedeclarationKind::ForVisibleRedeclaration);
979
980 // Build the variable that holds the non-decomposed object.
981 bool AddToScope = true;
982 NamedDecl *New =
983 ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
984 TemplateParamLists: MultiTemplateParamsArg(), AddToScope, Bindings);
985 if (AddToScope) {
986 S->AddDecl(D: New);
987 CurContext->addHiddenDecl(D: New);
988 }
989
990 if (OpenMP().isInOpenMPDeclareTargetContext())
991 OpenMP().checkDeclIsAllowedInOpenMPTarget(E: nullptr, D: New);
992
993 return New;
994}
995
996// Check the arity of the structured bindings.
997// Create the resolved pack expr if needed.
998static bool CheckBindingsCount(Sema &S, DecompositionDecl *DD,
999 QualType DecompType,
1000 ArrayRef<BindingDecl *> Bindings,
1001 unsigned MemberCount) {
1002 auto BindingWithPackItr = llvm::find_if(
1003 Range&: Bindings, P: [](BindingDecl *D) -> bool { return D->isParameterPack(); });
1004 bool HasPack = BindingWithPackItr != Bindings.end();
1005 bool IsValid;
1006 if (!HasPack) {
1007 IsValid = Bindings.size() == MemberCount;
1008 } else {
1009 // There may not be more members than non-pack bindings.
1010 IsValid = MemberCount >= Bindings.size() - 1;
1011 }
1012
1013 if (IsValid && HasPack) {
1014 // Create the pack expr and assign it to the binding.
1015 unsigned PackSize = MemberCount - Bindings.size() + 1;
1016
1017 BindingDecl *BPack = *BindingWithPackItr;
1018 BPack->setDecomposedDecl(DD);
1019 SmallVector<ValueDecl *, 8> NestedBDs(PackSize);
1020 // Create the nested BindingDecls.
1021 for (unsigned I = 0; I < PackSize; ++I) {
1022 BindingDecl *NestedBD = BindingDecl::Create(
1023 C&: S.Context, DC: BPack->getDeclContext(), IdLoc: BPack->getLocation(),
1024 Id: BPack->getIdentifier(), T: QualType());
1025 NestedBD->setDecomposedDecl(DD);
1026 NestedBDs[I] = NestedBD;
1027 }
1028
1029 QualType PackType = S.Context.getPackExpansionType(
1030 Pattern: S.Context.DependentTy, NumExpansions: PackSize, /*ExpectsPackInType=*/ExpectPackInType: false);
1031 auto *PackExpr = FunctionParmPackExpr::Create(
1032 Context: S.Context, T: PackType, ParamPack: BPack, NameLoc: BPack->getBeginLoc(), Params: NestedBDs);
1033 BPack->setBinding(DeclaredType: PackType, Binding: PackExpr);
1034 }
1035
1036 if (IsValid)
1037 return false;
1038
1039 S.Diag(Loc: DD->getLocation(), DiagID: diag::err_decomp_decl_wrong_number_bindings)
1040 << DecompType << (unsigned)Bindings.size() << MemberCount << MemberCount
1041 << (MemberCount < Bindings.size());
1042 return true;
1043}
1044
1045static bool checkSimpleDecomposition(
1046 Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
1047 QualType DecompType, const llvm::APSInt &NumElemsAPS, QualType ElemType,
1048 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
1049 unsigned NumElems = (unsigned)NumElemsAPS.getLimitedValue(UINT_MAX);
1050 auto *DD = cast<DecompositionDecl>(Val: Src);
1051
1052 if (CheckBindingsCount(S, DD, DecompType, Bindings, MemberCount: NumElems))
1053 return true;
1054
1055 unsigned I = 0;
1056 for (auto *B : DD->flat_bindings()) {
1057 SourceLocation Loc = B->getLocation();
1058 ExprResult E = S.BuildDeclRefExpr(D: Src, Ty: DecompType, VK: VK_LValue, Loc);
1059 if (E.isInvalid())
1060 return true;
1061 E = GetInit(Loc, E.get(), I++);
1062 if (E.isInvalid())
1063 return true;
1064 B->setBinding(DeclaredType: ElemType, Binding: E.get());
1065 }
1066
1067 return false;
1068}
1069
1070static bool checkArrayLikeDecomposition(Sema &S,
1071 ArrayRef<BindingDecl *> Bindings,
1072 ValueDecl *Src, QualType DecompType,
1073 const llvm::APSInt &NumElems,
1074 QualType ElemType) {
1075 return checkSimpleDecomposition(
1076 S, Bindings, Src, DecompType, NumElemsAPS: NumElems, ElemType,
1077 GetInit: [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
1078 ExprResult E = S.ActOnIntegerConstant(Loc, Val: I);
1079 if (E.isInvalid())
1080 return ExprError();
1081 return S.CreateBuiltinArraySubscriptExpr(Base, LLoc: Loc, Idx: E.get(), RLoc: Loc);
1082 });
1083}
1084
1085static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1086 ValueDecl *Src, QualType DecompType,
1087 const ConstantArrayType *CAT) {
1088 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
1089 NumElems: llvm::APSInt(CAT->getSize()),
1090 ElemType: CAT->getElementType());
1091}
1092
1093static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1094 ValueDecl *Src, QualType DecompType,
1095 const VectorType *VT) {
1096 return checkArrayLikeDecomposition(
1097 S, Bindings, Src, DecompType, NumElems: llvm::APSInt::get(X: VT->getNumElements()),
1098 ElemType: S.Context.getQualifiedType(T: VT->getElementType(),
1099 Qs: DecompType.getQualifiers()));
1100}
1101
1102static bool checkComplexDecomposition(Sema &S,
1103 ArrayRef<BindingDecl *> Bindings,
1104 ValueDecl *Src, QualType DecompType,
1105 const ComplexType *CT) {
1106 return checkSimpleDecomposition(
1107 S, Bindings, Src, DecompType, NumElemsAPS: llvm::APSInt::get(X: 2),
1108 ElemType: S.Context.getQualifiedType(T: CT->getElementType(),
1109 Qs: DecompType.getQualifiers()),
1110 GetInit: [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
1111 return S.CreateBuiltinUnaryOp(OpLoc: Loc, Opc: I ? UO_Imag : UO_Real, InputExpr: Base);
1112 });
1113}
1114
1115static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
1116 TemplateArgumentListInfo &Args,
1117 const TemplateParameterList *Params) {
1118 SmallString<128> SS;
1119 llvm::raw_svector_ostream OS(SS);
1120 bool First = true;
1121 unsigned I = 0;
1122 for (auto &Arg : Args.arguments()) {
1123 if (!First)
1124 OS << ", ";
1125 Arg.getArgument().print(Policy: PrintingPolicy, Out&: OS,
1126 IncludeType: TemplateParameterList::shouldIncludeTypeForArgument(
1127 Policy: PrintingPolicy, TPL: Params, Idx: I));
1128 First = false;
1129 I++;
1130 }
1131 return std::string(OS.str());
1132}
1133
1134static QualType getStdTrait(Sema &S, SourceLocation Loc, StringRef Trait,
1135 TemplateArgumentListInfo &Args, unsigned DiagID) {
1136 auto DiagnoseMissing = [&] {
1137 if (DiagID)
1138 S.Diag(Loc, DiagID) << printTemplateArgs(PrintingPolicy: S.Context.getPrintingPolicy(),
1139 Args, /*Params*/ nullptr);
1140 return QualType();
1141 };
1142
1143 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
1144 NamespaceDecl *Std = S.getStdNamespace();
1145 if (!Std)
1146 return DiagnoseMissing();
1147
1148 // Look up the trait itself, within namespace std. We can diagnose various
1149 // problems with this lookup even if we've been asked to not diagnose a
1150 // missing specialization, because this can only fail if the user has been
1151 // declaring their own names in namespace std or we don't support the
1152 // standard library implementation in use.
1153 LookupResult Result(S, &S.PP.getIdentifierTable().get(Name: Trait), Loc,
1154 Sema::LookupOrdinaryName);
1155 if (!S.LookupQualifiedName(R&: Result, LookupCtx: Std))
1156 return DiagnoseMissing();
1157 if (Result.isAmbiguous())
1158 return QualType();
1159
1160 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
1161 if (!TraitTD) {
1162 Result.suppressDiagnostics();
1163 NamedDecl *Found = *Result.begin();
1164 S.Diag(Loc, DiagID: diag::err_std_type_trait_not_class_template) << Trait;
1165 S.Diag(Loc: Found->getLocation(), DiagID: diag::note_declared_at);
1166 return QualType();
1167 }
1168
1169 // Build the template-id.
1170 QualType TraitTy = S.CheckTemplateIdType(
1171 Keyword: ElaboratedTypeKeyword::None, Template: TemplateName(TraitTD), TemplateLoc: Loc, TemplateArgs&: Args,
1172 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
1173 if (TraitTy.isNull())
1174 return QualType();
1175
1176 if (!S.isCompleteType(Loc, T: TraitTy)) {
1177 if (DiagID)
1178 S.RequireCompleteType(
1179 Loc, T: TraitTy, DiagID,
1180 Args: printTemplateArgs(PrintingPolicy: S.Context.getPrintingPolicy(), Args,
1181 Params: TraitTD->getTemplateParameters()));
1182 return QualType();
1183 }
1184 return TraitTy;
1185}
1186
1187static bool lookupMember(Sema &S, CXXRecordDecl *RD,
1188 LookupResult &MemberLookup) {
1189 assert(RD && "specialization of class template is not a class?");
1190 S.LookupQualifiedName(R&: MemberLookup, LookupCtx: RD);
1191 return MemberLookup.isAmbiguous();
1192}
1193
1194static TemplateArgumentLoc
1195getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
1196 uint64_t I) {
1197 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(Value: I, Type: T), T);
1198 return S.getTrivialTemplateArgumentLoc(Arg, NTTPType: T, Loc);
1199}
1200
1201static TemplateArgumentLoc
1202getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
1203 return S.getTrivialTemplateArgumentLoc(Arg: TemplateArgument(T), NTTPType: QualType(), Loc);
1204}
1205
1206namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1207
1208static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1209 unsigned &OutSize) {
1210 EnterExpressionEvaluationContext ContextRAII(
1211 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1212
1213 // Form template argument list for tuple_size<T>.
1214 TemplateArgumentListInfo Args(Loc, Loc);
1215 Args.addArgument(Loc: getTrivialTypeTemplateArgument(S, Loc, T));
1216
1217 QualType TraitTy = getStdTrait(S, Loc, Trait: "tuple_size", Args, /*DiagID=*/0);
1218 if (TraitTy.isNull())
1219 return IsTupleLike::NotTupleLike;
1220
1221 DeclarationName Value = S.PP.getIdentifierInfo(Name: "value");
1222 LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
1223
1224 // If there's no tuple_size specialization or the lookup of 'value' is empty,
1225 // it's not tuple-like.
1226 if (lookupMember(S, RD: TraitTy->getAsCXXRecordDecl(), MemberLookup&: R) || R.empty())
1227 return IsTupleLike::NotTupleLike;
1228
1229 // If we get this far, we've committed to the tuple interpretation, but
1230 // we can still fail if there actually isn't a usable ::value.
1231
1232 struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1233 LookupResult &R;
1234 TemplateArgumentListInfo &Args;
1235 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1236 : R(R), Args(Args) {}
1237 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
1238 SourceLocation Loc) override {
1239 return S.Diag(Loc, DiagID: diag::err_decomp_decl_std_tuple_size_not_constant)
1240 << printTemplateArgs(PrintingPolicy: S.Context.getPrintingPolicy(), Args,
1241 /*Params*/ nullptr);
1242 }
1243 } Diagnoser(R, Args);
1244
1245 ExprResult E =
1246 S.BuildDeclarationNameExpr(SS: CXXScopeSpec(), R, /*NeedsADL*/false);
1247 if (E.isInvalid())
1248 return IsTupleLike::Error;
1249
1250 llvm::APSInt Size;
1251 E = S.VerifyIntegerConstantExpression(E: E.get(), Result: &Size, Diagnoser);
1252 if (E.isInvalid())
1253 return IsTupleLike::Error;
1254
1255 // The implementation limit is UINT_MAX-1, to allow this to be passed down on
1256 // an UnsignedOrNone.
1257 if (Size < 0 || Size >= UINT_MAX) {
1258 llvm::SmallVector<char, 16> Str;
1259 Size.toString(Str);
1260 S.Diag(Loc, DiagID: diag::err_decomp_decl_std_tuple_size_invalid)
1261 << printTemplateArgs(PrintingPolicy: S.Context.getPrintingPolicy(), Args,
1262 /*Params=*/nullptr)
1263 << StringRef(Str.data(), Str.size());
1264 return IsTupleLike::Error;
1265 }
1266
1267 OutSize = Size.getExtValue();
1268 return IsTupleLike::TupleLike;
1269}
1270
1271/// \return std::tuple_element<I, T>::type.
1272static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1273 unsigned I, QualType T) {
1274 // Form template argument list for tuple_element<I, T>.
1275 TemplateArgumentListInfo Args(Loc, Loc);
1276 Args.addArgument(
1277 Loc: getTrivialIntegralTemplateArgument(S, Loc, T: S.Context.getSizeType(), I));
1278 Args.addArgument(Loc: getTrivialTypeTemplateArgument(S, Loc, T));
1279
1280 QualType TraitTy =
1281 getStdTrait(S, Loc, Trait: "tuple_element", Args,
1282 DiagID: diag::err_decomp_decl_std_tuple_element_not_specialized);
1283 if (TraitTy.isNull())
1284 return QualType();
1285
1286 DeclarationName TypeDN = S.PP.getIdentifierInfo(Name: "type");
1287 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1288 if (lookupMember(S, RD: TraitTy->getAsCXXRecordDecl(), MemberLookup&: R))
1289 return QualType();
1290
1291 auto *TD = R.getAsSingle<TypeDecl>();
1292 if (!TD) {
1293 R.suppressDiagnostics();
1294 S.Diag(Loc, DiagID: diag::err_decomp_decl_std_tuple_element_not_specialized)
1295 << printTemplateArgs(PrintingPolicy: S.Context.getPrintingPolicy(), Args,
1296 /*Params*/ nullptr);
1297 if (!R.empty())
1298 S.Diag(Loc: R.getRepresentativeDecl()->getLocation(), DiagID: diag::note_declared_at);
1299 return QualType();
1300 }
1301
1302 NestedNameSpecifier Qualifier(TraitTy.getTypePtr());
1303 return S.Context.getTypeDeclType(Keyword: ElaboratedTypeKeyword::None, Qualifier, Decl: TD);
1304}
1305
1306namespace {
1307struct InitializingBinding {
1308 Sema &S;
1309 InitializingBinding(Sema &S, BindingDecl *BD) : S(S) {
1310 Sema::CodeSynthesisContext Ctx;
1311 Ctx.Kind = Sema::CodeSynthesisContext::InitializingStructuredBinding;
1312 Ctx.PointOfInstantiation = BD->getLocation();
1313 Ctx.Entity = BD;
1314 S.pushCodeSynthesisContext(Ctx);
1315 }
1316 ~InitializingBinding() {
1317 S.popCodeSynthesisContext();
1318 }
1319};
1320}
1321
1322static bool checkTupleLikeDecomposition(Sema &S,
1323 ArrayRef<BindingDecl *> Bindings,
1324 VarDecl *Src, QualType DecompType,
1325 unsigned NumElems) {
1326 auto *DD = cast<DecompositionDecl>(Val: Src);
1327 if (CheckBindingsCount(S, DD, DecompType, Bindings, MemberCount: NumElems))
1328 return true;
1329
1330 if (Bindings.empty())
1331 return false;
1332
1333 DeclarationName GetDN = S.PP.getIdentifierInfo(Name: "get");
1334
1335 // [dcl.decomp]p3:
1336 // The unqualified-id get is looked up in the scope of E by class member
1337 // access lookup ...
1338 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1339 bool UseMemberGet = false;
1340 if (S.isCompleteType(Loc: Src->getLocation(), T: DecompType)) {
1341 if (auto *RD = DecompType->getAsCXXRecordDecl())
1342 S.LookupQualifiedName(R&: MemberGet, LookupCtx: RD);
1343 if (MemberGet.isAmbiguous())
1344 return true;
1345 // ... and if that finds at least one declaration that is a function
1346 // template whose first template parameter is a non-type parameter ...
1347 for (NamedDecl *D : MemberGet) {
1348 if (FunctionTemplateDecl *FTD =
1349 dyn_cast<FunctionTemplateDecl>(Val: D->getUnderlyingDecl())) {
1350 TemplateParameterList *TPL = FTD->getTemplateParameters();
1351 if (TPL->size() != 0 &&
1352 isa<NonTypeTemplateParmDecl>(Val: TPL->getParam(Idx: 0))) {
1353 // ... the initializer is e.get<i>().
1354 UseMemberGet = true;
1355 break;
1356 }
1357 }
1358 }
1359 }
1360
1361 unsigned I = 0;
1362 for (auto *B : DD->flat_bindings()) {
1363 InitializingBinding InitContext(S, B);
1364 SourceLocation Loc = B->getLocation();
1365
1366 ExprResult E = S.BuildDeclRefExpr(D: Src, Ty: DecompType, VK: VK_LValue, Loc);
1367 if (E.isInvalid())
1368 return true;
1369
1370 // e is an lvalue if the type of the entity is an lvalue reference and
1371 // an xvalue otherwise
1372 if (!Src->getType()->isLValueReferenceType())
1373 E = ImplicitCastExpr::Create(Context: S.Context, T: E.get()->getType(), Kind: CK_NoOp,
1374 Operand: E.get(), BasePath: nullptr, Cat: VK_XValue,
1375 FPO: FPOptionsOverride());
1376
1377 TemplateArgumentListInfo Args(Loc, Loc);
1378 Args.addArgument(
1379 Loc: getTrivialIntegralTemplateArgument(S, Loc, T: S.Context.getSizeType(), I));
1380
1381 if (UseMemberGet) {
1382 // if [lookup of member get] finds at least one declaration, the
1383 // initializer is e.get<i-1>().
1384 E = S.BuildMemberReferenceExpr(Base: E.get(), BaseType: DecompType, OpLoc: Loc, IsArrow: false,
1385 SS: CXXScopeSpec(), TemplateKWLoc: SourceLocation(), FirstQualifierInScope: nullptr,
1386 R&: MemberGet, TemplateArgs: &Args, S: nullptr);
1387 if (E.isInvalid())
1388 return true;
1389
1390 E = S.BuildCallExpr(S: nullptr, Fn: E.get(), LParenLoc: Loc, ArgExprs: {}, RParenLoc: Loc);
1391 } else {
1392 // Otherwise, the initializer is get<i-1>(e), where get is looked up
1393 // in the associated namespaces.
1394 Expr *Get = UnresolvedLookupExpr::Create(
1395 Context: S.Context, NamingClass: nullptr, QualifierLoc: NestedNameSpecifierLoc(), TemplateKWLoc: SourceLocation(),
1396 NameInfo: DeclarationNameInfo(GetDN, Loc), /*RequiresADL=*/true, Args: &Args,
1397 Begin: UnresolvedSetIterator(), End: UnresolvedSetIterator(),
1398 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
1399
1400 Expr *Arg = E.get();
1401 E = S.BuildCallExpr(S: nullptr, Fn: Get, LParenLoc: Loc, ArgExprs: Arg, RParenLoc: Loc);
1402 }
1403 if (E.isInvalid())
1404 return true;
1405 Expr *Init = E.get();
1406
1407 // Given the type T designated by std::tuple_element<i - 1, E>::type
1408 QualType T = getTupleLikeElementType(S, Loc, I, T: DecompType);
1409 if (T.isNull())
1410 return true;
1411
1412 // C++26 [dcl.struct.bind]p7:
1413 // and the type Ui, defined as Ti if the initializer is a prvalue,
1414 // as "lvalue reference to Ti" if the initializer is an lvalue,
1415 // or as "rvalue reference to Ti" otherwise
1416 // "defined as Ti if the initializer is a prvalue" was introduced by CWG3135
1417 QualType U = E.get()->isPRValue()
1418 ? T
1419 : S.BuildReferenceType(T, LValueRef: E.get()->isLValue(), Loc,
1420 Entity: B->getDeclName());
1421 if (U.isNull())
1422 return true;
1423
1424 // Don't give this VarDecl a TypeSourceInfo, since this is a synthesized
1425 // entity and this type was never written in source code.
1426 auto *BindingVD =
1427 VarDecl::Create(C&: S.Context, DC: Src->getDeclContext(), StartLoc: Loc, IdLoc: Loc,
1428 Id: B->getDeclName().getAsIdentifierInfo(), T: U,
1429 /*TInfo=*/nullptr, S: Src->getStorageClass());
1430 BindingVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1431 BindingVD->setTSCSpec(Src->getTSCSpec());
1432 BindingVD->setConstexpr(Src->isConstexpr());
1433 if (const auto *CIAttr = Src->getAttr<ConstInitAttr>())
1434 BindingVD->addAttr(A: CIAttr->clone(C&: S.Context));
1435 BindingVD->setImplicit();
1436 if (Src->isInlineSpecified())
1437 BindingVD->setInlineSpecified();
1438 BindingVD->getLexicalDeclContext()->addHiddenDecl(D: BindingVD);
1439
1440 InitializedEntity Entity = InitializedEntity::InitializeBinding(Binding: BindingVD);
1441 InitializationKind Kind = InitializationKind::CreateCopy(InitLoc: Loc, EqualLoc: Loc);
1442 InitializationSequence Seq(S, Entity, Kind, Init);
1443 E = Seq.Perform(S, Entity, Kind, Args: Init);
1444 if (E.isInvalid())
1445 return true;
1446 E = S.ActOnFinishFullExpr(Expr: E.get(), CC: Loc, /*DiscardedValue*/ false);
1447 if (E.isInvalid())
1448 return true;
1449 BindingVD->setInit(E.get());
1450 S.CheckCompleteVariableDeclaration(VD: BindingVD);
1451
1452 E = S.BuildDeclarationNameExpr(
1453 SS: CXXScopeSpec(), NameInfo: DeclarationNameInfo(B->getDeclName(), Loc), D: BindingVD);
1454 if (E.isInvalid())
1455 return true;
1456
1457 B->setBinding(DeclaredType: T, Binding: E.get());
1458 I++;
1459 }
1460
1461 return false;
1462}
1463
1464/// Find the base class to decompose in a built-in decomposition of a class type.
1465/// This base class search is, unfortunately, not quite like any other that we
1466/// perform anywhere else in C++.
1467static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc,
1468 const CXXRecordDecl *RD,
1469 CXXCastPath &BasePath) {
1470 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1471 CXXBasePath &Path) {
1472 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1473 };
1474
1475 const CXXRecordDecl *ClassWithFields = nullptr;
1476 AccessSpecifier AS = AS_public;
1477 if (RD->hasDirectFields())
1478 // [dcl.decomp]p4:
1479 // Otherwise, all of E's non-static data members shall be public direct
1480 // members of E ...
1481 ClassWithFields = RD;
1482 else {
1483 // ... or of ...
1484 CXXBasePaths Paths;
1485 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1486 if (!RD->lookupInBases(BaseMatches: BaseHasFields, Paths)) {
1487 // If no classes have fields, just decompose RD itself. (This will work
1488 // if and only if zero bindings were provided.)
1489 return DeclAccessPair::make(D: const_cast<CXXRecordDecl*>(RD), AS: AS_public);
1490 }
1491
1492 CXXBasePath *BestPath = nullptr;
1493 for (auto &P : Paths) {
1494 if (!BestPath)
1495 BestPath = &P;
1496 else if (!S.Context.hasSameType(T1: P.back().Base->getType(),
1497 T2: BestPath->back().Base->getType())) {
1498 // ... the same ...
1499 S.Diag(Loc, DiagID: diag::err_decomp_decl_multiple_bases_with_members)
1500 << false << RD << BestPath->back().Base->getType()
1501 << P.back().Base->getType();
1502 return DeclAccessPair();
1503 } else if (P.Access < BestPath->Access) {
1504 BestPath = &P;
1505 }
1506 }
1507
1508 // ... unambiguous ...
1509 QualType BaseType = BestPath->back().Base->getType();
1510 if (Paths.isAmbiguous(BaseType: S.Context.getCanonicalType(T: BaseType))) {
1511 S.Diag(Loc, DiagID: diag::err_decomp_decl_ambiguous_base)
1512 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1513 return DeclAccessPair();
1514 }
1515
1516 // ... [accessible, implied by other rules] base class of E.
1517 S.CheckBaseClassAccess(AccessLoc: Loc, Base: BaseType, Derived: S.Context.getCanonicalTagType(TD: RD),
1518 Path: *BestPath, DiagID: diag::err_decomp_decl_inaccessible_base);
1519 AS = BestPath->Access;
1520
1521 ClassWithFields = BaseType->getAsCXXRecordDecl();
1522 S.BuildBasePathArray(Paths, BasePath);
1523 }
1524
1525 // The above search did not check whether the selected class itself has base
1526 // classes with fields, so check that now.
1527 CXXBasePaths Paths;
1528 if (ClassWithFields->lookupInBases(BaseMatches: BaseHasFields, Paths)) {
1529 S.Diag(Loc, DiagID: diag::err_decomp_decl_multiple_bases_with_members)
1530 << (ClassWithFields == RD) << RD << ClassWithFields
1531 << Paths.front().back().Base->getType();
1532 return DeclAccessPair();
1533 }
1534
1535 return DeclAccessPair::make(D: const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1536}
1537
1538static bool CheckMemberDecompositionFields(Sema &S, SourceLocation Loc,
1539 const CXXRecordDecl *OrigRD,
1540 QualType DecompType,
1541 DeclAccessPair BasePair) {
1542 const auto *RD = cast_or_null<CXXRecordDecl>(Val: BasePair.getDecl());
1543 if (!RD)
1544 return true;
1545
1546 for (auto *FD : RD->fields()) {
1547 if (FD->isUnnamedBitField())
1548 continue;
1549
1550 // All the non-static data members are required to be nameable, so they
1551 // must all have names.
1552 if (!FD->getDeclName()) {
1553 if (RD->isLambda()) {
1554 S.Diag(Loc, DiagID: diag::err_decomp_decl_lambda);
1555 S.Diag(Loc: RD->getLocation(), DiagID: diag::note_lambda_decl);
1556 return true;
1557 }
1558
1559 if (FD->isAnonymousStructOrUnion()) {
1560 S.Diag(Loc, DiagID: diag::err_decomp_decl_anon_union_member)
1561 << DecompType << FD->getType()->isUnionType();
1562 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_declared_at);
1563 return true;
1564 }
1565
1566 // FIXME: Are there any other ways we could have an anonymous member?
1567 }
1568 // The field must be accessible in the context of the structured binding.
1569 // We already checked that the base class is accessible.
1570 // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1571 // const_cast here.
1572 S.CheckStructuredBindingMemberAccess(
1573 UseLoc: Loc, DecomposedClass: const_cast<CXXRecordDecl *>(OrigRD),
1574 Field: DeclAccessPair::make(D: FD, AS: CXXRecordDecl::MergeAccess(
1575 PathAccess: BasePair.getAccess(), DeclAccess: FD->getAccess())));
1576 }
1577 return false;
1578}
1579
1580static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1581 ValueDecl *Src, QualType DecompType,
1582 const CXXRecordDecl *OrigRD) {
1583 if (S.RequireCompleteType(Loc: Src->getLocation(), T: DecompType,
1584 DiagID: diag::err_incomplete_type))
1585 return true;
1586
1587 CXXCastPath BasePath;
1588 DeclAccessPair BasePair =
1589 findDecomposableBaseClass(S, Loc: Src->getLocation(), RD: OrigRD, BasePath);
1590 const auto *RD = cast_or_null<CXXRecordDecl>(Val: BasePair.getDecl());
1591 if (!RD)
1592 return true;
1593 QualType BaseType = S.Context.getQualifiedType(
1594 T: S.Context.getCanonicalTagType(TD: RD), Qs: DecompType.getQualifiers());
1595
1596 auto *DD = cast<DecompositionDecl>(Val: Src);
1597 unsigned NumFields = llvm::count_if(
1598 Range: RD->fields(), P: [](FieldDecl *FD) { return !FD->isUnnamedBitField(); });
1599 if (CheckBindingsCount(S, DD, DecompType, Bindings, MemberCount: NumFields))
1600 return true;
1601
1602 // all of E's non-static data members shall be [...] well-formed
1603 // when named as e.name in the context of the structured binding,
1604 // E shall not have an anonymous union member, ...
1605 auto FlatBindings = DD->flat_bindings();
1606 assert(llvm::range_size(FlatBindings) == NumFields);
1607 auto FlatBindingsItr = FlatBindings.begin();
1608
1609 if (CheckMemberDecompositionFields(S, Loc: Src->getLocation(), OrigRD, DecompType,
1610 BasePair))
1611 return true;
1612
1613 for (auto *FD : RD->fields()) {
1614 if (FD->isUnnamedBitField())
1615 continue;
1616
1617 // We have a real field to bind.
1618 assert(FlatBindingsItr != FlatBindings.end());
1619 BindingDecl *B = *(FlatBindingsItr++);
1620 SourceLocation Loc = B->getLocation();
1621
1622 // Initialize the binding to Src.FD.
1623 ExprResult E = S.BuildDeclRefExpr(D: Src, Ty: DecompType, VK: VK_LValue, Loc);
1624 if (E.isInvalid())
1625 return true;
1626 E = S.ImpCastExprToType(E: E.get(), Type: BaseType, CK: CK_UncheckedDerivedToBase,
1627 VK: VK_LValue, BasePath: &BasePath);
1628 if (E.isInvalid())
1629 return true;
1630 E = S.BuildFieldReferenceExpr(BaseExpr: E.get(), /*IsArrow*/ false, OpLoc: Loc,
1631 SS: CXXScopeSpec(), Field: FD,
1632 FoundDecl: DeclAccessPair::make(D: FD, AS: FD->getAccess()),
1633 MemberNameInfo: DeclarationNameInfo(FD->getDeclName(), Loc));
1634 if (E.isInvalid())
1635 return true;
1636
1637 // If the type of the member is T, the referenced type is cv T, where cv is
1638 // the cv-qualification of the decomposition expression.
1639 //
1640 // FIXME: We resolve a defect here: if the field is mutable, we do not add
1641 // 'const' to the type of the field.
1642 Qualifiers Q = DecompType.getQualifiers();
1643 if (FD->isMutable())
1644 Q.removeConst();
1645 B->setBinding(DeclaredType: S.BuildQualifiedType(T: FD->getType(), Loc, Qs: Q), Binding: E.get());
1646 }
1647
1648 return false;
1649}
1650
1651void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
1652 QualType DecompType = DD->getType();
1653
1654 // If the type of the decomposition is dependent, then so is the type of
1655 // each binding.
1656 if (DecompType->isDependentType()) {
1657 // Note that all of the types are still Null or PackExpansionType.
1658 for (auto *B : DD->bindings()) {
1659 // Do not overwrite any pack type.
1660 if (B->getType().isNull())
1661 B->setType(Context.DependentTy);
1662 }
1663 return;
1664 }
1665
1666 DecompType = DecompType.getNonReferenceType();
1667 ArrayRef<BindingDecl*> Bindings = DD->bindings();
1668
1669 // C++1z [dcl.decomp]/2:
1670 // If E is an array type [...]
1671 // As an extension, we also support decomposition of built-in complex and
1672 // vector types.
1673 if (auto *CAT = Context.getAsConstantArrayType(T: DecompType)) {
1674 if (checkArrayDecomposition(S&: *this, Bindings, Src: DD, DecompType, CAT))
1675 DD->setInvalidDecl();
1676 return;
1677 }
1678 if (auto *VT = DecompType->getAs<VectorType>()) {
1679 if (checkVectorDecomposition(S&: *this, Bindings, Src: DD, DecompType, VT))
1680 DD->setInvalidDecl();
1681 return;
1682 }
1683 if (auto *CT = DecompType->getAs<ComplexType>()) {
1684 if (checkComplexDecomposition(S&: *this, Bindings, Src: DD, DecompType, CT))
1685 DD->setInvalidDecl();
1686 return;
1687 }
1688
1689 // C++1z [dcl.decomp]/3:
1690 // if the expression std::tuple_size<E>::value is a well-formed integral
1691 // constant expression, [...]
1692 unsigned TupleSize;
1693 switch (isTupleLike(S&: *this, Loc: DD->getLocation(), T: DecompType, OutSize&: TupleSize)) {
1694 case IsTupleLike::Error:
1695 DD->setInvalidDecl();
1696 return;
1697
1698 case IsTupleLike::TupleLike:
1699 if (checkTupleLikeDecomposition(S&: *this, Bindings, Src: DD, DecompType, NumElems: TupleSize))
1700 DD->setInvalidDecl();
1701 return;
1702
1703 case IsTupleLike::NotTupleLike:
1704 break;
1705 }
1706
1707 // C++1z [dcl.dcl]/8:
1708 // [E shall be of array or non-union class type]
1709 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1710 if (!RD || RD->isUnion()) {
1711 Diag(Loc: DD->getLocation(), DiagID: diag::err_decomp_decl_unbindable_type)
1712 << DD << !RD << DecompType;
1713 DD->setInvalidDecl();
1714 return;
1715 }
1716
1717 // C++1z [dcl.decomp]/4:
1718 // all of E's non-static data members shall be [...] direct members of
1719 // E or of the same unambiguous public base class of E, ...
1720 if (checkMemberDecomposition(S&: *this, Bindings, Src: DD, DecompType, OrigRD: RD))
1721 DD->setInvalidDecl();
1722}
1723
1724UnsignedOrNone Sema::GetDecompositionElementCount(QualType T,
1725 SourceLocation Loc) {
1726 const ASTContext &Ctx = getASTContext();
1727 assert(!T->isDependentType());
1728
1729 Qualifiers Quals;
1730 QualType Unqual = Context.getUnqualifiedArrayType(T, Quals);
1731 Quals.removeCVRQualifiers();
1732 T = Context.getQualifiedType(T: Unqual, Qs: Quals);
1733
1734 if (auto *CAT = Ctx.getAsConstantArrayType(T))
1735 return static_cast<unsigned>(CAT->getSize().getZExtValue());
1736 if (auto *VT = T->getAs<VectorType>())
1737 return VT->getNumElements();
1738 if (T->getAs<ComplexType>())
1739 return 2u;
1740
1741 unsigned TupleSize;
1742 switch (isTupleLike(S&: *this, Loc, T, OutSize&: TupleSize)) {
1743 case IsTupleLike::Error:
1744 return std::nullopt;
1745 case IsTupleLike::TupleLike:
1746 return TupleSize;
1747 case IsTupleLike::NotTupleLike:
1748 break;
1749 }
1750
1751 const CXXRecordDecl *OrigRD = T->getAsCXXRecordDecl();
1752 if (!OrigRD || OrigRD->isUnion())
1753 return std::nullopt;
1754
1755 if (RequireCompleteType(Loc, T, DiagID: diag::err_incomplete_type))
1756 return std::nullopt;
1757
1758 CXXCastPath BasePath;
1759 DeclAccessPair BasePair =
1760 findDecomposableBaseClass(S&: *this, Loc, RD: OrigRD, BasePath);
1761 const auto *RD = cast_or_null<CXXRecordDecl>(Val: BasePair.getDecl());
1762 if (!RD)
1763 return std::nullopt;
1764
1765 unsigned NumFields = llvm::count_if(
1766 Range: RD->fields(), P: [](FieldDecl *FD) { return !FD->isUnnamedBitField(); });
1767
1768 if (CheckMemberDecompositionFields(S&: *this, Loc, OrigRD, DecompType: T, BasePair))
1769 return std::nullopt;
1770
1771 return NumFields;
1772}
1773
1774void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1775 // Shortcut if exceptions are disabled.
1776 if (!getLangOpts().CXXExceptions)
1777 return;
1778
1779 assert(Context.hasSameType(New->getType(), Old->getType()) &&
1780 "Should only be called if types are otherwise the same.");
1781
1782 QualType NewType = New->getType();
1783 QualType OldType = Old->getType();
1784
1785 // We're only interested in pointers and references to functions, as well
1786 // as pointers to member functions.
1787 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1788 NewType = R->getPointeeType();
1789 OldType = OldType->castAs<ReferenceType>()->getPointeeType();
1790 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1791 NewType = P->getPointeeType();
1792 OldType = OldType->castAs<PointerType>()->getPointeeType();
1793 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1794 NewType = M->getPointeeType();
1795 OldType = OldType->castAs<MemberPointerType>()->getPointeeType();
1796 }
1797
1798 if (!NewType->isFunctionProtoType())
1799 return;
1800
1801 // There's lots of special cases for functions. For function pointers, system
1802 // libraries are hopefully not as broken so that we don't need these
1803 // workarounds.
1804 if (CheckEquivalentExceptionSpec(
1805 Old: OldType->getAs<FunctionProtoType>(), OldLoc: Old->getLocation(),
1806 New: NewType->getAs<FunctionProtoType>(), NewLoc: New->getLocation())) {
1807 New->setInvalidDecl();
1808 }
1809}
1810
1811/// CheckCXXDefaultArguments - Verify that the default arguments for a
1812/// function declaration are well-formed according to C++
1813/// [dcl.fct.default].
1814void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1815 // This checking doesn't make sense for explicit specializations; their
1816 // default arguments are determined by the declaration we're specializing,
1817 // not by FD.
1818 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1819 return;
1820 if (auto *FTD = FD->getDescribedFunctionTemplate())
1821 if (FTD->isMemberSpecialization())
1822 return;
1823
1824 unsigned NumParams = FD->getNumParams();
1825 unsigned ParamIdx = 0;
1826
1827 // Find first parameter with a default argument
1828 for (; ParamIdx < NumParams; ++ParamIdx) {
1829 ParmVarDecl *Param = FD->getParamDecl(i: ParamIdx);
1830 if (Param->hasDefaultArg())
1831 break;
1832 }
1833
1834 // C++20 [dcl.fct.default]p4:
1835 // In a given function declaration, each parameter subsequent to a parameter
1836 // with a default argument shall have a default argument supplied in this or
1837 // a previous declaration, unless the parameter was expanded from a
1838 // parameter pack, or shall be a function parameter pack.
1839 for (++ParamIdx; ParamIdx < NumParams; ++ParamIdx) {
1840 ParmVarDecl *Param = FD->getParamDecl(i: ParamIdx);
1841 if (Param->hasDefaultArg() || Param->isParameterPack() ||
1842 (CurrentInstantiationScope &&
1843 CurrentInstantiationScope->isLocalPackExpansion(D: Param)))
1844 continue;
1845 if (Param->isInvalidDecl())
1846 /* We already complained about this parameter. */;
1847 else if (Param->getIdentifier())
1848 Diag(Loc: Param->getLocation(), DiagID: diag::err_param_default_argument_missing_name)
1849 << Param->getIdentifier();
1850 else
1851 Diag(Loc: Param->getLocation(), DiagID: diag::err_param_default_argument_missing);
1852 }
1853}
1854
1855/// Check that the given type is a literal type. Issue a diagnostic if not,
1856/// if Kind is Diagnose.
1857/// \return \c true if a problem has been found (and optionally diagnosed).
1858template <typename... Ts>
1859static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind,
1860 SourceLocation Loc, QualType T, unsigned DiagID,
1861 Ts &&...DiagArgs) {
1862 if (T->isDependentType())
1863 return false;
1864
1865 switch (Kind) {
1866 case Sema::CheckConstexprKind::Diagnose:
1867 return SemaRef.RequireLiteralType(Loc, T, DiagID,
1868 std::forward<Ts>(DiagArgs)...);
1869
1870 case Sema::CheckConstexprKind::CheckValid:
1871 return !T->isLiteralType(Ctx: SemaRef.Context);
1872 }
1873
1874 llvm_unreachable("unknown CheckConstexprKind");
1875}
1876
1877/// Determine whether a destructor cannot be constexpr due to
1878static bool CheckConstexprDestructorSubobjects(Sema &SemaRef,
1879 const CXXDestructorDecl *DD,
1880 Sema::CheckConstexprKind Kind) {
1881 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1882 "this check is obsolete for C++23");
1883 auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) {
1884 const CXXRecordDecl *RD =
1885 T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1886 if (!RD || RD->hasConstexprDestructor())
1887 return true;
1888
1889 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1890 SemaRef.Diag(Loc: DD->getLocation(), DiagID: diag::err_constexpr_dtor_subobject)
1891 << static_cast<int>(DD->getConstexprKind()) << !FD
1892 << (FD ? FD->getDeclName() : DeclarationName()) << T;
1893 SemaRef.Diag(Loc, DiagID: diag::note_constexpr_dtor_subobject)
1894 << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T;
1895 }
1896 return false;
1897 };
1898
1899 const CXXRecordDecl *RD = DD->getParent();
1900 for (const CXXBaseSpecifier &B : RD->bases())
1901 if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr))
1902 return false;
1903 for (const FieldDecl *FD : RD->fields())
1904 if (!Check(FD->getLocation(), FD->getType(), FD))
1905 return false;
1906 return true;
1907}
1908
1909/// Check whether a function's parameter types are all literal types. If so,
1910/// return true. If not, produce a suitable diagnostic and return false.
1911static bool CheckConstexprParameterTypes(Sema &SemaRef,
1912 const FunctionDecl *FD,
1913 Sema::CheckConstexprKind Kind) {
1914 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1915 "this check is obsolete for C++23");
1916 unsigned ArgIndex = 0;
1917 const auto *FT = FD->getType()->castAs<FunctionProtoType>();
1918 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1919 e = FT->param_type_end();
1920 i != e; ++i, ++ArgIndex) {
1921 const ParmVarDecl *PD = FD->getParamDecl(i: ArgIndex);
1922 assert(PD && "null in a parameter list");
1923 SourceLocation ParamLoc = PD->getLocation();
1924 if (CheckLiteralType(SemaRef, Kind, Loc: ParamLoc, T: *i,
1925 DiagID: diag::err_constexpr_non_literal_param, DiagArgs: ArgIndex + 1,
1926 DiagArgs: PD->getSourceRange(), DiagArgs: isa<CXXConstructorDecl>(Val: FD),
1927 DiagArgs: FD->isConsteval()))
1928 return false;
1929 }
1930 return true;
1931}
1932
1933/// Check whether a function's return type is a literal type. If so, return
1934/// true. If not, produce a suitable diagnostic and return false.
1935static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD,
1936 Sema::CheckConstexprKind Kind) {
1937 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1938 "this check is obsolete for C++23");
1939 if (CheckLiteralType(SemaRef, Kind, Loc: FD->getLocation(), T: FD->getReturnType(),
1940 DiagID: diag::err_constexpr_non_literal_return,
1941 DiagArgs: FD->isConsteval()))
1942 return false;
1943 return true;
1944}
1945
1946/// Get diagnostic %select index for tag kind for
1947/// record diagnostic message.
1948/// WARNING: Indexes apply to particular diagnostics only!
1949///
1950/// \returns diagnostic %select index.
1951static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1952 switch (Tag) {
1953 case TagTypeKind::Struct:
1954 return 0;
1955 case TagTypeKind::Interface:
1956 return 1;
1957 case TagTypeKind::Class:
1958 return 2;
1959 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1960 }
1961}
1962
1963static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
1964 Stmt *Body,
1965 Sema::CheckConstexprKind Kind);
1966static bool CheckConstexprMissingReturn(Sema &SemaRef, const FunctionDecl *Dcl);
1967
1968bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD,
1969 CheckConstexprKind Kind) {
1970 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: NewFD);
1971 if (!getLangOpts().CPlusPlus26 && MD && MD->isInstance()) {
1972 // C++11 [dcl.constexpr]p4:
1973 // The definition of a constexpr constructor shall satisfy the following
1974 // constraints:
1975 // - the class shall not have any virtual base classes;
1976 //
1977 // FIXME: This only applies to constructors and destructors, not arbitrary
1978 // member functions.
1979 const CXXRecordDecl *RD = MD->getParent();
1980 if (RD->getNumVBases()) {
1981 if (Kind == CheckConstexprKind::CheckValid)
1982 return false;
1983
1984 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_constexpr_virtual_base)
1985 << isa<CXXConstructorDecl>(Val: NewFD)
1986 << getRecordDiagFromTagKind(Tag: RD->getTagKind()) << RD->getNumVBases();
1987 for (const auto &I : RD->vbases())
1988 Diag(Loc: I.getBeginLoc(), DiagID: diag::note_constexpr_virtual_base_here)
1989 << I.getSourceRange();
1990 return false;
1991 }
1992 }
1993
1994 if (!isa<CXXConstructorDecl>(Val: NewFD)) {
1995 // C++11 [dcl.constexpr]p3:
1996 // The definition of a constexpr function shall satisfy the following
1997 // constraints:
1998 // - it shall not be virtual; (removed in C++20)
1999 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: NewFD);
2000 if (Method && Method->isVirtual()) {
2001 if (getLangOpts().CPlusPlus20) {
2002 if (Kind == CheckConstexprKind::Diagnose)
2003 Diag(Loc: Method->getLocation(), DiagID: diag::warn_cxx17_compat_constexpr_virtual);
2004 } else {
2005 if (Kind == CheckConstexprKind::CheckValid)
2006 return false;
2007
2008 Method = Method->getCanonicalDecl();
2009 Diag(Loc: Method->getLocation(), DiagID: diag::err_constexpr_virtual);
2010
2011 // If it's not obvious why this function is virtual, find an overridden
2012 // function which uses the 'virtual' keyword.
2013 const CXXMethodDecl *WrittenVirtual = Method;
2014 while (!WrittenVirtual->isVirtualAsWritten())
2015 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
2016 if (WrittenVirtual != Method)
2017 Diag(Loc: WrittenVirtual->getLocation(),
2018 DiagID: diag::note_overridden_virtual_function);
2019 return false;
2020 }
2021 }
2022
2023 // - its return type shall be a literal type; (removed in C++23)
2024 if (!getLangOpts().CPlusPlus23 &&
2025 !CheckConstexprReturnType(SemaRef&: *this, FD: NewFD, Kind))
2026 return false;
2027 }
2028
2029 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Val: NewFD)) {
2030 // A destructor can be constexpr only if the defaulted destructor could be;
2031 // we don't need to check the members and bases if we already know they all
2032 // have constexpr destructors. (removed in C++23)
2033 if (!getLangOpts().CPlusPlus23 &&
2034 !Dtor->getParent()->defaultedDestructorIsConstexpr()) {
2035 if (Kind == CheckConstexprKind::CheckValid)
2036 return false;
2037 if (!CheckConstexprDestructorSubobjects(SemaRef&: *this, DD: Dtor, Kind))
2038 return false;
2039 }
2040 }
2041
2042 // - each of its parameter types shall be a literal type; (removed in C++23)
2043 if (!getLangOpts().CPlusPlus23 &&
2044 !CheckConstexprParameterTypes(SemaRef&: *this, FD: NewFD, Kind))
2045 return false;
2046
2047 Stmt *Body = NewFD->getBody();
2048 assert(Body &&
2049 "CheckConstexprFunctionDefinition called on function with no body");
2050 return CheckConstexprFunctionBody(SemaRef&: *this, Dcl: NewFD, Body, Kind);
2051}
2052
2053/// Check the given declaration statement is legal within a constexpr function
2054/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
2055///
2056/// \return true if the body is OK (maybe only as an extension), false if we
2057/// have diagnosed a problem.
2058static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
2059 DeclStmt *DS, SourceLocation &Cxx1yLoc,
2060 Sema::CheckConstexprKind Kind) {
2061 // C++11 [dcl.constexpr]p3 and p4:
2062 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
2063 // contain only
2064 for (const auto *DclIt : DS->decls()) {
2065 switch (DclIt->getKind()) {
2066 case Decl::StaticAssert:
2067 case Decl::Using:
2068 case Decl::UsingShadow:
2069 case Decl::UsingDirective:
2070 case Decl::UnresolvedUsingTypename:
2071 case Decl::UnresolvedUsingValue:
2072 case Decl::UsingEnum:
2073 // - static_assert-declarations
2074 // - using-declarations,
2075 // - using-directives,
2076 // - using-enum-declaration
2077 continue;
2078
2079 case Decl::CXXExpansionStmt:
2080 continue;
2081
2082 case Decl::Typedef:
2083 case Decl::TypeAlias: {
2084 // - typedef declarations and alias-declarations that do not define
2085 // classes or enumerations,
2086 const auto *TN = cast<TypedefNameDecl>(Val: DclIt);
2087 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
2088 // Don't allow variably-modified types in constexpr functions.
2089 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2090 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
2091 SemaRef.Diag(Loc: TL.getBeginLoc(), DiagID: diag::err_constexpr_vla)
2092 << TL.getSourceRange() << TL.getType()
2093 << isa<CXXConstructorDecl>(Val: Dcl);
2094 }
2095 return false;
2096 }
2097 continue;
2098 }
2099
2100 case Decl::Enum:
2101 case Decl::CXXRecord:
2102 // C++1y allows types to be defined, not just declared.
2103 if (cast<TagDecl>(Val: DclIt)->isThisDeclarationADefinition()) {
2104 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2105 SemaRef.DiagCompat(Loc: DS->getBeginLoc(),
2106 CompatDiagId: diag_compat::constexpr_type_definition)
2107 << isa<CXXConstructorDecl>(Val: Dcl);
2108 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
2109 return false;
2110 }
2111 }
2112 continue;
2113
2114 case Decl::EnumConstant:
2115 case Decl::IndirectField:
2116 case Decl::ParmVar:
2117 // These can only appear with other declarations which are banned in
2118 // C++11 and permitted in C++1y, so ignore them.
2119 continue;
2120
2121 case Decl::Var:
2122 case Decl::Decomposition: {
2123 // C++1y [dcl.constexpr]p3 allows anything except:
2124 // a definition of a variable of non-literal type or of static or
2125 // thread storage duration or [before C++2a] for which no
2126 // initialization is performed.
2127 const auto *VD = cast<VarDecl>(Val: DclIt);
2128 if (VD->isThisDeclarationADefinition()) {
2129 if (VD->isStaticLocal()) {
2130 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2131 SemaRef.DiagCompat(Loc: VD->getLocation(),
2132 CompatDiagId: diag_compat::constexpr_static_var)
2133 << isa<CXXConstructorDecl>(Val: Dcl)
2134 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
2135 } else if (!SemaRef.getLangOpts().CPlusPlus23) {
2136 return false;
2137 }
2138 }
2139 if (SemaRef.LangOpts.CPlusPlus23) {
2140 CheckLiteralType(SemaRef, Kind, Loc: VD->getLocation(), T: VD->getType(),
2141 DiagID: diag::warn_cxx20_compat_constexpr_var,
2142 DiagArgs: isa<CXXConstructorDecl>(Val: Dcl));
2143 } else if (CheckLiteralType(
2144 SemaRef, Kind, Loc: VD->getLocation(), T: VD->getType(),
2145 DiagID: diag::err_constexpr_local_var_non_literal_type,
2146 DiagArgs: isa<CXXConstructorDecl>(Val: Dcl))) {
2147 return false;
2148 }
2149 if (!VD->getType()->isDependentType() &&
2150 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
2151 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2152 SemaRef.DiagCompat(Loc: VD->getLocation(),
2153 CompatDiagId: diag_compat::constexpr_local_var_no_init)
2154 << isa<CXXConstructorDecl>(Val: Dcl);
2155 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2156 return false;
2157 }
2158 continue;
2159 }
2160 }
2161 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2162 SemaRef.DiagCompat(Loc: VD->getLocation(), CompatDiagId: diag_compat::constexpr_local_var)
2163 << isa<CXXConstructorDecl>(Val: Dcl);
2164 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
2165 return false;
2166 }
2167 continue;
2168 }
2169
2170 case Decl::NamespaceAlias:
2171 case Decl::Function:
2172 // These are disallowed in C++11 and permitted in C++1y. Allow them
2173 // everywhere as an extension.
2174 if (!Cxx1yLoc.isValid())
2175 Cxx1yLoc = DS->getBeginLoc();
2176 continue;
2177
2178 default:
2179 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2180 SemaRef.Diag(Loc: DS->getBeginLoc(), DiagID: diag::err_constexpr_body_invalid_stmt)
2181 << isa<CXXConstructorDecl>(Val: Dcl) << Dcl->isConsteval();
2182 }
2183 return false;
2184 }
2185 }
2186
2187 return true;
2188}
2189
2190/// Check that the given field is initialized within a constexpr constructor.
2191///
2192/// \param Dcl The constexpr constructor being checked.
2193/// \param Field The field being checked. This may be a member of an anonymous
2194/// struct or union nested within the class being checked.
2195/// \param Inits All declarations, including anonymous struct/union members and
2196/// indirect members, for which any initialization was provided.
2197/// \param Diagnosed Whether we've emitted the error message yet. Used to attach
2198/// multiple notes for different members to the same error.
2199/// \param Kind Whether we're diagnosing a constructor as written or determining
2200/// whether the formal requirements are satisfied.
2201/// \return \c false if we're checking for validity and the constructor does
2202/// not satisfy the requirements on a constexpr constructor.
2203static bool CheckConstexprCtorInitializer(Sema &SemaRef,
2204 const FunctionDecl *Dcl,
2205 FieldDecl *Field,
2206 llvm::SmallPtrSet<Decl *, 16> &Inits,
2207 bool &Diagnosed,
2208 Sema::CheckConstexprKind Kind) {
2209 // In C++20 onwards, there's nothing to check for validity.
2210 if (Kind == Sema::CheckConstexprKind::CheckValid &&
2211 SemaRef.getLangOpts().CPlusPlus20)
2212 return true;
2213
2214 if (Field->isInvalidDecl())
2215 return true;
2216
2217 if (Field->isUnnamedBitField())
2218 return true;
2219
2220 // Anonymous unions with no variant members and empty anonymous structs do not
2221 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
2222 // indirect fields don't need initializing.
2223 if (Field->isAnonymousStructOrUnion() &&
2224 (Field->getType()->isUnionType()
2225 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
2226 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
2227 return true;
2228
2229 if (!Inits.count(Ptr: Field)) {
2230 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2231 if (!Diagnosed) {
2232 SemaRef.DiagCompat(Loc: Dcl->getLocation(),
2233 CompatDiagId: diag_compat::constexpr_ctor_missing_init);
2234 Diagnosed = true;
2235 }
2236 SemaRef.Diag(Loc: Field->getLocation(),
2237 DiagID: diag::note_constexpr_ctor_missing_init);
2238 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2239 return false;
2240 }
2241 } else if (Field->isAnonymousStructOrUnion()) {
2242 const auto *RD = Field->getType()->castAsRecordDecl();
2243 for (auto *I : RD->fields())
2244 // If an anonymous union contains an anonymous struct of which any member
2245 // is initialized, all members must be initialized.
2246 if (!RD->isUnion() || Inits.count(Ptr: I))
2247 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, Field: I, Inits, Diagnosed,
2248 Kind))
2249 return false;
2250 }
2251 return true;
2252}
2253
2254/// Check the provided statement is allowed in a constexpr function
2255/// definition.
2256static bool
2257CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
2258 SmallVectorImpl<SourceLocation> &ReturnStmts,
2259 SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
2260 SourceLocation &Cxx2bLoc,
2261 Sema::CheckConstexprKind Kind) {
2262 // - its function-body shall be [...] a compound-statement that contains only
2263 switch (S->getStmtClass()) {
2264 case Stmt::NullStmtClass:
2265 // - null statements,
2266 return true;
2267
2268 case Stmt::DeclStmtClass:
2269 // - static_assert-declarations
2270 // - using-declarations,
2271 // - using-directives,
2272 // - typedef declarations and alias-declarations that do not define
2273 // classes or enumerations,
2274 if (!CheckConstexprDeclStmt(SemaRef, Dcl, DS: cast<DeclStmt>(Val: S), Cxx1yLoc, Kind))
2275 return false;
2276 return true;
2277
2278 case Stmt::ReturnStmtClass:
2279 // - and exactly one return statement;
2280 if (isa<CXXConstructorDecl>(Val: Dcl)) {
2281 // C++1y allows return statements in constexpr constructors.
2282 if (!Cxx1yLoc.isValid())
2283 Cxx1yLoc = S->getBeginLoc();
2284 return true;
2285 }
2286
2287 ReturnStmts.push_back(Elt: S->getBeginLoc());
2288 return true;
2289
2290 case Stmt::AttributedStmtClass:
2291 // Attributes on a statement don't affect its formal kind and hence don't
2292 // affect its validity in a constexpr function.
2293 return CheckConstexprFunctionStmt(
2294 SemaRef, Dcl, S: cast<AttributedStmt>(Val: S)->getSubStmt(), ReturnStmts,
2295 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind);
2296
2297 case Stmt::CompoundStmtClass: {
2298 // C++1y allows compound-statements.
2299 if (!Cxx1yLoc.isValid())
2300 Cxx1yLoc = S->getBeginLoc();
2301
2302 CompoundStmt *CompStmt = cast<CompoundStmt>(Val: S);
2303 for (auto *BodyIt : CompStmt->body()) {
2304 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, S: BodyIt, ReturnStmts,
2305 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2306 return false;
2307 }
2308 return true;
2309 }
2310
2311 case Stmt::IfStmtClass: {
2312 // C++1y allows if-statements.
2313 if (!Cxx1yLoc.isValid())
2314 Cxx1yLoc = S->getBeginLoc();
2315
2316 IfStmt *If = cast<IfStmt>(Val: S);
2317 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, S: If->getThen(), ReturnStmts,
2318 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2319 return false;
2320 if (If->getElse() &&
2321 !CheckConstexprFunctionStmt(SemaRef, Dcl, S: If->getElse(), ReturnStmts,
2322 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2323 return false;
2324 return true;
2325 }
2326
2327 case Stmt::WhileStmtClass:
2328 case Stmt::DoStmtClass:
2329 case Stmt::ForStmtClass:
2330 case Stmt::CXXForRangeStmtClass:
2331 case Stmt::ContinueStmtClass:
2332 // C++1y allows all of these. We don't allow them as extensions in C++11,
2333 // because they don't make sense without variable mutation.
2334 if (!SemaRef.getLangOpts().CPlusPlus14)
2335 break;
2336 if (!Cxx1yLoc.isValid())
2337 Cxx1yLoc = S->getBeginLoc();
2338 for (Stmt *SubStmt : S->children()) {
2339 if (SubStmt &&
2340 !CheckConstexprFunctionStmt(SemaRef, Dcl, S: SubStmt, ReturnStmts,
2341 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2342 return false;
2343 }
2344 return true;
2345
2346 case Stmt::SwitchStmtClass:
2347 case Stmt::CaseStmtClass:
2348 case Stmt::DefaultStmtClass:
2349 case Stmt::BreakStmtClass:
2350 // C++1y allows switch-statements, and since they don't need variable
2351 // mutation, we can reasonably allow them in C++11 as an extension.
2352 if (!Cxx1yLoc.isValid())
2353 Cxx1yLoc = S->getBeginLoc();
2354 for (Stmt *SubStmt : S->children()) {
2355 if (SubStmt &&
2356 !CheckConstexprFunctionStmt(SemaRef, Dcl, S: SubStmt, ReturnStmts,
2357 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2358 return false;
2359 }
2360 return true;
2361
2362 case Stmt::LabelStmtClass:
2363 case Stmt::GotoStmtClass:
2364 case Stmt::IndirectGotoStmtClass:
2365 if (Cxx2bLoc.isInvalid())
2366 Cxx2bLoc = S->getBeginLoc();
2367 for (Stmt *SubStmt : S->children()) {
2368 if (SubStmt &&
2369 !CheckConstexprFunctionStmt(SemaRef, Dcl, S: SubStmt, ReturnStmts,
2370 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2371 return false;
2372 }
2373 return true;
2374
2375 case Stmt::GCCAsmStmtClass:
2376 case Stmt::MSAsmStmtClass:
2377 // C++2a allows inline assembly statements.
2378 case Stmt::CXXTryStmtClass:
2379 if (Cxx2aLoc.isInvalid())
2380 Cxx2aLoc = S->getBeginLoc();
2381 for (Stmt *SubStmt : S->children()) {
2382 if (SubStmt &&
2383 !CheckConstexprFunctionStmt(SemaRef, Dcl, S: SubStmt, ReturnStmts,
2384 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2385 return false;
2386 }
2387 return true;
2388
2389 case Stmt::CXXCatchStmtClass:
2390 // Do not bother checking the language mode (already covered by the
2391 // try block check).
2392 if (!CheckConstexprFunctionStmt(
2393 SemaRef, Dcl, S: cast<CXXCatchStmt>(Val: S)->getHandlerBlock(), ReturnStmts,
2394 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2395 return false;
2396 return true;
2397
2398 default:
2399 if (!isa<Expr>(Val: S))
2400 break;
2401
2402 // C++1y allows expression-statements.
2403 if (!Cxx1yLoc.isValid())
2404 Cxx1yLoc = S->getBeginLoc();
2405 return true;
2406 }
2407
2408 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2409 SemaRef.Diag(Loc: S->getBeginLoc(), DiagID: diag::err_constexpr_body_invalid_stmt)
2410 << isa<CXXConstructorDecl>(Val: Dcl) << Dcl->isConsteval();
2411 }
2412 return false;
2413}
2414
2415/// Check the body for the given constexpr function declaration only contains
2416/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
2417///
2418/// \return true if the body is OK, false if we have found or diagnosed a
2419/// problem.
2420static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
2421 Stmt *Body,
2422 Sema::CheckConstexprKind Kind) {
2423 SmallVector<SourceLocation, 4> ReturnStmts;
2424
2425 if (isa<CXXTryStmt>(Val: Body)) {
2426 // C++11 [dcl.constexpr]p3:
2427 // The definition of a constexpr function shall satisfy the following
2428 // constraints: [...]
2429 // - its function-body shall be = delete, = default, or a
2430 // compound-statement
2431 //
2432 // C++11 [dcl.constexpr]p4:
2433 // In the definition of a constexpr constructor, [...]
2434 // - its function-body shall not be a function-try-block;
2435 //
2436 // This restriction is lifted in C++2a, as long as inner statements also
2437 // apply the general constexpr rules.
2438 switch (Kind) {
2439 case Sema::CheckConstexprKind::CheckValid:
2440 if (!SemaRef.getLangOpts().CPlusPlus20)
2441 return false;
2442 break;
2443
2444 case Sema::CheckConstexprKind::Diagnose:
2445 SemaRef.DiagCompat(Loc: Body->getBeginLoc(),
2446 CompatDiagId: diag_compat::constexpr_function_try_block)
2447 << isa<CXXConstructorDecl>(Val: Dcl);
2448 break;
2449 }
2450 }
2451
2452 // - its function-body shall be [...] a compound-statement that contains only
2453 // [... list of cases ...]
2454 //
2455 // Note that walking the children here is enough to properly check for
2456 // CompoundStmt and CXXTryStmt body.
2457 SourceLocation Cxx1yLoc, Cxx2aLoc, Cxx2bLoc;
2458 for (Stmt *SubStmt : Body->children()) {
2459 if (SubStmt &&
2460 !CheckConstexprFunctionStmt(SemaRef, Dcl, S: SubStmt, ReturnStmts,
2461 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2462 return false;
2463 }
2464
2465 if (Kind == Sema::CheckConstexprKind::CheckValid) {
2466 // If this is only valid as an extension, report that we don't satisfy the
2467 // constraints of the current language.
2468 if ((Cxx2bLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus23) ||
2469 (Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) ||
2470 (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
2471 return false;
2472 } else if (Cxx2bLoc.isValid()) {
2473 SemaRef.DiagCompat(Loc: Cxx2bLoc, CompatDiagId: diag_compat::cxx23_constexpr_body_invalid_stmt)
2474 << isa<CXXConstructorDecl>(Val: Dcl);
2475 } else if (Cxx2aLoc.isValid()) {
2476 SemaRef.DiagCompat(Loc: Cxx2aLoc, CompatDiagId: diag_compat::cxx20_constexpr_body_invalid_stmt)
2477 << isa<CXXConstructorDecl>(Val: Dcl);
2478 } else if (Cxx1yLoc.isValid()) {
2479 SemaRef.DiagCompat(Loc: Cxx1yLoc, CompatDiagId: diag_compat::cxx14_constexpr_body_invalid_stmt)
2480 << isa<CXXConstructorDecl>(Val: Dcl);
2481 }
2482
2483 if (const CXXConstructorDecl *Constructor
2484 = dyn_cast<CXXConstructorDecl>(Val: Dcl)) {
2485 const CXXRecordDecl *RD = Constructor->getParent();
2486 // DR1359:
2487 // - every non-variant non-static data member and base class sub-object
2488 // shall be initialized;
2489 // DR1460:
2490 // - if the class is a union having variant members, exactly one of them
2491 // shall be initialized;
2492 if (RD->isUnion()) {
2493 if (Constructor->getNumCtorInitializers() == 0 &&
2494 RD->hasVariantMembers()) {
2495 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2496 SemaRef.DiagCompat(Loc: Dcl->getLocation(),
2497 CompatDiagId: diag_compat::constexpr_union_ctor_no_init);
2498 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2499 return false;
2500 }
2501 }
2502 } else if (!Constructor->isDependentContext() &&
2503 !Constructor->isDelegatingConstructor()) {
2504 // Skip detailed checking if we have enough initializers, and we would
2505 // allow at most one initializer per member.
2506 bool AnyAnonStructUnionMembers = false;
2507 unsigned Fields = 0;
2508 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
2509 E = RD->field_end(); I != E; ++I, ++Fields) {
2510 if (I->isAnonymousStructOrUnion()) {
2511 AnyAnonStructUnionMembers = true;
2512 break;
2513 }
2514 }
2515 // DR1460:
2516 // - if the class is a union-like class, but is not a union, for each of
2517 // its anonymous union members having variant members, exactly one of
2518 // them shall be initialized;
2519 if (AnyAnonStructUnionMembers ||
2520 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2521 // Check initialization of non-static data members. Base classes are
2522 // always initialized so do not need to be checked. Dependent bases
2523 // might not have initializers in the member initializer list.
2524 llvm::SmallPtrSet<Decl *, 16> Inits;
2525 for (const auto *I: Constructor->inits()) {
2526 if (FieldDecl *FD = I->getMember())
2527 Inits.insert(Ptr: FD);
2528 else if (IndirectFieldDecl *ID = I->getIndirectMember())
2529 Inits.insert(I: ID->chain_begin(), E: ID->chain_end());
2530 }
2531
2532 bool Diagnosed = false;
2533 for (auto *I : RD->fields())
2534 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, Field: I, Inits, Diagnosed,
2535 Kind))
2536 return false;
2537 }
2538 }
2539 } else {
2540 if (ReturnStmts.empty()) {
2541 switch (Kind) {
2542 case Sema::CheckConstexprKind::Diagnose:
2543 if (!CheckConstexprMissingReturn(SemaRef, Dcl))
2544 return false;
2545 break;
2546
2547 case Sema::CheckConstexprKind::CheckValid:
2548 // The formal requirements don't include this rule in C++14, even
2549 // though the "must be able to produce a constant expression" rules
2550 // still imply it in some cases.
2551 if (!SemaRef.getLangOpts().CPlusPlus14)
2552 return false;
2553 break;
2554 }
2555 } else if (ReturnStmts.size() > 1) {
2556 switch (Kind) {
2557 case Sema::CheckConstexprKind::Diagnose:
2558 SemaRef.DiagCompat(Loc: ReturnStmts.back(),
2559 CompatDiagId: diag_compat::constexpr_body_multiple_return);
2560 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2561 SemaRef.Diag(Loc: ReturnStmts[I],
2562 DiagID: diag::note_constexpr_body_previous_return);
2563 break;
2564
2565 case Sema::CheckConstexprKind::CheckValid:
2566 if (!SemaRef.getLangOpts().CPlusPlus14)
2567 return false;
2568 break;
2569 }
2570 }
2571 }
2572
2573 // C++11 [dcl.constexpr]p5:
2574 // if no function argument values exist such that the function invocation
2575 // substitution would produce a constant expression, the program is
2576 // ill-formed; no diagnostic required.
2577 // C++11 [dcl.constexpr]p3:
2578 // - every constructor call and implicit conversion used in initializing the
2579 // return value shall be one of those allowed in a constant expression.
2580 // C++11 [dcl.constexpr]p4:
2581 // - every constructor involved in initializing non-static data members and
2582 // base class sub-objects shall be a constexpr constructor.
2583 //
2584 // Note that this rule is distinct from the "requirements for a constexpr
2585 // function", so is not checked in CheckValid mode. Because the check for
2586 // constexpr potential is expensive, skip the check if the diagnostic is
2587 // disabled, the function is declared in a system header, or we're in C++23
2588 // or later mode (see https://wg21.link/P2448).
2589 bool SkipCheck =
2590 !SemaRef.getLangOpts().CheckConstexprFunctionBodies ||
2591 SemaRef.getSourceManager().isInSystemHeader(Loc: Dcl->getLocation()) ||
2592 SemaRef.getDiagnostics().isIgnored(
2593 DiagID: diag::ext_constexpr_function_never_constant_expr, Loc: Dcl->getLocation());
2594 SmallVector<PartialDiagnosticAt, 8> Diags;
2595 if (Kind == Sema::CheckConstexprKind::Diagnose && !SkipCheck &&
2596 !Expr::isPotentialConstantExpr(FD: Dcl, Diags)) {
2597 SemaRef.Diag(Loc: Dcl->getLocation(),
2598 DiagID: diag::ext_constexpr_function_never_constant_expr)
2599 << isa<CXXConstructorDecl>(Val: Dcl) << Dcl->isConsteval()
2600 << Dcl->getNameInfo().getSourceRange();
2601 for (const auto &Diag : Diags)
2602 SemaRef.Diag(Loc: Diag.first, PD: Diag.second);
2603 // Don't return false here: we allow this for compatibility in
2604 // system headers.
2605 }
2606
2607 return true;
2608}
2609
2610static bool CheckConstexprMissingReturn(Sema &SemaRef,
2611 const FunctionDecl *Dcl) {
2612 bool IsVoidOrDependentType = Dcl->getReturnType()->isVoidType() ||
2613 Dcl->getReturnType()->isDependentType();
2614 // Skip emitting a missing return error diagnostic for non-void functions
2615 // since C++23 no longer mandates constexpr functions to yield constant
2616 // expressions.
2617 if (SemaRef.getLangOpts().CPlusPlus23 && !IsVoidOrDependentType)
2618 return true;
2619
2620 // C++14 doesn't require constexpr functions to contain a 'return'
2621 // statement. We still do, unless the return type might be void, because
2622 // otherwise if there's no return statement, the function cannot
2623 // be used in a core constant expression.
2624 bool OK = SemaRef.getLangOpts().CPlusPlus14 && IsVoidOrDependentType;
2625 SemaRef.Diag(Loc: Dcl->getLocation(),
2626 DiagID: OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2627 : diag::err_constexpr_body_no_return)
2628 << Dcl->isConsteval();
2629 return OK;
2630}
2631
2632bool Sema::CheckImmediateEscalatingFunctionDefinition(
2633 FunctionDecl *FD, const sema::FunctionScopeInfo *FSI) {
2634 if (!getLangOpts().CPlusPlus20 || !FD->isImmediateEscalating())
2635 return true;
2636 FD->setBodyContainsImmediateEscalatingExpressions(
2637 FSI->FoundImmediateEscalatingExpression);
2638 if (FSI->FoundImmediateEscalatingExpression) {
2639 auto it = UndefinedButUsed.find(Key: FD->getCanonicalDecl());
2640 if (it != UndefinedButUsed.end()) {
2641 Diag(Loc: it->second, DiagID: diag::err_immediate_function_used_before_definition)
2642 << it->first;
2643 Diag(Loc: FD->getLocation(), DiagID: diag::note_defined_here) << FD;
2644 if (FD->isImmediateFunction() && !FD->isConsteval())
2645 DiagnoseImmediateEscalatingReason(FD);
2646 return false;
2647 }
2648 }
2649 return true;
2650}
2651
2652void Sema::DiagnoseImmediateEscalatingReason(FunctionDecl *FD) {
2653 assert(FD->isImmediateEscalating() && !FD->isConsteval() &&
2654 "expected an immediate function");
2655 assert(FD->hasBody() && "expected the function to have a body");
2656 struct ImmediateEscalatingExpressionsVisitor : DynamicRecursiveASTVisitor {
2657 Sema &SemaRef;
2658
2659 const FunctionDecl *ImmediateFn;
2660 bool ImmediateFnIsConstructor;
2661 CXXConstructorDecl *CurrentConstructor = nullptr;
2662 CXXCtorInitializer *CurrentInit = nullptr;
2663
2664 ImmediateEscalatingExpressionsVisitor(Sema &SemaRef, FunctionDecl *FD)
2665 : SemaRef(SemaRef), ImmediateFn(FD),
2666 ImmediateFnIsConstructor(isa<CXXConstructorDecl>(Val: FD)) {
2667 ShouldVisitImplicitCode = true;
2668 ShouldVisitLambdaBody = false;
2669 }
2670
2671 void Diag(const Expr *E, const FunctionDecl *Fn, bool IsCall) {
2672 SourceLocation Loc = E->getBeginLoc();
2673 SourceRange Range = E->getSourceRange();
2674 if (CurrentConstructor && CurrentInit) {
2675 Loc = CurrentConstructor->getLocation();
2676 Range = CurrentInit->isWritten() ? CurrentInit->getSourceRange()
2677 : SourceRange();
2678 }
2679
2680 FieldDecl* InitializedField = CurrentInit ? CurrentInit->getAnyMember() : nullptr;
2681
2682 SemaRef.Diag(Loc, DiagID: diag::note_immediate_function_reason)
2683 << ImmediateFn << Fn << Fn->isConsteval() << IsCall
2684 << isa<CXXConstructorDecl>(Val: Fn) << ImmediateFnIsConstructor
2685 << (InitializedField != nullptr)
2686 << (CurrentInit && !CurrentInit->isWritten())
2687 << InitializedField << Range;
2688 }
2689 bool TraverseCallExpr(CallExpr *E) override {
2690 if (const auto *DR =
2691 dyn_cast<DeclRefExpr>(Val: E->getCallee()->IgnoreImplicit());
2692 DR && DR->isImmediateEscalating()) {
2693 Diag(E, Fn: E->getDirectCallee(), /*IsCall=*/true);
2694 return false;
2695 }
2696
2697 for (Expr *A : E->arguments())
2698 if (!TraverseStmt(S: A))
2699 return false;
2700
2701 return true;
2702 }
2703
2704 bool VisitDeclRefExpr(DeclRefExpr *E) override {
2705 if (const auto *ReferencedFn = dyn_cast<FunctionDecl>(Val: E->getDecl());
2706 ReferencedFn && E->isImmediateEscalating()) {
2707 Diag(E, Fn: ReferencedFn, /*IsCall=*/false);
2708 return false;
2709 }
2710
2711 return true;
2712 }
2713
2714 bool VisitCXXConstructExpr(CXXConstructExpr *E) override {
2715 CXXConstructorDecl *D = E->getConstructor();
2716 if (E->isImmediateEscalating()) {
2717 Diag(E, Fn: D, /*IsCall=*/true);
2718 return false;
2719 }
2720 return true;
2721 }
2722
2723 bool TraverseConstructorInitializer(CXXCtorInitializer *Init) override {
2724 llvm::SaveAndRestore RAII(CurrentInit, Init);
2725 return DynamicRecursiveASTVisitor::TraverseConstructorInitializer(Init);
2726 }
2727
2728 bool TraverseCXXConstructorDecl(CXXConstructorDecl *Ctr) override {
2729 llvm::SaveAndRestore RAII(CurrentConstructor, Ctr);
2730 return DynamicRecursiveASTVisitor::TraverseCXXConstructorDecl(D: Ctr);
2731 }
2732
2733 bool TraverseType(QualType T, bool TraverseQualifier) override {
2734 return true;
2735 }
2736 bool VisitBlockExpr(BlockExpr *T) override { return true; }
2737
2738 } Visitor(*this, FD);
2739 Visitor.TraverseDecl(D: FD);
2740}
2741
2742CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {
2743 assert(getLangOpts().CPlusPlus && "No class names in C!");
2744
2745 if (SS && SS->isInvalid())
2746 return nullptr;
2747
2748 if (SS && SS->isNotEmpty()) {
2749 DeclContext *DC = computeDeclContext(SS: *SS, EnteringContext: true);
2750 return dyn_cast_or_null<CXXRecordDecl>(Val: DC);
2751 }
2752
2753 return dyn_cast_or_null<CXXRecordDecl>(Val: CurContext);
2754}
2755
2756bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,
2757 const CXXScopeSpec *SS) {
2758 CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2759 return CurDecl && &II == CurDecl->getIdentifier();
2760}
2761
2762bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2763 assert(getLangOpts().CPlusPlus && "No class names in C!");
2764
2765 if (!getLangOpts().SpellChecking)
2766 return false;
2767
2768 CXXRecordDecl *CurDecl;
2769 if (SS && SS->isSet() && !SS->isInvalid()) {
2770 DeclContext *DC = computeDeclContext(SS: *SS, EnteringContext: true);
2771 CurDecl = dyn_cast_or_null<CXXRecordDecl>(Val: DC);
2772 } else
2773 CurDecl = dyn_cast_or_null<CXXRecordDecl>(Val: CurContext);
2774
2775 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2776 3 * II->getName().edit_distance(Other: CurDecl->getIdentifier()->getName())
2777 < II->getLength()) {
2778 II = CurDecl->getIdentifier();
2779 return true;
2780 }
2781
2782 return false;
2783}
2784
2785CXXBaseSpecifier *Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2786 SourceRange SpecifierRange,
2787 bool Virtual, AccessSpecifier Access,
2788 TypeSourceInfo *TInfo,
2789 SourceLocation EllipsisLoc) {
2790 QualType BaseType = TInfo->getType();
2791 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2792 if (BaseType->containsErrors()) {
2793 // Already emitted a diagnostic when parsing the error type.
2794 return nullptr;
2795 }
2796
2797 if (EllipsisLoc.isValid() && !BaseType->containsUnexpandedParameterPack()) {
2798 Diag(Loc: EllipsisLoc, DiagID: diag::err_pack_expansion_without_parameter_packs)
2799 << TInfo->getTypeLoc().getSourceRange();
2800 EllipsisLoc = SourceLocation();
2801 }
2802
2803 auto *BaseDecl =
2804 dyn_cast_if_present<CXXRecordDecl>(Val: computeDeclContext(T: BaseType));
2805 // C++ [class.derived.general]p2:
2806 // A class-or-decltype shall denote a (possibly cv-qualified) class type
2807 // that is not an incompletely defined class; any cv-qualifiers are
2808 // ignored.
2809 if (BaseDecl) {
2810 // C++ [class.union.general]p4:
2811 // [...] A union shall not be used as a base class.
2812 if (BaseDecl->isUnion()) {
2813 Diag(Loc: BaseLoc, DiagID: diag::err_union_as_base_class) << SpecifierRange;
2814 return nullptr;
2815 }
2816
2817 if (BaseType.hasQualifiers()) {
2818 std::string Quals =
2819 BaseType.getQualifiers().getAsString(Policy: Context.getPrintingPolicy());
2820 Diag(Loc: BaseLoc, DiagID: diag::warn_qual_base_type)
2821 << Quals << llvm::count(Range&: Quals, Element: ' ') + 1 << BaseType;
2822 Diag(Loc: BaseLoc, DiagID: diag::note_base_class_specified_here) << BaseType;
2823 }
2824
2825 // For the MS ABI, propagate DLL attributes to base class templates.
2826 if (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
2827 Context.getTargetInfo().getTriple().isPS()) {
2828 if (Attr *ClassAttr = getDLLAttr(D: Class)) {
2829 if (auto *BaseSpec =
2830 dyn_cast<ClassTemplateSpecializationDecl>(Val: BaseDecl)) {
2831 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplateSpec: BaseSpec,
2832 BaseLoc);
2833 }
2834 }
2835 }
2836
2837 if (RequireCompleteType(Loc: BaseLoc, T: BaseType, DiagID: diag::err_incomplete_base_class,
2838 Args: SpecifierRange)) {
2839 Class->setInvalidDecl();
2840 return nullptr;
2841 }
2842
2843 BaseDecl = BaseDecl->getDefinition();
2844 assert(BaseDecl && "Base type is not incomplete, but has no definition");
2845
2846 // Microsoft docs say:
2847 // "If a base-class has a code_seg attribute, derived classes must have the
2848 // same attribute."
2849 const auto *BaseCSA = BaseDecl->getAttr<CodeSegAttr>();
2850 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2851 if ((DerivedCSA || BaseCSA) &&
2852 (!BaseCSA || !DerivedCSA ||
2853 BaseCSA->getName() != DerivedCSA->getName())) {
2854 Diag(Loc: Class->getLocation(), DiagID: diag::err_mismatched_code_seg_base);
2855 Diag(Loc: BaseDecl->getLocation(), DiagID: diag::note_base_class_specified_here)
2856 << BaseDecl;
2857 return nullptr;
2858 }
2859
2860 // A class which contains a flexible array member is not suitable for use as
2861 // a base class:
2862 // - If the layout determines that a base comes before another base,
2863 // the flexible array member would index into the subsequent base.
2864 // - If the layout determines that base comes before the derived class,
2865 // the flexible array member would index into the derived class.
2866 if (BaseDecl->hasFlexibleArrayMember()) {
2867 Diag(Loc: BaseLoc, DiagID: diag::err_base_class_has_flexible_array_member)
2868 << BaseDecl->getDeclName();
2869 return nullptr;
2870 }
2871
2872 // C++ [class]p3:
2873 // If a class is marked final and it appears as a base-type-specifier in
2874 // base-clause, the program is ill-formed.
2875 if (FinalAttr *FA = BaseDecl->getAttr<FinalAttr>()) {
2876 Diag(Loc: BaseLoc, DiagID: diag::err_class_marked_final_used_as_base)
2877 << BaseDecl->getDeclName() << FA->isSpelledAsSealed();
2878 Diag(Loc: BaseDecl->getLocation(), DiagID: diag::note_entity_declared_at)
2879 << BaseDecl->getDeclName() << FA->getRange();
2880 return nullptr;
2881 }
2882
2883 // If the base class is invalid the derived class is as well.
2884 if (BaseDecl->isInvalidDecl())
2885 Class->setInvalidDecl();
2886 } else if (BaseType->isDependentType()) {
2887 // Make sure that we don't make an ill-formed AST where the type of the
2888 // Class is non-dependent and its attached base class specifier is an
2889 // dependent type, which violates invariants in many clang code paths (e.g.
2890 // constexpr evaluator). If this case happens (in errory-recovery mode), we
2891 // explicitly mark the Class decl invalid. The diagnostic was already
2892 // emitted.
2893 if (!Class->isDependentContext())
2894 Class->setInvalidDecl();
2895 } else {
2896 // The base class is some non-dependent non-class type.
2897 Diag(Loc: BaseLoc, DiagID: diag::err_base_must_be_class) << SpecifierRange;
2898 return nullptr;
2899 }
2900
2901 // In HLSL, unspecified class access is public rather than private.
2902 if (getLangOpts().HLSL && Class->getTagKind() == TagTypeKind::Class &&
2903 Access == AS_none)
2904 Access = AS_public;
2905
2906 // Create the base specifier.
2907 return new (Context) CXXBaseSpecifier(
2908 SpecifierRange, Virtual, Class->getTagKind() == TagTypeKind::Class,
2909 Access, TInfo, EllipsisLoc);
2910}
2911
2912BaseResult Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2913 const ParsedAttributesView &Attributes,
2914 bool Virtual, AccessSpecifier Access,
2915 ParsedType basetype, SourceLocation BaseLoc,
2916 SourceLocation EllipsisLoc) {
2917 if (!classdecl)
2918 return true;
2919
2920 AdjustDeclIfTemplate(Decl&: classdecl);
2921 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Val: classdecl);
2922 if (!Class)
2923 return true;
2924
2925 // We haven't yet attached the base specifiers.
2926 Class->setIsParsingBaseSpecifiers();
2927
2928 // We do not support any C++11 attributes on base-specifiers yet.
2929 // Diagnose any attributes we see.
2930 for (const ParsedAttr &AL : Attributes) {
2931 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2932 continue;
2933 if (AL.getKind() == ParsedAttr::UnknownAttribute)
2934 DiagnoseUnknownAttribute(AL);
2935 else
2936 Diag(Loc: AL.getLoc(), DiagID: diag::err_base_specifier_attribute)
2937 << AL << AL.isRegularKeywordAttribute() << AL.getRange();
2938 }
2939
2940 TypeSourceInfo *TInfo = nullptr;
2941 GetTypeFromParser(Ty: basetype, TInfo: &TInfo);
2942
2943 if (EllipsisLoc.isInvalid() &&
2944 DiagnoseUnexpandedParameterPack(Loc: SpecifierRange.getBegin(), T: TInfo,
2945 UPPC: UPPC_BaseType))
2946 return true;
2947
2948 // C++ [class.union.general]p4:
2949 // [...] A union shall not have base classes.
2950 if (Class->isUnion()) {
2951 Diag(Loc: Class->getLocation(), DiagID: diag::err_base_clause_on_union)
2952 << SpecifierRange;
2953 return true;
2954 }
2955
2956 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2957 Virtual, Access, TInfo,
2958 EllipsisLoc))
2959 return BaseSpec;
2960
2961 Class->setInvalidDecl();
2962 return true;
2963}
2964
2965/// Use small set to collect indirect bases. As this is only used
2966/// locally, there's no need to abstract the small size parameter.
2967typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2968
2969/// Recursively add the bases of Type. Don't add Type itself.
2970static void
2971NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2972 const QualType &Type)
2973{
2974 // Even though the incoming type is a base, it might not be
2975 // a class -- it could be a template parm, for instance.
2976 if (const auto *Decl = Type->getAsCXXRecordDecl()) {
2977 // Iterate over its bases.
2978 for (const auto &BaseSpec : Decl->bases()) {
2979 QualType Base = Context.getCanonicalType(T: BaseSpec.getType())
2980 .getUnqualifiedType();
2981 if (Set.insert(Ptr: Base).second)
2982 // If we've not already seen it, recurse.
2983 NoteIndirectBases(Context, Set, Type: Base);
2984 }
2985 }
2986}
2987
2988bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2989 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2990 if (Bases.empty())
2991 return false;
2992
2993 // Used to keep track of which base types we have already seen, so
2994 // that we can properly diagnose redundant direct base types. Note
2995 // that the key is always the unqualified canonical type of the base
2996 // class.
2997 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2998
2999 // Used to track indirect bases so we can see if a direct base is
3000 // ambiguous.
3001 IndirectBaseSet IndirectBaseTypes;
3002
3003 // Copy non-redundant base specifiers into permanent storage.
3004 unsigned NumGoodBases = 0;
3005 bool Invalid = false;
3006 for (unsigned idx = 0; idx < Bases.size(); ++idx) {
3007 QualType NewBaseType
3008 = Context.getCanonicalType(T: Bases[idx]->getType());
3009 NewBaseType = NewBaseType.getLocalUnqualifiedType();
3010
3011 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
3012 if (KnownBase) {
3013 // C++ [class.mi]p3:
3014 // A class shall not be specified as a direct base class of a
3015 // derived class more than once.
3016 Diag(Loc: Bases[idx]->getBeginLoc(), DiagID: diag::err_duplicate_base_class)
3017 << KnownBase->getType() << Bases[idx]->getSourceRange();
3018
3019 // Delete the duplicate base class specifier; we're going to
3020 // overwrite its pointer later.
3021 Context.Deallocate(Ptr: Bases[idx]);
3022
3023 Invalid = true;
3024 } else {
3025 // Okay, add this new base class.
3026 KnownBase = Bases[idx];
3027 Bases[NumGoodBases++] = Bases[idx];
3028
3029 if (NewBaseType->isDependentType())
3030 continue;
3031 // Note this base's direct & indirect bases, if there could be ambiguity.
3032 if (Bases.size() > 1)
3033 NoteIndirectBases(Context, Set&: IndirectBaseTypes, Type: NewBaseType);
3034
3035 if (const auto *RD = NewBaseType->getAsCXXRecordDecl()) {
3036 if (Class->isInterface() &&
3037 (!RD->isInterfaceLike() ||
3038 KnownBase->getAccessSpecifier() != AS_public)) {
3039 // The Microsoft extension __interface does not permit bases that
3040 // are not themselves public interfaces.
3041 Diag(Loc: KnownBase->getBeginLoc(), DiagID: diag::err_invalid_base_in_interface)
3042 << getRecordDiagFromTagKind(Tag: RD->getTagKind()) << RD
3043 << RD->getSourceRange();
3044 Invalid = true;
3045 }
3046 if (RD->hasAttr<WeakAttr>())
3047 Class->addAttr(A: WeakAttr::CreateImplicit(Ctx&: Context));
3048 }
3049 }
3050 }
3051
3052 // Attach the remaining base class specifiers to the derived class.
3053 Class->setBases(Bases: Bases.data(), NumBases: NumGoodBases);
3054
3055 // Check that the only base classes that are duplicate are virtual.
3056 for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
3057 // Check whether this direct base is inaccessible due to ambiguity.
3058 QualType BaseType = Bases[idx]->getType();
3059
3060 // Skip all dependent types in templates being used as base specifiers.
3061 // Checks below assume that the base specifier is a CXXRecord.
3062 if (BaseType->isDependentType())
3063 continue;
3064
3065 CanQualType CanonicalBase = Context.getCanonicalType(T: BaseType)
3066 .getUnqualifiedType();
3067
3068 if (IndirectBaseTypes.count(Ptr: CanonicalBase)) {
3069 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3070 /*DetectVirtual=*/true);
3071 bool found
3072 = Class->isDerivedFrom(Base: CanonicalBase->getAsCXXRecordDecl(), Paths);
3073 assert(found);
3074 (void)found;
3075
3076 if (Paths.isAmbiguous(BaseType: CanonicalBase))
3077 Diag(Loc: Bases[idx]->getBeginLoc(), DiagID: diag::warn_inaccessible_base_class)
3078 << BaseType << getAmbiguousPathsDisplayString(Paths)
3079 << Bases[idx]->getSourceRange();
3080 else
3081 assert(Bases[idx]->isVirtual());
3082 }
3083
3084 // Delete the base class specifier, since its data has been copied
3085 // into the CXXRecordDecl.
3086 Context.Deallocate(Ptr: Bases[idx]);
3087 }
3088
3089 return Invalid;
3090}
3091
3092void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
3093 MutableArrayRef<CXXBaseSpecifier *> Bases) {
3094 if (!ClassDecl || Bases.empty())
3095 return;
3096
3097 AdjustDeclIfTemplate(Decl&: ClassDecl);
3098 AttachBaseSpecifiers(Class: cast<CXXRecordDecl>(Val: ClassDecl), Bases);
3099}
3100
3101bool Sema::IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived,
3102 CXXRecordDecl *Base, CXXBasePaths &Paths) {
3103 if (!getLangOpts().CPlusPlus)
3104 return false;
3105
3106 if (!Base || !Derived)
3107 return false;
3108
3109 // If either the base or the derived type is invalid, don't try to
3110 // check whether one is derived from the other.
3111 if (Base->isInvalidDecl() || Derived->isInvalidDecl())
3112 return false;
3113
3114 // FIXME: In a modules build, do we need the entire path to be visible for us
3115 // to be able to use the inheritance relationship?
3116 if (!isCompleteType(Loc, T: Context.getCanonicalTagType(TD: Derived)) &&
3117 !Derived->isBeingDefined())
3118 return false;
3119
3120 return Derived->isDerivedFrom(Base, Paths);
3121}
3122
3123bool Sema::IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived,
3124 CXXRecordDecl *Base) {
3125 CXXBasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/false,
3126 /*DetectVirtual=*/false);
3127 return IsDerivedFrom(Loc, Derived, Base, Paths);
3128}
3129
3130bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
3131 CXXBasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/false,
3132 /*DetectVirtual=*/false);
3133 return IsDerivedFrom(Loc, Derived: Derived->getAsCXXRecordDecl(),
3134 Base: Base->getAsCXXRecordDecl(), Paths);
3135}
3136
3137bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
3138 CXXBasePaths &Paths) {
3139 return IsDerivedFrom(Loc, Derived: Derived->getAsCXXRecordDecl(),
3140 Base: Base->getAsCXXRecordDecl(), Paths);
3141}
3142
3143static void BuildBasePathArray(const CXXBasePath &Path,
3144 CXXCastPath &BasePathArray) {
3145 // We first go backward and check if we have a virtual base.
3146 // FIXME: It would be better if CXXBasePath had the base specifier for
3147 // the nearest virtual base.
3148 unsigned Start = 0;
3149 for (unsigned I = Path.size(); I != 0; --I) {
3150 if (Path[I - 1].Base->isVirtual()) {
3151 Start = I - 1;
3152 break;
3153 }
3154 }
3155
3156 // Now add all bases.
3157 for (unsigned I = Start, E = Path.size(); I != E; ++I)
3158 BasePathArray.push_back(Elt: const_cast<CXXBaseSpecifier*>(Path[I].Base));
3159}
3160
3161
3162void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
3163 CXXCastPath &BasePathArray) {
3164 assert(BasePathArray.empty() && "Base path array must be empty!");
3165 assert(Paths.isRecordingPaths() && "Must record paths!");
3166 return ::BuildBasePathArray(Path: Paths.front(), BasePathArray);
3167}
3168
3169bool
3170Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
3171 unsigned InaccessibleBaseID,
3172 unsigned AmbiguousBaseConvID,
3173 SourceLocation Loc, SourceRange Range,
3174 DeclarationName Name,
3175 CXXCastPath *BasePath,
3176 bool IgnoreAccess) {
3177 // First, determine whether the path from Derived to Base is
3178 // ambiguous. This is slightly more expensive than checking whether
3179 // the Derived to Base conversion exists, because here we need to
3180 // explore multiple paths to determine if there is an ambiguity.
3181 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3182 /*DetectVirtual=*/false);
3183 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
3184 if (!DerivationOkay)
3185 return true;
3186
3187 const CXXBasePath *Path = nullptr;
3188 if (!Paths.isAmbiguous(BaseType: Context.getCanonicalType(T: Base).getUnqualifiedType()))
3189 Path = &Paths.front();
3190
3191 // For MSVC compatibility, check if Derived directly inherits from Base. Clang
3192 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
3193 // user to access such bases.
3194 if (!Path && getLangOpts().MSVCCompat) {
3195 for (const CXXBasePath &PossiblePath : Paths) {
3196 if (PossiblePath.size() == 1) {
3197 Path = &PossiblePath;
3198 if (AmbiguousBaseConvID)
3199 Diag(Loc, DiagID: diag::ext_ms_ambiguous_direct_base)
3200 << Base << Derived << Range;
3201 break;
3202 }
3203 }
3204 }
3205
3206 if (Path) {
3207 if (!IgnoreAccess) {
3208 // Check that the base class can be accessed.
3209 switch (
3210 CheckBaseClassAccess(AccessLoc: Loc, Base, Derived, Path: *Path, DiagID: InaccessibleBaseID)) {
3211 case AR_inaccessible:
3212 return true;
3213 case AR_accessible:
3214 case AR_dependent:
3215 case AR_delayed:
3216 break;
3217 }
3218 }
3219
3220 // Build a base path if necessary.
3221 if (BasePath)
3222 ::BuildBasePathArray(Path: *Path, BasePathArray&: *BasePath);
3223 return false;
3224 }
3225
3226 if (AmbiguousBaseConvID) {
3227 // We know that the derived-to-base conversion is ambiguous, and
3228 // we're going to produce a diagnostic. Perform the derived-to-base
3229 // search just one more time to compute all of the possible paths so
3230 // that we can print them out. This is more expensive than any of
3231 // the previous derived-to-base checks we've done, but at this point
3232 // performance isn't as much of an issue.
3233 Paths.clear();
3234 Paths.setRecordingPaths(true);
3235 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
3236 assert(StillOkay && "Can only be used with a derived-to-base conversion");
3237 (void)StillOkay;
3238
3239 // Build up a textual representation of the ambiguous paths, e.g.,
3240 // D -> B -> A, that will be used to illustrate the ambiguous
3241 // conversions in the diagnostic. We only print one of the paths
3242 // to each base class subobject.
3243 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3244
3245 Diag(Loc, DiagID: AmbiguousBaseConvID)
3246 << Derived << Base << PathDisplayStr << Range << Name;
3247 }
3248 return true;
3249}
3250
3251bool
3252Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
3253 SourceLocation Loc, SourceRange Range,
3254 CXXCastPath *BasePath,
3255 bool IgnoreAccess) {
3256 return CheckDerivedToBaseConversion(
3257 Derived, Base, InaccessibleBaseID: diag::err_upcast_to_inaccessible_base,
3258 AmbiguousBaseConvID: diag::err_ambiguous_derived_to_base_conv, Loc, Range, Name: DeclarationName(),
3259 BasePath, IgnoreAccess);
3260}
3261
3262std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
3263 std::string PathDisplayStr;
3264 std::set<unsigned> DisplayedPaths;
3265 for (const CXXBasePath &Path : Paths) {
3266 if (DisplayedPaths.insert(x: Path.back().SubobjectNumber).second) {
3267 // We haven't displayed a path to this particular base
3268 // class subobject yet.
3269 PathDisplayStr += "\n ";
3270 PathDisplayStr += QualType(Context.getCanonicalTagType(TD: Paths.getOrigin()))
3271 .getAsString();
3272 for (const CXXBasePathElement &Element : Path)
3273 PathDisplayStr += " -> " + Element.Base->getType().getAsString();
3274 }
3275 }
3276
3277 return PathDisplayStr;
3278}
3279
3280//===----------------------------------------------------------------------===//
3281// C++ class member Handling
3282//===----------------------------------------------------------------------===//
3283
3284bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
3285 SourceLocation ColonLoc,
3286 const ParsedAttributesView &Attrs) {
3287 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
3288 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(C&: Context, AS: Access, DC: CurContext,
3289 ASLoc, ColonLoc);
3290 CurContext->addHiddenDecl(D: ASDecl);
3291 return ProcessAccessDeclAttributeList(ASDecl, AttrList: Attrs);
3292}
3293
3294void Sema::CheckOverrideControl(NamedDecl *D) {
3295 if (D->isInvalidDecl())
3296 return;
3297
3298 // We only care about "override" and "final" declarations.
3299 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
3300 return;
3301
3302 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: D);
3303
3304 // We can't check dependent instance methods.
3305 if (MD && MD->isInstance() &&
3306 (MD->getParent()->hasAnyDependentBases() ||
3307 MD->getType()->isDependentType()))
3308 return;
3309
3310 if (MD && !MD->isVirtual()) {
3311 // If we have a non-virtual method, check if it hides a virtual method.
3312 // (In that case, it's most likely the method has the wrong type.)
3313 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3314 FindHiddenVirtualMethods(MD, OverloadedMethods);
3315
3316 if (!OverloadedMethods.empty()) {
3317 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3318 Diag(Loc: OA->getLocation(),
3319 DiagID: diag::override_keyword_hides_virtual_member_function)
3320 << "override" << (OverloadedMethods.size() > 1);
3321 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3322 Diag(Loc: FA->getLocation(),
3323 DiagID: diag::override_keyword_hides_virtual_member_function)
3324 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3325 << (OverloadedMethods.size() > 1);
3326 }
3327 NoteHiddenVirtualMethods(MD, OverloadedMethods);
3328 MD->setInvalidDecl();
3329 return;
3330 }
3331 // Fall through into the general case diagnostic.
3332 // FIXME: We might want to attempt typo correction here.
3333 }
3334
3335 if (!MD || !MD->isVirtual()) {
3336 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3337 Diag(Loc: OA->getLocation(),
3338 DiagID: diag::override_keyword_only_allowed_on_virtual_member_functions)
3339 << "override" << FixItHint::CreateRemoval(RemoveRange: OA->getLocation());
3340 D->dropAttr<OverrideAttr>();
3341 }
3342 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3343 Diag(Loc: FA->getLocation(),
3344 DiagID: diag::override_keyword_only_allowed_on_virtual_member_functions)
3345 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3346 << FixItHint::CreateRemoval(RemoveRange: FA->getLocation());
3347 D->dropAttr<FinalAttr>();
3348 }
3349 return;
3350 }
3351
3352 // C++11 [class.virtual]p5:
3353 // If a function is marked with the virt-specifier override and
3354 // does not override a member function of a base class, the program is
3355 // ill-formed.
3356 bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
3357 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
3358 Diag(Loc: MD->getLocation(), DiagID: diag::err_function_marked_override_not_overriding)
3359 << MD->getDeclName();
3360}
3361
3362void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent) {
3363 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
3364 return;
3365 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: D);
3366 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
3367 return;
3368
3369 SourceLocation Loc = MD->getLocation();
3370 SourceLocation SpellingLoc = Loc;
3371 if (getSourceManager().isMacroArgExpansion(Loc))
3372 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
3373 SpellingLoc = getSourceManager().getSpellingLoc(Loc: SpellingLoc);
3374 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(Loc: SpellingLoc))
3375 return;
3376
3377 if (MD->size_overridden_methods() > 0) {
3378 auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) {
3379 unsigned DiagID =
3380 Inconsistent && !Diags.isIgnored(DiagID: DiagInconsistent, Loc: MD->getLocation())
3381 ? DiagInconsistent
3382 : DiagSuggest;
3383 Diag(Loc: MD->getLocation(), DiagID) << MD->getDeclName();
3384 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
3385 Diag(Loc: OMD->getLocation(), DiagID: diag::note_overridden_virtual_function);
3386 };
3387 if (isa<CXXDestructorDecl>(Val: MD))
3388 EmitDiag(
3389 diag::warn_inconsistent_destructor_marked_not_override_overriding,
3390 diag::warn_suggest_destructor_marked_not_override_overriding);
3391 else
3392 EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding,
3393 diag::warn_suggest_function_marked_not_override_overriding);
3394 }
3395}
3396
3397bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
3398 const CXXMethodDecl *Old) {
3399 FinalAttr *FA = Old->getAttr<FinalAttr>();
3400 if (!FA)
3401 return false;
3402
3403 Diag(Loc: New->getLocation(), DiagID: diag::err_final_function_overridden)
3404 << New->getDeclName()
3405 << FA->isSpelledAsSealed();
3406 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function);
3407 return true;
3408}
3409
3410static bool InitializationHasSideEffects(const FieldDecl &FD) {
3411 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
3412 // FIXME: Destruction of ObjC lifetime types has side-effects.
3413 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3414 return !RD->isCompleteDefinition() ||
3415 !RD->hasTrivialDefaultConstructor() ||
3416 !RD->hasTrivialDestructor();
3417 return false;
3418}
3419
3420void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
3421 DeclarationName FieldName,
3422 const CXXRecordDecl *RD,
3423 bool DeclIsField) {
3424 if (Diags.isIgnored(DiagID: diag::warn_shadow_field, Loc))
3425 return;
3426
3427 // To record a shadowed field in a base
3428 std::map<CXXRecordDecl*, NamedDecl*> Bases;
3429 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
3430 CXXBasePath &Path) {
3431 const auto Base = Specifier->getType()->getAsCXXRecordDecl();
3432 // Record an ambiguous path directly
3433 if (Bases.find(x: Base) != Bases.end())
3434 return true;
3435 for (const auto Field : Base->lookup(Name: FieldName)) {
3436 if ((isa<FieldDecl>(Val: Field) || isa<IndirectFieldDecl>(Val: Field)) &&
3437 Field->getAccess() != AS_private) {
3438 assert(Field->getAccess() != AS_none);
3439 assert(Bases.find(Base) == Bases.end());
3440 Bases[Base] = Field;
3441 return true;
3442 }
3443 }
3444 return false;
3445 };
3446
3447 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3448 /*DetectVirtual=*/true);
3449 if (!RD->lookupInBases(BaseMatches: FieldShadowed, Paths))
3450 return;
3451
3452 for (const auto &P : Paths) {
3453 auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
3454 auto It = Bases.find(x: Base);
3455 // Skip duplicated bases
3456 if (It == Bases.end())
3457 continue;
3458 auto BaseField = It->second;
3459 assert(BaseField->getAccess() != AS_private);
3460 if (AS_none !=
3461 CXXRecordDecl::MergeAccess(PathAccess: P.Access, DeclAccess: BaseField->getAccess())) {
3462 Diag(Loc, DiagID: diag::warn_shadow_field)
3463 << FieldName << RD << Base << DeclIsField;
3464 Diag(Loc: BaseField->getLocation(), DiagID: diag::note_shadow_field);
3465 Bases.erase(position: It);
3466 }
3467 }
3468}
3469
3470template <typename AttrType>
3471inline static bool HasAttribute(const QualType &T) {
3472 if (const TagDecl *TD = T->getAsTagDecl())
3473 return TD->hasAttr<AttrType>();
3474 if (const TypedefType *TDT = T->getAs<TypedefType>())
3475 return TDT->getDecl()->hasAttr<AttrType>();
3476 return false;
3477}
3478
3479static bool IsUnusedPrivateField(const FieldDecl *FD) {
3480 if (FD->getAccess() == AS_private && FD->getDeclName()) {
3481 QualType FieldType = FD->getType();
3482 if (HasAttribute<WarnUnusedAttr>(T: FieldType))
3483 return true;
3484
3485 return !FD->isImplicit() && !FD->hasAttr<UnusedAttr>() &&
3486 !FD->getParent()->isDependentContext() &&
3487 !HasAttribute<UnusedAttr>(T: FieldType) &&
3488 !InitializationHasSideEffects(FD: *FD);
3489 }
3490 return false;
3491}
3492
3493NamedDecl *
3494Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
3495 MultiTemplateParamsArg TemplateParameterLists,
3496 Expr *BitWidth, const VirtSpecifiers &VS,
3497 InClassInitStyle InitStyle) {
3498 const DeclSpec &DS = D.getDeclSpec();
3499 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
3500 DeclarationName Name = NameInfo.getName();
3501 SourceLocation Loc = NameInfo.getLoc();
3502
3503 // For anonymous bitfields, the location should point to the type.
3504 if (Loc.isInvalid())
3505 Loc = D.getBeginLoc();
3506
3507 assert(isa<CXXRecordDecl>(CurContext));
3508 assert(!DS.isFriendSpecified());
3509
3510 bool isFunc = D.isDeclarationOfFunction();
3511 const ParsedAttr *MSPropertyAttr =
3512 D.getDeclSpec().getAttributes().getMSPropertyAttr();
3513
3514 if (cast<CXXRecordDecl>(Val: CurContext)->isInterface()) {
3515 // The Microsoft extension __interface only permits public member functions
3516 // and prohibits constructors, destructors, operators, non-public member
3517 // functions, static methods and data members.
3518 unsigned InvalidDecl;
3519 bool ShowDeclName = true;
3520 if (!isFunc &&
3521 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
3522 InvalidDecl = 0;
3523 else if (!isFunc)
3524 InvalidDecl = 1;
3525 else if (AS != AS_public)
3526 InvalidDecl = 2;
3527 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
3528 InvalidDecl = 3;
3529 else switch (Name.getNameKind()) {
3530 case DeclarationName::CXXConstructorName:
3531 InvalidDecl = 4;
3532 ShowDeclName = false;
3533 break;
3534
3535 case DeclarationName::CXXDestructorName:
3536 InvalidDecl = 5;
3537 ShowDeclName = false;
3538 break;
3539
3540 case DeclarationName::CXXOperatorName:
3541 case DeclarationName::CXXConversionFunctionName:
3542 InvalidDecl = 6;
3543 break;
3544
3545 default:
3546 InvalidDecl = 0;
3547 break;
3548 }
3549
3550 if (InvalidDecl) {
3551 if (ShowDeclName)
3552 Diag(Loc, DiagID: diag::err_invalid_member_in_interface)
3553 << (InvalidDecl-1) << Name;
3554 else
3555 Diag(Loc, DiagID: diag::err_invalid_member_in_interface)
3556 << (InvalidDecl-1) << "";
3557 return nullptr;
3558 }
3559 }
3560
3561 // HLSL prohibits user defined constructors and destructors.
3562 if (getLangOpts().HLSL) {
3563 switch (Name.getNameKind()) {
3564 case DeclarationName::CXXConstructorName:
3565 case DeclarationName::CXXDestructorName:
3566 Diag(Loc, DiagID: diag::err_hlsl_cstor_dstor);
3567 return nullptr;
3568 default:
3569 break;
3570 }
3571 }
3572
3573 // C++ 9.2p6: A member shall not be declared to have automatic storage
3574 // duration (auto, register) or with the extern storage-class-specifier.
3575 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3576 // data members and cannot be applied to names declared const or static,
3577 // and cannot be applied to reference members.
3578 switch (DS.getStorageClassSpec()) {
3579 case DeclSpec::SCS_unspecified:
3580 case DeclSpec::SCS_typedef:
3581 case DeclSpec::SCS_static:
3582 break;
3583 case DeclSpec::SCS_mutable:
3584 if (isFunc) {
3585 Diag(Loc: DS.getStorageClassSpecLoc(), DiagID: diag::err_mutable_function);
3586
3587 // FIXME: It would be nicer if the keyword was ignored only for this
3588 // declarator. Otherwise we could get follow-up errors.
3589 D.getMutableDeclSpec().ClearStorageClassSpecs();
3590 }
3591 break;
3592 default:
3593 Diag(Loc: DS.getStorageClassSpecLoc(),
3594 DiagID: diag::err_storageclass_invalid_for_member);
3595 D.getMutableDeclSpec().ClearStorageClassSpecs();
3596 break;
3597 }
3598
3599 bool isInstField = (DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3600 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
3601 !isFunc && TemplateParameterLists.empty();
3602
3603 if (DS.hasConstexprSpecifier() && isInstField) {
3604 SemaDiagnosticBuilder B =
3605 Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_invalid_constexpr_member);
3606 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3607 if (InitStyle == ICIS_NoInit) {
3608 B << 0 << 0;
3609 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
3610 B << FixItHint::CreateRemoval(RemoveRange: ConstexprLoc);
3611 else {
3612 B << FixItHint::CreateReplacement(RemoveRange: ConstexprLoc, Code: "const");
3613 D.getMutableDeclSpec().ClearConstexprSpec();
3614 const char *PrevSpec;
3615 unsigned DiagID;
3616 bool Failed = D.getMutableDeclSpec().SetTypeQual(
3617 T: DeclSpec::TQ_const, Loc: ConstexprLoc, PrevSpec, DiagID, Lang: getLangOpts());
3618 (void)Failed;
3619 assert(!Failed && "Making a constexpr member const shouldn't fail");
3620 }
3621 } else {
3622 B << 1;
3623 const char *PrevSpec;
3624 unsigned DiagID;
3625 if (D.getMutableDeclSpec().SetStorageClassSpec(
3626 S&: *this, SC: DeclSpec::SCS_static, Loc: ConstexprLoc, PrevSpec, DiagID,
3627 Policy: Context.getPrintingPolicy())) {
3628 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
3629 "This is the only DeclSpec that should fail to be applied");
3630 B << 1;
3631 } else {
3632 B << 0 << FixItHint::CreateInsertion(InsertionLoc: ConstexprLoc, Code: "static ");
3633 isInstField = false;
3634 }
3635 }
3636 }
3637
3638 NamedDecl *Member;
3639 if (isInstField) {
3640 CXXScopeSpec &SS = D.getCXXScopeSpec();
3641
3642 // Data members must have identifiers for names.
3643 if (!Name.isIdentifier()) {
3644 Diag(Loc, DiagID: diag::err_bad_variable_name)
3645 << Name;
3646 return nullptr;
3647 }
3648
3649 IdentifierInfo *II = Name.getAsIdentifierInfo();
3650 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
3651 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_member_with_template_arguments)
3652 << II
3653 << SourceRange(D.getName().TemplateId->LAngleLoc,
3654 D.getName().TemplateId->RAngleLoc)
3655 << D.getName().TemplateId->LAngleLoc;
3656 D.SetIdentifier(Id: II, IdLoc: Loc);
3657 }
3658
3659 if (SS.isSet() && !SS.isInvalid()) {
3660 // The user provided a superfluous scope specifier inside a class
3661 // definition:
3662 //
3663 // class X {
3664 // int X::member;
3665 // };
3666 if (DeclContext *DC = computeDeclContext(SS, EnteringContext: false)) {
3667 TemplateIdAnnotation *TemplateId =
3668 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
3669 ? D.getName().TemplateId
3670 : nullptr;
3671 diagnoseQualifiedDeclaration(SS, DC, Name, Loc: D.getIdentifierLoc(),
3672 TemplateId,
3673 /*IsMemberSpecialization=*/false);
3674 } else {
3675 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_member_qualification)
3676 << Name << SS.getRange();
3677 }
3678 SS.clear();
3679 }
3680
3681 if (MSPropertyAttr) {
3682 Member = HandleMSProperty(S, TagD: cast<CXXRecordDecl>(Val: CurContext), DeclStart: Loc, D,
3683 BitfieldWidth: BitWidth, InitStyle, AS, MSPropertyAttr: *MSPropertyAttr);
3684 if (!Member)
3685 return nullptr;
3686 isInstField = false;
3687 } else {
3688 Member = HandleField(S, TagD: cast<CXXRecordDecl>(Val: CurContext), DeclStart: Loc, D,
3689 BitfieldWidth: BitWidth, InitStyle, AS);
3690 if (!Member)
3691 return nullptr;
3692 }
3693
3694 CheckShadowInheritedFields(Loc, FieldName: Name, RD: cast<CXXRecordDecl>(Val: CurContext));
3695 } else {
3696 Member = HandleDeclarator(S, D, TemplateParameterLists);
3697 if (!Member)
3698 return nullptr;
3699
3700 // Non-instance-fields can't have a bitfield.
3701 if (BitWidth) {
3702 if (Member->isInvalidDecl()) {
3703 // don't emit another diagnostic.
3704 } else if (isa<VarDecl>(Val: Member) || isa<VarTemplateDecl>(Val: Member)) {
3705 // C++ 9.6p3: A bit-field shall not be a static member.
3706 // "static member 'A' cannot be a bit-field"
3707 Diag(Loc, DiagID: diag::err_static_not_bitfield)
3708 << Name << BitWidth->getSourceRange();
3709 } else if (isa<TypedefDecl>(Val: Member)) {
3710 // "typedef member 'x' cannot be a bit-field"
3711 Diag(Loc, DiagID: diag::err_typedef_not_bitfield)
3712 << Name << BitWidth->getSourceRange();
3713 } else {
3714 // A function typedef ("typedef int f(); f a;").
3715 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3716 Diag(Loc, DiagID: diag::err_not_integral_type_bitfield)
3717 << Name << cast<ValueDecl>(Val: Member)->getType()
3718 << BitWidth->getSourceRange();
3719 }
3720
3721 BitWidth = nullptr;
3722 Member->setInvalidDecl();
3723 }
3724
3725 NamedDecl *NonTemplateMember = Member;
3726 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: Member))
3727 NonTemplateMember = FunTmpl->getTemplatedDecl();
3728 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Val: Member))
3729 NonTemplateMember = VarTmpl->getTemplatedDecl();
3730
3731 Member->setAccess(AS);
3732
3733 // If we have declared a member function template or static data member
3734 // template, set the access of the templated declaration as well.
3735 if (NonTemplateMember != Member)
3736 NonTemplateMember->setAccess(AS);
3737
3738 // C++ [temp.deduct.guide]p3:
3739 // A deduction guide [...] for a member class template [shall be
3740 // declared] with the same access [as the template].
3741 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(Val: NonTemplateMember)) {
3742 auto *TD = DG->getDeducedTemplate();
3743 // Access specifiers are only meaningful if both the template and the
3744 // deduction guide are from the same scope.
3745 if (AS != TD->getAccess() &&
3746 TD->getDeclContext()->getRedeclContext()->Equals(
3747 DC: DG->getDeclContext()->getRedeclContext())) {
3748 Diag(Loc: DG->getBeginLoc(), DiagID: diag::err_deduction_guide_wrong_access);
3749 Diag(Loc: TD->getBeginLoc(), DiagID: diag::note_deduction_guide_template_access)
3750 << TD->getAccess();
3751 const AccessSpecDecl *LastAccessSpec = nullptr;
3752 for (const auto *D : cast<CXXRecordDecl>(Val: CurContext)->decls()) {
3753 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(Val: D))
3754 LastAccessSpec = AccessSpec;
3755 }
3756 assert(LastAccessSpec && "differing access with no access specifier");
3757 Diag(Loc: LastAccessSpec->getBeginLoc(), DiagID: diag::note_deduction_guide_access)
3758 << AS;
3759 }
3760 }
3761 }
3762
3763 if (VS.isOverrideSpecified())
3764 Member->addAttr(A: OverrideAttr::Create(Ctx&: Context, Range: VS.getOverrideLoc()));
3765 if (VS.isFinalSpecified())
3766 Member->addAttr(A: FinalAttr::Create(Ctx&: Context, Range: VS.getFinalLoc(),
3767 S: VS.isFinalSpelledSealed()
3768 ? FinalAttr::Keyword_sealed
3769 : FinalAttr::Keyword_final));
3770
3771 if (VS.getLastLocation().isValid()) {
3772 // Update the end location of a method that has a virt-specifiers.
3773 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Val: Member))
3774 MD->setRangeEnd(VS.getLastLocation());
3775 }
3776
3777 CheckOverrideControl(D: Member);
3778
3779 assert((Name || isInstField) && "No identifier for non-field ?");
3780
3781 if (isInstField) {
3782 FieldDecl *FD = cast<FieldDecl>(Val: Member);
3783 FieldCollector->Add(D: FD);
3784
3785 if (!Diags.isIgnored(DiagID: diag::warn_unused_private_field, Loc: FD->getLocation()) &&
3786 IsUnusedPrivateField(FD)) {
3787 // Remember all explicit private FieldDecls that have a name, no side
3788 // effects and are not part of a dependent type declaration.
3789 UnusedPrivateFields.insert(X: FD);
3790 }
3791 }
3792
3793 return Member;
3794}
3795
3796namespace {
3797 class UninitializedFieldVisitor
3798 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3799 Sema &S;
3800 // List of Decls to generate a warning on. Also remove Decls that become
3801 // initialized.
3802 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3803 // List of base classes of the record. Classes are removed after their
3804 // initializers.
3805 llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3806 // Vector of decls to be removed from the Decl set prior to visiting the
3807 // nodes. These Decls may have been initialized in the prior initializer.
3808 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3809 // If non-null, add a note to the warning pointing back to the constructor.
3810 const CXXConstructorDecl *Constructor;
3811 // Variables to hold state when processing an initializer list. When
3812 // InitList is true, special case initialization of FieldDecls matching
3813 // InitListFieldDecl.
3814 bool InitList;
3815 FieldDecl *InitListFieldDecl;
3816 llvm::SmallVector<unsigned, 4> InitFieldIndex;
3817
3818 public:
3819 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3820 UninitializedFieldVisitor(Sema &S,
3821 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3822 llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3823 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3824 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3825
3826 // Returns true if the use of ME is not an uninitialized use.
3827 bool IsInitListMemberExprInitialized(MemberExpr *ME,
3828 bool CheckReferenceOnly) {
3829 llvm::SmallVector<FieldDecl*, 4> Fields;
3830 bool ReferenceField = false;
3831 while (ME) {
3832 FieldDecl *FD = dyn_cast<FieldDecl>(Val: ME->getMemberDecl());
3833 if (!FD)
3834 return false;
3835 Fields.push_back(Elt: FD);
3836 if (FD->getType()->isReferenceType())
3837 ReferenceField = true;
3838 ME = dyn_cast<MemberExpr>(Val: ME->getBase()->IgnoreParenImpCasts());
3839 }
3840
3841 // Binding a reference to an uninitialized field is not an
3842 // uninitialized use.
3843 if (CheckReferenceOnly && !ReferenceField)
3844 return true;
3845
3846 // Discard the first field since it is the field decl that is being
3847 // initialized.
3848 auto UsedFields = llvm::drop_begin(RangeOrContainer: llvm::reverse(C&: Fields));
3849 auto UsedIter = UsedFields.begin();
3850 const auto UsedEnd = UsedFields.end();
3851
3852 for (const unsigned Orig : InitFieldIndex) {
3853 if (UsedIter == UsedEnd)
3854 break;
3855 const unsigned UsedIndex = (*UsedIter)->getFieldIndex();
3856 if (UsedIndex < Orig)
3857 return true;
3858 if (UsedIndex > Orig)
3859 break;
3860 ++UsedIter;
3861 }
3862
3863 return false;
3864 }
3865
3866 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3867 bool AddressOf) {
3868 if (isa<EnumConstantDecl>(Val: ME->getMemberDecl()))
3869 return;
3870
3871 // FieldME is the inner-most MemberExpr that is not an anonymous struct
3872 // or union.
3873 MemberExpr *FieldME = ME;
3874
3875 bool AllPODFields = FieldME->getType().isPODType(Context: S.Context);
3876
3877 Expr *Base = ME;
3878 while (MemberExpr *SubME =
3879 dyn_cast<MemberExpr>(Val: Base->IgnoreParenImpCasts())) {
3880
3881 if (isa<VarDecl>(Val: SubME->getMemberDecl()))
3882 return;
3883
3884 if (FieldDecl *FD = dyn_cast<FieldDecl>(Val: SubME->getMemberDecl()))
3885 if (!FD->isAnonymousStructOrUnion())
3886 FieldME = SubME;
3887
3888 if (!FieldME->getType().isPODType(Context: S.Context))
3889 AllPODFields = false;
3890
3891 Base = SubME->getBase();
3892 }
3893
3894 if (!isa<CXXThisExpr>(Val: Base->IgnoreParenImpCasts())) {
3895 Visit(S: Base);
3896 return;
3897 }
3898
3899 if (AddressOf && AllPODFields)
3900 return;
3901
3902 ValueDecl* FoundVD = FieldME->getMemberDecl();
3903
3904 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Val: Base)) {
3905 while (isa<ImplicitCastExpr>(Val: BaseCast->getSubExpr())) {
3906 BaseCast = cast<ImplicitCastExpr>(Val: BaseCast->getSubExpr());
3907 }
3908
3909 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3910 QualType T = BaseCast->getType();
3911 if (T->isPointerType() &&
3912 BaseClasses.count(Ptr: T->getPointeeType())) {
3913 S.Diag(Loc: FieldME->getExprLoc(), DiagID: diag::warn_base_class_is_uninit)
3914 << T->getPointeeType() << FoundVD;
3915 }
3916 }
3917 }
3918
3919 if (!Decls.count(Ptr: FoundVD))
3920 return;
3921
3922 const bool IsReference = FoundVD->getType()->isReferenceType();
3923
3924 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3925 // Special checking for initializer lists.
3926 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3927 return;
3928 }
3929 } else {
3930 // Prevent double warnings on use of unbounded references.
3931 if (CheckReferenceOnly && !IsReference)
3932 return;
3933 }
3934
3935 unsigned diag = IsReference
3936 ? diag::warn_reference_field_is_uninit
3937 : diag::warn_field_is_uninit;
3938 S.Diag(Loc: FieldME->getExprLoc(), DiagID: diag) << FoundVD;
3939 if (Constructor)
3940 S.Diag(Loc: Constructor->getLocation(),
3941 DiagID: diag::note_uninit_in_this_constructor)
3942 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3943
3944 }
3945
3946 void HandleValue(Expr *E, bool AddressOf) {
3947 E = E->IgnoreParens();
3948
3949 if (MemberExpr *ME = dyn_cast<MemberExpr>(Val: E)) {
3950 HandleMemberExpr(ME, CheckReferenceOnly: false /*CheckReferenceOnly*/,
3951 AddressOf /*AddressOf*/);
3952 return;
3953 }
3954
3955 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(Val: E)) {
3956 Visit(S: CO->getCond());
3957 HandleValue(E: CO->getTrueExpr(), AddressOf);
3958 HandleValue(E: CO->getFalseExpr(), AddressOf);
3959 return;
3960 }
3961
3962 if (BinaryConditionalOperator *BCO =
3963 dyn_cast<BinaryConditionalOperator>(Val: E)) {
3964 Visit(S: BCO->getCond());
3965 HandleValue(E: BCO->getFalseExpr(), AddressOf);
3966 return;
3967 }
3968
3969 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Val: E)) {
3970 HandleValue(E: OVE->getSourceExpr(), AddressOf);
3971 return;
3972 }
3973
3974 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: E)) {
3975 switch (BO->getOpcode()) {
3976 default:
3977 break;
3978 case(BO_PtrMemD):
3979 case(BO_PtrMemI):
3980 HandleValue(E: BO->getLHS(), AddressOf);
3981 Visit(S: BO->getRHS());
3982 return;
3983 case(BO_Comma):
3984 Visit(S: BO->getLHS());
3985 HandleValue(E: BO->getRHS(), AddressOf);
3986 return;
3987 }
3988 }
3989
3990 Visit(S: E);
3991 }
3992
3993 void CheckInitListExpr(InitListExpr *ILE) {
3994 InitFieldIndex.push_back(Elt: 0);
3995 for (auto *Child : ILE->children()) {
3996 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Val: Child)) {
3997 CheckInitListExpr(ILE: SubList);
3998 } else {
3999 Visit(S: Child);
4000 }
4001 ++InitFieldIndex.back();
4002 }
4003 InitFieldIndex.pop_back();
4004 }
4005
4006 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
4007 FieldDecl *Field, const Type *BaseClass) {
4008 // Remove Decls that may have been initialized in the previous
4009 // initializer.
4010 for (ValueDecl* VD : DeclsToRemove)
4011 Decls.erase(Ptr: VD);
4012 DeclsToRemove.clear();
4013
4014 Constructor = FieldConstructor;
4015 InitListExpr *ILE = dyn_cast<InitListExpr>(Val: E);
4016
4017 if (ILE && Field) {
4018 InitList = true;
4019 InitListFieldDecl = Field;
4020 InitFieldIndex.clear();
4021 CheckInitListExpr(ILE);
4022 } else {
4023 InitList = false;
4024 Visit(S: E);
4025 }
4026
4027 if (Field)
4028 Decls.erase(Ptr: Field);
4029 if (BaseClass)
4030 BaseClasses.erase(Ptr: BaseClass->getCanonicalTypeInternal());
4031 }
4032
4033 void VisitMemberExpr(MemberExpr *ME) {
4034 // All uses of unbounded reference fields will warn.
4035 HandleMemberExpr(ME, CheckReferenceOnly: true /*CheckReferenceOnly*/, AddressOf: false /*AddressOf*/);
4036 }
4037
4038 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
4039 if (E->getCastKind() == CK_LValueToRValue) {
4040 HandleValue(E: E->getSubExpr(), AddressOf: false /*AddressOf*/);
4041 return;
4042 }
4043
4044 Inherited::VisitImplicitCastExpr(S: E);
4045 }
4046
4047 void VisitCXXConstructExpr(CXXConstructExpr *E) {
4048 if (E->getConstructor()->isCopyConstructor()) {
4049 Expr *ArgExpr = E->getArg(Arg: 0);
4050 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Val: ArgExpr))
4051 if (ILE->getNumInits() == 1)
4052 ArgExpr = ILE->getInit(Init: 0);
4053 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: ArgExpr))
4054 if (ICE->getCastKind() == CK_NoOp)
4055 ArgExpr = ICE->getSubExpr();
4056 HandleValue(E: ArgExpr, AddressOf: false /*AddressOf*/);
4057 return;
4058 }
4059 Inherited::VisitCXXConstructExpr(S: E);
4060 }
4061
4062 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
4063 Expr *Callee = E->getCallee();
4064 if (isa<MemberExpr>(Val: Callee)) {
4065 HandleValue(E: Callee, AddressOf: false /*AddressOf*/);
4066 for (auto *Arg : E->arguments())
4067 Visit(S: Arg);
4068 return;
4069 }
4070
4071 Inherited::VisitCXXMemberCallExpr(S: E);
4072 }
4073
4074 void VisitCallExpr(CallExpr *E) {
4075 // Treat std::move as a use.
4076 if (E->isCallToStdMove()) {
4077 HandleValue(E: E->getArg(Arg: 0), /*AddressOf=*/false);
4078 return;
4079 }
4080
4081 Inherited::VisitCallExpr(CE: E);
4082 }
4083
4084 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
4085 Expr *Callee = E->getCallee();
4086
4087 if (isa<UnresolvedLookupExpr>(Val: Callee))
4088 return Inherited::VisitCXXOperatorCallExpr(S: E);
4089
4090 Visit(S: Callee);
4091 for (auto *Arg : E->arguments())
4092 HandleValue(E: Arg->IgnoreParenImpCasts(), AddressOf: false /*AddressOf*/);
4093 }
4094
4095 void VisitBinaryOperator(BinaryOperator *E) {
4096 // If a field assignment is detected, remove the field from the
4097 // uninitiailized field set.
4098 if (E->getOpcode() == BO_Assign)
4099 if (MemberExpr *ME = dyn_cast<MemberExpr>(Val: E->getLHS()))
4100 if (FieldDecl *FD = dyn_cast<FieldDecl>(Val: ME->getMemberDecl()))
4101 if (!FD->getType()->isReferenceType())
4102 DeclsToRemove.push_back(Elt: FD);
4103
4104 if (E->isCompoundAssignmentOp()) {
4105 HandleValue(E: E->getLHS(), AddressOf: false /*AddressOf*/);
4106 Visit(S: E->getRHS());
4107 return;
4108 }
4109
4110 Inherited::VisitBinaryOperator(S: E);
4111 }
4112
4113 void VisitUnaryOperator(UnaryOperator *E) {
4114 if (E->isIncrementDecrementOp()) {
4115 HandleValue(E: E->getSubExpr(), AddressOf: false /*AddressOf*/);
4116 return;
4117 }
4118 if (E->getOpcode() == UO_AddrOf) {
4119 if (MemberExpr *ME = dyn_cast<MemberExpr>(Val: E->getSubExpr())) {
4120 HandleValue(E: ME->getBase(), AddressOf: true /*AddressOf*/);
4121 return;
4122 }
4123 }
4124
4125 Inherited::VisitUnaryOperator(S: E);
4126 }
4127 };
4128
4129 // Diagnose value-uses of fields to initialize themselves, e.g.
4130 // foo(foo)
4131 // where foo is not also a parameter to the constructor.
4132 // Also diagnose across field uninitialized use such as
4133 // x(y), y(x)
4134 // TODO: implement -Wuninitialized and fold this into that framework.
4135 static void DiagnoseUninitializedFields(
4136 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
4137
4138 if (SemaRef.getDiagnostics().isIgnored(DiagID: diag::warn_field_is_uninit,
4139 Loc: Constructor->getLocation())) {
4140 return;
4141 }
4142
4143 if (Constructor->isInvalidDecl())
4144 return;
4145
4146 const CXXRecordDecl *RD = Constructor->getParent();
4147
4148 if (RD->isDependentContext())
4149 return;
4150
4151 // Holds fields that are uninitialized.
4152 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
4153
4154 // At the beginning, all fields are uninitialized.
4155 for (auto *I : RD->decls()) {
4156 if (auto *FD = dyn_cast<FieldDecl>(Val: I)) {
4157 UninitializedFields.insert(Ptr: FD);
4158 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(Val: I)) {
4159 UninitializedFields.insert(Ptr: IFD->getAnonField());
4160 }
4161 }
4162
4163 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
4164 for (const auto &I : RD->bases()) {
4165 // Virtual bases are initialized from the most derived class, so an
4166 // abstract base class constructor can assume it to be initialized.
4167 if (I.isVirtual() && RD->isAbstract())
4168 continue;
4169 UninitializedBaseClasses.insert(Ptr: I.getType().getCanonicalType());
4170 }
4171
4172 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
4173 return;
4174
4175 UninitializedFieldVisitor UninitializedChecker(SemaRef,
4176 UninitializedFields,
4177 UninitializedBaseClasses);
4178
4179 for (const auto *FieldInit : Constructor->inits()) {
4180 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
4181 break;
4182
4183 Expr *InitExpr = FieldInit->getInit();
4184 if (!InitExpr)
4185 continue;
4186
4187 if (CXXDefaultInitExpr *Default =
4188 dyn_cast<CXXDefaultInitExpr>(Val: InitExpr)) {
4189 InitExpr = Default->getExpr();
4190 if (!InitExpr)
4191 continue;
4192 // In class initializers will point to the constructor.
4193 UninitializedChecker.CheckInitializer(E: InitExpr, FieldConstructor: Constructor,
4194 Field: FieldInit->getAnyMember(),
4195 BaseClass: FieldInit->getBaseClass());
4196 } else {
4197 UninitializedChecker.CheckInitializer(E: InitExpr, FieldConstructor: nullptr,
4198 Field: FieldInit->getAnyMember(),
4199 BaseClass: FieldInit->getBaseClass());
4200 }
4201 }
4202 }
4203} // namespace
4204
4205void Sema::ActOnStartCXXInClassMemberInitializer() {
4206 // Create a synthetic function scope to represent the call to the constructor
4207 // that notionally surrounds a use of this initializer.
4208 PushFunctionScope();
4209}
4210
4211void Sema::ActOnStartTrailingRequiresClause(Scope *S, Declarator &D) {
4212 if (!D.isFunctionDeclarator())
4213 return;
4214 auto &FTI = D.getFunctionTypeInfo();
4215 if (!FTI.Params)
4216 return;
4217 for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params,
4218 FTI.NumParams)) {
4219 auto *ParamDecl = cast<NamedDecl>(Val: Param.Param);
4220 if (ParamDecl->getDeclName())
4221 PushOnScopeChains(D: ParamDecl, S, /*AddToContext=*/false);
4222 }
4223}
4224
4225ExprResult Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr) {
4226 return ActOnRequiresClause(ConstraintExpr);
4227}
4228
4229ExprResult Sema::ActOnRequiresClause(ExprResult ConstraintExpr) {
4230 if (ConstraintExpr.isInvalid())
4231 return ExprError();
4232
4233 if (DiagnoseUnexpandedParameterPack(E: ConstraintExpr.get(),
4234 UPPC: UPPC_RequiresClause))
4235 return ExprError();
4236
4237 return ConstraintExpr;
4238}
4239
4240ExprResult Sema::ConvertMemberDefaultInitExpression(FieldDecl *FD,
4241 Expr *InitExpr,
4242 SourceLocation InitLoc) {
4243 InitializedEntity Entity =
4244 InitializedEntity::InitializeMemberFromDefaultMemberInitializer(Member: FD);
4245 InitializationKind Kind =
4246 FD->getInClassInitStyle() == ICIS_ListInit
4247 ? InitializationKind::CreateDirectList(InitLoc: InitExpr->getBeginLoc(),
4248 LBraceLoc: InitExpr->getBeginLoc(),
4249 RBraceLoc: InitExpr->getEndLoc())
4250 : InitializationKind::CreateCopy(InitLoc: InitExpr->getBeginLoc(), EqualLoc: InitLoc);
4251 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
4252 return Seq.Perform(S&: *this, Entity, Kind, Args: InitExpr);
4253}
4254
4255void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
4256 SourceLocation InitLoc,
4257 ExprResult InitExpr) {
4258 // Pop the notional constructor scope we created earlier.
4259 PopFunctionScopeInfo(WP: nullptr, D);
4260
4261 // Microsoft C++'s property declaration cannot have a default member
4262 // initializer.
4263 if (isa<MSPropertyDecl>(Val: D)) {
4264 D->setInvalidDecl();
4265 return;
4266 }
4267
4268 FieldDecl *FD = dyn_cast<FieldDecl>(Val: D);
4269 assert((FD && FD->getInClassInitStyle() != ICIS_NoInit) &&
4270 "must set init style when field is created");
4271
4272 if (!InitExpr.isUsable() ||
4273 DiagnoseUnexpandedParameterPack(E: InitExpr.get(), UPPC: UPPC_Initializer)) {
4274 FD->setInvalidDecl();
4275 ExprResult RecoveryInit =
4276 CreateRecoveryExpr(Begin: InitLoc, End: InitLoc, SubExprs: {}, T: FD->getType());
4277 if (RecoveryInit.isUsable())
4278 FD->setInClassInitializer(RecoveryInit.get());
4279 return;
4280 }
4281
4282 if (!FD->getType()->isDependentType() && !InitExpr.get()->isTypeDependent()) {
4283 InitExpr = ConvertMemberDefaultInitExpression(FD, InitExpr: InitExpr.get(), InitLoc);
4284 // C++11 [class.base.init]p7:
4285 // The initialization of each base and member constitutes a
4286 // full-expression.
4287 if (!InitExpr.isInvalid())
4288 InitExpr = ActOnFinishFullExpr(Expr: InitExpr.get(), /*DiscarededValue=*/DiscardedValue: false);
4289 if (InitExpr.isInvalid()) {
4290 FD->setInvalidDecl();
4291 return;
4292 }
4293 }
4294
4295 FD->setInClassInitializer(InitExpr.get());
4296}
4297
4298/// Find the direct and/or virtual base specifiers that
4299/// correspond to the given base type, for use in base initialization
4300/// within a constructor.
4301static bool FindBaseInitializer(Sema &SemaRef,
4302 CXXRecordDecl *ClassDecl,
4303 QualType BaseType,
4304 const CXXBaseSpecifier *&DirectBaseSpec,
4305 const CXXBaseSpecifier *&VirtualBaseSpec) {
4306 // First, check for a direct base class.
4307 DirectBaseSpec = nullptr;
4308 for (const auto &Base : ClassDecl->bases()) {
4309 if (SemaRef.Context.hasSameUnqualifiedType(T1: BaseType, T2: Base.getType())) {
4310 // We found a direct base of this type. That's what we're
4311 // initializing.
4312 DirectBaseSpec = &Base;
4313 break;
4314 }
4315 }
4316
4317 // Check for a virtual base class.
4318 // FIXME: We might be able to short-circuit this if we know in advance that
4319 // there are no virtual bases.
4320 VirtualBaseSpec = nullptr;
4321 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
4322 // We haven't found a base yet; search the class hierarchy for a
4323 // virtual base class.
4324 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
4325 /*DetectVirtual=*/false);
4326 if (SemaRef.IsDerivedFrom(Loc: ClassDecl->getLocation(),
4327 Derived: SemaRef.Context.getCanonicalTagType(TD: ClassDecl),
4328 Base: BaseType, Paths)) {
4329 for (const CXXBasePath &Path : Paths) {
4330 if (Path.back().Base->isVirtual()) {
4331 VirtualBaseSpec = Path.back().Base;
4332 break;
4333 }
4334 }
4335 }
4336 }
4337
4338 return DirectBaseSpec || VirtualBaseSpec;
4339}
4340
4341MemInitResult
4342Sema::ActOnMemInitializer(Decl *ConstructorD,
4343 Scope *S,
4344 CXXScopeSpec &SS,
4345 IdentifierInfo *MemberOrBase,
4346 ParsedType TemplateTypeTy,
4347 const DeclSpec &DS,
4348 SourceLocation IdLoc,
4349 Expr *InitList,
4350 SourceLocation EllipsisLoc) {
4351 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4352 DS, IdLoc, Init: InitList,
4353 EllipsisLoc);
4354}
4355
4356MemInitResult
4357Sema::ActOnMemInitializer(Decl *ConstructorD,
4358 Scope *S,
4359 CXXScopeSpec &SS,
4360 IdentifierInfo *MemberOrBase,
4361 ParsedType TemplateTypeTy,
4362 const DeclSpec &DS,
4363 SourceLocation IdLoc,
4364 SourceLocation LParenLoc,
4365 ArrayRef<Expr *> Args,
4366 SourceLocation RParenLoc,
4367 SourceLocation EllipsisLoc) {
4368 Expr *List = ParenListExpr::Create(Ctx: Context, LParenLoc, Exprs: Args, RParenLoc);
4369 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4370 DS, IdLoc, Init: List, EllipsisLoc);
4371}
4372
4373namespace {
4374
4375// Callback to only accept typo corrections that can be a valid C++ member
4376// initializer: either a non-static field member or a base class.
4377class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
4378public:
4379 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
4380 : ClassDecl(ClassDecl) {}
4381
4382 bool ValidateCandidate(const TypoCorrection &candidate) override {
4383 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
4384 if (FieldDecl *Member = dyn_cast<FieldDecl>(Val: ND))
4385 return Member->getDeclContext()->getRedeclContext()->Equals(DC: ClassDecl);
4386 return isa<TypeDecl>(Val: ND);
4387 }
4388 return false;
4389 }
4390
4391 std::unique_ptr<CorrectionCandidateCallback> clone() override {
4392 return std::make_unique<MemInitializerValidatorCCC>(args&: *this);
4393 }
4394
4395private:
4396 CXXRecordDecl *ClassDecl;
4397};
4398
4399}
4400
4401bool Sema::DiagRedefinedPlaceholderFieldDecl(SourceLocation Loc,
4402 RecordDecl *ClassDecl,
4403 const IdentifierInfo *Name) {
4404 DeclContextLookupResult Result = ClassDecl->lookup(Name);
4405 DeclContextLookupResult::iterator Found =
4406 llvm::find_if(Range&: Result, P: [this](const NamedDecl *Elem) {
4407 return isa<FieldDecl, IndirectFieldDecl>(Val: Elem) &&
4408 Elem->isPlaceholderVar(LangOpts: getLangOpts());
4409 });
4410 // We did not find a placeholder variable
4411 if (Found == Result.end())
4412 return false;
4413 Diag(Loc, DiagID: diag::err_using_placeholder_variable) << Name;
4414 for (DeclContextLookupResult::iterator It = Found; It != Result.end(); It++) {
4415 const NamedDecl *ND = *It;
4416 if (ND->getDeclContext() != ND->getDeclContext())
4417 break;
4418 if (isa<FieldDecl, IndirectFieldDecl>(Val: ND) &&
4419 ND->isPlaceholderVar(LangOpts: getLangOpts()))
4420 Diag(Loc: ND->getLocation(), DiagID: diag::note_reference_placeholder) << ND;
4421 }
4422 return true;
4423}
4424
4425ValueDecl *
4426Sema::tryLookupUnambiguousFieldDecl(RecordDecl *ClassDecl,
4427 const IdentifierInfo *MemberOrBase) {
4428 ValueDecl *ND = nullptr;
4429 for (auto *D : ClassDecl->lookup(Name: MemberOrBase)) {
4430 if (isa<FieldDecl, IndirectFieldDecl>(Val: D)) {
4431 bool IsPlaceholder = D->isPlaceholderVar(LangOpts: getLangOpts());
4432 if (ND) {
4433 if (IsPlaceholder && D->getDeclContext() == ND->getDeclContext())
4434 return nullptr;
4435 break;
4436 }
4437 if (!IsPlaceholder)
4438 return cast<ValueDecl>(Val: D);
4439 ND = cast<ValueDecl>(Val: D);
4440 }
4441 }
4442 return ND;
4443}
4444
4445ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
4446 CXXScopeSpec &SS,
4447 ParsedType TemplateTypeTy,
4448 IdentifierInfo *MemberOrBase) {
4449 if (SS.getScopeRep() || TemplateTypeTy)
4450 return nullptr;
4451 return tryLookupUnambiguousFieldDecl(ClassDecl, MemberOrBase);
4452}
4453
4454MemInitResult
4455Sema::BuildMemInitializer(Decl *ConstructorD,
4456 Scope *S,
4457 CXXScopeSpec &SS,
4458 IdentifierInfo *MemberOrBase,
4459 ParsedType TemplateTypeTy,
4460 const DeclSpec &DS,
4461 SourceLocation IdLoc,
4462 Expr *Init,
4463 SourceLocation EllipsisLoc) {
4464 if (!ConstructorD || !Init)
4465 return true;
4466
4467 AdjustDeclIfTemplate(Decl&: ConstructorD);
4468
4469 CXXConstructorDecl *Constructor
4470 = dyn_cast<CXXConstructorDecl>(Val: ConstructorD);
4471 if (!Constructor) {
4472 // The user wrote a constructor initializer on a function that is
4473 // not a C++ constructor. Ignore the error for now, because we may
4474 // have more member initializers coming; we'll diagnose it just
4475 // once in ActOnMemInitializers.
4476 return true;
4477 }
4478
4479 CXXRecordDecl *ClassDecl = Constructor->getParent();
4480
4481 // C++ [class.base.init]p2:
4482 // Names in a mem-initializer-id are looked up in the scope of the
4483 // constructor's class and, if not found in that scope, are looked
4484 // up in the scope containing the constructor's definition.
4485 // [Note: if the constructor's class contains a member with the
4486 // same name as a direct or virtual base class of the class, a
4487 // mem-initializer-id naming the member or base class and composed
4488 // of a single identifier refers to the class member. A
4489 // mem-initializer-id for the hidden base class may be specified
4490 // using a qualified name. ]
4491
4492 // Look for a member, first.
4493 if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
4494 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
4495 if (EllipsisLoc.isValid())
4496 Diag(Loc: EllipsisLoc, DiagID: diag::err_pack_expansion_member_init)
4497 << MemberOrBase
4498 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4499
4500 return BuildMemberInitializer(Member, Init, IdLoc);
4501 }
4502 // It didn't name a member, so see if it names a class.
4503 QualType BaseType;
4504 TypeSourceInfo *TInfo = nullptr;
4505
4506 if (TemplateTypeTy) {
4507 BaseType = GetTypeFromParser(Ty: TemplateTypeTy, TInfo: &TInfo);
4508 if (BaseType.isNull())
4509 return true;
4510 } else if (DS.getTypeSpecType() == TST_decltype) {
4511 BaseType = BuildDecltypeType(E: DS.getRepAsExpr());
4512 } else if (DS.getTypeSpecType() == TST_decltype_auto) {
4513 Diag(Loc: DS.getTypeSpecTypeLoc(), DiagID: diag::err_decltype_auto_invalid);
4514 return true;
4515 } else if (DS.getTypeSpecType() == TST_typename_pack_indexing) {
4516 BaseType =
4517 BuildPackIndexingType(Pattern: DS.getRepAsType().get(), IndexExpr: DS.getPackIndexingExpr(),
4518 Loc: DS.getBeginLoc(), EllipsisLoc: DS.getEllipsisLoc());
4519 } else {
4520 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
4521 LookupParsedName(R, S, SS: &SS, /*ObjectType=*/QualType());
4522
4523 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
4524 if (!TyD) {
4525 if (R.isAmbiguous()) return true;
4526
4527 // We don't want access-control diagnostics here.
4528 R.suppressDiagnostics();
4529
4530 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
4531 bool NotUnknownSpecialization = false;
4532 DeclContext *DC = computeDeclContext(SS, EnteringContext: false);
4533 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Val: DC))
4534 NotUnknownSpecialization = !Record->hasAnyDependentBases();
4535
4536 if (!NotUnknownSpecialization) {
4537 // When the scope specifier can refer to a member of an unknown
4538 // specialization, we take it as a type name.
4539 BaseType = CheckTypenameType(
4540 Keyword: ElaboratedTypeKeyword::None, KeywordLoc: SourceLocation(),
4541 QualifierLoc: SS.getWithLocInContext(Context), II: *MemberOrBase, IILoc: IdLoc);
4542 if (BaseType.isNull())
4543 return true;
4544
4545 TInfo = Context.CreateTypeSourceInfo(T: BaseType);
4546 DependentNameTypeLoc TL =
4547 TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
4548 if (!TL.isNull()) {
4549 TL.setNameLoc(IdLoc);
4550 TL.setElaboratedKeywordLoc(SourceLocation());
4551 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4552 }
4553
4554 R.clear();
4555 R.setLookupName(MemberOrBase);
4556 }
4557 }
4558
4559 if (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus20) {
4560 if (auto UnqualifiedBase = R.getAsSingle<ClassTemplateDecl>()) {
4561 auto *TempSpec = cast<TemplateSpecializationType>(
4562 Val: UnqualifiedBase->getCanonicalInjectedSpecializationType(Ctx: Context));
4563 TemplateName TN = TempSpec->getTemplateName();
4564 for (auto const &Base : ClassDecl->bases()) {
4565 auto BaseTemplate =
4566 Base.getType()->getAs<TemplateSpecializationType>();
4567 if (BaseTemplate &&
4568 Context.hasSameTemplateName(X: BaseTemplate->getTemplateName(), Y: TN,
4569 /*IgnoreDeduced=*/true)) {
4570 Diag(Loc: IdLoc, DiagID: diag::ext_unqualified_base_class)
4571 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4572 BaseType = Base.getType();
4573 break;
4574 }
4575 }
4576 }
4577 }
4578
4579 // If no results were found, try to correct typos.
4580 TypoCorrection Corr;
4581 MemInitializerValidatorCCC CCC(ClassDecl);
4582 if (R.empty() && BaseType.isNull() &&
4583 (Corr =
4584 CorrectTypo(Typo: R.getLookupNameInfo(), LookupKind: R.getLookupKind(), S, SS: &SS,
4585 CCC, Mode: CorrectTypoKind::ErrorRecovery, MemberContext: ClassDecl))) {
4586 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
4587 // We have found a non-static data member with a similar
4588 // name to what was typed; complain and initialize that
4589 // member.
4590 diagnoseTypo(Correction: Corr,
4591 TypoDiag: PDiag(DiagID: diag::err_mem_init_not_member_or_class_suggest)
4592 << MemberOrBase << true);
4593 return BuildMemberInitializer(Member, Init, IdLoc);
4594 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
4595 const CXXBaseSpecifier *DirectBaseSpec;
4596 const CXXBaseSpecifier *VirtualBaseSpec;
4597 if (FindBaseInitializer(SemaRef&: *this, ClassDecl,
4598 BaseType: Context.getTypeDeclType(Decl: Type),
4599 DirectBaseSpec, VirtualBaseSpec)) {
4600 // We have found a direct or virtual base class with a
4601 // similar name to what was typed; complain and initialize
4602 // that base class.
4603 diagnoseTypo(Correction: Corr,
4604 TypoDiag: PDiag(DiagID: diag::err_mem_init_not_member_or_class_suggest)
4605 << MemberOrBase << false,
4606 PrevNote: PDiag() /*Suppress note, we provide our own.*/);
4607
4608 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
4609 : VirtualBaseSpec;
4610 Diag(Loc: BaseSpec->getBeginLoc(), DiagID: diag::note_base_class_specified_here)
4611 << BaseSpec->getType() << BaseSpec->getSourceRange();
4612
4613 TyD = Type;
4614 }
4615 }
4616 }
4617
4618 if (!TyD && BaseType.isNull()) {
4619 Diag(Loc: IdLoc, DiagID: diag::err_mem_init_not_member_or_class)
4620 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4621 return true;
4622 }
4623 }
4624
4625 if (BaseType.isNull()) {
4626 MarkAnyDeclReferenced(Loc: TyD->getLocation(), D: TyD, /*OdrUse=*/MightBeOdrUse: false);
4627
4628 TypeLocBuilder TLB;
4629 // FIXME: This is missing building the UsingType for TyD, if any.
4630 if (const auto *TD = dyn_cast<TagDecl>(Val: TyD)) {
4631 BaseType = Context.getTagType(Keyword: ElaboratedTypeKeyword::None,
4632 Qualifier: SS.getScopeRep(), TD, /*OwnsTag=*/false);
4633 auto TL = TLB.push<TagTypeLoc>(T: BaseType);
4634 TL.setElaboratedKeywordLoc(SourceLocation());
4635 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4636 TL.setNameLoc(IdLoc);
4637 } else if (auto *TN = dyn_cast<TypedefNameDecl>(Val: TyD)) {
4638 BaseType = Context.getTypedefType(Keyword: ElaboratedTypeKeyword::None,
4639 Qualifier: SS.getScopeRep(), Decl: TN);
4640 TLB.push<TypedefTypeLoc>(T: BaseType).set(
4641 /*ElaboratedKeywordLoc=*/SourceLocation(),
4642 QualifierLoc: SS.getWithLocInContext(Context), NameLoc: IdLoc);
4643 } else if (auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(Val: TyD)) {
4644 BaseType = Context.getUnresolvedUsingType(Keyword: ElaboratedTypeKeyword::None,
4645 Qualifier: SS.getScopeRep(), D: UD);
4646 TLB.push<UnresolvedUsingTypeLoc>(T: BaseType).set(
4647 /*ElaboratedKeywordLoc=*/SourceLocation(),
4648 QualifierLoc: SS.getWithLocInContext(Context), NameLoc: IdLoc);
4649 } else {
4650 // FIXME: What else can appear here?
4651 assert(SS.isEmpty());
4652 BaseType = Context.getTypeDeclType(Decl: TyD);
4653 TLB.pushTypeSpec(T: BaseType).setNameLoc(IdLoc);
4654 }
4655 TInfo = TLB.getTypeSourceInfo(Context, T: BaseType);
4656 }
4657 }
4658
4659 if (!TInfo)
4660 TInfo = Context.getTrivialTypeSourceInfo(T: BaseType, Loc: IdLoc);
4661
4662 return BuildBaseInitializer(BaseType, BaseTInfo: TInfo, Init, ClassDecl, EllipsisLoc);
4663}
4664
4665MemInitResult
4666Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
4667 SourceLocation IdLoc) {
4668 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Val: Member);
4669 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Val: Member);
4670 assert((DirectMember || IndirectMember) &&
4671 "Member must be a FieldDecl or IndirectFieldDecl");
4672
4673 if (DiagnoseUnexpandedParameterPack(E: Init, UPPC: UPPC_Initializer))
4674 return true;
4675
4676 if (Member->isInvalidDecl())
4677 return true;
4678
4679 MultiExprArg Args;
4680 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Val: Init)) {
4681 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4682 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Val: Init)) {
4683 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4684 } else {
4685 // Template instantiation doesn't reconstruct ParenListExprs for us.
4686 Args = Init;
4687 }
4688
4689 SourceRange InitRange = Init->getSourceRange();
4690
4691 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4692 // Can't check initialization for a member of dependent type or when
4693 // any of the arguments are type-dependent expressions.
4694 DiscardCleanupsInEvaluationContext();
4695 } else {
4696 bool InitList = false;
4697 if (isa<InitListExpr>(Val: Init)) {
4698 InitList = true;
4699 Args = Init;
4700 }
4701
4702 // Initialize the member.
4703 InitializedEntity MemberEntity =
4704 DirectMember ? InitializedEntity::InitializeMember(Member: DirectMember, Parent: nullptr)
4705 : InitializedEntity::InitializeMember(Member: IndirectMember,
4706 Parent: nullptr);
4707 InitializationKind Kind =
4708 InitList ? InitializationKind::CreateDirectList(
4709 InitLoc: IdLoc, LBraceLoc: Init->getBeginLoc(), RBraceLoc: Init->getEndLoc())
4710 : InitializationKind::CreateDirect(InitLoc: IdLoc, LParenLoc: InitRange.getBegin(),
4711 RParenLoc: InitRange.getEnd());
4712
4713 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4714 ExprResult MemberInit = InitSeq.Perform(S&: *this, Entity: MemberEntity, Kind, Args,
4715 ResultType: nullptr);
4716 if (!MemberInit.isInvalid()) {
4717 // C++11 [class.base.init]p7:
4718 // The initialization of each base and member constitutes a
4719 // full-expression.
4720 MemberInit = ActOnFinishFullExpr(Expr: MemberInit.get(), CC: InitRange.getBegin(),
4721 /*DiscardedValue*/ false);
4722 }
4723
4724 if (MemberInit.isInvalid()) {
4725 // Args were sensible expressions but we couldn't initialize the member
4726 // from them. Preserve them in a RecoveryExpr instead.
4727 Init = CreateRecoveryExpr(Begin: InitRange.getBegin(), End: InitRange.getEnd(), SubExprs: Args,
4728 T: Member->getType())
4729 .get();
4730 if (!Init)
4731 return true;
4732 } else {
4733 Init = MemberInit.get();
4734 }
4735 }
4736
4737 if (DirectMember) {
4738 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4739 InitRange.getBegin(), Init,
4740 InitRange.getEnd());
4741 } else {
4742 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4743 InitRange.getBegin(), Init,
4744 InitRange.getEnd());
4745 }
4746}
4747
4748MemInitResult
4749Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
4750 CXXRecordDecl *ClassDecl) {
4751 SourceLocation NameLoc = TInfo->getTypeLoc().getSourceRange().getBegin();
4752 if (!LangOpts.CPlusPlus11)
4753 return Diag(Loc: NameLoc, DiagID: diag::err_delegating_ctor)
4754 << TInfo->getTypeLoc().getSourceRange();
4755 Diag(Loc: NameLoc, DiagID: diag::warn_cxx98_compat_delegating_ctor);
4756
4757 bool InitList = true;
4758 MultiExprArg Args = Init;
4759 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Val: Init)) {
4760 InitList = false;
4761 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4762 }
4763
4764 CanQualType ClassType = Context.getCanonicalTagType(TD: ClassDecl);
4765
4766 SourceRange InitRange = Init->getSourceRange();
4767 // Initialize the object.
4768 InitializedEntity DelegationEntity =
4769 InitializedEntity::InitializeDelegation(Type: ClassType);
4770 InitializationKind Kind =
4771 InitList ? InitializationKind::CreateDirectList(
4772 InitLoc: NameLoc, LBraceLoc: Init->getBeginLoc(), RBraceLoc: Init->getEndLoc())
4773 : InitializationKind::CreateDirect(InitLoc: NameLoc, LParenLoc: InitRange.getBegin(),
4774 RParenLoc: InitRange.getEnd());
4775 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4776 ExprResult DelegationInit = InitSeq.Perform(S&: *this, Entity: DelegationEntity, Kind,
4777 Args, ResultType: nullptr);
4778 if (!DelegationInit.isInvalid()) {
4779 assert((DelegationInit.get()->containsErrors() ||
4780 cast<CXXConstructExpr>(DelegationInit.get())->getConstructor()) &&
4781 "Delegating constructor with no target?");
4782
4783 // C++11 [class.base.init]p7:
4784 // The initialization of each base and member constitutes a
4785 // full-expression.
4786 DelegationInit = ActOnFinishFullExpr(
4787 Expr: DelegationInit.get(), CC: InitRange.getBegin(), /*DiscardedValue*/ false);
4788 }
4789
4790 if (DelegationInit.isInvalid()) {
4791 DelegationInit = CreateRecoveryExpr(Begin: InitRange.getBegin(),
4792 End: InitRange.getEnd(), SubExprs: Args, T: ClassType);
4793 if (DelegationInit.isInvalid())
4794 return true;
4795 } else {
4796 // If we are in a dependent context, template instantiation will
4797 // perform this type-checking again. Just save the arguments that we
4798 // received in a ParenListExpr.
4799 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4800 // of the information that we have about the base
4801 // initializer. However, deconstructing the ASTs is a dicey process,
4802 // and this approach is far more likely to get the corner cases right.
4803 if (CurContext->isDependentContext())
4804 DelegationInit = Init;
4805 }
4806
4807 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4808 DelegationInit.getAs<Expr>(),
4809 InitRange.getEnd());
4810}
4811
4812MemInitResult
4813Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4814 Expr *Init, CXXRecordDecl *ClassDecl,
4815 SourceLocation EllipsisLoc) {
4816 SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getBeginLoc();
4817
4818 if (!BaseType->isDependentType() && !BaseType->isRecordType())
4819 return Diag(Loc: BaseLoc, DiagID: diag::err_base_init_does_not_name_class)
4820 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
4821
4822 // C++ [class.base.init]p2:
4823 // [...] Unless the mem-initializer-id names a nonstatic data
4824 // member of the constructor's class or a direct or virtual base
4825 // of that class, the mem-initializer is ill-formed. A
4826 // mem-initializer-list can initialize a base class using any
4827 // name that denotes that base class type.
4828
4829 // We can store the initializers in "as-written" form and delay analysis until
4830 // instantiation if the constructor is dependent. But not for dependent
4831 // (broken) code in a non-template! SetCtorInitializers does not expect this.
4832 bool Dependent = CurContext->isDependentContext() &&
4833 (BaseType->isDependentType() || Init->isTypeDependent());
4834
4835 SourceRange InitRange = Init->getSourceRange();
4836 if (EllipsisLoc.isValid()) {
4837 // This is a pack expansion.
4838 if (!BaseType->containsUnexpandedParameterPack()) {
4839 Diag(Loc: EllipsisLoc, DiagID: diag::err_pack_expansion_without_parameter_packs)
4840 << SourceRange(BaseLoc, InitRange.getEnd());
4841
4842 EllipsisLoc = SourceLocation();
4843 }
4844 } else {
4845 // Check for any unexpanded parameter packs.
4846 if (DiagnoseUnexpandedParameterPack(Loc: BaseLoc, T: BaseTInfo, UPPC: UPPC_Initializer))
4847 return true;
4848
4849 if (DiagnoseUnexpandedParameterPack(E: Init, UPPC: UPPC_Initializer))
4850 return true;
4851 }
4852
4853 // Check for direct and virtual base classes.
4854 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4855 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4856 if (!Dependent) {
4857 if (declaresSameEntity(D1: ClassDecl, D2: BaseType->getAsCXXRecordDecl()))
4858 return BuildDelegatingInitializer(TInfo: BaseTInfo, Init, ClassDecl);
4859
4860 FindBaseInitializer(SemaRef&: *this, ClassDecl, BaseType, DirectBaseSpec,
4861 VirtualBaseSpec);
4862
4863 // C++ [base.class.init]p2:
4864 // Unless the mem-initializer-id names a nonstatic data member of the
4865 // constructor's class or a direct or virtual base of that class, the
4866 // mem-initializer is ill-formed.
4867 if (!DirectBaseSpec && !VirtualBaseSpec) {
4868 // If the class has any dependent bases, then it's possible that
4869 // one of those types will resolve to the same type as
4870 // BaseType. Therefore, just treat this as a dependent base
4871 // class initialization. FIXME: Should we try to check the
4872 // initialization anyway? It seems odd.
4873 if (ClassDecl->hasAnyDependentBases())
4874 Dependent = true;
4875 else
4876 return Diag(Loc: BaseLoc, DiagID: diag::err_not_direct_base_or_virtual)
4877 << BaseType << Context.getCanonicalTagType(TD: ClassDecl)
4878 << BaseTInfo->getTypeLoc().getSourceRange();
4879 }
4880 }
4881
4882 if (Dependent) {
4883 DiscardCleanupsInEvaluationContext();
4884
4885 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4886 /*IsVirtual=*/false,
4887 InitRange.getBegin(), Init,
4888 InitRange.getEnd(), EllipsisLoc);
4889 }
4890
4891 // C++ [base.class.init]p2:
4892 // If a mem-initializer-id is ambiguous because it designates both
4893 // a direct non-virtual base class and an inherited virtual base
4894 // class, the mem-initializer is ill-formed.
4895 if (DirectBaseSpec && VirtualBaseSpec)
4896 return Diag(Loc: BaseLoc, DiagID: diag::err_base_init_direct_and_virtual)
4897 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4898
4899 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4900 if (!BaseSpec)
4901 BaseSpec = VirtualBaseSpec;
4902
4903 // Initialize the base.
4904 bool InitList = true;
4905 MultiExprArg Args = Init;
4906 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Val: Init)) {
4907 InitList = false;
4908 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4909 }
4910
4911 InitializedEntity BaseEntity =
4912 InitializedEntity::InitializeBase(Context, Base: BaseSpec, IsInheritedVirtualBase: VirtualBaseSpec);
4913 InitializationKind Kind =
4914 InitList ? InitializationKind::CreateDirectList(InitLoc: BaseLoc)
4915 : InitializationKind::CreateDirect(InitLoc: BaseLoc, LParenLoc: InitRange.getBegin(),
4916 RParenLoc: InitRange.getEnd());
4917 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4918 ExprResult BaseInit = InitSeq.Perform(S&: *this, Entity: BaseEntity, Kind, Args, ResultType: nullptr);
4919 if (!BaseInit.isInvalid()) {
4920 // C++11 [class.base.init]p7:
4921 // The initialization of each base and member constitutes a
4922 // full-expression.
4923 BaseInit = ActOnFinishFullExpr(Expr: BaseInit.get(), CC: InitRange.getBegin(),
4924 /*DiscardedValue*/ false);
4925 }
4926
4927 if (BaseInit.isInvalid()) {
4928 BaseInit = CreateRecoveryExpr(Begin: InitRange.getBegin(), End: InitRange.getEnd(),
4929 SubExprs: Args, T: BaseType);
4930 if (BaseInit.isInvalid())
4931 return true;
4932 } else {
4933 // If we are in a dependent context, template instantiation will
4934 // perform this type-checking again. Just save the arguments that we
4935 // received in a ParenListExpr.
4936 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4937 // of the information that we have about the base
4938 // initializer. However, deconstructing the ASTs is a dicey process,
4939 // and this approach is far more likely to get the corner cases right.
4940 if (CurContext->isDependentContext())
4941 BaseInit = Init;
4942 }
4943
4944 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4945 BaseSpec->isVirtual(),
4946 InitRange.getBegin(),
4947 BaseInit.getAs<Expr>(),
4948 InitRange.getEnd(), EllipsisLoc);
4949}
4950
4951// Create a static_cast\<T&&>(expr).
4952static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
4953 QualType TargetType =
4954 SemaRef.BuildReferenceType(T: E->getType(), /*SpelledAsLValue*/ LValueRef: false,
4955 Loc: SourceLocation(), Entity: DeclarationName());
4956 SourceLocation ExprLoc = E->getBeginLoc();
4957 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4958 T: TargetType, Loc: ExprLoc);
4959
4960 return SemaRef.BuildCXXNamedCast(OpLoc: ExprLoc, Kind: tok::kw_static_cast, Ty: TargetLoc, E,
4961 AngleBrackets: SourceRange(ExprLoc, ExprLoc),
4962 Parens: E->getSourceRange()).get();
4963}
4964
4965/// ImplicitInitializerKind - How an implicit base or member initializer should
4966/// initialize its base or member.
4967enum ImplicitInitializerKind {
4968 IIK_Default,
4969 IIK_Copy,
4970 IIK_Move,
4971 IIK_Inherit
4972};
4973
4974static bool
4975BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4976 ImplicitInitializerKind ImplicitInitKind,
4977 CXXBaseSpecifier *BaseSpec,
4978 bool IsInheritedVirtualBase,
4979 CXXCtorInitializer *&CXXBaseInit) {
4980 InitializedEntity InitEntity
4981 = InitializedEntity::InitializeBase(Context&: SemaRef.Context, Base: BaseSpec,
4982 IsInheritedVirtualBase);
4983
4984 ExprResult BaseInit;
4985
4986 switch (ImplicitInitKind) {
4987 case IIK_Inherit:
4988 case IIK_Default: {
4989 InitializationKind InitKind
4990 = InitializationKind::CreateDefault(InitLoc: Constructor->getLocation());
4991 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, {});
4992 BaseInit = InitSeq.Perform(S&: SemaRef, Entity: InitEntity, Kind: InitKind, Args: {});
4993 break;
4994 }
4995
4996 case IIK_Move:
4997 case IIK_Copy: {
4998 bool Moving = ImplicitInitKind == IIK_Move;
4999 ParmVarDecl *Param = Constructor->getParamDecl(i: 0);
5000 QualType ParamType = Param->getType().getNonReferenceType();
5001
5002 Expr *CopyCtorArg =
5003 DeclRefExpr::Create(Context: SemaRef.Context, QualifierLoc: NestedNameSpecifierLoc(),
5004 TemplateKWLoc: SourceLocation(), D: Param, RefersToEnclosingVariableOrCapture: false,
5005 NameLoc: Constructor->getLocation(), T: ParamType,
5006 VK: VK_LValue, FoundD: nullptr);
5007
5008 SemaRef.MarkDeclRefReferenced(E: cast<DeclRefExpr>(Val: CopyCtorArg));
5009
5010 // Cast to the base class to avoid ambiguities.
5011 QualType ArgTy =
5012 SemaRef.Context.getQualifiedType(T: BaseSpec->getType().getUnqualifiedType(),
5013 Qs: ParamType.getQualifiers());
5014
5015 if (Moving) {
5016 CopyCtorArg = CastForMoving(SemaRef, E: CopyCtorArg);
5017 }
5018
5019 CXXCastPath BasePath;
5020 BasePath.push_back(Elt: BaseSpec);
5021 CopyCtorArg = SemaRef.ImpCastExprToType(E: CopyCtorArg, Type: ArgTy,
5022 CK: CK_UncheckedDerivedToBase,
5023 VK: Moving ? VK_XValue : VK_LValue,
5024 BasePath: &BasePath).get();
5025
5026 InitializationKind InitKind
5027 = InitializationKind::CreateDirect(InitLoc: Constructor->getLocation(),
5028 LParenLoc: SourceLocation(), RParenLoc: SourceLocation());
5029 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
5030 BaseInit = InitSeq.Perform(S&: SemaRef, Entity: InitEntity, Kind: InitKind, Args: CopyCtorArg);
5031 break;
5032 }
5033 }
5034
5035 BaseInit = SemaRef.MaybeCreateExprWithCleanups(SubExpr: BaseInit);
5036 if (BaseInit.isInvalid())
5037 return true;
5038
5039 CXXBaseInit =
5040 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5041 SemaRef.Context.getTrivialTypeSourceInfo(T: BaseSpec->getType(),
5042 Loc: SourceLocation()),
5043 BaseSpec->isVirtual(),
5044 SourceLocation(),
5045 BaseInit.getAs<Expr>(),
5046 SourceLocation(),
5047 SourceLocation());
5048
5049 return false;
5050}
5051
5052static bool RefersToRValueRef(Expr *MemRef) {
5053 ValueDecl *Referenced = cast<MemberExpr>(Val: MemRef)->getMemberDecl();
5054 return Referenced->getType()->isRValueReferenceType();
5055}
5056
5057static bool
5058BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
5059 ImplicitInitializerKind ImplicitInitKind,
5060 FieldDecl *Field, IndirectFieldDecl *Indirect,
5061 CXXCtorInitializer *&CXXMemberInit) {
5062 if (Field->isInvalidDecl())
5063 return true;
5064
5065 SourceLocation Loc = Constructor->getLocation();
5066
5067 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
5068 bool Moving = ImplicitInitKind == IIK_Move;
5069 ParmVarDecl *Param = Constructor->getParamDecl(i: 0);
5070 QualType ParamType = Param->getType().getNonReferenceType();
5071
5072 // Suppress copying zero-width bitfields.
5073 if (Field->isZeroLengthBitField())
5074 return false;
5075
5076 Expr *MemberExprBase =
5077 DeclRefExpr::Create(Context: SemaRef.Context, QualifierLoc: NestedNameSpecifierLoc(),
5078 TemplateKWLoc: SourceLocation(), D: Param, RefersToEnclosingVariableOrCapture: false,
5079 NameLoc: Loc, T: ParamType, VK: VK_LValue, FoundD: nullptr);
5080
5081 SemaRef.MarkDeclRefReferenced(E: cast<DeclRefExpr>(Val: MemberExprBase));
5082
5083 if (Moving) {
5084 MemberExprBase = CastForMoving(SemaRef, E: MemberExprBase);
5085 }
5086
5087 // Build a reference to this field within the parameter.
5088 CXXScopeSpec SS;
5089 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
5090 Sema::LookupMemberName);
5091 MemberLookup.addDecl(D: Indirect ? cast<ValueDecl>(Val: Indirect)
5092 : cast<ValueDecl>(Val: Field), AS: AS_public);
5093 MemberLookup.resolveKind();
5094 ExprResult CtorArg
5095 = SemaRef.BuildMemberReferenceExpr(Base: MemberExprBase,
5096 BaseType: ParamType, OpLoc: Loc,
5097 /*IsArrow=*/false,
5098 SS,
5099 /*TemplateKWLoc=*/SourceLocation(),
5100 /*FirstQualifierInScope=*/nullptr,
5101 R&: MemberLookup,
5102 /*TemplateArgs=*/nullptr,
5103 /*S*/nullptr);
5104 if (CtorArg.isInvalid())
5105 return true;
5106
5107 // C++11 [class.copy]p15:
5108 // - if a member m has rvalue reference type T&&, it is direct-initialized
5109 // with static_cast<T&&>(x.m);
5110 if (RefersToRValueRef(MemRef: CtorArg.get())) {
5111 CtorArg = CastForMoving(SemaRef, E: CtorArg.get());
5112 }
5113
5114 InitializedEntity Entity =
5115 Indirect ? InitializedEntity::InitializeMemberImplicit(Member: Indirect)
5116 : InitializedEntity::InitializeMemberImplicit(Member: Field);
5117
5118 // Direct-initialize to use the copy constructor.
5119 InitializationKind InitKind =
5120 InitializationKind::CreateDirect(InitLoc: Loc, LParenLoc: SourceLocation(), RParenLoc: SourceLocation());
5121
5122 Expr *CtorArgE = CtorArg.getAs<Expr>();
5123 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
5124 ExprResult MemberInit =
5125 InitSeq.Perform(S&: SemaRef, Entity, Kind: InitKind, Args: MultiExprArg(&CtorArgE, 1));
5126 MemberInit = SemaRef.MaybeCreateExprWithCleanups(SubExpr: MemberInit);
5127 if (MemberInit.isInvalid())
5128 return true;
5129
5130 if (Indirect)
5131 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
5132 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
5133 else
5134 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
5135 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
5136 return false;
5137 }
5138
5139 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
5140 "Unhandled implicit init kind!");
5141
5142 QualType FieldBaseElementType =
5143 SemaRef.Context.getBaseElementType(QT: Field->getType());
5144
5145 if (FieldBaseElementType->isRecordType()) {
5146 InitializedEntity InitEntity =
5147 Indirect ? InitializedEntity::InitializeMemberImplicit(Member: Indirect)
5148 : InitializedEntity::InitializeMemberImplicit(Member: Field);
5149 InitializationKind InitKind =
5150 InitializationKind::CreateDefault(InitLoc: Loc);
5151
5152 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, {});
5153 ExprResult MemberInit = InitSeq.Perform(S&: SemaRef, Entity: InitEntity, Kind: InitKind, Args: {});
5154
5155 MemberInit = SemaRef.MaybeCreateExprWithCleanups(SubExpr: MemberInit);
5156 if (MemberInit.isInvalid())
5157 return true;
5158
5159 if (Indirect)
5160 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5161 Indirect, Loc,
5162 Loc,
5163 MemberInit.get(),
5164 Loc);
5165 else
5166 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5167 Field, Loc, Loc,
5168 MemberInit.get(),
5169 Loc);
5170 return false;
5171 }
5172
5173 if (!Field->getParent()->isUnion()) {
5174 if (FieldBaseElementType->isReferenceType()) {
5175 SemaRef.Diag(Loc: Constructor->getLocation(),
5176 DiagID: diag::err_uninitialized_member_in_ctor)
5177 << (int)Constructor->isImplicit()
5178 << SemaRef.Context.getCanonicalTagType(TD: Constructor->getParent()) << 0
5179 << Field->getDeclName();
5180 SemaRef.Diag(Loc: Field->getLocation(), DiagID: diag::note_declared_at);
5181 return true;
5182 }
5183
5184 if (FieldBaseElementType.isConstQualified()) {
5185 SemaRef.Diag(Loc: Constructor->getLocation(),
5186 DiagID: diag::err_uninitialized_member_in_ctor)
5187 << (int)Constructor->isImplicit()
5188 << SemaRef.Context.getCanonicalTagType(TD: Constructor->getParent()) << 1
5189 << Field->getDeclName();
5190 SemaRef.Diag(Loc: Field->getLocation(), DiagID: diag::note_declared_at);
5191 return true;
5192 }
5193 }
5194
5195 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
5196 // ARC and Weak:
5197 // Default-initialize Objective-C pointers to NULL.
5198 CXXMemberInit
5199 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
5200 Loc, Loc,
5201 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
5202 Loc);
5203 return false;
5204 }
5205
5206 // Nothing to initialize.
5207 CXXMemberInit = nullptr;
5208 return false;
5209}
5210
5211namespace {
5212struct BaseAndFieldInfo {
5213 Sema &S;
5214 CXXConstructorDecl *Ctor;
5215 bool AnyErrorsInInits;
5216 ImplicitInitializerKind IIK;
5217 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
5218 SmallVector<CXXCtorInitializer*, 8> AllToInit;
5219 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
5220
5221 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
5222 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
5223 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
5224 if (Ctor->getInheritedConstructor())
5225 IIK = IIK_Inherit;
5226 else if (Generated && Ctor->isCopyConstructor())
5227 IIK = IIK_Copy;
5228 else if (Generated && Ctor->isMoveConstructor())
5229 IIK = IIK_Move;
5230 else
5231 IIK = IIK_Default;
5232 }
5233
5234 bool isImplicitCopyOrMove() const {
5235 switch (IIK) {
5236 case IIK_Copy:
5237 case IIK_Move:
5238 return true;
5239
5240 case IIK_Default:
5241 case IIK_Inherit:
5242 return false;
5243 }
5244
5245 llvm_unreachable("Invalid ImplicitInitializerKind!");
5246 }
5247
5248 bool addFieldInitializer(CXXCtorInitializer *Init) {
5249 AllToInit.push_back(Elt: Init);
5250
5251 // Check whether this initializer makes the field "used".
5252 if (Init->getInit()->HasSideEffects(Ctx: S.Context))
5253 S.UnusedPrivateFields.remove(X: Init->getAnyMember());
5254
5255 return false;
5256 }
5257
5258 bool isInactiveUnionMember(FieldDecl *Field) {
5259 RecordDecl *Record = Field->getParent();
5260 if (!Record->isUnion())
5261 return false;
5262
5263 if (FieldDecl *Active =
5264 ActiveUnionMember.lookup(Val: Record->getCanonicalDecl()))
5265 return Active != Field->getCanonicalDecl();
5266
5267 // In an implicit copy or move constructor, ignore any in-class initializer.
5268 if (isImplicitCopyOrMove())
5269 return true;
5270
5271 // If there's no explicit initialization, the field is active only if it
5272 // has an in-class initializer...
5273 if (Field->hasInClassInitializer())
5274 return false;
5275 // ... or it's an anonymous struct or union whose class has an in-class
5276 // initializer.
5277 if (!Field->isAnonymousStructOrUnion())
5278 return true;
5279 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
5280 return !FieldRD->hasInClassInitializer();
5281 }
5282
5283 /// Determine whether the given field is, or is within, a union member
5284 /// that is inactive (because there was an initializer given for a different
5285 /// member of the union, or because the union was not initialized at all).
5286 bool isWithinInactiveUnionMember(FieldDecl *Field,
5287 IndirectFieldDecl *Indirect) {
5288 if (!Indirect)
5289 return isInactiveUnionMember(Field);
5290
5291 for (auto *C : Indirect->chain()) {
5292 FieldDecl *Field = dyn_cast<FieldDecl>(Val: C);
5293 if (Field && isInactiveUnionMember(Field))
5294 return true;
5295 }
5296 return false;
5297 }
5298};
5299}
5300
5301/// Determine whether the given type is an incomplete or zero-lenfgth
5302/// array type.
5303static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
5304 if (T->isIncompleteArrayType())
5305 return true;
5306
5307 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
5308 if (ArrayT->isZeroSize())
5309 return true;
5310
5311 T = ArrayT->getElementType();
5312 }
5313
5314 return false;
5315}
5316
5317static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
5318 FieldDecl *Field,
5319 IndirectFieldDecl *Indirect = nullptr) {
5320 if (Field->isInvalidDecl())
5321 return false;
5322
5323 // Overwhelmingly common case: we have a direct initializer for this field.
5324 if (CXXCtorInitializer *Init =
5325 Info.AllBaseFields.lookup(Val: Field->getCanonicalDecl()))
5326 return Info.addFieldInitializer(Init);
5327
5328 // C++11 [class.base.init]p8:
5329 // if the entity is a non-static data member that has a
5330 // brace-or-equal-initializer and either
5331 // -- the constructor's class is a union and no other variant member of that
5332 // union is designated by a mem-initializer-id or
5333 // -- the constructor's class is not a union, and, if the entity is a member
5334 // of an anonymous union, no other member of that union is designated by
5335 // a mem-initializer-id,
5336 // the entity is initialized as specified in [dcl.init].
5337 //
5338 // We also apply the same rules to handle anonymous structs within anonymous
5339 // unions.
5340 if (Info.isWithinInactiveUnionMember(Field, Indirect))
5341 return false;
5342
5343 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
5344 ExprResult DIE =
5345 SemaRef.BuildCXXDefaultInitExpr(Loc: Info.Ctor->getLocation(), Field);
5346 if (DIE.isInvalid())
5347 return true;
5348
5349 auto Entity = InitializedEntity::InitializeMemberImplicit(Member: Field);
5350 SemaRef.checkInitializerLifetime(Entity, Init: DIE.get());
5351
5352 CXXCtorInitializer *Init;
5353 if (Indirect)
5354 Init = new (SemaRef.Context)
5355 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
5356 SourceLocation(), DIE.get(), SourceLocation());
5357 else
5358 Init = new (SemaRef.Context)
5359 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
5360 SourceLocation(), DIE.get(), SourceLocation());
5361 return Info.addFieldInitializer(Init);
5362 }
5363
5364 // Don't initialize incomplete or zero-length arrays.
5365 if (isIncompleteOrZeroLengthArrayType(Context&: SemaRef.Context, T: Field->getType()))
5366 return false;
5367
5368 // Don't try to build an implicit initializer if there were semantic
5369 // errors in any of the initializers (and therefore we might be
5370 // missing some that the user actually wrote).
5371 if (Info.AnyErrorsInInits)
5372 return false;
5373
5374 CXXCtorInitializer *Init = nullptr;
5375 if (BuildImplicitMemberInitializer(SemaRef&: Info.S, Constructor: Info.Ctor, ImplicitInitKind: Info.IIK, Field,
5376 Indirect, CXXMemberInit&: Init))
5377 return true;
5378
5379 if (!Init)
5380 return false;
5381
5382 return Info.addFieldInitializer(Init);
5383}
5384
5385bool
5386Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
5387 CXXCtorInitializer *Initializer) {
5388 assert(Initializer->isDelegatingInitializer());
5389 Constructor->setNumCtorInitializers(1);
5390 CXXCtorInitializer **initializer =
5391 new (Context) CXXCtorInitializer*[1];
5392 memcpy(dest: initializer, src: &Initializer, n: sizeof (CXXCtorInitializer*));
5393 Constructor->setCtorInitializers(initializer);
5394
5395 if (CXXDestructorDecl *Dtor = LookupDestructor(Class: Constructor->getParent())) {
5396 MarkFunctionReferenced(Loc: Initializer->getSourceLocation(), Func: Dtor);
5397 DiagnoseUseOfDecl(D: Dtor, Locs: Initializer->getSourceLocation());
5398 }
5399
5400 DelegatingCtorDecls.push_back(LocalValue: Constructor);
5401
5402 DiagnoseUninitializedFields(SemaRef&: *this, Constructor);
5403
5404 return false;
5405}
5406
5407static CXXDestructorDecl *LookupDestructorIfRelevant(Sema &S,
5408 CXXRecordDecl *Class) {
5409 if (Class->isInvalidDecl())
5410 return nullptr;
5411 if (Class->hasIrrelevantDestructor())
5412 return nullptr;
5413
5414 // Dtor might still be missing, e.g because it's invalid.
5415 return S.LookupDestructor(Class);
5416}
5417
5418static void MarkFieldDestructorReferenced(Sema &S, SourceLocation Location,
5419 FieldDecl *Field) {
5420 if (Field->isInvalidDecl())
5421 return;
5422
5423 // Don't destroy incomplete or zero-length arrays.
5424 if (isIncompleteOrZeroLengthArrayType(Context&: S.Context, T: Field->getType()))
5425 return;
5426
5427 QualType FieldType = S.Context.getBaseElementType(QT: Field->getType());
5428
5429 auto *FieldClassDecl = FieldType->getAsCXXRecordDecl();
5430 if (!FieldClassDecl)
5431 return;
5432
5433 // The destructor for an implicit anonymous union member is never invoked.
5434 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5435 return;
5436
5437 auto *Dtor = LookupDestructorIfRelevant(S, Class: FieldClassDecl);
5438 if (!Dtor)
5439 return;
5440
5441 S.CheckDestructorAccess(Loc: Field->getLocation(), Dtor,
5442 PDiag: S.PDiag(DiagID: diag::err_access_dtor_field)
5443 << Field->getDeclName() << FieldType);
5444
5445 S.MarkFunctionReferenced(Loc: Location, Func: Dtor);
5446 S.DiagnoseUseOfDecl(D: Dtor, Locs: Location);
5447}
5448
5449static void MarkBaseDestructorsReferenced(Sema &S, SourceLocation Location,
5450 CXXRecordDecl *ClassDecl) {
5451 if (ClassDecl->isDependentContext())
5452 return;
5453
5454 // We only potentially invoke the destructors of potentially constructed
5455 // subobjects.
5456 bool VisitVirtualBases = !ClassDecl->isAbstract();
5457
5458 // If the destructor exists and has already been marked used in the MS ABI,
5459 // then virtual base destructors have already been checked and marked used.
5460 // Skip checking them again to avoid duplicate diagnostics.
5461 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5462 CXXDestructorDecl *Dtor = ClassDecl->getDestructor();
5463 if (Dtor && Dtor->isUsed())
5464 VisitVirtualBases = false;
5465 }
5466
5467 llvm::SmallPtrSet<const CXXRecordDecl *, 8> DirectVirtualBases;
5468
5469 // Bases.
5470 for (const auto &Base : ClassDecl->bases()) {
5471 auto *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
5472 if (!BaseClassDecl)
5473 continue;
5474
5475 // Remember direct virtual bases.
5476 if (Base.isVirtual()) {
5477 if (!VisitVirtualBases)
5478 continue;
5479 DirectVirtualBases.insert(Ptr: BaseClassDecl);
5480 }
5481
5482 auto *Dtor = LookupDestructorIfRelevant(S, Class: BaseClassDecl);
5483 if (!Dtor)
5484 continue;
5485
5486 // FIXME: caret should be on the start of the class name
5487 S.CheckDestructorAccess(Loc: Base.getBeginLoc(), Dtor,
5488 PDiag: S.PDiag(DiagID: diag::err_access_dtor_base)
5489 << Base.getType() << Base.getSourceRange(),
5490 objectType: S.Context.getCanonicalTagType(TD: ClassDecl));
5491
5492 S.MarkFunctionReferenced(Loc: Location, Func: Dtor);
5493 S.DiagnoseUseOfDecl(D: Dtor, Locs: Location);
5494 }
5495
5496 if (VisitVirtualBases)
5497 S.MarkVirtualBaseDestructorsReferenced(Location, ClassDecl,
5498 DirectVirtualBases: &DirectVirtualBases);
5499}
5500
5501bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5502 ArrayRef<CXXCtorInitializer *> Initializers) {
5503 if (Constructor->isDependentContext()) {
5504 // Just store the initializers as written, they will be checked during
5505 // instantiation.
5506 if (!Initializers.empty()) {
5507 Constructor->setNumCtorInitializers(Initializers.size());
5508 CXXCtorInitializer **baseOrMemberInitializers =
5509 new (Context) CXXCtorInitializer*[Initializers.size()];
5510 memcpy(dest: baseOrMemberInitializers, src: Initializers.data(),
5511 n: Initializers.size() * sizeof(CXXCtorInitializer*));
5512 Constructor->setCtorInitializers(baseOrMemberInitializers);
5513 }
5514
5515 // Let template instantiation know whether we had errors.
5516 if (AnyErrors)
5517 Constructor->setInvalidDecl();
5518
5519 return false;
5520 }
5521
5522 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
5523
5524 // We need to build the initializer AST according to order of construction
5525 // and not what user specified in the Initializers list.
5526 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
5527 if (!ClassDecl)
5528 return true;
5529
5530 bool HadError = false;
5531
5532 for (CXXCtorInitializer *Member : Initializers) {
5533 if (Member->isBaseInitializer())
5534 Info.AllBaseFields[Member->getBaseClass()->getAsCanonical<RecordType>()] =
5535 Member;
5536 else {
5537 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
5538
5539 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
5540 for (auto *C : F->chain()) {
5541 FieldDecl *FD = dyn_cast<FieldDecl>(Val: C);
5542 if (FD && FD->getParent()->isUnion())
5543 Info.ActiveUnionMember.insert(KV: std::make_pair(
5544 x: FD->getParent()->getCanonicalDecl(), y: FD->getCanonicalDecl()));
5545 }
5546 } else if (FieldDecl *FD = Member->getMember()) {
5547 if (FD->getParent()->isUnion())
5548 Info.ActiveUnionMember.insert(KV: std::make_pair(
5549 x: FD->getParent()->getCanonicalDecl(), y: FD->getCanonicalDecl()));
5550 }
5551 }
5552 }
5553
5554 // Keep track of the direct virtual bases.
5555 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
5556 for (auto &I : ClassDecl->bases()) {
5557 if (I.isVirtual())
5558 DirectVBases.insert(Ptr: &I);
5559 }
5560
5561 // Push virtual bases before others.
5562 for (auto &VBase : ClassDecl->vbases()) {
5563 if (CXXCtorInitializer *Value = Info.AllBaseFields.lookup(
5564 Val: VBase.getType()->getAsCanonical<RecordType>())) {
5565 // [class.base.init]p7, per DR257:
5566 // A mem-initializer where the mem-initializer-id names a virtual base
5567 // class is ignored during execution of a constructor of any class that
5568 // is not the most derived class.
5569 if (ClassDecl->isAbstract()) {
5570 // FIXME: Provide a fixit to remove the base specifier. This requires
5571 // tracking the location of the associated comma for a base specifier.
5572 Diag(Loc: Value->getSourceLocation(), DiagID: diag::warn_abstract_vbase_init_ignored)
5573 << VBase.getType() << ClassDecl;
5574 DiagnoseAbstractType(RD: ClassDecl);
5575 }
5576
5577 Info.AllToInit.push_back(Elt: Value);
5578 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
5579 // [class.base.init]p8, per DR257:
5580 // If a given [...] base class is not named by a mem-initializer-id
5581 // [...] and the entity is not a virtual base class of an abstract
5582 // class, then [...] the entity is default-initialized.
5583 bool IsInheritedVirtualBase = !DirectVBases.count(Ptr: &VBase);
5584 CXXCtorInitializer *CXXBaseInit;
5585 if (BuildImplicitBaseInitializer(SemaRef&: *this, Constructor, ImplicitInitKind: Info.IIK,
5586 BaseSpec: &VBase, IsInheritedVirtualBase,
5587 CXXBaseInit)) {
5588 HadError = true;
5589 continue;
5590 }
5591
5592 Info.AllToInit.push_back(Elt: CXXBaseInit);
5593 }
5594 }
5595
5596 // Non-virtual bases.
5597 for (auto &Base : ClassDecl->bases()) {
5598 // Virtuals are in the virtual base list and already constructed.
5599 if (Base.isVirtual())
5600 continue;
5601
5602 if (CXXCtorInitializer *Value = Info.AllBaseFields.lookup(
5603 Val: Base.getType()->getAsCanonical<RecordType>())) {
5604 Info.AllToInit.push_back(Elt: Value);
5605 } else if (!AnyErrors) {
5606 CXXCtorInitializer *CXXBaseInit;
5607 if (BuildImplicitBaseInitializer(SemaRef&: *this, Constructor, ImplicitInitKind: Info.IIK,
5608 BaseSpec: &Base, /*IsInheritedVirtualBase=*/false,
5609 CXXBaseInit)) {
5610 HadError = true;
5611 continue;
5612 }
5613
5614 Info.AllToInit.push_back(Elt: CXXBaseInit);
5615 }
5616 }
5617
5618 // Fields.
5619 for (auto *Mem : ClassDecl->decls()) {
5620 if (auto *F = dyn_cast<FieldDecl>(Val: Mem)) {
5621 // C++ [class.bit]p2:
5622 // A declaration for a bit-field that omits the identifier declares an
5623 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
5624 // initialized.
5625 if (F->isUnnamedBitField())
5626 continue;
5627
5628 // If we're not generating the implicit copy/move constructor, then we'll
5629 // handle anonymous struct/union fields based on their individual
5630 // indirect fields.
5631 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
5632 continue;
5633
5634 if (CollectFieldInitializer(SemaRef&: *this, Info, Field: F))
5635 HadError = true;
5636 continue;
5637 }
5638
5639 // Beyond this point, we only consider default initialization.
5640 if (Info.isImplicitCopyOrMove())
5641 continue;
5642
5643 if (auto *F = dyn_cast<IndirectFieldDecl>(Val: Mem)) {
5644 if (F->getType()->isIncompleteArrayType()) {
5645 assert(ClassDecl->hasFlexibleArrayMember() &&
5646 "Incomplete array type is not valid");
5647 continue;
5648 }
5649
5650 // Initialize each field of an anonymous struct individually.
5651 if (CollectFieldInitializer(SemaRef&: *this, Info, Field: F->getAnonField(), Indirect: F))
5652 HadError = true;
5653
5654 continue;
5655 }
5656 }
5657
5658 unsigned NumInitializers = Info.AllToInit.size();
5659 if (NumInitializers > 0) {
5660 Constructor->setNumCtorInitializers(NumInitializers);
5661 CXXCtorInitializer **baseOrMemberInitializers =
5662 new (Context) CXXCtorInitializer*[NumInitializers];
5663 memcpy(dest: baseOrMemberInitializers, src: Info.AllToInit.data(),
5664 n: NumInitializers * sizeof(CXXCtorInitializer*));
5665 Constructor->setCtorInitializers(baseOrMemberInitializers);
5666
5667 SourceLocation Location = Constructor->getLocation();
5668
5669 // Constructors implicitly reference the base and member
5670 // destructors.
5671
5672 for (CXXCtorInitializer *Initializer : Info.AllToInit) {
5673 FieldDecl *Field = Initializer->getAnyMember();
5674 if (!Field)
5675 continue;
5676
5677 // C++ [class.base.init]p12:
5678 // In a non-delegating constructor, the destructor for each
5679 // potentially constructed subobject of class type is potentially
5680 // invoked.
5681 MarkFieldDestructorReferenced(S&: *this, Location, Field);
5682 }
5683
5684 MarkBaseDestructorsReferenced(S&: *this, Location, ClassDecl: Constructor->getParent());
5685 }
5686
5687 return HadError;
5688}
5689
5690static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
5691 if (const RecordType *RT = Field->getType()->getAsCanonical<RecordType>()) {
5692 const RecordDecl *RD = RT->getDecl();
5693 if (RD->isAnonymousStructOrUnion()) {
5694 for (auto *Field : RD->getDefinitionOrSelf()->fields())
5695 PopulateKeysForFields(Field, IdealInits);
5696 return;
5697 }
5698 }
5699 IdealInits.push_back(Elt: Field->getCanonicalDecl());
5700}
5701
5702static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
5703 return Context.getCanonicalType(T: BaseType).getTypePtr();
5704}
5705
5706static const void *GetKeyForMember(ASTContext &Context,
5707 CXXCtorInitializer *Member) {
5708 if (!Member->isAnyMemberInitializer())
5709 return GetKeyForBase(Context, BaseType: QualType(Member->getBaseClass(), 0));
5710
5711 return Member->getAnyMember()->getCanonicalDecl();
5712}
5713
5714static void AddInitializerToDiag(const Sema::SemaDiagnosticBuilder &Diag,
5715 const CXXCtorInitializer *Previous,
5716 const CXXCtorInitializer *Current) {
5717 if (Previous->isAnyMemberInitializer())
5718 Diag << 0 << Previous->getAnyMember();
5719 else
5720 Diag << 1 << Previous->getTypeSourceInfo()->getType();
5721
5722 if (Current->isAnyMemberInitializer())
5723 Diag << 0 << Current->getAnyMember();
5724 else
5725 Diag << 1 << Current->getTypeSourceInfo()->getType();
5726}
5727
5728static void DiagnoseBaseOrMemInitializerOrder(
5729 Sema &SemaRef, const CXXConstructorDecl *Constructor,
5730 ArrayRef<CXXCtorInitializer *> Inits) {
5731 if (Constructor->getDeclContext()->isDependentContext())
5732 return;
5733
5734 // Don't check initializers order unless the warning is enabled at the
5735 // location of at least one initializer.
5736 bool ShouldCheckOrder = false;
5737 for (const CXXCtorInitializer *Init : Inits) {
5738 if (!SemaRef.Diags.isIgnored(DiagID: diag::warn_initializer_out_of_order,
5739 Loc: Init->getSourceLocation())) {
5740 ShouldCheckOrder = true;
5741 break;
5742 }
5743 }
5744 if (!ShouldCheckOrder)
5745 return;
5746
5747 // Build the list of bases and members in the order that they'll
5748 // actually be initialized. The explicit initializers should be in
5749 // this same order but may be missing things.
5750 SmallVector<const void*, 32> IdealInitKeys;
5751
5752 const CXXRecordDecl *ClassDecl = Constructor->getParent();
5753
5754 // 1. Virtual bases.
5755 for (const auto &VBase : ClassDecl->vbases())
5756 IdealInitKeys.push_back(Elt: GetKeyForBase(Context&: SemaRef.Context, BaseType: VBase.getType()));
5757
5758 // 2. Non-virtual bases.
5759 for (const auto &Base : ClassDecl->bases()) {
5760 if (Base.isVirtual())
5761 continue;
5762 IdealInitKeys.push_back(Elt: GetKeyForBase(Context&: SemaRef.Context, BaseType: Base.getType()));
5763 }
5764
5765 // 3. Direct fields.
5766 for (auto *Field : ClassDecl->fields()) {
5767 if (Field->isUnnamedBitField())
5768 continue;
5769
5770 PopulateKeysForFields(Field, IdealInits&: IdealInitKeys);
5771 }
5772
5773 unsigned NumIdealInits = IdealInitKeys.size();
5774 unsigned IdealIndex = 0;
5775
5776 // Track initializers that are in an incorrect order for either a warning or
5777 // note if multiple ones occur.
5778 SmallVector<unsigned> WarnIndexes;
5779 // Correlates the index of an initializer in the init-list to the index of
5780 // the field/base in the class.
5781 SmallVector<std::pair<unsigned, unsigned>, 32> CorrelatedInitOrder;
5782
5783 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5784 const void *InitKey = GetKeyForMember(Context&: SemaRef.Context, Member: Inits[InitIndex]);
5785
5786 // Scan forward to try to find this initializer in the idealized
5787 // initializers list.
5788 for (; IdealIndex != NumIdealInits; ++IdealIndex)
5789 if (InitKey == IdealInitKeys[IdealIndex])
5790 break;
5791
5792 // If we didn't find this initializer, it must be because we
5793 // scanned past it on a previous iteration. That can only
5794 // happen if we're out of order; emit a warning.
5795 if (IdealIndex == NumIdealInits && InitIndex) {
5796 WarnIndexes.push_back(Elt: InitIndex);
5797
5798 // Move back to the initializer's location in the ideal list.
5799 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5800 if (InitKey == IdealInitKeys[IdealIndex])
5801 break;
5802
5803 assert(IdealIndex < NumIdealInits &&
5804 "initializer not found in initializer list");
5805 }
5806 CorrelatedInitOrder.emplace_back(Args&: IdealIndex, Args&: InitIndex);
5807 }
5808
5809 if (WarnIndexes.empty())
5810 return;
5811
5812 // Sort based on the ideal order, first in the pair.
5813 llvm::sort(C&: CorrelatedInitOrder, Comp: llvm::less_first());
5814
5815 // Introduce a new scope as SemaDiagnosticBuilder needs to be destroyed to
5816 // emit the diagnostic before we can try adding notes.
5817 {
5818 Sema::SemaDiagnosticBuilder D = SemaRef.Diag(
5819 Loc: Inits[WarnIndexes.front() - 1]->getSourceLocation(),
5820 DiagID: WarnIndexes.size() == 1 ? diag::warn_initializer_out_of_order
5821 : diag::warn_some_initializers_out_of_order);
5822
5823 for (unsigned I = 0; I < CorrelatedInitOrder.size(); ++I) {
5824 if (CorrelatedInitOrder[I].second == I)
5825 continue;
5826 // Ideally we would be using InsertFromRange here, but clang doesn't
5827 // appear to handle InsertFromRange correctly when the source range is
5828 // modified by another fix-it.
5829 D << FixItHint::CreateReplacement(
5830 RemoveRange: Inits[I]->getSourceRange(),
5831 Code: Lexer::getSourceText(
5832 Range: CharSourceRange::getTokenRange(
5833 R: Inits[CorrelatedInitOrder[I].second]->getSourceRange()),
5834 SM: SemaRef.getSourceManager(), LangOpts: SemaRef.getLangOpts()));
5835 }
5836
5837 // If there is only 1 item out of order, the warning expects the name and
5838 // type of each being added to it.
5839 if (WarnIndexes.size() == 1) {
5840 AddInitializerToDiag(Diag: D, Previous: Inits[WarnIndexes.front() - 1],
5841 Current: Inits[WarnIndexes.front()]);
5842 return;
5843 }
5844 }
5845 // More than 1 item to warn, create notes letting the user know which ones
5846 // are bad.
5847 for (unsigned WarnIndex : WarnIndexes) {
5848 const clang::CXXCtorInitializer *PrevInit = Inits[WarnIndex - 1];
5849 auto D = SemaRef.Diag(Loc: PrevInit->getSourceLocation(),
5850 DiagID: diag::note_initializer_out_of_order);
5851 AddInitializerToDiag(Diag: D, Previous: PrevInit, Current: Inits[WarnIndex]);
5852 D << PrevInit->getSourceRange();
5853 }
5854}
5855
5856namespace {
5857bool CheckRedundantInit(Sema &S,
5858 CXXCtorInitializer *Init,
5859 CXXCtorInitializer *&PrevInit) {
5860 if (!PrevInit) {
5861 PrevInit = Init;
5862 return false;
5863 }
5864
5865 if (FieldDecl *Field = Init->getAnyMember())
5866 S.Diag(Loc: Init->getSourceLocation(),
5867 DiagID: diag::err_multiple_mem_initialization)
5868 << Field->getDeclName()
5869 << Init->getSourceRange();
5870 else {
5871 const Type *BaseClass = Init->getBaseClass();
5872 assert(BaseClass && "neither field nor base");
5873 S.Diag(Loc: Init->getSourceLocation(),
5874 DiagID: diag::err_multiple_base_initialization)
5875 << QualType(BaseClass, 0)
5876 << Init->getSourceRange();
5877 }
5878 S.Diag(Loc: PrevInit->getSourceLocation(), DiagID: diag::note_previous_initializer)
5879 << 0 << PrevInit->getSourceRange();
5880
5881 return true;
5882}
5883
5884typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5885typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5886
5887bool CheckRedundantUnionInit(Sema &S,
5888 CXXCtorInitializer *Init,
5889 RedundantUnionMap &Unions) {
5890 FieldDecl *Field = Init->getAnyMember();
5891 RecordDecl *Parent = Field->getParent();
5892 NamedDecl *Child = Field;
5893
5894 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5895 if (Parent->isUnion()) {
5896 UnionEntry &En = Unions[Parent];
5897 if (En.first && En.first != Child) {
5898 S.Diag(Loc: Init->getSourceLocation(),
5899 DiagID: diag::err_multiple_mem_union_initialization)
5900 << Field->getDeclName()
5901 << Init->getSourceRange();
5902 S.Diag(Loc: En.second->getSourceLocation(), DiagID: diag::note_previous_initializer)
5903 << 0 << En.second->getSourceRange();
5904 return true;
5905 }
5906 if (!En.first) {
5907 En.first = Child;
5908 En.second = Init;
5909 }
5910 if (!Parent->isAnonymousStructOrUnion())
5911 return false;
5912 }
5913
5914 Child = Parent;
5915 Parent = cast<RecordDecl>(Val: Parent->getDeclContext());
5916 }
5917
5918 return false;
5919}
5920} // namespace
5921
5922void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5923 SourceLocation ColonLoc,
5924 ArrayRef<CXXCtorInitializer*> MemInits,
5925 bool AnyErrors) {
5926 if (!ConstructorDecl)
5927 return;
5928
5929 AdjustDeclIfTemplate(Decl&: ConstructorDecl);
5930
5931 CXXConstructorDecl *Constructor
5932 = dyn_cast<CXXConstructorDecl>(Val: ConstructorDecl);
5933
5934 if (!Constructor) {
5935 Diag(Loc: ColonLoc, DiagID: diag::err_only_constructors_take_base_inits);
5936 return;
5937 }
5938
5939 // Mapping for the duplicate initializers check.
5940 // For member initializers, this is keyed with a FieldDecl*.
5941 // For base initializers, this is keyed with a Type*.
5942 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5943
5944 // Mapping for the inconsistent anonymous-union initializers check.
5945 RedundantUnionMap MemberUnions;
5946
5947 bool HadError = false;
5948 for (unsigned i = 0; i < MemInits.size(); i++) {
5949 CXXCtorInitializer *Init = MemInits[i];
5950
5951 // Set the source order index.
5952 Init->setSourceOrder(i);
5953
5954 if (Init->isAnyMemberInitializer()) {
5955 const void *Key = GetKeyForMember(Context, Member: Init);
5956 if (CheckRedundantInit(S&: *this, Init, PrevInit&: Members[Key]) ||
5957 CheckRedundantUnionInit(S&: *this, Init, Unions&: MemberUnions))
5958 HadError = true;
5959 } else if (Init->isBaseInitializer()) {
5960 const void *Key = GetKeyForMember(Context, Member: Init);
5961 if (CheckRedundantInit(S&: *this, Init, PrevInit&: Members[Key]))
5962 HadError = true;
5963 } else {
5964 assert(Init->isDelegatingInitializer());
5965 // This must be the only initializer
5966 if (MemInits.size() != 1) {
5967 Diag(Loc: Init->getSourceLocation(),
5968 DiagID: diag::err_delegating_initializer_alone)
5969 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5970 // We will treat this as being the only initializer.
5971 }
5972 SetDelegatingInitializer(Constructor, Initializer: MemInits[i]);
5973 // Return immediately as the initializer is set.
5974 return;
5975 }
5976 }
5977
5978 if (HadError)
5979 return;
5980
5981 DiagnoseBaseOrMemInitializerOrder(SemaRef&: *this, Constructor, Inits: MemInits);
5982
5983 SetCtorInitializers(Constructor, AnyErrors, Initializers: MemInits);
5984
5985 DiagnoseUninitializedFields(SemaRef&: *this, Constructor);
5986}
5987
5988void Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5989 CXXRecordDecl *ClassDecl) {
5990 // Ignore dependent contexts. Also ignore unions, since their members never
5991 // have destructors implicitly called.
5992 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5993 return;
5994
5995 // FIXME: all the access-control diagnostics are positioned on the
5996 // field/base declaration. That's probably good; that said, the
5997 // user might reasonably want to know why the destructor is being
5998 // emitted, and we currently don't say.
5999
6000 // Non-static data members.
6001 for (auto *Field : ClassDecl->fields()) {
6002 MarkFieldDestructorReferenced(S&: *this, Location, Field);
6003 }
6004
6005 MarkBaseDestructorsReferenced(S&: *this, Location, ClassDecl);
6006}
6007
6008void Sema::MarkVirtualBaseDestructorsReferenced(
6009 SourceLocation Location, CXXRecordDecl *ClassDecl,
6010 llvm::SmallPtrSetImpl<const CXXRecordDecl *> *DirectVirtualBases) {
6011 // Virtual bases.
6012 for (const auto &VBase : ClassDecl->vbases()) {
6013 auto *BaseClassDecl = VBase.getType()->getAsCXXRecordDecl();
6014 if (!BaseClassDecl)
6015 continue;
6016
6017 // Ignore already visited direct virtual bases.
6018 if (DirectVirtualBases && DirectVirtualBases->count(Ptr: BaseClassDecl))
6019 continue;
6020
6021 auto *Dtor = LookupDestructorIfRelevant(S&: *this, Class: BaseClassDecl);
6022 if (!Dtor)
6023 continue;
6024
6025 CanQualType CT = Context.getCanonicalTagType(TD: ClassDecl);
6026 if (CheckDestructorAccess(Loc: ClassDecl->getLocation(), Dtor,
6027 PDiag: PDiag(DiagID: diag::err_access_dtor_vbase)
6028 << CT << VBase.getType(),
6029 objectType: CT) == AR_accessible) {
6030 CheckDerivedToBaseConversion(
6031 Derived: CT, Base: VBase.getType(), InaccessibleBaseID: diag::err_access_dtor_vbase, AmbiguousBaseConvID: 0,
6032 Loc: ClassDecl->getLocation(), Range: SourceRange(), Name: DeclarationName(), BasePath: nullptr);
6033 }
6034
6035 MarkFunctionReferenced(Loc: Location, Func: Dtor);
6036 DiagnoseUseOfDecl(D: Dtor, Locs: Location);
6037 }
6038}
6039
6040void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
6041 if (!CDtorDecl)
6042 return;
6043
6044 if (CXXConstructorDecl *Constructor
6045 = dyn_cast<CXXConstructorDecl>(Val: CDtorDecl)) {
6046 if (CXXRecordDecl *ClassDecl = Constructor->getParent();
6047 !ClassDecl || ClassDecl->isInvalidDecl()) {
6048 return;
6049 }
6050 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
6051 DiagnoseUninitializedFields(SemaRef&: *this, Constructor);
6052 }
6053}
6054
6055bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
6056 if (!getLangOpts().CPlusPlus)
6057 return false;
6058
6059 const auto *RD = Context.getBaseElementType(QT: T)->getAsCXXRecordDecl();
6060 if (!RD)
6061 return false;
6062
6063 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
6064 // class template specialization here, but doing so breaks a lot of code.
6065
6066 // We can't answer whether something is abstract until it has a
6067 // definition. If it's currently being defined, we'll walk back
6068 // over all the declarations when we have a full definition.
6069 const CXXRecordDecl *Def = RD->getDefinition();
6070 if (!Def || Def->isBeingDefined())
6071 return false;
6072
6073 return RD->isAbstract();
6074}
6075
6076bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
6077 TypeDiagnoser &Diagnoser) {
6078 if (!isAbstractType(Loc, T))
6079 return false;
6080
6081 T = Context.getBaseElementType(QT: T);
6082 Diagnoser.diagnose(S&: *this, Loc, T);
6083 DiagnoseAbstractType(RD: T->getAsCXXRecordDecl());
6084 return true;
6085}
6086
6087void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
6088 // Check if we've already emitted the list of pure virtual functions
6089 // for this class.
6090 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(Ptr: RD))
6091 return;
6092
6093 // If the diagnostic is suppressed, don't emit the notes. We're only
6094 // going to emit them once, so try to attach them to a diagnostic we're
6095 // actually going to show.
6096 if (Diags.isLastDiagnosticIgnored())
6097 return;
6098
6099 CXXFinalOverriderMap FinalOverriders;
6100 RD->getFinalOverriders(FinaOverriders&: FinalOverriders);
6101
6102 // Keep a set of seen pure methods so we won't diagnose the same method
6103 // more than once.
6104 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
6105
6106 for (const auto &M : FinalOverriders) {
6107 for (const auto &SO : M.second) {
6108 // C++ [class.abstract]p4:
6109 // A class is abstract if it contains or inherits at least one
6110 // pure virtual function for which the final overrider is pure
6111 // virtual.
6112
6113 if (SO.second.size() != 1)
6114 continue;
6115 const CXXMethodDecl *Method = SO.second.front().Method;
6116
6117 if (!Method->isPureVirtual())
6118 continue;
6119
6120 if (!SeenPureMethods.insert(Ptr: Method).second)
6121 continue;
6122
6123 Diag(Loc: Method->getLocation(), DiagID: diag::note_pure_virtual_function)
6124 << Method->getDeclName() << RD->getDeclName();
6125 }
6126 }
6127
6128 if (!PureVirtualClassDiagSet)
6129 PureVirtualClassDiagSet.reset(p: new RecordDeclSetTy);
6130 PureVirtualClassDiagSet->insert(Ptr: RD);
6131}
6132
6133namespace {
6134struct AbstractUsageInfo {
6135 Sema &S;
6136 CXXRecordDecl *Record;
6137 CanQualType AbstractType;
6138 bool Invalid;
6139
6140 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
6141 : S(S), Record(Record),
6142 AbstractType(S.Context.getCanonicalTagType(TD: Record)), Invalid(false) {}
6143
6144 void DiagnoseAbstractType() {
6145 if (Invalid) return;
6146 S.DiagnoseAbstractType(RD: Record);
6147 Invalid = true;
6148 }
6149
6150 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
6151};
6152
6153struct CheckAbstractUsage {
6154 AbstractUsageInfo &Info;
6155 const NamedDecl *Ctx;
6156
6157 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
6158 : Info(Info), Ctx(Ctx) {}
6159
6160 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
6161 switch (TL.getTypeLocClass()) {
6162#define ABSTRACT_TYPELOC(CLASS, PARENT)
6163#define TYPELOC(CLASS, PARENT) \
6164 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
6165#include "clang/AST/TypeLocNodes.def"
6166 }
6167 }
6168
6169 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6170 Visit(TL: TL.getReturnLoc(), Sel: Sema::AbstractReturnType);
6171 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
6172 if (!TL.getParam(i: I))
6173 continue;
6174
6175 TypeSourceInfo *TSI = TL.getParam(i: I)->getTypeSourceInfo();
6176 if (TSI) Visit(TL: TSI->getTypeLoc(), Sel: Sema::AbstractParamType);
6177 }
6178 }
6179
6180 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6181 Visit(TL: TL.getElementLoc(), Sel: Sema::AbstractArrayType);
6182 }
6183
6184 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6185 // Visit the type parameters from a permissive context.
6186 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
6187 TemplateArgumentLoc TAL = TL.getArgLoc(i: I);
6188 if (TAL.getArgument().getKind() == TemplateArgument::Type)
6189 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
6190 Visit(TL: TSI->getTypeLoc(), Sel: Sema::AbstractNone);
6191 // TODO: other template argument types?
6192 }
6193 }
6194
6195 // Visit pointee types from a permissive context.
6196#define CheckPolymorphic(Type) \
6197 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
6198 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
6199 }
6200 CheckPolymorphic(PointerTypeLoc)
6201 CheckPolymorphic(ReferenceTypeLoc)
6202 CheckPolymorphic(MemberPointerTypeLoc)
6203 CheckPolymorphic(BlockPointerTypeLoc)
6204 CheckPolymorphic(AtomicTypeLoc)
6205
6206 /// Handle all the types we haven't given a more specific
6207 /// implementation for above.
6208 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
6209 // Every other kind of type that we haven't called out already
6210 // that has an inner type is either (1) sugar or (2) contains that
6211 // inner type in some way as a subobject.
6212 if (TypeLoc Next = TL.getNextTypeLoc())
6213 return Visit(TL: Next, Sel);
6214
6215 // If there's no inner type and we're in a permissive context,
6216 // don't diagnose.
6217 if (Sel == Sema::AbstractNone) return;
6218
6219 // Check whether the type matches the abstract type.
6220 QualType T = TL.getType();
6221 if (T->isArrayType()) {
6222 Sel = Sema::AbstractArrayType;
6223 T = Info.S.Context.getBaseElementType(QT: T);
6224 }
6225 CanQualType CT = T->getCanonicalTypeUnqualified();
6226 if (CT != Info.AbstractType) return;
6227
6228 // It matched; do some magic.
6229 // FIXME: These should be at most warnings. See P0929R2, CWG1640, CWG1646.
6230 if (Sel == Sema::AbstractArrayType) {
6231 Info.S.Diag(Loc: Ctx->getLocation(), DiagID: diag::err_array_of_abstract_type)
6232 << T << TL.getSourceRange();
6233 } else {
6234 Info.S.Diag(Loc: Ctx->getLocation(), DiagID: diag::err_abstract_type_in_decl)
6235 << Sel << T << TL.getSourceRange();
6236 }
6237 Info.DiagnoseAbstractType();
6238 }
6239};
6240
6241void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
6242 Sema::AbstractDiagSelID Sel) {
6243 CheckAbstractUsage(*this, D).Visit(TL, Sel);
6244}
6245
6246}
6247
6248/// Check for invalid uses of an abstract type in a function declaration.
6249static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6250 FunctionDecl *FD) {
6251 // Only definitions are required to refer to complete and
6252 // non-abstract types.
6253 if (!FD->doesThisDeclarationHaveABody())
6254 return;
6255
6256 // For safety's sake, just ignore it if we don't have type source
6257 // information. This should never happen for non-implicit methods,
6258 // but...
6259 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6260 Info.CheckType(D: FD, TL: TSI->getTypeLoc(), Sel: Sema::AbstractNone);
6261}
6262
6263/// Check for invalid uses of an abstract type in a variable0 declaration.
6264static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6265 VarDecl *VD) {
6266 // No need to do the check on definitions, which require that
6267 // the type is complete.
6268 if (VD->isThisDeclarationADefinition())
6269 return;
6270
6271 Info.CheckType(D: VD, TL: VD->getTypeSourceInfo()->getTypeLoc(),
6272 Sel: Sema::AbstractVariableType);
6273}
6274
6275/// Check for invalid uses of an abstract type within a class definition.
6276static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6277 CXXRecordDecl *RD) {
6278 for (auto *D : RD->decls()) {
6279 if (D->isImplicit()) continue;
6280
6281 // Step through friends to the befriended declaration.
6282 if (auto *FD = dyn_cast<FriendDecl>(Val: D)) {
6283 D = FD->getFriendDecl();
6284 if (!D) continue;
6285 }
6286
6287 // Functions and function templates.
6288 if (auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
6289 CheckAbstractClassUsage(Info, FD);
6290 } else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Val: D)) {
6291 CheckAbstractClassUsage(Info, FD: FTD->getTemplatedDecl());
6292
6293 // Fields and static variables.
6294 } else if (auto *FD = dyn_cast<FieldDecl>(Val: D)) {
6295 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6296 Info.CheckType(D: FD, TL: TSI->getTypeLoc(), Sel: Sema::AbstractFieldType);
6297 } else if (auto *VD = dyn_cast<VarDecl>(Val: D)) {
6298 CheckAbstractClassUsage(Info, VD);
6299 } else if (auto *VTD = dyn_cast<VarTemplateDecl>(Val: D)) {
6300 CheckAbstractClassUsage(Info, VD: VTD->getTemplatedDecl());
6301
6302 // Nested classes and class templates.
6303 } else if (auto *RD = dyn_cast<CXXRecordDecl>(Val: D)) {
6304 CheckAbstractClassUsage(Info, RD);
6305 } else if (auto *CTD = dyn_cast<ClassTemplateDecl>(Val: D)) {
6306 CheckAbstractClassUsage(Info, RD: CTD->getTemplatedDecl());
6307 }
6308 }
6309}
6310
6311static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
6312 Attr *ClassAttr = getDLLAttr(D: Class);
6313 if (!ClassAttr)
6314 return;
6315
6316 assert(ClassAttr->getKind() == attr::DLLExport);
6317
6318 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6319
6320 if (TSK == TSK_ExplicitInstantiationDeclaration)
6321 // Don't go any further if this is just an explicit instantiation
6322 // declaration.
6323 return;
6324
6325 // Add a context note to explain how we got to any diagnostics produced below.
6326 struct MarkingClassDllexported {
6327 Sema &S;
6328 MarkingClassDllexported(Sema &S, CXXRecordDecl *Class,
6329 SourceLocation AttrLoc)
6330 : S(S) {
6331 Sema::CodeSynthesisContext Ctx;
6332 Ctx.Kind = Sema::CodeSynthesisContext::MarkingClassDllexported;
6333 Ctx.PointOfInstantiation = AttrLoc;
6334 Ctx.Entity = Class;
6335 S.pushCodeSynthesisContext(Ctx);
6336 }
6337 ~MarkingClassDllexported() {
6338 S.popCodeSynthesisContext();
6339 }
6340 } MarkingDllexportedContext(S, Class, ClassAttr->getLocation());
6341
6342 if (S.Context.getTargetInfo().getTriple().isOSCygMing())
6343 S.MarkVTableUsed(Loc: Class->getLocation(), Class, DefinitionRequired: true);
6344
6345 for (Decl *Member : Class->decls()) {
6346 // Skip members that were not marked exported.
6347 if (!Member->hasAttr<DLLExportAttr>())
6348 continue;
6349
6350 // Defined static variables that are members of an exported base
6351 // class must be marked export too.
6352 auto *VD = dyn_cast<VarDecl>(Val: Member);
6353 if (VD && VD->getStorageClass() == SC_Static &&
6354 TSK == TSK_ImplicitInstantiation)
6355 S.MarkVariableReferenced(Loc: VD->getLocation(), Var: VD);
6356
6357 auto *MD = dyn_cast<CXXMethodDecl>(Val: Member);
6358 if (!MD)
6359 continue;
6360
6361 if (MD->isUserProvided()) {
6362 // Instantiate non-default class member functions ...
6363
6364 // .. except for certain kinds of template specializations.
6365 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
6366 continue;
6367
6368 // If this is an MS ABI dllexport default constructor, instantiate any
6369 // default arguments.
6370 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
6371 auto *CD = dyn_cast<CXXConstructorDecl>(Val: MD);
6372 if (CD && CD->isDefaultConstructor() && TSK == TSK_Undeclared) {
6373 S.BuildCtorClosureDefaultArgs(
6374 Loc: CD->getAttr<DLLExportAttr>()->getLocation(), Ctor: CD);
6375 }
6376 }
6377
6378 S.MarkFunctionReferenced(Loc: Class->getLocation(), Func: MD);
6379
6380 // The function will be passed to the consumer when its definition is
6381 // encountered.
6382 } else if (MD->isExplicitlyDefaulted()) {
6383 // Synthesize and instantiate explicitly defaulted methods.
6384 S.MarkFunctionReferenced(Loc: Class->getLocation(), Func: MD);
6385
6386 if (TSK != TSK_ExplicitInstantiationDefinition) {
6387 // Except for explicit instantiation defs, we will not see the
6388 // definition again later, so pass it to the consumer now.
6389 S.Consumer.HandleTopLevelDecl(D: DeclGroupRef(MD));
6390 }
6391 } else if (!MD->isTrivial() ||
6392 MD->isCopyAssignmentOperator() ||
6393 MD->isMoveAssignmentOperator()) {
6394 // Synthesize and instantiate non-trivial implicit methods, and the copy
6395 // and move assignment operators. The latter are exported even if they
6396 // are trivial, because the address of an operator can be taken and
6397 // should compare equal across libraries.
6398 S.MarkFunctionReferenced(Loc: Class->getLocation(), Func: MD);
6399
6400 // There is no later point when we will see the definition of this
6401 // function, so pass it to the consumer now.
6402 S.Consumer.HandleTopLevelDecl(D: DeclGroupRef(MD));
6403 }
6404 }
6405}
6406
6407static void checkForMultipleExportedDefaultConstructors(Sema &S,
6408 CXXRecordDecl *Class) {
6409 // Only the MS ABI has default constructor closures, so we don't need to do
6410 // this semantic checking anywhere else.
6411 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
6412 return;
6413
6414 if (Class->isInvalidDecl())
6415 return;
6416
6417 CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
6418 for (Decl *Member : Class->decls()) {
6419 // Nested classes finish delayed default argument parsing with the outermost
6420 // class, so check each nested definition here.
6421 if (auto *NestedClass = dyn_cast<CXXRecordDecl>(Val: Member)) {
6422 if (NestedClass->isThisDeclarationADefinition())
6423 checkForMultipleExportedDefaultConstructors(S, Class: NestedClass);
6424 continue;
6425 }
6426
6427 // Look for exported default constructors.
6428 auto *CD = dyn_cast<CXXConstructorDecl>(Val: Member);
6429 if (!CD || !CD->isDefaultConstructor())
6430 continue;
6431 auto *Attr = CD->getAttr<DLLExportAttr>();
6432 if (!Attr)
6433 continue;
6434
6435 // If the class is non-dependent, mark the default arguments as ODR-used so
6436 // that we can properly codegen the constructor closure.
6437 if (!Class->isDependentContext()) {
6438 S.BuildCtorClosureDefaultArgs(Loc: Attr->getLocation(), Ctor: CD);
6439 S.DiscardCleanupsInEvaluationContext();
6440 }
6441
6442 if (LastExportedDefaultCtor) {
6443 S.Diag(Loc: LastExportedDefaultCtor->getLocation(),
6444 DiagID: diag::err_attribute_dll_ambiguous_default_ctor)
6445 << Class;
6446 S.Diag(Loc: CD->getLocation(), DiagID: diag::note_entity_declared_at)
6447 << CD->getDeclName();
6448 return;
6449 }
6450 LastExportedDefaultCtor = CD;
6451 }
6452}
6453
6454static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S,
6455 CXXRecordDecl *Class) {
6456 bool ErrorReported = false;
6457 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6458 ClassTemplateDecl *TD) {
6459 if (ErrorReported)
6460 return;
6461 S.Diag(Loc: TD->getLocation(),
6462 DiagID: diag::err_cuda_device_builtin_surftex_cls_template)
6463 << /*surface*/ 0 << TD;
6464 ErrorReported = true;
6465 };
6466
6467 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6468 if (!TD) {
6469 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Val: Class);
6470 if (!SD) {
6471 S.Diag(Loc: Class->getLocation(),
6472 DiagID: diag::err_cuda_device_builtin_surftex_ref_decl)
6473 << /*surface*/ 0 << Class;
6474 S.Diag(Loc: Class->getLocation(),
6475 DiagID: diag::note_cuda_device_builtin_surftex_should_be_template_class)
6476 << Class;
6477 return;
6478 }
6479 TD = SD->getSpecializedTemplate();
6480 }
6481
6482 TemplateParameterList *Params = TD->getTemplateParameters();
6483 unsigned N = Params->size();
6484
6485 if (N != 2) {
6486 reportIllegalClassTemplate(S, TD);
6487 S.Diag(Loc: TD->getLocation(),
6488 DiagID: diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6489 << TD << 2;
6490 }
6491 if (N > 0 && !isa<TemplateTypeParmDecl>(Val: Params->getParam(Idx: 0))) {
6492 reportIllegalClassTemplate(S, TD);
6493 S.Diag(Loc: TD->getLocation(),
6494 DiagID: diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6495 << TD << /*1st*/ 0 << /*type*/ 0;
6496 }
6497 if (N > 1) {
6498 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: Params->getParam(Idx: 1));
6499 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6500 reportIllegalClassTemplate(S, TD);
6501 S.Diag(Loc: TD->getLocation(),
6502 DiagID: diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6503 << TD << /*2nd*/ 1 << /*integer*/ 1;
6504 }
6505 }
6506}
6507
6508static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S,
6509 CXXRecordDecl *Class) {
6510 bool ErrorReported = false;
6511 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6512 ClassTemplateDecl *TD) {
6513 if (ErrorReported)
6514 return;
6515 S.Diag(Loc: TD->getLocation(),
6516 DiagID: diag::err_cuda_device_builtin_surftex_cls_template)
6517 << /*texture*/ 1 << TD;
6518 ErrorReported = true;
6519 };
6520
6521 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6522 if (!TD) {
6523 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Val: Class);
6524 if (!SD) {
6525 S.Diag(Loc: Class->getLocation(),
6526 DiagID: diag::err_cuda_device_builtin_surftex_ref_decl)
6527 << /*texture*/ 1 << Class;
6528 S.Diag(Loc: Class->getLocation(),
6529 DiagID: diag::note_cuda_device_builtin_surftex_should_be_template_class)
6530 << Class;
6531 return;
6532 }
6533 TD = SD->getSpecializedTemplate();
6534 }
6535
6536 TemplateParameterList *Params = TD->getTemplateParameters();
6537 unsigned N = Params->size();
6538
6539 if (N != 3) {
6540 reportIllegalClassTemplate(S, TD);
6541 S.Diag(Loc: TD->getLocation(),
6542 DiagID: diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6543 << TD << 3;
6544 }
6545 if (N > 0 && !isa<TemplateTypeParmDecl>(Val: Params->getParam(Idx: 0))) {
6546 reportIllegalClassTemplate(S, TD);
6547 S.Diag(Loc: TD->getLocation(),
6548 DiagID: diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6549 << TD << /*1st*/ 0 << /*type*/ 0;
6550 }
6551 if (N > 1) {
6552 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: Params->getParam(Idx: 1));
6553 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6554 reportIllegalClassTemplate(S, TD);
6555 S.Diag(Loc: TD->getLocation(),
6556 DiagID: diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6557 << TD << /*2nd*/ 1 << /*integer*/ 1;
6558 }
6559 }
6560 if (N > 2) {
6561 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: Params->getParam(Idx: 2));
6562 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6563 reportIllegalClassTemplate(S, TD);
6564 S.Diag(Loc: TD->getLocation(),
6565 DiagID: diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6566 << TD << /*3rd*/ 2 << /*integer*/ 1;
6567 }
6568 }
6569}
6570
6571void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
6572 // Mark any compiler-generated routines with the implicit code_seg attribute.
6573 for (auto *Method : Class->methods()) {
6574 if (Method->isUserProvided())
6575 continue;
6576 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(FD: Method, /*IsDefinition=*/true))
6577 Method->addAttr(A);
6578 }
6579}
6580
6581void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
6582 Attr *ClassAttr = getDLLAttr(D: Class);
6583
6584 // MSVC inherits DLL attributes to partial class template specializations.
6585 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) {
6586 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Val: Class)) {
6587 if (Attr *TemplateAttr =
6588 getDLLAttr(D: Spec->getSpecializedTemplate()->getTemplatedDecl())) {
6589 auto *A = cast<InheritableAttr>(Val: TemplateAttr->clone(C&: getASTContext()));
6590 A->setInherited(true);
6591 ClassAttr = A;
6592 }
6593 }
6594 }
6595
6596 if (!ClassAttr)
6597 return;
6598
6599 // MSVC allows imported or exported template classes that have UniqueExternal
6600 // linkage. This occurs when the template class has been instantiated with
6601 // a template parameter which itself has internal linkage.
6602 // We drop the attribute to avoid exporting or importing any members.
6603 if ((Context.getTargetInfo().getCXXABI().isMicrosoft() ||
6604 Context.getTargetInfo().getTriple().isPS()) &&
6605 (!Class->isExternallyVisible() && Class->hasExternalFormalLinkage())) {
6606 Class->dropAttrs<DLLExportAttr, DLLImportAttr>();
6607 return;
6608 }
6609
6610 if (!Class->isExternallyVisible()) {
6611 Diag(Loc: Class->getLocation(), DiagID: diag::err_attribute_dll_not_extern)
6612 << Class << ClassAttr;
6613 return;
6614 }
6615
6616 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6617 !ClassAttr->isInherited()) {
6618 // Diagnose dll attributes on members of class with dll attribute.
6619 for (Decl *Member : Class->decls()) {
6620 if (!isa<VarDecl>(Val: Member) && !isa<CXXMethodDecl>(Val: Member))
6621 continue;
6622 InheritableAttr *MemberAttr = getDLLAttr(D: Member);
6623 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
6624 continue;
6625
6626 Diag(Loc: MemberAttr->getLocation(),
6627 DiagID: diag::err_attribute_dll_member_of_dll_class)
6628 << MemberAttr << ClassAttr;
6629 Diag(Loc: ClassAttr->getLocation(), DiagID: diag::note_previous_attribute);
6630 Member->setInvalidDecl();
6631 }
6632 }
6633
6634 if (Class->getDescribedClassTemplate())
6635 // Don't inherit dll attribute until the template is instantiated.
6636 return;
6637
6638 // The class is either imported or exported.
6639 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
6640
6641 // Check if this was a dllimport attribute propagated from a derived class to
6642 // a base class template specialization. We don't apply these attributes to
6643 // static data members.
6644 const bool PropagatedImport =
6645 !ClassExported &&
6646 cast<DLLImportAttr>(Val: ClassAttr)->wasPropagatedToBaseTemplate();
6647
6648 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6649
6650 // Ignore explicit dllexport on explicit class template instantiation
6651 // declarations, except in MinGW mode.
6652 if (ClassExported && !ClassAttr->isInherited() &&
6653 TSK == TSK_ExplicitInstantiationDeclaration &&
6654 !Context.getTargetInfo().getTriple().isOSCygMing()) {
6655 if (auto *DEA = Class->getAttr<DLLExportAttr>()) {
6656 Class->addAttr(A: DLLExportOnDeclAttr::Create(Ctx&: Context, Range: DEA->getLoc()));
6657 Class->dropAttr<DLLExportAttr>();
6658 }
6659 return;
6660 }
6661
6662 // Force declaration of implicit members so they can inherit the attribute.
6663 ForceDeclarationOfImplicitMembers(Class);
6664
6665 // Inherited constructors are created lazily; force their creation now so the
6666 // loop below can propagate the DLL attribute to them.
6667 if (ClassExported && getLangOpts().DllExportInlines) {
6668 SmallVector<ConstructorUsingShadowDecl *, 4> Shadows;
6669 for (Decl *D : Class->decls())
6670 if (auto *S = dyn_cast<ConstructorUsingShadowDecl>(Val: D))
6671 Shadows.push_back(Elt: S);
6672 for (ConstructorUsingShadowDecl *S : Shadows) {
6673 CXXConstructorDecl *BC = dyn_cast<CXXConstructorDecl>(Val: S->getTargetDecl());
6674 if (!BC || BC->isDeleted())
6675 continue;
6676 // Skip constructors whose requires clause is not satisfied.
6677 // Normally overload resolution filters these, but we are bypassing
6678 // it to eagerly create inherited constructors for dllexport.
6679 if (BC->getTrailingRequiresClause()) {
6680 ConstraintSatisfaction Satisfaction;
6681 if (CheckFunctionConstraints(FD: BC, Satisfaction) ||
6682 !Satisfaction.IsSatisfied)
6683 continue;
6684 }
6685 findInheritingConstructor(Loc: Class->getLocation(), BaseCtor: BC, DerivedShadow: S);
6686 }
6687 }
6688
6689 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
6690 // seem to be true in practice?
6691
6692 for (Decl *Member : Class->decls()) {
6693 if (Member->hasAttr<ExcludeFromExplicitInstantiationAttr>())
6694 continue;
6695
6696 VarDecl *VD = dyn_cast<VarDecl>(Val: Member);
6697 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: Member);
6698
6699 // Only methods and static fields inherit the attributes.
6700 if (!VD && !MD)
6701 continue;
6702
6703 if (MD) {
6704 // Don't process deleted methods.
6705 if (MD->isDeleted())
6706 continue;
6707
6708 if (ClassExported && getLangOpts().DllExportInlines) {
6709 CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Val: MD);
6710 if (CD && CD->getInheritedConstructor()) {
6711 // Inherited constructors already had their base constructor's
6712 // constraints checked before creation via
6713 // findInheritingConstructor, so only ABI-compatibility checks
6714 // are needed here.
6715 //
6716 // Don't export inherited constructors whose parameters prevent
6717 // ABI-compatible forwarding. When canEmitDelegateCallArgs (in
6718 // CodeGen) returns false, Clang inlines the constructor body
6719 // instead of emitting a forwarding thunk, producing code that
6720 // is not ABI-compatible with MSVC. Suppress the export and warn
6721 // so the user gets a linker error rather than a silent runtime
6722 // mismatch.
6723 if (CD->isVariadic()) {
6724 Diag(Loc: CD->getLocation(),
6725 DiagID: diag::warn_dllexport_inherited_ctor_unsupported)
6726 << /*variadic=*/0;
6727 continue;
6728 }
6729 if (Context.getTargetInfo()
6730 .getCXXABI()
6731 .areArgsDestroyedLeftToRightInCallee()) {
6732 bool HasCalleeCleanupParam = false;
6733 for (const ParmVarDecl *P : CD->parameters())
6734 if (P->needsDestruction(Ctx: Context)) {
6735 HasCalleeCleanupParam = true;
6736 break;
6737 }
6738 if (HasCalleeCleanupParam) {
6739 Diag(Loc: CD->getLocation(),
6740 DiagID: diag::warn_dllexport_inherited_ctor_unsupported)
6741 << /*callee-cleanup=*/1;
6742 continue;
6743 }
6744 }
6745 } else if (MD->getTrailingRequiresClause()) {
6746 // Don't export methods whose requires clause is not satisfied.
6747 // For class template specializations, member constraints may
6748 // depend on template arguments and an unsatisfied constraint
6749 // means the member should not be available in this
6750 // specialization.
6751 ConstraintSatisfaction Satisfaction;
6752 if (CheckFunctionConstraints(FD: MD, Satisfaction) ||
6753 !Satisfaction.IsSatisfied)
6754 continue;
6755 }
6756 }
6757
6758 if (MD->isInlined()) {
6759 // MinGW does not import or export inline methods. But do it for
6760 // template instantiations and inherited constructors (which are
6761 // marked inline but must be exported to match MSVC behavior).
6762 if (!Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6763 TSK != TSK_ExplicitInstantiationDeclaration &&
6764 TSK != TSK_ExplicitInstantiationDefinition) {
6765 if (auto *CD = dyn_cast<CXXConstructorDecl>(Val: MD);
6766 !CD || !CD->getInheritedConstructor())
6767 continue;
6768 }
6769
6770 // MSVC versions before 2015 don't export the move assignment operators
6771 // and move constructor, so don't attempt to import/export them if
6772 // we have a definition.
6773 auto *Ctor = dyn_cast<CXXConstructorDecl>(Val: MD);
6774 if ((MD->isMoveAssignmentOperator() ||
6775 (Ctor && Ctor->isMoveConstructor())) &&
6776 getLangOpts().isCompatibleWithMSVC() &&
6777 !getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015))
6778 continue;
6779
6780 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
6781 // operator is exported anyway.
6782 if (getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015) &&
6783 (Ctor || isa<CXXDestructorDecl>(Val: MD)) && MD->isTrivial())
6784 continue;
6785 }
6786 }
6787
6788 // Don't apply dllimport attributes to static data members of class template
6789 // instantiations when the attribute is propagated from a derived class.
6790 if (VD && PropagatedImport)
6791 continue;
6792
6793 if (!cast<NamedDecl>(Val: Member)->isExternallyVisible())
6794 continue;
6795
6796 if (!getDLLAttr(D: Member)) {
6797 InheritableAttr *NewAttr = nullptr;
6798
6799 // Do not export/import inline function when -fno-dllexport-inlines is
6800 // passed. But add attribute for later local static var check.
6801 if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
6802 TSK != TSK_ExplicitInstantiationDeclaration &&
6803 TSK != TSK_ExplicitInstantiationDefinition) {
6804 if (ClassExported) {
6805 NewAttr = ::new (getASTContext())
6806 DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);
6807 } else {
6808 NewAttr = ::new (getASTContext())
6809 DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);
6810 }
6811 } else {
6812 NewAttr = cast<InheritableAttr>(Val: ClassAttr->clone(C&: getASTContext()));
6813 }
6814
6815 NewAttr->setInherited(true);
6816 Member->addAttr(A: NewAttr);
6817
6818 if (MD) {
6819 // Propagate DLLAttr to friend re-declarations of MD that have already
6820 // been constructed.
6821 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
6822 FD = FD->getPreviousDecl()) {
6823 if (FD->getFriendObjectKind() == Decl::FOK_None)
6824 continue;
6825 assert(!getDLLAttr(FD) &&
6826 "friend re-decl should not already have a DLLAttr");
6827 NewAttr = cast<InheritableAttr>(Val: ClassAttr->clone(C&: getASTContext()));
6828 NewAttr->setInherited(true);
6829 FD->addAttr(A: NewAttr);
6830 }
6831 }
6832 }
6833 }
6834
6835 if (ClassExported)
6836 DelayedDllExportClasses.push_back(Elt: Class);
6837}
6838
6839void Sema::propagateDLLAttrToBaseClassTemplate(
6840 CXXRecordDecl *Class, Attr *ClassAttr,
6841 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
6842 if (getDLLAttr(
6843 D: BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
6844 // If the base class template has a DLL attribute, don't try to change it.
6845 return;
6846 }
6847
6848 auto TSK = BaseTemplateSpec->getSpecializationKind();
6849 if (!getDLLAttr(D: BaseTemplateSpec) &&
6850 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
6851 TSK == TSK_ImplicitInstantiation)) {
6852 // The template hasn't been instantiated yet (or it has, but only as an
6853 // explicit instantiation declaration or implicit instantiation, which means
6854 // we haven't codegenned any members yet), so propagate the attribute.
6855 auto *NewAttr = cast<InheritableAttr>(Val: ClassAttr->clone(C&: getASTContext()));
6856 NewAttr->setInherited(true);
6857 BaseTemplateSpec->addAttr(A: NewAttr);
6858
6859 // If this was an import, mark that we propagated it from a derived class to
6860 // a base class template specialization.
6861 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(Val: NewAttr))
6862 ImportAttr->setPropagatedToBaseTemplate();
6863
6864 // If the template is already instantiated, checkDLLAttributeRedeclaration()
6865 // needs to be run again to work see the new attribute. Otherwise this will
6866 // get run whenever the template is instantiated.
6867 if (TSK != TSK_Undeclared)
6868 checkClassLevelDLLAttribute(Class: BaseTemplateSpec);
6869
6870 return;
6871 }
6872
6873 if (getDLLAttr(D: BaseTemplateSpec)) {
6874 // The template has already been specialized or instantiated with an
6875 // attribute, explicitly or through propagation. We should not try to change
6876 // it.
6877 return;
6878 }
6879
6880 // The template was previously instantiated or explicitly specialized without
6881 // a dll attribute, It's too late for us to add an attribute, so warn that
6882 // this is unsupported.
6883 Diag(Loc: BaseLoc, DiagID: diag::warn_attribute_dll_instantiated_base_class)
6884 << BaseTemplateSpec->isExplicitSpecialization();
6885 Diag(Loc: ClassAttr->getLocation(), DiagID: diag::note_attribute);
6886 if (BaseTemplateSpec->isExplicitSpecialization()) {
6887 Diag(Loc: BaseTemplateSpec->getLocation(),
6888 DiagID: diag::note_template_class_explicit_specialization_was_here)
6889 << BaseTemplateSpec;
6890 } else {
6891 Diag(Loc: BaseTemplateSpec->getPointOfInstantiation(),
6892 DiagID: diag::note_template_class_instantiation_was_here)
6893 << BaseTemplateSpec;
6894 }
6895}
6896
6897namespace {
6898/// RAII object to restore the floating-point (FP) features active at the time
6899/// a defaulted function was declared. This ensures that the synthesized body
6900/// of the function respects the FP pragmas (e.g., #pragma STDC FENV_ACCESS)
6901/// that were in effect when the function was explicitly defaulted.
6902struct DefaultedFunctionFPFeaturesRAII {
6903 Sema::FPFeaturesStateRAII SavedFPFeatures;
6904 DefaultedFunctionFPFeaturesRAII(Sema &S, FunctionDecl *FD)
6905 : SavedFPFeatures(S) {
6906 auto *Info = FD->getDefaultedOrDeletedInfo();
6907 FPOptionsOverride FPO = Info ? Info->getFPFeatures() : FPOptionsOverride();
6908 S.CurFPFeatures = FPO.applyOverrides(LO: S.LangOpts);
6909 S.FpPragmaStack.CurrentValue = FPO;
6910 }
6911
6912 ~DefaultedFunctionFPFeaturesRAII() = default;
6913};
6914} // namespace
6915
6916static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD,
6917 SourceLocation DefaultLoc) {
6918 FunctionDecl::DefaultedFunctionKind DFK = FD->getDefaultedFunctionKind();
6919 if (DFK.isComparison())
6920 return S.DefineDefaultedComparison(Loc: DefaultLoc, FD, DCK: DFK.asComparison());
6921
6922 switch (DFK.asSpecialMember()) {
6923 case CXXSpecialMemberKind::DefaultConstructor:
6924 S.DefineImplicitDefaultConstructor(CurrentLocation: DefaultLoc,
6925 Constructor: cast<CXXConstructorDecl>(Val: FD));
6926 break;
6927 case CXXSpecialMemberKind::CopyConstructor:
6928 S.DefineImplicitCopyConstructor(CurrentLocation: DefaultLoc, Constructor: cast<CXXConstructorDecl>(Val: FD));
6929 break;
6930 case CXXSpecialMemberKind::CopyAssignment:
6931 S.DefineImplicitCopyAssignment(CurrentLocation: DefaultLoc, MethodDecl: cast<CXXMethodDecl>(Val: FD));
6932 break;
6933 case CXXSpecialMemberKind::Destructor:
6934 S.DefineImplicitDestructor(CurrentLocation: DefaultLoc, Destructor: cast<CXXDestructorDecl>(Val: FD));
6935 break;
6936 case CXXSpecialMemberKind::MoveConstructor:
6937 S.DefineImplicitMoveConstructor(CurrentLocation: DefaultLoc, Constructor: cast<CXXConstructorDecl>(Val: FD));
6938 break;
6939 case CXXSpecialMemberKind::MoveAssignment:
6940 S.DefineImplicitMoveAssignment(CurrentLocation: DefaultLoc, MethodDecl: cast<CXXMethodDecl>(Val: FD));
6941 break;
6942 case CXXSpecialMemberKind::Invalid:
6943 llvm_unreachable("Invalid special member.");
6944 }
6945}
6946
6947/// Determine whether a type is permitted to be passed or returned in
6948/// registers, per C++ [class.temporary]p3.
6949static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
6950 TargetInfo::CallingConvKind CCK) {
6951 if (D->isDependentType() || D->isInvalidDecl())
6952 return false;
6953
6954 // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
6955 // The PS4 platform ABI follows the behavior of Clang 3.2.
6956 if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
6957 return !D->hasNonTrivialDestructorForCall() &&
6958 !D->hasNonTrivialCopyConstructorForCall();
6959
6960 if (CCK == TargetInfo::CCK_MicrosoftWin64) {
6961 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
6962 bool DtorIsTrivialForCall = false;
6963
6964 // If a class has at least one eligible, trivial copy constructor, it
6965 // is passed according to the C ABI. Otherwise, it is passed indirectly.
6966 //
6967 // Note: This permits classes with non-trivial copy or move ctors to be
6968 // passed in registers, so long as they *also* have a trivial copy ctor,
6969 // which is non-conforming.
6970 if (D->needsImplicitCopyConstructor()) {
6971 if (!D->defaultedCopyConstructorIsDeleted()) {
6972 if (D->hasTrivialCopyConstructor())
6973 CopyCtorIsTrivial = true;
6974 if (D->hasTrivialCopyConstructorForCall())
6975 CopyCtorIsTrivialForCall = true;
6976 }
6977 } else {
6978 for (const CXXConstructorDecl *CD : D->ctors()) {
6979 if (CD->isCopyConstructor() && !CD->isDeleted() &&
6980 !CD->isIneligibleOrNotSelected()) {
6981 if (CD->isTrivial())
6982 CopyCtorIsTrivial = true;
6983 if (CD->isTrivialForCall())
6984 CopyCtorIsTrivialForCall = true;
6985 }
6986 }
6987 }
6988
6989 if (D->needsImplicitDestructor()) {
6990 if (!D->defaultedDestructorIsDeleted() &&
6991 D->hasTrivialDestructorForCall())
6992 DtorIsTrivialForCall = true;
6993 } else if (const auto *DD = D->getDestructor()) {
6994 if (!DD->isDeleted() && DD->isTrivialForCall())
6995 DtorIsTrivialForCall = true;
6996 }
6997
6998 // If the copy ctor and dtor are both trivial-for-calls, pass direct.
6999 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
7000 return true;
7001
7002 // If a class has a destructor, we'd really like to pass it indirectly
7003 // because it allows us to elide copies. Unfortunately, MSVC makes that
7004 // impossible for small types, which it will pass in a single register or
7005 // stack slot. Most objects with dtors are large-ish, so handle that early.
7006 // We can't call out all large objects as being indirect because there are
7007 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
7008 // how we pass large POD types.
7009
7010 // Note: This permits small classes with nontrivial destructors to be
7011 // passed in registers, which is non-conforming.
7012 bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
7013 uint64_t TypeSize = isAArch64 ? 128 : 64;
7014
7015 if (CopyCtorIsTrivial && S.getASTContext().getTypeSize(
7016 T: S.Context.getCanonicalTagType(TD: D)) <= TypeSize)
7017 return true;
7018 return false;
7019 }
7020
7021 // Per C++ [class.temporary]p3, the relevant condition is:
7022 // each copy constructor, move constructor, and destructor of X is
7023 // either trivial or deleted, and X has at least one non-deleted copy
7024 // or move constructor
7025 bool HasNonDeletedCopyOrMove = false;
7026
7027 if (D->needsImplicitCopyConstructor() &&
7028 !D->defaultedCopyConstructorIsDeleted()) {
7029 if (!D->hasTrivialCopyConstructorForCall())
7030 return false;
7031 HasNonDeletedCopyOrMove = true;
7032 }
7033
7034 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
7035 !D->defaultedMoveConstructorIsDeleted()) {
7036 if (!D->hasTrivialMoveConstructorForCall())
7037 return false;
7038 HasNonDeletedCopyOrMove = true;
7039 }
7040
7041 if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
7042 !D->hasTrivialDestructorForCall())
7043 return false;
7044
7045 for (const CXXMethodDecl *MD : D->methods()) {
7046 if (MD->isDeleted() || MD->isIneligibleOrNotSelected())
7047 continue;
7048
7049 auto *CD = dyn_cast<CXXConstructorDecl>(Val: MD);
7050 if (CD && CD->isCopyOrMoveConstructor())
7051 HasNonDeletedCopyOrMove = true;
7052 else if (!isa<CXXDestructorDecl>(Val: MD))
7053 continue;
7054
7055 if (!MD->isTrivialForCall())
7056 return false;
7057 }
7058
7059 return HasNonDeletedCopyOrMove;
7060}
7061
7062/// Report an error regarding overriding, along with any relevant
7063/// overridden methods.
7064///
7065/// \param DiagID the primary error to report.
7066/// \param MD the overriding method.
7067static bool
7068ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD,
7069 llvm::function_ref<bool(const CXXMethodDecl *)> Report) {
7070 bool IssuedDiagnostic = false;
7071 for (const CXXMethodDecl *O : MD->overridden_methods()) {
7072 if (Report(O)) {
7073 if (!IssuedDiagnostic) {
7074 S.Diag(Loc: MD->getLocation(), DiagID) << MD->getDeclName();
7075 IssuedDiagnostic = true;
7076 }
7077 S.Diag(Loc: O->getLocation(), DiagID: diag::note_overridden_virtual_function);
7078 }
7079 }
7080 return IssuedDiagnostic;
7081}
7082
7083void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) {
7084 if (!Record)
7085 return;
7086
7087 if (Record->isAbstract() && !Record->isInvalidDecl()) {
7088 AbstractUsageInfo Info(*this, Record);
7089 CheckAbstractClassUsage(Info, RD: Record);
7090 }
7091
7092 // If this is not an aggregate type and has no user-declared constructor,
7093 // complain about any non-static data members of reference or const scalar
7094 // type, since they will never get initializers.
7095 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
7096 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
7097 !Record->isLambda()) {
7098 bool Complained = false;
7099 for (const auto *F : Record->fields()) {
7100 if (F->hasInClassInitializer() || F->isUnnamedBitField())
7101 continue;
7102
7103 if (F->getType()->isReferenceType() ||
7104 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
7105 if (!Complained) {
7106 Diag(Loc: Record->getLocation(), DiagID: diag::warn_no_constructor_for_refconst)
7107 << Record->getTagKind() << Record;
7108 Complained = true;
7109 }
7110
7111 Diag(Loc: F->getLocation(), DiagID: diag::note_refconst_member_not_initialized)
7112 << F->getType()->isReferenceType()
7113 << F->getDeclName();
7114 }
7115 }
7116 }
7117
7118 if (Record->getIdentifier()) {
7119 // C++ [class.mem]p13:
7120 // If T is the name of a class, then each of the following shall have a
7121 // name different from T:
7122 // - every member of every anonymous union that is a member of class T.
7123 //
7124 // C++ [class.mem]p14:
7125 // In addition, if class T has a user-declared constructor (12.1), every
7126 // non-static data member of class T shall have a name different from T.
7127 for (const NamedDecl *Element : Record->lookup(Name: Record->getDeclName())) {
7128 const NamedDecl *D = Element->getUnderlyingDecl();
7129 // Invalid IndirectFieldDecls have already been diagnosed with
7130 // err_anonymous_record_member_redecl in
7131 // SemaDecl.cpp:CheckAnonMemberRedeclaration.
7132 if (((isa<FieldDecl>(Val: D) || isa<UnresolvedUsingValueDecl>(Val: D)) &&
7133 Record->hasUserDeclaredConstructor()) ||
7134 (isa<IndirectFieldDecl>(Val: D) && !D->isInvalidDecl())) {
7135 Diag(Loc: Element->getLocation(), DiagID: diag::err_member_name_of_class)
7136 << D->getDeclName();
7137 break;
7138 }
7139 }
7140 }
7141
7142 // Warn if the class has virtual methods but non-virtual public destructor.
7143 if (Record->isPolymorphic() && !Record->isDependentType()) {
7144 CXXDestructorDecl *dtor = Record->getDestructor();
7145 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
7146 !Record->hasAttr<FinalAttr>())
7147 Diag(Loc: dtor ? dtor->getLocation() : Record->getLocation(),
7148 DiagID: diag::warn_non_virtual_dtor)
7149 << Context.getCanonicalTagType(TD: Record);
7150 }
7151
7152 if (Record->isAbstract()) {
7153 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
7154 Diag(Loc: Record->getLocation(), DiagID: diag::warn_abstract_final_class)
7155 << FA->isSpelledAsSealed();
7156 DiagnoseAbstractType(RD: Record);
7157 }
7158 }
7159
7160 // Warn if the class has a final destructor but is not itself marked final.
7161 if (!Record->hasAttr<FinalAttr>()) {
7162 if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
7163 if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
7164 Diag(Loc: FA->getLocation(), DiagID: diag::warn_final_dtor_non_final_class)
7165 << FA->isSpelledAsSealed()
7166 << FixItHint::CreateInsertion(
7167 InsertionLoc: getLocForEndOfToken(Loc: Record->getLocation()),
7168 Code: (FA->isSpelledAsSealed() ? " sealed" : " final"));
7169 Diag(Loc: Record->getLocation(),
7170 DiagID: diag::note_final_dtor_non_final_class_silence)
7171 << Context.getCanonicalTagType(TD: Record) << FA->isSpelledAsSealed();
7172 }
7173 }
7174 }
7175
7176 // See if trivial_abi has to be dropped.
7177 if (Record->hasAttr<TrivialABIAttr>())
7178 checkIllFormedTrivialABIStruct(RD&: *Record);
7179
7180 // Set HasTrivialSpecialMemberForCall if the record has attribute
7181 // "trivial_abi".
7182 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
7183
7184 if (HasTrivialABI)
7185 Record->setHasTrivialSpecialMemberForCall();
7186
7187 // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=).
7188 // We check these last because they can depend on the properties of the
7189 // primary comparison functions (==, <=>).
7190 llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons;
7191
7192 // Perform checks that can't be done until we know all the properties of a
7193 // member function (whether it's defaulted, deleted, virtual, overriding,
7194 // ...).
7195 auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) {
7196 // A static function cannot override anything.
7197 if (MD->getStorageClass() == SC_Static) {
7198 if (ReportOverrides(S&: *this, DiagID: diag::err_static_overrides_virtual, MD,
7199 Report: [](const CXXMethodDecl *) { return true; }))
7200 return;
7201 }
7202
7203 // A deleted function cannot override a non-deleted function and vice
7204 // versa.
7205 if (ReportOverrides(S&: *this,
7206 DiagID: MD->isDeleted() ? diag::err_deleted_override
7207 : diag::err_non_deleted_override,
7208 MD, Report: [&](const CXXMethodDecl *V) {
7209 return MD->isDeleted() != V->isDeleted();
7210 })) {
7211 if (MD->isDefaulted() && MD->isDeleted())
7212 // Explain why this defaulted function was deleted.
7213 DiagnoseDeletedDefaultedFunction(FD: MD);
7214 return;
7215 }
7216
7217 // A consteval function cannot override a non-consteval function and vice
7218 // versa.
7219 if (ReportOverrides(S&: *this,
7220 DiagID: MD->isConsteval() ? diag::err_consteval_override
7221 : diag::err_non_consteval_override,
7222 MD, Report: [&](const CXXMethodDecl *V) {
7223 return MD->isConsteval() != V->isConsteval();
7224 })) {
7225 if (MD->isDefaulted() && MD->isDeleted())
7226 // Explain why this defaulted function was deleted.
7227 DiagnoseDeletedDefaultedFunction(FD: MD);
7228 return;
7229 }
7230 };
7231
7232 auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool {
7233 if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted())
7234 return false;
7235
7236 FunctionDecl::DefaultedFunctionKind DFK = FD->getDefaultedFunctionKind();
7237 if (DFK.asComparison() == DefaultedComparisonKind::NotEqual ||
7238 DFK.asComparison() == DefaultedComparisonKind::Relational) {
7239 DefaultedSecondaryComparisons.push_back(Elt: FD);
7240 return true;
7241 }
7242
7243 CheckExplicitlyDefaultedFunction(S, MD: FD);
7244 return false;
7245 };
7246
7247 if (!Record->isInvalidDecl() &&
7248 Record->hasAttr<VTablePointerAuthenticationAttr>())
7249 checkIncorrectVTablePointerAuthenticationAttribute(RD&: *Record);
7250
7251 auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
7252 // Check whether the explicitly-defaulted members are valid.
7253 bool Incomplete = CheckForDefaultedFunction(M);
7254
7255 // Skip the rest of the checks for a member of a dependent class.
7256 if (Record->isDependentType())
7257 return;
7258
7259 // For an explicitly defaulted or deleted special member, we defer
7260 // determining triviality until the class is complete. That time is now!
7261 CXXSpecialMemberKind CSM = M->getSpecialMemberKind();
7262 if (!M->isImplicit() && !M->isUserProvided()) {
7263 if (CSM != CXXSpecialMemberKind::Invalid) {
7264 M->setTrivial(SpecialMemberIsTrivial(MD: M, CSM));
7265 // Inform the class that we've finished declaring this member.
7266 Record->finishedDefaultedOrDeletedMember(MD: M);
7267 M->setTrivialForCall(
7268 HasTrivialABI ||
7269 SpecialMemberIsTrivial(MD: M, CSM,
7270 TAH: TrivialABIHandling::ConsiderTrivialABI));
7271 Record->setTrivialForCallFlags(M);
7272 }
7273 }
7274
7275 // Set triviality for the purpose of calls if this is a user-provided
7276 // copy/move constructor or destructor.
7277 if ((CSM == CXXSpecialMemberKind::CopyConstructor ||
7278 CSM == CXXSpecialMemberKind::MoveConstructor ||
7279 CSM == CXXSpecialMemberKind::Destructor) &&
7280 M->isUserProvided()) {
7281 M->setTrivialForCall(HasTrivialABI);
7282 Record->setTrivialForCallFlags(M);
7283 }
7284
7285 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
7286 M->hasAttr<DLLExportAttr>()) {
7287 if (getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015) &&
7288 M->isTrivial() &&
7289 (CSM == CXXSpecialMemberKind::DefaultConstructor ||
7290 CSM == CXXSpecialMemberKind::CopyConstructor ||
7291 CSM == CXXSpecialMemberKind::Destructor))
7292 M->dropAttr<DLLExportAttr>();
7293
7294 if (M->hasAttr<DLLExportAttr>()) {
7295 // Define after any fields with in-class initializers have been parsed.
7296 DelayedDllExportMemberFunctions.push_back(Elt: M);
7297 }
7298 }
7299
7300 bool EffectivelyConstexprDestructor = true;
7301 // Avoid triggering vtable instantiation due to a dtor that is not
7302 // "effectively constexpr" for better compatibility.
7303 // See https://github.com/llvm/llvm-project/issues/102293 for more info.
7304 if (isa<CXXDestructorDecl>(Val: M)) {
7305 llvm::SmallDenseSet<QualType> Visited;
7306 auto Check = [&Visited](QualType T, auto &&Check) -> bool {
7307 if (!Visited.insert(V: T->getCanonicalTypeUnqualified()).second)
7308 return false;
7309 const CXXRecordDecl *RD =
7310 T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
7311 if (!RD || !RD->isCompleteDefinition())
7312 return true;
7313
7314 if (!RD->hasConstexprDestructor())
7315 return false;
7316
7317 for (const CXXBaseSpecifier &B : RD->bases())
7318 if (!Check(B.getType(), Check))
7319 return false;
7320 for (const FieldDecl *FD : RD->fields())
7321 if (!Check(FD->getType(), Check))
7322 return false;
7323 return true;
7324 };
7325 EffectivelyConstexprDestructor =
7326 Check(Context.getCanonicalTagType(TD: Record), Check);
7327 }
7328
7329 // Define defaulted constexpr virtual functions that override a base class
7330 // function right away.
7331 // FIXME: We can defer doing this until the vtable is marked as used.
7332 if (CSM != CXXSpecialMemberKind::Invalid && !M->isDeleted() &&
7333 M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods() &&
7334 EffectivelyConstexprDestructor)
7335 DefineDefaultedFunction(S&: *this, FD: M, DefaultLoc: M->getLocation());
7336
7337 if (!Incomplete)
7338 CheckCompletedMemberFunction(M);
7339 };
7340
7341 // Check the destructor before any other member function. We need to
7342 // determine whether it's trivial in order to determine whether the claas
7343 // type is a literal type, which is a prerequisite for determining whether
7344 // other special member functions are valid and whether they're implicitly
7345 // 'constexpr'.
7346 if (CXXDestructorDecl *Dtor = Record->getDestructor())
7347 CompleteMemberFunction(Dtor);
7348
7349 bool HasMethodWithOverrideControl = false,
7350 HasOverridingMethodWithoutOverrideControl = false;
7351 for (auto *D : Record->decls()) {
7352 if (auto *M = dyn_cast<CXXMethodDecl>(Val: D)) {
7353 // FIXME: We could do this check for dependent types with non-dependent
7354 // bases.
7355 if (!Record->isDependentType()) {
7356 // See if a method overloads virtual methods in a base
7357 // class without overriding any.
7358 if (!M->isStatic())
7359 DiagnoseHiddenVirtualMethods(MD: M);
7360
7361 if (M->hasAttr<OverrideAttr>()) {
7362 HasMethodWithOverrideControl = true;
7363 } else if (M->size_overridden_methods() > 0) {
7364 HasOverridingMethodWithoutOverrideControl = true;
7365 } else {
7366 // Warn on newly-declared virtual methods in `final` classes
7367 if (M->isVirtualAsWritten() && Record->isEffectivelyFinal()) {
7368 Diag(Loc: M->getLocation(), DiagID: diag::warn_unnecessary_virtual_specifier)
7369 << M;
7370 }
7371 }
7372 }
7373
7374 if (!isa<CXXDestructorDecl>(Val: M))
7375 CompleteMemberFunction(M);
7376 } else if (auto *F = dyn_cast<FriendDecl>(Val: D)) {
7377 CheckForDefaultedFunction(
7378 dyn_cast_or_null<FunctionDecl>(Val: F->getFriendDecl()));
7379 }
7380 }
7381
7382 if (HasOverridingMethodWithoutOverrideControl) {
7383 bool HasInconsistentOverrideControl = HasMethodWithOverrideControl;
7384 for (auto *M : Record->methods())
7385 DiagnoseAbsenceOfOverrideControl(D: M, Inconsistent: HasInconsistentOverrideControl);
7386 }
7387
7388 // Check the defaulted secondary comparisons after any other member functions.
7389 for (FunctionDecl *FD : DefaultedSecondaryComparisons) {
7390 CheckExplicitlyDefaultedFunction(S, MD: FD);
7391
7392 // If this is a member function, we deferred checking it until now.
7393 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: FD))
7394 CheckCompletedMemberFunction(MD);
7395 }
7396
7397 // {ms,gcc}_struct is a request to change ABI rules to either follow
7398 // Microsoft or Itanium C++ ABI. However, even if these attributes are
7399 // present, we do not layout classes following foreign ABI rules, but
7400 // instead enter a special "compatibility mode", which only changes
7401 // alignments of fundamental types and layout of bit fields.
7402 // Check whether this class uses any C++ features that are implemented
7403 // completely differently in the requested ABI, and if so, emit a
7404 // diagnostic. That diagnostic defaults to an error, but we allow
7405 // projects to map it down to a warning (or ignore it). It's a fairly
7406 // common practice among users of the ms_struct pragma to
7407 // mass-annotate headers, sweeping up a bunch of types that the
7408 // project doesn't really rely on MSVC-compatible layout for. We must
7409 // therefore support "ms_struct except for C++ stuff" as a secondary
7410 // ABI.
7411 // Don't emit this diagnostic if the feature was enabled as a
7412 // language option (as opposed to via a pragma or attribute), as
7413 // the option -mms-bitfields otherwise essentially makes it impossible
7414 // to build C++ code, unless this diagnostic is turned off.
7415 if (Context.getLangOpts().getLayoutCompatibility() ==
7416 LangOptions::LayoutCompatibilityKind::Default &&
7417 Record->isMsStruct(C: Context) != Context.defaultsToMsStruct() &&
7418 (Record->isPolymorphic() || Record->getNumBases())) {
7419 Diag(Loc: Record->getLocation(), DiagID: diag::warn_cxx_ms_struct);
7420 }
7421
7422 checkClassLevelDLLAttribute(Class: Record);
7423 checkClassLevelCodeSegAttribute(Class: Record);
7424
7425 bool ClangABICompat4 =
7426 Context.getLangOpts().isCompatibleWith(Version: LangOptions::ClangABI::Ver4);
7427 TargetInfo::CallingConvKind CCK =
7428 Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
7429 bool CanPass = canPassInRegisters(S&: *this, D: Record, CCK);
7430
7431 // Do not change ArgPassingRestrictions if it has already been set to
7432 // RecordArgPassingKind::CanNeverPassInRegs.
7433 if (Record->getArgPassingRestrictions() !=
7434 RecordArgPassingKind::CanNeverPassInRegs)
7435 Record->setArgPassingRestrictions(
7436 CanPass ? RecordArgPassingKind::CanPassInRegs
7437 : RecordArgPassingKind::CannotPassInRegs);
7438
7439 // If canPassInRegisters returns true despite the record having a non-trivial
7440 // destructor, the record is destructed in the callee. This happens only when
7441 // the record or one of its subobjects has a field annotated with trivial_abi
7442 // or a field qualified with ObjC __strong/__weak.
7443 if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
7444 Record->setParamDestroyedInCallee(true);
7445 else if (Record->hasNonTrivialDestructor())
7446 Record->setParamDestroyedInCallee(CanPass);
7447
7448 if (getLangOpts().ForceEmitVTables) {
7449 // If we want to emit all the vtables, we need to mark it as used. This
7450 // is especially required for cases like vtable assumption loads.
7451 MarkVTableUsed(Loc: Record->getInnerLocStart(), Class: Record);
7452 }
7453
7454 if (getLangOpts().CUDA) {
7455 if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>())
7456 checkCUDADeviceBuiltinSurfaceClassTemplate(S&: *this, Class: Record);
7457 else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>())
7458 checkCUDADeviceBuiltinTextureClassTemplate(S&: *this, Class: Record);
7459 }
7460
7461 llvm::SmallDenseMap<OverloadedOperatorKind,
7462 llvm::SmallVector<const FunctionDecl *, 2>, 4>
7463 TypeAwareDecls{{OO_New, {}},
7464 {OO_Array_New, {}},
7465 {OO_Delete, {}},
7466 {OO_Array_New, {}}};
7467 for (auto *D : Record->decls()) {
7468 const FunctionDecl *FnDecl = D->getAsFunction();
7469 if (!FnDecl || !FnDecl->isTypeAwareOperatorNewOrDelete())
7470 continue;
7471 assert(FnDecl->getDeclName().isAnyOperatorNewOrDelete());
7472 TypeAwareDecls[FnDecl->getOverloadedOperator()].push_back(Elt: FnDecl);
7473 }
7474 auto CheckMismatchedTypeAwareAllocators =
7475 [this, &TypeAwareDecls, Record](OverloadedOperatorKind NewKind,
7476 OverloadedOperatorKind DeleteKind) {
7477 auto &NewDecls = TypeAwareDecls[NewKind];
7478 auto &DeleteDecls = TypeAwareDecls[DeleteKind];
7479 if (NewDecls.empty() == DeleteDecls.empty())
7480 return;
7481 DeclarationName FoundOperator =
7482 Context.DeclarationNames.getCXXOperatorName(
7483 Op: NewDecls.empty() ? DeleteKind : NewKind);
7484 DeclarationName MissingOperator =
7485 Context.DeclarationNames.getCXXOperatorName(
7486 Op: NewDecls.empty() ? NewKind : DeleteKind);
7487 Diag(Loc: Record->getLocation(),
7488 DiagID: diag::err_type_aware_allocator_missing_matching_operator)
7489 << FoundOperator << Context.getCanonicalTagType(TD: Record)
7490 << MissingOperator;
7491 for (auto MD : NewDecls)
7492 Diag(Loc: MD->getLocation(),
7493 DiagID: diag::note_unmatched_type_aware_allocator_declared)
7494 << MD;
7495 for (auto MD : DeleteDecls)
7496 Diag(Loc: MD->getLocation(),
7497 DiagID: diag::note_unmatched_type_aware_allocator_declared)
7498 << MD;
7499 };
7500 CheckMismatchedTypeAwareAllocators(OO_New, OO_Delete);
7501 CheckMismatchedTypeAwareAllocators(OO_Array_New, OO_Array_Delete);
7502}
7503
7504/// Look up the special member function that would be called by a special
7505/// member function for a subobject of class type.
7506///
7507/// \param Class The class type of the subobject.
7508/// \param CSM The kind of special member function.
7509/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
7510/// \param ConstRHS True if this is a copy operation with a const object
7511/// on its RHS, that is, if the argument to the outer special member
7512/// function is 'const' and this is not a field marked 'mutable'.
7513static Sema::SpecialMemberOverloadResult
7514lookupCallFromSpecialMember(Sema &S, CXXRecordDecl *Class,
7515 CXXSpecialMemberKind CSM, unsigned FieldQuals,
7516 bool ConstRHS) {
7517 unsigned LHSQuals = 0;
7518 if (CSM == CXXSpecialMemberKind::CopyAssignment ||
7519 CSM == CXXSpecialMemberKind::MoveAssignment)
7520 LHSQuals = FieldQuals;
7521
7522 unsigned RHSQuals = FieldQuals;
7523 if (CSM == CXXSpecialMemberKind::DefaultConstructor ||
7524 CSM == CXXSpecialMemberKind::Destructor)
7525 RHSQuals = 0;
7526 else if (ConstRHS)
7527 RHSQuals |= Qualifiers::Const;
7528
7529 return S.LookupSpecialMember(D: Class, SM: CSM,
7530 ConstArg: RHSQuals & Qualifiers::Const,
7531 VolatileArg: RHSQuals & Qualifiers::Volatile,
7532 RValueThis: false,
7533 ConstThis: LHSQuals & Qualifiers::Const,
7534 VolatileThis: LHSQuals & Qualifiers::Volatile);
7535}
7536
7537class Sema::InheritedConstructorInfo {
7538 Sema &S;
7539 SourceLocation UseLoc;
7540
7541 /// A mapping from the base classes through which the constructor was
7542 /// inherited to the using shadow declaration in that base class (or a null
7543 /// pointer if the constructor was declared in that base class).
7544 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
7545 InheritedFromBases;
7546
7547public:
7548 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
7549 ConstructorUsingShadowDecl *Shadow)
7550 : S(S), UseLoc(UseLoc) {
7551 bool DiagnosedMultipleConstructedBases = false;
7552 CXXRecordDecl *ConstructedBase = nullptr;
7553 BaseUsingDecl *ConstructedBaseIntroducer = nullptr;
7554
7555 // Find the set of such base class subobjects and check that there's a
7556 // unique constructed subobject.
7557 for (auto *D : Shadow->redecls()) {
7558 auto *DShadow = cast<ConstructorUsingShadowDecl>(Val: D);
7559 auto *DNominatedBase = DShadow->getNominatedBaseClass();
7560 auto *DConstructedBase = DShadow->getConstructedBaseClass();
7561
7562 InheritedFromBases.insert(
7563 KV: std::make_pair(x: DNominatedBase->getCanonicalDecl(),
7564 y: DShadow->getNominatedBaseClassShadowDecl()));
7565 if (DShadow->constructsVirtualBase())
7566 InheritedFromBases.insert(
7567 KV: std::make_pair(x: DConstructedBase->getCanonicalDecl(),
7568 y: DShadow->getConstructedBaseClassShadowDecl()));
7569 else
7570 assert(DNominatedBase == DConstructedBase);
7571
7572 // [class.inhctor.init]p2:
7573 // If the constructor was inherited from multiple base class subobjects
7574 // of type B, the program is ill-formed.
7575 if (!ConstructedBase) {
7576 ConstructedBase = DConstructedBase;
7577 ConstructedBaseIntroducer = D->getIntroducer();
7578 } else if (ConstructedBase != DConstructedBase &&
7579 !Shadow->isInvalidDecl()) {
7580 if (!DiagnosedMultipleConstructedBases) {
7581 S.Diag(Loc: UseLoc, DiagID: diag::err_ambiguous_inherited_constructor)
7582 << Shadow->getTargetDecl();
7583 S.Diag(Loc: ConstructedBaseIntroducer->getLocation(),
7584 DiagID: diag::note_ambiguous_inherited_constructor_using)
7585 << ConstructedBase;
7586 DiagnosedMultipleConstructedBases = true;
7587 }
7588 S.Diag(Loc: D->getIntroducer()->getLocation(),
7589 DiagID: diag::note_ambiguous_inherited_constructor_using)
7590 << DConstructedBase;
7591 }
7592 }
7593
7594 if (DiagnosedMultipleConstructedBases)
7595 Shadow->setInvalidDecl();
7596 }
7597
7598 /// Find the constructor to use for inherited construction of a base class,
7599 /// and whether that base class constructor inherits the constructor from a
7600 /// virtual base class (in which case it won't actually invoke it).
7601 std::pair<CXXConstructorDecl *, bool>
7602 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
7603 auto It = InheritedFromBases.find(Val: Base->getCanonicalDecl());
7604 if (It == InheritedFromBases.end())
7605 return std::make_pair(x: nullptr, y: false);
7606
7607 // This is an intermediary class.
7608 if (It->second)
7609 return std::make_pair(
7610 x: S.findInheritingConstructor(Loc: UseLoc, BaseCtor: Ctor, DerivedShadow: It->second),
7611 y: It->second->constructsVirtualBase());
7612
7613 // This is the base class from which the constructor was inherited.
7614 return std::make_pair(x&: Ctor, y: false);
7615 }
7616};
7617
7618/// Is the special member function which would be selected to perform the
7619/// specified operation on the specified class type a constexpr constructor?
7620static bool specialMemberIsConstexpr(
7621 Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, unsigned Quals,
7622 bool ConstRHS, CXXConstructorDecl *InheritedCtor = nullptr,
7623 Sema::InheritedConstructorInfo *Inherited = nullptr) {
7624 // Suppress duplicate constraint checking here, in case a constraint check
7625 // caused us to decide to do this. Any truely recursive checks will get
7626 // caught during these checks anyway.
7627 Sema::SatisfactionStackResetRAII SSRAII{S};
7628
7629 // If we're inheriting a constructor, see if we need to call it for this base
7630 // class.
7631 if (InheritedCtor) {
7632 assert(CSM == CXXSpecialMemberKind::DefaultConstructor);
7633 auto BaseCtor =
7634 Inherited->findConstructorForBase(Base: ClassDecl, Ctor: InheritedCtor).first;
7635 if (BaseCtor)
7636 return BaseCtor->isConstexpr();
7637 }
7638
7639 if (CSM == CXXSpecialMemberKind::DefaultConstructor)
7640 return ClassDecl->hasConstexprDefaultConstructor();
7641 if (CSM == CXXSpecialMemberKind::Destructor)
7642 return ClassDecl->hasConstexprDestructor();
7643
7644 Sema::SpecialMemberOverloadResult SMOR =
7645 lookupCallFromSpecialMember(S, Class: ClassDecl, CSM, FieldQuals: Quals, ConstRHS);
7646 if (!SMOR.getMethod())
7647 // A constructor we wouldn't select can't be "involved in initializing"
7648 // anything.
7649 return true;
7650 return SMOR.getMethod()->isConstexpr();
7651}
7652
7653/// Determine whether the specified special member function would be constexpr
7654/// if it were implicitly defined.
7655static bool defaultedSpecialMemberIsConstexpr(
7656 Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, bool ConstArg,
7657 CXXConstructorDecl *InheritedCtor = nullptr,
7658 Sema::InheritedConstructorInfo *Inherited = nullptr) {
7659 if (!S.getLangOpts().CPlusPlus11)
7660 return false;
7661
7662 // C++11 [dcl.constexpr]p4:
7663 // In the definition of a constexpr constructor [...]
7664 bool Ctor = true;
7665 switch (CSM) {
7666 case CXXSpecialMemberKind::DefaultConstructor:
7667 if (Inherited)
7668 break;
7669 // Since default constructor lookup is essentially trivial (and cannot
7670 // involve, for instance, template instantiation), we compute whether a
7671 // defaulted default constructor is constexpr directly within CXXRecordDecl.
7672 //
7673 // This is important for performance; we need to know whether the default
7674 // constructor is constexpr to determine whether the type is a literal type.
7675 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
7676
7677 case CXXSpecialMemberKind::CopyConstructor:
7678 case CXXSpecialMemberKind::MoveConstructor:
7679 // For copy or move constructors, we need to perform overload resolution.
7680 break;
7681
7682 case CXXSpecialMemberKind::CopyAssignment:
7683 case CXXSpecialMemberKind::MoveAssignment:
7684 if (!S.getLangOpts().CPlusPlus14)
7685 return false;
7686 // In C++1y, we need to perform overload resolution.
7687 Ctor = false;
7688 break;
7689
7690 case CXXSpecialMemberKind::Destructor:
7691 return ClassDecl->defaultedDestructorIsConstexpr();
7692
7693 case CXXSpecialMemberKind::Invalid:
7694 return false;
7695 }
7696
7697 // -- if the class is a non-empty union, or for each non-empty anonymous
7698 // union member of a non-union class, exactly one non-static data member
7699 // shall be initialized; [DR1359]
7700 //
7701 // If we squint, this is guaranteed, since exactly one non-static data member
7702 // will be initialized (if the constructor isn't deleted), we just don't know
7703 // which one.
7704 if (Ctor && ClassDecl->isUnion())
7705 return CSM == CXXSpecialMemberKind::DefaultConstructor
7706 ? ClassDecl->hasInClassInitializer() ||
7707 !ClassDecl->hasVariantMembers()
7708 : true;
7709
7710 // -- the class shall not have any virtual base classes;
7711 if (!S.getLangOpts().CPlusPlus26 && Ctor && ClassDecl->getNumVBases())
7712 return false;
7713
7714 // C++1y [class.copy]p26:
7715 // -- [the class] is a literal type, and
7716 if (!S.getLangOpts().CPlusPlus23 && !Ctor && !ClassDecl->isLiteral())
7717 return false;
7718
7719 // -- every constructor involved in initializing [...] base class
7720 // sub-objects shall be a constexpr constructor;
7721 // -- the assignment operator selected to copy/move each direct base
7722 // class is a constexpr function, and
7723 if (!S.getLangOpts().CPlusPlus23) {
7724 for (const auto &B : ClassDecl->bases()) {
7725 auto *BaseClassDecl = B.getType()->getAsCXXRecordDecl();
7726 if (!BaseClassDecl)
7727 continue;
7728 if (!specialMemberIsConstexpr(S, ClassDecl: BaseClassDecl, CSM, Quals: 0, ConstRHS: ConstArg,
7729 InheritedCtor, Inherited))
7730 return false;
7731 }
7732 }
7733
7734 // -- every constructor involved in initializing non-static data members
7735 // [...] shall be a constexpr constructor;
7736 // -- every non-static data member and base class sub-object shall be
7737 // initialized
7738 // -- for each non-static data member of X that is of class type (or array
7739 // thereof), the assignment operator selected to copy/move that member is
7740 // a constexpr function
7741 if (!S.getLangOpts().CPlusPlus23) {
7742 for (const auto *F : ClassDecl->fields()) {
7743 if (F->isInvalidDecl())
7744 continue;
7745 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
7746 F->hasInClassInitializer())
7747 continue;
7748 QualType BaseType = S.Context.getBaseElementType(QT: F->getType());
7749 if (const RecordType *RecordTy = BaseType->getAsCanonical<RecordType>()) {
7750 auto *FieldRecDecl =
7751 cast<CXXRecordDecl>(Val: RecordTy->getDecl())->getDefinitionOrSelf();
7752 if (!specialMemberIsConstexpr(S, ClassDecl: FieldRecDecl, CSM,
7753 Quals: BaseType.getCVRQualifiers(),
7754 ConstRHS: ConstArg && !F->isMutable()))
7755 return false;
7756 } else if (CSM == CXXSpecialMemberKind::DefaultConstructor) {
7757 return false;
7758 }
7759 }
7760 }
7761
7762 // All OK, it's constexpr!
7763 return true;
7764}
7765
7766namespace {
7767/// RAII object to register a defaulted function as having its exception
7768/// specification computed.
7769struct ComputingExceptionSpec {
7770 Sema &S;
7771
7772 ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc)
7773 : S(S) {
7774 Sema::CodeSynthesisContext Ctx;
7775 Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;
7776 Ctx.PointOfInstantiation = Loc;
7777 Ctx.Entity = FD;
7778 S.pushCodeSynthesisContext(Ctx);
7779 }
7780 ~ComputingExceptionSpec() {
7781 S.popCodeSynthesisContext();
7782 }
7783};
7784}
7785
7786static Sema::ImplicitExceptionSpecification
7787ComputeDefaultedSpecialMemberExceptionSpec(Sema &S, SourceLocation Loc,
7788 CXXMethodDecl *MD,
7789 CXXSpecialMemberKind CSM,
7790 Sema::InheritedConstructorInfo *ICI);
7791
7792static Sema::ImplicitExceptionSpecification
7793ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
7794 FunctionDecl *FD,
7795 DefaultedComparisonKind DCK);
7796
7797static Sema::ImplicitExceptionSpecification
7798computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD) {
7799 auto DFK = FD->getDefaultedFunctionKind();
7800 if (DFK.isSpecialMember())
7801 return ComputeDefaultedSpecialMemberExceptionSpec(
7802 S, Loc, MD: cast<CXXMethodDecl>(Val: FD), CSM: DFK.asSpecialMember(), ICI: nullptr);
7803 if (DFK.isComparison())
7804 return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD,
7805 DCK: DFK.asComparison());
7806
7807 auto *CD = cast<CXXConstructorDecl>(Val: FD);
7808 assert(CD->getInheritedConstructor() &&
7809 "only defaulted functions and inherited constructors have implicit "
7810 "exception specs");
7811 Sema::InheritedConstructorInfo ICI(
7812 S, Loc, CD->getInheritedConstructor().getShadowDecl());
7813 return ComputeDefaultedSpecialMemberExceptionSpec(
7814 S, Loc, MD: CD, CSM: CXXSpecialMemberKind::DefaultConstructor, ICI: &ICI);
7815}
7816
7817static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
7818 CXXMethodDecl *MD) {
7819 FunctionProtoType::ExtProtoInfo EPI;
7820
7821 // Build an exception specification pointing back at this member.
7822 EPI.ExceptionSpec.Type = EST_Unevaluated;
7823 EPI.ExceptionSpec.SourceDecl = MD;
7824
7825 // Set the calling convention to the default for C++ instance methods.
7826 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
7827 cc: S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
7828 /*IsCXXMethod=*/true));
7829 return EPI;
7830}
7831
7832void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD) {
7833 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
7834 if (FPT->getExceptionSpecType() != EST_Unevaluated)
7835 return;
7836
7837 // Evaluate the exception specification.
7838 auto IES = computeImplicitExceptionSpec(S&: *this, Loc, FD);
7839 auto ESI = IES.getExceptionSpec();
7840
7841 // Update the type of the special member to use it.
7842 UpdateExceptionSpec(FD, ESI);
7843}
7844
7845void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) {
7846 assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted");
7847
7848 FunctionDecl::DefaultedFunctionKind DefKind = FD->getDefaultedFunctionKind();
7849 if (!DefKind) {
7850 assert(FD->getDeclContext()->isDependentContext());
7851 return;
7852 }
7853
7854 if (DefKind.isComparison()) {
7855 auto PT = FD->getParamDecl(i: 0)->getType();
7856 if (const CXXRecordDecl *RD =
7857 PT.getNonReferenceType()->getAsCXXRecordDecl()) {
7858 for (FieldDecl *Field : RD->fields()) {
7859 UnusedPrivateFields.remove(X: Field);
7860 }
7861 }
7862 }
7863
7864 if (DefKind.isSpecialMember()
7865 ? CheckExplicitlyDefaultedSpecialMember(MD: cast<CXXMethodDecl>(Val: FD),
7866 CSM: DefKind.asSpecialMember(),
7867 DefaultLoc: FD->getDefaultLoc())
7868 : CheckExplicitlyDefaultedComparison(S, MD: FD, DCK: DefKind.asComparison()))
7869 FD->setInvalidDecl();
7870}
7871
7872bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
7873 CXXSpecialMemberKind CSM,
7874 SourceLocation DefaultLoc) {
7875 CXXRecordDecl *RD = MD->getParent();
7876
7877 assert(MD->isExplicitlyDefaulted() && CSM != CXXSpecialMemberKind::Invalid &&
7878 "not an explicitly-defaulted special member");
7879
7880 // Defer all checking for special members of a dependent type.
7881 if (RD->isDependentType())
7882 return false;
7883
7884 // Whether this was the first-declared instance of the constructor.
7885 // This affects whether we implicitly add an exception spec and constexpr.
7886 bool First = MD == MD->getCanonicalDecl();
7887
7888 bool HadError = false;
7889
7890 // C++11 [dcl.fct.def.default]p1:
7891 // A function that is explicitly defaulted shall
7892 // -- be a special member function [...] (checked elsewhere),
7893 // -- have the same type (except for ref-qualifiers, and except that a
7894 // copy operation can take a non-const reference) as an implicit
7895 // declaration, and
7896 // -- not have default arguments.
7897 // C++2a changes the second bullet to instead delete the function if it's
7898 // defaulted on its first declaration, unless it's "an assignment operator,
7899 // and its return type differs or its parameter type is not a reference".
7900 bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First;
7901 bool ShouldDeleteForTypeMismatch = false;
7902 unsigned ExpectedParams = 1;
7903 if (CSM == CXXSpecialMemberKind::DefaultConstructor ||
7904 CSM == CXXSpecialMemberKind::Destructor)
7905 ExpectedParams = 0;
7906 if (MD->getNumExplicitParams() != ExpectedParams) {
7907 // This checks for default arguments: a copy or move constructor with a
7908 // default argument is classified as a default constructor, and assignment
7909 // operations and destructors can't have default arguments.
7910 Diag(Loc: MD->getLocation(), DiagID: diag::err_defaulted_special_member_params)
7911 << CSM << MD->getSourceRange();
7912 HadError = true;
7913 } else if (MD->isVariadic()) {
7914 if (DeleteOnTypeMismatch)
7915 ShouldDeleteForTypeMismatch = true;
7916 else {
7917 Diag(Loc: MD->getLocation(), DiagID: diag::err_defaulted_special_member_variadic)
7918 << CSM << MD->getSourceRange();
7919 HadError = true;
7920 }
7921 }
7922
7923 const FunctionProtoType *Type = MD->getType()->castAs<FunctionProtoType>();
7924
7925 bool CanHaveConstParam = false;
7926 if (CSM == CXXSpecialMemberKind::CopyConstructor)
7927 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
7928 else if (CSM == CXXSpecialMemberKind::CopyAssignment)
7929 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
7930
7931 QualType ReturnType = Context.VoidTy;
7932 if (CSM == CXXSpecialMemberKind::CopyAssignment ||
7933 CSM == CXXSpecialMemberKind::MoveAssignment) {
7934 // Check for return type matching.
7935 ReturnType = Type->getReturnType();
7936 QualType ThisType = MD->getFunctionObjectParameterType();
7937
7938 QualType DeclType =
7939 Context.getTagType(Keyword: ElaboratedTypeKeyword::None,
7940 /*Qualifier=*/std::nullopt, TD: RD, /*OwnsTag=*/false);
7941 DeclType = Context.getAddrSpaceQualType(
7942 T: DeclType, AddressSpace: ThisType.getQualifiers().getAddressSpace());
7943 QualType ExpectedReturnType = Context.getLValueReferenceType(T: DeclType);
7944
7945 if (!Context.hasSameType(T1: ReturnType, T2: ExpectedReturnType)) {
7946 Diag(Loc: MD->getLocation(), DiagID: diag::err_defaulted_special_member_return_type)
7947 << (CSM == CXXSpecialMemberKind::MoveAssignment)
7948 << ExpectedReturnType;
7949 HadError = true;
7950 }
7951
7952 // A defaulted special member cannot have cv-qualifiers.
7953 if (ThisType.isConstQualified() || ThisType.isVolatileQualified()) {
7954 if (DeleteOnTypeMismatch)
7955 ShouldDeleteForTypeMismatch = true;
7956 else {
7957 Diag(Loc: MD->getLocation(), DiagID: diag::err_defaulted_special_member_quals)
7958 << (CSM == CXXSpecialMemberKind::MoveAssignment)
7959 << getLangOpts().CPlusPlus14;
7960 HadError = true;
7961 }
7962 }
7963 // [C++23][dcl.fct.def.default]/p2.2
7964 // if F2 has an implicit object parameter of type “reference to C”,
7965 // F1 may be an explicit object member function whose explicit object
7966 // parameter is of (possibly different) type “reference to C”,
7967 // in which case the type of F1 would differ from the type of F2
7968 // in that the type of F1 has an additional parameter;
7969 QualType ExplicitObjectParameter = MD->isExplicitObjectMemberFunction()
7970 ? MD->getParamDecl(i: 0)->getType()
7971 : QualType();
7972 if (!ExplicitObjectParameter.isNull() &&
7973 (!ExplicitObjectParameter->isReferenceType() ||
7974 !Context.hasSameType(T1: ExplicitObjectParameter.getNonReferenceType(),
7975 T2: Context.getCanonicalTagType(TD: RD)))) {
7976 if (DeleteOnTypeMismatch)
7977 ShouldDeleteForTypeMismatch = true;
7978 else {
7979 Diag(Loc: MD->getLocation(),
7980 DiagID: diag::err_defaulted_special_member_explicit_object_mismatch)
7981 << (CSM == CXXSpecialMemberKind::MoveAssignment) << RD
7982 << MD->getSourceRange();
7983 HadError = true;
7984 }
7985 }
7986 }
7987
7988 // Check for parameter type matching.
7989 QualType ArgType =
7990 ExpectedParams
7991 ? Type->getParamType(i: MD->isExplicitObjectMemberFunction() ? 1 : 0)
7992 : QualType();
7993 bool HasConstParam = false;
7994 if (ExpectedParams && ArgType->isReferenceType()) {
7995 // Argument must be reference to possibly-const T.
7996 QualType ReferentType = ArgType->getPointeeType();
7997 HasConstParam = ReferentType.isConstQualified();
7998
7999 if (ReferentType.isVolatileQualified()) {
8000 if (DeleteOnTypeMismatch)
8001 ShouldDeleteForTypeMismatch = true;
8002 else {
8003 Diag(Loc: MD->getLocation(),
8004 DiagID: diag::err_defaulted_special_member_volatile_param)
8005 << CSM;
8006 HadError = true;
8007 }
8008 }
8009
8010 if (HasConstParam && !CanHaveConstParam) {
8011 if (DeleteOnTypeMismatch)
8012 ShouldDeleteForTypeMismatch = true;
8013 else if (CSM == CXXSpecialMemberKind::CopyConstructor ||
8014 CSM == CXXSpecialMemberKind::CopyAssignment) {
8015 Diag(Loc: MD->getLocation(),
8016 DiagID: diag::err_defaulted_special_member_copy_const_param)
8017 << (CSM == CXXSpecialMemberKind::CopyAssignment);
8018 // FIXME: Explain why this special member can't be const.
8019 HadError = true;
8020 } else {
8021 Diag(Loc: MD->getLocation(),
8022 DiagID: diag::err_defaulted_special_member_move_const_param)
8023 << (CSM == CXXSpecialMemberKind::MoveAssignment);
8024 HadError = true;
8025 }
8026 }
8027 } else if (ExpectedParams) {
8028 // A copy assignment operator can take its argument by value, but a
8029 // defaulted one cannot.
8030 assert(CSM == CXXSpecialMemberKind::CopyAssignment &&
8031 "unexpected non-ref argument");
8032 Diag(Loc: MD->getLocation(), DiagID: diag::err_defaulted_copy_assign_not_ref);
8033 HadError = true;
8034 }
8035
8036 // C++11 [dcl.fct.def.default]p2:
8037 // An explicitly-defaulted function may be declared constexpr only if it
8038 // would have been implicitly declared as constexpr,
8039 // Do not apply this rule to members of class templates, since core issue 1358
8040 // makes such functions always instantiate to constexpr functions. For
8041 // functions which cannot be constexpr (for non-constructors in C++11 and for
8042 // destructors in C++14 and C++17), this is checked elsewhere.
8043 //
8044 // FIXME: This should not apply if the member is deleted.
8045 bool Constexpr = defaultedSpecialMemberIsConstexpr(S&: *this, ClassDecl: RD, CSM,
8046 ConstArg: HasConstParam);
8047
8048 // C++14 [dcl.constexpr]p6 (CWG DR647/CWG DR1358):
8049 // If the instantiated template specialization of a constexpr function
8050 // template or member function of a class template would fail to satisfy
8051 // the requirements for a constexpr function or constexpr constructor, that
8052 // specialization is still a constexpr function or constexpr constructor,
8053 // even though a call to such a function cannot appear in a constant
8054 // expression.
8055 if (MD->isTemplateInstantiation() && MD->isConstexpr())
8056 Constexpr = true;
8057
8058 if ((getLangOpts().CPlusPlus20 ||
8059 (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(Val: MD)
8060 : isa<CXXConstructorDecl>(Val: MD))) &&
8061 MD->isConstexpr() && !Constexpr &&
8062 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
8063 if (!MD->isConsteval() && RD->getNumVBases()) {
8064 Diag(Loc: MD->getBeginLoc(),
8065 DiagID: diag::err_incorrect_defaulted_constexpr_with_vb)
8066 << CSM;
8067 for (const auto &I : RD->vbases())
8068 Diag(Loc: I.getBeginLoc(), DiagID: diag::note_constexpr_virtual_base_here);
8069 } else {
8070 Diag(Loc: MD->getBeginLoc(), DiagID: diag::err_incorrect_defaulted_constexpr)
8071 << CSM << MD->isConsteval();
8072 }
8073 HadError = true;
8074 // FIXME: Explain why the special member can't be constexpr.
8075 }
8076 if (First) {
8077 // C++2a [dcl.fct.def.default]p3:
8078 // If a function is explicitly defaulted on its first declaration, it is
8079 // implicitly considered to be constexpr if the implicit declaration
8080 // would be.
8081 MD->setConstexprKind(Constexpr ? (MD->isConsteval()
8082 ? ConstexprSpecKind::Consteval
8083 : ConstexprSpecKind::Constexpr)
8084 : ConstexprSpecKind::Unspecified);
8085
8086 if (!Type->hasExceptionSpec()) {
8087 // C++2a [except.spec]p3:
8088 // If a declaration of a function does not have a noexcept-specifier
8089 // [and] is defaulted on its first declaration, [...] the exception
8090 // specification is as specified below
8091 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
8092 EPI.ExceptionSpec.Type = EST_Unevaluated;
8093 EPI.ExceptionSpec.SourceDecl = MD;
8094 MD->setType(
8095 Context.getFunctionType(ResultTy: ReturnType, Args: Type->getParamTypes(), EPI));
8096 }
8097 }
8098
8099 if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
8100 if (First) {
8101 SetDeclDeleted(dcl: MD, DelLoc: MD->getLocation());
8102 if (!inTemplateInstantiation() && !HadError) {
8103 Diag(Loc: MD->getLocation(), DiagID: diag::warn_defaulted_method_deleted) << CSM;
8104 if (ShouldDeleteForTypeMismatch) {
8105 Diag(Loc: MD->getLocation(), DiagID: diag::note_deleted_type_mismatch) << CSM;
8106 } else if (ShouldDeleteSpecialMember(MD, CSM, ICI: nullptr,
8107 /*Diagnose*/ true) &&
8108 DefaultLoc.isValid()) {
8109 Diag(Loc: DefaultLoc, DiagID: diag::note_replace_equals_default_to_delete)
8110 << FixItHint::CreateReplacement(RemoveRange: DefaultLoc, Code: "delete");
8111 }
8112 }
8113 if (ShouldDeleteForTypeMismatch && !HadError) {
8114 Diag(Loc: MD->getLocation(),
8115 DiagID: diag::warn_cxx17_compat_defaulted_method_type_mismatch)
8116 << CSM;
8117 }
8118 } else {
8119 // C++11 [dcl.fct.def.default]p4:
8120 // [For a] user-provided explicitly-defaulted function [...] if such a
8121 // function is implicitly defined as deleted, the program is ill-formed.
8122 Diag(Loc: MD->getLocation(), DiagID: diag::err_out_of_line_default_deletes) << CSM;
8123 assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
8124 ShouldDeleteSpecialMember(MD, CSM, ICI: nullptr, /*Diagnose*/true);
8125 HadError = true;
8126 }
8127 }
8128
8129 return HadError;
8130}
8131
8132namespace {
8133/// Helper class for building and checking a defaulted comparison.
8134///
8135/// Defaulted functions are built in two phases:
8136///
8137/// * First, the set of operations that the function will perform are
8138/// identified, and some of them are checked. If any of the checked
8139/// operations is invalid in certain ways, the comparison function is
8140/// defined as deleted and no body is built.
8141/// * Then, if the function is not defined as deleted, the body is built.
8142///
8143/// This is accomplished by performing two visitation steps over the eventual
8144/// body of the function.
8145template<typename Derived, typename ResultList, typename Result,
8146 typename Subobject>
8147class DefaultedComparisonVisitor {
8148public:
8149 DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8150 DefaultedComparisonKind DCK)
8151 : S(S), RD(RD), FD(FD), DCK(DCK) {
8152 if (auto *Info = FD->getDefaultedOrDeletedInfo()) {
8153 // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an
8154 // UnresolvedSet to avoid this copy.
8155 Fns.assign(I: Info->getUnqualifiedLookups().begin(),
8156 E: Info->getUnqualifiedLookups().end());
8157 }
8158 }
8159
8160 ResultList visit() {
8161 // The type of an lvalue naming a parameter of this function.
8162 QualType ParamLvalType =
8163 FD->getParamDecl(i: 0)->getType().getNonReferenceType();
8164
8165 ResultList Results;
8166
8167 switch (DCK) {
8168 case DefaultedComparisonKind::None:
8169 llvm_unreachable("not a defaulted comparison");
8170
8171 case DefaultedComparisonKind::Equal:
8172 case DefaultedComparisonKind::ThreeWay:
8173 getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers());
8174 return Results;
8175
8176 case DefaultedComparisonKind::NotEqual:
8177 case DefaultedComparisonKind::Relational:
8178 Results.add(getDerived().visitExpandedSubobject(
8179 ParamLvalType, getDerived().getCompleteObject()));
8180 return Results;
8181 }
8182 llvm_unreachable("");
8183 }
8184
8185protected:
8186 Derived &getDerived() { return static_cast<Derived&>(*this); }
8187
8188 /// Visit the expanded list of subobjects of the given type, as specified in
8189 /// C++2a [class.compare.default].
8190 ///
8191 /// \return \c true if the ResultList object said we're done, \c false if not.
8192 bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record,
8193 Qualifiers Quals) {
8194 // C++2a [class.compare.default]p4:
8195 // The direct base class subobjects of C
8196 for (CXXBaseSpecifier &Base : Record->bases())
8197 if (Results.add(getDerived().visitSubobject(
8198 S.Context.getQualifiedType(T: Base.getType(), Qs: Quals),
8199 getDerived().getBase(&Base))))
8200 return true;
8201
8202 // followed by the non-static data members of C
8203 for (FieldDecl *Field : Record->fields()) {
8204 // C++23 [class.bit]p2:
8205 // Unnamed bit-fields are not members ...
8206 if (Field->isUnnamedBitField())
8207 continue;
8208 // Recursively expand anonymous structs.
8209 if (Field->isAnonymousStructOrUnion()) {
8210 if (visitSubobjects(Results, Record: Field->getType()->getAsCXXRecordDecl(),
8211 Quals))
8212 return true;
8213 continue;
8214 }
8215
8216 // Figure out the type of an lvalue denoting this field.
8217 Qualifiers FieldQuals = Quals;
8218 if (Field->isMutable())
8219 FieldQuals.removeConst();
8220 QualType FieldType =
8221 S.Context.getQualifiedType(T: Field->getType(), Qs: FieldQuals);
8222
8223 if (Results.add(getDerived().visitSubobject(
8224 FieldType, getDerived().getField(Field))))
8225 return true;
8226 }
8227
8228 // form a list of subobjects.
8229 return false;
8230 }
8231
8232 Result visitSubobject(QualType Type, Subobject Subobj) {
8233 // In that list, any subobject of array type is recursively expanded
8234 const ArrayType *AT = S.Context.getAsArrayType(T: Type);
8235 if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(Val: AT))
8236 return getDerived().visitSubobjectArray(CAT->getElementType(),
8237 CAT->getSize(), Subobj);
8238 return getDerived().visitExpandedSubobject(Type, Subobj);
8239 }
8240
8241 Result visitSubobjectArray(QualType Type, const llvm::APInt &Size,
8242 Subobject Subobj) {
8243 return getDerived().visitSubobject(Type, Subobj);
8244 }
8245
8246protected:
8247 Sema &S;
8248 CXXRecordDecl *RD;
8249 FunctionDecl *FD;
8250 DefaultedComparisonKind DCK;
8251 UnresolvedSet<16> Fns;
8252};
8253
8254/// Information about a defaulted comparison, as determined by
8255/// DefaultedComparisonAnalyzer.
8256struct DefaultedComparisonInfo {
8257 bool Deleted = false;
8258 bool Constexpr = true;
8259 ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering;
8260
8261 static DefaultedComparisonInfo deleted() {
8262 DefaultedComparisonInfo Deleted;
8263 Deleted.Deleted = true;
8264 return Deleted;
8265 }
8266
8267 bool add(const DefaultedComparisonInfo &R) {
8268 Deleted |= R.Deleted;
8269 Constexpr &= R.Constexpr;
8270 Category = commonComparisonType(A: Category, B: R.Category);
8271 return Deleted;
8272 }
8273};
8274
8275/// An element in the expanded list of subobjects of a defaulted comparison, as
8276/// specified in C++2a [class.compare.default]p4.
8277struct DefaultedComparisonSubobject {
8278 enum { CompleteObject, Member, Base } Kind;
8279 NamedDecl *Decl;
8280 SourceLocation Loc;
8281};
8282
8283/// A visitor over the notional body of a defaulted comparison that determines
8284/// whether that body would be deleted or constexpr.
8285class DefaultedComparisonAnalyzer
8286 : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer,
8287 DefaultedComparisonInfo,
8288 DefaultedComparisonInfo,
8289 DefaultedComparisonSubobject> {
8290public:
8291 enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr };
8292
8293private:
8294 DiagnosticKind Diagnose;
8295
8296public:
8297 using Base = DefaultedComparisonVisitor;
8298 using Result = DefaultedComparisonInfo;
8299 using Subobject = DefaultedComparisonSubobject;
8300
8301 friend Base;
8302
8303 DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8304 DefaultedComparisonKind DCK,
8305 DiagnosticKind Diagnose = NoDiagnostics)
8306 : Base(S, RD, FD, DCK), Diagnose(Diagnose) {}
8307
8308 Result visit() {
8309 if ((DCK == DefaultedComparisonKind::Equal ||
8310 DCK == DefaultedComparisonKind::ThreeWay) &&
8311 RD->hasVariantMembers()) {
8312 // C++2a [class.compare.default]p2 [P2002R0]:
8313 // A defaulted comparison operator function for class C is defined as
8314 // deleted if [...] C has variant members.
8315 if (Diagnose == ExplainDeleted) {
8316 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_defaulted_comparison_union)
8317 << FD << RD->isUnion() << RD;
8318 }
8319 return Result::deleted();
8320 }
8321
8322 return Base::visit();
8323 }
8324
8325private:
8326 Subobject getCompleteObject() {
8327 return Subobject{.Kind: Subobject::CompleteObject, .Decl: RD, .Loc: FD->getLocation()};
8328 }
8329
8330 Subobject getBase(CXXBaseSpecifier *Base) {
8331 return Subobject{.Kind: Subobject::Base, .Decl: Base->getType()->getAsCXXRecordDecl(),
8332 .Loc: Base->getBaseTypeLoc()};
8333 }
8334
8335 Subobject getField(FieldDecl *Field) {
8336 return Subobject{.Kind: Subobject::Member, .Decl: Field, .Loc: Field->getLocation()};
8337 }
8338
8339 Result visitExpandedSubobject(QualType Type, Subobject Subobj) {
8340 // C++2a [class.compare.default]p2 [P2002R0]:
8341 // A defaulted <=> or == operator function for class C is defined as
8342 // deleted if any non-static data member of C is of reference type
8343 if (Type->isReferenceType()) {
8344 if (Diagnose == ExplainDeleted) {
8345 S.Diag(Loc: Subobj.Loc, DiagID: diag::note_defaulted_comparison_reference_member)
8346 << FD << RD;
8347 }
8348 return Result::deleted();
8349 }
8350
8351 // [...] Let xi be an lvalue denoting the ith element [...]
8352 OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue);
8353 Expr *Args[] = {&Xi, &Xi};
8354
8355 // All operators start by trying to apply that same operator recursively.
8356 OverloadedOperatorKind OO = FD->getOverloadedOperator();
8357 assert(OO != OO_None && "not an overloaded operator!");
8358 return visitBinaryOperator(OO, Args, Subobj);
8359 }
8360
8361 Result
8362 visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args,
8363 Subobject Subobj,
8364 OverloadCandidateSet *SpaceshipCandidates = nullptr) {
8365 // Note that there is no need to consider rewritten candidates here if
8366 // we've already found there is no viable 'operator<=>' candidate (and are
8367 // considering synthesizing a '<=>' from '==' and '<').
8368 OverloadCandidateSet CandidateSet(
8369 FD->getLocation(), OverloadCandidateSet::CSK_Operator,
8370 OverloadCandidateSet::OperatorRewriteInfo(
8371 OO, FD->getLocation(),
8372 /*AllowRewrittenCandidates=*/!SpaceshipCandidates));
8373
8374 /// C++2a [class.compare.default]p1 [P2002R0]:
8375 /// [...] the defaulted function itself is never a candidate for overload
8376 /// resolution [...]
8377 CandidateSet.exclude(F: FD);
8378
8379 if (Args[0]->getType()->isOverloadableType())
8380 S.LookupOverloadedBinOp(CandidateSet, Op: OO, Fns, Args);
8381 else
8382 // FIXME: We determine whether this is a valid expression by checking to
8383 // see if there's a viable builtin operator candidate for it. That isn't
8384 // really what the rules ask us to do, but should give the right results.
8385 S.AddBuiltinOperatorCandidates(Op: OO, OpLoc: FD->getLocation(), Args, CandidateSet);
8386
8387 Result R;
8388
8389 OverloadCandidateSet::iterator Best;
8390 switch (CandidateSet.BestViableFunction(S, Loc: FD->getLocation(), Best)) {
8391 case OR_Success: {
8392 // C++2a [class.compare.secondary]p2 [P2002R0]:
8393 // The operator function [...] is defined as deleted if [...] the
8394 // candidate selected by overload resolution is not a rewritten
8395 // candidate.
8396 if ((DCK == DefaultedComparisonKind::NotEqual ||
8397 DCK == DefaultedComparisonKind::Relational) &&
8398 !Best->RewriteKind) {
8399 if (Diagnose == ExplainDeleted) {
8400 if (Best->Function) {
8401 S.Diag(Loc: Best->Function->getLocation(),
8402 DiagID: diag::note_defaulted_comparison_not_rewritten_callee)
8403 << FD;
8404 } else {
8405 assert(Best->Conversions.size() == 2 &&
8406 Best->Conversions[0].isUserDefined() &&
8407 "non-user-defined conversion from class to built-in "
8408 "comparison");
8409 S.Diag(Loc: Best->Conversions[0]
8410 .UserDefined.FoundConversionFunction.getDecl()
8411 ->getLocation(),
8412 DiagID: diag::note_defaulted_comparison_not_rewritten_conversion)
8413 << FD;
8414 }
8415 }
8416 return Result::deleted();
8417 }
8418
8419 // Throughout C++2a [class.compare]: if overload resolution does not
8420 // result in a usable function, the candidate function is defined as
8421 // deleted. This requires that we selected an accessible function.
8422 //
8423 // Note that this only considers the access of the function when named
8424 // within the type of the subobject, and not the access path for any
8425 // derived-to-base conversion.
8426 CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl();
8427 if (ArgClass && Best->FoundDecl.getDecl() &&
8428 Best->FoundDecl.getDecl()->isCXXClassMember()) {
8429 QualType ObjectType = Subobj.Kind == Subobject::Member
8430 ? Args[0]->getType()
8431 : S.Context.getCanonicalTagType(TD: RD);
8432 if (!S.isMemberAccessibleForDeletion(
8433 NamingClass: ArgClass, Found: Best->FoundDecl, ObjectType, Loc: Subobj.Loc,
8434 Diag: Diagnose == ExplainDeleted
8435 ? S.PDiag(DiagID: diag::note_defaulted_comparison_inaccessible)
8436 << FD << Subobj.Kind << Subobj.Decl
8437 : S.PDiag()))
8438 return Result::deleted();
8439 }
8440
8441 bool NeedsDeducing =
8442 OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType();
8443
8444 if (FunctionDecl *BestFD = Best->Function) {
8445 // C++2a [class.compare.default]p3 [P2002R0]:
8446 // A defaulted comparison function is constexpr-compatible if
8447 // [...] no overlod resolution performed [...] results in a
8448 // non-constexpr function.
8449 assert(!BestFD->isDeleted() && "wrong overload resolution result");
8450 // If it's not constexpr, explain why not.
8451 if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) {
8452 if (Subobj.Kind != Subobject::CompleteObject)
8453 S.Diag(Loc: Subobj.Loc, DiagID: diag::note_defaulted_comparison_not_constexpr)
8454 << Subobj.Kind << Subobj.Decl;
8455 S.Diag(Loc: BestFD->getLocation(),
8456 DiagID: diag::note_defaulted_comparison_not_constexpr_here);
8457 // Bail out after explaining; we don't want any more notes.
8458 return Result::deleted();
8459 }
8460 R.Constexpr &= BestFD->isConstexpr();
8461
8462 if (NeedsDeducing) {
8463 // If any callee has an undeduced return type, deduce it now.
8464 // FIXME: It's not clear how a failure here should be handled. For
8465 // now, we produce an eager diagnostic, because that is forward
8466 // compatible with most (all?) other reasonable options.
8467 if (BestFD->getReturnType()->isUndeducedType() &&
8468 S.DeduceReturnType(FD: BestFD, Loc: FD->getLocation(),
8469 /*Diagnose=*/false)) {
8470 // Don't produce a duplicate error when asked to explain why the
8471 // comparison is deleted: we diagnosed that when initially checking
8472 // the defaulted operator.
8473 if (Diagnose == NoDiagnostics) {
8474 S.Diag(
8475 Loc: FD->getLocation(),
8476 DiagID: diag::err_defaulted_comparison_cannot_deduce_undeduced_auto)
8477 << Subobj.Kind << Subobj.Decl;
8478 S.Diag(
8479 Loc: Subobj.Loc,
8480 DiagID: diag::note_defaulted_comparison_cannot_deduce_undeduced_auto)
8481 << Subobj.Kind << Subobj.Decl;
8482 S.Diag(Loc: BestFD->getLocation(),
8483 DiagID: diag::note_defaulted_comparison_cannot_deduce_callee)
8484 << Subobj.Kind << Subobj.Decl;
8485 }
8486 return Result::deleted();
8487 }
8488 auto *Info = S.Context.CompCategories.lookupInfoForType(
8489 Ty: BestFD->getCallResultType());
8490 if (!Info) {
8491 if (Diagnose == ExplainDeleted) {
8492 S.Diag(Loc: Subobj.Loc, DiagID: diag::note_defaulted_comparison_cannot_deduce)
8493 << Subobj.Kind << Subobj.Decl
8494 << BestFD->getCallResultType().withoutLocalFastQualifiers();
8495 S.Diag(Loc: BestFD->getLocation(),
8496 DiagID: diag::note_defaulted_comparison_cannot_deduce_callee)
8497 << Subobj.Kind << Subobj.Decl;
8498 }
8499 return Result::deleted();
8500 }
8501 R.Category = Info->Kind;
8502 }
8503 } else {
8504 QualType T = Best->BuiltinParamTypes[0];
8505 assert(T == Best->BuiltinParamTypes[1] &&
8506 "builtin comparison for different types?");
8507 assert(Best->BuiltinParamTypes[2].isNull() &&
8508 "invalid builtin comparison");
8509
8510 // FIXME: If the type we deduced is a vector type, we mark the
8511 // comparison as deleted because we don't yet support this.
8512 if (isa<VectorType>(Val: T)) {
8513 if (Diagnose == ExplainDeleted) {
8514 S.Diag(Loc: FD->getLocation(),
8515 DiagID: diag::note_defaulted_comparison_vector_types)
8516 << FD;
8517 S.Diag(Loc: Subobj.Decl->getLocation(), DiagID: diag::note_declared_at);
8518 }
8519 return Result::deleted();
8520 }
8521
8522 if (NeedsDeducing) {
8523 std::optional<ComparisonCategoryType> Cat =
8524 getComparisonCategoryForBuiltinCmp(T);
8525 assert(Cat && "no category for builtin comparison?");
8526 R.Category = *Cat;
8527 }
8528 }
8529
8530 // Note that we might be rewriting to a different operator. That call is
8531 // not considered until we come to actually build the comparison function.
8532 break;
8533 }
8534
8535 case OR_Ambiguous:
8536 if (Diagnose == ExplainDeleted) {
8537 unsigned Kind = 0;
8538 if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship)
8539 Kind = OO == OO_EqualEqual ? 1 : 2;
8540 CandidateSet.NoteCandidates(
8541 PA: PartialDiagnosticAt(
8542 Subobj.Loc, S.PDiag(DiagID: diag::note_defaulted_comparison_ambiguous)
8543 << FD << Kind << Subobj.Kind << Subobj.Decl),
8544 S, OCD: OCD_AmbiguousCandidates, Args);
8545 }
8546 R = Result::deleted();
8547 break;
8548
8549 case OR_Deleted:
8550 if (Diagnose == ExplainDeleted) {
8551 if ((DCK == DefaultedComparisonKind::NotEqual ||
8552 DCK == DefaultedComparisonKind::Relational) &&
8553 !Best->RewriteKind) {
8554 S.Diag(Loc: Best->Function->getLocation(),
8555 DiagID: diag::note_defaulted_comparison_not_rewritten_callee)
8556 << FD;
8557 } else {
8558 S.Diag(Loc: Subobj.Loc,
8559 DiagID: diag::note_defaulted_comparison_calls_deleted)
8560 << FD << Subobj.Kind << Subobj.Decl;
8561 S.NoteDeletedFunction(FD: Best->Function);
8562 }
8563 }
8564 R = Result::deleted();
8565 break;
8566
8567 case OR_No_Viable_Function:
8568 // If there's no usable candidate, we're done unless we can rewrite a
8569 // '<=>' in terms of '==' and '<'.
8570 if (OO == OO_Spaceship &&
8571 S.Context.CompCategories.lookupInfoForType(Ty: FD->getReturnType())) {
8572 // For any kind of comparison category return type, we need a usable
8573 // '==' and a usable '<'.
8574 if (!R.add(R: visitBinaryOperator(OO: OO_EqualEqual, Args, Subobj,
8575 SpaceshipCandidates: &CandidateSet)))
8576 R.add(R: visitBinaryOperator(OO: OO_Less, Args, Subobj, SpaceshipCandidates: &CandidateSet));
8577 break;
8578 }
8579
8580 if (Diagnose == ExplainDeleted) {
8581 S.Diag(Loc: Subobj.Loc, DiagID: diag::note_defaulted_comparison_no_viable_function)
8582 << FD << (OO == OO_EqualEqual || OO == OO_ExclaimEqual)
8583 << Subobj.Kind << Subobj.Decl;
8584
8585 // For a three-way comparison, list both the candidates for the
8586 // original operator and the candidates for the synthesized operator.
8587 if (SpaceshipCandidates) {
8588 SpaceshipCandidates->NoteCandidates(
8589 S, Args,
8590 Cands: SpaceshipCandidates->CompleteCandidates(S, OCD: OCD_AllCandidates,
8591 Args, OpLoc: FD->getLocation()));
8592 S.Diag(Loc: Subobj.Loc,
8593 DiagID: diag::note_defaulted_comparison_no_viable_function_synthesized)
8594 << (OO == OO_EqualEqual ? 0 : 1);
8595 }
8596
8597 CandidateSet.NoteCandidates(
8598 S, Args,
8599 Cands: CandidateSet.CompleteCandidates(S, OCD: OCD_AllCandidates, Args,
8600 OpLoc: FD->getLocation()));
8601 }
8602 R = Result::deleted();
8603 break;
8604 }
8605
8606 return R;
8607 }
8608};
8609
8610/// A list of statements.
8611struct StmtListResult {
8612 bool IsInvalid = false;
8613 llvm::SmallVector<Stmt*, 16> Stmts;
8614
8615 bool add(const StmtResult &S) {
8616 IsInvalid |= S.isInvalid();
8617 if (IsInvalid)
8618 return true;
8619 Stmts.push_back(Elt: S.get());
8620 return false;
8621 }
8622};
8623
8624/// A visitor over the notional body of a defaulted comparison that synthesizes
8625/// the actual body.
8626class DefaultedComparisonSynthesizer
8627 : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer,
8628 StmtListResult, StmtResult,
8629 std::pair<ExprResult, ExprResult>> {
8630 SourceLocation Loc;
8631 unsigned ArrayDepth = 0;
8632
8633public:
8634 using Base = DefaultedComparisonVisitor;
8635 using ExprPair = std::pair<ExprResult, ExprResult>;
8636
8637 friend Base;
8638
8639 DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8640 DefaultedComparisonKind DCK,
8641 SourceLocation BodyLoc)
8642 : Base(S, RD, FD, DCK), Loc(BodyLoc) {}
8643
8644 /// Build a suitable function body for this defaulted comparison operator.
8645 StmtResult build() {
8646 Sema::CompoundScopeRAII CompoundScope(S);
8647
8648 StmtListResult Stmts = visit();
8649 if (Stmts.IsInvalid)
8650 return StmtError();
8651
8652 ExprResult RetVal;
8653 switch (DCK) {
8654 case DefaultedComparisonKind::None:
8655 llvm_unreachable("not a defaulted comparison");
8656
8657 case DefaultedComparisonKind::Equal: {
8658 // C++2a [class.eq]p3:
8659 // [...] compar[e] the corresponding elements [...] until the first
8660 // index i where xi == yi yields [...] false. If no such index exists,
8661 // V is true. Otherwise, V is false.
8662 //
8663 // Join the comparisons with '&&'s and return the result. Use a right
8664 // fold (traversing the conditions right-to-left), because that
8665 // short-circuits more naturally.
8666 auto OldStmts = std::move(Stmts.Stmts);
8667 Stmts.Stmts.clear();
8668 ExprResult CmpSoFar;
8669 // Finish a particular comparison chain.
8670 auto FinishCmp = [&] {
8671 if (Expr *Prior = CmpSoFar.get()) {
8672 // Convert the last expression to 'return ...;'
8673 if (RetVal.isUnset() && Stmts.Stmts.empty())
8674 RetVal = CmpSoFar;
8675 // Convert any prior comparison to 'if (!(...)) return false;'
8676 else if (Stmts.add(S: buildIfNotCondReturnFalse(Cond: Prior)))
8677 return true;
8678 CmpSoFar = ExprResult();
8679 }
8680 return false;
8681 };
8682 for (Stmt *EAsStmt : llvm::reverse(C&: OldStmts)) {
8683 Expr *E = dyn_cast<Expr>(Val: EAsStmt);
8684 if (!E) {
8685 // Found an array comparison.
8686 if (FinishCmp() || Stmts.add(S: EAsStmt))
8687 return StmtError();
8688 continue;
8689 }
8690
8691 if (CmpSoFar.isUnset()) {
8692 CmpSoFar = E;
8693 continue;
8694 }
8695 CmpSoFar = S.CreateBuiltinBinOp(OpLoc: Loc, Opc: BO_LAnd, LHSExpr: E, RHSExpr: CmpSoFar.get());
8696 if (CmpSoFar.isInvalid())
8697 return StmtError();
8698 }
8699 if (FinishCmp())
8700 return StmtError();
8701 std::reverse(first: Stmts.Stmts.begin(), last: Stmts.Stmts.end());
8702 // If no such index exists, V is true.
8703 if (RetVal.isUnset())
8704 RetVal = S.ActOnCXXBoolLiteral(OpLoc: Loc, Kind: tok::kw_true);
8705 break;
8706 }
8707
8708 case DefaultedComparisonKind::ThreeWay: {
8709 // Per C++2a [class.spaceship]p3, as a fallback add:
8710 // return static_cast<R>(std::strong_ordering::equal);
8711 QualType StrongOrdering = S.CheckComparisonCategoryType(
8712 Kind: ComparisonCategoryType::StrongOrdering, Loc,
8713 Usage: Sema::ComparisonCategoryUsage::DefaultedOperator);
8714 if (StrongOrdering.isNull())
8715 return StmtError();
8716 VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(Ty: StrongOrdering)
8717 .getValueInfo(ValueKind: ComparisonCategoryResult::Equal)
8718 ->VD;
8719 RetVal = getDecl(VD: EqualVD);
8720 if (RetVal.isInvalid())
8721 return StmtError();
8722 RetVal = buildStaticCastToR(E: RetVal.get());
8723 break;
8724 }
8725
8726 case DefaultedComparisonKind::NotEqual:
8727 case DefaultedComparisonKind::Relational:
8728 RetVal = cast<Expr>(Val: Stmts.Stmts.pop_back_val());
8729 break;
8730 }
8731
8732 // Build the final return statement.
8733 if (RetVal.isInvalid())
8734 return StmtError();
8735 StmtResult ReturnStmt = S.BuildReturnStmt(ReturnLoc: Loc, RetValExp: RetVal.get());
8736 if (ReturnStmt.isInvalid())
8737 return StmtError();
8738 Stmts.Stmts.push_back(Elt: ReturnStmt.get());
8739
8740 return S.ActOnCompoundStmt(L: Loc, R: Loc, Elts: Stmts.Stmts, /*IsStmtExpr=*/isStmtExpr: false);
8741 }
8742
8743private:
8744 ExprResult getDecl(ValueDecl *VD) {
8745 return S.BuildDeclarationNameExpr(
8746 SS: CXXScopeSpec(), NameInfo: DeclarationNameInfo(VD->getDeclName(), Loc), D: VD);
8747 }
8748
8749 ExprResult getParam(unsigned I) {
8750 ParmVarDecl *PD = FD->getParamDecl(i: I);
8751 return getDecl(VD: PD);
8752 }
8753
8754 ExprPair getCompleteObject() {
8755 unsigned Param = 0;
8756 ExprResult LHS;
8757 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: FD);
8758 MD && MD->isImplicitObjectMemberFunction()) {
8759 // LHS is '*this'.
8760 LHS = S.ActOnCXXThis(Loc);
8761 if (!LHS.isInvalid())
8762 LHS = S.CreateBuiltinUnaryOp(OpLoc: Loc, Opc: UO_Deref, InputExpr: LHS.get());
8763 } else {
8764 LHS = getParam(I: Param++);
8765 }
8766 ExprResult RHS = getParam(I: Param++);
8767 assert(Param == FD->getNumParams());
8768 return {LHS, RHS};
8769 }
8770
8771 ExprPair getBase(CXXBaseSpecifier *Base) {
8772 ExprPair Obj = getCompleteObject();
8773 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8774 return {ExprError(), ExprError()};
8775 CXXCastPath Path = {Base};
8776 const auto CastToBase = [&](Expr *E) {
8777 QualType ToType = S.Context.getQualifiedType(
8778 T: Base->getType(), Qs: E->getType().getQualifiers());
8779 return S.ImpCastExprToType(E, Type: ToType, CK: CK_DerivedToBase, VK: VK_LValue, BasePath: &Path);
8780 };
8781 return {CastToBase(Obj.first.get()), CastToBase(Obj.second.get())};
8782 }
8783
8784 ExprPair getField(FieldDecl *Field) {
8785 ExprPair Obj = getCompleteObject();
8786 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8787 return {ExprError(), ExprError()};
8788
8789 DeclAccessPair Found = DeclAccessPair::make(D: Field, AS: Field->getAccess());
8790 DeclarationNameInfo NameInfo(Field->getDeclName(), Loc);
8791 return {S.BuildFieldReferenceExpr(BaseExpr: Obj.first.get(), /*IsArrow=*/false, OpLoc: Loc,
8792 SS: CXXScopeSpec(), Field, FoundDecl: Found, MemberNameInfo: NameInfo),
8793 S.BuildFieldReferenceExpr(BaseExpr: Obj.second.get(), /*IsArrow=*/false, OpLoc: Loc,
8794 SS: CXXScopeSpec(), Field, FoundDecl: Found, MemberNameInfo: NameInfo)};
8795 }
8796
8797 // FIXME: When expanding a subobject, register a note in the code synthesis
8798 // stack to say which subobject we're comparing.
8799
8800 StmtResult buildIfNotCondReturnFalse(ExprResult Cond) {
8801 if (Cond.isInvalid())
8802 return StmtError();
8803
8804 ExprResult NotCond = S.CreateBuiltinUnaryOp(OpLoc: Loc, Opc: UO_LNot, InputExpr: Cond.get());
8805 if (NotCond.isInvalid())
8806 return StmtError();
8807
8808 ExprResult False = S.ActOnCXXBoolLiteral(OpLoc: Loc, Kind: tok::kw_false);
8809 assert(!False.isInvalid() && "should never fail");
8810 StmtResult ReturnFalse = S.BuildReturnStmt(ReturnLoc: Loc, RetValExp: False.get());
8811 if (ReturnFalse.isInvalid())
8812 return StmtError();
8813
8814 return S.ActOnIfStmt(IfLoc: Loc, StatementKind: IfStatementKind::Ordinary, LParenLoc: Loc, InitStmt: nullptr,
8815 Cond: S.ActOnCondition(S: nullptr, Loc, SubExpr: NotCond.get(),
8816 CK: Sema::ConditionKind::Boolean),
8817 RParenLoc: Loc, ThenVal: ReturnFalse.get(), ElseLoc: SourceLocation(), ElseVal: nullptr);
8818 }
8819
8820 StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size,
8821 ExprPair Subobj) {
8822 QualType SizeType = S.Context.getSizeType();
8823 Size = Size.zextOrTrunc(width: S.Context.getTypeSize(T: SizeType));
8824
8825 // Build 'size_t i$n = 0'.
8826 IdentifierInfo *IterationVarName = nullptr;
8827 {
8828 SmallString<8> Str;
8829 llvm::raw_svector_ostream OS(Str);
8830 OS << "i" << ArrayDepth;
8831 IterationVarName = &S.Context.Idents.get(Name: OS.str());
8832 }
8833 VarDecl *IterationVar = VarDecl::Create(
8834 C&: S.Context, DC: S.CurContext, StartLoc: Loc, IdLoc: Loc, Id: IterationVarName, T: SizeType,
8835 TInfo: S.Context.getTrivialTypeSourceInfo(T: SizeType, Loc), S: SC_None);
8836 llvm::APInt Zero(S.Context.getTypeSize(T: SizeType), 0);
8837 IterationVar->setInit(
8838 IntegerLiteral::Create(C: S.Context, V: Zero, type: SizeType, l: Loc));
8839 Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc);
8840
8841 auto IterRef = [&] {
8842 ExprResult Ref = S.BuildDeclarationNameExpr(
8843 SS: CXXScopeSpec(), NameInfo: DeclarationNameInfo(IterationVarName, Loc),
8844 D: IterationVar);
8845 assert(!Ref.isInvalid() && "can't reference our own variable?");
8846 return Ref.get();
8847 };
8848
8849 // Build 'i$n != Size'.
8850 ExprResult Cond = S.CreateBuiltinBinOp(
8851 OpLoc: Loc, Opc: BO_NE, LHSExpr: IterRef(),
8852 RHSExpr: IntegerLiteral::Create(C: S.Context, V: Size, type: SizeType, l: Loc));
8853 assert(!Cond.isInvalid() && "should never fail");
8854
8855 // Build '++i$n'.
8856 ExprResult Inc = S.CreateBuiltinUnaryOp(OpLoc: Loc, Opc: UO_PreInc, InputExpr: IterRef());
8857 assert(!Inc.isInvalid() && "should never fail");
8858
8859 // Build 'a[i$n]' and 'b[i$n]'.
8860 auto Index = [&](ExprResult E) {
8861 if (E.isInvalid())
8862 return ExprError();
8863 return S.CreateBuiltinArraySubscriptExpr(Base: E.get(), LLoc: Loc, Idx: IterRef(), RLoc: Loc);
8864 };
8865 Subobj.first = Index(Subobj.first);
8866 Subobj.second = Index(Subobj.second);
8867
8868 // Compare the array elements.
8869 ++ArrayDepth;
8870 StmtResult Substmt = visitSubobject(Type, Subobj);
8871 --ArrayDepth;
8872
8873 if (Substmt.isInvalid())
8874 return StmtError();
8875
8876 // For the inner level of an 'operator==', build 'if (!cmp) return false;'.
8877 // For outer levels or for an 'operator<=>' we already have a suitable
8878 // statement that returns as necessary.
8879 if (Expr *ElemCmp = dyn_cast<Expr>(Val: Substmt.get())) {
8880 assert(DCK == DefaultedComparisonKind::Equal &&
8881 "should have non-expression statement");
8882 Substmt = buildIfNotCondReturnFalse(Cond: ElemCmp);
8883 if (Substmt.isInvalid())
8884 return StmtError();
8885 }
8886
8887 // Build 'for (...) ...'
8888 return S.ActOnForStmt(ForLoc: Loc, LParenLoc: Loc, First: Init,
8889 Second: S.ActOnCondition(S: nullptr, Loc, SubExpr: Cond.get(),
8890 CK: Sema::ConditionKind::Boolean),
8891 Third: S.MakeFullDiscardedValueExpr(Arg: Inc.get()), RParenLoc: Loc,
8892 Body: Substmt.get());
8893 }
8894
8895 StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) {
8896 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8897 return StmtError();
8898
8899 OverloadedOperatorKind OO = FD->getOverloadedOperator();
8900 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(OO);
8901 ExprResult Op;
8902 if (Type->isOverloadableType())
8903 Op = S.CreateOverloadedBinOp(OpLoc: Loc, Opc, Fns, LHS: Obj.first.get(),
8904 RHS: Obj.second.get(), /*PerformADL=*/RequiresADL: true,
8905 /*AllowRewrittenCandidates=*/true, DefaultedFn: FD);
8906 else
8907 Op = S.CreateBuiltinBinOp(OpLoc: Loc, Opc, LHSExpr: Obj.first.get(), RHSExpr: Obj.second.get());
8908 if (Op.isInvalid())
8909 return StmtError();
8910
8911 switch (DCK) {
8912 case DefaultedComparisonKind::None:
8913 llvm_unreachable("not a defaulted comparison");
8914
8915 case DefaultedComparisonKind::Equal:
8916 // Per C++2a [class.eq]p2, each comparison is individually contextually
8917 // converted to bool.
8918 Op = S.PerformContextuallyConvertToBool(From: Op.get());
8919 if (Op.isInvalid())
8920 return StmtError();
8921 return Op.get();
8922
8923 case DefaultedComparisonKind::ThreeWay: {
8924 // Per C++2a [class.spaceship]p3, form:
8925 // if (R cmp = static_cast<R>(op); cmp != 0)
8926 // return cmp;
8927 QualType R = FD->getReturnType();
8928 Op = buildStaticCastToR(E: Op.get());
8929 if (Op.isInvalid())
8930 return StmtError();
8931
8932 // R cmp = ...;
8933 IdentifierInfo *Name = &S.Context.Idents.get(Name: "cmp");
8934 VarDecl *VD =
8935 VarDecl::Create(C&: S.Context, DC: S.CurContext, StartLoc: Loc, IdLoc: Loc, Id: Name, T: R,
8936 TInfo: S.Context.getTrivialTypeSourceInfo(T: R, Loc), S: SC_None);
8937 S.AddInitializerToDecl(dcl: VD, init: Op.get(), /*DirectInit=*/false);
8938 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc);
8939
8940 // cmp != 0
8941 ExprResult VDRef = getDecl(VD);
8942 if (VDRef.isInvalid())
8943 return StmtError();
8944 llvm::APInt ZeroVal(S.Context.getIntWidth(T: S.Context.IntTy), 0);
8945 Expr *Zero =
8946 IntegerLiteral::Create(C: S.Context, V: ZeroVal, type: S.Context.IntTy, l: Loc);
8947 ExprResult Comp;
8948 if (VDRef.get()->getType()->isOverloadableType())
8949 Comp = S.CreateOverloadedBinOp(OpLoc: Loc, Opc: BO_NE, Fns, LHS: VDRef.get(), RHS: Zero, RequiresADL: true,
8950 AllowRewrittenCandidates: true, DefaultedFn: FD);
8951 else
8952 Comp = S.CreateBuiltinBinOp(OpLoc: Loc, Opc: BO_NE, LHSExpr: VDRef.get(), RHSExpr: Zero);
8953 if (Comp.isInvalid())
8954 return StmtError();
8955 Sema::ConditionResult Cond = S.ActOnCondition(
8956 S: nullptr, Loc, SubExpr: Comp.get(), CK: Sema::ConditionKind::Boolean);
8957 if (Cond.isInvalid())
8958 return StmtError();
8959
8960 // return cmp;
8961 VDRef = getDecl(VD);
8962 if (VDRef.isInvalid())
8963 return StmtError();
8964 StmtResult ReturnStmt = S.BuildReturnStmt(ReturnLoc: Loc, RetValExp: VDRef.get());
8965 if (ReturnStmt.isInvalid())
8966 return StmtError();
8967
8968 // if (...)
8969 return S.ActOnIfStmt(IfLoc: Loc, StatementKind: IfStatementKind::Ordinary, LParenLoc: Loc, InitStmt, Cond,
8970 RParenLoc: Loc, ThenVal: ReturnStmt.get(),
8971 /*ElseLoc=*/SourceLocation(), /*Else=*/ElseVal: nullptr);
8972 }
8973
8974 case DefaultedComparisonKind::NotEqual:
8975 case DefaultedComparisonKind::Relational:
8976 // C++2a [class.compare.secondary]p2:
8977 // Otherwise, the operator function yields x @ y.
8978 return Op.get();
8979 }
8980 llvm_unreachable("");
8981 }
8982
8983 /// Build "static_cast<R>(E)".
8984 ExprResult buildStaticCastToR(Expr *E) {
8985 QualType R = FD->getReturnType();
8986 assert(!R->isUndeducedType() && "type should have been deduced already");
8987
8988 // Don't bother forming a no-op cast in the common case.
8989 if (E->isPRValue() && S.Context.hasSameType(T1: E->getType(), T2: R))
8990 return E;
8991 return S.BuildCXXNamedCast(OpLoc: Loc, Kind: tok::kw_static_cast,
8992 Ty: S.Context.getTrivialTypeSourceInfo(T: R, Loc), E,
8993 AngleBrackets: SourceRange(Loc, Loc), Parens: SourceRange(Loc, Loc));
8994 }
8995};
8996}
8997
8998/// Perform the unqualified lookups that might be needed to form a defaulted
8999/// comparison function for the given operator.
9000static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S,
9001 UnresolvedSetImpl &Operators,
9002 OverloadedOperatorKind Op) {
9003 auto Lookup = [&](OverloadedOperatorKind OO) {
9004 Self.LookupOverloadedOperatorName(Op: OO, S, Functions&: Operators);
9005 };
9006
9007 // Every defaulted operator looks up itself.
9008 Lookup(Op);
9009 // ... and the rewritten form of itself, if any.
9010 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Kind: Op))
9011 Lookup(ExtraOp);
9012
9013 // For 'operator<=>', we also form a 'cmp != 0' expression, and might
9014 // synthesize a three-way comparison from '<' and '=='. In a dependent
9015 // context, we also need to look up '==' in case we implicitly declare a
9016 // defaulted 'operator=='.
9017 if (Op == OO_Spaceship) {
9018 Lookup(OO_ExclaimEqual);
9019 Lookup(OO_Less);
9020 Lookup(OO_EqualEqual);
9021 }
9022}
9023
9024bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *FD,
9025 DefaultedComparisonKind DCK) {
9026 assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison");
9027
9028 // Perform any unqualified lookups we're going to need to default this
9029 // function.
9030 if (S) {
9031 UnresolvedSet<32> Operators;
9032 lookupOperatorsForDefaultedComparison(Self&: *this, S, Operators,
9033 Op: FD->getOverloadedOperator());
9034 FD->setDefaultedOrDeletedInfo(
9035 FunctionDecl::DefaultedOrDeletedFunctionInfo::Create(
9036 Context, Lookups: Operators.pairs(), FPFeatures: CurFPFeatureOverrides()));
9037 }
9038
9039 // C++2a [class.compare.default]p1:
9040 // A defaulted comparison operator function for some class C shall be a
9041 // non-template function declared in the member-specification of C that is
9042 // -- a non-static const non-volatile member of C having one parameter of
9043 // type const C& and either no ref-qualifier or the ref-qualifier &, or
9044 // -- a friend of C having two parameters of type const C& or two
9045 // parameters of type C.
9046
9047 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: FD->getLexicalDeclContext());
9048 bool IsMethod = isa<CXXMethodDecl>(Val: FD);
9049 if (IsMethod) {
9050 auto *MD = cast<CXXMethodDecl>(Val: FD);
9051 assert(!MD->isStatic() && "comparison function cannot be a static member");
9052
9053 if (MD->getRefQualifier() == RQ_RValue) {
9054 Diag(Loc: MD->getLocation(), DiagID: diag::err_ref_qualifier_comparison_operator);
9055
9056 // Remove the ref qualifier to recover.
9057 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
9058 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9059 EPI.RefQualifier = RQ_None;
9060 MD->setType(Context.getFunctionType(ResultTy: FPT->getReturnType(),
9061 Args: FPT->getParamTypes(), EPI));
9062 }
9063
9064 // If we're out-of-class, this is the class we're comparing.
9065 if (!RD)
9066 RD = MD->getParent();
9067 QualType T = MD->getFunctionObjectParameterReferenceType();
9068 if (!T.getNonReferenceType().isConstQualified() &&
9069 (MD->isImplicitObjectMemberFunction() || T->isLValueReferenceType())) {
9070 SourceLocation Loc, InsertLoc;
9071 if (MD->isExplicitObjectMemberFunction()) {
9072 Loc = MD->getParamDecl(i: 0)->getBeginLoc();
9073 InsertLoc = getLocForEndOfToken(
9074 Loc: MD->getParamDecl(i: 0)->getExplicitObjectParamThisLoc());
9075 } else {
9076 Loc = MD->getLocation();
9077 if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc())
9078 InsertLoc = getLocForEndOfToken(Loc: Loc.getRParenLoc());
9079 }
9080 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
9081 // corresponding defaulted 'operator<=>' already.
9082 if (!MD->isImplicit()) {
9083 Diag(Loc, DiagID: diag::err_defaulted_comparison_non_const)
9084 << (int)DCK << FixItHint::CreateInsertion(InsertionLoc: InsertLoc, Code: " const");
9085 }
9086
9087 // Add the 'const' to the type to recover.
9088 if (MD->isExplicitObjectMemberFunction()) {
9089 assert(T->isLValueReferenceType());
9090 MD->getParamDecl(i: 0)->setType(Context.getLValueReferenceType(
9091 T: T.getNonReferenceType().withConst()));
9092 } else {
9093 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
9094 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9095 EPI.TypeQuals.addConst();
9096 MD->setType(Context.getFunctionType(ResultTy: FPT->getReturnType(),
9097 Args: FPT->getParamTypes(), EPI));
9098 }
9099 }
9100
9101 if (MD->isVolatile()) {
9102 Diag(Loc: MD->getLocation(), DiagID: diag::err_volatile_comparison_operator);
9103
9104 // Remove the 'volatile' from the type to recover.
9105 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
9106 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9107 EPI.TypeQuals.removeVolatile();
9108 MD->setType(Context.getFunctionType(ResultTy: FPT->getReturnType(),
9109 Args: FPT->getParamTypes(), EPI));
9110 }
9111 }
9112
9113 if ((FD->getNumParams() -
9114 (unsigned)FD->hasCXXExplicitFunctionObjectParameter()) !=
9115 (IsMethod ? 1 : 2)) {
9116 // Let's not worry about using a variadic template pack here -- who would do
9117 // such a thing?
9118 Diag(Loc: FD->getLocation(), DiagID: diag::err_defaulted_comparison_num_args)
9119 << int(IsMethod) << int(DCK);
9120 return true;
9121 }
9122
9123 const ParmVarDecl *KnownParm = nullptr;
9124 for (const ParmVarDecl *Param : FD->parameters()) {
9125 QualType ParmTy = Param->getType();
9126 if (!KnownParm) {
9127 auto CTy = ParmTy;
9128 // Is it `T const &`?
9129 bool Ok = !IsMethod || FD->hasCXXExplicitFunctionObjectParameter();
9130 QualType ExpectedTy;
9131 if (RD)
9132 ExpectedTy = Context.getCanonicalTagType(TD: RD);
9133 if (auto *Ref = CTy->getAs<LValueReferenceType>()) {
9134 CTy = Ref->getPointeeType();
9135 if (RD)
9136 ExpectedTy.addConst();
9137 Ok = true;
9138 }
9139
9140 // Is T a class?
9141 if (RD) {
9142 Ok &= RD->isDependentType() || Context.hasSameType(T1: CTy, T2: ExpectedTy);
9143 } else {
9144 RD = CTy->getAsCXXRecordDecl();
9145 Ok &= RD != nullptr;
9146 }
9147
9148 if (Ok) {
9149 KnownParm = Param;
9150 } else {
9151 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
9152 // corresponding defaulted 'operator<=>' already.
9153 if (!FD->isImplicit()) {
9154 if (RD) {
9155 CanQualType PlainTy = Context.getCanonicalTagType(TD: RD);
9156 QualType RefTy =
9157 Context.getLValueReferenceType(T: PlainTy.withConst());
9158 Diag(Loc: FD->getLocation(), DiagID: diag::err_defaulted_comparison_param)
9159 << int(DCK) << ParmTy << RefTy << int(!IsMethod) << PlainTy
9160 << Param->getSourceRange();
9161 } else {
9162 assert(!IsMethod && "should know expected type for method");
9163 Diag(Loc: FD->getLocation(),
9164 DiagID: diag::err_defaulted_comparison_param_unknown)
9165 << int(DCK) << ParmTy << Param->getSourceRange();
9166 }
9167 }
9168 return true;
9169 }
9170 } else if (!Context.hasSameType(T1: KnownParm->getType(), T2: ParmTy)) {
9171 Diag(Loc: FD->getLocation(), DiagID: diag::err_defaulted_comparison_param_mismatch)
9172 << int(DCK) << KnownParm->getType() << KnownParm->getSourceRange()
9173 << ParmTy << Param->getSourceRange();
9174 return true;
9175 }
9176 }
9177
9178 assert(RD && "must have determined class");
9179 if (IsMethod) {
9180 } else if (isa<CXXRecordDecl>(Val: FD->getLexicalDeclContext())) {
9181 // In-class, must be a friend decl.
9182 assert(FD->getFriendObjectKind() && "expected a friend declaration");
9183 } else {
9184 // Out of class, require the defaulted comparison to be a friend (of a
9185 // complete type, per CWG2547).
9186 if (RequireCompleteType(Loc: FD->getLocation(), T: Context.getCanonicalTagType(TD: RD),
9187 DiagID: diag::err_defaulted_comparison_not_friend, Args: int(DCK),
9188 Args: int(1)))
9189 return true;
9190
9191 if (llvm::none_of(Range: RD->friends(), P: [&](const FriendDecl *F) {
9192 return declaresSameEntity(D1: F->getFriendDecl(), D2: FD);
9193 })) {
9194 Diag(Loc: FD->getLocation(), DiagID: diag::err_defaulted_comparison_not_friend)
9195 << int(DCK) << int(0) << RD;
9196 Diag(Loc: RD->getCanonicalDecl()->getLocation(), DiagID: diag::note_declared_at);
9197 return true;
9198 }
9199 }
9200
9201 // C++2a [class.eq]p1, [class.rel]p1:
9202 // A [defaulted comparison other than <=>] shall have a declared return
9203 // type bool.
9204 if (DCK != DefaultedComparisonKind::ThreeWay &&
9205 !FD->getDeclaredReturnType()->isDependentType() &&
9206 !Context.hasSameType(T1: FD->getDeclaredReturnType(), T2: Context.BoolTy)) {
9207 Diag(Loc: FD->getLocation(), DiagID: diag::err_defaulted_comparison_return_type_not_bool)
9208 << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy
9209 << FD->getReturnTypeSourceRange();
9210 return true;
9211 }
9212 // C++2a [class.spaceship]p2 [P2002R0]:
9213 // Let R be the declared return type [...]. If R is auto, [...]. Otherwise,
9214 // R shall not contain a placeholder type.
9215 if (QualType RT = FD->getDeclaredReturnType();
9216 DCK == DefaultedComparisonKind::ThreeWay &&
9217 RT->getContainedDeducedType() &&
9218 (!Context.hasSameType(T1: RT, T2: Context.getAutoDeductType()) ||
9219 RT->getContainedAutoType()->isConstrained())) {
9220 Diag(Loc: FD->getLocation(),
9221 DiagID: diag::err_defaulted_comparison_deduced_return_type_not_auto)
9222 << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy
9223 << FD->getReturnTypeSourceRange();
9224 return true;
9225 }
9226
9227 // For a defaulted function in a dependent class, defer all remaining checks
9228 // until instantiation.
9229 if (RD->isDependentType())
9230 return false;
9231
9232 // Determine whether the function should be defined as deleted.
9233 DefaultedComparisonInfo Info =
9234 DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit();
9235
9236 bool First = FD == FD->getCanonicalDecl();
9237
9238 if (!First) {
9239 if (Info.Deleted) {
9240 // C++11 [dcl.fct.def.default]p4:
9241 // [For a] user-provided explicitly-defaulted function [...] if such a
9242 // function is implicitly defined as deleted, the program is ill-formed.
9243 //
9244 // This is really just a consequence of the general rule that you can
9245 // only delete a function on its first declaration.
9246 Diag(Loc: FD->getLocation(), DiagID: diag::err_non_first_default_compare_deletes)
9247 << FD->isImplicit() << (int)DCK;
9248 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9249 DefaultedComparisonAnalyzer::ExplainDeleted)
9250 .visit();
9251 return true;
9252 }
9253 if (isa<CXXRecordDecl>(Val: FD->getLexicalDeclContext())) {
9254 // C++20 [class.compare.default]p1:
9255 // [...] A definition of a comparison operator as defaulted that appears
9256 // in a class shall be the first declaration of that function.
9257 Diag(Loc: FD->getLocation(), DiagID: diag::err_non_first_default_compare_in_class)
9258 << (int)DCK;
9259 Diag(Loc: FD->getCanonicalDecl()->getLocation(),
9260 DiagID: diag::note_previous_declaration);
9261 return true;
9262 }
9263 }
9264
9265 // If we want to delete the function, then do so; there's nothing else to
9266 // check in that case.
9267 if (Info.Deleted) {
9268 SetDeclDeleted(dcl: FD, DelLoc: FD->getLocation());
9269 if (!inTemplateInstantiation() && !FD->isImplicit()) {
9270 Diag(Loc: FD->getLocation(), DiagID: diag::warn_defaulted_comparison_deleted)
9271 << (int)DCK;
9272 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9273 DefaultedComparisonAnalyzer::ExplainDeleted)
9274 .visit();
9275 if (FD->getDefaultLoc().isValid())
9276 Diag(Loc: FD->getDefaultLoc(), DiagID: diag::note_replace_equals_default_to_delete)
9277 << FixItHint::CreateReplacement(RemoveRange: FD->getDefaultLoc(), Code: "delete");
9278 }
9279 return false;
9280 }
9281
9282 // C++2a [class.spaceship]p2:
9283 // The return type is deduced as the common comparison type of R0, R1, ...
9284 if (DCK == DefaultedComparisonKind::ThreeWay &&
9285 FD->getDeclaredReturnType()->isUndeducedAutoType()) {
9286 SourceLocation RetLoc = FD->getReturnTypeSourceRange().getBegin();
9287 if (RetLoc.isInvalid())
9288 RetLoc = FD->getBeginLoc();
9289 // FIXME: Should we really care whether we have the complete type and the
9290 // 'enumerator' constants here? A forward declaration seems sufficient.
9291 QualType Cat = CheckComparisonCategoryType(
9292 Kind: Info.Category, Loc: RetLoc, Usage: ComparisonCategoryUsage::DefaultedOperator);
9293 if (Cat.isNull())
9294 return true;
9295 Context.adjustDeducedFunctionResultType(
9296 FD, ResultType: SubstAutoType(TypeWithAuto: FD->getDeclaredReturnType(), Replacement: Cat));
9297 }
9298
9299 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
9300 // An explicitly-defaulted function that is not defined as deleted may be
9301 // declared constexpr or consteval only if it is constexpr-compatible.
9302 // C++2a [class.compare.default]p3 [P2002R0]:
9303 // A defaulted comparison function is constexpr-compatible if it satisfies
9304 // the requirements for a constexpr function [...]
9305 // The only relevant requirements are that the parameter and return types are
9306 // literal types. The remaining conditions are checked by the analyzer.
9307 //
9308 // We support P2448R2 in language modes earlier than C++23 as an extension.
9309 // The concept of constexpr-compatible was removed.
9310 // C++23 [dcl.fct.def.default]p3 [P2448R2]
9311 // A function explicitly defaulted on its first declaration is implicitly
9312 // inline, and is implicitly constexpr if it is constexpr-suitable.
9313 // C++23 [dcl.constexpr]p3
9314 // A function is constexpr-suitable if
9315 // - it is not a coroutine, and
9316 // - if the function is a constructor or destructor, its class does not
9317 // have any virtual base classes.
9318 if (FD->isConstexpr()) {
9319 if (!getLangOpts().CPlusPlus23 &&
9320 CheckConstexprReturnType(SemaRef&: *this, FD, Kind: CheckConstexprKind::Diagnose) &&
9321 CheckConstexprParameterTypes(SemaRef&: *this, FD, Kind: CheckConstexprKind::Diagnose) &&
9322 !Info.Constexpr) {
9323 Diag(Loc: FD->getBeginLoc(), DiagID: diag::err_defaulted_comparison_constexpr_mismatch)
9324 << FD->isImplicit() << (int)DCK << FD->isConsteval();
9325 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9326 DefaultedComparisonAnalyzer::ExplainConstexpr)
9327 .visit();
9328 }
9329 }
9330
9331 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
9332 // If a constexpr-compatible function is explicitly defaulted on its first
9333 // declaration, it is implicitly considered to be constexpr.
9334 // FIXME: Only applying this to the first declaration seems problematic, as
9335 // simple reorderings can affect the meaning of the program.
9336 if (First && !FD->isConstexpr() && Info.Constexpr)
9337 FD->setConstexprKind(ConstexprSpecKind::Constexpr);
9338
9339 // C++2a [except.spec]p3:
9340 // If a declaration of a function does not have a noexcept-specifier
9341 // [and] is defaulted on its first declaration, [...] the exception
9342 // specification is as specified below
9343 if (FD->getExceptionSpecType() == EST_None) {
9344 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9345 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9346 EPI.ExceptionSpec.Type = EST_Unevaluated;
9347 EPI.ExceptionSpec.SourceDecl = FD;
9348 FD->setType(Context.getFunctionType(ResultTy: FPT->getReturnType(),
9349 Args: FPT->getParamTypes(), EPI));
9350 }
9351
9352 return false;
9353}
9354
9355void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
9356 FunctionDecl *Spaceship) {
9357 Sema::CodeSynthesisContext Ctx;
9358 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison;
9359 Ctx.PointOfInstantiation = Spaceship->getEndLoc();
9360 Ctx.Entity = Spaceship;
9361 pushCodeSynthesisContext(Ctx);
9362
9363 if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship))
9364 EqualEqual->setImplicit();
9365
9366 popCodeSynthesisContext();
9367}
9368
9369void Sema::DefineDefaultedComparison(SourceLocation UseLoc, FunctionDecl *FD,
9370 DefaultedComparisonKind DCK) {
9371 assert(FD->isDefaulted() && !FD->isDeleted() &&
9372 !FD->doesThisDeclarationHaveABody());
9373 if (FD->willHaveBody() || FD->isInvalidDecl())
9374 return;
9375
9376 SynthesizedFunctionScope Scope(*this, FD);
9377
9378 // Add a context note for diagnostics produced after this point.
9379 Scope.addContextNote(UseLoc);
9380
9381 DefaultedFunctionFPFeaturesRAII RestoreFP(*this, FD);
9382
9383 {
9384 // Build and set up the function body.
9385 // The first parameter has type maybe-ref-to maybe-const T, use that to get
9386 // the type of the class being compared.
9387 auto PT = FD->getParamDecl(i: 0)->getType();
9388 CXXRecordDecl *RD = PT.getNonReferenceType()->getAsCXXRecordDecl();
9389 SourceLocation BodyLoc =
9390 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
9391 StmtResult Body =
9392 DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build();
9393 if (Body.isInvalid()) {
9394 FD->setInvalidDecl();
9395 return;
9396 }
9397 FD->setBody(Body.get());
9398 FD->markUsed(C&: Context);
9399 }
9400
9401 // The exception specification is needed because we are defining the
9402 // function. Note that this will reuse the body we just built.
9403 ResolveExceptionSpec(Loc: UseLoc, FPT: FD->getType()->castAs<FunctionProtoType>());
9404
9405 if (ASTMutationListener *L = getASTMutationListener())
9406 L->CompletedImplicitDefinition(D: FD);
9407}
9408
9409static Sema::ImplicitExceptionSpecification
9410ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
9411 FunctionDecl *FD,
9412 DefaultedComparisonKind DCK) {
9413 ComputingExceptionSpec CES(S, FD, Loc);
9414 Sema::ImplicitExceptionSpecification ExceptSpec(S);
9415
9416 if (FD->isInvalidDecl())
9417 return ExceptSpec;
9418
9419 // The common case is that we just defined the comparison function. In that
9420 // case, just look at whether the body can throw.
9421 if (FD->hasBody()) {
9422 ExceptSpec.CalledStmt(S: FD->getBody());
9423 } else {
9424 // Otherwise, build a body so we can check it. This should ideally only
9425 // happen when we're not actually marking the function referenced. (This is
9426 // only really important for efficiency: we don't want to build and throw
9427 // away bodies for comparison functions more than we strictly need to.)
9428
9429 // Pretend to synthesize the function body in an unevaluated context.
9430 // Note that we can't actually just go ahead and define the function here:
9431 // we are not permitted to mark its callees as referenced.
9432 Sema::SynthesizedFunctionScope Scope(S, FD);
9433 EnterExpressionEvaluationContext Context(
9434 S, Sema::ExpressionEvaluationContext::Unevaluated);
9435
9436 CXXRecordDecl *RD =
9437 cast<CXXRecordDecl>(Val: FD->getFriendObjectKind() == Decl::FOK_None
9438 ? FD->getDeclContext()
9439 : FD->getLexicalDeclContext());
9440 SourceLocation BodyLoc =
9441 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
9442 StmtResult Body =
9443 DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build();
9444 if (!Body.isInvalid())
9445 ExceptSpec.CalledStmt(S: Body.get());
9446
9447 // FIXME: Can we hold onto this body and just transform it to potentially
9448 // evaluated when we're asked to define the function rather than rebuilding
9449 // it? Either that, or we should only build the bits of the body that we
9450 // need (the expressions, not the statements).
9451 }
9452
9453 return ExceptSpec;
9454}
9455
9456void Sema::CheckDelayedMemberExceptionSpecs() {
9457 decltype(DelayedOverridingExceptionSpecChecks) Overriding;
9458 decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
9459
9460 std::swap(LHS&: Overriding, RHS&: DelayedOverridingExceptionSpecChecks);
9461 std::swap(LHS&: Equivalent, RHS&: DelayedEquivalentExceptionSpecChecks);
9462
9463 // Perform any deferred checking of exception specifications for virtual
9464 // destructors.
9465 for (auto &Check : Overriding)
9466 CheckOverridingFunctionExceptionSpec(New: Check.first, Old: Check.second);
9467
9468 // Perform any deferred checking of exception specifications for befriended
9469 // special members.
9470 for (auto &Check : Equivalent)
9471 CheckEquivalentExceptionSpec(Old: Check.second, New: Check.first);
9472}
9473
9474namespace {
9475/// CRTP base class for visiting operations performed by a special member
9476/// function (or inherited constructor).
9477template<typename Derived>
9478struct SpecialMemberVisitor {
9479 Sema &S;
9480 CXXMethodDecl *MD;
9481 CXXSpecialMemberKind CSM;
9482 Sema::InheritedConstructorInfo *ICI;
9483
9484 // Properties of the special member, computed for convenience.
9485 bool IsConstructor = false, IsAssignment = false, ConstArg = false;
9486
9487 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, CXXSpecialMemberKind CSM,
9488 Sema::InheritedConstructorInfo *ICI)
9489 : S(S), MD(MD), CSM(CSM), ICI(ICI) {
9490 switch (CSM) {
9491 case CXXSpecialMemberKind::DefaultConstructor:
9492 case CXXSpecialMemberKind::CopyConstructor:
9493 case CXXSpecialMemberKind::MoveConstructor:
9494 IsConstructor = true;
9495 break;
9496 case CXXSpecialMemberKind::CopyAssignment:
9497 case CXXSpecialMemberKind::MoveAssignment:
9498 IsAssignment = true;
9499 break;
9500 case CXXSpecialMemberKind::Destructor:
9501 break;
9502 case CXXSpecialMemberKind::Invalid:
9503 llvm_unreachable("invalid special member kind");
9504 }
9505
9506 if (MD->getNumExplicitParams()) {
9507 if (const ReferenceType *RT =
9508 MD->getNonObjectParameter(I: 0)->getType()->getAs<ReferenceType>())
9509 ConstArg = RT->getPointeeType().isConstQualified();
9510 }
9511 }
9512
9513 Derived &getDerived() { return static_cast<Derived&>(*this); }
9514
9515 /// Is this a "move" special member?
9516 bool isMove() const {
9517 return CSM == CXXSpecialMemberKind::MoveConstructor ||
9518 CSM == CXXSpecialMemberKind::MoveAssignment;
9519 }
9520
9521 /// Look up the corresponding special member in the given class.
9522 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
9523 unsigned Quals, bool IsMutable) {
9524 return lookupCallFromSpecialMember(S, Class, CSM, FieldQuals: Quals,
9525 ConstRHS: ConstArg && !IsMutable);
9526 }
9527
9528 /// Look up the constructor for the specified base class to see if it's
9529 /// overridden due to this being an inherited constructor.
9530 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
9531 if (!ICI)
9532 return {};
9533 assert(CSM == CXXSpecialMemberKind::DefaultConstructor);
9534 auto *BaseCtor =
9535 cast<CXXConstructorDecl>(Val: MD)->getInheritedConstructor().getConstructor();
9536 if (auto *MD = ICI->findConstructorForBase(Base: Class, Ctor: BaseCtor).first)
9537 return MD;
9538 return {};
9539 }
9540
9541 /// A base or member subobject.
9542 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
9543
9544 /// Get the location to use for a subobject in diagnostics.
9545 static SourceLocation getSubobjectLoc(Subobject Subobj) {
9546 // FIXME: For an indirect virtual base, the direct base leading to
9547 // the indirect virtual base would be a more useful choice.
9548 if (auto *B = dyn_cast<CXXBaseSpecifier *>(Val&: Subobj))
9549 return B->getBaseTypeLoc();
9550 else
9551 return cast<FieldDecl *>(Val&: Subobj)->getLocation();
9552 }
9553
9554 enum BasesToVisit {
9555 /// Visit all non-virtual (direct) bases.
9556 VisitNonVirtualBases,
9557 /// Visit all direct bases, virtual or not.
9558 VisitDirectBases,
9559 /// Visit all non-virtual bases, and all virtual bases if the class
9560 /// is not abstract.
9561 VisitPotentiallyConstructedBases,
9562 /// Visit all direct or virtual bases.
9563 VisitAllBases
9564 };
9565
9566 // Visit the bases and members of the class.
9567 bool visit(BasesToVisit Bases) {
9568 CXXRecordDecl *RD = MD->getParent();
9569
9570 if (Bases == VisitPotentiallyConstructedBases)
9571 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
9572
9573 for (auto &B : RD->bases())
9574 if ((Bases == VisitDirectBases || !B.isVirtual()) &&
9575 getDerived().visitBase(&B))
9576 return true;
9577
9578 if (Bases == VisitAllBases)
9579 for (auto &B : RD->vbases())
9580 if (getDerived().visitBase(&B))
9581 return true;
9582
9583 for (auto *F : RD->fields())
9584 if (!F->isInvalidDecl() && !F->isUnnamedBitField() &&
9585 getDerived().visitField(F))
9586 return true;
9587
9588 return false;
9589 }
9590};
9591}
9592
9593namespace {
9594struct SpecialMemberDeletionInfo
9595 : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
9596 bool Diagnose;
9597
9598 SourceLocation Loc;
9599
9600 bool AllFieldsAreConst;
9601
9602 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
9603 CXXSpecialMemberKind CSM,
9604 Sema::InheritedConstructorInfo *ICI, bool Diagnose)
9605 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
9606 Loc(MD->getLocation()), AllFieldsAreConst(true) {}
9607
9608 bool inUnion() const { return MD->getParent()->isUnion(); }
9609
9610 CXXSpecialMemberKind getEffectiveCSM() {
9611 return ICI ? CXXSpecialMemberKind::Invalid : CSM;
9612 }
9613
9614 bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
9615
9616 bool shouldDeleteForVariantPtrAuthMember(const FieldDecl *FD);
9617
9618 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
9619 bool visitField(FieldDecl *Field) { return shouldDeleteForField(FD: Field); }
9620
9621 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
9622 bool shouldDeleteForField(FieldDecl *FD);
9623 bool shouldDeleteForAllConstMembers();
9624
9625 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
9626 unsigned Quals);
9627 bool shouldDeleteForSubobjectCall(Subobject Subobj,
9628 Sema::SpecialMemberOverloadResult SMOR,
9629 bool IsDtorCallInCtor);
9630
9631 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
9632};
9633}
9634
9635/// Is the given special member inaccessible when used on the given
9636/// sub-object.
9637bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
9638 CXXMethodDecl *target) {
9639 /// If we're operating on a base class, the object type is the
9640 /// type of this special member.
9641 CanQualType objectTy;
9642 AccessSpecifier access = target->getAccess();
9643 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
9644 objectTy = S.Context.getCanonicalTagType(TD: MD->getParent());
9645 access = CXXRecordDecl::MergeAccess(PathAccess: base->getAccessSpecifier(), DeclAccess: access);
9646
9647 // If we're operating on a field, the object type is the type of the field.
9648 } else {
9649 objectTy = S.Context.getCanonicalTagType(TD: target->getParent());
9650 }
9651
9652 return S.isMemberAccessibleForDeletion(
9653 NamingClass: target->getParent(), Found: DeclAccessPair::make(D: target, AS: access), ObjectType: objectTy);
9654}
9655
9656/// Check whether we should delete a special member due to the implicit
9657/// definition containing a call to a special member of a subobject.
9658bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
9659 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
9660 bool IsDtorCallInCtor) {
9661 CXXMethodDecl *Decl = SMOR.getMethod();
9662 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9663
9664 enum {
9665 NotSet = -1,
9666 NoDecl,
9667 DeletedDecl,
9668 MultipleDecl,
9669 InaccessibleDecl,
9670 NonTrivialDecl
9671 } DiagKind = NotSet;
9672
9673 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) {
9674 if (CSM == CXXSpecialMemberKind::DefaultConstructor && Field &&
9675 Field->getParent()->isUnion()) {
9676 // [class.default.ctor]p2:
9677 // A defaulted default constructor for class X is defined as deleted if
9678 // - X is a union that has a variant member with a non-trivial default
9679 // constructor and no variant member of X has a default member
9680 // initializer
9681 const auto *RD = cast<CXXRecordDecl>(Val: Field->getParent());
9682 if (RD->hasInClassInitializer())
9683 return false;
9684 }
9685 DiagKind = !Decl ? NoDecl : DeletedDecl;
9686 } else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
9687 DiagKind = MultipleDecl;
9688 else if (!isAccessible(Subobj, target: Decl))
9689 DiagKind = InaccessibleDecl;
9690 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
9691 !Decl->isTrivial()) {
9692 // A member of a union must have a trivial corresponding special member.
9693 // As a weird special case, a destructor call from a union's constructor
9694 // must be accessible and non-deleted, but need not be trivial. Such a
9695 // destructor is never actually called, but is semantically checked as
9696 // if it were.
9697 if (CSM == CXXSpecialMemberKind::DefaultConstructor) {
9698 // [class.default.ctor]p2:
9699 // A defaulted default constructor for class X is defined as deleted if
9700 // - X is a union that has a variant member with a non-trivial default
9701 // constructor and no variant member of X has a default member
9702 // initializer
9703 const auto *RD = cast<CXXRecordDecl>(Val: Field->getParent());
9704 if (!RD->hasInClassInitializer())
9705 DiagKind = NonTrivialDecl;
9706 } else {
9707 DiagKind = NonTrivialDecl;
9708 }
9709 }
9710
9711 if (DiagKind == NotSet)
9712 return false;
9713
9714 if (Diagnose) {
9715 if (Field) {
9716 S.Diag(Loc: Field->getLocation(),
9717 DiagID: diag::note_deleted_special_member_class_subobject)
9718 << getEffectiveCSM() << MD->getParent() << /*IsField*/ true << Field
9719 << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/ false;
9720 } else {
9721 CXXBaseSpecifier *Base = cast<CXXBaseSpecifier *>(Val&: Subobj);
9722 S.Diag(Loc: Base->getBeginLoc(),
9723 DiagID: diag::note_deleted_special_member_class_subobject)
9724 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9725 << Base->getType() << DiagKind << IsDtorCallInCtor
9726 << /*IsObjCPtr*/ false;
9727 }
9728
9729 if (DiagKind == DeletedDecl)
9730 S.NoteDeletedFunction(FD: Decl);
9731 // FIXME: Explain inaccessibility if DiagKind == InaccessibleDecl.
9732 }
9733
9734 return true;
9735}
9736
9737/// Check whether we should delete a special member function due to having a
9738/// direct or virtual base class or non-static data member of class type M.
9739bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
9740 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
9741 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9742 bool IsMutable = Field && Field->isMutable();
9743
9744 // C++11 [class.ctor]p5:
9745 // -- any direct or virtual base class, or non-static data member with no
9746 // brace-or-equal-initializer, has class type M (or array thereof) and
9747 // either M has no default constructor or overload resolution as applied
9748 // to M's default constructor results in an ambiguity or in a function
9749 // that is deleted or inaccessible
9750 // C++11 [class.copy]p11, C++11 [class.copy]p23:
9751 // -- a direct or virtual base class B that cannot be copied/moved because
9752 // overload resolution, as applied to B's corresponding special member,
9753 // results in an ambiguity or a function that is deleted or inaccessible
9754 // from the defaulted special member
9755 // C++11 [class.dtor]p5:
9756 // -- any direct or virtual base class [...] has a type with a destructor
9757 // that is deleted or inaccessible
9758 if (!(CSM == CXXSpecialMemberKind::DefaultConstructor && Field &&
9759 Field->hasInClassInitializer()) &&
9760 shouldDeleteForSubobjectCall(Subobj, SMOR: lookupIn(Class, Quals, IsMutable),
9761 IsDtorCallInCtor: false))
9762 return true;
9763
9764 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
9765 // -- any direct or virtual base class or non-static data member has a
9766 // type with a destructor that is deleted or inaccessible
9767 if (IsConstructor) {
9768 Sema::SpecialMemberOverloadResult SMOR =
9769 S.LookupSpecialMember(D: Class, SM: CXXSpecialMemberKind::Destructor, ConstArg: false,
9770 VolatileArg: false, RValueThis: false, ConstThis: false, VolatileThis: false);
9771 if (shouldDeleteForSubobjectCall(Subobj, SMOR, IsDtorCallInCtor: true))
9772 return true;
9773 }
9774
9775 return false;
9776}
9777
9778bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
9779 FieldDecl *FD, QualType FieldType) {
9780 // The defaulted special functions are defined as deleted if this is a variant
9781 // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
9782 // type under ARC.
9783 if (!FieldType.hasNonTrivialObjCLifetime())
9784 return false;
9785
9786 // Don't make the defaulted default constructor defined as deleted if the
9787 // member has an in-class initializer.
9788 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
9789 FD->hasInClassInitializer())
9790 return false;
9791
9792 if (Diagnose) {
9793 auto *ParentClass = cast<CXXRecordDecl>(Val: FD->getParent());
9794 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_deleted_special_member_class_subobject)
9795 << getEffectiveCSM() << ParentClass << /*IsField*/ true << FD << 4
9796 << /*IsDtorCallInCtor*/ false << /*IsObjCPtr*/ true;
9797 }
9798
9799 return true;
9800}
9801
9802bool SpecialMemberDeletionInfo::shouldDeleteForVariantPtrAuthMember(
9803 const FieldDecl *FD) {
9804 QualType FieldType = S.Context.getBaseElementType(QT: FD->getType());
9805 // Copy/move constructors/assignment operators are deleted if the field has an
9806 // address-discriminated ptrauth qualifier.
9807 PointerAuthQualifier Q = FieldType.getPointerAuth();
9808
9809 if (!Q || !Q.isAddressDiscriminated())
9810 return false;
9811
9812 if (CSM == CXXSpecialMemberKind::DefaultConstructor ||
9813 CSM == CXXSpecialMemberKind::Destructor)
9814 return false;
9815
9816 if (Diagnose) {
9817 auto *ParentClass = cast<CXXRecordDecl>(Val: FD->getParent());
9818 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_deleted_special_member_class_subobject)
9819 << getEffectiveCSM() << ParentClass << /*IsField*/ true << FD << 4
9820 << /*IsDtorCallInCtor*/ false << 2;
9821 }
9822
9823 return true;
9824}
9825
9826/// Check whether we should delete a special member function due to the class
9827/// having a particular direct or virtual base class.
9828bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
9829 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
9830 // If program is correct, BaseClass cannot be null, but if it is, the error
9831 // must be reported elsewhere.
9832 if (!BaseClass)
9833 return false;
9834 // If we have an inheriting constructor, check whether we're calling an
9835 // inherited constructor instead of a default constructor.
9836 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(Class: BaseClass);
9837 if (auto *BaseCtor = SMOR.getMethod()) {
9838 // Note that we do not check access along this path; other than that,
9839 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
9840 // FIXME: Check that the base has a usable destructor! Sink this into
9841 // shouldDeleteForClassSubobject.
9842 if (BaseCtor->isDeleted() && Diagnose) {
9843 S.Diag(Loc: Base->getBeginLoc(),
9844 DiagID: diag::note_deleted_special_member_class_subobject)
9845 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9846 << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
9847 << /*IsObjCPtr*/ false;
9848 S.NoteDeletedFunction(FD: BaseCtor);
9849 }
9850 return BaseCtor->isDeleted();
9851 }
9852 return shouldDeleteForClassSubobject(Class: BaseClass, Subobj: Base, Quals: 0);
9853}
9854
9855/// Check whether we should delete a special member function due to the class
9856/// having a particular non-static data member.
9857bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
9858 QualType FieldType = S.Context.getBaseElementType(QT: FD->getType());
9859 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
9860
9861 if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
9862 return true;
9863
9864 if (inUnion() && shouldDeleteForVariantPtrAuthMember(FD))
9865 return true;
9866
9867 if (CSM == CXXSpecialMemberKind::DefaultConstructor) {
9868 // For a default constructor, all references must be initialized in-class
9869 // and, if a union, it must have a non-const member.
9870 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
9871 if (Diagnose)
9872 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_deleted_default_ctor_uninit_field)
9873 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
9874 return true;
9875 }
9876 // C++11 [class.ctor]p5 (modified by DR2394): any non-variant non-static
9877 // data member of const-qualified type (or array thereof) with no
9878 // brace-or-equal-initializer is not const-default-constructible.
9879 if (!inUnion() && FieldType.isConstQualified() &&
9880 !FD->hasInClassInitializer() &&
9881 (!FieldRecord || !FieldRecord->allowConstDefaultInit())) {
9882 if (Diagnose)
9883 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_deleted_default_ctor_uninit_field)
9884 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
9885 return true;
9886 }
9887
9888 if (inUnion() && !FieldType.isConstQualified())
9889 AllFieldsAreConst = false;
9890 } else if (CSM == CXXSpecialMemberKind::CopyConstructor) {
9891 // For a copy constructor, data members must not be of rvalue reference
9892 // type.
9893 if (FieldType->isRValueReferenceType()) {
9894 if (Diagnose)
9895 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_deleted_copy_ctor_rvalue_reference)
9896 << MD->getParent() << FD << FieldType;
9897 return true;
9898 }
9899 } else if (IsAssignment) {
9900 // For an assignment operator, data members must not be of reference type.
9901 if (FieldType->isReferenceType()) {
9902 if (Diagnose)
9903 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_deleted_assign_field)
9904 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
9905 return true;
9906 }
9907 if (!FieldRecord && FieldType.isConstQualified()) {
9908 // C++11 [class.copy]p23:
9909 // -- a non-static data member of const non-class type (or array thereof)
9910 if (Diagnose)
9911 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_deleted_assign_field)
9912 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
9913 return true;
9914 }
9915 }
9916
9917 if (FieldRecord) {
9918 // Some additional restrictions exist on the variant members.
9919 if (!inUnion() && FieldRecord->isUnion() &&
9920 FieldRecord->isAnonymousStructOrUnion()) {
9921 bool AllVariantFieldsAreConst = true;
9922
9923 // FIXME: Handle anonymous unions declared within anonymous unions.
9924 for (auto *UI : FieldRecord->fields()) {
9925 QualType UnionFieldType = S.Context.getBaseElementType(QT: UI->getType());
9926
9927 if (shouldDeleteForVariantObjCPtrMember(FD: &*UI, FieldType: UnionFieldType))
9928 return true;
9929
9930 if (shouldDeleteForVariantPtrAuthMember(FD: &*UI))
9931 return true;
9932
9933 if (!UnionFieldType.isConstQualified())
9934 AllVariantFieldsAreConst = false;
9935
9936 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
9937 if (UnionFieldRecord &&
9938 shouldDeleteForClassSubobject(Class: UnionFieldRecord, Subobj: UI,
9939 Quals: UnionFieldType.getCVRQualifiers()))
9940 return true;
9941 }
9942
9943 // At least one member in each anonymous union must be non-const
9944 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
9945 AllVariantFieldsAreConst && !FieldRecord->field_empty()) {
9946 if (Diagnose)
9947 S.Diag(Loc: FieldRecord->getLocation(),
9948 DiagID: diag::note_deleted_default_ctor_all_const)
9949 << !!ICI << MD->getParent() << /*anonymous union*/1;
9950 return true;
9951 }
9952
9953 // Don't check the implicit member of the anonymous union type.
9954 // This is technically non-conformant but supported, and we have a
9955 // diagnostic for this elsewhere.
9956 return false;
9957 }
9958
9959 if (shouldDeleteForClassSubobject(Class: FieldRecord, Subobj: FD,
9960 Quals: FieldType.getCVRQualifiers()))
9961 return true;
9962 }
9963
9964 return false;
9965}
9966
9967/// C++11 [class.ctor] p5:
9968/// A defaulted default constructor for a class X is defined as deleted if
9969/// X is a union and all of its variant members are of const-qualified type.
9970bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
9971 // This is a silly definition, because it gives an empty union a deleted
9972 // default constructor. Don't do that.
9973 if (CSM == CXXSpecialMemberKind::DefaultConstructor && inUnion() &&
9974 AllFieldsAreConst) {
9975 bool AnyFields = false;
9976 for (auto *F : MD->getParent()->fields())
9977 if ((AnyFields = !F->isUnnamedBitField()))
9978 break;
9979 if (!AnyFields)
9980 return false;
9981 if (Diagnose)
9982 S.Diag(Loc: MD->getParent()->getLocation(),
9983 DiagID: diag::note_deleted_default_ctor_all_const)
9984 << !!ICI << MD->getParent() << /*not anonymous union*/0;
9985 return true;
9986 }
9987 return false;
9988}
9989
9990/// Determine whether a defaulted special member function should be defined as
9991/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
9992/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
9993bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD,
9994 CXXSpecialMemberKind CSM,
9995 InheritedConstructorInfo *ICI,
9996 bool Diagnose) {
9997 if (MD->isInvalidDecl())
9998 return false;
9999 CXXRecordDecl *RD = MD->getParent();
10000 assert(!RD->isDependentType() && "do deletion after instantiation");
10001 if (!LangOpts.CPlusPlus || (!LangOpts.CPlusPlus11 && !RD->isLambda()) ||
10002 RD->isInvalidDecl())
10003 return false;
10004
10005 // C++11 [expr.lambda.prim]p19:
10006 // The closure type associated with a lambda-expression has a
10007 // deleted (8.4.3) default constructor and a deleted copy
10008 // assignment operator.
10009 // C++2a adds back these operators if the lambda has no lambda-capture.
10010 if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() &&
10011 (CSM == CXXSpecialMemberKind::DefaultConstructor ||
10012 CSM == CXXSpecialMemberKind::CopyAssignment)) {
10013 if (Diagnose)
10014 Diag(Loc: RD->getLocation(), DiagID: diag::note_lambda_decl);
10015 return true;
10016 }
10017
10018 // C++11 [class.copy]p7, p18:
10019 // If the class definition declares a move constructor or move assignment
10020 // operator, an implicitly declared copy constructor or copy assignment
10021 // operator is defined as deleted.
10022 if (MD->isImplicit() && (CSM == CXXSpecialMemberKind::CopyConstructor ||
10023 CSM == CXXSpecialMemberKind::CopyAssignment)) {
10024 CXXMethodDecl *UserDeclaredMove = nullptr;
10025
10026 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
10027 // deletion of the corresponding copy operation, not both copy operations.
10028 // MSVC 2015 has adopted the standards conforming behavior.
10029 bool DeletesOnlyMatchingCopy =
10030 getLangOpts().MSVCCompat &&
10031 !getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015);
10032
10033 if (RD->hasUserDeclaredMoveConstructor() &&
10034 (!DeletesOnlyMatchingCopy ||
10035 CSM == CXXSpecialMemberKind::CopyConstructor)) {
10036 if (!Diagnose) return true;
10037
10038 // Find any user-declared move constructor.
10039 for (auto *I : RD->ctors()) {
10040 if (I->isMoveConstructor()) {
10041 UserDeclaredMove = I;
10042 break;
10043 }
10044 }
10045 assert(UserDeclaredMove);
10046 } else if (RD->hasUserDeclaredMoveAssignment() &&
10047 (!DeletesOnlyMatchingCopy ||
10048 CSM == CXXSpecialMemberKind::CopyAssignment)) {
10049 if (!Diagnose) return true;
10050
10051 // Find any user-declared move assignment operator.
10052 for (auto *I : RD->methods()) {
10053 if (I->isMoveAssignmentOperator()) {
10054 UserDeclaredMove = I;
10055 break;
10056 }
10057 }
10058 assert(UserDeclaredMove);
10059 }
10060
10061 if (UserDeclaredMove) {
10062 Diag(Loc: UserDeclaredMove->getLocation(),
10063 DiagID: diag::note_deleted_copy_user_declared_move)
10064 << (CSM == CXXSpecialMemberKind::CopyAssignment) << RD
10065 << UserDeclaredMove->isMoveAssignmentOperator();
10066 return true;
10067 }
10068 }
10069
10070 // Do access control from the special member function
10071 ContextRAII MethodContext(*this, MD);
10072
10073 // C++11 [class.dtor]p5:
10074 // -- for a virtual destructor, lookup of the non-array deallocation function
10075 // results in an ambiguity or in a function that is deleted or inaccessible
10076 if (CSM == CXXSpecialMemberKind::Destructor && MD->isVirtual()) {
10077 FunctionDecl *OperatorDelete = nullptr;
10078 CanQualType DeallocType = Context.getCanonicalTagType(TD: RD);
10079 DeclarationName Name =
10080 Context.DeclarationNames.getCXXOperatorName(Op: OO_Delete);
10081 ImplicitDeallocationParameters IDP = {
10082 DeallocType, ShouldUseTypeAwareOperatorNewOrDelete(),
10083 AlignedAllocationMode::No, SizedDeallocationMode::No};
10084 if (FindDeallocationFunction(StartLoc: MD->getLocation(), RD: MD->getParent(), Name,
10085 Operator&: OperatorDelete, IDP,
10086 /*Diagnose=*/false)) {
10087 if (Diagnose)
10088 Diag(Loc: RD->getLocation(), DiagID: diag::note_deleted_dtor_no_operator_delete);
10089 return true;
10090 }
10091 }
10092
10093 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
10094
10095 // Per DR1611, do not consider virtual bases of constructors of abstract
10096 // classes, since we are not going to construct them.
10097 // Per DR1658, do not consider virtual bases of destructors of abstract
10098 // classes either.
10099 // Per DR2180, for assignment operators we only assign (and thus only
10100 // consider) direct bases.
10101 if (SMI.visit(Bases: SMI.IsAssignment ? SMI.VisitDirectBases
10102 : SMI.VisitPotentiallyConstructedBases))
10103 return true;
10104
10105 if (SMI.shouldDeleteForAllConstMembers())
10106 return true;
10107
10108 if (getLangOpts().CUDA) {
10109 // We should delete the special member in CUDA mode if target inference
10110 // failed.
10111 // For inherited constructors (non-null ICI), CSM may be passed so that MD
10112 // is treated as certain special member, which may not reflect what special
10113 // member MD really is. However inferTargetForImplicitSpecialMember
10114 // expects CSM to match MD, therefore recalculate CSM.
10115 assert(ICI || CSM == MD->getSpecialMemberKind());
10116 auto RealCSM = CSM;
10117 if (ICI)
10118 RealCSM = MD->getSpecialMemberKind();
10119
10120 return CUDA().inferTargetForImplicitSpecialMember(ClassDecl: RD, CSM: RealCSM, MemberDecl: MD,
10121 ConstRHS: SMI.ConstArg, Diagnose);
10122 }
10123
10124 return false;
10125}
10126
10127void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl *FD) {
10128 FunctionDecl::DefaultedFunctionKind DFK = FD->getDefaultedFunctionKind();
10129 assert(DFK && "not a defaultable function");
10130 assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted");
10131
10132 if (DFK.isSpecialMember()) {
10133 ShouldDeleteSpecialMember(MD: cast<CXXMethodDecl>(Val: FD), CSM: DFK.asSpecialMember(),
10134 ICI: nullptr, /*Diagnose=*/true);
10135 } else {
10136 DefaultedComparisonAnalyzer(
10137 *this, cast<CXXRecordDecl>(Val: FD->getLexicalDeclContext()), FD,
10138 DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted)
10139 .visit();
10140 }
10141}
10142
10143/// Perform lookup for a special member of the specified kind, and determine
10144/// whether it is trivial. If the triviality can be determined without the
10145/// lookup, skip it. This is intended for use when determining whether a
10146/// special member of a containing object is trivial, and thus does not ever
10147/// perform overload resolution for default constructors.
10148///
10149/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
10150/// member that was most likely to be intended to be trivial, if any.
10151///
10152/// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
10153/// determine whether the special member is trivial.
10154static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
10155 CXXSpecialMemberKind CSM, unsigned Quals,
10156 bool ConstRHS, TrivialABIHandling TAH,
10157 CXXMethodDecl **Selected) {
10158 if (Selected)
10159 *Selected = nullptr;
10160
10161 switch (CSM) {
10162 case CXXSpecialMemberKind::Invalid:
10163 llvm_unreachable("not a special member");
10164
10165 case CXXSpecialMemberKind::DefaultConstructor:
10166 // C++11 [class.ctor]p5:
10167 // A default constructor is trivial if:
10168 // - all the [direct subobjects] have trivial default constructors
10169 //
10170 // Note, no overload resolution is performed in this case.
10171 if (RD->hasTrivialDefaultConstructor())
10172 return true;
10173
10174 if (Selected) {
10175 // If there's a default constructor which could have been trivial, dig it
10176 // out. Otherwise, if there's any user-provided default constructor, point
10177 // to that as an example of why there's not a trivial one.
10178 CXXConstructorDecl *DefCtor = nullptr;
10179 if (RD->needsImplicitDefaultConstructor())
10180 S.DeclareImplicitDefaultConstructor(ClassDecl: RD);
10181 for (auto *CI : RD->ctors()) {
10182 if (!CI->isDefaultConstructor())
10183 continue;
10184 DefCtor = CI;
10185 if (!DefCtor->isUserProvided())
10186 break;
10187 }
10188
10189 *Selected = DefCtor;
10190 }
10191
10192 return false;
10193
10194 case CXXSpecialMemberKind::Destructor:
10195 // C++11 [class.dtor]p5:
10196 // A destructor is trivial if:
10197 // - all the direct [subobjects] have trivial destructors
10198 if (RD->hasTrivialDestructor() ||
10199 (TAH == TrivialABIHandling::ConsiderTrivialABI &&
10200 RD->hasTrivialDestructorForCall()))
10201 return true;
10202
10203 if (Selected) {
10204 if (RD->needsImplicitDestructor())
10205 S.DeclareImplicitDestructor(ClassDecl: RD);
10206 *Selected = RD->getDestructor();
10207 }
10208
10209 return false;
10210
10211 case CXXSpecialMemberKind::CopyConstructor:
10212 // C++11 [class.copy]p12:
10213 // A copy constructor is trivial if:
10214 // - the constructor selected to copy each direct [subobject] is trivial
10215 if (RD->hasTrivialCopyConstructor() ||
10216 (TAH == TrivialABIHandling::ConsiderTrivialABI &&
10217 RD->hasTrivialCopyConstructorForCall())) {
10218 if (Quals == Qualifiers::Const)
10219 // We must either select the trivial copy constructor or reach an
10220 // ambiguity; no need to actually perform overload resolution.
10221 return true;
10222 } else if (!Selected) {
10223 return false;
10224 }
10225 // In C++98, we are not supposed to perform overload resolution here, but we
10226 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
10227 // cases like B as having a non-trivial copy constructor:
10228 // struct A { template<typename T> A(T&); };
10229 // struct B { mutable A a; };
10230 goto NeedOverloadResolution;
10231
10232 case CXXSpecialMemberKind::CopyAssignment:
10233 // C++11 [class.copy]p25:
10234 // A copy assignment operator is trivial if:
10235 // - the assignment operator selected to copy each direct [subobject] is
10236 // trivial
10237 if (RD->hasTrivialCopyAssignment()) {
10238 if (Quals == Qualifiers::Const)
10239 return true;
10240 } else if (!Selected) {
10241 return false;
10242 }
10243 // In C++98, we are not supposed to perform overload resolution here, but we
10244 // treat that as a language defect.
10245 goto NeedOverloadResolution;
10246
10247 case CXXSpecialMemberKind::MoveConstructor:
10248 case CXXSpecialMemberKind::MoveAssignment:
10249 NeedOverloadResolution:
10250 Sema::SpecialMemberOverloadResult SMOR =
10251 lookupCallFromSpecialMember(S, Class: RD, CSM, FieldQuals: Quals, ConstRHS);
10252
10253 // The standard doesn't describe how to behave if the lookup is ambiguous.
10254 // We treat it as not making the member non-trivial, just like the standard
10255 // mandates for the default constructor. This should rarely matter, because
10256 // the member will also be deleted.
10257 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
10258 return true;
10259
10260 if (!SMOR.getMethod()) {
10261 assert(SMOR.getKind() ==
10262 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
10263 return false;
10264 }
10265
10266 // We deliberately don't check if we found a deleted special member. We're
10267 // not supposed to!
10268 if (Selected)
10269 *Selected = SMOR.getMethod();
10270
10271 if (TAH == TrivialABIHandling::ConsiderTrivialABI &&
10272 (CSM == CXXSpecialMemberKind::CopyConstructor ||
10273 CSM == CXXSpecialMemberKind::MoveConstructor))
10274 return SMOR.getMethod()->isTrivialForCall();
10275 return SMOR.getMethod()->isTrivial();
10276 }
10277
10278 llvm_unreachable("unknown special method kind");
10279}
10280
10281static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
10282 for (auto *CI : RD->ctors())
10283 if (!CI->isImplicit())
10284 return CI;
10285
10286 // Look for constructor templates.
10287 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
10288 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
10289 if (CXXConstructorDecl *CD =
10290 dyn_cast<CXXConstructorDecl>(Val: TI->getTemplatedDecl()))
10291 return CD;
10292 }
10293
10294 return nullptr;
10295}
10296
10297/// The kind of subobject we are checking for triviality. The values of this
10298/// enumeration are used in diagnostics.
10299enum TrivialSubobjectKind {
10300 /// The subobject is a base class.
10301 TSK_BaseClass,
10302 /// The subobject is a non-static data member.
10303 TSK_Field,
10304 /// The object is actually the complete object.
10305 TSK_CompleteObject
10306};
10307
10308/// Check whether the special member selected for a given type would be trivial.
10309static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
10310 QualType SubType, bool ConstRHS,
10311 CXXSpecialMemberKind CSM,
10312 TrivialSubobjectKind Kind,
10313 TrivialABIHandling TAH, bool Diagnose) {
10314 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
10315 if (!SubRD)
10316 return true;
10317
10318 CXXMethodDecl *Selected;
10319 if (findTrivialSpecialMember(S, RD: SubRD, CSM, Quals: SubType.getCVRQualifiers(),
10320 ConstRHS, TAH, Selected: Diagnose ? &Selected : nullptr))
10321 return true;
10322
10323 if (Diagnose) {
10324 if (ConstRHS)
10325 SubType.addConst();
10326
10327 if (!Selected && CSM == CXXSpecialMemberKind::DefaultConstructor) {
10328 S.Diag(Loc: SubobjLoc, DiagID: diag::note_nontrivial_no_def_ctor)
10329 << Kind << SubType.getUnqualifiedType();
10330 if (CXXConstructorDecl *CD = findUserDeclaredCtor(RD: SubRD))
10331 S.Diag(Loc: CD->getLocation(), DiagID: diag::note_user_declared_ctor);
10332 } else if (!Selected)
10333 S.Diag(Loc: SubobjLoc, DiagID: diag::note_nontrivial_no_copy)
10334 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
10335 else if (Selected->isUserProvided()) {
10336 if (Kind == TSK_CompleteObject)
10337 S.Diag(Loc: Selected->getLocation(), DiagID: diag::note_nontrivial_user_provided)
10338 << Kind << SubType.getUnqualifiedType() << CSM;
10339 else {
10340 S.Diag(Loc: SubobjLoc, DiagID: diag::note_nontrivial_user_provided)
10341 << Kind << SubType.getUnqualifiedType() << CSM;
10342 S.Diag(Loc: Selected->getLocation(), DiagID: diag::note_declared_at);
10343 }
10344 } else {
10345 if (Kind != TSK_CompleteObject)
10346 S.Diag(Loc: SubobjLoc, DiagID: diag::note_nontrivial_subobject)
10347 << Kind << SubType.getUnqualifiedType() << CSM;
10348
10349 // Explain why the defaulted or deleted special member isn't trivial.
10350 S.SpecialMemberIsTrivial(MD: Selected, CSM,
10351 TAH: TrivialABIHandling::IgnoreTrivialABI, Diagnose);
10352 }
10353 }
10354
10355 return false;
10356}
10357
10358/// Check whether the members of a class type allow a special member to be
10359/// trivial.
10360static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
10361 CXXSpecialMemberKind CSM, bool ConstArg,
10362 TrivialABIHandling TAH, bool Diagnose) {
10363 for (const auto *FI : RD->fields()) {
10364 if (FI->isInvalidDecl() || FI->isUnnamedBitField())
10365 continue;
10366
10367 QualType FieldType = S.Context.getBaseElementType(QT: FI->getType());
10368
10369 // Pretend anonymous struct or union members are members of this class.
10370 if (FI->isAnonymousStructOrUnion()) {
10371 if (!checkTrivialClassMembers(S, RD: FieldType->getAsCXXRecordDecl(),
10372 CSM, ConstArg, TAH, Diagnose))
10373 return false;
10374 continue;
10375 }
10376
10377 // C++11 [class.ctor]p5:
10378 // A default constructor is trivial if [...]
10379 // -- no non-static data member of its class has a
10380 // brace-or-equal-initializer
10381 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
10382 FI->hasInClassInitializer()) {
10383 if (Diagnose)
10384 S.Diag(Loc: FI->getLocation(), DiagID: diag::note_nontrivial_default_member_init)
10385 << FI;
10386 return false;
10387 }
10388
10389 // Objective C ARC 4.3.5:
10390 // [...] nontrivally ownership-qualified types are [...] not trivially
10391 // default constructible, copy constructible, move constructible, copy
10392 // assignable, move assignable, or destructible [...]
10393 if (FieldType.hasNonTrivialObjCLifetime()) {
10394 if (Diagnose)
10395 S.Diag(Loc: FI->getLocation(), DiagID: diag::note_nontrivial_objc_ownership)
10396 << RD << FieldType.getObjCLifetime();
10397 return false;
10398 }
10399
10400 bool ConstRHS = ConstArg && !FI->isMutable();
10401 if (!checkTrivialSubobjectCall(S, SubobjLoc: FI->getLocation(), SubType: FieldType, ConstRHS,
10402 CSM, Kind: TSK_Field, TAH, Diagnose))
10403 return false;
10404 }
10405
10406 return true;
10407}
10408
10409void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD,
10410 CXXSpecialMemberKind CSM) {
10411 CanQualType Ty = Context.getCanonicalTagType(TD: RD);
10412
10413 bool ConstArg = (CSM == CXXSpecialMemberKind::CopyConstructor ||
10414 CSM == CXXSpecialMemberKind::CopyAssignment);
10415 checkTrivialSubobjectCall(S&: *this, SubobjLoc: RD->getLocation(), SubType: Ty, ConstRHS: ConstArg, CSM,
10416 Kind: TSK_CompleteObject,
10417 TAH: TrivialABIHandling::IgnoreTrivialABI,
10418 /*Diagnose*/ true);
10419}
10420
10421bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMemberKind CSM,
10422 TrivialABIHandling TAH, bool Diagnose) {
10423 assert(!MD->isUserProvided() && CSM != CXXSpecialMemberKind::Invalid &&
10424 "not special enough");
10425
10426 CXXRecordDecl *RD = MD->getParent();
10427
10428 bool ConstArg = false;
10429
10430 // C++11 [class.copy]p12, p25: [DR1593]
10431 // A [special member] is trivial if [...] its parameter-type-list is
10432 // equivalent to the parameter-type-list of an implicit declaration [...]
10433 switch (CSM) {
10434 case CXXSpecialMemberKind::DefaultConstructor:
10435 case CXXSpecialMemberKind::Destructor:
10436 // Trivial default constructors and destructors cannot have parameters.
10437 break;
10438
10439 case CXXSpecialMemberKind::CopyConstructor:
10440 case CXXSpecialMemberKind::CopyAssignment: {
10441 const ParmVarDecl *Param0 = MD->getNonObjectParameter(I: 0);
10442 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
10443
10444 // When ClangABICompat14 is true, CXX copy constructors will only be trivial
10445 // if they are not user-provided and their parameter-type-list is equivalent
10446 // to the parameter-type-list of an implicit declaration. This maintains the
10447 // behavior before dr2171 was implemented.
10448 //
10449 // Otherwise, if ClangABICompat14 is false, All copy constructors can be
10450 // trivial, if they are not user-provided, regardless of the qualifiers on
10451 // the reference type.
10452 const bool ClangABICompat14 =
10453 Context.getLangOpts().isCompatibleWith(Version: LangOptions::ClangABI::Ver14);
10454 if (!RT ||
10455 ((RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) &&
10456 ClangABICompat14)) {
10457 if (Diagnose)
10458 Diag(Loc: Param0->getLocation(), DiagID: diag::note_nontrivial_param_type)
10459 << Param0->getSourceRange() << Param0->getType()
10460 << Context.getLValueReferenceType(
10461 T: Context.getCanonicalTagType(TD: RD).withConst());
10462 return false;
10463 }
10464
10465 ConstArg = RT->getPointeeType().isConstQualified();
10466 break;
10467 }
10468
10469 case CXXSpecialMemberKind::MoveConstructor:
10470 case CXXSpecialMemberKind::MoveAssignment: {
10471 // Trivial move operations always have non-cv-qualified parameters.
10472 const ParmVarDecl *Param0 = MD->getNonObjectParameter(I: 0);
10473 const RValueReferenceType *RT =
10474 Param0->getType()->getAs<RValueReferenceType>();
10475 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
10476 if (Diagnose)
10477 Diag(Loc: Param0->getLocation(), DiagID: diag::note_nontrivial_param_type)
10478 << Param0->getSourceRange() << Param0->getType()
10479 << Context.getRValueReferenceType(T: Context.getCanonicalTagType(TD: RD));
10480 return false;
10481 }
10482 break;
10483 }
10484
10485 case CXXSpecialMemberKind::Invalid:
10486 llvm_unreachable("not a special member");
10487 }
10488
10489 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
10490 if (Diagnose)
10491 Diag(Loc: MD->getParamDecl(i: MD->getMinRequiredArguments())->getLocation(),
10492 DiagID: diag::note_nontrivial_default_arg)
10493 << MD->getParamDecl(i: MD->getMinRequiredArguments())->getSourceRange();
10494 return false;
10495 }
10496 if (MD->isVariadic()) {
10497 if (Diagnose)
10498 Diag(Loc: MD->getLocation(), DiagID: diag::note_nontrivial_variadic);
10499 return false;
10500 }
10501
10502 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
10503 // A copy/move [constructor or assignment operator] is trivial if
10504 // -- the [member] selected to copy/move each direct base class subobject
10505 // is trivial
10506 //
10507 // C++11 [class.copy]p12, C++11 [class.copy]p25:
10508 // A [default constructor or destructor] is trivial if
10509 // -- all the direct base classes have trivial [default constructors or
10510 // destructors]
10511 for (const auto &BI : RD->bases())
10512 if (!checkTrivialSubobjectCall(S&: *this, SubobjLoc: BI.getBeginLoc(), SubType: BI.getType(),
10513 ConstRHS: ConstArg, CSM, Kind: TSK_BaseClass, TAH, Diagnose))
10514 return false;
10515
10516 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
10517 // A copy/move [constructor or assignment operator] for a class X is
10518 // trivial if
10519 // -- for each non-static data member of X that is of class type (or array
10520 // thereof), the constructor selected to copy/move that member is
10521 // trivial
10522 //
10523 // C++11 [class.copy]p12, C++11 [class.copy]p25:
10524 // A [default constructor or destructor] is trivial if
10525 // -- for all of the non-static data members of its class that are of class
10526 // type (or array thereof), each such class has a trivial [default
10527 // constructor or destructor]
10528 if (!checkTrivialClassMembers(S&: *this, RD, CSM, ConstArg, TAH, Diagnose))
10529 return false;
10530
10531 // C++11 [class.dtor]p5:
10532 // A destructor is trivial if [...]
10533 // -- the destructor is not virtual
10534 if (CSM == CXXSpecialMemberKind::Destructor && MD->isVirtual()) {
10535 if (Diagnose)
10536 Diag(Loc: MD->getLocation(), DiagID: diag::note_nontrivial_virtual_dtor) << RD;
10537 return false;
10538 }
10539
10540 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
10541 // A [special member] for class X is trivial if [...]
10542 // -- class X has no virtual functions and no virtual base classes
10543 if (CSM != CXXSpecialMemberKind::Destructor &&
10544 MD->getParent()->isDynamicClass()) {
10545 if (!Diagnose)
10546 return false;
10547
10548 if (RD->getNumVBases()) {
10549 // Check for virtual bases. We already know that the corresponding
10550 // member in all bases is trivial, so vbases must all be direct.
10551 CXXBaseSpecifier &BS = *RD->vbases_begin();
10552 assert(BS.isVirtual());
10553 Diag(Loc: BS.getBeginLoc(), DiagID: diag::note_nontrivial_has_virtual) << RD << 1;
10554 return false;
10555 }
10556
10557 // Must have a virtual method.
10558 for (const auto *MI : RD->methods()) {
10559 if (MI->isVirtual()) {
10560 SourceLocation MLoc = MI->getBeginLoc();
10561 Diag(Loc: MLoc, DiagID: diag::note_nontrivial_has_virtual) << RD << 0;
10562 return false;
10563 }
10564 }
10565
10566 llvm_unreachable("dynamic class with no vbases and no virtual functions");
10567 }
10568
10569 // Looks like it's trivial!
10570 return true;
10571}
10572
10573namespace {
10574struct FindHiddenVirtualMethod {
10575 Sema *S;
10576 CXXMethodDecl *Method;
10577 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
10578 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10579
10580private:
10581 /// Check whether any most overridden method from MD in Methods
10582 static bool CheckMostOverridenMethods(
10583 const CXXMethodDecl *MD,
10584 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
10585 if (MD->size_overridden_methods() == 0)
10586 return Methods.count(Ptr: MD->getCanonicalDecl());
10587 for (const CXXMethodDecl *O : MD->overridden_methods())
10588 if (CheckMostOverridenMethods(MD: O, Methods))
10589 return true;
10590 return false;
10591 }
10592
10593public:
10594 /// Member lookup function that determines whether a given C++
10595 /// method overloads virtual methods in a base class without overriding any,
10596 /// to be used with CXXRecordDecl::lookupInBases().
10597 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
10598 auto *BaseRecord = Specifier->getType()->castAsRecordDecl();
10599 DeclarationName Name = Method->getDeclName();
10600 assert(Name.getNameKind() == DeclarationName::Identifier);
10601
10602 bool foundSameNameMethod = false;
10603 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
10604 for (Path.Decls = BaseRecord->lookup(Name).begin();
10605 Path.Decls != DeclContext::lookup_iterator(); ++Path.Decls) {
10606 NamedDecl *D = *Path.Decls;
10607 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: D)) {
10608 MD = MD->getCanonicalDecl();
10609 foundSameNameMethod = true;
10610 // Interested only in hidden virtual methods.
10611 if (!MD->isVirtual())
10612 continue;
10613 // If the method we are checking overrides a method from its base
10614 // don't warn about the other overloaded methods. Clang deviates from
10615 // GCC by only diagnosing overloads of inherited virtual functions that
10616 // do not override any other virtual functions in the base. GCC's
10617 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
10618 // function from a base class. These cases may be better served by a
10619 // warning (not specific to virtual functions) on call sites when the
10620 // call would select a different function from the base class, were it
10621 // visible.
10622 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
10623 if (!S->IsOverload(New: Method, Old: MD, UseMemberUsingDeclRules: false))
10624 return true;
10625 // Collect the overload only if its hidden.
10626 if (!CheckMostOverridenMethods(MD, Methods: OverridenAndUsingBaseMethods))
10627 overloadedMethods.push_back(Elt: MD);
10628 }
10629 }
10630
10631 if (foundSameNameMethod)
10632 OverloadedMethods.append(in_start: overloadedMethods.begin(),
10633 in_end: overloadedMethods.end());
10634 return foundSameNameMethod;
10635 }
10636};
10637} // end anonymous namespace
10638
10639/// Add the most overridden methods from MD to Methods
10640static void AddMostOverridenMethods(const CXXMethodDecl *MD,
10641 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
10642 if (MD->size_overridden_methods() == 0)
10643 Methods.insert(Ptr: MD->getCanonicalDecl());
10644 else
10645 for (const CXXMethodDecl *O : MD->overridden_methods())
10646 AddMostOverridenMethods(MD: O, Methods);
10647}
10648
10649void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
10650 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10651 if (!MD->getDeclName().isIdentifier())
10652 return;
10653
10654 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
10655 /*bool RecordPaths=*/false,
10656 /*bool DetectVirtual=*/false);
10657 FindHiddenVirtualMethod FHVM;
10658 FHVM.Method = MD;
10659 FHVM.S = this;
10660
10661 // Keep the base methods that were overridden or introduced in the subclass
10662 // by 'using' in a set. A base method not in this set is hidden.
10663 CXXRecordDecl *DC = MD->getParent();
10664 for (NamedDecl *ND : DC->lookup(Name: MD->getDeclName())) {
10665 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(Val: ND))
10666 ND = shad->getTargetDecl();
10667 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: ND))
10668 AddMostOverridenMethods(MD, Methods&: FHVM.OverridenAndUsingBaseMethods);
10669 }
10670
10671 if (DC->lookupInBases(BaseMatches: FHVM, Paths))
10672 OverloadedMethods = FHVM.OverloadedMethods;
10673}
10674
10675void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
10676 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10677 for (const CXXMethodDecl *overloadedMD : OverloadedMethods) {
10678 PartialDiagnostic PD = PDiag(
10679 DiagID: diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
10680 HandleFunctionTypeMismatch(PDiag&: PD, FromType: MD->getType(), ToType: overloadedMD->getType());
10681 Diag(Loc: overloadedMD->getLocation(), PD);
10682 }
10683}
10684
10685void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
10686 if (MD->isInvalidDecl())
10687 return;
10688
10689 if (Diags.isIgnored(DiagID: diag::warn_overloaded_virtual, Loc: MD->getLocation()))
10690 return;
10691
10692 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10693 FindHiddenVirtualMethods(MD, OverloadedMethods);
10694 if (!OverloadedMethods.empty()) {
10695 Diag(Loc: MD->getLocation(), DiagID: diag::warn_overloaded_virtual)
10696 << MD << (OverloadedMethods.size() > 1);
10697
10698 NoteHiddenVirtualMethods(MD, OverloadedMethods);
10699 }
10700}
10701
10702void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
10703 auto PrintDiagAndRemoveAttr = [&](unsigned N) {
10704 // No diagnostics if this is a template instantiation.
10705 if (!isTemplateInstantiation(Kind: RD.getTemplateSpecializationKind())) {
10706 Diag(Loc: RD.getAttr<TrivialABIAttr>()->getLocation(),
10707 DiagID: diag::ext_cannot_use_trivial_abi) << &RD;
10708 Diag(Loc: RD.getAttr<TrivialABIAttr>()->getLocation(),
10709 DiagID: diag::note_cannot_use_trivial_abi_reason) << &RD << N;
10710 }
10711 RD.dropAttr<TrivialABIAttr>();
10712 };
10713
10714 // Ill-formed if the struct has virtual functions.
10715 if (RD.isPolymorphic()) {
10716 PrintDiagAndRemoveAttr(1);
10717 return;
10718 }
10719
10720 for (const auto &B : RD.bases()) {
10721 // Ill-formed if the base class is non-trivial for the purpose of calls or a
10722 // virtual base.
10723 if (!B.getType()->isDependentType() &&
10724 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) {
10725 PrintDiagAndRemoveAttr(2);
10726 return;
10727 }
10728
10729 if (B.isVirtual()) {
10730 PrintDiagAndRemoveAttr(3);
10731 return;
10732 }
10733 }
10734
10735 for (const auto *FD : RD.fields()) {
10736 // Ill-formed if the field is an ObjectiveC pointer or of a type that is
10737 // non-trivial for the purpose of calls.
10738 QualType FT = FD->getType();
10739 if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
10740 PrintDiagAndRemoveAttr(4);
10741 return;
10742 }
10743
10744 // Ill-formed if the field is an address-discriminated value.
10745 if (FT.hasAddressDiscriminatedPointerAuth()) {
10746 PrintDiagAndRemoveAttr(6);
10747 return;
10748 }
10749
10750 if (const auto *RT =
10751 FT->getBaseElementTypeUnsafe()->getAsCanonical<RecordType>())
10752 if (!RT->isDependentType() &&
10753 !cast<CXXRecordDecl>(Val: RT->getDecl()->getDefinitionOrSelf())
10754 ->canPassInRegisters()) {
10755 PrintDiagAndRemoveAttr(5);
10756 return;
10757 }
10758 }
10759
10760 if (IsCXXTriviallyRelocatableType(RD))
10761 return;
10762
10763 // Ill-formed if the copy and move constructors are deleted.
10764 auto HasNonDeletedCopyOrMoveConstructor = [&]() {
10765 // If the type is dependent, then assume it might have
10766 // implicit copy or move ctor because we won't know yet at this point.
10767 if (RD.isDependentType())
10768 return true;
10769 if (RD.needsImplicitCopyConstructor() &&
10770 !RD.defaultedCopyConstructorIsDeleted())
10771 return true;
10772 if (RD.needsImplicitMoveConstructor() &&
10773 !RD.defaultedMoveConstructorIsDeleted())
10774 return true;
10775 for (const CXXConstructorDecl *CD : RD.ctors())
10776 if (CD->isCopyOrMoveConstructor() && !CD->isDeleted())
10777 return true;
10778 return false;
10779 };
10780
10781 if (!HasNonDeletedCopyOrMoveConstructor()) {
10782 PrintDiagAndRemoveAttr(0);
10783 return;
10784 }
10785}
10786
10787void Sema::checkIncorrectVTablePointerAuthenticationAttribute(
10788 CXXRecordDecl &RD) {
10789 if (RequireCompleteType(Loc: RD.getLocation(), T: Context.getCanonicalTagType(TD: &RD),
10790 DiagID: diag::err_incomplete_type_vtable_pointer_auth))
10791 return;
10792
10793 const CXXRecordDecl *PrimaryBase = &RD;
10794 if (PrimaryBase->hasAnyDependentBases())
10795 return;
10796
10797 while (1) {
10798 assert(PrimaryBase);
10799 const CXXRecordDecl *Base = nullptr;
10800 for (const CXXBaseSpecifier &BasePtr : PrimaryBase->bases()) {
10801 if (!BasePtr.getType()->getAsCXXRecordDecl()->isDynamicClass())
10802 continue;
10803 Base = BasePtr.getType()->getAsCXXRecordDecl();
10804 break;
10805 }
10806 if (!Base || Base == PrimaryBase || !Base->isPolymorphic())
10807 break;
10808 Diag(Loc: RD.getAttr<VTablePointerAuthenticationAttr>()->getLocation(),
10809 DiagID: diag::err_non_top_level_vtable_pointer_auth)
10810 << &RD << Base;
10811 PrimaryBase = Base;
10812 }
10813
10814 if (!RD.isPolymorphic())
10815 Diag(Loc: RD.getAttr<VTablePointerAuthenticationAttr>()->getLocation(),
10816 DiagID: diag::err_non_polymorphic_vtable_pointer_auth)
10817 << &RD;
10818}
10819
10820void Sema::ActOnFinishCXXMemberSpecification(
10821 Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
10822 SourceLocation RBrac, const ParsedAttributesView &AttrList) {
10823 if (!TagDecl)
10824 return;
10825
10826 AdjustDeclIfTemplate(Decl&: TagDecl);
10827
10828 for (const ParsedAttr &AL : AttrList) {
10829 if (AL.getKind() != ParsedAttr::AT_Visibility)
10830 continue;
10831 AL.setInvalid();
10832 Diag(Loc: AL.getLoc(), DiagID: diag::warn_attribute_after_definition_ignored) << AL;
10833 }
10834
10835 ActOnFields(S, RecLoc: RLoc, TagDecl,
10836 Fields: llvm::ArrayRef(
10837 // strict aliasing violation!
10838 reinterpret_cast<Decl **>(FieldCollector->getCurFields()),
10839 FieldCollector->getCurNumFields()),
10840 LBrac, RBrac, AttrList);
10841
10842 CheckCompletedCXXClass(S, Record: cast<CXXRecordDecl>(Val: TagDecl));
10843}
10844
10845/// Find the equality comparison functions that should be implicitly declared
10846/// in a given class definition, per C++2a [class.compare.default]p3.
10847static void findImplicitlyDeclaredEqualityComparisons(
10848 ASTContext &Ctx, CXXRecordDecl *RD,
10849 llvm::SmallVectorImpl<FunctionDecl *> &Spaceships) {
10850 DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(Op: OO_EqualEqual);
10851 if (!RD->lookup(Name: EqEq).empty())
10852 // Member operator== explicitly declared: no implicit operator==s.
10853 return;
10854
10855 // Traverse friends looking for an '==' or a '<=>'.
10856 for (FriendDecl *Friend : RD->friends()) {
10857 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Val: Friend->getFriendDecl());
10858 if (!FD) continue;
10859
10860 if (FD->getOverloadedOperator() == OO_EqualEqual) {
10861 // Friend operator== explicitly declared: no implicit operator==s.
10862 Spaceships.clear();
10863 return;
10864 }
10865
10866 if (FD->getOverloadedOperator() == OO_Spaceship &&
10867 FD->isExplicitlyDefaulted())
10868 Spaceships.push_back(Elt: FD);
10869 }
10870
10871 // Look for members named 'operator<=>'.
10872 DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(Op: OO_Spaceship);
10873 for (NamedDecl *ND : RD->lookup(Name: Cmp)) {
10874 // Note that we could find a non-function here (either a function template
10875 // or a using-declaration). Neither case results in an implicit
10876 // 'operator=='.
10877 if (auto *FD = dyn_cast<FunctionDecl>(Val: ND))
10878 if (FD->isExplicitlyDefaulted())
10879 Spaceships.push_back(Elt: FD);
10880 }
10881}
10882
10883void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
10884 // Don't add implicit special members to templated classes.
10885 // FIXME: This means unqualified lookups for 'operator=' within a class
10886 // template don't work properly.
10887 if (!ClassDecl->isDependentType()) {
10888 if (ClassDecl->needsImplicitDefaultConstructor()) {
10889 ++getASTContext().NumImplicitDefaultConstructors;
10890
10891 if (ClassDecl->hasInheritedConstructor())
10892 DeclareImplicitDefaultConstructor(ClassDecl);
10893 }
10894
10895 if (ClassDecl->needsImplicitCopyConstructor()) {
10896 ++getASTContext().NumImplicitCopyConstructors;
10897
10898 // If the properties or semantics of the copy constructor couldn't be
10899 // determined while the class was being declared, force a declaration
10900 // of it now.
10901 if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
10902 ClassDecl->hasInheritedConstructor())
10903 DeclareImplicitCopyConstructor(ClassDecl);
10904 // For the MS ABI we need to know whether the copy ctor is deleted. A
10905 // prerequisite for deleting the implicit copy ctor is that the class has
10906 // a move ctor or move assignment that is either user-declared or whose
10907 // semantics are inherited from a subobject. FIXME: We should provide a
10908 // more direct way for CodeGen to ask whether the constructor was deleted.
10909 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
10910 (ClassDecl->hasUserDeclaredMoveConstructor() ||
10911 ClassDecl->needsOverloadResolutionForMoveConstructor() ||
10912 ClassDecl->hasUserDeclaredMoveAssignment() ||
10913 ClassDecl->needsOverloadResolutionForMoveAssignment()))
10914 DeclareImplicitCopyConstructor(ClassDecl);
10915 }
10916
10917 if (getLangOpts().CPlusPlus11 &&
10918 ClassDecl->needsImplicitMoveConstructor()) {
10919 ++getASTContext().NumImplicitMoveConstructors;
10920
10921 if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
10922 ClassDecl->hasInheritedConstructor())
10923 DeclareImplicitMoveConstructor(ClassDecl);
10924 }
10925
10926 if (ClassDecl->needsImplicitCopyAssignment()) {
10927 ++getASTContext().NumImplicitCopyAssignmentOperators;
10928
10929 // If we have a dynamic class, then the copy assignment operator may be
10930 // virtual, so we have to declare it immediately. This ensures that, e.g.,
10931 // it shows up in the right place in the vtable and that we diagnose
10932 // problems with the implicit exception specification.
10933 if (ClassDecl->isDynamicClass() ||
10934 ClassDecl->needsOverloadResolutionForCopyAssignment() ||
10935 ClassDecl->hasInheritedAssignment())
10936 DeclareImplicitCopyAssignment(ClassDecl);
10937 }
10938
10939 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
10940 ++getASTContext().NumImplicitMoveAssignmentOperators;
10941
10942 // Likewise for the move assignment operator.
10943 if (ClassDecl->isDynamicClass() ||
10944 ClassDecl->needsOverloadResolutionForMoveAssignment() ||
10945 ClassDecl->hasInheritedAssignment())
10946 DeclareImplicitMoveAssignment(ClassDecl);
10947 }
10948
10949 if (ClassDecl->needsImplicitDestructor()) {
10950 ++getASTContext().NumImplicitDestructors;
10951
10952 // If we have a dynamic class, then the destructor may be virtual, so we
10953 // have to declare the destructor immediately. This ensures that, e.g., it
10954 // shows up in the right place in the vtable and that we diagnose problems
10955 // with the implicit exception specification.
10956 if (ClassDecl->isDynamicClass() ||
10957 ClassDecl->needsOverloadResolutionForDestructor())
10958 DeclareImplicitDestructor(ClassDecl);
10959 }
10960 }
10961
10962 // C++2a [class.compare.default]p3:
10963 // If the member-specification does not explicitly declare any member or
10964 // friend named operator==, an == operator function is declared implicitly
10965 // for each defaulted three-way comparison operator function defined in
10966 // the member-specification
10967 // FIXME: Consider doing this lazily.
10968 // We do this during the initial parse for a class template, not during
10969 // instantiation, so that we can handle unqualified lookups for 'operator=='
10970 // when parsing the template.
10971 if (getLangOpts().CPlusPlus20 && !inTemplateInstantiation()) {
10972 llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships;
10973 findImplicitlyDeclaredEqualityComparisons(Ctx&: Context, RD: ClassDecl,
10974 Spaceships&: DefaultedSpaceships);
10975 for (auto *FD : DefaultedSpaceships)
10976 DeclareImplicitEqualityComparison(RD: ClassDecl, Spaceship: FD);
10977 }
10978}
10979
10980unsigned
10981Sema::ActOnReenterTemplateScope(Decl *D,
10982 llvm::function_ref<Scope *()> EnterScope) {
10983 if (!D)
10984 return 0;
10985 AdjustDeclIfTemplate(Decl&: D);
10986
10987 // In order to get name lookup right, reenter template scopes in order from
10988 // outermost to innermost.
10989 SmallVector<TemplateParameterList *, 4> ParameterLists;
10990 DeclContext *LookupDC = dyn_cast<DeclContext>(Val: D);
10991
10992 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(Val: D)) {
10993 for (TemplateParameterList *TPL : DD->getTemplateParameterLists())
10994 ParameterLists.push_back(Elt: TPL);
10995
10996 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
10997 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
10998 ParameterLists.push_back(Elt: FTD->getTemplateParameters());
10999 } else if (VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
11000 LookupDC = VD->getDeclContext();
11001
11002 if (VarTemplateDecl *VTD = VD->getDescribedVarTemplate())
11003 ParameterLists.push_back(Elt: VTD->getTemplateParameters());
11004 else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(Val: D))
11005 ParameterLists.push_back(Elt: PSD->getTemplateParameters());
11006 }
11007 } else if (TagDecl *TD = dyn_cast<TagDecl>(Val: D)) {
11008 for (TemplateParameterList *TPL : TD->getTemplateParameterLists())
11009 ParameterLists.push_back(Elt: TPL);
11010
11011 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: TD)) {
11012 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
11013 ParameterLists.push_back(Elt: CTD->getTemplateParameters());
11014 else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(Val: D))
11015 ParameterLists.push_back(Elt: PSD->getTemplateParameters());
11016 }
11017 }
11018 // FIXME: Alias declarations and concepts.
11019
11020 unsigned Count = 0;
11021 Scope *InnermostTemplateScope = nullptr;
11022 for (TemplateParameterList *Params : ParameterLists) {
11023 // Ignore explicit specializations; they don't contribute to the template
11024 // depth.
11025 if (Params->size() == 0)
11026 continue;
11027
11028 InnermostTemplateScope = EnterScope();
11029 for (NamedDecl *Param : *Params) {
11030 if (Param->getDeclName()) {
11031 InnermostTemplateScope->AddDecl(D: Param);
11032 IdResolver.AddDecl(D: Param);
11033 }
11034 }
11035 ++Count;
11036 }
11037
11038 // Associate the new template scopes with the corresponding entities.
11039 if (InnermostTemplateScope) {
11040 assert(LookupDC && "no enclosing DeclContext for template lookup");
11041 EnterTemplatedContext(S: InnermostTemplateScope, DC: LookupDC);
11042 }
11043
11044 return Count;
11045}
11046
11047void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
11048 if (!RecordD) return;
11049 AdjustDeclIfTemplate(Decl&: RecordD);
11050 CXXRecordDecl *Record = cast<CXXRecordDecl>(Val: RecordD);
11051 PushDeclContext(S, DC: Record);
11052}
11053
11054void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
11055 if (!RecordD) return;
11056 PopDeclContext();
11057}
11058
11059void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
11060 if (!Param)
11061 return;
11062
11063 S->AddDecl(D: Param);
11064 if (Param->getDeclName())
11065 IdResolver.AddDecl(D: Param);
11066}
11067
11068void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
11069}
11070
11071/// ActOnDelayedCXXMethodParameter - We've already started a delayed
11072/// C++ method declaration. We're (re-)introducing the given
11073/// function parameter into scope for use in parsing later parts of
11074/// the method declaration. For example, we could see an
11075/// ActOnParamDefaultArgument event for this parameter.
11076void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
11077 if (!ParamD)
11078 return;
11079
11080 ParmVarDecl *Param = cast<ParmVarDecl>(Val: ParamD);
11081
11082 S->AddDecl(D: Param);
11083 if (Param->getDeclName())
11084 IdResolver.AddDecl(D: Param);
11085}
11086
11087void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
11088 if (!MethodD)
11089 return;
11090
11091 AdjustDeclIfTemplate(Decl&: MethodD);
11092
11093 FunctionDecl *Method = cast<FunctionDecl>(Val: MethodD);
11094
11095 // Now that we have our default arguments, check the constructor
11096 // again. It could produce additional diagnostics or affect whether
11097 // the class has implicitly-declared destructors, among other
11098 // things.
11099 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: Method))
11100 CheckConstructor(Constructor);
11101
11102 // Check the default arguments, which we may have added.
11103 if (!Method->isInvalidDecl())
11104 CheckCXXDefaultArguments(FD: Method);
11105}
11106
11107// Emit the given diagnostic for each non-address-space qualifier.
11108// Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
11109static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
11110 const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11111 if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
11112 bool DiagOccurred = false;
11113 FTI.MethodQualifiers->forEachQualifier(
11114 Handle: [DiagID, &S, &DiagOccurred](DeclSpec::TQ, StringRef QualName,
11115 SourceLocation SL) {
11116 // This diagnostic should be emitted on any qualifier except an addr
11117 // space qualifier. However, forEachQualifier currently doesn't visit
11118 // addr space qualifiers, so there's no way to write this condition
11119 // right now; we just diagnose on everything.
11120 S.Diag(Loc: SL, DiagID) << QualName << SourceRange(SL);
11121 DiagOccurred = true;
11122 });
11123 if (DiagOccurred)
11124 D.setInvalidType();
11125 }
11126}
11127
11128static void diagnoseInvalidDeclaratorChunks(Sema &S, Declarator &D,
11129 unsigned Kind) {
11130 if (D.isInvalidType() || D.getNumTypeObjects() <= 1)
11131 return;
11132
11133 DeclaratorChunk &Chunk = D.getTypeObject(i: D.getNumTypeObjects() - 1);
11134 if (Chunk.Kind == DeclaratorChunk::Paren ||
11135 Chunk.Kind == DeclaratorChunk::Function)
11136 return;
11137
11138 SourceLocation PointerLoc = Chunk.getSourceRange().getBegin();
11139 S.Diag(Loc: PointerLoc, DiagID: diag::err_invalid_ctor_dtor_decl)
11140 << Kind << Chunk.getSourceRange();
11141 D.setInvalidType();
11142}
11143
11144QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
11145 StorageClass &SC) {
11146 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
11147
11148 // C++ [class.ctor]p3:
11149 // A constructor shall not be virtual (10.3) or static (9.4). A
11150 // constructor can be invoked for a const, volatile or const
11151 // volatile object. A constructor shall not be declared const,
11152 // volatile, or const volatile (9.3.2).
11153 if (isVirtual) {
11154 if (!D.isInvalidType())
11155 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_constructor_cannot_be)
11156 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
11157 << SourceRange(D.getIdentifierLoc());
11158 D.setInvalidType();
11159 }
11160 if (SC == SC_Static) {
11161 if (!D.isInvalidType())
11162 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_constructor_cannot_be)
11163 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
11164 << SourceRange(D.getIdentifierLoc());
11165 D.setInvalidType();
11166 SC = SC_None;
11167 }
11168
11169 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
11170 diagnoseIgnoredQualifiers(
11171 DiagID: diag::err_constructor_return_type, Quals: TypeQuals, FallbackLoc: SourceLocation(),
11172 ConstQualLoc: D.getDeclSpec().getConstSpecLoc(), VolatileQualLoc: D.getDeclSpec().getVolatileSpecLoc(),
11173 RestrictQualLoc: D.getDeclSpec().getRestrictSpecLoc(),
11174 AtomicQualLoc: D.getDeclSpec().getAtomicSpecLoc());
11175 D.setInvalidType();
11176 }
11177
11178 checkMethodTypeQualifiers(S&: *this, D, DiagID: diag::err_invalid_qualified_constructor);
11179 diagnoseInvalidDeclaratorChunks(S&: *this, D, /*constructor*/ Kind: 0);
11180
11181 // C++0x [class.ctor]p4:
11182 // A constructor shall not be declared with a ref-qualifier.
11183 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11184 if (FTI.hasRefQualifier()) {
11185 Diag(Loc: FTI.getRefQualifierLoc(), DiagID: diag::err_ref_qualifier_constructor)
11186 << FTI.RefQualifierIsLValueRef
11187 << FixItHint::CreateRemoval(RemoveRange: FTI.getRefQualifierLoc());
11188 D.setInvalidType();
11189 }
11190
11191 // Rebuild the function type "R" without any type qualifiers (in
11192 // case any of the errors above fired) and with "void" as the
11193 // return type, since constructors don't have return types.
11194 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
11195 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
11196 return R;
11197
11198 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
11199 EPI.TypeQuals = Qualifiers();
11200 EPI.RefQualifier = RQ_None;
11201
11202 return Context.getFunctionType(ResultTy: Context.VoidTy, Args: Proto->getParamTypes(), EPI);
11203}
11204
11205void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
11206 CXXRecordDecl *ClassDecl
11207 = dyn_cast<CXXRecordDecl>(Val: Constructor->getDeclContext());
11208 if (!ClassDecl)
11209 return Constructor->setInvalidDecl();
11210
11211 // C++ [class.copy]p3:
11212 // A declaration of a constructor for a class X is ill-formed if
11213 // its first parameter is of type (optionally cv-qualified) X and
11214 // either there are no other parameters or else all other
11215 // parameters have default arguments.
11216 if (!Constructor->isInvalidDecl() &&
11217 Constructor->hasOneParamOrDefaultArgs() &&
11218 !Constructor->isFunctionTemplateSpecialization()) {
11219 CanQualType ParamType =
11220 Constructor->getParamDecl(i: 0)->getType()->getCanonicalTypeUnqualified();
11221 CanQualType ClassTy = Context.getCanonicalTagType(TD: ClassDecl);
11222 if (ParamType == ClassTy) {
11223 SourceLocation ParamLoc = Constructor->getParamDecl(i: 0)->getLocation();
11224 const char *ConstRef
11225 = Constructor->getParamDecl(i: 0)->getIdentifier() ? "const &"
11226 : " const &";
11227 Diag(Loc: ParamLoc, DiagID: diag::err_constructor_byvalue_arg)
11228 << FixItHint::CreateInsertion(InsertionLoc: ParamLoc, Code: ConstRef);
11229
11230 // FIXME: Rather that making the constructor invalid, we should endeavor
11231 // to fix the type.
11232 Constructor->setInvalidDecl();
11233 }
11234 }
11235}
11236
11237bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
11238 CXXRecordDecl *RD = Destructor->getParent();
11239
11240 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
11241 SourceLocation Loc;
11242
11243 if (!Destructor->isImplicit())
11244 Loc = Destructor->getLocation();
11245 else
11246 Loc = RD->getLocation();
11247
11248 DeclarationName Name =
11249 Context.DeclarationNames.getCXXOperatorName(Op: OO_Delete);
11250 // If we have a virtual destructor, look up the deallocation function
11251 if (FunctionDecl *OperatorDelete = FindDeallocationFunctionForDestructor(
11252 StartLoc: Loc, RD, /*Diagnose=*/true, /*LookForGlobal=*/false, Name)) {
11253 Expr *ThisArg = nullptr;
11254
11255 // If the notional 'delete this' expression requires a non-trivial
11256 // conversion from 'this' to the type of a destroying operator delete's
11257 // first parameter, perform that conversion now.
11258 if (OperatorDelete->isDestroyingOperatorDelete()) {
11259 unsigned AddressParamIndex = 0;
11260 if (OperatorDelete->isTypeAwareOperatorNewOrDelete())
11261 ++AddressParamIndex;
11262 QualType ParamType =
11263 OperatorDelete->getParamDecl(i: AddressParamIndex)->getType();
11264 if (!declaresSameEntity(D1: ParamType->getAsCXXRecordDecl(), D2: RD)) {
11265 // C++ [class.dtor]p13:
11266 // ... as if for the expression 'delete this' appearing in a
11267 // non-virtual destructor of the destructor's class.
11268 ContextRAII SwitchContext(*this, Destructor);
11269 ExprResult This = ActOnCXXThis(
11270 Loc: OperatorDelete->getParamDecl(i: AddressParamIndex)->getLocation());
11271 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
11272 This = PerformImplicitConversion(From: This.get(), ToType: ParamType,
11273 Action: AssignmentAction::Passing);
11274 if (This.isInvalid()) {
11275 // FIXME: Register this as a context note so that it comes out
11276 // in the right order.
11277 Diag(Loc, DiagID: diag::note_implicit_delete_this_in_destructor_here);
11278 return true;
11279 }
11280 ThisArg = This.get();
11281 }
11282 }
11283
11284 DiagnoseUseOfDecl(D: OperatorDelete, Locs: Loc);
11285 MarkFunctionReferenced(Loc, Func: OperatorDelete);
11286 Destructor->setOperatorDelete(OD: OperatorDelete, ThisArg);
11287
11288 if (isa<CXXMethodDecl>(Val: OperatorDelete) &&
11289 Context.getTargetInfo().callGlobalDeleteInDeletingDtor(
11290 Context.getLangOpts())) {
11291 // In Microsoft ABI whenever a class has a defined operator delete,
11292 // scalar deleting destructors check the 3rd bit of the implicit
11293 // parameter and if it is set, then, global operator delete must be
11294 // called instead of the class-specific one. Find and save the global
11295 // operator delete for that case. Do not diagnose at this point because
11296 // the lack of a global operator delete is not an error if there are no
11297 // delete calls that require it.
11298 FunctionDecl *GlobalOperatorDelete =
11299 FindDeallocationFunctionForDestructor(StartLoc: Loc, RD, /*Diagnose*/ false,
11300 /*LookForGlobal*/ true, Name);
11301 if (GlobalOperatorDelete) {
11302 MarkFunctionReferenced(Loc, Func: GlobalOperatorDelete);
11303 Destructor->setOperatorGlobalDelete(GlobalOperatorDelete);
11304 }
11305 }
11306
11307 if (Context.getTargetInfo().emitVectorDeletingDtors(
11308 Context.getLangOpts())) {
11309 bool DestructorIsExported = Destructor->hasAttr<DLLExportAttr>();
11310 // Lookup delete[] too in case we have to emit a vector deleting dtor.
11311 DeclarationName VDeleteName =
11312 Context.DeclarationNames.getCXXOperatorName(Op: OO_Array_Delete);
11313 FunctionDecl *ArrOperatorDelete = FindDeallocationFunctionForDestructor(
11314 StartLoc: Loc, RD, /*Diagnose*/ false,
11315 /*LookForGlobal*/ false, Name: VDeleteName);
11316 if (ArrOperatorDelete && isa<CXXMethodDecl>(Val: ArrOperatorDelete)) {
11317 FunctionDecl *GlobalArrOperatorDelete =
11318 FindDeallocationFunctionForDestructor(StartLoc: Loc, RD, /*Diagnose*/ false,
11319 /*LookForGlobal*/ true,
11320 Name: VDeleteName);
11321 Destructor->setGlobalOperatorArrayDelete(GlobalArrOperatorDelete);
11322 if (GlobalArrOperatorDelete &&
11323 (Context.classMaybeNeedsVectorDeletingDestructor(RD) ||
11324 DestructorIsExported))
11325 MarkFunctionReferenced(Loc, Func: GlobalArrOperatorDelete);
11326 } else if (!ArrOperatorDelete) {
11327 ArrOperatorDelete = FindDeallocationFunctionForDestructor(
11328 StartLoc: Loc, RD, /*Diagnose*/ false,
11329 /*LookForGlobal*/ true, Name: VDeleteName);
11330 }
11331 Destructor->setOperatorArrayDelete(ArrOperatorDelete);
11332 if (ArrOperatorDelete &&
11333 (Context.classMaybeNeedsVectorDeletingDestructor(RD) ||
11334 DestructorIsExported))
11335 MarkFunctionReferenced(Loc, Func: ArrOperatorDelete);
11336 }
11337 }
11338 }
11339
11340 return false;
11341}
11342
11343QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
11344 StorageClass& SC) {
11345 // C++ [class.dtor]p1:
11346 // [...] A typedef-name that names a class is a class-name
11347 // (7.1.3); however, a typedef-name that names a class shall not
11348 // be used as the identifier in the declarator for a destructor
11349 // declaration.
11350 QualType DeclaratorType = GetTypeFromParser(Ty: D.getName().DestructorName);
11351 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
11352 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::ext_destructor_typedef_name)
11353 << DeclaratorType << isa<TypeAliasDecl>(Val: TT->getDecl());
11354 else if (const TemplateSpecializationType *TST =
11355 DeclaratorType->getAs<TemplateSpecializationType>())
11356 if (TST->isTypeAlias())
11357 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::ext_destructor_typedef_name)
11358 << DeclaratorType << 1;
11359
11360 // C++ [class.dtor]p2:
11361 // A destructor is used to destroy objects of its class type. A
11362 // destructor takes no parameters, and no return type can be
11363 // specified for it (not even void). The address of a destructor
11364 // shall not be taken. A destructor shall not be static. A
11365 // destructor can be invoked for a const, volatile or const
11366 // volatile object. A destructor shall not be declared const,
11367 // volatile or const volatile (9.3.2).
11368 if (SC == SC_Static) {
11369 if (!D.isInvalidType())
11370 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_destructor_cannot_be)
11371 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
11372 << SourceRange(D.getIdentifierLoc())
11373 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
11374
11375 SC = SC_None;
11376 }
11377 if (!D.isInvalidType()) {
11378 // Destructors don't have return types, but the parser will
11379 // happily parse something like:
11380 //
11381 // class X {
11382 // float ~X();
11383 // };
11384 //
11385 // The return type will be eliminated later.
11386 if (D.getDeclSpec().hasTypeSpecifier())
11387 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_destructor_return_type)
11388 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
11389 << SourceRange(D.getIdentifierLoc());
11390 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
11391 diagnoseIgnoredQualifiers(DiagID: diag::err_destructor_return_type, Quals: TypeQuals,
11392 FallbackLoc: SourceLocation(),
11393 ConstQualLoc: D.getDeclSpec().getConstSpecLoc(),
11394 VolatileQualLoc: D.getDeclSpec().getVolatileSpecLoc(),
11395 RestrictQualLoc: D.getDeclSpec().getRestrictSpecLoc(),
11396 AtomicQualLoc: D.getDeclSpec().getAtomicSpecLoc());
11397 D.setInvalidType();
11398 }
11399 }
11400
11401 checkMethodTypeQualifiers(S&: *this, D, DiagID: diag::err_invalid_qualified_destructor);
11402 diagnoseInvalidDeclaratorChunks(S&: *this, D, /*destructor*/ Kind: 1);
11403
11404 // C++0x [class.dtor]p2:
11405 // A destructor shall not be declared with a ref-qualifier.
11406 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11407 if (FTI.hasRefQualifier()) {
11408 Diag(Loc: FTI.getRefQualifierLoc(), DiagID: diag::err_ref_qualifier_destructor)
11409 << FTI.RefQualifierIsLValueRef
11410 << FixItHint::CreateRemoval(RemoveRange: FTI.getRefQualifierLoc());
11411 D.setInvalidType();
11412 }
11413
11414 // Make sure we don't have any parameters.
11415 if (FTIHasNonVoidParameters(FTI)) {
11416 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_destructor_with_params);
11417
11418 // Delete the parameters.
11419 FTI.freeParams();
11420 D.setInvalidType();
11421 }
11422
11423 // Make sure the destructor isn't variadic.
11424 if (FTI.isVariadic) {
11425 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_destructor_variadic);
11426 D.setInvalidType();
11427 }
11428
11429 // Rebuild the function type "R" without any type qualifiers or
11430 // parameters (in case any of the errors above fired) and with
11431 // "void" as the return type, since destructors don't have return
11432 // types.
11433 if (!D.isInvalidType())
11434 return R;
11435
11436 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
11437 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
11438 EPI.Variadic = false;
11439 EPI.TypeQuals = Qualifiers();
11440 EPI.RefQualifier = RQ_None;
11441 return Context.getFunctionType(ResultTy: Context.VoidTy, Args: {}, EPI);
11442}
11443
11444static void extendLeft(SourceRange &R, SourceRange Before) {
11445 if (Before.isInvalid())
11446 return;
11447 R.setBegin(Before.getBegin());
11448 if (R.getEnd().isInvalid())
11449 R.setEnd(Before.getEnd());
11450}
11451
11452static void extendRight(SourceRange &R, SourceRange After) {
11453 if (After.isInvalid())
11454 return;
11455 if (R.getBegin().isInvalid())
11456 R.setBegin(After.getBegin());
11457 R.setEnd(After.getEnd());
11458}
11459
11460void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
11461 StorageClass& SC) {
11462 // C++ [class.conv.fct]p1:
11463 // Neither parameter types nor return type can be specified. The
11464 // type of a conversion function (8.3.5) is "function taking no
11465 // parameter returning conversion-type-id."
11466 if (SC == SC_Static) {
11467 if (!D.isInvalidType())
11468 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_conv_function_not_member)
11469 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
11470 << D.getName().getSourceRange();
11471 D.setInvalidType();
11472 SC = SC_None;
11473 }
11474
11475 TypeSourceInfo *ConvTSI = nullptr;
11476 QualType ConvType =
11477 GetTypeFromParser(Ty: D.getName().ConversionFunctionId, TInfo: &ConvTSI);
11478
11479 const DeclSpec &DS = D.getDeclSpec();
11480 if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
11481 // Conversion functions don't have return types, but the parser will
11482 // happily parse something like:
11483 //
11484 // class X {
11485 // float operator bool();
11486 // };
11487 //
11488 // The return type will be changed later anyway.
11489 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_conv_function_return_type)
11490 << SourceRange(DS.getTypeSpecTypeLoc())
11491 << SourceRange(D.getIdentifierLoc());
11492 D.setInvalidType();
11493 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
11494 // It's also plausible that the user writes type qualifiers in the wrong
11495 // place, such as:
11496 // struct S { const operator int(); };
11497 // FIXME: we could provide a fixit to move the qualifiers onto the
11498 // conversion type.
11499 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_conv_function_with_complex_decl)
11500 << SourceRange(D.getIdentifierLoc()) << 0;
11501 D.setInvalidType();
11502 }
11503 const auto *Proto = R->castAs<FunctionProtoType>();
11504 // Make sure we don't have any parameters.
11505 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11506 unsigned NumParam = Proto->getNumParams();
11507
11508 // [C++2b]
11509 // A conversion function shall have no non-object parameters.
11510 if (NumParam == 1) {
11511 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11512 if (const auto *First =
11513 dyn_cast_if_present<ParmVarDecl>(Val: FTI.Params[0].Param);
11514 First && First->isExplicitObjectParameter())
11515 NumParam--;
11516 }
11517
11518 if (NumParam != 0) {
11519 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_conv_function_with_params);
11520 // Delete the parameters.
11521 FTI.freeParams();
11522 D.setInvalidType();
11523 } else if (Proto->isVariadic()) {
11524 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_conv_function_variadic);
11525 D.setInvalidType();
11526 }
11527
11528 // Diagnose "&operator bool()" and other such nonsense. This
11529 // is actually a gcc extension which we don't support.
11530 if (Proto->getReturnType() != ConvType) {
11531 bool NeedsTypedef = false;
11532 SourceRange Before, After;
11533
11534 // Walk the chunks and extract information on them for our diagnostic.
11535 bool PastFunctionChunk = false;
11536 for (auto &Chunk : D.type_objects()) {
11537 switch (Chunk.Kind) {
11538 case DeclaratorChunk::Function:
11539 if (!PastFunctionChunk) {
11540 if (Chunk.Fun.HasTrailingReturnType) {
11541 TypeSourceInfo *TRT = nullptr;
11542 GetTypeFromParser(Ty: Chunk.Fun.getTrailingReturnType(), TInfo: &TRT);
11543 if (TRT) extendRight(R&: After, After: TRT->getTypeLoc().getSourceRange());
11544 }
11545 PastFunctionChunk = true;
11546 break;
11547 }
11548 [[fallthrough]];
11549 case DeclaratorChunk::Array:
11550 NeedsTypedef = true;
11551 extendRight(R&: After, After: Chunk.getSourceRange());
11552 break;
11553
11554 case DeclaratorChunk::Pointer:
11555 case DeclaratorChunk::BlockPointer:
11556 case DeclaratorChunk::Reference:
11557 case DeclaratorChunk::MemberPointer:
11558 case DeclaratorChunk::Pipe:
11559 extendLeft(R&: Before, Before: Chunk.getSourceRange());
11560 break;
11561
11562 case DeclaratorChunk::Paren:
11563 extendLeft(R&: Before, Before: Chunk.Loc);
11564 extendRight(R&: After, After: Chunk.EndLoc);
11565 break;
11566 }
11567 }
11568
11569 SourceLocation Loc = Before.isValid() ? Before.getBegin() :
11570 After.isValid() ? After.getBegin() :
11571 D.getIdentifierLoc();
11572 auto &&DB = Diag(Loc, DiagID: diag::err_conv_function_with_complex_decl);
11573 DB << Before << After;
11574
11575 if (!NeedsTypedef) {
11576 DB << /*don't need a typedef*/0;
11577
11578 // If we can provide a correct fix-it hint, do so.
11579 if (After.isInvalid() && ConvTSI) {
11580 SourceLocation InsertLoc =
11581 getLocForEndOfToken(Loc: ConvTSI->getTypeLoc().getEndLoc());
11582 DB << FixItHint::CreateInsertion(InsertionLoc: InsertLoc, Code: " ")
11583 << FixItHint::CreateInsertionFromRange(
11584 InsertionLoc: InsertLoc, FromRange: CharSourceRange::getTokenRange(R: Before))
11585 << FixItHint::CreateRemoval(RemoveRange: Before);
11586 }
11587 } else if (!Proto->getReturnType()->isDependentType()) {
11588 DB << /*typedef*/1 << Proto->getReturnType();
11589 } else if (getLangOpts().CPlusPlus11) {
11590 DB << /*alias template*/2 << Proto->getReturnType();
11591 } else {
11592 DB << /*might not be fixable*/3;
11593 }
11594
11595 // Recover by incorporating the other type chunks into the result type.
11596 // Note, this does *not* change the name of the function. This is compatible
11597 // with the GCC extension:
11598 // struct S { &operator int(); } s;
11599 // int &r = s.operator int(); // ok in GCC
11600 // S::operator int&() {} // error in GCC, function name is 'operator int'.
11601 ConvType = Proto->getReturnType();
11602 }
11603
11604 // C++ [class.conv.fct]p4:
11605 // The conversion-type-id shall not represent a function type nor
11606 // an array type.
11607 if (ConvType->isArrayType()) {
11608 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_conv_function_to_array);
11609 ConvType = Context.getPointerType(T: ConvType);
11610 D.setInvalidType();
11611 } else if (ConvType->isFunctionType()) {
11612 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_conv_function_to_function);
11613 ConvType = Context.getPointerType(T: ConvType);
11614 D.setInvalidType();
11615 }
11616
11617 // Rebuild the function type "R" without any parameters (in case any
11618 // of the errors above fired) and with the conversion type as the
11619 // return type.
11620 if (D.isInvalidType())
11621 R = Context.getFunctionType(ResultTy: ConvType, Args: {}, EPI: Proto->getExtProtoInfo());
11622
11623 // C++0x explicit conversion operators.
11624 if (DS.hasExplicitSpecifier())
11625 Diag(Loc: DS.getExplicitSpecLoc(),
11626 DiagID: getLangOpts().CPlusPlus11
11627 ? diag::warn_cxx98_compat_explicit_conversion_functions
11628 : diag::ext_explicit_conversion_functions)
11629 << SourceRange(DS.getExplicitSpecRange());
11630}
11631
11632Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
11633 assert(Conversion && "Expected to receive a conversion function declaration");
11634
11635 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Val: Conversion->getDeclContext());
11636
11637 // Make sure we aren't redeclaring the conversion function.
11638 QualType ConvType = Context.getCanonicalType(T: Conversion->getConversionType());
11639 // C++ [class.conv.fct]p1:
11640 // [...] A conversion function is never used to convert a
11641 // (possibly cv-qualified) object to the (possibly cv-qualified)
11642 // same object type (or a reference to it), to a (possibly
11643 // cv-qualified) base class of that type (or a reference to it),
11644 // or to (possibly cv-qualified) void.
11645 CanQualType ClassType = Context.getCanonicalTagType(TD: ClassDecl);
11646 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
11647 ConvType = ConvTypeRef->getPointeeType();
11648 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
11649 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
11650 /* Suppress diagnostics for instantiations. */;
11651 else if (Conversion->size_overridden_methods() != 0)
11652 /* Suppress diagnostics for overriding virtual function in a base class. */;
11653 else if (ConvType->isRecordType()) {
11654 ConvType = Context.getCanonicalType(T: ConvType).getUnqualifiedType();
11655 if (ConvType == ClassType)
11656 Diag(Loc: Conversion->getLocation(), DiagID: diag::warn_conv_to_self_not_used)
11657 << ClassType;
11658 else if (IsDerivedFrom(Loc: Conversion->getLocation(), Derived: ClassType, Base: ConvType))
11659 Diag(Loc: Conversion->getLocation(), DiagID: diag::warn_conv_to_base_not_used)
11660 << ClassType << ConvType;
11661 } else if (ConvType->isVoidType()) {
11662 Diag(Loc: Conversion->getLocation(), DiagID: diag::warn_conv_to_void_not_used)
11663 << ClassType << ConvType;
11664 }
11665
11666 if (FunctionTemplateDecl *ConversionTemplate =
11667 Conversion->getDescribedFunctionTemplate()) {
11668 if (const auto *ConvTypePtr = ConvType->getAs<PointerType>()) {
11669 ConvType = ConvTypePtr->getPointeeType();
11670 }
11671 if (ConvType->isUndeducedAutoType()) {
11672 Diag(Loc: Conversion->getTypeSpecStartLoc(), DiagID: diag::err_auto_not_allowed)
11673 << getReturnTypeLoc(FD: Conversion).getSourceRange()
11674 << ConvType->castAs<AutoType>()->getKeyword()
11675 << /* in declaration of conversion function template= */ 24;
11676 }
11677
11678 return ConversionTemplate;
11679 }
11680
11681 return Conversion;
11682}
11683
11684void Sema::CheckExplicitObjectMemberFunction(DeclContext *DC, Declarator &D,
11685 DeclarationName Name, QualType R) {
11686 CheckExplicitObjectMemberFunction(D, Name, R, IsLambda: false, DC);
11687}
11688
11689void Sema::CheckExplicitObjectLambda(Declarator &D) {
11690 CheckExplicitObjectMemberFunction(D, Name: {}, R: {}, IsLambda: true);
11691}
11692
11693void Sema::CheckExplicitObjectMemberFunction(Declarator &D,
11694 DeclarationName Name, QualType R,
11695 bool IsLambda, DeclContext *DC) {
11696 if (!D.isFunctionDeclarator())
11697 return;
11698
11699 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11700 if (FTI.NumParams == 0)
11701 return;
11702 ParmVarDecl *ExplicitObjectParam = nullptr;
11703 for (unsigned Idx = 0; Idx < FTI.NumParams; Idx++) {
11704 const auto &ParamInfo = FTI.Params[Idx];
11705 if (!ParamInfo.Param)
11706 continue;
11707 ParmVarDecl *Param = cast<ParmVarDecl>(Val: ParamInfo.Param);
11708 if (!Param->isExplicitObjectParameter())
11709 continue;
11710 if (Idx == 0) {
11711 ExplicitObjectParam = Param;
11712 continue;
11713 } else {
11714 Diag(Loc: Param->getLocation(),
11715 DiagID: diag::err_explicit_object_parameter_must_be_first)
11716 << IsLambda << Param->getSourceRange();
11717 }
11718 }
11719 if (!ExplicitObjectParam)
11720 return;
11721
11722 if (ExplicitObjectParam->hasDefaultArg()) {
11723 Diag(Loc: ExplicitObjectParam->getLocation(),
11724 DiagID: diag::err_explicit_object_default_arg)
11725 << ExplicitObjectParam->getSourceRange();
11726 D.setInvalidType();
11727 }
11728
11729 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static ||
11730 (D.getContext() == clang::DeclaratorContext::Member &&
11731 D.isStaticMember())) {
11732 Diag(Loc: ExplicitObjectParam->getBeginLoc(),
11733 DiagID: diag::err_explicit_object_parameter_nonmember)
11734 << D.getSourceRange() << /*static=*/0 << IsLambda;
11735 D.setInvalidType();
11736 }
11737
11738 if (D.getDeclSpec().isVirtualSpecified()) {
11739 Diag(Loc: ExplicitObjectParam->getBeginLoc(),
11740 DiagID: diag::err_explicit_object_parameter_nonmember)
11741 << D.getSourceRange() << /*virtual=*/1 << IsLambda;
11742 D.setInvalidType();
11743 }
11744
11745 // Friend declarations require some care. Consider:
11746 //
11747 // namespace N {
11748 // struct A{};
11749 // int f(A);
11750 // }
11751 //
11752 // struct S {
11753 // struct T {
11754 // int f(this T);
11755 // };
11756 //
11757 // friend int T::f(this T); // Allow this.
11758 // friend int f(this S); // But disallow this.
11759 // friend int N::f(this A); // And disallow this.
11760 // };
11761 //
11762 // Here, it seems to suffice to check whether the scope
11763 // specifier designates a class type.
11764 if (D.getDeclSpec().isFriendSpecified() &&
11765 !isa_and_present<CXXRecordDecl>(
11766 Val: computeDeclContext(SS: D.getCXXScopeSpec()))) {
11767 Diag(Loc: ExplicitObjectParam->getBeginLoc(),
11768 DiagID: diag::err_explicit_object_parameter_nonmember)
11769 << D.getSourceRange() << /*non-member=*/2 << IsLambda;
11770 D.setInvalidType();
11771 }
11772
11773 if (IsLambda && FTI.hasMutableQualifier()) {
11774 Diag(Loc: ExplicitObjectParam->getBeginLoc(),
11775 DiagID: diag::err_explicit_object_parameter_mutable)
11776 << D.getSourceRange();
11777 }
11778
11779 if (IsLambda)
11780 return;
11781
11782 if (!DC || !DC->isRecord()) {
11783 assert(D.isInvalidType() && "Explicit object parameter in non-member "
11784 "should have been diagnosed already");
11785 return;
11786 }
11787
11788 // CWG2674: constructors and destructors cannot have explicit parameters.
11789 if (Name.getNameKind() == DeclarationName::CXXConstructorName ||
11790 Name.getNameKind() == DeclarationName::CXXDestructorName) {
11791 Diag(Loc: ExplicitObjectParam->getBeginLoc(),
11792 DiagID: diag::err_explicit_object_parameter_constructor)
11793 << (Name.getNameKind() == DeclarationName::CXXDestructorName)
11794 << D.getSourceRange();
11795 D.setInvalidType();
11796 }
11797}
11798
11799namespace {
11800/// Utility class to accumulate and print a diagnostic listing the invalid
11801/// specifier(s) on a declaration.
11802struct BadSpecifierDiagnoser {
11803 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
11804 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
11805 ~BadSpecifierDiagnoser() {
11806 Diagnostic << Specifiers;
11807 }
11808
11809 template<typename T> void check(SourceLocation SpecLoc, T Spec) {
11810 return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
11811 }
11812 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
11813 return check(SpecLoc,
11814 Spec: DeclSpec::getSpecifierName(T: Spec, Policy: S.getPrintingPolicy()));
11815 }
11816 void check(SourceLocation SpecLoc, const char *Spec) {
11817 if (SpecLoc.isInvalid()) return;
11818 Diagnostic << SourceRange(SpecLoc, SpecLoc);
11819 if (!Specifiers.empty()) Specifiers += " ";
11820 Specifiers += Spec;
11821 }
11822
11823 Sema &S;
11824 Sema::SemaDiagnosticBuilder Diagnostic;
11825 std::string Specifiers;
11826};
11827}
11828
11829bool Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
11830 StorageClass &SC) {
11831 TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
11832 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
11833 assert(GuidedTemplateDecl && "missing template decl for deduction guide");
11834
11835 // C++ [temp.deduct.guide]p3:
11836 // A deduction-gide shall be declared in the same scope as the
11837 // corresponding class template.
11838 if (!CurContext->getRedeclContext()->Equals(
11839 DC: GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
11840 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_deduction_guide_wrong_scope)
11841 << GuidedTemplateDecl;
11842 NoteTemplateLocation(Decl: *GuidedTemplateDecl);
11843 }
11844
11845 auto &DS = D.getMutableDeclSpec();
11846 // We leave 'friend' and 'virtual' to be rejected in the normal way.
11847 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
11848 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
11849 DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
11850 BadSpecifierDiagnoser Diagnoser(
11851 *this, D.getIdentifierLoc(),
11852 diag::err_deduction_guide_invalid_specifier);
11853
11854 Diagnoser.check(SpecLoc: DS.getStorageClassSpecLoc(), Spec: DS.getStorageClassSpec());
11855 DS.ClearStorageClassSpecs();
11856 SC = SC_None;
11857
11858 // 'explicit' is permitted.
11859 Diagnoser.check(SpecLoc: DS.getInlineSpecLoc(), Spec: "inline");
11860 Diagnoser.check(SpecLoc: DS.getNoreturnSpecLoc(), Spec: "_Noreturn");
11861 Diagnoser.check(SpecLoc: DS.getConstexprSpecLoc(), Spec: "constexpr");
11862 DS.ClearConstexprSpec();
11863
11864 Diagnoser.check(SpecLoc: DS.getConstSpecLoc(), Spec: "const");
11865 Diagnoser.check(SpecLoc: DS.getRestrictSpecLoc(), Spec: "__restrict");
11866 Diagnoser.check(SpecLoc: DS.getVolatileSpecLoc(), Spec: "volatile");
11867 Diagnoser.check(SpecLoc: DS.getAtomicSpecLoc(), Spec: "_Atomic");
11868 Diagnoser.check(SpecLoc: DS.getUnalignedSpecLoc(), Spec: "__unaligned");
11869 DS.ClearTypeQualifiers();
11870
11871 Diagnoser.check(SpecLoc: DS.getTypeSpecComplexLoc(), Spec: DS.getTypeSpecComplex());
11872 Diagnoser.check(SpecLoc: DS.getTypeSpecSignLoc(), Spec: DS.getTypeSpecSign());
11873 Diagnoser.check(SpecLoc: DS.getTypeSpecWidthLoc(), Spec: DS.getTypeSpecWidth());
11874 Diagnoser.check(SpecLoc: DS.getTypeSpecTypeLoc(), Spec: DS.getTypeSpecType());
11875 DS.ClearTypeSpecType();
11876 }
11877
11878 if (D.isInvalidType())
11879 return true;
11880
11881 // Check the declarator is simple enough.
11882 bool FoundFunction = false;
11883 for (const DeclaratorChunk &Chunk : llvm::reverse(C: D.type_objects())) {
11884 if (Chunk.Kind == DeclaratorChunk::Paren)
11885 continue;
11886 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
11887 Diag(Loc: D.getDeclSpec().getBeginLoc(),
11888 DiagID: diag::err_deduction_guide_with_complex_decl)
11889 << D.getSourceRange();
11890 break;
11891 }
11892 if (!Chunk.Fun.hasTrailingReturnType())
11893 return Diag(Loc: D.getName().getBeginLoc(),
11894 DiagID: diag::err_deduction_guide_no_trailing_return_type);
11895
11896 // Check that the return type is written as a specialization of
11897 // the template specified as the deduction-guide's name.
11898 // The template name may not be qualified. [temp.deduct.guide]
11899 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
11900 TypeSourceInfo *TSI = nullptr;
11901 QualType RetTy = GetTypeFromParser(Ty: TrailingReturnType, TInfo: &TSI);
11902 assert(TSI && "deduction guide has valid type but invalid return type?");
11903 bool AcceptableReturnType = false;
11904 bool MightInstantiateToSpecialization = false;
11905 if (auto RetTST =
11906 TSI->getTypeLoc().getAsAdjusted<TemplateSpecializationTypeLoc>()) {
11907 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
11908 bool TemplateMatches = Context.hasSameTemplateName(
11909 X: SpecifiedName, Y: GuidedTemplate, /*IgnoreDeduced=*/true);
11910
11911 const QualifiedTemplateName *Qualifiers =
11912 SpecifiedName.getAsQualifiedTemplateName();
11913 // A Template template parameter is never wrapped in a
11914 // QualifiedTemplateName, but it's always simply-written.
11915 bool SimplyWritten = !Qualifiers || (!Qualifiers->hasTemplateKeyword() &&
11916 !Qualifiers->getQualifier());
11917 if (SimplyWritten && TemplateMatches)
11918 AcceptableReturnType = true;
11919 else {
11920 // This could still instantiate to the right type, unless we know it
11921 // names the wrong class template.
11922 auto *TD = SpecifiedName.getAsTemplateDecl();
11923 MightInstantiateToSpecialization =
11924 !(TD && isa<ClassTemplateDecl>(Val: TD) && !TemplateMatches);
11925 }
11926 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
11927 MightInstantiateToSpecialization = true;
11928 }
11929
11930 if (!AcceptableReturnType)
11931 return Diag(Loc: TSI->getTypeLoc().getBeginLoc(),
11932 DiagID: diag::err_deduction_guide_bad_trailing_return_type)
11933 << GuidedTemplate << TSI->getType()
11934 << MightInstantiateToSpecialization
11935 << TSI->getTypeLoc().getSourceRange();
11936
11937 // Keep going to check that we don't have any inner declarator pieces (we
11938 // could still have a function returning a pointer to a function).
11939 FoundFunction = true;
11940 }
11941
11942 if (D.isFunctionDefinition())
11943 // we can still create a valid deduction guide here.
11944 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_deduction_guide_defines_function);
11945 return false;
11946}
11947
11948//===----------------------------------------------------------------------===//
11949// Namespace Handling
11950//===----------------------------------------------------------------------===//
11951
11952/// Diagnose a mismatch in 'inline' qualifiers when a namespace is
11953/// reopened.
11954static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
11955 SourceLocation Loc,
11956 IdentifierInfo *II, bool *IsInline,
11957 NamespaceDecl *PrevNS) {
11958 assert(*IsInline != PrevNS->isInline());
11959
11960 // 'inline' must appear on the original definition, but not necessarily
11961 // on all extension definitions, so the note should point to the first
11962 // definition to avoid confusion.
11963 PrevNS = PrevNS->getFirstDecl();
11964
11965 if (PrevNS->isInline())
11966 // The user probably just forgot the 'inline', so suggest that it
11967 // be added back.
11968 S.Diag(Loc, DiagID: diag::warn_inline_namespace_reopened_noninline)
11969 << FixItHint::CreateInsertion(InsertionLoc: KeywordLoc, Code: "inline ");
11970 else
11971 S.Diag(Loc, DiagID: diag::err_inline_namespace_mismatch);
11972
11973 S.Diag(Loc: PrevNS->getLocation(), DiagID: diag::note_previous_definition);
11974 *IsInline = PrevNS->isInline();
11975}
11976
11977/// ActOnStartNamespaceDef - This is called at the start of a namespace
11978/// definition.
11979Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
11980 SourceLocation InlineLoc,
11981 SourceLocation NamespaceLoc,
11982 SourceLocation IdentLoc, IdentifierInfo *II,
11983 SourceLocation LBrace,
11984 const ParsedAttributesView &AttrList,
11985 UsingDirectiveDecl *&UD, bool IsNested) {
11986 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
11987 // For anonymous namespace, take the location of the left brace.
11988 SourceLocation Loc = II ? IdentLoc : LBrace;
11989 bool IsInline = InlineLoc.isValid();
11990 bool IsInvalid = false;
11991 bool IsStd = false;
11992 bool AddToKnown = false;
11993 Scope *DeclRegionScope = NamespcScope->getParent();
11994
11995 NamespaceDecl *PrevNS = nullptr;
11996 if (II) {
11997 // C++ [namespace.std]p7:
11998 // A translation unit shall not declare namespace std to be an inline
11999 // namespace (9.8.2).
12000 //
12001 // Precondition: the std namespace is in the file scope and is declared to
12002 // be inline
12003 auto DiagnoseInlineStdNS = [&]() {
12004 assert(IsInline && II->isStr("std") &&
12005 CurContext->getRedeclContext()->isTranslationUnit() &&
12006 "Precondition of DiagnoseInlineStdNS not met");
12007 Diag(Loc: InlineLoc, DiagID: diag::err_inline_namespace_std)
12008 << SourceRange(InlineLoc, InlineLoc.getLocWithOffset(Offset: 6));
12009 IsInline = false;
12010 };
12011 // C++ [namespace.def]p2:
12012 // The identifier in an original-namespace-definition shall not
12013 // have been previously defined in the declarative region in
12014 // which the original-namespace-definition appears. The
12015 // identifier in an original-namespace-definition is the name of
12016 // the namespace. Subsequently in that declarative region, it is
12017 // treated as an original-namespace-name.
12018 //
12019 // Since namespace names are unique in their scope, and we don't
12020 // look through using directives, just look for any ordinary names
12021 // as if by qualified name lookup.
12022 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
12023 RedeclarationKind::ForExternalRedeclaration);
12024 LookupQualifiedName(R, LookupCtx: CurContext->getRedeclContext());
12025 NamedDecl *PrevDecl =
12026 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
12027 PrevNS = dyn_cast_or_null<NamespaceDecl>(Val: PrevDecl);
12028
12029 if (PrevNS) {
12030 // This is an extended namespace definition.
12031 if (IsInline && II->isStr(Str: "std") &&
12032 CurContext->getRedeclContext()->isTranslationUnit())
12033 DiagnoseInlineStdNS();
12034 else if (IsInline != PrevNS->isInline())
12035 DiagnoseNamespaceInlineMismatch(S&: *this, KeywordLoc: NamespaceLoc, Loc, II,
12036 IsInline: &IsInline, PrevNS);
12037 } else if (PrevDecl) {
12038 // This is an invalid name redefinition.
12039 Diag(Loc, DiagID: diag::err_redefinition_different_kind)
12040 << II;
12041 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_definition);
12042 IsInvalid = true;
12043 // Continue on to push Namespc as current DeclContext and return it.
12044 } else if (II->isStr(Str: "std") &&
12045 CurContext->getRedeclContext()->isTranslationUnit()) {
12046 if (IsInline)
12047 DiagnoseInlineStdNS();
12048 // This is the first "real" definition of the namespace "std", so update
12049 // our cache of the "std" namespace to point at this definition.
12050 PrevNS = getStdNamespace();
12051 IsStd = true;
12052 AddToKnown = !IsInline;
12053 } else {
12054 // We've seen this namespace for the first time.
12055 AddToKnown = !IsInline;
12056 }
12057 } else {
12058 // Anonymous namespaces.
12059
12060 // Determine whether the parent already has an anonymous namespace.
12061 DeclContext *Parent = CurContext->getRedeclContext();
12062 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Val: Parent)) {
12063 PrevNS = TU->getAnonymousNamespace();
12064 } else {
12065 NamespaceDecl *ND = cast<NamespaceDecl>(Val: Parent);
12066 PrevNS = ND->getAnonymousNamespace();
12067 }
12068
12069 if (PrevNS && IsInline != PrevNS->isInline())
12070 DiagnoseNamespaceInlineMismatch(S&: *this, KeywordLoc: NamespaceLoc, Loc: NamespaceLoc, II,
12071 IsInline: &IsInline, PrevNS);
12072 }
12073
12074 NamespaceDecl *Namespc = NamespaceDecl::Create(
12075 C&: Context, DC: CurContext, Inline: IsInline, StartLoc, IdLoc: Loc, Id: II, PrevDecl: PrevNS, Nested: IsNested);
12076 if (IsInvalid)
12077 Namespc->setInvalidDecl();
12078
12079 ProcessDeclAttributeList(S: DeclRegionScope, D: Namespc, AttrList);
12080 AddPragmaAttributes(S: DeclRegionScope, D: Namespc);
12081 ProcessAPINotes(D: Namespc);
12082
12083 // FIXME: Should we be merging attributes?
12084 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
12085 PushNamespaceVisibilityAttr(Attr, Loc);
12086
12087 if (IsStd)
12088 StdNamespace = Namespc;
12089 if (AddToKnown)
12090 KnownNamespaces[Namespc] = false;
12091
12092 if (II) {
12093 PushOnScopeChains(D: Namespc, S: DeclRegionScope);
12094 } else {
12095 // Link the anonymous namespace into its parent.
12096 DeclContext *Parent = CurContext->getRedeclContext();
12097 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Val: Parent)) {
12098 TU->setAnonymousNamespace(Namespc);
12099 } else {
12100 cast<NamespaceDecl>(Val: Parent)->setAnonymousNamespace(Namespc);
12101 }
12102
12103 CurContext->addDecl(D: Namespc);
12104
12105 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
12106 // behaves as if it were replaced by
12107 // namespace unique { /* empty body */ }
12108 // using namespace unique;
12109 // namespace unique { namespace-body }
12110 // where all occurrences of 'unique' in a translation unit are
12111 // replaced by the same identifier and this identifier differs
12112 // from all other identifiers in the entire program.
12113
12114 // We just create the namespace with an empty name and then add an
12115 // implicit using declaration, just like the standard suggests.
12116 //
12117 // CodeGen enforces the "universally unique" aspect by giving all
12118 // declarations semantically contained within an anonymous
12119 // namespace internal linkage.
12120
12121 if (!PrevNS) {
12122 UD = UsingDirectiveDecl::Create(C&: Context, DC: Parent,
12123 /* 'using' */ UsingLoc: LBrace,
12124 /* 'namespace' */ NamespaceLoc: SourceLocation(),
12125 /* qualifier */ QualifierLoc: NestedNameSpecifierLoc(),
12126 /* identifier */ IdentLoc: SourceLocation(),
12127 Nominated: Namespc,
12128 /* Ancestor */ CommonAncestor: Parent);
12129 UD->setImplicit();
12130 Parent->addDecl(D: UD);
12131 }
12132 }
12133
12134 ActOnDocumentableDecl(D: Namespc);
12135
12136 // Although we could have an invalid decl (i.e. the namespace name is a
12137 // redefinition), push it as current DeclContext and try to continue parsing.
12138 // FIXME: We should be able to push Namespc here, so that the each DeclContext
12139 // for the namespace has the declarations that showed up in that particular
12140 // namespace definition.
12141 PushDeclContext(S: NamespcScope, DC: Namespc);
12142 return Namespc;
12143}
12144
12145/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
12146/// is a namespace alias, returns the namespace it points to.
12147static inline NamespaceDecl *getNamespaceDecl(NamespaceBaseDecl *D) {
12148 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(Val: D))
12149 return AD->getNamespace();
12150 return dyn_cast_or_null<NamespaceDecl>(Val: D);
12151}
12152
12153void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
12154 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Val: Dcl);
12155 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
12156 Namespc->setRBraceLoc(RBrace);
12157 PopDeclContext();
12158 if (Namespc->hasAttr<VisibilityAttr>())
12159 PopPragmaVisibility(IsNamespaceEnd: true, EndLoc: RBrace);
12160 // If this namespace contains an export-declaration, export it now.
12161 if (DeferredExportedNamespaces.erase(Ptr: Namespc))
12162 Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
12163}
12164
12165CXXRecordDecl *Sema::getStdBadAlloc() const {
12166 return cast_or_null<CXXRecordDecl>(
12167 Val: StdBadAlloc.get(Source: Context.getExternalSource()));
12168}
12169
12170EnumDecl *Sema::getStdAlignValT() const {
12171 return cast_or_null<EnumDecl>(Val: StdAlignValT.get(Source: Context.getExternalSource()));
12172}
12173
12174NamespaceDecl *Sema::getStdNamespace() const {
12175 return cast_or_null<NamespaceDecl>(
12176 Val: StdNamespace.get(Source: Context.getExternalSource()));
12177}
12178
12179namespace {
12180
12181enum UnsupportedSTLSelect {
12182 USS_InvalidMember,
12183 USS_MissingMember,
12184 USS_NonTrivial,
12185 USS_Other
12186};
12187
12188struct InvalidSTLDiagnoser {
12189 Sema &S;
12190 SourceLocation Loc;
12191 QualType TyForDiags;
12192
12193 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
12194 const VarDecl *VD = nullptr) {
12195 {
12196 auto D = S.Diag(Loc, DiagID: diag::err_std_compare_type_not_supported)
12197 << TyForDiags << ((int)Sel);
12198 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
12199 assert(!Name.empty());
12200 D << Name;
12201 }
12202 }
12203 if (Sel == USS_InvalidMember) {
12204 S.Diag(Loc: VD->getLocation(), DiagID: diag::note_var_declared_here)
12205 << VD << VD->getSourceRange();
12206 }
12207 return QualType();
12208 }
12209};
12210} // namespace
12211
12212QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
12213 SourceLocation Loc,
12214 ComparisonCategoryUsage Usage) {
12215 assert(getLangOpts().CPlusPlus &&
12216 "Looking for comparison category type outside of C++.");
12217
12218 // Use an elaborated type for diagnostics which has a name containing the
12219 // prepended 'std' namespace but not any inline namespace names.
12220 auto TyForDiags = [&](ComparisonCategoryInfo *Info) {
12221 NestedNameSpecifier Qualifier(Context, getStdNamespace(),
12222 /*Prefix=*/std::nullopt);
12223 return Context.getTagType(Keyword: ElaboratedTypeKeyword::None, Qualifier,
12224 TD: Info->Record,
12225 /*OwnsTag=*/false);
12226 };
12227
12228 // Check if we've already successfully checked the comparison category type
12229 // before. If so, skip checking it again.
12230 ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
12231 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) {
12232 // The only thing we need to check is that the type has a reachable
12233 // definition in the current context.
12234 if (RequireCompleteType(Loc, T: TyForDiags(Info), DiagID: diag::err_incomplete_type))
12235 return QualType();
12236
12237 return Info->getType();
12238 }
12239
12240 // If lookup failed
12241 if (!Info) {
12242 std::string NameForDiags = "std::";
12243 NameForDiags += ComparisonCategories::getCategoryString(Kind);
12244 Diag(Loc, DiagID: diag::err_implied_comparison_category_type_not_found)
12245 << NameForDiags << (int)Usage;
12246 return QualType();
12247 }
12248
12249 assert(Info->Kind == Kind);
12250 assert(Info->Record);
12251
12252 // Update the Record decl in case we encountered a forward declaration on our
12253 // first pass. FIXME: This is a bit of a hack.
12254 if (Info->Record->hasDefinition())
12255 Info->Record = Info->Record->getDefinition();
12256
12257 if (RequireCompleteType(Loc, T: TyForDiags(Info), DiagID: diag::err_incomplete_type))
12258 return QualType();
12259
12260 InvalidSTLDiagnoser UnsupportedSTLError{.S: *this, .Loc: Loc, .TyForDiags: TyForDiags(Info)};
12261
12262 if (!Info->Record->isTriviallyCopyable())
12263 return UnsupportedSTLError(USS_NonTrivial);
12264
12265 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
12266 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
12267 // Tolerate empty base classes.
12268 if (Base->isEmpty())
12269 continue;
12270 // Reject STL implementations which have at least one non-empty base.
12271 return UnsupportedSTLError();
12272 }
12273
12274 // Check that the STL has implemented the types using a single integer field.
12275 // This expectation allows better codegen for builtin operators. We require:
12276 // (1) The class has exactly one field.
12277 // (2) The field is an integral or enumeration type.
12278 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
12279 if (std::distance(first: FIt, last: FEnd) != 1 ||
12280 !FIt->getType()->isIntegralOrEnumerationType()) {
12281 return UnsupportedSTLError();
12282 }
12283
12284 // Build each of the require values and store them in Info.
12285 for (ComparisonCategoryResult CCR :
12286 ComparisonCategories::getPossibleResultsForType(Type: Kind)) {
12287 StringRef MemName = ComparisonCategories::getResultString(Kind: CCR);
12288 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(ValueKind: CCR);
12289
12290 if (!ValInfo)
12291 return UnsupportedSTLError(USS_MissingMember, MemName);
12292
12293 VarDecl *VD = ValInfo->VD;
12294 assert(VD && "should not be null!");
12295
12296 // Attempt to diagnose reasons why the STL definition of this type
12297 // might be foobar, including it failing to be a constant expression.
12298 // TODO Handle more ways the lookup or result can be invalid.
12299 if (!VD->isStaticDataMember() ||
12300 !VD->isUsableInConstantExpressions(C: Context))
12301 return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
12302
12303 // Attempt to evaluate the var decl as a constant expression and extract
12304 // the value of its first field as a ICE. If this fails, the STL
12305 // implementation is not supported.
12306 if (!ValInfo->hasValidIntValue())
12307 return UnsupportedSTLError();
12308
12309 MarkVariableReferenced(Loc, Var: VD);
12310 }
12311
12312 // We've successfully built the required types and expressions. Update
12313 // the cache and return the newly cached value.
12314 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
12315 return Info->getType();
12316}
12317
12318NamespaceDecl *Sema::getOrCreateStdNamespace() {
12319 if (!StdNamespace) {
12320 // The "std" namespace has not yet been defined, so build one implicitly.
12321 StdNamespace = NamespaceDecl::Create(
12322 C&: Context, DC: Context.getTranslationUnitDecl(),
12323 /*Inline=*/false, StartLoc: SourceLocation(), IdLoc: SourceLocation(),
12324 Id: &PP.getIdentifierTable().get(Name: "std"),
12325 /*PrevDecl=*/nullptr, /*Nested=*/false);
12326 getStdNamespace()->setImplicit(true);
12327 // We want the created NamespaceDecl to be available for redeclaration
12328 // lookups, but not for regular name lookups.
12329 Context.getTranslationUnitDecl()->addDecl(D: getStdNamespace());
12330 getStdNamespace()->clearIdentifierNamespace();
12331 }
12332
12333 return getStdNamespace();
12334}
12335
12336static bool isStdClassTemplate(Sema &S, QualType SugaredType, QualType *TypeArg,
12337 const char *ClassName,
12338 ClassTemplateDecl **CachedDecl,
12339 const Decl **MalformedDecl) {
12340 // We're looking for implicit instantiations of
12341 // template <typename U> class std::{ClassName}.
12342
12343 if (!S.StdNamespace) // If we haven't seen namespace std yet, this can't be
12344 // it.
12345 return false;
12346
12347 auto ReportMatchingNameAsMalformed = [&](NamedDecl *D) {
12348 if (!MalformedDecl)
12349 return;
12350 if (!D)
12351 D = SugaredType->getAsTagDecl();
12352 if (!D || !D->isInStdNamespace())
12353 return;
12354 IdentifierInfo *II = D->getDeclName().getAsIdentifierInfo();
12355 if (II && II == &S.PP.getIdentifierTable().get(Name: ClassName))
12356 *MalformedDecl = D;
12357 };
12358
12359 ClassTemplateDecl *Template = nullptr;
12360 ArrayRef<TemplateArgument> Arguments;
12361 if (const TemplateSpecializationType *TST =
12362 SugaredType->getAsNonAliasTemplateSpecializationType()) {
12363 Template = dyn_cast_or_null<ClassTemplateDecl>(
12364 Val: TST->getTemplateName().getAsTemplateDecl());
12365 Arguments = TST->template_arguments();
12366 } else if (const auto *TT = SugaredType->getAs<TagType>()) {
12367 Template = TT->getTemplateDecl();
12368 Arguments = TT->getTemplateArgs(Ctx: S.Context);
12369 }
12370
12371 if (!Template) {
12372 ReportMatchingNameAsMalformed(SugaredType->getAsTagDecl());
12373 return false;
12374 }
12375
12376 if (!*CachedDecl) {
12377 // Haven't recognized std::{ClassName} yet, maybe this is it.
12378 // FIXME: It seems we should just reuse LookupStdClassTemplate but the
12379 // semantics of this are slightly different, most notably the existing
12380 // "lookup" semantics explicitly diagnose an invalid definition as an
12381 // error.
12382 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
12383 if (TemplateClass->getIdentifier() !=
12384 &S.PP.getIdentifierTable().get(Name: ClassName) ||
12385 !S.getStdNamespace()->InEnclosingNamespaceSetOf(
12386 NS: TemplateClass->getNonTransparentDeclContext()))
12387 return false;
12388 // This is a template called std::{ClassName}, but is it the right
12389 // template?
12390 TemplateParameterList *Params = Template->getTemplateParameters();
12391 if (Params->getMinRequiredArguments() != 1 ||
12392 !isa<TemplateTypeParmDecl>(Val: Params->getParam(Idx: 0)) ||
12393 Params->getParam(Idx: 0)->isTemplateParameterPack()) {
12394 if (MalformedDecl)
12395 *MalformedDecl = TemplateClass;
12396 return false;
12397 }
12398
12399 // It's the right template.
12400 *CachedDecl = Template;
12401 }
12402
12403 if (Template->getCanonicalDecl() != (*CachedDecl)->getCanonicalDecl())
12404 return false;
12405
12406 // This is an instance of std::{ClassName}. Find the argument type.
12407 if (TypeArg) {
12408 QualType ArgType = Arguments[0].getAsType();
12409 // FIXME: Since TST only has as-written arguments, we have to perform the
12410 // only kind of conversion applicable to type arguments; in Objective-C ARC:
12411 // - If an explicitly-specified template argument type is a lifetime type
12412 // with no lifetime qualifier, the __strong lifetime qualifier is
12413 // inferred.
12414 if (S.getLangOpts().ObjCAutoRefCount && ArgType->isObjCLifetimeType() &&
12415 !ArgType.getObjCLifetime()) {
12416 Qualifiers Qs;
12417 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
12418 ArgType = S.Context.getQualifiedType(T: ArgType, Qs);
12419 }
12420 *TypeArg = ArgType;
12421 }
12422
12423 return true;
12424}
12425
12426bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
12427 assert(getLangOpts().CPlusPlus &&
12428 "Looking for std::initializer_list outside of C++.");
12429
12430 // We're looking for implicit instantiations of
12431 // template <typename E> class std::initializer_list.
12432
12433 return isStdClassTemplate(S&: *this, SugaredType: Ty, TypeArg: Element, ClassName: "initializer_list",
12434 CachedDecl: &StdInitializerList, /*MalformedDecl=*/nullptr);
12435}
12436
12437bool Sema::isStdTypeIdentity(QualType Ty, QualType *Element,
12438 const Decl **MalformedDecl) {
12439 assert(getLangOpts().CPlusPlus &&
12440 "Looking for std::type_identity outside of C++.");
12441
12442 // We're looking for implicit instantiations of
12443 // template <typename T> struct std::type_identity.
12444
12445 return isStdClassTemplate(S&: *this, SugaredType: Ty, TypeArg: Element, ClassName: "type_identity",
12446 CachedDecl: &StdTypeIdentity, MalformedDecl);
12447}
12448
12449static ClassTemplateDecl *LookupStdClassTemplate(Sema &S, SourceLocation Loc,
12450 const char *ClassName,
12451 bool *WasMalformed) {
12452 if (!S.StdNamespace)
12453 return nullptr;
12454
12455 LookupResult Result(S, &S.PP.getIdentifierTable().get(Name: ClassName), Loc,
12456 Sema::LookupOrdinaryName);
12457 if (!S.LookupQualifiedName(R&: Result, LookupCtx: S.getStdNamespace()))
12458 return nullptr;
12459
12460 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
12461 if (!Template) {
12462 Result.suppressDiagnostics();
12463 // We found something weird. Complain about the first thing we found.
12464 NamedDecl *Found = *Result.begin();
12465 S.Diag(Loc: Found->getLocation(), DiagID: diag::err_malformed_std_class_template)
12466 << ClassName;
12467 if (WasMalformed)
12468 *WasMalformed = true;
12469 return nullptr;
12470 }
12471
12472 // We found some template with the correct name. Now verify that it's
12473 // correct.
12474 TemplateParameterList *Params = Template->getTemplateParameters();
12475 if (Params->getMinRequiredArguments() != 1 ||
12476 !isa<TemplateTypeParmDecl>(Val: Params->getParam(Idx: 0))) {
12477 S.Diag(Loc: Template->getLocation(), DiagID: diag::err_malformed_std_class_template)
12478 << ClassName;
12479 if (WasMalformed)
12480 *WasMalformed = true;
12481 return nullptr;
12482 }
12483
12484 return Template;
12485}
12486
12487static QualType BuildStdClassTemplate(Sema &S, ClassTemplateDecl *CTD,
12488 QualType TypeParam, SourceLocation Loc) {
12489 assert(S.getStdNamespace());
12490 TemplateArgumentListInfo Args(Loc, Loc);
12491 auto TSI = S.Context.getTrivialTypeSourceInfo(T: TypeParam, Loc);
12492 Args.addArgument(Loc: TemplateArgumentLoc(TemplateArgument(TypeParam), TSI));
12493
12494 return S.CheckTemplateIdType(Keyword: ElaboratedTypeKeyword::None, Template: TemplateName(CTD),
12495 TemplateLoc: Loc, TemplateArgs&: Args, /*Scope=*/nullptr,
12496 /*ForNestedNameSpecifier=*/false);
12497}
12498
12499QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
12500 if (!StdInitializerList) {
12501 bool WasMalformed = false;
12502 StdInitializerList =
12503 LookupStdClassTemplate(S&: *this, Loc, ClassName: "initializer_list", WasMalformed: &WasMalformed);
12504 if (!StdInitializerList) {
12505 if (!WasMalformed)
12506 Diag(Loc, DiagID: diag::err_implied_std_initializer_list_not_found);
12507 return QualType();
12508 }
12509 }
12510 return BuildStdClassTemplate(S&: *this, CTD: StdInitializerList, TypeParam: Element, Loc);
12511}
12512
12513QualType Sema::tryBuildStdTypeIdentity(QualType Type, SourceLocation Loc) {
12514 if (!StdTypeIdentity) {
12515 StdTypeIdentity = LookupStdClassTemplate(S&: *this, Loc, ClassName: "type_identity",
12516 /*WasMalformed=*/nullptr);
12517 if (!StdTypeIdentity)
12518 return QualType();
12519 }
12520 return BuildStdClassTemplate(S&: *this, CTD: StdTypeIdentity, TypeParam: Type, Loc);
12521}
12522
12523bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
12524 // C++ [dcl.init.list]p2:
12525 // A constructor is an initializer-list constructor if its first parameter
12526 // is of type std::initializer_list<E> or reference to possibly cv-qualified
12527 // std::initializer_list<E> for some type E, and either there are no other
12528 // parameters or else all other parameters have default arguments.
12529 if (!Ctor->hasOneParamOrDefaultArgs())
12530 return false;
12531
12532 QualType ArgType = Ctor->getParamDecl(i: 0)->getType();
12533 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
12534 ArgType = RT->getPointeeType().getUnqualifiedType();
12535
12536 return isStdInitializerList(Ty: ArgType, Element: nullptr);
12537}
12538
12539/// Determine whether a using statement is in a context where it will be
12540/// apply in all contexts.
12541static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
12542 switch (CurContext->getDeclKind()) {
12543 case Decl::TranslationUnit:
12544 return true;
12545 case Decl::LinkageSpec:
12546 return IsUsingDirectiveInToplevelContext(CurContext: CurContext->getParent());
12547 default:
12548 return false;
12549 }
12550}
12551
12552namespace {
12553
12554// Callback to only accept typo corrections that are namespaces.
12555class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
12556public:
12557 bool ValidateCandidate(const TypoCorrection &candidate) override {
12558 if (NamedDecl *ND = candidate.getCorrectionDecl())
12559 return isa<NamespaceDecl>(Val: ND) || isa<NamespaceAliasDecl>(Val: ND);
12560 return false;
12561 }
12562
12563 std::unique_ptr<CorrectionCandidateCallback> clone() override {
12564 return std::make_unique<NamespaceValidatorCCC>(args&: *this);
12565 }
12566};
12567
12568}
12569
12570static void DiagnoseInvisibleNamespace(const TypoCorrection &Corrected,
12571 Sema &S) {
12572 auto *ND = cast<NamespaceDecl>(Val: Corrected.getFoundDecl());
12573 Module *M = ND->getOwningModule();
12574 assert(M && "hidden namespace definition not in a module?");
12575
12576 if (M->isExplicitGlobalModule())
12577 S.Diag(Loc: Corrected.getCorrectionRange().getBegin(),
12578 DiagID: diag::err_module_unimported_use_header)
12579 << (int)Sema::MissingImportKind::Declaration << Corrected.getFoundDecl()
12580 << /*Header Name*/ false;
12581 else
12582 S.Diag(Loc: Corrected.getCorrectionRange().getBegin(),
12583 DiagID: diag::err_module_unimported_use)
12584 << (int)Sema::MissingImportKind::Declaration << Corrected.getFoundDecl()
12585 << M->getTopLevelModuleName();
12586}
12587
12588static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
12589 CXXScopeSpec &SS,
12590 SourceLocation IdentLoc,
12591 IdentifierInfo *Ident) {
12592 R.clear();
12593 NamespaceValidatorCCC CCC{};
12594 if (TypoCorrection Corrected =
12595 S.CorrectTypo(Typo: R.getLookupNameInfo(), LookupKind: R.getLookupKind(), S: Sc, SS: &SS, CCC,
12596 Mode: CorrectTypoKind::ErrorRecovery)) {
12597 // Generally we find it is confusing more than helpful to diagnose the
12598 // invisible namespace.
12599 // See https://github.com/llvm/llvm-project/issues/73893.
12600 //
12601 // However, we should diagnose when the users are trying to using an
12602 // invisible namespace. So we handle the case specially here.
12603 if (isa_and_nonnull<NamespaceDecl>(Val: Corrected.getFoundDecl()) &&
12604 Corrected.requiresImport()) {
12605 DiagnoseInvisibleNamespace(Corrected, S);
12606 } else if (DeclContext *DC = S.computeDeclContext(SS, EnteringContext: false)) {
12607 std::string CorrectedStr(Corrected.getAsString(LO: S.getLangOpts()));
12608 bool DroppedSpecifier =
12609 Corrected.WillReplaceSpecifier() && Ident->getName() == CorrectedStr;
12610 S.diagnoseTypo(Correction: Corrected,
12611 TypoDiag: S.PDiag(DiagID: diag::err_using_directive_member_suggest)
12612 << Ident << DC << DroppedSpecifier << SS.getRange(),
12613 PrevNote: S.PDiag(DiagID: diag::note_namespace_defined_here));
12614 } else {
12615 S.diagnoseTypo(Correction: Corrected,
12616 TypoDiag: S.PDiag(DiagID: diag::err_using_directive_suggest) << Ident,
12617 PrevNote: S.PDiag(DiagID: diag::note_namespace_defined_here));
12618 }
12619 R.addDecl(D: Corrected.getFoundDecl());
12620 return true;
12621 }
12622 return false;
12623}
12624
12625Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
12626 SourceLocation NamespcLoc, CXXScopeSpec &SS,
12627 SourceLocation IdentLoc,
12628 IdentifierInfo *NamespcName,
12629 const ParsedAttributesView &AttrList) {
12630 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
12631 assert(NamespcName && "Invalid NamespcName.");
12632 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
12633
12634 // Get the innermost enclosing declaration scope.
12635 S = S->getDeclParent();
12636
12637 UsingDirectiveDecl *UDir = nullptr;
12638 NestedNameSpecifier Qualifier = SS.getScopeRep();
12639
12640 // Lookup namespace name.
12641 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
12642 LookupParsedName(R, S, SS: &SS, /*ObjectType=*/QualType());
12643 if (R.isAmbiguous())
12644 return nullptr;
12645
12646 if (R.empty()) {
12647 R.clear();
12648 // Allow "using namespace std;" or "using namespace ::std;" even if
12649 // "std" hasn't been defined yet, for GCC compatibility.
12650 if ((!Qualifier ||
12651 Qualifier.getKind() == NestedNameSpecifier::Kind::Global) &&
12652 NamespcName->isStr(Str: "std")) {
12653 Diag(Loc: IdentLoc, DiagID: diag::ext_using_undefined_std);
12654 R.addDecl(D: getOrCreateStdNamespace());
12655 R.resolveKind();
12656 }
12657 // Otherwise, attempt typo correction.
12658 else
12659 TryNamespaceTypoCorrection(S&: *this, R, Sc: S, SS, IdentLoc, Ident: NamespcName);
12660 }
12661
12662 if (!R.empty()) {
12663 NamedDecl *Named = R.getRepresentativeDecl();
12664 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
12665 assert(NS && "expected namespace decl");
12666
12667 // The use of a nested name specifier may trigger deprecation warnings.
12668 DiagnoseUseOfDecl(D: Named, Locs: IdentLoc);
12669
12670 // C++ [namespace.udir]p1:
12671 // A using-directive specifies that the names in the nominated
12672 // namespace can be used in the scope in which the
12673 // using-directive appears after the using-directive. During
12674 // unqualified name lookup (3.4.1), the names appear as if they
12675 // were declared in the nearest enclosing namespace which
12676 // contains both the using-directive and the nominated
12677 // namespace. [Note: in this context, "contains" means "contains
12678 // directly or indirectly". ]
12679
12680 // Find enclosing context containing both using-directive and
12681 // nominated namespace.
12682 DeclContext *CommonAncestor = NS;
12683 while (CommonAncestor && !CommonAncestor->Encloses(DC: CurContext))
12684 CommonAncestor = CommonAncestor->getParent();
12685
12686 UDir = UsingDirectiveDecl::Create(C&: Context, DC: CurContext, UsingLoc, NamespaceLoc: NamespcLoc,
12687 QualifierLoc: SS.getWithLocInContext(Context),
12688 IdentLoc, Nominated: Named, CommonAncestor);
12689
12690 if (IsUsingDirectiveInToplevelContext(CurContext) &&
12691 !SourceMgr.isInMainFile(Loc: SourceMgr.getExpansionLoc(Loc: IdentLoc))) {
12692 Diag(Loc: IdentLoc, DiagID: diag::warn_using_directive_in_header);
12693 }
12694
12695 PushUsingDirective(S, UDir);
12696 } else {
12697 Diag(Loc: IdentLoc, DiagID: diag::err_expected_namespace_name) << SS.getRange();
12698 }
12699
12700 if (UDir) {
12701 ProcessDeclAttributeList(S, D: UDir, AttrList);
12702 ProcessAPINotes(D: UDir);
12703 }
12704
12705 return UDir;
12706}
12707
12708void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
12709 // If the scope has an associated entity and the using directive is at
12710 // namespace or translation unit scope, add the UsingDirectiveDecl into
12711 // its lookup structure so qualified name lookup can find it.
12712 DeclContext *Ctx = S->getEntity();
12713 if (Ctx && !Ctx->isFunctionOrMethod())
12714 Ctx->addDecl(D: UDir);
12715 else
12716 // Otherwise, it is at block scope. The using-directives will affect lookup
12717 // only to the end of the scope.
12718 S->PushUsingDirective(UDir);
12719}
12720
12721Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
12722 SourceLocation UsingLoc,
12723 SourceLocation TypenameLoc, CXXScopeSpec &SS,
12724 UnqualifiedId &Name,
12725 SourceLocation EllipsisLoc,
12726 const ParsedAttributesView &AttrList) {
12727 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
12728
12729 if (SS.isEmpty()) {
12730 Diag(Loc: Name.getBeginLoc(), DiagID: diag::err_using_requires_qualname);
12731 return nullptr;
12732 }
12733
12734 switch (Name.getKind()) {
12735 case UnqualifiedIdKind::IK_ImplicitSelfParam:
12736 case UnqualifiedIdKind::IK_Identifier:
12737 case UnqualifiedIdKind::IK_OperatorFunctionId:
12738 case UnqualifiedIdKind::IK_LiteralOperatorId:
12739 case UnqualifiedIdKind::IK_ConversionFunctionId:
12740 break;
12741
12742 case UnqualifiedIdKind::IK_ConstructorName:
12743 case UnqualifiedIdKind::IK_ConstructorTemplateId:
12744 // C++11 inheriting constructors.
12745 Diag(Loc: Name.getBeginLoc(),
12746 DiagID: getLangOpts().CPlusPlus11
12747 ? diag::warn_cxx98_compat_using_decl_constructor
12748 : diag::err_using_decl_constructor)
12749 << SS.getRange();
12750
12751 if (getLangOpts().CPlusPlus11) break;
12752
12753 return nullptr;
12754
12755 case UnqualifiedIdKind::IK_DestructorName:
12756 Diag(Loc: Name.getBeginLoc(), DiagID: diag::err_using_decl_destructor) << SS.getRange();
12757 return nullptr;
12758
12759 case UnqualifiedIdKind::IK_TemplateId:
12760 Diag(Loc: Name.getBeginLoc(), DiagID: diag::err_using_decl_template_id)
12761 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
12762 return nullptr;
12763
12764 case UnqualifiedIdKind::IK_DeductionGuideName:
12765 llvm_unreachable("cannot parse qualified deduction guide name");
12766 }
12767
12768 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
12769 DeclarationName TargetName = TargetNameInfo.getName();
12770 if (!TargetName)
12771 return nullptr;
12772
12773 // Warn about access declarations.
12774 if (UsingLoc.isInvalid()) {
12775 Diag(Loc: Name.getBeginLoc(), DiagID: getLangOpts().CPlusPlus11
12776 ? diag::err_access_decl
12777 : diag::warn_access_decl_deprecated)
12778 << FixItHint::CreateInsertion(InsertionLoc: SS.getRange().getBegin(), Code: "using ");
12779 }
12780
12781 if (EllipsisLoc.isInvalid()) {
12782 if (DiagnoseUnexpandedParameterPack(SS, UPPC: UPPC_UsingDeclaration) ||
12783 DiagnoseUnexpandedParameterPack(NameInfo: TargetNameInfo, UPPC: UPPC_UsingDeclaration))
12784 return nullptr;
12785 } else {
12786 if (!SS.getScopeRep().containsUnexpandedParameterPack() &&
12787 !TargetNameInfo.containsUnexpandedParameterPack()) {
12788 Diag(Loc: EllipsisLoc, DiagID: diag::err_pack_expansion_without_parameter_packs)
12789 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
12790 EllipsisLoc = SourceLocation();
12791 }
12792 }
12793
12794 NamedDecl *UD =
12795 BuildUsingDeclaration(S, AS, UsingLoc, HasTypenameKeyword: TypenameLoc.isValid(), TypenameLoc,
12796 SS, NameInfo: TargetNameInfo, EllipsisLoc, AttrList,
12797 /*IsInstantiation*/ false,
12798 IsUsingIfExists: AttrList.hasAttribute(K: ParsedAttr::AT_UsingIfExists));
12799 if (UD)
12800 PushOnScopeChains(D: UD, S, /*AddToContext*/ false);
12801
12802 return UD;
12803}
12804
12805Decl *Sema::ActOnUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
12806 SourceLocation UsingLoc,
12807 SourceLocation EnumLoc, SourceRange TyLoc,
12808 const IdentifierInfo &II, ParsedType Ty,
12809 const CXXScopeSpec &SS) {
12810 TypeSourceInfo *TSI = nullptr;
12811 SourceLocation IdentLoc = TyLoc.getBegin();
12812 QualType EnumTy = GetTypeFromParser(Ty, TInfo: &TSI);
12813 if (EnumTy.isNull()) {
12814 Diag(Loc: IdentLoc, DiagID: isDependentScopeSpecifier(SS)
12815 ? diag::err_using_enum_is_dependent
12816 : diag::err_unknown_typename)
12817 << II.getName()
12818 << SourceRange(SS.isValid() ? SS.getBeginLoc() : IdentLoc,
12819 TyLoc.getEnd());
12820 return nullptr;
12821 }
12822
12823 if (EnumTy->isDependentType()) {
12824 Diag(Loc: IdentLoc, DiagID: diag::err_using_enum_is_dependent);
12825 return nullptr;
12826 }
12827
12828 auto *Enum = EnumTy->getAsEnumDecl();
12829 if (!Enum) {
12830 Diag(Loc: IdentLoc, DiagID: diag::err_using_enum_not_enum) << EnumTy;
12831 return nullptr;
12832 }
12833
12834 if (TSI == nullptr)
12835 TSI = Context.getTrivialTypeSourceInfo(T: EnumTy, Loc: IdentLoc);
12836
12837 auto *UD =
12838 BuildUsingEnumDeclaration(S, AS, UsingLoc, EnumLoc, NameLoc: IdentLoc, EnumType: TSI, ED: Enum);
12839
12840 if (UD)
12841 PushOnScopeChains(D: UD, S, /*AddToContext*/ false);
12842
12843 return UD;
12844}
12845
12846/// Determine whether a using declaration considers the given
12847/// declarations as "equivalent", e.g., if they are redeclarations of
12848/// the same entity or are both typedefs of the same type.
12849static bool
12850IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
12851 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
12852 return true;
12853
12854 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(Val: D1))
12855 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(Val: D2))
12856 return Context.hasSameType(T1: TD1->getUnderlyingType(),
12857 T2: TD2->getUnderlyingType());
12858
12859 // Two using_if_exists using-declarations are equivalent if both are
12860 // unresolved.
12861 if (isa<UnresolvedUsingIfExistsDecl>(Val: D1) &&
12862 isa<UnresolvedUsingIfExistsDecl>(Val: D2))
12863 return true;
12864
12865 return false;
12866}
12867
12868bool Sema::CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Orig,
12869 const LookupResult &Previous,
12870 UsingShadowDecl *&PrevShadow) {
12871 // Diagnose finding a decl which is not from a base class of the
12872 // current class. We do this now because there are cases where this
12873 // function will silently decide not to build a shadow decl, which
12874 // will pre-empt further diagnostics.
12875 //
12876 // We don't need to do this in C++11 because we do the check once on
12877 // the qualifier.
12878 //
12879 // FIXME: diagnose the following if we care enough:
12880 // struct A { int foo; };
12881 // struct B : A { using A::foo; };
12882 // template <class T> struct C : A {};
12883 // template <class T> struct D : C<T> { using B::foo; } // <---
12884 // This is invalid (during instantiation) in C++03 because B::foo
12885 // resolves to the using decl in B, which is not a base class of D<T>.
12886 // We can't diagnose it immediately because C<T> is an unknown
12887 // specialization. The UsingShadowDecl in D<T> then points directly
12888 // to A::foo, which will look well-formed when we instantiate.
12889 // The right solution is to not collapse the shadow-decl chain.
12890 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord())
12891 if (auto *Using = dyn_cast<UsingDecl>(Val: BUD)) {
12892 DeclContext *OrigDC = Orig->getDeclContext();
12893
12894 // Handle enums and anonymous structs.
12895 if (isa<EnumDecl>(Val: OrigDC))
12896 OrigDC = OrigDC->getParent();
12897 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(Val: OrigDC);
12898 while (OrigRec->isAnonymousStructOrUnion())
12899 OrigRec = cast<CXXRecordDecl>(Val: OrigRec->getDeclContext());
12900
12901 if (cast<CXXRecordDecl>(Val: CurContext)->isProvablyNotDerivedFrom(Base: OrigRec)) {
12902 if (OrigDC == CurContext) {
12903 Diag(Loc: Using->getLocation(),
12904 DiagID: diag::err_using_decl_nested_name_specifier_is_current_class)
12905 << Using->getQualifierLoc().getSourceRange();
12906 Diag(Loc: Orig->getLocation(), DiagID: diag::note_using_decl_target);
12907 Using->setInvalidDecl();
12908 return true;
12909 }
12910
12911 Diag(Loc: Using->getQualifierLoc().getBeginLoc(),
12912 DiagID: diag::err_using_decl_nested_name_specifier_is_not_base_class)
12913 << Using->getQualifier() << cast<CXXRecordDecl>(Val: CurContext)
12914 << Using->getQualifierLoc().getSourceRange();
12915 Diag(Loc: Orig->getLocation(), DiagID: diag::note_using_decl_target);
12916 Using->setInvalidDecl();
12917 return true;
12918 }
12919 }
12920
12921 if (Previous.empty()) return false;
12922
12923 NamedDecl *Target = Orig;
12924 if (isa<UsingShadowDecl>(Val: Target))
12925 Target = cast<UsingShadowDecl>(Val: Target)->getTargetDecl();
12926
12927 // If the target happens to be one of the previous declarations, we
12928 // don't have a conflict.
12929 //
12930 // FIXME: but we might be increasing its access, in which case we
12931 // should redeclare it.
12932 NamedDecl *NonTag = nullptr, *Tag = nullptr;
12933 bool FoundEquivalentDecl = false;
12934 for (NamedDecl *Element : Previous) {
12935 NamedDecl *D = Element->getUnderlyingDecl();
12936 // We can have UsingDecls in our Previous results because we use the same
12937 // LookupResult for checking whether the UsingDecl itself is a valid
12938 // redeclaration.
12939 if (isa<UsingDecl>(Val: D) || isa<UsingPackDecl>(Val: D) || isa<UsingEnumDecl>(Val: D))
12940 continue;
12941
12942 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: D)) {
12943 // C++ [class.mem]p19:
12944 // If T is the name of a class, then [every named member other than
12945 // a non-static data member] shall have a name different from T
12946 if (RD->isInjectedClassName() && !isa<FieldDecl>(Val: Target) &&
12947 !isa<IndirectFieldDecl>(Val: Target) &&
12948 !isa<UnresolvedUsingValueDecl>(Val: Target) &&
12949 DiagnoseClassNameShadow(
12950 DC: CurContext,
12951 Info: DeclarationNameInfo(BUD->getDeclName(), BUD->getLocation())))
12952 return true;
12953 }
12954
12955 if (IsEquivalentForUsingDecl(Context, D1: D, D2: Target)) {
12956 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Val: Element))
12957 PrevShadow = Shadow;
12958 FoundEquivalentDecl = true;
12959 } else if (isEquivalentInternalLinkageDeclaration(A: D, B: Target)) {
12960 // We don't conflict with an existing using shadow decl of an equivalent
12961 // declaration, but we're not a redeclaration of it.
12962 FoundEquivalentDecl = true;
12963 }
12964
12965 if (isVisible(D))
12966 (isa<TagDecl>(Val: D) ? Tag : NonTag) = D;
12967 }
12968
12969 if (FoundEquivalentDecl)
12970 return false;
12971
12972 // Always emit a diagnostic for a mismatch between an unresolved
12973 // using_if_exists and a resolved using declaration in either direction.
12974 if (isa<UnresolvedUsingIfExistsDecl>(Val: Target) !=
12975 (isa_and_nonnull<UnresolvedUsingIfExistsDecl>(Val: NonTag))) {
12976 if (!NonTag && !Tag)
12977 return false;
12978 Diag(Loc: BUD->getLocation(), DiagID: diag::err_using_decl_conflict);
12979 Diag(Loc: Target->getLocation(), DiagID: diag::note_using_decl_target);
12980 Diag(Loc: (NonTag ? NonTag : Tag)->getLocation(),
12981 DiagID: diag::note_using_decl_conflict);
12982 BUD->setInvalidDecl();
12983 return true;
12984 }
12985
12986 if (FunctionDecl *FD = Target->getAsFunction()) {
12987 NamedDecl *OldDecl = nullptr;
12988 switch (CheckOverload(S: nullptr, New: FD, OldDecls: Previous, OldDecl,
12989 /*IsForUsingDecl*/ UseMemberUsingDeclRules: true)) {
12990 case OverloadKind::Overload:
12991 return false;
12992
12993 case OverloadKind::NonFunction:
12994 Diag(Loc: BUD->getLocation(), DiagID: diag::err_using_decl_conflict);
12995 break;
12996
12997 // We found a decl with the exact signature.
12998 case OverloadKind::Match:
12999 // If we're in a record, we want to hide the target, so we
13000 // return true (without a diagnostic) to tell the caller not to
13001 // build a shadow decl.
13002 if (CurContext->isRecord())
13003 return true;
13004
13005 // If we're not in a record, this is an error.
13006 Diag(Loc: BUD->getLocation(), DiagID: diag::err_using_decl_conflict);
13007 break;
13008 }
13009
13010 Diag(Loc: Target->getLocation(), DiagID: diag::note_using_decl_target);
13011 Diag(Loc: OldDecl->getLocation(), DiagID: diag::note_using_decl_conflict);
13012 BUD->setInvalidDecl();
13013 return true;
13014 }
13015
13016 // Target is not a function.
13017
13018 if (isa<TagDecl>(Val: Target)) {
13019 // No conflict between a tag and a non-tag.
13020 if (!Tag) return false;
13021
13022 Diag(Loc: BUD->getLocation(), DiagID: diag::err_using_decl_conflict);
13023 Diag(Loc: Target->getLocation(), DiagID: diag::note_using_decl_target);
13024 Diag(Loc: Tag->getLocation(), DiagID: diag::note_using_decl_conflict);
13025 BUD->setInvalidDecl();
13026 return true;
13027 }
13028
13029 // No conflict between a tag and a non-tag.
13030 if (!NonTag) return false;
13031
13032 Diag(Loc: BUD->getLocation(), DiagID: diag::err_using_decl_conflict);
13033 Diag(Loc: Target->getLocation(), DiagID: diag::note_using_decl_target);
13034 Diag(Loc: NonTag->getLocation(), DiagID: diag::note_using_decl_conflict);
13035 BUD->setInvalidDecl();
13036 return true;
13037}
13038
13039/// Determine whether a direct base class is a virtual base class.
13040static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
13041 if (!Derived->getNumVBases())
13042 return false;
13043 for (auto &B : Derived->bases())
13044 if (B.getType()->getAsCXXRecordDecl() == Base)
13045 return B.isVirtual();
13046 llvm_unreachable("not a direct base class");
13047}
13048
13049UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD,
13050 NamedDecl *Orig,
13051 UsingShadowDecl *PrevDecl) {
13052 // If we resolved to another shadow declaration, just coalesce them.
13053 NamedDecl *Target = Orig;
13054 if (isa<UsingShadowDecl>(Val: Target)) {
13055 Target = cast<UsingShadowDecl>(Val: Target)->getTargetDecl();
13056 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
13057 }
13058
13059 NamedDecl *NonTemplateTarget = Target;
13060 if (auto *TargetTD = dyn_cast<TemplateDecl>(Val: Target))
13061 NonTemplateTarget = TargetTD->getTemplatedDecl();
13062
13063 UsingShadowDecl *Shadow;
13064 if (NonTemplateTarget && isa<CXXConstructorDecl>(Val: NonTemplateTarget)) {
13065 UsingDecl *Using = cast<UsingDecl>(Val: BUD);
13066 bool IsVirtualBase =
13067 isVirtualDirectBase(Derived: cast<CXXRecordDecl>(Val: CurContext),
13068 Base: Using->getQualifier().getAsRecordDecl());
13069 Shadow = ConstructorUsingShadowDecl::Create(
13070 C&: Context, DC: CurContext, Loc: Using->getLocation(), Using, Target: Orig, IsVirtual: IsVirtualBase);
13071 } else {
13072 Shadow = UsingShadowDecl::Create(C&: Context, DC: CurContext, Loc: BUD->getLocation(),
13073 Name: Target->getDeclName(), Introducer: BUD, Target);
13074 }
13075 BUD->addShadowDecl(S: Shadow);
13076
13077 Shadow->setAccess(BUD->getAccess());
13078 if (Orig->isInvalidDecl() || BUD->isInvalidDecl())
13079 Shadow->setInvalidDecl();
13080
13081 Shadow->setPreviousDecl(PrevDecl);
13082
13083 if (S)
13084 PushOnScopeChains(D: Shadow, S);
13085 else
13086 CurContext->addDecl(D: Shadow);
13087
13088
13089 return Shadow;
13090}
13091
13092void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
13093 if (Shadow->getDeclName().getNameKind() ==
13094 DeclarationName::CXXConversionFunctionName)
13095 cast<CXXRecordDecl>(Val: Shadow->getDeclContext())->removeConversion(Old: Shadow);
13096
13097 // Remove it from the DeclContext...
13098 Shadow->getDeclContext()->removeDecl(D: Shadow);
13099
13100 // ...and the scope, if applicable...
13101 if (S) {
13102 S->RemoveDecl(D: Shadow);
13103 IdResolver.RemoveDecl(D: Shadow);
13104 }
13105
13106 // ...and the using decl.
13107 Shadow->getIntroducer()->removeShadowDecl(S: Shadow);
13108
13109 // TODO: complain somehow if Shadow was used. It shouldn't
13110 // be possible for this to happen, because...?
13111}
13112
13113/// Find the base specifier for a base class with the given type.
13114static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
13115 QualType DesiredBase,
13116 bool &AnyDependentBases) {
13117 // Check whether the named type is a direct base class.
13118 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
13119 for (auto &Base : Derived->bases()) {
13120 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
13121 if (CanonicalDesiredBase == BaseType)
13122 return &Base;
13123 if (BaseType->isDependentType())
13124 AnyDependentBases = true;
13125 }
13126 return nullptr;
13127}
13128
13129namespace {
13130class UsingValidatorCCC final : public CorrectionCandidateCallback {
13131public:
13132 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
13133 NestedNameSpecifier NNS, CXXRecordDecl *RequireMemberOf)
13134 : HasTypenameKeyword(HasTypenameKeyword),
13135 IsInstantiation(IsInstantiation), OldNNS(NNS),
13136 RequireMemberOf(RequireMemberOf) {}
13137
13138 bool ValidateCandidate(const TypoCorrection &Candidate) override {
13139 NamedDecl *ND = Candidate.getCorrectionDecl();
13140
13141 // Keywords are not valid here.
13142 if (!ND || isa<NamespaceDecl>(Val: ND))
13143 return false;
13144
13145 // Completely unqualified names are invalid for a 'using' declaration.
13146 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
13147 return false;
13148
13149 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
13150 // reject.
13151
13152 if (RequireMemberOf) {
13153 auto *FoundRecord = dyn_cast<CXXRecordDecl>(Val: ND);
13154 if (FoundRecord && FoundRecord->isInjectedClassName()) {
13155 // No-one ever wants a using-declaration to name an injected-class-name
13156 // of a base class, unless they're declaring an inheriting constructor.
13157 ASTContext &Ctx = ND->getASTContext();
13158 if (!Ctx.getLangOpts().CPlusPlus11)
13159 return false;
13160 CanQualType FoundType = Ctx.getCanonicalTagType(TD: FoundRecord);
13161
13162 // Check that the injected-class-name is named as a member of its own
13163 // type; we don't want to suggest 'using Derived::Base;', since that
13164 // means something else.
13165 NestedNameSpecifier Specifier = Candidate.WillReplaceSpecifier()
13166 ? Candidate.getCorrectionSpecifier()
13167 : OldNNS;
13168 if (Specifier.getKind() != NestedNameSpecifier::Kind::Type ||
13169 !Ctx.hasSameType(T1: QualType(Specifier.getAsType(), 0), T2: FoundType))
13170 return false;
13171
13172 // Check that this inheriting constructor declaration actually names a
13173 // direct base class of the current class.
13174 bool AnyDependentBases = false;
13175 if (!findDirectBaseWithType(Derived: RequireMemberOf,
13176 DesiredBase: Ctx.getCanonicalTagType(TD: FoundRecord),
13177 AnyDependentBases) &&
13178 !AnyDependentBases)
13179 return false;
13180 } else {
13181 auto *RD = dyn_cast<CXXRecordDecl>(Val: ND->getDeclContext());
13182 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(Base: RD))
13183 return false;
13184
13185 // FIXME: Check that the base class member is accessible?
13186 }
13187 } else {
13188 auto *FoundRecord = dyn_cast<CXXRecordDecl>(Val: ND);
13189 if (FoundRecord && FoundRecord->isInjectedClassName())
13190 return false;
13191 }
13192
13193 if (isa<TypeDecl>(Val: ND))
13194 return HasTypenameKeyword || !IsInstantiation;
13195
13196 return !HasTypenameKeyword;
13197 }
13198
13199 std::unique_ptr<CorrectionCandidateCallback> clone() override {
13200 return std::make_unique<UsingValidatorCCC>(args&: *this);
13201 }
13202
13203private:
13204 bool HasTypenameKeyword;
13205 bool IsInstantiation;
13206 NestedNameSpecifier OldNNS;
13207 CXXRecordDecl *RequireMemberOf;
13208};
13209} // end anonymous namespace
13210
13211void Sema::FilterUsingLookup(Scope *S, LookupResult &Previous) {
13212 // It is really dumb that we have to do this.
13213 LookupResult::Filter F = Previous.makeFilter();
13214 while (F.hasNext()) {
13215 NamedDecl *D = F.next();
13216 if (!isDeclInScope(D, Ctx: CurContext, S))
13217 F.erase();
13218 // If we found a local extern declaration that's not ordinarily visible,
13219 // and this declaration is being added to a non-block scope, ignore it.
13220 // We're only checking for scope conflicts here, not also for violations
13221 // of the linkage rules.
13222 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
13223 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
13224 F.erase();
13225 }
13226 F.done();
13227}
13228
13229NamedDecl *Sema::BuildUsingDeclaration(
13230 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
13231 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
13232 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
13233 const ParsedAttributesView &AttrList, bool IsInstantiation,
13234 bool IsUsingIfExists) {
13235 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
13236 SourceLocation IdentLoc = NameInfo.getLoc();
13237 assert(IdentLoc.isValid() && "Invalid TargetName location.");
13238
13239 // FIXME: We ignore attributes for now.
13240
13241 // For an inheriting constructor declaration, the name of the using
13242 // declaration is the name of a constructor in this class, not in the
13243 // base class.
13244 DeclarationNameInfo UsingName = NameInfo;
13245 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
13246 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: CurContext))
13247 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
13248 Ty: Context.getCanonicalTagType(TD: RD)));
13249
13250 // Do the redeclaration lookup in the current scope.
13251 LookupResult Previous(*this, UsingName, LookupUsingDeclName,
13252 RedeclarationKind::ForVisibleRedeclaration);
13253 Previous.setHideTags(false);
13254 if (S) {
13255 LookupName(R&: Previous, S);
13256
13257 FilterUsingLookup(S, Previous);
13258 } else {
13259 assert(IsInstantiation && "no scope in non-instantiation");
13260 if (CurContext->isRecord())
13261 LookupQualifiedName(R&: Previous, LookupCtx: CurContext);
13262 else {
13263 // No redeclaration check is needed here; in non-member contexts we
13264 // diagnosed all possible conflicts with other using-declarations when
13265 // building the template:
13266 //
13267 // For a dependent non-type using declaration, the only valid case is
13268 // if we instantiate to a single enumerator. We check for conflicts
13269 // between shadow declarations we introduce, and we check in the template
13270 // definition for conflicts between a non-type using declaration and any
13271 // other declaration, which together covers all cases.
13272 //
13273 // A dependent typename using declaration will never successfully
13274 // instantiate, since it will always name a class member, so we reject
13275 // that in the template definition.
13276 }
13277 }
13278
13279 // Check for invalid redeclarations.
13280 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
13281 SS, NameLoc: IdentLoc, Previous))
13282 return nullptr;
13283
13284 // 'using_if_exists' doesn't make sense on an inherited constructor.
13285 if (IsUsingIfExists && UsingName.getName().getNameKind() ==
13286 DeclarationName::CXXConstructorName) {
13287 Diag(Loc: UsingLoc, DiagID: diag::err_using_if_exists_on_ctor);
13288 return nullptr;
13289 }
13290
13291 DeclContext *LookupContext = computeDeclContext(SS);
13292 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
13293 if (!LookupContext || EllipsisLoc.isValid()) {
13294 NamedDecl *D;
13295 // Dependent scope, or an unexpanded pack
13296 if (!LookupContext && CheckUsingDeclQualifier(UsingLoc, HasTypename: HasTypenameKeyword,
13297 SS, NameInfo, NameLoc: IdentLoc))
13298 return nullptr;
13299
13300 if (Previous.isSingleResult() &&
13301 Previous.getFoundDecl()->isTemplateParameter())
13302 DiagnoseTemplateParameterShadow(Loc: IdentLoc, PrevDecl: Previous.getFoundDecl());
13303
13304 if (HasTypenameKeyword) {
13305 // FIXME: not all declaration name kinds are legal here
13306 D = UnresolvedUsingTypenameDecl::Create(C&: Context, DC: CurContext,
13307 UsingLoc, TypenameLoc,
13308 QualifierLoc,
13309 TargetNameLoc: IdentLoc, TargetName: NameInfo.getName(),
13310 EllipsisLoc);
13311 } else {
13312 D = UnresolvedUsingValueDecl::Create(C&: Context, DC: CurContext, UsingLoc,
13313 QualifierLoc, NameInfo, EllipsisLoc);
13314 }
13315 D->setAccess(AS);
13316 CurContext->addDecl(D);
13317 ProcessDeclAttributeList(S, D, AttrList);
13318 return D;
13319 }
13320
13321 auto Build = [&](bool Invalid) {
13322 UsingDecl *UD =
13323 UsingDecl::Create(C&: Context, DC: CurContext, UsingL: UsingLoc, QualifierLoc,
13324 NameInfo: UsingName, HasTypenameKeyword);
13325 UD->setAccess(AS);
13326 CurContext->addDecl(D: UD);
13327 ProcessDeclAttributeList(S, D: UD, AttrList);
13328 UD->setInvalidDecl(Invalid);
13329 return UD;
13330 };
13331 auto BuildInvalid = [&]{ return Build(true); };
13332 auto BuildValid = [&]{ return Build(false); };
13333
13334 if (RequireCompleteDeclContext(SS, DC: LookupContext))
13335 return BuildInvalid();
13336
13337 // Look up the target name.
13338 LookupResult R(*this, NameInfo, LookupOrdinaryName);
13339
13340 // Unlike most lookups, we don't always want to hide tag
13341 // declarations: tag names are visible through the using declaration
13342 // even if hidden by ordinary names, *except* in a dependent context
13343 // where they may be used by two-phase lookup.
13344 if (!IsInstantiation)
13345 R.setHideTags(false);
13346
13347 // For the purposes of this lookup, we have a base object type
13348 // equal to that of the current context.
13349 if (CurContext->isRecord()) {
13350 R.setBaseObjectType(
13351 Context.getCanonicalTagType(TD: cast<CXXRecordDecl>(Val: CurContext)));
13352 }
13353
13354 LookupQualifiedName(R, LookupCtx: LookupContext);
13355
13356 // Validate the context, now we have a lookup
13357 if (CheckUsingDeclQualifier(UsingLoc, HasTypename: HasTypenameKeyword, SS, NameInfo,
13358 NameLoc: IdentLoc, R: &R))
13359 return nullptr;
13360
13361 if (R.empty() && IsUsingIfExists)
13362 R.addDecl(D: UnresolvedUsingIfExistsDecl::Create(Ctx&: Context, DC: CurContext, Loc: UsingLoc,
13363 Name: UsingName.getName()),
13364 AS: AS_public);
13365
13366 // Try to correct typos if possible. If constructor name lookup finds no
13367 // results, that means the named class has no explicit constructors, and we
13368 // suppressed declaring implicit ones (probably because it's dependent or
13369 // invalid).
13370 if (R.empty() &&
13371 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
13372 // HACK 2017-01-08: Work around an issue with libstdc++'s detection of
13373 // ::gets. Sometimes it believes that glibc provides a ::gets in cases where
13374 // it does not. The issue was fixed in libstdc++ 6.3 (2016-12-21) and later.
13375 auto *II = NameInfo.getName().getAsIdentifierInfo();
13376 if (getLangOpts().CPlusPlus14 && II && II->isStr(Str: "gets") &&
13377 CurContext->isStdNamespace() &&
13378 isa<TranslationUnitDecl>(Val: LookupContext) &&
13379 PP.NeedsStdLibCxxWorkaroundBefore(FixedVersion: 2016'12'21) &&
13380 getSourceManager().isInSystemHeader(Loc: UsingLoc))
13381 return nullptr;
13382 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
13383 dyn_cast<CXXRecordDecl>(Val: CurContext));
13384 if (TypoCorrection Corrected =
13385 CorrectTypo(Typo: R.getLookupNameInfo(), LookupKind: R.getLookupKind(), S, SS: &SS, CCC,
13386 Mode: CorrectTypoKind::ErrorRecovery)) {
13387 // We reject candidates where DroppedSpecifier == true, hence the
13388 // literal '0' below.
13389 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: diag::err_no_member_suggest)
13390 << NameInfo.getName() << LookupContext << 0
13391 << SS.getRange());
13392
13393 // If we picked a correction with no attached Decl we can't do anything
13394 // useful with it, bail out.
13395 NamedDecl *ND = Corrected.getCorrectionDecl();
13396 if (!ND)
13397 return BuildInvalid();
13398
13399 // If we corrected to an inheriting constructor, handle it as one.
13400 auto *RD = dyn_cast<CXXRecordDecl>(Val: ND);
13401 if (RD && RD->isInjectedClassName()) {
13402 // The parent of the injected class name is the class itself.
13403 RD = cast<CXXRecordDecl>(Val: RD->getParent());
13404
13405 // Fix up the information we'll use to build the using declaration.
13406 if (Corrected.WillReplaceSpecifier()) {
13407 NestedNameSpecifierLocBuilder Builder;
13408 Builder.MakeTrivial(Context, Qualifier: Corrected.getCorrectionSpecifier(),
13409 R: QualifierLoc.getSourceRange());
13410 QualifierLoc = Builder.getWithLocInContext(Context);
13411 }
13412
13413 // In this case, the name we introduce is the name of a derived class
13414 // constructor.
13415 auto *CurClass = cast<CXXRecordDecl>(Val: CurContext);
13416 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
13417 Ty: Context.getCanonicalTagType(TD: CurClass)));
13418 UsingName.setNamedTypeInfo(nullptr);
13419 for (auto *Ctor : LookupConstructors(Class: RD))
13420 R.addDecl(D: Ctor);
13421 R.resolveKind();
13422 } else {
13423 // FIXME: Pick up all the declarations if we found an overloaded
13424 // function.
13425 UsingName.setName(ND->getDeclName());
13426 R.addDecl(D: ND);
13427 }
13428 } else {
13429 Diag(Loc: IdentLoc, DiagID: diag::err_no_member)
13430 << NameInfo.getName() << LookupContext << SS.getRange();
13431 return BuildInvalid();
13432 }
13433 }
13434
13435 if (R.isAmbiguous())
13436 return BuildInvalid();
13437
13438 if (HasTypenameKeyword) {
13439 // If we asked for a typename and got a non-type decl, error out.
13440 if (!R.getAsSingle<TypeDecl>() &&
13441 !R.getAsSingle<UnresolvedUsingIfExistsDecl>()) {
13442 Diag(Loc: IdentLoc, DiagID: diag::err_using_typename_non_type);
13443 for (const NamedDecl *D : R)
13444 Diag(Loc: D->getUnderlyingDecl()->getLocation(),
13445 DiagID: diag::note_using_decl_target);
13446 return BuildInvalid();
13447 }
13448 } else {
13449 // If we asked for a non-typename and we got a type, error out,
13450 // but only if this is an instantiation of an unresolved using
13451 // decl. Otherwise just silently find the type name.
13452 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
13453 Diag(Loc: IdentLoc, DiagID: diag::err_using_dependent_value_is_type);
13454 Diag(Loc: R.getFoundDecl()->getLocation(), DiagID: diag::note_using_decl_target);
13455 return BuildInvalid();
13456 }
13457 }
13458
13459 // C++14 [namespace.udecl]p6:
13460 // A using-declaration shall not name a namespace.
13461 if (R.getAsSingle<NamespaceDecl>()) {
13462 Diag(Loc: IdentLoc, DiagID: diag::err_using_decl_can_not_refer_to_namespace)
13463 << SS.getRange();
13464 // Suggest using 'using namespace ...' instead.
13465 Diag(Loc: SS.getBeginLoc(), DiagID: diag::note_namespace_using_decl)
13466 << FixItHint::CreateInsertion(InsertionLoc: SS.getBeginLoc(), Code: "namespace ");
13467 return BuildInvalid();
13468 }
13469
13470 UsingDecl *UD = BuildValid();
13471
13472 // Some additional rules apply to inheriting constructors.
13473 if (UsingName.getName().getNameKind() ==
13474 DeclarationName::CXXConstructorName) {
13475 // Suppress access diagnostics; the access check is instead performed at the
13476 // point of use for an inheriting constructor.
13477 R.suppressDiagnostics();
13478 if (CheckInheritingConstructorUsingDecl(UD))
13479 return UD;
13480 }
13481
13482 for (NamedDecl *D : R) {
13483 UsingShadowDecl *PrevDecl = nullptr;
13484 if (!CheckUsingShadowDecl(BUD: UD, Orig: D, Previous, PrevShadow&: PrevDecl))
13485 BuildUsingShadowDecl(S, BUD: UD, Orig: D, PrevDecl);
13486 }
13487
13488 return UD;
13489}
13490
13491NamedDecl *Sema::BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
13492 SourceLocation UsingLoc,
13493 SourceLocation EnumLoc,
13494 SourceLocation NameLoc,
13495 TypeSourceInfo *EnumType,
13496 EnumDecl *ED) {
13497 bool Invalid = false;
13498
13499 if (CurContext->getRedeclContext()->isRecord()) {
13500 /// In class scope, check if this is a duplicate, for better a diagnostic.
13501 DeclarationNameInfo UsingEnumName(ED->getDeclName(), NameLoc);
13502 LookupResult Previous(*this, UsingEnumName, LookupUsingDeclName,
13503 RedeclarationKind::ForVisibleRedeclaration);
13504
13505 LookupQualifiedName(R&: Previous, LookupCtx: CurContext);
13506
13507 for (NamedDecl *D : Previous)
13508 if (UsingEnumDecl *UED = dyn_cast<UsingEnumDecl>(Val: D))
13509 if (UED->getEnumDecl() == ED) {
13510 Diag(Loc: UsingLoc, DiagID: diag::err_using_enum_decl_redeclaration)
13511 << SourceRange(EnumLoc, NameLoc);
13512 Diag(Loc: D->getLocation(), DiagID: diag::note_using_enum_decl) << 1;
13513 Invalid = true;
13514 break;
13515 }
13516 }
13517
13518 if (RequireCompleteEnumDecl(D: ED, L: NameLoc))
13519 Invalid = true;
13520
13521 UsingEnumDecl *UD = UsingEnumDecl::Create(C&: Context, DC: CurContext, UsingL: UsingLoc,
13522 EnumL: EnumLoc, NameL: NameLoc, EnumType);
13523 UD->setAccess(AS);
13524 CurContext->addDecl(D: UD);
13525
13526 if (Invalid) {
13527 UD->setInvalidDecl();
13528 return UD;
13529 }
13530
13531 // Create the shadow decls for each enumerator
13532 for (EnumConstantDecl *EC : ED->enumerators()) {
13533 UsingShadowDecl *PrevDecl = nullptr;
13534 DeclarationNameInfo DNI(EC->getDeclName(), EC->getLocation());
13535 LookupResult Previous(*this, DNI, LookupOrdinaryName,
13536 RedeclarationKind::ForVisibleRedeclaration);
13537 LookupName(R&: Previous, S);
13538 FilterUsingLookup(S, Previous);
13539
13540 if (!CheckUsingShadowDecl(BUD: UD, Orig: EC, Previous, PrevShadow&: PrevDecl))
13541 BuildUsingShadowDecl(S, BUD: UD, Orig: EC, PrevDecl);
13542 }
13543
13544 return UD;
13545}
13546
13547NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
13548 ArrayRef<NamedDecl *> Expansions) {
13549 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
13550 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
13551 isa<UsingPackDecl>(InstantiatedFrom));
13552
13553 auto *UPD =
13554 UsingPackDecl::Create(C&: Context, DC: CurContext, InstantiatedFrom, UsingDecls: Expansions);
13555 UPD->setAccess(InstantiatedFrom->getAccess());
13556 CurContext->addDecl(D: UPD);
13557 return UPD;
13558}
13559
13560bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
13561 assert(!UD->hasTypename() && "expecting a constructor name");
13562
13563 QualType SourceType(UD->getQualifier().getAsType(), 0);
13564 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(Val: CurContext);
13565
13566 // Check whether the named type is a direct base class.
13567 bool AnyDependentBases = false;
13568 auto *Base =
13569 findDirectBaseWithType(Derived: TargetClass, DesiredBase: SourceType, AnyDependentBases);
13570 if (!Base && !AnyDependentBases) {
13571 Diag(Loc: UD->getUsingLoc(), DiagID: diag::err_using_decl_constructor_not_in_direct_base)
13572 << UD->getNameInfo().getSourceRange() << SourceType << TargetClass;
13573 UD->setInvalidDecl();
13574 return true;
13575 }
13576
13577 if (Base)
13578 Base->setInheritConstructors();
13579
13580 return false;
13581}
13582
13583bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
13584 bool HasTypenameKeyword,
13585 const CXXScopeSpec &SS,
13586 SourceLocation NameLoc,
13587 const LookupResult &Prev) {
13588 NestedNameSpecifier Qual = SS.getScopeRep();
13589
13590 // C++03 [namespace.udecl]p8:
13591 // C++0x [namespace.udecl]p10:
13592 // A using-declaration is a declaration and can therefore be used
13593 // repeatedly where (and only where) multiple declarations are
13594 // allowed.
13595 //
13596 // That's in non-member contexts.
13597 if (!CurContext->getRedeclContext()->isRecord()) {
13598 // A dependent qualifier outside a class can only ever resolve to an
13599 // enumeration type. Therefore it conflicts with any other non-type
13600 // declaration in the same scope.
13601 // FIXME: How should we check for dependent type-type conflicts at block
13602 // scope?
13603 if (Qual.isDependent() && !HasTypenameKeyword) {
13604 for (auto *D : Prev) {
13605 if (!isa<TypeDecl>(Val: D) && !isa<UsingDecl>(Val: D) && !isa<UsingPackDecl>(Val: D)) {
13606 bool OldCouldBeEnumerator =
13607 isa<UnresolvedUsingValueDecl>(Val: D) || isa<EnumConstantDecl>(Val: D);
13608 Diag(Loc: NameLoc,
13609 DiagID: OldCouldBeEnumerator ? diag::err_redefinition
13610 : diag::err_redefinition_different_kind)
13611 << Prev.getLookupName();
13612 Diag(Loc: D->getLocation(), DiagID: diag::note_previous_definition);
13613 return true;
13614 }
13615 }
13616 }
13617 return false;
13618 }
13619
13620 NestedNameSpecifier CNNS = Qual.getCanonical();
13621 for (const NamedDecl *D : Prev) {
13622 bool DTypename;
13623 NestedNameSpecifier DQual = std::nullopt;
13624 if (const auto *UD = dyn_cast<UsingDecl>(Val: D)) {
13625 DTypename = UD->hasTypename();
13626 DQual = UD->getQualifier();
13627 } else if (const auto *UD = dyn_cast<UnresolvedUsingValueDecl>(Val: D)) {
13628 DTypename = false;
13629 DQual = UD->getQualifier();
13630 } else if (const auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(Val: D)) {
13631 DTypename = true;
13632 DQual = UD->getQualifier();
13633 } else
13634 continue;
13635
13636 // using decls differ if one says 'typename' and the other doesn't.
13637 // FIXME: non-dependent using decls?
13638 if (HasTypenameKeyword != DTypename) continue;
13639
13640 // using decls differ if they name different scopes (but note that
13641 // template instantiation can cause this check to trigger when it
13642 // didn't before instantiation).
13643 if (CNNS != DQual.getCanonical())
13644 continue;
13645
13646 Diag(Loc: NameLoc, DiagID: diag::err_using_decl_redeclaration) << SS.getRange();
13647 Diag(Loc: D->getLocation(), DiagID: diag::note_using_decl) << 1;
13648 return true;
13649 }
13650
13651 return false;
13652}
13653
13654bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
13655 const CXXScopeSpec &SS,
13656 const DeclarationNameInfo &NameInfo,
13657 SourceLocation NameLoc,
13658 const LookupResult *R, const UsingDecl *UD) {
13659 DeclContext *NamedContext = computeDeclContext(SS);
13660 assert(bool(NamedContext) == (R || UD) && !(R && UD) &&
13661 "resolvable context must have exactly one set of decls");
13662
13663 // C++ 20 permits using an enumerator that does not have a class-hierarchy
13664 // relationship.
13665 bool Cxx20Enumerator = false;
13666 if (NamedContext) {
13667 EnumConstantDecl *EC = nullptr;
13668 if (R)
13669 EC = R->getAsSingle<EnumConstantDecl>();
13670 else if (UD && UD->shadow_size() == 1)
13671 EC = dyn_cast<EnumConstantDecl>(Val: UD->shadow_begin()->getTargetDecl());
13672 if (EC)
13673 Cxx20Enumerator = getLangOpts().CPlusPlus20;
13674
13675 if (auto *ED = dyn_cast<EnumDecl>(Val: NamedContext)) {
13676 // C++14 [namespace.udecl]p7:
13677 // A using-declaration shall not name a scoped enumerator.
13678 // C++20 p1099 permits enumerators.
13679 if (EC && R && ED->isScoped())
13680 Diag(Loc: SS.getBeginLoc(),
13681 DiagID: getLangOpts().CPlusPlus20
13682 ? diag::warn_cxx17_compat_using_decl_scoped_enumerator
13683 : diag::ext_using_decl_scoped_enumerator)
13684 << SS.getRange();
13685
13686 // We want to consider the scope of the enumerator
13687 NamedContext = ED->getDeclContext();
13688 }
13689 }
13690
13691 if (!CurContext->isRecord()) {
13692 // C++03 [namespace.udecl]p3:
13693 // C++0x [namespace.udecl]p8:
13694 // A using-declaration for a class member shall be a member-declaration.
13695 // C++20 [namespace.udecl]p7
13696 // ... other than an enumerator ...
13697
13698 // If we weren't able to compute a valid scope, it might validly be a
13699 // dependent class or enumeration scope. If we have a 'typename' keyword,
13700 // the scope must resolve to a class type.
13701 if (NamedContext ? !NamedContext->getRedeclContext()->isRecord()
13702 : !HasTypename)
13703 return false; // OK
13704
13705 Diag(Loc: NameLoc,
13706 DiagID: Cxx20Enumerator
13707 ? diag::warn_cxx17_compat_using_decl_class_member_enumerator
13708 : diag::err_using_decl_can_not_refer_to_class_member)
13709 << SS.getRange();
13710
13711 if (Cxx20Enumerator)
13712 return false; // OK
13713
13714 auto *RD = NamedContext
13715 ? cast<CXXRecordDecl>(Val: NamedContext->getRedeclContext())
13716 : nullptr;
13717 if (RD && !RequireCompleteDeclContext(SS&: const_cast<CXXScopeSpec &>(SS), DC: RD)) {
13718 // See if there's a helpful fixit
13719
13720 if (!R) {
13721 // We will have already diagnosed the problem on the template
13722 // definition, Maybe we should do so again?
13723 } else if (R->getAsSingle<TypeDecl>()) {
13724 if (getLangOpts().CPlusPlus11) {
13725 // Convert 'using X::Y;' to 'using Y = X::Y;'.
13726 Diag(Loc: SS.getBeginLoc(), DiagID: diag::note_using_decl_class_member_workaround)
13727 << diag::MemClassWorkaround::AliasDecl
13728 << FixItHint::CreateInsertion(InsertionLoc: SS.getBeginLoc(),
13729 Code: NameInfo.getName().getAsString() +
13730 " = ");
13731 } else {
13732 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
13733 SourceLocation InsertLoc = getLocForEndOfToken(Loc: NameInfo.getEndLoc());
13734 Diag(Loc: InsertLoc, DiagID: diag::note_using_decl_class_member_workaround)
13735 << diag::MemClassWorkaround::TypedefDecl
13736 << FixItHint::CreateReplacement(RemoveRange: UsingLoc, Code: "typedef")
13737 << FixItHint::CreateInsertion(
13738 InsertionLoc: InsertLoc, Code: " " + NameInfo.getName().getAsString());
13739 }
13740 } else if (R->getAsSingle<VarDecl>()) {
13741 // Don't provide a fixit outside C++11 mode; we don't want to suggest
13742 // repeating the type of the static data member here.
13743 FixItHint FixIt;
13744 if (getLangOpts().CPlusPlus11) {
13745 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
13746 FixIt = FixItHint::CreateReplacement(
13747 RemoveRange: UsingLoc, Code: "auto &" + NameInfo.getName().getAsString() + " = ");
13748 }
13749
13750 Diag(Loc: UsingLoc, DiagID: diag::note_using_decl_class_member_workaround)
13751 << diag::MemClassWorkaround::ReferenceDecl << FixIt;
13752 } else if (R->getAsSingle<EnumConstantDecl>()) {
13753 // Don't provide a fixit outside C++11 mode; we don't want to suggest
13754 // repeating the type of the enumeration here, and we can't do so if
13755 // the type is anonymous.
13756 FixItHint FixIt;
13757 if (getLangOpts().CPlusPlus11) {
13758 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
13759 FixIt = FixItHint::CreateReplacement(
13760 RemoveRange: UsingLoc,
13761 Code: "constexpr auto " + NameInfo.getName().getAsString() + " = ");
13762 }
13763
13764 Diag(Loc: UsingLoc, DiagID: diag::note_using_decl_class_member_workaround)
13765 << (getLangOpts().CPlusPlus11
13766 ? diag::MemClassWorkaround::ConstexprVar
13767 : diag::MemClassWorkaround::ConstVar)
13768 << FixIt;
13769 }
13770 }
13771
13772 return true; // Fail
13773 }
13774
13775 // If the named context is dependent, we can't decide much.
13776 if (!NamedContext) {
13777 // FIXME: in C++0x, we can diagnose if we can prove that the
13778 // nested-name-specifier does not refer to a base class, which is
13779 // still possible in some cases.
13780
13781 // Otherwise we have to conservatively report that things might be
13782 // okay.
13783 return false;
13784 }
13785
13786 // The current scope is a record.
13787 if (!NamedContext->isRecord()) {
13788 // Ideally this would point at the last name in the specifier,
13789 // but we don't have that level of source info.
13790 Diag(Loc: SS.getBeginLoc(),
13791 DiagID: Cxx20Enumerator
13792 ? diag::warn_cxx17_compat_using_decl_non_member_enumerator
13793 : diag::err_using_decl_nested_name_specifier_is_not_class)
13794 << SS.getScopeRep() << SS.getRange();
13795
13796 if (Cxx20Enumerator)
13797 return false; // OK
13798
13799 return true;
13800 }
13801
13802 if (!NamedContext->isDependentContext() &&
13803 RequireCompleteDeclContext(SS&: const_cast<CXXScopeSpec&>(SS), DC: NamedContext))
13804 return true;
13805
13806 // C++26 [namespace.udecl]p3:
13807 // In a using-declaration used as a member-declaration, each
13808 // using-declarator shall either name an enumerator or have a
13809 // nested-name-specifier naming a base class of the current class
13810 // ([expr.prim.this]). ...
13811 // "have a nested-name-specifier naming a base class of the current class"
13812 // was introduced by CWG400.
13813
13814 if (cast<CXXRecordDecl>(Val: CurContext)
13815 ->isProvablyNotDerivedFrom(Base: cast<CXXRecordDecl>(Val: NamedContext))) {
13816
13817 if (Cxx20Enumerator) {
13818 Diag(Loc: NameLoc, DiagID: diag::warn_cxx17_compat_using_decl_non_member_enumerator)
13819 << SS.getScopeRep() << SS.getRange();
13820 return false;
13821 }
13822
13823 if (CurContext == NamedContext) {
13824 Diag(Loc: SS.getBeginLoc(),
13825 DiagID: diag::err_using_decl_nested_name_specifier_is_current_class)
13826 << SS.getRange();
13827 return true;
13828 }
13829
13830 if (!cast<CXXRecordDecl>(Val: NamedContext)->isInvalidDecl()) {
13831 Diag(Loc: SS.getBeginLoc(),
13832 DiagID: diag::err_using_decl_nested_name_specifier_is_not_base_class)
13833 << SS.getScopeRep() << cast<CXXRecordDecl>(Val: CurContext)
13834 << SS.getRange();
13835 }
13836 return true;
13837 }
13838
13839 return false;
13840}
13841
13842Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
13843 MultiTemplateParamsArg TemplateParamLists,
13844 SourceLocation UsingLoc, UnqualifiedId &Name,
13845 const ParsedAttributesView &AttrList,
13846 TypeResult Type, Decl *DeclFromDeclSpec) {
13847
13848 if (Type.isInvalid())
13849 return nullptr;
13850
13851 bool Invalid = false;
13852 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
13853 TypeSourceInfo *TInfo = nullptr;
13854 GetTypeFromParser(Ty: Type.get(), TInfo: &TInfo);
13855
13856 if (DiagnoseClassNameShadow(DC: CurContext, Info: NameInfo))
13857 return nullptr;
13858
13859 if (DiagnoseUnexpandedParameterPack(Loc: Name.StartLocation, T: TInfo,
13860 UPPC: UPPC_DeclarationType)) {
13861 Invalid = true;
13862 TInfo = Context.getTrivialTypeSourceInfo(T: Context.IntTy,
13863 Loc: TInfo->getTypeLoc().getBeginLoc());
13864 }
13865
13866 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
13867 TemplateParamLists.size()
13868 ? forRedeclarationInCurContext()
13869 : RedeclarationKind::ForVisibleRedeclaration);
13870 LookupName(R&: Previous, S);
13871
13872 // Warn about shadowing the name of a template parameter.
13873 if (Previous.isSingleResult() &&
13874 Previous.getFoundDecl()->isTemplateParameter()) {
13875 DiagnoseTemplateParameterShadow(Loc: Name.StartLocation,PrevDecl: Previous.getFoundDecl());
13876 Previous.clear();
13877 }
13878
13879 assert(Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
13880 "name in alias declaration must be an identifier");
13881 TypeAliasDecl *NewTD = TypeAliasDecl::Create(C&: Context, DC: CurContext, StartLoc: UsingLoc,
13882 IdLoc: Name.StartLocation,
13883 Id: Name.Identifier, TInfo);
13884
13885 NewTD->setAccess(AS);
13886
13887 if (Invalid)
13888 NewTD->setInvalidDecl();
13889
13890 ProcessDeclAttributeList(S, D: NewTD, AttrList);
13891 AddPragmaAttributes(S, D: NewTD);
13892 ProcessAPINotes(D: NewTD);
13893
13894 CheckTypedefForVariablyModifiedType(S, D: NewTD);
13895 Invalid |= NewTD->isInvalidDecl();
13896
13897 // Get the innermost enclosing declaration scope.
13898 S = S->getDeclParent();
13899
13900 bool Redeclaration = false;
13901
13902 NamedDecl *NewND;
13903 if (TemplateParamLists.size()) {
13904 TypeAliasTemplateDecl *OldDecl = nullptr;
13905 TemplateParameterList *OldTemplateParams = nullptr;
13906
13907 TemplateParameterList *TemplateParams = TemplateParamLists[0];
13908 if (TemplateParamLists.size() != 1) {
13909 Diag(Loc: UsingLoc, DiagID: diag::err_alias_template_extra_headers)
13910 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
13911 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
13912 Invalid = true;
13913
13914 // Recover by picking the last non-empty template parameter list.
13915 auto It = llvm::find_if(
13916 Range: llvm::reverse(C&: TemplateParamLists),
13917 P: [](TemplateParameterList *TPL) { return !TPL->empty(); });
13918 assert(It != TemplateParamLists.rend() &&
13919 "if all template parameter lists were empty, this should have "
13920 "been rejected as an explicit specialization");
13921 TemplateParams = *It;
13922 }
13923
13924 // Check that we can declare a template here.
13925 if (CheckTemplateDeclScope(S, TemplateParams))
13926 return nullptr;
13927
13928 // Only consider previous declarations in the same scope.
13929 FilterLookupForScope(R&: Previous, Ctx: CurContext, S, /*ConsiderLinkage*/false,
13930 /*ExplicitInstantiationOrSpecialization*/AllowInlineNamespace: false);
13931 if (!Previous.empty()) {
13932 Redeclaration = true;
13933
13934 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
13935 if (!OldDecl && !Invalid) {
13936 Diag(Loc: UsingLoc, DiagID: diag::err_redefinition_different_kind)
13937 << Name.Identifier;
13938
13939 NamedDecl *OldD = Previous.getRepresentativeDecl();
13940 if (OldD->getLocation().isValid())
13941 Diag(Loc: OldD->getLocation(), DiagID: diag::note_previous_definition);
13942
13943 Invalid = true;
13944 }
13945
13946 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
13947 if (TemplateParameterListsAreEqual(New: TemplateParams,
13948 Old: OldDecl->getTemplateParameters(),
13949 /*Complain=*/true,
13950 Kind: TPL_TemplateMatch))
13951 OldTemplateParams =
13952 OldDecl->getMostRecentDecl()->getTemplateParameters();
13953 else
13954 Invalid = true;
13955
13956 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
13957 if (!Invalid &&
13958 !Context.hasSameType(T1: OldTD->getUnderlyingType(),
13959 T2: NewTD->getUnderlyingType())) {
13960 // FIXME: The C++0x standard does not clearly say this is ill-formed,
13961 // but we can't reasonably accept it.
13962 Diag(Loc: NewTD->getLocation(), DiagID: diag::err_redefinition_different_typedef)
13963 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
13964 if (OldTD->getLocation().isValid())
13965 Diag(Loc: OldTD->getLocation(), DiagID: diag::note_previous_definition);
13966 Invalid = true;
13967 }
13968 }
13969 }
13970
13971 // Merge any previous default template arguments into our parameters,
13972 // and check the parameter list.
13973 if (CheckTemplateParameterList(NewParams: TemplateParams, OldParams: OldTemplateParams,
13974 TPC: TPC_Other))
13975 return nullptr;
13976
13977 TypeAliasTemplateDecl *NewDecl =
13978 TypeAliasTemplateDecl::Create(C&: Context, DC: CurContext, L: UsingLoc,
13979 Name: Name.Identifier, Params: TemplateParams,
13980 Decl: NewTD);
13981 NewTD->setDescribedAliasTemplate(NewDecl);
13982
13983 NewDecl->setAccess(AS);
13984
13985 if (Invalid)
13986 NewDecl->setInvalidDecl();
13987 else if (OldDecl) {
13988 NewDecl->setPreviousDecl(OldDecl);
13989 CheckRedeclarationInModule(New: NewDecl, Old: OldDecl);
13990 }
13991
13992 NewND = NewDecl;
13993 } else {
13994 if (auto *TD = dyn_cast_or_null<TagDecl>(Val: DeclFromDeclSpec)) {
13995 setTagNameForLinkagePurposes(TagFromDeclSpec: TD, NewTD);
13996 handleTagNumbering(Tag: TD, TagScope: S);
13997 }
13998 ActOnTypedefNameDecl(S, DC: CurContext, D: NewTD, Previous, Redeclaration);
13999 NewND = NewTD;
14000 }
14001
14002 PushOnScopeChains(D: NewND, S);
14003 ActOnDocumentableDecl(D: NewND);
14004 return NewND;
14005}
14006
14007Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
14008 SourceLocation AliasLoc,
14009 IdentifierInfo *Alias, CXXScopeSpec &SS,
14010 SourceLocation IdentLoc,
14011 IdentifierInfo *Ident) {
14012
14013 // Lookup the namespace name.
14014 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
14015 LookupParsedName(R, S, SS: &SS, /*ObjectType=*/QualType());
14016
14017 if (R.isAmbiguous())
14018 return nullptr;
14019
14020 if (R.empty()) {
14021 if (!TryNamespaceTypoCorrection(S&: *this, R, Sc: S, SS, IdentLoc, Ident)) {
14022 Diag(Loc: IdentLoc, DiagID: diag::err_expected_namespace_name) << SS.getRange();
14023 return nullptr;
14024 }
14025 }
14026 assert(!R.isAmbiguous() && !R.empty());
14027 auto *ND = cast<NamespaceBaseDecl>(Val: R.getRepresentativeDecl());
14028
14029 // Check if we have a previous declaration with the same name.
14030 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
14031 RedeclarationKind::ForVisibleRedeclaration);
14032 LookupName(R&: PrevR, S);
14033
14034 // Check we're not shadowing a template parameter.
14035 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
14036 DiagnoseTemplateParameterShadow(Loc: AliasLoc, PrevDecl: PrevR.getFoundDecl());
14037 PrevR.clear();
14038 }
14039
14040 // Filter out any other lookup result from an enclosing scope.
14041 FilterLookupForScope(R&: PrevR, Ctx: CurContext, S, /*ConsiderLinkage*/false,
14042 /*AllowInlineNamespace*/false);
14043
14044 // Find the previous declaration and check that we can redeclare it.
14045 NamespaceAliasDecl *Prev = nullptr;
14046 if (PrevR.isSingleResult()) {
14047 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
14048 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(Val: PrevDecl)) {
14049 // We already have an alias with the same name that points to the same
14050 // namespace; check that it matches.
14051 if (AD->getNamespace()->Equals(DC: getNamespaceDecl(D: ND))) {
14052 Prev = AD;
14053 } else if (isVisible(D: PrevDecl)) {
14054 Diag(Loc: AliasLoc, DiagID: diag::err_redefinition_different_namespace_alias)
14055 << Alias;
14056 Diag(Loc: AD->getLocation(), DiagID: diag::note_previous_namespace_alias)
14057 << AD->getNamespace();
14058 return nullptr;
14059 }
14060 } else if (isVisible(D: PrevDecl)) {
14061 unsigned DiagID = isa<NamespaceDecl>(Val: PrevDecl->getUnderlyingDecl())
14062 ? diag::err_redefinition
14063 : diag::err_redefinition_different_kind;
14064 Diag(Loc: AliasLoc, DiagID) << Alias;
14065 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_definition);
14066 return nullptr;
14067 }
14068 }
14069
14070 // The use of a nested name specifier may trigger deprecation warnings.
14071 DiagnoseUseOfDecl(D: ND, Locs: IdentLoc);
14072
14073 NamespaceAliasDecl *AliasDecl =
14074 NamespaceAliasDecl::Create(C&: Context, DC: CurContext, NamespaceLoc, AliasLoc,
14075 Alias, QualifierLoc: SS.getWithLocInContext(Context),
14076 IdentLoc, Namespace: ND);
14077 if (Prev)
14078 AliasDecl->setPreviousDecl(Prev);
14079
14080 PushOnScopeChains(D: AliasDecl, S);
14081 return AliasDecl;
14082}
14083
14084namespace {
14085struct SpecialMemberExceptionSpecInfo
14086 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
14087 SourceLocation Loc;
14088 Sema::ImplicitExceptionSpecification ExceptSpec;
14089
14090 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
14091 CXXSpecialMemberKind CSM,
14092 Sema::InheritedConstructorInfo *ICI,
14093 SourceLocation Loc)
14094 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
14095
14096 bool visitBase(CXXBaseSpecifier *Base);
14097 bool visitField(FieldDecl *FD);
14098
14099 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
14100 unsigned Quals);
14101
14102 void visitSubobjectCall(Subobject Subobj,
14103 Sema::SpecialMemberOverloadResult SMOR);
14104};
14105}
14106
14107bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
14108 auto *BaseClass = Base->getType()->getAsCXXRecordDecl();
14109 if (!BaseClass)
14110 return false;
14111
14112 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(Class: BaseClass);
14113 if (auto *BaseCtor = SMOR.getMethod()) {
14114 visitSubobjectCall(Subobj: Base, SMOR: BaseCtor);
14115 return false;
14116 }
14117
14118 visitClassSubobject(Class: BaseClass, Subobj: Base, Quals: 0);
14119 return false;
14120}
14121
14122bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
14123 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
14124 FD->hasInClassInitializer()) {
14125 Expr *E = FD->getInClassInitializer();
14126 if (!E)
14127 // FIXME: It's a little wasteful to build and throw away a
14128 // CXXDefaultInitExpr here.
14129 // FIXME: We should have a single context note pointing at Loc, and
14130 // this location should be MD->getLocation() instead, since that's
14131 // the location where we actually use the default init expression.
14132 E = S.BuildCXXDefaultInitExpr(Loc, Field: FD).get();
14133 if (E)
14134 ExceptSpec.CalledExpr(E);
14135 } else if (auto *RD = S.Context.getBaseElementType(QT: FD->getType())
14136 ->getAsCXXRecordDecl()) {
14137 visitClassSubobject(Class: RD, Subobj: FD, Quals: FD->getType().getCVRQualifiers());
14138 }
14139 return false;
14140}
14141
14142void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
14143 Subobject Subobj,
14144 unsigned Quals) {
14145 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
14146 bool IsMutable = Field && Field->isMutable();
14147 visitSubobjectCall(Subobj, SMOR: lookupIn(Class, Quals, IsMutable));
14148}
14149
14150void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
14151 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
14152 // Note, if lookup fails, it doesn't matter what exception specification we
14153 // choose because the special member will be deleted.
14154 if (CXXMethodDecl *MD = SMOR.getMethod())
14155 ExceptSpec.CalledDecl(CallLoc: getSubobjectLoc(Subobj), Method: MD);
14156}
14157
14158bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) {
14159 llvm::APSInt Result;
14160 ExprResult Converted = CheckConvertedConstantExpression(
14161 From: ExplicitSpec.getExpr(), T: Context.BoolTy, Value&: Result, CCE: CCEKind::ExplicitBool);
14162 ExplicitSpec.setExpr(Converted.get());
14163 if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
14164 ExplicitSpec.setKind(Result.getBoolValue()
14165 ? ExplicitSpecKind::ResolvedTrue
14166 : ExplicitSpecKind::ResolvedFalse);
14167 return true;
14168 }
14169 ExplicitSpec.setKind(ExplicitSpecKind::Unresolved);
14170 return false;
14171}
14172
14173ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) {
14174 ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved);
14175 if (!ExplicitExpr->isTypeDependent())
14176 tryResolveExplicitSpecifier(ExplicitSpec&: ES);
14177 return ES;
14178}
14179
14180static Sema::ImplicitExceptionSpecification
14181ComputeDefaultedSpecialMemberExceptionSpec(
14182 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, CXXSpecialMemberKind CSM,
14183 Sema::InheritedConstructorInfo *ICI) {
14184 ComputingExceptionSpec CES(S, MD, Loc);
14185
14186 CXXRecordDecl *ClassDecl = MD->getParent();
14187
14188 // C++ [except.spec]p14:
14189 // An implicitly declared special member function (Clause 12) shall have an
14190 // exception-specification. [...]
14191 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
14192 if (ClassDecl->isInvalidDecl())
14193 return Info.ExceptSpec;
14194
14195 // FIXME: If this diagnostic fires, we're probably missing a check for
14196 // attempting to resolve an exception specification before it's known
14197 // at a higher level.
14198 if (S.RequireCompleteType(Loc: MD->getLocation(),
14199 T: S.Context.getCanonicalTagType(TD: ClassDecl),
14200 DiagID: diag::err_exception_spec_incomplete_type))
14201 return Info.ExceptSpec;
14202
14203 // C++1z [except.spec]p7:
14204 // [Look for exceptions thrown by] a constructor selected [...] to
14205 // initialize a potentially constructed subobject,
14206 // C++1z [except.spec]p8:
14207 // The exception specification for an implicitly-declared destructor, or a
14208 // destructor without a noexcept-specifier, is potentially-throwing if and
14209 // only if any of the destructors for any of its potentially constructed
14210 // subojects is potentially throwing.
14211 // FIXME: We respect the first rule but ignore the "potentially constructed"
14212 // in the second rule to resolve a core issue (no number yet) that would have
14213 // us reject:
14214 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
14215 // struct B : A {};
14216 // struct C : B { void f(); };
14217 // ... due to giving B::~B() a non-throwing exception specification.
14218 Info.visit(Bases: Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
14219 : Info.VisitAllBases);
14220
14221 return Info.ExceptSpec;
14222}
14223
14224namespace {
14225/// RAII object to register a special member as being currently declared.
14226struct DeclaringSpecialMember {
14227 Sema &S;
14228 Sema::SpecialMemberDecl D;
14229 Sema::ContextRAII SavedContext;
14230 bool WasAlreadyBeingDeclared;
14231
14232 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, CXXSpecialMemberKind CSM)
14233 : S(S), D(RD, CSM), SavedContext(S, RD) {
14234 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(Ptr: D).second;
14235 if (WasAlreadyBeingDeclared)
14236 // This almost never happens, but if it does, ensure that our cache
14237 // doesn't contain a stale result.
14238 S.SpecialMemberCache.clear();
14239 else {
14240 // Register a note to be produced if we encounter an error while
14241 // declaring the special member.
14242 Sema::CodeSynthesisContext Ctx;
14243 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
14244 // FIXME: We don't have a location to use here. Using the class's
14245 // location maintains the fiction that we declare all special members
14246 // with the class, but (1) it's not clear that lying about that helps our
14247 // users understand what's going on, and (2) there may be outer contexts
14248 // on the stack (some of which are relevant) and printing them exposes
14249 // our lies.
14250 Ctx.PointOfInstantiation = RD->getLocation();
14251 Ctx.Entity = RD;
14252 Ctx.SpecialMember = CSM;
14253 S.pushCodeSynthesisContext(Ctx);
14254 }
14255 }
14256 ~DeclaringSpecialMember() {
14257 if (!WasAlreadyBeingDeclared) {
14258 S.SpecialMembersBeingDeclared.erase(Ptr: D);
14259 S.popCodeSynthesisContext();
14260 }
14261 }
14262
14263 /// Are we already trying to declare this special member?
14264 bool isAlreadyBeingDeclared() const {
14265 return WasAlreadyBeingDeclared;
14266 }
14267};
14268}
14269
14270void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
14271 // Look up any existing declarations, but don't trigger declaration of all
14272 // implicit special members with this name.
14273 DeclarationName Name = FD->getDeclName();
14274 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
14275 RedeclarationKind::ForExternalRedeclaration);
14276 for (auto *D : FD->getParent()->lookup(Name))
14277 if (auto *Acceptable = R.getAcceptableDecl(D))
14278 R.addDecl(D: Acceptable);
14279 R.resolveKind();
14280 R.suppressDiagnostics();
14281
14282 CheckFunctionDeclaration(S, NewFD: FD, Previous&: R, /*IsMemberSpecialization*/ false,
14283 DeclIsDefn: FD->isThisDeclarationADefinition());
14284}
14285
14286void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
14287 QualType ResultTy,
14288 ArrayRef<QualType> Args) {
14289 // Build an exception specification pointing back at this constructor.
14290 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(S&: *this, MD: SpecialMem);
14291
14292 LangAS AS = getDefaultCXXMethodAddrSpace();
14293 if (AS != LangAS::Default) {
14294 EPI.TypeQuals.addAddressSpace(space: AS);
14295 }
14296
14297 auto QT = Context.getFunctionType(ResultTy, Args, EPI);
14298 SpecialMem->setType(QT);
14299
14300 // During template instantiation of implicit special member functions we need
14301 // a reliable TypeSourceInfo for the function prototype in order to allow
14302 // functions to be substituted.
14303 if (inTemplateInstantiation() && isLambdaMethod(DC: SpecialMem)) {
14304 TypeSourceInfo *TSI =
14305 Context.getTrivialTypeSourceInfo(T: SpecialMem->getType());
14306 SpecialMem->setTypeSourceInfo(TSI);
14307 }
14308}
14309
14310CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
14311 CXXRecordDecl *ClassDecl) {
14312 // C++ [class.ctor]p5:
14313 // A default constructor for a class X is a constructor of class X
14314 // that can be called without an argument. If there is no
14315 // user-declared constructor for class X, a default constructor is
14316 // implicitly declared. An implicitly-declared default constructor
14317 // is an inline public member of its class.
14318 assert(ClassDecl->needsImplicitDefaultConstructor() &&
14319 "Should not build implicit default constructor!");
14320
14321 DeclaringSpecialMember DSM(*this, ClassDecl,
14322 CXXSpecialMemberKind::DefaultConstructor);
14323 if (DSM.isAlreadyBeingDeclared())
14324 return nullptr;
14325
14326 bool Constexpr = defaultedSpecialMemberIsConstexpr(
14327 S&: *this, ClassDecl, CSM: CXXSpecialMemberKind::DefaultConstructor, ConstArg: false);
14328
14329 // Create the actual constructor declaration.
14330 CanQualType ClassType = Context.getCanonicalTagType(TD: ClassDecl);
14331 SourceLocation ClassLoc = ClassDecl->getLocation();
14332 DeclarationName Name
14333 = Context.DeclarationNames.getCXXConstructorName(Ty: ClassType);
14334 DeclarationNameInfo NameInfo(Name, ClassLoc);
14335 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
14336 C&: Context, RD: ClassDecl, StartLoc: ClassLoc, NameInfo, /*Type*/ T: QualType(),
14337 /*TInfo=*/nullptr, ES: ExplicitSpecifier(),
14338 UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
14339 /*isInline=*/true, /*isImplicitlyDeclared=*/true,
14340 ConstexprKind: Constexpr ? ConstexprSpecKind::Constexpr
14341 : ConstexprSpecKind::Unspecified);
14342 DefaultCon->setAccess(AS_public);
14343 DefaultCon->setDefaulted();
14344
14345 setupImplicitSpecialMemberType(SpecialMem: DefaultCon, ResultTy: Context.VoidTy, Args: {});
14346
14347 if (getLangOpts().CUDA)
14348 CUDA().inferTargetForImplicitSpecialMember(
14349 ClassDecl, CSM: CXXSpecialMemberKind::DefaultConstructor, MemberDecl: DefaultCon,
14350 /* ConstRHS */ false,
14351 /* Diagnose */ false);
14352
14353 // We don't need to use SpecialMemberIsTrivial here; triviality for default
14354 // constructors is easy to compute.
14355 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
14356
14357 // Note that we have declared this constructor.
14358 ++getASTContext().NumImplicitDefaultConstructorsDeclared;
14359
14360 Scope *S = getScopeForContext(Ctx: ClassDecl);
14361 CheckImplicitSpecialMemberDeclaration(S, FD: DefaultCon);
14362
14363 if (ShouldDeleteSpecialMember(MD: DefaultCon,
14364 CSM: CXXSpecialMemberKind::DefaultConstructor))
14365 SetDeclDeleted(dcl: DefaultCon, DelLoc: ClassLoc);
14366
14367 if (S)
14368 PushOnScopeChains(D: DefaultCon, S, AddToContext: false);
14369 ClassDecl->addDecl(D: DefaultCon);
14370
14371 return DefaultCon;
14372}
14373
14374void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
14375 CXXConstructorDecl *Constructor) {
14376 DefaultedFunctionFPFeaturesRAII RestoreFP(*this, Constructor);
14377 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
14378 !Constructor->doesThisDeclarationHaveABody() &&
14379 !Constructor->isDeleted()) &&
14380 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
14381 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
14382 return;
14383
14384 CXXRecordDecl *ClassDecl = Constructor->getParent();
14385 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
14386 if (ClassDecl->isInvalidDecl()) {
14387 return;
14388 }
14389
14390 SynthesizedFunctionScope Scope(*this, Constructor);
14391
14392 // The exception specification is needed because we are defining the
14393 // function.
14394 ResolveExceptionSpec(Loc: CurrentLocation,
14395 FPT: Constructor->getType()->castAs<FunctionProtoType>());
14396 MarkVTableUsed(Loc: CurrentLocation, Class: ClassDecl);
14397
14398 // Add a context note for diagnostics produced after this point.
14399 Scope.addContextNote(UseLoc: CurrentLocation);
14400
14401 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
14402 Constructor->setInvalidDecl();
14403 return;
14404 }
14405
14406 SourceLocation Loc = Constructor->getEndLoc().isValid()
14407 ? Constructor->getEndLoc()
14408 : Constructor->getLocation();
14409 Constructor->setBody(new (Context) CompoundStmt(Loc));
14410 Constructor->markUsed(C&: Context);
14411
14412 if (ASTMutationListener *L = getASTMutationListener()) {
14413 L->CompletedImplicitDefinition(D: Constructor);
14414 }
14415
14416 DiagnoseUninitializedFields(SemaRef&: *this, Constructor);
14417
14418 // The synthesized body applies the class's NSDMIs and never reaches the
14419 // normal IssueWarnings path, so run lifetime safety on it here.
14420 AnalysisWarnings.IssueWarningsForImplicitFunction(D: Constructor);
14421}
14422
14423void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
14424 // Perform any delayed checks on exception specifications.
14425 CheckDelayedMemberExceptionSpecs();
14426}
14427
14428/// Find or create the fake constructor we synthesize to model constructing an
14429/// object of a derived class via a constructor of a base class.
14430CXXConstructorDecl *
14431Sema::findInheritingConstructor(SourceLocation Loc,
14432 CXXConstructorDecl *BaseCtor,
14433 ConstructorUsingShadowDecl *Shadow) {
14434 CXXRecordDecl *Derived = Shadow->getParent();
14435 SourceLocation UsingLoc = Shadow->getLocation();
14436
14437 // FIXME: Add a new kind of DeclarationName for an inherited constructor.
14438 // For now we use the name of the base class constructor as a member of the
14439 // derived class to indicate a (fake) inherited constructor name.
14440 DeclarationName Name = BaseCtor->getDeclName();
14441
14442 // Check to see if we already have a fake constructor for this inherited
14443 // constructor call.
14444 for (NamedDecl *Ctor : Derived->lookup(Name))
14445 if (declaresSameEntity(D1: cast<CXXConstructorDecl>(Val: Ctor)
14446 ->getInheritedConstructor()
14447 .getConstructor(),
14448 D2: BaseCtor))
14449 return cast<CXXConstructorDecl>(Val: Ctor);
14450
14451 DeclarationNameInfo NameInfo(Name, UsingLoc);
14452 TypeSourceInfo *TInfo =
14453 Context.getTrivialTypeSourceInfo(T: BaseCtor->getType(), Loc: UsingLoc);
14454 FunctionProtoTypeLoc ProtoLoc =
14455 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
14456
14457 // Check the inherited constructor is valid and find the list of base classes
14458 // from which it was inherited.
14459 InheritedConstructorInfo ICI(*this, Loc, Shadow);
14460
14461 bool Constexpr = BaseCtor->isConstexpr() &&
14462 defaultedSpecialMemberIsConstexpr(
14463 S&: *this, ClassDecl: Derived, CSM: CXXSpecialMemberKind::DefaultConstructor,
14464 ConstArg: false, InheritedCtor: BaseCtor, Inherited: &ICI);
14465
14466 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
14467 C&: Context, RD: Derived, StartLoc: UsingLoc, NameInfo, T: TInfo->getType(), TInfo,
14468 ES: BaseCtor->getExplicitSpecifier(), UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
14469 /*isInline=*/true,
14470 /*isImplicitlyDeclared=*/true,
14471 ConstexprKind: Constexpr ? BaseCtor->getConstexprKind() : ConstexprSpecKind::Unspecified,
14472 Inherited: InheritedConstructor(Shadow, BaseCtor),
14473 TrailingRequiresClause: BaseCtor->getTrailingRequiresClause());
14474 if (Shadow->isInvalidDecl())
14475 DerivedCtor->setInvalidDecl();
14476
14477 // Build an unevaluated exception specification for this fake constructor.
14478 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
14479 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
14480 EPI.ExceptionSpec.Type = EST_Unevaluated;
14481 EPI.ExceptionSpec.SourceDecl = DerivedCtor;
14482 DerivedCtor->setType(Context.getFunctionType(ResultTy: FPT->getReturnType(),
14483 Args: FPT->getParamTypes(), EPI));
14484
14485 // Build the parameter declarations.
14486 SmallVector<ParmVarDecl *, 16> ParamDecls;
14487 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
14488 TypeSourceInfo *TInfo =
14489 Context.getTrivialTypeSourceInfo(T: FPT->getParamType(i: I), Loc: UsingLoc);
14490 ParmVarDecl *PD = ParmVarDecl::Create(
14491 C&: Context, DC: DerivedCtor, StartLoc: UsingLoc, IdLoc: UsingLoc, /*IdentifierInfo=*/Id: nullptr,
14492 T: FPT->getParamType(i: I), TInfo, S: SC_None, /*DefArg=*/nullptr);
14493 PD->setScopeInfo(scopeDepth: 0, parameterIndex: I);
14494 PD->setImplicit();
14495 // Ensure attributes are propagated onto parameters (this matters for
14496 // format, pass_object_size, ...).
14497 mergeDeclAttributes(New: PD, Old: BaseCtor->getParamDecl(i: I));
14498 ParamDecls.push_back(Elt: PD);
14499 ProtoLoc.setParam(i: I, VD: PD);
14500 }
14501
14502 // Set up the new constructor.
14503 assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
14504 DerivedCtor->setAccess(BaseCtor->getAccess());
14505 DerivedCtor->setParams(ParamDecls);
14506 Derived->addDecl(D: DerivedCtor);
14507
14508 if (ShouldDeleteSpecialMember(MD: DerivedCtor,
14509 CSM: CXXSpecialMemberKind::DefaultConstructor, ICI: &ICI))
14510 SetDeclDeleted(dcl: DerivedCtor, DelLoc: UsingLoc);
14511
14512 return DerivedCtor;
14513}
14514
14515void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
14516 InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
14517 Ctor->getInheritedConstructor().getShadowDecl());
14518 ShouldDeleteSpecialMember(MD: Ctor, CSM: CXXSpecialMemberKind::DefaultConstructor,
14519 ICI: &ICI,
14520 /*Diagnose*/ true);
14521}
14522
14523void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
14524 CXXConstructorDecl *Constructor) {
14525 CXXRecordDecl *ClassDecl = Constructor->getParent();
14526 assert(Constructor->getInheritedConstructor() &&
14527 !Constructor->doesThisDeclarationHaveABody() &&
14528 !Constructor->isDeleted());
14529 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
14530 return;
14531
14532 // Initializations are performed "as if by a defaulted default constructor",
14533 // so enter the appropriate scope.
14534 SynthesizedFunctionScope Scope(*this, Constructor);
14535
14536 // The exception specification is needed because we are defining the
14537 // function.
14538 ResolveExceptionSpec(Loc: CurrentLocation,
14539 FPT: Constructor->getType()->castAs<FunctionProtoType>());
14540 MarkVTableUsed(Loc: CurrentLocation, Class: ClassDecl);
14541
14542 // Add a context note for diagnostics produced after this point.
14543 Scope.addContextNote(UseLoc: CurrentLocation);
14544
14545 ConstructorUsingShadowDecl *Shadow =
14546 Constructor->getInheritedConstructor().getShadowDecl();
14547 CXXConstructorDecl *InheritedCtor =
14548 Constructor->getInheritedConstructor().getConstructor();
14549
14550 // [class.inhctor.init]p1:
14551 // initialization proceeds as if a defaulted default constructor is used to
14552 // initialize the D object and each base class subobject from which the
14553 // constructor was inherited
14554
14555 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
14556 CXXRecordDecl *RD = Shadow->getParent();
14557 SourceLocation InitLoc = Shadow->getLocation();
14558
14559 // Build explicit initializers for all base classes from which the
14560 // constructor was inherited.
14561 SmallVector<CXXCtorInitializer*, 8> Inits;
14562 for (bool VBase : {false, true}) {
14563 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
14564 if (B.isVirtual() != VBase)
14565 continue;
14566
14567 auto *BaseRD = B.getType()->getAsCXXRecordDecl();
14568 if (!BaseRD)
14569 continue;
14570
14571 auto BaseCtor = ICI.findConstructorForBase(Base: BaseRD, Ctor: InheritedCtor);
14572 if (!BaseCtor.first)
14573 continue;
14574
14575 MarkFunctionReferenced(Loc: CurrentLocation, Func: BaseCtor.first);
14576 ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
14577 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
14578
14579 auto *TInfo = Context.getTrivialTypeSourceInfo(T: B.getType(), Loc: InitLoc);
14580 Inits.push_back(Elt: new (Context) CXXCtorInitializer(
14581 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
14582 SourceLocation()));
14583 }
14584 }
14585
14586 // We now proceed as if for a defaulted default constructor, with the relevant
14587 // initializers replaced.
14588
14589 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Initializers: Inits)) {
14590 Constructor->setInvalidDecl();
14591 return;
14592 }
14593
14594 Constructor->setBody(new (Context) CompoundStmt(InitLoc));
14595 Constructor->markUsed(C&: Context);
14596
14597 if (ASTMutationListener *L = getASTMutationListener()) {
14598 L->CompletedImplicitDefinition(D: Constructor);
14599 }
14600
14601 DiagnoseUninitializedFields(SemaRef&: *this, Constructor);
14602
14603 // The synthesized body applies the class's NSDMIs and never reaches the
14604 // normal IssueWarnings path, so run lifetime safety on it here.
14605 AnalysisWarnings.IssueWarningsForImplicitFunction(D: Constructor);
14606}
14607
14608CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
14609 // C++ [class.dtor]p2:
14610 // If a class has no user-declared destructor, a destructor is
14611 // declared implicitly. An implicitly-declared destructor is an
14612 // inline public member of its class.
14613 assert(ClassDecl->needsImplicitDestructor());
14614
14615 DeclaringSpecialMember DSM(*this, ClassDecl,
14616 CXXSpecialMemberKind::Destructor);
14617 if (DSM.isAlreadyBeingDeclared())
14618 return nullptr;
14619
14620 bool Constexpr = defaultedSpecialMemberIsConstexpr(
14621 S&: *this, ClassDecl, CSM: CXXSpecialMemberKind::Destructor, ConstArg: false);
14622
14623 // Create the actual destructor declaration.
14624 CanQualType ClassType = Context.getCanonicalTagType(TD: ClassDecl);
14625 SourceLocation ClassLoc = ClassDecl->getLocation();
14626 DeclarationName Name
14627 = Context.DeclarationNames.getCXXDestructorName(Ty: ClassType);
14628 DeclarationNameInfo NameInfo(Name, ClassLoc);
14629 CXXDestructorDecl *Destructor = CXXDestructorDecl::Create(
14630 C&: Context, RD: ClassDecl, StartLoc: ClassLoc, NameInfo, T: QualType(), TInfo: nullptr,
14631 UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
14632 /*isInline=*/true,
14633 /*isImplicitlyDeclared=*/true,
14634 ConstexprKind: Constexpr ? ConstexprSpecKind::Constexpr
14635 : ConstexprSpecKind::Unspecified);
14636 Destructor->setAccess(AS_public);
14637 Destructor->setDefaulted();
14638
14639 setupImplicitSpecialMemberType(SpecialMem: Destructor, ResultTy: Context.VoidTy, Args: {});
14640
14641 if (getLangOpts().CUDA)
14642 CUDA().inferTargetForImplicitSpecialMember(
14643 ClassDecl, CSM: CXXSpecialMemberKind::Destructor, MemberDecl: Destructor,
14644 /* ConstRHS */ false,
14645 /* Diagnose */ false);
14646
14647 // We don't need to use SpecialMemberIsTrivial here; triviality for
14648 // destructors is easy to compute.
14649 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
14650 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
14651 ClassDecl->hasTrivialDestructorForCall());
14652
14653 // Note that we have declared this destructor.
14654 ++getASTContext().NumImplicitDestructorsDeclared;
14655
14656 Scope *S = getScopeForContext(Ctx: ClassDecl);
14657 CheckImplicitSpecialMemberDeclaration(S, FD: Destructor);
14658
14659 // We can't check whether an implicit destructor is deleted before we complete
14660 // the definition of the class, because its validity depends on the alignment
14661 // of the class. We'll check this from ActOnFields once the class is complete.
14662 if (ClassDecl->isCompleteDefinition() &&
14663 ShouldDeleteSpecialMember(MD: Destructor, CSM: CXXSpecialMemberKind::Destructor))
14664 SetDeclDeleted(dcl: Destructor, DelLoc: ClassLoc);
14665
14666 // Introduce this destructor into its scope.
14667 if (S)
14668 PushOnScopeChains(D: Destructor, S, AddToContext: false);
14669 ClassDecl->addDecl(D: Destructor);
14670
14671 return Destructor;
14672}
14673
14674void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
14675 CXXDestructorDecl *Destructor) {
14676 DefaultedFunctionFPFeaturesRAII RestoreFP(*this, Destructor);
14677 assert((Destructor->isDefaulted() &&
14678 !Destructor->doesThisDeclarationHaveABody() &&
14679 !Destructor->isDeleted()) &&
14680 "DefineImplicitDestructor - call it for implicit default dtor");
14681 if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
14682 return;
14683
14684 CXXRecordDecl *ClassDecl = Destructor->getParent();
14685 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
14686
14687 SynthesizedFunctionScope Scope(*this, Destructor);
14688
14689 // The exception specification is needed because we are defining the
14690 // function.
14691 ResolveExceptionSpec(Loc: CurrentLocation,
14692 FPT: Destructor->getType()->castAs<FunctionProtoType>());
14693 MarkVTableUsed(Loc: CurrentLocation, Class: ClassDecl);
14694
14695 // Add a context note for diagnostics produced after this point.
14696 Scope.addContextNote(UseLoc: CurrentLocation);
14697
14698 MarkBaseAndMemberDestructorsReferenced(Location: Destructor->getLocation(),
14699 ClassDecl: Destructor->getParent());
14700
14701 if (CheckDestructor(Destructor)) {
14702 Destructor->setInvalidDecl();
14703 return;
14704 }
14705
14706 SourceLocation Loc = Destructor->getEndLoc().isValid()
14707 ? Destructor->getEndLoc()
14708 : Destructor->getLocation();
14709 Destructor->setBody(new (Context) CompoundStmt(Loc));
14710 Destructor->markUsed(C&: Context);
14711
14712 if (ASTMutationListener *L = getASTMutationListener()) {
14713 L->CompletedImplicitDefinition(D: Destructor);
14714 }
14715}
14716
14717void Sema::CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
14718 CXXDestructorDecl *Destructor) {
14719 if (Destructor->isInvalidDecl())
14720 return;
14721
14722 CXXRecordDecl *ClassDecl = Destructor->getParent();
14723 assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&
14724 "implicit complete dtors unneeded outside MS ABI");
14725 assert(ClassDecl->getNumVBases() > 0 &&
14726 "complete dtor only exists for classes with vbases");
14727
14728 SynthesizedFunctionScope Scope(*this, Destructor);
14729
14730 // Add a context note for diagnostics produced after this point.
14731 Scope.addContextNote(UseLoc: CurrentLocation);
14732
14733 MarkVirtualBaseDestructorsReferenced(Location: Destructor->getLocation(), ClassDecl);
14734}
14735
14736void Sema::ActOnFinishCXXMemberDecls() {
14737 // If the context is an invalid C++ class, just suppress these checks.
14738 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: CurContext)) {
14739 if (Record->isInvalidDecl()) {
14740 DelayedOverridingExceptionSpecChecks.clear();
14741 DelayedEquivalentExceptionSpecChecks.clear();
14742 return;
14743 }
14744 checkForMultipleExportedDefaultConstructors(S&: *this, Class: Record);
14745 }
14746}
14747
14748void Sema::ActOnFinishCXXNonNestedClass() {
14749 referenceDLLExportedClassMethods();
14750
14751 if (!DelayedDllExportMemberFunctions.empty()) {
14752 SmallVector<CXXMethodDecl*, 4> WorkList;
14753 std::swap(LHS&: DelayedDllExportMemberFunctions, RHS&: WorkList);
14754 for (CXXMethodDecl *M : WorkList) {
14755 DefineDefaultedFunction(S&: *this, FD: M, DefaultLoc: M->getLocation());
14756
14757 // Pass the method to the consumer to get emitted. This is not necessary
14758 // for explicit instantiation definitions, as they will get emitted
14759 // anyway.
14760 if (M->getParent()->getTemplateSpecializationKind() !=
14761 TSK_ExplicitInstantiationDefinition)
14762 ActOnFinishInlineFunctionDef(D: M);
14763 }
14764 }
14765}
14766
14767void Sema::referenceDLLExportedClassMethods() {
14768 if (!DelayedDllExportClasses.empty()) {
14769 // Calling ReferenceDllExportedMembers might cause the current function to
14770 // be called again, so use a local copy of DelayedDllExportClasses.
14771 SmallVector<CXXRecordDecl *, 4> WorkList;
14772 std::swap(LHS&: DelayedDllExportClasses, RHS&: WorkList);
14773 for (CXXRecordDecl *Class : WorkList)
14774 ReferenceDllExportedMembers(S&: *this, Class);
14775 }
14776}
14777
14778void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
14779 assert(getLangOpts().CPlusPlus11 &&
14780 "adjusting dtor exception specs was introduced in c++11");
14781
14782 if (Destructor->isDependentContext())
14783 return;
14784
14785 // C++11 [class.dtor]p3:
14786 // A declaration of a destructor that does not have an exception-
14787 // specification is implicitly considered to have the same exception-
14788 // specification as an implicit declaration.
14789 const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>();
14790 if (DtorType->hasExceptionSpec())
14791 return;
14792
14793 // Replace the destructor's type, building off the existing one. Fortunately,
14794 // the only thing of interest in the destructor type is its extended info.
14795 // The return and arguments are fixed.
14796 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
14797 EPI.ExceptionSpec.Type = EST_Unevaluated;
14798 EPI.ExceptionSpec.SourceDecl = Destructor;
14799 Destructor->setType(Context.getFunctionType(ResultTy: Context.VoidTy, Args: {}, EPI));
14800
14801 // FIXME: If the destructor has a body that could throw, and the newly created
14802 // spec doesn't allow exceptions, we should emit a warning, because this
14803 // change in behavior can break conforming C++03 programs at runtime.
14804 // However, we don't have a body or an exception specification yet, so it
14805 // needs to be done somewhere else.
14806}
14807
14808namespace {
14809/// An abstract base class for all helper classes used in building the
14810// copy/move operators. These classes serve as factory functions and help us
14811// avoid using the same Expr* in the AST twice.
14812class ExprBuilder {
14813 ExprBuilder(const ExprBuilder&) = delete;
14814 ExprBuilder &operator=(const ExprBuilder&) = delete;
14815
14816protected:
14817 static Expr *assertNotNull(Expr *E) {
14818 assert(E && "Expression construction must not fail.");
14819 return E;
14820 }
14821
14822public:
14823 ExprBuilder() {}
14824 virtual ~ExprBuilder() {}
14825
14826 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
14827};
14828
14829class RefBuilder: public ExprBuilder {
14830 VarDecl *Var;
14831 QualType VarType;
14832
14833public:
14834 Expr *build(Sema &S, SourceLocation Loc) const override {
14835 return assertNotNull(E: S.BuildDeclRefExpr(D: Var, Ty: VarType, VK: VK_LValue, Loc));
14836 }
14837
14838 RefBuilder(VarDecl *Var, QualType VarType)
14839 : Var(Var), VarType(VarType) {}
14840};
14841
14842class ThisBuilder: public ExprBuilder {
14843public:
14844 Expr *build(Sema &S, SourceLocation Loc) const override {
14845 return assertNotNull(E: S.ActOnCXXThis(Loc).getAs<Expr>());
14846 }
14847};
14848
14849class CastBuilder: public ExprBuilder {
14850 const ExprBuilder &Builder;
14851 QualType Type;
14852 ExprValueKind Kind;
14853 const CXXCastPath &Path;
14854
14855public:
14856 Expr *build(Sema &S, SourceLocation Loc) const override {
14857 return assertNotNull(E: S.ImpCastExprToType(E: Builder.build(S, Loc), Type,
14858 CK: CK_UncheckedDerivedToBase, VK: Kind,
14859 BasePath: &Path).get());
14860 }
14861
14862 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
14863 const CXXCastPath &Path)
14864 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
14865};
14866
14867class DerefBuilder: public ExprBuilder {
14868 const ExprBuilder &Builder;
14869
14870public:
14871 Expr *build(Sema &S, SourceLocation Loc) const override {
14872 return assertNotNull(
14873 E: S.CreateBuiltinUnaryOp(OpLoc: Loc, Opc: UO_Deref, InputExpr: Builder.build(S, Loc)).get());
14874 }
14875
14876 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14877};
14878
14879class MemberBuilder: public ExprBuilder {
14880 const ExprBuilder &Builder;
14881 QualType Type;
14882 CXXScopeSpec SS;
14883 bool IsArrow;
14884 LookupResult &MemberLookup;
14885
14886public:
14887 Expr *build(Sema &S, SourceLocation Loc) const override {
14888 return assertNotNull(E: S.BuildMemberReferenceExpr(
14889 Base: Builder.build(S, Loc), BaseType: Type, OpLoc: Loc, IsArrow, SS, TemplateKWLoc: SourceLocation(),
14890 FirstQualifierInScope: nullptr, R&: MemberLookup, TemplateArgs: nullptr, S: nullptr).get());
14891 }
14892
14893 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
14894 LookupResult &MemberLookup)
14895 : Builder(Builder), Type(Type), IsArrow(IsArrow),
14896 MemberLookup(MemberLookup) {}
14897};
14898
14899class MoveCastBuilder: public ExprBuilder {
14900 const ExprBuilder &Builder;
14901
14902public:
14903 Expr *build(Sema &S, SourceLocation Loc) const override {
14904 return assertNotNull(E: CastForMoving(SemaRef&: S, E: Builder.build(S, Loc)));
14905 }
14906
14907 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14908};
14909
14910class LvalueConvBuilder: public ExprBuilder {
14911 const ExprBuilder &Builder;
14912
14913public:
14914 Expr *build(Sema &S, SourceLocation Loc) const override {
14915 return assertNotNull(
14916 E: S.DefaultLvalueConversion(E: Builder.build(S, Loc)).get());
14917 }
14918
14919 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14920};
14921
14922class SubscriptBuilder: public ExprBuilder {
14923 const ExprBuilder &Base;
14924 const ExprBuilder &Index;
14925
14926public:
14927 Expr *build(Sema &S, SourceLocation Loc) const override {
14928 return assertNotNull(E: S.CreateBuiltinArraySubscriptExpr(
14929 Base: Base.build(S, Loc), LLoc: Loc, Idx: Index.build(S, Loc), RLoc: Loc).get());
14930 }
14931
14932 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
14933 : Base(Base), Index(Index) {}
14934};
14935
14936} // end anonymous namespace
14937
14938/// When generating a defaulted copy or move assignment operator, if a field
14939/// should be copied with __builtin_memcpy rather than via explicit assignments,
14940/// do so. This optimization only applies for arrays of scalars, and for arrays
14941/// of class type where the selected copy/move-assignment operator is trivial.
14942static StmtResult
14943buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
14944 const ExprBuilder &ToB, const ExprBuilder &FromB) {
14945 // Compute the size of the memory buffer to be copied.
14946 QualType SizeType = S.Context.getSizeType();
14947 llvm::APInt Size(S.Context.getTypeSize(T: SizeType),
14948 S.Context.getTypeSizeInChars(T).getQuantity());
14949
14950 // Take the address of the field references for "from" and "to". We
14951 // directly construct UnaryOperators here because semantic analysis
14952 // does not permit us to take the address of an xvalue.
14953 Expr *From = FromB.build(S, Loc);
14954 From = UnaryOperator::Create(
14955 C: S.Context, input: From, opc: UO_AddrOf, type: S.Context.getPointerType(T: From->getType()),
14956 VK: VK_PRValue, OK: OK_Ordinary, l: Loc, CanOverflow: false, FPFeatures: S.CurFPFeatureOverrides());
14957 Expr *To = ToB.build(S, Loc);
14958 To = UnaryOperator::Create(
14959 C: S.Context, input: To, opc: UO_AddrOf, type: S.Context.getPointerType(T: To->getType()),
14960 VK: VK_PRValue, OK: OK_Ordinary, l: Loc, CanOverflow: false, FPFeatures: S.CurFPFeatureOverrides());
14961
14962 bool NeedsCollectableMemCpy = false;
14963 if (auto *RD = T->getBaseElementTypeUnsafe()->getAsRecordDecl())
14964 NeedsCollectableMemCpy = RD->hasObjectMember();
14965
14966 // Create a reference to the __builtin_objc_memmove_collectable function
14967 StringRef MemCpyName = NeedsCollectableMemCpy ?
14968 "__builtin_objc_memmove_collectable" :
14969 "__builtin_memcpy";
14970 LookupResult R(S, &S.Context.Idents.get(Name: MemCpyName), Loc,
14971 Sema::LookupOrdinaryName);
14972 S.LookupName(R, S: S.TUScope, AllowBuiltinCreation: true);
14973
14974 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
14975 if (!MemCpy)
14976 // Something went horribly wrong earlier, and we will have complained
14977 // about it.
14978 return StmtError();
14979
14980 ExprResult MemCpyRef = S.BuildDeclRefExpr(D: MemCpy, Ty: S.Context.BuiltinFnTy,
14981 VK: VK_PRValue, Loc, SS: nullptr);
14982 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
14983
14984 Expr *CallArgs[] = {
14985 To, From, IntegerLiteral::Create(C: S.Context, V: Size, type: SizeType, l: Loc)
14986 };
14987 ExprResult Call = S.BuildCallExpr(/*Scope=*/S: nullptr, Fn: MemCpyRef.get(),
14988 LParenLoc: Loc, ArgExprs: CallArgs, RParenLoc: Loc);
14989
14990 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
14991 return Call.getAs<Stmt>();
14992}
14993
14994/// Builds a statement that copies/moves the given entity from \p From to
14995/// \c To.
14996///
14997/// This routine is used to copy/move the members of a class with an
14998/// implicitly-declared copy/move assignment operator. When the entities being
14999/// copied are arrays, this routine builds for loops to copy them.
15000///
15001/// \param S The Sema object used for type-checking.
15002///
15003/// \param Loc The location where the implicit copy/move is being generated.
15004///
15005/// \param T The type of the expressions being copied/moved. Both expressions
15006/// must have this type.
15007///
15008/// \param To The expression we are copying/moving to.
15009///
15010/// \param From The expression we are copying/moving from.
15011///
15012/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
15013/// Otherwise, it's a non-static member subobject.
15014///
15015/// \param Copying Whether we're copying or moving.
15016///
15017/// \param Depth Internal parameter recording the depth of the recursion.
15018///
15019/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
15020/// if a memcpy should be used instead.
15021static StmtResult
15022buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
15023 const ExprBuilder &To, const ExprBuilder &From,
15024 bool CopyingBaseSubobject, bool Copying,
15025 unsigned Depth = 0) {
15026 // C++11 [class.copy]p28:
15027 // Each subobject is assigned in the manner appropriate to its type:
15028 //
15029 // - if the subobject is of class type, as if by a call to operator= with
15030 // the subobject as the object expression and the corresponding
15031 // subobject of x as a single function argument (as if by explicit
15032 // qualification; that is, ignoring any possible virtual overriding
15033 // functions in more derived classes);
15034 //
15035 // C++03 [class.copy]p13:
15036 // - if the subobject is of class type, the copy assignment operator for
15037 // the class is used (as if by explicit qualification; that is,
15038 // ignoring any possible virtual overriding functions in more derived
15039 // classes);
15040 if (auto *ClassDecl = T->getAsCXXRecordDecl()) {
15041 // Look for operator=.
15042 DeclarationName Name
15043 = S.Context.DeclarationNames.getCXXOperatorName(Op: OO_Equal);
15044 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
15045 S.LookupQualifiedName(R&: OpLookup, LookupCtx: ClassDecl, InUnqualifiedLookup: false);
15046
15047 // Prior to C++11, filter out any result that isn't a copy/move-assignment
15048 // operator.
15049 if (!S.getLangOpts().CPlusPlus11) {
15050 LookupResult::Filter F = OpLookup.makeFilter();
15051 while (F.hasNext()) {
15052 NamedDecl *D = F.next();
15053 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: D))
15054 if (Method->isCopyAssignmentOperator() ||
15055 (!Copying && Method->isMoveAssignmentOperator()))
15056 continue;
15057
15058 F.erase();
15059 }
15060 F.done();
15061 }
15062
15063 // Suppress the protected check (C++ [class.protected]) for each of the
15064 // assignment operators we found. This strange dance is required when
15065 // we're assigning via a base classes's copy-assignment operator. To
15066 // ensure that we're getting the right base class subobject (without
15067 // ambiguities), we need to cast "this" to that subobject type; to
15068 // ensure that we don't go through the virtual call mechanism, we need
15069 // to qualify the operator= name with the base class (see below). However,
15070 // this means that if the base class has a protected copy assignment
15071 // operator, the protected member access check will fail. So, we
15072 // rewrite "protected" access to "public" access in this case, since we
15073 // know by construction that we're calling from a derived class.
15074 if (CopyingBaseSubobject) {
15075 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
15076 L != LEnd; ++L) {
15077 if (L.getAccess() == AS_protected)
15078 L.setAccess(AS_public);
15079 }
15080 }
15081
15082 // Create the nested-name-specifier that will be used to qualify the
15083 // reference to operator=; this is required to suppress the virtual
15084 // call mechanism.
15085 CXXScopeSpec SS;
15086 // FIXME: Don't canonicalize this.
15087 const Type *CanonicalT = S.Context.getCanonicalType(T: T.getTypePtr());
15088 SS.MakeTrivial(Context&: S.Context, Qualifier: NestedNameSpecifier(CanonicalT), R: Loc);
15089
15090 // Create the reference to operator=.
15091 ExprResult OpEqualRef
15092 = S.BuildMemberReferenceExpr(Base: To.build(S, Loc), BaseType: T, OpLoc: Loc, /*IsArrow=*/false,
15093 SS, /*TemplateKWLoc=*/SourceLocation(),
15094 /*FirstQualifierInScope=*/nullptr,
15095 R&: OpLookup,
15096 /*TemplateArgs=*/nullptr, /*S*/nullptr,
15097 /*SuppressQualifierCheck=*/true);
15098 if (OpEqualRef.isInvalid())
15099 return StmtError();
15100
15101 // Build the call to the assignment operator.
15102
15103 Expr *FromInst = From.build(S, Loc);
15104 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/S: nullptr,
15105 MemExpr: OpEqualRef.getAs<Expr>(),
15106 LParenLoc: Loc, Args: FromInst, RParenLoc: Loc);
15107 if (Call.isInvalid())
15108 return StmtError();
15109
15110 // If we built a call to a trivial 'operator=' while copying an array,
15111 // bail out. We'll replace the whole shebang with a memcpy.
15112 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Val: Call.get());
15113 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
15114 return StmtResult((Stmt*)nullptr);
15115
15116 // Convert to an expression-statement, and clean up any produced
15117 // temporaries.
15118 return S.ActOnExprStmt(Arg: Call);
15119 }
15120
15121 // - if the subobject is of scalar type, the built-in assignment
15122 // operator is used.
15123 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
15124 if (!ArrayTy) {
15125 ExprResult Assignment = S.CreateBuiltinBinOp(
15126 OpLoc: Loc, Opc: BO_Assign, LHSExpr: To.build(S, Loc), RHSExpr: From.build(S, Loc));
15127 if (Assignment.isInvalid())
15128 return StmtError();
15129 return S.ActOnExprStmt(Arg: Assignment);
15130 }
15131
15132 // - if the subobject is an array, each element is assigned, in the
15133 // manner appropriate to the element type;
15134
15135 // Construct a loop over the array bounds, e.g.,
15136 //
15137 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
15138 //
15139 // that will copy each of the array elements.
15140 QualType SizeType = S.Context.getSizeType();
15141
15142 // Create the iteration variable.
15143 IdentifierInfo *IterationVarName = nullptr;
15144 {
15145 SmallString<8> Str;
15146 llvm::raw_svector_ostream OS(Str);
15147 OS << "__i" << Depth;
15148 IterationVarName = &S.Context.Idents.get(Name: OS.str());
15149 }
15150 VarDecl *IterationVar = VarDecl::Create(C&: S.Context, DC: S.CurContext, StartLoc: Loc, IdLoc: Loc,
15151 Id: IterationVarName, T: SizeType,
15152 TInfo: S.Context.getTrivialTypeSourceInfo(T: SizeType, Loc),
15153 S: SC_None);
15154
15155 // Initialize the iteration variable to zero.
15156 llvm::APInt Zero(S.Context.getTypeSize(T: SizeType), 0);
15157 IterationVar->setInit(IntegerLiteral::Create(C: S.Context, V: Zero, type: SizeType, l: Loc));
15158
15159 // Creates a reference to the iteration variable.
15160 RefBuilder IterationVarRef(IterationVar, SizeType);
15161 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
15162
15163 // Create the DeclStmt that holds the iteration variable.
15164 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
15165
15166 // Subscript the "from" and "to" expressions with the iteration variable.
15167 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
15168 MoveCastBuilder FromIndexMove(FromIndexCopy);
15169 const ExprBuilder *FromIndex;
15170 if (Copying)
15171 FromIndex = &FromIndexCopy;
15172 else
15173 FromIndex = &FromIndexMove;
15174
15175 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
15176
15177 // Build the copy/move for an individual element of the array.
15178 StmtResult Copy =
15179 buildSingleCopyAssignRecursively(S, Loc, T: ArrayTy->getElementType(),
15180 To: ToIndex, From: *FromIndex, CopyingBaseSubobject,
15181 Copying, Depth: Depth + 1);
15182 // Bail out if copying fails or if we determined that we should use memcpy.
15183 if (Copy.isInvalid() || !Copy.get())
15184 return Copy;
15185
15186 // Create the comparison against the array bound.
15187 llvm::APInt Upper
15188 = ArrayTy->getSize().zextOrTrunc(width: S.Context.getTypeSize(T: SizeType));
15189 Expr *Comparison = BinaryOperator::Create(
15190 C: S.Context, lhs: IterationVarRefRVal.build(S, Loc),
15191 rhs: IntegerLiteral::Create(C: S.Context, V: Upper, type: SizeType, l: Loc), opc: BO_NE,
15192 ResTy: S.Context.BoolTy, VK: VK_PRValue, OK: OK_Ordinary, opLoc: Loc,
15193 FPFeatures: S.CurFPFeatureOverrides());
15194
15195 // Create the pre-increment of the iteration variable. We can determine
15196 // whether the increment will overflow based on the value of the array
15197 // bound.
15198 Expr *Increment = UnaryOperator::Create(
15199 C: S.Context, input: IterationVarRef.build(S, Loc), opc: UO_PreInc, type: SizeType, VK: VK_LValue,
15200 OK: OK_Ordinary, l: Loc, CanOverflow: Upper.isMaxValue(), FPFeatures: S.CurFPFeatureOverrides());
15201
15202 // Construct the loop that copies all elements of this array.
15203 return S.ActOnForStmt(
15204 ForLoc: Loc, LParenLoc: Loc, First: InitStmt,
15205 Second: S.ActOnCondition(S: nullptr, Loc, SubExpr: Comparison, CK: Sema::ConditionKind::Boolean),
15206 Third: S.MakeFullDiscardedValueExpr(Arg: Increment), RParenLoc: Loc, Body: Copy.get());
15207}
15208
15209static StmtResult
15210buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
15211 const ExprBuilder &To, const ExprBuilder &From,
15212 bool CopyingBaseSubobject, bool Copying) {
15213 // Maybe we should use a memcpy?
15214 if (T->isArrayType() && !T.hasQualifiers() &&
15215 T.isTriviallyCopyableType(Context: S.Context))
15216 return buildMemcpyForAssignmentOp(S, Loc, T, ToB: To, FromB: From);
15217
15218 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
15219 CopyingBaseSubobject,
15220 Copying, Depth: 0));
15221
15222 // If we ended up picking a trivial assignment operator for an array of a
15223 // non-trivially-copyable class type, just emit a memcpy.
15224 if (!Result.isInvalid() && !Result.get())
15225 return buildMemcpyForAssignmentOp(S, Loc, T, ToB: To, FromB: From);
15226
15227 return Result;
15228}
15229
15230CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
15231 // Note: The following rules are largely analoguous to the copy
15232 // constructor rules. Note that virtual bases are not taken into account
15233 // for determining the argument type of the operator. Note also that
15234 // operators taking an object instead of a reference are allowed.
15235 assert(ClassDecl->needsImplicitCopyAssignment());
15236
15237 DeclaringSpecialMember DSM(*this, ClassDecl,
15238 CXXSpecialMemberKind::CopyAssignment);
15239 if (DSM.isAlreadyBeingDeclared())
15240 return nullptr;
15241
15242 QualType ArgType = Context.getTagType(Keyword: ElaboratedTypeKeyword::None,
15243 /*Qualifier=*/std::nullopt, TD: ClassDecl,
15244 /*OwnsTag=*/false);
15245 LangAS AS = getDefaultCXXMethodAddrSpace();
15246 if (AS != LangAS::Default)
15247 ArgType = Context.getAddrSpaceQualType(T: ArgType, AddressSpace: AS);
15248 QualType RetType = Context.getLValueReferenceType(T: ArgType);
15249 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
15250 if (Const)
15251 ArgType = ArgType.withConst();
15252
15253 ArgType = Context.getLValueReferenceType(T: ArgType);
15254
15255 bool Constexpr = defaultedSpecialMemberIsConstexpr(
15256 S&: *this, ClassDecl, CSM: CXXSpecialMemberKind::CopyAssignment, ConstArg: Const);
15257
15258 // An implicitly-declared copy assignment operator is an inline public
15259 // member of its class.
15260 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(Op: OO_Equal);
15261 SourceLocation ClassLoc = ClassDecl->getLocation();
15262 DeclarationNameInfo NameInfo(Name, ClassLoc);
15263 CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create(
15264 C&: Context, RD: ClassDecl, StartLoc: ClassLoc, NameInfo, T: QualType(),
15265 /*TInfo=*/nullptr, /*StorageClass=*/SC: SC_None,
15266 UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
15267 /*isInline=*/true,
15268 ConstexprKind: Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
15269 EndLocation: SourceLocation());
15270 CopyAssignment->setAccess(AS_public);
15271 CopyAssignment->setDefaulted();
15272 CopyAssignment->setImplicit();
15273
15274 setupImplicitSpecialMemberType(SpecialMem: CopyAssignment, ResultTy: RetType, Args: ArgType);
15275
15276 if (getLangOpts().CUDA)
15277 CUDA().inferTargetForImplicitSpecialMember(
15278 ClassDecl, CSM: CXXSpecialMemberKind::CopyAssignment, MemberDecl: CopyAssignment,
15279 /* ConstRHS */ Const,
15280 /* Diagnose */ false);
15281
15282 // Add the parameter to the operator.
15283 ParmVarDecl *FromParam = ParmVarDecl::Create(C&: Context, DC: CopyAssignment,
15284 StartLoc: ClassLoc, IdLoc: ClassLoc,
15285 /*Id=*/nullptr, T: ArgType,
15286 /*TInfo=*/nullptr, S: SC_None,
15287 DefArg: nullptr);
15288 CopyAssignment->setParams(FromParam);
15289
15290 CopyAssignment->setTrivial(
15291 ClassDecl->needsOverloadResolutionForCopyAssignment()
15292 ? SpecialMemberIsTrivial(MD: CopyAssignment,
15293 CSM: CXXSpecialMemberKind::CopyAssignment)
15294 : ClassDecl->hasTrivialCopyAssignment());
15295
15296 // Note that we have added this copy-assignment operator.
15297 ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
15298
15299 Scope *S = getScopeForContext(Ctx: ClassDecl);
15300 CheckImplicitSpecialMemberDeclaration(S, FD: CopyAssignment);
15301
15302 if (ShouldDeleteSpecialMember(MD: CopyAssignment,
15303 CSM: CXXSpecialMemberKind::CopyAssignment)) {
15304 ClassDecl->setImplicitCopyAssignmentIsDeleted();
15305 SetDeclDeleted(dcl: CopyAssignment, DelLoc: ClassLoc);
15306 }
15307
15308 if (S)
15309 PushOnScopeChains(D: CopyAssignment, S, AddToContext: false);
15310 ClassDecl->addDecl(D: CopyAssignment);
15311
15312 return CopyAssignment;
15313}
15314
15315/// Diagnose an implicit copy operation for a class which is odr-used, but
15316/// which is deprecated because the class has a user-declared copy constructor,
15317/// copy assignment operator, or destructor.
15318static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
15319 assert(CopyOp->isImplicit());
15320
15321 CXXRecordDecl *RD = CopyOp->getParent();
15322 CXXMethodDecl *UserDeclaredOperation = nullptr;
15323
15324 if (RD->hasUserDeclaredDestructor()) {
15325 UserDeclaredOperation = RD->getDestructor();
15326 } else if (!isa<CXXConstructorDecl>(Val: CopyOp) &&
15327 RD->hasUserDeclaredCopyConstructor()) {
15328 // Find any user-declared copy constructor.
15329 for (auto *I : RD->ctors()) {
15330 if (I->isCopyConstructor()) {
15331 UserDeclaredOperation = I;
15332 break;
15333 }
15334 }
15335 assert(UserDeclaredOperation);
15336 } else if (isa<CXXConstructorDecl>(Val: CopyOp) &&
15337 RD->hasUserDeclaredCopyAssignment()) {
15338 // Find any user-declared move assignment operator.
15339 for (auto *I : RD->methods()) {
15340 if (I->isCopyAssignmentOperator()) {
15341 UserDeclaredOperation = I;
15342 break;
15343 }
15344 }
15345 assert(UserDeclaredOperation);
15346 }
15347
15348 if (UserDeclaredOperation) {
15349 bool UDOIsUserProvided = UserDeclaredOperation->isUserProvided();
15350 bool UDOIsDestructor = isa<CXXDestructorDecl>(Val: UserDeclaredOperation);
15351 bool IsCopyAssignment = !isa<CXXConstructorDecl>(Val: CopyOp);
15352 unsigned DiagID =
15353 (UDOIsUserProvided && UDOIsDestructor)
15354 ? diag::warn_deprecated_copy_with_user_provided_dtor
15355 : (UDOIsUserProvided && !UDOIsDestructor)
15356 ? diag::warn_deprecated_copy_with_user_provided_copy
15357 : (!UDOIsUserProvided && UDOIsDestructor)
15358 ? diag::warn_deprecated_copy_with_dtor
15359 : diag::warn_deprecated_copy;
15360 S.Diag(Loc: UserDeclaredOperation->getLocation(), DiagID)
15361 << RD << IsCopyAssignment;
15362 }
15363}
15364
15365void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
15366 CXXMethodDecl *CopyAssignOperator) {
15367 DefaultedFunctionFPFeaturesRAII RestoreFP(*this, CopyAssignOperator);
15368 assert((CopyAssignOperator->isDefaulted() &&
15369 CopyAssignOperator->isOverloadedOperator() &&
15370 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
15371 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
15372 !CopyAssignOperator->isDeleted()) &&
15373 "DefineImplicitCopyAssignment called for wrong function");
15374 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
15375 return;
15376
15377 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
15378 if (ClassDecl->isInvalidDecl()) {
15379 CopyAssignOperator->setInvalidDecl();
15380 return;
15381 }
15382
15383 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
15384
15385 // The exception specification is needed because we are defining the
15386 // function.
15387 ResolveExceptionSpec(Loc: CurrentLocation,
15388 FPT: CopyAssignOperator->getType()->castAs<FunctionProtoType>());
15389
15390 // Add a context note for diagnostics produced after this point.
15391 Scope.addContextNote(UseLoc: CurrentLocation);
15392
15393 // C++11 [class.copy]p18:
15394 // The [definition of an implicitly declared copy assignment operator] is
15395 // deprecated if the class has a user-declared copy constructor or a
15396 // user-declared destructor.
15397 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
15398 diagnoseDeprecatedCopyOperation(S&: *this, CopyOp: CopyAssignOperator);
15399
15400 // C++0x [class.copy]p30:
15401 // The implicitly-defined or explicitly-defaulted copy assignment operator
15402 // for a non-union class X performs memberwise copy assignment of its
15403 // subobjects. The direct base classes of X are assigned first, in the
15404 // order of their declaration in the base-specifier-list, and then the
15405 // immediate non-static data members of X are assigned, in the order in
15406 // which they were declared in the class definition.
15407
15408 // The statements that form the synthesized function body.
15409 SmallVector<Stmt*, 8> Statements;
15410
15411 // The parameter for the "other" object, which we are copying from.
15412 ParmVarDecl *Other = CopyAssignOperator->getNonObjectParameter(I: 0);
15413 Qualifiers OtherQuals = Other->getType().getQualifiers();
15414 QualType OtherRefType = Other->getType();
15415 if (OtherRefType->isLValueReferenceType()) {
15416 OtherRefType = OtherRefType->getPointeeType();
15417 OtherQuals = OtherRefType.getQualifiers();
15418 }
15419
15420 // Our location for everything implicitly-generated.
15421 SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
15422 ? CopyAssignOperator->getEndLoc()
15423 : CopyAssignOperator->getLocation();
15424
15425 // Builds a DeclRefExpr for the "other" object.
15426 RefBuilder OtherRef(Other, OtherRefType);
15427
15428 // Builds the function object parameter.
15429 std::optional<ThisBuilder> This;
15430 std::optional<DerefBuilder> DerefThis;
15431 std::optional<RefBuilder> ExplicitObject;
15432 bool IsArrow = false;
15433 QualType ObjectType;
15434 if (CopyAssignOperator->isExplicitObjectMemberFunction()) {
15435 ObjectType = CopyAssignOperator->getParamDecl(i: 0)->getType();
15436 if (ObjectType->isReferenceType())
15437 ObjectType = ObjectType->getPointeeType();
15438 ExplicitObject.emplace(args: CopyAssignOperator->getParamDecl(i: 0), args&: ObjectType);
15439 } else {
15440 ObjectType = getCurrentThisType();
15441 This.emplace();
15442 DerefThis.emplace(args&: *This);
15443 IsArrow = !LangOpts.HLSL;
15444 }
15445 ExprBuilder &ObjectParameter =
15446 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15447 : static_cast<ExprBuilder &>(*This);
15448
15449 // Assign base classes.
15450 bool Invalid = false;
15451 for (auto &Base : ClassDecl->bases()) {
15452 // Form the assignment:
15453 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
15454 QualType BaseType = Base.getType().getUnqualifiedType();
15455 if (!BaseType->isRecordType()) {
15456 Invalid = true;
15457 continue;
15458 }
15459
15460 CXXCastPath BasePath;
15461 BasePath.push_back(Elt: &Base);
15462
15463 // Construct the "from" expression, which is an implicit cast to the
15464 // appropriately-qualified base type.
15465 CastBuilder From(OtherRef, Context.getQualifiedType(T: BaseType, Qs: OtherQuals),
15466 VK_LValue, BasePath);
15467
15468 // Dereference "this".
15469 CastBuilder To(
15470 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15471 : static_cast<ExprBuilder &>(*DerefThis),
15472 Context.getQualifiedType(T: BaseType, Qs: ObjectType.getQualifiers()),
15473 VK_LValue, BasePath);
15474
15475 // Build the copy.
15476 StmtResult Copy = buildSingleCopyAssign(S&: *this, Loc, T: BaseType,
15477 To, From,
15478 /*CopyingBaseSubobject=*/true,
15479 /*Copying=*/true);
15480 if (Copy.isInvalid()) {
15481 CopyAssignOperator->setInvalidDecl();
15482 return;
15483 }
15484
15485 // Success! Record the copy.
15486 Statements.push_back(Elt: Copy.getAs<Expr>());
15487 }
15488
15489 // A defaulted copy assignment operator for a union copies the object
15490 // representation as if by a memcpy, the same way the defaulted union copy
15491 // constructor does. The memberwise loop below skips union members.
15492 if (ClassDecl->isUnion()) {
15493 ExprBuilder &To = ExplicitObject
15494 ? static_cast<ExprBuilder &>(*ExplicitObject)
15495 : static_cast<ExprBuilder &>(*DerefThis);
15496 // Copying the object representation is correct even for a union that is
15497 // not trivially copyable, so -Wnontrivial-memcall is a false positive
15498 // here. Ignoring warnings rather than casting the arguments to void*
15499 // keeps them typed, which preserves their address space.
15500 IgnoreAllWarningDiagRAII IgnoreWarnings(Diags);
15501 StmtResult Copy = buildMemcpyForAssignmentOp(
15502 S&: *this, Loc, T: Context.getCanonicalTagType(TD: ClassDecl), ToB: To, FromB: OtherRef);
15503 if (Copy.isInvalid()) {
15504 CopyAssignOperator->setInvalidDecl();
15505 return;
15506 }
15507 Statements.push_back(Elt: Copy.getAs<Stmt>());
15508 }
15509
15510 // Assign non-static members.
15511 for (auto *Field : ClassDecl->fields()) {
15512 // Union members are copied by the whole-object memcpy emitted above.
15513 if (Field->isUnnamedBitField() || Field->getParent()->isUnion())
15514 continue;
15515
15516 if (Field->isInvalidDecl()) {
15517 Invalid = true;
15518 continue;
15519 }
15520
15521 // Check for members of reference type; we can't copy those.
15522 if (Field->getType()->isReferenceType()) {
15523 Diag(Loc: ClassDecl->getLocation(), DiagID: diag::err_uninitialized_member_for_assign)
15524 << Context.getCanonicalTagType(TD: ClassDecl) << 0
15525 << Field->getDeclName();
15526 Diag(Loc: Field->getLocation(), DiagID: diag::note_declared_at);
15527 Invalid = true;
15528 continue;
15529 }
15530
15531 // Check for members of const-qualified, non-class type.
15532 QualType BaseType = Context.getBaseElementType(QT: Field->getType());
15533 if (!BaseType->isRecordType() && BaseType.isConstQualified()) {
15534 Diag(Loc: ClassDecl->getLocation(), DiagID: diag::err_uninitialized_member_for_assign)
15535 << Context.getCanonicalTagType(TD: ClassDecl) << 1
15536 << Field->getDeclName();
15537 Diag(Loc: Field->getLocation(), DiagID: diag::note_declared_at);
15538 Invalid = true;
15539 continue;
15540 }
15541
15542 // Suppress assigning zero-width bitfields.
15543 if (Field->isZeroLengthBitField())
15544 continue;
15545
15546 QualType FieldType = Field->getType().getNonReferenceType();
15547 if (FieldType->isIncompleteArrayType()) {
15548 assert(ClassDecl->hasFlexibleArrayMember() &&
15549 "Incomplete array type is not valid");
15550 continue;
15551 }
15552
15553 // Build references to the field in the object we're copying from and to.
15554 CXXScopeSpec SS; // Intentionally empty
15555 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
15556 LookupMemberName);
15557 MemberLookup.addDecl(D: Field);
15558 MemberLookup.resolveKind();
15559
15560 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
15561 MemberBuilder To(ObjectParameter, ObjectType, IsArrow, MemberLookup);
15562 // Build the copy of this field.
15563 StmtResult Copy = buildSingleCopyAssign(S&: *this, Loc, T: FieldType,
15564 To, From,
15565 /*CopyingBaseSubobject=*/false,
15566 /*Copying=*/true);
15567 if (Copy.isInvalid()) {
15568 CopyAssignOperator->setInvalidDecl();
15569 return;
15570 }
15571
15572 // Success! Record the copy.
15573 Statements.push_back(Elt: Copy.getAs<Stmt>());
15574 }
15575
15576 if (!Invalid) {
15577 // Add a "return *this;"
15578 Expr *ThisExpr =
15579 (ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15580 : LangOpts.HLSL ? static_cast<ExprBuilder &>(*This)
15581 : static_cast<ExprBuilder &>(*DerefThis))
15582 .build(S&: *this, Loc);
15583 StmtResult Return = BuildReturnStmt(ReturnLoc: Loc, RetValExp: ThisExpr);
15584 if (Return.isInvalid())
15585 Invalid = true;
15586 else
15587 Statements.push_back(Elt: Return.getAs<Stmt>());
15588 }
15589
15590 if (Invalid) {
15591 CopyAssignOperator->setInvalidDecl();
15592 return;
15593 }
15594
15595 StmtResult Body;
15596 {
15597 CompoundScopeRAII CompoundScope(*this);
15598 Body = ActOnCompoundStmt(L: Loc, R: Loc, Elts: Statements,
15599 /*isStmtExpr=*/false);
15600 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
15601 }
15602 CopyAssignOperator->setBody(Body.getAs<Stmt>());
15603 CopyAssignOperator->markUsed(C&: Context);
15604
15605 if (ASTMutationListener *L = getASTMutationListener()) {
15606 L->CompletedImplicitDefinition(D: CopyAssignOperator);
15607 }
15608}
15609
15610CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
15611 assert(ClassDecl->needsImplicitMoveAssignment());
15612
15613 DeclaringSpecialMember DSM(*this, ClassDecl,
15614 CXXSpecialMemberKind::MoveAssignment);
15615 if (DSM.isAlreadyBeingDeclared())
15616 return nullptr;
15617
15618 // Note: The following rules are largely analoguous to the move
15619 // constructor rules.
15620
15621 QualType ArgType = Context.getTagType(Keyword: ElaboratedTypeKeyword::None,
15622 /*Qualifier=*/std::nullopt, TD: ClassDecl,
15623 /*OwnsTag=*/false);
15624 LangAS AS = getDefaultCXXMethodAddrSpace();
15625 if (AS != LangAS::Default)
15626 ArgType = Context.getAddrSpaceQualType(T: ArgType, AddressSpace: AS);
15627 QualType RetType = Context.getLValueReferenceType(T: ArgType);
15628 ArgType = Context.getRValueReferenceType(T: ArgType);
15629
15630 bool Constexpr = defaultedSpecialMemberIsConstexpr(
15631 S&: *this, ClassDecl, CSM: CXXSpecialMemberKind::MoveAssignment, ConstArg: false);
15632
15633 // An implicitly-declared move assignment operator is an inline public
15634 // member of its class.
15635 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(Op: OO_Equal);
15636 SourceLocation ClassLoc = ClassDecl->getLocation();
15637 DeclarationNameInfo NameInfo(Name, ClassLoc);
15638 CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create(
15639 C&: Context, RD: ClassDecl, StartLoc: ClassLoc, NameInfo, T: QualType(),
15640 /*TInfo=*/nullptr, /*StorageClass=*/SC: SC_None,
15641 UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
15642 /*isInline=*/true,
15643 ConstexprKind: Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
15644 EndLocation: SourceLocation());
15645 MoveAssignment->setAccess(AS_public);
15646 MoveAssignment->setDefaulted();
15647 MoveAssignment->setImplicit();
15648
15649 setupImplicitSpecialMemberType(SpecialMem: MoveAssignment, ResultTy: RetType, Args: ArgType);
15650
15651 if (getLangOpts().CUDA)
15652 CUDA().inferTargetForImplicitSpecialMember(
15653 ClassDecl, CSM: CXXSpecialMemberKind::MoveAssignment, MemberDecl: MoveAssignment,
15654 /* ConstRHS */ false,
15655 /* Diagnose */ false);
15656
15657 // Add the parameter to the operator.
15658 ParmVarDecl *FromParam = ParmVarDecl::Create(C&: Context, DC: MoveAssignment,
15659 StartLoc: ClassLoc, IdLoc: ClassLoc,
15660 /*Id=*/nullptr, T: ArgType,
15661 /*TInfo=*/nullptr, S: SC_None,
15662 DefArg: nullptr);
15663 MoveAssignment->setParams(FromParam);
15664
15665 MoveAssignment->setTrivial(
15666 ClassDecl->needsOverloadResolutionForMoveAssignment()
15667 ? SpecialMemberIsTrivial(MD: MoveAssignment,
15668 CSM: CXXSpecialMemberKind::MoveAssignment)
15669 : ClassDecl->hasTrivialMoveAssignment());
15670
15671 // Note that we have added this copy-assignment operator.
15672 ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
15673
15674 Scope *S = getScopeForContext(Ctx: ClassDecl);
15675 CheckImplicitSpecialMemberDeclaration(S, FD: MoveAssignment);
15676
15677 if (ShouldDeleteSpecialMember(MD: MoveAssignment,
15678 CSM: CXXSpecialMemberKind::MoveAssignment)) {
15679 ClassDecl->setImplicitMoveAssignmentIsDeleted();
15680 SetDeclDeleted(dcl: MoveAssignment, DelLoc: ClassLoc);
15681 }
15682
15683 if (S)
15684 PushOnScopeChains(D: MoveAssignment, S, AddToContext: false);
15685 ClassDecl->addDecl(D: MoveAssignment);
15686
15687 return MoveAssignment;
15688}
15689
15690/// Check if we're implicitly defining a move assignment operator for a class
15691/// with virtual bases. Such a move assignment might move-assign the virtual
15692/// base multiple times.
15693static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
15694 SourceLocation CurrentLocation) {
15695 assert(!Class->isDependentContext() && "should not define dependent move");
15696
15697 // Only a virtual base could get implicitly move-assigned multiple times.
15698 // Only a non-trivial move assignment can observe this. We only want to
15699 // diagnose if we implicitly define an assignment operator that assigns
15700 // two base classes, both of which move-assign the same virtual base.
15701 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
15702 Class->getNumBases() < 2)
15703 return;
15704
15705 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
15706 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
15707 VBaseMap VBases;
15708
15709 for (auto &BI : Class->bases()) {
15710 Worklist.push_back(Elt: &BI);
15711 while (!Worklist.empty()) {
15712 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
15713 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
15714
15715 // If the base has no non-trivial move assignment operators,
15716 // we don't care about moves from it.
15717 if (!Base->hasNonTrivialMoveAssignment())
15718 continue;
15719
15720 // If there's nothing virtual here, skip it.
15721 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
15722 continue;
15723
15724 // If we're not actually going to call a move assignment for this base,
15725 // or the selected move assignment is trivial, skip it.
15726 Sema::SpecialMemberOverloadResult SMOR =
15727 S.LookupSpecialMember(D: Base, SM: CXXSpecialMemberKind::MoveAssignment,
15728 /*ConstArg*/ false, /*VolatileArg*/ false,
15729 /*RValueThis*/ true, /*ConstThis*/ false,
15730 /*VolatileThis*/ false);
15731 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
15732 !SMOR.getMethod()->isMoveAssignmentOperator())
15733 continue;
15734
15735 if (BaseSpec->isVirtual()) {
15736 // We're going to move-assign this virtual base, and its move
15737 // assignment operator is not trivial. If this can happen for
15738 // multiple distinct direct bases of Class, diagnose it. (If it
15739 // only happens in one base, we'll diagnose it when synthesizing
15740 // that base class's move assignment operator.)
15741 CXXBaseSpecifier *&Existing =
15742 VBases.insert(KV: std::make_pair(x: Base->getCanonicalDecl(), y: &BI))
15743 .first->second;
15744 if (Existing && Existing != &BI) {
15745 S.Diag(Loc: CurrentLocation, DiagID: diag::warn_vbase_moved_multiple_times)
15746 << Class << Base;
15747 S.Diag(Loc: Existing->getBeginLoc(), DiagID: diag::note_vbase_moved_here)
15748 << (Base->getCanonicalDecl() ==
15749 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
15750 << Base << Existing->getType() << Existing->getSourceRange();
15751 S.Diag(Loc: BI.getBeginLoc(), DiagID: diag::note_vbase_moved_here)
15752 << (Base->getCanonicalDecl() ==
15753 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
15754 << Base << BI.getType() << BaseSpec->getSourceRange();
15755
15756 // Only diagnose each vbase once.
15757 Existing = nullptr;
15758 }
15759 } else {
15760 // Only walk over bases that have defaulted move assignment operators.
15761 // We assume that any user-provided move assignment operator handles
15762 // the multiple-moves-of-vbase case itself somehow.
15763 if (!SMOR.getMethod()->isDefaulted())
15764 continue;
15765
15766 // We're going to move the base classes of Base. Add them to the list.
15767 llvm::append_range(C&: Worklist, R: llvm::make_pointer_range(Range: Base->bases()));
15768 }
15769 }
15770 }
15771}
15772
15773void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
15774 CXXMethodDecl *MoveAssignOperator) {
15775 DefaultedFunctionFPFeaturesRAII RestoreFP(*this, MoveAssignOperator);
15776 assert((MoveAssignOperator->isDefaulted() &&
15777 MoveAssignOperator->isOverloadedOperator() &&
15778 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
15779 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
15780 !MoveAssignOperator->isDeleted()) &&
15781 "DefineImplicitMoveAssignment called for wrong function");
15782 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
15783 return;
15784
15785 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
15786 if (ClassDecl->isInvalidDecl()) {
15787 MoveAssignOperator->setInvalidDecl();
15788 return;
15789 }
15790
15791 // C++0x [class.copy]p28:
15792 // The implicitly-defined or move assignment operator for a non-union class
15793 // X performs memberwise move assignment of its subobjects. The direct base
15794 // classes of X are assigned first, in the order of their declaration in the
15795 // base-specifier-list, and then the immediate non-static data members of X
15796 // are assigned, in the order in which they were declared in the class
15797 // definition.
15798
15799 // Issue a warning if our implicit move assignment operator will move
15800 // from a virtual base more than once.
15801 checkMoveAssignmentForRepeatedMove(S&: *this, Class: ClassDecl, CurrentLocation);
15802
15803 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
15804
15805 // The exception specification is needed because we are defining the
15806 // function.
15807 ResolveExceptionSpec(Loc: CurrentLocation,
15808 FPT: MoveAssignOperator->getType()->castAs<FunctionProtoType>());
15809
15810 // Add a context note for diagnostics produced after this point.
15811 Scope.addContextNote(UseLoc: CurrentLocation);
15812
15813 // The statements that form the synthesized function body.
15814 SmallVector<Stmt*, 8> Statements;
15815
15816 // The parameter for the "other" object, which we are move from.
15817 ParmVarDecl *Other = MoveAssignOperator->getNonObjectParameter(I: 0);
15818 QualType OtherRefType =
15819 Other->getType()->castAs<RValueReferenceType>()->getPointeeType();
15820
15821 // Our location for everything implicitly-generated.
15822 SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
15823 ? MoveAssignOperator->getEndLoc()
15824 : MoveAssignOperator->getLocation();
15825
15826 // Builds a reference to the "other" object.
15827 RefBuilder OtherRef(Other, OtherRefType);
15828 // Cast to rvalue.
15829 MoveCastBuilder MoveOther(OtherRef);
15830
15831 // Builds the function object parameter.
15832 std::optional<ThisBuilder> This;
15833 std::optional<DerefBuilder> DerefThis;
15834 std::optional<RefBuilder> ExplicitObject;
15835 QualType ObjectType;
15836 bool IsArrow = false;
15837 if (MoveAssignOperator->isExplicitObjectMemberFunction()) {
15838 ObjectType = MoveAssignOperator->getParamDecl(i: 0)->getType();
15839 if (ObjectType->isReferenceType())
15840 ObjectType = ObjectType->getPointeeType();
15841 ExplicitObject.emplace(args: MoveAssignOperator->getParamDecl(i: 0), args&: ObjectType);
15842 } else {
15843 ObjectType = getCurrentThisType();
15844 This.emplace();
15845 DerefThis.emplace(args&: *This);
15846 IsArrow = !getLangOpts().HLSL;
15847 }
15848 ExprBuilder &ObjectParameter =
15849 ExplicitObject ? *ExplicitObject : static_cast<ExprBuilder &>(*This);
15850
15851 // Assign base classes.
15852 bool Invalid = false;
15853 for (auto &Base : ClassDecl->bases()) {
15854 // C++11 [class.copy]p28:
15855 // It is unspecified whether subobjects representing virtual base classes
15856 // are assigned more than once by the implicitly-defined copy assignment
15857 // operator.
15858 // FIXME: Do not assign to a vbase that will be assigned by some other base
15859 // class. For a move-assignment, this can result in the vbase being moved
15860 // multiple times.
15861
15862 // Form the assignment:
15863 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
15864 QualType BaseType = Base.getType().getUnqualifiedType();
15865 if (!BaseType->isRecordType()) {
15866 Invalid = true;
15867 continue;
15868 }
15869
15870 CXXCastPath BasePath;
15871 BasePath.push_back(Elt: &Base);
15872
15873 // Construct the "from" expression, which is an implicit cast to the
15874 // appropriately-qualified base type.
15875 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
15876
15877 // Implicitly cast "this" to the appropriately-qualified base type.
15878 // Dereference "this".
15879 CastBuilder To(
15880 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15881 : static_cast<ExprBuilder &>(*DerefThis),
15882 Context.getQualifiedType(T: BaseType, Qs: ObjectType.getQualifiers()),
15883 VK_LValue, BasePath);
15884
15885 // Build the move.
15886 StmtResult Move = buildSingleCopyAssign(S&: *this, Loc, T: BaseType,
15887 To, From,
15888 /*CopyingBaseSubobject=*/true,
15889 /*Copying=*/false);
15890 if (Move.isInvalid()) {
15891 MoveAssignOperator->setInvalidDecl();
15892 return;
15893 }
15894
15895 // Success! Record the move.
15896 Statements.push_back(Elt: Move.getAs<Expr>());
15897 }
15898
15899 // A defaulted move assignment operator for a union copies the object
15900 // representation as if by a memcpy, the same way the defaulted union copy
15901 // constructor does. The memberwise loop below skips union members.
15902 if (ClassDecl->isUnion()) {
15903 ExprBuilder &To = ExplicitObject
15904 ? static_cast<ExprBuilder &>(*ExplicitObject)
15905 : static_cast<ExprBuilder &>(*DerefThis);
15906 // Copying the object representation is correct even for a union that is
15907 // not trivially copyable, so -Wnontrivial-memcall is a false positive
15908 // here. Ignoring warnings rather than casting the arguments to void*
15909 // keeps them typed, which preserves their address space.
15910 IgnoreAllWarningDiagRAII IgnoreWarnings(Diags);
15911 StmtResult Copy = buildMemcpyForAssignmentOp(
15912 S&: *this, Loc, T: Context.getCanonicalTagType(TD: ClassDecl), ToB: To, FromB: OtherRef);
15913 if (Copy.isInvalid()) {
15914 MoveAssignOperator->setInvalidDecl();
15915 return;
15916 }
15917 Statements.push_back(Elt: Copy.getAs<Stmt>());
15918 }
15919
15920 // Assign non-static members.
15921 for (auto *Field : ClassDecl->fields()) {
15922 // Union members are copied by the whole-object memcpy emitted above.
15923 if (Field->isUnnamedBitField() || Field->getParent()->isUnion())
15924 continue;
15925
15926 if (Field->isInvalidDecl()) {
15927 Invalid = true;
15928 continue;
15929 }
15930
15931 // Check for members of reference type; we can't move those.
15932 if (Field->getType()->isReferenceType()) {
15933 Diag(Loc: ClassDecl->getLocation(), DiagID: diag::err_uninitialized_member_for_assign)
15934 << Context.getCanonicalTagType(TD: ClassDecl) << 0
15935 << Field->getDeclName();
15936 Diag(Loc: Field->getLocation(), DiagID: diag::note_declared_at);
15937 Invalid = true;
15938 continue;
15939 }
15940
15941 // Check for members of const-qualified, non-class type.
15942 QualType BaseType = Context.getBaseElementType(QT: Field->getType());
15943 if (!BaseType->isRecordType() && BaseType.isConstQualified()) {
15944 Diag(Loc: ClassDecl->getLocation(), DiagID: diag::err_uninitialized_member_for_assign)
15945 << Context.getCanonicalTagType(TD: ClassDecl) << 1
15946 << Field->getDeclName();
15947 Diag(Loc: Field->getLocation(), DiagID: diag::note_declared_at);
15948 Invalid = true;
15949 continue;
15950 }
15951
15952 // Suppress assigning zero-width bitfields.
15953 if (Field->isZeroLengthBitField())
15954 continue;
15955
15956 QualType FieldType = Field->getType().getNonReferenceType();
15957 if (FieldType->isIncompleteArrayType()) {
15958 assert(ClassDecl->hasFlexibleArrayMember() &&
15959 "Incomplete array type is not valid");
15960 continue;
15961 }
15962
15963 // Build references to the field in the object we're copying from and to.
15964 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
15965 LookupMemberName);
15966 MemberLookup.addDecl(D: Field);
15967 MemberLookup.resolveKind();
15968 MemberBuilder From(MoveOther, OtherRefType,
15969 /*IsArrow=*/false, MemberLookup);
15970 MemberBuilder To(ObjectParameter, ObjectType, IsArrow, MemberLookup);
15971
15972 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
15973 "Member reference with rvalue base must be rvalue except for reference "
15974 "members, which aren't allowed for move assignment.");
15975
15976 // Build the move of this field.
15977 StmtResult Move = buildSingleCopyAssign(S&: *this, Loc, T: FieldType,
15978 To, From,
15979 /*CopyingBaseSubobject=*/false,
15980 /*Copying=*/false);
15981 if (Move.isInvalid()) {
15982 MoveAssignOperator->setInvalidDecl();
15983 return;
15984 }
15985
15986 // Success! Record the copy.
15987 Statements.push_back(Elt: Move.getAs<Stmt>());
15988 }
15989
15990 if (!Invalid) {
15991 // Add a "return *this;"
15992 Expr *ThisExpr =
15993 (ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15994 : LangOpts.HLSL ? static_cast<ExprBuilder &>(*This)
15995 : static_cast<ExprBuilder &>(*DerefThis))
15996 .build(S&: *this, Loc);
15997
15998 StmtResult Return = BuildReturnStmt(ReturnLoc: Loc, RetValExp: ThisExpr);
15999 if (Return.isInvalid())
16000 Invalid = true;
16001 else
16002 Statements.push_back(Elt: Return.getAs<Stmt>());
16003 }
16004
16005 if (Invalid) {
16006 MoveAssignOperator->setInvalidDecl();
16007 return;
16008 }
16009
16010 StmtResult Body;
16011 {
16012 CompoundScopeRAII CompoundScope(*this);
16013 Body = ActOnCompoundStmt(L: Loc, R: Loc, Elts: Statements,
16014 /*isStmtExpr=*/false);
16015 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
16016 }
16017 MoveAssignOperator->setBody(Body.getAs<Stmt>());
16018 MoveAssignOperator->markUsed(C&: Context);
16019
16020 if (ASTMutationListener *L = getASTMutationListener()) {
16021 L->CompletedImplicitDefinition(D: MoveAssignOperator);
16022 }
16023}
16024
16025CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
16026 CXXRecordDecl *ClassDecl) {
16027 // C++ [class.copy]p4:
16028 // If the class definition does not explicitly declare a copy
16029 // constructor, one is declared implicitly.
16030 assert(ClassDecl->needsImplicitCopyConstructor());
16031
16032 DeclaringSpecialMember DSM(*this, ClassDecl,
16033 CXXSpecialMemberKind::CopyConstructor);
16034 if (DSM.isAlreadyBeingDeclared())
16035 return nullptr;
16036
16037 QualType ClassType = Context.getTagType(Keyword: ElaboratedTypeKeyword::None,
16038 /*Qualifier=*/std::nullopt, TD: ClassDecl,
16039 /*OwnsTag=*/false);
16040 QualType ArgType = ClassType;
16041 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
16042 if (Const)
16043 ArgType = ArgType.withConst();
16044
16045 LangAS AS = getDefaultCXXMethodAddrSpace();
16046 if (AS != LangAS::Default)
16047 ArgType = Context.getAddrSpaceQualType(T: ArgType, AddressSpace: AS);
16048
16049 ArgType = Context.getLValueReferenceType(T: ArgType);
16050
16051 bool Constexpr = defaultedSpecialMemberIsConstexpr(
16052 S&: *this, ClassDecl, CSM: CXXSpecialMemberKind::CopyConstructor, ConstArg: Const);
16053
16054 DeclarationName Name
16055 = Context.DeclarationNames.getCXXConstructorName(
16056 Ty: Context.getCanonicalType(T: ClassType));
16057 SourceLocation ClassLoc = ClassDecl->getLocation();
16058 DeclarationNameInfo NameInfo(Name, ClassLoc);
16059
16060 // An implicitly-declared copy constructor is an inline public
16061 // member of its class.
16062 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
16063 C&: Context, RD: ClassDecl, StartLoc: ClassLoc, NameInfo, T: QualType(), /*TInfo=*/nullptr,
16064 ES: ExplicitSpecifier(), UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
16065 /*isInline=*/true,
16066 /*isImplicitlyDeclared=*/true,
16067 ConstexprKind: Constexpr ? ConstexprSpecKind::Constexpr
16068 : ConstexprSpecKind::Unspecified);
16069 CopyConstructor->setAccess(AS_public);
16070 CopyConstructor->setDefaulted();
16071
16072 setupImplicitSpecialMemberType(SpecialMem: CopyConstructor, ResultTy: Context.VoidTy, Args: ArgType);
16073
16074 if (getLangOpts().CUDA)
16075 CUDA().inferTargetForImplicitSpecialMember(
16076 ClassDecl, CSM: CXXSpecialMemberKind::CopyConstructor, MemberDecl: CopyConstructor,
16077 /* ConstRHS */ Const,
16078 /* Diagnose */ false);
16079
16080 // During template instantiation of special member functions we need a
16081 // reliable TypeSourceInfo for the parameter types in order to allow functions
16082 // to be substituted.
16083 TypeSourceInfo *TSI = nullptr;
16084 if (inTemplateInstantiation() && ClassDecl->isLambda())
16085 TSI = Context.getTrivialTypeSourceInfo(T: ArgType);
16086
16087 // Add the parameter to the constructor.
16088 ParmVarDecl *FromParam =
16089 ParmVarDecl::Create(C&: Context, DC: CopyConstructor, StartLoc: ClassLoc, IdLoc: ClassLoc,
16090 /*IdentifierInfo=*/Id: nullptr, T: ArgType,
16091 /*TInfo=*/TSI, S: SC_None, DefArg: nullptr);
16092 CopyConstructor->setParams(FromParam);
16093
16094 CopyConstructor->setTrivial(
16095 ClassDecl->needsOverloadResolutionForCopyConstructor()
16096 ? SpecialMemberIsTrivial(MD: CopyConstructor,
16097 CSM: CXXSpecialMemberKind::CopyConstructor)
16098 : ClassDecl->hasTrivialCopyConstructor());
16099
16100 CopyConstructor->setTrivialForCall(
16101 ClassDecl->hasAttr<TrivialABIAttr>() ||
16102 (ClassDecl->needsOverloadResolutionForCopyConstructor()
16103 ? SpecialMemberIsTrivial(MD: CopyConstructor,
16104 CSM: CXXSpecialMemberKind::CopyConstructor,
16105 TAH: TrivialABIHandling::ConsiderTrivialABI)
16106 : ClassDecl->hasTrivialCopyConstructorForCall()));
16107
16108 // Note that we have declared this constructor.
16109 ++getASTContext().NumImplicitCopyConstructorsDeclared;
16110
16111 Scope *S = getScopeForContext(Ctx: ClassDecl);
16112 CheckImplicitSpecialMemberDeclaration(S, FD: CopyConstructor);
16113
16114 if (ShouldDeleteSpecialMember(MD: CopyConstructor,
16115 CSM: CXXSpecialMemberKind::CopyConstructor)) {
16116 ClassDecl->setImplicitCopyConstructorIsDeleted();
16117 SetDeclDeleted(dcl: CopyConstructor, DelLoc: ClassLoc);
16118 }
16119
16120 if (S)
16121 PushOnScopeChains(D: CopyConstructor, S, AddToContext: false);
16122 ClassDecl->addDecl(D: CopyConstructor);
16123
16124 return CopyConstructor;
16125}
16126
16127void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
16128 CXXConstructorDecl *CopyConstructor) {
16129 DefaultedFunctionFPFeaturesRAII RestoreFP(*this, CopyConstructor);
16130 assert((CopyConstructor->isDefaulted() &&
16131 CopyConstructor->isCopyConstructor() &&
16132 !CopyConstructor->doesThisDeclarationHaveABody() &&
16133 !CopyConstructor->isDeleted()) &&
16134 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
16135 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
16136 return;
16137
16138 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
16139 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
16140
16141 SynthesizedFunctionScope Scope(*this, CopyConstructor);
16142
16143 // The exception specification is needed because we are defining the
16144 // function.
16145 ResolveExceptionSpec(Loc: CurrentLocation,
16146 FPT: CopyConstructor->getType()->castAs<FunctionProtoType>());
16147 MarkVTableUsed(Loc: CurrentLocation, Class: ClassDecl);
16148
16149 // Add a context note for diagnostics produced after this point.
16150 Scope.addContextNote(UseLoc: CurrentLocation);
16151
16152 // C++11 [class.copy]p7:
16153 // The [definition of an implicitly declared copy constructor] is
16154 // deprecated if the class has a user-declared copy assignment operator
16155 // or a user-declared destructor.
16156 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
16157 diagnoseDeprecatedCopyOperation(S&: *this, CopyOp: CopyConstructor);
16158
16159 if (SetCtorInitializers(Constructor: CopyConstructor, /*AnyErrors=*/false)) {
16160 CopyConstructor->setInvalidDecl();
16161 } else {
16162 SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
16163 ? CopyConstructor->getEndLoc()
16164 : CopyConstructor->getLocation();
16165 Sema::CompoundScopeRAII CompoundScope(*this);
16166 CopyConstructor->setBody(
16167 ActOnCompoundStmt(L: Loc, R: Loc, Elts: {}, /*isStmtExpr=*/false).getAs<Stmt>());
16168 CopyConstructor->markUsed(C&: Context);
16169 }
16170
16171 if (ASTMutationListener *L = getASTMutationListener()) {
16172 L->CompletedImplicitDefinition(D: CopyConstructor);
16173 }
16174}
16175
16176CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
16177 CXXRecordDecl *ClassDecl) {
16178 assert(ClassDecl->needsImplicitMoveConstructor());
16179
16180 DeclaringSpecialMember DSM(*this, ClassDecl,
16181 CXXSpecialMemberKind::MoveConstructor);
16182 if (DSM.isAlreadyBeingDeclared())
16183 return nullptr;
16184
16185 QualType ClassType = Context.getTagType(Keyword: ElaboratedTypeKeyword::None,
16186 /*Qualifier=*/std::nullopt, TD: ClassDecl,
16187 /*OwnsTag=*/false);
16188
16189 QualType ArgType = ClassType;
16190 LangAS AS = getDefaultCXXMethodAddrSpace();
16191 if (AS != LangAS::Default)
16192 ArgType = Context.getAddrSpaceQualType(T: ClassType, AddressSpace: AS);
16193 ArgType = Context.getRValueReferenceType(T: ArgType);
16194
16195 bool Constexpr = defaultedSpecialMemberIsConstexpr(
16196 S&: *this, ClassDecl, CSM: CXXSpecialMemberKind::MoveConstructor, ConstArg: false);
16197
16198 DeclarationName Name
16199 = Context.DeclarationNames.getCXXConstructorName(
16200 Ty: Context.getCanonicalType(T: ClassType));
16201 SourceLocation ClassLoc = ClassDecl->getLocation();
16202 DeclarationNameInfo NameInfo(Name, ClassLoc);
16203
16204 // C++11 [class.copy]p11:
16205 // An implicitly-declared copy/move constructor is an inline public
16206 // member of its class.
16207 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
16208 C&: Context, RD: ClassDecl, StartLoc: ClassLoc, NameInfo, T: QualType(), /*TInfo=*/nullptr,
16209 ES: ExplicitSpecifier(), UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
16210 /*isInline=*/true,
16211 /*isImplicitlyDeclared=*/true,
16212 ConstexprKind: Constexpr ? ConstexprSpecKind::Constexpr
16213 : ConstexprSpecKind::Unspecified);
16214 MoveConstructor->setAccess(AS_public);
16215 MoveConstructor->setDefaulted();
16216
16217 setupImplicitSpecialMemberType(SpecialMem: MoveConstructor, ResultTy: Context.VoidTy, Args: ArgType);
16218
16219 if (getLangOpts().CUDA)
16220 CUDA().inferTargetForImplicitSpecialMember(
16221 ClassDecl, CSM: CXXSpecialMemberKind::MoveConstructor, MemberDecl: MoveConstructor,
16222 /* ConstRHS */ false,
16223 /* Diagnose */ false);
16224
16225 // Add the parameter to the constructor.
16226 ParmVarDecl *FromParam = ParmVarDecl::Create(C&: Context, DC: MoveConstructor,
16227 StartLoc: ClassLoc, IdLoc: ClassLoc,
16228 /*IdentifierInfo=*/Id: nullptr,
16229 T: ArgType, /*TInfo=*/nullptr,
16230 S: SC_None, DefArg: nullptr);
16231 MoveConstructor->setParams(FromParam);
16232
16233 MoveConstructor->setTrivial(
16234 ClassDecl->needsOverloadResolutionForMoveConstructor()
16235 ? SpecialMemberIsTrivial(MD: MoveConstructor,
16236 CSM: CXXSpecialMemberKind::MoveConstructor)
16237 : ClassDecl->hasTrivialMoveConstructor());
16238
16239 MoveConstructor->setTrivialForCall(
16240 ClassDecl->hasAttr<TrivialABIAttr>() ||
16241 (ClassDecl->needsOverloadResolutionForMoveConstructor()
16242 ? SpecialMemberIsTrivial(MD: MoveConstructor,
16243 CSM: CXXSpecialMemberKind::MoveConstructor,
16244 TAH: TrivialABIHandling::ConsiderTrivialABI)
16245 : ClassDecl->hasTrivialMoveConstructorForCall()));
16246
16247 // Note that we have declared this constructor.
16248 ++getASTContext().NumImplicitMoveConstructorsDeclared;
16249
16250 Scope *S = getScopeForContext(Ctx: ClassDecl);
16251 CheckImplicitSpecialMemberDeclaration(S, FD: MoveConstructor);
16252
16253 if (ShouldDeleteSpecialMember(MD: MoveConstructor,
16254 CSM: CXXSpecialMemberKind::MoveConstructor)) {
16255 ClassDecl->setImplicitMoveConstructorIsDeleted();
16256 SetDeclDeleted(dcl: MoveConstructor, DelLoc: ClassLoc);
16257 }
16258
16259 if (S)
16260 PushOnScopeChains(D: MoveConstructor, S, AddToContext: false);
16261 ClassDecl->addDecl(D: MoveConstructor);
16262
16263 return MoveConstructor;
16264}
16265
16266void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
16267 CXXConstructorDecl *MoveConstructor) {
16268 DefaultedFunctionFPFeaturesRAII RestoreFP(*this, MoveConstructor);
16269 assert((MoveConstructor->isDefaulted() &&
16270 MoveConstructor->isMoveConstructor() &&
16271 !MoveConstructor->doesThisDeclarationHaveABody() &&
16272 !MoveConstructor->isDeleted()) &&
16273 "DefineImplicitMoveConstructor - call it for implicit move ctor");
16274 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
16275 return;
16276
16277 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
16278 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
16279
16280 SynthesizedFunctionScope Scope(*this, MoveConstructor);
16281
16282 // The exception specification is needed because we are defining the
16283 // function.
16284 ResolveExceptionSpec(Loc: CurrentLocation,
16285 FPT: MoveConstructor->getType()->castAs<FunctionProtoType>());
16286 MarkVTableUsed(Loc: CurrentLocation, Class: ClassDecl);
16287
16288 // Add a context note for diagnostics produced after this point.
16289 Scope.addContextNote(UseLoc: CurrentLocation);
16290
16291 if (SetCtorInitializers(Constructor: MoveConstructor, /*AnyErrors=*/false)) {
16292 MoveConstructor->setInvalidDecl();
16293 } else {
16294 SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
16295 ? MoveConstructor->getEndLoc()
16296 : MoveConstructor->getLocation();
16297 Sema::CompoundScopeRAII CompoundScope(*this);
16298 MoveConstructor->setBody(
16299 ActOnCompoundStmt(L: Loc, R: Loc, Elts: {}, /*isStmtExpr=*/false).getAs<Stmt>());
16300 MoveConstructor->markUsed(C&: Context);
16301 }
16302
16303 if (ASTMutationListener *L = getASTMutationListener()) {
16304 L->CompletedImplicitDefinition(D: MoveConstructor);
16305 }
16306}
16307
16308bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
16309 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(Val: FD);
16310}
16311
16312void Sema::DefineImplicitLambdaToFunctionPointerConversion(
16313 SourceLocation CurrentLocation,
16314 CXXConversionDecl *Conv) {
16315 SynthesizedFunctionScope Scope(*this, Conv);
16316 assert(!Conv->getReturnType()->isUndeducedType());
16317
16318 QualType ConvRT = Conv->getType()->castAs<FunctionType>()->getReturnType();
16319 CallingConv CC =
16320 ConvRT->getPointeeType()->castAs<FunctionType>()->getCallConv();
16321
16322 CXXRecordDecl *Lambda = Conv->getParent();
16323 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
16324 FunctionDecl *Invoker =
16325 CallOp->hasCXXExplicitFunctionObjectParameter() || CallOp->isStatic()
16326 ? CallOp
16327 : Lambda->getLambdaStaticInvoker(CC);
16328
16329 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
16330 CallOp = InstantiateFunctionDeclaration(
16331 FTD: CallOp->getDescribedFunctionTemplate(), Args: TemplateArgs, Loc: CurrentLocation);
16332 if (!CallOp)
16333 return;
16334
16335 if (CallOp != Invoker) {
16336 Invoker = InstantiateFunctionDeclaration(
16337 FTD: Invoker->getDescribedFunctionTemplate(), Args: TemplateArgs,
16338 Loc: CurrentLocation);
16339 if (!Invoker)
16340 return;
16341 }
16342 }
16343
16344 if (CallOp->isInvalidDecl())
16345 return;
16346
16347 // Mark the call operator referenced (and add to pending instantiations
16348 // if necessary).
16349 // For both the conversion and static-invoker template specializations
16350 // we construct their body's in this function, so no need to add them
16351 // to the PendingInstantiations.
16352 MarkFunctionReferenced(Loc: CurrentLocation, Func: CallOp);
16353
16354 if (Invoker != CallOp) {
16355 // Fill in the __invoke function with a dummy implementation. IR generation
16356 // will fill in the actual details. Update its type in case it contained
16357 // an 'auto'.
16358 Invoker->markUsed(C&: Context);
16359 Invoker->setReferenced();
16360 Invoker->setType(Conv->getReturnType()->getPointeeType());
16361 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
16362 }
16363
16364 // Construct the body of the conversion function { return __invoke; }.
16365 Expr *FunctionRef = BuildDeclRefExpr(D: Invoker, Ty: Invoker->getType(), VK: VK_LValue,
16366 Loc: Conv->getLocation());
16367 assert(FunctionRef && "Can't refer to __invoke function?");
16368 Stmt *Return = BuildReturnStmt(ReturnLoc: Conv->getLocation(), RetValExp: FunctionRef).get();
16369 Conv->setBody(CompoundStmt::Create(C: Context, Stmts: Return, FPFeatures: FPOptionsOverride(),
16370 LB: Conv->getLocation(), RB: Conv->getLocation()));
16371 Conv->markUsed(C&: Context);
16372 Conv->setReferenced();
16373
16374 if (ASTMutationListener *L = getASTMutationListener()) {
16375 L->CompletedImplicitDefinition(D: Conv);
16376 if (Invoker != CallOp)
16377 L->CompletedImplicitDefinition(D: Invoker);
16378 }
16379}
16380
16381void Sema::DefineImplicitLambdaToBlockPointerConversion(
16382 SourceLocation CurrentLocation, CXXConversionDecl *Conv) {
16383 assert(!Conv->getParent()->isGenericLambda());
16384
16385 SynthesizedFunctionScope Scope(*this, Conv);
16386
16387 // Copy-initialize the lambda object as needed to capture it.
16388 Expr *This = ActOnCXXThis(Loc: CurrentLocation).get();
16389 Expr *DerefThis =CreateBuiltinUnaryOp(OpLoc: CurrentLocation, Opc: UO_Deref, InputExpr: This).get();
16390
16391 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
16392 ConvLocation: Conv->getLocation(),
16393 Conv, Src: DerefThis);
16394
16395 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
16396 // behavior. Note that only the general conversion function does this
16397 // (since it's unusable otherwise); in the case where we inline the
16398 // block literal, it has block literal lifetime semantics.
16399 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
16400 BuildBlock = ImplicitCastExpr::Create(
16401 Context, T: BuildBlock.get()->getType(), Kind: CK_CopyAndAutoreleaseBlockObject,
16402 Operand: BuildBlock.get(), BasePath: nullptr, Cat: VK_PRValue, FPO: FPOptionsOverride());
16403
16404 if (BuildBlock.isInvalid()) {
16405 Diag(Loc: CurrentLocation, DiagID: diag::note_lambda_to_block_conv);
16406 Conv->setInvalidDecl();
16407 return;
16408 }
16409
16410 // Create the return statement that returns the block from the conversion
16411 // function.
16412 StmtResult Return = BuildReturnStmt(ReturnLoc: Conv->getLocation(), RetValExp: BuildBlock.get());
16413 if (Return.isInvalid()) {
16414 Diag(Loc: CurrentLocation, DiagID: diag::note_lambda_to_block_conv);
16415 Conv->setInvalidDecl();
16416 return;
16417 }
16418
16419 // Set the body of the conversion function.
16420 Stmt *ReturnS = Return.get();
16421 Conv->setBody(CompoundStmt::Create(C: Context, Stmts: ReturnS, FPFeatures: FPOptionsOverride(),
16422 LB: Conv->getLocation(), RB: Conv->getLocation()));
16423 Conv->markUsed(C&: Context);
16424
16425 // We're done; notify the mutation listener, if any.
16426 if (ASTMutationListener *L = getASTMutationListener()) {
16427 L->CompletedImplicitDefinition(D: Conv);
16428 }
16429}
16430
16431/// Determine whether the given list arguments contains exactly one
16432/// "real" (non-default) argument.
16433static bool hasOneRealArgument(MultiExprArg Args) {
16434 switch (Args.size()) {
16435 case 0:
16436 return false;
16437
16438 default:
16439 if (!Args[1]->isDefaultArgument())
16440 return false;
16441
16442 [[fallthrough]];
16443 case 1:
16444 return !Args[0]->isDefaultArgument();
16445 }
16446
16447 return false;
16448}
16449
16450ExprResult Sema::BuildCXXConstructExpr(
16451 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
16452 CXXConstructorDecl *Constructor, MultiExprArg ExprArgs,
16453 bool HadMultipleCandidates, bool IsListInitialization,
16454 bool IsStdInitListInitialization, bool RequiresZeroInit,
16455 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16456 bool Elidable = false;
16457
16458 // C++0x [class.copy]p34:
16459 // When certain criteria are met, an implementation is allowed to
16460 // omit the copy/move construction of a class object, even if the
16461 // copy/move constructor and/or destructor for the object have
16462 // side effects. [...]
16463 // - when a temporary class object that has not been bound to a
16464 // reference (12.2) would be copied/moved to a class object
16465 // with the same cv-unqualified type, the copy/move operation
16466 // can be omitted by constructing the temporary object
16467 // directly into the target of the omitted copy/move
16468 if (ConstructKind == CXXConstructionKind::Complete && Constructor &&
16469 // FIXME: Converting constructors should also be accepted.
16470 // But to fix this, the logic that digs down into a CXXConstructExpr
16471 // to find the source object needs to handle it.
16472 // Right now it assumes the source object is passed directly as the
16473 // first argument.
16474 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(Args: ExprArgs)) {
16475 Expr *SubExpr = ExprArgs[0];
16476 // FIXME: Per above, this is also incorrect if we want to accept
16477 // converting constructors, as isTemporaryObject will
16478 // reject temporaries with different type from the
16479 // CXXRecord itself.
16480 Elidable = SubExpr->isTemporaryObject(
16481 Ctx&: Context, TempTy: cast<CXXRecordDecl>(Val: FoundDecl->getDeclContext()));
16482 }
16483
16484 return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
16485 FoundDecl, Constructor,
16486 Elidable, Exprs: ExprArgs, HadMultipleCandidates,
16487 IsListInitialization,
16488 IsStdInitListInitialization, RequiresZeroInit,
16489 ConstructKind, ParenRange);
16490}
16491
16492ExprResult Sema::BuildCXXConstructExpr(
16493 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
16494 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg ExprArgs,
16495 bool HadMultipleCandidates, bool IsListInitialization,
16496 bool IsStdInitListInitialization, bool RequiresZeroInit,
16497 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16498 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(Val: FoundDecl)) {
16499 Constructor = findInheritingConstructor(Loc: ConstructLoc, BaseCtor: Constructor, Shadow);
16500 // The only way to get here is if we did overload resolution to find the
16501 // shadow decl, so we don't need to worry about re-checking the trailing
16502 // requires clause.
16503 if (DiagnoseUseOfOverloadedDecl(D: Constructor, Loc: ConstructLoc))
16504 return ExprError();
16505 }
16506
16507 return BuildCXXConstructExpr(
16508 ConstructLoc, DeclInitType, Constructor, Elidable, Exprs: ExprArgs,
16509 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
16510 RequiresZeroInit, ConstructKind, ParenRange);
16511}
16512
16513/// BuildCXXConstructExpr - Creates a complete call to a constructor,
16514/// including handling of its default argument expressions.
16515ExprResult Sema::BuildCXXConstructExpr(
16516 SourceLocation ConstructLoc, QualType DeclInitType,
16517 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg ExprArgs,
16518 bool HadMultipleCandidates, bool IsListInitialization,
16519 bool IsStdInitListInitialization, bool RequiresZeroInit,
16520 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16521 assert(declaresSameEntity(
16522 Constructor->getParent(),
16523 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
16524 "given constructor for wrong type");
16525 MarkFunctionReferenced(Loc: ConstructLoc, Func: Constructor);
16526 if (getLangOpts().CUDA && !CUDA().CheckCall(Loc: ConstructLoc, Callee: Constructor))
16527 return ExprError();
16528
16529 return CheckForImmediateInvocation(
16530 E: CXXConstructExpr::Create(
16531 Ctx: Context, Ty: DeclInitType, Loc: ConstructLoc, Ctor: Constructor, Elidable, Args: ExprArgs,
16532 HadMultipleCandidates, ListInitialization: IsListInitialization,
16533 StdInitListInitialization: IsStdInitListInitialization, ZeroInitialization: RequiresZeroInit,
16534 ConstructKind: static_cast<CXXConstructionKind>(ConstructKind), ParenOrBraceRange: ParenRange),
16535 Decl: Constructor);
16536}
16537
16538void Sema::FinalizeVarWithDestructor(VarDecl *VD, CXXRecordDecl *ClassDecl) {
16539 if (VD->isInvalidDecl()) return;
16540 // If initializing the variable failed, don't also diagnose problems with
16541 // the destructor, they're likely related.
16542 if (VD->getInit() && VD->getInit()->containsErrors())
16543 return;
16544
16545 ClassDecl = ClassDecl->getDefinitionOrSelf();
16546 if (ClassDecl->isInvalidDecl()) return;
16547 if (ClassDecl->hasIrrelevantDestructor()) return;
16548 if (ClassDecl->isDependentContext()) return;
16549
16550 if (VD->isNoDestroy(getASTContext()))
16551 return;
16552
16553 CXXDestructorDecl *Destructor = LookupDestructor(Class: ClassDecl);
16554 // The result of `LookupDestructor` might be nullptr if the destructor is
16555 // invalid, in which case it is marked as `IneligibleOrNotSelected` and
16556 // will not be selected by `CXXRecordDecl::getDestructor()`.
16557 if (!Destructor)
16558 return;
16559 // If this is an array, we'll require the destructor during initialization, so
16560 // we can skip over this. We still want to emit exit-time destructor warnings
16561 // though.
16562 if (!VD->getType()->isArrayType()) {
16563 MarkFunctionReferenced(Loc: VD->getLocation(), Func: Destructor);
16564 CheckDestructorAccess(Loc: VD->getLocation(), Dtor: Destructor,
16565 PDiag: PDiag(DiagID: diag::err_access_dtor_var)
16566 << VD->getDeclName() << VD->getType());
16567 DiagnoseUseOfDecl(D: Destructor, Locs: VD->getLocation());
16568 }
16569
16570 if (Destructor->isTrivial()) return;
16571
16572 // If the destructor is constexpr, check whether the variable has constant
16573 // destruction now.
16574 if (Destructor->isConstexpr()) {
16575 bool HasConstantInit = false;
16576 if (VD->getInit() && !VD->getInit()->isValueDependent())
16577 HasConstantInit = VD->evaluateValue();
16578 SmallVector<PartialDiagnosticAt, 8> Notes;
16579 if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() &&
16580 HasConstantInit) {
16581 Diag(Loc: VD->getLocation(),
16582 DiagID: diag::err_constexpr_var_requires_const_destruction) << VD;
16583 for (const PartialDiagnosticAt &Note : Notes)
16584 Diag(Loc: Note.first, PD: Note.second);
16585 }
16586 }
16587
16588 if (!VD->hasGlobalStorage() || !VD->needsDestruction(Ctx: Context))
16589 return;
16590
16591 // Emit warning for non-trivial dtor in global scope (a real global,
16592 // class-static, function-static).
16593 if (!VD->hasAttr<AlwaysDestroyAttr>())
16594 Diag(Loc: VD->getLocation(), DiagID: diag::warn_exit_time_destructor);
16595
16596 // TODO: this should be re-enabled for static locals by !CXAAtExit
16597 if (!VD->isStaticLocal())
16598 Diag(Loc: VD->getLocation(), DiagID: diag::warn_global_destructor);
16599}
16600
16601bool Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
16602 QualType DeclInitType, MultiExprArg ArgsPtr,
16603 SourceLocation Loc,
16604 SmallVectorImpl<Expr *> &ConvertedArgs,
16605 bool AllowExplicit,
16606 bool IsListInitialization) {
16607 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
16608 unsigned NumArgs = ArgsPtr.size();
16609 Expr **Args = ArgsPtr.data();
16610
16611 const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>();
16612 unsigned NumParams = Proto->getNumParams();
16613
16614 // If too few arguments are available, we'll fill in the rest with defaults.
16615 if (NumArgs < NumParams)
16616 ConvertedArgs.reserve(N: NumParams);
16617 else
16618 ConvertedArgs.reserve(N: NumArgs);
16619
16620 VariadicCallType CallType = Proto->isVariadic()
16621 ? VariadicCallType::Constructor
16622 : VariadicCallType::DoesNotApply;
16623 SmallVector<Expr *, 8> AllArgs;
16624 bool Invalid = GatherArgumentsForCall(
16625 CallLoc: Loc, FDecl: Constructor, Proto, FirstParam: 0, Args: llvm::ArrayRef(Args, NumArgs), AllArgs,
16626 CallType, AllowExplicit, IsListInitialization);
16627 ConvertedArgs.append(in_start: AllArgs.begin(), in_end: AllArgs.end());
16628
16629 DiagnoseSentinelCalls(D: Constructor, Loc, Args: AllArgs);
16630
16631 CheckConstructorCall(FDecl: Constructor, ThisType: DeclInitType, Args: llvm::ArrayRef(AllArgs),
16632 Proto, Loc);
16633
16634 return Invalid;
16635}
16636
16637TypeAwareAllocationMode Sema::ShouldUseTypeAwareOperatorNewOrDelete() const {
16638 bool SeenTypedOperators = Context.hasSeenTypeAwareOperatorNewOrDelete();
16639 return typeAwareAllocationModeFromBool(IsTypeAwareAllocation: SeenTypedOperators);
16640}
16641
16642FunctionDecl *
16643Sema::BuildTypeAwareUsualDelete(FunctionTemplateDecl *FnTemplateDecl,
16644 QualType DeallocType, SourceLocation Loc) {
16645 if (DeallocType.isNull())
16646 return nullptr;
16647
16648 FunctionDecl *FnDecl = FnTemplateDecl->getTemplatedDecl();
16649 if (!FnDecl->isTypeAwareOperatorNewOrDelete())
16650 return nullptr;
16651
16652 if (FnDecl->isVariadic())
16653 return nullptr;
16654
16655 unsigned NumParams = FnDecl->getNumParams();
16656 constexpr unsigned RequiredParameterCount =
16657 FunctionDecl::RequiredTypeAwareDeleteParameterCount;
16658 // A usual deallocation function has no placement parameters
16659 if (NumParams != RequiredParameterCount)
16660 return nullptr;
16661
16662 // A type aware allocation is only usual if the only dependent parameter is
16663 // the first parameter.
16664 if (llvm::any_of(Range: FnDecl->parameters().drop_front(),
16665 P: [](const ParmVarDecl *ParamDecl) {
16666 return ParamDecl->getType()->isDependentType();
16667 }))
16668 return nullptr;
16669
16670 QualType SpecializedTypeIdentity = tryBuildStdTypeIdentity(Type: DeallocType, Loc);
16671 if (SpecializedTypeIdentity.isNull())
16672 return nullptr;
16673
16674 SmallVector<QualType, RequiredParameterCount> ArgTypes;
16675 ArgTypes.reserve(N: NumParams);
16676
16677 // The first parameter to a type aware operator delete is by definition the
16678 // type-identity argument, so we explicitly set this to the target
16679 // type-identity type, the remaining usual parameters should then simply match
16680 // the type declared in the function template.
16681 ArgTypes.push_back(Elt: SpecializedTypeIdentity);
16682 for (unsigned ParamIdx = 1; ParamIdx < RequiredParameterCount; ++ParamIdx)
16683 ArgTypes.push_back(Elt: FnDecl->getParamDecl(i: ParamIdx)->getType());
16684
16685 FunctionProtoType::ExtProtoInfo EPI;
16686 QualType ExpectedFunctionType =
16687 Context.getFunctionType(ResultTy: Context.VoidTy, Args: ArgTypes, EPI);
16688 sema::TemplateDeductionInfo Info(Loc);
16689 FunctionDecl *Result;
16690 if (DeduceTemplateArguments(FunctionTemplate: FnTemplateDecl, ExplicitTemplateArgs: nullptr, ArgFunctionType: ExpectedFunctionType,
16691 Specialization&: Result, Info) != TemplateDeductionResult::Success)
16692 return nullptr;
16693 return Result;
16694}
16695
16696static inline bool
16697CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
16698 const FunctionDecl *FnDecl) {
16699 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
16700 if (isa<NamespaceDecl>(Val: DC)) {
16701 return SemaRef.Diag(Loc: FnDecl->getLocation(),
16702 DiagID: diag::err_operator_new_delete_declared_in_namespace)
16703 << FnDecl->getDeclName();
16704 }
16705
16706 if (isa<TranslationUnitDecl>(Val: DC) &&
16707 FnDecl->getStorageClass() == SC_Static) {
16708 return SemaRef.Diag(Loc: FnDecl->getLocation(),
16709 DiagID: diag::err_operator_new_delete_declared_static)
16710 << FnDecl->getDeclName();
16711 }
16712
16713 return false;
16714}
16715
16716static CanQualType RemoveAddressSpaceFromPtr(Sema &SemaRef,
16717 const PointerType *PtrTy) {
16718 auto &Ctx = SemaRef.Context;
16719 Qualifiers PtrQuals = PtrTy->getPointeeType().getQualifiers();
16720 PtrQuals.removeAddressSpace();
16721 return Ctx.getPointerType(T: Ctx.getCanonicalType(T: Ctx.getQualifiedType(
16722 T: PtrTy->getPointeeType().getUnqualifiedType(), Qs: PtrQuals)));
16723}
16724
16725enum class AllocationOperatorKind { New, Delete };
16726
16727static bool IsPotentiallyTypeAwareOperatorNewOrDelete(Sema &SemaRef,
16728 const FunctionDecl *FD,
16729 bool *WasMalformed) {
16730 const Decl *MalformedDecl = nullptr;
16731 if (FD->getNumParams() > 0 &&
16732 SemaRef.isStdTypeIdentity(Ty: FD->getParamDecl(i: 0)->getType(),
16733 /*TypeArgument=*/Element: nullptr, MalformedDecl: &MalformedDecl))
16734 return true;
16735
16736 if (!MalformedDecl)
16737 return false;
16738
16739 if (WasMalformed)
16740 *WasMalformed = true;
16741
16742 return true;
16743}
16744
16745static bool isDestroyingDeleteT(QualType Type) {
16746 auto *RD = Type->getAsCXXRecordDecl();
16747 return RD && RD->isInStdNamespace() && RD->getIdentifier() &&
16748 RD->getIdentifier()->isStr(Str: "destroying_delete_t");
16749}
16750
16751static bool IsPotentiallyDestroyingOperatorDelete(Sema &SemaRef,
16752 const FunctionDecl *FD) {
16753 // C++ P0722:
16754 // Within a class C, a single object deallocation function with signature
16755 // (T, std::destroying_delete_t, <more params>)
16756 // is a destroying operator delete.
16757 bool IsPotentiallyTypeAware = IsPotentiallyTypeAwareOperatorNewOrDelete(
16758 SemaRef, FD, /*WasMalformed=*/nullptr);
16759 unsigned DestroyingDeleteIdx = IsPotentiallyTypeAware + /* address */ 1;
16760 return isa<CXXMethodDecl>(Val: FD) && FD->getOverloadedOperator() == OO_Delete &&
16761 FD->getNumParams() > DestroyingDeleteIdx &&
16762 isDestroyingDeleteT(Type: FD->getParamDecl(i: DestroyingDeleteIdx)->getType());
16763}
16764
16765static inline bool CheckOperatorNewDeleteTypes(
16766 Sema &SemaRef, FunctionDecl *FnDecl, AllocationOperatorKind OperatorKind,
16767 CanQualType ExpectedResultType, CanQualType ExpectedSizeOrAddressParamType,
16768 unsigned DependentParamTypeDiag, unsigned InvalidParamTypeDiag) {
16769 auto NormalizeType = [&SemaRef](QualType T) {
16770 if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
16771 // The operator is valid on any address space for OpenCL.
16772 // Drop address space from actual and expected result types.
16773 if (const auto PtrTy = T->template getAs<PointerType>())
16774 T = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
16775 }
16776 return SemaRef.Context.getCanonicalType(T);
16777 };
16778
16779 const unsigned NumParams = FnDecl->getNumParams();
16780 unsigned FirstNonTypeParam = 0;
16781 bool MalformedTypeIdentity = false;
16782 bool IsPotentiallyTypeAware = IsPotentiallyTypeAwareOperatorNewOrDelete(
16783 SemaRef, FD: FnDecl, WasMalformed: &MalformedTypeIdentity);
16784 unsigned MinimumMandatoryArgumentCount = 1;
16785 unsigned SizeParameterIndex = 0;
16786 if (IsPotentiallyTypeAware) {
16787 // We don't emit this diagnosis for template instantiations as we will
16788 // have already emitted it for the original template declaration.
16789 if (!FnDecl->isTemplateInstantiation())
16790 SemaRef.Diag(Loc: FnDecl->getLocation(), DiagID: diag::warn_ext_type_aware_allocators);
16791
16792 if (OperatorKind == AllocationOperatorKind::New) {
16793 SizeParameterIndex = 1;
16794 MinimumMandatoryArgumentCount =
16795 FunctionDecl::RequiredTypeAwareNewParameterCount;
16796 } else {
16797 SizeParameterIndex = 2;
16798 MinimumMandatoryArgumentCount =
16799 FunctionDecl::RequiredTypeAwareDeleteParameterCount;
16800 }
16801 FirstNonTypeParam = 1;
16802 }
16803
16804 bool IsPotentiallyDestroyingDelete =
16805 IsPotentiallyDestroyingOperatorDelete(SemaRef, FD: FnDecl);
16806
16807 if (IsPotentiallyDestroyingDelete) {
16808 ++MinimumMandatoryArgumentCount;
16809 ++SizeParameterIndex;
16810 }
16811
16812 if (NumParams < MinimumMandatoryArgumentCount)
16813 return SemaRef.Diag(Loc: FnDecl->getLocation(),
16814 DiagID: diag::err_operator_new_delete_too_few_parameters)
16815 << IsPotentiallyTypeAware << IsPotentiallyDestroyingDelete
16816 << FnDecl->getDeclName() << MinimumMandatoryArgumentCount;
16817
16818 for (unsigned Idx = 0; Idx < MinimumMandatoryArgumentCount; ++Idx) {
16819 const ParmVarDecl *ParamDecl = FnDecl->getParamDecl(i: Idx);
16820 if (ParamDecl->hasDefaultArg())
16821 return SemaRef.Diag(Loc: FnDecl->getLocation(),
16822 DiagID: diag::err_operator_new_default_arg)
16823 << FnDecl->getDeclName() << Idx << ParamDecl->getDefaultArgRange();
16824 }
16825
16826 auto *FnType = FnDecl->getType()->castAs<FunctionType>();
16827 QualType CanResultType = NormalizeType(FnType->getReturnType());
16828 QualType CanExpectedResultType = NormalizeType(ExpectedResultType);
16829 QualType CanExpectedSizeOrAddressParamType =
16830 NormalizeType(ExpectedSizeOrAddressParamType);
16831
16832 // Check that the result type is what we expect.
16833 if (CanResultType != CanExpectedResultType) {
16834 // Reject even if the type is dependent; an operator delete function is
16835 // required to have a non-dependent result type.
16836 return SemaRef.Diag(
16837 Loc: FnDecl->getLocation(),
16838 DiagID: CanResultType->isDependentType()
16839 ? diag::err_operator_new_delete_dependent_result_type
16840 : diag::err_operator_new_delete_invalid_result_type)
16841 << FnDecl->getDeclName() << ExpectedResultType;
16842 }
16843
16844 // A function template must have at least 2 parameters.
16845 if (FnDecl->getDescribedFunctionTemplate() && NumParams < 2)
16846 return SemaRef.Diag(Loc: FnDecl->getLocation(),
16847 DiagID: diag::err_operator_new_delete_template_too_few_parameters)
16848 << FnDecl->getDeclName();
16849
16850 auto CheckType = [&](unsigned ParamIdx, QualType ExpectedType,
16851 auto FallbackType) -> bool {
16852 const ParmVarDecl *ParamDecl = FnDecl->getParamDecl(i: ParamIdx);
16853 if (ExpectedType.isNull()) {
16854 return SemaRef.Diag(Loc: FnDecl->getLocation(), DiagID: InvalidParamTypeDiag)
16855 << IsPotentiallyTypeAware << IsPotentiallyDestroyingDelete
16856 << FnDecl->getDeclName() << (1 + ParamIdx) << FallbackType
16857 << ParamDecl->getSourceRange();
16858 }
16859 CanQualType CanExpectedTy =
16860 NormalizeType(SemaRef.Context.getCanonicalType(T: ExpectedType));
16861 auto ActualParamType =
16862 NormalizeType(ParamDecl->getType().getUnqualifiedType());
16863 if (ActualParamType == CanExpectedTy)
16864 return false;
16865 unsigned Diagnostic = ActualParamType->isDependentType()
16866 ? DependentParamTypeDiag
16867 : InvalidParamTypeDiag;
16868 return SemaRef.Diag(Loc: FnDecl->getLocation(), DiagID: Diagnostic)
16869 << IsPotentiallyTypeAware << IsPotentiallyDestroyingDelete
16870 << FnDecl->getDeclName() << (1 + ParamIdx) << ExpectedType
16871 << FallbackType << ParamDecl->getSourceRange();
16872 };
16873
16874 // Check that the first parameter type is what we expect.
16875 if (CheckType(FirstNonTypeParam, CanExpectedSizeOrAddressParamType, "size_t"))
16876 return true;
16877
16878 FnDecl->setIsDestroyingOperatorDelete(IsPotentiallyDestroyingDelete);
16879
16880 // If the first parameter type is not a type-identity we're done, otherwise
16881 // we need to ensure the size and alignment parameters have the correct type
16882 if (!IsPotentiallyTypeAware)
16883 return false;
16884
16885 if (CheckType(SizeParameterIndex, SemaRef.Context.getSizeType(), "size_t"))
16886 return true;
16887 TagDecl *StdAlignValTDecl = SemaRef.getStdAlignValT();
16888 CanQualType StdAlignValT =
16889 StdAlignValTDecl ? SemaRef.Context.getCanonicalTagType(TD: StdAlignValTDecl)
16890 : CanQualType();
16891 if (CheckType(SizeParameterIndex + 1, StdAlignValT, "std::align_val_t"))
16892 return true;
16893
16894 FnDecl->setIsTypeAwareOperatorNewOrDelete();
16895 return MalformedTypeIdentity;
16896}
16897
16898static bool CheckOperatorNewDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
16899 // C++ [basic.stc.dynamic.allocation]p1:
16900 // A program is ill-formed if an allocation function is declared in a
16901 // namespace scope other than global scope or declared static in global
16902 // scope.
16903 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
16904 return true;
16905
16906 CanQualType SizeTy =
16907 SemaRef.Context.getCanonicalType(T: SemaRef.Context.getSizeType());
16908
16909 // C++ [basic.stc.dynamic.allocation]p1:
16910 // The return type shall be void*. The first parameter shall have type
16911 // std::size_t.
16912 return CheckOperatorNewDeleteTypes(
16913 SemaRef, FnDecl, OperatorKind: AllocationOperatorKind::New, ExpectedResultType: SemaRef.Context.VoidPtrTy,
16914 ExpectedSizeOrAddressParamType: SizeTy, DependentParamTypeDiag: diag::err_operator_new_dependent_param_type,
16915 InvalidParamTypeDiag: diag::err_operator_new_param_type);
16916}
16917
16918static bool
16919CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
16920 // C++ [basic.stc.dynamic.deallocation]p1:
16921 // A program is ill-formed if deallocation functions are declared in a
16922 // namespace scope other than global scope or declared static in global
16923 // scope.
16924 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
16925 return true;
16926
16927 auto *MD = dyn_cast<CXXMethodDecl>(Val: FnDecl);
16928 auto ConstructDestroyingDeleteAddressType = [&]() {
16929 assert(MD);
16930 return SemaRef.Context.getPointerType(
16931 T: SemaRef.Context.getCanonicalTagType(TD: MD->getParent()));
16932 };
16933
16934 // C++ P2719: A destroying operator delete cannot be type aware
16935 // so for QoL we actually check for this explicitly by considering
16936 // an destroying-delete appropriate address type and the presence of
16937 // any parameter of type destroying_delete_t as an erroneous attempt
16938 // to declare a type aware destroying delete, rather than emitting a
16939 // pile of incorrect parameter type errors.
16940 if (MD && IsPotentiallyTypeAwareOperatorNewOrDelete(
16941 SemaRef, FD: MD, /*WasMalformed=*/nullptr)) {
16942 QualType AddressParamType =
16943 SemaRef.Context.getCanonicalType(T: MD->getParamDecl(i: 1)->getType());
16944 if (AddressParamType != SemaRef.Context.VoidPtrTy &&
16945 AddressParamType == ConstructDestroyingDeleteAddressType()) {
16946 // The address parameter type implies an author trying to construct a
16947 // type aware destroying delete, so we'll see if we can find a parameter
16948 // of type `std::destroying_delete_t`, and if we find it we'll report
16949 // this as being an attempt at a type aware destroying delete just stop
16950 // here. If we don't do this, the resulting incorrect parameter ordering
16951 // results in a pile mismatched argument type errors that don't explain
16952 // the core problem.
16953 for (auto Param : MD->parameters()) {
16954 if (isDestroyingDeleteT(Type: Param->getType())) {
16955 SemaRef.Diag(Loc: MD->getLocation(),
16956 DiagID: diag::err_type_aware_destroying_operator_delete)
16957 << Param->getSourceRange();
16958 return true;
16959 }
16960 }
16961 }
16962 }
16963
16964 // C++ P0722:
16965 // Within a class C, the first parameter of a destroying operator delete
16966 // shall be of type C *. The first parameter of any other deallocation
16967 // function shall be of type void *.
16968 CanQualType ExpectedAddressParamType =
16969 MD && IsPotentiallyDestroyingOperatorDelete(SemaRef, FD: MD)
16970 ? SemaRef.Context.getPointerType(
16971 T: SemaRef.Context.getCanonicalTagType(TD: MD->getParent()))
16972 : SemaRef.Context.VoidPtrTy;
16973
16974 // C++ [basic.stc.dynamic.deallocation]p2:
16975 // Each deallocation function shall return void
16976 if (CheckOperatorNewDeleteTypes(
16977 SemaRef, FnDecl, OperatorKind: AllocationOperatorKind::Delete,
16978 ExpectedResultType: SemaRef.Context.VoidTy, ExpectedSizeOrAddressParamType: ExpectedAddressParamType,
16979 DependentParamTypeDiag: diag::err_operator_delete_dependent_param_type,
16980 InvalidParamTypeDiag: diag::err_operator_delete_param_type))
16981 return true;
16982
16983 // C++ P0722:
16984 // A destroying operator delete shall be a usual deallocation function.
16985 if (MD && !MD->getParent()->isDependentContext() &&
16986 MD->isDestroyingOperatorDelete()) {
16987 if (!SemaRef.isUsualDeallocationFunction(FD: MD)) {
16988 SemaRef.Diag(Loc: MD->getLocation(),
16989 DiagID: diag::err_destroying_operator_delete_not_usual);
16990 return true;
16991 }
16992 }
16993
16994 return false;
16995}
16996
16997bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
16998 assert(FnDecl && FnDecl->isOverloadedOperator() &&
16999 "Expected an overloaded operator declaration");
17000
17001 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
17002
17003 // C++ [over.oper]p5:
17004 // The allocation and deallocation functions, operator new,
17005 // operator new[], operator delete and operator delete[], are
17006 // described completely in 3.7.3. The attributes and restrictions
17007 // found in the rest of this subclause do not apply to them unless
17008 // explicitly stated in 3.7.3.
17009 if (Op == OO_Delete || Op == OO_Array_Delete)
17010 return CheckOperatorDeleteDeclaration(SemaRef&: *this, FnDecl);
17011
17012 if (Op == OO_New || Op == OO_Array_New)
17013 return CheckOperatorNewDeclaration(SemaRef&: *this, FnDecl);
17014
17015 // C++ [over.oper]p7:
17016 // An operator function shall either be a member function or
17017 // be a non-member function and have at least one parameter
17018 // whose type is a class, a reference to a class, an enumeration,
17019 // or a reference to an enumeration.
17020 // Note: Before C++23, a member function could not be static. The only member
17021 // function allowed to be static is the call operator function.
17022 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Val: FnDecl)) {
17023 if (MethodDecl->isStatic()) {
17024 if (Op == OO_Call || Op == OO_Subscript)
17025 Diag(Loc: FnDecl->getLocation(),
17026 DiagID: (LangOpts.CPlusPlus23
17027 ? diag::warn_cxx20_compat_operator_overload_static
17028 : diag::ext_operator_overload_static))
17029 << FnDecl;
17030 else
17031 return Diag(Loc: FnDecl->getLocation(), DiagID: diag::err_operator_overload_static)
17032 << FnDecl;
17033 }
17034 } else {
17035 bool ClassOrEnumParam = false;
17036 for (auto *Param : FnDecl->parameters()) {
17037 QualType ParamType = Param->getType().getNonReferenceType();
17038 if (ParamType->isDependentType() || ParamType->isRecordType() ||
17039 ParamType->isEnumeralType()) {
17040 ClassOrEnumParam = true;
17041 break;
17042 }
17043 }
17044
17045 if (!ClassOrEnumParam)
17046 return Diag(Loc: FnDecl->getLocation(),
17047 DiagID: diag::err_operator_overload_needs_class_or_enum)
17048 << FnDecl->getDeclName();
17049 }
17050
17051 // C++ [over.oper]p8:
17052 // An operator function cannot have default arguments (8.3.6),
17053 // except where explicitly stated below.
17054 //
17055 // Only the function-call operator (C++ [over.call]p1) and the subscript
17056 // operator (CWG2507) allow default arguments.
17057 if (Op != OO_Call) {
17058 ParmVarDecl *FirstDefaultedParam = nullptr;
17059 for (auto *Param : FnDecl->parameters()) {
17060 if (Param->hasDefaultArg()) {
17061 FirstDefaultedParam = Param;
17062 break;
17063 }
17064 }
17065 if (FirstDefaultedParam) {
17066 if (Op == OO_Subscript) {
17067 Diag(Loc: FnDecl->getLocation(), DiagID: LangOpts.CPlusPlus23
17068 ? diag::ext_subscript_overload
17069 : diag::error_subscript_overload)
17070 << FnDecl->getDeclName() << 1
17071 << FirstDefaultedParam->getDefaultArgRange();
17072 } else {
17073 return Diag(Loc: FirstDefaultedParam->getLocation(),
17074 DiagID: diag::err_operator_overload_default_arg)
17075 << FnDecl->getDeclName()
17076 << FirstDefaultedParam->getDefaultArgRange();
17077 }
17078 }
17079 }
17080
17081 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
17082 { false, false, false }
17083#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
17084 , { Unary, Binary, MemberOnly }
17085#include "clang/Basic/OperatorKinds.def"
17086 };
17087
17088 bool CanBeUnaryOperator = OperatorUses[Op][0];
17089 bool CanBeBinaryOperator = OperatorUses[Op][1];
17090 bool MustBeMemberOperator = OperatorUses[Op][2];
17091
17092 // C++ [over.oper]p8:
17093 // [...] Operator functions cannot have more or fewer parameters
17094 // than the number required for the corresponding operator, as
17095 // described in the rest of this subclause.
17096 unsigned NumParams = FnDecl->getNumParams() +
17097 (isa<CXXMethodDecl>(Val: FnDecl) &&
17098 !FnDecl->hasCXXExplicitFunctionObjectParameter()
17099 ? 1
17100 : 0);
17101 if (Op != OO_Call && Op != OO_Subscript &&
17102 ((NumParams == 1 && !CanBeUnaryOperator) ||
17103 (NumParams == 2 && !CanBeBinaryOperator) || (NumParams < 1) ||
17104 (NumParams > 2))) {
17105 // We have the wrong number of parameters.
17106 unsigned ErrorKind;
17107 if (CanBeUnaryOperator && CanBeBinaryOperator) {
17108 ErrorKind = 2; // 2 -> unary or binary.
17109 } else if (CanBeUnaryOperator) {
17110 ErrorKind = 0; // 0 -> unary
17111 } else {
17112 assert(CanBeBinaryOperator &&
17113 "All non-call overloaded operators are unary or binary!");
17114 ErrorKind = 1; // 1 -> binary
17115 }
17116 return Diag(Loc: FnDecl->getLocation(), DiagID: diag::err_operator_overload_must_be)
17117 << FnDecl->getDeclName() << NumParams << ErrorKind;
17118 }
17119
17120 if (Op == OO_Subscript && NumParams != 2) {
17121 Diag(Loc: FnDecl->getLocation(), DiagID: LangOpts.CPlusPlus23
17122 ? diag::ext_subscript_overload
17123 : diag::error_subscript_overload)
17124 << FnDecl->getDeclName() << (NumParams == 1 ? 0 : 2);
17125 }
17126
17127 // Overloaded operators other than operator() and operator[] cannot be
17128 // variadic.
17129 if (Op != OO_Call &&
17130 FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) {
17131 return Diag(Loc: FnDecl->getLocation(), DiagID: diag::err_operator_overload_variadic)
17132 << FnDecl->getDeclName();
17133 }
17134
17135 // Some operators must be member functions.
17136 if (MustBeMemberOperator && !isa<CXXMethodDecl>(Val: FnDecl)) {
17137 return Diag(Loc: FnDecl->getLocation(),
17138 DiagID: diag::err_operator_overload_must_be_member)
17139 << FnDecl->getDeclName();
17140 }
17141
17142 // C++ [over.inc]p1:
17143 // The user-defined function called operator++ implements the
17144 // prefix and postfix ++ operator. If this function is a member
17145 // function with no parameters, or a non-member function with one
17146 // parameter of class or enumeration type, it defines the prefix
17147 // increment operator ++ for objects of that type. If the function
17148 // is a member function with one parameter (which shall be of type
17149 // int) or a non-member function with two parameters (the second
17150 // of which shall be of type int), it defines the postfix
17151 // increment operator ++ for objects of that type.
17152 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
17153 ParmVarDecl *LastParam = FnDecl->getParamDecl(i: FnDecl->getNumParams() - 1);
17154 QualType ParamType = LastParam->getType();
17155
17156 if (!ParamType->isSpecificBuiltinType(K: BuiltinType::Int) &&
17157 !ParamType->isDependentType())
17158 return Diag(Loc: LastParam->getLocation(),
17159 DiagID: diag::err_operator_overload_post_incdec_must_be_int)
17160 << LastParam->getType() << (Op == OO_MinusMinus);
17161 }
17162
17163 return false;
17164}
17165
17166static bool
17167checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
17168 FunctionTemplateDecl *TpDecl) {
17169 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
17170
17171 // Must have one or two template parameters.
17172 if (TemplateParams->size() == 1) {
17173 NonTypeTemplateParmDecl *PmDecl =
17174 dyn_cast<NonTypeTemplateParmDecl>(Val: TemplateParams->getParam(Idx: 0));
17175
17176 // The template parameter must be a char parameter pack.
17177 if (PmDecl && PmDecl->isTemplateParameterPack() &&
17178 SemaRef.Context.hasSameType(T1: PmDecl->getType(), T2: SemaRef.Context.CharTy))
17179 return false;
17180
17181 // C++20 [over.literal]p5:
17182 // A string literal operator template is a literal operator template
17183 // whose template-parameter-list comprises a single non-type
17184 // template-parameter of class type.
17185 //
17186 // As a DR resolution, we also allow placeholders for deduced class
17187 // template specializations.
17188 if (SemaRef.getLangOpts().CPlusPlus20 && PmDecl &&
17189 !PmDecl->isTemplateParameterPack() &&
17190 (PmDecl->getType()->isRecordType() ||
17191 PmDecl->getType()->getAs<DeducedTemplateSpecializationType>()))
17192 return false;
17193 } else if (TemplateParams->size() == 2) {
17194 TemplateTypeParmDecl *PmType =
17195 dyn_cast<TemplateTypeParmDecl>(Val: TemplateParams->getParam(Idx: 0));
17196 NonTypeTemplateParmDecl *PmArgs =
17197 dyn_cast<NonTypeTemplateParmDecl>(Val: TemplateParams->getParam(Idx: 1));
17198
17199 // The second template parameter must be a parameter pack with the
17200 // first template parameter as its type.
17201 if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
17202 PmArgs->isTemplateParameterPack()) {
17203 if (const auto *TArgs =
17204 PmArgs->getType()->getAsCanonical<TemplateTypeParmType>();
17205 TArgs && TArgs->getDepth() == PmType->getDepth() &&
17206 TArgs->getIndex() == PmType->getIndex()) {
17207 if (!SemaRef.inTemplateInstantiation())
17208 SemaRef.Diag(Loc: TpDecl->getLocation(),
17209 DiagID: diag::ext_string_literal_operator_template);
17210 return false;
17211 }
17212 }
17213 }
17214
17215 SemaRef.Diag(Loc: TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
17216 DiagID: diag::err_literal_operator_template)
17217 << TpDecl->getTemplateParameters()->getSourceRange();
17218 return true;
17219}
17220
17221bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
17222 if (isa<CXXMethodDecl>(Val: FnDecl)) {
17223 Diag(Loc: FnDecl->getLocation(), DiagID: diag::err_literal_operator_outside_namespace)
17224 << FnDecl->getDeclName();
17225 return true;
17226 }
17227
17228 if (FnDecl->isExternC()) {
17229 Diag(Loc: FnDecl->getLocation(), DiagID: diag::err_literal_operator_extern_c);
17230 if (const LinkageSpecDecl *LSD =
17231 FnDecl->getDeclContext()->getExternCContext())
17232 Diag(Loc: LSD->getExternLoc(), DiagID: diag::note_extern_c_begins_here);
17233 return true;
17234 }
17235
17236 // This might be the definition of a literal operator template.
17237 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
17238
17239 // This might be a specialization of a literal operator template.
17240 if (!TpDecl)
17241 TpDecl = FnDecl->getPrimaryTemplate();
17242
17243 // template <char...> type operator "" name() and
17244 // template <class T, T...> type operator "" name() are the only valid
17245 // template signatures, and the only valid signatures with no parameters.
17246 //
17247 // C++20 also allows template <SomeClass T> type operator "" name().
17248 if (TpDecl) {
17249 if (FnDecl->param_size() != 0) {
17250 Diag(Loc: FnDecl->getLocation(),
17251 DiagID: diag::err_literal_operator_template_with_params);
17252 return true;
17253 }
17254
17255 if (checkLiteralOperatorTemplateParameterList(SemaRef&: *this, TpDecl))
17256 return true;
17257
17258 } else if (FnDecl->param_size() == 1) {
17259 const ParmVarDecl *Param = FnDecl->getParamDecl(i: 0);
17260
17261 QualType ParamType = Param->getType().getUnqualifiedType();
17262
17263 // Only unsigned long long int, long double, any character type, and const
17264 // char * are allowed as the only parameters.
17265 if (ParamType->isSpecificBuiltinType(K: BuiltinType::ULongLong) ||
17266 ParamType->isSpecificBuiltinType(K: BuiltinType::LongDouble) ||
17267 Context.hasSameType(T1: ParamType, T2: Context.CharTy) ||
17268 Context.hasSameType(T1: ParamType, T2: Context.WideCharTy) ||
17269 Context.hasSameType(T1: ParamType, T2: Context.Char8Ty) ||
17270 Context.hasSameType(T1: ParamType, T2: Context.Char16Ty) ||
17271 Context.hasSameType(T1: ParamType, T2: Context.Char32Ty)) {
17272 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
17273 QualType InnerType = Ptr->getPointeeType();
17274
17275 // Pointer parameter must be a const char *.
17276 if (!(Context.hasSameType(T1: InnerType.getUnqualifiedType(),
17277 T2: Context.CharTy) &&
17278 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
17279 Diag(Loc: Param->getSourceRange().getBegin(),
17280 DiagID: diag::err_literal_operator_param)
17281 << ParamType << "'const char *'" << Param->getSourceRange();
17282 return true;
17283 }
17284
17285 } else if (ParamType->isRealFloatingType()) {
17286 Diag(Loc: Param->getSourceRange().getBegin(), DiagID: diag::err_literal_operator_param)
17287 << ParamType << Context.LongDoubleTy << Param->getSourceRange();
17288 return true;
17289
17290 } else if (ParamType->isIntegerType()) {
17291 Diag(Loc: Param->getSourceRange().getBegin(), DiagID: diag::err_literal_operator_param)
17292 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
17293 return true;
17294
17295 } else {
17296 Diag(Loc: Param->getSourceRange().getBegin(),
17297 DiagID: diag::err_literal_operator_invalid_param)
17298 << ParamType << Param->getSourceRange();
17299 return true;
17300 }
17301
17302 } else if (FnDecl->param_size() == 2) {
17303 FunctionDecl::param_iterator Param = FnDecl->param_begin();
17304
17305 // First, verify that the first parameter is correct.
17306
17307 QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
17308
17309 // Two parameter function must have a pointer to const as a
17310 // first parameter; let's strip those qualifiers.
17311 const PointerType *PT = FirstParamType->getAs<PointerType>();
17312
17313 if (!PT) {
17314 Diag(Loc: (*Param)->getSourceRange().getBegin(),
17315 DiagID: diag::err_literal_operator_param)
17316 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
17317 return true;
17318 }
17319
17320 QualType PointeeType = PT->getPointeeType();
17321 // First parameter must be const
17322 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
17323 Diag(Loc: (*Param)->getSourceRange().getBegin(),
17324 DiagID: diag::err_literal_operator_param)
17325 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
17326 return true;
17327 }
17328
17329 QualType InnerType = PointeeType.getUnqualifiedType();
17330 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
17331 // const char32_t* are allowed as the first parameter to a two-parameter
17332 // function
17333 if (!(Context.hasSameType(T1: InnerType, T2: Context.CharTy) ||
17334 Context.hasSameType(T1: InnerType, T2: Context.WideCharTy) ||
17335 Context.hasSameType(T1: InnerType, T2: Context.Char8Ty) ||
17336 Context.hasSameType(T1: InnerType, T2: Context.Char16Ty) ||
17337 Context.hasSameType(T1: InnerType, T2: Context.Char32Ty))) {
17338 Diag(Loc: (*Param)->getSourceRange().getBegin(),
17339 DiagID: diag::err_literal_operator_param)
17340 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
17341 return true;
17342 }
17343
17344 // Move on to the second and final parameter.
17345 ++Param;
17346
17347 // The second parameter must be a std::size_t.
17348 QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
17349 if (!Context.hasSameType(T1: SecondParamType, T2: Context.getSizeType())) {
17350 Diag(Loc: (*Param)->getSourceRange().getBegin(),
17351 DiagID: diag::err_literal_operator_param)
17352 << SecondParamType << Context.getSizeType()
17353 << (*Param)->getSourceRange();
17354 return true;
17355 }
17356 } else {
17357 Diag(Loc: FnDecl->getLocation(), DiagID: diag::err_literal_operator_bad_param_count);
17358 return true;
17359 }
17360
17361 // Parameters are good.
17362
17363 // A parameter-declaration-clause containing a default argument is not
17364 // equivalent to any of the permitted forms.
17365 for (auto *Param : FnDecl->parameters()) {
17366 if (Param->hasDefaultArg()) {
17367 Diag(Loc: Param->getDefaultArgRange().getBegin(),
17368 DiagID: diag::err_literal_operator_default_argument)
17369 << Param->getDefaultArgRange();
17370 break;
17371 }
17372 }
17373
17374 const IdentifierInfo *II = FnDecl->getDeclName().getCXXLiteralIdentifier();
17375 ReservedLiteralSuffixIdStatus Status = II->isReservedLiteralSuffixId();
17376 if (Status != ReservedLiteralSuffixIdStatus::NotReserved &&
17377 !getSourceManager().isInSystemHeader(Loc: FnDecl->getLocation())) {
17378 // C++23 [usrlit.suffix]p1:
17379 // Literal suffix identifiers that do not start with an underscore are
17380 // reserved for future standardization. Literal suffix identifiers that
17381 // contain a double underscore __ are reserved for use by C++
17382 // implementations.
17383 Diag(Loc: FnDecl->getLocation(), DiagID: diag::warn_user_literal_reserved)
17384 << static_cast<int>(Status)
17385 << StringLiteralParser::isValidUDSuffix(LangOpts: getLangOpts(), Suffix: II->getName());
17386 }
17387
17388 return false;
17389}
17390
17391Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
17392 Expr *LangStr,
17393 SourceLocation LBraceLoc) {
17394 StringLiteral *Lit = cast<StringLiteral>(Val: LangStr);
17395 assert(Lit->isUnevaluated() && "Unexpected string literal kind");
17396
17397 StringRef Lang = Lit->getString();
17398 LinkageSpecLanguageIDs Language;
17399 if (Lang == "C")
17400 Language = LinkageSpecLanguageIDs::C;
17401 else if (Lang == "C++")
17402 Language = LinkageSpecLanguageIDs::CXX;
17403 else {
17404 Diag(Loc: LangStr->getExprLoc(), DiagID: diag::err_language_linkage_spec_unknown)
17405 << LangStr->getSourceRange();
17406 return nullptr;
17407 }
17408
17409 // FIXME: Add all the various semantics of linkage specifications
17410
17411 LinkageSpecDecl *D = LinkageSpecDecl::Create(C&: Context, DC: CurContext, ExternLoc,
17412 LangLoc: LangStr->getExprLoc(), Lang: Language,
17413 HasBraces: LBraceLoc.isValid());
17414
17415 /// C++ [module.unit]p7.2.3
17416 /// - Otherwise, if the declaration
17417 /// - ...
17418 /// - ...
17419 /// - appears within a linkage-specification,
17420 /// it is attached to the global module.
17421 ///
17422 /// If the declaration is already in global module fragment, we don't
17423 /// need to attach it again.
17424 if (getLangOpts().CPlusPlusModules && isCurrentModulePurview()) {
17425 Module *GlobalModule = PushImplicitGlobalModuleFragment(BeginLoc: ExternLoc);
17426 D->setLocalOwningModule(GlobalModule);
17427 }
17428
17429 CurContext->addDecl(D);
17430 PushDeclContext(S, DC: D);
17431 return D;
17432}
17433
17434Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
17435 Decl *LinkageSpec,
17436 SourceLocation RBraceLoc) {
17437 if (RBraceLoc.isValid()) {
17438 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(Val: LinkageSpec);
17439 LSDecl->setRBraceLoc(RBraceLoc);
17440 }
17441
17442 // If the current module doesn't has Parent, it implies that the
17443 // LinkageSpec isn't in the module created by itself. So we don't
17444 // need to pop it.
17445 if (getLangOpts().CPlusPlusModules && getCurrentModule() &&
17446 getCurrentModule()->isImplicitGlobalModule() &&
17447 getCurrentModule()->Parent)
17448 PopImplicitGlobalModuleFragment();
17449
17450 PopDeclContext();
17451 return LinkageSpec;
17452}
17453
17454Decl *Sema::ActOnEmptyDeclaration(Scope *S,
17455 const ParsedAttributesView &AttrList,
17456 SourceLocation SemiLoc) {
17457 Decl *ED = EmptyDecl::Create(C&: Context, DC: CurContext, L: SemiLoc);
17458 // Attribute declarations appertain to empty declaration so we handle
17459 // them here.
17460 ProcessDeclAttributeList(S, D: ED, AttrList);
17461
17462 CurContext->addDecl(D: ED);
17463 return ED;
17464}
17465
17466VarDecl *Sema::BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
17467 SourceLocation StartLoc,
17468 SourceLocation Loc,
17469 const IdentifierInfo *Name) {
17470 bool Invalid = false;
17471 QualType ExDeclType = TInfo->getType();
17472
17473 // Arrays and functions decay.
17474 if (ExDeclType->isArrayType())
17475 ExDeclType = Context.getArrayDecayedType(T: ExDeclType);
17476 else if (ExDeclType->isFunctionType())
17477 ExDeclType = Context.getPointerType(T: ExDeclType);
17478
17479 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
17480 // The exception-declaration shall not denote a pointer or reference to an
17481 // incomplete type, other than [cv] void*.
17482 // N2844 forbids rvalue references.
17483 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
17484 Diag(Loc, DiagID: diag::err_catch_rvalue_ref);
17485 Invalid = true;
17486 }
17487
17488 if (ExDeclType->isVariablyModifiedType()) {
17489 Diag(Loc, DiagID: diag::err_catch_variably_modified) << ExDeclType;
17490 Invalid = true;
17491 }
17492
17493 QualType BaseType = ExDeclType;
17494 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
17495 unsigned DK = diag::err_catch_incomplete;
17496 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
17497 BaseType = Ptr->getPointeeType();
17498 Mode = 1;
17499 DK = diag::err_catch_incomplete_ptr;
17500 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
17501 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
17502 BaseType = Ref->getPointeeType();
17503 Mode = 2;
17504 DK = diag::err_catch_incomplete_ref;
17505 }
17506 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
17507 !BaseType->isDependentType() && RequireCompleteType(Loc, T: BaseType, DiagID: DK))
17508 Invalid = true;
17509
17510 if (!Invalid && BaseType.isWebAssemblyReferenceType()) {
17511 Diag(Loc, DiagID: diag::err_wasm_reftype_tc) << 1;
17512 Invalid = true;
17513 }
17514
17515 if (!Invalid && Mode != 1 && BaseType->isSizelessType()) {
17516 Diag(Loc, DiagID: diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType;
17517 Invalid = true;
17518 }
17519
17520 if (!Invalid && !ExDeclType->isDependentType() &&
17521 RequireNonAbstractType(Loc, T: ExDeclType,
17522 DiagID: diag::err_abstract_type_in_decl,
17523 Args: AbstractVariableType))
17524 Invalid = true;
17525
17526 // Only the non-fragile NeXT runtime currently supports C++ catches
17527 // of ObjC types, and no runtime supports catching ObjC types by value.
17528 if (!Invalid && getLangOpts().ObjC) {
17529 QualType T = ExDeclType;
17530 if (const ReferenceType *RT = T->getAs<ReferenceType>())
17531 T = RT->getPointeeType();
17532
17533 if (T->isObjCObjectType()) {
17534 Diag(Loc, DiagID: diag::err_objc_object_catch);
17535 Invalid = true;
17536 } else if (T->isObjCObjectPointerType()) {
17537 // FIXME: should this be a test for macosx-fragile specifically?
17538 if (getLangOpts().ObjCRuntime.isFragile())
17539 Diag(Loc, DiagID: diag::warn_objc_pointer_cxx_catch_fragile);
17540 }
17541 }
17542
17543 VarDecl *ExDecl = VarDecl::Create(C&: Context, DC: CurContext, StartLoc, IdLoc: Loc, Id: Name,
17544 T: ExDeclType, TInfo, S: SC_None);
17545 ExDecl->setExceptionVariable(true);
17546
17547 // In ARC, infer 'retaining' for variables of retainable type.
17548 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(decl: ExDecl))
17549 Invalid = true;
17550
17551 if (!Invalid && !ExDeclType->isDependentType()) {
17552 if (auto *ClassDecl = ExDeclType->getAsCXXRecordDecl()) {
17553 // Insulate this from anything else we might currently be parsing.
17554 EnterExpressionEvaluationContext scope(
17555 *this, ExpressionEvaluationContext::PotentiallyEvaluated);
17556
17557 // C++ [except.handle]p16:
17558 // The object declared in an exception-declaration or, if the
17559 // exception-declaration does not specify a name, a temporary (12.2) is
17560 // copy-initialized (8.5) from the exception object. [...]
17561 // The object is destroyed when the handler exits, after the destruction
17562 // of any automatic objects initialized within the handler.
17563 //
17564 // We just pretend to initialize the object with itself, then make sure
17565 // it can be destroyed later.
17566 QualType initType = Context.getExceptionObjectType(T: ExDeclType);
17567
17568 InitializedEntity entity =
17569 InitializedEntity::InitializeVariable(Var: ExDecl);
17570 InitializationKind initKind =
17571 InitializationKind::CreateCopy(InitLoc: Loc, EqualLoc: SourceLocation());
17572
17573 Expr *opaqueValue =
17574 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
17575 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
17576 ExprResult result = sequence.Perform(S&: *this, Entity: entity, Kind: initKind, Args: opaqueValue);
17577 if (result.isInvalid())
17578 Invalid = true;
17579 else {
17580 // If the constructor used was non-trivial, set this as the
17581 // "initializer".
17582 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
17583 if (!construct->getConstructor()->isTrivial()) {
17584 Expr *init = MaybeCreateExprWithCleanups(SubExpr: construct);
17585 ExDecl->setInit(init);
17586 }
17587
17588 // And make sure it's destructable.
17589 FinalizeVarWithDestructor(VD: ExDecl, ClassDecl);
17590 }
17591 }
17592 }
17593
17594 if (Invalid)
17595 ExDecl->setInvalidDecl();
17596
17597 return ExDecl;
17598}
17599
17600Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
17601 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
17602 bool Invalid = D.isInvalidType();
17603
17604 // Check for unexpanded parameter packs.
17605 if (DiagnoseUnexpandedParameterPack(Loc: D.getIdentifierLoc(), T: TInfo,
17606 UPPC: UPPC_ExceptionType)) {
17607 TInfo = Context.getTrivialTypeSourceInfo(T: Context.IntTy,
17608 Loc: D.getIdentifierLoc());
17609 Invalid = true;
17610 }
17611
17612 const IdentifierInfo *II = D.getIdentifier();
17613 if (NamedDecl *PrevDecl =
17614 LookupSingleName(S, Name: II, Loc: D.getIdentifierLoc(), NameKind: LookupOrdinaryName,
17615 Redecl: RedeclarationKind::ForVisibleRedeclaration)) {
17616 // The scope should be freshly made just for us. There is just no way
17617 // it contains any previous declaration, except for function parameters in
17618 // a function-try-block's catch statement.
17619 assert(!S->isDeclScope(PrevDecl));
17620 if (isDeclInScope(D: PrevDecl, Ctx: CurContext, S)) {
17621 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_redefinition)
17622 << D.getIdentifier();
17623 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_definition);
17624 Invalid = true;
17625 } else if (PrevDecl->isTemplateParameter())
17626 // Maybe we will complain about the shadowed template parameter.
17627 DiagnoseTemplateParameterShadow(Loc: D.getIdentifierLoc(), PrevDecl);
17628 }
17629
17630 if (D.getCXXScopeSpec().isSet() && !Invalid) {
17631 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_qualified_catch_declarator)
17632 << D.getCXXScopeSpec().getRange();
17633 Invalid = true;
17634 }
17635
17636 VarDecl *ExDecl = BuildExceptionDeclaration(
17637 S, TInfo, StartLoc: D.getBeginLoc(), Loc: D.getIdentifierLoc(), Name: D.getIdentifier());
17638 if (Invalid)
17639 ExDecl->setInvalidDecl();
17640
17641 // Add the exception declaration into this scope.
17642 if (II)
17643 PushOnScopeChains(D: ExDecl, S);
17644 else
17645 CurContext->addDecl(D: ExDecl);
17646
17647 ProcessDeclAttributes(S, D: ExDecl, PD: D);
17648 return ExDecl;
17649}
17650
17651Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
17652 Expr *AssertExpr,
17653 Expr *AssertMessageExpr,
17654 SourceLocation RParenLoc) {
17655 if (DiagnoseUnexpandedParameterPack(E: AssertExpr, UPPC: UPPC_StaticAssertExpression))
17656 return nullptr;
17657
17658 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
17659 AssertMessageExpr, RParenLoc, Failed: false);
17660}
17661
17662static void WriteCharTypePrefix(BuiltinType::Kind BTK, llvm::raw_ostream &OS) {
17663 switch (BTK) {
17664 case BuiltinType::Char_S:
17665 case BuiltinType::Char_U:
17666 break;
17667 case BuiltinType::Char8:
17668 OS << "u8";
17669 break;
17670 case BuiltinType::Char16:
17671 OS << 'u';
17672 break;
17673 case BuiltinType::Char32:
17674 OS << 'U';
17675 break;
17676 case BuiltinType::WChar_S:
17677 case BuiltinType::WChar_U:
17678 OS << 'L';
17679 break;
17680 default:
17681 llvm_unreachable("Non-character type");
17682 }
17683}
17684
17685/// Convert character's value, interpreted as a code unit, to a string.
17686/// The value needs to be zero-extended to 32-bits.
17687/// FIXME: This assumes Unicode literal encodings
17688static void WriteCharValueForDiagnostic(uint32_t Value, const BuiltinType *BTy,
17689 unsigned TyWidth,
17690 SmallVectorImpl<char> &Str) {
17691 char Arr[UNI_MAX_UTF8_BYTES_PER_CODE_POINT];
17692 char *Ptr = Arr;
17693 BuiltinType::Kind K = BTy->getKind();
17694 llvm::raw_svector_ostream OS(Str);
17695
17696 // This should catch Char_S, Char_U, Char8, and use of escaped characters in
17697 // other types.
17698 if (K == BuiltinType::Char_S || K == BuiltinType::Char_U ||
17699 K == BuiltinType::Char8 || Value <= 0x7F) {
17700 StringRef Escaped = escapeCStyle<EscapeChar::Single>(Ch: Value);
17701 if (!Escaped.empty())
17702 EscapeStringForDiagnostic(Str: Escaped, OutStr&: Str);
17703 else
17704 OS << static_cast<char>(Value);
17705 return;
17706 }
17707
17708 switch (K) {
17709 case BuiltinType::Char16:
17710 case BuiltinType::Char32:
17711 case BuiltinType::WChar_S:
17712 case BuiltinType::WChar_U: {
17713 if (llvm::ConvertCodePointToUTF8(Source: Value, ResultPtr&: Ptr))
17714 EscapeStringForDiagnostic(Str: StringRef(Arr, Ptr - Arr), OutStr&: Str);
17715 else
17716 OS << "\\x"
17717 << llvm::format_hex_no_prefix(N: Value, Width: TyWidth / 4, /*Upper=*/true);
17718 break;
17719 }
17720 default:
17721 llvm_unreachable("Non-character type is passed");
17722 }
17723}
17724
17725/// Convert \V to a string we can present to the user in a diagnostic
17726/// \T is the type of the expression that has been evaluated into \V
17727static bool ConvertAPValueToString(const APValue &V, QualType T,
17728 SmallVectorImpl<char> &Str,
17729 ASTContext &Context) {
17730 if (!V.hasValue())
17731 return false;
17732
17733 switch (V.getKind()) {
17734 case APValue::ValueKind::Int:
17735 if (T->isBooleanType()) {
17736 // Bools are reduced to ints during evaluation, but for
17737 // diagnostic purposes we want to print them as
17738 // true or false.
17739 int64_t BoolValue = V.getInt().getExtValue();
17740 assert((BoolValue == 0 || BoolValue == 1) &&
17741 "Bool type, but value is not 0 or 1");
17742 llvm::raw_svector_ostream OS(Str);
17743 OS << (BoolValue ? "true" : "false");
17744 } else {
17745 llvm::raw_svector_ostream OS(Str);
17746 // Same is true for chars.
17747 // We want to print the character representation for textual types
17748 const auto *BTy = T->getAs<BuiltinType>();
17749 if (BTy) {
17750 switch (BTy->getKind()) {
17751 case BuiltinType::Char_S:
17752 case BuiltinType::Char_U:
17753 case BuiltinType::Char8:
17754 case BuiltinType::Char16:
17755 case BuiltinType::Char32:
17756 case BuiltinType::WChar_S:
17757 case BuiltinType::WChar_U: {
17758 unsigned TyWidth = Context.getIntWidth(T);
17759 assert(8 <= TyWidth && TyWidth <= 32 && "Unexpected integer width");
17760 uint32_t CodeUnit = static_cast<uint32_t>(V.getInt().getZExtValue());
17761 WriteCharTypePrefix(BTK: BTy->getKind(), OS);
17762 OS << '\'';
17763 WriteCharValueForDiagnostic(Value: CodeUnit, BTy, TyWidth, Str);
17764 OS << "' (0x"
17765 << llvm::format_hex_no_prefix(N: CodeUnit, /*Width=*/2,
17766 /*Upper=*/true)
17767 << ", " << V.getInt() << ')';
17768 return true;
17769 }
17770 default:
17771 break;
17772 }
17773 }
17774 V.getInt().toString(Str);
17775 }
17776
17777 break;
17778
17779 case APValue::ValueKind::Float:
17780 V.getFloat().toString(Str);
17781 break;
17782
17783 case APValue::ValueKind::LValue:
17784 if (V.isNullPointer()) {
17785 llvm::raw_svector_ostream OS(Str);
17786 OS << "nullptr";
17787 } else
17788 return false;
17789 break;
17790
17791 case APValue::ValueKind::ComplexFloat: {
17792 llvm::raw_svector_ostream OS(Str);
17793 OS << '(';
17794 V.getComplexFloatReal().toString(Str);
17795 OS << " + ";
17796 V.getComplexFloatImag().toString(Str);
17797 OS << "i)";
17798 } break;
17799
17800 case APValue::ValueKind::ComplexInt: {
17801 llvm::raw_svector_ostream OS(Str);
17802 OS << '(';
17803 V.getComplexIntReal().toString(Str);
17804 OS << " + ";
17805 V.getComplexIntImag().toString(Str);
17806 OS << "i)";
17807 } break;
17808
17809 default:
17810 return false;
17811 }
17812
17813 return true;
17814}
17815
17816/// Some Expression types are not useful to print notes about,
17817/// e.g. literals and values that have already been expanded
17818/// before such as int-valued template parameters.
17819static bool UsefulToPrintExpr(const Expr *E) {
17820 E = E->IgnoreParenImpCasts();
17821 // Literals are pretty easy for humans to understand.
17822 if (isa<IntegerLiteral, FloatingLiteral, CharacterLiteral, CXXBoolLiteralExpr,
17823 CXXNullPtrLiteralExpr, FixedPointLiteral, ImaginaryLiteral>(Val: E))
17824 return false;
17825
17826 // These have been substituted from template parameters
17827 // and appear as literals in the static assert error.
17828 if (isa<SubstNonTypeTemplateParmExpr>(Val: E))
17829 return false;
17830
17831 // -5 is also simple to understand.
17832 if (const auto *UnaryOp = dyn_cast<UnaryOperator>(Val: E))
17833 return UsefulToPrintExpr(E: UnaryOp->getSubExpr());
17834
17835 // Only print nested arithmetic operators.
17836 if (const auto *BO = dyn_cast<BinaryOperator>(Val: E))
17837 return (BO->isShiftOp() || BO->isAdditiveOp() || BO->isMultiplicativeOp() ||
17838 BO->isBitwiseOp());
17839
17840 return true;
17841}
17842
17843void Sema::DiagnoseStaticAssertDetails(const Expr *E) {
17844 // FIXME: Should we also ignore explicit casts?
17845 E = E->IgnoreParenImpCasts();
17846 if (const auto *Op = dyn_cast<BinaryOperator>(Val: E);
17847 Op && Op->getOpcode() != BO_LOr) {
17848 const Expr *LHS = Op->getLHS()->IgnoreParenImpCasts();
17849 const Expr *RHS = Op->getRHS()->IgnoreParenImpCasts();
17850
17851 // Ignore comparisons of boolean expressions with a boolean literal.
17852 if ((isa<CXXBoolLiteralExpr>(Val: LHS) && RHS->getType()->isBooleanType()) ||
17853 (isa<CXXBoolLiteralExpr>(Val: RHS) && LHS->getType()->isBooleanType()))
17854 return;
17855
17856 // Don't print obvious expressions.
17857 if (!UsefulToPrintExpr(E: LHS) && !UsefulToPrintExpr(E: RHS))
17858 return;
17859
17860 struct {
17861 const clang::Expr *Cond;
17862 Expr::EvalResult Result;
17863 SmallString<12> ValueString;
17864 bool Print;
17865 } DiagSides[2] = {{.Cond: LHS, .Result: Expr::EvalResult(), .ValueString: {}, .Print: false},
17866 {.Cond: RHS, .Result: Expr::EvalResult(), .ValueString: {}, .Print: false}};
17867 for (auto &DiagSide : DiagSides) {
17868 const Expr *Side = DiagSide.Cond;
17869
17870 Side->EvaluateAsRValue(Result&: DiagSide.Result, Ctx: Context, InConstantContext: true);
17871
17872 DiagSide.Print = ConvertAPValueToString(
17873 V: DiagSide.Result.Val, T: Side->getType(), Str&: DiagSide.ValueString, Context);
17874 }
17875 if (DiagSides[0].Print && DiagSides[1].Print) {
17876 Diag(Loc: Op->getExprLoc(), DiagID: diag::note_expr_evaluates_to)
17877 << DiagSides[0].ValueString << Op->getOpcodeStr()
17878 << DiagSides[1].ValueString << Op->getSourceRange();
17879 }
17880 } else if (const auto *RE = dyn_cast<RequiresExpr>(Val: E)) {
17881 DiagnoseUnsatisfiedRequiresExpr(RequiresExpr: RE);
17882 } else {
17883 DiagnoseTypeTraitDetails(E);
17884 }
17885}
17886
17887template <typename ResultType>
17888static bool EvaluateAsStringImpl(Sema &SemaRef, Expr *Message,
17889 ResultType &Result, ASTContext &Ctx,
17890 Sema::StringEvaluationContext EvalContext,
17891 bool ErrorOnInvalidMessage) {
17892
17893 assert(Message);
17894 assert(!Message->isTypeDependent() && !Message->isValueDependent() &&
17895 "can't evaluate a dependant static assert message");
17896
17897 if (const auto *SL = dyn_cast<StringLiteral>(Val: Message)) {
17898 assert(SL->isUnevaluated() && "expected an unevaluated string");
17899 if constexpr (std::is_same_v<APValue, ResultType>) {
17900 Result =
17901 APValue(APValue::UninitArray{}, SL->getLength(), SL->getLength());
17902 const ConstantArrayType *CAT =
17903 SemaRef.getASTContext().getAsConstantArrayType(T: SL->getType());
17904 assert(CAT && "string literal isn't an array");
17905 QualType CharType = CAT->getElementType();
17906 llvm::APSInt Value(SemaRef.getASTContext().getTypeSize(T: CharType),
17907 CharType->isUnsignedIntegerType());
17908 for (unsigned I = 0; I < SL->getLength(); I++) {
17909 Value = SL->getCodeUnit(I);
17910 Result.getArrayInitializedElt(I) = APValue(Value);
17911 }
17912 } else {
17913 Result.assign(SL->getString().begin(), SL->getString().end());
17914 }
17915 return true;
17916 }
17917
17918 SourceLocation Loc = Message->getBeginLoc();
17919 QualType T = Message->getType().getNonReferenceType();
17920 auto *RD = T->getAsCXXRecordDecl();
17921 if (!RD) {
17922 SemaRef.Diag(Loc, DiagID: diag::err_user_defined_msg_invalid) << EvalContext;
17923 return false;
17924 }
17925
17926 auto FindMember = [&](StringRef Member) -> std::optional<LookupResult> {
17927 DeclarationName DN = SemaRef.PP.getIdentifierInfo(Name: Member);
17928 LookupResult MemberLookup(SemaRef, DN, Loc, Sema::LookupMemberName);
17929 SemaRef.LookupQualifiedName(R&: MemberLookup, LookupCtx: RD);
17930 OverloadCandidateSet Candidates(MemberLookup.getNameLoc(),
17931 OverloadCandidateSet::CSK_Normal);
17932 if (MemberLookup.empty())
17933 return std::nullopt;
17934 return std::move(MemberLookup);
17935 };
17936
17937 std::optional<LookupResult> SizeMember = FindMember("size");
17938 std::optional<LookupResult> DataMember = FindMember("data");
17939 if (!SizeMember || !DataMember) {
17940 SemaRef.Diag(Loc, DiagID: diag::err_user_defined_msg_missing_member_function)
17941 << EvalContext
17942 << ((!SizeMember && !DataMember) ? 2
17943 : !SizeMember ? 0
17944 : 1);
17945 return false;
17946 }
17947
17948 auto BuildExpr = [&](LookupResult &LR) {
17949 ExprResult Res = SemaRef.BuildMemberReferenceExpr(
17950 Base: Message, BaseType: Message->getType(), OpLoc: Message->getBeginLoc(), IsArrow: false,
17951 SS: CXXScopeSpec(), TemplateKWLoc: SourceLocation(), FirstQualifierInScope: nullptr, R&: LR, TemplateArgs: nullptr, S: nullptr);
17952 if (Res.isInvalid())
17953 return ExprError();
17954 Res = SemaRef.BuildCallExpr(S: nullptr, Fn: Res.get(), LParenLoc: Loc, ArgExprs: {}, RParenLoc: Loc, ExecConfig: nullptr,
17955 IsExecConfig: false, AllowRecovery: true);
17956 if (Res.isInvalid())
17957 return ExprError();
17958 if (Res.get()->isTypeDependent() || Res.get()->isValueDependent())
17959 return ExprError();
17960 return SemaRef.TemporaryMaterializationConversion(E: Res.get());
17961 };
17962
17963 ExprResult SizeE = BuildExpr(*SizeMember);
17964 ExprResult DataE = BuildExpr(*DataMember);
17965
17966 QualType SizeT = SemaRef.Context.getSizeType();
17967 QualType ConstCharPtr = SemaRef.Context.getPointerType(
17968 T: SemaRef.Context.getConstType(T: SemaRef.Context.CharTy));
17969
17970 ExprResult EvaluatedSize =
17971 SizeE.isInvalid()
17972 ? ExprError()
17973 : SemaRef.BuildConvertedConstantExpression(
17974 From: SizeE.get(), T: SizeT, CCE: CCEKind::StaticAssertMessageSize);
17975 if (EvaluatedSize.isInvalid()) {
17976 SemaRef.Diag(Loc, DiagID: diag::err_user_defined_msg_invalid_mem_fn_ret_ty)
17977 << EvalContext << /*size*/ 0;
17978 return false;
17979 }
17980
17981 ExprResult EvaluatedData =
17982 DataE.isInvalid()
17983 ? ExprError()
17984 : SemaRef.BuildConvertedConstantExpression(
17985 From: DataE.get(), T: ConstCharPtr, CCE: CCEKind::StaticAssertMessageData);
17986 if (EvaluatedData.isInvalid()) {
17987 SemaRef.Diag(Loc, DiagID: diag::err_user_defined_msg_invalid_mem_fn_ret_ty)
17988 << EvalContext << /*data*/ 1;
17989 return false;
17990 }
17991
17992 if (!ErrorOnInvalidMessage &&
17993 SemaRef.Diags.isIgnored(DiagID: diag::warn_user_defined_msg_constexpr, Loc))
17994 return true;
17995
17996 Expr::EvalResult Status;
17997 SmallVector<PartialDiagnosticAt, 8> Notes;
17998 Status.Diag = &Notes;
17999 if (!Message->EvaluateCharRangeAsString(Result, EvaluatedSize.get(),
18000 EvaluatedData.get(), Ctx, Status) ||
18001 !Notes.empty()) {
18002 SemaRef.Diag(Loc: Message->getBeginLoc(),
18003 DiagID: ErrorOnInvalidMessage ? diag::err_user_defined_msg_constexpr
18004 : diag::warn_user_defined_msg_constexpr)
18005 << EvalContext;
18006 for (const auto &Note : Notes)
18007 SemaRef.Diag(Loc: Note.first, PD: Note.second);
18008 return !ErrorOnInvalidMessage;
18009 }
18010 return true;
18011}
18012
18013bool Sema::EvaluateAsString(Expr *Message, APValue &Result, ASTContext &Ctx,
18014 StringEvaluationContext EvalContext,
18015 bool ErrorOnInvalidMessage) {
18016 return EvaluateAsStringImpl(SemaRef&: *this, Message, Result, Ctx, EvalContext,
18017 ErrorOnInvalidMessage);
18018}
18019
18020bool Sema::EvaluateAsString(Expr *Message, std::string &Result, ASTContext &Ctx,
18021 StringEvaluationContext EvalContext,
18022 bool ErrorOnInvalidMessage) {
18023 return EvaluateAsStringImpl(SemaRef&: *this, Message, Result, Ctx, EvalContext,
18024 ErrorOnInvalidMessage);
18025}
18026
18027Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
18028 Expr *AssertExpr, Expr *AssertMessage,
18029 SourceLocation RParenLoc,
18030 bool Failed) {
18031 assert(AssertExpr != nullptr && "Expected non-null condition");
18032 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
18033 (!AssertMessage || (!AssertMessage->isTypeDependent() &&
18034 !AssertMessage->isValueDependent())) &&
18035 !Failed) {
18036 // In a static_assert-declaration, the constant-expression shall be a
18037 // constant expression that can be contextually converted to bool.
18038 ExprResult Converted = PerformContextuallyConvertToBool(From: AssertExpr);
18039 if (Converted.isInvalid())
18040 Failed = true;
18041
18042 ExprResult FullAssertExpr =
18043 ActOnFinishFullExpr(Expr: Converted.get(), CC: StaticAssertLoc,
18044 /*DiscardedValue*/ false,
18045 /*IsConstexpr*/ true);
18046 if (FullAssertExpr.isInvalid())
18047 Failed = true;
18048 else
18049 AssertExpr = FullAssertExpr.get();
18050
18051 llvm::APSInt Cond;
18052 Expr *BaseExpr = AssertExpr;
18053 AllowFoldKind FoldKind = AllowFoldKind::No;
18054
18055 if (!getLangOpts().CPlusPlus) {
18056 // In C mode, allow folding as an extension for better compatibility with
18057 // C++ in terms of expressions like static_assert("test") or
18058 // static_assert(nullptr).
18059 FoldKind = AllowFoldKind::Allow;
18060 }
18061
18062 if (!Failed && VerifyIntegerConstantExpression(
18063 E: BaseExpr, Result: &Cond,
18064 DiagID: diag::err_static_assert_expression_is_not_constant,
18065 CanFold: FoldKind).isInvalid())
18066 Failed = true;
18067
18068 // If the static_assert passes, only verify that
18069 // the message is grammatically valid without evaluating it.
18070 if (!Failed && AssertMessage && Cond.getBoolValue()) {
18071 std::string Str;
18072 EvaluateAsString(Message: AssertMessage, Result&: Str, Ctx&: Context,
18073 EvalContext: StringEvaluationContext::StaticAssert,
18074 /*ErrorOnInvalidMessage=*/false);
18075 }
18076
18077 // CWG2518
18078 // [dcl.pre]/p10 If [...] the expression is evaluated in the context of a
18079 // template definition, the declaration has no effect.
18080 bool InTemplateDefinition =
18081 getLangOpts().CPlusPlus && CurContext->isDependentContext();
18082
18083 if (!Failed && !Cond && !InTemplateDefinition) {
18084 SmallString<256> MsgBuffer;
18085 llvm::raw_svector_ostream Msg(MsgBuffer);
18086 bool HasMessage = AssertMessage;
18087 if (AssertMessage) {
18088 std::string Str;
18089 HasMessage = EvaluateAsString(Message: AssertMessage, Result&: Str, Ctx&: Context,
18090 EvalContext: StringEvaluationContext::StaticAssert,
18091 /*ErrorOnInvalidMessage=*/true) ||
18092 !Str.empty();
18093 Msg << Str;
18094 }
18095 Expr *InnerCond = nullptr;
18096 std::string InnerCondDescription;
18097 std::tie(args&: InnerCond, args&: InnerCondDescription) =
18098 findFailedBooleanCondition(Cond: Converted.get());
18099 if (const auto *ConceptIDExpr =
18100 dyn_cast_or_null<ConceptSpecializationExpr>(Val: InnerCond)) {
18101 const ASTConstraintSatisfaction &Satisfaction =
18102 ConceptIDExpr->getSatisfaction();
18103 if (!Satisfaction.ContainsErrors || Satisfaction.NumRecords) {
18104 Diag(Loc: AssertExpr->getBeginLoc(), DiagID: diag::err_static_assert_failed)
18105 << !HasMessage << Msg.str() << AssertExpr->getSourceRange();
18106 // Drill down into concept specialization expressions to see why they
18107 // weren't satisfied.
18108 DiagnoseUnsatisfiedConstraint(ConstraintExpr: ConceptIDExpr);
18109 }
18110 } else if (InnerCond && !isa<CXXBoolLiteralExpr>(Val: InnerCond) &&
18111 !isa<IntegerLiteral>(Val: InnerCond)) {
18112 Diag(Loc: InnerCond->getBeginLoc(),
18113 DiagID: diag::err_static_assert_requirement_failed)
18114 << InnerCondDescription << !HasMessage << Msg.str()
18115 << InnerCond->getSourceRange();
18116 DiagnoseStaticAssertDetails(E: InnerCond);
18117 } else {
18118 Diag(Loc: AssertExpr->getBeginLoc(), DiagID: diag::err_static_assert_failed)
18119 << !HasMessage << Msg.str() << AssertExpr->getSourceRange();
18120 PrintContextStack();
18121 }
18122 Failed = true;
18123 }
18124 } else {
18125 ExprResult FullAssertExpr = ActOnFinishFullExpr(Expr: AssertExpr, CC: StaticAssertLoc,
18126 /*DiscardedValue*/false,
18127 /*IsConstexpr*/true);
18128 if (FullAssertExpr.isInvalid())
18129 Failed = true;
18130 else
18131 AssertExpr = FullAssertExpr.get();
18132 }
18133
18134 Decl *Decl = StaticAssertDecl::Create(C&: Context, DC: CurContext, StaticAssertLoc,
18135 AssertExpr, Message: AssertMessage, RParenLoc,
18136 Failed);
18137
18138 CurContext->addDecl(D: Decl);
18139 return Decl;
18140}
18141
18142static QualType IgnorePackIndexing(QualType T) {
18143 if (const auto *PIT = dyn_cast<PackIndexingType>(Val&: T))
18144 return PIT->getPattern();
18145 return T;
18146}
18147
18148static const TemplateSpecializationType *
18149GetClassTemplateSpecializationType(ASTContext &Context, QualType T) {
18150 T = IgnorePackIndexing(T);
18151 if (const auto *ICNT = dyn_cast<InjectedClassNameType>(Val&: T))
18152 T = ICNT->getDecl()->getCanonicalTemplateSpecializationType(Ctx: Context);
18153
18154 const auto *TST = dyn_cast<TemplateSpecializationType>(Val&: T);
18155 if (!TST)
18156 return nullptr;
18157
18158 TemplateDecl *TD = TST->getTemplateName().getAsTemplateDecl();
18159 if (!TD || isa<ClassTemplateDecl>(Val: TD))
18160 return TST;
18161 return nullptr;
18162}
18163
18164bool Sema::DiagnosePackIndexingInFriendNNS(SourceLocation Loc,
18165 NestedNameSpecifierLoc NNSLoc) {
18166 for (TypeLoc TL = NNSLoc.getAsTypeLoc(); TL;
18167 TL = TL.getPrefix().getAsTypeLoc()) {
18168 if (TL.getTypeLocClass() != TypeLoc::PackIndexing)
18169 continue;
18170
18171 Diag(Loc, DiagID: diag::err_pack_indexing_in_friend) << TL.getSourceRange();
18172 return true;
18173 }
18174 return false;
18175}
18176
18177static void DiagnoseDependentFriendNotMember(Sema &S, SourceLocation Loc,
18178 NestedNameSpecifier NNS) {
18179 QualType T(NNS.getAsType(), 0);
18180 if (const auto *TST =
18181 dyn_cast<TemplateSpecializationType>(Val: IgnorePackIndexing(T))) {
18182 if (isa_and_nonnull<TypeAliasTemplateDecl>(
18183 Val: TST->getTemplateName().getAsTemplateDecl())) {
18184 S.Diag(Loc, DiagID: diag::err_dependent_friend_not_member_of_template_spec)
18185 << NNS;
18186 return;
18187 }
18188 }
18189
18190 if (NNS.getAsRecordDecl()) {
18191 S.Diag(Loc, DiagID: diag::err_dependent_friend_not_member_of_template_spec) << NNS;
18192 } else {
18193 S.Diag(Loc, DiagID: diag::err_dependent_friend_not_member);
18194 }
18195}
18196
18197bool Sema::CheckDependentFriend(SourceLocation Loc,
18198 NestedNameSpecifierLoc NNSLoc,
18199 ArrayRef<TemplateParameterList *> TPLs,
18200 bool IsInstantiation) {
18201 NestedNameSpecifier NNS = NNSLoc.getNestedNameSpecifier();
18202 if (!NNS.isDependent() && !IsInstantiation)
18203 return false;
18204
18205 assert(NNS.getKind() == NestedNameSpecifier::Kind::Type &&
18206 "nested-name-specifier of dependent friend must be a type");
18207
18208 QualType T(NNS.getAsType(), 0);
18209 if (DiagnosePackIndexingInFriendNNS(Loc, NNSLoc))
18210 return true;
18211
18212 const TemplateSpecializationType *TST =
18213 GetClassTemplateSpecializationType(Context, T);
18214 if (!TST) {
18215 DiagnoseDependentFriendNotMember(S&: *this, Loc, NNS);
18216 return true;
18217 }
18218
18219 if (TPLs.empty())
18220 return false;
18221
18222 SmallVector<NamedDecl *, 4> UndeducedParameters;
18223 for (TemplateParameterList *Params : TPLs) {
18224 llvm::SmallBitVector UsedParameters(Params->size());
18225 MarkUsedTemplateParameters(TemplateArgs: TST->template_arguments(),
18226 /*OnlyDeduced=*/true, Depth: Params->getDepth(),
18227 Used&: UsedParameters);
18228
18229 for (unsigned I = 0, N = UsedParameters.size(); I != N; ++I)
18230 if (!UsedParameters[I])
18231 UndeducedParameters.push_back(Elt: Params->getParam(Idx: I));
18232 }
18233
18234 if (UndeducedParameters.empty())
18235 return false;
18236
18237 Diag(Loc, DiagID: diag::err_dependent_friend_undeduced_params)
18238 << (UndeducedParameters.size() > 1) << QualType(TST, 0);
18239
18240 for (NamedDecl *Param : UndeducedParameters) {
18241 if (Param->getDeclName())
18242 Diag(Loc: Param->getLocation(), DiagID: diag::note_non_deducible_parameter)
18243 << Param->getDeclName();
18244 else
18245 Diag(Loc: Param->getLocation(), DiagID: diag::note_non_deducible_parameter)
18246 << "(anonymous)";
18247 }
18248
18249 return true;
18250}
18251
18252DeclResult Sema::ActOnTemplatedFriendTag(
18253 Scope *S, SourceLocation FriendLoc, unsigned TagSpec, SourceLocation TagLoc,
18254 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
18255 SourceLocation EllipsisLoc, const ParsedAttributesView &Attr,
18256 MultiTemplateParamsArg TempParamLists, TemplateIdAnnotation *TemplateId) {
18257 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
18258
18259 bool IsMemberSpecialization = false;
18260 bool Invalid = false;
18261
18262 TemplateParameterList *TemplateParams =
18263 MatchTemplateParametersToScopeSpecifier(DeclStartLoc: TagLoc, DeclLoc: NameLoc, SS, TemplateId,
18264 ParamLists: TempParamLists, /*friend*/ IsFriend: true,
18265 IsMemberSpecialization, Invalid);
18266 if (TemplateId) {
18267 if (Invalid)
18268 return true;
18269
18270 if (TemplateParams) {
18271 Diag(Loc: NameLoc, DiagID: diag::err_not_class_template_specialization) << 0;
18272 return true;
18273 }
18274 }
18275
18276 if (TemplateParams) {
18277 if (TemplateParams->size() > 0) {
18278 if (Invalid)
18279 return true;
18280
18281 if (SS.isEmpty() || !SS.getScopeRep().isDependent()) {
18282 DeclResult Result = CheckClassTemplate(
18283 S, TagSpec, TUK: TagUseKind::Friend, KWLoc: TagLoc, SS, Name, NameLoc, Attr,
18284 TemplateParams, AS: AS_public, /*ModulePrivateLoc=*/SourceLocation(),
18285 FriendLoc, NumOuterTemplateParamLists: TempParamLists.size() - 1, OuterTemplateParamLists: TempParamLists.data(),
18286 IsMemberSpecialization);
18287 return Result.get();
18288 }
18289 } else {
18290 // The "template<>" header is extraneous.
18291 Diag(Loc: TemplateParams->getTemplateLoc(), DiagID: diag::err_template_tag_noparams)
18292 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
18293 }
18294 }
18295
18296 if (Invalid)
18297 return true;
18298
18299 bool IsAllExplicitSpecializations =
18300 llvm::all_of(Range&: TempParamLists, P: [](const TemplateParameterList *List) {
18301 return List->size() == 0;
18302 });
18303
18304 // FIXME: don't ignore attributes.
18305
18306 // If it's explicit specializations all the way down, just forget
18307 // about the template header and build an appropriate non-templated
18308 // friend. TODO: for source fidelity, remember the headers.
18309 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
18310 if (!TemplateId && IsAllExplicitSpecializations) {
18311 if (SS.isEmpty()) {
18312 bool Owned = false;
18313 bool IsDependent = false;
18314 return ActOnTag(S, TagSpec, TUK: TagUseKind::Friend, KWLoc: TagLoc, SS, Name, NameLoc,
18315 Attr, AS: AS_public,
18316 /*ModulePrivateLoc=*/SourceLocation(),
18317 TemplateParameterLists: MultiTemplateParamsArg(), OwnedDecl&: Owned, IsDependent,
18318 /*ScopedEnumKWLoc=*/SourceLocation(),
18319 /*ScopedEnumUsesClassTag=*/false,
18320 /*UnderlyingType=*/TypeResult(),
18321 /*IsTypeSpecifier=*/false,
18322 /*IsTemplateParamOrArg=*/false,
18323 /*OOK=*/OffsetOfKind::Outside);
18324 }
18325
18326 TypeSourceInfo *TSI = nullptr;
18327 ElaboratedTypeKeyword Keyword =
18328 TypeWithKeyword::getKeywordForTagTypeKind(Tag: Kind);
18329 QualType T = CheckTypenameType(Keyword, KeywordLoc: TagLoc, QualifierLoc, II: *Name,
18330 IILoc: NameLoc, TSI: &TSI, /*DeducedTSTContext=*/true);
18331 if (T.isNull())
18332 return true;
18333
18334 FriendDecl *Friend = FriendDecl::Create(C&: Context, DC: CurContext, L: NameLoc, Friend: TSI,
18335 FriendL: FriendLoc, EllipsisLoc);
18336 Friend->setAccess(AS_public);
18337 CurContext->addDecl(D: Friend);
18338 return Friend;
18339 }
18340
18341 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
18342
18343 ArrayRef<TemplateParameterList *> TPLs = TempParamLists;
18344 if (TemplateParams)
18345 TPLs = TPLs.drop_back();
18346 if (CheckDependentFriend(Loc: TagLoc, NNSLoc: QualifierLoc, TPLs,
18347 /*IsInstantiation=*/false))
18348 return true;
18349
18350 TypeSourceInfo *TSI = nullptr;
18351 if (TemplateId) {
18352 ASTTemplateArgsPtr ParsedArgs(TemplateId->getTemplateArgs(),
18353 TemplateId->NumArgs);
18354 TypeResult ParsedType = ActOnTagTemplateIdType(
18355 TUK: TagUseKind::Friend, TagSpec: static_cast<TypeSpecifierType>(TagSpec), TagLoc, SS,
18356 TemplateKWLoc: TemplateId->TemplateKWLoc, TemplateD: TemplateId->Template, TemplateLoc: NameLoc,
18357 LAngleLoc: TemplateId->LAngleLoc, TemplateArgsIn: ParsedArgs, RAngleLoc: TemplateId->RAngleLoc);
18358 if (ParsedType.isInvalid())
18359 return true;
18360
18361 GetTypeFromParser(Ty: ParsedType.get(), TInfo: &TSI);
18362 } else {
18363 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Tag: Kind);
18364 QualType T = Context.getDependentNameType(Keyword: ETK, NNS: SS.getScopeRep(), Name);
18365 TSI = Context.CreateTypeSourceInfo(T);
18366
18367 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
18368 TL.setElaboratedKeywordLoc(TagLoc);
18369 TL.setQualifierLoc(QualifierLoc);
18370 TL.setNameLoc(NameLoc);
18371 }
18372
18373 SmallVector<UnexpandedParameterPack, 1> Unexpanded;
18374 collectUnexpandedParameterPacks(TL: TSI->getTypeLoc(), Unexpanded);
18375 if (EllipsisLoc.isInvalid()) {
18376 if (DiagnoseUnexpandedParameterPack(Loc: TagLoc, T: TSI, UPPC: UPPC_FriendDeclaration))
18377 return true;
18378 } else if (Unexpanded.empty()) {
18379 Diag(Loc: EllipsisLoc, DiagID: diag::err_pack_expansion_without_parameter_packs)
18380 << TSI->getTypeLoc().getSourceRange();
18381 return true;
18382 } else {
18383 // CWG 2917: a pack expanded by a friend-type-specifier cannot have been
18384 // introduced by the template-declaration containing that specifier.
18385 if (!TempParamLists.empty()) {
18386 unsigned FriendDeclDepth = TempParamLists.front()->getDepth();
18387 for (UnexpandedParameterPack &U : Unexpanded) {
18388 if (std::optional<std::pair<unsigned, unsigned>> DI =
18389 getDepthAndIndex(UPP: U);
18390 DI && DI->first >= FriendDeclDepth) {
18391 auto *ND = dyn_cast<NamedDecl *>(Val&: U.first);
18392 if (!ND)
18393 ND = cast<const TemplateTypeParmType *>(Val&: U.first)->getDecl();
18394 Diag(Loc: U.second, DiagID: diag::friend_template_decl_malformed_pack_expansion)
18395 << ND->getDeclName()
18396 << SourceRange(TSI->getTypeLoc().getBeginLoc(), EllipsisLoc);
18397 return true;
18398 }
18399 }
18400 }
18401 }
18402
18403 FriendDecl *Friend;
18404 if (TempParamLists.empty())
18405 Friend = FriendDecl::Create(C&: Context, DC: CurContext, L: NameLoc, Friend: TSI, FriendL: FriendLoc,
18406 EllipsisLoc);
18407 else {
18408 if (CheckTemplateDeclScope(S, TemplateParams: TempParamLists.back()))
18409 return true;
18410
18411 TemplateName FriendTemplate;
18412 if (TemplateParams)
18413 FriendTemplate = Context.getDependentTemplateName(
18414 Name: {SS.getScopeRep(), Name, /*HasTemplateKeyword=*/false});
18415 Friend =
18416 FriendTemplateDecl::Create(Context, DC: CurContext, Loc: NameLoc, Friend: TSI, FriendLoc,
18417 FriendTPLists: TempParamLists, EllipsisLoc, Template: FriendTemplate);
18418 }
18419
18420 Friend->setAccess(AS_public);
18421 CurContext->addDecl(D: Friend);
18422
18423 return Friend;
18424}
18425
18426Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
18427 MultiTemplateParamsArg TempParams,
18428 SourceLocation EllipsisLoc) {
18429 SourceLocation Loc = DS.getBeginLoc();
18430 SourceLocation FriendLoc = DS.getFriendSpecLoc();
18431
18432 assert(DS.isFriendSpecified());
18433 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
18434
18435 // C++ [class.friend]p3:
18436 // A friend declaration that does not declare a function shall have one of
18437 // the following forms:
18438 // friend elaborated-type-specifier ;
18439 // friend simple-type-specifier ;
18440 // friend typename-specifier ;
18441 //
18442 // If the friend keyword isn't first, or if the declarations has any type
18443 // qualifiers, then the declaration doesn't have that form.
18444 if (getLangOpts().CPlusPlus11 && !DS.isFriendSpecifiedFirst())
18445 Diag(Loc: FriendLoc, DiagID: diag::err_friend_not_first_in_declaration);
18446 if (DS.getTypeQualifiers()) {
18447 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
18448 Diag(Loc: DS.getConstSpecLoc(), DiagID: diag::err_friend_decl_spec) << "const";
18449 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
18450 Diag(Loc: DS.getVolatileSpecLoc(), DiagID: diag::err_friend_decl_spec) << "volatile";
18451 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
18452 Diag(Loc: DS.getRestrictSpecLoc(), DiagID: diag::err_friend_decl_spec) << "restrict";
18453 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
18454 Diag(Loc: DS.getAtomicSpecLoc(), DiagID: diag::err_friend_decl_spec) << "_Atomic";
18455 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
18456 Diag(Loc: DS.getUnalignedSpecLoc(), DiagID: diag::err_friend_decl_spec) << "__unaligned";
18457 }
18458
18459 // Try to convert the decl specifier to a type. This works for
18460 // friend templates because ActOnTag never produces a ClassTemplateDecl
18461 // for a TagUseKind::Friend.
18462 Declarator TheDeclarator(DS, ParsedAttributesView::none(),
18463 DeclaratorContext::Member);
18464 TypeSourceInfo *TSI = GetTypeForDeclarator(D&: TheDeclarator);
18465 QualType T = TSI->getType();
18466 if (TheDeclarator.isInvalidType())
18467 return nullptr;
18468
18469 // If '...' is present, the type must contain an unexpanded parameter
18470 // pack, and vice versa.
18471 bool Invalid = false;
18472 if (EllipsisLoc.isInvalid() &&
18473 DiagnoseUnexpandedParameterPack(Loc, T: TSI, UPPC: UPPC_FriendDeclaration))
18474 return nullptr;
18475 if (EllipsisLoc.isValid() &&
18476 !TSI->getType()->containsUnexpandedParameterPack()) {
18477 Diag(Loc: EllipsisLoc, DiagID: diag::err_pack_expansion_without_parameter_packs)
18478 << TSI->getTypeLoc().getSourceRange();
18479 Invalid = true;
18480 }
18481
18482 if (!T->isElaboratedTypeSpecifier()) {
18483 if (TempParams.size()) {
18484 // C++23 [dcl.pre]p5:
18485 // In a simple-declaration, the optional init-declarator-list can be
18486 // omitted only when declaring a class or enumeration, that is, when
18487 // the decl-specifier-seq contains either a class-specifier, an
18488 // elaborated-type-specifier with a class-key, or an enum-specifier.
18489 //
18490 // The declaration of a template-declaration or explicit-specialization
18491 // is never a member-declaration, so this must be a simple-declaration
18492 // with no init-declarator-list. Therefore, this is ill-formed.
18493 Diag(Loc, DiagID: diag::err_tagless_friend_type_template) << DS.getSourceRange();
18494 return nullptr;
18495 } else if (const RecordDecl *RD = T->getAsRecordDecl()) {
18496 SmallString<16> InsertionText(" ");
18497 InsertionText += RD->getKindName();
18498
18499 Diag(Loc, DiagID: getLangOpts().CPlusPlus11
18500 ? diag::warn_cxx98_compat_unelaborated_friend_type
18501 : diag::ext_unelaborated_friend_type)
18502 << (unsigned)RD->getTagKind() << T
18503 << FixItHint::CreateInsertion(InsertionLoc: getLocForEndOfToken(Loc: FriendLoc),
18504 Code: InsertionText);
18505 } else {
18506 DiagCompat(Loc: FriendLoc, CompatDiagId: diag_compat::nonclass_type_friend)
18507 << T << DS.getSourceRange();
18508 }
18509 }
18510
18511 // C++98 [class.friend]p1: A friend of a class is a function
18512 // or class that is not a member of the class . . .
18513 // This is fixed in DR77, which just barely didn't make the C++03
18514 // deadline. It's also a very silly restriction that seriously
18515 // affects inner classes and which nobody else seems to implement;
18516 // thus we never diagnose it, not even in -pedantic.
18517 //
18518 // But note that we could warn about it: it's always useless to
18519 // friend one of your own members (it's not, however, worthless to
18520 // friend a member of an arbitrary specialization of your template).
18521
18522 Decl *D;
18523 if (!TempParams.empty()) {
18524 if (CheckTemplateDeclScope(S, TemplateParams: TempParams.back()))
18525 return nullptr;
18526
18527 // TODO: Support variadic friend template decls?
18528 D = FriendTemplateDecl::Create(Context, DC: CurContext, Loc, Friend: TSI, FriendLoc,
18529 FriendTPLists: TempParams, EllipsisLoc);
18530 } else
18531 D = FriendDecl::Create(C&: Context, DC: CurContext, L: TSI->getTypeLoc().getBeginLoc(),
18532 Friend: TSI, FriendL: FriendLoc, EllipsisLoc);
18533
18534 if (!D)
18535 return nullptr;
18536
18537 D->setAccess(AS_public);
18538 CurContext->addDecl(D);
18539
18540 if (Invalid)
18541 D->setInvalidDecl();
18542
18543 return D;
18544}
18545
18546NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
18547 MultiTemplateParamsArg TemplateParams) {
18548 const DeclSpec &DS = D.getDeclSpec();
18549
18550 assert(DS.isFriendSpecified());
18551 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
18552
18553 SourceLocation Loc = D.getIdentifierLoc();
18554 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
18555
18556 // C++ [class.friend]p1
18557 // A friend of a class is a function or class....
18558 // Note that this sees through typedefs, which is intended.
18559 // It *doesn't* see through dependent types, which is correct
18560 // according to [temp.arg.type]p3:
18561 // If a declaration acquires a function type through a
18562 // type dependent on a template-parameter and this causes
18563 // a declaration that does not use the syntactic form of a
18564 // function declarator to have a function type, the program
18565 // is ill-formed.
18566 if (!TInfo->getType()->isFunctionType()) {
18567 Diag(Loc, DiagID: diag::err_unexpected_friend);
18568
18569 // It might be worthwhile to try to recover by creating an
18570 // appropriate declaration.
18571 return nullptr;
18572 }
18573
18574 // C++ [namespace.memdef]p3
18575 // - If a friend declaration in a non-local class first declares a
18576 // class or function, the friend class or function is a member
18577 // of the innermost enclosing namespace.
18578 // - The name of the friend is not found by simple name lookup
18579 // until a matching declaration is provided in that namespace
18580 // scope (either before or after the class declaration granting
18581 // friendship).
18582 // - If a friend function is called, its name may be found by the
18583 // name lookup that considers functions from namespaces and
18584 // classes associated with the types of the function arguments.
18585 // - When looking for a prior declaration of a class or a function
18586 // declared as a friend, scopes outside the innermost enclosing
18587 // namespace scope are not considered.
18588
18589 CXXScopeSpec &SS = D.getCXXScopeSpec();
18590 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
18591 assert(NameInfo.getName());
18592
18593 if (SS.isValid() && DiagnosePackIndexingInFriendNNS(
18594 Loc: NameInfo.getLoc(), NNSLoc: SS.getWithLocInContext(Context)))
18595 return nullptr;
18596
18597 // Check for unexpanded parameter packs.
18598 if (DiagnoseUnexpandedParameterPack(Loc, T: TInfo, UPPC: UPPC_FriendDeclaration) ||
18599 DiagnoseUnexpandedParameterPack(NameInfo, UPPC: UPPC_FriendDeclaration) ||
18600 DiagnoseUnexpandedParameterPack(SS, UPPC: UPPC_FriendDeclaration))
18601 return nullptr;
18602
18603 bool isTemplateId = D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
18604
18605 if (D.isFunctionDefinition() && SS.isNotEmpty() && !isTemplateId) {
18606 auto Kind = SS.getScopeRep().getKind();
18607 bool IsNamespaceOrGlobal = Kind == NestedNameSpecifier::Kind::Global ||
18608 Kind == NestedNameSpecifier::Kind::Namespace;
18609 if (IsNamespaceOrGlobal) {
18610 Diag(Loc: SS.getRange().getBegin(), DiagID: diag::err_qualified_friend_def)
18611 << SS.getScopeRep();
18612 SS.clear();
18613 }
18614 }
18615
18616 // The context we found the declaration in, or in which we should
18617 // create the declaration.
18618 DeclContext *DC;
18619 Scope *DCScope = S;
18620 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
18621 RedeclarationKind::ForExternalRedeclaration);
18622
18623 // There are five cases here.
18624 // - There's no scope specifier and we're in a local class. Only look
18625 // for functions declared in the immediately-enclosing block scope.
18626 // We recover from invalid scope qualifiers as if they just weren't there.
18627 FunctionDecl *FunctionContainingLocalClass = nullptr;
18628 if ((SS.isInvalid() || !SS.isSet()) &&
18629 (FunctionContainingLocalClass =
18630 cast<CXXRecordDecl>(Val: CurContext)->isLocalClass())) {
18631 // C++11 [class.friend]p11:
18632 // If a friend declaration appears in a local class and the name
18633 // specified is an unqualified name, a prior declaration is
18634 // looked up without considering scopes that are outside the
18635 // innermost enclosing non-class scope. For a friend function
18636 // declaration, if there is no prior declaration, the program is
18637 // ill-formed.
18638
18639 // Find the innermost enclosing non-class scope. This is the block
18640 // scope containing the local class definition (or for a nested class,
18641 // the outer local class).
18642 DCScope = S->getFnParent();
18643
18644 // Look up the function name in the scope.
18645 Previous.clear(Kind: LookupLocalFriendName);
18646 LookupName(R&: Previous, S, /*AllowBuiltinCreation*/false);
18647
18648 if (!Previous.empty()) {
18649 // All possible previous declarations must have the same context:
18650 // either they were declared at block scope or they are members of
18651 // one of the enclosing local classes.
18652 DC = Previous.getRepresentativeDecl()->getDeclContext();
18653 } else {
18654 // This is ill-formed, but provide the context that we would have
18655 // declared the function in, if we were permitted to, for error recovery.
18656 DC = FunctionContainingLocalClass;
18657 }
18658 adjustContextForLocalExternDecl(DC);
18659
18660 // - There's no scope specifier, in which case we just go to the
18661 // appropriate scope and look for a function or function template
18662 // there as appropriate.
18663 } else if (SS.isInvalid() || !SS.isSet()) {
18664 // C++11 [namespace.memdef]p3:
18665 // If the name in a friend declaration is neither qualified nor
18666 // a template-id and the declaration is a function or an
18667 // elaborated-type-specifier, the lookup to determine whether
18668 // the entity has been previously declared shall not consider
18669 // any scopes outside the innermost enclosing namespace.
18670
18671 // Find the appropriate context according to the above.
18672 DC = CurContext;
18673
18674 // Skip class contexts. If someone can cite chapter and verse
18675 // for this behavior, that would be nice --- it's what GCC and
18676 // EDG do, and it seems like a reasonable intent, but the spec
18677 // really only says that checks for unqualified existing
18678 // declarations should stop at the nearest enclosing namespace,
18679 // not that they should only consider the nearest enclosing
18680 // namespace.
18681 while (DC->isRecord())
18682 DC = DC->getParent();
18683
18684 DeclContext *LookupDC = DC->getNonTransparentContext();
18685 while (true) {
18686 LookupQualifiedName(R&: Previous, LookupCtx: LookupDC);
18687
18688 if (!Previous.empty()) {
18689 DC = LookupDC;
18690 break;
18691 }
18692
18693 if (isTemplateId) {
18694 if (isa<TranslationUnitDecl>(Val: LookupDC)) break;
18695 } else {
18696 if (LookupDC->isFileContext()) break;
18697 }
18698 LookupDC = LookupDC->getParent();
18699 }
18700
18701 DCScope = getScopeForDeclContext(S, DC);
18702
18703 // - There's a non-dependent scope specifier, in which case we
18704 // compute it and do a previous lookup there for a function
18705 // or function template.
18706 } else if (!SS.getScopeRep().isDependent()) {
18707 DC = computeDeclContext(SS);
18708 if (!DC) return nullptr;
18709
18710 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
18711
18712 LookupQualifiedName(R&: Previous, LookupCtx: DC);
18713
18714 // C++ [class.friend]p1: A friend of a class is a function or
18715 // class that is not a member of the class . . .
18716 if (DC->Equals(DC: CurContext))
18717 Diag(Loc: DS.getFriendSpecLoc(),
18718 DiagID: getLangOpts().CPlusPlus11 ?
18719 diag::warn_cxx98_compat_friend_is_member :
18720 diag::err_friend_is_member);
18721
18722 // - There's a dependent scope specifier, in which case we use an
18723 // arbitrary context and wait for instantiation.
18724 } else {
18725 DC = CurContext;
18726 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
18727 }
18728
18729 if (!DC->isRecord()) {
18730 int DiagArg = -1;
18731 switch (D.getName().getKind()) {
18732 case UnqualifiedIdKind::IK_ConstructorTemplateId:
18733 case UnqualifiedIdKind::IK_ConstructorName:
18734 DiagArg = 0;
18735 break;
18736 case UnqualifiedIdKind::IK_DestructorName:
18737 DiagArg = 1;
18738 break;
18739 case UnqualifiedIdKind::IK_ConversionFunctionId:
18740 DiagArg = 2;
18741 break;
18742 case UnqualifiedIdKind::IK_DeductionGuideName:
18743 DiagArg = 3;
18744 break;
18745 case UnqualifiedIdKind::IK_Identifier:
18746 case UnqualifiedIdKind::IK_ImplicitSelfParam:
18747 case UnqualifiedIdKind::IK_LiteralOperatorId:
18748 case UnqualifiedIdKind::IK_OperatorFunctionId:
18749 case UnqualifiedIdKind::IK_TemplateId:
18750 break;
18751 }
18752 // This implies that it has to be an operator or function.
18753 if (DiagArg >= 0) {
18754 Diag(Loc, DiagID: diag::err_introducing_special_friend) << DiagArg;
18755 return nullptr;
18756 }
18757 } else {
18758 CXXRecordDecl *RC = dyn_cast<CXXRecordDecl>(Val: DC);
18759 if (RC->isLambda()) {
18760 Diag(Loc: NameInfo.getBeginLoc(), DiagID: diag::err_friend_lambda_decl);
18761 }
18762 }
18763
18764 // FIXME: This is an egregious hack to cope with cases where the scope stack
18765 // does not contain the declaration context, i.e., in an out-of-line
18766 // definition of a class.
18767 Scope FakeDCScope(S, Scope::DeclScope, Diags);
18768 if (!DCScope) {
18769 FakeDCScope.setEntity(DC);
18770 DCScope = &FakeDCScope;
18771 }
18772
18773 bool AddToScope = true;
18774 NamedDecl *ND = ActOnFunctionDeclarator(S: DCScope, D, DC, TInfo, Previous,
18775 TemplateParamLists: TemplateParams, AddToScope);
18776 if (!ND) return nullptr;
18777
18778 assert(ND->getLexicalDeclContext() == CurContext);
18779
18780 // If we performed typo correction, we might have added a scope specifier
18781 // and changed the decl context.
18782 DC = ND->getDeclContext();
18783
18784 // Add the function declaration to the appropriate lookup tables,
18785 // adjusting the redeclarations list as necessary. We don't
18786 // want to do this yet if the friending class is dependent.
18787 //
18788 // Also update the scope-based lookup if the target context's
18789 // lookup context is in lexical scope.
18790 if (!CurContext->isDependentContext()) {
18791 DC = DC->getRedeclContext();
18792 DC->makeDeclVisibleInContext(D: ND);
18793 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
18794 PushOnScopeChains(D: ND, S: EnclosingScope, /*AddToContext=*/ false);
18795 }
18796
18797 warnOnReservedIdentifier(D: ND);
18798
18799 if (ND->isInvalidDecl()) {
18800 FriendDecl *Friend = FriendDecl::Create(
18801 C&: Context, DC: CurContext, L: D.getIdentifierLoc(), Friend: ND, FriendL: DS.getFriendSpecLoc());
18802 Friend->setAccess(AS_public);
18803 if (!isa<FunctionTemplateDecl>(Val: ND))
18804 Friend->setInvalidDecl();
18805 CurContext->addDecl(D: Friend);
18806 return ND;
18807 }
18808
18809 FunctionDecl *FD = ND->getAsFunction();
18810 assert(FD && "Expected a function declaration!");
18811
18812 ArrayRef<TemplateParameterList *> TPLs = FD->getTemplateParameterLists();
18813 if (!TPLs.empty() && SS.isValid() && CheckTemplateDeclScope(S, TemplateParams: TPLs.back()))
18814 return nullptr;
18815
18816 FriendDecl *Friend;
18817 if (!TPLs.empty() && SS.isValid())
18818 Friend =
18819 FriendTemplateDecl::Create(Context, DC: CurContext, Loc: D.getIdentifierLoc(),
18820 Friend: ND, FriendLoc: DS.getFriendSpecLoc(), FriendTPLists: TPLs);
18821 else
18822 Friend = FriendDecl::Create(C&: Context, DC: CurContext, L: D.getIdentifierLoc(), Friend: ND,
18823 FriendL: DS.getFriendSpecLoc());
18824
18825 Friend->setAccess(AS_public);
18826 CurContext->addDecl(D: Friend);
18827
18828 if (DC->isRecord())
18829 CheckFriendAccess(D: ND);
18830
18831 if (!TemplateParams.empty() && SS.isValid() &&
18832 CheckDependentFriend(Loc: NameInfo.getLoc(), NNSLoc: SS.getWithLocInContext(Context),
18833 TPLs: FD->getTemplateParameterLists(),
18834 /*IsInstantiation=*/false))
18835 return ND;
18836
18837 // C++ [class.friend]p6:
18838 // A function may be defined in a friend declaration of a class if and
18839 // only if the class is a non-local class, and the function name is
18840 // unqualified.
18841 if (D.isFunctionDefinition()) {
18842 // Qualified friend function definition.
18843 if (SS.isNotEmpty()) {
18844 SemaDiagnosticBuilder DB =
18845 Diag(Loc: SS.getRange().getBegin(), DiagID: diag::err_qualified_friend_def);
18846
18847 DB << SS.getScopeRep();
18848
18849 // Friend function defined in a local class.
18850 } else if (FunctionContainingLocalClass) {
18851 Diag(Loc: NameInfo.getBeginLoc(), DiagID: diag::err_friend_def_in_local_class);
18852
18853 // Per [basic.pre]p4, a template-id is not a name. Therefore, if we have
18854 // a template-id, the function name is not unqualified because these is
18855 // no name. While the wording requires some reading in-between the
18856 // lines, GCC, MSVC, and EDG all consider a friend function
18857 // specialization definitions to be de facto explicit specialization
18858 // and diagnose them as such.
18859 } else if (isTemplateId) {
18860 Diag(Loc: NameInfo.getBeginLoc(), DiagID: diag::err_friend_specialization_def);
18861 }
18862 }
18863
18864 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
18865 // default argument expression, that declaration shall be a definition
18866 // and shall be the only declaration of the function or function
18867 // template in the translation unit.
18868 if (functionDeclHasDefaultArgument(FD)) {
18869 // We can't look at FD->getPreviousDecl() because it may not have been set
18870 // if we're in a dependent context. If the function is known to be a
18871 // redeclaration, we will have narrowed Previous down to the right decl.
18872 if (D.isRedeclaration()) {
18873 Diag(Loc: FD->getLocation(), DiagID: diag::err_friend_decl_with_def_arg_redeclared);
18874 Diag(Loc: Previous.getRepresentativeDecl()->getLocation(),
18875 DiagID: diag::note_previous_declaration);
18876 } else if (!D.isFunctionDefinition())
18877 Diag(Loc: FD->getLocation(), DiagID: diag::err_friend_decl_with_def_arg_must_be_def);
18878 }
18879
18880 return ND;
18881}
18882
18883void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc,
18884 StringLiteral *Message) {
18885 AdjustDeclIfTemplate(Decl&: Dcl);
18886
18887 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Val: Dcl);
18888 if (!Fn) {
18889 Diag(Loc: DelLoc, DiagID: diag::err_deleted_non_function);
18890 return;
18891 }
18892
18893 // Deleted function does not have a body.
18894 Fn->setWillHaveBody(false);
18895
18896 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
18897 // Don't consider the implicit declaration we generate for explicit
18898 // specializations. FIXME: Do not generate these implicit declarations.
18899 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
18900 Prev->getPreviousDecl()) &&
18901 !Prev->isDefined()) {
18902 Diag(Loc: DelLoc, DiagID: diag::err_deleted_decl_not_first);
18903 Diag(Loc: Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
18904 DiagID: Prev->isImplicit() ? diag::note_previous_implicit_declaration
18905 : diag::note_previous_declaration);
18906 // We can't recover from this; the declaration might have already
18907 // been used.
18908 Fn->setInvalidDecl();
18909 return;
18910 }
18911
18912 // To maintain the invariant that functions are only deleted on their first
18913 // declaration, mark the implicitly-instantiated declaration of the
18914 // explicitly-specialized function as deleted instead of marking the
18915 // instantiated redeclaration.
18916 Fn = Fn->getCanonicalDecl();
18917 }
18918
18919 // dllimport/dllexport cannot be deleted.
18920 if (const InheritableAttr *DLLAttr = getDLLAttr(D: Fn)) {
18921 Diag(Loc: Fn->getLocation(), DiagID: diag::err_attribute_dll_deleted) << DLLAttr;
18922 Fn->setInvalidDecl();
18923 }
18924
18925 // C++11 [basic.start.main]p3:
18926 // A program that defines main as deleted [...] is ill-formed.
18927 if (Fn->isMain())
18928 Diag(Loc: DelLoc, DiagID: diag::err_deleted_main);
18929
18930 // C++11 [dcl.fct.def.delete]p4:
18931 // A deleted function is implicitly inline.
18932 Fn->setImplicitlyInline();
18933 Fn->setDeletedAsWritten(D: true, Message);
18934}
18935
18936void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
18937 if (!Dcl || Dcl->isInvalidDecl())
18938 return;
18939
18940 auto *FD = dyn_cast<FunctionDecl>(Val: Dcl);
18941 if (!FD) {
18942 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Val: Dcl)) {
18943 if (FTD->getTemplatedDecl()->getDefaultedFunctionKind().isComparison()) {
18944 Diag(Loc: DefaultLoc, DiagID: diag::err_defaulted_comparison_template);
18945 return;
18946 }
18947 }
18948
18949 Diag(Loc: DefaultLoc, DiagID: diag::err_default_special_members)
18950 << getLangOpts().CPlusPlus20;
18951 return;
18952 }
18953
18954 // Reject if this can't possibly be a defaultable function.
18955 FunctionDecl::DefaultedFunctionKind DefKind = FD->getDefaultedFunctionKind();
18956 if (!DefKind &&
18957 // A dependent function that doesn't locally look defaultable can
18958 // still instantiate to a defaultable function if it's a constructor
18959 // or assignment operator.
18960 (!FD->isDependentContext() ||
18961 (!isa<CXXConstructorDecl>(Val: FD) &&
18962 FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) {
18963 Diag(Loc: DefaultLoc, DiagID: diag::err_default_special_members)
18964 << getLangOpts().CPlusPlus20;
18965 return;
18966 }
18967
18968 // Issue compatibility warning. We already warned if the operator is
18969 // 'operator<=>' when parsing the '<=>' token.
18970 if (DefKind.isComparison() &&
18971 DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) {
18972 Diag(Loc: DefaultLoc, DiagID: getLangOpts().CPlusPlus20
18973 ? diag::warn_cxx17_compat_defaulted_comparison
18974 : diag::ext_defaulted_comparison);
18975 }
18976
18977 FD->setDefaulted();
18978 FD->setExplicitlyDefaulted();
18979 FD->setDefaultLoc(DefaultLoc);
18980
18981 // Defer checking functions that are defaulted in a dependent context.
18982 if (FD->isDependentContext())
18983 return;
18984
18985 // Unset that we will have a body for this function. We might not,
18986 // if it turns out to be trivial, and we don't need this marking now
18987 // that we've marked it as defaulted.
18988 FD->setWillHaveBody(false);
18989
18990 if (DefKind.isComparison()) {
18991 // If this comparison's defaulting occurs within the definition of its
18992 // lexical class context, we have to do the checking when complete.
18993 if (auto const *RD = dyn_cast<CXXRecordDecl>(Val: FD->getLexicalDeclContext()))
18994 if (!RD->isCompleteDefinition())
18995 return;
18996 }
18997
18998 // If this member fn was defaulted on its first declaration, we will have
18999 // already performed the checking in CheckCompletedCXXClass. Such a
19000 // declaration doesn't trigger an implicit definition.
19001 if (isa<CXXMethodDecl>(Val: FD)) {
19002 const FunctionDecl *Primary = FD;
19003 if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
19004 // Ask the template instantiation pattern that actually had the
19005 // '= default' on it.
19006 Primary = Pattern;
19007 if (Primary->getCanonicalDecl()->isDefaulted())
19008 return;
19009 }
19010
19011 // Only allocate DefaultedOrDeletedFunctionInfo if we actually have
19012 // non-default FP features to stash. This avoids memory overhead for
19013 // the vast majority of defaulted functions.
19014 if (!FD->getDefaultedOrDeletedInfo() &&
19015 CurFPFeatureOverrides().requiresTrailingStorage()) {
19016 FD->setDefaultedOrDeletedInfo(
19017 FunctionDecl::DefaultedOrDeletedFunctionInfo::Create(
19018 Context, /*Lookups=*/{}, FPFeatures: CurFPFeatureOverrides()));
19019 }
19020
19021 if (DefKind.isComparison()) {
19022 if (CheckExplicitlyDefaultedComparison(S: nullptr, FD, DCK: DefKind.asComparison()))
19023 FD->setInvalidDecl();
19024 else
19025 DefineDefaultedComparison(UseLoc: DefaultLoc, FD, DCK: DefKind.asComparison());
19026 } else {
19027 auto *MD = cast<CXXMethodDecl>(Val: FD);
19028
19029 if (CheckExplicitlyDefaultedSpecialMember(MD, CSM: DefKind.asSpecialMember(),
19030 DefaultLoc))
19031 MD->setInvalidDecl();
19032 else
19033 DefineDefaultedFunction(S&: *this, FD: MD, DefaultLoc);
19034 }
19035}
19036
19037static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
19038 for (Stmt *SubStmt : S->children()) {
19039 if (!SubStmt)
19040 continue;
19041 if (isa<ReturnStmt>(Val: SubStmt))
19042 Self.Diag(Loc: SubStmt->getBeginLoc(),
19043 DiagID: diag::err_return_in_constructor_handler);
19044 if (!isa<Expr>(Val: SubStmt))
19045 SearchForReturnInStmt(Self, S: SubStmt);
19046 }
19047}
19048
19049void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
19050 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
19051 CXXCatchStmt *Handler = TryBlock->getHandler(i: I);
19052 SearchForReturnInStmt(Self&: *this, S: Handler);
19053 }
19054}
19055
19056void Sema::SetFunctionBodyKind(Decl *D, SourceLocation Loc, FnBodyKind BodyKind,
19057 StringLiteral *DeletedMessage) {
19058 switch (BodyKind) {
19059 case FnBodyKind::Delete:
19060 SetDeclDeleted(Dcl: D, DelLoc: Loc, Message: DeletedMessage);
19061 break;
19062 case FnBodyKind::Default:
19063 SetDeclDefaulted(Dcl: D, DefaultLoc: Loc);
19064 break;
19065 case FnBodyKind::Other:
19066 llvm_unreachable(
19067 "Parsed function body should be '= delete;' or '= default;'");
19068 }
19069}
19070
19071bool Sema::CheckOverridingFunctionAttributes(CXXMethodDecl *New,
19072 const CXXMethodDecl *Old) {
19073 const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
19074 const auto *OldFT = Old->getType()->castAs<FunctionProtoType>();
19075
19076 if (OldFT->hasExtParameterInfos()) {
19077 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
19078 // A parameter of the overriding method should be annotated with noescape
19079 // if the corresponding parameter of the overridden method is annotated.
19080 if (OldFT->getExtParameterInfo(I).isNoEscape() &&
19081 !NewFT->getExtParameterInfo(I).isNoEscape()) {
19082 Diag(Loc: New->getParamDecl(i: I)->getLocation(),
19083 DiagID: diag::warn_overriding_method_missing_noescape);
19084 Diag(Loc: Old->getParamDecl(i: I)->getLocation(),
19085 DiagID: diag::note_overridden_marked_noescape);
19086 }
19087 }
19088
19089 // SME attributes must match when overriding a function declaration.
19090 if (IsInvalidSMECallConversion(FromType: Old->getType(), ToType: New->getType())) {
19091 Diag(Loc: New->getLocation(), DiagID: diag::err_conflicting_overriding_attributes)
19092 << New << New->getType() << Old->getType();
19093 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function);
19094 return true;
19095 }
19096
19097 // Virtual overrides must have the same code_seg.
19098 const auto *OldCSA = Old->getAttr<CodeSegAttr>();
19099 const auto *NewCSA = New->getAttr<CodeSegAttr>();
19100 if ((NewCSA || OldCSA) &&
19101 (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
19102 Diag(Loc: New->getLocation(), DiagID: diag::err_mismatched_code_seg_override);
19103 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
19104 return true;
19105 }
19106
19107 // Virtual overrides: check for matching effects.
19108 if (Context.hasAnyFunctionEffects()) {
19109 const auto OldFX = Old->getFunctionEffects();
19110 const auto NewFXOrig = New->getFunctionEffects();
19111
19112 if (OldFX != NewFXOrig) {
19113 FunctionEffectSet NewFX(NewFXOrig);
19114 const auto Diffs = FunctionEffectDiffVector(OldFX, NewFX);
19115 FunctionEffectSet::Conflicts Errs;
19116 for (const auto &Diff : Diffs) {
19117 switch (Diff.shouldDiagnoseMethodOverride(OldMethod: *Old, OldFX, NewMethod: *New, NewFX)) {
19118 case FunctionEffectDiff::OverrideResult::NoAction:
19119 break;
19120 case FunctionEffectDiff::OverrideResult::Warn:
19121 Diag(Loc: New->getLocation(), DiagID: diag::warn_conflicting_func_effect_override)
19122 << Diff.effectName();
19123 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function)
19124 << Old->getReturnTypeSourceRange();
19125 break;
19126 case FunctionEffectDiff::OverrideResult::Merge: {
19127 NewFX.insert(NewEC: Diff.Old.value(), Errs);
19128 const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
19129 FunctionProtoType::ExtProtoInfo EPI = NewFT->getExtProtoInfo();
19130 EPI.FunctionEffects = FunctionEffectsRef(NewFX);
19131 QualType ModQT = Context.getFunctionType(ResultTy: NewFT->getReturnType(),
19132 Args: NewFT->getParamTypes(), EPI);
19133 New->setType(ModQT);
19134 if (Errs.empty()) {
19135 // A warning here is somewhat pedantic. Skip this if there was
19136 // already a merge conflict, which is more serious.
19137 Diag(Loc: New->getLocation(), DiagID: diag::warn_mismatched_func_effect_override)
19138 << Diff.effectName();
19139 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function)
19140 << Old->getReturnTypeSourceRange();
19141 }
19142 break;
19143 }
19144 }
19145 }
19146 if (!Errs.empty())
19147 diagnoseFunctionEffectMergeConflicts(Errs, NewLoc: New->getLocation(),
19148 OldLoc: Old->getLocation());
19149 }
19150 }
19151
19152 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
19153
19154 // If the calling conventions match, everything is fine
19155 if (NewCC == OldCC)
19156 return false;
19157
19158 // If the calling conventions mismatch because the new function is static,
19159 // suppress the calling convention mismatch error; the error about static
19160 // function override (err_static_overrides_virtual from
19161 // Sema::CheckFunctionDeclaration) is more clear.
19162 if (New->getStorageClass() == SC_Static)
19163 return false;
19164
19165 Diag(Loc: New->getLocation(),
19166 DiagID: diag::err_conflicting_overriding_cc_attributes)
19167 << New->getDeclName() << New->getType() << Old->getType();
19168 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function);
19169 return true;
19170}
19171
19172bool Sema::CheckExplicitObjectOverride(CXXMethodDecl *New,
19173 const CXXMethodDecl *Old) {
19174 // CWG2553
19175 // A virtual function shall not be an explicit object member function.
19176 if (!New->isExplicitObjectMemberFunction())
19177 return true;
19178 Diag(Loc: New->getParamDecl(i: 0)->getBeginLoc(),
19179 DiagID: diag::err_explicit_object_parameter_nonmember)
19180 << New->getSourceRange() << /*virtual*/ 1 << /*IsLambda*/ false;
19181 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function);
19182 New->setInvalidDecl();
19183 return false;
19184}
19185
19186bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
19187 const CXXMethodDecl *Old) {
19188 QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType();
19189 QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType();
19190
19191 if (Context.hasSameType(T1: NewTy, T2: OldTy) ||
19192 NewTy->isDependentType() || OldTy->isDependentType())
19193 return false;
19194
19195 // Check if the return types are covariant
19196 QualType NewClassTy, OldClassTy;
19197
19198 /// Both types must be pointers or references to classes.
19199 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
19200 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
19201 NewClassTy = NewPT->getPointeeType();
19202 OldClassTy = OldPT->getPointeeType();
19203 }
19204 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
19205 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
19206 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
19207 NewClassTy = NewRT->getPointeeType();
19208 OldClassTy = OldRT->getPointeeType();
19209 }
19210 }
19211 }
19212
19213 // The return types aren't either both pointers or references to a class type.
19214 if (NewClassTy.isNull() || !NewClassTy->isStructureOrClassType()) {
19215 Diag(Loc: New->getLocation(),
19216 DiagID: diag::err_different_return_type_for_overriding_virtual_function)
19217 << New->getDeclName() << NewTy << OldTy
19218 << New->getReturnTypeSourceRange();
19219 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function)
19220 << Old->getReturnTypeSourceRange();
19221
19222 return true;
19223 }
19224
19225 if (!Context.hasSameUnqualifiedType(T1: NewClassTy, T2: OldClassTy)) {
19226 // C++14 [class.virtual]p8:
19227 // If the class type in the covariant return type of D::f differs from
19228 // that of B::f, the class type in the return type of D::f shall be
19229 // complete at the point of declaration of D::f or shall be the class
19230 // type D.
19231 if (const auto *RD = NewClassTy->getAsCXXRecordDecl()) {
19232 if (!RD->isBeingDefined() &&
19233 RequireCompleteType(Loc: New->getLocation(), T: NewClassTy,
19234 DiagID: diag::err_covariant_return_incomplete,
19235 Args: New->getDeclName()))
19236 return true;
19237 }
19238
19239 // Check if the new class derives from the old class.
19240 if (!IsDerivedFrom(Loc: New->getLocation(), Derived: NewClassTy, Base: OldClassTy)) {
19241 Diag(Loc: New->getLocation(), DiagID: diag::err_covariant_return_not_derived)
19242 << New->getDeclName() << NewTy << OldTy
19243 << New->getReturnTypeSourceRange();
19244 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function)
19245 << Old->getReturnTypeSourceRange();
19246 return true;
19247 }
19248
19249 // Check if we the conversion from derived to base is valid.
19250 if (CheckDerivedToBaseConversion(
19251 Derived: NewClassTy, Base: OldClassTy,
19252 InaccessibleBaseID: diag::err_covariant_return_inaccessible_base,
19253 AmbiguousBaseConvID: diag::err_covariant_return_ambiguous_derived_to_base_conv,
19254 Loc: New->getLocation(), Range: New->getReturnTypeSourceRange(),
19255 Name: New->getDeclName(), BasePath: nullptr)) {
19256 // FIXME: this note won't trigger for delayed access control
19257 // diagnostics, and it's impossible to get an undelayed error
19258 // here from access control during the original parse because
19259 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
19260 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function)
19261 << Old->getReturnTypeSourceRange();
19262 return true;
19263 }
19264 }
19265
19266 // The qualifiers of the return types must be the same.
19267 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
19268 Diag(Loc: New->getLocation(),
19269 DiagID: diag::err_covariant_return_type_different_qualifications)
19270 << New->getDeclName() << NewTy << OldTy
19271 << New->getReturnTypeSourceRange();
19272 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function)
19273 << Old->getReturnTypeSourceRange();
19274 return true;
19275 }
19276
19277
19278 // The new class type must have the same or less qualifiers as the old type.
19279 if (!OldClassTy.isAtLeastAsQualifiedAs(other: NewClassTy, Ctx: getASTContext())) {
19280 Diag(Loc: New->getLocation(),
19281 DiagID: diag::err_covariant_return_type_class_type_not_same_or_less_qualified)
19282 << New->getDeclName() << NewTy << OldTy
19283 << New->getReturnTypeSourceRange();
19284 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function)
19285 << Old->getReturnTypeSourceRange();
19286 return true;
19287 }
19288
19289 return false;
19290}
19291
19292bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
19293 SourceLocation EndLoc = InitRange.getEnd();
19294 if (EndLoc.isValid())
19295 Method->setRangeEnd(EndLoc);
19296
19297 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
19298 Method->setIsPureVirtual();
19299 return false;
19300 }
19301
19302 if (!Method->isInvalidDecl())
19303 Diag(Loc: Method->getLocation(), DiagID: diag::err_non_virtual_pure)
19304 << Method->getDeclName() << InitRange;
19305 return true;
19306}
19307
19308void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
19309 if (D->getFriendObjectKind())
19310 Diag(Loc: D->getLocation(), DiagID: diag::err_pure_friend);
19311 else if (auto *M = dyn_cast<CXXMethodDecl>(Val: D))
19312 CheckPureMethod(Method: M, InitRange: ZeroLoc);
19313 else
19314 Diag(Loc: D->getLocation(), DiagID: diag::err_illegal_initializer);
19315}
19316
19317/// Invoked when we are about to parse an initializer for the declaration
19318/// 'Dcl'.
19319///
19320/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
19321/// static data member of class X, names should be looked up in the scope of
19322/// class X. If the declaration had a scope specifier, a scope will have
19323/// been created and passed in for this purpose. Otherwise, S will be null.
19324void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
19325 assert(D && !D->isInvalidDecl());
19326
19327 // We will always have a nested name specifier here, but this declaration
19328 // might not be out of line if the specifier names the current namespace:
19329 // extern int n;
19330 // int ::n = 0;
19331 if (S && D->isOutOfLine())
19332 EnterDeclaratorContext(S, DC: D->getDeclContext());
19333
19334 PushExpressionEvaluationContext(
19335 NewContext: ExpressionEvaluationContext::PotentiallyEvaluated, LambdaContextDecl: D,
19336 Type: ExpressionEvaluationContextRecord::EK_VariableInit);
19337}
19338
19339void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
19340 assert(D);
19341
19342 if (S && D->isOutOfLine())
19343 ExitDeclaratorContext(S);
19344
19345 PopExpressionEvaluationContext();
19346}
19347
19348DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
19349 // C++ 6.4p2:
19350 // The declarator shall not specify a function or an array.
19351 // The type-specifier-seq shall not contain typedef and shall not declare a
19352 // new class or enumeration.
19353 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
19354 "Parser allowed 'typedef' as storage class of condition decl.");
19355
19356 Decl *Dcl = ActOnDeclarator(S, D);
19357 if (!Dcl)
19358 return true;
19359
19360 if (isa<FunctionDecl>(Val: Dcl)) { // The declarator shall not specify a function.
19361 Diag(Loc: Dcl->getLocation(), DiagID: diag::err_invalid_use_of_function_type)
19362 << D.getSourceRange();
19363 return true;
19364 }
19365
19366 if (auto *VD = dyn_cast<VarDecl>(Val: Dcl))
19367 VD->setCXXCondDecl();
19368
19369 return Dcl;
19370}
19371
19372void Sema::LoadExternalVTableUses() {
19373 if (!ExternalSource)
19374 return;
19375
19376 SmallVector<ExternalVTableUse, 4> VTables;
19377 ExternalSource->ReadUsedVTables(VTables);
19378 SmallVector<VTableUse, 4> NewUses;
19379 for (const ExternalVTableUse &VTable : VTables) {
19380 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos =
19381 VTablesUsed.find(Val: VTable.Record);
19382 // Even if a definition wasn't required before, it may be required now.
19383 if (Pos != VTablesUsed.end()) {
19384 if (!Pos->second && VTable.DefinitionRequired)
19385 Pos->second = true;
19386 continue;
19387 }
19388
19389 VTablesUsed[VTable.Record] = VTable.DefinitionRequired;
19390 NewUses.push_back(Elt: VTableUse(VTable.Record, VTable.Location));
19391 }
19392
19393 VTableUses.insert(I: VTableUses.begin(), From: NewUses.begin(), To: NewUses.end());
19394}
19395
19396void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
19397 bool DefinitionRequired) {
19398 // Ignore any vtable uses in unevaluated operands or for classes that do
19399 // not have a vtable.
19400 if (!Class->isDynamicClass() || Class->isDependentContext() ||
19401 CurContext->isDependentContext() || isUnevaluatedContext())
19402 return;
19403 // Do not mark as used if compiling for the device outside of the target
19404 // region.
19405 if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice &&
19406 !OpenMP().isInOpenMPDeclareTargetContext() &&
19407 !OpenMP().isInOpenMPTargetExecutionDirective()) {
19408 if (!DefinitionRequired)
19409 MarkVirtualMembersReferenced(Loc, RD: Class);
19410 return;
19411 }
19412
19413 // Try to insert this class into the map.
19414 LoadExternalVTableUses();
19415 Class = Class->getCanonicalDecl();
19416 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
19417 Pos = VTablesUsed.insert(KV: std::make_pair(x&: Class, y&: DefinitionRequired));
19418 if (!Pos.second) {
19419 // If we already had an entry, check to see if we are promoting this vtable
19420 // to require a definition. If so, we need to reappend to the VTableUses
19421 // list, since we may have already processed the first entry.
19422 if (DefinitionRequired && !Pos.first->second) {
19423 Pos.first->second = true;
19424 } else {
19425 // Otherwise, we can early exit.
19426 return;
19427 }
19428 } else {
19429 // The Microsoft ABI requires that we perform the destructor body
19430 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
19431 // the deleting destructor is emitted with the vtable, not with the
19432 // destructor definition as in the Itanium ABI.
19433 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
19434 CXXDestructorDecl *DD = Class->getDestructor();
19435 if (DD && DD->isVirtual() && !DD->isDeleted()) {
19436 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
19437 // If this is an out-of-line declaration, marking it referenced will
19438 // not do anything. Manually call CheckDestructor to look up operator
19439 // delete().
19440 ContextRAII SavedContext(*this, DD);
19441 CheckDestructor(Destructor: DD);
19442 if (!DD->getOperatorDelete())
19443 DD->setInvalidDecl();
19444 } else {
19445 MarkFunctionReferenced(Loc, Func: Class->getDestructor());
19446 }
19447 }
19448 }
19449 }
19450
19451 // Local classes need to have their virtual members marked
19452 // immediately. For all other classes, we mark their virtual members
19453 // at the end of the translation unit.
19454 if (Class->isLocalClass())
19455 MarkVirtualMembersReferenced(Loc, RD: Class->getDefinition());
19456 else
19457 VTableUses.push_back(Elt: std::make_pair(x&: Class, y&: Loc));
19458}
19459
19460bool Sema::DefineUsedVTables() {
19461 LoadExternalVTableUses();
19462 if (VTableUses.empty())
19463 return false;
19464
19465 // Note: The VTableUses vector could grow as a result of marking
19466 // the members of a class as "used", so we check the size each
19467 // time through the loop and prefer indices (which are stable) to
19468 // iterators (which are not).
19469 bool DefinedAnything = false;
19470 for (unsigned I = 0; I != VTableUses.size(); ++I) {
19471 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
19472 if (!Class)
19473 continue;
19474 TemplateSpecializationKind ClassTSK =
19475 Class->getTemplateSpecializationKind();
19476
19477 SourceLocation Loc = VTableUses[I].second;
19478
19479 bool DefineVTable = true;
19480
19481 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(RD: Class);
19482 // V-tables for non-template classes with an owning module are always
19483 // uniquely emitted in that module.
19484 if (Class->isInCurrentModuleUnit()) {
19485 DefineVTable = true;
19486 } else if (KeyFunction && !KeyFunction->hasBody()) {
19487 // If this class has a key function, but that key function is
19488 // defined in another translation unit, we don't need to emit the
19489 // vtable even though we're using it.
19490 // The key function is in another translation unit.
19491 DefineVTable = false;
19492 TemplateSpecializationKind TSK =
19493 KeyFunction->getTemplateSpecializationKind();
19494 assert(TSK != TSK_ExplicitInstantiationDefinition &&
19495 TSK != TSK_ImplicitInstantiation &&
19496 "Instantiations don't have key functions");
19497 (void)TSK;
19498 } else if (!KeyFunction) {
19499 // If we have a class with no key function that is the subject
19500 // of an explicit instantiation declaration, suppress the
19501 // vtable; it will live with the explicit instantiation
19502 // definition.
19503 bool IsExplicitInstantiationDeclaration =
19504 ClassTSK == TSK_ExplicitInstantiationDeclaration;
19505 for (auto *R : Class->redecls()) {
19506 TemplateSpecializationKind TSK
19507 = cast<CXXRecordDecl>(Val: R)->getTemplateSpecializationKind();
19508 if (TSK == TSK_ExplicitInstantiationDeclaration)
19509 IsExplicitInstantiationDeclaration = true;
19510 else if (TSK == TSK_ExplicitInstantiationDefinition) {
19511 IsExplicitInstantiationDeclaration = false;
19512 break;
19513 }
19514 }
19515
19516 if (IsExplicitInstantiationDeclaration) {
19517 const bool HasExcludeFromExplicitInstantiation =
19518 llvm::any_of(Range: Class->methods(), P: [](CXXMethodDecl *method) {
19519 // If the class has a member function declared with
19520 // `__attribute__((exclude_from_explicit_instantiation))`, the
19521 // explicit instantiation declaration should not suppress emitting
19522 // the vtable, since the corresponding explicit instantiation
19523 // definition might not emit the vtable if a triggering method is
19524 // excluded.
19525 return method->hasAttr<ExcludeFromExplicitInstantiationAttr>();
19526 });
19527 if (!HasExcludeFromExplicitInstantiation)
19528 DefineVTable = false;
19529 }
19530 }
19531
19532 // The exception specifications for all virtual members may be needed even
19533 // if we are not providing an authoritative form of the vtable in this TU.
19534 // We may choose to emit it available_externally anyway.
19535 if (!DefineVTable) {
19536 MarkVirtualMemberExceptionSpecsNeeded(Loc, RD: Class);
19537 continue;
19538 }
19539
19540 // Mark all of the virtual members of this class as referenced, so
19541 // that we can build a vtable. Then, tell the AST consumer that a
19542 // vtable for this class is required.
19543 DefinedAnything = true;
19544 MarkVirtualMembersReferenced(Loc, RD: Class);
19545 CXXRecordDecl *Canonical = Class->getCanonicalDecl();
19546 // The vtable is assumed to be emitted in an external source only for
19547 // classes attached to a named module, which is guaranteed to have an object
19548 // file. This isn't true for -fmodules-debuginfo, which still has
19549 // shouldEmitInExternalSource as true so that debug info gets supressed.
19550 if (VTablesUsed[Canonical] &&
19551 !(Class->isInNamedModule() && Class->shouldEmitInExternalSource()))
19552 Consumer.HandleVTable(RD: Class);
19553
19554 // Warn if we're emitting a weak vtable. The vtable will be weak if there is
19555 // no key function or the key function is inlined. Don't warn in C++ ABIs
19556 // that lack key functions, since the user won't be able to make one.
19557 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
19558 Class->isExternallyVisible() &&
19559 !(Class->getOwningModule() &&
19560 Class->getOwningModule()->isInterfaceOrPartition()) &&
19561 ClassTSK != TSK_ImplicitInstantiation &&
19562 ClassTSK != TSK_ExplicitInstantiationDeclaration &&
19563 ClassTSK != TSK_ExplicitInstantiationDefinition) {
19564 const FunctionDecl *KeyFunctionDef = nullptr;
19565 if (!KeyFunction || (KeyFunction->hasBody(Definition&: KeyFunctionDef) &&
19566 KeyFunctionDef->isInlined()))
19567 Diag(Loc: Class->getLocation(), DiagID: diag::warn_weak_vtable) << Class;
19568 }
19569 }
19570 VTableUses.clear();
19571
19572 return DefinedAnything;
19573}
19574
19575void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
19576 const CXXRecordDecl *RD) {
19577 for (const auto *I : RD->methods())
19578 if (I->isVirtual() && !I->isPureVirtual())
19579 ResolveExceptionSpec(Loc, FPT: I->getType()->castAs<FunctionProtoType>());
19580}
19581
19582void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
19583 const CXXRecordDecl *RD,
19584 bool ConstexprOnly) {
19585 // Mark all functions which will appear in RD's vtable as used.
19586 CXXFinalOverriderMap FinalOverriders;
19587 RD->getFinalOverriders(FinaOverriders&: FinalOverriders);
19588 for (const auto &FinalOverrider : FinalOverriders) {
19589 for (const auto &OverridingMethod : FinalOverrider.second) {
19590 assert(OverridingMethod.second.size() > 0 && "no final overrider");
19591 CXXMethodDecl *Overrider = OverridingMethod.second.front().Method;
19592
19593 // C++ [basic.def.odr]p2:
19594 // [...] A virtual member function is used if it is not pure. [...]
19595 if (!Overrider->isPureVirtual() &&
19596 (!ConstexprOnly || Overrider->isConstexpr()))
19597 MarkFunctionReferenced(Loc, Func: Overrider);
19598 }
19599 }
19600
19601 // Only classes that have virtual bases need a VTT.
19602 if (RD->getNumVBases() == 0)
19603 return;
19604
19605 for (const auto &I : RD->bases()) {
19606 const auto *Base = I.getType()->castAsCXXRecordDecl();
19607 if (Base->getNumVBases() == 0)
19608 continue;
19609 MarkVirtualMembersReferenced(Loc, RD: Base);
19610 }
19611}
19612
19613static
19614void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
19615 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
19616 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
19617 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
19618 Sema &S) {
19619 if (Ctor->isInvalidDecl())
19620 return;
19621
19622 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
19623
19624 // Target may not be determinable yet, for instance if this is a dependent
19625 // call in an uninstantiated template.
19626 if (Target) {
19627 const FunctionDecl *FNTarget = nullptr;
19628 (void)Target->hasBody(Definition&: FNTarget);
19629 Target = const_cast<CXXConstructorDecl*>(
19630 cast_or_null<CXXConstructorDecl>(Val: FNTarget));
19631 }
19632
19633 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
19634 // Avoid dereferencing a null pointer here.
19635 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
19636
19637 if (!Current.insert(Ptr: Canonical).second)
19638 return;
19639
19640 // We know that beyond here, we aren't chaining into a cycle.
19641 if (!Target || !Target->isDelegatingConstructor() ||
19642 Target->isInvalidDecl() || Valid.count(Ptr: TCanonical)) {
19643 Valid.insert_range(R&: Current);
19644 Current.clear();
19645 // We've hit a cycle.
19646 } else if (TCanonical == Canonical || Invalid.count(Ptr: TCanonical) ||
19647 Current.count(Ptr: TCanonical)) {
19648 // If we haven't diagnosed this cycle yet, do so now.
19649 if (!Invalid.count(Ptr: TCanonical)) {
19650 S.Diag(Loc: (*Ctor->init_begin())->getSourceLocation(),
19651 DiagID: diag::warn_delegating_ctor_cycle)
19652 << Ctor;
19653
19654 // Don't add a note for a function delegating directly to itself.
19655 if (TCanonical != Canonical)
19656 S.Diag(Loc: Target->getLocation(), DiagID: diag::note_it_delegates_to);
19657
19658 CXXConstructorDecl *C = Target;
19659 while (C->getCanonicalDecl() != Canonical) {
19660 const FunctionDecl *FNTarget = nullptr;
19661 (void)C->getTargetConstructor()->hasBody(Definition&: FNTarget);
19662 assert(FNTarget && "Ctor cycle through bodiless function");
19663
19664 C = const_cast<CXXConstructorDecl*>(
19665 cast<CXXConstructorDecl>(Val: FNTarget));
19666 S.Diag(Loc: C->getLocation(), DiagID: diag::note_which_delegates_to);
19667 }
19668 }
19669
19670 Invalid.insert_range(R&: Current);
19671 Current.clear();
19672 } else {
19673 DelegatingCycleHelper(Ctor: Target, Valid, Invalid, Current, S);
19674 }
19675}
19676
19677
19678void Sema::CheckDelegatingCtorCycles() {
19679 llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
19680
19681 for (DelegatingCtorDeclsType::iterator
19682 I = DelegatingCtorDecls.begin(source: ExternalSource.get()),
19683 E = DelegatingCtorDecls.end();
19684 I != E; ++I)
19685 DelegatingCycleHelper(Ctor: *I, Valid, Invalid, Current, S&: *this);
19686
19687 for (CXXConstructorDecl *CI : Invalid)
19688 CI->setInvalidDecl();
19689}
19690
19691namespace {
19692 /// AST visitor that finds references to the 'this' expression.
19693class FindCXXThisExpr : public DynamicRecursiveASTVisitor {
19694 Sema &S;
19695
19696public:
19697 explicit FindCXXThisExpr(Sema &S) : S(S) {}
19698
19699 bool VisitCXXThisExpr(CXXThisExpr *E) override {
19700 S.Diag(Loc: E->getLocation(), DiagID: diag::err_this_static_member_func)
19701 << E->isImplicit();
19702 return false;
19703 }
19704};
19705}
19706
19707bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
19708 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
19709 if (!TSInfo)
19710 return false;
19711
19712 TypeLoc TL = TSInfo->getTypeLoc();
19713 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
19714 if (!ProtoTL)
19715 return false;
19716
19717 // C++11 [expr.prim.general]p3:
19718 // [The expression this] shall not appear before the optional
19719 // cv-qualifier-seq and it shall not appear within the declaration of a
19720 // static member function (although its type and value category are defined
19721 // within a static member function as they are within a non-static member
19722 // function). [ Note: this is because declaration matching does not occur
19723 // until the complete declarator is known. - end note ]
19724 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
19725 FindCXXThisExpr Finder(*this);
19726
19727 // If the return type came after the cv-qualifier-seq, check it now.
19728 if (Proto->hasTrailingReturn() &&
19729 !Finder.TraverseTypeLoc(TL: ProtoTL.getReturnLoc()))
19730 return true;
19731
19732 // Check the exception specification.
19733 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
19734 return true;
19735
19736 // Check the trailing requires clause
19737 if (const AssociatedConstraint &TRC = Method->getTrailingRequiresClause())
19738 if (!Finder.TraverseStmt(S: const_cast<Expr *>(TRC.ConstraintExpr)))
19739 return true;
19740
19741 return checkThisInStaticMemberFunctionAttributes(Method);
19742}
19743
19744bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
19745 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
19746 if (!TSInfo)
19747 return false;
19748
19749 TypeLoc TL = TSInfo->getTypeLoc();
19750 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
19751 if (!ProtoTL)
19752 return false;
19753
19754 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
19755 FindCXXThisExpr Finder(*this);
19756
19757 switch (Proto->getExceptionSpecType()) {
19758 case EST_Unparsed:
19759 case EST_Uninstantiated:
19760 case EST_Unevaluated:
19761 case EST_BasicNoexcept:
19762 case EST_NoThrow:
19763 case EST_DynamicNone:
19764 case EST_MSAny:
19765 case EST_None:
19766 break;
19767
19768 case EST_DependentNoexcept:
19769 case EST_NoexceptFalse:
19770 case EST_NoexceptTrue:
19771 if (!Finder.TraverseStmt(S: Proto->getNoexceptExpr()))
19772 return true;
19773 [[fallthrough]];
19774
19775 case EST_Dynamic:
19776 for (const auto &E : Proto->exceptions()) {
19777 if (!Finder.TraverseType(T: E))
19778 return true;
19779 }
19780 break;
19781 }
19782
19783 return false;
19784}
19785
19786bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
19787 FindCXXThisExpr Finder(*this);
19788
19789 // Check attributes.
19790 for (const auto *A : Method->attrs()) {
19791 // FIXME: This should be emitted by tblgen.
19792 Expr *Arg = nullptr;
19793 ArrayRef<Expr *> Args;
19794 if (const auto *G = dyn_cast<GuardedByAttr>(Val: A))
19795 Args = llvm::ArrayRef(G->args_begin(), G->args_size());
19796 else if (const auto *G = dyn_cast<PtGuardedByAttr>(Val: A))
19797 Args = llvm::ArrayRef(G->args_begin(), G->args_size());
19798 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(Val: A))
19799 Args = llvm::ArrayRef(AA->args_begin(), AA->args_size());
19800 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(Val: A))
19801 Args = llvm::ArrayRef(AB->args_begin(), AB->args_size());
19802 else if (const auto *LR = dyn_cast<LockReturnedAttr>(Val: A))
19803 Arg = LR->getArg();
19804 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(Val: A))
19805 Args = llvm::ArrayRef(LE->args_begin(), LE->args_size());
19806 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(Val: A))
19807 Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());
19808 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(Val: A))
19809 Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());
19810 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(Val: A)) {
19811 Arg = AC->getSuccessValue();
19812 Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());
19813 } else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(Val: A))
19814 Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());
19815
19816 if (Arg && !Finder.TraverseStmt(S: Arg))
19817 return true;
19818
19819 for (Expr *A : Args) {
19820 if (!Finder.TraverseStmt(S: A))
19821 return true;
19822 }
19823 }
19824
19825 return false;
19826}
19827
19828void Sema::checkExceptionSpecification(
19829 bool IsTopLevel, ExceptionSpecificationType EST,
19830 ArrayRef<ParsedType> DynamicExceptions,
19831 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
19832 SmallVectorImpl<QualType> &Exceptions,
19833 FunctionProtoType::ExceptionSpecInfo &ESI) {
19834 Exceptions.clear();
19835 ESI.Type = EST;
19836 if (EST == EST_Dynamic) {
19837 Exceptions.reserve(N: DynamicExceptions.size());
19838 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
19839 // FIXME: Preserve type source info.
19840 QualType ET = GetTypeFromParser(Ty: DynamicExceptions[ei]);
19841
19842 if (IsTopLevel) {
19843 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
19844 collectUnexpandedParameterPacks(T: ET, Unexpanded);
19845 if (!Unexpanded.empty()) {
19846 DiagnoseUnexpandedParameterPacks(
19847 Loc: DynamicExceptionRanges[ei].getBegin(), UPPC: UPPC_ExceptionType,
19848 Unexpanded);
19849 continue;
19850 }
19851 }
19852
19853 // Check that the type is valid for an exception spec, and
19854 // drop it if not.
19855 if (!CheckSpecifiedExceptionType(T&: ET, Range: DynamicExceptionRanges[ei]))
19856 Exceptions.push_back(Elt: ET);
19857 }
19858 ESI.Exceptions = Exceptions;
19859 return;
19860 }
19861
19862 if (isComputedNoexcept(ESpecType: EST)) {
19863 assert((NoexceptExpr->isTypeDependent() ||
19864 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
19865 Context.BoolTy) &&
19866 "Parser should have made sure that the expression is boolean");
19867 if (IsTopLevel && DiagnoseUnexpandedParameterPack(E: NoexceptExpr)) {
19868 ESI.Type = EST_BasicNoexcept;
19869 return;
19870 }
19871
19872 ESI.NoexceptExpr = NoexceptExpr;
19873 return;
19874 }
19875}
19876
19877void Sema::actOnDelayedExceptionSpecification(
19878 Decl *D, ExceptionSpecificationType EST, SourceRange SpecificationRange,
19879 ArrayRef<ParsedType> DynamicExceptions,
19880 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr) {
19881 if (!D)
19882 return;
19883
19884 // Dig out the function we're referring to.
19885 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(Val: D))
19886 D = FTD->getTemplatedDecl();
19887
19888 FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D);
19889 if (!FD)
19890 return;
19891
19892 // Check the exception specification.
19893 llvm::SmallVector<QualType, 4> Exceptions;
19894 FunctionProtoType::ExceptionSpecInfo ESI;
19895 checkExceptionSpecification(/*IsTopLevel=*/true, EST, DynamicExceptions,
19896 DynamicExceptionRanges, NoexceptExpr, Exceptions,
19897 ESI);
19898
19899 // Update the exception specification on the function type.
19900 Context.adjustExceptionSpec(FD, ESI, /*AsWritten=*/true);
19901
19902 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: D)) {
19903 if (MD->isStatic())
19904 checkThisInStaticMemberFunctionExceptionSpec(Method: MD);
19905
19906 if (MD->isVirtual()) {
19907 // Check overrides, which we previously had to delay.
19908 for (const CXXMethodDecl *O : MD->overridden_methods())
19909 CheckOverridingFunctionExceptionSpec(New: MD, Old: O);
19910 }
19911 }
19912}
19913
19914/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
19915///
19916MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
19917 SourceLocation DeclStart, Declarator &D,
19918 Expr *BitWidth,
19919 InClassInitStyle InitStyle,
19920 AccessSpecifier AS,
19921 const ParsedAttr &MSPropertyAttr) {
19922 const IdentifierInfo *II = D.getIdentifier();
19923 if (!II) {
19924 Diag(Loc: DeclStart, DiagID: diag::err_anonymous_property);
19925 return nullptr;
19926 }
19927 SourceLocation Loc = D.getIdentifierLoc();
19928
19929 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
19930 QualType T = TInfo->getType();
19931 if (getLangOpts().CPlusPlus) {
19932 CheckExtraCXXDefaultArguments(D);
19933
19934 if (DiagnoseUnexpandedParameterPack(Loc: D.getIdentifierLoc(), T: TInfo,
19935 UPPC: UPPC_DataMemberType)) {
19936 D.setInvalidType();
19937 T = Context.IntTy;
19938 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
19939 }
19940 }
19941
19942 DiagnoseFunctionSpecifiers(DS: D.getDeclSpec());
19943
19944 if (D.getDeclSpec().isInlineSpecified())
19945 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(), DiagID: diag::err_inline_non_function)
19946 << getLangOpts().CPlusPlus17;
19947 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
19948 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
19949 DiagID: diag::err_invalid_thread)
19950 << DeclSpec::getSpecifierName(S: TSCS);
19951
19952 // Check to see if this name was declared as a member previously
19953 NamedDecl *PrevDecl = nullptr;
19954 LookupResult Previous(*this, II, Loc, LookupMemberName,
19955 RedeclarationKind::ForVisibleRedeclaration);
19956 LookupName(R&: Previous, S);
19957 switch (Previous.getResultKind()) {
19958 case LookupResultKind::Found:
19959 case LookupResultKind::FoundUnresolvedValue:
19960 PrevDecl = Previous.getAsSingle<NamedDecl>();
19961 break;
19962
19963 case LookupResultKind::FoundOverloaded:
19964 PrevDecl = Previous.getRepresentativeDecl();
19965 break;
19966
19967 case LookupResultKind::NotFound:
19968 case LookupResultKind::NotFoundInCurrentInstantiation:
19969 case LookupResultKind::Ambiguous:
19970 break;
19971 }
19972
19973 if (PrevDecl && PrevDecl->isTemplateParameter()) {
19974 // Maybe we will complain about the shadowed template parameter.
19975 DiagnoseTemplateParameterShadow(Loc: D.getIdentifierLoc(), PrevDecl);
19976 // Just pretend that we didn't see the previous declaration.
19977 PrevDecl = nullptr;
19978 }
19979
19980 if (PrevDecl && !isDeclInScope(D: PrevDecl, Ctx: Record, S))
19981 PrevDecl = nullptr;
19982
19983 SourceLocation TSSL = D.getBeginLoc();
19984 MSPropertyDecl *NewPD =
19985 MSPropertyDecl::Create(C&: Context, DC: Record, L: Loc, N: II, T, TInfo, StartL: TSSL,
19986 Getter: MSPropertyAttr.getPropertyDataGetter(),
19987 Setter: MSPropertyAttr.getPropertyDataSetter());
19988 ProcessDeclAttributes(S: TUScope, D: NewPD, PD: D);
19989 NewPD->setAccess(AS);
19990
19991 if (NewPD->isInvalidDecl())
19992 Record->setInvalidDecl();
19993
19994 if (D.getDeclSpec().isModulePrivateSpecified())
19995 NewPD->setModulePrivate();
19996
19997 if (NewPD->isInvalidDecl() && PrevDecl) {
19998 // Don't introduce NewFD into scope; there's already something
19999 // with the same name in the same scope.
20000 } else if (II) {
20001 PushOnScopeChains(D: NewPD, S);
20002 } else
20003 Record->addDecl(D: NewPD);
20004
20005 return NewPD;
20006}
20007
20008void Sema::ActOnStartFunctionDeclarationDeclarator(
20009 Declarator &Declarator, unsigned TemplateParameterDepth) {
20010 auto &Info = InventedParameterInfos.emplace_back();
20011 TemplateParameterList *ExplicitParams = nullptr;
20012 ArrayRef<TemplateParameterList *> ExplicitLists =
20013 Declarator.getTemplateParameterLists();
20014 if (!ExplicitLists.empty()) {
20015 bool IsMemberSpecialization, IsInvalid;
20016 ExplicitParams = MatchTemplateParametersToScopeSpecifier(
20017 DeclStartLoc: Declarator.getBeginLoc(), DeclLoc: Declarator.getIdentifierLoc(),
20018 SS: Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr,
20019 ParamLists: ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, Invalid&: IsInvalid,
20020 /*SuppressDiagnostic=*/true);
20021 }
20022 // C++23 [dcl.fct]p23:
20023 // An abbreviated function template can have a template-head. The invented
20024 // template-parameters are appended to the template-parameter-list after
20025 // the explicitly declared template-parameters.
20026 //
20027 // A template-head must have one or more template-parameters (read:
20028 // 'template<>' is *not* a template-head). Only append the invented
20029 // template parameters if we matched the nested-name-specifier to a non-empty
20030 // TemplateParameterList.
20031 if (ExplicitParams && !ExplicitParams->empty()) {
20032 Info.AutoTemplateParameterDepth = ExplicitParams->getDepth();
20033 llvm::append_range(C&: Info.TemplateParams, R&: *ExplicitParams);
20034 Info.NumExplicitTemplateParams = ExplicitParams->size();
20035 } else {
20036 Info.AutoTemplateParameterDepth = TemplateParameterDepth;
20037 Info.NumExplicitTemplateParams = 0;
20038 }
20039}
20040
20041void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator &Declarator) {
20042 auto &FSI = InventedParameterInfos.back();
20043 if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) {
20044 if (FSI.NumExplicitTemplateParams != 0) {
20045 TemplateParameterList *ExplicitParams =
20046 Declarator.getTemplateParameterLists().back();
20047 Declarator.setInventedTemplateParameterList(
20048 TemplateParameterList::Create(
20049 C: Context, TemplateLoc: ExplicitParams->getTemplateLoc(),
20050 LAngleLoc: ExplicitParams->getLAngleLoc(), Params: FSI.TemplateParams,
20051 RAngleLoc: ExplicitParams->getRAngleLoc(),
20052 RequiresClause: ExplicitParams->getRequiresClause()));
20053 } else {
20054 Declarator.setInventedTemplateParameterList(TemplateParameterList::Create(
20055 C: Context, TemplateLoc: Declarator.getBeginLoc(), LAngleLoc: SourceLocation(),
20056 Params: FSI.TemplateParams, RAngleLoc: Declarator.getEndLoc(),
20057 /*RequiresClause=*/nullptr));
20058 }
20059 }
20060 InventedParameterInfos.pop_back();
20061}
20062
20063bool Sema::BuildCtorClosureDefaultArgs(SourceLocation Loc,
20064 CXXConstructorDecl *Ctor, bool IsCopy) {
20065 assert(Context.getTargetInfo().getCXXABI().isMicrosoft());
20066
20067 if (!Ctor->getCtorClosureDefaultArgs().empty()) {
20068 // If we build args for default constructor closures, those will have
20069 // been generated *before* building args for any copy constructor closures.
20070 assert(IsCopy || Ctor->getCtorClosureDefaultArgs()[0] != nullptr);
20071 return false;
20072 }
20073
20074 unsigned NumParams = Ctor->getNumParams();
20075 if (NumParams == 0)
20076 return false;
20077
20078 CXXDefaultArgExpr **Args =
20079 new (getASTContext()) CXXDefaultArgExpr *[NumParams];
20080
20081 if (IsCopy)
20082 Args[0] = nullptr; // Copy ctor closure will provide the first argument.
20083
20084 for (unsigned I = IsCopy ? 1 : 0; I != NumParams; ++I) {
20085 ExprResult R = BuildCXXDefaultArgExpr(CallLoc: Loc, FD: Ctor, Param: Ctor->getParamDecl(i: I));
20086 CleanupVarDeclMarking();
20087 if (R.isInvalid())
20088 return true;
20089 Args[I] = cast<CXXDefaultArgExpr>(Val: R.get());
20090 }
20091
20092 Ctor->setCtorClosureDefaultArgs(ArrayRef(Args, NumParams));
20093 return false;
20094}
20095