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()
644 ->getEnclosingNonExpansionStatementContext()
645 ->isDependentContext()) {
646 // C++ [dcl.fct.default]p6 (DR217):
647 // Default arguments for a member function of a class template shall
648 // be specified on the initial declaration of the member function
649 // within the class template.
650 //
651 // Reading the tea leaves a bit in DR217 and its reference to DR205
652 // leads me to the conclusion that one cannot add default function
653 // arguments for an out-of-line definition of a member function of a
654 // dependent type.
655 int WhichKind = 2;
656 if (CXXRecordDecl *Record
657 = dyn_cast<CXXRecordDecl>(Val: New->getDeclContext())) {
658 if (Record->getDescribedClassTemplate())
659 WhichKind = 0;
660 else if (isa<ClassTemplatePartialSpecializationDecl>(Val: Record))
661 WhichKind = 1;
662 else
663 WhichKind = 2;
664 }
665
666 Diag(Loc: NewParam->getLocation(),
667 DiagID: diag::err_param_default_argument_member_template_redecl)
668 << WhichKind
669 << NewParam->getDefaultArgRange();
670 }
671 }
672 }
673
674 // DR1344: If a default argument is added outside a class definition and that
675 // default argument makes the function a special member function, the program
676 // is ill-formed. This can only happen for constructors.
677 if (isa<CXXConstructorDecl>(Val: New) &&
678 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
679 CXXSpecialMemberKind NewSM =
680 cast<CXXMethodDecl>(Val: New)->getSpecialMemberKind(),
681 OldSM =
682 cast<CXXMethodDecl>(Val: Old)->getSpecialMemberKind();
683 if (NewSM != OldSM) {
684 auto It = llvm::find_if(Range: New->parameters(), P: [](const ParmVarDecl *P) {
685 return P->hasDefaultArg();
686 });
687 assert(It != New->param_end());
688 ParmVarDecl *NewParam = *It;
689 Diag(Loc: NewParam->getLocation(), DiagID: diag::err_default_arg_makes_ctor_special)
690 << NewParam->getDefaultArgRange() << NewSM;
691 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
692 }
693 }
694
695 const FunctionDecl *Def;
696 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
697 // template has a constexpr specifier then all its declarations shall
698 // contain the constexpr specifier.
699 if (New->getConstexprKind() != Old->getConstexprKind()) {
700 Diag(Loc: New->getLocation(), DiagID: diag::err_constexpr_redecl_mismatch)
701 << New << static_cast<int>(New->getConstexprKind())
702 << static_cast<int>(Old->getConstexprKind());
703 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
704 Invalid = true;
705 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
706 Old->isDefined(Definition&: Def) &&
707 // If a friend function is inlined but does not have 'inline'
708 // specifier, it is a definition. Do not report attribute conflict
709 // in this case, redefinition will be diagnosed later.
710 (New->isInlineSpecified() ||
711 New->getFriendObjectKind() == Decl::FOK_None)) {
712 // C++11 [dcl.fcn.spec]p4:
713 // If the definition of a function appears in a translation unit before its
714 // first declaration as inline, the program is ill-formed.
715 Diag(Loc: New->getLocation(), DiagID: diag::err_inline_decl_follows_def) << New;
716 Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
717 Invalid = true;
718 }
719
720 // C++17 [temp.deduct.guide]p3:
721 // Two deduction guide declarations in the same translation unit
722 // for the same class template shall not have equivalent
723 // parameter-declaration-clauses.
724 if (isa<CXXDeductionGuideDecl>(Val: New) &&
725 !New->isFunctionTemplateSpecialization() && isVisible(D: Old)) {
726 Diag(Loc: New->getLocation(), DiagID: diag::err_deduction_guide_redeclared);
727 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
728 }
729
730 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
731 // argument expression, that declaration shall be a definition and shall be
732 // the only declaration of the function or function template in the
733 // translation unit.
734 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
735 functionDeclHasDefaultArgument(FD: Old)) {
736 Diag(Loc: New->getLocation(), DiagID: diag::err_friend_decl_with_def_arg_redeclared);
737 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
738 Invalid = true;
739 }
740
741 // C++11 [temp.friend]p4 (DR329):
742 // When a function is defined in a friend function declaration in a class
743 // template, the function is instantiated when the function is odr-used.
744 // The same restrictions on multiple declarations and definitions that
745 // apply to non-template function declarations and definitions also apply
746 // to these implicit definitions.
747 const FunctionDecl *OldDefinition = nullptr;
748 if (New->isThisDeclarationInstantiatedFromAFriendDefinition() &&
749 Old->isDefined(Definition&: OldDefinition, CheckForPendingFriendDefinition: true))
750 CheckForFunctionRedefinition(FD: New, EffectiveDefinition: OldDefinition);
751
752 return Invalid;
753}
754
755void Sema::DiagPlaceholderVariableDefinition(SourceLocation Loc) {
756 DiagCompat(Loc, CompatDiagId: diag_compat::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::Typedef:
2080 case Decl::TypeAlias: {
2081 // - typedef declarations and alias-declarations that do not define
2082 // classes or enumerations,
2083 const auto *TN = cast<TypedefNameDecl>(Val: DclIt);
2084 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
2085 // Don't allow variably-modified types in constexpr functions.
2086 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2087 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
2088 SemaRef.Diag(Loc: TL.getBeginLoc(), DiagID: diag::err_constexpr_vla)
2089 << TL.getSourceRange() << TL.getType()
2090 << isa<CXXConstructorDecl>(Val: Dcl);
2091 }
2092 return false;
2093 }
2094 continue;
2095 }
2096
2097 case Decl::Enum:
2098 case Decl::CXXRecord:
2099 // C++1y allows types to be defined, not just declared.
2100 if (cast<TagDecl>(Val: DclIt)->isThisDeclarationADefinition()) {
2101 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2102 SemaRef.DiagCompat(Loc: DS->getBeginLoc(),
2103 CompatDiagId: diag_compat::constexpr_type_definition)
2104 << isa<CXXConstructorDecl>(Val: Dcl);
2105 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
2106 return false;
2107 }
2108 }
2109 continue;
2110
2111 case Decl::EnumConstant:
2112 case Decl::IndirectField:
2113 case Decl::ParmVar:
2114 // These can only appear with other declarations which are banned in
2115 // C++11 and permitted in C++1y, so ignore them.
2116 continue;
2117
2118 case Decl::Var:
2119 case Decl::Decomposition: {
2120 // C++1y [dcl.constexpr]p3 allows anything except:
2121 // a definition of a variable of non-literal type or of static or
2122 // thread storage duration or [before C++2a] for which no
2123 // initialization is performed.
2124 const auto *VD = cast<VarDecl>(Val: DclIt);
2125 if (VD->isThisDeclarationADefinition()) {
2126 if (VD->isStaticLocal()) {
2127 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2128 SemaRef.DiagCompat(Loc: VD->getLocation(),
2129 CompatDiagId: diag_compat::constexpr_static_var)
2130 << isa<CXXConstructorDecl>(Val: Dcl)
2131 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
2132 } else if (!SemaRef.getLangOpts().CPlusPlus23) {
2133 return false;
2134 }
2135 }
2136 if (SemaRef.LangOpts.CPlusPlus23) {
2137 CheckLiteralType(SemaRef, Kind, Loc: VD->getLocation(), T: VD->getType(),
2138 DiagID: diag::warn_cxx20_compat_constexpr_var,
2139 DiagArgs: isa<CXXConstructorDecl>(Val: Dcl));
2140 } else if (CheckLiteralType(
2141 SemaRef, Kind, Loc: VD->getLocation(), T: VD->getType(),
2142 DiagID: diag::err_constexpr_local_var_non_literal_type,
2143 DiagArgs: isa<CXXConstructorDecl>(Val: Dcl))) {
2144 return false;
2145 }
2146 if (!VD->getType()->isDependentType() &&
2147 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
2148 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2149 SemaRef.DiagCompat(Loc: VD->getLocation(),
2150 CompatDiagId: diag_compat::constexpr_local_var_no_init)
2151 << isa<CXXConstructorDecl>(Val: Dcl);
2152 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2153 return false;
2154 }
2155 continue;
2156 }
2157 }
2158 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2159 SemaRef.DiagCompat(Loc: VD->getLocation(), CompatDiagId: diag_compat::constexpr_local_var)
2160 << isa<CXXConstructorDecl>(Val: Dcl);
2161 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
2162 return false;
2163 }
2164 continue;
2165 }
2166
2167 case Decl::NamespaceAlias:
2168 case Decl::Function:
2169 // These are disallowed in C++11 and permitted in C++1y. Allow them
2170 // everywhere as an extension.
2171 if (!Cxx1yLoc.isValid())
2172 Cxx1yLoc = DS->getBeginLoc();
2173 continue;
2174
2175 default:
2176 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2177 SemaRef.Diag(Loc: DS->getBeginLoc(), DiagID: diag::err_constexpr_body_invalid_stmt)
2178 << isa<CXXConstructorDecl>(Val: Dcl) << Dcl->isConsteval();
2179 }
2180 return false;
2181 }
2182 }
2183
2184 return true;
2185}
2186
2187/// Check that the given field is initialized within a constexpr constructor.
2188///
2189/// \param Dcl The constexpr constructor being checked.
2190/// \param Field The field being checked. This may be a member of an anonymous
2191/// struct or union nested within the class being checked.
2192/// \param Inits All declarations, including anonymous struct/union members and
2193/// indirect members, for which any initialization was provided.
2194/// \param Diagnosed Whether we've emitted the error message yet. Used to attach
2195/// multiple notes for different members to the same error.
2196/// \param Kind Whether we're diagnosing a constructor as written or determining
2197/// whether the formal requirements are satisfied.
2198/// \return \c false if we're checking for validity and the constructor does
2199/// not satisfy the requirements on a constexpr constructor.
2200static bool CheckConstexprCtorInitializer(Sema &SemaRef,
2201 const FunctionDecl *Dcl,
2202 FieldDecl *Field,
2203 llvm::SmallPtrSet<Decl *, 16> &Inits,
2204 bool &Diagnosed,
2205 Sema::CheckConstexprKind Kind) {
2206 // In C++20 onwards, there's nothing to check for validity.
2207 if (Kind == Sema::CheckConstexprKind::CheckValid &&
2208 SemaRef.getLangOpts().CPlusPlus20)
2209 return true;
2210
2211 if (Field->isInvalidDecl())
2212 return true;
2213
2214 if (Field->isUnnamedBitField())
2215 return true;
2216
2217 // Anonymous unions with no variant members and empty anonymous structs do not
2218 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
2219 // indirect fields don't need initializing.
2220 if (Field->isAnonymousStructOrUnion() &&
2221 (Field->getType()->isUnionType()
2222 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
2223 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
2224 return true;
2225
2226 if (!Inits.count(Ptr: Field)) {
2227 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2228 if (!Diagnosed) {
2229 SemaRef.DiagCompat(Loc: Dcl->getLocation(),
2230 CompatDiagId: diag_compat::constexpr_ctor_missing_init);
2231 Diagnosed = true;
2232 }
2233 SemaRef.Diag(Loc: Field->getLocation(),
2234 DiagID: diag::note_constexpr_ctor_missing_init);
2235 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2236 return false;
2237 }
2238 } else if (Field->isAnonymousStructOrUnion()) {
2239 const auto *RD = Field->getType()->castAsRecordDecl();
2240 for (auto *I : RD->fields())
2241 // If an anonymous union contains an anonymous struct of which any member
2242 // is initialized, all members must be initialized.
2243 if (!RD->isUnion() || Inits.count(Ptr: I))
2244 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, Field: I, Inits, Diagnosed,
2245 Kind))
2246 return false;
2247 }
2248 return true;
2249}
2250
2251/// Check the provided statement is allowed in a constexpr function
2252/// definition.
2253static bool
2254CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
2255 SmallVectorImpl<SourceLocation> &ReturnStmts,
2256 SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
2257 SourceLocation &Cxx2bLoc,
2258 Sema::CheckConstexprKind Kind) {
2259 // - its function-body shall be [...] a compound-statement that contains only
2260 switch (S->getStmtClass()) {
2261 case Stmt::NullStmtClass:
2262 // - null statements,
2263 return true;
2264
2265 case Stmt::DeclStmtClass: {
2266 auto *DS = cast<DeclStmt>(Val: S);
2267
2268 // Expansion statement 'declarations' have substatements, so we need to
2269 // handle them separately.
2270 if (DS->isSingleDecl()) {
2271 if (auto *ESD = dyn_cast<CXXExpansionStmtDecl>(Val: DS->getSingleDecl())) {
2272 // Don't check unexpanded expansion statements.
2273 if (!ESD->getInstantiations())
2274 return true;
2275 for (auto *BodyIt : ESD->getInstantiations()->getInstantiations()) {
2276 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, S: BodyIt, ReturnStmts,
2277 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2278 return false;
2279 }
2280 return true;
2281 }
2282 }
2283
2284 // - static_assert-declarations
2285 // - using-declarations,
2286 // - using-directives,
2287 // - typedef declarations and alias-declarations that do not define
2288 // classes or enumerations,
2289 if (!CheckConstexprDeclStmt(SemaRef, Dcl, DS, Cxx1yLoc, Kind))
2290 return false;
2291 return true;
2292 }
2293
2294 case Stmt::ReturnStmtClass:
2295 // - and exactly one return statement;
2296 if (isa<CXXConstructorDecl>(Val: Dcl)) {
2297 // C++1y allows return statements in constexpr constructors.
2298 if (!Cxx1yLoc.isValid())
2299 Cxx1yLoc = S->getBeginLoc();
2300 return true;
2301 }
2302
2303 ReturnStmts.push_back(Elt: S->getBeginLoc());
2304 return true;
2305
2306 case Stmt::AttributedStmtClass:
2307 // Attributes on a statement don't affect its formal kind and hence don't
2308 // affect its validity in a constexpr function.
2309 return CheckConstexprFunctionStmt(
2310 SemaRef, Dcl, S: cast<AttributedStmt>(Val: S)->getSubStmt(), ReturnStmts,
2311 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind);
2312
2313 case Stmt::CompoundStmtClass: {
2314 // C++1y allows compound-statements.
2315 if (!Cxx1yLoc.isValid())
2316 Cxx1yLoc = S->getBeginLoc();
2317
2318 CompoundStmt *CompStmt = cast<CompoundStmt>(Val: S);
2319 for (auto *BodyIt : CompStmt->body()) {
2320 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, S: BodyIt, ReturnStmts,
2321 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2322 return false;
2323 }
2324 return true;
2325 }
2326
2327 case Stmt::IfStmtClass: {
2328 // C++1y allows if-statements.
2329 if (!Cxx1yLoc.isValid())
2330 Cxx1yLoc = S->getBeginLoc();
2331
2332 IfStmt *If = cast<IfStmt>(Val: S);
2333 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, S: If->getThen(), ReturnStmts,
2334 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2335 return false;
2336 if (If->getElse() &&
2337 !CheckConstexprFunctionStmt(SemaRef, Dcl, S: If->getElse(), ReturnStmts,
2338 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2339 return false;
2340 return true;
2341 }
2342
2343 case Stmt::WhileStmtClass:
2344 case Stmt::DoStmtClass:
2345 case Stmt::ForStmtClass:
2346 case Stmt::CXXForRangeStmtClass:
2347 case Stmt::ContinueStmtClass:
2348 // C++1y allows all of these. We don't allow them as extensions in C++11,
2349 // because they don't make sense without variable mutation.
2350 if (!SemaRef.getLangOpts().CPlusPlus14)
2351 break;
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::SwitchStmtClass:
2363 case Stmt::CaseStmtClass:
2364 case Stmt::DefaultStmtClass:
2365 case Stmt::BreakStmtClass:
2366 // C++1y allows switch-statements, and since they don't need variable
2367 // mutation, we can reasonably allow them in C++11 as an extension.
2368 if (!Cxx1yLoc.isValid())
2369 Cxx1yLoc = S->getBeginLoc();
2370 for (Stmt *SubStmt : S->children()) {
2371 if (SubStmt &&
2372 !CheckConstexprFunctionStmt(SemaRef, Dcl, S: SubStmt, ReturnStmts,
2373 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2374 return false;
2375 }
2376 return true;
2377
2378 case Stmt::LabelStmtClass:
2379 case Stmt::GotoStmtClass:
2380 case Stmt::IndirectGotoStmtClass:
2381 if (Cxx2bLoc.isInvalid())
2382 Cxx2bLoc = S->getBeginLoc();
2383 for (Stmt *SubStmt : S->children()) {
2384 if (SubStmt &&
2385 !CheckConstexprFunctionStmt(SemaRef, Dcl, S: SubStmt, ReturnStmts,
2386 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2387 return false;
2388 }
2389 return true;
2390
2391 case Stmt::GCCAsmStmtClass:
2392 case Stmt::MSAsmStmtClass:
2393 // C++2a allows inline assembly statements.
2394 case Stmt::CXXTryStmtClass:
2395 if (Cxx2aLoc.isInvalid())
2396 Cxx2aLoc = S->getBeginLoc();
2397 for (Stmt *SubStmt : S->children()) {
2398 if (SubStmt &&
2399 !CheckConstexprFunctionStmt(SemaRef, Dcl, S: SubStmt, ReturnStmts,
2400 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2401 return false;
2402 }
2403 return true;
2404
2405 case Stmt::CXXCatchStmtClass:
2406 // Do not bother checking the language mode (already covered by the
2407 // try block check).
2408 if (!CheckConstexprFunctionStmt(
2409 SemaRef, Dcl, S: cast<CXXCatchStmt>(Val: S)->getHandlerBlock(), ReturnStmts,
2410 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2411 return false;
2412 return true;
2413
2414 default:
2415 if (!isa<Expr>(Val: S))
2416 break;
2417
2418 // C++1y allows expression-statements.
2419 if (!Cxx1yLoc.isValid())
2420 Cxx1yLoc = S->getBeginLoc();
2421 return true;
2422 }
2423
2424 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2425 SemaRef.Diag(Loc: S->getBeginLoc(), DiagID: diag::err_constexpr_body_invalid_stmt)
2426 << isa<CXXConstructorDecl>(Val: Dcl) << Dcl->isConsteval();
2427 }
2428 return false;
2429}
2430
2431/// Check the body for the given constexpr function declaration only contains
2432/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
2433///
2434/// \return true if the body is OK, false if we have found or diagnosed a
2435/// problem.
2436static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
2437 Stmt *Body,
2438 Sema::CheckConstexprKind Kind) {
2439 SmallVector<SourceLocation, 4> ReturnStmts;
2440
2441 if (isa<CXXTryStmt>(Val: Body)) {
2442 // C++11 [dcl.constexpr]p3:
2443 // The definition of a constexpr function shall satisfy the following
2444 // constraints: [...]
2445 // - its function-body shall be = delete, = default, or a
2446 // compound-statement
2447 //
2448 // C++11 [dcl.constexpr]p4:
2449 // In the definition of a constexpr constructor, [...]
2450 // - its function-body shall not be a function-try-block;
2451 //
2452 // This restriction is lifted in C++2a, as long as inner statements also
2453 // apply the general constexpr rules.
2454 switch (Kind) {
2455 case Sema::CheckConstexprKind::CheckValid:
2456 if (!SemaRef.getLangOpts().CPlusPlus20)
2457 return false;
2458 break;
2459
2460 case Sema::CheckConstexprKind::Diagnose:
2461 SemaRef.DiagCompat(Loc: Body->getBeginLoc(),
2462 CompatDiagId: diag_compat::constexpr_function_try_block)
2463 << isa<CXXConstructorDecl>(Val: Dcl);
2464 break;
2465 }
2466 }
2467
2468 // - its function-body shall be [...] a compound-statement that contains only
2469 // [... list of cases ...]
2470 //
2471 // Note that walking the children here is enough to properly check for
2472 // CompoundStmt and CXXTryStmt body.
2473 SourceLocation Cxx1yLoc, Cxx2aLoc, Cxx2bLoc;
2474 for (Stmt *SubStmt : Body->children()) {
2475 if (SubStmt &&
2476 !CheckConstexprFunctionStmt(SemaRef, Dcl, S: SubStmt, ReturnStmts,
2477 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2478 return false;
2479 }
2480
2481 if (Kind == Sema::CheckConstexprKind::CheckValid) {
2482 // If this is only valid as an extension, report that we don't satisfy the
2483 // constraints of the current language.
2484 if ((Cxx2bLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus23) ||
2485 (Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) ||
2486 (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
2487 return false;
2488 } else if (Cxx2bLoc.isValid()) {
2489 SemaRef.DiagCompat(Loc: Cxx2bLoc, CompatDiagId: diag_compat::cxx23_constexpr_body_invalid_stmt)
2490 << isa<CXXConstructorDecl>(Val: Dcl);
2491 } else if (Cxx2aLoc.isValid()) {
2492 SemaRef.DiagCompat(Loc: Cxx2aLoc, CompatDiagId: diag_compat::cxx20_constexpr_body_invalid_stmt)
2493 << isa<CXXConstructorDecl>(Val: Dcl);
2494 } else if (Cxx1yLoc.isValid()) {
2495 SemaRef.DiagCompat(Loc: Cxx1yLoc, CompatDiagId: diag_compat::cxx14_constexpr_body_invalid_stmt)
2496 << isa<CXXConstructorDecl>(Val: Dcl);
2497 }
2498
2499 if (const CXXConstructorDecl *Constructor
2500 = dyn_cast<CXXConstructorDecl>(Val: Dcl)) {
2501 const CXXRecordDecl *RD = Constructor->getParent();
2502 // DR1359:
2503 // - every non-variant non-static data member and base class sub-object
2504 // shall be initialized;
2505 // DR1460:
2506 // - if the class is a union having variant members, exactly one of them
2507 // shall be initialized;
2508 if (RD->isUnion()) {
2509 if (Constructor->getNumCtorInitializers() == 0 &&
2510 RD->hasVariantMembers()) {
2511 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2512 SemaRef.DiagCompat(Loc: Dcl->getLocation(),
2513 CompatDiagId: diag_compat::constexpr_union_ctor_no_init);
2514 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2515 return false;
2516 }
2517 }
2518 } else if (!Constructor->isDependentContext() &&
2519 !Constructor->isDelegatingConstructor()) {
2520 // Skip detailed checking if we have enough initializers, and we would
2521 // allow at most one initializer per member.
2522 bool AnyAnonStructUnionMembers = false;
2523 unsigned Fields = 0;
2524 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
2525 E = RD->field_end(); I != E; ++I, ++Fields) {
2526 if (I->isAnonymousStructOrUnion()) {
2527 AnyAnonStructUnionMembers = true;
2528 break;
2529 }
2530 }
2531 // DR1460:
2532 // - if the class is a union-like class, but is not a union, for each of
2533 // its anonymous union members having variant members, exactly one of
2534 // them shall be initialized;
2535 if (AnyAnonStructUnionMembers ||
2536 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2537 // Check initialization of non-static data members. Base classes are
2538 // always initialized so do not need to be checked. Dependent bases
2539 // might not have initializers in the member initializer list.
2540 llvm::SmallPtrSet<Decl *, 16> Inits;
2541 for (const auto *I: Constructor->inits()) {
2542 if (FieldDecl *FD = I->getMember())
2543 Inits.insert(Ptr: FD);
2544 else if (IndirectFieldDecl *ID = I->getIndirectMember())
2545 Inits.insert(I: ID->chain_begin(), E: ID->chain_end());
2546 }
2547
2548 bool Diagnosed = false;
2549 for (auto *I : RD->fields())
2550 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, Field: I, Inits, Diagnosed,
2551 Kind))
2552 return false;
2553 }
2554 }
2555 } else {
2556 if (ReturnStmts.empty()) {
2557 switch (Kind) {
2558 case Sema::CheckConstexprKind::Diagnose:
2559 if (!CheckConstexprMissingReturn(SemaRef, Dcl))
2560 return false;
2561 break;
2562
2563 case Sema::CheckConstexprKind::CheckValid:
2564 // The formal requirements don't include this rule in C++14, even
2565 // though the "must be able to produce a constant expression" rules
2566 // still imply it in some cases.
2567 if (!SemaRef.getLangOpts().CPlusPlus14)
2568 return false;
2569 break;
2570 }
2571 } else if (ReturnStmts.size() > 1) {
2572 switch (Kind) {
2573 case Sema::CheckConstexprKind::Diagnose:
2574 SemaRef.DiagCompat(Loc: ReturnStmts.back(),
2575 CompatDiagId: diag_compat::constexpr_body_multiple_return);
2576 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2577 SemaRef.Diag(Loc: ReturnStmts[I],
2578 DiagID: diag::note_constexpr_body_previous_return);
2579 break;
2580
2581 case Sema::CheckConstexprKind::CheckValid:
2582 if (!SemaRef.getLangOpts().CPlusPlus14)
2583 return false;
2584 break;
2585 }
2586 }
2587 }
2588
2589 // C++11 [dcl.constexpr]p5:
2590 // if no function argument values exist such that the function invocation
2591 // substitution would produce a constant expression, the program is
2592 // ill-formed; no diagnostic required.
2593 // C++11 [dcl.constexpr]p3:
2594 // - every constructor call and implicit conversion used in initializing the
2595 // return value shall be one of those allowed in a constant expression.
2596 // C++11 [dcl.constexpr]p4:
2597 // - every constructor involved in initializing non-static data members and
2598 // base class sub-objects shall be a constexpr constructor.
2599 //
2600 // Note that this rule is distinct from the "requirements for a constexpr
2601 // function", so is not checked in CheckValid mode. Because the check for
2602 // constexpr potential is expensive, skip the check if the diagnostic is
2603 // disabled, the function is declared in a system header, or we're in C++23
2604 // or later mode (see https://wg21.link/P2448).
2605 bool SkipCheck =
2606 !SemaRef.getLangOpts().CheckConstexprFunctionBodies ||
2607 SemaRef.getSourceManager().isInSystemHeader(Loc: Dcl->getLocation()) ||
2608 SemaRef.getDiagnostics().isIgnored(
2609 DiagID: diag::ext_constexpr_function_never_constant_expr, Loc: Dcl->getLocation());
2610 SmallVector<PartialDiagnosticAt, 8> Diags;
2611 if (Kind == Sema::CheckConstexprKind::Diagnose && !SkipCheck &&
2612 !Expr::isPotentialConstantExpr(FD: Dcl, Diags)) {
2613 SemaRef.Diag(Loc: Dcl->getLocation(),
2614 DiagID: diag::ext_constexpr_function_never_constant_expr)
2615 << isa<CXXConstructorDecl>(Val: Dcl) << Dcl->isConsteval()
2616 << Dcl->getNameInfo().getSourceRange();
2617 for (const auto &Diag : Diags)
2618 SemaRef.Diag(Loc: Diag.first, PD: Diag.second);
2619 // Don't return false here: we allow this for compatibility in
2620 // system headers.
2621 }
2622
2623 return true;
2624}
2625
2626static bool CheckConstexprMissingReturn(Sema &SemaRef,
2627 const FunctionDecl *Dcl) {
2628 bool IsVoidOrDependentType = Dcl->getReturnType()->isVoidType() ||
2629 Dcl->getReturnType()->isDependentType();
2630 // Skip emitting a missing return error diagnostic for non-void functions
2631 // since C++23 no longer mandates constexpr functions to yield constant
2632 // expressions.
2633 if (SemaRef.getLangOpts().CPlusPlus23 && !IsVoidOrDependentType)
2634 return true;
2635
2636 // C++14 doesn't require constexpr functions to contain a 'return'
2637 // statement. We still do, unless the return type might be void, because
2638 // otherwise if there's no return statement, the function cannot
2639 // be used in a core constant expression.
2640 bool OK = SemaRef.getLangOpts().CPlusPlus14 && IsVoidOrDependentType;
2641 SemaRef.Diag(Loc: Dcl->getLocation(),
2642 DiagID: OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2643 : diag::err_constexpr_body_no_return)
2644 << Dcl->isConsteval();
2645 return OK;
2646}
2647
2648bool Sema::CheckImmediateEscalatingFunctionDefinition(
2649 FunctionDecl *FD, const sema::FunctionScopeInfo *FSI) {
2650 if (!getLangOpts().CPlusPlus20 || !FD->isImmediateEscalating())
2651 return true;
2652 FD->setBodyContainsImmediateEscalatingExpressions(
2653 FSI->FoundImmediateEscalatingExpression);
2654 if (FSI->FoundImmediateEscalatingExpression) {
2655 auto it = UndefinedButUsed.find(Key: FD->getCanonicalDecl());
2656 if (it != UndefinedButUsed.end()) {
2657 Diag(Loc: it->second, DiagID: diag::err_immediate_function_used_before_definition)
2658 << it->first;
2659 Diag(Loc: FD->getLocation(), DiagID: diag::note_defined_here) << FD;
2660 if (FD->isImmediateFunction() && !FD->isConsteval())
2661 DiagnoseImmediateEscalatingReason(FD);
2662 return false;
2663 }
2664 }
2665 return true;
2666}
2667
2668void Sema::DiagnoseImmediateEscalatingReason(FunctionDecl *FD) {
2669 assert(FD->isImmediateEscalating() && !FD->isConsteval() &&
2670 "expected an immediate function");
2671 assert(FD->hasBody() && "expected the function to have a body");
2672 struct ImmediateEscalatingExpressionsVisitor : DynamicRecursiveASTVisitor {
2673 Sema &SemaRef;
2674
2675 const FunctionDecl *ImmediateFn;
2676 bool ImmediateFnIsConstructor;
2677 CXXConstructorDecl *CurrentConstructor = nullptr;
2678 CXXCtorInitializer *CurrentInit = nullptr;
2679
2680 ImmediateEscalatingExpressionsVisitor(Sema &SemaRef, FunctionDecl *FD)
2681 : SemaRef(SemaRef), ImmediateFn(FD),
2682 ImmediateFnIsConstructor(isa<CXXConstructorDecl>(Val: FD)) {
2683 ShouldVisitImplicitCode = true;
2684 ShouldVisitLambdaBody = false;
2685 }
2686
2687 void Diag(const Expr *E, const FunctionDecl *Fn, bool IsCall) {
2688 SourceLocation Loc = E->getBeginLoc();
2689 SourceRange Range = E->getSourceRange();
2690 if (CurrentConstructor && CurrentInit) {
2691 Loc = CurrentConstructor->getLocation();
2692 Range = CurrentInit->isWritten() ? CurrentInit->getSourceRange()
2693 : SourceRange();
2694 }
2695
2696 FieldDecl* InitializedField = CurrentInit ? CurrentInit->getAnyMember() : nullptr;
2697
2698 SemaRef.Diag(Loc, DiagID: diag::note_immediate_function_reason)
2699 << ImmediateFn << Fn << Fn->isConsteval() << IsCall
2700 << isa<CXXConstructorDecl>(Val: Fn) << ImmediateFnIsConstructor
2701 << (InitializedField != nullptr)
2702 << (CurrentInit && !CurrentInit->isWritten())
2703 << InitializedField << Range;
2704 }
2705 bool TraverseCallExpr(CallExpr *E) override {
2706 if (const auto *DR =
2707 dyn_cast<DeclRefExpr>(Val: E->getCallee()->IgnoreImplicit());
2708 DR && DR->isImmediateEscalating()) {
2709 Diag(E, Fn: E->getDirectCallee(), /*IsCall=*/true);
2710 return false;
2711 }
2712
2713 for (Expr *A : E->arguments())
2714 if (!TraverseStmt(S: A))
2715 return false;
2716
2717 return true;
2718 }
2719
2720 bool VisitDeclRefExpr(DeclRefExpr *E) override {
2721 if (const auto *ReferencedFn = dyn_cast<FunctionDecl>(Val: E->getDecl());
2722 ReferencedFn && E->isImmediateEscalating()) {
2723 Diag(E, Fn: ReferencedFn, /*IsCall=*/false);
2724 return false;
2725 }
2726
2727 return true;
2728 }
2729
2730 bool VisitCXXConstructExpr(CXXConstructExpr *E) override {
2731 CXXConstructorDecl *D = E->getConstructor();
2732 if (E->isImmediateEscalating()) {
2733 Diag(E, Fn: D, /*IsCall=*/true);
2734 return false;
2735 }
2736 return true;
2737 }
2738
2739 bool TraverseConstructorInitializer(CXXCtorInitializer *Init) override {
2740 llvm::SaveAndRestore RAII(CurrentInit, Init);
2741 return DynamicRecursiveASTVisitor::TraverseConstructorInitializer(Init);
2742 }
2743
2744 bool TraverseCXXConstructorDecl(CXXConstructorDecl *Ctr) override {
2745 llvm::SaveAndRestore RAII(CurrentConstructor, Ctr);
2746 return DynamicRecursiveASTVisitor::TraverseCXXConstructorDecl(D: Ctr);
2747 }
2748
2749 bool TraverseType(QualType T, bool TraverseQualifier) override {
2750 return true;
2751 }
2752 bool VisitBlockExpr(BlockExpr *T) override { return true; }
2753
2754 } Visitor(*this, FD);
2755 Visitor.TraverseDecl(D: FD);
2756}
2757
2758CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {
2759 assert(getLangOpts().CPlusPlus && "No class names in C!");
2760
2761 if (SS && SS->isInvalid())
2762 return nullptr;
2763
2764 if (SS && SS->isNotEmpty()) {
2765 DeclContext *DC = computeDeclContext(SS: *SS, EnteringContext: true);
2766 return dyn_cast_or_null<CXXRecordDecl>(Val: DC);
2767 }
2768
2769 return dyn_cast_or_null<CXXRecordDecl>(Val: CurContext);
2770}
2771
2772bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,
2773 const CXXScopeSpec *SS) {
2774 CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2775 return CurDecl && &II == CurDecl->getIdentifier();
2776}
2777
2778bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2779 assert(getLangOpts().CPlusPlus && "No class names in C!");
2780
2781 if (!getLangOpts().SpellChecking)
2782 return false;
2783
2784 CXXRecordDecl *CurDecl;
2785 if (SS && SS->isSet() && !SS->isInvalid()) {
2786 DeclContext *DC = computeDeclContext(SS: *SS, EnteringContext: true);
2787 CurDecl = dyn_cast_or_null<CXXRecordDecl>(Val: DC);
2788 } else
2789 CurDecl = dyn_cast_or_null<CXXRecordDecl>(Val: CurContext);
2790
2791 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2792 3 * II->getName().edit_distance(Other: CurDecl->getIdentifier()->getName())
2793 < II->getLength()) {
2794 II = CurDecl->getIdentifier();
2795 return true;
2796 }
2797
2798 return false;
2799}
2800
2801CXXBaseSpecifier *Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2802 SourceRange SpecifierRange,
2803 bool Virtual, AccessSpecifier Access,
2804 TypeSourceInfo *TInfo,
2805 SourceLocation EllipsisLoc) {
2806 QualType BaseType = TInfo->getType();
2807 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2808 if (BaseType->containsErrors()) {
2809 // Already emitted a diagnostic when parsing the error type.
2810 return nullptr;
2811 }
2812
2813 if (EllipsisLoc.isValid() && !BaseType->containsUnexpandedParameterPack()) {
2814 Diag(Loc: EllipsisLoc, DiagID: diag::err_pack_expansion_without_parameter_packs)
2815 << TInfo->getTypeLoc().getSourceRange();
2816 EllipsisLoc = SourceLocation();
2817 }
2818
2819 auto *BaseDecl =
2820 dyn_cast_if_present<CXXRecordDecl>(Val: computeDeclContext(T: BaseType));
2821 // C++ [class.derived.general]p2:
2822 // A class-or-decltype shall denote a (possibly cv-qualified) class type
2823 // that is not an incompletely defined class; any cv-qualifiers are
2824 // ignored.
2825 if (BaseDecl) {
2826 // C++ [class.union.general]p4:
2827 // [...] A union shall not be used as a base class.
2828 if (BaseDecl->isUnion()) {
2829 Diag(Loc: BaseLoc, DiagID: diag::err_union_as_base_class) << SpecifierRange;
2830 return nullptr;
2831 }
2832
2833 if (BaseType.hasQualifiers()) {
2834 std::string Quals =
2835 BaseType.getQualifiers().getAsString(Policy: Context.getPrintingPolicy());
2836 Diag(Loc: BaseLoc, DiagID: diag::warn_qual_base_type)
2837 << Quals << llvm::count(Range&: Quals, Element: ' ') + 1 << BaseType;
2838 Diag(Loc: BaseLoc, DiagID: diag::note_base_class_specified_here) << BaseType;
2839 }
2840
2841 // For the MS ABI, propagate DLL attributes to base class templates.
2842 if (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
2843 Context.getTargetInfo().getTriple().isPS()) {
2844 if (Attr *ClassAttr = getDLLAttr(D: Class)) {
2845 if (auto *BaseSpec =
2846 dyn_cast<ClassTemplateSpecializationDecl>(Val: BaseDecl)) {
2847 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplateSpec: BaseSpec,
2848 BaseLoc);
2849 }
2850 }
2851 }
2852
2853 if (RequireCompleteType(Loc: BaseLoc, T: BaseType, DiagID: diag::err_incomplete_base_class,
2854 Args: SpecifierRange)) {
2855 Class->setInvalidDecl();
2856 return nullptr;
2857 }
2858
2859 BaseDecl = BaseDecl->getDefinition();
2860 assert(BaseDecl && "Base type is not incomplete, but has no definition");
2861
2862 // Microsoft docs say:
2863 // "If a base-class has a code_seg attribute, derived classes must have the
2864 // same attribute."
2865 const auto *BaseCSA = BaseDecl->getAttr<CodeSegAttr>();
2866 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2867 if ((DerivedCSA || BaseCSA) &&
2868 (!BaseCSA || !DerivedCSA ||
2869 BaseCSA->getName() != DerivedCSA->getName())) {
2870 Diag(Loc: Class->getLocation(), DiagID: diag::err_mismatched_code_seg_base);
2871 Diag(Loc: BaseDecl->getLocation(), DiagID: diag::note_base_class_specified_here)
2872 << BaseDecl;
2873 return nullptr;
2874 }
2875
2876 // A class which contains a flexible array member is not suitable for use as
2877 // a base class:
2878 // - If the layout determines that a base comes before another base,
2879 // the flexible array member would index into the subsequent base.
2880 // - If the layout determines that base comes before the derived class,
2881 // the flexible array member would index into the derived class.
2882 if (BaseDecl->hasFlexibleArrayMember()) {
2883 Diag(Loc: BaseLoc, DiagID: diag::err_base_class_has_flexible_array_member)
2884 << BaseDecl->getDeclName();
2885 return nullptr;
2886 }
2887
2888 // C++ [class]p3:
2889 // If a class is marked final and it appears as a base-type-specifier in
2890 // base-clause, the program is ill-formed.
2891 if (FinalAttr *FA = BaseDecl->getAttr<FinalAttr>()) {
2892 Diag(Loc: BaseLoc, DiagID: diag::err_class_marked_final_used_as_base)
2893 << BaseDecl->getDeclName() << FA->isSpelledAsSealed();
2894 Diag(Loc: BaseDecl->getLocation(), DiagID: diag::note_entity_declared_at)
2895 << BaseDecl->getDeclName() << FA->getRange();
2896 return nullptr;
2897 }
2898
2899 // If the base class is invalid the derived class is as well.
2900 if (BaseDecl->isInvalidDecl())
2901 Class->setInvalidDecl();
2902 } else if (BaseType->isDependentType()) {
2903 // Make sure that we don't make an ill-formed AST where the type of the
2904 // Class is non-dependent and its attached base class specifier is an
2905 // dependent type, which violates invariants in many clang code paths (e.g.
2906 // constexpr evaluator). If this case happens (in errory-recovery mode), we
2907 // explicitly mark the Class decl invalid. The diagnostic was already
2908 // emitted.
2909 if (!Class->isDependentContext())
2910 Class->setInvalidDecl();
2911 } else {
2912 // The base class is some non-dependent non-class type.
2913 Diag(Loc: BaseLoc, DiagID: diag::err_base_must_be_class) << SpecifierRange;
2914 return nullptr;
2915 }
2916
2917 // In HLSL, unspecified class access is public rather than private.
2918 if (getLangOpts().HLSL && Class->getTagKind() == TagTypeKind::Class &&
2919 Access == AS_none)
2920 Access = AS_public;
2921
2922 // Create the base specifier.
2923 return new (Context) CXXBaseSpecifier(
2924 SpecifierRange, Virtual, Class->getTagKind() == TagTypeKind::Class,
2925 Access, TInfo, EllipsisLoc);
2926}
2927
2928BaseResult Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2929 const ParsedAttributesView &Attributes,
2930 bool Virtual, AccessSpecifier Access,
2931 ParsedType basetype, SourceLocation BaseLoc,
2932 SourceLocation EllipsisLoc) {
2933 if (!classdecl)
2934 return true;
2935
2936 AdjustDeclIfTemplate(Decl&: classdecl);
2937 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Val: classdecl);
2938 if (!Class)
2939 return true;
2940
2941 // We haven't yet attached the base specifiers.
2942 Class->setIsParsingBaseSpecifiers();
2943
2944 // We do not support any C++11 attributes on base-specifiers yet.
2945 // Diagnose any attributes we see.
2946 for (const ParsedAttr &AL : Attributes) {
2947 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2948 continue;
2949 if (AL.getKind() == ParsedAttr::UnknownAttribute)
2950 DiagnoseUnknownAttribute(AL);
2951 else
2952 Diag(Loc: AL.getLoc(), DiagID: diag::err_base_specifier_attribute)
2953 << AL << AL.isRegularKeywordAttribute() << AL.getRange();
2954 }
2955
2956 TypeSourceInfo *TInfo = nullptr;
2957 GetTypeFromParser(Ty: basetype, TInfo: &TInfo);
2958
2959 if (EllipsisLoc.isInvalid() &&
2960 DiagnoseUnexpandedParameterPack(Loc: SpecifierRange.getBegin(), T: TInfo,
2961 UPPC: UPPC_BaseType))
2962 return true;
2963
2964 // C++ [class.union.general]p4:
2965 // [...] A union shall not have base classes.
2966 if (Class->isUnion()) {
2967 Diag(Loc: Class->getLocation(), DiagID: diag::err_base_clause_on_union)
2968 << SpecifierRange;
2969 return true;
2970 }
2971
2972 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2973 Virtual, Access, TInfo,
2974 EllipsisLoc))
2975 return BaseSpec;
2976
2977 Class->setInvalidDecl();
2978 return true;
2979}
2980
2981/// Use small set to collect indirect bases. As this is only used
2982/// locally, there's no need to abstract the small size parameter.
2983typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2984
2985/// Recursively add the bases of Type. Don't add Type itself.
2986static void
2987NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2988 const QualType &Type)
2989{
2990 // Even though the incoming type is a base, it might not be
2991 // a class -- it could be a template parm, for instance.
2992 if (const auto *Decl = Type->getAsCXXRecordDecl()) {
2993 // Iterate over its bases.
2994 for (const auto &BaseSpec : Decl->bases()) {
2995 QualType Base = Context.getCanonicalType(T: BaseSpec.getType())
2996 .getUnqualifiedType();
2997 if (Set.insert(Ptr: Base).second)
2998 // If we've not already seen it, recurse.
2999 NoteIndirectBases(Context, Set, Type: Base);
3000 }
3001 }
3002}
3003
3004bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
3005 MutableArrayRef<CXXBaseSpecifier *> Bases) {
3006 if (Bases.empty())
3007 return false;
3008
3009 // Used to keep track of which base types we have already seen, so
3010 // that we can properly diagnose redundant direct base types. Note
3011 // that the key is always the unqualified canonical type of the base
3012 // class.
3013 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
3014
3015 // Used to track indirect bases so we can see if a direct base is
3016 // ambiguous.
3017 IndirectBaseSet IndirectBaseTypes;
3018
3019 // Copy non-redundant base specifiers into permanent storage.
3020 unsigned NumGoodBases = 0;
3021 bool Invalid = false;
3022 for (unsigned idx = 0; idx < Bases.size(); ++idx) {
3023 QualType NewBaseType
3024 = Context.getCanonicalType(T: Bases[idx]->getType());
3025 NewBaseType = NewBaseType.getLocalUnqualifiedType();
3026
3027 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
3028 if (KnownBase) {
3029 // C++ [class.mi]p3:
3030 // A class shall not be specified as a direct base class of a
3031 // derived class more than once.
3032 Diag(Loc: Bases[idx]->getBeginLoc(), DiagID: diag::err_duplicate_base_class)
3033 << KnownBase->getType() << Bases[idx]->getSourceRange();
3034
3035 // Delete the duplicate base class specifier; we're going to
3036 // overwrite its pointer later.
3037 Context.Deallocate(Ptr: Bases[idx]);
3038
3039 Invalid = true;
3040 } else {
3041 // Okay, add this new base class.
3042 KnownBase = Bases[idx];
3043 Bases[NumGoodBases++] = Bases[idx];
3044
3045 if (NewBaseType->isDependentType())
3046 continue;
3047 // Note this base's direct & indirect bases, if there could be ambiguity.
3048 if (Bases.size() > 1)
3049 NoteIndirectBases(Context, Set&: IndirectBaseTypes, Type: NewBaseType);
3050
3051 if (const auto *RD = NewBaseType->getAsCXXRecordDecl()) {
3052 if (Class->isInterface() &&
3053 (!RD->isInterfaceLike() ||
3054 KnownBase->getAccessSpecifier() != AS_public)) {
3055 // The Microsoft extension __interface does not permit bases that
3056 // are not themselves public interfaces.
3057 Diag(Loc: KnownBase->getBeginLoc(), DiagID: diag::err_invalid_base_in_interface)
3058 << getRecordDiagFromTagKind(Tag: RD->getTagKind()) << RD
3059 << RD->getSourceRange();
3060 Invalid = true;
3061 }
3062 if (RD->hasAttr<WeakAttr>())
3063 Class->addAttr(A: WeakAttr::CreateImplicit(Ctx&: Context));
3064 }
3065 }
3066 }
3067
3068 // Attach the remaining base class specifiers to the derived class.
3069 Class->setBases(Bases: Bases.data(), NumBases: NumGoodBases);
3070
3071 // Check that the only base classes that are duplicate are virtual.
3072 for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
3073 // Check whether this direct base is inaccessible due to ambiguity.
3074 QualType BaseType = Bases[idx]->getType();
3075
3076 // Skip all dependent types in templates being used as base specifiers.
3077 // Checks below assume that the base specifier is a CXXRecord.
3078 if (BaseType->isDependentType())
3079 continue;
3080
3081 CanQualType CanonicalBase = Context.getCanonicalType(T: BaseType)
3082 .getUnqualifiedType();
3083
3084 if (IndirectBaseTypes.count(Ptr: CanonicalBase)) {
3085 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3086 /*DetectVirtual=*/true);
3087 bool found
3088 = Class->isDerivedFrom(Base: CanonicalBase->getAsCXXRecordDecl(), Paths);
3089 assert(found);
3090 (void)found;
3091
3092 if (Paths.isAmbiguous(BaseType: CanonicalBase))
3093 Diag(Loc: Bases[idx]->getBeginLoc(), DiagID: diag::warn_inaccessible_base_class)
3094 << BaseType << getAmbiguousPathsDisplayString(Paths)
3095 << Bases[idx]->getSourceRange();
3096 else
3097 assert(Bases[idx]->isVirtual());
3098 }
3099
3100 // Delete the base class specifier, since its data has been copied
3101 // into the CXXRecordDecl.
3102 Context.Deallocate(Ptr: Bases[idx]);
3103 }
3104
3105 return Invalid;
3106}
3107
3108void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
3109 MutableArrayRef<CXXBaseSpecifier *> Bases) {
3110 if (!ClassDecl || Bases.empty())
3111 return;
3112
3113 AdjustDeclIfTemplate(Decl&: ClassDecl);
3114 AttachBaseSpecifiers(Class: cast<CXXRecordDecl>(Val: ClassDecl), Bases);
3115}
3116
3117bool Sema::IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived,
3118 CXXRecordDecl *Base, CXXBasePaths &Paths) {
3119 if (!getLangOpts().CPlusPlus)
3120 return false;
3121
3122 if (!Base || !Derived)
3123 return false;
3124
3125 // If either the base or the derived type is invalid, don't try to
3126 // check whether one is derived from the other.
3127 if (Base->isInvalidDecl() || Derived->isInvalidDecl())
3128 return false;
3129
3130 // FIXME: In a modules build, do we need the entire path to be visible for us
3131 // to be able to use the inheritance relationship?
3132 if (!isCompleteType(Loc, T: Context.getCanonicalTagType(TD: Derived)) &&
3133 !Derived->isBeingDefined())
3134 return false;
3135
3136 return Derived->isDerivedFrom(Base, Paths);
3137}
3138
3139bool Sema::IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived,
3140 CXXRecordDecl *Base) {
3141 CXXBasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/false,
3142 /*DetectVirtual=*/false);
3143 return IsDerivedFrom(Loc, Derived, Base, Paths);
3144}
3145
3146bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
3147 CXXBasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/false,
3148 /*DetectVirtual=*/false);
3149 return IsDerivedFrom(Loc, Derived: Derived->getAsCXXRecordDecl(),
3150 Base: Base->getAsCXXRecordDecl(), Paths);
3151}
3152
3153bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
3154 CXXBasePaths &Paths) {
3155 return IsDerivedFrom(Loc, Derived: Derived->getAsCXXRecordDecl(),
3156 Base: Base->getAsCXXRecordDecl(), Paths);
3157}
3158
3159static void BuildBasePathArray(const CXXBasePath &Path,
3160 CXXCastPath &BasePathArray) {
3161 // We first go backward and check if we have a virtual base.
3162 // FIXME: It would be better if CXXBasePath had the base specifier for
3163 // the nearest virtual base.
3164 unsigned Start = 0;
3165 for (unsigned I = Path.size(); I != 0; --I) {
3166 if (Path[I - 1].Base->isVirtual()) {
3167 Start = I - 1;
3168 break;
3169 }
3170 }
3171
3172 // Now add all bases.
3173 for (unsigned I = Start, E = Path.size(); I != E; ++I)
3174 BasePathArray.push_back(Elt: const_cast<CXXBaseSpecifier*>(Path[I].Base));
3175}
3176
3177
3178void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
3179 CXXCastPath &BasePathArray) {
3180 assert(BasePathArray.empty() && "Base path array must be empty!");
3181 assert(Paths.isRecordingPaths() && "Must record paths!");
3182 return ::BuildBasePathArray(Path: Paths.front(), BasePathArray);
3183}
3184
3185bool
3186Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
3187 unsigned InaccessibleBaseID,
3188 unsigned AmbiguousBaseConvID,
3189 SourceLocation Loc, SourceRange Range,
3190 DeclarationName Name,
3191 CXXCastPath *BasePath,
3192 bool IgnoreAccess) {
3193 // First, determine whether the path from Derived to Base is
3194 // ambiguous. This is slightly more expensive than checking whether
3195 // the Derived to Base conversion exists, because here we need to
3196 // explore multiple paths to determine if there is an ambiguity.
3197 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3198 /*DetectVirtual=*/false);
3199 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
3200 if (!DerivationOkay)
3201 return true;
3202
3203 const CXXBasePath *Path = nullptr;
3204 if (!Paths.isAmbiguous(BaseType: Context.getCanonicalType(T: Base).getUnqualifiedType()))
3205 Path = &Paths.front();
3206
3207 // For MSVC compatibility, check if Derived directly inherits from Base. Clang
3208 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
3209 // user to access such bases.
3210 if (!Path && getLangOpts().MSVCCompat) {
3211 for (const CXXBasePath &PossiblePath : Paths) {
3212 if (PossiblePath.size() == 1) {
3213 Path = &PossiblePath;
3214 if (AmbiguousBaseConvID)
3215 Diag(Loc, DiagID: diag::ext_ms_ambiguous_direct_base)
3216 << Base << Derived << Range;
3217 break;
3218 }
3219 }
3220 }
3221
3222 if (Path) {
3223 if (!IgnoreAccess) {
3224 // Check that the base class can be accessed.
3225 switch (
3226 CheckBaseClassAccess(AccessLoc: Loc, Base, Derived, Path: *Path, DiagID: InaccessibleBaseID)) {
3227 case AR_inaccessible:
3228 return true;
3229 case AR_accessible:
3230 case AR_dependent:
3231 case AR_delayed:
3232 break;
3233 }
3234 }
3235
3236 // Build a base path if necessary.
3237 if (BasePath)
3238 ::BuildBasePathArray(Path: *Path, BasePathArray&: *BasePath);
3239 return false;
3240 }
3241
3242 if (AmbiguousBaseConvID) {
3243 // We know that the derived-to-base conversion is ambiguous, and
3244 // we're going to produce a diagnostic. Perform the derived-to-base
3245 // search just one more time to compute all of the possible paths so
3246 // that we can print them out. This is more expensive than any of
3247 // the previous derived-to-base checks we've done, but at this point
3248 // performance isn't as much of an issue.
3249 Paths.clear();
3250 Paths.setRecordingPaths(true);
3251 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
3252 assert(StillOkay && "Can only be used with a derived-to-base conversion");
3253 (void)StillOkay;
3254
3255 // Build up a textual representation of the ambiguous paths, e.g.,
3256 // D -> B -> A, that will be used to illustrate the ambiguous
3257 // conversions in the diagnostic. We only print one of the paths
3258 // to each base class subobject.
3259 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3260
3261 Diag(Loc, DiagID: AmbiguousBaseConvID)
3262 << Derived << Base << PathDisplayStr << Range << Name;
3263 }
3264 return true;
3265}
3266
3267bool
3268Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
3269 SourceLocation Loc, SourceRange Range,
3270 CXXCastPath *BasePath,
3271 bool IgnoreAccess) {
3272 return CheckDerivedToBaseConversion(
3273 Derived, Base, InaccessibleBaseID: diag::err_upcast_to_inaccessible_base,
3274 AmbiguousBaseConvID: diag::err_ambiguous_derived_to_base_conv, Loc, Range, Name: DeclarationName(),
3275 BasePath, IgnoreAccess);
3276}
3277
3278std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
3279 std::string PathDisplayStr;
3280 std::set<unsigned> DisplayedPaths;
3281 for (const CXXBasePath &Path : Paths) {
3282 if (DisplayedPaths.insert(x: Path.back().SubobjectNumber).second) {
3283 // We haven't displayed a path to this particular base
3284 // class subobject yet.
3285 PathDisplayStr += "\n ";
3286 PathDisplayStr += QualType(Context.getCanonicalTagType(TD: Paths.getOrigin()))
3287 .getAsString();
3288 for (const CXXBasePathElement &Element : Path)
3289 PathDisplayStr += " -> " + Element.Base->getType().getAsString();
3290 }
3291 }
3292
3293 return PathDisplayStr;
3294}
3295
3296//===----------------------------------------------------------------------===//
3297// C++ class member Handling
3298//===----------------------------------------------------------------------===//
3299
3300bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
3301 SourceLocation ColonLoc,
3302 const ParsedAttributesView &Attrs) {
3303 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
3304 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(C&: Context, AS: Access, DC: CurContext,
3305 ASLoc, ColonLoc);
3306 CurContext->addHiddenDecl(D: ASDecl);
3307 return ProcessAccessDeclAttributeList(ASDecl, AttrList: Attrs);
3308}
3309
3310void Sema::CheckOverrideControl(NamedDecl *D) {
3311 if (D->isInvalidDecl())
3312 return;
3313
3314 // We only care about "override" and "final" declarations.
3315 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
3316 return;
3317
3318 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: D);
3319
3320 // We can't check dependent instance methods.
3321 if (MD && MD->isInstance() &&
3322 (MD->getParent()->hasAnyDependentBases() ||
3323 MD->getType()->isDependentType()))
3324 return;
3325
3326 if (MD && !MD->isVirtual()) {
3327 // If we have a non-virtual method, check if it hides a virtual method.
3328 // (In that case, it's most likely the method has the wrong type.)
3329 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3330 FindHiddenVirtualMethods(MD, OverloadedMethods);
3331
3332 if (!OverloadedMethods.empty()) {
3333 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3334 Diag(Loc: OA->getLocation(),
3335 DiagID: diag::override_keyword_hides_virtual_member_function)
3336 << "override" << (OverloadedMethods.size() > 1);
3337 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3338 Diag(Loc: FA->getLocation(),
3339 DiagID: diag::override_keyword_hides_virtual_member_function)
3340 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3341 << (OverloadedMethods.size() > 1);
3342 }
3343 NoteHiddenVirtualMethods(MD, OverloadedMethods);
3344 MD->setInvalidDecl();
3345 return;
3346 }
3347 // Fall through into the general case diagnostic.
3348 // FIXME: We might want to attempt typo correction here.
3349 }
3350
3351 if (!MD || !MD->isVirtual()) {
3352 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3353 Diag(Loc: OA->getLocation(),
3354 DiagID: diag::override_keyword_only_allowed_on_virtual_member_functions)
3355 << "override" << FixItHint::CreateRemoval(RemoveRange: OA->getLocation());
3356 D->dropAttr<OverrideAttr>();
3357 }
3358 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3359 Diag(Loc: FA->getLocation(),
3360 DiagID: diag::override_keyword_only_allowed_on_virtual_member_functions)
3361 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3362 << FixItHint::CreateRemoval(RemoveRange: FA->getLocation());
3363 D->dropAttr<FinalAttr>();
3364 }
3365 return;
3366 }
3367
3368 // C++11 [class.virtual]p5:
3369 // If a function is marked with the virt-specifier override and
3370 // does not override a member function of a base class, the program is
3371 // ill-formed.
3372 bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
3373 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
3374 Diag(Loc: MD->getLocation(), DiagID: diag::err_function_marked_override_not_overriding)
3375 << MD->getDeclName();
3376}
3377
3378void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent) {
3379 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
3380 return;
3381 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: D);
3382 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
3383 return;
3384
3385 SourceLocation Loc = MD->getLocation();
3386 SourceLocation SpellingLoc = Loc;
3387 if (getSourceManager().isMacroArgExpansion(Loc))
3388 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
3389 SpellingLoc = getSourceManager().getSpellingLoc(Loc: SpellingLoc);
3390 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(Loc: SpellingLoc))
3391 return;
3392
3393 if (MD->size_overridden_methods() > 0) {
3394 auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) {
3395 unsigned DiagID =
3396 Inconsistent && !Diags.isIgnored(DiagID: DiagInconsistent, Loc: MD->getLocation())
3397 ? DiagInconsistent
3398 : DiagSuggest;
3399 Diag(Loc: MD->getLocation(), DiagID) << MD->getDeclName();
3400 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
3401 Diag(Loc: OMD->getLocation(), DiagID: diag::note_overridden_virtual_function);
3402 };
3403 if (isa<CXXDestructorDecl>(Val: MD))
3404 EmitDiag(
3405 diag::warn_inconsistent_destructor_marked_not_override_overriding,
3406 diag::warn_suggest_destructor_marked_not_override_overriding);
3407 else
3408 EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding,
3409 diag::warn_suggest_function_marked_not_override_overriding);
3410 }
3411}
3412
3413bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
3414 const CXXMethodDecl *Old) {
3415 FinalAttr *FA = Old->getAttr<FinalAttr>();
3416 if (!FA)
3417 return false;
3418
3419 Diag(Loc: New->getLocation(), DiagID: diag::err_final_function_overridden)
3420 << New->getDeclName()
3421 << FA->isSpelledAsSealed();
3422 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function);
3423 return true;
3424}
3425
3426static bool InitializationHasSideEffects(const FieldDecl &FD) {
3427 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
3428 // FIXME: Destruction of ObjC lifetime types has side-effects.
3429 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3430 return !RD->isCompleteDefinition() ||
3431 !RD->hasTrivialDefaultConstructor() ||
3432 !RD->hasTrivialDestructor();
3433 return false;
3434}
3435
3436void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
3437 DeclarationName FieldName,
3438 const CXXRecordDecl *RD,
3439 bool DeclIsField) {
3440 if (Diags.isIgnored(DiagID: diag::warn_shadow_field, Loc))
3441 return;
3442
3443 // To record a shadowed field in a base
3444 std::map<CXXRecordDecl*, NamedDecl*> Bases;
3445 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
3446 CXXBasePath &Path) {
3447 const auto Base = Specifier->getType()->getAsCXXRecordDecl();
3448 // Record an ambiguous path directly
3449 if (Bases.find(x: Base) != Bases.end())
3450 return true;
3451 for (const auto Field : Base->lookup(Name: FieldName)) {
3452 if ((isa<FieldDecl>(Val: Field) || isa<IndirectFieldDecl>(Val: Field)) &&
3453 Field->getAccess() != AS_private) {
3454 assert(Field->getAccess() != AS_none);
3455 assert(Bases.find(Base) == Bases.end());
3456 Bases[Base] = Field;
3457 return true;
3458 }
3459 }
3460 return false;
3461 };
3462
3463 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3464 /*DetectVirtual=*/true);
3465 if (!RD->lookupInBases(BaseMatches: FieldShadowed, Paths))
3466 return;
3467
3468 for (const auto &P : Paths) {
3469 auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
3470 auto It = Bases.find(x: Base);
3471 // Skip duplicated bases
3472 if (It == Bases.end())
3473 continue;
3474 auto BaseField = It->second;
3475 assert(BaseField->getAccess() != AS_private);
3476 if (AS_none !=
3477 CXXRecordDecl::MergeAccess(PathAccess: P.Access, DeclAccess: BaseField->getAccess())) {
3478 Diag(Loc, DiagID: diag::warn_shadow_field)
3479 << FieldName << RD << Base << DeclIsField;
3480 Diag(Loc: BaseField->getLocation(), DiagID: diag::note_shadow_field);
3481 Bases.erase(position: It);
3482 }
3483 }
3484}
3485
3486template <typename AttrType>
3487inline static bool HasAttribute(const QualType &T) {
3488 if (const TagDecl *TD = T->getAsTagDecl())
3489 return TD->hasAttr<AttrType>();
3490 if (const TypedefType *TDT = T->getAs<TypedefType>())
3491 return TDT->getDecl()->hasAttr<AttrType>();
3492 return false;
3493}
3494
3495static bool IsUnusedPrivateField(const FieldDecl *FD) {
3496 if (FD->getAccess() == AS_private && FD->getDeclName()) {
3497 QualType FieldType = FD->getType();
3498 if (HasAttribute<WarnUnusedAttr>(T: FieldType))
3499 return true;
3500
3501 return !FD->isImplicit() && !FD->hasAttr<UnusedAttr>() &&
3502 !FD->getParent()->isDependentContext() &&
3503 !HasAttribute<UnusedAttr>(T: FieldType) &&
3504 !InitializationHasSideEffects(FD: *FD);
3505 }
3506 return false;
3507}
3508
3509NamedDecl *
3510Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
3511 MultiTemplateParamsArg TemplateParameterLists,
3512 Expr *BitWidth, const VirtSpecifiers &VS,
3513 InClassInitStyle InitStyle) {
3514 const DeclSpec &DS = D.getDeclSpec();
3515 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
3516 DeclarationName Name = NameInfo.getName();
3517 SourceLocation Loc = NameInfo.getLoc();
3518
3519 // For anonymous bitfields, the location should point to the type.
3520 if (Loc.isInvalid())
3521 Loc = D.getBeginLoc();
3522
3523 assert(isa<CXXRecordDecl>(CurContext));
3524 assert(!DS.isFriendSpecified());
3525
3526 bool isFunc = D.isDeclarationOfFunction();
3527 const ParsedAttr *MSPropertyAttr =
3528 D.getDeclSpec().getAttributes().getMSPropertyAttr();
3529
3530 if (cast<CXXRecordDecl>(Val: CurContext)->isInterface()) {
3531 // The Microsoft extension __interface only permits public member functions
3532 // and prohibits constructors, destructors, operators, non-public member
3533 // functions, static methods and data members.
3534 unsigned InvalidDecl;
3535 bool ShowDeclName = true;
3536 if (!isFunc &&
3537 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
3538 InvalidDecl = 0;
3539 else if (!isFunc)
3540 InvalidDecl = 1;
3541 else if (AS != AS_public)
3542 InvalidDecl = 2;
3543 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
3544 InvalidDecl = 3;
3545 else switch (Name.getNameKind()) {
3546 case DeclarationName::CXXConstructorName:
3547 InvalidDecl = 4;
3548 ShowDeclName = false;
3549 break;
3550
3551 case DeclarationName::CXXDestructorName:
3552 InvalidDecl = 5;
3553 ShowDeclName = false;
3554 break;
3555
3556 case DeclarationName::CXXOperatorName:
3557 case DeclarationName::CXXConversionFunctionName:
3558 InvalidDecl = 6;
3559 break;
3560
3561 default:
3562 InvalidDecl = 0;
3563 break;
3564 }
3565
3566 if (InvalidDecl) {
3567 if (ShowDeclName)
3568 Diag(Loc, DiagID: diag::err_invalid_member_in_interface)
3569 << (InvalidDecl-1) << Name;
3570 else
3571 Diag(Loc, DiagID: diag::err_invalid_member_in_interface)
3572 << (InvalidDecl-1) << "";
3573 return nullptr;
3574 }
3575 }
3576
3577 // HLSL prohibits user defined constructors and destructors.
3578 if (getLangOpts().HLSL) {
3579 switch (Name.getNameKind()) {
3580 case DeclarationName::CXXConstructorName:
3581 case DeclarationName::CXXDestructorName:
3582 Diag(Loc, DiagID: diag::err_hlsl_cstor_dstor);
3583 return nullptr;
3584 default:
3585 break;
3586 }
3587 }
3588
3589 // C++ 9.2p6: A member shall not be declared to have automatic storage
3590 // duration (auto, register) or with the extern storage-class-specifier.
3591 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3592 // data members and cannot be applied to names declared const or static,
3593 // and cannot be applied to reference members.
3594 switch (DS.getStorageClassSpec()) {
3595 case DeclSpec::SCS_unspecified:
3596 case DeclSpec::SCS_typedef:
3597 case DeclSpec::SCS_static:
3598 break;
3599 case DeclSpec::SCS_mutable:
3600 if (isFunc) {
3601 Diag(Loc: DS.getStorageClassSpecLoc(), DiagID: diag::err_mutable_function);
3602
3603 // FIXME: It would be nicer if the keyword was ignored only for this
3604 // declarator. Otherwise we could get follow-up errors.
3605 D.getMutableDeclSpec().ClearStorageClassSpecs();
3606 }
3607 break;
3608 default:
3609 Diag(Loc: DS.getStorageClassSpecLoc(),
3610 DiagID: diag::err_storageclass_invalid_for_member);
3611 D.getMutableDeclSpec().ClearStorageClassSpecs();
3612 break;
3613 }
3614
3615 bool isInstField = (DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3616 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
3617 !isFunc && TemplateParameterLists.empty();
3618
3619 if (DS.hasConstexprSpecifier() && isInstField) {
3620 SemaDiagnosticBuilder B =
3621 Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_invalid_constexpr_member);
3622 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3623 if (InitStyle == ICIS_NoInit) {
3624 B << 0 << 0;
3625 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
3626 B << FixItHint::CreateRemoval(RemoveRange: ConstexprLoc);
3627 else {
3628 B << FixItHint::CreateReplacement(RemoveRange: ConstexprLoc, Code: "const");
3629 D.getMutableDeclSpec().ClearConstexprSpec();
3630 const char *PrevSpec;
3631 unsigned DiagID;
3632 bool Failed = D.getMutableDeclSpec().SetTypeQual(
3633 T: DeclSpec::TQ_const, Loc: ConstexprLoc, PrevSpec, DiagID, Lang: getLangOpts());
3634 (void)Failed;
3635 assert(!Failed && "Making a constexpr member const shouldn't fail");
3636 }
3637 } else {
3638 B << 1;
3639 const char *PrevSpec;
3640 unsigned DiagID;
3641 if (D.getMutableDeclSpec().SetStorageClassSpec(
3642 S&: *this, SC: DeclSpec::SCS_static, Loc: ConstexprLoc, PrevSpec, DiagID,
3643 Policy: Context.getPrintingPolicy())) {
3644 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
3645 "This is the only DeclSpec that should fail to be applied");
3646 B << 1;
3647 } else {
3648 B << 0 << FixItHint::CreateInsertion(InsertionLoc: ConstexprLoc, Code: "static ");
3649 isInstField = false;
3650 }
3651 }
3652 }
3653
3654 NamedDecl *Member;
3655 if (isInstField) {
3656 CXXScopeSpec &SS = D.getCXXScopeSpec();
3657
3658 // Data members must have identifiers for names.
3659 if (!Name.isIdentifier()) {
3660 Diag(Loc, DiagID: diag::err_bad_variable_name)
3661 << Name;
3662 return nullptr;
3663 }
3664
3665 IdentifierInfo *II = Name.getAsIdentifierInfo();
3666 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
3667 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_member_with_template_arguments)
3668 << II
3669 << SourceRange(D.getName().TemplateId->LAngleLoc,
3670 D.getName().TemplateId->RAngleLoc)
3671 << D.getName().TemplateId->LAngleLoc;
3672 D.SetIdentifier(Id: II, IdLoc: Loc);
3673 }
3674
3675 if (SS.isSet() && !SS.isInvalid()) {
3676 // The user provided a superfluous scope specifier inside a class
3677 // definition:
3678 //
3679 // class X {
3680 // int X::member;
3681 // };
3682 if (DeclContext *DC = computeDeclContext(SS, EnteringContext: false)) {
3683 TemplateIdAnnotation *TemplateId =
3684 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
3685 ? D.getName().TemplateId
3686 : nullptr;
3687 diagnoseQualifiedDeclaration(SS, DC, Name, Loc: D.getIdentifierLoc(),
3688 TemplateId,
3689 /*IsMemberSpecialization=*/false);
3690 } else {
3691 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_member_qualification)
3692 << Name << SS.getRange();
3693 }
3694 SS.clear();
3695 }
3696
3697 if (MSPropertyAttr) {
3698 Member = HandleMSProperty(S, TagD: cast<CXXRecordDecl>(Val: CurContext), DeclStart: Loc, D,
3699 BitfieldWidth: BitWidth, InitStyle, AS, MSPropertyAttr: *MSPropertyAttr);
3700 if (!Member)
3701 return nullptr;
3702 isInstField = false;
3703 } else {
3704 Member = HandleField(S, TagD: cast<CXXRecordDecl>(Val: CurContext), DeclStart: Loc, D,
3705 BitfieldWidth: BitWidth, InitStyle, AS);
3706 if (!Member)
3707 return nullptr;
3708 }
3709
3710 CheckShadowInheritedFields(Loc, FieldName: Name, RD: cast<CXXRecordDecl>(Val: CurContext));
3711 } else {
3712 Member = HandleDeclarator(S, D, TemplateParameterLists);
3713 if (!Member)
3714 return nullptr;
3715
3716 // Non-instance-fields can't have a bitfield.
3717 if (BitWidth) {
3718 if (Member->isInvalidDecl()) {
3719 // don't emit another diagnostic.
3720 } else if (isa<VarDecl>(Val: Member) || isa<VarTemplateDecl>(Val: Member)) {
3721 // C++ 9.6p3: A bit-field shall not be a static member.
3722 // "static member 'A' cannot be a bit-field"
3723 Diag(Loc, DiagID: diag::err_static_not_bitfield)
3724 << Name << BitWidth->getSourceRange();
3725 } else if (isa<TypedefDecl>(Val: Member)) {
3726 // "typedef member 'x' cannot be a bit-field"
3727 Diag(Loc, DiagID: diag::err_typedef_not_bitfield)
3728 << Name << BitWidth->getSourceRange();
3729 } else {
3730 // A function typedef ("typedef int f(); f a;").
3731 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3732 Diag(Loc, DiagID: diag::err_not_integral_type_bitfield)
3733 << Name << cast<ValueDecl>(Val: Member)->getType()
3734 << BitWidth->getSourceRange();
3735 }
3736
3737 BitWidth = nullptr;
3738 Member->setInvalidDecl();
3739 }
3740
3741 NamedDecl *NonTemplateMember = Member;
3742 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: Member))
3743 NonTemplateMember = FunTmpl->getTemplatedDecl();
3744 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Val: Member))
3745 NonTemplateMember = VarTmpl->getTemplatedDecl();
3746
3747 Member->setAccess(AS);
3748
3749 // If we have declared a member function template or static data member
3750 // template, set the access of the templated declaration as well.
3751 if (NonTemplateMember != Member)
3752 NonTemplateMember->setAccess(AS);
3753
3754 // C++ [temp.deduct.guide]p3:
3755 // A deduction guide [...] for a member class template [shall be
3756 // declared] with the same access [as the template].
3757 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(Val: NonTemplateMember)) {
3758 auto *TD = DG->getDeducedTemplate();
3759 // Access specifiers are only meaningful if both the template and the
3760 // deduction guide are from the same scope.
3761 if (AS != TD->getAccess() &&
3762 TD->getDeclContext()->getRedeclContext()->Equals(
3763 DC: DG->getDeclContext()->getRedeclContext())) {
3764 Diag(Loc: DG->getBeginLoc(), DiagID: diag::err_deduction_guide_wrong_access);
3765 Diag(Loc: TD->getBeginLoc(), DiagID: diag::note_deduction_guide_template_access)
3766 << TD->getAccess();
3767 const AccessSpecDecl *LastAccessSpec = nullptr;
3768 for (const auto *D : cast<CXXRecordDecl>(Val: CurContext)->decls()) {
3769 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(Val: D))
3770 LastAccessSpec = AccessSpec;
3771 }
3772 assert(LastAccessSpec && "differing access with no access specifier");
3773 Diag(Loc: LastAccessSpec->getBeginLoc(), DiagID: diag::note_deduction_guide_access)
3774 << AS;
3775 }
3776 }
3777 }
3778
3779 if (VS.isOverrideSpecified())
3780 Member->addAttr(A: OverrideAttr::Create(Ctx&: Context, Range: VS.getOverrideLoc()));
3781 if (VS.isFinalSpecified())
3782 Member->addAttr(A: FinalAttr::Create(Ctx&: Context, Range: VS.getFinalLoc(),
3783 S: VS.isFinalSpelledSealed()
3784 ? FinalAttr::Keyword_sealed
3785 : FinalAttr::Keyword_final));
3786
3787 if (VS.getLastLocation().isValid()) {
3788 // Update the end location of a method that has a virt-specifiers.
3789 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Val: Member))
3790 MD->setRangeEnd(VS.getLastLocation());
3791 }
3792
3793 CheckOverrideControl(D: Member);
3794
3795 assert((Name || isInstField) && "No identifier for non-field ?");
3796
3797 if (isInstField) {
3798 FieldDecl *FD = cast<FieldDecl>(Val: Member);
3799 FieldCollector->Add(D: FD);
3800
3801 if (!Diags.isIgnored(DiagID: diag::warn_unused_private_field, Loc: FD->getLocation()) &&
3802 IsUnusedPrivateField(FD)) {
3803 // Remember all explicit private FieldDecls that have a name, no side
3804 // effects and are not part of a dependent type declaration.
3805 UnusedPrivateFields.insert(X: FD);
3806 }
3807 }
3808
3809 return Member;
3810}
3811
3812namespace {
3813 class UninitializedFieldVisitor
3814 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3815 Sema &S;
3816 // List of Decls to generate a warning on. Also remove Decls that become
3817 // initialized.
3818 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3819 // List of base classes of the record. Classes are removed after their
3820 // initializers.
3821 llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3822 // Vector of decls to be removed from the Decl set prior to visiting the
3823 // nodes. These Decls may have been initialized in the prior initializer.
3824 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3825 // If non-null, add a note to the warning pointing back to the constructor.
3826 const CXXConstructorDecl *Constructor;
3827 // Variables to hold state when processing an initializer list. When
3828 // InitList is true, special case initialization of FieldDecls matching
3829 // InitListFieldDecl.
3830 bool InitList;
3831 FieldDecl *InitListFieldDecl;
3832 llvm::SmallVector<unsigned, 4> InitFieldIndex;
3833
3834 public:
3835 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3836 UninitializedFieldVisitor(Sema &S,
3837 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3838 llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3839 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3840 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3841
3842 // Returns true if the use of ME is not an uninitialized use.
3843 bool IsInitListMemberExprInitialized(MemberExpr *ME,
3844 bool CheckReferenceOnly) {
3845 llvm::SmallVector<FieldDecl*, 4> Fields;
3846 bool ReferenceField = false;
3847 while (ME) {
3848 FieldDecl *FD = dyn_cast<FieldDecl>(Val: ME->getMemberDecl());
3849 if (!FD)
3850 return false;
3851 Fields.push_back(Elt: FD);
3852 if (FD->getType()->isReferenceType())
3853 ReferenceField = true;
3854 ME = dyn_cast<MemberExpr>(Val: ME->getBase()->IgnoreParenImpCasts());
3855 }
3856
3857 // Binding a reference to an uninitialized field is not an
3858 // uninitialized use.
3859 if (CheckReferenceOnly && !ReferenceField)
3860 return true;
3861
3862 // Discard the first field since it is the field decl that is being
3863 // initialized.
3864 auto UsedFields = llvm::drop_begin(RangeOrContainer: llvm::reverse(C&: Fields));
3865 auto UsedIter = UsedFields.begin();
3866 const auto UsedEnd = UsedFields.end();
3867
3868 for (const unsigned Orig : InitFieldIndex) {
3869 if (UsedIter == UsedEnd)
3870 break;
3871 const unsigned UsedIndex = (*UsedIter)->getFieldIndex();
3872 if (UsedIndex < Orig)
3873 return true;
3874 if (UsedIndex > Orig)
3875 break;
3876 ++UsedIter;
3877 }
3878
3879 return false;
3880 }
3881
3882 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3883 bool AddressOf) {
3884 if (isa<EnumConstantDecl>(Val: ME->getMemberDecl()))
3885 return;
3886
3887 // FieldME is the inner-most MemberExpr that is not an anonymous struct
3888 // or union.
3889 MemberExpr *FieldME = ME;
3890
3891 bool AllPODFields = FieldME->getType().isPODType(Context: S.Context);
3892
3893 Expr *Base = ME;
3894 while (MemberExpr *SubME =
3895 dyn_cast<MemberExpr>(Val: Base->IgnoreParenImpCasts())) {
3896
3897 if (isa<VarDecl>(Val: SubME->getMemberDecl()))
3898 return;
3899
3900 if (FieldDecl *FD = dyn_cast<FieldDecl>(Val: SubME->getMemberDecl()))
3901 if (!FD->isAnonymousStructOrUnion())
3902 FieldME = SubME;
3903
3904 if (!FieldME->getType().isPODType(Context: S.Context))
3905 AllPODFields = false;
3906
3907 Base = SubME->getBase();
3908 }
3909
3910 if (!isa<CXXThisExpr>(Val: Base->IgnoreParenImpCasts())) {
3911 Visit(S: Base);
3912 return;
3913 }
3914
3915 if (AddressOf && AllPODFields)
3916 return;
3917
3918 ValueDecl* FoundVD = FieldME->getMemberDecl();
3919
3920 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Val: Base)) {
3921 while (isa<ImplicitCastExpr>(Val: BaseCast->getSubExpr())) {
3922 BaseCast = cast<ImplicitCastExpr>(Val: BaseCast->getSubExpr());
3923 }
3924
3925 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3926 QualType T = BaseCast->getType();
3927 if (T->isPointerType() &&
3928 BaseClasses.count(Ptr: T->getPointeeType())) {
3929 S.Diag(Loc: FieldME->getExprLoc(), DiagID: diag::warn_base_class_is_uninit)
3930 << T->getPointeeType() << FoundVD;
3931 }
3932 }
3933 }
3934
3935 if (!Decls.count(Ptr: FoundVD))
3936 return;
3937
3938 const bool IsReference = FoundVD->getType()->isReferenceType();
3939
3940 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3941 // Special checking for initializer lists.
3942 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3943 return;
3944 }
3945 } else {
3946 // Prevent double warnings on use of unbounded references.
3947 if (CheckReferenceOnly && !IsReference)
3948 return;
3949 }
3950
3951 unsigned diag = IsReference
3952 ? diag::warn_reference_field_is_uninit
3953 : diag::warn_field_is_uninit;
3954 S.Diag(Loc: FieldME->getExprLoc(), DiagID: diag) << FoundVD;
3955 if (Constructor)
3956 S.Diag(Loc: Constructor->getLocation(),
3957 DiagID: diag::note_uninit_in_this_constructor)
3958 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3959
3960 }
3961
3962 void HandleValue(Expr *E, bool AddressOf) {
3963 E = E->IgnoreParens();
3964
3965 if (MemberExpr *ME = dyn_cast<MemberExpr>(Val: E)) {
3966 HandleMemberExpr(ME, CheckReferenceOnly: false /*CheckReferenceOnly*/,
3967 AddressOf /*AddressOf*/);
3968 return;
3969 }
3970
3971 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(Val: E)) {
3972 Visit(S: CO->getCond());
3973 HandleValue(E: CO->getTrueExpr(), AddressOf);
3974 HandleValue(E: CO->getFalseExpr(), AddressOf);
3975 return;
3976 }
3977
3978 if (BinaryConditionalOperator *BCO =
3979 dyn_cast<BinaryConditionalOperator>(Val: E)) {
3980 Visit(S: BCO->getCond());
3981 HandleValue(E: BCO->getFalseExpr(), AddressOf);
3982 return;
3983 }
3984
3985 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Val: E)) {
3986 HandleValue(E: OVE->getSourceExpr(), AddressOf);
3987 return;
3988 }
3989
3990 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: E)) {
3991 switch (BO->getOpcode()) {
3992 default:
3993 break;
3994 case(BO_PtrMemD):
3995 case(BO_PtrMemI):
3996 HandleValue(E: BO->getLHS(), AddressOf);
3997 Visit(S: BO->getRHS());
3998 return;
3999 case(BO_Comma):
4000 Visit(S: BO->getLHS());
4001 HandleValue(E: BO->getRHS(), AddressOf);
4002 return;
4003 }
4004 }
4005
4006 Visit(S: E);
4007 }
4008
4009 void CheckInitListExpr(InitListExpr *ILE) {
4010 InitFieldIndex.push_back(Elt: 0);
4011 for (auto *Child : ILE->children()) {
4012 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Val: Child)) {
4013 CheckInitListExpr(ILE: SubList);
4014 } else {
4015 Visit(S: Child);
4016 }
4017 ++InitFieldIndex.back();
4018 }
4019 InitFieldIndex.pop_back();
4020 }
4021
4022 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
4023 FieldDecl *Field, const Type *BaseClass) {
4024 // Remove Decls that may have been initialized in the previous
4025 // initializer.
4026 for (ValueDecl* VD : DeclsToRemove)
4027 Decls.erase(Ptr: VD);
4028 DeclsToRemove.clear();
4029
4030 Constructor = FieldConstructor;
4031 InitListExpr *ILE = dyn_cast<InitListExpr>(Val: E);
4032
4033 if (ILE && Field) {
4034 InitList = true;
4035 InitListFieldDecl = Field;
4036 InitFieldIndex.clear();
4037 CheckInitListExpr(ILE);
4038 } else {
4039 InitList = false;
4040 Visit(S: E);
4041 }
4042
4043 if (Field)
4044 Decls.erase(Ptr: Field);
4045 if (BaseClass)
4046 BaseClasses.erase(Ptr: BaseClass->getCanonicalTypeInternal());
4047 }
4048
4049 void VisitMemberExpr(MemberExpr *ME) {
4050 // All uses of unbounded reference fields will warn.
4051 HandleMemberExpr(ME, CheckReferenceOnly: true /*CheckReferenceOnly*/, AddressOf: false /*AddressOf*/);
4052 }
4053
4054 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
4055 if (E->getCastKind() == CK_LValueToRValue) {
4056 HandleValue(E: E->getSubExpr(), AddressOf: false /*AddressOf*/);
4057 return;
4058 }
4059
4060 Inherited::VisitImplicitCastExpr(S: E);
4061 }
4062
4063 void VisitCXXConstructExpr(CXXConstructExpr *E) {
4064 if (E->getConstructor()->isCopyConstructor()) {
4065 Expr *ArgExpr = E->getArg(Arg: 0);
4066 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Val: ArgExpr))
4067 if (ILE->getNumInits() == 1)
4068 ArgExpr = ILE->getInit(Init: 0);
4069 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: ArgExpr))
4070 if (ICE->getCastKind() == CK_NoOp)
4071 ArgExpr = ICE->getSubExpr();
4072 HandleValue(E: ArgExpr, AddressOf: false /*AddressOf*/);
4073 return;
4074 }
4075 Inherited::VisitCXXConstructExpr(S: E);
4076 }
4077
4078 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
4079 Expr *Callee = E->getCallee();
4080 if (isa<MemberExpr>(Val: Callee)) {
4081 HandleValue(E: Callee, AddressOf: false /*AddressOf*/);
4082 for (auto *Arg : E->arguments())
4083 Visit(S: Arg);
4084 return;
4085 }
4086
4087 Inherited::VisitCXXMemberCallExpr(S: E);
4088 }
4089
4090 void VisitCallExpr(CallExpr *E) {
4091 // Treat std::move as a use.
4092 if (E->isCallToStdMove()) {
4093 HandleValue(E: E->getArg(Arg: 0), /*AddressOf=*/false);
4094 return;
4095 }
4096
4097 Inherited::VisitCallExpr(CE: E);
4098 }
4099
4100 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
4101 Expr *Callee = E->getCallee();
4102
4103 if (isa<UnresolvedLookupExpr>(Val: Callee))
4104 return Inherited::VisitCXXOperatorCallExpr(S: E);
4105
4106 Visit(S: Callee);
4107 for (auto *Arg : E->arguments())
4108 HandleValue(E: Arg->IgnoreParenImpCasts(), AddressOf: false /*AddressOf*/);
4109 }
4110
4111 void VisitBinaryOperator(BinaryOperator *E) {
4112 // If a field assignment is detected, remove the field from the
4113 // uninitiailized field set.
4114 if (E->getOpcode() == BO_Assign)
4115 if (MemberExpr *ME = dyn_cast<MemberExpr>(Val: E->getLHS()))
4116 if (FieldDecl *FD = dyn_cast<FieldDecl>(Val: ME->getMemberDecl()))
4117 if (!FD->getType()->isReferenceType())
4118 DeclsToRemove.push_back(Elt: FD);
4119
4120 if (E->isCompoundAssignmentOp()) {
4121 HandleValue(E: E->getLHS(), AddressOf: false /*AddressOf*/);
4122 Visit(S: E->getRHS());
4123 return;
4124 }
4125
4126 Inherited::VisitBinaryOperator(S: E);
4127 }
4128
4129 void VisitUnaryOperator(UnaryOperator *E) {
4130 if (E->isIncrementDecrementOp()) {
4131 HandleValue(E: E->getSubExpr(), AddressOf: false /*AddressOf*/);
4132 return;
4133 }
4134 if (E->getOpcode() == UO_AddrOf) {
4135 if (MemberExpr *ME = dyn_cast<MemberExpr>(Val: E->getSubExpr())) {
4136 HandleValue(E: ME->getBase(), AddressOf: true /*AddressOf*/);
4137 return;
4138 }
4139 }
4140
4141 Inherited::VisitUnaryOperator(S: E);
4142 }
4143 };
4144
4145 // Diagnose value-uses of fields to initialize themselves, e.g.
4146 // foo(foo)
4147 // where foo is not also a parameter to the constructor.
4148 // Also diagnose across field uninitialized use such as
4149 // x(y), y(x)
4150 // TODO: implement -Wuninitialized and fold this into that framework.
4151 static void DiagnoseUninitializedFields(
4152 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
4153
4154 if (SemaRef.getDiagnostics().isIgnored(DiagID: diag::warn_field_is_uninit,
4155 Loc: Constructor->getLocation())) {
4156 return;
4157 }
4158
4159 if (Constructor->isInvalidDecl())
4160 return;
4161
4162 const CXXRecordDecl *RD = Constructor->getParent();
4163
4164 if (RD->isDependentContext())
4165 return;
4166
4167 // Holds fields that are uninitialized.
4168 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
4169
4170 // At the beginning, all fields are uninitialized.
4171 for (auto *I : RD->decls()) {
4172 if (auto *FD = dyn_cast<FieldDecl>(Val: I)) {
4173 UninitializedFields.insert(Ptr: FD);
4174 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(Val: I)) {
4175 UninitializedFields.insert(Ptr: IFD->getAnonField());
4176 }
4177 }
4178
4179 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
4180 for (const auto &I : RD->bases()) {
4181 // Virtual bases are initialized from the most derived class, so an
4182 // abstract base class constructor can assume it to be initialized.
4183 if (I.isVirtual() && RD->isAbstract())
4184 continue;
4185 UninitializedBaseClasses.insert(Ptr: I.getType().getCanonicalType());
4186 }
4187
4188 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
4189 return;
4190
4191 UninitializedFieldVisitor UninitializedChecker(SemaRef,
4192 UninitializedFields,
4193 UninitializedBaseClasses);
4194
4195 for (const auto *FieldInit : Constructor->inits()) {
4196 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
4197 break;
4198
4199 Expr *InitExpr = FieldInit->getInit();
4200 if (!InitExpr)
4201 continue;
4202
4203 if (CXXDefaultInitExpr *Default =
4204 dyn_cast<CXXDefaultInitExpr>(Val: InitExpr)) {
4205 InitExpr = Default->getExpr();
4206 if (!InitExpr)
4207 continue;
4208 // In class initializers will point to the constructor.
4209 UninitializedChecker.CheckInitializer(E: InitExpr, FieldConstructor: Constructor,
4210 Field: FieldInit->getAnyMember(),
4211 BaseClass: FieldInit->getBaseClass());
4212 } else {
4213 UninitializedChecker.CheckInitializer(E: InitExpr, FieldConstructor: nullptr,
4214 Field: FieldInit->getAnyMember(),
4215 BaseClass: FieldInit->getBaseClass());
4216 }
4217 }
4218 }
4219} // namespace
4220
4221void Sema::ActOnStartCXXInClassMemberInitializer() {
4222 // Create a synthetic function scope to represent the call to the constructor
4223 // that notionally surrounds a use of this initializer.
4224 PushFunctionScope();
4225}
4226
4227void Sema::ActOnStartTrailingRequiresClause(Scope *S, Declarator &D) {
4228 if (!D.isFunctionDeclarator())
4229 return;
4230 auto &FTI = D.getFunctionTypeInfo();
4231 if (!FTI.Params)
4232 return;
4233 for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params,
4234 FTI.NumParams)) {
4235 auto *ParamDecl = cast<NamedDecl>(Val: Param.Param);
4236 if (ParamDecl->getDeclName())
4237 PushOnScopeChains(D: ParamDecl, S, /*AddToContext=*/false);
4238 }
4239}
4240
4241ExprResult Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr) {
4242 return ActOnRequiresClause(ConstraintExpr);
4243}
4244
4245ExprResult Sema::ActOnRequiresClause(ExprResult ConstraintExpr) {
4246 if (ConstraintExpr.isInvalid())
4247 return ExprError();
4248
4249 if (DiagnoseUnexpandedParameterPack(E: ConstraintExpr.get(),
4250 UPPC: UPPC_RequiresClause))
4251 return ExprError();
4252
4253 return ConstraintExpr;
4254}
4255
4256ExprResult Sema::ConvertMemberDefaultInitExpression(FieldDecl *FD,
4257 Expr *InitExpr,
4258 SourceLocation InitLoc) {
4259 InitializedEntity Entity =
4260 InitializedEntity::InitializeMemberFromDefaultMemberInitializer(Member: FD);
4261 return ConvertMemberDefaultInitExpression(FD, Entity, InitExpr, InitLoc);
4262}
4263
4264ExprResult Sema::ConvertMemberDefaultInitExpression(
4265 FieldDecl *FD, const InitializedEntity &Entity, Expr *InitExpr,
4266 SourceLocation InitLoc) {
4267 InitializationKind Kind =
4268 FD->getInClassInitStyle() == ICIS_ListInit
4269 ? InitializationKind::CreateDirectList(InitLoc: InitExpr->getBeginLoc(),
4270 LBraceLoc: InitExpr->getBeginLoc(),
4271 RBraceLoc: InitExpr->getEndLoc())
4272 : InitializationKind::CreateCopy(InitLoc: InitExpr->getBeginLoc(), EqualLoc: InitLoc);
4273 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
4274 return Seq.Perform(S&: *this, Entity, Kind, Args: InitExpr);
4275}
4276
4277void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
4278 SourceLocation InitLoc,
4279 ExprResult InitExpr) {
4280 // Pop the notional constructor scope we created earlier.
4281 PopFunctionScopeInfo(WP: nullptr, D);
4282
4283 // Microsoft C++'s property declaration cannot have a default member
4284 // initializer.
4285 if (isa<MSPropertyDecl>(Val: D)) {
4286 D->setInvalidDecl();
4287 return;
4288 }
4289
4290 FieldDecl *FD = dyn_cast<FieldDecl>(Val: D);
4291 assert((FD && FD->getInClassInitStyle() != ICIS_NoInit) &&
4292 "must set init style when field is created");
4293
4294 if (!InitExpr.isUsable() ||
4295 DiagnoseUnexpandedParameterPack(E: InitExpr.get(), UPPC: UPPC_Initializer)) {
4296 FD->setInvalidDecl();
4297 ExprResult RecoveryInit =
4298 CreateRecoveryExpr(Begin: InitLoc, End: InitLoc, SubExprs: {}, T: FD->getType());
4299 if (RecoveryInit.isUsable())
4300 FD->setInClassInitializer(RecoveryInit.get());
4301 return;
4302 }
4303
4304 if (!FD->getType()->isDependentType() && !InitExpr.get()->isTypeDependent()) {
4305 InitExpr = ConvertMemberDefaultInitExpression(FD, InitExpr: InitExpr.get(), InitLoc);
4306 // C++11 [class.base.init]p7:
4307 // The initialization of each base and member constitutes a
4308 // full-expression.
4309 if (!InitExpr.isInvalid())
4310 InitExpr = ActOnFinishFullExpr(Expr: InitExpr.get(), /*DiscarededValue=*/DiscardedValue: false);
4311 if (InitExpr.isInvalid()) {
4312 FD->setInvalidDecl();
4313 return;
4314 }
4315 }
4316
4317 FD->setInClassInitializer(InitExpr.get());
4318}
4319
4320/// Find the direct and/or virtual base specifiers that
4321/// correspond to the given base type, for use in base initialization
4322/// within a constructor.
4323static bool FindBaseInitializer(Sema &SemaRef,
4324 CXXRecordDecl *ClassDecl,
4325 QualType BaseType,
4326 const CXXBaseSpecifier *&DirectBaseSpec,
4327 const CXXBaseSpecifier *&VirtualBaseSpec) {
4328 // First, check for a direct base class.
4329 DirectBaseSpec = nullptr;
4330 for (const auto &Base : ClassDecl->bases()) {
4331 if (SemaRef.Context.hasSameUnqualifiedType(T1: BaseType, T2: Base.getType())) {
4332 // We found a direct base of this type. That's what we're
4333 // initializing.
4334 DirectBaseSpec = &Base;
4335 break;
4336 }
4337 }
4338
4339 // Check for a virtual base class.
4340 // FIXME: We might be able to short-circuit this if we know in advance that
4341 // there are no virtual bases.
4342 VirtualBaseSpec = nullptr;
4343 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
4344 // We haven't found a base yet; search the class hierarchy for a
4345 // virtual base class.
4346 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
4347 /*DetectVirtual=*/false);
4348 if (SemaRef.IsDerivedFrom(Loc: ClassDecl->getLocation(),
4349 Derived: SemaRef.Context.getCanonicalTagType(TD: ClassDecl),
4350 Base: BaseType, Paths)) {
4351 for (const CXXBasePath &Path : Paths) {
4352 if (Path.back().Base->isVirtual()) {
4353 VirtualBaseSpec = Path.back().Base;
4354 break;
4355 }
4356 }
4357 }
4358 }
4359
4360 return DirectBaseSpec || VirtualBaseSpec;
4361}
4362
4363MemInitResult
4364Sema::ActOnMemInitializer(Decl *ConstructorD,
4365 Scope *S,
4366 CXXScopeSpec &SS,
4367 IdentifierInfo *MemberOrBase,
4368 ParsedType TemplateTypeTy,
4369 const DeclSpec &DS,
4370 SourceLocation IdLoc,
4371 Expr *InitList,
4372 SourceLocation EllipsisLoc) {
4373 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4374 DS, IdLoc, Init: InitList,
4375 EllipsisLoc);
4376}
4377
4378MemInitResult
4379Sema::ActOnMemInitializer(Decl *ConstructorD,
4380 Scope *S,
4381 CXXScopeSpec &SS,
4382 IdentifierInfo *MemberOrBase,
4383 ParsedType TemplateTypeTy,
4384 const DeclSpec &DS,
4385 SourceLocation IdLoc,
4386 SourceLocation LParenLoc,
4387 ArrayRef<Expr *> Args,
4388 SourceLocation RParenLoc,
4389 SourceLocation EllipsisLoc) {
4390 Expr *List = ParenListExpr::Create(Ctx: Context, LParenLoc, Exprs: Args, RParenLoc);
4391 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4392 DS, IdLoc, Init: List, EllipsisLoc);
4393}
4394
4395namespace {
4396
4397// Callback to only accept typo corrections that can be a valid C++ member
4398// initializer: either a non-static field member or a base class.
4399class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
4400public:
4401 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
4402 : ClassDecl(ClassDecl) {}
4403
4404 bool ValidateCandidate(const TypoCorrection &candidate) override {
4405 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
4406 if (FieldDecl *Member = dyn_cast<FieldDecl>(Val: ND))
4407 return Member->getDeclContext()->getRedeclContext()->Equals(DC: ClassDecl);
4408 return isa<TypeDecl>(Val: ND);
4409 }
4410 return false;
4411 }
4412
4413 std::unique_ptr<CorrectionCandidateCallback> clone() override {
4414 return std::make_unique<MemInitializerValidatorCCC>(args&: *this);
4415 }
4416
4417private:
4418 CXXRecordDecl *ClassDecl;
4419};
4420
4421}
4422
4423bool Sema::DiagRedefinedPlaceholderFieldDecl(SourceLocation Loc,
4424 RecordDecl *ClassDecl,
4425 const IdentifierInfo *Name) {
4426 DeclContextLookupResult Result = ClassDecl->lookup(Name);
4427 DeclContextLookupResult::iterator Found =
4428 llvm::find_if(Range&: Result, P: [this](const NamedDecl *Elem) {
4429 return isa<FieldDecl, IndirectFieldDecl>(Val: Elem) &&
4430 Elem->isPlaceholderVar(LangOpts: getLangOpts());
4431 });
4432 // We did not find a placeholder variable
4433 if (Found == Result.end())
4434 return false;
4435 Diag(Loc, DiagID: diag::err_using_placeholder_variable) << Name;
4436 for (DeclContextLookupResult::iterator It = Found; It != Result.end(); It++) {
4437 const NamedDecl *ND = *It;
4438 if (ND->getDeclContext() != ND->getDeclContext())
4439 break;
4440 if (isa<FieldDecl, IndirectFieldDecl>(Val: ND) &&
4441 ND->isPlaceholderVar(LangOpts: getLangOpts()))
4442 Diag(Loc: ND->getLocation(), DiagID: diag::note_reference_placeholder) << ND;
4443 }
4444 return true;
4445}
4446
4447ValueDecl *
4448Sema::tryLookupUnambiguousFieldDecl(RecordDecl *ClassDecl,
4449 const IdentifierInfo *MemberOrBase) {
4450 ValueDecl *ND = nullptr;
4451 for (auto *D : ClassDecl->lookup(Name: MemberOrBase)) {
4452 if (isa<FieldDecl, IndirectFieldDecl>(Val: D)) {
4453 bool IsPlaceholder = D->isPlaceholderVar(LangOpts: getLangOpts());
4454 if (ND) {
4455 if (IsPlaceholder && D->getDeclContext() == ND->getDeclContext())
4456 return nullptr;
4457 break;
4458 }
4459 if (!IsPlaceholder)
4460 return cast<ValueDecl>(Val: D);
4461 ND = cast<ValueDecl>(Val: D);
4462 }
4463 }
4464 return ND;
4465}
4466
4467ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
4468 CXXScopeSpec &SS,
4469 ParsedType TemplateTypeTy,
4470 IdentifierInfo *MemberOrBase) {
4471 if (SS.getScopeRep() || TemplateTypeTy)
4472 return nullptr;
4473 return tryLookupUnambiguousFieldDecl(ClassDecl, MemberOrBase);
4474}
4475
4476MemInitResult
4477Sema::BuildMemInitializer(Decl *ConstructorD,
4478 Scope *S,
4479 CXXScopeSpec &SS,
4480 IdentifierInfo *MemberOrBase,
4481 ParsedType TemplateTypeTy,
4482 const DeclSpec &DS,
4483 SourceLocation IdLoc,
4484 Expr *Init,
4485 SourceLocation EllipsisLoc) {
4486 if (!ConstructorD || !Init)
4487 return true;
4488
4489 AdjustDeclIfTemplate(Decl&: ConstructorD);
4490
4491 CXXConstructorDecl *Constructor
4492 = dyn_cast<CXXConstructorDecl>(Val: ConstructorD);
4493 if (!Constructor) {
4494 // The user wrote a constructor initializer on a function that is
4495 // not a C++ constructor. Ignore the error for now, because we may
4496 // have more member initializers coming; we'll diagnose it just
4497 // once in ActOnMemInitializers.
4498 return true;
4499 }
4500
4501 CXXRecordDecl *ClassDecl = Constructor->getParent();
4502
4503 // C++ [class.base.init]p2:
4504 // Names in a mem-initializer-id are looked up in the scope of the
4505 // constructor's class and, if not found in that scope, are looked
4506 // up in the scope containing the constructor's definition.
4507 // [Note: if the constructor's class contains a member with the
4508 // same name as a direct or virtual base class of the class, a
4509 // mem-initializer-id naming the member or base class and composed
4510 // of a single identifier refers to the class member. A
4511 // mem-initializer-id for the hidden base class may be specified
4512 // using a qualified name. ]
4513
4514 // Look for a member, first.
4515 if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
4516 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
4517 if (EllipsisLoc.isValid())
4518 Diag(Loc: EllipsisLoc, DiagID: diag::err_pack_expansion_member_init)
4519 << MemberOrBase
4520 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4521
4522 return BuildMemberInitializer(Member, Init, IdLoc);
4523 }
4524 // It didn't name a member, so see if it names a class.
4525 QualType BaseType;
4526 TypeSourceInfo *TInfo = nullptr;
4527
4528 if (TemplateTypeTy) {
4529 BaseType = GetTypeFromParser(Ty: TemplateTypeTy, TInfo: &TInfo);
4530 if (BaseType.isNull())
4531 return true;
4532 } else if (DS.getTypeSpecType() == TST_decltype) {
4533 BaseType = BuildDecltypeType(E: DS.getRepAsExpr());
4534 } else if (DS.getTypeSpecType() == TST_decltype_auto) {
4535 Diag(Loc: DS.getTypeSpecTypeLoc(), DiagID: diag::err_decltype_auto_invalid);
4536 return true;
4537 } else if (DS.getTypeSpecType() == TST_typename_pack_indexing) {
4538 BaseType =
4539 BuildPackIndexingType(Pattern: DS.getRepAsType().get(), IndexExpr: DS.getPackIndexingExpr(),
4540 Loc: DS.getBeginLoc(), EllipsisLoc: DS.getEllipsisLoc());
4541 } else {
4542 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
4543 LookupParsedName(R, S, SS: &SS, /*ObjectType=*/QualType());
4544
4545 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
4546 if (!TyD) {
4547 if (R.isAmbiguous()) return true;
4548
4549 // We don't want access-control diagnostics here.
4550 R.suppressDiagnostics();
4551
4552 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
4553 bool NotUnknownSpecialization = false;
4554 DeclContext *DC = computeDeclContext(SS, EnteringContext: false);
4555 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Val: DC))
4556 NotUnknownSpecialization = !Record->hasAnyDependentBases();
4557
4558 if (!NotUnknownSpecialization) {
4559 // When the scope specifier can refer to a member of an unknown
4560 // specialization, we take it as a type name.
4561 BaseType = CheckTypenameType(
4562 Keyword: ElaboratedTypeKeyword::None, KeywordLoc: SourceLocation(),
4563 QualifierLoc: SS.getWithLocInContext(Context), II: *MemberOrBase, IILoc: IdLoc);
4564 if (BaseType.isNull())
4565 return true;
4566
4567 TInfo = Context.CreateTypeSourceInfo(T: BaseType);
4568 DependentNameTypeLoc TL =
4569 TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
4570 if (!TL.isNull()) {
4571 TL.setNameLoc(IdLoc);
4572 TL.setElaboratedKeywordLoc(SourceLocation());
4573 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4574 }
4575
4576 R.clear();
4577 R.setLookupName(MemberOrBase);
4578 }
4579 }
4580
4581 if (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus20) {
4582 if (auto UnqualifiedBase = R.getAsSingle<ClassTemplateDecl>()) {
4583 auto *TempSpec = cast<TemplateSpecializationType>(
4584 Val: UnqualifiedBase->getCanonicalInjectedSpecializationType(Ctx: Context));
4585 TemplateName TN = TempSpec->getTemplateName();
4586 for (auto const &Base : ClassDecl->bases()) {
4587 auto BaseTemplate =
4588 Base.getType()->getAs<TemplateSpecializationType>();
4589 if (BaseTemplate &&
4590 Context.hasSameTemplateName(X: BaseTemplate->getTemplateName(), Y: TN,
4591 /*IgnoreDeduced=*/true)) {
4592 Diag(Loc: IdLoc, DiagID: diag::ext_unqualified_base_class)
4593 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4594 BaseType = Base.getType();
4595 break;
4596 }
4597 }
4598 }
4599 }
4600
4601 // If no results were found, try to correct typos.
4602 TypoCorrection Corr;
4603 MemInitializerValidatorCCC CCC(ClassDecl);
4604 if (R.empty() && BaseType.isNull() &&
4605 (Corr =
4606 CorrectTypo(Typo: R.getLookupNameInfo(), LookupKind: R.getLookupKind(), S, SS: &SS,
4607 CCC, Mode: CorrectTypoKind::ErrorRecovery, MemberContext: ClassDecl))) {
4608 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
4609 // We have found a non-static data member with a similar
4610 // name to what was typed; complain and initialize that
4611 // member.
4612 diagnoseTypo(Correction: Corr,
4613 TypoDiag: PDiag(DiagID: diag::err_mem_init_not_member_or_class_suggest)
4614 << MemberOrBase << true);
4615 return BuildMemberInitializer(Member, Init, IdLoc);
4616 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
4617 const CXXBaseSpecifier *DirectBaseSpec;
4618 const CXXBaseSpecifier *VirtualBaseSpec;
4619 if (FindBaseInitializer(SemaRef&: *this, ClassDecl,
4620 BaseType: Context.getTypeDeclType(Decl: Type),
4621 DirectBaseSpec, VirtualBaseSpec)) {
4622 // We have found a direct or virtual base class with a
4623 // similar name to what was typed; complain and initialize
4624 // that base class.
4625 diagnoseTypo(Correction: Corr,
4626 TypoDiag: PDiag(DiagID: diag::err_mem_init_not_member_or_class_suggest)
4627 << MemberOrBase << false,
4628 PrevNote: PDiag() /*Suppress note, we provide our own.*/);
4629
4630 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
4631 : VirtualBaseSpec;
4632 Diag(Loc: BaseSpec->getBeginLoc(), DiagID: diag::note_base_class_specified_here)
4633 << BaseSpec->getType() << BaseSpec->getSourceRange();
4634
4635 TyD = Type;
4636 }
4637 }
4638 }
4639
4640 if (!TyD && BaseType.isNull()) {
4641 Diag(Loc: IdLoc, DiagID: diag::err_mem_init_not_member_or_class)
4642 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4643 return true;
4644 }
4645 }
4646
4647 if (BaseType.isNull()) {
4648 MarkAnyDeclReferenced(Loc: TyD->getLocation(), D: TyD, /*OdrUse=*/MightBeOdrUse: false);
4649
4650 TypeLocBuilder TLB;
4651 // FIXME: This is missing building the UsingType for TyD, if any.
4652 if (const auto *TD = dyn_cast<TagDecl>(Val: TyD)) {
4653 BaseType = Context.getTagType(Keyword: ElaboratedTypeKeyword::None,
4654 Qualifier: SS.getScopeRep(), TD, /*OwnsTag=*/false);
4655 auto TL = TLB.push<TagTypeLoc>(T: BaseType);
4656 TL.setElaboratedKeywordLoc(SourceLocation());
4657 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4658 TL.setNameLoc(IdLoc);
4659 } else if (auto *TN = dyn_cast<TypedefNameDecl>(Val: TyD)) {
4660 BaseType = Context.getTypedefType(Keyword: ElaboratedTypeKeyword::None,
4661 Qualifier: SS.getScopeRep(), Decl: TN);
4662 TLB.push<TypedefTypeLoc>(T: BaseType).set(
4663 /*ElaboratedKeywordLoc=*/SourceLocation(),
4664 QualifierLoc: SS.getWithLocInContext(Context), NameLoc: IdLoc);
4665 } else if (auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(Val: TyD)) {
4666 BaseType = Context.getUnresolvedUsingType(Keyword: ElaboratedTypeKeyword::None,
4667 Qualifier: SS.getScopeRep(), D: UD);
4668 TLB.push<UnresolvedUsingTypeLoc>(T: BaseType).set(
4669 /*ElaboratedKeywordLoc=*/SourceLocation(),
4670 QualifierLoc: SS.getWithLocInContext(Context), NameLoc: IdLoc);
4671 } else {
4672 // FIXME: What else can appear here?
4673 assert(SS.isEmpty());
4674 BaseType = Context.getTypeDeclType(Decl: TyD);
4675 TLB.pushTypeSpec(T: BaseType).setNameLoc(IdLoc);
4676 }
4677 TInfo = TLB.getTypeSourceInfo(Context, T: BaseType);
4678 }
4679 }
4680
4681 if (!TInfo)
4682 TInfo = Context.getTrivialTypeSourceInfo(T: BaseType, Loc: IdLoc);
4683
4684 return BuildBaseInitializer(BaseType, BaseTInfo: TInfo, Init, ClassDecl, EllipsisLoc);
4685}
4686
4687MemInitResult
4688Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
4689 SourceLocation IdLoc) {
4690 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Val: Member);
4691 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Val: Member);
4692 assert((DirectMember || IndirectMember) &&
4693 "Member must be a FieldDecl or IndirectFieldDecl");
4694
4695 if (DiagnoseUnexpandedParameterPack(E: Init, UPPC: UPPC_Initializer))
4696 return true;
4697
4698 if (Member->isInvalidDecl())
4699 return true;
4700
4701 MultiExprArg Args;
4702 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Val: Init)) {
4703 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4704 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Val: Init)) {
4705 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4706 } else {
4707 // Template instantiation doesn't reconstruct ParenListExprs for us.
4708 Args = Init;
4709 }
4710
4711 SourceRange InitRange = Init->getSourceRange();
4712
4713 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4714 // Can't check initialization for a member of dependent type or when
4715 // any of the arguments are type-dependent expressions.
4716 DiscardCleanupsInEvaluationContext();
4717 } else {
4718 bool InitList = false;
4719 if (isa<InitListExpr>(Val: Init)) {
4720 InitList = true;
4721 Args = Init;
4722 }
4723
4724 // Initialize the member.
4725 InitializedEntity MemberEntity =
4726 DirectMember ? InitializedEntity::InitializeMember(Member: DirectMember, Parent: nullptr)
4727 : InitializedEntity::InitializeMember(Member: IndirectMember,
4728 Parent: nullptr);
4729 InitializationKind Kind =
4730 InitList ? InitializationKind::CreateDirectList(
4731 InitLoc: IdLoc, LBraceLoc: Init->getBeginLoc(), RBraceLoc: Init->getEndLoc())
4732 : InitializationKind::CreateDirect(InitLoc: IdLoc, LParenLoc: InitRange.getBegin(),
4733 RParenLoc: InitRange.getEnd());
4734
4735 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4736 ExprResult MemberInit = InitSeq.Perform(S&: *this, Entity: MemberEntity, Kind, Args,
4737 ResultType: nullptr);
4738 if (!MemberInit.isInvalid()) {
4739 // C++11 [class.base.init]p7:
4740 // The initialization of each base and member constitutes a
4741 // full-expression.
4742 MemberInit = ActOnFinishFullExpr(Expr: MemberInit.get(), CC: InitRange.getBegin(),
4743 /*DiscardedValue*/ false);
4744 }
4745
4746 if (MemberInit.isInvalid()) {
4747 // Args were sensible expressions but we couldn't initialize the member
4748 // from them. Preserve them in a RecoveryExpr instead.
4749 Init = CreateRecoveryExpr(Begin: InitRange.getBegin(), End: InitRange.getEnd(), SubExprs: Args,
4750 T: Member->getType())
4751 .get();
4752 if (!Init)
4753 return true;
4754 } else {
4755 Init = MemberInit.get();
4756 }
4757 }
4758
4759 if (DirectMember) {
4760 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4761 InitRange.getBegin(), Init,
4762 InitRange.getEnd());
4763 } else {
4764 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4765 InitRange.getBegin(), Init,
4766 InitRange.getEnd());
4767 }
4768}
4769
4770MemInitResult
4771Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
4772 CXXRecordDecl *ClassDecl) {
4773 SourceLocation NameLoc = TInfo->getTypeLoc().getSourceRange().getBegin();
4774 if (!LangOpts.CPlusPlus11)
4775 return Diag(Loc: NameLoc, DiagID: diag::err_delegating_ctor)
4776 << TInfo->getTypeLoc().getSourceRange();
4777 Diag(Loc: NameLoc, DiagID: diag::warn_cxx98_compat_delegating_ctor);
4778
4779 bool InitList = true;
4780 MultiExprArg Args = Init;
4781 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Val: Init)) {
4782 InitList = false;
4783 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4784 }
4785
4786 CanQualType ClassType = Context.getCanonicalTagType(TD: ClassDecl);
4787
4788 SourceRange InitRange = Init->getSourceRange();
4789 // Initialize the object.
4790 InitializedEntity DelegationEntity =
4791 InitializedEntity::InitializeDelegation(Type: ClassType);
4792 InitializationKind Kind =
4793 InitList ? InitializationKind::CreateDirectList(
4794 InitLoc: NameLoc, LBraceLoc: Init->getBeginLoc(), RBraceLoc: Init->getEndLoc())
4795 : InitializationKind::CreateDirect(InitLoc: NameLoc, LParenLoc: InitRange.getBegin(),
4796 RParenLoc: InitRange.getEnd());
4797 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4798 ExprResult DelegationInit = InitSeq.Perform(S&: *this, Entity: DelegationEntity, Kind,
4799 Args, ResultType: nullptr);
4800 if (!DelegationInit.isInvalid()) {
4801 assert((DelegationInit.get()->containsErrors() ||
4802 cast<CXXConstructExpr>(DelegationInit.get())->getConstructor()) &&
4803 "Delegating constructor with no target?");
4804
4805 // C++11 [class.base.init]p7:
4806 // The initialization of each base and member constitutes a
4807 // full-expression.
4808 DelegationInit = ActOnFinishFullExpr(
4809 Expr: DelegationInit.get(), CC: InitRange.getBegin(), /*DiscardedValue*/ false);
4810 }
4811
4812 if (DelegationInit.isInvalid()) {
4813 DelegationInit = CreateRecoveryExpr(Begin: InitRange.getBegin(),
4814 End: InitRange.getEnd(), SubExprs: Args, T: ClassType);
4815 if (DelegationInit.isInvalid())
4816 return true;
4817 } else {
4818 // If we are in a dependent context, template instantiation will
4819 // perform this type-checking again. Just save the arguments that we
4820 // received in a ParenListExpr.
4821 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4822 // of the information that we have about the base
4823 // initializer. However, deconstructing the ASTs is a dicey process,
4824 // and this approach is far more likely to get the corner cases right.
4825 if (CurContext->isDependentContext())
4826 DelegationInit = Init;
4827 }
4828
4829 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4830 DelegationInit.getAs<Expr>(),
4831 InitRange.getEnd());
4832}
4833
4834MemInitResult
4835Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4836 Expr *Init, CXXRecordDecl *ClassDecl,
4837 SourceLocation EllipsisLoc) {
4838 SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getBeginLoc();
4839
4840 if (!BaseType->isDependentType() && !BaseType->isRecordType())
4841 return Diag(Loc: BaseLoc, DiagID: diag::err_base_init_does_not_name_class)
4842 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
4843
4844 // C++ [class.base.init]p2:
4845 // [...] Unless the mem-initializer-id names a nonstatic data
4846 // member of the constructor's class or a direct or virtual base
4847 // of that class, the mem-initializer is ill-formed. A
4848 // mem-initializer-list can initialize a base class using any
4849 // name that denotes that base class type.
4850
4851 // We can store the initializers in "as-written" form and delay analysis until
4852 // instantiation if the constructor is dependent. But not for dependent
4853 // (broken) code in a non-template! SetCtorInitializers does not expect this.
4854 bool Dependent = CurContext->isDependentContext() &&
4855 (BaseType->isDependentType() || Init->isTypeDependent());
4856
4857 SourceRange InitRange = Init->getSourceRange();
4858 if (EllipsisLoc.isValid()) {
4859 // This is a pack expansion.
4860 if (!BaseType->containsUnexpandedParameterPack()) {
4861 Diag(Loc: EllipsisLoc, DiagID: diag::err_pack_expansion_without_parameter_packs)
4862 << SourceRange(BaseLoc, InitRange.getEnd());
4863
4864 EllipsisLoc = SourceLocation();
4865 }
4866 } else {
4867 // Check for any unexpanded parameter packs.
4868 if (DiagnoseUnexpandedParameterPack(Loc: BaseLoc, T: BaseTInfo, UPPC: UPPC_Initializer))
4869 return true;
4870
4871 if (DiagnoseUnexpandedParameterPack(E: Init, UPPC: UPPC_Initializer))
4872 return true;
4873 }
4874
4875 // Check for direct and virtual base classes.
4876 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4877 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4878 if (!Dependent) {
4879 if (declaresSameEntity(D1: ClassDecl, D2: BaseType->getAsCXXRecordDecl()))
4880 return BuildDelegatingInitializer(TInfo: BaseTInfo, Init, ClassDecl);
4881
4882 FindBaseInitializer(SemaRef&: *this, ClassDecl, BaseType, DirectBaseSpec,
4883 VirtualBaseSpec);
4884
4885 // C++ [base.class.init]p2:
4886 // Unless the mem-initializer-id names a nonstatic data member of the
4887 // constructor's class or a direct or virtual base of that class, the
4888 // mem-initializer is ill-formed.
4889 if (!DirectBaseSpec && !VirtualBaseSpec) {
4890 // If the class has any dependent bases, then it's possible that
4891 // one of those types will resolve to the same type as
4892 // BaseType. Therefore, just treat this as a dependent base
4893 // class initialization. FIXME: Should we try to check the
4894 // initialization anyway? It seems odd.
4895 if (ClassDecl->hasAnyDependentBases())
4896 Dependent = true;
4897 else
4898 return Diag(Loc: BaseLoc, DiagID: diag::err_not_direct_base_or_virtual)
4899 << BaseType << Context.getCanonicalTagType(TD: ClassDecl)
4900 << BaseTInfo->getTypeLoc().getSourceRange();
4901 }
4902 }
4903
4904 if (Dependent) {
4905 DiscardCleanupsInEvaluationContext();
4906
4907 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4908 /*IsVirtual=*/false,
4909 InitRange.getBegin(), Init,
4910 InitRange.getEnd(), EllipsisLoc);
4911 }
4912
4913 // C++ [base.class.init]p2:
4914 // If a mem-initializer-id is ambiguous because it designates both
4915 // a direct non-virtual base class and an inherited virtual base
4916 // class, the mem-initializer is ill-formed.
4917 if (DirectBaseSpec && VirtualBaseSpec)
4918 return Diag(Loc: BaseLoc, DiagID: diag::err_base_init_direct_and_virtual)
4919 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4920
4921 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4922 if (!BaseSpec)
4923 BaseSpec = VirtualBaseSpec;
4924
4925 // Initialize the base.
4926 bool InitList = true;
4927 MultiExprArg Args = Init;
4928 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Val: Init)) {
4929 InitList = false;
4930 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4931 }
4932
4933 InitializedEntity BaseEntity =
4934 InitializedEntity::InitializeBase(Context, Base: BaseSpec, IsInheritedVirtualBase: VirtualBaseSpec);
4935 InitializationKind Kind =
4936 InitList ? InitializationKind::CreateDirectList(InitLoc: BaseLoc)
4937 : InitializationKind::CreateDirect(InitLoc: BaseLoc, LParenLoc: InitRange.getBegin(),
4938 RParenLoc: InitRange.getEnd());
4939 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4940 ExprResult BaseInit = InitSeq.Perform(S&: *this, Entity: BaseEntity, Kind, Args, ResultType: nullptr);
4941 if (!BaseInit.isInvalid()) {
4942 // C++11 [class.base.init]p7:
4943 // The initialization of each base and member constitutes a
4944 // full-expression.
4945 BaseInit = ActOnFinishFullExpr(Expr: BaseInit.get(), CC: InitRange.getBegin(),
4946 /*DiscardedValue*/ false);
4947 }
4948
4949 if (BaseInit.isInvalid()) {
4950 BaseInit = CreateRecoveryExpr(Begin: InitRange.getBegin(), End: InitRange.getEnd(),
4951 SubExprs: Args, T: BaseType);
4952 if (BaseInit.isInvalid())
4953 return true;
4954 } else {
4955 // If we are in a dependent context, template instantiation will
4956 // perform this type-checking again. Just save the arguments that we
4957 // received in a ParenListExpr.
4958 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4959 // of the information that we have about the base
4960 // initializer. However, deconstructing the ASTs is a dicey process,
4961 // and this approach is far more likely to get the corner cases right.
4962 if (CurContext->isDependentContext())
4963 BaseInit = Init;
4964 }
4965
4966 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4967 BaseSpec->isVirtual(),
4968 InitRange.getBegin(),
4969 BaseInit.getAs<Expr>(),
4970 InitRange.getEnd(), EllipsisLoc);
4971}
4972
4973// Create a static_cast\<T&&>(expr).
4974static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
4975 QualType TargetType =
4976 SemaRef.BuildReferenceType(T: E->getType(), /*SpelledAsLValue*/ LValueRef: false,
4977 Loc: SourceLocation(), Entity: DeclarationName());
4978 SourceLocation ExprLoc = E->getBeginLoc();
4979 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4980 T: TargetType, Loc: ExprLoc);
4981
4982 return SemaRef.BuildCXXNamedCast(OpLoc: ExprLoc, Kind: tok::kw_static_cast, Ty: TargetLoc, E,
4983 AngleBrackets: SourceRange(ExprLoc, ExprLoc),
4984 Parens: E->getSourceRange()).get();
4985}
4986
4987/// ImplicitInitializerKind - How an implicit base or member initializer should
4988/// initialize its base or member.
4989enum ImplicitInitializerKind {
4990 IIK_Default,
4991 IIK_Copy,
4992 IIK_Move,
4993 IIK_Inherit
4994};
4995
4996static bool
4997BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4998 ImplicitInitializerKind ImplicitInitKind,
4999 CXXBaseSpecifier *BaseSpec,
5000 bool IsInheritedVirtualBase,
5001 CXXCtorInitializer *&CXXBaseInit) {
5002 InitializedEntity InitEntity
5003 = InitializedEntity::InitializeBase(Context&: SemaRef.Context, Base: BaseSpec,
5004 IsInheritedVirtualBase);
5005
5006 ExprResult BaseInit;
5007
5008 switch (ImplicitInitKind) {
5009 case IIK_Inherit:
5010 case IIK_Default: {
5011 InitializationKind InitKind
5012 = InitializationKind::CreateDefault(InitLoc: Constructor->getLocation());
5013 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, {});
5014 BaseInit = InitSeq.Perform(S&: SemaRef, Entity: InitEntity, Kind: InitKind, Args: {});
5015 break;
5016 }
5017
5018 case IIK_Move:
5019 case IIK_Copy: {
5020 bool Moving = ImplicitInitKind == IIK_Move;
5021 ParmVarDecl *Param = Constructor->getParamDecl(i: 0);
5022 QualType ParamType = Param->getType().getNonReferenceType();
5023
5024 Expr *CopyCtorArg =
5025 DeclRefExpr::Create(Context: SemaRef.Context, QualifierLoc: NestedNameSpecifierLoc(),
5026 TemplateKWLoc: SourceLocation(), D: Param, RefersToEnclosingVariableOrCapture: false,
5027 NameLoc: Constructor->getLocation(), T: ParamType,
5028 VK: VK_LValue, FoundD: nullptr);
5029
5030 SemaRef.MarkDeclRefReferenced(E: cast<DeclRefExpr>(Val: CopyCtorArg));
5031
5032 // Cast to the base class to avoid ambiguities.
5033 QualType ArgTy =
5034 SemaRef.Context.getQualifiedType(T: BaseSpec->getType().getUnqualifiedType(),
5035 Qs: ParamType.getQualifiers());
5036
5037 if (Moving) {
5038 CopyCtorArg = CastForMoving(SemaRef, E: CopyCtorArg);
5039 }
5040
5041 CXXCastPath BasePath;
5042 BasePath.push_back(Elt: BaseSpec);
5043 CopyCtorArg = SemaRef.ImpCastExprToType(E: CopyCtorArg, Type: ArgTy,
5044 CK: CK_UncheckedDerivedToBase,
5045 VK: Moving ? VK_XValue : VK_LValue,
5046 BasePath: &BasePath).get();
5047
5048 InitializationKind InitKind
5049 = InitializationKind::CreateDirect(InitLoc: Constructor->getLocation(),
5050 LParenLoc: SourceLocation(), RParenLoc: SourceLocation());
5051 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
5052 BaseInit = InitSeq.Perform(S&: SemaRef, Entity: InitEntity, Kind: InitKind, Args: CopyCtorArg);
5053 break;
5054 }
5055 }
5056
5057 BaseInit = SemaRef.MaybeCreateExprWithCleanups(SubExpr: BaseInit);
5058 if (BaseInit.isInvalid())
5059 return true;
5060
5061 CXXBaseInit =
5062 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5063 SemaRef.Context.getTrivialTypeSourceInfo(T: BaseSpec->getType(),
5064 Loc: SourceLocation()),
5065 BaseSpec->isVirtual(),
5066 SourceLocation(),
5067 BaseInit.getAs<Expr>(),
5068 SourceLocation(),
5069 SourceLocation());
5070
5071 return false;
5072}
5073
5074static bool RefersToRValueRef(Expr *MemRef) {
5075 ValueDecl *Referenced = cast<MemberExpr>(Val: MemRef)->getMemberDecl();
5076 return Referenced->getType()->isRValueReferenceType();
5077}
5078
5079static bool
5080BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
5081 ImplicitInitializerKind ImplicitInitKind,
5082 FieldDecl *Field, IndirectFieldDecl *Indirect,
5083 CXXCtorInitializer *&CXXMemberInit) {
5084 if (Field->isInvalidDecl())
5085 return true;
5086
5087 SourceLocation Loc = Constructor->getLocation();
5088
5089 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
5090 bool Moving = ImplicitInitKind == IIK_Move;
5091 ParmVarDecl *Param = Constructor->getParamDecl(i: 0);
5092 QualType ParamType = Param->getType().getNonReferenceType();
5093
5094 // Suppress copying zero-width bitfields.
5095 if (Field->isZeroLengthBitField())
5096 return false;
5097
5098 Expr *MemberExprBase =
5099 DeclRefExpr::Create(Context: SemaRef.Context, QualifierLoc: NestedNameSpecifierLoc(),
5100 TemplateKWLoc: SourceLocation(), D: Param, RefersToEnclosingVariableOrCapture: false,
5101 NameLoc: Loc, T: ParamType, VK: VK_LValue, FoundD: nullptr);
5102
5103 SemaRef.MarkDeclRefReferenced(E: cast<DeclRefExpr>(Val: MemberExprBase));
5104
5105 if (Moving) {
5106 MemberExprBase = CastForMoving(SemaRef, E: MemberExprBase);
5107 }
5108
5109 // Build a reference to this field within the parameter.
5110 CXXScopeSpec SS;
5111 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
5112 Sema::LookupMemberName);
5113 MemberLookup.addDecl(D: Indirect ? cast<ValueDecl>(Val: Indirect)
5114 : cast<ValueDecl>(Val: Field), AS: AS_public);
5115 MemberLookup.resolveKind();
5116 ExprResult CtorArg
5117 = SemaRef.BuildMemberReferenceExpr(Base: MemberExprBase,
5118 BaseType: ParamType, OpLoc: Loc,
5119 /*IsArrow=*/false,
5120 SS,
5121 /*TemplateKWLoc=*/SourceLocation(),
5122 /*FirstQualifierInScope=*/nullptr,
5123 R&: MemberLookup,
5124 /*TemplateArgs=*/nullptr,
5125 /*S*/nullptr);
5126 if (CtorArg.isInvalid())
5127 return true;
5128
5129 // C++11 [class.copy]p15:
5130 // - if a member m has rvalue reference type T&&, it is direct-initialized
5131 // with static_cast<T&&>(x.m);
5132 if (RefersToRValueRef(MemRef: CtorArg.get())) {
5133 CtorArg = CastForMoving(SemaRef, E: CtorArg.get());
5134 }
5135
5136 InitializedEntity Entity =
5137 Indirect ? InitializedEntity::InitializeMemberImplicit(Member: Indirect)
5138 : InitializedEntity::InitializeMemberImplicit(Member: Field);
5139
5140 // Direct-initialize to use the copy constructor.
5141 InitializationKind InitKind =
5142 InitializationKind::CreateDirect(InitLoc: Loc, LParenLoc: SourceLocation(), RParenLoc: SourceLocation());
5143
5144 Expr *CtorArgE = CtorArg.getAs<Expr>();
5145 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
5146 ExprResult MemberInit =
5147 InitSeq.Perform(S&: SemaRef, Entity, Kind: InitKind, Args: MultiExprArg(&CtorArgE, 1));
5148 MemberInit = SemaRef.MaybeCreateExprWithCleanups(SubExpr: MemberInit);
5149 if (MemberInit.isInvalid())
5150 return true;
5151
5152 if (Indirect)
5153 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
5154 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
5155 else
5156 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
5157 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
5158 return false;
5159 }
5160
5161 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
5162 "Unhandled implicit init kind!");
5163
5164 QualType FieldBaseElementType =
5165 SemaRef.Context.getBaseElementType(QT: Field->getType());
5166
5167 if (FieldBaseElementType->isRecordType()) {
5168 InitializedEntity InitEntity =
5169 Indirect ? InitializedEntity::InitializeMemberImplicit(Member: Indirect)
5170 : InitializedEntity::InitializeMemberImplicit(Member: Field);
5171 InitializationKind InitKind =
5172 InitializationKind::CreateDefault(InitLoc: Loc);
5173
5174 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, {});
5175 ExprResult MemberInit = InitSeq.Perform(S&: SemaRef, Entity: InitEntity, Kind: InitKind, Args: {});
5176
5177 MemberInit = SemaRef.MaybeCreateExprWithCleanups(SubExpr: MemberInit);
5178 if (MemberInit.isInvalid())
5179 return true;
5180
5181 if (Indirect)
5182 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5183 Indirect, Loc,
5184 Loc,
5185 MemberInit.get(),
5186 Loc);
5187 else
5188 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5189 Field, Loc, Loc,
5190 MemberInit.get(),
5191 Loc);
5192 return false;
5193 }
5194
5195 if (!Field->getParent()->isUnion()) {
5196 if (FieldBaseElementType->isReferenceType()) {
5197 SemaRef.Diag(Loc: Constructor->getLocation(),
5198 DiagID: diag::err_uninitialized_member_in_ctor)
5199 << (int)Constructor->isImplicit()
5200 << SemaRef.Context.getCanonicalTagType(TD: Constructor->getParent()) << 0
5201 << Field->getDeclName();
5202 SemaRef.Diag(Loc: Field->getLocation(), DiagID: diag::note_declared_at);
5203 return true;
5204 }
5205
5206 if (FieldBaseElementType.isConstQualified()) {
5207 SemaRef.Diag(Loc: Constructor->getLocation(),
5208 DiagID: diag::err_uninitialized_member_in_ctor)
5209 << (int)Constructor->isImplicit()
5210 << SemaRef.Context.getCanonicalTagType(TD: Constructor->getParent()) << 1
5211 << Field->getDeclName();
5212 SemaRef.Diag(Loc: Field->getLocation(), DiagID: diag::note_declared_at);
5213 return true;
5214 }
5215 }
5216
5217 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
5218 // ARC and Weak:
5219 // Default-initialize Objective-C pointers to NULL.
5220 CXXMemberInit
5221 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
5222 Loc, Loc,
5223 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
5224 Loc);
5225 return false;
5226 }
5227
5228 // Nothing to initialize.
5229 CXXMemberInit = nullptr;
5230 return false;
5231}
5232
5233namespace {
5234struct BaseAndFieldInfo {
5235 Sema &S;
5236 CXXConstructorDecl *Ctor;
5237 bool AnyErrorsInInits;
5238 ImplicitInitializerKind IIK;
5239 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
5240 SmallVector<CXXCtorInitializer*, 8> AllToInit;
5241 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
5242
5243 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
5244 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
5245 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
5246 if (Ctor->getInheritedConstructor())
5247 IIK = IIK_Inherit;
5248 else if (Generated && Ctor->isCopyConstructor())
5249 IIK = IIK_Copy;
5250 else if (Generated && Ctor->isMoveConstructor())
5251 IIK = IIK_Move;
5252 else
5253 IIK = IIK_Default;
5254 }
5255
5256 bool isImplicitCopyOrMove() const {
5257 switch (IIK) {
5258 case IIK_Copy:
5259 case IIK_Move:
5260 return true;
5261
5262 case IIK_Default:
5263 case IIK_Inherit:
5264 return false;
5265 }
5266
5267 llvm_unreachable("Invalid ImplicitInitializerKind!");
5268 }
5269
5270 bool addFieldInitializer(CXXCtorInitializer *Init) {
5271 AllToInit.push_back(Elt: Init);
5272
5273 // Check whether this initializer makes the field "used".
5274 if (Init->getInit()->HasSideEffects(Ctx: S.Context))
5275 S.UnusedPrivateFields.remove(X: Init->getAnyMember());
5276
5277 return false;
5278 }
5279
5280 bool isInactiveUnionMember(FieldDecl *Field) {
5281 RecordDecl *Record = Field->getParent();
5282 if (!Record->isUnion())
5283 return false;
5284
5285 if (FieldDecl *Active =
5286 ActiveUnionMember.lookup(Val: Record->getCanonicalDecl()))
5287 return Active != Field->getCanonicalDecl();
5288
5289 // In an implicit copy or move constructor, ignore any in-class initializer.
5290 if (isImplicitCopyOrMove())
5291 return true;
5292
5293 // If there's no explicit initialization, the field is active only if it
5294 // has an in-class initializer...
5295 if (Field->hasInClassInitializer())
5296 return false;
5297 // ... or it's an anonymous struct or union whose class has an in-class
5298 // initializer.
5299 if (!Field->isAnonymousStructOrUnion())
5300 return true;
5301 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
5302 return !FieldRD->hasInClassInitializer();
5303 }
5304
5305 /// Determine whether the given field is, or is within, a union member
5306 /// that is inactive (because there was an initializer given for a different
5307 /// member of the union, or because the union was not initialized at all).
5308 bool isWithinInactiveUnionMember(FieldDecl *Field,
5309 IndirectFieldDecl *Indirect) {
5310 if (!Indirect)
5311 return isInactiveUnionMember(Field);
5312
5313 for (auto *C : Indirect->chain()) {
5314 FieldDecl *Field = dyn_cast<FieldDecl>(Val: C);
5315 if (Field && isInactiveUnionMember(Field))
5316 return true;
5317 }
5318 return false;
5319 }
5320};
5321}
5322
5323/// Determine whether the given type is an incomplete or zero-lenfgth
5324/// array type.
5325static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
5326 if (T->isIncompleteArrayType())
5327 return true;
5328
5329 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
5330 if (ArrayT->isZeroSize())
5331 return true;
5332
5333 T = ArrayT->getElementType();
5334 }
5335
5336 return false;
5337}
5338
5339static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
5340 FieldDecl *Field,
5341 IndirectFieldDecl *Indirect = nullptr) {
5342 if (Field->isInvalidDecl())
5343 return false;
5344
5345 // Overwhelmingly common case: we have a direct initializer for this field.
5346 if (CXXCtorInitializer *Init =
5347 Info.AllBaseFields.lookup(Val: Field->getCanonicalDecl()))
5348 return Info.addFieldInitializer(Init);
5349
5350 // C++11 [class.base.init]p8:
5351 // if the entity is a non-static data member that has a
5352 // brace-or-equal-initializer and either
5353 // -- the constructor's class is a union and no other variant member of that
5354 // union is designated by a mem-initializer-id or
5355 // -- the constructor's class is not a union, and, if the entity is a member
5356 // of an anonymous union, no other member of that union is designated by
5357 // a mem-initializer-id,
5358 // the entity is initialized as specified in [dcl.init].
5359 //
5360 // We also apply the same rules to handle anonymous structs within anonymous
5361 // unions.
5362 if (Info.isWithinInactiveUnionMember(Field, Indirect))
5363 return false;
5364
5365 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
5366 ExprResult DIE =
5367 SemaRef.BuildCXXCtorDefaultInitExpr(Loc: Info.Ctor->getLocation(), Field);
5368 if (DIE.isInvalid())
5369 return true;
5370
5371 auto Entity = InitializedEntity::InitializeMemberImplicit(Member: Field);
5372 SemaRef.checkInitializerLifetime(Entity, Init: DIE.get());
5373
5374 CXXCtorInitializer *Init;
5375 if (Indirect)
5376 Init = new (SemaRef.Context)
5377 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
5378 SourceLocation(), DIE.get(), SourceLocation());
5379 else
5380 Init = new (SemaRef.Context)
5381 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
5382 SourceLocation(), DIE.get(), SourceLocation());
5383 return Info.addFieldInitializer(Init);
5384 }
5385
5386 // Don't initialize incomplete or zero-length arrays.
5387 if (isIncompleteOrZeroLengthArrayType(Context&: SemaRef.Context, T: Field->getType()))
5388 return false;
5389
5390 // Don't try to build an implicit initializer if there were semantic
5391 // errors in any of the initializers (and therefore we might be
5392 // missing some that the user actually wrote).
5393 if (Info.AnyErrorsInInits)
5394 return false;
5395
5396 CXXCtorInitializer *Init = nullptr;
5397 if (BuildImplicitMemberInitializer(SemaRef&: Info.S, Constructor: Info.Ctor, ImplicitInitKind: Info.IIK, Field,
5398 Indirect, CXXMemberInit&: Init))
5399 return true;
5400
5401 if (!Init)
5402 return false;
5403
5404 return Info.addFieldInitializer(Init);
5405}
5406
5407bool
5408Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
5409 CXXCtorInitializer *Initializer) {
5410 assert(Initializer->isDelegatingInitializer());
5411 Constructor->setNumCtorInitializers(1);
5412 CXXCtorInitializer **initializer =
5413 new (Context) CXXCtorInitializer*[1];
5414 memcpy(dest: initializer, src: &Initializer, n: sizeof (CXXCtorInitializer*));
5415 Constructor->setCtorInitializers(initializer);
5416
5417 if (CXXDestructorDecl *Dtor = LookupDestructor(Class: Constructor->getParent())) {
5418 MarkFunctionReferenced(Loc: Initializer->getSourceLocation(), Func: Dtor);
5419 DiagnoseUseOfDecl(D: Dtor, Locs: Initializer->getSourceLocation());
5420 }
5421
5422 DelegatingCtorDecls.push_back(LocalValue: Constructor);
5423
5424 DiagnoseUninitializedFields(SemaRef&: *this, Constructor);
5425
5426 return false;
5427}
5428
5429static CXXDestructorDecl *LookupDestructorIfRelevant(Sema &S,
5430 CXXRecordDecl *Class) {
5431 if (Class->isInvalidDecl())
5432 return nullptr;
5433 if (Class->hasIrrelevantDestructor())
5434 return nullptr;
5435
5436 // Dtor might still be missing, e.g because it's invalid.
5437 return S.LookupDestructor(Class);
5438}
5439
5440static void MarkFieldDestructorReferenced(Sema &S, SourceLocation Location,
5441 FieldDecl *Field) {
5442 if (Field->isInvalidDecl())
5443 return;
5444
5445 // Don't destroy incomplete or zero-length arrays.
5446 if (isIncompleteOrZeroLengthArrayType(Context&: S.Context, T: Field->getType()))
5447 return;
5448
5449 QualType FieldType = S.Context.getBaseElementType(QT: Field->getType());
5450
5451 auto *FieldClassDecl = FieldType->getAsCXXRecordDecl();
5452 if (!FieldClassDecl)
5453 return;
5454
5455 // The destructor for an implicit anonymous union member is never invoked.
5456 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5457 return;
5458
5459 auto *Dtor = LookupDestructorIfRelevant(S, Class: FieldClassDecl);
5460 if (!Dtor)
5461 return;
5462
5463 S.CheckDestructorAccess(Loc: Field->getLocation(), Dtor,
5464 PDiag: S.PDiag(DiagID: diag::err_access_dtor_field)
5465 << Field->getDeclName() << FieldType);
5466
5467 S.MarkFunctionReferenced(Loc: Location, Func: Dtor);
5468 S.DiagnoseUseOfDecl(D: Dtor, Locs: Location);
5469}
5470
5471static void MarkBaseDestructorsReferenced(Sema &S, SourceLocation Location,
5472 CXXRecordDecl *ClassDecl) {
5473 if (ClassDecl->isDependentContext())
5474 return;
5475
5476 // We only potentially invoke the destructors of potentially constructed
5477 // subobjects.
5478 bool VisitVirtualBases = !ClassDecl->isAbstract();
5479
5480 // If the destructor exists and has already been marked used in the MS ABI,
5481 // then virtual base destructors have already been checked and marked used.
5482 // Skip checking them again to avoid duplicate diagnostics.
5483 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5484 CXXDestructorDecl *Dtor = ClassDecl->getDestructor();
5485 if (Dtor && Dtor->isUsed())
5486 VisitVirtualBases = false;
5487 }
5488
5489 llvm::SmallPtrSet<const CXXRecordDecl *, 8> DirectVirtualBases;
5490
5491 // Bases.
5492 for (const auto &Base : ClassDecl->bases()) {
5493 auto *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
5494 if (!BaseClassDecl)
5495 continue;
5496
5497 // Remember direct virtual bases.
5498 if (Base.isVirtual()) {
5499 if (!VisitVirtualBases)
5500 continue;
5501 DirectVirtualBases.insert(Ptr: BaseClassDecl);
5502 }
5503
5504 auto *Dtor = LookupDestructorIfRelevant(S, Class: BaseClassDecl);
5505 if (!Dtor)
5506 continue;
5507
5508 // FIXME: caret should be on the start of the class name
5509 S.CheckDestructorAccess(Loc: Base.getBeginLoc(), Dtor,
5510 PDiag: S.PDiag(DiagID: diag::err_access_dtor_base)
5511 << Base.getType() << Base.getSourceRange(),
5512 objectType: S.Context.getCanonicalTagType(TD: ClassDecl));
5513
5514 S.MarkFunctionReferenced(Loc: Location, Func: Dtor);
5515 S.DiagnoseUseOfDecl(D: Dtor, Locs: Location);
5516 }
5517
5518 if (VisitVirtualBases)
5519 S.MarkVirtualBaseDestructorsReferenced(Location, ClassDecl,
5520 DirectVirtualBases: &DirectVirtualBases);
5521}
5522
5523bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5524 ArrayRef<CXXCtorInitializer *> Initializers) {
5525 if (Constructor->isDependentContext()) {
5526 // Just store the initializers as written, they will be checked during
5527 // instantiation.
5528 if (!Initializers.empty()) {
5529 Constructor->setNumCtorInitializers(Initializers.size());
5530 CXXCtorInitializer **baseOrMemberInitializers =
5531 new (Context) CXXCtorInitializer*[Initializers.size()];
5532 memcpy(dest: baseOrMemberInitializers, src: Initializers.data(),
5533 n: Initializers.size() * sizeof(CXXCtorInitializer*));
5534 Constructor->setCtorInitializers(baseOrMemberInitializers);
5535 }
5536
5537 // Let template instantiation know whether we had errors.
5538 if (AnyErrors)
5539 Constructor->setInvalidDecl();
5540
5541 return false;
5542 }
5543
5544 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
5545
5546 // We need to build the initializer AST according to order of construction
5547 // and not what user specified in the Initializers list.
5548 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
5549 if (!ClassDecl)
5550 return true;
5551
5552 bool HadError = false;
5553
5554 for (CXXCtorInitializer *Member : Initializers) {
5555 if (Member->isBaseInitializer())
5556 Info.AllBaseFields[Member->getBaseClass()->getAsCanonical<RecordType>()] =
5557 Member;
5558 else {
5559 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
5560
5561 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
5562 for (auto *C : F->chain()) {
5563 FieldDecl *FD = dyn_cast<FieldDecl>(Val: C);
5564 if (FD && FD->getParent()->isUnion())
5565 Info.ActiveUnionMember.insert(KV: std::make_pair(
5566 x: FD->getParent()->getCanonicalDecl(), y: FD->getCanonicalDecl()));
5567 }
5568 } else if (FieldDecl *FD = Member->getMember()) {
5569 if (FD->getParent()->isUnion())
5570 Info.ActiveUnionMember.insert(KV: std::make_pair(
5571 x: FD->getParent()->getCanonicalDecl(), y: FD->getCanonicalDecl()));
5572 }
5573 }
5574 }
5575
5576 // Keep track of the direct virtual bases.
5577 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
5578 for (auto &I : ClassDecl->bases()) {
5579 if (I.isVirtual())
5580 DirectVBases.insert(Ptr: &I);
5581 }
5582
5583 // Push virtual bases before others.
5584 for (auto &VBase : ClassDecl->vbases()) {
5585 if (CXXCtorInitializer *Value = Info.AllBaseFields.lookup(
5586 Val: VBase.getType()->getAsCanonical<RecordType>())) {
5587 // [class.base.init]p7, per DR257:
5588 // A mem-initializer where the mem-initializer-id names a virtual base
5589 // class is ignored during execution of a constructor of any class that
5590 // is not the most derived class.
5591 if (ClassDecl->isAbstract()) {
5592 // FIXME: Provide a fixit to remove the base specifier. This requires
5593 // tracking the location of the associated comma for a base specifier.
5594 Diag(Loc: Value->getSourceLocation(), DiagID: diag::warn_abstract_vbase_init_ignored)
5595 << VBase.getType() << ClassDecl;
5596 DiagnoseAbstractType(RD: ClassDecl);
5597 }
5598
5599 Info.AllToInit.push_back(Elt: Value);
5600 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
5601 // [class.base.init]p8, per DR257:
5602 // If a given [...] base class is not named by a mem-initializer-id
5603 // [...] and the entity is not a virtual base class of an abstract
5604 // class, then [...] the entity is default-initialized.
5605 bool IsInheritedVirtualBase = !DirectVBases.count(Ptr: &VBase);
5606 CXXCtorInitializer *CXXBaseInit;
5607 if (BuildImplicitBaseInitializer(SemaRef&: *this, Constructor, ImplicitInitKind: Info.IIK,
5608 BaseSpec: &VBase, IsInheritedVirtualBase,
5609 CXXBaseInit)) {
5610 HadError = true;
5611 continue;
5612 }
5613
5614 Info.AllToInit.push_back(Elt: CXXBaseInit);
5615 }
5616 }
5617
5618 // Non-virtual bases.
5619 for (auto &Base : ClassDecl->bases()) {
5620 // Virtuals are in the virtual base list and already constructed.
5621 if (Base.isVirtual())
5622 continue;
5623
5624 if (CXXCtorInitializer *Value = Info.AllBaseFields.lookup(
5625 Val: Base.getType()->getAsCanonical<RecordType>())) {
5626 Info.AllToInit.push_back(Elt: Value);
5627 } else if (!AnyErrors) {
5628 CXXCtorInitializer *CXXBaseInit;
5629 if (BuildImplicitBaseInitializer(SemaRef&: *this, Constructor, ImplicitInitKind: Info.IIK,
5630 BaseSpec: &Base, /*IsInheritedVirtualBase=*/false,
5631 CXXBaseInit)) {
5632 HadError = true;
5633 continue;
5634 }
5635
5636 Info.AllToInit.push_back(Elt: CXXBaseInit);
5637 }
5638 }
5639
5640 // Fields.
5641 for (auto *Mem : ClassDecl->decls()) {
5642 if (auto *F = dyn_cast<FieldDecl>(Val: Mem)) {
5643 // C++ [class.bit]p2:
5644 // A declaration for a bit-field that omits the identifier declares an
5645 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
5646 // initialized.
5647 if (F->isUnnamedBitField())
5648 continue;
5649
5650 // If we're not generating the implicit copy/move constructor, then we'll
5651 // handle anonymous struct/union fields based on their individual
5652 // indirect fields.
5653 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
5654 continue;
5655
5656 if (CollectFieldInitializer(SemaRef&: *this, Info, Field: F))
5657 HadError = true;
5658 continue;
5659 }
5660
5661 // Beyond this point, we only consider default initialization.
5662 if (Info.isImplicitCopyOrMove())
5663 continue;
5664
5665 if (auto *F = dyn_cast<IndirectFieldDecl>(Val: Mem)) {
5666 if (F->getType()->isIncompleteArrayType()) {
5667 assert(ClassDecl->hasFlexibleArrayMember() &&
5668 "Incomplete array type is not valid");
5669 continue;
5670 }
5671
5672 // Initialize each field of an anonymous struct individually.
5673 if (CollectFieldInitializer(SemaRef&: *this, Info, Field: F->getAnonField(), Indirect: F))
5674 HadError = true;
5675
5676 continue;
5677 }
5678 }
5679
5680 unsigned NumInitializers = Info.AllToInit.size();
5681 if (NumInitializers > 0) {
5682 Constructor->setNumCtorInitializers(NumInitializers);
5683 CXXCtorInitializer **baseOrMemberInitializers =
5684 new (Context) CXXCtorInitializer*[NumInitializers];
5685 memcpy(dest: baseOrMemberInitializers, src: Info.AllToInit.data(),
5686 n: NumInitializers * sizeof(CXXCtorInitializer*));
5687 Constructor->setCtorInitializers(baseOrMemberInitializers);
5688
5689 SourceLocation Location = Constructor->getLocation();
5690
5691 // Constructors implicitly reference the base and member
5692 // destructors.
5693
5694 for (CXXCtorInitializer *Initializer : Info.AllToInit) {
5695 FieldDecl *Field = Initializer->getAnyMember();
5696 if (!Field)
5697 continue;
5698
5699 // C++ [class.base.init]p12:
5700 // In a non-delegating constructor, the destructor for each
5701 // potentially constructed subobject of class type is potentially
5702 // invoked.
5703 MarkFieldDestructorReferenced(S&: *this, Location, Field);
5704 }
5705
5706 MarkBaseDestructorsReferenced(S&: *this, Location, ClassDecl: Constructor->getParent());
5707 }
5708
5709 return HadError;
5710}
5711
5712static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
5713 if (const RecordType *RT = Field->getType()->getAsCanonical<RecordType>()) {
5714 const RecordDecl *RD = RT->getDecl();
5715 if (RD->isAnonymousStructOrUnion()) {
5716 for (auto *Field : RD->getDefinitionOrSelf()->fields())
5717 PopulateKeysForFields(Field, IdealInits);
5718 return;
5719 }
5720 }
5721 IdealInits.push_back(Elt: Field->getCanonicalDecl());
5722}
5723
5724static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
5725 return Context.getCanonicalType(T: BaseType).getTypePtr();
5726}
5727
5728static const void *GetKeyForMember(ASTContext &Context,
5729 CXXCtorInitializer *Member) {
5730 if (!Member->isAnyMemberInitializer())
5731 return GetKeyForBase(Context, BaseType: QualType(Member->getBaseClass(), 0));
5732
5733 return Member->getAnyMember()->getCanonicalDecl();
5734}
5735
5736static void AddInitializerToDiag(const Sema::SemaDiagnosticBuilder &Diag,
5737 const CXXCtorInitializer *Previous,
5738 const CXXCtorInitializer *Current) {
5739 if (Previous->isAnyMemberInitializer())
5740 Diag << 0 << Previous->getAnyMember();
5741 else
5742 Diag << 1 << Previous->getTypeSourceInfo()->getType();
5743
5744 if (Current->isAnyMemberInitializer())
5745 Diag << 0 << Current->getAnyMember();
5746 else
5747 Diag << 1 << Current->getTypeSourceInfo()->getType();
5748}
5749
5750static void DiagnoseBaseOrMemInitializerOrder(
5751 Sema &SemaRef, const CXXConstructorDecl *Constructor,
5752 ArrayRef<CXXCtorInitializer *> Inits) {
5753 if (Constructor->getDeclContext()->isDependentContext())
5754 return;
5755
5756 // Don't check initializers order unless the warning is enabled at the
5757 // location of at least one initializer.
5758 bool ShouldCheckOrder = false;
5759 for (const CXXCtorInitializer *Init : Inits) {
5760 if (!SemaRef.Diags.isIgnored(DiagID: diag::warn_initializer_out_of_order,
5761 Loc: Init->getSourceLocation())) {
5762 ShouldCheckOrder = true;
5763 break;
5764 }
5765 }
5766 if (!ShouldCheckOrder)
5767 return;
5768
5769 // Build the list of bases and members in the order that they'll
5770 // actually be initialized. The explicit initializers should be in
5771 // this same order but may be missing things.
5772 SmallVector<const void*, 32> IdealInitKeys;
5773
5774 const CXXRecordDecl *ClassDecl = Constructor->getParent();
5775
5776 // 1. Virtual bases.
5777 for (const auto &VBase : ClassDecl->vbases())
5778 IdealInitKeys.push_back(Elt: GetKeyForBase(Context&: SemaRef.Context, BaseType: VBase.getType()));
5779
5780 // 2. Non-virtual bases.
5781 for (const auto &Base : ClassDecl->bases()) {
5782 if (Base.isVirtual())
5783 continue;
5784 IdealInitKeys.push_back(Elt: GetKeyForBase(Context&: SemaRef.Context, BaseType: Base.getType()));
5785 }
5786
5787 // 3. Direct fields.
5788 for (auto *Field : ClassDecl->fields()) {
5789 if (Field->isUnnamedBitField())
5790 continue;
5791
5792 PopulateKeysForFields(Field, IdealInits&: IdealInitKeys);
5793 }
5794
5795 unsigned NumIdealInits = IdealInitKeys.size();
5796 unsigned IdealIndex = 0;
5797
5798 // Track initializers that are in an incorrect order for either a warning or
5799 // note if multiple ones occur.
5800 SmallVector<unsigned> WarnIndexes;
5801 // Correlates the index of an initializer in the init-list to the index of
5802 // the field/base in the class.
5803 SmallVector<std::pair<unsigned, unsigned>, 32> CorrelatedInitOrder;
5804
5805 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5806 const void *InitKey = GetKeyForMember(Context&: SemaRef.Context, Member: Inits[InitIndex]);
5807
5808 // Scan forward to try to find this initializer in the idealized
5809 // initializers list.
5810 for (; IdealIndex != NumIdealInits; ++IdealIndex)
5811 if (InitKey == IdealInitKeys[IdealIndex])
5812 break;
5813
5814 // If we didn't find this initializer, it must be because we
5815 // scanned past it on a previous iteration. That can only
5816 // happen if we're out of order; emit a warning.
5817 if (IdealIndex == NumIdealInits && InitIndex) {
5818 WarnIndexes.push_back(Elt: InitIndex);
5819
5820 // Move back to the initializer's location in the ideal list.
5821 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5822 if (InitKey == IdealInitKeys[IdealIndex])
5823 break;
5824
5825 assert(IdealIndex < NumIdealInits &&
5826 "initializer not found in initializer list");
5827 }
5828 CorrelatedInitOrder.emplace_back(Args&: IdealIndex, Args&: InitIndex);
5829 }
5830
5831 if (WarnIndexes.empty())
5832 return;
5833
5834 // Sort based on the ideal order, first in the pair.
5835 llvm::sort(C&: CorrelatedInitOrder, Comp: llvm::less_first());
5836
5837 // Introduce a new scope as SemaDiagnosticBuilder needs to be destroyed to
5838 // emit the diagnostic before we can try adding notes.
5839 {
5840 Sema::SemaDiagnosticBuilder D = SemaRef.Diag(
5841 Loc: Inits[WarnIndexes.front() - 1]->getSourceLocation(),
5842 DiagID: WarnIndexes.size() == 1 ? diag::warn_initializer_out_of_order
5843 : diag::warn_some_initializers_out_of_order);
5844
5845 for (unsigned I = 0; I < CorrelatedInitOrder.size(); ++I) {
5846 if (CorrelatedInitOrder[I].second == I)
5847 continue;
5848 // Ideally we would be using InsertFromRange here, but clang doesn't
5849 // appear to handle InsertFromRange correctly when the source range is
5850 // modified by another fix-it.
5851 D << FixItHint::CreateReplacement(
5852 RemoveRange: Inits[I]->getSourceRange(),
5853 Code: Lexer::getSourceText(
5854 Range: CharSourceRange::getTokenRange(
5855 R: Inits[CorrelatedInitOrder[I].second]->getSourceRange()),
5856 SM: SemaRef.getSourceManager(), LangOpts: SemaRef.getLangOpts()));
5857 }
5858
5859 // If there is only 1 item out of order, the warning expects the name and
5860 // type of each being added to it.
5861 if (WarnIndexes.size() == 1) {
5862 AddInitializerToDiag(Diag: D, Previous: Inits[WarnIndexes.front() - 1],
5863 Current: Inits[WarnIndexes.front()]);
5864 return;
5865 }
5866 }
5867 // More than 1 item to warn, create notes letting the user know which ones
5868 // are bad.
5869 for (unsigned WarnIndex : WarnIndexes) {
5870 const clang::CXXCtorInitializer *PrevInit = Inits[WarnIndex - 1];
5871 auto D = SemaRef.Diag(Loc: PrevInit->getSourceLocation(),
5872 DiagID: diag::note_initializer_out_of_order);
5873 AddInitializerToDiag(Diag: D, Previous: PrevInit, Current: Inits[WarnIndex]);
5874 D << PrevInit->getSourceRange();
5875 }
5876}
5877
5878namespace {
5879bool CheckRedundantInit(Sema &S,
5880 CXXCtorInitializer *Init,
5881 CXXCtorInitializer *&PrevInit) {
5882 if (!PrevInit) {
5883 PrevInit = Init;
5884 return false;
5885 }
5886
5887 if (FieldDecl *Field = Init->getAnyMember())
5888 S.Diag(Loc: Init->getSourceLocation(),
5889 DiagID: diag::err_multiple_mem_initialization)
5890 << Field->getDeclName()
5891 << Init->getSourceRange();
5892 else {
5893 const Type *BaseClass = Init->getBaseClass();
5894 assert(BaseClass && "neither field nor base");
5895 S.Diag(Loc: Init->getSourceLocation(),
5896 DiagID: diag::err_multiple_base_initialization)
5897 << QualType(BaseClass, 0)
5898 << Init->getSourceRange();
5899 }
5900 S.Diag(Loc: PrevInit->getSourceLocation(), DiagID: diag::note_previous_initializer)
5901 << 0 << PrevInit->getSourceRange();
5902
5903 return true;
5904}
5905
5906typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5907typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5908
5909bool CheckRedundantUnionInit(Sema &S,
5910 CXXCtorInitializer *Init,
5911 RedundantUnionMap &Unions) {
5912 FieldDecl *Field = Init->getAnyMember();
5913 RecordDecl *Parent = Field->getParent();
5914 NamedDecl *Child = Field;
5915
5916 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5917 if (Parent->isUnion()) {
5918 UnionEntry &En = Unions[Parent];
5919 if (En.first && En.first != Child) {
5920 S.Diag(Loc: Init->getSourceLocation(),
5921 DiagID: diag::err_multiple_mem_union_initialization)
5922 << Field->getDeclName()
5923 << Init->getSourceRange();
5924 S.Diag(Loc: En.second->getSourceLocation(), DiagID: diag::note_previous_initializer)
5925 << 0 << En.second->getSourceRange();
5926 return true;
5927 }
5928 if (!En.first) {
5929 En.first = Child;
5930 En.second = Init;
5931 }
5932 if (!Parent->isAnonymousStructOrUnion())
5933 return false;
5934 }
5935
5936 Child = Parent;
5937 Parent = cast<RecordDecl>(Val: Parent->getDeclContext());
5938 }
5939
5940 return false;
5941}
5942} // namespace
5943
5944void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5945 SourceLocation ColonLoc,
5946 ArrayRef<CXXCtorInitializer*> MemInits,
5947 bool AnyErrors) {
5948 if (!ConstructorDecl)
5949 return;
5950
5951 AdjustDeclIfTemplate(Decl&: ConstructorDecl);
5952
5953 CXXConstructorDecl *Constructor
5954 = dyn_cast<CXXConstructorDecl>(Val: ConstructorDecl);
5955
5956 if (!Constructor) {
5957 Diag(Loc: ColonLoc, DiagID: diag::err_only_constructors_take_base_inits);
5958 return;
5959 }
5960
5961 // Mapping for the duplicate initializers check.
5962 // For member initializers, this is keyed with a FieldDecl*.
5963 // For base initializers, this is keyed with a Type*.
5964 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5965
5966 // Mapping for the inconsistent anonymous-union initializers check.
5967 RedundantUnionMap MemberUnions;
5968
5969 bool HadError = false;
5970 for (unsigned i = 0; i < MemInits.size(); i++) {
5971 CXXCtorInitializer *Init = MemInits[i];
5972
5973 // Set the source order index.
5974 Init->setSourceOrder(i);
5975
5976 if (Init->isAnyMemberInitializer()) {
5977 const void *Key = GetKeyForMember(Context, Member: Init);
5978 if (CheckRedundantInit(S&: *this, Init, PrevInit&: Members[Key]) ||
5979 CheckRedundantUnionInit(S&: *this, Init, Unions&: MemberUnions))
5980 HadError = true;
5981 } else if (Init->isBaseInitializer()) {
5982 const void *Key = GetKeyForMember(Context, Member: Init);
5983 if (CheckRedundantInit(S&: *this, Init, PrevInit&: Members[Key]))
5984 HadError = true;
5985 } else {
5986 assert(Init->isDelegatingInitializer());
5987 // This must be the only initializer
5988 if (MemInits.size() != 1) {
5989 Diag(Loc: Init->getSourceLocation(),
5990 DiagID: diag::err_delegating_initializer_alone)
5991 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5992 // We will treat this as being the only initializer.
5993 }
5994 SetDelegatingInitializer(Constructor, Initializer: MemInits[i]);
5995 // Return immediately as the initializer is set.
5996 return;
5997 }
5998 }
5999
6000 if (HadError)
6001 return;
6002
6003 DiagnoseBaseOrMemInitializerOrder(SemaRef&: *this, Constructor, Inits: MemInits);
6004
6005 SetCtorInitializers(Constructor, AnyErrors, Initializers: MemInits);
6006
6007 DiagnoseUninitializedFields(SemaRef&: *this, Constructor);
6008}
6009
6010void Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
6011 CXXRecordDecl *ClassDecl) {
6012 // Ignore dependent contexts. Also ignore unions, since their members never
6013 // have destructors implicitly called.
6014 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
6015 return;
6016
6017 // FIXME: all the access-control diagnostics are positioned on the
6018 // field/base declaration. That's probably good; that said, the
6019 // user might reasonably want to know why the destructor is being
6020 // emitted, and we currently don't say.
6021
6022 // Non-static data members.
6023 for (auto *Field : ClassDecl->fields()) {
6024 MarkFieldDestructorReferenced(S&: *this, Location, Field);
6025 }
6026
6027 MarkBaseDestructorsReferenced(S&: *this, Location, ClassDecl);
6028}
6029
6030void Sema::MarkVirtualBaseDestructorsReferenced(
6031 SourceLocation Location, CXXRecordDecl *ClassDecl,
6032 llvm::SmallPtrSetImpl<const CXXRecordDecl *> *DirectVirtualBases) {
6033 // Virtual bases.
6034 for (const auto &VBase : ClassDecl->vbases()) {
6035 auto *BaseClassDecl = VBase.getType()->getAsCXXRecordDecl();
6036 if (!BaseClassDecl)
6037 continue;
6038
6039 // Ignore already visited direct virtual bases.
6040 if (DirectVirtualBases && DirectVirtualBases->count(Ptr: BaseClassDecl))
6041 continue;
6042
6043 auto *Dtor = LookupDestructorIfRelevant(S&: *this, Class: BaseClassDecl);
6044 if (!Dtor)
6045 continue;
6046
6047 CanQualType CT = Context.getCanonicalTagType(TD: ClassDecl);
6048 if (CheckDestructorAccess(Loc: ClassDecl->getLocation(), Dtor,
6049 PDiag: PDiag(DiagID: diag::err_access_dtor_vbase)
6050 << CT << VBase.getType(),
6051 objectType: CT) == AR_accessible) {
6052 CheckDerivedToBaseConversion(
6053 Derived: CT, Base: VBase.getType(), InaccessibleBaseID: diag::err_access_dtor_vbase, AmbiguousBaseConvID: 0,
6054 Loc: ClassDecl->getLocation(), Range: SourceRange(), Name: DeclarationName(), BasePath: nullptr);
6055 }
6056
6057 MarkFunctionReferenced(Loc: Location, Func: Dtor);
6058 DiagnoseUseOfDecl(D: Dtor, Locs: Location);
6059 }
6060}
6061
6062void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
6063 if (!CDtorDecl)
6064 return;
6065
6066 if (CXXConstructorDecl *Constructor
6067 = dyn_cast<CXXConstructorDecl>(Val: CDtorDecl)) {
6068 if (CXXRecordDecl *ClassDecl = Constructor->getParent();
6069 !ClassDecl || ClassDecl->isInvalidDecl()) {
6070 return;
6071 }
6072 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
6073 DiagnoseUninitializedFields(SemaRef&: *this, Constructor);
6074 }
6075}
6076
6077bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
6078 if (!getLangOpts().CPlusPlus)
6079 return false;
6080
6081 const auto *RD = Context.getBaseElementType(QT: T)->getAsCXXRecordDecl();
6082 if (!RD)
6083 return false;
6084
6085 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
6086 // class template specialization here, but doing so breaks a lot of code.
6087
6088 // We can't answer whether something is abstract until it has a
6089 // definition. If it's currently being defined, we'll walk back
6090 // over all the declarations when we have a full definition.
6091 const CXXRecordDecl *Def = RD->getDefinition();
6092 if (!Def || Def->isBeingDefined())
6093 return false;
6094
6095 return RD->isAbstract();
6096}
6097
6098bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
6099 TypeDiagnoser &Diagnoser) {
6100 if (!isAbstractType(Loc, T))
6101 return false;
6102
6103 T = Context.getBaseElementType(QT: T);
6104 Diagnoser.diagnose(S&: *this, Loc, T);
6105 DiagnoseAbstractType(RD: T->getAsCXXRecordDecl());
6106 return true;
6107}
6108
6109void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
6110 // Check if we've already emitted the list of pure virtual functions
6111 // for this class.
6112 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(Ptr: RD))
6113 return;
6114
6115 // If the diagnostic is suppressed, don't emit the notes. We're only
6116 // going to emit them once, so try to attach them to a diagnostic we're
6117 // actually going to show.
6118 if (Diags.isLastDiagnosticIgnored())
6119 return;
6120
6121 CXXFinalOverriderMap FinalOverriders;
6122 RD->getFinalOverriders(FinaOverriders&: FinalOverriders);
6123
6124 // Keep a set of seen pure methods so we won't diagnose the same method
6125 // more than once.
6126 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
6127
6128 for (const auto &M : FinalOverriders) {
6129 for (const auto &SO : M.second) {
6130 // C++ [class.abstract]p4:
6131 // A class is abstract if it contains or inherits at least one
6132 // pure virtual function for which the final overrider is pure
6133 // virtual.
6134
6135 if (SO.second.size() != 1)
6136 continue;
6137 const CXXMethodDecl *Method = SO.second.front().Method;
6138
6139 if (!Method->isPureVirtual())
6140 continue;
6141
6142 if (!SeenPureMethods.insert(Ptr: Method).second)
6143 continue;
6144
6145 Diag(Loc: Method->getLocation(), DiagID: diag::note_pure_virtual_function)
6146 << Method->getDeclName() << RD->getDeclName();
6147 }
6148 }
6149
6150 if (!PureVirtualClassDiagSet)
6151 PureVirtualClassDiagSet.reset(p: new RecordDeclSetTy);
6152 PureVirtualClassDiagSet->insert(Ptr: RD);
6153}
6154
6155namespace {
6156struct AbstractUsageInfo {
6157 Sema &S;
6158 CXXRecordDecl *Record;
6159 CanQualType AbstractType;
6160 bool Invalid;
6161
6162 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
6163 : S(S), Record(Record),
6164 AbstractType(S.Context.getCanonicalTagType(TD: Record)), Invalid(false) {}
6165
6166 void DiagnoseAbstractType() {
6167 if (Invalid) return;
6168 S.DiagnoseAbstractType(RD: Record);
6169 Invalid = true;
6170 }
6171
6172 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
6173};
6174
6175struct CheckAbstractUsage {
6176 AbstractUsageInfo &Info;
6177 const NamedDecl *Ctx;
6178
6179 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
6180 : Info(Info), Ctx(Ctx) {}
6181
6182 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
6183 switch (TL.getTypeLocClass()) {
6184#define ABSTRACT_TYPELOC(CLASS, PARENT)
6185#define TYPELOC(CLASS, PARENT) \
6186 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
6187#include "clang/AST/TypeLocNodes.def"
6188 }
6189 }
6190
6191 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6192 Visit(TL: TL.getReturnLoc(), Sel: Sema::AbstractReturnType);
6193 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
6194 if (!TL.getParam(i: I))
6195 continue;
6196
6197 TypeSourceInfo *TSI = TL.getParam(i: I)->getTypeSourceInfo();
6198 if (TSI) Visit(TL: TSI->getTypeLoc(), Sel: Sema::AbstractParamType);
6199 }
6200 }
6201
6202 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6203 Visit(TL: TL.getElementLoc(), Sel: Sema::AbstractArrayType);
6204 }
6205
6206 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6207 // Visit the type parameters from a permissive context.
6208 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
6209 TemplateArgumentLoc TAL = TL.getArgLoc(i: I);
6210 if (TAL.getArgument().getKind() == TemplateArgument::Type)
6211 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
6212 Visit(TL: TSI->getTypeLoc(), Sel: Sema::AbstractNone);
6213 // TODO: other template argument types?
6214 }
6215 }
6216
6217 // Visit pointee types from a permissive context.
6218#define CheckPolymorphic(Type) \
6219 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
6220 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
6221 }
6222 CheckPolymorphic(PointerTypeLoc)
6223 CheckPolymorphic(ReferenceTypeLoc)
6224 CheckPolymorphic(MemberPointerTypeLoc)
6225 CheckPolymorphic(BlockPointerTypeLoc)
6226 CheckPolymorphic(AtomicTypeLoc)
6227
6228 /// Handle all the types we haven't given a more specific
6229 /// implementation for above.
6230 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
6231 // Every other kind of type that we haven't called out already
6232 // that has an inner type is either (1) sugar or (2) contains that
6233 // inner type in some way as a subobject.
6234 if (TypeLoc Next = TL.getNextTypeLoc())
6235 return Visit(TL: Next, Sel);
6236
6237 // If there's no inner type and we're in a permissive context,
6238 // don't diagnose.
6239 if (Sel == Sema::AbstractNone) return;
6240
6241 // Check whether the type matches the abstract type.
6242 QualType T = TL.getType();
6243 if (T->isArrayType()) {
6244 Sel = Sema::AbstractArrayType;
6245 T = Info.S.Context.getBaseElementType(QT: T);
6246 }
6247 CanQualType CT = T->getCanonicalTypeUnqualified();
6248 if (CT != Info.AbstractType) return;
6249
6250 // It matched; do some magic.
6251 // FIXME: These should be at most warnings. See P0929R2, CWG1640, CWG1646.
6252 if (Sel == Sema::AbstractArrayType) {
6253 Info.S.Diag(Loc: Ctx->getLocation(), DiagID: diag::err_array_of_abstract_type)
6254 << T << TL.getSourceRange();
6255 } else {
6256 Info.S.Diag(Loc: Ctx->getLocation(), DiagID: diag::err_abstract_type_in_decl)
6257 << Sel << T << TL.getSourceRange();
6258 }
6259 Info.DiagnoseAbstractType();
6260 }
6261};
6262
6263void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
6264 Sema::AbstractDiagSelID Sel) {
6265 CheckAbstractUsage(*this, D).Visit(TL, Sel);
6266}
6267
6268}
6269
6270/// Check for invalid uses of an abstract type in a function declaration.
6271static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6272 FunctionDecl *FD) {
6273 // Only definitions are required to refer to complete and
6274 // non-abstract types.
6275 if (!FD->doesThisDeclarationHaveABody())
6276 return;
6277
6278 // For safety's sake, just ignore it if we don't have type source
6279 // information. This should never happen for non-implicit methods,
6280 // but...
6281 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6282 Info.CheckType(D: FD, TL: TSI->getTypeLoc(), Sel: Sema::AbstractNone);
6283}
6284
6285/// Check for invalid uses of an abstract type in a variable0 declaration.
6286static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6287 VarDecl *VD) {
6288 // No need to do the check on definitions, which require that
6289 // the type is complete.
6290 if (VD->isThisDeclarationADefinition())
6291 return;
6292
6293 Info.CheckType(D: VD, TL: VD->getTypeSourceInfo()->getTypeLoc(),
6294 Sel: Sema::AbstractVariableType);
6295}
6296
6297/// Check for invalid uses of an abstract type within a class definition.
6298static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6299 CXXRecordDecl *RD) {
6300 for (auto *D : RD->decls()) {
6301 if (D->isImplicit()) continue;
6302
6303 // Step through friends to the befriended declaration.
6304 if (auto *FD = dyn_cast<FriendDecl>(Val: D)) {
6305 D = FD->getFriendDecl();
6306 if (!D) continue;
6307 }
6308
6309 // Functions and function templates.
6310 if (auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
6311 CheckAbstractClassUsage(Info, FD);
6312 } else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Val: D)) {
6313 CheckAbstractClassUsage(Info, FD: FTD->getTemplatedDecl());
6314
6315 // Fields and static variables.
6316 } else if (auto *FD = dyn_cast<FieldDecl>(Val: D)) {
6317 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6318 Info.CheckType(D: FD, TL: TSI->getTypeLoc(), Sel: Sema::AbstractFieldType);
6319 } else if (auto *VD = dyn_cast<VarDecl>(Val: D)) {
6320 CheckAbstractClassUsage(Info, VD);
6321 } else if (auto *VTD = dyn_cast<VarTemplateDecl>(Val: D)) {
6322 CheckAbstractClassUsage(Info, VD: VTD->getTemplatedDecl());
6323
6324 // Nested classes and class templates.
6325 } else if (auto *RD = dyn_cast<CXXRecordDecl>(Val: D)) {
6326 CheckAbstractClassUsage(Info, RD);
6327 } else if (auto *CTD = dyn_cast<ClassTemplateDecl>(Val: D)) {
6328 CheckAbstractClassUsage(Info, RD: CTD->getTemplatedDecl());
6329 }
6330 }
6331}
6332
6333static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
6334 Attr *ClassAttr = getDLLAttr(D: Class);
6335 if (!ClassAttr)
6336 return;
6337
6338 assert(ClassAttr->getKind() == attr::DLLExport);
6339
6340 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6341
6342 if (TSK == TSK_ExplicitInstantiationDeclaration)
6343 // Don't go any further if this is just an explicit instantiation
6344 // declaration.
6345 return;
6346
6347 // Add a context note to explain how we got to any diagnostics produced below.
6348 struct MarkingClassDllexported {
6349 Sema &S;
6350 MarkingClassDllexported(Sema &S, CXXRecordDecl *Class,
6351 SourceLocation AttrLoc)
6352 : S(S) {
6353 Sema::CodeSynthesisContext Ctx;
6354 Ctx.Kind = Sema::CodeSynthesisContext::MarkingClassDllexported;
6355 Ctx.PointOfInstantiation = AttrLoc;
6356 Ctx.Entity = Class;
6357 S.pushCodeSynthesisContext(Ctx);
6358 }
6359 ~MarkingClassDllexported() {
6360 S.popCodeSynthesisContext();
6361 }
6362 } MarkingDllexportedContext(S, Class, ClassAttr->getLocation());
6363
6364 if (S.Context.getTargetInfo().getTriple().isOSCygMing())
6365 S.MarkVTableUsed(Loc: Class->getLocation(), Class, DefinitionRequired: true);
6366
6367 for (Decl *Member : Class->decls()) {
6368 // Skip members that were not marked exported.
6369 if (!Member->hasAttr<DLLExportAttr>())
6370 continue;
6371
6372 // Defined static variables that are members of an exported base
6373 // class must be marked export too.
6374 auto *VD = dyn_cast<VarDecl>(Val: Member);
6375 if (VD && VD->getStorageClass() == SC_Static &&
6376 TSK == TSK_ImplicitInstantiation)
6377 S.MarkVariableReferenced(Loc: VD->getLocation(), Var: VD);
6378
6379 auto *MD = dyn_cast<CXXMethodDecl>(Val: Member);
6380 if (!MD)
6381 continue;
6382
6383 if (MD->isUserProvided()) {
6384 // Instantiate non-default class member functions ...
6385
6386 // .. except for certain kinds of template specializations.
6387 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
6388 continue;
6389
6390 // If this is an MS ABI dllexport default constructor, instantiate any
6391 // default arguments.
6392 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
6393 auto *CD = dyn_cast<CXXConstructorDecl>(Val: MD);
6394 if (CD && CD->isDefaultConstructor() && TSK == TSK_Undeclared) {
6395 S.BuildCtorClosureDefaultArgs(
6396 Loc: CD->getAttr<DLLExportAttr>()->getLocation(), Ctor: CD);
6397 }
6398 }
6399
6400 S.MarkFunctionReferenced(Loc: Class->getLocation(), Func: MD);
6401
6402 // The function will be passed to the consumer when its definition is
6403 // encountered.
6404 } else if (MD->isExplicitlyDefaulted()) {
6405 // Synthesize and instantiate explicitly defaulted methods.
6406 S.MarkFunctionReferenced(Loc: Class->getLocation(), Func: MD);
6407
6408 if (TSK != TSK_ExplicitInstantiationDefinition) {
6409 // Except for explicit instantiation defs, we will not see the
6410 // definition again later, so pass it to the consumer now.
6411 S.Consumer.HandleTopLevelDecl(D: DeclGroupRef(MD));
6412 }
6413 } else if (!MD->isTrivial() ||
6414 MD->isCopyAssignmentOperator() ||
6415 MD->isMoveAssignmentOperator()) {
6416 // Synthesize and instantiate non-trivial implicit methods, and the copy
6417 // and move assignment operators. The latter are exported even if they
6418 // are trivial, because the address of an operator can be taken and
6419 // should compare equal across libraries.
6420 S.MarkFunctionReferenced(Loc: Class->getLocation(), Func: MD);
6421
6422 // There is no later point when we will see the definition of this
6423 // function, so pass it to the consumer now.
6424 S.Consumer.HandleTopLevelDecl(D: DeclGroupRef(MD));
6425 }
6426 }
6427}
6428
6429static void checkForMultipleExportedDefaultConstructors(Sema &S,
6430 CXXRecordDecl *Class) {
6431 // Only the MS ABI has default constructor closures, so we don't need to do
6432 // this semantic checking anywhere else.
6433 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
6434 return;
6435
6436 if (Class->isInvalidDecl())
6437 return;
6438
6439 CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
6440 for (Decl *Member : Class->decls()) {
6441 // Nested classes finish delayed default argument parsing with the outermost
6442 // class, so check each nested definition here.
6443 if (auto *NestedClass = dyn_cast<CXXRecordDecl>(Val: Member)) {
6444 if (NestedClass->isThisDeclarationADefinition())
6445 checkForMultipleExportedDefaultConstructors(S, Class: NestedClass);
6446 continue;
6447 }
6448
6449 // Look for exported default constructors.
6450 auto *CD = dyn_cast<CXXConstructorDecl>(Val: Member);
6451 if (!CD || !CD->isDefaultConstructor())
6452 continue;
6453 auto *Attr = CD->getAttr<DLLExportAttr>();
6454 if (!Attr)
6455 continue;
6456
6457 // If the class is non-dependent, mark the default arguments as ODR-used so
6458 // that we can properly codegen the constructor closure.
6459 if (!Class->isDependentContext()) {
6460 S.BuildCtorClosureDefaultArgs(Loc: Attr->getLocation(), Ctor: CD);
6461 S.DiscardCleanupsInEvaluationContext();
6462 }
6463
6464 if (LastExportedDefaultCtor) {
6465 S.Diag(Loc: LastExportedDefaultCtor->getLocation(),
6466 DiagID: diag::err_attribute_dll_ambiguous_default_ctor)
6467 << Class;
6468 S.Diag(Loc: CD->getLocation(), DiagID: diag::note_entity_declared_at)
6469 << CD->getDeclName();
6470 return;
6471 }
6472 LastExportedDefaultCtor = CD;
6473 }
6474}
6475
6476static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S,
6477 CXXRecordDecl *Class) {
6478 bool ErrorReported = false;
6479 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6480 ClassTemplateDecl *TD) {
6481 if (ErrorReported)
6482 return;
6483 S.Diag(Loc: TD->getLocation(),
6484 DiagID: diag::err_cuda_device_builtin_surftex_cls_template)
6485 << /*surface*/ 0 << TD;
6486 ErrorReported = true;
6487 };
6488
6489 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6490 if (!TD) {
6491 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Val: Class);
6492 if (!SD) {
6493 S.Diag(Loc: Class->getLocation(),
6494 DiagID: diag::err_cuda_device_builtin_surftex_ref_decl)
6495 << /*surface*/ 0 << Class;
6496 S.Diag(Loc: Class->getLocation(),
6497 DiagID: diag::note_cuda_device_builtin_surftex_should_be_template_class)
6498 << Class;
6499 return;
6500 }
6501 TD = SD->getSpecializedTemplate();
6502 }
6503
6504 TemplateParameterList *Params = TD->getTemplateParameters();
6505 unsigned N = Params->size();
6506
6507 if (N != 2) {
6508 reportIllegalClassTemplate(S, TD);
6509 S.Diag(Loc: TD->getLocation(),
6510 DiagID: diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6511 << TD << 2;
6512 }
6513 if (N > 0 && !isa<TemplateTypeParmDecl>(Val: Params->getParam(Idx: 0))) {
6514 reportIllegalClassTemplate(S, TD);
6515 S.Diag(Loc: TD->getLocation(),
6516 DiagID: diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6517 << TD << /*1st*/ 0 << /*type*/ 0;
6518 }
6519 if (N > 1) {
6520 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: Params->getParam(Idx: 1));
6521 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6522 reportIllegalClassTemplate(S, TD);
6523 S.Diag(Loc: TD->getLocation(),
6524 DiagID: diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6525 << TD << /*2nd*/ 1 << /*integer*/ 1;
6526 }
6527 }
6528}
6529
6530static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S,
6531 CXXRecordDecl *Class) {
6532 bool ErrorReported = false;
6533 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6534 ClassTemplateDecl *TD) {
6535 if (ErrorReported)
6536 return;
6537 S.Diag(Loc: TD->getLocation(),
6538 DiagID: diag::err_cuda_device_builtin_surftex_cls_template)
6539 << /*texture*/ 1 << TD;
6540 ErrorReported = true;
6541 };
6542
6543 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6544 if (!TD) {
6545 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Val: Class);
6546 if (!SD) {
6547 S.Diag(Loc: Class->getLocation(),
6548 DiagID: diag::err_cuda_device_builtin_surftex_ref_decl)
6549 << /*texture*/ 1 << Class;
6550 S.Diag(Loc: Class->getLocation(),
6551 DiagID: diag::note_cuda_device_builtin_surftex_should_be_template_class)
6552 << Class;
6553 return;
6554 }
6555 TD = SD->getSpecializedTemplate();
6556 }
6557
6558 TemplateParameterList *Params = TD->getTemplateParameters();
6559 unsigned N = Params->size();
6560
6561 if (N != 3) {
6562 reportIllegalClassTemplate(S, TD);
6563 S.Diag(Loc: TD->getLocation(),
6564 DiagID: diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6565 << TD << 3;
6566 }
6567 if (N > 0 && !isa<TemplateTypeParmDecl>(Val: Params->getParam(Idx: 0))) {
6568 reportIllegalClassTemplate(S, TD);
6569 S.Diag(Loc: TD->getLocation(),
6570 DiagID: diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6571 << TD << /*1st*/ 0 << /*type*/ 0;
6572 }
6573 if (N > 1) {
6574 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: Params->getParam(Idx: 1));
6575 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6576 reportIllegalClassTemplate(S, TD);
6577 S.Diag(Loc: TD->getLocation(),
6578 DiagID: diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6579 << TD << /*2nd*/ 1 << /*integer*/ 1;
6580 }
6581 }
6582 if (N > 2) {
6583 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: Params->getParam(Idx: 2));
6584 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6585 reportIllegalClassTemplate(S, TD);
6586 S.Diag(Loc: TD->getLocation(),
6587 DiagID: diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6588 << TD << /*3rd*/ 2 << /*integer*/ 1;
6589 }
6590 }
6591}
6592
6593void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
6594 // Mark any compiler-generated routines with the implicit code_seg attribute.
6595 for (auto *Method : Class->methods()) {
6596 if (Method->isUserProvided())
6597 continue;
6598 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(FD: Method, /*IsDefinition=*/true))
6599 Method->addAttr(A);
6600 }
6601}
6602
6603void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
6604 Attr *ClassAttr = getDLLAttr(D: Class);
6605
6606 // MSVC inherits DLL attributes to partial class template specializations.
6607 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) {
6608 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Val: Class)) {
6609 if (Attr *TemplateAttr =
6610 getDLLAttr(D: Spec->getSpecializedTemplate()->getTemplatedDecl())) {
6611 auto *A = cast<InheritableAttr>(Val: TemplateAttr->clone(C&: getASTContext()));
6612 A->setInherited(true);
6613 ClassAttr = A;
6614 }
6615 }
6616 }
6617
6618 if (!ClassAttr)
6619 return;
6620
6621 // MSVC allows imported or exported template classes that have UniqueExternal
6622 // linkage. This occurs when the template class has been instantiated with
6623 // a template parameter which itself has internal linkage.
6624 // We drop the attribute to avoid exporting or importing any members.
6625 if ((Context.getTargetInfo().getCXXABI().isMicrosoft() ||
6626 Context.getTargetInfo().getTriple().isPS()) &&
6627 (!Class->isExternallyVisible() && Class->hasExternalFormalLinkage())) {
6628 Class->dropAttrs<DLLExportAttr, DLLImportAttr>();
6629 return;
6630 }
6631
6632 if (!Class->isExternallyVisible()) {
6633 Diag(Loc: Class->getLocation(), DiagID: diag::err_attribute_dll_not_extern)
6634 << Class << ClassAttr;
6635 return;
6636 }
6637
6638 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6639 !ClassAttr->isInherited()) {
6640 // Diagnose dll attributes on members of class with dll attribute.
6641 for (Decl *Member : Class->decls()) {
6642 if (!isa<VarDecl>(Val: Member) && !isa<CXXMethodDecl>(Val: Member))
6643 continue;
6644 InheritableAttr *MemberAttr = getDLLAttr(D: Member);
6645 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
6646 continue;
6647
6648 Diag(Loc: MemberAttr->getLocation(),
6649 DiagID: diag::err_attribute_dll_member_of_dll_class)
6650 << MemberAttr << ClassAttr;
6651 Diag(Loc: ClassAttr->getLocation(), DiagID: diag::note_previous_attribute);
6652 Member->setInvalidDecl();
6653 }
6654 }
6655
6656 if (Class->getDescribedClassTemplate())
6657 // Don't inherit dll attribute until the template is instantiated.
6658 return;
6659
6660 // The class is either imported or exported.
6661 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
6662
6663 // Check if this was a dllimport attribute propagated from a derived class to
6664 // a base class template specialization. We don't apply these attributes to
6665 // static data members.
6666 const bool PropagatedImport =
6667 !ClassExported &&
6668 cast<DLLImportAttr>(Val: ClassAttr)->wasPropagatedToBaseTemplate();
6669
6670 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6671
6672 // Ignore explicit dllexport on explicit class template instantiation
6673 // declarations, except in MinGW mode.
6674 if (ClassExported && !ClassAttr->isInherited() &&
6675 TSK == TSK_ExplicitInstantiationDeclaration &&
6676 !Context.getTargetInfo().getTriple().isOSCygMing()) {
6677 if (auto *DEA = Class->getAttr<DLLExportAttr>()) {
6678 Class->addAttr(A: DLLExportOnDeclAttr::Create(Ctx&: Context, Range: DEA->getLoc()));
6679 Class->dropAttr<DLLExportAttr>();
6680 }
6681 return;
6682 }
6683
6684 // Force declaration of implicit members so they can inherit the attribute.
6685 ForceDeclarationOfImplicitMembers(Class);
6686
6687 // Inherited constructors are created lazily; force their creation now so the
6688 // loop below can propagate the DLL attribute to them.
6689 if (ClassExported && getLangOpts().DllExportInlines) {
6690 SmallVector<ConstructorUsingShadowDecl *, 4> Shadows;
6691 for (Decl *D : Class->decls())
6692 if (auto *S = dyn_cast<ConstructorUsingShadowDecl>(Val: D))
6693 Shadows.push_back(Elt: S);
6694 for (ConstructorUsingShadowDecl *S : Shadows) {
6695 CXXConstructorDecl *BC = dyn_cast<CXXConstructorDecl>(Val: S->getTargetDecl());
6696 if (!BC || BC->isDeleted())
6697 continue;
6698 // Skip constructors whose requires clause is not satisfied.
6699 // Normally overload resolution filters these, but we are bypassing
6700 // it to eagerly create inherited constructors for dllexport.
6701 if (BC->getTrailingRequiresClause()) {
6702 ConstraintSatisfaction Satisfaction;
6703 if (CheckFunctionConstraints(FD: BC, Satisfaction) ||
6704 !Satisfaction.IsSatisfied)
6705 continue;
6706 }
6707 findInheritingConstructor(Loc: Class->getLocation(), BaseCtor: BC, DerivedShadow: S);
6708 }
6709 }
6710
6711 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
6712 // seem to be true in practice?
6713
6714 for (Decl *Member : Class->decls()) {
6715 if (Member->hasAttr<ExcludeFromExplicitInstantiationAttr>())
6716 continue;
6717
6718 VarDecl *VD = dyn_cast<VarDecl>(Val: Member);
6719 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: Member);
6720
6721 // Only methods and static fields inherit the attributes.
6722 if (!VD && !MD)
6723 continue;
6724
6725 if (MD) {
6726 // Don't process deleted methods.
6727 if (MD->isDeleted())
6728 continue;
6729
6730 if (ClassExported && getLangOpts().DllExportInlines) {
6731 CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Val: MD);
6732 if (CD && CD->getInheritedConstructor()) {
6733 // Inherited constructors already had their base constructor's
6734 // constraints checked before creation via
6735 // findInheritingConstructor, so only ABI-compatibility checks
6736 // are needed here.
6737 //
6738 // Don't export inherited constructors whose parameters prevent
6739 // ABI-compatible forwarding. When canEmitDelegateCallArgs (in
6740 // CodeGen) returns false, Clang inlines the constructor body
6741 // instead of emitting a forwarding thunk, producing code that
6742 // is not ABI-compatible with MSVC. Suppress the export and warn
6743 // so the user gets a linker error rather than a silent runtime
6744 // mismatch.
6745 if (CD->isVariadic()) {
6746 Diag(Loc: CD->getLocation(),
6747 DiagID: diag::warn_dllexport_inherited_ctor_unsupported)
6748 << /*variadic=*/0;
6749 continue;
6750 }
6751 if (Context.getTargetInfo()
6752 .getCXXABI()
6753 .areArgsDestroyedLeftToRightInCallee()) {
6754 bool HasCalleeCleanupParam = false;
6755 for (const ParmVarDecl *P : CD->parameters())
6756 if (P->needsDestruction(Ctx: Context)) {
6757 HasCalleeCleanupParam = true;
6758 break;
6759 }
6760 if (HasCalleeCleanupParam) {
6761 Diag(Loc: CD->getLocation(),
6762 DiagID: diag::warn_dllexport_inherited_ctor_unsupported)
6763 << /*callee-cleanup=*/1;
6764 continue;
6765 }
6766 }
6767 } else if (MD->getTrailingRequiresClause()) {
6768 // Don't export methods whose requires clause is not satisfied.
6769 // For class template specializations, member constraints may
6770 // depend on template arguments and an unsatisfied constraint
6771 // means the member should not be available in this
6772 // specialization.
6773 ConstraintSatisfaction Satisfaction;
6774 if (CheckFunctionConstraints(FD: MD, Satisfaction) ||
6775 !Satisfaction.IsSatisfied)
6776 continue;
6777 }
6778 }
6779
6780 if (MD->isInlined()) {
6781 // MinGW does not import or export inline methods. But do it for
6782 // template instantiations and inherited constructors (which are
6783 // marked inline but must be exported to match MSVC behavior).
6784 if (!Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6785 TSK != TSK_ExplicitInstantiationDeclaration &&
6786 TSK != TSK_ExplicitInstantiationDefinition) {
6787 if (auto *CD = dyn_cast<CXXConstructorDecl>(Val: MD);
6788 !CD || !CD->getInheritedConstructor())
6789 continue;
6790 }
6791
6792 // MSVC versions before 2015 don't export the move assignment operators
6793 // and move constructor, so don't attempt to import/export them if
6794 // we have a definition.
6795 auto *Ctor = dyn_cast<CXXConstructorDecl>(Val: MD);
6796 if ((MD->isMoveAssignmentOperator() ||
6797 (Ctor && Ctor->isMoveConstructor())) &&
6798 getLangOpts().isCompatibleWithMSVC() &&
6799 !getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015))
6800 continue;
6801
6802 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
6803 // operator is exported anyway.
6804 if (getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015) &&
6805 (Ctor || isa<CXXDestructorDecl>(Val: MD)) && MD->isTrivial())
6806 continue;
6807 }
6808 }
6809
6810 // Don't apply dllimport attributes to static data members of class template
6811 // instantiations when the attribute is propagated from a derived class.
6812 if (VD && PropagatedImport)
6813 continue;
6814
6815 if (!cast<NamedDecl>(Val: Member)->isExternallyVisible())
6816 continue;
6817
6818 if (!getDLLAttr(D: Member)) {
6819 InheritableAttr *NewAttr = nullptr;
6820
6821 // Do not export/import inline function when -fno-dllexport-inlines is
6822 // passed. But add attribute for later local static var check.
6823 if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
6824 TSK != TSK_ExplicitInstantiationDeclaration &&
6825 TSK != TSK_ExplicitInstantiationDefinition) {
6826 if (ClassExported) {
6827 NewAttr = ::new (getASTContext())
6828 DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);
6829 } else {
6830 NewAttr = ::new (getASTContext())
6831 DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);
6832 }
6833 } else {
6834 NewAttr = cast<InheritableAttr>(Val: ClassAttr->clone(C&: getASTContext()));
6835 }
6836
6837 NewAttr->setInherited(true);
6838 Member->addAttr(A: NewAttr);
6839
6840 if (MD) {
6841 // Propagate DLLAttr to friend re-declarations of MD that have already
6842 // been constructed.
6843 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
6844 FD = FD->getPreviousDecl()) {
6845 if (FD->getFriendObjectKind() == Decl::FOK_None)
6846 continue;
6847 assert(!getDLLAttr(FD) &&
6848 "friend re-decl should not already have a DLLAttr");
6849 NewAttr = cast<InheritableAttr>(Val: ClassAttr->clone(C&: getASTContext()));
6850 NewAttr->setInherited(true);
6851 FD->addAttr(A: NewAttr);
6852 }
6853 }
6854 }
6855 }
6856
6857 if (ClassExported)
6858 DelayedDllExportClasses.push_back(Elt: Class);
6859}
6860
6861void Sema::propagateDLLAttrToBaseClassTemplate(
6862 CXXRecordDecl *Class, Attr *ClassAttr,
6863 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
6864 if (getDLLAttr(
6865 D: BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
6866 // If the base class template has a DLL attribute, don't try to change it.
6867 return;
6868 }
6869
6870 auto TSK = BaseTemplateSpec->getSpecializationKind();
6871 if (!getDLLAttr(D: BaseTemplateSpec) &&
6872 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
6873 TSK == TSK_ImplicitInstantiation)) {
6874 // The template hasn't been instantiated yet (or it has, but only as an
6875 // explicit instantiation declaration or implicit instantiation, which means
6876 // we haven't codegenned any members yet), so propagate the attribute.
6877 auto *NewAttr = cast<InheritableAttr>(Val: ClassAttr->clone(C&: getASTContext()));
6878 NewAttr->setInherited(true);
6879 BaseTemplateSpec->addAttr(A: NewAttr);
6880
6881 // If this was an import, mark that we propagated it from a derived class to
6882 // a base class template specialization.
6883 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(Val: NewAttr))
6884 ImportAttr->setPropagatedToBaseTemplate();
6885
6886 // If the template is already instantiated, checkDLLAttributeRedeclaration()
6887 // needs to be run again to work see the new attribute. Otherwise this will
6888 // get run whenever the template is instantiated.
6889 if (TSK != TSK_Undeclared)
6890 checkClassLevelDLLAttribute(Class: BaseTemplateSpec);
6891
6892 return;
6893 }
6894
6895 if (getDLLAttr(D: BaseTemplateSpec)) {
6896 // The template has already been specialized or instantiated with an
6897 // attribute, explicitly or through propagation. We should not try to change
6898 // it.
6899 return;
6900 }
6901
6902 // The template was previously instantiated or explicitly specialized without
6903 // a dll attribute, It's too late for us to add an attribute, so warn that
6904 // this is unsupported.
6905 Diag(Loc: BaseLoc, DiagID: diag::warn_attribute_dll_instantiated_base_class)
6906 << BaseTemplateSpec->isExplicitSpecialization();
6907 Diag(Loc: ClassAttr->getLocation(), DiagID: diag::note_attribute);
6908 if (BaseTemplateSpec->isExplicitSpecialization()) {
6909 Diag(Loc: BaseTemplateSpec->getLocation(),
6910 DiagID: diag::note_template_class_explicit_specialization_was_here)
6911 << BaseTemplateSpec;
6912 } else {
6913 Diag(Loc: BaseTemplateSpec->getPointOfInstantiation(),
6914 DiagID: diag::note_template_class_instantiation_was_here)
6915 << BaseTemplateSpec;
6916 }
6917}
6918
6919namespace {
6920/// RAII object to restore the floating-point (FP) features active at the time
6921/// a defaulted function was declared. This ensures that the synthesized body
6922/// of the function respects the FP pragmas (e.g., #pragma STDC FENV_ACCESS)
6923/// that were in effect when the function was explicitly defaulted.
6924struct DefaultedFunctionFPFeaturesRAII {
6925 Sema::FPFeaturesStateRAII SavedFPFeatures;
6926 DefaultedFunctionFPFeaturesRAII(Sema &S, FunctionDecl *FD)
6927 : SavedFPFeatures(S) {
6928 auto *Info = FD->getDefaultedOrDeletedInfo();
6929 FPOptionsOverride FPO = Info ? Info->getFPFeatures() : FPOptionsOverride();
6930 S.CurFPFeatures = FPO.applyOverrides(LO: S.LangOpts);
6931 S.FpPragmaStack.CurrentValue = FPO;
6932 }
6933
6934 ~DefaultedFunctionFPFeaturesRAII() = default;
6935};
6936} // namespace
6937
6938static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD,
6939 SourceLocation DefaultLoc) {
6940 FunctionDecl::DefaultedFunctionKind DFK = FD->getDefaultedFunctionKind();
6941 if (DFK.isComparison())
6942 return S.DefineDefaultedComparison(Loc: DefaultLoc, FD, DCK: DFK.asComparison());
6943
6944 switch (DFK.asSpecialMember()) {
6945 case CXXSpecialMemberKind::DefaultConstructor:
6946 S.DefineImplicitDefaultConstructor(CurrentLocation: DefaultLoc,
6947 Constructor: cast<CXXConstructorDecl>(Val: FD));
6948 break;
6949 case CXXSpecialMemberKind::CopyConstructor:
6950 S.DefineImplicitCopyConstructor(CurrentLocation: DefaultLoc, Constructor: cast<CXXConstructorDecl>(Val: FD));
6951 break;
6952 case CXXSpecialMemberKind::CopyAssignment:
6953 S.DefineImplicitCopyAssignment(CurrentLocation: DefaultLoc, MethodDecl: cast<CXXMethodDecl>(Val: FD));
6954 break;
6955 case CXXSpecialMemberKind::Destructor:
6956 S.DefineImplicitDestructor(CurrentLocation: DefaultLoc, Destructor: cast<CXXDestructorDecl>(Val: FD));
6957 break;
6958 case CXXSpecialMemberKind::MoveConstructor:
6959 S.DefineImplicitMoveConstructor(CurrentLocation: DefaultLoc, Constructor: cast<CXXConstructorDecl>(Val: FD));
6960 break;
6961 case CXXSpecialMemberKind::MoveAssignment:
6962 S.DefineImplicitMoveAssignment(CurrentLocation: DefaultLoc, MethodDecl: cast<CXXMethodDecl>(Val: FD));
6963 break;
6964 case CXXSpecialMemberKind::Invalid:
6965 llvm_unreachable("Invalid special member.");
6966 }
6967}
6968
6969/// Determine whether a type is permitted to be passed or returned in
6970/// registers, per C++ [class.temporary]p3.
6971static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
6972 TargetInfo::CallingConvKind CCK) {
6973 if (D->isDependentType() || D->isInvalidDecl())
6974 return false;
6975
6976 // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
6977 // The PS4 platform ABI follows the behavior of Clang 3.2.
6978 if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
6979 return !D->hasNonTrivialDestructorForCall() &&
6980 !D->hasNonTrivialCopyConstructorForCall();
6981
6982 if (CCK == TargetInfo::CCK_MicrosoftWin64) {
6983 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
6984 bool DtorIsTrivialForCall = false;
6985
6986 // If a class has at least one eligible, trivial copy constructor, it
6987 // is passed according to the C ABI. Otherwise, it is passed indirectly.
6988 //
6989 // Note: This permits classes with non-trivial copy or move ctors to be
6990 // passed in registers, so long as they *also* have a trivial copy ctor,
6991 // which is non-conforming.
6992 if (D->needsImplicitCopyConstructor()) {
6993 if (!D->defaultedCopyConstructorIsDeleted()) {
6994 if (D->hasTrivialCopyConstructor())
6995 CopyCtorIsTrivial = true;
6996 if (D->hasTrivialCopyConstructorForCall())
6997 CopyCtorIsTrivialForCall = true;
6998 }
6999 } else {
7000 for (const CXXConstructorDecl *CD : D->ctors()) {
7001 if (CD->isCopyConstructor() && !CD->isDeleted() &&
7002 !CD->isIneligibleOrNotSelected()) {
7003 if (CD->isTrivial())
7004 CopyCtorIsTrivial = true;
7005 if (CD->isTrivialForCall())
7006 CopyCtorIsTrivialForCall = true;
7007 }
7008 }
7009 }
7010
7011 if (D->needsImplicitDestructor()) {
7012 if (!D->defaultedDestructorIsDeleted() &&
7013 D->hasTrivialDestructorForCall())
7014 DtorIsTrivialForCall = true;
7015 } else if (const auto *DD = D->getDestructor()) {
7016 if (!DD->isDeleted() && DD->isTrivialForCall())
7017 DtorIsTrivialForCall = true;
7018 }
7019
7020 // If the copy ctor and dtor are both trivial-for-calls, pass direct.
7021 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
7022 return true;
7023
7024 // If a class has a destructor, we'd really like to pass it indirectly
7025 // because it allows us to elide copies. Unfortunately, MSVC makes that
7026 // impossible for small types, which it will pass in a single register or
7027 // stack slot. Most objects with dtors are large-ish, so handle that early.
7028 // We can't call out all large objects as being indirect because there are
7029 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
7030 // how we pass large POD types.
7031
7032 // Note: This permits small classes with nontrivial destructors to be
7033 // passed in registers, which is non-conforming.
7034 bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
7035 uint64_t TypeSize = isAArch64 ? 128 : 64;
7036
7037 if (CopyCtorIsTrivial && S.getASTContext().getTypeSize(
7038 T: S.Context.getCanonicalTagType(TD: D)) <= TypeSize)
7039 return true;
7040 return false;
7041 }
7042
7043 // Per C++ [class.temporary]p3, the relevant condition is:
7044 // each copy constructor, move constructor, and destructor of X is
7045 // either trivial or deleted, and X has at least one non-deleted copy
7046 // or move constructor
7047 bool HasNonDeletedCopyOrMove = false;
7048
7049 if (D->needsImplicitCopyConstructor() &&
7050 !D->defaultedCopyConstructorIsDeleted()) {
7051 if (!D->hasTrivialCopyConstructorForCall())
7052 return false;
7053 HasNonDeletedCopyOrMove = true;
7054 }
7055
7056 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
7057 !D->defaultedMoveConstructorIsDeleted()) {
7058 if (!D->hasTrivialMoveConstructorForCall())
7059 return false;
7060 HasNonDeletedCopyOrMove = true;
7061 }
7062
7063 if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
7064 !D->hasTrivialDestructorForCall())
7065 return false;
7066
7067 for (const CXXMethodDecl *MD : D->methods()) {
7068 if (MD->isDeleted() || MD->isIneligibleOrNotSelected())
7069 continue;
7070
7071 auto *CD = dyn_cast<CXXConstructorDecl>(Val: MD);
7072 if (CD && CD->isCopyOrMoveConstructor())
7073 HasNonDeletedCopyOrMove = true;
7074 else if (!isa<CXXDestructorDecl>(Val: MD))
7075 continue;
7076
7077 if (!MD->isTrivialForCall())
7078 return false;
7079 }
7080
7081 return HasNonDeletedCopyOrMove;
7082}
7083
7084/// Report an error regarding overriding, along with any relevant
7085/// overridden methods.
7086///
7087/// \param DiagID the primary error to report.
7088/// \param MD the overriding method.
7089static bool
7090ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD,
7091 llvm::function_ref<bool(const CXXMethodDecl *)> Report) {
7092 bool IssuedDiagnostic = false;
7093 for (const CXXMethodDecl *O : MD->overridden_methods()) {
7094 if (Report(O)) {
7095 if (!IssuedDiagnostic) {
7096 S.Diag(Loc: MD->getLocation(), DiagID) << MD->getDeclName();
7097 IssuedDiagnostic = true;
7098 }
7099 S.Diag(Loc: O->getLocation(), DiagID: diag::note_overridden_virtual_function);
7100 }
7101 }
7102 return IssuedDiagnostic;
7103}
7104
7105void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) {
7106 if (!Record)
7107 return;
7108
7109 if (Record->isAbstract() && !Record->isInvalidDecl()) {
7110 AbstractUsageInfo Info(*this, Record);
7111 CheckAbstractClassUsage(Info, RD: Record);
7112 }
7113
7114 // If this is not an aggregate type and has no user-declared constructor,
7115 // complain about any non-static data members of reference or const scalar
7116 // type, since they will never get initializers.
7117 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
7118 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
7119 !Record->isLambda()) {
7120 bool Complained = false;
7121 for (const auto *F : Record->fields()) {
7122 if (F->hasInClassInitializer() || F->isUnnamedBitField())
7123 continue;
7124
7125 if (F->getType()->isReferenceType() ||
7126 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
7127 if (!Complained) {
7128 Diag(Loc: Record->getLocation(), DiagID: diag::warn_no_constructor_for_refconst)
7129 << Record->getTagKind() << Record;
7130 Complained = true;
7131 }
7132
7133 Diag(Loc: F->getLocation(), DiagID: diag::note_refconst_member_not_initialized)
7134 << F->getType()->isReferenceType()
7135 << F->getDeclName();
7136 }
7137 }
7138 }
7139
7140 if (Record->getIdentifier()) {
7141 // C++ [class.mem]p13:
7142 // If T is the name of a class, then each of the following shall have a
7143 // name different from T:
7144 // - every member of every anonymous union that is a member of class T.
7145 //
7146 // C++ [class.mem]p14:
7147 // In addition, if class T has a user-declared constructor (12.1), every
7148 // non-static data member of class T shall have a name different from T.
7149 for (const NamedDecl *Element : Record->lookup(Name: Record->getDeclName())) {
7150 const NamedDecl *D = Element->getUnderlyingDecl();
7151 // Invalid IndirectFieldDecls have already been diagnosed with
7152 // err_anonymous_record_member_redecl in
7153 // SemaDecl.cpp:CheckAnonMemberRedeclaration.
7154 if (((isa<FieldDecl>(Val: D) || isa<UnresolvedUsingValueDecl>(Val: D)) &&
7155 Record->hasUserDeclaredConstructor()) ||
7156 (isa<IndirectFieldDecl>(Val: D) && !D->isInvalidDecl())) {
7157 Diag(Loc: Element->getLocation(), DiagID: diag::err_member_name_of_class)
7158 << D->getDeclName();
7159 break;
7160 }
7161 }
7162 }
7163
7164 // Warn if the class has virtual methods but non-virtual public destructor.
7165 if (Record->isPolymorphic() && !Record->isDependentType()) {
7166 CXXDestructorDecl *dtor = Record->getDestructor();
7167 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
7168 !Record->hasAttr<FinalAttr>())
7169 Diag(Loc: dtor ? dtor->getLocation() : Record->getLocation(),
7170 DiagID: diag::warn_non_virtual_dtor)
7171 << Context.getCanonicalTagType(TD: Record);
7172 }
7173
7174 if (Record->isAbstract()) {
7175 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
7176 Diag(Loc: Record->getLocation(), DiagID: diag::warn_abstract_final_class)
7177 << FA->isSpelledAsSealed();
7178 DiagnoseAbstractType(RD: Record);
7179 }
7180 }
7181
7182 // Warn if the class has a final destructor but is not itself marked final.
7183 if (!Record->hasAttr<FinalAttr>()) {
7184 if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
7185 if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
7186 Diag(Loc: FA->getLocation(), DiagID: diag::warn_final_dtor_non_final_class)
7187 << FA->isSpelledAsSealed()
7188 << FixItHint::CreateInsertion(
7189 InsertionLoc: getLocForEndOfToken(Loc: Record->getLocation()),
7190 Code: (FA->isSpelledAsSealed() ? " sealed" : " final"));
7191 Diag(Loc: Record->getLocation(),
7192 DiagID: diag::note_final_dtor_non_final_class_silence)
7193 << Context.getCanonicalTagType(TD: Record) << FA->isSpelledAsSealed();
7194 }
7195 }
7196 }
7197
7198 // See if trivial_abi has to be dropped.
7199 if (Record->hasAttr<TrivialABIAttr>())
7200 checkIllFormedTrivialABIStruct(RD&: *Record);
7201
7202 // Set HasTrivialSpecialMemberForCall if the record has attribute
7203 // "trivial_abi".
7204 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
7205
7206 if (HasTrivialABI)
7207 Record->setHasTrivialSpecialMemberForCall();
7208
7209 // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=).
7210 // We check these last because they can depend on the properties of the
7211 // primary comparison functions (==, <=>).
7212 llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons;
7213
7214 // Perform checks that can't be done until we know all the properties of a
7215 // member function (whether it's defaulted, deleted, virtual, overriding,
7216 // ...).
7217 auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) {
7218 // A static function cannot override anything.
7219 if (MD->getStorageClass() == SC_Static) {
7220 if (ReportOverrides(S&: *this, DiagID: diag::err_static_overrides_virtual, MD,
7221 Report: [](const CXXMethodDecl *) { return true; }))
7222 return;
7223 }
7224
7225 // A deleted function cannot override a non-deleted function and vice
7226 // versa.
7227 if (ReportOverrides(S&: *this,
7228 DiagID: MD->isDeleted() ? diag::err_deleted_override
7229 : diag::err_non_deleted_override,
7230 MD, Report: [&](const CXXMethodDecl *V) {
7231 return MD->isDeleted() != V->isDeleted();
7232 })) {
7233 if (MD->isDefaulted() && MD->isDeleted())
7234 // Explain why this defaulted function was deleted.
7235 DiagnoseDeletedDefaultedFunction(FD: MD);
7236 return;
7237 }
7238
7239 // A consteval function cannot override a non-consteval function and vice
7240 // versa.
7241 if (ReportOverrides(S&: *this,
7242 DiagID: MD->isConsteval() ? diag::err_consteval_override
7243 : diag::err_non_consteval_override,
7244 MD, Report: [&](const CXXMethodDecl *V) {
7245 return MD->isConsteval() != V->isConsteval();
7246 })) {
7247 if (MD->isDefaulted() && MD->isDeleted())
7248 // Explain why this defaulted function was deleted.
7249 DiagnoseDeletedDefaultedFunction(FD: MD);
7250 return;
7251 }
7252 };
7253
7254 auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool {
7255 if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted())
7256 return false;
7257
7258 FunctionDecl::DefaultedFunctionKind DFK = FD->getDefaultedFunctionKind();
7259 if (DFK.asComparison() == DefaultedComparisonKind::NotEqual ||
7260 DFK.asComparison() == DefaultedComparisonKind::Relational) {
7261 DefaultedSecondaryComparisons.push_back(Elt: FD);
7262 return true;
7263 }
7264
7265 CheckExplicitlyDefaultedFunction(S, MD: FD);
7266 return false;
7267 };
7268
7269 if (!Record->isInvalidDecl() &&
7270 Record->hasAttr<VTablePointerAuthenticationAttr>())
7271 checkIncorrectVTablePointerAuthenticationAttribute(RD&: *Record);
7272
7273 auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
7274 // Check whether the explicitly-defaulted members are valid.
7275 bool Incomplete = CheckForDefaultedFunction(M);
7276
7277 // Skip the rest of the checks for a member of a dependent class.
7278 if (Record->isDependentType())
7279 return;
7280
7281 // For an explicitly defaulted or deleted special member, we defer
7282 // determining triviality until the class is complete. That time is now!
7283 CXXSpecialMemberKind CSM = M->getSpecialMemberKind();
7284 if (!M->isImplicit() && !M->isUserProvided()) {
7285 if (CSM != CXXSpecialMemberKind::Invalid) {
7286 M->setTrivial(SpecialMemberIsTrivial(MD: M, CSM));
7287 // Inform the class that we've finished declaring this member.
7288 Record->finishedDefaultedOrDeletedMember(MD: M);
7289 M->setTrivialForCall(
7290 HasTrivialABI ||
7291 SpecialMemberIsTrivial(MD: M, CSM,
7292 TAH: TrivialABIHandling::ConsiderTrivialABI));
7293 Record->setTrivialForCallFlags(M);
7294 }
7295 }
7296
7297 // Set triviality for the purpose of calls if this is a user-provided
7298 // copy/move constructor or destructor.
7299 if ((CSM == CXXSpecialMemberKind::CopyConstructor ||
7300 CSM == CXXSpecialMemberKind::MoveConstructor ||
7301 CSM == CXXSpecialMemberKind::Destructor) &&
7302 M->isUserProvided()) {
7303 M->setTrivialForCall(HasTrivialABI);
7304 Record->setTrivialForCallFlags(M);
7305 }
7306
7307 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
7308 M->hasAttr<DLLExportAttr>()) {
7309 if (getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015) &&
7310 M->isTrivial() &&
7311 (CSM == CXXSpecialMemberKind::DefaultConstructor ||
7312 CSM == CXXSpecialMemberKind::CopyConstructor ||
7313 CSM == CXXSpecialMemberKind::Destructor))
7314 M->dropAttr<DLLExportAttr>();
7315
7316 if (M->hasAttr<DLLExportAttr>()) {
7317 // Define after any fields with in-class initializers have been parsed.
7318 DelayedDllExportMemberFunctions.push_back(Elt: M);
7319 }
7320 }
7321
7322 bool EffectivelyConstexprDestructor = true;
7323 // Avoid triggering vtable instantiation due to a dtor that is not
7324 // "effectively constexpr" for better compatibility.
7325 // See https://github.com/llvm/llvm-project/issues/102293 for more info.
7326 if (isa<CXXDestructorDecl>(Val: M)) {
7327 llvm::SmallDenseSet<QualType> Visited;
7328 auto Check = [&Visited](QualType T, auto &&Check) -> bool {
7329 if (!Visited.insert(V: T->getCanonicalTypeUnqualified()).second)
7330 return false;
7331 const CXXRecordDecl *RD =
7332 T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
7333 if (!RD || !RD->isCompleteDefinition())
7334 return true;
7335
7336 if (!RD->hasConstexprDestructor())
7337 return false;
7338
7339 for (const CXXBaseSpecifier &B : RD->bases())
7340 if (!Check(B.getType(), Check))
7341 return false;
7342 for (const FieldDecl *FD : RD->fields())
7343 if (!Check(FD->getType(), Check))
7344 return false;
7345 return true;
7346 };
7347 EffectivelyConstexprDestructor =
7348 Check(Context.getCanonicalTagType(TD: Record), Check);
7349 }
7350
7351 // Define defaulted constexpr virtual functions that override a base class
7352 // function right away.
7353 // FIXME: We can defer doing this until the vtable is marked as used.
7354 if (CSM != CXXSpecialMemberKind::Invalid && !M->isDeleted() &&
7355 M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods() &&
7356 EffectivelyConstexprDestructor)
7357 DefineDefaultedFunction(S&: *this, FD: M, DefaultLoc: M->getLocation());
7358
7359 if (!Incomplete)
7360 CheckCompletedMemberFunction(M);
7361 };
7362
7363 // Check the destructor before any other member function. We need to
7364 // determine whether it's trivial in order to determine whether the claas
7365 // type is a literal type, which is a prerequisite for determining whether
7366 // other special member functions are valid and whether they're implicitly
7367 // 'constexpr'.
7368 if (CXXDestructorDecl *Dtor = Record->getDestructor())
7369 CompleteMemberFunction(Dtor);
7370
7371 bool HasMethodWithOverrideControl = false,
7372 HasOverridingMethodWithoutOverrideControl = false;
7373 for (auto *D : Record->decls()) {
7374 if (auto *M = dyn_cast<CXXMethodDecl>(Val: D)) {
7375 // FIXME: We could do this check for dependent types with non-dependent
7376 // bases.
7377 if (!Record->isDependentType()) {
7378 // See if a method overloads virtual methods in a base
7379 // class without overriding any.
7380 if (!M->isStatic())
7381 DiagnoseHiddenVirtualMethods(MD: M);
7382
7383 if (M->hasAttr<OverrideAttr>()) {
7384 HasMethodWithOverrideControl = true;
7385 } else if (M->size_overridden_methods() > 0) {
7386 HasOverridingMethodWithoutOverrideControl = true;
7387 } else {
7388 // Warn on newly-declared virtual methods in `final` classes
7389 if (M->isVirtualAsWritten() && Record->isEffectivelyFinal()) {
7390 Diag(Loc: M->getLocation(), DiagID: diag::warn_unnecessary_virtual_specifier)
7391 << M;
7392 }
7393 }
7394 }
7395
7396 if (!isa<CXXDestructorDecl>(Val: M))
7397 CompleteMemberFunction(M);
7398 } else if (auto *F = dyn_cast<FriendDecl>(Val: D)) {
7399 CheckForDefaultedFunction(
7400 dyn_cast_or_null<FunctionDecl>(Val: F->getFriendDecl()));
7401 }
7402 }
7403
7404 if (HasOverridingMethodWithoutOverrideControl) {
7405 bool HasInconsistentOverrideControl = HasMethodWithOverrideControl;
7406 for (auto *M : Record->methods())
7407 DiagnoseAbsenceOfOverrideControl(D: M, Inconsistent: HasInconsistentOverrideControl);
7408 }
7409
7410 // Check the defaulted secondary comparisons after any other member functions.
7411 for (FunctionDecl *FD : DefaultedSecondaryComparisons) {
7412 CheckExplicitlyDefaultedFunction(S, MD: FD);
7413
7414 // If this is a member function, we deferred checking it until now.
7415 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: FD))
7416 CheckCompletedMemberFunction(MD);
7417 }
7418
7419 // {ms,gcc}_struct is a request to change ABI rules to either follow
7420 // Microsoft or Itanium C++ ABI. However, even if these attributes are
7421 // present, we do not layout classes following foreign ABI rules, but
7422 // instead enter a special "compatibility mode", which only changes
7423 // alignments of fundamental types and layout of bit fields.
7424 // Check whether this class uses any C++ features that are implemented
7425 // completely differently in the requested ABI, and if so, emit a
7426 // diagnostic. That diagnostic defaults to an error, but we allow
7427 // projects to map it down to a warning (or ignore it). It's a fairly
7428 // common practice among users of the ms_struct pragma to
7429 // mass-annotate headers, sweeping up a bunch of types that the
7430 // project doesn't really rely on MSVC-compatible layout for. We must
7431 // therefore support "ms_struct except for C++ stuff" as a secondary
7432 // ABI.
7433 // Don't emit this diagnostic if the feature was enabled as a
7434 // language option (as opposed to via a pragma or attribute), as
7435 // the option -mms-bitfields otherwise essentially makes it impossible
7436 // to build C++ code, unless this diagnostic is turned off.
7437 if (Context.getLangOpts().getLayoutCompatibility() ==
7438 LangOptions::LayoutCompatibilityKind::Default &&
7439 Record->isMsStruct(C: Context) != Context.defaultsToMsStruct() &&
7440 (Record->isPolymorphic() || Record->getNumBases())) {
7441 Diag(Loc: Record->getLocation(), DiagID: diag::warn_cxx_ms_struct);
7442 }
7443
7444 checkClassLevelDLLAttribute(Class: Record);
7445 checkClassLevelCodeSegAttribute(Class: Record);
7446
7447 bool ClangABICompat4 =
7448 Context.getLangOpts().isCompatibleWith(Version: LangOptions::ClangABI::Ver4);
7449 TargetInfo::CallingConvKind CCK =
7450 Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
7451 bool CanPass = canPassInRegisters(S&: *this, D: Record, CCK);
7452
7453 // Do not change ArgPassingRestrictions if it has already been set to
7454 // RecordArgPassingKind::CanNeverPassInRegs.
7455 if (Record->getArgPassingRestrictions() !=
7456 RecordArgPassingKind::CanNeverPassInRegs)
7457 Record->setArgPassingRestrictions(
7458 CanPass ? RecordArgPassingKind::CanPassInRegs
7459 : RecordArgPassingKind::CannotPassInRegs);
7460
7461 // If canPassInRegisters returns true despite the record having a non-trivial
7462 // destructor, the record is destructed in the callee. This happens only when
7463 // the record or one of its subobjects has a field annotated with trivial_abi
7464 // or a field qualified with ObjC __strong/__weak.
7465 if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
7466 Record->setParamDestroyedInCallee(true);
7467 else if (Record->hasNonTrivialDestructor())
7468 Record->setParamDestroyedInCallee(CanPass);
7469
7470 if (getLangOpts().ForceEmitVTables) {
7471 // If we want to emit all the vtables, we need to mark it as used. This
7472 // is especially required for cases like vtable assumption loads.
7473 MarkVTableUsed(Loc: Record->getInnerLocStart(), Class: Record);
7474 }
7475
7476 if (getLangOpts().CUDA) {
7477 if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>())
7478 checkCUDADeviceBuiltinSurfaceClassTemplate(S&: *this, Class: Record);
7479 else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>())
7480 checkCUDADeviceBuiltinTextureClassTemplate(S&: *this, Class: Record);
7481 }
7482
7483 llvm::SmallDenseMap<OverloadedOperatorKind,
7484 llvm::SmallVector<const FunctionDecl *, 2>, 4>
7485 TypeAwareDecls{{OO_New, {}},
7486 {OO_Array_New, {}},
7487 {OO_Delete, {}},
7488 {OO_Array_New, {}}};
7489 for (auto *D : Record->decls()) {
7490 const FunctionDecl *FnDecl = D->getAsFunction();
7491 if (!FnDecl || !FnDecl->isTypeAwareOperatorNewOrDelete())
7492 continue;
7493 assert(FnDecl->getDeclName().isAnyOperatorNewOrDelete());
7494 TypeAwareDecls[FnDecl->getOverloadedOperator()].push_back(Elt: FnDecl);
7495 }
7496 auto CheckMismatchedTypeAwareAllocators =
7497 [this, &TypeAwareDecls, Record](OverloadedOperatorKind NewKind,
7498 OverloadedOperatorKind DeleteKind) {
7499 auto &NewDecls = TypeAwareDecls[NewKind];
7500 auto &DeleteDecls = TypeAwareDecls[DeleteKind];
7501 if (NewDecls.empty() == DeleteDecls.empty())
7502 return;
7503 DeclarationName FoundOperator =
7504 Context.DeclarationNames.getCXXOperatorName(
7505 Op: NewDecls.empty() ? DeleteKind : NewKind);
7506 DeclarationName MissingOperator =
7507 Context.DeclarationNames.getCXXOperatorName(
7508 Op: NewDecls.empty() ? NewKind : DeleteKind);
7509 Diag(Loc: Record->getLocation(),
7510 DiagID: diag::err_type_aware_allocator_missing_matching_operator)
7511 << FoundOperator << Context.getCanonicalTagType(TD: Record)
7512 << MissingOperator;
7513 for (auto MD : NewDecls)
7514 Diag(Loc: MD->getLocation(),
7515 DiagID: diag::note_unmatched_type_aware_allocator_declared)
7516 << MD;
7517 for (auto MD : DeleteDecls)
7518 Diag(Loc: MD->getLocation(),
7519 DiagID: diag::note_unmatched_type_aware_allocator_declared)
7520 << MD;
7521 };
7522 CheckMismatchedTypeAwareAllocators(OO_New, OO_Delete);
7523 CheckMismatchedTypeAwareAllocators(OO_Array_New, OO_Array_Delete);
7524}
7525
7526/// Look up the special member function that would be called by a special
7527/// member function for a subobject of class type.
7528///
7529/// \param Class The class type of the subobject.
7530/// \param CSM The kind of special member function.
7531/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
7532/// \param ConstRHS True if this is a copy operation with a const object
7533/// on its RHS, that is, if the argument to the outer special member
7534/// function is 'const' and this is not a field marked 'mutable'.
7535static Sema::SpecialMemberOverloadResult
7536lookupCallFromSpecialMember(Sema &S, CXXRecordDecl *Class,
7537 CXXSpecialMemberKind CSM, unsigned FieldQuals,
7538 bool ConstRHS) {
7539 unsigned LHSQuals = 0;
7540 if (CSM == CXXSpecialMemberKind::CopyAssignment ||
7541 CSM == CXXSpecialMemberKind::MoveAssignment)
7542 LHSQuals = FieldQuals;
7543
7544 unsigned RHSQuals = FieldQuals;
7545 if (CSM == CXXSpecialMemberKind::DefaultConstructor ||
7546 CSM == CXXSpecialMemberKind::Destructor)
7547 RHSQuals = 0;
7548 else if (ConstRHS)
7549 RHSQuals |= Qualifiers::Const;
7550
7551 return S.LookupSpecialMember(D: Class, SM: CSM,
7552 ConstArg: RHSQuals & Qualifiers::Const,
7553 VolatileArg: RHSQuals & Qualifiers::Volatile,
7554 RValueThis: false,
7555 ConstThis: LHSQuals & Qualifiers::Const,
7556 VolatileThis: LHSQuals & Qualifiers::Volatile);
7557}
7558
7559class Sema::InheritedConstructorInfo {
7560 Sema &S;
7561 SourceLocation UseLoc;
7562
7563 /// A mapping from the base classes through which the constructor was
7564 /// inherited to the using shadow declaration in that base class (or a null
7565 /// pointer if the constructor was declared in that base class).
7566 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
7567 InheritedFromBases;
7568
7569public:
7570 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
7571 ConstructorUsingShadowDecl *Shadow)
7572 : S(S), UseLoc(UseLoc) {
7573 bool DiagnosedMultipleConstructedBases = false;
7574 CXXRecordDecl *ConstructedBase = nullptr;
7575 BaseUsingDecl *ConstructedBaseIntroducer = nullptr;
7576
7577 // Find the set of such base class subobjects and check that there's a
7578 // unique constructed subobject.
7579 for (auto *D : Shadow->redecls()) {
7580 auto *DShadow = cast<ConstructorUsingShadowDecl>(Val: D);
7581 auto *DNominatedBase = DShadow->getNominatedBaseClass();
7582 auto *DConstructedBase = DShadow->getConstructedBaseClass();
7583
7584 InheritedFromBases.insert(
7585 KV: std::make_pair(x: DNominatedBase->getCanonicalDecl(),
7586 y: DShadow->getNominatedBaseClassShadowDecl()));
7587 if (DShadow->constructsVirtualBase())
7588 InheritedFromBases.insert(
7589 KV: std::make_pair(x: DConstructedBase->getCanonicalDecl(),
7590 y: DShadow->getConstructedBaseClassShadowDecl()));
7591 else
7592 assert(DNominatedBase == DConstructedBase);
7593
7594 // [class.inhctor.init]p2:
7595 // If the constructor was inherited from multiple base class subobjects
7596 // of type B, the program is ill-formed.
7597 if (!ConstructedBase) {
7598 ConstructedBase = DConstructedBase;
7599 ConstructedBaseIntroducer = D->getIntroducer();
7600 } else if (ConstructedBase != DConstructedBase &&
7601 !Shadow->isInvalidDecl()) {
7602 if (!DiagnosedMultipleConstructedBases) {
7603 S.Diag(Loc: UseLoc, DiagID: diag::err_ambiguous_inherited_constructor)
7604 << Shadow->getTargetDecl();
7605 S.Diag(Loc: ConstructedBaseIntroducer->getLocation(),
7606 DiagID: diag::note_ambiguous_inherited_constructor_using)
7607 << ConstructedBase;
7608 DiagnosedMultipleConstructedBases = true;
7609 }
7610 S.Diag(Loc: D->getIntroducer()->getLocation(),
7611 DiagID: diag::note_ambiguous_inherited_constructor_using)
7612 << DConstructedBase;
7613 }
7614 }
7615
7616 if (DiagnosedMultipleConstructedBases)
7617 Shadow->setInvalidDecl();
7618 }
7619
7620 /// Find the constructor to use for inherited construction of a base class,
7621 /// and whether that base class constructor inherits the constructor from a
7622 /// virtual base class (in which case it won't actually invoke it).
7623 std::pair<CXXConstructorDecl *, bool>
7624 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
7625 auto It = InheritedFromBases.find(Val: Base->getCanonicalDecl());
7626 if (It == InheritedFromBases.end())
7627 return std::make_pair(x: nullptr, y: false);
7628
7629 // This is an intermediary class.
7630 if (It->second)
7631 return std::make_pair(
7632 x: S.findInheritingConstructor(Loc: UseLoc, BaseCtor: Ctor, DerivedShadow: It->second),
7633 y: It->second->constructsVirtualBase());
7634
7635 // This is the base class from which the constructor was inherited.
7636 return std::make_pair(x&: Ctor, y: false);
7637 }
7638};
7639
7640/// Is the special member function which would be selected to perform the
7641/// specified operation on the specified class type a constexpr constructor?
7642static bool specialMemberIsConstexpr(
7643 Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, unsigned Quals,
7644 bool ConstRHS, CXXConstructorDecl *InheritedCtor = nullptr,
7645 Sema::InheritedConstructorInfo *Inherited = nullptr) {
7646 // Suppress duplicate constraint checking here, in case a constraint check
7647 // caused us to decide to do this. Any truely recursive checks will get
7648 // caught during these checks anyway.
7649 Sema::SatisfactionStackResetRAII SSRAII{S};
7650
7651 // If we're inheriting a constructor, see if we need to call it for this base
7652 // class.
7653 if (InheritedCtor) {
7654 assert(CSM == CXXSpecialMemberKind::DefaultConstructor);
7655 auto BaseCtor =
7656 Inherited->findConstructorForBase(Base: ClassDecl, Ctor: InheritedCtor).first;
7657 if (BaseCtor)
7658 return BaseCtor->isConstexpr();
7659 }
7660
7661 if (CSM == CXXSpecialMemberKind::DefaultConstructor)
7662 return ClassDecl->hasConstexprDefaultConstructor();
7663 if (CSM == CXXSpecialMemberKind::Destructor)
7664 return ClassDecl->hasConstexprDestructor();
7665
7666 Sema::SpecialMemberOverloadResult SMOR =
7667 lookupCallFromSpecialMember(S, Class: ClassDecl, CSM, FieldQuals: Quals, ConstRHS);
7668 if (!SMOR.getMethod())
7669 // A constructor we wouldn't select can't be "involved in initializing"
7670 // anything.
7671 return true;
7672 return SMOR.getMethod()->isConstexpr();
7673}
7674
7675/// Determine whether the specified special member function would be constexpr
7676/// if it were implicitly defined.
7677static bool defaultedSpecialMemberIsConstexpr(
7678 Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, bool ConstArg,
7679 CXXConstructorDecl *InheritedCtor = nullptr,
7680 Sema::InheritedConstructorInfo *Inherited = nullptr) {
7681 if (!S.getLangOpts().CPlusPlus11)
7682 return false;
7683
7684 // C++11 [dcl.constexpr]p4:
7685 // In the definition of a constexpr constructor [...]
7686 bool Ctor = true;
7687 switch (CSM) {
7688 case CXXSpecialMemberKind::DefaultConstructor:
7689 if (Inherited)
7690 break;
7691 // Since default constructor lookup is essentially trivial (and cannot
7692 // involve, for instance, template instantiation), we compute whether a
7693 // defaulted default constructor is constexpr directly within CXXRecordDecl.
7694 //
7695 // This is important for performance; we need to know whether the default
7696 // constructor is constexpr to determine whether the type is a literal type.
7697 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
7698
7699 case CXXSpecialMemberKind::CopyConstructor:
7700 case CXXSpecialMemberKind::MoveConstructor:
7701 // For copy or move constructors, we need to perform overload resolution.
7702 break;
7703
7704 case CXXSpecialMemberKind::CopyAssignment:
7705 case CXXSpecialMemberKind::MoveAssignment:
7706 if (!S.getLangOpts().CPlusPlus14)
7707 return false;
7708 // In C++1y, we need to perform overload resolution.
7709 Ctor = false;
7710 break;
7711
7712 case CXXSpecialMemberKind::Destructor:
7713 return ClassDecl->defaultedDestructorIsConstexpr();
7714
7715 case CXXSpecialMemberKind::Invalid:
7716 return false;
7717 }
7718
7719 // -- if the class is a non-empty union, or for each non-empty anonymous
7720 // union member of a non-union class, exactly one non-static data member
7721 // shall be initialized; [DR1359]
7722 //
7723 // If we squint, this is guaranteed, since exactly one non-static data member
7724 // will be initialized (if the constructor isn't deleted), we just don't know
7725 // which one.
7726 if (Ctor && ClassDecl->isUnion())
7727 return CSM == CXXSpecialMemberKind::DefaultConstructor
7728 ? ClassDecl->hasInClassInitializer() ||
7729 !ClassDecl->hasVariantMembers()
7730 : true;
7731
7732 // -- the class shall not have any virtual base classes;
7733 if (!S.getLangOpts().CPlusPlus26 && Ctor && ClassDecl->getNumVBases())
7734 return false;
7735
7736 // C++1y [class.copy]p26:
7737 // -- [the class] is a literal type, and
7738 if (!S.getLangOpts().CPlusPlus23 && !Ctor && !ClassDecl->isLiteral())
7739 return false;
7740
7741 // -- every constructor involved in initializing [...] base class
7742 // sub-objects shall be a constexpr constructor;
7743 // -- the assignment operator selected to copy/move each direct base
7744 // class is a constexpr function, and
7745 if (!S.getLangOpts().CPlusPlus23) {
7746 for (const auto &B : ClassDecl->bases()) {
7747 auto *BaseClassDecl = B.getType()->getAsCXXRecordDecl();
7748 if (!BaseClassDecl)
7749 continue;
7750 if (!specialMemberIsConstexpr(S, ClassDecl: BaseClassDecl, CSM, Quals: 0, ConstRHS: ConstArg,
7751 InheritedCtor, Inherited))
7752 return false;
7753 }
7754 }
7755
7756 // -- every constructor involved in initializing non-static data members
7757 // [...] shall be a constexpr constructor;
7758 // -- every non-static data member and base class sub-object shall be
7759 // initialized
7760 // -- for each non-static data member of X that is of class type (or array
7761 // thereof), the assignment operator selected to copy/move that member is
7762 // a constexpr function
7763 if (!S.getLangOpts().CPlusPlus23) {
7764 for (const auto *F : ClassDecl->fields()) {
7765 if (F->isInvalidDecl())
7766 continue;
7767 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
7768 F->hasInClassInitializer())
7769 continue;
7770 QualType BaseType = S.Context.getBaseElementType(QT: F->getType());
7771 if (const RecordType *RecordTy = BaseType->getAsCanonical<RecordType>()) {
7772 auto *FieldRecDecl =
7773 cast<CXXRecordDecl>(Val: RecordTy->getDecl())->getDefinitionOrSelf();
7774 if (!specialMemberIsConstexpr(S, ClassDecl: FieldRecDecl, CSM,
7775 Quals: BaseType.getCVRQualifiers(),
7776 ConstRHS: ConstArg && !F->isMutable()))
7777 return false;
7778 } else if (CSM == CXXSpecialMemberKind::DefaultConstructor) {
7779 return false;
7780 }
7781 }
7782 }
7783
7784 // All OK, it's constexpr!
7785 return true;
7786}
7787
7788namespace {
7789/// RAII object to register a defaulted function as having its exception
7790/// specification computed.
7791struct ComputingExceptionSpec {
7792 Sema &S;
7793
7794 ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc)
7795 : S(S) {
7796 Sema::CodeSynthesisContext Ctx;
7797 Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;
7798 Ctx.PointOfInstantiation = Loc;
7799 Ctx.Entity = FD;
7800 S.pushCodeSynthesisContext(Ctx);
7801 }
7802 ~ComputingExceptionSpec() {
7803 S.popCodeSynthesisContext();
7804 }
7805};
7806}
7807
7808static Sema::ImplicitExceptionSpecification
7809ComputeDefaultedSpecialMemberExceptionSpec(Sema &S, SourceLocation Loc,
7810 CXXMethodDecl *MD,
7811 CXXSpecialMemberKind CSM,
7812 Sema::InheritedConstructorInfo *ICI);
7813
7814static Sema::ImplicitExceptionSpecification
7815ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
7816 FunctionDecl *FD,
7817 DefaultedComparisonKind DCK);
7818
7819static Sema::ImplicitExceptionSpecification
7820computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD) {
7821 auto DFK = FD->getDefaultedFunctionKind();
7822 if (DFK.isSpecialMember())
7823 return ComputeDefaultedSpecialMemberExceptionSpec(
7824 S, Loc, MD: cast<CXXMethodDecl>(Val: FD), CSM: DFK.asSpecialMember(), ICI: nullptr);
7825 if (DFK.isComparison())
7826 return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD,
7827 DCK: DFK.asComparison());
7828
7829 auto *CD = cast<CXXConstructorDecl>(Val: FD);
7830 assert(CD->getInheritedConstructor() &&
7831 "only defaulted functions and inherited constructors have implicit "
7832 "exception specs");
7833 Sema::InheritedConstructorInfo ICI(
7834 S, Loc, CD->getInheritedConstructor().getShadowDecl());
7835 return ComputeDefaultedSpecialMemberExceptionSpec(
7836 S, Loc, MD: CD, CSM: CXXSpecialMemberKind::DefaultConstructor, ICI: &ICI);
7837}
7838
7839static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
7840 CXXMethodDecl *MD) {
7841 FunctionProtoType::ExtProtoInfo EPI;
7842
7843 // Build an exception specification pointing back at this member.
7844 EPI.ExceptionSpec.Type = EST_Unevaluated;
7845 EPI.ExceptionSpec.SourceDecl = MD;
7846
7847 // Set the calling convention to the default for C++ instance methods.
7848 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
7849 cc: S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
7850 /*IsCXXMethod=*/true));
7851 return EPI;
7852}
7853
7854void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD) {
7855 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
7856 if (FPT->getExceptionSpecType() != EST_Unevaluated)
7857 return;
7858
7859 // Evaluate the exception specification.
7860 auto IES = computeImplicitExceptionSpec(S&: *this, Loc, FD);
7861 auto ESI = IES.getExceptionSpec();
7862
7863 // Update the type of the special member to use it.
7864 UpdateExceptionSpec(FD, ESI);
7865}
7866
7867void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) {
7868 assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted");
7869
7870 FunctionDecl::DefaultedFunctionKind DefKind = FD->getDefaultedFunctionKind();
7871 if (!DefKind) {
7872 assert(FD->getDeclContext()->isDependentContext());
7873 return;
7874 }
7875
7876 if (DefKind.isComparison()) {
7877 auto PT = FD->getParamDecl(i: 0)->getType();
7878 if (const CXXRecordDecl *RD =
7879 PT.getNonReferenceType()->getAsCXXRecordDecl()) {
7880 for (FieldDecl *Field : RD->fields()) {
7881 UnusedPrivateFields.remove(X: Field);
7882 }
7883 }
7884 }
7885
7886 if (DefKind.isSpecialMember()
7887 ? CheckExplicitlyDefaultedSpecialMember(MD: cast<CXXMethodDecl>(Val: FD),
7888 CSM: DefKind.asSpecialMember(),
7889 DefaultLoc: FD->getDefaultLoc())
7890 : CheckExplicitlyDefaultedComparison(S, MD: FD, DCK: DefKind.asComparison()))
7891 FD->setInvalidDecl();
7892}
7893
7894bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
7895 CXXSpecialMemberKind CSM,
7896 SourceLocation DefaultLoc) {
7897 CXXRecordDecl *RD = MD->getParent();
7898
7899 assert(MD->isExplicitlyDefaulted() && CSM != CXXSpecialMemberKind::Invalid &&
7900 "not an explicitly-defaulted special member");
7901
7902 // Defer all checking for special members of a dependent type.
7903 if (RD->isDependentType())
7904 return false;
7905
7906 // Whether this was the first-declared instance of the constructor.
7907 // This affects whether we implicitly add an exception spec and constexpr.
7908 bool First = MD == MD->getCanonicalDecl();
7909
7910 bool HadError = false;
7911
7912 // C++11 [dcl.fct.def.default]p1:
7913 // A function that is explicitly defaulted shall
7914 // -- be a special member function [...] (checked elsewhere),
7915 // -- have the same type (except for ref-qualifiers, and except that a
7916 // copy operation can take a non-const reference) as an implicit
7917 // declaration, and
7918 // -- not have default arguments.
7919 // C++2a changes the second bullet to instead delete the function if it's
7920 // defaulted on its first declaration, unless it's "an assignment operator,
7921 // and its return type differs or its parameter type is not a reference".
7922 bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First;
7923 bool ShouldDeleteForTypeMismatch = false;
7924 unsigned ExpectedParams = 1;
7925 if (CSM == CXXSpecialMemberKind::DefaultConstructor ||
7926 CSM == CXXSpecialMemberKind::Destructor)
7927 ExpectedParams = 0;
7928 if (MD->getNumExplicitParams() != ExpectedParams) {
7929 // This checks for default arguments: a copy or move constructor with a
7930 // default argument is classified as a default constructor, and assignment
7931 // operations and destructors can't have default arguments.
7932 Diag(Loc: MD->getLocation(), DiagID: diag::err_defaulted_special_member_params)
7933 << CSM << MD->getSourceRange();
7934 HadError = true;
7935 } else if (MD->isVariadic()) {
7936 if (DeleteOnTypeMismatch)
7937 ShouldDeleteForTypeMismatch = true;
7938 else {
7939 Diag(Loc: MD->getLocation(), DiagID: diag::err_defaulted_special_member_variadic)
7940 << CSM << MD->getSourceRange();
7941 HadError = true;
7942 }
7943 }
7944
7945 const FunctionProtoType *Type = MD->getType()->castAs<FunctionProtoType>();
7946
7947 bool CanHaveConstParam = false;
7948 if (CSM == CXXSpecialMemberKind::CopyConstructor)
7949 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
7950 else if (CSM == CXXSpecialMemberKind::CopyAssignment)
7951 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
7952
7953 QualType ReturnType = Context.VoidTy;
7954 if (CSM == CXXSpecialMemberKind::CopyAssignment ||
7955 CSM == CXXSpecialMemberKind::MoveAssignment) {
7956 // Check for return type matching.
7957 ReturnType = Type->getReturnType();
7958 QualType ThisType = MD->getFunctionObjectParameterType();
7959
7960 QualType DeclType =
7961 Context.getTagType(Keyword: ElaboratedTypeKeyword::None,
7962 /*Qualifier=*/std::nullopt, TD: RD, /*OwnsTag=*/false);
7963 DeclType = Context.getAddrSpaceQualType(
7964 T: DeclType, AddressSpace: ThisType.getQualifiers().getAddressSpace());
7965 QualType ExpectedReturnType = Context.getLValueReferenceType(T: DeclType);
7966
7967 if (!Context.hasSameType(T1: ReturnType, T2: ExpectedReturnType)) {
7968 Diag(Loc: MD->getLocation(), DiagID: diag::err_defaulted_special_member_return_type)
7969 << (CSM == CXXSpecialMemberKind::MoveAssignment)
7970 << ExpectedReturnType;
7971 HadError = true;
7972 }
7973
7974 // A defaulted special member cannot have cv-qualifiers.
7975 if (ThisType.isConstQualified() || ThisType.isVolatileQualified()) {
7976 if (DeleteOnTypeMismatch)
7977 ShouldDeleteForTypeMismatch = true;
7978 else {
7979 Diag(Loc: MD->getLocation(), DiagID: diag::err_defaulted_special_member_quals)
7980 << (CSM == CXXSpecialMemberKind::MoveAssignment)
7981 << getLangOpts().CPlusPlus14;
7982 HadError = true;
7983 }
7984 }
7985 // [C++23][dcl.fct.def.default]/p2.2
7986 // if F2 has an implicit object parameter of type “reference to C”,
7987 // F1 may be an explicit object member function whose explicit object
7988 // parameter is of (possibly different) type “reference to C”,
7989 // in which case the type of F1 would differ from the type of F2
7990 // in that the type of F1 has an additional parameter;
7991 QualType ExplicitObjectParameter = MD->isExplicitObjectMemberFunction()
7992 ? MD->getParamDecl(i: 0)->getType()
7993 : QualType();
7994 if (!ExplicitObjectParameter.isNull() &&
7995 (!ExplicitObjectParameter->isReferenceType() ||
7996 !Context.hasSameType(T1: ExplicitObjectParameter.getNonReferenceType(),
7997 T2: Context.getCanonicalTagType(TD: RD)))) {
7998 if (DeleteOnTypeMismatch)
7999 ShouldDeleteForTypeMismatch = true;
8000 else {
8001 Diag(Loc: MD->getLocation(),
8002 DiagID: diag::err_defaulted_special_member_explicit_object_mismatch)
8003 << (CSM == CXXSpecialMemberKind::MoveAssignment) << RD
8004 << MD->getSourceRange();
8005 HadError = true;
8006 }
8007 }
8008 }
8009
8010 // Check for parameter type matching.
8011 QualType ArgType =
8012 ExpectedParams
8013 ? Type->getParamType(i: MD->isExplicitObjectMemberFunction() ? 1 : 0)
8014 : QualType();
8015 bool HasConstParam = false;
8016 if (ExpectedParams && ArgType->isReferenceType()) {
8017 // Argument must be reference to possibly-const T.
8018 QualType ReferentType = ArgType->getPointeeType();
8019 HasConstParam = ReferentType.isConstQualified();
8020
8021 if (ReferentType.isVolatileQualified()) {
8022 if (DeleteOnTypeMismatch)
8023 ShouldDeleteForTypeMismatch = true;
8024 else {
8025 Diag(Loc: MD->getLocation(),
8026 DiagID: diag::err_defaulted_special_member_volatile_param)
8027 << CSM;
8028 HadError = true;
8029 }
8030 }
8031
8032 if (HasConstParam && !CanHaveConstParam) {
8033 if (DeleteOnTypeMismatch)
8034 ShouldDeleteForTypeMismatch = true;
8035 else if (CSM == CXXSpecialMemberKind::CopyConstructor ||
8036 CSM == CXXSpecialMemberKind::CopyAssignment) {
8037 Diag(Loc: MD->getLocation(),
8038 DiagID: diag::err_defaulted_special_member_copy_const_param)
8039 << (CSM == CXXSpecialMemberKind::CopyAssignment);
8040 // FIXME: Explain why this special member can't be const.
8041 HadError = true;
8042 } else {
8043 Diag(Loc: MD->getLocation(),
8044 DiagID: diag::err_defaulted_special_member_move_const_param)
8045 << (CSM == CXXSpecialMemberKind::MoveAssignment);
8046 HadError = true;
8047 }
8048 }
8049 } else if (ExpectedParams) {
8050 // A copy assignment operator can take its argument by value, but a
8051 // defaulted one cannot.
8052 assert(CSM == CXXSpecialMemberKind::CopyAssignment &&
8053 "unexpected non-ref argument");
8054 Diag(Loc: MD->getLocation(), DiagID: diag::err_defaulted_copy_assign_not_ref);
8055 HadError = true;
8056 }
8057
8058 // C++11 [dcl.fct.def.default]p2:
8059 // An explicitly-defaulted function may be declared constexpr only if it
8060 // would have been implicitly declared as constexpr,
8061 // Do not apply this rule to members of class templates, since core issue 1358
8062 // makes such functions always instantiate to constexpr functions. For
8063 // functions which cannot be constexpr (for non-constructors in C++11 and for
8064 // destructors in C++14 and C++17), this is checked elsewhere.
8065 //
8066 // FIXME: This should not apply if the member is deleted.
8067 bool Constexpr = defaultedSpecialMemberIsConstexpr(S&: *this, ClassDecl: RD, CSM,
8068 ConstArg: HasConstParam);
8069
8070 // C++14 [dcl.constexpr]p6 (CWG DR647/CWG DR1358):
8071 // If the instantiated template specialization of a constexpr function
8072 // template or member function of a class template would fail to satisfy
8073 // the requirements for a constexpr function or constexpr constructor, that
8074 // specialization is still a constexpr function or constexpr constructor,
8075 // even though a call to such a function cannot appear in a constant
8076 // expression.
8077 if (MD->isTemplateInstantiation() && MD->isConstexpr())
8078 Constexpr = true;
8079
8080 if ((getLangOpts().CPlusPlus20 ||
8081 (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(Val: MD)
8082 : isa<CXXConstructorDecl>(Val: MD))) &&
8083 MD->isConstexpr() && !Constexpr &&
8084 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
8085 if (!MD->isConsteval() && RD->getNumVBases()) {
8086 Diag(Loc: MD->getBeginLoc(),
8087 DiagID: diag::err_incorrect_defaulted_constexpr_with_vb)
8088 << CSM;
8089 for (const auto &I : RD->vbases())
8090 Diag(Loc: I.getBeginLoc(), DiagID: diag::note_constexpr_virtual_base_here);
8091 } else {
8092 Diag(Loc: MD->getBeginLoc(), DiagID: diag::err_incorrect_defaulted_constexpr)
8093 << CSM << MD->isConsteval();
8094 }
8095 HadError = true;
8096 // FIXME: Explain why the special member can't be constexpr.
8097 }
8098 if (First) {
8099 // C++2a [dcl.fct.def.default]p3:
8100 // If a function is explicitly defaulted on its first declaration, it is
8101 // implicitly considered to be constexpr if the implicit declaration
8102 // would be.
8103 MD->setConstexprKind(Constexpr ? (MD->isConsteval()
8104 ? ConstexprSpecKind::Consteval
8105 : ConstexprSpecKind::Constexpr)
8106 : ConstexprSpecKind::Unspecified);
8107
8108 if (!Type->hasExceptionSpec()) {
8109 // C++2a [except.spec]p3:
8110 // If a declaration of a function does not have a noexcept-specifier
8111 // [and] is defaulted on its first declaration, [...] the exception
8112 // specification is as specified below
8113 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
8114 EPI.ExceptionSpec.Type = EST_Unevaluated;
8115 EPI.ExceptionSpec.SourceDecl = MD;
8116 MD->setType(
8117 Context.getFunctionType(ResultTy: ReturnType, Args: Type->getParamTypes(), EPI));
8118 }
8119 }
8120
8121 if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
8122 if (First) {
8123 SetDeclDeleted(dcl: MD, DelLoc: MD->getLocation());
8124 if (!inTemplateInstantiation() && !HadError) {
8125 Diag(Loc: MD->getLocation(), DiagID: diag::warn_defaulted_method_deleted) << CSM;
8126 if (ShouldDeleteForTypeMismatch) {
8127 Diag(Loc: MD->getLocation(), DiagID: diag::note_deleted_type_mismatch) << CSM;
8128 } else if (ShouldDeleteSpecialMember(MD, CSM, ICI: nullptr,
8129 /*Diagnose*/ true) &&
8130 DefaultLoc.isValid()) {
8131 Diag(Loc: DefaultLoc, DiagID: diag::note_replace_equals_default_to_delete)
8132 << FixItHint::CreateReplacement(RemoveRange: DefaultLoc, Code: "delete");
8133 }
8134 }
8135 if (ShouldDeleteForTypeMismatch && !HadError) {
8136 Diag(Loc: MD->getLocation(),
8137 DiagID: diag::warn_cxx17_compat_defaulted_method_type_mismatch)
8138 << CSM;
8139 }
8140 } else {
8141 // C++11 [dcl.fct.def.default]p4:
8142 // [For a] user-provided explicitly-defaulted function [...] if such a
8143 // function is implicitly defined as deleted, the program is ill-formed.
8144 Diag(Loc: MD->getLocation(), DiagID: diag::err_out_of_line_default_deletes) << CSM;
8145 assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
8146 ShouldDeleteSpecialMember(MD, CSM, ICI: nullptr, /*Diagnose*/true);
8147 HadError = true;
8148 }
8149 }
8150
8151 return HadError;
8152}
8153
8154namespace {
8155/// Helper class for building and checking a defaulted comparison.
8156///
8157/// Defaulted functions are built in two phases:
8158///
8159/// * First, the set of operations that the function will perform are
8160/// identified, and some of them are checked. If any of the checked
8161/// operations is invalid in certain ways, the comparison function is
8162/// defined as deleted and no body is built.
8163/// * Then, if the function is not defined as deleted, the body is built.
8164///
8165/// This is accomplished by performing two visitation steps over the eventual
8166/// body of the function.
8167template<typename Derived, typename ResultList, typename Result,
8168 typename Subobject>
8169class DefaultedComparisonVisitor {
8170public:
8171 DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8172 DefaultedComparisonKind DCK)
8173 : S(S), RD(RD), FD(FD), DCK(DCK) {
8174 if (auto *Info = FD->getDefaultedOrDeletedInfo()) {
8175 // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an
8176 // UnresolvedSet to avoid this copy.
8177 Fns.assign(I: Info->getUnqualifiedLookups().begin(),
8178 E: Info->getUnqualifiedLookups().end());
8179 }
8180 }
8181
8182 ResultList visit() {
8183 // The type of an lvalue naming a parameter of this function.
8184 QualType ParamLvalType =
8185 FD->getParamDecl(i: 0)->getType().getNonReferenceType();
8186
8187 ResultList Results;
8188
8189 switch (DCK) {
8190 case DefaultedComparisonKind::None:
8191 llvm_unreachable("not a defaulted comparison");
8192
8193 case DefaultedComparisonKind::Equal:
8194 case DefaultedComparisonKind::ThreeWay:
8195 getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers());
8196 return Results;
8197
8198 case DefaultedComparisonKind::NotEqual:
8199 case DefaultedComparisonKind::Relational:
8200 Results.add(getDerived().visitExpandedSubobject(
8201 ParamLvalType, getDerived().getCompleteObject()));
8202 return Results;
8203 }
8204 llvm_unreachable("");
8205 }
8206
8207protected:
8208 Derived &getDerived() { return static_cast<Derived&>(*this); }
8209
8210 /// Visit the expanded list of subobjects of the given type, as specified in
8211 /// C++2a [class.compare.default].
8212 ///
8213 /// \return \c true if the ResultList object said we're done, \c false if not.
8214 bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record,
8215 Qualifiers Quals) {
8216 // C++2a [class.compare.default]p4:
8217 // The direct base class subobjects of C
8218 for (CXXBaseSpecifier &Base : Record->bases())
8219 if (Results.add(getDerived().visitSubobject(
8220 S.Context.getQualifiedType(T: Base.getType(), Qs: Quals),
8221 getDerived().getBase(&Base))))
8222 return true;
8223
8224 // followed by the non-static data members of C
8225 for (FieldDecl *Field : Record->fields()) {
8226 // C++23 [class.bit]p2:
8227 // Unnamed bit-fields are not members ...
8228 if (Field->isUnnamedBitField())
8229 continue;
8230 if (Field->isInvalidDecl())
8231 continue;
8232 // Recursively expand anonymous structs.
8233 if (Field->isAnonymousStructOrUnion()) {
8234 if (visitSubobjects(Results, Record: Field->getType()->getAsCXXRecordDecl(),
8235 Quals))
8236 return true;
8237 continue;
8238 }
8239
8240 // Figure out the type of an lvalue denoting this field.
8241 Qualifiers FieldQuals = Quals;
8242 if (Field->isMutable())
8243 FieldQuals.removeConst();
8244 QualType FieldType =
8245 S.Context.getQualifiedType(T: Field->getType(), Qs: FieldQuals);
8246
8247 if (Results.add(getDerived().visitSubobject(
8248 FieldType, getDerived().getField(Field))))
8249 return true;
8250 }
8251
8252 // form a list of subobjects.
8253 return false;
8254 }
8255
8256 Result visitSubobject(QualType Type, Subobject Subobj) {
8257 // In that list, any subobject of array type is recursively expanded
8258 const ArrayType *AT = S.Context.getAsArrayType(T: Type);
8259 if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(Val: AT))
8260 return getDerived().visitSubobjectArray(CAT->getElementType(),
8261 CAT->getSize(), Subobj);
8262 return getDerived().visitExpandedSubobject(Type, Subobj);
8263 }
8264
8265 Result visitSubobjectArray(QualType Type, const llvm::APInt &Size,
8266 Subobject Subobj) {
8267 return getDerived().visitSubobject(Type, Subobj);
8268 }
8269
8270protected:
8271 Sema &S;
8272 CXXRecordDecl *RD;
8273 FunctionDecl *FD;
8274 DefaultedComparisonKind DCK;
8275 UnresolvedSet<16> Fns;
8276};
8277
8278/// Information about a defaulted comparison, as determined by
8279/// DefaultedComparisonAnalyzer.
8280struct DefaultedComparisonInfo {
8281 bool Deleted = false;
8282 bool Constexpr = true;
8283 ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering;
8284
8285 static DefaultedComparisonInfo deleted() {
8286 DefaultedComparisonInfo Deleted;
8287 Deleted.Deleted = true;
8288 return Deleted;
8289 }
8290
8291 bool add(const DefaultedComparisonInfo &R) {
8292 Deleted |= R.Deleted;
8293 Constexpr &= R.Constexpr;
8294 Category = commonComparisonType(A: Category, B: R.Category);
8295 return Deleted;
8296 }
8297};
8298
8299/// An element in the expanded list of subobjects of a defaulted comparison, as
8300/// specified in C++2a [class.compare.default]p4.
8301struct DefaultedComparisonSubobject {
8302 enum { CompleteObject, Member, Base } Kind;
8303 NamedDecl *Decl;
8304 SourceLocation Loc;
8305};
8306
8307/// A visitor over the notional body of a defaulted comparison that determines
8308/// whether that body would be deleted or constexpr.
8309class DefaultedComparisonAnalyzer
8310 : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer,
8311 DefaultedComparisonInfo,
8312 DefaultedComparisonInfo,
8313 DefaultedComparisonSubobject> {
8314public:
8315 enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr };
8316
8317private:
8318 DiagnosticKind Diagnose;
8319
8320public:
8321 using Base = DefaultedComparisonVisitor;
8322 using Result = DefaultedComparisonInfo;
8323 using Subobject = DefaultedComparisonSubobject;
8324
8325 friend Base;
8326
8327 DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8328 DefaultedComparisonKind DCK,
8329 DiagnosticKind Diagnose = NoDiagnostics)
8330 : Base(S, RD, FD, DCK), Diagnose(Diagnose) {}
8331
8332 Result visit() {
8333 if ((DCK == DefaultedComparisonKind::Equal ||
8334 DCK == DefaultedComparisonKind::ThreeWay) &&
8335 RD->hasVariantMembers()) {
8336 // C++2a [class.compare.default]p2 [P2002R0]:
8337 // A defaulted comparison operator function for class C is defined as
8338 // deleted if [...] C has variant members.
8339 if (Diagnose == ExplainDeleted) {
8340 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_defaulted_comparison_union)
8341 << FD << RD->isUnion() << RD;
8342 }
8343 return Result::deleted();
8344 }
8345
8346 return Base::visit();
8347 }
8348
8349private:
8350 Subobject getCompleteObject() {
8351 return Subobject{.Kind: Subobject::CompleteObject, .Decl: RD, .Loc: FD->getLocation()};
8352 }
8353
8354 Subobject getBase(CXXBaseSpecifier *Base) {
8355 return Subobject{.Kind: Subobject::Base, .Decl: Base->getType()->getAsCXXRecordDecl(),
8356 .Loc: Base->getBaseTypeLoc()};
8357 }
8358
8359 Subobject getField(FieldDecl *Field) {
8360 return Subobject{.Kind: Subobject::Member, .Decl: Field, .Loc: Field->getLocation()};
8361 }
8362
8363 Result visitExpandedSubobject(QualType Type, Subobject Subobj) {
8364 // C++2a [class.compare.default]p2 [P2002R0]:
8365 // A defaulted <=> or == operator function for class C is defined as
8366 // deleted if any non-static data member of C is of reference type
8367 if (Type->isReferenceType()) {
8368 if (Diagnose == ExplainDeleted) {
8369 S.Diag(Loc: Subobj.Loc, DiagID: diag::note_defaulted_comparison_reference_member)
8370 << FD << RD;
8371 }
8372 return Result::deleted();
8373 }
8374
8375 // [...] Let xi be an lvalue denoting the ith element [...]
8376 OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue);
8377 Expr *Args[] = {&Xi, &Xi};
8378
8379 // All operators start by trying to apply that same operator recursively.
8380 OverloadedOperatorKind OO = FD->getOverloadedOperator();
8381 assert(OO != OO_None && "not an overloaded operator!");
8382 return visitBinaryOperator(OO, Args, Subobj);
8383 }
8384
8385 Result
8386 visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args,
8387 Subobject Subobj,
8388 OverloadCandidateSet *SpaceshipCandidates = nullptr) {
8389 // Note that there is no need to consider rewritten candidates here if
8390 // we've already found there is no viable 'operator<=>' candidate (and are
8391 // considering synthesizing a '<=>' from '==' and '<').
8392 OverloadCandidateSet CandidateSet(
8393 FD->getLocation(), OverloadCandidateSet::CSK_Operator,
8394 OverloadCandidateSet::OperatorRewriteInfo(
8395 OO, FD->getLocation(),
8396 /*AllowRewrittenCandidates=*/!SpaceshipCandidates));
8397
8398 /// C++2a [class.compare.default]p1 [P2002R0]:
8399 /// [...] the defaulted function itself is never a candidate for overload
8400 /// resolution [...]
8401 CandidateSet.exclude(F: FD);
8402
8403 if (Args[0]->getType()->isOverloadableType())
8404 S.LookupOverloadedBinOp(CandidateSet, Op: OO, Fns, Args);
8405 else
8406 // FIXME: We determine whether this is a valid expression by checking to
8407 // see if there's a viable builtin operator candidate for it. That isn't
8408 // really what the rules ask us to do, but should give the right results.
8409 S.AddBuiltinOperatorCandidates(Op: OO, OpLoc: FD->getLocation(), Args, CandidateSet);
8410
8411 Result R;
8412
8413 OverloadCandidateSet::iterator Best;
8414 switch (CandidateSet.BestViableFunction(S, Loc: FD->getLocation(), Best)) {
8415 case OR_Success: {
8416 // C++2a [class.compare.secondary]p2 [P2002R0]:
8417 // The operator function [...] is defined as deleted if [...] the
8418 // candidate selected by overload resolution is not a rewritten
8419 // candidate.
8420 if ((DCK == DefaultedComparisonKind::NotEqual ||
8421 DCK == DefaultedComparisonKind::Relational) &&
8422 !Best->RewriteKind) {
8423 if (Diagnose == ExplainDeleted) {
8424 if (Best->Function) {
8425 S.Diag(Loc: Best->Function->getLocation(),
8426 DiagID: diag::note_defaulted_comparison_not_rewritten_callee)
8427 << FD;
8428 } else {
8429 assert(Best->Conversions.size() == 2 &&
8430 Best->Conversions[0].isUserDefined() &&
8431 "non-user-defined conversion from class to built-in "
8432 "comparison");
8433 S.Diag(Loc: Best->Conversions[0]
8434 .UserDefined.FoundConversionFunction.getDecl()
8435 ->getLocation(),
8436 DiagID: diag::note_defaulted_comparison_not_rewritten_conversion)
8437 << FD;
8438 }
8439 }
8440 return Result::deleted();
8441 }
8442
8443 // Throughout C++2a [class.compare]: if overload resolution does not
8444 // result in a usable function, the candidate function is defined as
8445 // deleted. This requires that we selected an accessible function.
8446 //
8447 // Note that this only considers the access of the function when named
8448 // within the type of the subobject, and not the access path for any
8449 // derived-to-base conversion.
8450 CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl();
8451 if (ArgClass && Best->FoundDecl.getDecl() &&
8452 Best->FoundDecl.getDecl()->isCXXClassMember()) {
8453 QualType ObjectType = Subobj.Kind == Subobject::Member
8454 ? Args[0]->getType()
8455 : S.Context.getCanonicalTagType(TD: RD);
8456 if (!S.isMemberAccessibleForDeletion(
8457 NamingClass: ArgClass, Found: Best->FoundDecl, ObjectType, Loc: Subobj.Loc,
8458 Diag: Diagnose == ExplainDeleted
8459 ? S.PDiag(DiagID: diag::note_defaulted_comparison_inaccessible)
8460 << FD << Subobj.Kind << Subobj.Decl
8461 : S.PDiag()))
8462 return Result::deleted();
8463 }
8464
8465 bool NeedsDeducing =
8466 OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType();
8467
8468 if (FunctionDecl *BestFD = Best->Function) {
8469 // C++2a [class.compare.default]p3 [P2002R0]:
8470 // A defaulted comparison function is constexpr-compatible if
8471 // [...] no overlod resolution performed [...] results in a
8472 // non-constexpr function.
8473 assert(!BestFD->isDeleted() && "wrong overload resolution result");
8474 // If it's not constexpr, explain why not.
8475 if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) {
8476 if (Subobj.Kind != Subobject::CompleteObject)
8477 S.Diag(Loc: Subobj.Loc, DiagID: diag::note_defaulted_comparison_not_constexpr)
8478 << Subobj.Kind << Subobj.Decl;
8479 S.Diag(Loc: BestFD->getLocation(),
8480 DiagID: diag::note_defaulted_comparison_not_constexpr_here);
8481 // Bail out after explaining; we don't want any more notes.
8482 return Result::deleted();
8483 }
8484 R.Constexpr &= BestFD->isConstexpr();
8485
8486 if (NeedsDeducing) {
8487 // If any callee has an undeduced return type, deduce it now.
8488 // FIXME: It's not clear how a failure here should be handled. For
8489 // now, we produce an eager diagnostic, because that is forward
8490 // compatible with most (all?) other reasonable options.
8491 if (BestFD->getReturnType()->isUndeducedType() &&
8492 S.DeduceReturnType(FD: BestFD, Loc: FD->getLocation(),
8493 /*Diagnose=*/false)) {
8494 // Don't produce a duplicate error when asked to explain why the
8495 // comparison is deleted: we diagnosed that when initially checking
8496 // the defaulted operator.
8497 if (Diagnose == NoDiagnostics) {
8498 S.Diag(
8499 Loc: FD->getLocation(),
8500 DiagID: diag::err_defaulted_comparison_cannot_deduce_undeduced_auto)
8501 << Subobj.Kind << Subobj.Decl;
8502 S.Diag(
8503 Loc: Subobj.Loc,
8504 DiagID: diag::note_defaulted_comparison_cannot_deduce_undeduced_auto)
8505 << Subobj.Kind << Subobj.Decl;
8506 S.Diag(Loc: BestFD->getLocation(),
8507 DiagID: diag::note_defaulted_comparison_cannot_deduce_callee)
8508 << Subobj.Kind << Subobj.Decl;
8509 }
8510 return Result::deleted();
8511 }
8512 auto *Info = S.Context.CompCategories.lookupInfoForType(
8513 Ty: BestFD->getCallResultType());
8514 if (!Info) {
8515 if (Diagnose == ExplainDeleted) {
8516 S.Diag(Loc: Subobj.Loc, DiagID: diag::note_defaulted_comparison_cannot_deduce)
8517 << Subobj.Kind << Subobj.Decl
8518 << BestFD->getCallResultType().withoutLocalFastQualifiers();
8519 S.Diag(Loc: BestFD->getLocation(),
8520 DiagID: diag::note_defaulted_comparison_cannot_deduce_callee)
8521 << Subobj.Kind << Subobj.Decl;
8522 }
8523 return Result::deleted();
8524 }
8525 R.Category = Info->Kind;
8526 }
8527 } else {
8528 QualType T = Best->BuiltinParamTypes[0];
8529 assert(T == Best->BuiltinParamTypes[1] &&
8530 "builtin comparison for different types?");
8531 assert(Best->BuiltinParamTypes[2].isNull() &&
8532 "invalid builtin comparison");
8533
8534 // FIXME: If the type we deduced is a vector type, we mark the
8535 // comparison as deleted because we don't yet support this.
8536 if (isa<VectorType>(Val: T)) {
8537 if (Diagnose == ExplainDeleted) {
8538 S.Diag(Loc: FD->getLocation(),
8539 DiagID: diag::note_defaulted_comparison_vector_types)
8540 << FD;
8541 S.Diag(Loc: Subobj.Decl->getLocation(), DiagID: diag::note_declared_at);
8542 }
8543 return Result::deleted();
8544 }
8545
8546 if (NeedsDeducing) {
8547 std::optional<ComparisonCategoryType> Cat =
8548 getComparisonCategoryForBuiltinCmp(T);
8549 assert(Cat && "no category for builtin comparison?");
8550 R.Category = *Cat;
8551 }
8552 }
8553
8554 // Note that we might be rewriting to a different operator. That call is
8555 // not considered until we come to actually build the comparison function.
8556 break;
8557 }
8558
8559 case OR_Ambiguous:
8560 if (Diagnose == ExplainDeleted) {
8561 unsigned Kind = 0;
8562 if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship)
8563 Kind = OO == OO_EqualEqual ? 1 : 2;
8564 CandidateSet.NoteCandidates(
8565 PA: PartialDiagnosticAt(
8566 Subobj.Loc, S.PDiag(DiagID: diag::note_defaulted_comparison_ambiguous)
8567 << FD << Kind << Subobj.Kind << Subobj.Decl),
8568 S, OCD: OCD_AmbiguousCandidates, Args);
8569 }
8570 R = Result::deleted();
8571 break;
8572
8573 case OR_Deleted:
8574 if (Diagnose == ExplainDeleted) {
8575 if ((DCK == DefaultedComparisonKind::NotEqual ||
8576 DCK == DefaultedComparisonKind::Relational) &&
8577 !Best->RewriteKind) {
8578 S.Diag(Loc: Best->Function->getLocation(),
8579 DiagID: diag::note_defaulted_comparison_not_rewritten_callee)
8580 << FD;
8581 } else {
8582 S.Diag(Loc: Subobj.Loc,
8583 DiagID: diag::note_defaulted_comparison_calls_deleted)
8584 << FD << Subobj.Kind << Subobj.Decl;
8585 S.NoteDeletedFunction(FD: Best->Function);
8586 }
8587 }
8588 R = Result::deleted();
8589 break;
8590
8591 case OR_No_Viable_Function:
8592 // If there's no usable candidate, we're done unless we can rewrite a
8593 // '<=>' in terms of '==' and '<'.
8594 if (OO == OO_Spaceship &&
8595 S.Context.CompCategories.lookupInfoForType(Ty: FD->getReturnType())) {
8596 // For any kind of comparison category return type, we need a usable
8597 // '==' and a usable '<'.
8598 if (!R.add(R: visitBinaryOperator(OO: OO_EqualEqual, Args, Subobj,
8599 SpaceshipCandidates: &CandidateSet)))
8600 R.add(R: visitBinaryOperator(OO: OO_Less, Args, Subobj, SpaceshipCandidates: &CandidateSet));
8601 break;
8602 }
8603
8604 if (Diagnose == ExplainDeleted) {
8605 S.Diag(Loc: Subobj.Loc, DiagID: diag::note_defaulted_comparison_no_viable_function)
8606 << FD << (OO == OO_EqualEqual || OO == OO_ExclaimEqual)
8607 << Subobj.Kind << Subobj.Decl;
8608
8609 // For a three-way comparison, list both the candidates for the
8610 // original operator and the candidates for the synthesized operator.
8611 if (SpaceshipCandidates) {
8612 SpaceshipCandidates->NoteCandidates(
8613 S, Args,
8614 Cands: SpaceshipCandidates->CompleteCandidates(S, OCD: OCD_AllCandidates,
8615 Args, OpLoc: FD->getLocation()));
8616 S.Diag(Loc: Subobj.Loc,
8617 DiagID: diag::note_defaulted_comparison_no_viable_function_synthesized)
8618 << (OO == OO_EqualEqual ? 0 : 1);
8619 }
8620
8621 CandidateSet.NoteCandidates(
8622 S, Args,
8623 Cands: CandidateSet.CompleteCandidates(S, OCD: OCD_AllCandidates, Args,
8624 OpLoc: FD->getLocation()));
8625 }
8626 R = Result::deleted();
8627 break;
8628 }
8629
8630 return R;
8631 }
8632};
8633
8634/// A list of statements.
8635struct StmtListResult {
8636 bool IsInvalid = false;
8637 llvm::SmallVector<Stmt*, 16> Stmts;
8638
8639 bool add(const StmtResult &S) {
8640 IsInvalid |= S.isInvalid();
8641 if (IsInvalid)
8642 return true;
8643 Stmts.push_back(Elt: S.get());
8644 return false;
8645 }
8646};
8647
8648/// A visitor over the notional body of a defaulted comparison that synthesizes
8649/// the actual body.
8650class DefaultedComparisonSynthesizer
8651 : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer,
8652 StmtListResult, StmtResult,
8653 std::pair<ExprResult, ExprResult>> {
8654 SourceLocation Loc;
8655 unsigned ArrayDepth = 0;
8656
8657public:
8658 using Base = DefaultedComparisonVisitor;
8659 using ExprPair = std::pair<ExprResult, ExprResult>;
8660
8661 friend Base;
8662
8663 DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8664 DefaultedComparisonKind DCK,
8665 SourceLocation BodyLoc)
8666 : Base(S, RD, FD, DCK), Loc(BodyLoc) {}
8667
8668 /// Build a suitable function body for this defaulted comparison operator.
8669 StmtResult build() {
8670 Sema::CompoundScopeRAII CompoundScope(S);
8671
8672 StmtListResult Stmts = visit();
8673 if (Stmts.IsInvalid)
8674 return StmtError();
8675
8676 ExprResult RetVal;
8677 switch (DCK) {
8678 case DefaultedComparisonKind::None:
8679 llvm_unreachable("not a defaulted comparison");
8680
8681 case DefaultedComparisonKind::Equal: {
8682 // C++2a [class.eq]p3:
8683 // [...] compar[e] the corresponding elements [...] until the first
8684 // index i where xi == yi yields [...] false. If no such index exists,
8685 // V is true. Otherwise, V is false.
8686 //
8687 // Join the comparisons with '&&'s and return the result. Use a right
8688 // fold (traversing the conditions right-to-left), because that
8689 // short-circuits more naturally.
8690 auto OldStmts = std::move(Stmts.Stmts);
8691 Stmts.Stmts.clear();
8692 ExprResult CmpSoFar;
8693 // Finish a particular comparison chain.
8694 auto FinishCmp = [&] {
8695 if (Expr *Prior = CmpSoFar.get()) {
8696 // Convert the last expression to 'return ...;'
8697 if (RetVal.isUnset() && Stmts.Stmts.empty())
8698 RetVal = CmpSoFar;
8699 // Convert any prior comparison to 'if (!(...)) return false;'
8700 else if (Stmts.add(S: buildIfNotCondReturnFalse(Cond: Prior)))
8701 return true;
8702 CmpSoFar = ExprResult();
8703 }
8704 return false;
8705 };
8706 for (Stmt *EAsStmt : llvm::reverse(C&: OldStmts)) {
8707 Expr *E = dyn_cast<Expr>(Val: EAsStmt);
8708 if (!E) {
8709 // Found an array comparison.
8710 if (FinishCmp() || Stmts.add(S: EAsStmt))
8711 return StmtError();
8712 continue;
8713 }
8714
8715 if (CmpSoFar.isUnset()) {
8716 CmpSoFar = E;
8717 continue;
8718 }
8719 CmpSoFar = S.CreateBuiltinBinOp(OpLoc: Loc, Opc: BO_LAnd, LHSExpr: E, RHSExpr: CmpSoFar.get());
8720 if (CmpSoFar.isInvalid())
8721 return StmtError();
8722 }
8723 if (FinishCmp())
8724 return StmtError();
8725 std::reverse(first: Stmts.Stmts.begin(), last: Stmts.Stmts.end());
8726 // If no such index exists, V is true.
8727 if (RetVal.isUnset())
8728 RetVal = S.ActOnCXXBoolLiteral(OpLoc: Loc, Kind: tok::kw_true);
8729 break;
8730 }
8731
8732 case DefaultedComparisonKind::ThreeWay: {
8733 // Per C++2a [class.spaceship]p3, as a fallback add:
8734 // return static_cast<R>(std::strong_ordering::equal);
8735 QualType StrongOrdering = S.CheckComparisonCategoryType(
8736 Kind: ComparisonCategoryType::StrongOrdering, Loc,
8737 Usage: Sema::ComparisonCategoryUsage::DefaultedOperator);
8738 if (StrongOrdering.isNull())
8739 return StmtError();
8740 VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(Ty: StrongOrdering)
8741 .getValueInfo(ValueKind: ComparisonCategoryResult::Equal)
8742 ->VD;
8743 RetVal = getDecl(VD: EqualVD);
8744 if (RetVal.isInvalid())
8745 return StmtError();
8746 RetVal = buildStaticCastToR(E: RetVal.get());
8747 break;
8748 }
8749
8750 case DefaultedComparisonKind::NotEqual:
8751 case DefaultedComparisonKind::Relational:
8752 RetVal = cast<Expr>(Val: Stmts.Stmts.pop_back_val());
8753 break;
8754 }
8755
8756 // Build the final return statement.
8757 if (RetVal.isInvalid())
8758 return StmtError();
8759 StmtResult ReturnStmt = S.BuildReturnStmt(ReturnLoc: Loc, RetValExp: RetVal.get());
8760 if (ReturnStmt.isInvalid())
8761 return StmtError();
8762 Stmts.Stmts.push_back(Elt: ReturnStmt.get());
8763
8764 return S.ActOnCompoundStmt(L: Loc, R: Loc, Elts: Stmts.Stmts, /*IsStmtExpr=*/isStmtExpr: false);
8765 }
8766
8767private:
8768 ExprResult getDecl(ValueDecl *VD) {
8769 return S.BuildDeclarationNameExpr(
8770 SS: CXXScopeSpec(), NameInfo: DeclarationNameInfo(VD->getDeclName(), Loc), D: VD);
8771 }
8772
8773 ExprResult getParam(unsigned I) {
8774 ParmVarDecl *PD = FD->getParamDecl(i: I);
8775 return getDecl(VD: PD);
8776 }
8777
8778 ExprPair getCompleteObject() {
8779 unsigned Param = 0;
8780 ExprResult LHS;
8781 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: FD);
8782 MD && MD->isImplicitObjectMemberFunction()) {
8783 // LHS is '*this'.
8784 LHS = S.ActOnCXXThis(Loc);
8785 if (!LHS.isInvalid())
8786 LHS = S.CreateBuiltinUnaryOp(OpLoc: Loc, Opc: UO_Deref, InputExpr: LHS.get());
8787 } else {
8788 LHS = getParam(I: Param++);
8789 }
8790 ExprResult RHS = getParam(I: Param++);
8791 assert(Param == FD->getNumParams());
8792 return {LHS, RHS};
8793 }
8794
8795 ExprPair getBase(CXXBaseSpecifier *Base) {
8796 ExprPair Obj = getCompleteObject();
8797 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8798 return {ExprError(), ExprError()};
8799 CXXCastPath Path = {Base};
8800 const auto CastToBase = [&](Expr *E) {
8801 QualType ToType = S.Context.getQualifiedType(
8802 T: Base->getType(), Qs: E->getType().getQualifiers());
8803 return S.ImpCastExprToType(E, Type: ToType, CK: CK_DerivedToBase, VK: VK_LValue, BasePath: &Path);
8804 };
8805 return {CastToBase(Obj.first.get()), CastToBase(Obj.second.get())};
8806 }
8807
8808 ExprPair getField(FieldDecl *Field) {
8809 ExprPair Obj = getCompleteObject();
8810 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8811 return {ExprError(), ExprError()};
8812
8813 DeclAccessPair Found = DeclAccessPair::make(D: Field, AS: Field->getAccess());
8814 DeclarationNameInfo NameInfo(Field->getDeclName(), Loc);
8815 return {S.BuildFieldReferenceExpr(BaseExpr: Obj.first.get(), /*IsArrow=*/false, OpLoc: Loc,
8816 SS: CXXScopeSpec(), Field, FoundDecl: Found, MemberNameInfo: NameInfo),
8817 S.BuildFieldReferenceExpr(BaseExpr: Obj.second.get(), /*IsArrow=*/false, OpLoc: Loc,
8818 SS: CXXScopeSpec(), Field, FoundDecl: Found, MemberNameInfo: NameInfo)};
8819 }
8820
8821 // FIXME: When expanding a subobject, register a note in the code synthesis
8822 // stack to say which subobject we're comparing.
8823
8824 StmtResult buildIfNotCondReturnFalse(ExprResult Cond) {
8825 if (Cond.isInvalid())
8826 return StmtError();
8827
8828 ExprResult NotCond = S.CreateBuiltinUnaryOp(OpLoc: Loc, Opc: UO_LNot, InputExpr: Cond.get());
8829 if (NotCond.isInvalid())
8830 return StmtError();
8831
8832 ExprResult False = S.ActOnCXXBoolLiteral(OpLoc: Loc, Kind: tok::kw_false);
8833 assert(!False.isInvalid() && "should never fail");
8834 StmtResult ReturnFalse = S.BuildReturnStmt(ReturnLoc: Loc, RetValExp: False.get());
8835 if (ReturnFalse.isInvalid())
8836 return StmtError();
8837
8838 return S.ActOnIfStmt(IfLoc: Loc, StatementKind: IfStatementKind::Ordinary, LParenLoc: Loc, InitStmt: nullptr,
8839 Cond: S.ActOnCondition(S: nullptr, Loc, SubExpr: NotCond.get(),
8840 CK: Sema::ConditionKind::Boolean),
8841 RParenLoc: Loc, ThenVal: ReturnFalse.get(), ElseLoc: SourceLocation(), ElseVal: nullptr);
8842 }
8843
8844 StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size,
8845 ExprPair Subobj) {
8846 QualType SizeType = S.Context.getSizeType();
8847 Size = Size.zextOrTrunc(width: S.Context.getTypeSize(T: SizeType));
8848
8849 // Build 'size_t i$n = 0'.
8850 IdentifierInfo *IterationVarName = nullptr;
8851 {
8852 SmallString<8> Str;
8853 llvm::raw_svector_ostream OS(Str);
8854 OS << "i" << ArrayDepth;
8855 IterationVarName = &S.Context.Idents.get(Name: OS.str());
8856 }
8857 VarDecl *IterationVar = VarDecl::Create(
8858 C&: S.Context, DC: S.CurContext, StartLoc: Loc, IdLoc: Loc, Id: IterationVarName, T: SizeType,
8859 TInfo: S.Context.getTrivialTypeSourceInfo(T: SizeType, Loc), S: SC_None);
8860 llvm::APInt Zero(S.Context.getTypeSize(T: SizeType), 0);
8861 IterationVar->setInit(
8862 IntegerLiteral::Create(C: S.Context, V: Zero, type: SizeType, l: Loc));
8863 Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc);
8864
8865 auto IterRef = [&] {
8866 ExprResult Ref = S.BuildDeclarationNameExpr(
8867 SS: CXXScopeSpec(), NameInfo: DeclarationNameInfo(IterationVarName, Loc),
8868 D: IterationVar);
8869 assert(!Ref.isInvalid() && "can't reference our own variable?");
8870 return Ref.get();
8871 };
8872
8873 // Build 'i$n != Size'.
8874 ExprResult Cond = S.CreateBuiltinBinOp(
8875 OpLoc: Loc, Opc: BO_NE, LHSExpr: IterRef(),
8876 RHSExpr: IntegerLiteral::Create(C: S.Context, V: Size, type: SizeType, l: Loc));
8877 assert(!Cond.isInvalid() && "should never fail");
8878
8879 // Build '++i$n'.
8880 ExprResult Inc = S.CreateBuiltinUnaryOp(OpLoc: Loc, Opc: UO_PreInc, InputExpr: IterRef());
8881 assert(!Inc.isInvalid() && "should never fail");
8882
8883 // Build 'a[i$n]' and 'b[i$n]'.
8884 auto Index = [&](ExprResult E) {
8885 if (E.isInvalid())
8886 return ExprError();
8887 return S.CreateBuiltinArraySubscriptExpr(Base: E.get(), LLoc: Loc, Idx: IterRef(), RLoc: Loc);
8888 };
8889 Subobj.first = Index(Subobj.first);
8890 Subobj.second = Index(Subobj.second);
8891
8892 // Compare the array elements.
8893 ++ArrayDepth;
8894 StmtResult Substmt = visitSubobject(Type, Subobj);
8895 --ArrayDepth;
8896
8897 if (Substmt.isInvalid())
8898 return StmtError();
8899
8900 // For the inner level of an 'operator==', build 'if (!cmp) return false;'.
8901 // For outer levels or for an 'operator<=>' we already have a suitable
8902 // statement that returns as necessary.
8903 if (Expr *ElemCmp = dyn_cast<Expr>(Val: Substmt.get())) {
8904 assert(DCK == DefaultedComparisonKind::Equal &&
8905 "should have non-expression statement");
8906 Substmt = buildIfNotCondReturnFalse(Cond: ElemCmp);
8907 if (Substmt.isInvalid())
8908 return StmtError();
8909 }
8910
8911 // Build 'for (...) ...'
8912 return S.ActOnForStmt(ForLoc: Loc, LParenLoc: Loc, First: Init,
8913 Second: S.ActOnCondition(S: nullptr, Loc, SubExpr: Cond.get(),
8914 CK: Sema::ConditionKind::Boolean),
8915 Third: S.MakeFullDiscardedValueExpr(Arg: Inc.get()), RParenLoc: Loc,
8916 Body: Substmt.get());
8917 }
8918
8919 StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) {
8920 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8921 return StmtError();
8922
8923 OverloadedOperatorKind OO = FD->getOverloadedOperator();
8924 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(OO);
8925 ExprResult Op;
8926 if (Type->isOverloadableType())
8927 Op = S.CreateOverloadedBinOp(OpLoc: Loc, Opc, Fns, LHS: Obj.first.get(),
8928 RHS: Obj.second.get(), /*PerformADL=*/RequiresADL: true,
8929 /*AllowRewrittenCandidates=*/true, DefaultedFn: FD);
8930 else
8931 Op = S.CreateBuiltinBinOp(OpLoc: Loc, Opc, LHSExpr: Obj.first.get(), RHSExpr: Obj.second.get());
8932 if (Op.isInvalid())
8933 return StmtError();
8934
8935 switch (DCK) {
8936 case DefaultedComparisonKind::None:
8937 llvm_unreachable("not a defaulted comparison");
8938
8939 case DefaultedComparisonKind::Equal:
8940 // Per C++2a [class.eq]p2, each comparison is individually contextually
8941 // converted to bool.
8942 Op = S.PerformContextuallyConvertToBool(From: Op.get());
8943 if (Op.isInvalid())
8944 return StmtError();
8945 return Op.get();
8946
8947 case DefaultedComparisonKind::ThreeWay: {
8948 // Per C++2a [class.spaceship]p3, form:
8949 // if (R cmp = static_cast<R>(op); cmp != 0)
8950 // return cmp;
8951 QualType R = FD->getReturnType();
8952 Op = buildStaticCastToR(E: Op.get());
8953 if (Op.isInvalid())
8954 return StmtError();
8955
8956 // R cmp = ...;
8957 IdentifierInfo *Name = &S.Context.Idents.get(Name: "cmp");
8958 VarDecl *VD =
8959 VarDecl::Create(C&: S.Context, DC: S.CurContext, StartLoc: Loc, IdLoc: Loc, Id: Name, T: R,
8960 TInfo: S.Context.getTrivialTypeSourceInfo(T: R, Loc), S: SC_None);
8961 S.AddInitializerToDecl(dcl: VD, init: Op.get(), /*DirectInit=*/false);
8962 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc);
8963
8964 // cmp != 0
8965 ExprResult VDRef = getDecl(VD);
8966 if (VDRef.isInvalid())
8967 return StmtError();
8968 llvm::APInt ZeroVal(S.Context.getIntWidth(T: S.Context.IntTy), 0);
8969 Expr *Zero =
8970 IntegerLiteral::Create(C: S.Context, V: ZeroVal, type: S.Context.IntTy, l: Loc);
8971 ExprResult Comp;
8972 if (VDRef.get()->getType()->isOverloadableType())
8973 Comp = S.CreateOverloadedBinOp(OpLoc: Loc, Opc: BO_NE, Fns, LHS: VDRef.get(), RHS: Zero, RequiresADL: true,
8974 AllowRewrittenCandidates: true, DefaultedFn: FD);
8975 else
8976 Comp = S.CreateBuiltinBinOp(OpLoc: Loc, Opc: BO_NE, LHSExpr: VDRef.get(), RHSExpr: Zero);
8977 if (Comp.isInvalid())
8978 return StmtError();
8979 Sema::ConditionResult Cond = S.ActOnCondition(
8980 S: nullptr, Loc, SubExpr: Comp.get(), CK: Sema::ConditionKind::Boolean);
8981 if (Cond.isInvalid())
8982 return StmtError();
8983
8984 // return cmp;
8985 VDRef = getDecl(VD);
8986 if (VDRef.isInvalid())
8987 return StmtError();
8988 StmtResult ReturnStmt = S.BuildReturnStmt(ReturnLoc: Loc, RetValExp: VDRef.get());
8989 if (ReturnStmt.isInvalid())
8990 return StmtError();
8991
8992 // if (...)
8993 return S.ActOnIfStmt(IfLoc: Loc, StatementKind: IfStatementKind::Ordinary, LParenLoc: Loc, InitStmt, Cond,
8994 RParenLoc: Loc, ThenVal: ReturnStmt.get(),
8995 /*ElseLoc=*/SourceLocation(), /*Else=*/ElseVal: nullptr);
8996 }
8997
8998 case DefaultedComparisonKind::NotEqual:
8999 case DefaultedComparisonKind::Relational:
9000 // C++2a [class.compare.secondary]p2:
9001 // Otherwise, the operator function yields x @ y.
9002 return Op.get();
9003 }
9004 llvm_unreachable("");
9005 }
9006
9007 /// Build "static_cast<R>(E)".
9008 ExprResult buildStaticCastToR(Expr *E) {
9009 QualType R = FD->getReturnType();
9010 assert(!R->isUndeducedType() && "type should have been deduced already");
9011
9012 // Don't bother forming a no-op cast in the common case.
9013 if (E->isPRValue() && S.Context.hasSameType(T1: E->getType(), T2: R))
9014 return E;
9015 return S.BuildCXXNamedCast(OpLoc: Loc, Kind: tok::kw_static_cast,
9016 Ty: S.Context.getTrivialTypeSourceInfo(T: R, Loc), E,
9017 AngleBrackets: SourceRange(Loc, Loc), Parens: SourceRange(Loc, Loc));
9018 }
9019};
9020}
9021
9022/// Perform the unqualified lookups that might be needed to form a defaulted
9023/// comparison function for the given operator.
9024static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S,
9025 UnresolvedSetImpl &Operators,
9026 OverloadedOperatorKind Op) {
9027 auto Lookup = [&](OverloadedOperatorKind OO) {
9028 Self.LookupOverloadedOperatorName(Op: OO, S, Functions&: Operators);
9029 };
9030
9031 // Every defaulted operator looks up itself.
9032 Lookup(Op);
9033 // ... and the rewritten form of itself, if any.
9034 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Kind: Op))
9035 Lookup(ExtraOp);
9036
9037 // For 'operator<=>', we also form a 'cmp != 0' expression, and might
9038 // synthesize a three-way comparison from '<' and '=='. In a dependent
9039 // context, we also need to look up '==' in case we implicitly declare a
9040 // defaulted 'operator=='.
9041 if (Op == OO_Spaceship) {
9042 Lookup(OO_ExclaimEqual);
9043 Lookup(OO_Less);
9044 Lookup(OO_EqualEqual);
9045 }
9046}
9047
9048bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *FD,
9049 DefaultedComparisonKind DCK) {
9050 assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison");
9051
9052 // Perform any unqualified lookups we're going to need to default this
9053 // function.
9054 if (S) {
9055 UnresolvedSet<32> Operators;
9056 lookupOperatorsForDefaultedComparison(Self&: *this, S, Operators,
9057 Op: FD->getOverloadedOperator());
9058 FD->setDefaultedOrDeletedInfo(
9059 FunctionDecl::DefaultedOrDeletedFunctionInfo::Create(
9060 Context, Lookups: Operators.pairs(), FPFeatures: CurFPFeatureOverrides()));
9061 }
9062
9063 // C++2a [class.compare.default]p1:
9064 // A defaulted comparison operator function for some class C shall be a
9065 // non-template function declared in the member-specification of C that is
9066 // -- a non-static const non-volatile member of C having one parameter of
9067 // type const C& and either no ref-qualifier or the ref-qualifier &, or
9068 // -- a friend of C having two parameters of type const C& or two
9069 // parameters of type C.
9070
9071 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: FD->getLexicalDeclContext());
9072 bool IsMethod = isa<CXXMethodDecl>(Val: FD);
9073 if (IsMethod) {
9074 auto *MD = cast<CXXMethodDecl>(Val: FD);
9075 assert(!MD->isStatic() && "comparison function cannot be a static member");
9076
9077 if (MD->getRefQualifier() == RQ_RValue) {
9078 Diag(Loc: MD->getLocation(), DiagID: diag::err_ref_qualifier_comparison_operator);
9079
9080 // Remove the ref qualifier to recover.
9081 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
9082 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9083 EPI.RefQualifier = RQ_None;
9084 MD->setType(Context.getFunctionType(ResultTy: FPT->getReturnType(),
9085 Args: FPT->getParamTypes(), EPI));
9086 }
9087
9088 // If we're out-of-class, this is the class we're comparing.
9089 if (!RD)
9090 RD = MD->getParent();
9091 QualType T = MD->getFunctionObjectParameterReferenceType();
9092 if (!T.getNonReferenceType().isConstQualified() &&
9093 (MD->isImplicitObjectMemberFunction() || T->isLValueReferenceType())) {
9094 SourceLocation Loc, InsertLoc;
9095 if (MD->isExplicitObjectMemberFunction()) {
9096 Loc = MD->getParamDecl(i: 0)->getBeginLoc();
9097 InsertLoc = getLocForEndOfToken(
9098 Loc: MD->getParamDecl(i: 0)->getExplicitObjectParamThisLoc());
9099 } else {
9100 Loc = MD->getLocation();
9101 if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc())
9102 InsertLoc = getLocForEndOfToken(Loc: Loc.getRParenLoc());
9103 }
9104 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
9105 // corresponding defaulted 'operator<=>' already.
9106 if (!MD->isImplicit()) {
9107 Diag(Loc, DiagID: diag::err_defaulted_comparison_non_const)
9108 << (int)DCK << FixItHint::CreateInsertion(InsertionLoc: InsertLoc, Code: " const");
9109 }
9110
9111 // Add the 'const' to the type to recover.
9112 if (MD->isExplicitObjectMemberFunction()) {
9113 assert(T->isLValueReferenceType());
9114 MD->getParamDecl(i: 0)->setType(Context.getLValueReferenceType(
9115 T: T.getNonReferenceType().withConst()));
9116 } else {
9117 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
9118 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9119 EPI.TypeQuals.addConst();
9120 MD->setType(Context.getFunctionType(ResultTy: FPT->getReturnType(),
9121 Args: FPT->getParamTypes(), EPI));
9122 }
9123 }
9124
9125 if (MD->isVolatile()) {
9126 Diag(Loc: MD->getLocation(), DiagID: diag::err_volatile_comparison_operator);
9127
9128 // Remove the 'volatile' from the type to recover.
9129 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
9130 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9131 EPI.TypeQuals.removeVolatile();
9132 MD->setType(Context.getFunctionType(ResultTy: FPT->getReturnType(),
9133 Args: FPT->getParamTypes(), EPI));
9134 }
9135 }
9136
9137 if ((FD->getNumParams() -
9138 (unsigned)FD->hasCXXExplicitFunctionObjectParameter()) !=
9139 (IsMethod ? 1 : 2)) {
9140 // Let's not worry about using a variadic template pack here -- who would do
9141 // such a thing?
9142 Diag(Loc: FD->getLocation(), DiagID: diag::err_defaulted_comparison_num_args)
9143 << int(IsMethod) << int(DCK);
9144 return true;
9145 }
9146
9147 const ParmVarDecl *KnownParm = nullptr;
9148 for (const ParmVarDecl *Param : FD->parameters()) {
9149 QualType ParmTy = Param->getType();
9150 if (!KnownParm) {
9151 auto CTy = ParmTy;
9152 // Is it `T const &`?
9153 bool Ok = !IsMethod || FD->hasCXXExplicitFunctionObjectParameter();
9154 QualType ExpectedTy;
9155 if (RD)
9156 ExpectedTy = Context.getCanonicalTagType(TD: RD);
9157 if (auto *Ref = CTy->getAs<LValueReferenceType>()) {
9158 CTy = Ref->getPointeeType();
9159 if (RD)
9160 ExpectedTy.addConst();
9161 Ok = true;
9162 }
9163
9164 // Is T a class?
9165 if (RD) {
9166 Ok &= RD->isDependentType() || Context.hasSameType(T1: CTy, T2: ExpectedTy);
9167 } else {
9168 RD = CTy->getAsCXXRecordDecl();
9169 Ok &= RD != nullptr;
9170 }
9171
9172 if (Ok) {
9173 KnownParm = Param;
9174 } else {
9175 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
9176 // corresponding defaulted 'operator<=>' already.
9177 if (!FD->isImplicit()) {
9178 if (RD) {
9179 CanQualType PlainTy = Context.getCanonicalTagType(TD: RD);
9180 QualType RefTy =
9181 Context.getLValueReferenceType(T: PlainTy.withConst());
9182 Diag(Loc: FD->getLocation(), DiagID: diag::err_defaulted_comparison_param)
9183 << int(DCK) << ParmTy << RefTy << int(!IsMethod) << PlainTy
9184 << Param->getSourceRange();
9185 } else {
9186 assert(!IsMethod && "should know expected type for method");
9187 Diag(Loc: FD->getLocation(),
9188 DiagID: diag::err_defaulted_comparison_param_unknown)
9189 << int(DCK) << ParmTy << Param->getSourceRange();
9190 }
9191 }
9192 return true;
9193 }
9194 } else if (!Context.hasSameType(T1: KnownParm->getType(), T2: ParmTy)) {
9195 Diag(Loc: FD->getLocation(), DiagID: diag::err_defaulted_comparison_param_mismatch)
9196 << int(DCK) << KnownParm->getType() << KnownParm->getSourceRange()
9197 << ParmTy << Param->getSourceRange();
9198 return true;
9199 }
9200 }
9201
9202 assert(RD && "must have determined class");
9203 if (IsMethod) {
9204 } else if (isa<CXXRecordDecl>(Val: FD->getLexicalDeclContext())) {
9205 // In-class, must be a friend decl.
9206 assert(FD->getFriendObjectKind() && "expected a friend declaration");
9207 } else {
9208 // Out of class, require the defaulted comparison to be a friend (of a
9209 // complete type, per CWG2547).
9210 if (RequireCompleteType(Loc: FD->getLocation(), T: Context.getCanonicalTagType(TD: RD),
9211 DiagID: diag::err_defaulted_comparison_not_friend, Args: int(DCK),
9212 Args: int(1)))
9213 return true;
9214
9215 if (llvm::none_of(Range: RD->friends(), P: [&](const FriendDecl *F) {
9216 return declaresSameEntity(D1: F->getFriendDecl(), D2: FD);
9217 })) {
9218 Diag(Loc: FD->getLocation(), DiagID: diag::err_defaulted_comparison_not_friend)
9219 << int(DCK) << int(0) << RD;
9220 Diag(Loc: RD->getCanonicalDecl()->getLocation(), DiagID: diag::note_declared_at);
9221 return true;
9222 }
9223 }
9224
9225 // C++2a [class.eq]p1, [class.rel]p1:
9226 // A [defaulted comparison other than <=>] shall have a declared return
9227 // type bool.
9228 if (DCK != DefaultedComparisonKind::ThreeWay &&
9229 !FD->getDeclaredReturnType()->isDependentType() &&
9230 !Context.hasSameType(T1: FD->getDeclaredReturnType(), T2: Context.BoolTy)) {
9231 Diag(Loc: FD->getLocation(), DiagID: diag::err_defaulted_comparison_return_type_not_bool)
9232 << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy
9233 << FD->getReturnTypeSourceRange();
9234 return true;
9235 }
9236 // C++2a [class.spaceship]p2 [P2002R0]:
9237 // Let R be the declared return type [...]. If R is auto, [...]. Otherwise,
9238 // R shall not contain a placeholder type.
9239 if (QualType RT = FD->getDeclaredReturnType();
9240 DCK == DefaultedComparisonKind::ThreeWay &&
9241 RT->getContainedDeducedType() &&
9242 (!Context.hasSameType(T1: RT, T2: Context.getAutoDeductType()) ||
9243 RT->getContainedAutoType()->isConstrained())) {
9244 Diag(Loc: FD->getLocation(),
9245 DiagID: diag::err_defaulted_comparison_deduced_return_type_not_auto)
9246 << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy
9247 << FD->getReturnTypeSourceRange();
9248 return true;
9249 }
9250
9251 // For a defaulted function in a dependent class, defer all remaining checks
9252 // until instantiation.
9253 if (RD->isDependentType())
9254 return false;
9255
9256 // Determine whether the function should be defined as deleted.
9257 DefaultedComparisonInfo Info =
9258 DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit();
9259
9260 bool First = FD == FD->getCanonicalDecl();
9261
9262 if (!First) {
9263 if (Info.Deleted) {
9264 // C++11 [dcl.fct.def.default]p4:
9265 // [For a] user-provided explicitly-defaulted function [...] if such a
9266 // function is implicitly defined as deleted, the program is ill-formed.
9267 //
9268 // This is really just a consequence of the general rule that you can
9269 // only delete a function on its first declaration.
9270 Diag(Loc: FD->getLocation(), DiagID: diag::err_non_first_default_compare_deletes)
9271 << FD->isImplicit() << (int)DCK;
9272 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9273 DefaultedComparisonAnalyzer::ExplainDeleted)
9274 .visit();
9275 return true;
9276 }
9277 if (isa<CXXRecordDecl>(Val: FD->getLexicalDeclContext())) {
9278 // C++20 [class.compare.default]p1:
9279 // [...] A definition of a comparison operator as defaulted that appears
9280 // in a class shall be the first declaration of that function.
9281 Diag(Loc: FD->getLocation(), DiagID: diag::err_non_first_default_compare_in_class)
9282 << (int)DCK;
9283 Diag(Loc: FD->getCanonicalDecl()->getLocation(),
9284 DiagID: diag::note_previous_declaration);
9285 return true;
9286 }
9287 }
9288
9289 // If we want to delete the function, then do so; there's nothing else to
9290 // check in that case.
9291 if (Info.Deleted) {
9292 SetDeclDeleted(dcl: FD, DelLoc: FD->getLocation());
9293 if (!inTemplateInstantiation() && !FD->isImplicit()) {
9294 Diag(Loc: FD->getLocation(), DiagID: diag::warn_defaulted_comparison_deleted)
9295 << (int)DCK;
9296 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9297 DefaultedComparisonAnalyzer::ExplainDeleted)
9298 .visit();
9299 if (FD->getDefaultLoc().isValid())
9300 Diag(Loc: FD->getDefaultLoc(), DiagID: diag::note_replace_equals_default_to_delete)
9301 << FixItHint::CreateReplacement(RemoveRange: FD->getDefaultLoc(), Code: "delete");
9302 }
9303 return false;
9304 }
9305
9306 // C++2a [class.spaceship]p2:
9307 // The return type is deduced as the common comparison type of R0, R1, ...
9308 if (DCK == DefaultedComparisonKind::ThreeWay &&
9309 FD->getDeclaredReturnType()->isUndeducedAutoType()) {
9310 SourceLocation RetLoc = FD->getReturnTypeSourceRange().getBegin();
9311 if (RetLoc.isInvalid())
9312 RetLoc = FD->getBeginLoc();
9313 // FIXME: Should we really care whether we have the complete type and the
9314 // 'enumerator' constants here? A forward declaration seems sufficient.
9315 QualType Cat = CheckComparisonCategoryType(
9316 Kind: Info.Category, Loc: RetLoc, Usage: ComparisonCategoryUsage::DefaultedOperator);
9317 if (Cat.isNull())
9318 return true;
9319 Context.adjustDeducedFunctionResultType(
9320 FD, ResultType: SubstAutoType(TypeWithAuto: FD->getDeclaredReturnType(), Replacement: Cat));
9321 }
9322
9323 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
9324 // An explicitly-defaulted function that is not defined as deleted may be
9325 // declared constexpr or consteval only if it is constexpr-compatible.
9326 // C++2a [class.compare.default]p3 [P2002R0]:
9327 // A defaulted comparison function is constexpr-compatible if it satisfies
9328 // the requirements for a constexpr function [...]
9329 // The only relevant requirements are that the parameter and return types are
9330 // literal types. The remaining conditions are checked by the analyzer.
9331 //
9332 // We support P2448R2 in language modes earlier than C++23 as an extension.
9333 // The concept of constexpr-compatible was removed.
9334 // C++23 [dcl.fct.def.default]p3 [P2448R2]
9335 // A function explicitly defaulted on its first declaration is implicitly
9336 // inline, and is implicitly constexpr if it is constexpr-suitable.
9337 // C++23 [dcl.constexpr]p3
9338 // A function is constexpr-suitable if
9339 // - it is not a coroutine, and
9340 // - if the function is a constructor or destructor, its class does not
9341 // have any virtual base classes.
9342 if (FD->isConstexpr()) {
9343 if (!getLangOpts().CPlusPlus23 &&
9344 CheckConstexprReturnType(SemaRef&: *this, FD, Kind: CheckConstexprKind::Diagnose) &&
9345 CheckConstexprParameterTypes(SemaRef&: *this, FD, Kind: CheckConstexprKind::Diagnose) &&
9346 !Info.Constexpr) {
9347 Diag(Loc: FD->getBeginLoc(), DiagID: diag::err_defaulted_comparison_constexpr_mismatch)
9348 << FD->isImplicit() << (int)DCK << FD->isConsteval();
9349 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9350 DefaultedComparisonAnalyzer::ExplainConstexpr)
9351 .visit();
9352 }
9353 }
9354
9355 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
9356 // If a constexpr-compatible function is explicitly defaulted on its first
9357 // declaration, it is implicitly considered to be constexpr.
9358 // FIXME: Only applying this to the first declaration seems problematic, as
9359 // simple reorderings can affect the meaning of the program.
9360 if (First && !FD->isConstexpr() && Info.Constexpr)
9361 FD->setConstexprKind(ConstexprSpecKind::Constexpr);
9362
9363 // C++2a [except.spec]p3:
9364 // If a declaration of a function does not have a noexcept-specifier
9365 // [and] is defaulted on its first declaration, [...] the exception
9366 // specification is as specified below
9367 if (FD->getExceptionSpecType() == EST_None) {
9368 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9369 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9370 EPI.ExceptionSpec.Type = EST_Unevaluated;
9371 EPI.ExceptionSpec.SourceDecl = FD;
9372 FD->setType(Context.getFunctionType(ResultTy: FPT->getReturnType(),
9373 Args: FPT->getParamTypes(), EPI));
9374 }
9375
9376 return false;
9377}
9378
9379void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
9380 FunctionDecl *Spaceship) {
9381 Sema::CodeSynthesisContext Ctx;
9382 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison;
9383 Ctx.PointOfInstantiation = Spaceship->getEndLoc();
9384 Ctx.Entity = Spaceship;
9385 pushCodeSynthesisContext(Ctx);
9386
9387 if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship))
9388 EqualEqual->setImplicit();
9389
9390 popCodeSynthesisContext();
9391}
9392
9393void Sema::DefineDefaultedComparison(SourceLocation UseLoc, FunctionDecl *FD,
9394 DefaultedComparisonKind DCK) {
9395 assert(FD->isDefaulted() && !FD->isDeleted() &&
9396 !FD->doesThisDeclarationHaveABody());
9397 if (FD->willHaveBody() || FD->isInvalidDecl())
9398 return;
9399
9400 SynthesizedFunctionScope Scope(*this, FD);
9401
9402 // Add a context note for diagnostics produced after this point.
9403 Scope.addContextNote(UseLoc);
9404
9405 DefaultedFunctionFPFeaturesRAII RestoreFP(*this, FD);
9406
9407 {
9408 // Build and set up the function body.
9409 // The first parameter has type maybe-ref-to maybe-const T, use that to get
9410 // the type of the class being compared.
9411 auto PT = FD->getParamDecl(i: 0)->getType();
9412 CXXRecordDecl *RD = PT.getNonReferenceType()->getAsCXXRecordDecl();
9413 SourceLocation BodyLoc =
9414 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
9415 StmtResult Body =
9416 DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build();
9417 if (Body.isInvalid()) {
9418 FD->setInvalidDecl();
9419 return;
9420 }
9421 FD->setBody(Body.get());
9422 FD->markUsed(C&: Context);
9423 }
9424
9425 // The exception specification is needed because we are defining the
9426 // function. Note that this will reuse the body we just built.
9427 ResolveExceptionSpec(Loc: UseLoc, FPT: FD->getType()->castAs<FunctionProtoType>());
9428
9429 if (ASTMutationListener *L = getASTMutationListener())
9430 L->CompletedImplicitDefinition(D: FD);
9431}
9432
9433static Sema::ImplicitExceptionSpecification
9434ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
9435 FunctionDecl *FD,
9436 DefaultedComparisonKind DCK) {
9437 ComputingExceptionSpec CES(S, FD, Loc);
9438 Sema::ImplicitExceptionSpecification ExceptSpec(S);
9439
9440 if (FD->isInvalidDecl())
9441 return ExceptSpec;
9442
9443 // The common case is that we just defined the comparison function. In that
9444 // case, just look at whether the body can throw.
9445 if (Stmt *FunctionBody = FD->getBody()) {
9446 ExceptSpec.CalledStmt(S: FunctionBody);
9447 } else {
9448 // Otherwise, build a body so we can check it. This should ideally only
9449 // happen when we're not actually marking the function referenced. (This is
9450 // only really important for efficiency: we don't want to build and throw
9451 // away bodies for comparison functions more than we strictly need to.)
9452
9453 // Pretend to synthesize the function body in an unevaluated context.
9454 // Note that we can't actually just go ahead and define the function here:
9455 // we are not permitted to mark its callees as referenced.
9456 Sema::SynthesizedFunctionScope Scope(S, FD);
9457 EnterExpressionEvaluationContext Context(
9458 S, Sema::ExpressionEvaluationContext::Unevaluated);
9459
9460 CXXRecordDecl *RD =
9461 cast<CXXRecordDecl>(Val: FD->getFriendObjectKind() == Decl::FOK_None
9462 ? FD->getDeclContext()
9463 : FD->getLexicalDeclContext());
9464 SourceLocation BodyLoc =
9465 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
9466 StmtResult Body =
9467 DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build();
9468 if (!Body.isInvalid())
9469 ExceptSpec.CalledStmt(S: Body.get());
9470
9471 // FIXME: Can we hold onto this body and just transform it to potentially
9472 // evaluated when we're asked to define the function rather than rebuilding
9473 // it? Either that, or we should only build the bits of the body that we
9474 // need (the expressions, not the statements).
9475 }
9476
9477 return ExceptSpec;
9478}
9479
9480void Sema::CheckDelayedMemberExceptionSpecs() {
9481 decltype(DelayedOverridingExceptionSpecChecks) Overriding;
9482 decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
9483
9484 std::swap(LHS&: Overriding, RHS&: DelayedOverridingExceptionSpecChecks);
9485 std::swap(LHS&: Equivalent, RHS&: DelayedEquivalentExceptionSpecChecks);
9486
9487 // Perform any deferred checking of exception specifications for virtual
9488 // destructors.
9489 for (auto &Check : Overriding)
9490 CheckOverridingFunctionExceptionSpec(New: Check.first, Old: Check.second);
9491
9492 // Perform any deferred checking of exception specifications for befriended
9493 // special members.
9494 for (auto &Check : Equivalent)
9495 CheckEquivalentExceptionSpec(Old: Check.second, New: Check.first);
9496}
9497
9498namespace {
9499/// CRTP base class for visiting operations performed by a special member
9500/// function (or inherited constructor).
9501template<typename Derived>
9502struct SpecialMemberVisitor {
9503 Sema &S;
9504 CXXMethodDecl *MD;
9505 CXXSpecialMemberKind CSM;
9506 Sema::InheritedConstructorInfo *ICI;
9507
9508 // Properties of the special member, computed for convenience.
9509 bool IsConstructor = false, IsAssignment = false, ConstArg = false;
9510
9511 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, CXXSpecialMemberKind CSM,
9512 Sema::InheritedConstructorInfo *ICI)
9513 : S(S), MD(MD), CSM(CSM), ICI(ICI) {
9514 switch (CSM) {
9515 case CXXSpecialMemberKind::DefaultConstructor:
9516 case CXXSpecialMemberKind::CopyConstructor:
9517 case CXXSpecialMemberKind::MoveConstructor:
9518 IsConstructor = true;
9519 break;
9520 case CXXSpecialMemberKind::CopyAssignment:
9521 case CXXSpecialMemberKind::MoveAssignment:
9522 IsAssignment = true;
9523 break;
9524 case CXXSpecialMemberKind::Destructor:
9525 break;
9526 case CXXSpecialMemberKind::Invalid:
9527 llvm_unreachable("invalid special member kind");
9528 }
9529
9530 if (MD->getNumExplicitParams()) {
9531 if (const ReferenceType *RT =
9532 MD->getNonObjectParameter(I: 0)->getType()->getAs<ReferenceType>())
9533 ConstArg = RT->getPointeeType().isConstQualified();
9534 }
9535 }
9536
9537 Derived &getDerived() { return static_cast<Derived&>(*this); }
9538
9539 /// Is this a "move" special member?
9540 bool isMove() const {
9541 return CSM == CXXSpecialMemberKind::MoveConstructor ||
9542 CSM == CXXSpecialMemberKind::MoveAssignment;
9543 }
9544
9545 /// Look up the corresponding special member in the given class.
9546 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
9547 unsigned Quals, bool IsMutable) {
9548 return lookupCallFromSpecialMember(S, Class, CSM, FieldQuals: Quals,
9549 ConstRHS: ConstArg && !IsMutable);
9550 }
9551
9552 /// Look up the constructor for the specified base class to see if it's
9553 /// overridden due to this being an inherited constructor.
9554 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
9555 if (!ICI)
9556 return {};
9557 assert(CSM == CXXSpecialMemberKind::DefaultConstructor);
9558 auto *BaseCtor =
9559 cast<CXXConstructorDecl>(Val: MD)->getInheritedConstructor().getConstructor();
9560 if (auto *MD = ICI->findConstructorForBase(Base: Class, Ctor: BaseCtor).first)
9561 return MD;
9562 return {};
9563 }
9564
9565 /// A base or member subobject.
9566 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
9567
9568 /// Get the location to use for a subobject in diagnostics.
9569 static SourceLocation getSubobjectLoc(Subobject Subobj) {
9570 // FIXME: For an indirect virtual base, the direct base leading to
9571 // the indirect virtual base would be a more useful choice.
9572 if (auto *B = dyn_cast<CXXBaseSpecifier *>(Val&: Subobj))
9573 return B->getBaseTypeLoc();
9574 else
9575 return cast<FieldDecl *>(Val&: Subobj)->getLocation();
9576 }
9577
9578 enum BasesToVisit {
9579 /// Visit all non-virtual (direct) bases.
9580 VisitNonVirtualBases,
9581 /// Visit all direct bases, virtual or not.
9582 VisitDirectBases,
9583 /// Visit all non-virtual bases, and all virtual bases if the class
9584 /// is not abstract.
9585 VisitPotentiallyConstructedBases,
9586 /// Visit all direct or virtual bases.
9587 VisitAllBases
9588 };
9589
9590 // Visit the bases and members of the class.
9591 bool visit(BasesToVisit Bases) {
9592 CXXRecordDecl *RD = MD->getParent();
9593
9594 if (Bases == VisitPotentiallyConstructedBases)
9595 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
9596
9597 for (auto &B : RD->bases())
9598 if ((Bases == VisitDirectBases || !B.isVirtual()) &&
9599 getDerived().visitBase(&B))
9600 return true;
9601
9602 if (Bases == VisitAllBases)
9603 for (auto &B : RD->vbases())
9604 if (getDerived().visitBase(&B))
9605 return true;
9606
9607 for (auto *F : RD->fields())
9608 if (!F->isInvalidDecl() && !F->isUnnamedBitField() &&
9609 getDerived().visitField(F))
9610 return true;
9611
9612 return false;
9613 }
9614};
9615}
9616
9617namespace {
9618struct SpecialMemberDeletionInfo
9619 : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
9620 bool Diagnose;
9621
9622 SourceLocation Loc;
9623
9624 bool AllFieldsAreConst;
9625
9626 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
9627 CXXSpecialMemberKind CSM,
9628 Sema::InheritedConstructorInfo *ICI, bool Diagnose)
9629 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
9630 Loc(MD->getLocation()), AllFieldsAreConst(true) {}
9631
9632 bool inUnion() const { return MD->getParent()->isUnion(); }
9633
9634 CXXSpecialMemberKind getEffectiveCSM() {
9635 return ICI ? CXXSpecialMemberKind::Invalid : CSM;
9636 }
9637
9638 bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
9639
9640 bool shouldDeleteForVariantPtrAuthMember(const FieldDecl *FD);
9641
9642 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
9643 bool visitField(FieldDecl *Field) { return shouldDeleteForField(FD: Field); }
9644
9645 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
9646 bool shouldDeleteForField(FieldDecl *FD);
9647 bool shouldDeleteForAllConstMembers();
9648
9649 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
9650 unsigned Quals);
9651 bool shouldDeleteForSubobjectCall(Subobject Subobj,
9652 Sema::SpecialMemberOverloadResult SMOR,
9653 bool IsDtorCallInCtor);
9654
9655 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
9656};
9657}
9658
9659/// Is the given special member inaccessible when used on the given
9660/// sub-object.
9661bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
9662 CXXMethodDecl *target) {
9663 /// If we're operating on a base class, the object type is the
9664 /// type of this special member.
9665 CanQualType objectTy;
9666 AccessSpecifier access = target->getAccess();
9667 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
9668 objectTy = S.Context.getCanonicalTagType(TD: MD->getParent());
9669 access = CXXRecordDecl::MergeAccess(PathAccess: base->getAccessSpecifier(), DeclAccess: access);
9670
9671 // If we're operating on a field, the object type is the type of the field.
9672 } else {
9673 objectTy = S.Context.getCanonicalTagType(TD: target->getParent());
9674 }
9675
9676 return S.isMemberAccessibleForDeletion(
9677 NamingClass: target->getParent(), Found: DeclAccessPair::make(D: target, AS: access), ObjectType: objectTy);
9678}
9679
9680/// Check whether we should delete a special member due to the implicit
9681/// definition containing a call to a special member of a subobject.
9682bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
9683 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
9684 bool IsDtorCallInCtor) {
9685 CXXMethodDecl *Decl = SMOR.getMethod();
9686 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9687
9688 enum {
9689 NotSet = -1,
9690 NoDecl,
9691 DeletedDecl,
9692 MultipleDecl,
9693 InaccessibleDecl,
9694 NonTrivialDecl
9695 } DiagKind = NotSet;
9696
9697 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) {
9698 if (CSM == CXXSpecialMemberKind::DefaultConstructor && Field &&
9699 Field->getParent()->isUnion()) {
9700 // [class.default.ctor]p2:
9701 // A defaulted default constructor for class X is defined as deleted if
9702 // - X is a union that has a variant member with a non-trivial default
9703 // constructor and no variant member of X has a default member
9704 // initializer
9705 const auto *RD = cast<CXXRecordDecl>(Val: Field->getParent());
9706 if (RD->hasInClassInitializer())
9707 return false;
9708 }
9709 DiagKind = !Decl ? NoDecl : DeletedDecl;
9710 } else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
9711 DiagKind = MultipleDecl;
9712 else if (!isAccessible(Subobj, target: Decl))
9713 DiagKind = InaccessibleDecl;
9714 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
9715 !Decl->isTrivial()) {
9716 // A member of a union must have a trivial corresponding special member.
9717 // As a weird special case, a destructor call from a union's constructor
9718 // must be accessible and non-deleted, but need not be trivial. Such a
9719 // destructor is never actually called, but is semantically checked as
9720 // if it were.
9721 if (CSM == CXXSpecialMemberKind::DefaultConstructor) {
9722 // [class.default.ctor]p2:
9723 // A defaulted default constructor for class X is defined as deleted if
9724 // - X is a union that has a variant member with a non-trivial default
9725 // constructor and no variant member of X has a default member
9726 // initializer
9727 const auto *RD = cast<CXXRecordDecl>(Val: Field->getParent());
9728 if (!RD->hasInClassInitializer())
9729 DiagKind = NonTrivialDecl;
9730 } else {
9731 DiagKind = NonTrivialDecl;
9732 }
9733 }
9734
9735 if (DiagKind == NotSet)
9736 return false;
9737
9738 if (Diagnose) {
9739 if (Field) {
9740 S.Diag(Loc: Field->getLocation(),
9741 DiagID: diag::note_deleted_special_member_class_subobject)
9742 << getEffectiveCSM() << MD->getParent() << /*IsField*/ true << Field
9743 << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/ false;
9744 } else {
9745 CXXBaseSpecifier *Base = cast<CXXBaseSpecifier *>(Val&: Subobj);
9746 S.Diag(Loc: Base->getBeginLoc(),
9747 DiagID: diag::note_deleted_special_member_class_subobject)
9748 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9749 << Base->getType() << DiagKind << IsDtorCallInCtor
9750 << /*IsObjCPtr*/ false;
9751 }
9752
9753 if (DiagKind == DeletedDecl)
9754 S.NoteDeletedFunction(FD: Decl);
9755 // FIXME: Explain inaccessibility if DiagKind == InaccessibleDecl.
9756 }
9757
9758 return true;
9759}
9760
9761/// Check whether we should delete a special member function due to having a
9762/// direct or virtual base class or non-static data member of class type M.
9763bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
9764 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
9765 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9766 bool IsMutable = Field && Field->isMutable();
9767
9768 // C++11 [class.ctor]p5:
9769 // -- any direct or virtual base class, or non-static data member with no
9770 // brace-or-equal-initializer, has class type M (or array thereof) and
9771 // either M has no default constructor or overload resolution as applied
9772 // to M's default constructor results in an ambiguity or in a function
9773 // that is deleted or inaccessible
9774 // C++11 [class.copy]p11, C++11 [class.copy]p23:
9775 // -- a direct or virtual base class B that cannot be copied/moved because
9776 // overload resolution, as applied to B's corresponding special member,
9777 // results in an ambiguity or a function that is deleted or inaccessible
9778 // from the defaulted special member
9779 // C++11 [class.dtor]p5:
9780 // -- any direct or virtual base class [...] has a type with a destructor
9781 // that is deleted or inaccessible
9782 if (!(CSM == CXXSpecialMemberKind::DefaultConstructor && Field &&
9783 Field->hasInClassInitializer()) &&
9784 shouldDeleteForSubobjectCall(Subobj, SMOR: lookupIn(Class, Quals, IsMutable),
9785 IsDtorCallInCtor: false))
9786 return true;
9787
9788 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
9789 // -- any direct or virtual base class or non-static data member has a
9790 // type with a destructor that is deleted or inaccessible
9791 if (IsConstructor) {
9792 Sema::SpecialMemberOverloadResult SMOR =
9793 S.LookupSpecialMember(D: Class, SM: CXXSpecialMemberKind::Destructor, ConstArg: false,
9794 VolatileArg: false, RValueThis: false, ConstThis: false, VolatileThis: false);
9795 if (shouldDeleteForSubobjectCall(Subobj, SMOR, IsDtorCallInCtor: true))
9796 return true;
9797 }
9798
9799 return false;
9800}
9801
9802bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
9803 FieldDecl *FD, QualType FieldType) {
9804 // The defaulted special functions are defined as deleted if this is a variant
9805 // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
9806 // type under ARC.
9807 if (!FieldType.hasNonTrivialObjCLifetime())
9808 return false;
9809
9810 // Don't make the defaulted default constructor defined as deleted if the
9811 // member has an in-class initializer.
9812 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
9813 FD->hasInClassInitializer())
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 << /*IsObjCPtr*/ true;
9821 }
9822
9823 return true;
9824}
9825
9826bool SpecialMemberDeletionInfo::shouldDeleteForVariantPtrAuthMember(
9827 const FieldDecl *FD) {
9828 QualType FieldType = S.Context.getBaseElementType(QT: FD->getType());
9829 // Copy/move constructors/assignment operators are deleted if the field has an
9830 // address-discriminated ptrauth qualifier.
9831 PointerAuthQualifier Q = FieldType.getPointerAuth();
9832
9833 if (!Q || !Q.isAddressDiscriminated())
9834 return false;
9835
9836 if (CSM == CXXSpecialMemberKind::DefaultConstructor ||
9837 CSM == CXXSpecialMemberKind::Destructor)
9838 return false;
9839
9840 if (Diagnose) {
9841 auto *ParentClass = cast<CXXRecordDecl>(Val: FD->getParent());
9842 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_deleted_special_member_class_subobject)
9843 << getEffectiveCSM() << ParentClass << /*IsField*/ true << FD << 4
9844 << /*IsDtorCallInCtor*/ false << 2;
9845 }
9846
9847 return true;
9848}
9849
9850/// Check whether we should delete a special member function due to the class
9851/// having a particular direct or virtual base class.
9852bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
9853 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
9854 // If program is correct, BaseClass cannot be null, but if it is, the error
9855 // must be reported elsewhere.
9856 if (!BaseClass)
9857 return false;
9858 // If we have an inheriting constructor, check whether we're calling an
9859 // inherited constructor instead of a default constructor.
9860 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(Class: BaseClass);
9861 if (auto *BaseCtor = SMOR.getMethod()) {
9862 // Note that we do not check access along this path; other than that,
9863 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
9864 // FIXME: Check that the base has a usable destructor! Sink this into
9865 // shouldDeleteForClassSubobject.
9866 if (BaseCtor->isDeleted() && Diagnose) {
9867 S.Diag(Loc: Base->getBeginLoc(),
9868 DiagID: diag::note_deleted_special_member_class_subobject)
9869 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9870 << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
9871 << /*IsObjCPtr*/ false;
9872 S.NoteDeletedFunction(FD: BaseCtor);
9873 }
9874 return BaseCtor->isDeleted();
9875 }
9876 return shouldDeleteForClassSubobject(Class: BaseClass, Subobj: Base, Quals: 0);
9877}
9878
9879/// Check whether we should delete a special member function due to the class
9880/// having a particular non-static data member.
9881bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
9882 QualType FieldType = S.Context.getBaseElementType(QT: FD->getType());
9883 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
9884
9885 if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
9886 return true;
9887
9888 if (inUnion() && shouldDeleteForVariantPtrAuthMember(FD))
9889 return true;
9890
9891 if (CSM == CXXSpecialMemberKind::DefaultConstructor) {
9892 // For a default constructor, all references must be initialized in-class
9893 // and, if a union, it must have a non-const member.
9894 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
9895 if (Diagnose)
9896 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_deleted_default_ctor_uninit_field)
9897 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
9898 return true;
9899 }
9900 // C++11 [class.ctor]p5 (modified by DR2394): any non-variant non-static
9901 // data member of const-qualified type (or array thereof) with no
9902 // brace-or-equal-initializer is not const-default-constructible.
9903 if (!inUnion() && FieldType.isConstQualified() &&
9904 !FD->hasInClassInitializer() &&
9905 (!FieldRecord || !FieldRecord->allowConstDefaultInit())) {
9906 if (Diagnose)
9907 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_deleted_default_ctor_uninit_field)
9908 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
9909 return true;
9910 }
9911
9912 if (inUnion() && !FieldType.isConstQualified())
9913 AllFieldsAreConst = false;
9914 } else if (CSM == CXXSpecialMemberKind::CopyConstructor) {
9915 // For a copy constructor, data members must not be of rvalue reference
9916 // type.
9917 if (FieldType->isRValueReferenceType()) {
9918 if (Diagnose)
9919 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_deleted_copy_ctor_rvalue_reference)
9920 << MD->getParent() << FD << FieldType;
9921 return true;
9922 }
9923 } else if (IsAssignment) {
9924 // For an assignment operator, data members must not be of reference type.
9925 if (FieldType->isReferenceType()) {
9926 if (Diagnose)
9927 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_deleted_assign_field)
9928 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
9929 return true;
9930 }
9931 if (!FieldRecord && FieldType.isConstQualified()) {
9932 // C++11 [class.copy]p23:
9933 // -- a non-static data member of const non-class type (or array thereof)
9934 if (Diagnose)
9935 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_deleted_assign_field)
9936 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
9937 return true;
9938 }
9939 }
9940
9941 if (FieldRecord) {
9942 // Some additional restrictions exist on the variant members.
9943 if (!inUnion() && FieldRecord->isUnion() &&
9944 FieldRecord->isAnonymousStructOrUnion()) {
9945 bool AllVariantFieldsAreConst = true;
9946
9947 // FIXME: Handle anonymous unions declared within anonymous unions.
9948 for (auto *UI : FieldRecord->fields()) {
9949 QualType UnionFieldType = S.Context.getBaseElementType(QT: UI->getType());
9950
9951 if (shouldDeleteForVariantObjCPtrMember(FD: &*UI, FieldType: UnionFieldType))
9952 return true;
9953
9954 if (shouldDeleteForVariantPtrAuthMember(FD: &*UI))
9955 return true;
9956
9957 if (!UnionFieldType.isConstQualified())
9958 AllVariantFieldsAreConst = false;
9959
9960 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
9961 if (UnionFieldRecord &&
9962 shouldDeleteForClassSubobject(Class: UnionFieldRecord, Subobj: UI,
9963 Quals: UnionFieldType.getCVRQualifiers()))
9964 return true;
9965 }
9966
9967 // At least one member in each anonymous union must be non-const
9968 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
9969 AllVariantFieldsAreConst && !FieldRecord->field_empty()) {
9970 if (Diagnose)
9971 S.Diag(Loc: FieldRecord->getLocation(),
9972 DiagID: diag::note_deleted_default_ctor_all_const)
9973 << !!ICI << MD->getParent() << /*anonymous union*/1;
9974 return true;
9975 }
9976
9977 // Don't check the implicit member of the anonymous union type.
9978 // This is technically non-conformant but supported, and we have a
9979 // diagnostic for this elsewhere.
9980 return false;
9981 }
9982
9983 if (shouldDeleteForClassSubobject(Class: FieldRecord, Subobj: FD,
9984 Quals: FieldType.getCVRQualifiers()))
9985 return true;
9986 }
9987
9988 return false;
9989}
9990
9991/// C++11 [class.ctor] p5:
9992/// A defaulted default constructor for a class X is defined as deleted if
9993/// X is a union and all of its variant members are of const-qualified type.
9994bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
9995 // This is a silly definition, because it gives an empty union a deleted
9996 // default constructor. Don't do that.
9997 if (CSM == CXXSpecialMemberKind::DefaultConstructor && inUnion() &&
9998 AllFieldsAreConst) {
9999 bool AnyFields = false;
10000 for (auto *F : MD->getParent()->fields())
10001 if ((AnyFields = !F->isUnnamedBitField()))
10002 break;
10003 if (!AnyFields)
10004 return false;
10005 if (Diagnose)
10006 S.Diag(Loc: MD->getParent()->getLocation(),
10007 DiagID: diag::note_deleted_default_ctor_all_const)
10008 << !!ICI << MD->getParent() << /*not anonymous union*/0;
10009 return true;
10010 }
10011 return false;
10012}
10013
10014/// Determine whether a defaulted special member function should be defined as
10015/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
10016/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
10017bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD,
10018 CXXSpecialMemberKind CSM,
10019 InheritedConstructorInfo *ICI,
10020 bool Diagnose) {
10021 if (MD->isInvalidDecl())
10022 return false;
10023 CXXRecordDecl *RD = MD->getParent();
10024 assert(!RD->isDependentType() && "do deletion after instantiation");
10025 if (!LangOpts.CPlusPlus || (!LangOpts.CPlusPlus11 && !RD->isLambda()) ||
10026 RD->isInvalidDecl())
10027 return false;
10028
10029 // C++11 [expr.lambda.prim]p19:
10030 // The closure type associated with a lambda-expression has a
10031 // deleted (8.4.3) default constructor and a deleted copy
10032 // assignment operator.
10033 // C++2a adds back these operators if the lambda has no lambda-capture.
10034 if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() &&
10035 (CSM == CXXSpecialMemberKind::DefaultConstructor ||
10036 CSM == CXXSpecialMemberKind::CopyAssignment)) {
10037 if (Diagnose)
10038 Diag(Loc: RD->getLocation(), DiagID: diag::note_lambda_decl);
10039 return true;
10040 }
10041
10042 // C++11 [class.copy]p7, p18:
10043 // If the class definition declares a move constructor or move assignment
10044 // operator, an implicitly declared copy constructor or copy assignment
10045 // operator is defined as deleted.
10046 if (MD->isImplicit() && (CSM == CXXSpecialMemberKind::CopyConstructor ||
10047 CSM == CXXSpecialMemberKind::CopyAssignment)) {
10048 CXXMethodDecl *UserDeclaredMove = nullptr;
10049
10050 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
10051 // deletion of the corresponding copy operation, not both copy operations.
10052 // MSVC 2015 has adopted the standards conforming behavior.
10053 bool DeletesOnlyMatchingCopy =
10054 getLangOpts().MSVCCompat &&
10055 !getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015);
10056
10057 if (RD->hasUserDeclaredMoveConstructor() &&
10058 (!DeletesOnlyMatchingCopy ||
10059 CSM == CXXSpecialMemberKind::CopyConstructor)) {
10060 if (!Diagnose) return true;
10061
10062 // Find any user-declared move constructor.
10063 for (auto *I : RD->ctors()) {
10064 if (I->isMoveConstructor()) {
10065 UserDeclaredMove = I;
10066 break;
10067 }
10068 }
10069 assert(UserDeclaredMove);
10070 } else if (RD->hasUserDeclaredMoveAssignment() &&
10071 (!DeletesOnlyMatchingCopy ||
10072 CSM == CXXSpecialMemberKind::CopyAssignment)) {
10073 if (!Diagnose) return true;
10074
10075 // Find any user-declared move assignment operator.
10076 for (auto *I : RD->methods()) {
10077 if (I->isMoveAssignmentOperator()) {
10078 UserDeclaredMove = I;
10079 break;
10080 }
10081 }
10082 assert(UserDeclaredMove);
10083 }
10084
10085 if (UserDeclaredMove) {
10086 Diag(Loc: UserDeclaredMove->getLocation(),
10087 DiagID: diag::note_deleted_copy_user_declared_move)
10088 << (CSM == CXXSpecialMemberKind::CopyAssignment) << RD
10089 << UserDeclaredMove->isMoveAssignmentOperator();
10090 return true;
10091 }
10092 }
10093
10094 // Do access control from the special member function
10095 ContextRAII MethodContext(*this, MD);
10096
10097 // C++11 [class.dtor]p5:
10098 // -- for a virtual destructor, lookup of the non-array deallocation function
10099 // results in an ambiguity or in a function that is deleted or inaccessible
10100 if (CSM == CXXSpecialMemberKind::Destructor && MD->isVirtual()) {
10101 FunctionDecl *OperatorDelete = nullptr;
10102 CanQualType DeallocType = Context.getCanonicalTagType(TD: RD);
10103 DeclarationName Name =
10104 Context.DeclarationNames.getCXXOperatorName(Op: OO_Delete);
10105 ImplicitDeallocationParameters IDP = {
10106 DeallocType, ShouldUseTypeAwareOperatorNewOrDelete(),
10107 AlignedAllocationMode::No, SizedDeallocationMode::No};
10108 if (FindDeallocationFunction(StartLoc: MD->getLocation(), RD: MD->getParent(), Name,
10109 Operator&: OperatorDelete, IDP,
10110 /*Diagnose=*/false)) {
10111 if (Diagnose)
10112 Diag(Loc: RD->getLocation(), DiagID: diag::note_deleted_dtor_no_operator_delete);
10113 return true;
10114 }
10115 }
10116
10117 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
10118
10119 // Per DR1611, do not consider virtual bases of constructors of abstract
10120 // classes, since we are not going to construct them.
10121 // Per DR1658, do not consider virtual bases of destructors of abstract
10122 // classes either.
10123 // Per DR2180, for assignment operators we only assign (and thus only
10124 // consider) direct bases.
10125 if (SMI.visit(Bases: SMI.IsAssignment ? SMI.VisitDirectBases
10126 : SMI.VisitPotentiallyConstructedBases))
10127 return true;
10128
10129 if (SMI.shouldDeleteForAllConstMembers())
10130 return true;
10131
10132 if (getLangOpts().CUDA) {
10133 // We should delete the special member in CUDA mode if target inference
10134 // failed.
10135 // For inherited constructors (non-null ICI), CSM may be passed so that MD
10136 // is treated as certain special member, which may not reflect what special
10137 // member MD really is. However inferTargetForImplicitSpecialMember
10138 // expects CSM to match MD, therefore recalculate CSM.
10139 assert(ICI || CSM == MD->getSpecialMemberKind());
10140 auto RealCSM = CSM;
10141 if (ICI)
10142 RealCSM = MD->getSpecialMemberKind();
10143
10144 return CUDA().inferTargetForImplicitSpecialMember(ClassDecl: RD, CSM: RealCSM, MemberDecl: MD,
10145 ConstRHS: SMI.ConstArg, Diagnose);
10146 }
10147
10148 return false;
10149}
10150
10151void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl *FD) {
10152 FunctionDecl::DefaultedFunctionKind DFK = FD->getDefaultedFunctionKind();
10153 assert(DFK && "not a defaultable function");
10154 assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted");
10155
10156 if (DFK.isSpecialMember()) {
10157 ShouldDeleteSpecialMember(MD: cast<CXXMethodDecl>(Val: FD), CSM: DFK.asSpecialMember(),
10158 ICI: nullptr, /*Diagnose=*/true);
10159 } else {
10160 DefaultedComparisonAnalyzer(
10161 *this, cast<CXXRecordDecl>(Val: FD->getLexicalDeclContext()), FD,
10162 DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted)
10163 .visit();
10164 }
10165}
10166
10167/// Perform lookup for a special member of the specified kind, and determine
10168/// whether it is trivial. If the triviality can be determined without the
10169/// lookup, skip it. This is intended for use when determining whether a
10170/// special member of a containing object is trivial, and thus does not ever
10171/// perform overload resolution for default constructors.
10172///
10173/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
10174/// member that was most likely to be intended to be trivial, if any.
10175///
10176/// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
10177/// determine whether the special member is trivial.
10178static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
10179 CXXSpecialMemberKind CSM, unsigned Quals,
10180 bool ConstRHS, TrivialABIHandling TAH,
10181 CXXMethodDecl **Selected) {
10182 if (Selected)
10183 *Selected = nullptr;
10184
10185 switch (CSM) {
10186 case CXXSpecialMemberKind::Invalid:
10187 llvm_unreachable("not a special member");
10188
10189 case CXXSpecialMemberKind::DefaultConstructor:
10190 // C++11 [class.ctor]p5:
10191 // A default constructor is trivial if:
10192 // - all the [direct subobjects] have trivial default constructors
10193 //
10194 // Note, no overload resolution is performed in this case.
10195 if (RD->hasTrivialDefaultConstructor())
10196 return true;
10197
10198 if (Selected) {
10199 // If there's a default constructor which could have been trivial, dig it
10200 // out. Otherwise, if there's any user-provided default constructor, point
10201 // to that as an example of why there's not a trivial one.
10202 CXXConstructorDecl *DefCtor = nullptr;
10203 if (RD->needsImplicitDefaultConstructor())
10204 S.DeclareImplicitDefaultConstructor(ClassDecl: RD);
10205 for (auto *CI : RD->ctors()) {
10206 if (!CI->isDefaultConstructor())
10207 continue;
10208 DefCtor = CI;
10209 if (!DefCtor->isUserProvided())
10210 break;
10211 }
10212
10213 *Selected = DefCtor;
10214 }
10215
10216 return false;
10217
10218 case CXXSpecialMemberKind::Destructor:
10219 // C++11 [class.dtor]p5:
10220 // A destructor is trivial if:
10221 // - all the direct [subobjects] have trivial destructors
10222 if (RD->hasTrivialDestructor() ||
10223 (TAH == TrivialABIHandling::ConsiderTrivialABI &&
10224 RD->hasTrivialDestructorForCall()))
10225 return true;
10226
10227 if (Selected) {
10228 if (RD->needsImplicitDestructor())
10229 S.DeclareImplicitDestructor(ClassDecl: RD);
10230 *Selected = RD->getDestructor();
10231 }
10232
10233 return false;
10234
10235 case CXXSpecialMemberKind::CopyConstructor:
10236 // C++11 [class.copy]p12:
10237 // A copy constructor is trivial if:
10238 // - the constructor selected to copy each direct [subobject] is trivial
10239 if (RD->hasTrivialCopyConstructor() ||
10240 (TAH == TrivialABIHandling::ConsiderTrivialABI &&
10241 RD->hasTrivialCopyConstructorForCall())) {
10242 if (Quals == Qualifiers::Const)
10243 // We must either select the trivial copy constructor or reach an
10244 // ambiguity; no need to actually perform overload resolution.
10245 return true;
10246 } else if (!Selected) {
10247 return false;
10248 }
10249 // In C++98, we are not supposed to perform overload resolution here, but we
10250 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
10251 // cases like B as having a non-trivial copy constructor:
10252 // struct A { template<typename T> A(T&); };
10253 // struct B { mutable A a; };
10254 goto NeedOverloadResolution;
10255
10256 case CXXSpecialMemberKind::CopyAssignment:
10257 // C++11 [class.copy]p25:
10258 // A copy assignment operator is trivial if:
10259 // - the assignment operator selected to copy each direct [subobject] is
10260 // trivial
10261 if (RD->hasTrivialCopyAssignment()) {
10262 if (Quals == Qualifiers::Const)
10263 return true;
10264 } else if (!Selected) {
10265 return false;
10266 }
10267 // In C++98, we are not supposed to perform overload resolution here, but we
10268 // treat that as a language defect.
10269 goto NeedOverloadResolution;
10270
10271 case CXXSpecialMemberKind::MoveConstructor:
10272 case CXXSpecialMemberKind::MoveAssignment:
10273 NeedOverloadResolution:
10274 Sema::SpecialMemberOverloadResult SMOR =
10275 lookupCallFromSpecialMember(S, Class: RD, CSM, FieldQuals: Quals, ConstRHS);
10276
10277 // The standard doesn't describe how to behave if the lookup is ambiguous.
10278 // We treat it as not making the member non-trivial, just like the standard
10279 // mandates for the default constructor. This should rarely matter, because
10280 // the member will also be deleted.
10281 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
10282 return true;
10283
10284 if (!SMOR.getMethod()) {
10285 assert(SMOR.getKind() ==
10286 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
10287 return false;
10288 }
10289
10290 // We deliberately don't check if we found a deleted special member. We're
10291 // not supposed to!
10292 if (Selected)
10293 *Selected = SMOR.getMethod();
10294
10295 if (TAH == TrivialABIHandling::ConsiderTrivialABI &&
10296 (CSM == CXXSpecialMemberKind::CopyConstructor ||
10297 CSM == CXXSpecialMemberKind::MoveConstructor))
10298 return SMOR.getMethod()->isTrivialForCall();
10299 return SMOR.getMethod()->isTrivial();
10300 }
10301
10302 llvm_unreachable("unknown special method kind");
10303}
10304
10305static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
10306 for (auto *CI : RD->ctors())
10307 if (!CI->isImplicit())
10308 return CI;
10309
10310 // Look for constructor templates.
10311 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
10312 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
10313 if (CXXConstructorDecl *CD =
10314 dyn_cast<CXXConstructorDecl>(Val: TI->getTemplatedDecl()))
10315 return CD;
10316 }
10317
10318 return nullptr;
10319}
10320
10321/// The kind of subobject we are checking for triviality. The values of this
10322/// enumeration are used in diagnostics.
10323enum TrivialSubobjectKind {
10324 /// The subobject is a base class.
10325 TSK_BaseClass,
10326 /// The subobject is a non-static data member.
10327 TSK_Field,
10328 /// The object is actually the complete object.
10329 TSK_CompleteObject
10330};
10331
10332/// Check whether the special member selected for a given type would be trivial.
10333static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
10334 QualType SubType, bool ConstRHS,
10335 CXXSpecialMemberKind CSM,
10336 TrivialSubobjectKind Kind,
10337 TrivialABIHandling TAH, bool Diagnose) {
10338 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
10339 if (!SubRD)
10340 return true;
10341
10342 CXXMethodDecl *Selected;
10343 if (findTrivialSpecialMember(S, RD: SubRD, CSM, Quals: SubType.getCVRQualifiers(),
10344 ConstRHS, TAH, Selected: Diagnose ? &Selected : nullptr))
10345 return true;
10346
10347 if (Diagnose) {
10348 if (ConstRHS)
10349 SubType.addConst();
10350
10351 if (!Selected && CSM == CXXSpecialMemberKind::DefaultConstructor) {
10352 S.Diag(Loc: SubobjLoc, DiagID: diag::note_nontrivial_no_def_ctor)
10353 << Kind << SubType.getUnqualifiedType();
10354 if (CXXConstructorDecl *CD = findUserDeclaredCtor(RD: SubRD))
10355 S.Diag(Loc: CD->getLocation(), DiagID: diag::note_user_declared_ctor);
10356 } else if (!Selected)
10357 S.Diag(Loc: SubobjLoc, DiagID: diag::note_nontrivial_no_copy)
10358 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
10359 else if (Selected->isUserProvided()) {
10360 if (Kind == TSK_CompleteObject)
10361 S.Diag(Loc: Selected->getLocation(), DiagID: diag::note_nontrivial_user_provided)
10362 << Kind << SubType.getUnqualifiedType() << CSM;
10363 else {
10364 S.Diag(Loc: SubobjLoc, DiagID: diag::note_nontrivial_user_provided)
10365 << Kind << SubType.getUnqualifiedType() << CSM;
10366 S.Diag(Loc: Selected->getLocation(), DiagID: diag::note_declared_at);
10367 }
10368 } else {
10369 if (Kind != TSK_CompleteObject)
10370 S.Diag(Loc: SubobjLoc, DiagID: diag::note_nontrivial_subobject)
10371 << Kind << SubType.getUnqualifiedType() << CSM;
10372
10373 // Explain why the defaulted or deleted special member isn't trivial.
10374 S.SpecialMemberIsTrivial(MD: Selected, CSM,
10375 TAH: TrivialABIHandling::IgnoreTrivialABI, Diagnose);
10376 }
10377 }
10378
10379 return false;
10380}
10381
10382/// Check whether the members of a class type allow a special member to be
10383/// trivial.
10384static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
10385 CXXSpecialMemberKind CSM, bool ConstArg,
10386 TrivialABIHandling TAH, bool Diagnose) {
10387 for (const auto *FI : RD->fields()) {
10388 if (FI->isInvalidDecl() || FI->isUnnamedBitField())
10389 continue;
10390
10391 QualType FieldType = S.Context.getBaseElementType(QT: FI->getType());
10392
10393 // Pretend anonymous struct or union members are members of this class.
10394 if (FI->isAnonymousStructOrUnion()) {
10395 if (!checkTrivialClassMembers(S, RD: FieldType->getAsCXXRecordDecl(),
10396 CSM, ConstArg, TAH, Diagnose))
10397 return false;
10398 continue;
10399 }
10400
10401 // C++11 [class.ctor]p5:
10402 // A default constructor is trivial if [...]
10403 // -- no non-static data member of its class has a
10404 // brace-or-equal-initializer
10405 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
10406 FI->hasInClassInitializer()) {
10407 if (Diagnose)
10408 S.Diag(Loc: FI->getLocation(), DiagID: diag::note_nontrivial_default_member_init)
10409 << FI;
10410 return false;
10411 }
10412
10413 // Objective C ARC 4.3.5:
10414 // [...] nontrivally ownership-qualified types are [...] not trivially
10415 // default constructible, copy constructible, move constructible, copy
10416 // assignable, move assignable, or destructible [...]
10417 if (FieldType.hasNonTrivialObjCLifetime()) {
10418 if (Diagnose)
10419 S.Diag(Loc: FI->getLocation(), DiagID: diag::note_nontrivial_objc_ownership)
10420 << RD << FieldType.getObjCLifetime();
10421 return false;
10422 }
10423
10424 bool ConstRHS = ConstArg && !FI->isMutable();
10425 if (!checkTrivialSubobjectCall(S, SubobjLoc: FI->getLocation(), SubType: FieldType, ConstRHS,
10426 CSM, Kind: TSK_Field, TAH, Diagnose))
10427 return false;
10428 }
10429
10430 return true;
10431}
10432
10433void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD,
10434 CXXSpecialMemberKind CSM) {
10435 CanQualType Ty = Context.getCanonicalTagType(TD: RD);
10436
10437 bool ConstArg = (CSM == CXXSpecialMemberKind::CopyConstructor ||
10438 CSM == CXXSpecialMemberKind::CopyAssignment);
10439 checkTrivialSubobjectCall(S&: *this, SubobjLoc: RD->getLocation(), SubType: Ty, ConstRHS: ConstArg, CSM,
10440 Kind: TSK_CompleteObject,
10441 TAH: TrivialABIHandling::IgnoreTrivialABI,
10442 /*Diagnose*/ true);
10443}
10444
10445bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMemberKind CSM,
10446 TrivialABIHandling TAH, bool Diagnose) {
10447 assert(!MD->isUserProvided() && CSM != CXXSpecialMemberKind::Invalid &&
10448 "not special enough");
10449
10450 CXXRecordDecl *RD = MD->getParent();
10451
10452 bool ConstArg = false;
10453
10454 // C++11 [class.copy]p12, p25: [DR1593]
10455 // A [special member] is trivial if [...] its parameter-type-list is
10456 // equivalent to the parameter-type-list of an implicit declaration [...]
10457 switch (CSM) {
10458 case CXXSpecialMemberKind::DefaultConstructor:
10459 case CXXSpecialMemberKind::Destructor:
10460 // Trivial default constructors and destructors cannot have parameters.
10461 break;
10462
10463 case CXXSpecialMemberKind::CopyConstructor:
10464 case CXXSpecialMemberKind::CopyAssignment: {
10465 const ParmVarDecl *Param0 = MD->getNonObjectParameter(I: 0);
10466 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
10467
10468 // When ClangABICompat14 is true, CXX copy constructors will only be trivial
10469 // if they are not user-provided and their parameter-type-list is equivalent
10470 // to the parameter-type-list of an implicit declaration. This maintains the
10471 // behavior before dr2171 was implemented.
10472 //
10473 // Otherwise, if ClangABICompat14 is false, All copy constructors can be
10474 // trivial, if they are not user-provided, regardless of the qualifiers on
10475 // the reference type.
10476 const bool ClangABICompat14 =
10477 Context.getLangOpts().isCompatibleWith(Version: LangOptions::ClangABI::Ver14);
10478 if (!RT ||
10479 ((RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) &&
10480 ClangABICompat14)) {
10481 if (Diagnose)
10482 Diag(Loc: Param0->getLocation(), DiagID: diag::note_nontrivial_param_type)
10483 << Param0->getSourceRange() << Param0->getType()
10484 << Context.getLValueReferenceType(
10485 T: Context.getCanonicalTagType(TD: RD).withConst());
10486 return false;
10487 }
10488
10489 ConstArg = RT->getPointeeType().isConstQualified();
10490 break;
10491 }
10492
10493 case CXXSpecialMemberKind::MoveConstructor:
10494 case CXXSpecialMemberKind::MoveAssignment: {
10495 // Trivial move operations always have non-cv-qualified parameters.
10496 const ParmVarDecl *Param0 = MD->getNonObjectParameter(I: 0);
10497 const RValueReferenceType *RT =
10498 Param0->getType()->getAs<RValueReferenceType>();
10499 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
10500 if (Diagnose)
10501 Diag(Loc: Param0->getLocation(), DiagID: diag::note_nontrivial_param_type)
10502 << Param0->getSourceRange() << Param0->getType()
10503 << Context.getRValueReferenceType(T: Context.getCanonicalTagType(TD: RD));
10504 return false;
10505 }
10506 break;
10507 }
10508
10509 case CXXSpecialMemberKind::Invalid:
10510 llvm_unreachable("not a special member");
10511 }
10512
10513 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
10514 if (Diagnose)
10515 Diag(Loc: MD->getParamDecl(i: MD->getMinRequiredArguments())->getLocation(),
10516 DiagID: diag::note_nontrivial_default_arg)
10517 << MD->getParamDecl(i: MD->getMinRequiredArguments())->getSourceRange();
10518 return false;
10519 }
10520 if (MD->isVariadic()) {
10521 if (Diagnose)
10522 Diag(Loc: MD->getLocation(), DiagID: diag::note_nontrivial_variadic);
10523 return false;
10524 }
10525
10526 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
10527 // A copy/move [constructor or assignment operator] is trivial if
10528 // -- the [member] selected to copy/move each direct base class subobject
10529 // is trivial
10530 //
10531 // C++11 [class.copy]p12, C++11 [class.copy]p25:
10532 // A [default constructor or destructor] is trivial if
10533 // -- all the direct base classes have trivial [default constructors or
10534 // destructors]
10535 for (const auto &BI : RD->bases())
10536 if (!checkTrivialSubobjectCall(S&: *this, SubobjLoc: BI.getBeginLoc(), SubType: BI.getType(),
10537 ConstRHS: ConstArg, CSM, Kind: TSK_BaseClass, TAH, Diagnose))
10538 return false;
10539
10540 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
10541 // A copy/move [constructor or assignment operator] for a class X is
10542 // trivial if
10543 // -- for each non-static data member of X that is of class type (or array
10544 // thereof), the constructor selected to copy/move that member is
10545 // trivial
10546 //
10547 // C++11 [class.copy]p12, C++11 [class.copy]p25:
10548 // A [default constructor or destructor] is trivial if
10549 // -- for all of the non-static data members of its class that are of class
10550 // type (or array thereof), each such class has a trivial [default
10551 // constructor or destructor]
10552 if (!checkTrivialClassMembers(S&: *this, RD, CSM, ConstArg, TAH, Diagnose))
10553 return false;
10554
10555 // C++11 [class.dtor]p5:
10556 // A destructor is trivial if [...]
10557 // -- the destructor is not virtual
10558 if (CSM == CXXSpecialMemberKind::Destructor && MD->isVirtual()) {
10559 if (Diagnose)
10560 Diag(Loc: MD->getLocation(), DiagID: diag::note_nontrivial_virtual_dtor) << RD;
10561 return false;
10562 }
10563
10564 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
10565 // A [special member] for class X is trivial if [...]
10566 // -- class X has no virtual functions and no virtual base classes
10567 if (CSM != CXXSpecialMemberKind::Destructor &&
10568 MD->getParent()->isDynamicClass()) {
10569 if (!Diagnose)
10570 return false;
10571
10572 if (RD->getNumVBases()) {
10573 // Check for virtual bases. We already know that the corresponding
10574 // member in all bases is trivial, so vbases must all be direct.
10575 CXXBaseSpecifier &BS = *RD->vbases_begin();
10576 assert(BS.isVirtual());
10577 Diag(Loc: BS.getBeginLoc(), DiagID: diag::note_nontrivial_has_virtual) << RD << 1;
10578 return false;
10579 }
10580
10581 // Must have a virtual method.
10582 for (const auto *MI : RD->methods()) {
10583 if (MI->isVirtual()) {
10584 SourceLocation MLoc = MI->getBeginLoc();
10585 Diag(Loc: MLoc, DiagID: diag::note_nontrivial_has_virtual) << RD << 0;
10586 return false;
10587 }
10588 }
10589
10590 llvm_unreachable("dynamic class with no vbases and no virtual functions");
10591 }
10592
10593 // Looks like it's trivial!
10594 return true;
10595}
10596
10597namespace {
10598struct FindHiddenVirtualMethod {
10599 Sema *S;
10600 CXXMethodDecl *Method;
10601 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
10602 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10603
10604private:
10605 /// Check whether any most overridden method from MD in Methods
10606 static bool CheckMostOverridenMethods(
10607 const CXXMethodDecl *MD,
10608 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
10609 if (MD->size_overridden_methods() == 0)
10610 return Methods.count(Ptr: MD->getCanonicalDecl());
10611 for (const CXXMethodDecl *O : MD->overridden_methods())
10612 if (CheckMostOverridenMethods(MD: O, Methods))
10613 return true;
10614 return false;
10615 }
10616
10617public:
10618 /// Member lookup function that determines whether a given C++
10619 /// method overloads virtual methods in a base class without overriding any,
10620 /// to be used with CXXRecordDecl::lookupInBases().
10621 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
10622 auto *BaseRecord = Specifier->getType()->castAsRecordDecl();
10623 DeclarationName Name = Method->getDeclName();
10624 assert(Name.getNameKind() == DeclarationName::Identifier);
10625
10626 bool foundSameNameMethod = false;
10627 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
10628 for (Path.Decls = BaseRecord->lookup(Name).begin();
10629 Path.Decls != DeclContext::lookup_iterator(); ++Path.Decls) {
10630 NamedDecl *D = *Path.Decls;
10631 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: D)) {
10632 MD = MD->getCanonicalDecl();
10633 foundSameNameMethod = true;
10634 // Interested only in hidden virtual methods.
10635 if (!MD->isVirtual())
10636 continue;
10637 // If the method we are checking overrides a method from its base
10638 // don't warn about the other overloaded methods. Clang deviates from
10639 // GCC by only diagnosing overloads of inherited virtual functions that
10640 // do not override any other virtual functions in the base. GCC's
10641 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
10642 // function from a base class. These cases may be better served by a
10643 // warning (not specific to virtual functions) on call sites when the
10644 // call would select a different function from the base class, were it
10645 // visible.
10646 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
10647 if (!S->IsOverload(New: Method, Old: MD, UseMemberUsingDeclRules: false))
10648 return true;
10649 // Collect the overload only if its hidden.
10650 if (!CheckMostOverridenMethods(MD, Methods: OverridenAndUsingBaseMethods))
10651 overloadedMethods.push_back(Elt: MD);
10652 }
10653 }
10654
10655 if (foundSameNameMethod)
10656 OverloadedMethods.append(in_start: overloadedMethods.begin(),
10657 in_end: overloadedMethods.end());
10658 return foundSameNameMethod;
10659 }
10660};
10661} // end anonymous namespace
10662
10663/// Add the most overridden methods from MD to Methods
10664static void AddMostOverridenMethods(const CXXMethodDecl *MD,
10665 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
10666 if (MD->size_overridden_methods() == 0)
10667 Methods.insert(Ptr: MD->getCanonicalDecl());
10668 else
10669 for (const CXXMethodDecl *O : MD->overridden_methods())
10670 AddMostOverridenMethods(MD: O, Methods);
10671}
10672
10673void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
10674 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10675 if (!MD->getDeclName().isIdentifier())
10676 return;
10677
10678 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
10679 /*bool RecordPaths=*/false,
10680 /*bool DetectVirtual=*/false);
10681 FindHiddenVirtualMethod FHVM;
10682 FHVM.Method = MD;
10683 FHVM.S = this;
10684
10685 // Keep the base methods that were overridden or introduced in the subclass
10686 // by 'using' in a set. A base method not in this set is hidden.
10687 CXXRecordDecl *DC = MD->getParent();
10688 for (NamedDecl *ND : DC->lookup(Name: MD->getDeclName())) {
10689 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(Val: ND))
10690 ND = shad->getTargetDecl();
10691 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: ND))
10692 AddMostOverridenMethods(MD, Methods&: FHVM.OverridenAndUsingBaseMethods);
10693 }
10694
10695 if (DC->lookupInBases(BaseMatches: FHVM, Paths))
10696 OverloadedMethods = FHVM.OverloadedMethods;
10697}
10698
10699void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
10700 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10701 for (const CXXMethodDecl *overloadedMD : OverloadedMethods) {
10702 PartialDiagnostic PD = PDiag(
10703 DiagID: diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
10704 HandleFunctionTypeMismatch(PDiag&: PD, FromType: MD->getType(), ToType: overloadedMD->getType());
10705 Diag(Loc: overloadedMD->getLocation(), PD);
10706 }
10707}
10708
10709void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
10710 if (MD->isInvalidDecl())
10711 return;
10712
10713 if (Diags.isIgnored(DiagID: diag::warn_overloaded_virtual, Loc: MD->getLocation()))
10714 return;
10715
10716 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10717 FindHiddenVirtualMethods(MD, OverloadedMethods);
10718 if (!OverloadedMethods.empty()) {
10719 Diag(Loc: MD->getLocation(), DiagID: diag::warn_overloaded_virtual)
10720 << MD << (OverloadedMethods.size() > 1);
10721
10722 NoteHiddenVirtualMethods(MD, OverloadedMethods);
10723 }
10724}
10725
10726void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
10727 auto PrintDiagAndRemoveAttr = [&](unsigned N) {
10728 // No diagnostics if this is a template instantiation.
10729 if (!isTemplateInstantiation(Kind: RD.getTemplateSpecializationKind())) {
10730 Diag(Loc: RD.getAttr<TrivialABIAttr>()->getLocation(),
10731 DiagID: diag::ext_cannot_use_trivial_abi) << &RD;
10732 Diag(Loc: RD.getAttr<TrivialABIAttr>()->getLocation(),
10733 DiagID: diag::note_cannot_use_trivial_abi_reason) << &RD << N;
10734 }
10735 RD.dropAttr<TrivialABIAttr>();
10736 };
10737
10738 // Ill-formed if the struct has virtual functions.
10739 if (RD.isPolymorphic()) {
10740 PrintDiagAndRemoveAttr(1);
10741 return;
10742 }
10743
10744 for (const auto &B : RD.bases()) {
10745 // Ill-formed if the base class is non-trivial for the purpose of calls or a
10746 // virtual base.
10747 if (!B.getType()->isDependentType() &&
10748 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) {
10749 PrintDiagAndRemoveAttr(2);
10750 return;
10751 }
10752
10753 if (B.isVirtual()) {
10754 PrintDiagAndRemoveAttr(3);
10755 return;
10756 }
10757 }
10758
10759 for (const auto *FD : RD.fields()) {
10760 // Ill-formed if the field is an ObjectiveC pointer or of a type that is
10761 // non-trivial for the purpose of calls.
10762 QualType FT = FD->getType();
10763 if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
10764 PrintDiagAndRemoveAttr(4);
10765 return;
10766 }
10767
10768 // Ill-formed if the field is an address-discriminated value.
10769 if (FT.hasAddressDiscriminatedPointerAuth()) {
10770 PrintDiagAndRemoveAttr(6);
10771 return;
10772 }
10773
10774 if (const auto *RT =
10775 FT->getBaseElementTypeUnsafe()->getAsCanonical<RecordType>())
10776 if (!RT->isDependentType() &&
10777 !cast<CXXRecordDecl>(Val: RT->getDecl()->getDefinitionOrSelf())
10778 ->canPassInRegisters()) {
10779 PrintDiagAndRemoveAttr(5);
10780 return;
10781 }
10782 }
10783
10784 if (IsCXXTriviallyRelocatableType(RD))
10785 return;
10786
10787 // Ill-formed if the copy and move constructors are deleted.
10788 auto HasNonDeletedCopyOrMoveConstructor = [&]() {
10789 // If the type is dependent, then assume it might have
10790 // implicit copy or move ctor because we won't know yet at this point.
10791 if (RD.isDependentType())
10792 return true;
10793 if (RD.needsImplicitCopyConstructor() &&
10794 !RD.defaultedCopyConstructorIsDeleted())
10795 return true;
10796 if (RD.needsImplicitMoveConstructor() &&
10797 !RD.defaultedMoveConstructorIsDeleted())
10798 return true;
10799 for (const CXXConstructorDecl *CD : RD.ctors())
10800 if (CD->isCopyOrMoveConstructor() && !CD->isDeleted())
10801 return true;
10802 return false;
10803 };
10804
10805 if (!HasNonDeletedCopyOrMoveConstructor()) {
10806 PrintDiagAndRemoveAttr(0);
10807 return;
10808 }
10809}
10810
10811void Sema::checkIncorrectVTablePointerAuthenticationAttribute(
10812 CXXRecordDecl &RD) {
10813 if (RequireCompleteType(Loc: RD.getLocation(), T: Context.getCanonicalTagType(TD: &RD),
10814 DiagID: diag::err_incomplete_type_vtable_pointer_auth))
10815 return;
10816
10817 const CXXRecordDecl *PrimaryBase = &RD;
10818 if (PrimaryBase->hasAnyDependentBases())
10819 return;
10820
10821 while (1) {
10822 assert(PrimaryBase);
10823 const CXXRecordDecl *Base = nullptr;
10824 for (const CXXBaseSpecifier &BasePtr : PrimaryBase->bases()) {
10825 if (!BasePtr.getType()->getAsCXXRecordDecl()->isDynamicClass())
10826 continue;
10827 Base = BasePtr.getType()->getAsCXXRecordDecl();
10828 break;
10829 }
10830 if (!Base || Base == PrimaryBase || !Base->isPolymorphic())
10831 break;
10832 Diag(Loc: RD.getAttr<VTablePointerAuthenticationAttr>()->getLocation(),
10833 DiagID: diag::err_non_top_level_vtable_pointer_auth)
10834 << &RD << Base;
10835 PrimaryBase = Base;
10836 }
10837
10838 if (!RD.isPolymorphic())
10839 Diag(Loc: RD.getAttr<VTablePointerAuthenticationAttr>()->getLocation(),
10840 DiagID: diag::err_non_polymorphic_vtable_pointer_auth)
10841 << &RD;
10842}
10843
10844void Sema::ActOnFinishCXXMemberSpecification(
10845 Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
10846 SourceLocation RBrac, const ParsedAttributesView &AttrList) {
10847 if (!TagDecl)
10848 return;
10849
10850 AdjustDeclIfTemplate(Decl&: TagDecl);
10851
10852 for (const ParsedAttr &AL : AttrList) {
10853 if (AL.getKind() != ParsedAttr::AT_Visibility)
10854 continue;
10855 AL.setInvalid();
10856 Diag(Loc: AL.getLoc(), DiagID: diag::warn_attribute_after_definition_ignored) << AL;
10857 }
10858
10859 ActOnFields(S, RecLoc: RLoc, TagDecl,
10860 Fields: llvm::ArrayRef(
10861 // strict aliasing violation!
10862 reinterpret_cast<Decl **>(FieldCollector->getCurFields()),
10863 FieldCollector->getCurNumFields()),
10864 LBrac, RBrac, AttrList);
10865
10866 CheckCompletedCXXClass(S, Record: cast<CXXRecordDecl>(Val: TagDecl));
10867}
10868
10869/// Find the equality comparison functions that should be implicitly declared
10870/// in a given class definition, per C++2a [class.compare.default]p3.
10871static void findImplicitlyDeclaredEqualityComparisons(
10872 ASTContext &Ctx, CXXRecordDecl *RD,
10873 llvm::SmallVectorImpl<FunctionDecl *> &Spaceships) {
10874 DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(Op: OO_EqualEqual);
10875 if (!RD->lookup(Name: EqEq).empty())
10876 // Member operator== explicitly declared: no implicit operator==s.
10877 return;
10878
10879 // Traverse friends looking for an '==' or a '<=>'.
10880 for (FriendDecl *Friend : RD->friends()) {
10881 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Val: Friend->getFriendDecl());
10882 if (!FD) continue;
10883
10884 if (FD->getOverloadedOperator() == OO_EqualEqual) {
10885 // Friend operator== explicitly declared: no implicit operator==s.
10886 Spaceships.clear();
10887 return;
10888 }
10889
10890 if (FD->getOverloadedOperator() == OO_Spaceship &&
10891 FD->isExplicitlyDefaulted())
10892 Spaceships.push_back(Elt: FD);
10893 }
10894
10895 // Look for members named 'operator<=>'.
10896 DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(Op: OO_Spaceship);
10897 for (NamedDecl *ND : RD->lookup(Name: Cmp)) {
10898 // Note that we could find a non-function here (either a function template
10899 // or a using-declaration). Neither case results in an implicit
10900 // 'operator=='.
10901 if (auto *FD = dyn_cast<FunctionDecl>(Val: ND))
10902 if (FD->isExplicitlyDefaulted())
10903 Spaceships.push_back(Elt: FD);
10904 }
10905}
10906
10907void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
10908 // Don't add implicit special members to templated classes.
10909 // FIXME: This means unqualified lookups for 'operator=' within a class
10910 // template don't work properly.
10911 if (!ClassDecl->isDependentType()) {
10912 if (ClassDecl->needsImplicitDefaultConstructor()) {
10913 ++getASTContext().NumImplicitDefaultConstructors;
10914
10915 if (ClassDecl->hasInheritedConstructor())
10916 DeclareImplicitDefaultConstructor(ClassDecl);
10917 }
10918
10919 if (ClassDecl->needsImplicitCopyConstructor()) {
10920 ++getASTContext().NumImplicitCopyConstructors;
10921
10922 // If the properties or semantics of the copy constructor couldn't be
10923 // determined while the class was being declared, force a declaration
10924 // of it now.
10925 if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
10926 ClassDecl->hasInheritedConstructor())
10927 DeclareImplicitCopyConstructor(ClassDecl);
10928 // For the MS ABI we need to know whether the copy ctor is deleted. A
10929 // prerequisite for deleting the implicit copy ctor is that the class has
10930 // a move ctor or move assignment that is either user-declared or whose
10931 // semantics are inherited from a subobject. FIXME: We should provide a
10932 // more direct way for CodeGen to ask whether the constructor was deleted.
10933 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
10934 (ClassDecl->hasUserDeclaredMoveConstructor() ||
10935 ClassDecl->needsOverloadResolutionForMoveConstructor() ||
10936 ClassDecl->hasUserDeclaredMoveAssignment() ||
10937 ClassDecl->needsOverloadResolutionForMoveAssignment()))
10938 DeclareImplicitCopyConstructor(ClassDecl);
10939 }
10940
10941 if (getLangOpts().CPlusPlus11 &&
10942 ClassDecl->needsImplicitMoveConstructor()) {
10943 ++getASTContext().NumImplicitMoveConstructors;
10944
10945 if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
10946 ClassDecl->hasInheritedConstructor())
10947 DeclareImplicitMoveConstructor(ClassDecl);
10948 }
10949
10950 if (ClassDecl->needsImplicitCopyAssignment()) {
10951 ++getASTContext().NumImplicitCopyAssignmentOperators;
10952
10953 // If we have a dynamic class, then the copy assignment operator may be
10954 // virtual, so we have to declare it immediately. This ensures that, e.g.,
10955 // it shows up in the right place in the vtable and that we diagnose
10956 // problems with the implicit exception specification.
10957 if (ClassDecl->isDynamicClass() ||
10958 ClassDecl->needsOverloadResolutionForCopyAssignment() ||
10959 ClassDecl->hasInheritedAssignment())
10960 DeclareImplicitCopyAssignment(ClassDecl);
10961 }
10962
10963 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
10964 ++getASTContext().NumImplicitMoveAssignmentOperators;
10965
10966 // Likewise for the move assignment operator.
10967 if (ClassDecl->isDynamicClass() ||
10968 ClassDecl->needsOverloadResolutionForMoveAssignment() ||
10969 ClassDecl->hasInheritedAssignment())
10970 DeclareImplicitMoveAssignment(ClassDecl);
10971 }
10972
10973 if (ClassDecl->needsImplicitDestructor()) {
10974 ++getASTContext().NumImplicitDestructors;
10975
10976 // If we have a dynamic class, then the destructor may be virtual, so we
10977 // have to declare the destructor immediately. This ensures that, e.g., it
10978 // shows up in the right place in the vtable and that we diagnose problems
10979 // with the implicit exception specification.
10980 if (ClassDecl->isDynamicClass() ||
10981 ClassDecl->needsOverloadResolutionForDestructor())
10982 DeclareImplicitDestructor(ClassDecl);
10983 }
10984 }
10985
10986 // C++2a [class.compare.default]p3:
10987 // If the member-specification does not explicitly declare any member or
10988 // friend named operator==, an == operator function is declared implicitly
10989 // for each defaulted three-way comparison operator function defined in
10990 // the member-specification
10991 // FIXME: Consider doing this lazily.
10992 // We do this during the initial parse for a class template, not during
10993 // instantiation, so that we can handle unqualified lookups for 'operator=='
10994 // when parsing the template.
10995 if (getLangOpts().CPlusPlus20 && !inTemplateInstantiation()) {
10996 llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships;
10997 findImplicitlyDeclaredEqualityComparisons(Ctx&: Context, RD: ClassDecl,
10998 Spaceships&: DefaultedSpaceships);
10999 for (auto *FD : DefaultedSpaceships)
11000 DeclareImplicitEqualityComparison(RD: ClassDecl, Spaceship: FD);
11001 }
11002}
11003
11004unsigned
11005Sema::ActOnReenterTemplateScope(Decl *D,
11006 llvm::function_ref<Scope *()> EnterScope) {
11007 if (!D)
11008 return 0;
11009 AdjustDeclIfTemplate(Decl&: D);
11010
11011 // In order to get name lookup right, reenter template scopes in order from
11012 // outermost to innermost.
11013 SmallVector<TemplateParameterList *, 4> ParameterLists;
11014 DeclContext *LookupDC = dyn_cast<DeclContext>(Val: D);
11015
11016 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(Val: D)) {
11017 for (TemplateParameterList *TPL : DD->getTemplateParameterLists())
11018 ParameterLists.push_back(Elt: TPL);
11019
11020 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
11021 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
11022 ParameterLists.push_back(Elt: FTD->getTemplateParameters());
11023 } else if (VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
11024 LookupDC = VD->getDeclContext();
11025
11026 if (VarTemplateDecl *VTD = VD->getDescribedVarTemplate())
11027 ParameterLists.push_back(Elt: VTD->getTemplateParameters());
11028 else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(Val: D))
11029 ParameterLists.push_back(Elt: PSD->getTemplateParameters());
11030 }
11031 } else if (TagDecl *TD = dyn_cast<TagDecl>(Val: D)) {
11032 for (TemplateParameterList *TPL : TD->getTemplateParameterLists())
11033 ParameterLists.push_back(Elt: TPL);
11034
11035 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: TD)) {
11036 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
11037 ParameterLists.push_back(Elt: CTD->getTemplateParameters());
11038 else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(Val: D))
11039 ParameterLists.push_back(Elt: PSD->getTemplateParameters());
11040 }
11041 }
11042 // FIXME: Alias declarations and concepts.
11043
11044 unsigned Count = 0;
11045 Scope *InnermostTemplateScope = nullptr;
11046 for (TemplateParameterList *Params : ParameterLists) {
11047 // Ignore explicit specializations; they don't contribute to the template
11048 // depth.
11049 if (Params->size() == 0)
11050 continue;
11051
11052 InnermostTemplateScope = EnterScope();
11053 for (NamedDecl *Param : *Params) {
11054 if (Param->getDeclName()) {
11055 InnermostTemplateScope->AddDecl(D: Param);
11056 IdResolver.AddDecl(D: Param);
11057 }
11058 }
11059 ++Count;
11060 }
11061
11062 // Associate the new template scopes with the corresponding entities.
11063 if (InnermostTemplateScope) {
11064 assert(LookupDC && "no enclosing DeclContext for template lookup");
11065 EnterTemplatedContext(S: InnermostTemplateScope, DC: LookupDC);
11066 }
11067
11068 return Count;
11069}
11070
11071void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
11072 if (!RecordD) return;
11073 AdjustDeclIfTemplate(Decl&: RecordD);
11074 CXXRecordDecl *Record = cast<CXXRecordDecl>(Val: RecordD);
11075 PushDeclContext(S, DC: Record);
11076}
11077
11078void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
11079 if (!RecordD) return;
11080 PopDeclContext();
11081}
11082
11083void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
11084 if (!Param)
11085 return;
11086
11087 S->AddDecl(D: Param);
11088 if (Param->getDeclName())
11089 IdResolver.AddDecl(D: Param);
11090}
11091
11092void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
11093}
11094
11095/// ActOnDelayedCXXMethodParameter - We've already started a delayed
11096/// C++ method declaration. We're (re-)introducing the given
11097/// function parameter into scope for use in parsing later parts of
11098/// the method declaration. For example, we could see an
11099/// ActOnParamDefaultArgument event for this parameter.
11100void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
11101 if (!ParamD)
11102 return;
11103
11104 ParmVarDecl *Param = cast<ParmVarDecl>(Val: ParamD);
11105
11106 S->AddDecl(D: Param);
11107 if (Param->getDeclName())
11108 IdResolver.AddDecl(D: Param);
11109}
11110
11111void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
11112 if (!MethodD)
11113 return;
11114
11115 AdjustDeclIfTemplate(Decl&: MethodD);
11116
11117 FunctionDecl *Method = cast<FunctionDecl>(Val: MethodD);
11118
11119 // Now that we have our default arguments, check the constructor
11120 // again. It could produce additional diagnostics or affect whether
11121 // the class has implicitly-declared destructors, among other
11122 // things.
11123 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: Method))
11124 CheckConstructor(Constructor);
11125
11126 // Check the default arguments, which we may have added.
11127 if (!Method->isInvalidDecl())
11128 CheckCXXDefaultArguments(FD: Method);
11129}
11130
11131// Emit the given diagnostic for each non-address-space qualifier.
11132// Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
11133static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
11134 const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11135 if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
11136 bool DiagOccurred = false;
11137 FTI.MethodQualifiers->forEachQualifier(
11138 Handle: [DiagID, &S, &DiagOccurred](DeclSpec::TQ, StringRef QualName,
11139 SourceLocation SL) {
11140 // This diagnostic should be emitted on any qualifier except an addr
11141 // space qualifier. However, forEachQualifier currently doesn't visit
11142 // addr space qualifiers, so there's no way to write this condition
11143 // right now; we just diagnose on everything.
11144 S.Diag(Loc: SL, DiagID) << QualName << SourceRange(SL);
11145 DiagOccurred = true;
11146 });
11147 if (DiagOccurred)
11148 D.setInvalidType();
11149 }
11150}
11151
11152static void diagnoseInvalidDeclaratorChunks(Sema &S, Declarator &D,
11153 unsigned Kind) {
11154 if (D.isInvalidType() || D.getNumTypeObjects() <= 1)
11155 return;
11156
11157 DeclaratorChunk &Chunk = D.getTypeObject(i: D.getNumTypeObjects() - 1);
11158 if (Chunk.Kind == DeclaratorChunk::Paren ||
11159 Chunk.Kind == DeclaratorChunk::Function)
11160 return;
11161
11162 SourceLocation PointerLoc = Chunk.getSourceRange().getBegin();
11163 S.Diag(Loc: PointerLoc, DiagID: diag::err_invalid_ctor_dtor_decl)
11164 << Kind << Chunk.getSourceRange();
11165 D.setInvalidType();
11166}
11167
11168QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
11169 StorageClass &SC) {
11170 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
11171
11172 // C++ [class.ctor]p3:
11173 // A constructor shall not be virtual (10.3) or static (9.4). A
11174 // constructor can be invoked for a const, volatile or const
11175 // volatile object. A constructor shall not be declared const,
11176 // volatile, or const volatile (9.3.2).
11177 if (isVirtual) {
11178 if (!D.isInvalidType())
11179 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_constructor_cannot_be)
11180 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
11181 << SourceRange(D.getIdentifierLoc());
11182 D.setInvalidType();
11183 }
11184 if (SC == SC_Static) {
11185 if (!D.isInvalidType())
11186 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_constructor_cannot_be)
11187 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
11188 << SourceRange(D.getIdentifierLoc());
11189 D.setInvalidType();
11190 SC = SC_None;
11191 }
11192
11193 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
11194 diagnoseIgnoredQualifiers(
11195 DiagID: diag::err_constructor_return_type, Quals: TypeQuals, FallbackLoc: SourceLocation(),
11196 ConstQualLoc: D.getDeclSpec().getConstSpecLoc(), VolatileQualLoc: D.getDeclSpec().getVolatileSpecLoc(),
11197 RestrictQualLoc: D.getDeclSpec().getRestrictSpecLoc(),
11198 AtomicQualLoc: D.getDeclSpec().getAtomicSpecLoc());
11199 D.setInvalidType();
11200 }
11201
11202 checkMethodTypeQualifiers(S&: *this, D, DiagID: diag::err_invalid_qualified_constructor);
11203 diagnoseInvalidDeclaratorChunks(S&: *this, D, /*constructor*/ Kind: 0);
11204
11205 // C++0x [class.ctor]p4:
11206 // A constructor shall not be declared with a ref-qualifier.
11207 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11208 if (FTI.hasRefQualifier()) {
11209 Diag(Loc: FTI.getRefQualifierLoc(), DiagID: diag::err_ref_qualifier_constructor)
11210 << FTI.RefQualifierIsLValueRef
11211 << FixItHint::CreateRemoval(RemoveRange: FTI.getRefQualifierLoc());
11212 D.setInvalidType();
11213 }
11214
11215 // Rebuild the function type "R" without any type qualifiers (in
11216 // case any of the errors above fired) and with "void" as the
11217 // return type, since constructors don't have return types.
11218 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
11219 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
11220 return R;
11221
11222 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
11223 EPI.TypeQuals = Qualifiers();
11224 EPI.RefQualifier = RQ_None;
11225
11226 return Context.getFunctionType(ResultTy: Context.VoidTy, Args: Proto->getParamTypes(), EPI);
11227}
11228
11229void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
11230 CXXRecordDecl *ClassDecl
11231 = dyn_cast<CXXRecordDecl>(Val: Constructor->getDeclContext());
11232 if (!ClassDecl)
11233 return Constructor->setInvalidDecl();
11234
11235 // C++ [class.copy]p3:
11236 // A declaration of a constructor for a class X is ill-formed if
11237 // its first parameter is of type (optionally cv-qualified) X and
11238 // either there are no other parameters or else all other
11239 // parameters have default arguments.
11240 if (!Constructor->isInvalidDecl() &&
11241 Constructor->hasOneParamOrDefaultArgs() &&
11242 !Constructor->isFunctionTemplateSpecialization()) {
11243 CanQualType ParamType =
11244 Constructor->getParamDecl(i: 0)->getType()->getCanonicalTypeUnqualified();
11245 CanQualType ClassTy = Context.getCanonicalTagType(TD: ClassDecl);
11246 if (ParamType == ClassTy) {
11247 SourceLocation ParamLoc = Constructor->getParamDecl(i: 0)->getLocation();
11248 const char *ConstRef
11249 = Constructor->getParamDecl(i: 0)->getIdentifier() ? "const &"
11250 : " const &";
11251 Diag(Loc: ParamLoc, DiagID: diag::err_constructor_byvalue_arg)
11252 << FixItHint::CreateInsertion(InsertionLoc: ParamLoc, Code: ConstRef);
11253
11254 // FIXME: Rather that making the constructor invalid, we should endeavor
11255 // to fix the type.
11256 Constructor->setInvalidDecl();
11257 }
11258 }
11259}
11260
11261bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
11262 CXXRecordDecl *RD = Destructor->getParent();
11263
11264 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
11265 SourceLocation Loc;
11266
11267 if (!Destructor->isImplicit())
11268 Loc = Destructor->getLocation();
11269 else
11270 Loc = RD->getLocation();
11271
11272 DeclarationName Name =
11273 Context.DeclarationNames.getCXXOperatorName(Op: OO_Delete);
11274 // If we have a virtual destructor, look up the deallocation function
11275 if (FunctionDecl *OperatorDelete = FindDeallocationFunctionForDestructor(
11276 StartLoc: Loc, RD, /*Diagnose=*/true, /*LookForGlobal=*/false, Name)) {
11277 Expr *ThisArg = nullptr;
11278
11279 // If the notional 'delete this' expression requires a non-trivial
11280 // conversion from 'this' to the type of a destroying operator delete's
11281 // first parameter, perform that conversion now.
11282 if (OperatorDelete->isDestroyingOperatorDelete()) {
11283 unsigned AddressParamIndex = 0;
11284 if (OperatorDelete->isTypeAwareOperatorNewOrDelete())
11285 ++AddressParamIndex;
11286 QualType ParamType =
11287 OperatorDelete->getParamDecl(i: AddressParamIndex)->getType();
11288 if (!declaresSameEntity(D1: ParamType->getAsCXXRecordDecl(), D2: RD)) {
11289 // C++ [class.dtor]p13:
11290 // ... as if for the expression 'delete this' appearing in a
11291 // non-virtual destructor of the destructor's class.
11292 ContextRAII SwitchContext(*this, Destructor);
11293 ExprResult This = ActOnCXXThis(
11294 Loc: OperatorDelete->getParamDecl(i: AddressParamIndex)->getLocation());
11295 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
11296 This = PerformImplicitConversion(From: This.get(), ToType: ParamType,
11297 Action: AssignmentAction::Passing);
11298 if (This.isInvalid()) {
11299 // FIXME: Register this as a context note so that it comes out
11300 // in the right order.
11301 Diag(Loc, DiagID: diag::note_implicit_delete_this_in_destructor_here);
11302 return true;
11303 }
11304 ThisArg = This.get();
11305 }
11306 }
11307
11308 DiagnoseUseOfDecl(D: OperatorDelete, Locs: Loc);
11309 MarkFunctionReferenced(Loc, Func: OperatorDelete);
11310 Destructor->setOperatorDelete(OD: OperatorDelete, ThisArg);
11311
11312 if (isa<CXXMethodDecl>(Val: OperatorDelete) &&
11313 Context.getTargetInfo().callGlobalDeleteInDeletingDtor(
11314 Context.getLangOpts())) {
11315 // In Microsoft ABI whenever a class has a defined operator delete,
11316 // scalar deleting destructors check the 3rd bit of the implicit
11317 // parameter and if it is set, then, global operator delete must be
11318 // called instead of the class-specific one. Find and save the global
11319 // operator delete for that case. Do not diagnose at this point because
11320 // the lack of a global operator delete is not an error if there are no
11321 // delete calls that require it.
11322 FunctionDecl *GlobalOperatorDelete =
11323 FindDeallocationFunctionForDestructor(StartLoc: Loc, RD, /*Diagnose*/ false,
11324 /*LookForGlobal*/ true, Name);
11325 if (GlobalOperatorDelete) {
11326 MarkFunctionReferenced(Loc, Func: GlobalOperatorDelete);
11327 Destructor->setOperatorGlobalDelete(GlobalOperatorDelete);
11328 }
11329 }
11330
11331 if (Context.getTargetInfo().emitVectorDeletingDtors(
11332 Context.getLangOpts())) {
11333 bool DestructorIsExported = Destructor->hasAttr<DLLExportAttr>();
11334 // Lookup delete[] too in case we have to emit a vector deleting dtor.
11335 DeclarationName VDeleteName =
11336 Context.DeclarationNames.getCXXOperatorName(Op: OO_Array_Delete);
11337 FunctionDecl *ArrOperatorDelete = FindDeallocationFunctionForDestructor(
11338 StartLoc: Loc, RD, /*Diagnose*/ false,
11339 /*LookForGlobal*/ false, Name: VDeleteName);
11340 if (ArrOperatorDelete && isa<CXXMethodDecl>(Val: ArrOperatorDelete)) {
11341 FunctionDecl *GlobalArrOperatorDelete =
11342 FindDeallocationFunctionForDestructor(StartLoc: Loc, RD, /*Diagnose*/ false,
11343 /*LookForGlobal*/ true,
11344 Name: VDeleteName);
11345 Destructor->setGlobalOperatorArrayDelete(GlobalArrOperatorDelete);
11346 if (GlobalArrOperatorDelete &&
11347 (Context.classMaybeNeedsVectorDeletingDestructor(RD) ||
11348 DestructorIsExported))
11349 MarkFunctionReferenced(Loc, Func: GlobalArrOperatorDelete);
11350 } else if (!ArrOperatorDelete) {
11351 ArrOperatorDelete = FindDeallocationFunctionForDestructor(
11352 StartLoc: Loc, RD, /*Diagnose*/ false,
11353 /*LookForGlobal*/ true, Name: VDeleteName);
11354 }
11355 Destructor->setOperatorArrayDelete(ArrOperatorDelete);
11356 if (ArrOperatorDelete &&
11357 (Context.classMaybeNeedsVectorDeletingDestructor(RD) ||
11358 DestructorIsExported))
11359 MarkFunctionReferenced(Loc, Func: ArrOperatorDelete);
11360 }
11361 }
11362 }
11363
11364 return false;
11365}
11366
11367QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
11368 StorageClass& SC) {
11369 // C++ [class.dtor]p1:
11370 // [...] A typedef-name that names a class is a class-name
11371 // (7.1.3); however, a typedef-name that names a class shall not
11372 // be used as the identifier in the declarator for a destructor
11373 // declaration.
11374 QualType DeclaratorType = GetTypeFromParser(Ty: D.getName().DestructorName);
11375 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
11376 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::ext_destructor_typedef_name)
11377 << DeclaratorType << isa<TypeAliasDecl>(Val: TT->getDecl());
11378 else if (const TemplateSpecializationType *TST =
11379 DeclaratorType->getAs<TemplateSpecializationType>())
11380 if (TST->isTypeAlias())
11381 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::ext_destructor_typedef_name)
11382 << DeclaratorType << 1;
11383
11384 // C++ [class.dtor]p2:
11385 // A destructor is used to destroy objects of its class type. A
11386 // destructor takes no parameters, and no return type can be
11387 // specified for it (not even void). The address of a destructor
11388 // shall not be taken. A destructor shall not be static. A
11389 // destructor can be invoked for a const, volatile or const
11390 // volatile object. A destructor shall not be declared const,
11391 // volatile or const volatile (9.3.2).
11392 if (SC == SC_Static) {
11393 if (!D.isInvalidType())
11394 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_destructor_cannot_be)
11395 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
11396 << SourceRange(D.getIdentifierLoc())
11397 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
11398
11399 SC = SC_None;
11400 }
11401 if (!D.isInvalidType()) {
11402 // Destructors don't have return types, but the parser will
11403 // happily parse something like:
11404 //
11405 // class X {
11406 // float ~X();
11407 // };
11408 //
11409 // The return type will be eliminated later.
11410 if (D.getDeclSpec().hasTypeSpecifier())
11411 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_destructor_return_type)
11412 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
11413 << SourceRange(D.getIdentifierLoc());
11414 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
11415 diagnoseIgnoredQualifiers(DiagID: diag::err_destructor_return_type, Quals: TypeQuals,
11416 FallbackLoc: SourceLocation(),
11417 ConstQualLoc: D.getDeclSpec().getConstSpecLoc(),
11418 VolatileQualLoc: D.getDeclSpec().getVolatileSpecLoc(),
11419 RestrictQualLoc: D.getDeclSpec().getRestrictSpecLoc(),
11420 AtomicQualLoc: D.getDeclSpec().getAtomicSpecLoc());
11421 D.setInvalidType();
11422 }
11423 }
11424
11425 checkMethodTypeQualifiers(S&: *this, D, DiagID: diag::err_invalid_qualified_destructor);
11426 diagnoseInvalidDeclaratorChunks(S&: *this, D, /*destructor*/ Kind: 1);
11427
11428 // C++0x [class.dtor]p2:
11429 // A destructor shall not be declared with a ref-qualifier.
11430 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11431 if (FTI.hasRefQualifier()) {
11432 Diag(Loc: FTI.getRefQualifierLoc(), DiagID: diag::err_ref_qualifier_destructor)
11433 << FTI.RefQualifierIsLValueRef
11434 << FixItHint::CreateRemoval(RemoveRange: FTI.getRefQualifierLoc());
11435 D.setInvalidType();
11436 }
11437
11438 // Make sure we don't have any parameters.
11439 if (FTIHasNonVoidParameters(FTI)) {
11440 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_destructor_with_params);
11441
11442 // Delete the parameters.
11443 FTI.freeParams();
11444 D.setInvalidType();
11445 }
11446
11447 // Make sure the destructor isn't variadic.
11448 if (FTI.isVariadic) {
11449 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_destructor_variadic);
11450 D.setInvalidType();
11451 }
11452
11453 // Rebuild the function type "R" without any type qualifiers or
11454 // parameters (in case any of the errors above fired) and with
11455 // "void" as the return type, since destructors don't have return
11456 // types.
11457 if (!D.isInvalidType())
11458 return R;
11459
11460 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
11461 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
11462 EPI.Variadic = false;
11463 EPI.TypeQuals = Qualifiers();
11464 EPI.RefQualifier = RQ_None;
11465 return Context.getFunctionType(ResultTy: Context.VoidTy, Args: {}, EPI);
11466}
11467
11468static void extendLeft(SourceRange &R, SourceRange Before) {
11469 if (Before.isInvalid())
11470 return;
11471 R.setBegin(Before.getBegin());
11472 if (R.getEnd().isInvalid())
11473 R.setEnd(Before.getEnd());
11474}
11475
11476static void extendRight(SourceRange &R, SourceRange After) {
11477 if (After.isInvalid())
11478 return;
11479 if (R.getBegin().isInvalid())
11480 R.setBegin(After.getBegin());
11481 R.setEnd(After.getEnd());
11482}
11483
11484void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
11485 StorageClass& SC) {
11486 // C++ [class.conv.fct]p1:
11487 // Neither parameter types nor return type can be specified. The
11488 // type of a conversion function (8.3.5) is "function taking no
11489 // parameter returning conversion-type-id."
11490 if (SC == SC_Static) {
11491 if (!D.isInvalidType())
11492 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_conv_function_not_member)
11493 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
11494 << D.getName().getSourceRange();
11495 D.setInvalidType();
11496 SC = SC_None;
11497 }
11498
11499 TypeSourceInfo *ConvTSI = nullptr;
11500 QualType ConvType =
11501 GetTypeFromParser(Ty: D.getName().ConversionFunctionId, TInfo: &ConvTSI);
11502
11503 const DeclSpec &DS = D.getDeclSpec();
11504 if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
11505 // Conversion functions don't have return types, but the parser will
11506 // happily parse something like:
11507 //
11508 // class X {
11509 // float operator bool();
11510 // };
11511 //
11512 // The return type will be changed later anyway.
11513 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_conv_function_return_type)
11514 << SourceRange(DS.getTypeSpecTypeLoc())
11515 << SourceRange(D.getIdentifierLoc());
11516 D.setInvalidType();
11517 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
11518 // It's also plausible that the user writes type qualifiers in the wrong
11519 // place, such as:
11520 // struct S { const operator int(); };
11521 // FIXME: we could provide a fixit to move the qualifiers onto the
11522 // conversion type.
11523 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_conv_function_with_complex_decl)
11524 << SourceRange(D.getIdentifierLoc()) << 0;
11525 D.setInvalidType();
11526 }
11527 const auto *Proto = R->castAs<FunctionProtoType>();
11528 // Make sure we don't have any parameters.
11529 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11530 unsigned NumParam = Proto->getNumParams();
11531
11532 // [C++2b]
11533 // A conversion function shall have no non-object parameters.
11534 if (NumParam == 1) {
11535 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11536 if (const auto *First =
11537 dyn_cast_if_present<ParmVarDecl>(Val: FTI.Params[0].Param);
11538 First && First->isExplicitObjectParameter())
11539 NumParam--;
11540 }
11541
11542 if (NumParam != 0) {
11543 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_conv_function_with_params);
11544 // Delete the parameters.
11545 FTI.freeParams();
11546 D.setInvalidType();
11547 } else if (Proto->isVariadic()) {
11548 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_conv_function_variadic);
11549 D.setInvalidType();
11550 }
11551
11552 // Diagnose "&operator bool()" and other such nonsense. This
11553 // is actually a gcc extension which we don't support.
11554 if (Proto->getReturnType() != ConvType) {
11555 bool NeedsTypedef = false;
11556 SourceRange Before, After;
11557
11558 // Walk the chunks and extract information on them for our diagnostic.
11559 bool PastFunctionChunk = false;
11560 for (auto &Chunk : D.type_objects()) {
11561 switch (Chunk.Kind) {
11562 case DeclaratorChunk::Function:
11563 if (!PastFunctionChunk) {
11564 if (Chunk.Fun.HasTrailingReturnType) {
11565 TypeSourceInfo *TRT = nullptr;
11566 GetTypeFromParser(Ty: Chunk.Fun.getTrailingReturnType(), TInfo: &TRT);
11567 if (TRT) extendRight(R&: After, After: TRT->getTypeLoc().getSourceRange());
11568 }
11569 PastFunctionChunk = true;
11570 break;
11571 }
11572 [[fallthrough]];
11573 case DeclaratorChunk::Array:
11574 NeedsTypedef = true;
11575 extendRight(R&: After, After: Chunk.getSourceRange());
11576 break;
11577
11578 case DeclaratorChunk::Pointer:
11579 case DeclaratorChunk::BlockPointer:
11580 case DeclaratorChunk::Reference:
11581 case DeclaratorChunk::MemberPointer:
11582 case DeclaratorChunk::Pipe:
11583 extendLeft(R&: Before, Before: Chunk.getSourceRange());
11584 break;
11585
11586 case DeclaratorChunk::Paren:
11587 extendLeft(R&: Before, Before: Chunk.Loc);
11588 extendRight(R&: After, After: Chunk.EndLoc);
11589 break;
11590 }
11591 }
11592
11593 SourceLocation Loc = Before.isValid() ? Before.getBegin() :
11594 After.isValid() ? After.getBegin() :
11595 D.getIdentifierLoc();
11596 auto &&DB = Diag(Loc, DiagID: diag::err_conv_function_with_complex_decl);
11597 DB << Before << After;
11598
11599 if (!NeedsTypedef) {
11600 DB << /*don't need a typedef*/0;
11601
11602 // If we can provide a correct fix-it hint, do so.
11603 if (After.isInvalid() && ConvTSI) {
11604 SourceLocation InsertLoc =
11605 getLocForEndOfToken(Loc: ConvTSI->getTypeLoc().getEndLoc());
11606 DB << FixItHint::CreateInsertion(InsertionLoc: InsertLoc, Code: " ")
11607 << FixItHint::CreateInsertionFromRange(
11608 InsertionLoc: InsertLoc, FromRange: CharSourceRange::getTokenRange(R: Before))
11609 << FixItHint::CreateRemoval(RemoveRange: Before);
11610 }
11611 } else if (!Proto->getReturnType()->isDependentType()) {
11612 DB << /*typedef*/1 << Proto->getReturnType();
11613 } else if (getLangOpts().CPlusPlus11) {
11614 DB << /*alias template*/2 << Proto->getReturnType();
11615 } else {
11616 DB << /*might not be fixable*/3;
11617 }
11618
11619 // Recover by incorporating the other type chunks into the result type.
11620 // Note, this does *not* change the name of the function. This is compatible
11621 // with the GCC extension:
11622 // struct S { &operator int(); } s;
11623 // int &r = s.operator int(); // ok in GCC
11624 // S::operator int&() {} // error in GCC, function name is 'operator int'.
11625 ConvType = Proto->getReturnType();
11626 }
11627
11628 // C++ [class.conv.fct]p4:
11629 // The conversion-type-id shall not represent a function type nor
11630 // an array type.
11631 if (ConvType->isArrayType()) {
11632 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_conv_function_to_array);
11633 ConvType = Context.getPointerType(T: ConvType);
11634 D.setInvalidType();
11635 } else if (ConvType->isFunctionType()) {
11636 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_conv_function_to_function);
11637 ConvType = Context.getPointerType(T: ConvType);
11638 D.setInvalidType();
11639 }
11640
11641 // Rebuild the function type "R" without any parameters (in case any
11642 // of the errors above fired) and with the conversion type as the
11643 // return type.
11644 if (D.isInvalidType())
11645 R = Context.getFunctionType(ResultTy: ConvType, Args: {}, EPI: Proto->getExtProtoInfo());
11646
11647 // C++0x explicit conversion operators.
11648 if (DS.hasExplicitSpecifier())
11649 DiagCompat(Loc: DS.getExplicitSpecLoc(),
11650 CompatDiagId: diag_compat::explicit_conversion_functions)
11651 << SourceRange(DS.getExplicitSpecRange());
11652}
11653
11654Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
11655 assert(Conversion && "Expected to receive a conversion function declaration");
11656
11657 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Val: Conversion->getDeclContext());
11658
11659 // Make sure we aren't redeclaring the conversion function.
11660 QualType ConvType = Context.getCanonicalType(T: Conversion->getConversionType());
11661 // C++ [class.conv.fct]p1:
11662 // [...] A conversion function is never used to convert a
11663 // (possibly cv-qualified) object to the (possibly cv-qualified)
11664 // same object type (or a reference to it), to a (possibly
11665 // cv-qualified) base class of that type (or a reference to it),
11666 // or to (possibly cv-qualified) void.
11667 CanQualType ClassType = Context.getCanonicalTagType(TD: ClassDecl);
11668 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
11669 ConvType = ConvTypeRef->getPointeeType();
11670 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
11671 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
11672 /* Suppress diagnostics for instantiations. */;
11673 else if (Conversion->size_overridden_methods() != 0)
11674 /* Suppress diagnostics for overriding virtual function in a base class. */;
11675 else if (ConvType->isRecordType()) {
11676 ConvType = Context.getCanonicalType(T: ConvType).getUnqualifiedType();
11677 if (ConvType == ClassType)
11678 Diag(Loc: Conversion->getLocation(), DiagID: diag::warn_conv_to_self_not_used)
11679 << ClassType;
11680 else if (IsDerivedFrom(Loc: Conversion->getLocation(), Derived: ClassType, Base: ConvType))
11681 Diag(Loc: Conversion->getLocation(), DiagID: diag::warn_conv_to_base_not_used)
11682 << ClassType << ConvType;
11683 } else if (ConvType->isVoidType()) {
11684 Diag(Loc: Conversion->getLocation(), DiagID: diag::warn_conv_to_void_not_used)
11685 << ClassType << ConvType;
11686 }
11687
11688 if (FunctionTemplateDecl *ConversionTemplate =
11689 Conversion->getDescribedFunctionTemplate()) {
11690 if (const auto *ConvTypePtr = ConvType->getAs<PointerType>()) {
11691 ConvType = ConvTypePtr->getPointeeType();
11692 }
11693 if (ConvType->isUndeducedAutoType()) {
11694 Diag(Loc: Conversion->getTypeSpecStartLoc(), DiagID: diag::err_auto_not_allowed)
11695 << getReturnTypeLoc(FD: Conversion).getSourceRange()
11696 << ConvType->castAs<AutoType>()->getKeyword()
11697 << /* in declaration of conversion function template= */ 24;
11698 }
11699
11700 return ConversionTemplate;
11701 }
11702
11703 return Conversion;
11704}
11705
11706void Sema::CheckExplicitObjectMemberFunction(DeclContext *DC, Declarator &D,
11707 DeclarationName Name, QualType R) {
11708 CheckExplicitObjectMemberFunction(D, Name, R, IsLambda: false, DC);
11709}
11710
11711void Sema::CheckExplicitObjectLambda(Declarator &D) {
11712 CheckExplicitObjectMemberFunction(D, Name: {}, R: {}, IsLambda: true);
11713}
11714
11715void Sema::CheckExplicitObjectMemberFunction(Declarator &D,
11716 DeclarationName Name, QualType R,
11717 bool IsLambda, DeclContext *DC) {
11718 if (!D.isFunctionDeclarator())
11719 return;
11720
11721 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11722 if (FTI.NumParams == 0)
11723 return;
11724 ParmVarDecl *ExplicitObjectParam = nullptr;
11725 for (unsigned Idx = 0; Idx < FTI.NumParams; Idx++) {
11726 const auto &ParamInfo = FTI.Params[Idx];
11727 if (!ParamInfo.Param)
11728 continue;
11729 ParmVarDecl *Param = cast<ParmVarDecl>(Val: ParamInfo.Param);
11730 if (!Param->isExplicitObjectParameter())
11731 continue;
11732 if (Idx == 0) {
11733 ExplicitObjectParam = Param;
11734 continue;
11735 } else {
11736 Diag(Loc: Param->getLocation(),
11737 DiagID: diag::err_explicit_object_parameter_must_be_first)
11738 << IsLambda << Param->getSourceRange();
11739 }
11740 }
11741 if (!ExplicitObjectParam)
11742 return;
11743
11744 if (ExplicitObjectParam->hasDefaultArg()) {
11745 Diag(Loc: ExplicitObjectParam->getLocation(),
11746 DiagID: diag::err_explicit_object_default_arg)
11747 << ExplicitObjectParam->getSourceRange();
11748 D.setInvalidType();
11749 }
11750
11751 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static ||
11752 (D.getContext() == clang::DeclaratorContext::Member &&
11753 D.isStaticMember())) {
11754 Diag(Loc: ExplicitObjectParam->getBeginLoc(),
11755 DiagID: diag::err_explicit_object_parameter_nonmember)
11756 << D.getSourceRange() << /*static=*/0 << IsLambda;
11757 D.setInvalidType();
11758 }
11759
11760 if (D.getDeclSpec().isVirtualSpecified()) {
11761 Diag(Loc: ExplicitObjectParam->getBeginLoc(),
11762 DiagID: diag::err_explicit_object_parameter_nonmember)
11763 << D.getSourceRange() << /*virtual=*/1 << IsLambda;
11764 D.setInvalidType();
11765 }
11766
11767 // Friend declarations require some care. Consider:
11768 //
11769 // namespace N {
11770 // struct A{};
11771 // int f(A);
11772 // }
11773 //
11774 // struct S {
11775 // struct T {
11776 // int f(this T);
11777 // };
11778 //
11779 // friend int T::f(this T); // Allow this.
11780 // friend int f(this S); // But disallow this.
11781 // friend int N::f(this A); // And disallow this.
11782 // };
11783 //
11784 // Here, it seems to suffice to check whether the scope
11785 // specifier designates a class type.
11786 if (D.getDeclSpec().isFriendSpecified() &&
11787 !isa_and_present<CXXRecordDecl>(
11788 Val: computeDeclContext(SS: D.getCXXScopeSpec()))) {
11789 Diag(Loc: ExplicitObjectParam->getBeginLoc(),
11790 DiagID: diag::err_explicit_object_parameter_nonmember)
11791 << D.getSourceRange() << /*non-member=*/2 << IsLambda;
11792 D.setInvalidType();
11793 }
11794
11795 if (IsLambda && FTI.hasMutableQualifier()) {
11796 Diag(Loc: ExplicitObjectParam->getBeginLoc(),
11797 DiagID: diag::err_explicit_object_parameter_mutable)
11798 << D.getSourceRange();
11799 }
11800
11801 if (IsLambda)
11802 return;
11803
11804 if (!DC || !DC->isRecord()) {
11805 assert(D.isInvalidType() && "Explicit object parameter in non-member "
11806 "should have been diagnosed already");
11807 return;
11808 }
11809
11810 // CWG2674: constructors and destructors cannot have explicit parameters.
11811 if (Name.getNameKind() == DeclarationName::CXXConstructorName ||
11812 Name.getNameKind() == DeclarationName::CXXDestructorName) {
11813 Diag(Loc: ExplicitObjectParam->getBeginLoc(),
11814 DiagID: diag::err_explicit_object_parameter_constructor)
11815 << (Name.getNameKind() == DeclarationName::CXXDestructorName)
11816 << D.getSourceRange();
11817 D.setInvalidType();
11818 }
11819}
11820
11821namespace {
11822/// Utility class to accumulate and print a diagnostic listing the invalid
11823/// specifier(s) on a declaration.
11824struct BadSpecifierDiagnoser {
11825 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
11826 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
11827 ~BadSpecifierDiagnoser() {
11828 Diagnostic << Specifiers;
11829 }
11830
11831 template<typename T> void check(SourceLocation SpecLoc, T Spec) {
11832 return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
11833 }
11834 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
11835 return check(SpecLoc,
11836 Spec: DeclSpec::getSpecifierName(T: Spec, Policy: S.getPrintingPolicy()));
11837 }
11838 void check(SourceLocation SpecLoc, const char *Spec) {
11839 if (SpecLoc.isInvalid()) return;
11840 Diagnostic << SourceRange(SpecLoc, SpecLoc);
11841 if (!Specifiers.empty()) Specifiers += " ";
11842 Specifiers += Spec;
11843 }
11844
11845 Sema &S;
11846 Sema::SemaDiagnosticBuilder Diagnostic;
11847 std::string Specifiers;
11848};
11849}
11850
11851bool Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
11852 StorageClass &SC) {
11853 TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
11854 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
11855 assert(GuidedTemplateDecl && "missing template decl for deduction guide");
11856
11857 // C++ [temp.deduct.guide]p3:
11858 // A deduction-gide shall be declared in the same scope as the
11859 // corresponding class template.
11860 if (!CurContext->getRedeclContext()->Equals(
11861 DC: GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
11862 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_deduction_guide_wrong_scope)
11863 << GuidedTemplateDecl;
11864 NoteTemplateLocation(Decl: *GuidedTemplateDecl);
11865 }
11866
11867 auto &DS = D.getMutableDeclSpec();
11868 // We leave 'friend' and 'virtual' to be rejected in the normal way.
11869 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
11870 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
11871 DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
11872 BadSpecifierDiagnoser Diagnoser(
11873 *this, D.getIdentifierLoc(),
11874 diag::err_deduction_guide_invalid_specifier);
11875
11876 Diagnoser.check(SpecLoc: DS.getStorageClassSpecLoc(), Spec: DS.getStorageClassSpec());
11877 DS.ClearStorageClassSpecs();
11878 SC = SC_None;
11879
11880 // 'explicit' is permitted.
11881 Diagnoser.check(SpecLoc: DS.getInlineSpecLoc(), Spec: "inline");
11882 Diagnoser.check(SpecLoc: DS.getNoreturnSpecLoc(), Spec: "_Noreturn");
11883 Diagnoser.check(SpecLoc: DS.getConstexprSpecLoc(), Spec: "constexpr");
11884 DS.ClearConstexprSpec();
11885
11886 Diagnoser.check(SpecLoc: DS.getConstSpecLoc(), Spec: "const");
11887 Diagnoser.check(SpecLoc: DS.getRestrictSpecLoc(), Spec: "__restrict");
11888 Diagnoser.check(SpecLoc: DS.getVolatileSpecLoc(), Spec: "volatile");
11889 Diagnoser.check(SpecLoc: DS.getAtomicSpecLoc(), Spec: "_Atomic");
11890 Diagnoser.check(SpecLoc: DS.getUnalignedSpecLoc(), Spec: "__unaligned");
11891 DS.ClearTypeQualifiers();
11892
11893 Diagnoser.check(SpecLoc: DS.getTypeSpecComplexLoc(), Spec: DS.getTypeSpecComplex());
11894 Diagnoser.check(SpecLoc: DS.getTypeSpecSignLoc(), Spec: DS.getTypeSpecSign());
11895 Diagnoser.check(SpecLoc: DS.getTypeSpecWidthLoc(), Spec: DS.getTypeSpecWidth());
11896 Diagnoser.check(SpecLoc: DS.getTypeSpecTypeLoc(), Spec: DS.getTypeSpecType());
11897 DS.ClearTypeSpecType();
11898 }
11899
11900 if (D.isInvalidType())
11901 return true;
11902
11903 // Check the declarator is simple enough.
11904 bool FoundFunction = false;
11905 for (const DeclaratorChunk &Chunk : llvm::reverse(C: D.type_objects())) {
11906 if (Chunk.Kind == DeclaratorChunk::Paren)
11907 continue;
11908 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
11909 Diag(Loc: D.getDeclSpec().getBeginLoc(),
11910 DiagID: diag::err_deduction_guide_with_complex_decl)
11911 << D.getSourceRange();
11912 break;
11913 }
11914 if (!Chunk.Fun.hasTrailingReturnType())
11915 return Diag(Loc: D.getName().getBeginLoc(),
11916 DiagID: diag::err_deduction_guide_no_trailing_return_type);
11917
11918 // Check that the return type is written as a specialization of
11919 // the template specified as the deduction-guide's name.
11920 // The template name may not be qualified. [temp.deduct.guide]
11921 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
11922 TypeSourceInfo *TSI = nullptr;
11923 QualType RetTy = GetTypeFromParser(Ty: TrailingReturnType, TInfo: &TSI);
11924 assert(TSI && "deduction guide has valid type but invalid return type?");
11925 bool AcceptableReturnType = false;
11926 bool MightInstantiateToSpecialization = false;
11927 if (auto RetTST =
11928 TSI->getTypeLoc().getAsAdjusted<TemplateSpecializationTypeLoc>()) {
11929 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
11930 bool TemplateMatches = Context.hasSameTemplateName(
11931 X: SpecifiedName, Y: GuidedTemplate, /*IgnoreDeduced=*/true);
11932
11933 const QualifiedTemplateName *Qualifiers =
11934 SpecifiedName.getAsQualifiedTemplateName();
11935 // A Template template parameter is never wrapped in a
11936 // QualifiedTemplateName, but it's always simply-written.
11937 bool SimplyWritten = !Qualifiers || (!Qualifiers->hasTemplateKeyword() &&
11938 !Qualifiers->getQualifier());
11939 if (SimplyWritten && TemplateMatches)
11940 AcceptableReturnType = true;
11941 else {
11942 // This could still instantiate to the right type, unless we know it
11943 // names the wrong class template.
11944 auto *TD = SpecifiedName.getAsTemplateDecl();
11945 MightInstantiateToSpecialization =
11946 !(TD && isa<ClassTemplateDecl>(Val: TD) && !TemplateMatches);
11947 }
11948 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
11949 MightInstantiateToSpecialization = true;
11950 }
11951
11952 if (!AcceptableReturnType)
11953 return Diag(Loc: TSI->getTypeLoc().getBeginLoc(),
11954 DiagID: diag::err_deduction_guide_bad_trailing_return_type)
11955 << GuidedTemplate << TSI->getType()
11956 << MightInstantiateToSpecialization
11957 << TSI->getTypeLoc().getSourceRange();
11958
11959 // Keep going to check that we don't have any inner declarator pieces (we
11960 // could still have a function returning a pointer to a function).
11961 FoundFunction = true;
11962 }
11963
11964 if (D.isFunctionDefinition())
11965 // we can still create a valid deduction guide here.
11966 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_deduction_guide_defines_function);
11967 return false;
11968}
11969
11970//===----------------------------------------------------------------------===//
11971// Namespace Handling
11972//===----------------------------------------------------------------------===//
11973
11974/// Diagnose a mismatch in 'inline' qualifiers when a namespace is
11975/// reopened.
11976static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
11977 SourceLocation Loc,
11978 IdentifierInfo *II, bool *IsInline,
11979 NamespaceDecl *PrevNS) {
11980 assert(*IsInline != PrevNS->isInline());
11981
11982 // 'inline' must appear on the original definition, but not necessarily
11983 // on all extension definitions, so the note should point to the first
11984 // definition to avoid confusion.
11985 PrevNS = PrevNS->getFirstDecl();
11986
11987 if (PrevNS->isInline())
11988 // The user probably just forgot the 'inline', so suggest that it
11989 // be added back.
11990 S.Diag(Loc, DiagID: diag::warn_inline_namespace_reopened_noninline)
11991 << FixItHint::CreateInsertion(InsertionLoc: KeywordLoc, Code: "inline ");
11992 else
11993 S.Diag(Loc, DiagID: diag::err_inline_namespace_mismatch);
11994
11995 S.Diag(Loc: PrevNS->getLocation(), DiagID: diag::note_previous_definition);
11996 *IsInline = PrevNS->isInline();
11997}
11998
11999/// ActOnStartNamespaceDef - This is called at the start of a namespace
12000/// definition.
12001Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
12002 SourceLocation InlineLoc,
12003 SourceLocation NamespaceLoc,
12004 SourceLocation IdentLoc, IdentifierInfo *II,
12005 SourceLocation LBrace,
12006 const ParsedAttributesView &AttrList,
12007 UsingDirectiveDecl *&UD, bool IsNested) {
12008 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
12009 // For anonymous namespace, take the location of the left brace.
12010 SourceLocation Loc = II ? IdentLoc : LBrace;
12011 bool IsInline = InlineLoc.isValid();
12012 bool IsInvalid = false;
12013 bool IsStd = false;
12014 bool AddToKnown = false;
12015 Scope *DeclRegionScope = NamespcScope->getParent();
12016
12017 NamespaceDecl *PrevNS = nullptr;
12018 if (II) {
12019 // C++ [namespace.std]p7:
12020 // A translation unit shall not declare namespace std to be an inline
12021 // namespace (9.8.2).
12022 //
12023 // Precondition: the std namespace is in the file scope and is declared to
12024 // be inline
12025 auto DiagnoseInlineStdNS = [&]() {
12026 assert(IsInline && II->isStr("std") &&
12027 CurContext->getRedeclContext()->isTranslationUnit() &&
12028 "Precondition of DiagnoseInlineStdNS not met");
12029 Diag(Loc: InlineLoc, DiagID: diag::err_inline_namespace_std)
12030 << SourceRange(InlineLoc, InlineLoc.getLocWithOffset(Offset: 6));
12031 IsInline = false;
12032 };
12033 // C++ [namespace.def]p2:
12034 // The identifier in an original-namespace-definition shall not
12035 // have been previously defined in the declarative region in
12036 // which the original-namespace-definition appears. The
12037 // identifier in an original-namespace-definition is the name of
12038 // the namespace. Subsequently in that declarative region, it is
12039 // treated as an original-namespace-name.
12040 //
12041 // Since namespace names are unique in their scope, and we don't
12042 // look through using directives, just look for any ordinary names
12043 // as if by qualified name lookup.
12044 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
12045 RedeclarationKind::ForExternalRedeclaration);
12046 LookupQualifiedName(R, LookupCtx: CurContext->getRedeclContext());
12047 NamedDecl *PrevDecl =
12048 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
12049 PrevNS = dyn_cast_or_null<NamespaceDecl>(Val: PrevDecl);
12050
12051 if (PrevNS) {
12052 // This is an extended namespace definition.
12053 if (IsInline && II->isStr(Str: "std") &&
12054 CurContext->getRedeclContext()->isTranslationUnit())
12055 DiagnoseInlineStdNS();
12056 else if (IsInline != PrevNS->isInline())
12057 DiagnoseNamespaceInlineMismatch(S&: *this, KeywordLoc: NamespaceLoc, Loc, II,
12058 IsInline: &IsInline, PrevNS);
12059 } else if (PrevDecl) {
12060 // This is an invalid name redefinition.
12061 Diag(Loc, DiagID: diag::err_redefinition_different_kind)
12062 << II;
12063 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_definition);
12064 IsInvalid = true;
12065 // Continue on to push Namespc as current DeclContext and return it.
12066 } else if (II->isStr(Str: "std") &&
12067 CurContext->getRedeclContext()->isTranslationUnit()) {
12068 if (IsInline)
12069 DiagnoseInlineStdNS();
12070 // This is the first "real" definition of the namespace "std", so update
12071 // our cache of the "std" namespace to point at this definition.
12072 PrevNS = getStdNamespace();
12073 IsStd = true;
12074 AddToKnown = !IsInline;
12075 } else {
12076 // We've seen this namespace for the first time.
12077 AddToKnown = !IsInline;
12078 }
12079 } else {
12080 // Anonymous namespaces.
12081
12082 // Determine whether the parent already has an anonymous namespace.
12083 DeclContext *Parent = CurContext->getRedeclContext();
12084 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Val: Parent)) {
12085 PrevNS = TU->getAnonymousNamespace();
12086 } else {
12087 NamespaceDecl *ND = cast<NamespaceDecl>(Val: Parent);
12088 PrevNS = ND->getAnonymousNamespace();
12089 }
12090
12091 if (PrevNS && IsInline != PrevNS->isInline())
12092 DiagnoseNamespaceInlineMismatch(S&: *this, KeywordLoc: NamespaceLoc, Loc: NamespaceLoc, II,
12093 IsInline: &IsInline, PrevNS);
12094 }
12095
12096 NamespaceDecl *Namespc = NamespaceDecl::Create(
12097 C&: Context, DC: CurContext, Inline: IsInline, StartLoc, IdLoc: Loc, Id: II, PrevDecl: PrevNS, Nested: IsNested);
12098 if (IsInvalid)
12099 Namespc->setInvalidDecl();
12100
12101 ProcessDeclAttributeList(S: DeclRegionScope, D: Namespc, AttrList);
12102 AddPragmaAttributes(S: DeclRegionScope, D: Namespc);
12103 ProcessAPINotes(D: Namespc);
12104
12105 // FIXME: Should we be merging attributes?
12106 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
12107 PushNamespaceVisibilityAttr(Attr, Loc);
12108
12109 if (IsStd)
12110 StdNamespace = Namespc;
12111 if (AddToKnown)
12112 KnownNamespaces[Namespc] = false;
12113
12114 if (II) {
12115 PushOnScopeChains(D: Namespc, S: DeclRegionScope);
12116 } else {
12117 // Link the anonymous namespace into its parent.
12118 DeclContext *Parent = CurContext->getRedeclContext();
12119 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Val: Parent)) {
12120 TU->setAnonymousNamespace(Namespc);
12121 } else {
12122 cast<NamespaceDecl>(Val: Parent)->setAnonymousNamespace(Namespc);
12123 }
12124
12125 CurContext->addDecl(D: Namespc);
12126
12127 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
12128 // behaves as if it were replaced by
12129 // namespace unique { /* empty body */ }
12130 // using namespace unique;
12131 // namespace unique { namespace-body }
12132 // where all occurrences of 'unique' in a translation unit are
12133 // replaced by the same identifier and this identifier differs
12134 // from all other identifiers in the entire program.
12135
12136 // We just create the namespace with an empty name and then add an
12137 // implicit using declaration, just like the standard suggests.
12138 //
12139 // CodeGen enforces the "universally unique" aspect by giving all
12140 // declarations semantically contained within an anonymous
12141 // namespace internal linkage.
12142
12143 if (!PrevNS) {
12144 UD = UsingDirectiveDecl::Create(C&: Context, DC: Parent,
12145 /* 'using' */ UsingLoc: LBrace,
12146 /* 'namespace' */ NamespaceLoc: SourceLocation(),
12147 /* qualifier */ QualifierLoc: NestedNameSpecifierLoc(),
12148 /* identifier */ IdentLoc: SourceLocation(),
12149 Nominated: Namespc,
12150 /* Ancestor */ CommonAncestor: Parent);
12151 UD->setImplicit();
12152 Parent->addDecl(D: UD);
12153 }
12154 }
12155
12156 ActOnDocumentableDecl(D: Namespc);
12157
12158 // Although we could have an invalid decl (i.e. the namespace name is a
12159 // redefinition), push it as current DeclContext and try to continue parsing.
12160 // FIXME: We should be able to push Namespc here, so that the each DeclContext
12161 // for the namespace has the declarations that showed up in that particular
12162 // namespace definition.
12163 PushDeclContext(S: NamespcScope, DC: Namespc);
12164 return Namespc;
12165}
12166
12167/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
12168/// is a namespace alias, returns the namespace it points to.
12169static inline NamespaceDecl *getNamespaceDecl(NamespaceBaseDecl *D) {
12170 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(Val: D))
12171 return AD->getNamespace();
12172 return dyn_cast_or_null<NamespaceDecl>(Val: D);
12173}
12174
12175void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
12176 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Val: Dcl);
12177 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
12178 Namespc->setRBraceLoc(RBrace);
12179 PopDeclContext();
12180 if (Namespc->hasAttr<VisibilityAttr>())
12181 PopPragmaVisibility(IsNamespaceEnd: true, EndLoc: RBrace);
12182 // If this namespace contains an export-declaration, export it now.
12183 if (DeferredExportedNamespaces.erase(Ptr: Namespc))
12184 Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
12185}
12186
12187CXXRecordDecl *Sema::getStdBadAlloc() const {
12188 return cast_or_null<CXXRecordDecl>(
12189 Val: StdBadAlloc.get(Source: Context.getExternalSource()));
12190}
12191
12192EnumDecl *Sema::getStdAlignValT() const {
12193 return cast_or_null<EnumDecl>(Val: StdAlignValT.get(Source: Context.getExternalSource()));
12194}
12195
12196NamespaceDecl *Sema::getStdNamespace() const {
12197 return cast_or_null<NamespaceDecl>(
12198 Val: StdNamespace.get(Source: Context.getExternalSource()));
12199}
12200
12201namespace {
12202
12203enum UnsupportedSTLSelect {
12204 USS_InvalidMember,
12205 USS_MissingMember,
12206 USS_NonTrivial,
12207 USS_Other
12208};
12209
12210struct InvalidSTLDiagnoser {
12211 Sema &S;
12212 SourceLocation Loc;
12213 QualType TyForDiags;
12214
12215 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
12216 const VarDecl *VD = nullptr) {
12217 {
12218 auto D = S.Diag(Loc, DiagID: diag::err_std_compare_type_not_supported)
12219 << TyForDiags << ((int)Sel);
12220 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
12221 assert(!Name.empty());
12222 D << Name;
12223 }
12224 }
12225 if (Sel == USS_InvalidMember) {
12226 S.Diag(Loc: VD->getLocation(), DiagID: diag::note_var_declared_here)
12227 << VD << VD->getSourceRange();
12228 }
12229 return QualType();
12230 }
12231};
12232} // namespace
12233
12234QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
12235 SourceLocation Loc,
12236 ComparisonCategoryUsage Usage) {
12237 assert(getLangOpts().CPlusPlus &&
12238 "Looking for comparison category type outside of C++.");
12239
12240 // Use an elaborated type for diagnostics which has a name containing the
12241 // prepended 'std' namespace but not any inline namespace names.
12242 auto TyForDiags = [&](ComparisonCategoryInfo *Info) {
12243 NestedNameSpecifier Qualifier(Context, getStdNamespace(),
12244 /*Prefix=*/std::nullopt);
12245 return Context.getTagType(Keyword: ElaboratedTypeKeyword::None, Qualifier,
12246 TD: Info->Record,
12247 /*OwnsTag=*/false);
12248 };
12249
12250 // Check if we've already successfully checked the comparison category type
12251 // before. If so, skip checking it again.
12252 ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
12253 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) {
12254 // The only thing we need to check is that the type has a reachable
12255 // definition in the current context.
12256 if (RequireCompleteType(Loc, T: TyForDiags(Info), DiagID: diag::err_incomplete_type))
12257 return QualType();
12258
12259 return Info->getType();
12260 }
12261
12262 // If lookup failed
12263 if (!Info) {
12264 std::string NameForDiags = "std::";
12265 NameForDiags += ComparisonCategories::getCategoryString(Kind);
12266 Diag(Loc, DiagID: diag::err_implied_comparison_category_type_not_found)
12267 << NameForDiags << (int)Usage;
12268 return QualType();
12269 }
12270
12271 assert(Info->Kind == Kind);
12272 assert(Info->Record);
12273
12274 // Update the Record decl in case we encountered a forward declaration on our
12275 // first pass. FIXME: This is a bit of a hack.
12276 if (Info->Record->hasDefinition())
12277 Info->Record = Info->Record->getDefinition();
12278
12279 if (RequireCompleteType(Loc, T: TyForDiags(Info), DiagID: diag::err_incomplete_type))
12280 return QualType();
12281
12282 InvalidSTLDiagnoser UnsupportedSTLError{.S: *this, .Loc: Loc, .TyForDiags: TyForDiags(Info)};
12283
12284 if (!Info->Record->isTriviallyCopyable())
12285 return UnsupportedSTLError(USS_NonTrivial);
12286
12287 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
12288 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
12289 // Tolerate empty base classes.
12290 if (Base->isEmpty())
12291 continue;
12292 // Reject STL implementations which have at least one non-empty base.
12293 return UnsupportedSTLError();
12294 }
12295
12296 // Check that the STL has implemented the types using a single integer field.
12297 // This expectation allows better codegen for builtin operators. We require:
12298 // (1) The class has exactly one field.
12299 // (2) The field is an integral or enumeration type.
12300 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
12301 if (std::distance(first: FIt, last: FEnd) != 1 ||
12302 !FIt->getType()->isIntegralOrEnumerationType()) {
12303 return UnsupportedSTLError();
12304 }
12305
12306 // Build each of the require values and store them in Info.
12307 for (ComparisonCategoryResult CCR :
12308 ComparisonCategories::getPossibleResultsForType(Type: Kind)) {
12309 StringRef MemName = ComparisonCategories::getResultString(Kind: CCR);
12310 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(ValueKind: CCR);
12311
12312 if (!ValInfo)
12313 return UnsupportedSTLError(USS_MissingMember, MemName);
12314
12315 VarDecl *VD = ValInfo->VD;
12316 assert(VD && "should not be null!");
12317
12318 // Attempt to diagnose reasons why the STL definition of this type
12319 // might be foobar, including it failing to be a constant expression.
12320 // TODO Handle more ways the lookup or result can be invalid.
12321 if (!VD->isStaticDataMember() ||
12322 !VD->isUsableInConstantExpressions(C: Context))
12323 return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
12324
12325 // Attempt to evaluate the var decl as a constant expression and extract
12326 // the value of its first field as a ICE. If this fails, the STL
12327 // implementation is not supported.
12328 if (!ValInfo->hasValidIntValue())
12329 return UnsupportedSTLError();
12330
12331 MarkVariableReferenced(Loc, Var: VD);
12332 }
12333
12334 // We've successfully built the required types and expressions. Update
12335 // the cache and return the newly cached value.
12336 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
12337 return Info->getType();
12338}
12339
12340NamespaceDecl *Sema::getOrCreateStdNamespace() {
12341 if (!StdNamespace) {
12342 // The "std" namespace has not yet been defined, so build one implicitly.
12343 StdNamespace = NamespaceDecl::Create(
12344 C&: Context, DC: Context.getTranslationUnitDecl(),
12345 /*Inline=*/false, StartLoc: SourceLocation(), IdLoc: SourceLocation(),
12346 Id: &PP.getIdentifierTable().get(Name: "std"),
12347 /*PrevDecl=*/nullptr, /*Nested=*/false);
12348 getStdNamespace()->setImplicit(true);
12349 // We want the created NamespaceDecl to be available for redeclaration
12350 // lookups, but not for regular name lookups.
12351 Context.getTranslationUnitDecl()->addDecl(D: getStdNamespace());
12352 getStdNamespace()->clearIdentifierNamespace();
12353 }
12354
12355 return getStdNamespace();
12356}
12357
12358static bool isStdClassTemplate(Sema &S, QualType SugaredType, QualType *TypeArg,
12359 const char *ClassName,
12360 ClassTemplateDecl **CachedDecl,
12361 const Decl **MalformedDecl) {
12362 // We're looking for implicit instantiations of
12363 // template <typename U> class std::{ClassName}.
12364
12365 if (!S.StdNamespace) // If we haven't seen namespace std yet, this can't be
12366 // it.
12367 return false;
12368
12369 auto ReportMatchingNameAsMalformed = [&](NamedDecl *D) {
12370 if (!MalformedDecl)
12371 return;
12372 if (!D)
12373 D = SugaredType->getAsTagDecl();
12374 if (!D || !D->isInStdNamespace())
12375 return;
12376 IdentifierInfo *II = D->getDeclName().getAsIdentifierInfo();
12377 if (II && II == &S.PP.getIdentifierTable().get(Name: ClassName))
12378 *MalformedDecl = D;
12379 };
12380
12381 ClassTemplateDecl *Template = nullptr;
12382 ArrayRef<TemplateArgument> Arguments;
12383 if (const TemplateSpecializationType *TST =
12384 SugaredType->getAsNonAliasTemplateSpecializationType()) {
12385 Template = dyn_cast_or_null<ClassTemplateDecl>(
12386 Val: TST->getTemplateName().getAsTemplateDecl());
12387 Arguments = TST->template_arguments();
12388 } else if (const auto *TT = SugaredType->getAs<TagType>()) {
12389 Template = TT->getTemplateDecl();
12390 Arguments = TT->getTemplateArgs(Ctx: S.Context);
12391 }
12392
12393 if (!Template) {
12394 ReportMatchingNameAsMalformed(SugaredType->getAsTagDecl());
12395 return false;
12396 }
12397
12398 if (!*CachedDecl) {
12399 // Haven't recognized std::{ClassName} yet, maybe this is it.
12400 // FIXME: It seems we should just reuse LookupStdClassTemplate but the
12401 // semantics of this are slightly different, most notably the existing
12402 // "lookup" semantics explicitly diagnose an invalid definition as an
12403 // error.
12404 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
12405 if (TemplateClass->getIdentifier() !=
12406 &S.PP.getIdentifierTable().get(Name: ClassName) ||
12407 !S.getStdNamespace()->InEnclosingNamespaceSetOf(
12408 NS: TemplateClass->getNonTransparentDeclContext()))
12409 return false;
12410 // This is a template called std::{ClassName}, but is it the right
12411 // template?
12412 TemplateParameterList *Params = Template->getTemplateParameters();
12413 if (Params->getMinRequiredArguments() != 1 ||
12414 !isa<TemplateTypeParmDecl>(Val: Params->getParam(Idx: 0)) ||
12415 Params->getParam(Idx: 0)->isTemplateParameterPack()) {
12416 if (MalformedDecl)
12417 *MalformedDecl = TemplateClass;
12418 return false;
12419 }
12420
12421 // It's the right template.
12422 *CachedDecl = Template;
12423 }
12424
12425 if (Template->getCanonicalDecl() != (*CachedDecl)->getCanonicalDecl())
12426 return false;
12427
12428 // This is an instance of std::{ClassName}. Find the argument type.
12429 if (TypeArg) {
12430 QualType ArgType = Arguments[0].getAsType();
12431 // FIXME: Since TST only has as-written arguments, we have to perform the
12432 // only kind of conversion applicable to type arguments; in Objective-C ARC:
12433 // - If an explicitly-specified template argument type is a lifetime type
12434 // with no lifetime qualifier, the __strong lifetime qualifier is
12435 // inferred.
12436 if (S.getLangOpts().ObjCAutoRefCount && ArgType->isObjCLifetimeType() &&
12437 !ArgType.getObjCLifetime()) {
12438 Qualifiers Qs;
12439 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
12440 ArgType = S.Context.getQualifiedType(T: ArgType, Qs);
12441 }
12442 *TypeArg = ArgType;
12443 }
12444
12445 return true;
12446}
12447
12448bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
12449 assert(getLangOpts().CPlusPlus &&
12450 "Looking for std::initializer_list outside of C++.");
12451
12452 // We're looking for implicit instantiations of
12453 // template <typename E> class std::initializer_list.
12454
12455 return isStdClassTemplate(S&: *this, SugaredType: Ty, TypeArg: Element, ClassName: "initializer_list",
12456 CachedDecl: &StdInitializerList, /*MalformedDecl=*/nullptr);
12457}
12458
12459bool Sema::isStdTypeIdentity(QualType Ty, QualType *Element,
12460 const Decl **MalformedDecl) {
12461 assert(getLangOpts().CPlusPlus &&
12462 "Looking for std::type_identity outside of C++.");
12463
12464 // We're looking for implicit instantiations of
12465 // template <typename T> struct std::type_identity.
12466
12467 return isStdClassTemplate(S&: *this, SugaredType: Ty, TypeArg: Element, ClassName: "type_identity",
12468 CachedDecl: &StdTypeIdentity, MalformedDecl);
12469}
12470
12471static ClassTemplateDecl *LookupStdClassTemplate(Sema &S, SourceLocation Loc,
12472 const char *ClassName,
12473 bool *WasMalformed) {
12474 if (!S.StdNamespace)
12475 return nullptr;
12476
12477 LookupResult Result(S, &S.PP.getIdentifierTable().get(Name: ClassName), Loc,
12478 Sema::LookupOrdinaryName);
12479 if (!S.LookupQualifiedName(R&: Result, LookupCtx: S.getStdNamespace()))
12480 return nullptr;
12481
12482 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
12483 if (!Template) {
12484 Result.suppressDiagnostics();
12485 // We found something weird. Complain about the first thing we found.
12486 NamedDecl *Found = *Result.begin();
12487 S.Diag(Loc: Found->getLocation(), DiagID: diag::err_malformed_std_class_template)
12488 << ClassName;
12489 if (WasMalformed)
12490 *WasMalformed = true;
12491 return nullptr;
12492 }
12493
12494 // We found some template with the correct name. Now verify that it's
12495 // correct.
12496 TemplateParameterList *Params = Template->getTemplateParameters();
12497 if (Params->getMinRequiredArguments() != 1 ||
12498 !isa<TemplateTypeParmDecl>(Val: Params->getParam(Idx: 0))) {
12499 S.Diag(Loc: Template->getLocation(), DiagID: diag::err_malformed_std_class_template)
12500 << ClassName;
12501 if (WasMalformed)
12502 *WasMalformed = true;
12503 return nullptr;
12504 }
12505
12506 return Template;
12507}
12508
12509static QualType BuildStdClassTemplate(Sema &S, ClassTemplateDecl *CTD,
12510 QualType TypeParam, SourceLocation Loc) {
12511 assert(S.getStdNamespace());
12512 TemplateArgumentListInfo Args(Loc, Loc);
12513 auto TSI = S.Context.getTrivialTypeSourceInfo(T: TypeParam, Loc);
12514 Args.addArgument(Loc: TemplateArgumentLoc(TemplateArgument(TypeParam), TSI));
12515
12516 return S.CheckTemplateIdType(Keyword: ElaboratedTypeKeyword::None, Template: TemplateName(CTD),
12517 TemplateLoc: Loc, TemplateArgs&: Args, /*Scope=*/nullptr,
12518 /*ForNestedNameSpecifier=*/false);
12519}
12520
12521QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
12522 if (!StdInitializerList) {
12523 bool WasMalformed = false;
12524 StdInitializerList =
12525 LookupStdClassTemplate(S&: *this, Loc, ClassName: "initializer_list", WasMalformed: &WasMalformed);
12526 if (!StdInitializerList) {
12527 if (!WasMalformed)
12528 Diag(Loc, DiagID: diag::err_implied_std_initializer_list_not_found);
12529 return QualType();
12530 }
12531 }
12532 return BuildStdClassTemplate(S&: *this, CTD: StdInitializerList, TypeParam: Element, Loc);
12533}
12534
12535QualType Sema::tryBuildStdTypeIdentity(QualType Type, SourceLocation Loc) {
12536 if (!StdTypeIdentity) {
12537 StdTypeIdentity = LookupStdClassTemplate(S&: *this, Loc, ClassName: "type_identity",
12538 /*WasMalformed=*/nullptr);
12539 if (!StdTypeIdentity)
12540 return QualType();
12541 }
12542 return BuildStdClassTemplate(S&: *this, CTD: StdTypeIdentity, TypeParam: Type, Loc);
12543}
12544
12545bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
12546 // C++ [dcl.init.list]p2:
12547 // A constructor is an initializer-list constructor if its first parameter
12548 // is of type std::initializer_list<E> or reference to possibly cv-qualified
12549 // std::initializer_list<E> for some type E, and either there are no other
12550 // parameters or else all other parameters have default arguments.
12551 if (!Ctor->hasOneParamOrDefaultArgs())
12552 return false;
12553
12554 QualType ArgType = Ctor->getParamDecl(i: 0)->getType();
12555 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
12556 ArgType = RT->getPointeeType().getUnqualifiedType();
12557
12558 return isStdInitializerList(Ty: ArgType, Element: nullptr);
12559}
12560
12561/// Determine whether a using statement is in a context where it will be
12562/// apply in all contexts.
12563static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
12564 switch (CurContext->getDeclKind()) {
12565 case Decl::TranslationUnit:
12566 return true;
12567 case Decl::LinkageSpec:
12568 return IsUsingDirectiveInToplevelContext(CurContext: CurContext->getParent());
12569 default:
12570 return false;
12571 }
12572}
12573
12574namespace {
12575
12576// Callback to only accept typo corrections that are namespaces.
12577class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
12578public:
12579 bool ValidateCandidate(const TypoCorrection &candidate) override {
12580 if (NamedDecl *ND = candidate.getCorrectionDecl())
12581 return isa<NamespaceDecl>(Val: ND) || isa<NamespaceAliasDecl>(Val: ND);
12582 return false;
12583 }
12584
12585 std::unique_ptr<CorrectionCandidateCallback> clone() override {
12586 return std::make_unique<NamespaceValidatorCCC>(args&: *this);
12587 }
12588};
12589
12590}
12591
12592static void DiagnoseInvisibleNamespace(const TypoCorrection &Corrected,
12593 Sema &S) {
12594 auto *ND = cast<NamespaceDecl>(Val: Corrected.getFoundDecl());
12595 Module *M = ND->getOwningModule();
12596 assert(M && "hidden namespace definition not in a module?");
12597
12598 if (M->isExplicitGlobalModule())
12599 S.Diag(Loc: Corrected.getCorrectionRange().getBegin(),
12600 DiagID: diag::err_module_unimported_use_header)
12601 << (int)Sema::MissingImportKind::Declaration << Corrected.getFoundDecl()
12602 << /*Header Name*/ false;
12603 else
12604 S.Diag(Loc: Corrected.getCorrectionRange().getBegin(),
12605 DiagID: diag::err_module_unimported_use)
12606 << (int)Sema::MissingImportKind::Declaration << Corrected.getFoundDecl()
12607 << M->getTopLevelModuleName();
12608}
12609
12610static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
12611 CXXScopeSpec &SS,
12612 SourceLocation IdentLoc,
12613 IdentifierInfo *Ident) {
12614 R.clear();
12615 NamespaceValidatorCCC CCC{};
12616 if (TypoCorrection Corrected =
12617 S.CorrectTypo(Typo: R.getLookupNameInfo(), LookupKind: R.getLookupKind(), S: Sc, SS: &SS, CCC,
12618 Mode: CorrectTypoKind::ErrorRecovery)) {
12619 // Generally we find it is confusing more than helpful to diagnose the
12620 // invisible namespace.
12621 // See https://github.com/llvm/llvm-project/issues/73893.
12622 //
12623 // However, we should diagnose when the users are trying to using an
12624 // invisible namespace. So we handle the case specially here.
12625 if (isa_and_nonnull<NamespaceDecl>(Val: Corrected.getFoundDecl()) &&
12626 Corrected.requiresImport()) {
12627 DiagnoseInvisibleNamespace(Corrected, S);
12628 } else if (DeclContext *DC = S.computeDeclContext(SS, EnteringContext: false)) {
12629 std::string CorrectedStr(Corrected.getAsString(LO: S.getLangOpts()));
12630 bool DroppedSpecifier =
12631 Corrected.WillReplaceSpecifier() && Ident->getName() == CorrectedStr;
12632 S.diagnoseTypo(Correction: Corrected,
12633 TypoDiag: S.PDiag(DiagID: diag::err_using_directive_member_suggest)
12634 << Ident << DC << DroppedSpecifier << SS.getRange(),
12635 PrevNote: S.PDiag(DiagID: diag::note_namespace_defined_here));
12636 } else {
12637 S.diagnoseTypo(Correction: Corrected,
12638 TypoDiag: S.PDiag(DiagID: diag::err_using_directive_suggest) << Ident,
12639 PrevNote: S.PDiag(DiagID: diag::note_namespace_defined_here));
12640 }
12641 R.addDecl(D: Corrected.getFoundDecl());
12642 return true;
12643 }
12644 return false;
12645}
12646
12647Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
12648 SourceLocation NamespcLoc, CXXScopeSpec &SS,
12649 SourceLocation IdentLoc,
12650 IdentifierInfo *NamespcName,
12651 const ParsedAttributesView &AttrList) {
12652 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
12653 assert(NamespcName && "Invalid NamespcName.");
12654 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
12655
12656 // Get the innermost enclosing declaration scope.
12657 S = S->getDeclParent();
12658
12659 UsingDirectiveDecl *UDir = nullptr;
12660 NestedNameSpecifier Qualifier = SS.getScopeRep();
12661
12662 // Lookup namespace name.
12663 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
12664 LookupParsedName(R, S, SS: &SS, /*ObjectType=*/QualType());
12665 if (R.isAmbiguous())
12666 return nullptr;
12667
12668 if (R.empty()) {
12669 R.clear();
12670 // Allow "using namespace std;" or "using namespace ::std;" even if
12671 // "std" hasn't been defined yet, for GCC compatibility.
12672 if ((!Qualifier ||
12673 Qualifier.getKind() == NestedNameSpecifier::Kind::Global) &&
12674 NamespcName->isStr(Str: "std")) {
12675 Diag(Loc: IdentLoc, DiagID: diag::ext_using_undefined_std);
12676 R.addDecl(D: getOrCreateStdNamespace());
12677 R.resolveKind();
12678 }
12679 // Otherwise, attempt typo correction.
12680 else
12681 TryNamespaceTypoCorrection(S&: *this, R, Sc: S, SS, IdentLoc, Ident: NamespcName);
12682 }
12683
12684 if (!R.empty()) {
12685 NamedDecl *Named = R.getRepresentativeDecl();
12686 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
12687 assert(NS && "expected namespace decl");
12688
12689 // The use of a nested name specifier may trigger deprecation warnings.
12690 DiagnoseUseOfDecl(D: Named, Locs: IdentLoc);
12691
12692 // C++ [namespace.udir]p1:
12693 // A using-directive specifies that the names in the nominated
12694 // namespace can be used in the scope in which the
12695 // using-directive appears after the using-directive. During
12696 // unqualified name lookup (3.4.1), the names appear as if they
12697 // were declared in the nearest enclosing namespace which
12698 // contains both the using-directive and the nominated
12699 // namespace. [Note: in this context, "contains" means "contains
12700 // directly or indirectly". ]
12701
12702 // Find enclosing context containing both using-directive and
12703 // nominated namespace.
12704 DeclContext *CommonAncestor = NS;
12705 while (CommonAncestor && !CommonAncestor->Encloses(DC: CurContext))
12706 CommonAncestor = CommonAncestor->getParent();
12707
12708 UDir = UsingDirectiveDecl::Create(C&: Context, DC: CurContext, UsingLoc, NamespaceLoc: NamespcLoc,
12709 QualifierLoc: SS.getWithLocInContext(Context),
12710 IdentLoc, Nominated: Named, CommonAncestor);
12711
12712 if (IsUsingDirectiveInToplevelContext(CurContext) &&
12713 !SourceMgr.isInMainFile(Loc: SourceMgr.getExpansionLoc(Loc: IdentLoc))) {
12714 Diag(Loc: IdentLoc, DiagID: diag::warn_using_directive_in_header);
12715 }
12716
12717 PushUsingDirective(S, UDir);
12718 } else {
12719 Diag(Loc: IdentLoc, DiagID: diag::err_expected_namespace_name) << SS.getRange();
12720 }
12721
12722 if (UDir) {
12723 ProcessDeclAttributeList(S, D: UDir, AttrList);
12724 ProcessAPINotes(D: UDir);
12725 }
12726
12727 return UDir;
12728}
12729
12730void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
12731 // If the scope has an associated entity and the using directive is at
12732 // namespace or translation unit scope, add the UsingDirectiveDecl into
12733 // its lookup structure so qualified name lookup can find it.
12734 DeclContext *Ctx = S->getEntity();
12735 if (Ctx && !Ctx->isFunctionOrMethod())
12736 Ctx->addDecl(D: UDir);
12737 else
12738 // Otherwise, it is at block scope. The using-directives will affect lookup
12739 // only to the end of the scope.
12740 S->PushUsingDirective(UDir);
12741}
12742
12743Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
12744 SourceLocation UsingLoc,
12745 SourceLocation TypenameLoc, CXXScopeSpec &SS,
12746 UnqualifiedId &Name,
12747 SourceLocation EllipsisLoc,
12748 const ParsedAttributesView &AttrList) {
12749 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
12750
12751 if (SS.isEmpty()) {
12752 Diag(Loc: Name.getBeginLoc(), DiagID: diag::err_using_requires_qualname);
12753 return nullptr;
12754 }
12755
12756 switch (Name.getKind()) {
12757 case UnqualifiedIdKind::IK_ImplicitSelfParam:
12758 case UnqualifiedIdKind::IK_Identifier:
12759 case UnqualifiedIdKind::IK_OperatorFunctionId:
12760 case UnqualifiedIdKind::IK_LiteralOperatorId:
12761 case UnqualifiedIdKind::IK_ConversionFunctionId:
12762 break;
12763
12764 case UnqualifiedIdKind::IK_ConstructorName:
12765 case UnqualifiedIdKind::IK_ConstructorTemplateId:
12766 // C++11 inheriting constructors.
12767 Diag(Loc: Name.getBeginLoc(),
12768 DiagID: getLangOpts().CPlusPlus11
12769 ? diag::warn_cxx98_compat_using_decl_constructor
12770 : diag::err_using_decl_constructor)
12771 << SS.getRange();
12772
12773 if (getLangOpts().CPlusPlus11) break;
12774
12775 return nullptr;
12776
12777 case UnqualifiedIdKind::IK_DestructorName:
12778 Diag(Loc: Name.getBeginLoc(), DiagID: diag::err_using_decl_destructor) << SS.getRange();
12779 return nullptr;
12780
12781 case UnqualifiedIdKind::IK_TemplateId:
12782 Diag(Loc: Name.getBeginLoc(), DiagID: diag::err_using_decl_template_id)
12783 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
12784 return nullptr;
12785
12786 case UnqualifiedIdKind::IK_DeductionGuideName:
12787 llvm_unreachable("cannot parse qualified deduction guide name");
12788 }
12789
12790 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
12791 DeclarationName TargetName = TargetNameInfo.getName();
12792 if (!TargetName)
12793 return nullptr;
12794
12795 // Warn about access declarations.
12796 if (UsingLoc.isInvalid()) {
12797 Diag(Loc: Name.getBeginLoc(), DiagID: getLangOpts().CPlusPlus11
12798 ? diag::err_access_decl
12799 : diag::warn_access_decl_deprecated)
12800 << FixItHint::CreateInsertion(InsertionLoc: SS.getRange().getBegin(), Code: "using ");
12801 }
12802
12803 if (EllipsisLoc.isInvalid()) {
12804 if (DiagnoseUnexpandedParameterPack(SS, UPPC: UPPC_UsingDeclaration) ||
12805 DiagnoseUnexpandedParameterPack(NameInfo: TargetNameInfo, UPPC: UPPC_UsingDeclaration))
12806 return nullptr;
12807 } else {
12808 if (!SS.getScopeRep().containsUnexpandedParameterPack() &&
12809 !TargetNameInfo.containsUnexpandedParameterPack()) {
12810 Diag(Loc: EllipsisLoc, DiagID: diag::err_pack_expansion_without_parameter_packs)
12811 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
12812 EllipsisLoc = SourceLocation();
12813 }
12814 }
12815
12816 NamedDecl *UD =
12817 BuildUsingDeclaration(S, AS, UsingLoc, HasTypenameKeyword: TypenameLoc.isValid(), TypenameLoc,
12818 SS, NameInfo: TargetNameInfo, EllipsisLoc, AttrList,
12819 /*IsInstantiation*/ false,
12820 IsUsingIfExists: AttrList.hasAttribute(K: ParsedAttr::AT_UsingIfExists));
12821 if (UD)
12822 PushOnScopeChains(D: UD, S, /*AddToContext*/ false);
12823
12824 return UD;
12825}
12826
12827Decl *Sema::ActOnUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
12828 SourceLocation UsingLoc,
12829 SourceLocation EnumLoc, SourceRange TyLoc,
12830 const IdentifierInfo &II, ParsedType Ty,
12831 const CXXScopeSpec &SS) {
12832 TypeSourceInfo *TSI = nullptr;
12833 SourceLocation IdentLoc = TyLoc.getBegin();
12834 QualType EnumTy = GetTypeFromParser(Ty, TInfo: &TSI);
12835 if (EnumTy.isNull()) {
12836 Diag(Loc: IdentLoc, DiagID: isDependentScopeSpecifier(SS)
12837 ? diag::err_using_enum_is_dependent
12838 : diag::err_unknown_typename)
12839 << II.getName()
12840 << SourceRange(SS.isValid() ? SS.getBeginLoc() : IdentLoc,
12841 TyLoc.getEnd());
12842 return nullptr;
12843 }
12844
12845 if (EnumTy->isDependentType()) {
12846 Diag(Loc: IdentLoc, DiagID: diag::err_using_enum_is_dependent);
12847 return nullptr;
12848 }
12849
12850 auto *Enum = EnumTy->getAsEnumDecl();
12851 if (!Enum) {
12852 Diag(Loc: IdentLoc, DiagID: diag::err_using_enum_not_enum) << EnumTy;
12853 return nullptr;
12854 }
12855
12856 if (TSI == nullptr)
12857 TSI = Context.getTrivialTypeSourceInfo(T: EnumTy, Loc: IdentLoc);
12858
12859 auto *UD =
12860 BuildUsingEnumDeclaration(S, AS, UsingLoc, EnumLoc, NameLoc: IdentLoc, EnumType: TSI, ED: Enum);
12861
12862 if (UD)
12863 PushOnScopeChains(D: UD, S, /*AddToContext*/ false);
12864
12865 return UD;
12866}
12867
12868/// Determine whether a using declaration considers the given
12869/// declarations as "equivalent", e.g., if they are redeclarations of
12870/// the same entity or are both typedefs of the same type.
12871static bool
12872IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
12873 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
12874 return true;
12875
12876 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(Val: D1))
12877 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(Val: D2))
12878 return Context.hasSameType(T1: TD1->getUnderlyingType(),
12879 T2: TD2->getUnderlyingType());
12880
12881 // Two using_if_exists using-declarations are equivalent if both are
12882 // unresolved.
12883 if (isa<UnresolvedUsingIfExistsDecl>(Val: D1) &&
12884 isa<UnresolvedUsingIfExistsDecl>(Val: D2))
12885 return true;
12886
12887 return false;
12888}
12889
12890bool Sema::CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Orig,
12891 const LookupResult &Previous,
12892 UsingShadowDecl *&PrevShadow) {
12893 // Diagnose finding a decl which is not from a base class of the
12894 // current class. We do this now because there are cases where this
12895 // function will silently decide not to build a shadow decl, which
12896 // will pre-empt further diagnostics.
12897 //
12898 // We don't need to do this in C++11 because we do the check once on
12899 // the qualifier.
12900 //
12901 // FIXME: diagnose the following if we care enough:
12902 // struct A { int foo; };
12903 // struct B : A { using A::foo; };
12904 // template <class T> struct C : A {};
12905 // template <class T> struct D : C<T> { using B::foo; } // <---
12906 // This is invalid (during instantiation) in C++03 because B::foo
12907 // resolves to the using decl in B, which is not a base class of D<T>.
12908 // We can't diagnose it immediately because C<T> is an unknown
12909 // specialization. The UsingShadowDecl in D<T> then points directly
12910 // to A::foo, which will look well-formed when we instantiate.
12911 // The right solution is to not collapse the shadow-decl chain.
12912 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord())
12913 if (auto *Using = dyn_cast<UsingDecl>(Val: BUD)) {
12914 DeclContext *OrigDC = Orig->getDeclContext();
12915
12916 // Handle enums and anonymous structs.
12917 if (isa<EnumDecl>(Val: OrigDC))
12918 OrigDC = OrigDC->getParent();
12919 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(Val: OrigDC);
12920 while (OrigRec->isAnonymousStructOrUnion())
12921 OrigRec = cast<CXXRecordDecl>(Val: OrigRec->getDeclContext());
12922
12923 if (cast<CXXRecordDecl>(Val: CurContext)->isProvablyNotDerivedFrom(Base: OrigRec)) {
12924 if (OrigDC == CurContext) {
12925 Diag(Loc: Using->getLocation(),
12926 DiagID: diag::err_using_decl_nested_name_specifier_is_current_class)
12927 << Using->getQualifierLoc().getSourceRange();
12928 Diag(Loc: Orig->getLocation(), DiagID: diag::note_using_decl_target);
12929 Using->setInvalidDecl();
12930 return true;
12931 }
12932
12933 Diag(Loc: Using->getQualifierLoc().getBeginLoc(),
12934 DiagID: diag::err_using_decl_nested_name_specifier_is_not_base_class)
12935 << Using->getQualifier() << cast<CXXRecordDecl>(Val: CurContext)
12936 << Using->getQualifierLoc().getSourceRange();
12937 Diag(Loc: Orig->getLocation(), DiagID: diag::note_using_decl_target);
12938 Using->setInvalidDecl();
12939 return true;
12940 }
12941 }
12942
12943 if (Previous.empty()) return false;
12944
12945 NamedDecl *Target = Orig;
12946 if (isa<UsingShadowDecl>(Val: Target))
12947 Target = cast<UsingShadowDecl>(Val: Target)->getTargetDecl();
12948
12949 // If the target happens to be one of the previous declarations, we
12950 // don't have a conflict.
12951 //
12952 // FIXME: but we might be increasing its access, in which case we
12953 // should redeclare it.
12954 NamedDecl *NonTag = nullptr, *Tag = nullptr;
12955 bool FoundEquivalentDecl = false;
12956 for (NamedDecl *Element : Previous) {
12957 NamedDecl *D = Element->getUnderlyingDecl();
12958 // We can have UsingDecls in our Previous results because we use the same
12959 // LookupResult for checking whether the UsingDecl itself is a valid
12960 // redeclaration.
12961 if (isa<UsingDecl>(Val: D) || isa<UsingPackDecl>(Val: D) || isa<UsingEnumDecl>(Val: D))
12962 continue;
12963
12964 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: D)) {
12965 // C++ [class.mem]p19:
12966 // If T is the name of a class, then [every named member other than
12967 // a non-static data member] shall have a name different from T
12968 if (RD->isInjectedClassName() && !isa<FieldDecl>(Val: Target) &&
12969 !isa<IndirectFieldDecl>(Val: Target) &&
12970 !isa<UnresolvedUsingValueDecl>(Val: Target) &&
12971 DiagnoseClassNameShadow(
12972 DC: CurContext,
12973 Info: DeclarationNameInfo(BUD->getDeclName(), BUD->getLocation())))
12974 return true;
12975 }
12976
12977 if (IsEquivalentForUsingDecl(Context, D1: D, D2: Target)) {
12978 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Val: Element))
12979 PrevShadow = Shadow;
12980 FoundEquivalentDecl = true;
12981 } else if (isEquivalentInternalLinkageDeclaration(A: D, B: Target)) {
12982 // We don't conflict with an existing using shadow decl of an equivalent
12983 // declaration, but we're not a redeclaration of it.
12984 FoundEquivalentDecl = true;
12985 }
12986
12987 if (isVisible(D))
12988 (isa<TagDecl>(Val: D) ? Tag : NonTag) = D;
12989 }
12990
12991 if (FoundEquivalentDecl)
12992 return false;
12993
12994 // Always emit a diagnostic for a mismatch between an unresolved
12995 // using_if_exists and a resolved using declaration in either direction.
12996 if (isa<UnresolvedUsingIfExistsDecl>(Val: Target) !=
12997 (isa_and_nonnull<UnresolvedUsingIfExistsDecl>(Val: NonTag))) {
12998 if (!NonTag && !Tag)
12999 return false;
13000 Diag(Loc: BUD->getLocation(), DiagID: diag::err_using_decl_conflict);
13001 Diag(Loc: Target->getLocation(), DiagID: diag::note_using_decl_target);
13002 Diag(Loc: (NonTag ? NonTag : Tag)->getLocation(),
13003 DiagID: diag::note_using_decl_conflict);
13004 BUD->setInvalidDecl();
13005 return true;
13006 }
13007
13008 if (FunctionDecl *FD = Target->getAsFunction()) {
13009 NamedDecl *OldDecl = nullptr;
13010 switch (CheckOverload(S: nullptr, New: FD, OldDecls: Previous, OldDecl,
13011 /*IsForUsingDecl*/ UseMemberUsingDeclRules: true)) {
13012 case OverloadKind::Overload:
13013 return false;
13014
13015 case OverloadKind::NonFunction:
13016 Diag(Loc: BUD->getLocation(), DiagID: diag::err_using_decl_conflict);
13017 break;
13018
13019 // We found a decl with the exact signature.
13020 case OverloadKind::Match:
13021 // If we're in a record, we want to hide the target, so we
13022 // return true (without a diagnostic) to tell the caller not to
13023 // build a shadow decl.
13024 if (CurContext->isRecord())
13025 return true;
13026
13027 // If we're not in a record, this is an error.
13028 Diag(Loc: BUD->getLocation(), DiagID: diag::err_using_decl_conflict);
13029 break;
13030 }
13031
13032 Diag(Loc: Target->getLocation(), DiagID: diag::note_using_decl_target);
13033 Diag(Loc: OldDecl->getLocation(), DiagID: diag::note_using_decl_conflict);
13034 BUD->setInvalidDecl();
13035 return true;
13036 }
13037
13038 // Target is not a function.
13039
13040 if (isa<TagDecl>(Val: Target)) {
13041 // No conflict between a tag and a non-tag.
13042 if (!Tag) return false;
13043
13044 Diag(Loc: BUD->getLocation(), DiagID: diag::err_using_decl_conflict);
13045 Diag(Loc: Target->getLocation(), DiagID: diag::note_using_decl_target);
13046 Diag(Loc: Tag->getLocation(), DiagID: diag::note_using_decl_conflict);
13047 BUD->setInvalidDecl();
13048 return true;
13049 }
13050
13051 // No conflict between a tag and a non-tag.
13052 if (!NonTag) return false;
13053
13054 Diag(Loc: BUD->getLocation(), DiagID: diag::err_using_decl_conflict);
13055 Diag(Loc: Target->getLocation(), DiagID: diag::note_using_decl_target);
13056 Diag(Loc: NonTag->getLocation(), DiagID: diag::note_using_decl_conflict);
13057 BUD->setInvalidDecl();
13058 return true;
13059}
13060
13061/// Determine whether a direct base class is a virtual base class.
13062static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
13063 if (!Derived->getNumVBases())
13064 return false;
13065 for (auto &B : Derived->bases())
13066 if (B.getType()->getAsCXXRecordDecl() == Base)
13067 return B.isVirtual();
13068 llvm_unreachable("not a direct base class");
13069}
13070
13071UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD,
13072 NamedDecl *Orig,
13073 UsingShadowDecl *PrevDecl) {
13074 // If we resolved to another shadow declaration, just coalesce them.
13075 NamedDecl *Target = Orig;
13076 if (isa<UsingShadowDecl>(Val: Target)) {
13077 Target = cast<UsingShadowDecl>(Val: Target)->getTargetDecl();
13078 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
13079 }
13080
13081 NamedDecl *NonTemplateTarget = Target;
13082 if (auto *TargetTD = dyn_cast<TemplateDecl>(Val: Target))
13083 NonTemplateTarget = TargetTD->getTemplatedDecl();
13084
13085 UsingShadowDecl *Shadow;
13086 if (NonTemplateTarget && isa<CXXConstructorDecl>(Val: NonTemplateTarget)) {
13087 UsingDecl *Using = cast<UsingDecl>(Val: BUD);
13088 bool IsVirtualBase =
13089 isVirtualDirectBase(Derived: cast<CXXRecordDecl>(Val: CurContext),
13090 Base: Using->getQualifier().getAsRecordDecl());
13091 Shadow = ConstructorUsingShadowDecl::Create(
13092 C&: Context, DC: CurContext, Loc: Using->getLocation(), Using, Target: Orig, IsVirtual: IsVirtualBase);
13093 } else {
13094 Shadow = UsingShadowDecl::Create(C&: Context, DC: CurContext, Loc: BUD->getLocation(),
13095 Name: Target->getDeclName(), Introducer: BUD, Target);
13096 }
13097 BUD->addShadowDecl(S: Shadow);
13098
13099 Shadow->setAccess(BUD->getAccess());
13100 if (Orig->isInvalidDecl() || BUD->isInvalidDecl())
13101 Shadow->setInvalidDecl();
13102
13103 Shadow->setPreviousDecl(PrevDecl);
13104
13105 if (S)
13106 PushOnScopeChains(D: Shadow, S);
13107 else
13108 CurContext->addDecl(D: Shadow);
13109
13110
13111 return Shadow;
13112}
13113
13114void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
13115 if (Shadow->getDeclName().getNameKind() ==
13116 DeclarationName::CXXConversionFunctionName)
13117 cast<CXXRecordDecl>(Val: Shadow->getDeclContext())->removeConversion(Old: Shadow);
13118
13119 // Remove it from the DeclContext...
13120 Shadow->getDeclContext()->removeDecl(D: Shadow);
13121
13122 // ...and the scope, if applicable...
13123 if (S) {
13124 S->RemoveDecl(D: Shadow);
13125 IdResolver.RemoveDecl(D: Shadow);
13126 }
13127
13128 // ...and the using decl.
13129 Shadow->getIntroducer()->removeShadowDecl(S: Shadow);
13130
13131 // TODO: complain somehow if Shadow was used. It shouldn't
13132 // be possible for this to happen, because...?
13133}
13134
13135/// Find the base specifier for a base class with the given type.
13136static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
13137 QualType DesiredBase,
13138 bool &AnyDependentBases) {
13139 // Check whether the named type is a direct base class.
13140 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
13141 for (auto &Base : Derived->bases()) {
13142 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
13143 if (CanonicalDesiredBase == BaseType)
13144 return &Base;
13145 if (BaseType->isDependentType())
13146 AnyDependentBases = true;
13147 }
13148 return nullptr;
13149}
13150
13151namespace {
13152class UsingValidatorCCC final : public CorrectionCandidateCallback {
13153public:
13154 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
13155 NestedNameSpecifier NNS, CXXRecordDecl *RequireMemberOf)
13156 : HasTypenameKeyword(HasTypenameKeyword),
13157 IsInstantiation(IsInstantiation), OldNNS(NNS),
13158 RequireMemberOf(RequireMemberOf) {}
13159
13160 bool ValidateCandidate(const TypoCorrection &Candidate) override {
13161 NamedDecl *ND = Candidate.getCorrectionDecl();
13162
13163 // Keywords are not valid here.
13164 if (!ND || isa<NamespaceDecl>(Val: ND))
13165 return false;
13166
13167 // Completely unqualified names are invalid for a 'using' declaration.
13168 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
13169 return false;
13170
13171 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
13172 // reject.
13173
13174 if (RequireMemberOf) {
13175 auto *FoundRecord = dyn_cast<CXXRecordDecl>(Val: ND);
13176 if (FoundRecord && FoundRecord->isInjectedClassName()) {
13177 // No-one ever wants a using-declaration to name an injected-class-name
13178 // of a base class, unless they're declaring an inheriting constructor.
13179 ASTContext &Ctx = ND->getASTContext();
13180 if (!Ctx.getLangOpts().CPlusPlus11)
13181 return false;
13182 CanQualType FoundType = Ctx.getCanonicalTagType(TD: FoundRecord);
13183
13184 // Check that the injected-class-name is named as a member of its own
13185 // type; we don't want to suggest 'using Derived::Base;', since that
13186 // means something else.
13187 NestedNameSpecifier Specifier = Candidate.WillReplaceSpecifier()
13188 ? Candidate.getCorrectionSpecifier()
13189 : OldNNS;
13190 if (Specifier.getKind() != NestedNameSpecifier::Kind::Type ||
13191 !Ctx.hasSameType(T1: QualType(Specifier.getAsType(), 0), T2: FoundType))
13192 return false;
13193
13194 // Check that this inheriting constructor declaration actually names a
13195 // direct base class of the current class.
13196 bool AnyDependentBases = false;
13197 if (!findDirectBaseWithType(Derived: RequireMemberOf,
13198 DesiredBase: Ctx.getCanonicalTagType(TD: FoundRecord),
13199 AnyDependentBases) &&
13200 !AnyDependentBases)
13201 return false;
13202 } else {
13203 auto *RD = dyn_cast<CXXRecordDecl>(Val: ND->getDeclContext());
13204 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(Base: RD))
13205 return false;
13206
13207 // FIXME: Check that the base class member is accessible?
13208 }
13209 } else {
13210 auto *FoundRecord = dyn_cast<CXXRecordDecl>(Val: ND);
13211 if (FoundRecord && FoundRecord->isInjectedClassName())
13212 return false;
13213 }
13214
13215 if (isa<TypeDecl>(Val: ND))
13216 return HasTypenameKeyword || !IsInstantiation;
13217
13218 return !HasTypenameKeyword;
13219 }
13220
13221 std::unique_ptr<CorrectionCandidateCallback> clone() override {
13222 return std::make_unique<UsingValidatorCCC>(args&: *this);
13223 }
13224
13225private:
13226 bool HasTypenameKeyword;
13227 bool IsInstantiation;
13228 NestedNameSpecifier OldNNS;
13229 CXXRecordDecl *RequireMemberOf;
13230};
13231} // end anonymous namespace
13232
13233void Sema::FilterUsingLookup(Scope *S, LookupResult &Previous) {
13234 // It is really dumb that we have to do this.
13235 LookupResult::Filter F = Previous.makeFilter();
13236 while (F.hasNext()) {
13237 NamedDecl *D = F.next();
13238 if (!isDeclInScope(D, Ctx: CurContext, S))
13239 F.erase();
13240 // If we found a local extern declaration that's not ordinarily visible,
13241 // and this declaration is being added to a non-block scope, ignore it.
13242 // We're only checking for scope conflicts here, not also for violations
13243 // of the linkage rules.
13244 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
13245 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
13246 F.erase();
13247 }
13248 F.done();
13249}
13250
13251NamedDecl *Sema::BuildUsingDeclaration(
13252 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
13253 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
13254 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
13255 const ParsedAttributesView &AttrList, bool IsInstantiation,
13256 bool IsUsingIfExists) {
13257 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
13258 SourceLocation IdentLoc = NameInfo.getLoc();
13259 assert(IdentLoc.isValid() && "Invalid TargetName location.");
13260
13261 // FIXME: We ignore attributes for now.
13262
13263 // For an inheriting constructor declaration, the name of the using
13264 // declaration is the name of a constructor in this class, not in the
13265 // base class.
13266 DeclarationNameInfo UsingName = NameInfo;
13267 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
13268 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: CurContext))
13269 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
13270 Ty: Context.getCanonicalTagType(TD: RD)));
13271
13272 // Do the redeclaration lookup in the current scope.
13273 LookupResult Previous(*this, UsingName, LookupUsingDeclName,
13274 RedeclarationKind::ForVisibleRedeclaration);
13275 Previous.setHideTags(false);
13276 if (S) {
13277 LookupName(R&: Previous, S);
13278
13279 FilterUsingLookup(S, Previous);
13280 } else {
13281 assert(IsInstantiation && "no scope in non-instantiation");
13282 if (CurContext->isRecord())
13283 LookupQualifiedName(R&: Previous, LookupCtx: CurContext);
13284 else {
13285 // No redeclaration check is needed here; in non-member contexts we
13286 // diagnosed all possible conflicts with other using-declarations when
13287 // building the template:
13288 //
13289 // For a dependent non-type using declaration, the only valid case is
13290 // if we instantiate to a single enumerator. We check for conflicts
13291 // between shadow declarations we introduce, and we check in the template
13292 // definition for conflicts between a non-type using declaration and any
13293 // other declaration, which together covers all cases.
13294 //
13295 // A dependent typename using declaration will never successfully
13296 // instantiate, since it will always name a class member, so we reject
13297 // that in the template definition.
13298 }
13299 }
13300
13301 // Check for invalid redeclarations.
13302 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
13303 SS, NameLoc: IdentLoc, Previous))
13304 return nullptr;
13305
13306 // 'using_if_exists' doesn't make sense on an inherited constructor.
13307 if (IsUsingIfExists && UsingName.getName().getNameKind() ==
13308 DeclarationName::CXXConstructorName) {
13309 Diag(Loc: UsingLoc, DiagID: diag::err_using_if_exists_on_ctor);
13310 return nullptr;
13311 }
13312
13313 DeclContext *LookupContext = computeDeclContext(SS);
13314 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
13315 if (!LookupContext || EllipsisLoc.isValid()) {
13316 NamedDecl *D;
13317 // Dependent scope, or an unexpanded pack
13318 if (!LookupContext && CheckUsingDeclQualifier(UsingLoc, HasTypename: HasTypenameKeyword,
13319 SS, NameInfo, NameLoc: IdentLoc))
13320 return nullptr;
13321
13322 if (Previous.isSingleResult() &&
13323 Previous.getFoundDecl()->isTemplateParameter())
13324 DiagnoseTemplateParameterShadow(Loc: IdentLoc, PrevDecl: Previous.getFoundDecl());
13325
13326 if (HasTypenameKeyword) {
13327 // FIXME: not all declaration name kinds are legal here
13328 D = UnresolvedUsingTypenameDecl::Create(C&: Context, DC: CurContext,
13329 UsingLoc, TypenameLoc,
13330 QualifierLoc,
13331 TargetNameLoc: IdentLoc, TargetName: NameInfo.getName(),
13332 EllipsisLoc);
13333 } else {
13334 D = UnresolvedUsingValueDecl::Create(C&: Context, DC: CurContext, UsingLoc,
13335 QualifierLoc, NameInfo, EllipsisLoc);
13336 }
13337 D->setAccess(AS);
13338 CurContext->addDecl(D);
13339 ProcessDeclAttributeList(S, D, AttrList);
13340 return D;
13341 }
13342
13343 auto Build = [&](bool Invalid) {
13344 UsingDecl *UD =
13345 UsingDecl::Create(C&: Context, DC: CurContext, UsingL: UsingLoc, QualifierLoc,
13346 NameInfo: UsingName, HasTypenameKeyword);
13347 UD->setAccess(AS);
13348 CurContext->addDecl(D: UD);
13349 ProcessDeclAttributeList(S, D: UD, AttrList);
13350 UD->setInvalidDecl(Invalid);
13351 return UD;
13352 };
13353 auto BuildInvalid = [&]{ return Build(true); };
13354 auto BuildValid = [&]{ return Build(false); };
13355
13356 if (RequireCompleteDeclContext(SS, DC: LookupContext))
13357 return BuildInvalid();
13358
13359 // Look up the target name.
13360 LookupResult R(*this, NameInfo, LookupOrdinaryName);
13361
13362 // Unlike most lookups, we don't always want to hide tag
13363 // declarations: tag names are visible through the using declaration
13364 // even if hidden by ordinary names, *except* in a dependent context
13365 // where they may be used by two-phase lookup.
13366 if (!IsInstantiation)
13367 R.setHideTags(false);
13368
13369 // For the purposes of this lookup, we have a base object type
13370 // equal to that of the current context.
13371 if (CurContext->isRecord()) {
13372 R.setBaseObjectType(
13373 Context.getCanonicalTagType(TD: cast<CXXRecordDecl>(Val: CurContext)));
13374 }
13375
13376 LookupQualifiedName(R, LookupCtx: LookupContext);
13377
13378 // Validate the context, now we have a lookup
13379 if (CheckUsingDeclQualifier(UsingLoc, HasTypename: HasTypenameKeyword, SS, NameInfo,
13380 NameLoc: IdentLoc, R: &R))
13381 return nullptr;
13382
13383 if (R.empty() && IsUsingIfExists)
13384 R.addDecl(D: UnresolvedUsingIfExistsDecl::Create(Ctx&: Context, DC: CurContext, Loc: UsingLoc,
13385 Name: UsingName.getName()),
13386 AS: AS_public);
13387
13388 // Try to correct typos if possible. If constructor name lookup finds no
13389 // results, that means the named class has no explicit constructors, and we
13390 // suppressed declaring implicit ones (probably because it's dependent or
13391 // invalid).
13392 if (R.empty() &&
13393 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
13394 // HACK 2017-01-08: Work around an issue with libstdc++'s detection of
13395 // ::gets. Sometimes it believes that glibc provides a ::gets in cases where
13396 // it does not. The issue was fixed in libstdc++ 6.3 (2016-12-21) and later.
13397 auto *II = NameInfo.getName().getAsIdentifierInfo();
13398 if (getLangOpts().CPlusPlus14 && II && II->isStr(Str: "gets") &&
13399 CurContext->isStdNamespace() &&
13400 isa<TranslationUnitDecl>(Val: LookupContext) &&
13401 PP.NeedsStdLibCxxWorkaroundBefore(FixedVersion: 2016'12'21) &&
13402 getSourceManager().isInSystemHeader(Loc: UsingLoc))
13403 return nullptr;
13404 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
13405 dyn_cast<CXXRecordDecl>(Val: CurContext));
13406 if (TypoCorrection Corrected =
13407 CorrectTypo(Typo: R.getLookupNameInfo(), LookupKind: R.getLookupKind(), S, SS: &SS, CCC,
13408 Mode: CorrectTypoKind::ErrorRecovery)) {
13409 // We reject candidates where DroppedSpecifier == true, hence the
13410 // literal '0' below.
13411 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: diag::err_no_member_suggest)
13412 << NameInfo.getName() << LookupContext << 0
13413 << SS.getRange());
13414
13415 // If we picked a correction with no attached Decl we can't do anything
13416 // useful with it, bail out.
13417 NamedDecl *ND = Corrected.getCorrectionDecl();
13418 if (!ND)
13419 return BuildInvalid();
13420
13421 // If we corrected to an inheriting constructor, handle it as one.
13422 auto *RD = dyn_cast<CXXRecordDecl>(Val: ND);
13423 if (RD && RD->isInjectedClassName()) {
13424 // The parent of the injected class name is the class itself.
13425 RD = cast<CXXRecordDecl>(Val: RD->getParent());
13426
13427 // Fix up the information we'll use to build the using declaration.
13428 if (Corrected.WillReplaceSpecifier()) {
13429 NestedNameSpecifierLocBuilder Builder;
13430 Builder.MakeTrivial(Context, Qualifier: Corrected.getCorrectionSpecifier(),
13431 R: QualifierLoc.getSourceRange());
13432 QualifierLoc = Builder.getWithLocInContext(Context);
13433 }
13434
13435 // In this case, the name we introduce is the name of a derived class
13436 // constructor.
13437 auto *CurClass = cast<CXXRecordDecl>(Val: CurContext);
13438 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
13439 Ty: Context.getCanonicalTagType(TD: CurClass)));
13440 UsingName.setNamedTypeInfo(nullptr);
13441 for (auto *Ctor : LookupConstructors(Class: RD))
13442 R.addDecl(D: Ctor);
13443 R.resolveKind();
13444 } else {
13445 // FIXME: Pick up all the declarations if we found an overloaded
13446 // function.
13447 UsingName.setName(ND->getDeclName());
13448 R.addDecl(D: ND);
13449 }
13450 } else {
13451 Diag(Loc: IdentLoc, DiagID: diag::err_no_member)
13452 << NameInfo.getName() << LookupContext << SS.getRange();
13453 return BuildInvalid();
13454 }
13455 }
13456
13457 if (R.isAmbiguous())
13458 return BuildInvalid();
13459
13460 if (HasTypenameKeyword) {
13461 // If we asked for a typename and got a non-type decl, error out.
13462 if (!R.getAsSingle<TypeDecl>() &&
13463 !R.getAsSingle<UnresolvedUsingIfExistsDecl>()) {
13464 Diag(Loc: IdentLoc, DiagID: diag::err_using_typename_non_type);
13465 for (const NamedDecl *D : R)
13466 Diag(Loc: D->getUnderlyingDecl()->getLocation(),
13467 DiagID: diag::note_using_decl_target);
13468 return BuildInvalid();
13469 }
13470 } else {
13471 // If we asked for a non-typename and we got a type, error out,
13472 // but only if this is an instantiation of an unresolved using
13473 // decl. Otherwise just silently find the type name.
13474 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
13475 Diag(Loc: IdentLoc, DiagID: diag::err_using_dependent_value_is_type);
13476 Diag(Loc: R.getFoundDecl()->getLocation(), DiagID: diag::note_using_decl_target);
13477 return BuildInvalid();
13478 }
13479 }
13480
13481 // C++14 [namespace.udecl]p6:
13482 // A using-declaration shall not name a namespace.
13483 if (R.getAsSingle<NamespaceDecl>()) {
13484 Diag(Loc: IdentLoc, DiagID: diag::err_using_decl_can_not_refer_to_namespace)
13485 << SS.getRange();
13486 // Suggest using 'using namespace ...' instead.
13487 Diag(Loc: SS.getBeginLoc(), DiagID: diag::note_namespace_using_decl)
13488 << FixItHint::CreateInsertion(InsertionLoc: SS.getBeginLoc(), Code: "namespace ");
13489 return BuildInvalid();
13490 }
13491
13492 UsingDecl *UD = BuildValid();
13493
13494 // Some additional rules apply to inheriting constructors.
13495 if (UsingName.getName().getNameKind() ==
13496 DeclarationName::CXXConstructorName) {
13497 // Suppress access diagnostics; the access check is instead performed at the
13498 // point of use for an inheriting constructor.
13499 R.suppressDiagnostics();
13500 if (CheckInheritingConstructorUsingDecl(UD))
13501 return UD;
13502 }
13503
13504 for (NamedDecl *D : R) {
13505 UsingShadowDecl *PrevDecl = nullptr;
13506 if (!CheckUsingShadowDecl(BUD: UD, Orig: D, Previous, PrevShadow&: PrevDecl))
13507 BuildUsingShadowDecl(S, BUD: UD, Orig: D, PrevDecl);
13508 }
13509
13510 return UD;
13511}
13512
13513NamedDecl *Sema::BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
13514 SourceLocation UsingLoc,
13515 SourceLocation EnumLoc,
13516 SourceLocation NameLoc,
13517 TypeSourceInfo *EnumType,
13518 EnumDecl *ED) {
13519 bool Invalid = false;
13520
13521 if (CurContext->getRedeclContext()->isRecord()) {
13522 /// In class scope, check if this is a duplicate, for better a diagnostic.
13523 DeclarationNameInfo UsingEnumName(ED->getDeclName(), NameLoc);
13524 LookupResult Previous(*this, UsingEnumName, LookupUsingDeclName,
13525 RedeclarationKind::ForVisibleRedeclaration);
13526
13527 LookupQualifiedName(R&: Previous, LookupCtx: CurContext);
13528
13529 for (NamedDecl *D : Previous)
13530 if (UsingEnumDecl *UED = dyn_cast<UsingEnumDecl>(Val: D))
13531 if (UED->getEnumDecl() == ED) {
13532 Diag(Loc: UsingLoc, DiagID: diag::err_using_enum_decl_redeclaration)
13533 << SourceRange(EnumLoc, NameLoc);
13534 Diag(Loc: D->getLocation(), DiagID: diag::note_using_enum_decl) << 1;
13535 Invalid = true;
13536 break;
13537 }
13538 }
13539
13540 if (RequireCompleteEnumDecl(D: ED, L: NameLoc))
13541 Invalid = true;
13542
13543 UsingEnumDecl *UD = UsingEnumDecl::Create(C&: Context, DC: CurContext, UsingL: UsingLoc,
13544 EnumL: EnumLoc, NameL: NameLoc, EnumType);
13545 UD->setAccess(AS);
13546 CurContext->addDecl(D: UD);
13547
13548 if (Invalid) {
13549 UD->setInvalidDecl();
13550 return UD;
13551 }
13552
13553 // Create the shadow decls for each enumerator
13554 for (EnumConstantDecl *EC : ED->enumerators()) {
13555 UsingShadowDecl *PrevDecl = nullptr;
13556 DeclarationNameInfo DNI(EC->getDeclName(), EC->getLocation());
13557 LookupResult Previous(*this, DNI, LookupOrdinaryName,
13558 RedeclarationKind::ForVisibleRedeclaration);
13559 LookupName(R&: Previous, S);
13560 FilterUsingLookup(S, Previous);
13561
13562 if (!CheckUsingShadowDecl(BUD: UD, Orig: EC, Previous, PrevShadow&: PrevDecl))
13563 BuildUsingShadowDecl(S, BUD: UD, Orig: EC, PrevDecl);
13564 }
13565
13566 return UD;
13567}
13568
13569NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
13570 ArrayRef<NamedDecl *> Expansions) {
13571 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
13572 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
13573 isa<UsingPackDecl>(InstantiatedFrom));
13574
13575 auto *UPD =
13576 UsingPackDecl::Create(C&: Context, DC: CurContext, InstantiatedFrom, UsingDecls: Expansions);
13577 UPD->setAccess(InstantiatedFrom->getAccess());
13578 CurContext->addDecl(D: UPD);
13579 return UPD;
13580}
13581
13582bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
13583 assert(!UD->hasTypename() && "expecting a constructor name");
13584
13585 QualType SourceType(UD->getQualifier().getAsType(), 0);
13586 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(Val: CurContext);
13587
13588 // Check whether the named type is a direct base class.
13589 bool AnyDependentBases = false;
13590 auto *Base =
13591 findDirectBaseWithType(Derived: TargetClass, DesiredBase: SourceType, AnyDependentBases);
13592 if (!Base && !AnyDependentBases) {
13593 Diag(Loc: UD->getUsingLoc(), DiagID: diag::err_using_decl_constructor_not_in_direct_base)
13594 << UD->getNameInfo().getSourceRange() << SourceType << TargetClass;
13595 UD->setInvalidDecl();
13596 return true;
13597 }
13598
13599 if (Base)
13600 Base->setInheritConstructors();
13601
13602 return false;
13603}
13604
13605bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
13606 bool HasTypenameKeyword,
13607 const CXXScopeSpec &SS,
13608 SourceLocation NameLoc,
13609 const LookupResult &Prev) {
13610 NestedNameSpecifier Qual = SS.getScopeRep();
13611
13612 // C++03 [namespace.udecl]p8:
13613 // C++0x [namespace.udecl]p10:
13614 // A using-declaration is a declaration and can therefore be used
13615 // repeatedly where (and only where) multiple declarations are
13616 // allowed.
13617 //
13618 // That's in non-member contexts.
13619 if (!CurContext->getRedeclContext()->isRecord()) {
13620 // A dependent qualifier outside a class can only ever resolve to an
13621 // enumeration type. Therefore it conflicts with any other non-type
13622 // declaration in the same scope.
13623 // FIXME: How should we check for dependent type-type conflicts at block
13624 // scope?
13625 if (Qual.isDependent() && !HasTypenameKeyword) {
13626 for (auto *D : Prev) {
13627 if (!isa<TypeDecl>(Val: D) && !isa<UsingDecl>(Val: D) && !isa<UsingPackDecl>(Val: D)) {
13628 bool OldCouldBeEnumerator =
13629 isa<UnresolvedUsingValueDecl>(Val: D) || isa<EnumConstantDecl>(Val: D);
13630 Diag(Loc: NameLoc,
13631 DiagID: OldCouldBeEnumerator ? diag::err_redefinition
13632 : diag::err_redefinition_different_kind)
13633 << Prev.getLookupName();
13634 Diag(Loc: D->getLocation(), DiagID: diag::note_previous_definition);
13635 return true;
13636 }
13637 }
13638 }
13639 return false;
13640 }
13641
13642 NestedNameSpecifier CNNS = Qual.getCanonical();
13643 for (const NamedDecl *D : Prev) {
13644 bool DTypename;
13645 NestedNameSpecifier DQual = std::nullopt;
13646 if (const auto *UD = dyn_cast<UsingDecl>(Val: D)) {
13647 DTypename = UD->hasTypename();
13648 DQual = UD->getQualifier();
13649 } else if (const auto *UD = dyn_cast<UnresolvedUsingValueDecl>(Val: D)) {
13650 DTypename = false;
13651 DQual = UD->getQualifier();
13652 } else if (const auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(Val: D)) {
13653 DTypename = true;
13654 DQual = UD->getQualifier();
13655 } else
13656 continue;
13657
13658 // using decls differ if one says 'typename' and the other doesn't.
13659 // FIXME: non-dependent using decls?
13660 if (HasTypenameKeyword != DTypename) continue;
13661
13662 // using decls differ if they name different scopes (but note that
13663 // template instantiation can cause this check to trigger when it
13664 // didn't before instantiation).
13665 if (CNNS != DQual.getCanonical())
13666 continue;
13667
13668 Diag(Loc: NameLoc, DiagID: diag::err_using_decl_redeclaration) << SS.getRange();
13669 Diag(Loc: D->getLocation(), DiagID: diag::note_using_decl) << 1;
13670 return true;
13671 }
13672
13673 return false;
13674}
13675
13676bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
13677 const CXXScopeSpec &SS,
13678 const DeclarationNameInfo &NameInfo,
13679 SourceLocation NameLoc,
13680 const LookupResult *R, const UsingDecl *UD) {
13681 DeclContext *NamedContext = computeDeclContext(SS);
13682 assert(bool(NamedContext) == (R || UD) && !(R && UD) &&
13683 "resolvable context must have exactly one set of decls");
13684
13685 // C++ 20 permits using an enumerator that does not have a class-hierarchy
13686 // relationship.
13687 bool Cxx20Enumerator = false;
13688 if (NamedContext) {
13689 EnumConstantDecl *EC = nullptr;
13690 if (R)
13691 EC = R->getAsSingle<EnumConstantDecl>();
13692 else if (UD && UD->shadow_size() == 1)
13693 EC = dyn_cast<EnumConstantDecl>(Val: UD->shadow_begin()->getTargetDecl());
13694 if (EC)
13695 Cxx20Enumerator = getLangOpts().CPlusPlus20;
13696
13697 if (auto *ED = dyn_cast<EnumDecl>(Val: NamedContext)) {
13698 // C++14 [namespace.udecl]p7:
13699 // A using-declaration shall not name a scoped enumerator.
13700 // C++20 p1099 permits enumerators.
13701 if (EC && R && ED->isScoped())
13702 DiagCompat(Loc: SS.getBeginLoc(), CompatDiagId: diag_compat::using_decl_scoped_enumerator)
13703 << SS.getRange();
13704
13705 // We want to consider the scope of the enumerator
13706 NamedContext = ED->getDeclContext();
13707 }
13708 }
13709
13710 if (!CurContext->isRecord()) {
13711 // C++03 [namespace.udecl]p3:
13712 // C++0x [namespace.udecl]p8:
13713 // A using-declaration for a class member shall be a member-declaration.
13714 // C++20 [namespace.udecl]p7
13715 // ... other than an enumerator ...
13716
13717 // If we weren't able to compute a valid scope, it might validly be a
13718 // dependent class or enumeration scope. If we have a 'typename' keyword,
13719 // the scope must resolve to a class type.
13720 if (NamedContext ? !NamedContext->getRedeclContext()->isRecord()
13721 : !HasTypename)
13722 return false; // OK
13723
13724 Diag(Loc: NameLoc,
13725 DiagID: Cxx20Enumerator
13726 ? diag::warn_cxx17_compat_using_decl_class_member_enumerator
13727 : diag::err_using_decl_can_not_refer_to_class_member)
13728 << SS.getRange();
13729
13730 if (Cxx20Enumerator)
13731 return false; // OK
13732
13733 auto *RD = NamedContext
13734 ? cast<CXXRecordDecl>(Val: NamedContext->getRedeclContext())
13735 : nullptr;
13736 if (RD && !RequireCompleteDeclContext(SS&: const_cast<CXXScopeSpec &>(SS), DC: RD)) {
13737 // See if there's a helpful fixit
13738
13739 if (!R) {
13740 // We will have already diagnosed the problem on the template
13741 // definition, Maybe we should do so again?
13742 } else if (R->getAsSingle<TypeDecl>()) {
13743 if (getLangOpts().CPlusPlus11) {
13744 // Convert 'using X::Y;' to 'using Y = X::Y;'.
13745 Diag(Loc: SS.getBeginLoc(), DiagID: diag::note_using_decl_class_member_workaround)
13746 << diag::MemClassWorkaround::AliasDecl
13747 << FixItHint::CreateInsertion(InsertionLoc: SS.getBeginLoc(),
13748 Code: NameInfo.getName().getAsString() +
13749 " = ");
13750 } else {
13751 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
13752 SourceLocation InsertLoc = getLocForEndOfToken(Loc: NameInfo.getEndLoc());
13753 Diag(Loc: InsertLoc, DiagID: diag::note_using_decl_class_member_workaround)
13754 << diag::MemClassWorkaround::TypedefDecl
13755 << FixItHint::CreateReplacement(RemoveRange: UsingLoc, Code: "typedef")
13756 << FixItHint::CreateInsertion(
13757 InsertionLoc: InsertLoc, Code: " " + NameInfo.getName().getAsString());
13758 }
13759 } else if (R->getAsSingle<VarDecl>()) {
13760 // Don't provide a fixit outside C++11 mode; we don't want to suggest
13761 // repeating the type of the static data member here.
13762 FixItHint FixIt;
13763 if (getLangOpts().CPlusPlus11) {
13764 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
13765 FixIt = FixItHint::CreateReplacement(
13766 RemoveRange: UsingLoc, Code: "auto &" + NameInfo.getName().getAsString() + " = ");
13767 }
13768
13769 Diag(Loc: UsingLoc, DiagID: diag::note_using_decl_class_member_workaround)
13770 << diag::MemClassWorkaround::ReferenceDecl << FixIt;
13771 } else if (R->getAsSingle<EnumConstantDecl>()) {
13772 // Don't provide a fixit outside C++11 mode; we don't want to suggest
13773 // repeating the type of the enumeration here, and we can't do so if
13774 // the type is anonymous.
13775 FixItHint FixIt;
13776 if (getLangOpts().CPlusPlus11) {
13777 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
13778 FixIt = FixItHint::CreateReplacement(
13779 RemoveRange: UsingLoc,
13780 Code: "constexpr auto " + NameInfo.getName().getAsString() + " = ");
13781 }
13782
13783 Diag(Loc: UsingLoc, DiagID: diag::note_using_decl_class_member_workaround)
13784 << (getLangOpts().CPlusPlus11
13785 ? diag::MemClassWorkaround::ConstexprVar
13786 : diag::MemClassWorkaround::ConstVar)
13787 << FixIt;
13788 }
13789 }
13790
13791 return true; // Fail
13792 }
13793
13794 // If the named context is dependent, we can't decide much.
13795 if (!NamedContext) {
13796 // FIXME: in C++0x, we can diagnose if we can prove that the
13797 // nested-name-specifier does not refer to a base class, which is
13798 // still possible in some cases.
13799
13800 // Otherwise we have to conservatively report that things might be
13801 // okay.
13802 return false;
13803 }
13804
13805 // The current scope is a record.
13806 if (!NamedContext->isRecord()) {
13807 // Ideally this would point at the last name in the specifier,
13808 // but we don't have that level of source info.
13809 Diag(Loc: SS.getBeginLoc(),
13810 DiagID: Cxx20Enumerator
13811 ? diag::warn_cxx17_compat_using_decl_non_member_enumerator
13812 : diag::err_using_decl_nested_name_specifier_is_not_class)
13813 << SS.getScopeRep() << SS.getRange();
13814
13815 if (Cxx20Enumerator)
13816 return false; // OK
13817
13818 return true;
13819 }
13820
13821 if (!NamedContext->isDependentContext() &&
13822 RequireCompleteDeclContext(SS&: const_cast<CXXScopeSpec&>(SS), DC: NamedContext))
13823 return true;
13824
13825 // C++26 [namespace.udecl]p3:
13826 // In a using-declaration used as a member-declaration, each
13827 // using-declarator shall either name an enumerator or have a
13828 // nested-name-specifier naming a base class of the current class
13829 // ([expr.prim.this]). ...
13830 // "have a nested-name-specifier naming a base class of the current class"
13831 // was introduced by CWG400.
13832
13833 if (cast<CXXRecordDecl>(Val: CurContext)
13834 ->isProvablyNotDerivedFrom(Base: cast<CXXRecordDecl>(Val: NamedContext))) {
13835
13836 if (Cxx20Enumerator) {
13837 Diag(Loc: NameLoc, DiagID: diag::warn_cxx17_compat_using_decl_non_member_enumerator)
13838 << SS.getScopeRep() << SS.getRange();
13839 return false;
13840 }
13841
13842 if (CurContext == NamedContext) {
13843 Diag(Loc: SS.getBeginLoc(),
13844 DiagID: diag::err_using_decl_nested_name_specifier_is_current_class)
13845 << SS.getRange();
13846 return true;
13847 }
13848
13849 if (!cast<CXXRecordDecl>(Val: NamedContext)->isInvalidDecl()) {
13850 Diag(Loc: SS.getBeginLoc(),
13851 DiagID: diag::err_using_decl_nested_name_specifier_is_not_base_class)
13852 << SS.getScopeRep() << cast<CXXRecordDecl>(Val: CurContext)
13853 << SS.getRange();
13854 }
13855 return true;
13856 }
13857
13858 return false;
13859}
13860
13861Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
13862 MultiTemplateParamsArg TemplateParamLists,
13863 SourceLocation UsingLoc, UnqualifiedId &Name,
13864 const ParsedAttributesView &AttrList,
13865 TypeResult Type, Decl *DeclFromDeclSpec) {
13866
13867 if (Type.isInvalid())
13868 return nullptr;
13869
13870 bool Invalid = false;
13871 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
13872 TypeSourceInfo *TInfo = nullptr;
13873 GetTypeFromParser(Ty: Type.get(), TInfo: &TInfo);
13874
13875 if (DiagnoseClassNameShadow(DC: CurContext, Info: NameInfo))
13876 return nullptr;
13877
13878 if (DiagnoseUnexpandedParameterPack(Loc: Name.StartLocation, T: TInfo,
13879 UPPC: UPPC_DeclarationType)) {
13880 Invalid = true;
13881 TInfo = Context.getTrivialTypeSourceInfo(T: Context.IntTy,
13882 Loc: TInfo->getTypeLoc().getBeginLoc());
13883 }
13884
13885 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
13886 TemplateParamLists.size()
13887 ? forRedeclarationInCurContext()
13888 : RedeclarationKind::ForVisibleRedeclaration);
13889 LookupName(R&: Previous, S);
13890
13891 // Warn about shadowing the name of a template parameter.
13892 if (Previous.isSingleResult() &&
13893 Previous.getFoundDecl()->isTemplateParameter()) {
13894 DiagnoseTemplateParameterShadow(Loc: Name.StartLocation,PrevDecl: Previous.getFoundDecl());
13895 Previous.clear();
13896 }
13897
13898 assert(Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
13899 "name in alias declaration must be an identifier");
13900 TypeAliasDecl *NewTD = TypeAliasDecl::Create(C&: Context, DC: CurContext, StartLoc: UsingLoc,
13901 IdLoc: Name.StartLocation,
13902 Id: Name.Identifier, TInfo);
13903
13904 NewTD->setAccess(AS);
13905
13906 if (Invalid)
13907 NewTD->setInvalidDecl();
13908
13909 ProcessDeclAttributeList(S, D: NewTD, AttrList);
13910 AddPragmaAttributes(S, D: NewTD);
13911 ProcessAPINotes(D: NewTD);
13912
13913 CheckTypedefForVariablyModifiedType(S, D: NewTD);
13914 Invalid |= NewTD->isInvalidDecl();
13915
13916 // Get the innermost enclosing declaration scope.
13917 S = S->getDeclParent();
13918
13919 bool Redeclaration = false;
13920
13921 NamedDecl *NewND;
13922 if (TemplateParamLists.size()) {
13923 TypeAliasTemplateDecl *OldDecl = nullptr;
13924 TemplateParameterList *OldTemplateParams = nullptr;
13925
13926 TemplateParameterList *TemplateParams = TemplateParamLists[0];
13927 if (TemplateParamLists.size() != 1) {
13928 Diag(Loc: UsingLoc, DiagID: diag::err_alias_template_extra_headers)
13929 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
13930 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
13931 Invalid = true;
13932
13933 // Recover by picking the last non-empty template parameter list.
13934 auto It = llvm::find_if(
13935 Range: llvm::reverse(C&: TemplateParamLists),
13936 P: [](TemplateParameterList *TPL) { return !TPL->empty(); });
13937 assert(It != TemplateParamLists.rend() &&
13938 "if all template parameter lists were empty, this should have "
13939 "been rejected as an explicit specialization");
13940 TemplateParams = *It;
13941 }
13942
13943 // Check that we can declare a template here.
13944 if (CheckTemplateDeclScope(S, TemplateParams))
13945 return nullptr;
13946
13947 // Only consider previous declarations in the same scope.
13948 FilterLookupForScope(R&: Previous, Ctx: CurContext, S, /*ConsiderLinkage*/false,
13949 /*ExplicitInstantiationOrSpecialization*/AllowInlineNamespace: false);
13950 if (!Previous.empty()) {
13951 Redeclaration = true;
13952
13953 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
13954 if (!OldDecl && !Invalid) {
13955 Diag(Loc: UsingLoc, DiagID: diag::err_redefinition_different_kind)
13956 << Name.Identifier;
13957
13958 NamedDecl *OldD = Previous.getRepresentativeDecl();
13959 if (OldD->getLocation().isValid())
13960 Diag(Loc: OldD->getLocation(), DiagID: diag::note_previous_definition);
13961
13962 Invalid = true;
13963 }
13964
13965 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
13966 if (TemplateParameterListsAreEqual(New: TemplateParams,
13967 Old: OldDecl->getTemplateParameters(),
13968 /*Complain=*/true,
13969 Kind: TPL_TemplateMatch))
13970 OldTemplateParams =
13971 OldDecl->getMostRecentDecl()->getTemplateParameters();
13972 else
13973 Invalid = true;
13974
13975 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
13976 if (!Invalid &&
13977 !Context.hasSameType(T1: OldTD->getUnderlyingType(),
13978 T2: NewTD->getUnderlyingType())) {
13979 // FIXME: The C++0x standard does not clearly say this is ill-formed,
13980 // but we can't reasonably accept it.
13981 Diag(Loc: NewTD->getLocation(), DiagID: diag::err_redefinition_different_typedef)
13982 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
13983 if (OldTD->getLocation().isValid())
13984 Diag(Loc: OldTD->getLocation(), DiagID: diag::note_previous_definition);
13985 Invalid = true;
13986 }
13987 }
13988 }
13989
13990 // Merge any previous default template arguments into our parameters,
13991 // and check the parameter list.
13992 if (CheckTemplateParameterList(NewParams: TemplateParams, OldParams: OldTemplateParams,
13993 TPC: TPC_Other))
13994 return nullptr;
13995
13996 TypeAliasTemplateDecl *NewDecl =
13997 TypeAliasTemplateDecl::Create(C&: Context, DC: CurContext, L: UsingLoc,
13998 Name: Name.Identifier, Params: TemplateParams,
13999 Decl: NewTD);
14000 NewTD->setDescribedAliasTemplate(NewDecl);
14001
14002 NewDecl->setAccess(AS);
14003
14004 if (Invalid)
14005 NewDecl->setInvalidDecl();
14006 else if (OldDecl) {
14007 NewDecl->setPreviousDecl(OldDecl);
14008 CheckRedeclarationInModule(New: NewDecl, Old: OldDecl);
14009 }
14010
14011 NewND = NewDecl;
14012 } else {
14013 if (auto *TD = dyn_cast_or_null<TagDecl>(Val: DeclFromDeclSpec)) {
14014 setTagNameForLinkagePurposes(TagFromDeclSpec: TD, NewTD);
14015 handleTagNumbering(Tag: TD, TagScope: S);
14016 }
14017 ActOnTypedefNameDecl(S, DC: CurContext, D: NewTD, Previous, Redeclaration);
14018 NewND = NewTD;
14019 }
14020
14021 PushOnScopeChains(D: NewND, S);
14022 ActOnDocumentableDecl(D: NewND);
14023 return NewND;
14024}
14025
14026Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
14027 SourceLocation AliasLoc,
14028 IdentifierInfo *Alias, CXXScopeSpec &SS,
14029 SourceLocation IdentLoc,
14030 IdentifierInfo *Ident) {
14031
14032 // Lookup the namespace name.
14033 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
14034 LookupParsedName(R, S, SS: &SS, /*ObjectType=*/QualType());
14035
14036 if (R.isAmbiguous())
14037 return nullptr;
14038
14039 if (R.empty()) {
14040 if (!TryNamespaceTypoCorrection(S&: *this, R, Sc: S, SS, IdentLoc, Ident)) {
14041 Diag(Loc: IdentLoc, DiagID: diag::err_expected_namespace_name) << SS.getRange();
14042 return nullptr;
14043 }
14044 }
14045 assert(!R.isAmbiguous() && !R.empty());
14046 auto *ND = cast<NamespaceBaseDecl>(Val: R.getRepresentativeDecl());
14047
14048 // Check if we have a previous declaration with the same name.
14049 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
14050 RedeclarationKind::ForVisibleRedeclaration);
14051 LookupName(R&: PrevR, S);
14052
14053 // Check we're not shadowing a template parameter.
14054 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
14055 DiagnoseTemplateParameterShadow(Loc: AliasLoc, PrevDecl: PrevR.getFoundDecl());
14056 PrevR.clear();
14057 }
14058
14059 // Filter out any other lookup result from an enclosing scope.
14060 FilterLookupForScope(R&: PrevR, Ctx: CurContext, S, /*ConsiderLinkage*/false,
14061 /*AllowInlineNamespace*/false);
14062
14063 // Find the previous declaration and check that we can redeclare it.
14064 NamespaceAliasDecl *Prev = nullptr;
14065 if (PrevR.isSingleResult()) {
14066 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
14067 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(Val: PrevDecl)) {
14068 // We already have an alias with the same name that points to the same
14069 // namespace; check that it matches.
14070 if (AD->getNamespace()->Equals(DC: getNamespaceDecl(D: ND))) {
14071 Prev = AD;
14072 } else if (isVisible(D: PrevDecl)) {
14073 Diag(Loc: AliasLoc, DiagID: diag::err_redefinition_different_namespace_alias)
14074 << Alias;
14075 Diag(Loc: AD->getLocation(), DiagID: diag::note_previous_namespace_alias)
14076 << AD->getNamespace();
14077 return nullptr;
14078 }
14079 } else if (isVisible(D: PrevDecl)) {
14080 unsigned DiagID = isa<NamespaceDecl>(Val: PrevDecl->getUnderlyingDecl())
14081 ? diag::err_redefinition
14082 : diag::err_redefinition_different_kind;
14083 Diag(Loc: AliasLoc, DiagID) << Alias;
14084 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_definition);
14085 return nullptr;
14086 }
14087 }
14088
14089 // The use of a nested name specifier may trigger deprecation warnings.
14090 DiagnoseUseOfDecl(D: ND, Locs: IdentLoc);
14091
14092 NamespaceAliasDecl *AliasDecl =
14093 NamespaceAliasDecl::Create(C&: Context, DC: CurContext, NamespaceLoc, AliasLoc,
14094 Alias, QualifierLoc: SS.getWithLocInContext(Context),
14095 IdentLoc, Namespace: ND);
14096 if (Prev)
14097 AliasDecl->setPreviousDecl(Prev);
14098
14099 PushOnScopeChains(D: AliasDecl, S);
14100 return AliasDecl;
14101}
14102
14103namespace {
14104struct SpecialMemberExceptionSpecInfo
14105 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
14106 SourceLocation Loc;
14107 Sema::ImplicitExceptionSpecification ExceptSpec;
14108
14109 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
14110 CXXSpecialMemberKind CSM,
14111 Sema::InheritedConstructorInfo *ICI,
14112 SourceLocation Loc)
14113 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
14114
14115 bool visitBase(CXXBaseSpecifier *Base);
14116 bool visitField(FieldDecl *FD);
14117
14118 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
14119 unsigned Quals);
14120
14121 void visitSubobjectCall(Subobject Subobj,
14122 Sema::SpecialMemberOverloadResult SMOR);
14123};
14124}
14125
14126bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
14127 auto *BaseClass = Base->getType()->getAsCXXRecordDecl();
14128 if (!BaseClass)
14129 return false;
14130
14131 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(Class: BaseClass);
14132 if (auto *BaseCtor = SMOR.getMethod()) {
14133 visitSubobjectCall(Subobj: Base, SMOR: BaseCtor);
14134 return false;
14135 }
14136
14137 visitClassSubobject(Class: BaseClass, Subobj: Base, Quals: 0);
14138 return false;
14139}
14140
14141bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
14142 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
14143 FD->hasInClassInitializer()) {
14144 Expr *E = FD->getInClassInitializer();
14145 if (!E)
14146 // FIXME: It's a little wasteful to build and throw away a
14147 // CXXDefaultInitExpr here.
14148 // FIXME: We should have a single context note pointing at Loc, and
14149 // this location should be MD->getLocation() instead, since that's
14150 // the location where we actually use the default init expression.
14151 E = S.BuildCXXCtorDefaultInitExpr(Loc, Field: FD).get();
14152 if (E)
14153 ExceptSpec.CalledExpr(E);
14154 } else if (auto *RD = S.Context.getBaseElementType(QT: FD->getType())
14155 ->getAsCXXRecordDecl()) {
14156 visitClassSubobject(Class: RD, Subobj: FD, Quals: FD->getType().getCVRQualifiers());
14157 }
14158 return false;
14159}
14160
14161void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
14162 Subobject Subobj,
14163 unsigned Quals) {
14164 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
14165 bool IsMutable = Field && Field->isMutable();
14166 visitSubobjectCall(Subobj, SMOR: lookupIn(Class, Quals, IsMutable));
14167}
14168
14169void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
14170 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
14171 // Note, if lookup fails, it doesn't matter what exception specification we
14172 // choose because the special member will be deleted.
14173 if (CXXMethodDecl *MD = SMOR.getMethod())
14174 ExceptSpec.CalledDecl(CallLoc: getSubobjectLoc(Subobj), Method: MD);
14175}
14176
14177bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) {
14178 llvm::APSInt Result;
14179 ExprResult Converted = CheckConvertedConstantExpression(
14180 From: ExplicitSpec.getExpr(), T: Context.BoolTy, Value&: Result, CCE: CCEKind::ExplicitBool);
14181 ExplicitSpec.setExpr(Converted.get());
14182 if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
14183 ExplicitSpec.setKind(Result.getBoolValue()
14184 ? ExplicitSpecKind::ResolvedTrue
14185 : ExplicitSpecKind::ResolvedFalse);
14186 return true;
14187 }
14188 ExplicitSpec.setKind(ExplicitSpecKind::Unresolved);
14189 return false;
14190}
14191
14192ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) {
14193 ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved);
14194 if (!ExplicitExpr->isTypeDependent())
14195 tryResolveExplicitSpecifier(ExplicitSpec&: ES);
14196 return ES;
14197}
14198
14199static Sema::ImplicitExceptionSpecification
14200ComputeDefaultedSpecialMemberExceptionSpec(
14201 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, CXXSpecialMemberKind CSM,
14202 Sema::InheritedConstructorInfo *ICI) {
14203 ComputingExceptionSpec CES(S, MD, Loc);
14204
14205 CXXRecordDecl *ClassDecl = MD->getParent();
14206
14207 // C++ [except.spec]p14:
14208 // An implicitly declared special member function (Clause 12) shall have an
14209 // exception-specification. [...]
14210 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
14211 if (ClassDecl->isInvalidDecl())
14212 return Info.ExceptSpec;
14213
14214 // FIXME: If this diagnostic fires, we're probably missing a check for
14215 // attempting to resolve an exception specification before it's known
14216 // at a higher level.
14217 if (S.RequireCompleteType(Loc: MD->getLocation(),
14218 T: S.Context.getCanonicalTagType(TD: ClassDecl),
14219 DiagID: diag::err_exception_spec_incomplete_type))
14220 return Info.ExceptSpec;
14221
14222 // C++1z [except.spec]p7:
14223 // [Look for exceptions thrown by] a constructor selected [...] to
14224 // initialize a potentially constructed subobject,
14225 // C++1z [except.spec]p8:
14226 // The exception specification for an implicitly-declared destructor, or a
14227 // destructor without a noexcept-specifier, is potentially-throwing if and
14228 // only if any of the destructors for any of its potentially constructed
14229 // subojects is potentially throwing.
14230 // FIXME: We respect the first rule but ignore the "potentially constructed"
14231 // in the second rule to resolve a core issue (no number yet) that would have
14232 // us reject:
14233 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
14234 // struct B : A {};
14235 // struct C : B { void f(); };
14236 // ... due to giving B::~B() a non-throwing exception specification.
14237 Info.visit(Bases: Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
14238 : Info.VisitAllBases);
14239
14240 return Info.ExceptSpec;
14241}
14242
14243namespace {
14244/// RAII object to register a special member as being currently declared.
14245struct DeclaringSpecialMember {
14246 Sema &S;
14247 Sema::SpecialMemberDecl D;
14248 Sema::ContextRAII SavedContext;
14249 bool WasAlreadyBeingDeclared;
14250
14251 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, CXXSpecialMemberKind CSM)
14252 : S(S), D(RD, CSM), SavedContext(S, RD) {
14253 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(Ptr: D).second;
14254 if (WasAlreadyBeingDeclared)
14255 // This almost never happens, but if it does, ensure that our cache
14256 // doesn't contain a stale result.
14257 S.SpecialMemberCache.clear();
14258 else {
14259 // Register a note to be produced if we encounter an error while
14260 // declaring the special member.
14261 Sema::CodeSynthesisContext Ctx;
14262 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
14263 // FIXME: We don't have a location to use here. Using the class's
14264 // location maintains the fiction that we declare all special members
14265 // with the class, but (1) it's not clear that lying about that helps our
14266 // users understand what's going on, and (2) there may be outer contexts
14267 // on the stack (some of which are relevant) and printing them exposes
14268 // our lies.
14269 Ctx.PointOfInstantiation = RD->getLocation();
14270 Ctx.Entity = RD;
14271 Ctx.SpecialMember = CSM;
14272 S.pushCodeSynthesisContext(Ctx);
14273 }
14274 }
14275 ~DeclaringSpecialMember() {
14276 if (!WasAlreadyBeingDeclared) {
14277 S.SpecialMembersBeingDeclared.erase(Ptr: D);
14278 S.popCodeSynthesisContext();
14279 }
14280 }
14281
14282 /// Are we already trying to declare this special member?
14283 bool isAlreadyBeingDeclared() const {
14284 return WasAlreadyBeingDeclared;
14285 }
14286};
14287}
14288
14289void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
14290 // Look up any existing declarations, but don't trigger declaration of all
14291 // implicit special members with this name.
14292 DeclarationName Name = FD->getDeclName();
14293 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
14294 RedeclarationKind::ForExternalRedeclaration);
14295 for (auto *D : FD->getParent()->lookup(Name))
14296 if (auto *Acceptable = R.getAcceptableDecl(D))
14297 R.addDecl(D: Acceptable);
14298 R.resolveKind();
14299 R.suppressDiagnostics();
14300
14301 CheckFunctionDeclaration(S, NewFD: FD, Previous&: R, /*IsMemberSpecialization*/ false,
14302 DeclIsDefn: FD->isThisDeclarationADefinition());
14303}
14304
14305void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
14306 QualType ResultTy,
14307 ArrayRef<QualType> Args) {
14308 // Build an exception specification pointing back at this constructor.
14309 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(S&: *this, MD: SpecialMem);
14310
14311 LangAS AS = getDefaultCXXMethodAddrSpace();
14312 if (AS != LangAS::Default) {
14313 EPI.TypeQuals.addAddressSpace(space: AS);
14314 }
14315
14316 auto QT = Context.getFunctionType(ResultTy, Args, EPI);
14317 SpecialMem->setType(QT);
14318
14319 // During template instantiation of implicit special member functions we need
14320 // a reliable TypeSourceInfo for the function prototype in order to allow
14321 // functions to be substituted.
14322 if (inTemplateInstantiation() && isLambdaMethod(DC: SpecialMem)) {
14323 TypeSourceInfo *TSI =
14324 Context.getTrivialTypeSourceInfo(T: SpecialMem->getType());
14325 SpecialMem->setTypeSourceInfo(TSI);
14326 }
14327}
14328
14329CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
14330 CXXRecordDecl *ClassDecl) {
14331 // C++ [class.ctor]p5:
14332 // A default constructor for a class X is a constructor of class X
14333 // that can be called without an argument. If there is no
14334 // user-declared constructor for class X, a default constructor is
14335 // implicitly declared. An implicitly-declared default constructor
14336 // is an inline public member of its class.
14337 assert(ClassDecl->needsImplicitDefaultConstructor() &&
14338 "Should not build implicit default constructor!");
14339
14340 DeclaringSpecialMember DSM(*this, ClassDecl,
14341 CXXSpecialMemberKind::DefaultConstructor);
14342 if (DSM.isAlreadyBeingDeclared())
14343 return nullptr;
14344
14345 bool Constexpr = defaultedSpecialMemberIsConstexpr(
14346 S&: *this, ClassDecl, CSM: CXXSpecialMemberKind::DefaultConstructor, ConstArg: false);
14347
14348 // Create the actual constructor declaration.
14349 CanQualType ClassType = Context.getCanonicalTagType(TD: ClassDecl);
14350 SourceLocation ClassLoc = ClassDecl->getLocation();
14351 DeclarationName Name
14352 = Context.DeclarationNames.getCXXConstructorName(Ty: ClassType);
14353 DeclarationNameInfo NameInfo(Name, ClassLoc);
14354 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
14355 C&: Context, RD: ClassDecl, StartLoc: ClassLoc, NameInfo, /*Type*/ T: QualType(),
14356 /*TInfo=*/nullptr, ES: ExplicitSpecifier(),
14357 UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
14358 /*isInline=*/true, /*isImplicitlyDeclared=*/true,
14359 ConstexprKind: Constexpr ? ConstexprSpecKind::Constexpr
14360 : ConstexprSpecKind::Unspecified);
14361 DefaultCon->setAccess(AS_public);
14362 DefaultCon->setDefaulted();
14363
14364 setupImplicitSpecialMemberType(SpecialMem: DefaultCon, ResultTy: Context.VoidTy, Args: {});
14365
14366 if (getLangOpts().CUDA)
14367 CUDA().inferTargetForImplicitSpecialMember(
14368 ClassDecl, CSM: CXXSpecialMemberKind::DefaultConstructor, MemberDecl: DefaultCon,
14369 /* ConstRHS */ false,
14370 /* Diagnose */ false);
14371
14372 // We don't need to use SpecialMemberIsTrivial here; triviality for default
14373 // constructors is easy to compute.
14374 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
14375
14376 // Note that we have declared this constructor.
14377 ++getASTContext().NumImplicitDefaultConstructorsDeclared;
14378
14379 Scope *S = getScopeForContext(Ctx: ClassDecl);
14380 CheckImplicitSpecialMemberDeclaration(S, FD: DefaultCon);
14381
14382 if (ShouldDeleteSpecialMember(MD: DefaultCon,
14383 CSM: CXXSpecialMemberKind::DefaultConstructor))
14384 SetDeclDeleted(dcl: DefaultCon, DelLoc: ClassLoc);
14385
14386 if (S)
14387 PushOnScopeChains(D: DefaultCon, S, AddToContext: false);
14388 ClassDecl->addDecl(D: DefaultCon);
14389
14390 return DefaultCon;
14391}
14392
14393void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
14394 CXXConstructorDecl *Constructor) {
14395 DefaultedFunctionFPFeaturesRAII RestoreFP(*this, Constructor);
14396 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
14397 !Constructor->doesThisDeclarationHaveABody() &&
14398 !Constructor->isDeleted()) &&
14399 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
14400 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
14401 return;
14402
14403 CXXRecordDecl *ClassDecl = Constructor->getParent();
14404 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
14405 if (ClassDecl->isInvalidDecl()) {
14406 return;
14407 }
14408
14409 SynthesizedFunctionScope Scope(*this, Constructor);
14410
14411 // The exception specification is needed because we are defining the
14412 // function.
14413 ResolveExceptionSpec(Loc: CurrentLocation,
14414 FPT: Constructor->getType()->castAs<FunctionProtoType>());
14415 MarkVTableUsed(Loc: CurrentLocation, Class: ClassDecl);
14416
14417 // Add a context note for diagnostics produced after this point.
14418 Scope.addContextNote(UseLoc: CurrentLocation);
14419
14420 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
14421 Constructor->setInvalidDecl();
14422 return;
14423 }
14424
14425 SourceLocation Loc = Constructor->getEndLoc().isValid()
14426 ? Constructor->getEndLoc()
14427 : Constructor->getLocation();
14428 Constructor->setBody(new (Context) CompoundStmt(Loc));
14429 Constructor->markUsed(C&: Context);
14430
14431 if (ASTMutationListener *L = getASTMutationListener()) {
14432 L->CompletedImplicitDefinition(D: Constructor);
14433 }
14434
14435 DiagnoseUninitializedFields(SemaRef&: *this, Constructor);
14436
14437 // The synthesized body applies the class's NSDMIs and never reaches the
14438 // normal IssueWarnings path, so run lifetime safety on it here.
14439 AnalysisWarnings.IssueWarningsForImplicitFunction(D: Constructor);
14440}
14441
14442void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
14443 // Perform any delayed checks on exception specifications.
14444 CheckDelayedMemberExceptionSpecs();
14445}
14446
14447/// Find or create the fake constructor we synthesize to model constructing an
14448/// object of a derived class via a constructor of a base class.
14449CXXConstructorDecl *
14450Sema::findInheritingConstructor(SourceLocation Loc,
14451 CXXConstructorDecl *BaseCtor,
14452 ConstructorUsingShadowDecl *Shadow) {
14453 CXXRecordDecl *Derived = Shadow->getParent();
14454 SourceLocation UsingLoc = Shadow->getLocation();
14455
14456 // FIXME: Add a new kind of DeclarationName for an inherited constructor.
14457 // For now we use the name of the base class constructor as a member of the
14458 // derived class to indicate a (fake) inherited constructor name.
14459 DeclarationName Name = BaseCtor->getDeclName();
14460
14461 // Check to see if we already have a fake constructor for this inherited
14462 // constructor call.
14463 for (NamedDecl *Ctor : Derived->lookup(Name))
14464 if (declaresSameEntity(D1: cast<CXXConstructorDecl>(Val: Ctor)
14465 ->getInheritedConstructor()
14466 .getConstructor(),
14467 D2: BaseCtor))
14468 return cast<CXXConstructorDecl>(Val: Ctor);
14469
14470 DeclarationNameInfo NameInfo(Name, UsingLoc);
14471 TypeSourceInfo *TInfo =
14472 Context.getTrivialTypeSourceInfo(T: BaseCtor->getType(), Loc: UsingLoc);
14473 FunctionProtoTypeLoc ProtoLoc =
14474 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
14475
14476 // Check the inherited constructor is valid and find the list of base classes
14477 // from which it was inherited.
14478 InheritedConstructorInfo ICI(*this, Loc, Shadow);
14479
14480 bool Constexpr = BaseCtor->isConstexpr() &&
14481 defaultedSpecialMemberIsConstexpr(
14482 S&: *this, ClassDecl: Derived, CSM: CXXSpecialMemberKind::DefaultConstructor,
14483 ConstArg: false, InheritedCtor: BaseCtor, Inherited: &ICI);
14484
14485 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
14486 C&: Context, RD: Derived, StartLoc: UsingLoc, NameInfo, T: TInfo->getType(), TInfo,
14487 ES: BaseCtor->getExplicitSpecifier(), UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
14488 /*isInline=*/true,
14489 /*isImplicitlyDeclared=*/true,
14490 ConstexprKind: Constexpr ? BaseCtor->getConstexprKind() : ConstexprSpecKind::Unspecified,
14491 Inherited: InheritedConstructor(Shadow, BaseCtor),
14492 TrailingRequiresClause: BaseCtor->getTrailingRequiresClause());
14493 if (Shadow->isInvalidDecl())
14494 DerivedCtor->setInvalidDecl();
14495
14496 // Build an unevaluated exception specification for this fake constructor.
14497 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
14498 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
14499 EPI.ExceptionSpec.Type = EST_Unevaluated;
14500 EPI.ExceptionSpec.SourceDecl = DerivedCtor;
14501 DerivedCtor->setType(Context.getFunctionType(ResultTy: FPT->getReturnType(),
14502 Args: FPT->getParamTypes(), EPI));
14503
14504 // Build the parameter declarations.
14505 SmallVector<ParmVarDecl *, 16> ParamDecls;
14506 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
14507 TypeSourceInfo *TInfo =
14508 Context.getTrivialTypeSourceInfo(T: FPT->getParamType(i: I), Loc: UsingLoc);
14509 ParmVarDecl *PD = ParmVarDecl::Create(
14510 C&: Context, DC: DerivedCtor, StartLoc: UsingLoc, IdLoc: UsingLoc, /*IdentifierInfo=*/Id: nullptr,
14511 T: FPT->getParamType(i: I), TInfo, S: SC_None, /*DefArg=*/nullptr);
14512 PD->setScopeInfo(scopeDepth: 0, parameterIndex: I);
14513 PD->setImplicit();
14514 // Ensure attributes are propagated onto parameters (this matters for
14515 // format, pass_object_size, ...).
14516 mergeDeclAttributes(New: PD, Old: BaseCtor->getParamDecl(i: I));
14517 ParamDecls.push_back(Elt: PD);
14518 ProtoLoc.setParam(i: I, VD: PD);
14519 }
14520
14521 // Set up the new constructor.
14522 assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
14523 DerivedCtor->setAccess(BaseCtor->getAccess());
14524 DerivedCtor->setParams(ParamDecls);
14525 Derived->addDecl(D: DerivedCtor);
14526
14527 if (ShouldDeleteSpecialMember(MD: DerivedCtor,
14528 CSM: CXXSpecialMemberKind::DefaultConstructor, ICI: &ICI))
14529 SetDeclDeleted(dcl: DerivedCtor, DelLoc: UsingLoc);
14530
14531 return DerivedCtor;
14532}
14533
14534void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
14535 InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
14536 Ctor->getInheritedConstructor().getShadowDecl());
14537 ShouldDeleteSpecialMember(MD: Ctor, CSM: CXXSpecialMemberKind::DefaultConstructor,
14538 ICI: &ICI,
14539 /*Diagnose*/ true);
14540}
14541
14542void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
14543 CXXConstructorDecl *Constructor) {
14544 CXXRecordDecl *ClassDecl = Constructor->getParent();
14545 assert(Constructor->getInheritedConstructor() &&
14546 !Constructor->doesThisDeclarationHaveABody() &&
14547 !Constructor->isDeleted());
14548 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
14549 return;
14550
14551 // Initializations are performed "as if by a defaulted default constructor",
14552 // so enter the appropriate scope.
14553 SynthesizedFunctionScope Scope(*this, Constructor);
14554
14555 // The exception specification is needed because we are defining the
14556 // function.
14557 ResolveExceptionSpec(Loc: CurrentLocation,
14558 FPT: Constructor->getType()->castAs<FunctionProtoType>());
14559 MarkVTableUsed(Loc: CurrentLocation, Class: ClassDecl);
14560
14561 // Add a context note for diagnostics produced after this point.
14562 Scope.addContextNote(UseLoc: CurrentLocation);
14563
14564 ConstructorUsingShadowDecl *Shadow =
14565 Constructor->getInheritedConstructor().getShadowDecl();
14566 CXXConstructorDecl *InheritedCtor =
14567 Constructor->getInheritedConstructor().getConstructor();
14568
14569 // [class.inhctor.init]p1:
14570 // initialization proceeds as if a defaulted default constructor is used to
14571 // initialize the D object and each base class subobject from which the
14572 // constructor was inherited
14573
14574 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
14575 CXXRecordDecl *RD = Shadow->getParent();
14576 SourceLocation InitLoc = Shadow->getLocation();
14577
14578 // Build explicit initializers for all base classes from which the
14579 // constructor was inherited.
14580 SmallVector<CXXCtorInitializer*, 8> Inits;
14581 for (bool VBase : {false, true}) {
14582 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
14583 if (B.isVirtual() != VBase)
14584 continue;
14585
14586 auto *BaseRD = B.getType()->getAsCXXRecordDecl();
14587 if (!BaseRD)
14588 continue;
14589
14590 auto BaseCtor = ICI.findConstructorForBase(Base: BaseRD, Ctor: InheritedCtor);
14591 if (!BaseCtor.first)
14592 continue;
14593
14594 MarkFunctionReferenced(Loc: CurrentLocation, Func: BaseCtor.first);
14595 ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
14596 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
14597
14598 auto *TInfo = Context.getTrivialTypeSourceInfo(T: B.getType(), Loc: InitLoc);
14599 Inits.push_back(Elt: new (Context) CXXCtorInitializer(
14600 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
14601 SourceLocation()));
14602 }
14603 }
14604
14605 // We now proceed as if for a defaulted default constructor, with the relevant
14606 // initializers replaced.
14607
14608 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Initializers: Inits)) {
14609 Constructor->setInvalidDecl();
14610 return;
14611 }
14612
14613 Constructor->setBody(new (Context) CompoundStmt(InitLoc));
14614 Constructor->markUsed(C&: Context);
14615
14616 if (ASTMutationListener *L = getASTMutationListener()) {
14617 L->CompletedImplicitDefinition(D: Constructor);
14618 }
14619
14620 DiagnoseUninitializedFields(SemaRef&: *this, Constructor);
14621
14622 // The synthesized body applies the class's NSDMIs and never reaches the
14623 // normal IssueWarnings path, so run lifetime safety on it here.
14624 AnalysisWarnings.IssueWarningsForImplicitFunction(D: Constructor);
14625}
14626
14627CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
14628 // C++ [class.dtor]p2:
14629 // If a class has no user-declared destructor, a destructor is
14630 // declared implicitly. An implicitly-declared destructor is an
14631 // inline public member of its class.
14632 assert(ClassDecl->needsImplicitDestructor());
14633
14634 DeclaringSpecialMember DSM(*this, ClassDecl,
14635 CXXSpecialMemberKind::Destructor);
14636 if (DSM.isAlreadyBeingDeclared())
14637 return nullptr;
14638
14639 bool Constexpr = defaultedSpecialMemberIsConstexpr(
14640 S&: *this, ClassDecl, CSM: CXXSpecialMemberKind::Destructor, ConstArg: false);
14641
14642 // Create the actual destructor declaration.
14643 CanQualType ClassType = Context.getCanonicalTagType(TD: ClassDecl);
14644 SourceLocation ClassLoc = ClassDecl->getLocation();
14645 DeclarationName Name
14646 = Context.DeclarationNames.getCXXDestructorName(Ty: ClassType);
14647 DeclarationNameInfo NameInfo(Name, ClassLoc);
14648 CXXDestructorDecl *Destructor = CXXDestructorDecl::Create(
14649 C&: Context, RD: ClassDecl, StartLoc: ClassLoc, NameInfo, T: QualType(), TInfo: nullptr,
14650 UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
14651 /*isInline=*/true,
14652 /*isImplicitlyDeclared=*/true,
14653 ConstexprKind: Constexpr ? ConstexprSpecKind::Constexpr
14654 : ConstexprSpecKind::Unspecified);
14655 Destructor->setAccess(AS_public);
14656 Destructor->setDefaulted();
14657
14658 setupImplicitSpecialMemberType(SpecialMem: Destructor, ResultTy: Context.VoidTy, Args: {});
14659
14660 if (getLangOpts().CUDA)
14661 CUDA().inferTargetForImplicitSpecialMember(
14662 ClassDecl, CSM: CXXSpecialMemberKind::Destructor, MemberDecl: Destructor,
14663 /* ConstRHS */ false,
14664 /* Diagnose */ false);
14665
14666 // We don't need to use SpecialMemberIsTrivial here; triviality for
14667 // destructors is easy to compute.
14668 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
14669 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
14670 ClassDecl->hasTrivialDestructorForCall());
14671
14672 // Note that we have declared this destructor.
14673 ++getASTContext().NumImplicitDestructorsDeclared;
14674
14675 Scope *S = getScopeForContext(Ctx: ClassDecl);
14676 CheckImplicitSpecialMemberDeclaration(S, FD: Destructor);
14677
14678 // We can't check whether an implicit destructor is deleted before we complete
14679 // the definition of the class, because its validity depends on the alignment
14680 // of the class. We'll check this from ActOnFields once the class is complete.
14681 if (ClassDecl->isCompleteDefinition() &&
14682 ShouldDeleteSpecialMember(MD: Destructor, CSM: CXXSpecialMemberKind::Destructor))
14683 SetDeclDeleted(dcl: Destructor, DelLoc: ClassLoc);
14684
14685 // Introduce this destructor into its scope.
14686 if (S)
14687 PushOnScopeChains(D: Destructor, S, AddToContext: false);
14688 ClassDecl->addDecl(D: Destructor);
14689
14690 return Destructor;
14691}
14692
14693void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
14694 CXXDestructorDecl *Destructor) {
14695 DefaultedFunctionFPFeaturesRAII RestoreFP(*this, Destructor);
14696 assert((Destructor->isDefaulted() &&
14697 !Destructor->doesThisDeclarationHaveABody() &&
14698 !Destructor->isDeleted()) &&
14699 "DefineImplicitDestructor - call it for implicit default dtor");
14700 if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
14701 return;
14702
14703 CXXRecordDecl *ClassDecl = Destructor->getParent();
14704 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
14705
14706 SynthesizedFunctionScope Scope(*this, Destructor);
14707
14708 // The exception specification is needed because we are defining the
14709 // function.
14710 ResolveExceptionSpec(Loc: CurrentLocation,
14711 FPT: Destructor->getType()->castAs<FunctionProtoType>());
14712 MarkVTableUsed(Loc: CurrentLocation, Class: ClassDecl);
14713
14714 // Add a context note for diagnostics produced after this point.
14715 Scope.addContextNote(UseLoc: CurrentLocation);
14716
14717 MarkBaseAndMemberDestructorsReferenced(Location: Destructor->getLocation(),
14718 ClassDecl: Destructor->getParent());
14719
14720 if (CheckDestructor(Destructor)) {
14721 Destructor->setInvalidDecl();
14722 return;
14723 }
14724
14725 SourceLocation Loc = Destructor->getEndLoc().isValid()
14726 ? Destructor->getEndLoc()
14727 : Destructor->getLocation();
14728 Destructor->setBody(new (Context) CompoundStmt(Loc));
14729 Destructor->markUsed(C&: Context);
14730
14731 if (ASTMutationListener *L = getASTMutationListener()) {
14732 L->CompletedImplicitDefinition(D: Destructor);
14733 }
14734}
14735
14736void Sema::CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
14737 CXXDestructorDecl *Destructor) {
14738 if (Destructor->isInvalidDecl())
14739 return;
14740
14741 CXXRecordDecl *ClassDecl = Destructor->getParent();
14742 assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&
14743 "implicit complete dtors unneeded outside MS ABI");
14744 assert(ClassDecl->getNumVBases() > 0 &&
14745 "complete dtor only exists for classes with vbases");
14746
14747 SynthesizedFunctionScope Scope(*this, Destructor);
14748
14749 // Add a context note for diagnostics produced after this point.
14750 Scope.addContextNote(UseLoc: CurrentLocation);
14751
14752 MarkVirtualBaseDestructorsReferenced(Location: Destructor->getLocation(), ClassDecl);
14753}
14754
14755void Sema::ActOnFinishCXXMemberDecls() {
14756 // If the context is an invalid C++ class, just suppress these checks.
14757 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: CurContext)) {
14758 if (Record->isInvalidDecl()) {
14759 DelayedOverridingExceptionSpecChecks.clear();
14760 DelayedEquivalentExceptionSpecChecks.clear();
14761 return;
14762 }
14763 checkForMultipleExportedDefaultConstructors(S&: *this, Class: Record);
14764 }
14765}
14766
14767void Sema::ActOnFinishCXXNonNestedClass() {
14768 referenceDLLExportedClassMethods();
14769
14770 if (!DelayedDllExportMemberFunctions.empty()) {
14771 SmallVector<CXXMethodDecl*, 4> WorkList;
14772 std::swap(LHS&: DelayedDllExportMemberFunctions, RHS&: WorkList);
14773 for (CXXMethodDecl *M : WorkList) {
14774 DefineDefaultedFunction(S&: *this, FD: M, DefaultLoc: M->getLocation());
14775
14776 // Pass the method to the consumer to get emitted. This is not necessary
14777 // for explicit instantiation definitions, as they will get emitted
14778 // anyway.
14779 if (M->getParent()->getTemplateSpecializationKind() !=
14780 TSK_ExplicitInstantiationDefinition)
14781 ActOnFinishInlineFunctionDef(D: M);
14782 }
14783 }
14784}
14785
14786void Sema::referenceDLLExportedClassMethods() {
14787 if (!DelayedDllExportClasses.empty()) {
14788 // Calling ReferenceDllExportedMembers might cause the current function to
14789 // be called again, so use a local copy of DelayedDllExportClasses.
14790 SmallVector<CXXRecordDecl *, 4> WorkList;
14791 std::swap(LHS&: DelayedDllExportClasses, RHS&: WorkList);
14792 for (CXXRecordDecl *Class : WorkList)
14793 ReferenceDllExportedMembers(S&: *this, Class);
14794 }
14795}
14796
14797void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
14798 assert(getLangOpts().CPlusPlus11 &&
14799 "adjusting dtor exception specs was introduced in c++11");
14800
14801 if (Destructor->isDependentContext())
14802 return;
14803
14804 // C++11 [class.dtor]p3:
14805 // A declaration of a destructor that does not have an exception-
14806 // specification is implicitly considered to have the same exception-
14807 // specification as an implicit declaration.
14808 const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>();
14809 if (DtorType->hasExceptionSpec())
14810 return;
14811
14812 // Replace the destructor's type, building off the existing one. Fortunately,
14813 // the only thing of interest in the destructor type is its extended info.
14814 // The return and arguments are fixed.
14815 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
14816 EPI.ExceptionSpec.Type = EST_Unevaluated;
14817 EPI.ExceptionSpec.SourceDecl = Destructor;
14818 Destructor->setType(Context.getFunctionType(ResultTy: Context.VoidTy, Args: {}, EPI));
14819
14820 // FIXME: If the destructor has a body that could throw, and the newly created
14821 // spec doesn't allow exceptions, we should emit a warning, because this
14822 // change in behavior can break conforming C++03 programs at runtime.
14823 // However, we don't have a body or an exception specification yet, so it
14824 // needs to be done somewhere else.
14825}
14826
14827namespace {
14828/// An abstract base class for all helper classes used in building the
14829// copy/move operators. These classes serve as factory functions and help us
14830// avoid using the same Expr* in the AST twice.
14831class ExprBuilder {
14832 ExprBuilder(const ExprBuilder&) = delete;
14833 ExprBuilder &operator=(const ExprBuilder&) = delete;
14834
14835protected:
14836 static Expr *assertNotNull(Expr *E) {
14837 assert(E && "Expression construction must not fail.");
14838 return E;
14839 }
14840
14841public:
14842 ExprBuilder() {}
14843 virtual ~ExprBuilder() {}
14844
14845 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
14846};
14847
14848class RefBuilder: public ExprBuilder {
14849 VarDecl *Var;
14850 QualType VarType;
14851
14852public:
14853 Expr *build(Sema &S, SourceLocation Loc) const override {
14854 return assertNotNull(E: S.BuildDeclRefExpr(D: Var, Ty: VarType, VK: VK_LValue, Loc));
14855 }
14856
14857 RefBuilder(VarDecl *Var, QualType VarType)
14858 : Var(Var), VarType(VarType) {}
14859};
14860
14861class ThisBuilder: public ExprBuilder {
14862public:
14863 Expr *build(Sema &S, SourceLocation Loc) const override {
14864 return assertNotNull(E: S.ActOnCXXThis(Loc).getAs<Expr>());
14865 }
14866};
14867
14868class CastBuilder: public ExprBuilder {
14869 const ExprBuilder &Builder;
14870 QualType Type;
14871 ExprValueKind Kind;
14872 const CXXCastPath &Path;
14873
14874public:
14875 Expr *build(Sema &S, SourceLocation Loc) const override {
14876 return assertNotNull(E: S.ImpCastExprToType(E: Builder.build(S, Loc), Type,
14877 CK: CK_UncheckedDerivedToBase, VK: Kind,
14878 BasePath: &Path).get());
14879 }
14880
14881 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
14882 const CXXCastPath &Path)
14883 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
14884};
14885
14886class DerefBuilder: public ExprBuilder {
14887 const ExprBuilder &Builder;
14888
14889public:
14890 Expr *build(Sema &S, SourceLocation Loc) const override {
14891 return assertNotNull(
14892 E: S.CreateBuiltinUnaryOp(OpLoc: Loc, Opc: UO_Deref, InputExpr: Builder.build(S, Loc)).get());
14893 }
14894
14895 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14896};
14897
14898class MemberBuilder: public ExprBuilder {
14899 const ExprBuilder &Builder;
14900 QualType Type;
14901 CXXScopeSpec SS;
14902 bool IsArrow;
14903 LookupResult &MemberLookup;
14904
14905public:
14906 Expr *build(Sema &S, SourceLocation Loc) const override {
14907 return assertNotNull(E: S.BuildMemberReferenceExpr(
14908 Base: Builder.build(S, Loc), BaseType: Type, OpLoc: Loc, IsArrow, SS, TemplateKWLoc: SourceLocation(),
14909 FirstQualifierInScope: nullptr, R&: MemberLookup, TemplateArgs: nullptr, S: nullptr).get());
14910 }
14911
14912 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
14913 LookupResult &MemberLookup)
14914 : Builder(Builder), Type(Type), IsArrow(IsArrow),
14915 MemberLookup(MemberLookup) {}
14916};
14917
14918class MoveCastBuilder: public ExprBuilder {
14919 const ExprBuilder &Builder;
14920
14921public:
14922 Expr *build(Sema &S, SourceLocation Loc) const override {
14923 return assertNotNull(E: CastForMoving(SemaRef&: S, E: Builder.build(S, Loc)));
14924 }
14925
14926 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14927};
14928
14929class LvalueConvBuilder: public ExprBuilder {
14930 const ExprBuilder &Builder;
14931
14932public:
14933 Expr *build(Sema &S, SourceLocation Loc) const override {
14934 return assertNotNull(
14935 E: S.DefaultLvalueConversion(E: Builder.build(S, Loc)).get());
14936 }
14937
14938 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14939};
14940
14941class SubscriptBuilder: public ExprBuilder {
14942 const ExprBuilder &Base;
14943 const ExprBuilder &Index;
14944
14945public:
14946 Expr *build(Sema &S, SourceLocation Loc) const override {
14947 return assertNotNull(E: S.CreateBuiltinArraySubscriptExpr(
14948 Base: Base.build(S, Loc), LLoc: Loc, Idx: Index.build(S, Loc), RLoc: Loc).get());
14949 }
14950
14951 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
14952 : Base(Base), Index(Index) {}
14953};
14954
14955} // end anonymous namespace
14956
14957/// When generating a defaulted copy or move assignment operator, if a field
14958/// should be copied with __builtin_memcpy rather than via explicit assignments,
14959/// do so. This optimization only applies for arrays of scalars, and for arrays
14960/// of class type where the selected copy/move-assignment operator is trivial.
14961static StmtResult
14962buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
14963 const ExprBuilder &ToB, const ExprBuilder &FromB) {
14964 // Compute the size of the memory buffer to be copied.
14965 QualType SizeType = S.Context.getSizeType();
14966 llvm::APInt Size(S.Context.getTypeSize(T: SizeType),
14967 S.Context.getTypeSizeInChars(T).getQuantity());
14968
14969 // Take the address of the field references for "from" and "to". We
14970 // directly construct UnaryOperators here because semantic analysis
14971 // does not permit us to take the address of an xvalue.
14972 Expr *From = FromB.build(S, Loc);
14973 From = UnaryOperator::Create(
14974 C: S.Context, input: From, opc: UO_AddrOf, type: S.Context.getPointerType(T: From->getType()),
14975 VK: VK_PRValue, OK: OK_Ordinary, l: Loc, CanOverflow: false, FPFeatures: S.CurFPFeatureOverrides());
14976 Expr *To = ToB.build(S, Loc);
14977 To = UnaryOperator::Create(
14978 C: S.Context, input: To, opc: UO_AddrOf, type: S.Context.getPointerType(T: To->getType()),
14979 VK: VK_PRValue, OK: OK_Ordinary, l: Loc, CanOverflow: false, FPFeatures: S.CurFPFeatureOverrides());
14980
14981 bool NeedsCollectableMemCpy = false;
14982 if (auto *RD = T->getBaseElementTypeUnsafe()->getAsRecordDecl())
14983 NeedsCollectableMemCpy = RD->hasObjectMember();
14984
14985 // Create a reference to the __builtin_objc_memmove_collectable function
14986 StringRef MemCpyName = NeedsCollectableMemCpy ?
14987 "__builtin_objc_memmove_collectable" :
14988 "__builtin_memcpy";
14989 LookupResult R(S, &S.Context.Idents.get(Name: MemCpyName), Loc,
14990 Sema::LookupOrdinaryName);
14991 S.LookupName(R, S: S.TUScope, AllowBuiltinCreation: true);
14992
14993 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
14994 if (!MemCpy)
14995 // Something went horribly wrong earlier, and we will have complained
14996 // about it.
14997 return StmtError();
14998
14999 ExprResult MemCpyRef = S.BuildDeclRefExpr(D: MemCpy, Ty: S.Context.BuiltinFnTy,
15000 VK: VK_PRValue, Loc, SS: nullptr);
15001 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
15002
15003 Expr *CallArgs[] = {
15004 To, From, IntegerLiteral::Create(C: S.Context, V: Size, type: SizeType, l: Loc)
15005 };
15006 ExprResult Call = S.BuildCallExpr(/*Scope=*/S: nullptr, Fn: MemCpyRef.get(),
15007 LParenLoc: Loc, ArgExprs: CallArgs, RParenLoc: Loc);
15008
15009 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
15010 return Call.getAs<Stmt>();
15011}
15012
15013/// Builds a statement that copies/moves the given entity from \p From to
15014/// \c To.
15015///
15016/// This routine is used to copy/move the members of a class with an
15017/// implicitly-declared copy/move assignment operator. When the entities being
15018/// copied are arrays, this routine builds for loops to copy them.
15019///
15020/// \param S The Sema object used for type-checking.
15021///
15022/// \param Loc The location where the implicit copy/move is being generated.
15023///
15024/// \param T The type of the expressions being copied/moved. Both expressions
15025/// must have this type.
15026///
15027/// \param To The expression we are copying/moving to.
15028///
15029/// \param From The expression we are copying/moving from.
15030///
15031/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
15032/// Otherwise, it's a non-static member subobject.
15033///
15034/// \param Copying Whether we're copying or moving.
15035///
15036/// \param Depth Internal parameter recording the depth of the recursion.
15037///
15038/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
15039/// if a memcpy should be used instead.
15040static StmtResult
15041buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
15042 const ExprBuilder &To, const ExprBuilder &From,
15043 bool CopyingBaseSubobject, bool Copying,
15044 unsigned Depth = 0) {
15045 // C++11 [class.copy]p28:
15046 // Each subobject is assigned in the manner appropriate to its type:
15047 //
15048 // - if the subobject is of class type, as if by a call to operator= with
15049 // the subobject as the object expression and the corresponding
15050 // subobject of x as a single function argument (as if by explicit
15051 // qualification; that is, ignoring any possible virtual overriding
15052 // functions in more derived classes);
15053 //
15054 // C++03 [class.copy]p13:
15055 // - if the subobject is of class type, the copy assignment operator for
15056 // the class is used (as if by explicit qualification; that is,
15057 // ignoring any possible virtual overriding functions in more derived
15058 // classes);
15059 if (auto *ClassDecl = T->getAsCXXRecordDecl()) {
15060 // Look for operator=.
15061 DeclarationName Name
15062 = S.Context.DeclarationNames.getCXXOperatorName(Op: OO_Equal);
15063 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
15064 S.LookupQualifiedName(R&: OpLookup, LookupCtx: ClassDecl, InUnqualifiedLookup: false);
15065
15066 // Prior to C++11, filter out any result that isn't a copy/move-assignment
15067 // operator.
15068 if (!S.getLangOpts().CPlusPlus11) {
15069 LookupResult::Filter F = OpLookup.makeFilter();
15070 while (F.hasNext()) {
15071 NamedDecl *D = F.next();
15072 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: D))
15073 if (Method->isCopyAssignmentOperator() ||
15074 (!Copying && Method->isMoveAssignmentOperator()))
15075 continue;
15076
15077 F.erase();
15078 }
15079 F.done();
15080 }
15081
15082 // Suppress the protected check (C++ [class.protected]) for each of the
15083 // assignment operators we found. This strange dance is required when
15084 // we're assigning via a base classes's copy-assignment operator. To
15085 // ensure that we're getting the right base class subobject (without
15086 // ambiguities), we need to cast "this" to that subobject type; to
15087 // ensure that we don't go through the virtual call mechanism, we need
15088 // to qualify the operator= name with the base class (see below). However,
15089 // this means that if the base class has a protected copy assignment
15090 // operator, the protected member access check will fail. So, we
15091 // rewrite "protected" access to "public" access in this case, since we
15092 // know by construction that we're calling from a derived class.
15093 if (CopyingBaseSubobject) {
15094 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
15095 L != LEnd; ++L) {
15096 if (L.getAccess() == AS_protected)
15097 L.setAccess(AS_public);
15098 }
15099 }
15100
15101 // Create the nested-name-specifier that will be used to qualify the
15102 // reference to operator=; this is required to suppress the virtual
15103 // call mechanism.
15104 CXXScopeSpec SS;
15105 // FIXME: Don't canonicalize this.
15106 const Type *CanonicalT = S.Context.getCanonicalType(T: T.getTypePtr());
15107 SS.MakeTrivial(Context&: S.Context, Qualifier: NestedNameSpecifier(CanonicalT), R: Loc);
15108
15109 // Create the reference to operator=.
15110 ExprResult OpEqualRef
15111 = S.BuildMemberReferenceExpr(Base: To.build(S, Loc), BaseType: T, OpLoc: Loc, /*IsArrow=*/false,
15112 SS, /*TemplateKWLoc=*/SourceLocation(),
15113 /*FirstQualifierInScope=*/nullptr,
15114 R&: OpLookup,
15115 /*TemplateArgs=*/nullptr, /*S*/nullptr,
15116 /*SuppressQualifierCheck=*/true);
15117 if (OpEqualRef.isInvalid())
15118 return StmtError();
15119
15120 // Build the call to the assignment operator.
15121
15122 Expr *FromInst = From.build(S, Loc);
15123 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/S: nullptr,
15124 MemExpr: OpEqualRef.getAs<Expr>(),
15125 LParenLoc: Loc, Args: FromInst, RParenLoc: Loc);
15126 if (Call.isInvalid())
15127 return StmtError();
15128
15129 // If we built a call to a trivial 'operator=' while copying an array,
15130 // bail out. We'll replace the whole shebang with a memcpy.
15131 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Val: Call.get());
15132 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
15133 return StmtResult((Stmt*)nullptr);
15134
15135 // Convert to an expression-statement, and clean up any produced
15136 // temporaries.
15137 return S.ActOnExprStmt(Arg: Call);
15138 }
15139
15140 // - if the subobject is of scalar type, the built-in assignment
15141 // operator is used.
15142 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
15143 if (!ArrayTy) {
15144 ExprResult Assignment = S.CreateBuiltinBinOp(
15145 OpLoc: Loc, Opc: BO_Assign, LHSExpr: To.build(S, Loc), RHSExpr: From.build(S, Loc));
15146 if (Assignment.isInvalid())
15147 return StmtError();
15148 return S.ActOnExprStmt(Arg: Assignment);
15149 }
15150
15151 // - if the subobject is an array, each element is assigned, in the
15152 // manner appropriate to the element type;
15153
15154 // Construct a loop over the array bounds, e.g.,
15155 //
15156 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
15157 //
15158 // that will copy each of the array elements.
15159 QualType SizeType = S.Context.getSizeType();
15160
15161 // Create the iteration variable.
15162 IdentifierInfo *IterationVarName = nullptr;
15163 {
15164 SmallString<8> Str;
15165 llvm::raw_svector_ostream OS(Str);
15166 OS << "__i" << Depth;
15167 IterationVarName = &S.Context.Idents.get(Name: OS.str());
15168 }
15169 VarDecl *IterationVar = VarDecl::Create(C&: S.Context, DC: S.CurContext, StartLoc: Loc, IdLoc: Loc,
15170 Id: IterationVarName, T: SizeType,
15171 TInfo: S.Context.getTrivialTypeSourceInfo(T: SizeType, Loc),
15172 S: SC_None);
15173
15174 // Initialize the iteration variable to zero.
15175 llvm::APInt Zero(S.Context.getTypeSize(T: SizeType), 0);
15176 IterationVar->setInit(IntegerLiteral::Create(C: S.Context, V: Zero, type: SizeType, l: Loc));
15177
15178 // Creates a reference to the iteration variable.
15179 RefBuilder IterationVarRef(IterationVar, SizeType);
15180 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
15181
15182 // Create the DeclStmt that holds the iteration variable.
15183 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
15184
15185 // Subscript the "from" and "to" expressions with the iteration variable.
15186 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
15187 MoveCastBuilder FromIndexMove(FromIndexCopy);
15188 const ExprBuilder *FromIndex;
15189 if (Copying)
15190 FromIndex = &FromIndexCopy;
15191 else
15192 FromIndex = &FromIndexMove;
15193
15194 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
15195
15196 // Build the copy/move for an individual element of the array.
15197 StmtResult Copy =
15198 buildSingleCopyAssignRecursively(S, Loc, T: ArrayTy->getElementType(),
15199 To: ToIndex, From: *FromIndex, CopyingBaseSubobject,
15200 Copying, Depth: Depth + 1);
15201 // Bail out if copying fails or if we determined that we should use memcpy.
15202 if (Copy.isInvalid() || !Copy.get())
15203 return Copy;
15204
15205 // Create the comparison against the array bound.
15206 llvm::APInt Upper
15207 = ArrayTy->getSize().zextOrTrunc(width: S.Context.getTypeSize(T: SizeType));
15208 Expr *Comparison = BinaryOperator::Create(
15209 C: S.Context, lhs: IterationVarRefRVal.build(S, Loc),
15210 rhs: IntegerLiteral::Create(C: S.Context, V: Upper, type: SizeType, l: Loc), opc: BO_NE,
15211 ResTy: S.Context.BoolTy, VK: VK_PRValue, OK: OK_Ordinary, opLoc: Loc,
15212 FPFeatures: S.CurFPFeatureOverrides());
15213
15214 // Create the pre-increment of the iteration variable. We can determine
15215 // whether the increment will overflow based on the value of the array
15216 // bound.
15217 Expr *Increment = UnaryOperator::Create(
15218 C: S.Context, input: IterationVarRef.build(S, Loc), opc: UO_PreInc, type: SizeType, VK: VK_LValue,
15219 OK: OK_Ordinary, l: Loc, CanOverflow: Upper.isMaxValue(), FPFeatures: S.CurFPFeatureOverrides());
15220
15221 // Construct the loop that copies all elements of this array.
15222 return S.ActOnForStmt(
15223 ForLoc: Loc, LParenLoc: Loc, First: InitStmt,
15224 Second: S.ActOnCondition(S: nullptr, Loc, SubExpr: Comparison, CK: Sema::ConditionKind::Boolean),
15225 Third: S.MakeFullDiscardedValueExpr(Arg: Increment), RParenLoc: Loc, Body: Copy.get());
15226}
15227
15228static StmtResult
15229buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
15230 const ExprBuilder &To, const ExprBuilder &From,
15231 bool CopyingBaseSubobject, bool Copying) {
15232 // Maybe we should use a memcpy?
15233 if (T->isArrayType() && !T.hasQualifiers() &&
15234 T.isTriviallyCopyableType(Context: S.Context))
15235 return buildMemcpyForAssignmentOp(S, Loc, T, ToB: To, FromB: From);
15236
15237 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
15238 CopyingBaseSubobject,
15239 Copying, Depth: 0));
15240
15241 // If we ended up picking a trivial assignment operator for an array of a
15242 // non-trivially-copyable class type, just emit a memcpy.
15243 if (!Result.isInvalid() && !Result.get())
15244 return buildMemcpyForAssignmentOp(S, Loc, T, ToB: To, FromB: From);
15245
15246 return Result;
15247}
15248
15249CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
15250 // Note: The following rules are largely analoguous to the copy
15251 // constructor rules. Note that virtual bases are not taken into account
15252 // for determining the argument type of the operator. Note also that
15253 // operators taking an object instead of a reference are allowed.
15254 assert(ClassDecl->needsImplicitCopyAssignment());
15255
15256 DeclaringSpecialMember DSM(*this, ClassDecl,
15257 CXXSpecialMemberKind::CopyAssignment);
15258 if (DSM.isAlreadyBeingDeclared())
15259 return nullptr;
15260
15261 QualType ArgType = Context.getTagType(Keyword: ElaboratedTypeKeyword::None,
15262 /*Qualifier=*/std::nullopt, TD: ClassDecl,
15263 /*OwnsTag=*/false);
15264 LangAS AS = getDefaultCXXMethodAddrSpace();
15265 if (AS != LangAS::Default)
15266 ArgType = Context.getAddrSpaceQualType(T: ArgType, AddressSpace: AS);
15267 QualType RetType = Context.getLValueReferenceType(T: ArgType);
15268 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
15269 if (Const)
15270 ArgType = ArgType.withConst();
15271
15272 ArgType = Context.getLValueReferenceType(T: ArgType);
15273
15274 bool Constexpr = defaultedSpecialMemberIsConstexpr(
15275 S&: *this, ClassDecl, CSM: CXXSpecialMemberKind::CopyAssignment, ConstArg: Const);
15276
15277 // An implicitly-declared copy assignment operator is an inline public
15278 // member of its class.
15279 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(Op: OO_Equal);
15280 SourceLocation ClassLoc = ClassDecl->getLocation();
15281 DeclarationNameInfo NameInfo(Name, ClassLoc);
15282 CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create(
15283 C&: Context, RD: ClassDecl, StartLoc: ClassLoc, NameInfo, T: QualType(),
15284 /*TInfo=*/nullptr, /*StorageClass=*/SC: SC_None,
15285 UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
15286 /*isInline=*/true,
15287 ConstexprKind: Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
15288 EndLocation: SourceLocation());
15289 CopyAssignment->setAccess(AS_public);
15290 CopyAssignment->setDefaulted();
15291 CopyAssignment->setImplicit();
15292
15293 setupImplicitSpecialMemberType(SpecialMem: CopyAssignment, ResultTy: RetType, Args: ArgType);
15294
15295 if (getLangOpts().CUDA)
15296 CUDA().inferTargetForImplicitSpecialMember(
15297 ClassDecl, CSM: CXXSpecialMemberKind::CopyAssignment, MemberDecl: CopyAssignment,
15298 /* ConstRHS */ Const,
15299 /* Diagnose */ false);
15300
15301 // Add the parameter to the operator.
15302 ParmVarDecl *FromParam = ParmVarDecl::Create(C&: Context, DC: CopyAssignment,
15303 StartLoc: ClassLoc, IdLoc: ClassLoc,
15304 /*Id=*/nullptr, T: ArgType,
15305 /*TInfo=*/nullptr, S: SC_None,
15306 DefArg: nullptr);
15307 CopyAssignment->setParams(FromParam);
15308
15309 CopyAssignment->setTrivial(
15310 ClassDecl->needsOverloadResolutionForCopyAssignment()
15311 ? SpecialMemberIsTrivial(MD: CopyAssignment,
15312 CSM: CXXSpecialMemberKind::CopyAssignment)
15313 : ClassDecl->hasTrivialCopyAssignment());
15314
15315 // Note that we have added this copy-assignment operator.
15316 ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
15317
15318 Scope *S = getScopeForContext(Ctx: ClassDecl);
15319 CheckImplicitSpecialMemberDeclaration(S, FD: CopyAssignment);
15320
15321 if (ShouldDeleteSpecialMember(MD: CopyAssignment,
15322 CSM: CXXSpecialMemberKind::CopyAssignment)) {
15323 ClassDecl->setImplicitCopyAssignmentIsDeleted();
15324 SetDeclDeleted(dcl: CopyAssignment, DelLoc: ClassLoc);
15325 }
15326
15327 if (S)
15328 PushOnScopeChains(D: CopyAssignment, S, AddToContext: false);
15329 ClassDecl->addDecl(D: CopyAssignment);
15330
15331 return CopyAssignment;
15332}
15333
15334/// Diagnose an implicit copy operation for a class which is odr-used, but
15335/// which is deprecated because the class has a user-declared copy constructor,
15336/// copy assignment operator, or destructor.
15337static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
15338 assert(CopyOp->isImplicit());
15339
15340 CXXRecordDecl *RD = CopyOp->getParent();
15341 CXXMethodDecl *UserDeclaredOperation = nullptr;
15342
15343 if (RD->hasUserDeclaredDestructor()) {
15344 UserDeclaredOperation = RD->getDestructor();
15345 } else if (!isa<CXXConstructorDecl>(Val: CopyOp) &&
15346 RD->hasUserDeclaredCopyConstructor()) {
15347 // Find any user-declared copy constructor.
15348 for (auto *I : RD->ctors()) {
15349 if (I->isCopyConstructor()) {
15350 UserDeclaredOperation = I;
15351 break;
15352 }
15353 }
15354 assert(UserDeclaredOperation);
15355 } else if (isa<CXXConstructorDecl>(Val: CopyOp) &&
15356 RD->hasUserDeclaredCopyAssignment()) {
15357 // Find any user-declared move assignment operator.
15358 for (auto *I : RD->methods()) {
15359 if (I->isCopyAssignmentOperator()) {
15360 UserDeclaredOperation = I;
15361 break;
15362 }
15363 }
15364 assert(UserDeclaredOperation);
15365 }
15366
15367 if (UserDeclaredOperation) {
15368 bool UDOIsUserProvided = UserDeclaredOperation->isUserProvided();
15369 bool UDOIsDestructor = isa<CXXDestructorDecl>(Val: UserDeclaredOperation);
15370 bool IsCopyAssignment = !isa<CXXConstructorDecl>(Val: CopyOp);
15371 unsigned DiagID =
15372 (UDOIsUserProvided && UDOIsDestructor)
15373 ? diag::warn_deprecated_copy_with_user_provided_dtor
15374 : (UDOIsUserProvided && !UDOIsDestructor)
15375 ? diag::warn_deprecated_copy_with_user_provided_copy
15376 : (!UDOIsUserProvided && UDOIsDestructor)
15377 ? diag::warn_deprecated_copy_with_dtor
15378 : diag::warn_deprecated_copy;
15379 S.Diag(Loc: UserDeclaredOperation->getLocation(), DiagID)
15380 << RD << IsCopyAssignment;
15381 }
15382}
15383
15384void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
15385 CXXMethodDecl *CopyAssignOperator) {
15386 DefaultedFunctionFPFeaturesRAII RestoreFP(*this, CopyAssignOperator);
15387 assert((CopyAssignOperator->isDefaulted() &&
15388 CopyAssignOperator->isOverloadedOperator() &&
15389 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
15390 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
15391 !CopyAssignOperator->isDeleted()) &&
15392 "DefineImplicitCopyAssignment called for wrong function");
15393 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
15394 return;
15395
15396 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
15397 if (ClassDecl->isInvalidDecl()) {
15398 CopyAssignOperator->setInvalidDecl();
15399 return;
15400 }
15401
15402 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
15403
15404 // The exception specification is needed because we are defining the
15405 // function.
15406 ResolveExceptionSpec(Loc: CurrentLocation,
15407 FPT: CopyAssignOperator->getType()->castAs<FunctionProtoType>());
15408
15409 // Add a context note for diagnostics produced after this point.
15410 Scope.addContextNote(UseLoc: CurrentLocation);
15411
15412 // C++11 [class.copy]p18:
15413 // The [definition of an implicitly declared copy assignment operator] is
15414 // deprecated if the class has a user-declared copy constructor or a
15415 // user-declared destructor.
15416 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
15417 diagnoseDeprecatedCopyOperation(S&: *this, CopyOp: CopyAssignOperator);
15418
15419 // C++0x [class.copy]p30:
15420 // The implicitly-defined or explicitly-defaulted copy assignment operator
15421 // for a non-union class X performs memberwise copy assignment of its
15422 // subobjects. The direct base classes of X are assigned first, in the
15423 // order of their declaration in the base-specifier-list, and then the
15424 // immediate non-static data members of X are assigned, in the order in
15425 // which they were declared in the class definition.
15426
15427 // The statements that form the synthesized function body.
15428 SmallVector<Stmt*, 8> Statements;
15429
15430 // The parameter for the "other" object, which we are copying from.
15431 ParmVarDecl *Other = CopyAssignOperator->getNonObjectParameter(I: 0);
15432 Qualifiers OtherQuals = Other->getType().getQualifiers();
15433 QualType OtherRefType = Other->getType();
15434 if (OtherRefType->isLValueReferenceType()) {
15435 OtherRefType = OtherRefType->getPointeeType();
15436 OtherQuals = OtherRefType.getQualifiers();
15437 }
15438
15439 // Our location for everything implicitly-generated.
15440 SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
15441 ? CopyAssignOperator->getEndLoc()
15442 : CopyAssignOperator->getLocation();
15443
15444 // Builds a DeclRefExpr for the "other" object.
15445 RefBuilder OtherRef(Other, OtherRefType);
15446
15447 // Builds the function object parameter.
15448 std::optional<ThisBuilder> This;
15449 std::optional<DerefBuilder> DerefThis;
15450 std::optional<RefBuilder> ExplicitObject;
15451 bool IsArrow = false;
15452 QualType ObjectType;
15453 if (CopyAssignOperator->isExplicitObjectMemberFunction()) {
15454 ObjectType = CopyAssignOperator->getParamDecl(i: 0)->getType();
15455 if (ObjectType->isReferenceType())
15456 ObjectType = ObjectType->getPointeeType();
15457 ExplicitObject.emplace(args: CopyAssignOperator->getParamDecl(i: 0), args&: ObjectType);
15458 } else {
15459 ObjectType = getCurrentThisType();
15460 This.emplace();
15461 DerefThis.emplace(args&: *This);
15462 IsArrow = !LangOpts.HLSL;
15463 }
15464 ExprBuilder &ObjectParameter =
15465 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15466 : static_cast<ExprBuilder &>(*This);
15467
15468 // Assign base classes.
15469 bool Invalid = false;
15470 for (auto &Base : ClassDecl->bases()) {
15471 // Form the assignment:
15472 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
15473 QualType BaseType = Base.getType().getUnqualifiedType();
15474 if (!BaseType->isRecordType()) {
15475 Invalid = true;
15476 continue;
15477 }
15478
15479 CXXCastPath BasePath;
15480 BasePath.push_back(Elt: &Base);
15481
15482 // Construct the "from" expression, which is an implicit cast to the
15483 // appropriately-qualified base type.
15484 CastBuilder From(OtherRef, Context.getQualifiedType(T: BaseType, Qs: OtherQuals),
15485 VK_LValue, BasePath);
15486
15487 // Dereference "this".
15488 CastBuilder To(
15489 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15490 : static_cast<ExprBuilder &>(*DerefThis),
15491 Context.getQualifiedType(T: BaseType, Qs: ObjectType.getQualifiers()),
15492 VK_LValue, BasePath);
15493
15494 // Build the copy.
15495 StmtResult Copy = buildSingleCopyAssign(S&: *this, Loc, T: BaseType,
15496 To, From,
15497 /*CopyingBaseSubobject=*/true,
15498 /*Copying=*/true);
15499 if (Copy.isInvalid()) {
15500 CopyAssignOperator->setInvalidDecl();
15501 return;
15502 }
15503
15504 // Success! Record the copy.
15505 Statements.push_back(Elt: Copy.getAs<Expr>());
15506 }
15507
15508 // A defaulted copy assignment operator for a union copies the object
15509 // representation as if by a memcpy, the same way the defaulted union copy
15510 // constructor does. The memberwise loop below skips union members.
15511 if (ClassDecl->isUnion()) {
15512 ExprBuilder &To = ExplicitObject
15513 ? static_cast<ExprBuilder &>(*ExplicitObject)
15514 : static_cast<ExprBuilder &>(*DerefThis);
15515 // Copying the object representation is correct even for a union that is
15516 // not trivially copyable, so -Wnontrivial-memcall is a false positive
15517 // here. Ignoring warnings rather than casting the arguments to void*
15518 // keeps them typed, which preserves their address space.
15519 IgnoreAllWarningDiagRAII IgnoreWarnings(Diags);
15520 StmtResult Copy = buildMemcpyForAssignmentOp(
15521 S&: *this, Loc, T: Context.getCanonicalTagType(TD: ClassDecl), ToB: To, FromB: OtherRef);
15522 if (Copy.isInvalid()) {
15523 CopyAssignOperator->setInvalidDecl();
15524 return;
15525 }
15526 Statements.push_back(Elt: Copy.getAs<Stmt>());
15527 }
15528
15529 // Assign non-static members.
15530 for (auto *Field : ClassDecl->fields()) {
15531 // Union members are copied by the whole-object memcpy emitted above.
15532 if (Field->isUnnamedBitField() || Field->getParent()->isUnion())
15533 continue;
15534
15535 if (Field->isInvalidDecl()) {
15536 Invalid = true;
15537 continue;
15538 }
15539
15540 // Check for members of reference type; we can't copy those.
15541 if (Field->getType()->isReferenceType()) {
15542 Diag(Loc: ClassDecl->getLocation(), DiagID: diag::err_uninitialized_member_for_assign)
15543 << Context.getCanonicalTagType(TD: ClassDecl) << 0
15544 << Field->getDeclName();
15545 Diag(Loc: Field->getLocation(), DiagID: diag::note_declared_at);
15546 Invalid = true;
15547 continue;
15548 }
15549
15550 // Check for members of const-qualified, non-class type.
15551 QualType BaseType = Context.getBaseElementType(QT: Field->getType());
15552 if (!BaseType->isRecordType() && BaseType.isConstQualified()) {
15553 Diag(Loc: ClassDecl->getLocation(), DiagID: diag::err_uninitialized_member_for_assign)
15554 << Context.getCanonicalTagType(TD: ClassDecl) << 1
15555 << Field->getDeclName();
15556 Diag(Loc: Field->getLocation(), DiagID: diag::note_declared_at);
15557 Invalid = true;
15558 continue;
15559 }
15560
15561 // Suppress assigning zero-width bitfields.
15562 if (Field->isZeroLengthBitField())
15563 continue;
15564
15565 QualType FieldType = Field->getType().getNonReferenceType();
15566 if (FieldType->isIncompleteArrayType()) {
15567 assert(ClassDecl->hasFlexibleArrayMember() &&
15568 "Incomplete array type is not valid");
15569 continue;
15570 }
15571
15572 // Build references to the field in the object we're copying from and to.
15573 CXXScopeSpec SS; // Intentionally empty
15574 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
15575 LookupMemberName);
15576 MemberLookup.addDecl(D: Field);
15577 MemberLookup.resolveKind();
15578
15579 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
15580 MemberBuilder To(ObjectParameter, ObjectType, IsArrow, MemberLookup);
15581 // Build the copy of this field.
15582 StmtResult Copy = buildSingleCopyAssign(S&: *this, Loc, T: FieldType,
15583 To, From,
15584 /*CopyingBaseSubobject=*/false,
15585 /*Copying=*/true);
15586 if (Copy.isInvalid()) {
15587 CopyAssignOperator->setInvalidDecl();
15588 return;
15589 }
15590
15591 // Success! Record the copy.
15592 Statements.push_back(Elt: Copy.getAs<Stmt>());
15593 }
15594
15595 if (!Invalid) {
15596 // Add a "return *this;"
15597 Expr *ThisExpr =
15598 (ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15599 : LangOpts.HLSL ? static_cast<ExprBuilder &>(*This)
15600 : static_cast<ExprBuilder &>(*DerefThis))
15601 .build(S&: *this, Loc);
15602 StmtResult Return = BuildReturnStmt(ReturnLoc: Loc, RetValExp: ThisExpr);
15603 if (Return.isInvalid())
15604 Invalid = true;
15605 else
15606 Statements.push_back(Elt: Return.getAs<Stmt>());
15607 }
15608
15609 if (Invalid) {
15610 CopyAssignOperator->setInvalidDecl();
15611 return;
15612 }
15613
15614 StmtResult Body;
15615 {
15616 CompoundScopeRAII CompoundScope(*this);
15617 Body = ActOnCompoundStmt(L: Loc, R: Loc, Elts: Statements,
15618 /*isStmtExpr=*/false);
15619 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
15620 }
15621 CopyAssignOperator->setBody(Body.getAs<Stmt>());
15622 CopyAssignOperator->markUsed(C&: Context);
15623
15624 if (ASTMutationListener *L = getASTMutationListener()) {
15625 L->CompletedImplicitDefinition(D: CopyAssignOperator);
15626 }
15627}
15628
15629CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
15630 assert(ClassDecl->needsImplicitMoveAssignment());
15631
15632 DeclaringSpecialMember DSM(*this, ClassDecl,
15633 CXXSpecialMemberKind::MoveAssignment);
15634 if (DSM.isAlreadyBeingDeclared())
15635 return nullptr;
15636
15637 // Note: The following rules are largely analoguous to the move
15638 // constructor rules.
15639
15640 QualType ArgType = Context.getTagType(Keyword: ElaboratedTypeKeyword::None,
15641 /*Qualifier=*/std::nullopt, TD: ClassDecl,
15642 /*OwnsTag=*/false);
15643 LangAS AS = getDefaultCXXMethodAddrSpace();
15644 if (AS != LangAS::Default)
15645 ArgType = Context.getAddrSpaceQualType(T: ArgType, AddressSpace: AS);
15646 QualType RetType = Context.getLValueReferenceType(T: ArgType);
15647 ArgType = Context.getRValueReferenceType(T: ArgType);
15648
15649 bool Constexpr = defaultedSpecialMemberIsConstexpr(
15650 S&: *this, ClassDecl, CSM: CXXSpecialMemberKind::MoveAssignment, ConstArg: false);
15651
15652 // An implicitly-declared move assignment operator is an inline public
15653 // member of its class.
15654 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(Op: OO_Equal);
15655 SourceLocation ClassLoc = ClassDecl->getLocation();
15656 DeclarationNameInfo NameInfo(Name, ClassLoc);
15657 CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create(
15658 C&: Context, RD: ClassDecl, StartLoc: ClassLoc, NameInfo, T: QualType(),
15659 /*TInfo=*/nullptr, /*StorageClass=*/SC: SC_None,
15660 UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
15661 /*isInline=*/true,
15662 ConstexprKind: Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
15663 EndLocation: SourceLocation());
15664 MoveAssignment->setAccess(AS_public);
15665 MoveAssignment->setDefaulted();
15666 MoveAssignment->setImplicit();
15667
15668 setupImplicitSpecialMemberType(SpecialMem: MoveAssignment, ResultTy: RetType, Args: ArgType);
15669
15670 if (getLangOpts().CUDA)
15671 CUDA().inferTargetForImplicitSpecialMember(
15672 ClassDecl, CSM: CXXSpecialMemberKind::MoveAssignment, MemberDecl: MoveAssignment,
15673 /* ConstRHS */ false,
15674 /* Diagnose */ false);
15675
15676 // Add the parameter to the operator.
15677 ParmVarDecl *FromParam = ParmVarDecl::Create(C&: Context, DC: MoveAssignment,
15678 StartLoc: ClassLoc, IdLoc: ClassLoc,
15679 /*Id=*/nullptr, T: ArgType,
15680 /*TInfo=*/nullptr, S: SC_None,
15681 DefArg: nullptr);
15682 MoveAssignment->setParams(FromParam);
15683
15684 MoveAssignment->setTrivial(
15685 ClassDecl->needsOverloadResolutionForMoveAssignment()
15686 ? SpecialMemberIsTrivial(MD: MoveAssignment,
15687 CSM: CXXSpecialMemberKind::MoveAssignment)
15688 : ClassDecl->hasTrivialMoveAssignment());
15689
15690 // Note that we have added this copy-assignment operator.
15691 ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
15692
15693 Scope *S = getScopeForContext(Ctx: ClassDecl);
15694 CheckImplicitSpecialMemberDeclaration(S, FD: MoveAssignment);
15695
15696 if (ShouldDeleteSpecialMember(MD: MoveAssignment,
15697 CSM: CXXSpecialMemberKind::MoveAssignment)) {
15698 ClassDecl->setImplicitMoveAssignmentIsDeleted();
15699 SetDeclDeleted(dcl: MoveAssignment, DelLoc: ClassLoc);
15700 }
15701
15702 if (S)
15703 PushOnScopeChains(D: MoveAssignment, S, AddToContext: false);
15704 ClassDecl->addDecl(D: MoveAssignment);
15705
15706 return MoveAssignment;
15707}
15708
15709/// Check if we're implicitly defining a move assignment operator for a class
15710/// with virtual bases. Such a move assignment might move-assign the virtual
15711/// base multiple times.
15712static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
15713 SourceLocation CurrentLocation) {
15714 assert(!Class->isDependentContext() && "should not define dependent move");
15715
15716 // Only a virtual base could get implicitly move-assigned multiple times.
15717 // Only a non-trivial move assignment can observe this. We only want to
15718 // diagnose if we implicitly define an assignment operator that assigns
15719 // two base classes, both of which move-assign the same virtual base.
15720 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
15721 Class->getNumBases() < 2)
15722 return;
15723
15724 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
15725 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
15726 VBaseMap VBases;
15727
15728 for (auto &BI : Class->bases()) {
15729 Worklist.push_back(Elt: &BI);
15730 while (!Worklist.empty()) {
15731 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
15732 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
15733
15734 // If the base has no non-trivial move assignment operators,
15735 // we don't care about moves from it.
15736 if (!Base->hasNonTrivialMoveAssignment())
15737 continue;
15738
15739 // If there's nothing virtual here, skip it.
15740 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
15741 continue;
15742
15743 // If we're not actually going to call a move assignment for this base,
15744 // or the selected move assignment is trivial, skip it.
15745 Sema::SpecialMemberOverloadResult SMOR =
15746 S.LookupSpecialMember(D: Base, SM: CXXSpecialMemberKind::MoveAssignment,
15747 /*ConstArg*/ false, /*VolatileArg*/ false,
15748 /*RValueThis*/ true, /*ConstThis*/ false,
15749 /*VolatileThis*/ false);
15750 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
15751 !SMOR.getMethod()->isMoveAssignmentOperator())
15752 continue;
15753
15754 if (BaseSpec->isVirtual()) {
15755 // We're going to move-assign this virtual base, and its move
15756 // assignment operator is not trivial. If this can happen for
15757 // multiple distinct direct bases of Class, diagnose it. (If it
15758 // only happens in one base, we'll diagnose it when synthesizing
15759 // that base class's move assignment operator.)
15760 CXXBaseSpecifier *&Existing =
15761 VBases.insert(KV: std::make_pair(x: Base->getCanonicalDecl(), y: &BI))
15762 .first->second;
15763 if (Existing && Existing != &BI) {
15764 S.Diag(Loc: CurrentLocation, DiagID: diag::warn_vbase_moved_multiple_times)
15765 << Class << Base;
15766 S.Diag(Loc: Existing->getBeginLoc(), DiagID: diag::note_vbase_moved_here)
15767 << (Base->getCanonicalDecl() ==
15768 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
15769 << Base << Existing->getType() << Existing->getSourceRange();
15770 S.Diag(Loc: BI.getBeginLoc(), DiagID: diag::note_vbase_moved_here)
15771 << (Base->getCanonicalDecl() ==
15772 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
15773 << Base << BI.getType() << BaseSpec->getSourceRange();
15774
15775 // Only diagnose each vbase once.
15776 Existing = nullptr;
15777 }
15778 } else {
15779 // Only walk over bases that have defaulted move assignment operators.
15780 // We assume that any user-provided move assignment operator handles
15781 // the multiple-moves-of-vbase case itself somehow.
15782 if (!SMOR.getMethod()->isDefaulted())
15783 continue;
15784
15785 // We're going to move the base classes of Base. Add them to the list.
15786 llvm::append_range(C&: Worklist, R: llvm::make_pointer_range(Range: Base->bases()));
15787 }
15788 }
15789 }
15790}
15791
15792void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
15793 CXXMethodDecl *MoveAssignOperator) {
15794 DefaultedFunctionFPFeaturesRAII RestoreFP(*this, MoveAssignOperator);
15795 assert((MoveAssignOperator->isDefaulted() &&
15796 MoveAssignOperator->isOverloadedOperator() &&
15797 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
15798 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
15799 !MoveAssignOperator->isDeleted()) &&
15800 "DefineImplicitMoveAssignment called for wrong function");
15801 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
15802 return;
15803
15804 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
15805 if (ClassDecl->isInvalidDecl()) {
15806 MoveAssignOperator->setInvalidDecl();
15807 return;
15808 }
15809
15810 // C++0x [class.copy]p28:
15811 // The implicitly-defined or move assignment operator for a non-union class
15812 // X performs memberwise move assignment of its subobjects. The direct base
15813 // classes of X are assigned first, in the order of their declaration in the
15814 // base-specifier-list, and then the immediate non-static data members of X
15815 // are assigned, in the order in which they were declared in the class
15816 // definition.
15817
15818 // Issue a warning if our implicit move assignment operator will move
15819 // from a virtual base more than once.
15820 checkMoveAssignmentForRepeatedMove(S&: *this, Class: ClassDecl, CurrentLocation);
15821
15822 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
15823
15824 // The exception specification is needed because we are defining the
15825 // function.
15826 ResolveExceptionSpec(Loc: CurrentLocation,
15827 FPT: MoveAssignOperator->getType()->castAs<FunctionProtoType>());
15828
15829 // Add a context note for diagnostics produced after this point.
15830 Scope.addContextNote(UseLoc: CurrentLocation);
15831
15832 // The statements that form the synthesized function body.
15833 SmallVector<Stmt*, 8> Statements;
15834
15835 // The parameter for the "other" object, which we are move from.
15836 ParmVarDecl *Other = MoveAssignOperator->getNonObjectParameter(I: 0);
15837 QualType OtherRefType =
15838 Other->getType()->castAs<RValueReferenceType>()->getPointeeType();
15839
15840 // Our location for everything implicitly-generated.
15841 SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
15842 ? MoveAssignOperator->getEndLoc()
15843 : MoveAssignOperator->getLocation();
15844
15845 // Builds a reference to the "other" object.
15846 RefBuilder OtherRef(Other, OtherRefType);
15847 // Cast to rvalue.
15848 MoveCastBuilder MoveOther(OtherRef);
15849
15850 // Builds the function object parameter.
15851 std::optional<ThisBuilder> This;
15852 std::optional<DerefBuilder> DerefThis;
15853 std::optional<RefBuilder> ExplicitObject;
15854 QualType ObjectType;
15855 bool IsArrow = false;
15856 if (MoveAssignOperator->isExplicitObjectMemberFunction()) {
15857 ObjectType = MoveAssignOperator->getParamDecl(i: 0)->getType();
15858 if (ObjectType->isReferenceType())
15859 ObjectType = ObjectType->getPointeeType();
15860 ExplicitObject.emplace(args: MoveAssignOperator->getParamDecl(i: 0), args&: ObjectType);
15861 } else {
15862 ObjectType = getCurrentThisType();
15863 This.emplace();
15864 DerefThis.emplace(args&: *This);
15865 IsArrow = !getLangOpts().HLSL;
15866 }
15867 ExprBuilder &ObjectParameter =
15868 ExplicitObject ? *ExplicitObject : static_cast<ExprBuilder &>(*This);
15869
15870 // Assign base classes.
15871 bool Invalid = false;
15872 for (auto &Base : ClassDecl->bases()) {
15873 // C++11 [class.copy]p28:
15874 // It is unspecified whether subobjects representing virtual base classes
15875 // are assigned more than once by the implicitly-defined copy assignment
15876 // operator.
15877 // FIXME: Do not assign to a vbase that will be assigned by some other base
15878 // class. For a move-assignment, this can result in the vbase being moved
15879 // multiple times.
15880
15881 // Form the assignment:
15882 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
15883 QualType BaseType = Base.getType().getUnqualifiedType();
15884 if (!BaseType->isRecordType()) {
15885 Invalid = true;
15886 continue;
15887 }
15888
15889 CXXCastPath BasePath;
15890 BasePath.push_back(Elt: &Base);
15891
15892 // Construct the "from" expression, which is an implicit cast to the
15893 // appropriately-qualified base type.
15894 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
15895
15896 // Implicitly cast "this" to the appropriately-qualified base type.
15897 // Dereference "this".
15898 CastBuilder To(
15899 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15900 : static_cast<ExprBuilder &>(*DerefThis),
15901 Context.getQualifiedType(T: BaseType, Qs: ObjectType.getQualifiers()),
15902 VK_LValue, BasePath);
15903
15904 // Build the move.
15905 StmtResult Move = buildSingleCopyAssign(S&: *this, Loc, T: BaseType,
15906 To, From,
15907 /*CopyingBaseSubobject=*/true,
15908 /*Copying=*/false);
15909 if (Move.isInvalid()) {
15910 MoveAssignOperator->setInvalidDecl();
15911 return;
15912 }
15913
15914 // Success! Record the move.
15915 Statements.push_back(Elt: Move.getAs<Expr>());
15916 }
15917
15918 // A defaulted move assignment operator for a union copies the object
15919 // representation as if by a memcpy, the same way the defaulted union copy
15920 // constructor does. The memberwise loop below skips union members.
15921 if (ClassDecl->isUnion()) {
15922 ExprBuilder &To = ExplicitObject
15923 ? static_cast<ExprBuilder &>(*ExplicitObject)
15924 : static_cast<ExprBuilder &>(*DerefThis);
15925 // Copying the object representation is correct even for a union that is
15926 // not trivially copyable, so -Wnontrivial-memcall is a false positive
15927 // here. Ignoring warnings rather than casting the arguments to void*
15928 // keeps them typed, which preserves their address space.
15929 IgnoreAllWarningDiagRAII IgnoreWarnings(Diags);
15930 StmtResult Copy = buildMemcpyForAssignmentOp(
15931 S&: *this, Loc, T: Context.getCanonicalTagType(TD: ClassDecl), ToB: To, FromB: OtherRef);
15932 if (Copy.isInvalid()) {
15933 MoveAssignOperator->setInvalidDecl();
15934 return;
15935 }
15936 Statements.push_back(Elt: Copy.getAs<Stmt>());
15937 }
15938
15939 // Assign non-static members.
15940 for (auto *Field : ClassDecl->fields()) {
15941 // Union members are copied by the whole-object memcpy emitted above.
15942 if (Field->isUnnamedBitField() || Field->getParent()->isUnion())
15943 continue;
15944
15945 if (Field->isInvalidDecl()) {
15946 Invalid = true;
15947 continue;
15948 }
15949
15950 // Check for members of reference type; we can't move those.
15951 if (Field->getType()->isReferenceType()) {
15952 Diag(Loc: ClassDecl->getLocation(), DiagID: diag::err_uninitialized_member_for_assign)
15953 << Context.getCanonicalTagType(TD: ClassDecl) << 0
15954 << Field->getDeclName();
15955 Diag(Loc: Field->getLocation(), DiagID: diag::note_declared_at);
15956 Invalid = true;
15957 continue;
15958 }
15959
15960 // Check for members of const-qualified, non-class type.
15961 QualType BaseType = Context.getBaseElementType(QT: Field->getType());
15962 if (!BaseType->isRecordType() && BaseType.isConstQualified()) {
15963 Diag(Loc: ClassDecl->getLocation(), DiagID: diag::err_uninitialized_member_for_assign)
15964 << Context.getCanonicalTagType(TD: ClassDecl) << 1
15965 << Field->getDeclName();
15966 Diag(Loc: Field->getLocation(), DiagID: diag::note_declared_at);
15967 Invalid = true;
15968 continue;
15969 }
15970
15971 // Suppress assigning zero-width bitfields.
15972 if (Field->isZeroLengthBitField())
15973 continue;
15974
15975 QualType FieldType = Field->getType().getNonReferenceType();
15976 if (FieldType->isIncompleteArrayType()) {
15977 assert(ClassDecl->hasFlexibleArrayMember() &&
15978 "Incomplete array type is not valid");
15979 continue;
15980 }
15981
15982 // Build references to the field in the object we're copying from and to.
15983 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
15984 LookupMemberName);
15985 MemberLookup.addDecl(D: Field);
15986 MemberLookup.resolveKind();
15987 MemberBuilder From(MoveOther, OtherRefType,
15988 /*IsArrow=*/false, MemberLookup);
15989 MemberBuilder To(ObjectParameter, ObjectType, IsArrow, MemberLookup);
15990
15991 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
15992 "Member reference with rvalue base must be rvalue except for reference "
15993 "members, which aren't allowed for move assignment.");
15994
15995 // Build the move of this field.
15996 StmtResult Move = buildSingleCopyAssign(S&: *this, Loc, T: FieldType,
15997 To, From,
15998 /*CopyingBaseSubobject=*/false,
15999 /*Copying=*/false);
16000 if (Move.isInvalid()) {
16001 MoveAssignOperator->setInvalidDecl();
16002 return;
16003 }
16004
16005 // Success! Record the copy.
16006 Statements.push_back(Elt: Move.getAs<Stmt>());
16007 }
16008
16009 if (!Invalid) {
16010 // Add a "return *this;"
16011 Expr *ThisExpr =
16012 (ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
16013 : LangOpts.HLSL ? static_cast<ExprBuilder &>(*This)
16014 : static_cast<ExprBuilder &>(*DerefThis))
16015 .build(S&: *this, Loc);
16016
16017 StmtResult Return = BuildReturnStmt(ReturnLoc: Loc, RetValExp: ThisExpr);
16018 if (Return.isInvalid())
16019 Invalid = true;
16020 else
16021 Statements.push_back(Elt: Return.getAs<Stmt>());
16022 }
16023
16024 if (Invalid) {
16025 MoveAssignOperator->setInvalidDecl();
16026 return;
16027 }
16028
16029 StmtResult Body;
16030 {
16031 CompoundScopeRAII CompoundScope(*this);
16032 Body = ActOnCompoundStmt(L: Loc, R: Loc, Elts: Statements,
16033 /*isStmtExpr=*/false);
16034 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
16035 }
16036 MoveAssignOperator->setBody(Body.getAs<Stmt>());
16037 MoveAssignOperator->markUsed(C&: Context);
16038
16039 if (ASTMutationListener *L = getASTMutationListener()) {
16040 L->CompletedImplicitDefinition(D: MoveAssignOperator);
16041 }
16042}
16043
16044CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
16045 CXXRecordDecl *ClassDecl) {
16046 // C++ [class.copy]p4:
16047 // If the class definition does not explicitly declare a copy
16048 // constructor, one is declared implicitly.
16049 assert(ClassDecl->needsImplicitCopyConstructor());
16050
16051 DeclaringSpecialMember DSM(*this, ClassDecl,
16052 CXXSpecialMemberKind::CopyConstructor);
16053 if (DSM.isAlreadyBeingDeclared())
16054 return nullptr;
16055
16056 QualType ClassType = Context.getTagType(Keyword: ElaboratedTypeKeyword::None,
16057 /*Qualifier=*/std::nullopt, TD: ClassDecl,
16058 /*OwnsTag=*/false);
16059 QualType ArgType = ClassType;
16060 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
16061 if (Const)
16062 ArgType = ArgType.withConst();
16063
16064 LangAS AS = getDefaultCXXMethodAddrSpace();
16065 if (AS != LangAS::Default)
16066 ArgType = Context.getAddrSpaceQualType(T: ArgType, AddressSpace: AS);
16067
16068 ArgType = Context.getLValueReferenceType(T: ArgType);
16069
16070 bool Constexpr = defaultedSpecialMemberIsConstexpr(
16071 S&: *this, ClassDecl, CSM: CXXSpecialMemberKind::CopyConstructor, ConstArg: Const);
16072
16073 DeclarationName Name
16074 = Context.DeclarationNames.getCXXConstructorName(
16075 Ty: Context.getCanonicalType(T: ClassType));
16076 SourceLocation ClassLoc = ClassDecl->getLocation();
16077 DeclarationNameInfo NameInfo(Name, ClassLoc);
16078
16079 // An implicitly-declared copy constructor is an inline public
16080 // member of its class.
16081 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
16082 C&: Context, RD: ClassDecl, StartLoc: ClassLoc, NameInfo, T: QualType(), /*TInfo=*/nullptr,
16083 ES: ExplicitSpecifier(), UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
16084 /*isInline=*/true,
16085 /*isImplicitlyDeclared=*/true,
16086 ConstexprKind: Constexpr ? ConstexprSpecKind::Constexpr
16087 : ConstexprSpecKind::Unspecified);
16088 CopyConstructor->setAccess(AS_public);
16089 CopyConstructor->setDefaulted();
16090
16091 setupImplicitSpecialMemberType(SpecialMem: CopyConstructor, ResultTy: Context.VoidTy, Args: ArgType);
16092
16093 if (getLangOpts().CUDA)
16094 CUDA().inferTargetForImplicitSpecialMember(
16095 ClassDecl, CSM: CXXSpecialMemberKind::CopyConstructor, MemberDecl: CopyConstructor,
16096 /* ConstRHS */ Const,
16097 /* Diagnose */ false);
16098
16099 // During template instantiation of special member functions we need a
16100 // reliable TypeSourceInfo for the parameter types in order to allow functions
16101 // to be substituted.
16102 TypeSourceInfo *TSI = nullptr;
16103 if (inTemplateInstantiation() && ClassDecl->isLambda())
16104 TSI = Context.getTrivialTypeSourceInfo(T: ArgType);
16105
16106 // Add the parameter to the constructor.
16107 ParmVarDecl *FromParam =
16108 ParmVarDecl::Create(C&: Context, DC: CopyConstructor, StartLoc: ClassLoc, IdLoc: ClassLoc,
16109 /*IdentifierInfo=*/Id: nullptr, T: ArgType,
16110 /*TInfo=*/TSI, S: SC_None, DefArg: nullptr);
16111 CopyConstructor->setParams(FromParam);
16112
16113 CopyConstructor->setTrivial(
16114 ClassDecl->needsOverloadResolutionForCopyConstructor()
16115 ? SpecialMemberIsTrivial(MD: CopyConstructor,
16116 CSM: CXXSpecialMemberKind::CopyConstructor)
16117 : ClassDecl->hasTrivialCopyConstructor());
16118
16119 CopyConstructor->setTrivialForCall(
16120 ClassDecl->hasAttr<TrivialABIAttr>() ||
16121 (ClassDecl->needsOverloadResolutionForCopyConstructor()
16122 ? SpecialMemberIsTrivial(MD: CopyConstructor,
16123 CSM: CXXSpecialMemberKind::CopyConstructor,
16124 TAH: TrivialABIHandling::ConsiderTrivialABI)
16125 : ClassDecl->hasTrivialCopyConstructorForCall()));
16126
16127 // Note that we have declared this constructor.
16128 ++getASTContext().NumImplicitCopyConstructorsDeclared;
16129
16130 Scope *S = getScopeForContext(Ctx: ClassDecl);
16131 CheckImplicitSpecialMemberDeclaration(S, FD: CopyConstructor);
16132
16133 if (ShouldDeleteSpecialMember(MD: CopyConstructor,
16134 CSM: CXXSpecialMemberKind::CopyConstructor)) {
16135 ClassDecl->setImplicitCopyConstructorIsDeleted();
16136 SetDeclDeleted(dcl: CopyConstructor, DelLoc: ClassLoc);
16137 }
16138
16139 if (S)
16140 PushOnScopeChains(D: CopyConstructor, S, AddToContext: false);
16141 ClassDecl->addDecl(D: CopyConstructor);
16142
16143 return CopyConstructor;
16144}
16145
16146void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
16147 CXXConstructorDecl *CopyConstructor) {
16148 DefaultedFunctionFPFeaturesRAII RestoreFP(*this, CopyConstructor);
16149 assert((CopyConstructor->isDefaulted() &&
16150 CopyConstructor->isCopyConstructor() &&
16151 !CopyConstructor->doesThisDeclarationHaveABody() &&
16152 !CopyConstructor->isDeleted()) &&
16153 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
16154 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
16155 return;
16156
16157 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
16158 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
16159
16160 SynthesizedFunctionScope Scope(*this, CopyConstructor);
16161
16162 // The exception specification is needed because we are defining the
16163 // function.
16164 ResolveExceptionSpec(Loc: CurrentLocation,
16165 FPT: CopyConstructor->getType()->castAs<FunctionProtoType>());
16166 MarkVTableUsed(Loc: CurrentLocation, Class: ClassDecl);
16167
16168 // Add a context note for diagnostics produced after this point.
16169 Scope.addContextNote(UseLoc: CurrentLocation);
16170
16171 // C++11 [class.copy]p7:
16172 // The [definition of an implicitly declared copy constructor] is
16173 // deprecated if the class has a user-declared copy assignment operator
16174 // or a user-declared destructor.
16175 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
16176 diagnoseDeprecatedCopyOperation(S&: *this, CopyOp: CopyConstructor);
16177
16178 if (SetCtorInitializers(Constructor: CopyConstructor, /*AnyErrors=*/false)) {
16179 CopyConstructor->setInvalidDecl();
16180 } else {
16181 SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
16182 ? CopyConstructor->getEndLoc()
16183 : CopyConstructor->getLocation();
16184 Sema::CompoundScopeRAII CompoundScope(*this);
16185 CopyConstructor->setBody(
16186 ActOnCompoundStmt(L: Loc, R: Loc, Elts: {}, /*isStmtExpr=*/false).getAs<Stmt>());
16187 CopyConstructor->markUsed(C&: Context);
16188 }
16189
16190 if (ASTMutationListener *L = getASTMutationListener()) {
16191 L->CompletedImplicitDefinition(D: CopyConstructor);
16192 }
16193}
16194
16195CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
16196 CXXRecordDecl *ClassDecl) {
16197 assert(ClassDecl->needsImplicitMoveConstructor());
16198
16199 DeclaringSpecialMember DSM(*this, ClassDecl,
16200 CXXSpecialMemberKind::MoveConstructor);
16201 if (DSM.isAlreadyBeingDeclared())
16202 return nullptr;
16203
16204 QualType ClassType = Context.getTagType(Keyword: ElaboratedTypeKeyword::None,
16205 /*Qualifier=*/std::nullopt, TD: ClassDecl,
16206 /*OwnsTag=*/false);
16207
16208 QualType ArgType = ClassType;
16209 LangAS AS = getDefaultCXXMethodAddrSpace();
16210 if (AS != LangAS::Default)
16211 ArgType = Context.getAddrSpaceQualType(T: ClassType, AddressSpace: AS);
16212 ArgType = Context.getRValueReferenceType(T: ArgType);
16213
16214 bool Constexpr = defaultedSpecialMemberIsConstexpr(
16215 S&: *this, ClassDecl, CSM: CXXSpecialMemberKind::MoveConstructor, ConstArg: false);
16216
16217 DeclarationName Name
16218 = Context.DeclarationNames.getCXXConstructorName(
16219 Ty: Context.getCanonicalType(T: ClassType));
16220 SourceLocation ClassLoc = ClassDecl->getLocation();
16221 DeclarationNameInfo NameInfo(Name, ClassLoc);
16222
16223 // C++11 [class.copy]p11:
16224 // An implicitly-declared copy/move constructor is an inline public
16225 // member of its class.
16226 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
16227 C&: Context, RD: ClassDecl, StartLoc: ClassLoc, NameInfo, T: QualType(), /*TInfo=*/nullptr,
16228 ES: ExplicitSpecifier(), UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
16229 /*isInline=*/true,
16230 /*isImplicitlyDeclared=*/true,
16231 ConstexprKind: Constexpr ? ConstexprSpecKind::Constexpr
16232 : ConstexprSpecKind::Unspecified);
16233 MoveConstructor->setAccess(AS_public);
16234 MoveConstructor->setDefaulted();
16235
16236 setupImplicitSpecialMemberType(SpecialMem: MoveConstructor, ResultTy: Context.VoidTy, Args: ArgType);
16237
16238 if (getLangOpts().CUDA)
16239 CUDA().inferTargetForImplicitSpecialMember(
16240 ClassDecl, CSM: CXXSpecialMemberKind::MoveConstructor, MemberDecl: MoveConstructor,
16241 /* ConstRHS */ false,
16242 /* Diagnose */ false);
16243
16244 // Add the parameter to the constructor.
16245 ParmVarDecl *FromParam = ParmVarDecl::Create(C&: Context, DC: MoveConstructor,
16246 StartLoc: ClassLoc, IdLoc: ClassLoc,
16247 /*IdentifierInfo=*/Id: nullptr,
16248 T: ArgType, /*TInfo=*/nullptr,
16249 S: SC_None, DefArg: nullptr);
16250 MoveConstructor->setParams(FromParam);
16251
16252 MoveConstructor->setTrivial(
16253 ClassDecl->needsOverloadResolutionForMoveConstructor()
16254 ? SpecialMemberIsTrivial(MD: MoveConstructor,
16255 CSM: CXXSpecialMemberKind::MoveConstructor)
16256 : ClassDecl->hasTrivialMoveConstructor());
16257
16258 MoveConstructor->setTrivialForCall(
16259 ClassDecl->hasAttr<TrivialABIAttr>() ||
16260 (ClassDecl->needsOverloadResolutionForMoveConstructor()
16261 ? SpecialMemberIsTrivial(MD: MoveConstructor,
16262 CSM: CXXSpecialMemberKind::MoveConstructor,
16263 TAH: TrivialABIHandling::ConsiderTrivialABI)
16264 : ClassDecl->hasTrivialMoveConstructorForCall()));
16265
16266 // Note that we have declared this constructor.
16267 ++getASTContext().NumImplicitMoveConstructorsDeclared;
16268
16269 Scope *S = getScopeForContext(Ctx: ClassDecl);
16270 CheckImplicitSpecialMemberDeclaration(S, FD: MoveConstructor);
16271
16272 if (ShouldDeleteSpecialMember(MD: MoveConstructor,
16273 CSM: CXXSpecialMemberKind::MoveConstructor)) {
16274 ClassDecl->setImplicitMoveConstructorIsDeleted();
16275 SetDeclDeleted(dcl: MoveConstructor, DelLoc: ClassLoc);
16276 }
16277
16278 if (S)
16279 PushOnScopeChains(D: MoveConstructor, S, AddToContext: false);
16280 ClassDecl->addDecl(D: MoveConstructor);
16281
16282 return MoveConstructor;
16283}
16284
16285void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
16286 CXXConstructorDecl *MoveConstructor) {
16287 DefaultedFunctionFPFeaturesRAII RestoreFP(*this, MoveConstructor);
16288 assert((MoveConstructor->isDefaulted() &&
16289 MoveConstructor->isMoveConstructor() &&
16290 !MoveConstructor->doesThisDeclarationHaveABody() &&
16291 !MoveConstructor->isDeleted()) &&
16292 "DefineImplicitMoveConstructor - call it for implicit move ctor");
16293 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
16294 return;
16295
16296 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
16297 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
16298
16299 SynthesizedFunctionScope Scope(*this, MoveConstructor);
16300
16301 // The exception specification is needed because we are defining the
16302 // function.
16303 ResolveExceptionSpec(Loc: CurrentLocation,
16304 FPT: MoveConstructor->getType()->castAs<FunctionProtoType>());
16305 MarkVTableUsed(Loc: CurrentLocation, Class: ClassDecl);
16306
16307 // Add a context note for diagnostics produced after this point.
16308 Scope.addContextNote(UseLoc: CurrentLocation);
16309
16310 if (SetCtorInitializers(Constructor: MoveConstructor, /*AnyErrors=*/false)) {
16311 MoveConstructor->setInvalidDecl();
16312 } else {
16313 SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
16314 ? MoveConstructor->getEndLoc()
16315 : MoveConstructor->getLocation();
16316 Sema::CompoundScopeRAII CompoundScope(*this);
16317 MoveConstructor->setBody(
16318 ActOnCompoundStmt(L: Loc, R: Loc, Elts: {}, /*isStmtExpr=*/false).getAs<Stmt>());
16319 MoveConstructor->markUsed(C&: Context);
16320 }
16321
16322 if (ASTMutationListener *L = getASTMutationListener()) {
16323 L->CompletedImplicitDefinition(D: MoveConstructor);
16324 }
16325}
16326
16327bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
16328 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(Val: FD);
16329}
16330
16331void Sema::DefineImplicitLambdaToFunctionPointerConversion(
16332 SourceLocation CurrentLocation,
16333 CXXConversionDecl *Conv) {
16334 SynthesizedFunctionScope Scope(*this, Conv);
16335 assert(!Conv->getReturnType()->isUndeducedType());
16336
16337 QualType ConvRT = Conv->getType()->castAs<FunctionType>()->getReturnType();
16338 CallingConv CC =
16339 ConvRT->getPointeeType()->castAs<FunctionType>()->getCallConv();
16340
16341 CXXRecordDecl *Lambda = Conv->getParent();
16342 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
16343 FunctionDecl *Invoker =
16344 CallOp->hasCXXExplicitFunctionObjectParameter() || CallOp->isStatic()
16345 ? CallOp
16346 : Lambda->getLambdaStaticInvoker(CC);
16347
16348 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
16349 CallOp = InstantiateFunctionDeclaration(
16350 FTD: CallOp->getDescribedFunctionTemplate(), Args: TemplateArgs, Loc: CurrentLocation);
16351 if (!CallOp)
16352 return;
16353
16354 if (CallOp != Invoker) {
16355 Invoker = InstantiateFunctionDeclaration(
16356 FTD: Invoker->getDescribedFunctionTemplate(), Args: TemplateArgs,
16357 Loc: CurrentLocation);
16358 if (!Invoker)
16359 return;
16360 }
16361 }
16362
16363 if (CallOp->isInvalidDecl())
16364 return;
16365
16366 // Mark the call operator referenced (and add to pending instantiations
16367 // if necessary).
16368 // For both the conversion and static-invoker template specializations
16369 // we construct their body's in this function, so no need to add them
16370 // to the PendingInstantiations.
16371 MarkFunctionReferenced(Loc: CurrentLocation, Func: CallOp);
16372
16373 if (Invoker != CallOp) {
16374 // Fill in the __invoke function with a dummy implementation. IR generation
16375 // will fill in the actual details. Update its type in case it contained
16376 // an 'auto'.
16377 Invoker->markUsed(C&: Context);
16378 Invoker->setReferenced();
16379 Invoker->setType(Conv->getReturnType()->getPointeeType());
16380 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
16381 }
16382
16383 // Construct the body of the conversion function { return __invoke; }.
16384 Expr *FunctionRef = BuildDeclRefExpr(D: Invoker, Ty: Invoker->getType(), VK: VK_LValue,
16385 Loc: Conv->getLocation());
16386 assert(FunctionRef && "Can't refer to __invoke function?");
16387 Stmt *Return = BuildReturnStmt(ReturnLoc: Conv->getLocation(), RetValExp: FunctionRef).get();
16388 Conv->setBody(CompoundStmt::Create(C: Context, Stmts: Return, FPFeatures: FPOptionsOverride(),
16389 LB: Conv->getLocation(), RB: Conv->getLocation()));
16390 Conv->markUsed(C&: Context);
16391 Conv->setReferenced();
16392
16393 if (ASTMutationListener *L = getASTMutationListener()) {
16394 L->CompletedImplicitDefinition(D: Conv);
16395 if (Invoker != CallOp)
16396 L->CompletedImplicitDefinition(D: Invoker);
16397 }
16398}
16399
16400void Sema::DefineImplicitLambdaToBlockPointerConversion(
16401 SourceLocation CurrentLocation, CXXConversionDecl *Conv) {
16402 assert(!Conv->getParent()->isGenericLambda());
16403
16404 SynthesizedFunctionScope Scope(*this, Conv);
16405
16406 // Copy-initialize the lambda object as needed to capture it.
16407 Expr *This = ActOnCXXThis(Loc: CurrentLocation).get();
16408 Expr *DerefThis =CreateBuiltinUnaryOp(OpLoc: CurrentLocation, Opc: UO_Deref, InputExpr: This).get();
16409
16410 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
16411 ConvLocation: Conv->getLocation(),
16412 Conv, Src: DerefThis);
16413
16414 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
16415 // behavior. Note that only the general conversion function does this
16416 // (since it's unusable otherwise); in the case where we inline the
16417 // block literal, it has block literal lifetime semantics.
16418 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
16419 BuildBlock = ImplicitCastExpr::Create(
16420 Context, T: BuildBlock.get()->getType(), Kind: CK_CopyAndAutoreleaseBlockObject,
16421 Operand: BuildBlock.get(), BasePath: nullptr, Cat: VK_PRValue, FPO: FPOptionsOverride());
16422
16423 if (BuildBlock.isInvalid()) {
16424 Diag(Loc: CurrentLocation, DiagID: diag::note_lambda_to_block_conv);
16425 Conv->setInvalidDecl();
16426 return;
16427 }
16428
16429 // Create the return statement that returns the block from the conversion
16430 // function.
16431 StmtResult Return = BuildReturnStmt(ReturnLoc: Conv->getLocation(), RetValExp: BuildBlock.get());
16432 if (Return.isInvalid()) {
16433 Diag(Loc: CurrentLocation, DiagID: diag::note_lambda_to_block_conv);
16434 Conv->setInvalidDecl();
16435 return;
16436 }
16437
16438 // Set the body of the conversion function.
16439 Stmt *ReturnS = Return.get();
16440 Conv->setBody(CompoundStmt::Create(C: Context, Stmts: ReturnS, FPFeatures: FPOptionsOverride(),
16441 LB: Conv->getLocation(), RB: Conv->getLocation()));
16442 Conv->markUsed(C&: Context);
16443
16444 // We're done; notify the mutation listener, if any.
16445 if (ASTMutationListener *L = getASTMutationListener()) {
16446 L->CompletedImplicitDefinition(D: Conv);
16447 }
16448}
16449
16450/// Determine whether the given list arguments contains exactly one
16451/// "real" (non-default) argument.
16452static bool hasOneRealArgument(MultiExprArg Args) {
16453 switch (Args.size()) {
16454 case 0:
16455 return false;
16456
16457 default:
16458 if (!Args[1]->isDefaultArgument())
16459 return false;
16460
16461 [[fallthrough]];
16462 case 1:
16463 return !Args[0]->isDefaultArgument();
16464 }
16465
16466 return false;
16467}
16468
16469ExprResult Sema::BuildCXXConstructExpr(
16470 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
16471 CXXConstructorDecl *Constructor, MultiExprArg ExprArgs,
16472 bool HadMultipleCandidates, bool IsListInitialization,
16473 bool IsStdInitListInitialization, bool RequiresZeroInit,
16474 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16475 bool Elidable = false;
16476
16477 // C++0x [class.copy]p34:
16478 // When certain criteria are met, an implementation is allowed to
16479 // omit the copy/move construction of a class object, even if the
16480 // copy/move constructor and/or destructor for the object have
16481 // side effects. [...]
16482 // - when a temporary class object that has not been bound to a
16483 // reference (12.2) would be copied/moved to a class object
16484 // with the same cv-unqualified type, the copy/move operation
16485 // can be omitted by constructing the temporary object
16486 // directly into the target of the omitted copy/move
16487 if (ConstructKind == CXXConstructionKind::Complete && Constructor &&
16488 // FIXME: Converting constructors should also be accepted.
16489 // But to fix this, the logic that digs down into a CXXConstructExpr
16490 // to find the source object needs to handle it.
16491 // Right now it assumes the source object is passed directly as the
16492 // first argument.
16493 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(Args: ExprArgs)) {
16494 Expr *SubExpr = ExprArgs[0];
16495 // FIXME: Per above, this is also incorrect if we want to accept
16496 // converting constructors, as isTemporaryObject will
16497 // reject temporaries with different type from the
16498 // CXXRecord itself.
16499 Elidable = SubExpr->isTemporaryObject(
16500 Ctx&: Context, TempTy: cast<CXXRecordDecl>(Val: FoundDecl->getDeclContext()));
16501 }
16502
16503 return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
16504 FoundDecl, Constructor,
16505 Elidable, Exprs: ExprArgs, HadMultipleCandidates,
16506 IsListInitialization,
16507 IsStdInitListInitialization, RequiresZeroInit,
16508 ConstructKind, ParenRange);
16509}
16510
16511ExprResult Sema::BuildCXXConstructExpr(
16512 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
16513 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg ExprArgs,
16514 bool HadMultipleCandidates, bool IsListInitialization,
16515 bool IsStdInitListInitialization, bool RequiresZeroInit,
16516 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16517 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(Val: FoundDecl)) {
16518 Constructor = findInheritingConstructor(Loc: ConstructLoc, BaseCtor: Constructor, Shadow);
16519 // The only way to get here is if we did overload resolution to find the
16520 // shadow decl, so we don't need to worry about re-checking the trailing
16521 // requires clause.
16522 if (DiagnoseUseOfOverloadedDecl(D: Constructor, Loc: ConstructLoc))
16523 return ExprError();
16524 }
16525
16526 return BuildCXXConstructExpr(
16527 ConstructLoc, DeclInitType, Constructor, Elidable, Exprs: ExprArgs,
16528 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
16529 RequiresZeroInit, ConstructKind, ParenRange);
16530}
16531
16532/// BuildCXXConstructExpr - Creates a complete call to a constructor,
16533/// including handling of its default argument expressions.
16534ExprResult Sema::BuildCXXConstructExpr(
16535 SourceLocation ConstructLoc, QualType DeclInitType,
16536 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg ExprArgs,
16537 bool HadMultipleCandidates, bool IsListInitialization,
16538 bool IsStdInitListInitialization, bool RequiresZeroInit,
16539 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16540 assert(declaresSameEntity(
16541 Constructor->getParent(),
16542 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
16543 "given constructor for wrong type");
16544 MarkFunctionReferenced(Loc: ConstructLoc, Func: Constructor);
16545 if (getLangOpts().CUDA && !CUDA().CheckCall(Loc: ConstructLoc, Callee: Constructor))
16546 return ExprError();
16547
16548 return CheckForImmediateInvocation(
16549 E: CXXConstructExpr::Create(
16550 Ctx: Context, Ty: DeclInitType, Loc: ConstructLoc, Ctor: Constructor, Elidable, Args: ExprArgs,
16551 HadMultipleCandidates, ListInitialization: IsListInitialization,
16552 StdInitListInitialization: IsStdInitListInitialization, ZeroInitialization: RequiresZeroInit,
16553 ConstructKind: static_cast<CXXConstructionKind>(ConstructKind), ParenOrBraceRange: ParenRange),
16554 Decl: Constructor);
16555}
16556
16557void Sema::FinalizeVarWithDestructor(VarDecl *VD, CXXRecordDecl *ClassDecl) {
16558 if (VD->isInvalidDecl()) return;
16559 // If initializing the variable failed, don't also diagnose problems with
16560 // the destructor, they're likely related.
16561 if (VD->getInit() && VD->getInit()->containsErrors())
16562 return;
16563
16564 ClassDecl = ClassDecl->getDefinitionOrSelf();
16565 if (ClassDecl->isInvalidDecl()) return;
16566 if (ClassDecl->hasIrrelevantDestructor()) return;
16567 if (ClassDecl->isDependentContext()) return;
16568
16569 if (VD->isNoDestroy(getASTContext()))
16570 return;
16571
16572 CXXDestructorDecl *Destructor = LookupDestructor(Class: ClassDecl);
16573 // The result of `LookupDestructor` might be nullptr if the destructor is
16574 // invalid, in which case it is marked as `IneligibleOrNotSelected` and
16575 // will not be selected by `CXXRecordDecl::getDestructor()`.
16576 if (!Destructor)
16577 return;
16578 // If this is an array, we'll require the destructor during initialization, so
16579 // we can skip over this. We still want to emit exit-time destructor warnings
16580 // though.
16581 if (!VD->getType()->isArrayType()) {
16582 MarkFunctionReferenced(Loc: VD->getLocation(), Func: Destructor);
16583 CheckDestructorAccess(Loc: VD->getLocation(), Dtor: Destructor,
16584 PDiag: PDiag(DiagID: diag::err_access_dtor_var)
16585 << VD->getDeclName() << VD->getType());
16586 DiagnoseUseOfDecl(D: Destructor, Locs: VD->getLocation());
16587 }
16588
16589 if (Destructor->isTrivial()) return;
16590
16591 // If the destructor is constexpr, check whether the variable has constant
16592 // destruction now.
16593 if (Destructor->isConstexpr()) {
16594 bool HasConstantInit = false;
16595 if (VD->getInit() && !VD->getInit()->isValueDependent())
16596 HasConstantInit = VD->evaluateValue();
16597 SmallVector<PartialDiagnosticAt, 8> Notes;
16598 if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() &&
16599 HasConstantInit) {
16600 Diag(Loc: VD->getLocation(),
16601 DiagID: diag::err_constexpr_var_requires_const_destruction) << VD;
16602 for (const PartialDiagnosticAt &Note : Notes)
16603 Diag(Loc: Note.first, PD: Note.second);
16604 }
16605 }
16606
16607 if (!VD->hasGlobalStorage() || !VD->needsDestruction(Ctx: Context))
16608 return;
16609
16610 // Emit warning for non-trivial dtor in global scope (a real global,
16611 // class-static, function-static).
16612 if (!VD->hasAttr<AlwaysDestroyAttr>())
16613 Diag(Loc: VD->getLocation(), DiagID: diag::warn_exit_time_destructor);
16614
16615 // TODO: this should be re-enabled for static locals by !CXAAtExit
16616 if (!VD->isStaticLocal())
16617 Diag(Loc: VD->getLocation(), DiagID: diag::warn_global_destructor);
16618}
16619
16620bool Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
16621 QualType DeclInitType, MultiExprArg ArgsPtr,
16622 SourceLocation Loc,
16623 SmallVectorImpl<Expr *> &ConvertedArgs,
16624 bool AllowExplicit,
16625 bool IsListInitialization) {
16626 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
16627 unsigned NumArgs = ArgsPtr.size();
16628 Expr **Args = ArgsPtr.data();
16629
16630 const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>();
16631 unsigned NumParams = Proto->getNumParams();
16632
16633 // If too few arguments are available, we'll fill in the rest with defaults.
16634 if (NumArgs < NumParams)
16635 ConvertedArgs.reserve(N: NumParams);
16636 else
16637 ConvertedArgs.reserve(N: NumArgs);
16638
16639 VariadicCallType CallType = Proto->isVariadic()
16640 ? VariadicCallType::Constructor
16641 : VariadicCallType::DoesNotApply;
16642 SmallVector<Expr *, 8> AllArgs;
16643 bool Invalid = GatherArgumentsForCall(
16644 CallLoc: Loc, FDecl: Constructor, Proto, FirstParam: 0, Args: llvm::ArrayRef(Args, NumArgs), AllArgs,
16645 CallType, AllowExplicit, IsListInitialization);
16646 ConvertedArgs.append(in_start: AllArgs.begin(), in_end: AllArgs.end());
16647
16648 DiagnoseSentinelCalls(D: Constructor, Loc, Args: AllArgs);
16649
16650 CheckConstructorCall(FDecl: Constructor, ThisType: DeclInitType, Args: llvm::ArrayRef(AllArgs),
16651 Proto, Loc);
16652
16653 return Invalid;
16654}
16655
16656TypeAwareAllocationMode Sema::ShouldUseTypeAwareOperatorNewOrDelete() const {
16657 bool SeenTypedOperators = Context.hasSeenTypeAwareOperatorNewOrDelete();
16658 return typeAwareAllocationModeFromBool(IsTypeAwareAllocation: SeenTypedOperators);
16659}
16660
16661FunctionDecl *
16662Sema::BuildTypeAwareUsualDelete(FunctionTemplateDecl *FnTemplateDecl,
16663 QualType DeallocType, SourceLocation Loc) {
16664 if (DeallocType.isNull())
16665 return nullptr;
16666
16667 FunctionDecl *FnDecl = FnTemplateDecl->getTemplatedDecl();
16668 if (!FnDecl->isTypeAwareOperatorNewOrDelete())
16669 return nullptr;
16670
16671 if (FnDecl->isVariadic())
16672 return nullptr;
16673
16674 unsigned NumParams = FnDecl->getNumParams();
16675 constexpr unsigned RequiredParameterCount =
16676 FunctionDecl::RequiredTypeAwareDeleteParameterCount;
16677 // A usual deallocation function has no placement parameters
16678 if (NumParams != RequiredParameterCount)
16679 return nullptr;
16680
16681 // A type aware allocation is only usual if the only dependent parameter is
16682 // the first parameter.
16683 if (llvm::any_of(Range: FnDecl->parameters().drop_front(),
16684 P: [](const ParmVarDecl *ParamDecl) {
16685 return ParamDecl->getType()->isDependentType();
16686 }))
16687 return nullptr;
16688
16689 QualType SpecializedTypeIdentity = tryBuildStdTypeIdentity(Type: DeallocType, Loc);
16690 if (SpecializedTypeIdentity.isNull())
16691 return nullptr;
16692
16693 SmallVector<QualType, RequiredParameterCount> ArgTypes;
16694 ArgTypes.reserve(N: NumParams);
16695
16696 // The first parameter to a type aware operator delete is by definition the
16697 // type-identity argument, so we explicitly set this to the target
16698 // type-identity type, the remaining usual parameters should then simply match
16699 // the type declared in the function template.
16700 ArgTypes.push_back(Elt: SpecializedTypeIdentity);
16701 for (unsigned ParamIdx = 1; ParamIdx < RequiredParameterCount; ++ParamIdx)
16702 ArgTypes.push_back(Elt: FnDecl->getParamDecl(i: ParamIdx)->getType());
16703
16704 FunctionProtoType::ExtProtoInfo EPI;
16705 QualType ExpectedFunctionType =
16706 Context.getFunctionType(ResultTy: Context.VoidTy, Args: ArgTypes, EPI);
16707 sema::TemplateDeductionInfo Info(Loc);
16708 FunctionDecl *Result;
16709 if (DeduceTemplateArguments(FunctionTemplate: FnTemplateDecl, ExplicitTemplateArgs: nullptr, ArgFunctionType: ExpectedFunctionType,
16710 Specialization&: Result, Info) != TemplateDeductionResult::Success)
16711 return nullptr;
16712 return Result;
16713}
16714
16715static inline bool
16716CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
16717 const FunctionDecl *FnDecl) {
16718 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
16719 if (isa<NamespaceDecl>(Val: DC)) {
16720 return SemaRef.Diag(Loc: FnDecl->getLocation(),
16721 DiagID: diag::err_operator_new_delete_declared_in_namespace)
16722 << FnDecl->getDeclName();
16723 }
16724
16725 if (isa<TranslationUnitDecl>(Val: DC) &&
16726 FnDecl->getStorageClass() == SC_Static) {
16727 return SemaRef.Diag(Loc: FnDecl->getLocation(),
16728 DiagID: diag::err_operator_new_delete_declared_static)
16729 << FnDecl->getDeclName();
16730 }
16731
16732 return false;
16733}
16734
16735static CanQualType RemoveAddressSpaceFromPtr(Sema &SemaRef,
16736 const PointerType *PtrTy) {
16737 auto &Ctx = SemaRef.Context;
16738 Qualifiers PtrQuals = PtrTy->getPointeeType().getQualifiers();
16739 PtrQuals.removeAddressSpace();
16740 return Ctx.getPointerType(T: Ctx.getCanonicalType(T: Ctx.getQualifiedType(
16741 T: PtrTy->getPointeeType().getUnqualifiedType(), Qs: PtrQuals)));
16742}
16743
16744enum class AllocationOperatorKind { New, Delete };
16745
16746static bool IsPotentiallyTypeAwareOperatorNewOrDelete(Sema &SemaRef,
16747 const FunctionDecl *FD,
16748 bool *WasMalformed) {
16749 const Decl *MalformedDecl = nullptr;
16750 if (FD->getNumParams() > 0 &&
16751 SemaRef.isStdTypeIdentity(Ty: FD->getParamDecl(i: 0)->getType(),
16752 /*TypeArgument=*/Element: nullptr, MalformedDecl: &MalformedDecl))
16753 return true;
16754
16755 if (!MalformedDecl)
16756 return false;
16757
16758 if (WasMalformed)
16759 *WasMalformed = true;
16760
16761 return true;
16762}
16763
16764static bool isDestroyingDeleteT(QualType Type) {
16765 auto *RD = Type->getAsCXXRecordDecl();
16766 return RD && RD->isInStdNamespace() && RD->getIdentifier() &&
16767 RD->getIdentifier()->isStr(Str: "destroying_delete_t");
16768}
16769
16770static bool IsPotentiallyDestroyingOperatorDelete(Sema &SemaRef,
16771 const FunctionDecl *FD) {
16772 // C++ P0722:
16773 // Within a class C, a single object deallocation function with signature
16774 // (T, std::destroying_delete_t, <more params>)
16775 // is a destroying operator delete.
16776 bool IsPotentiallyTypeAware = IsPotentiallyTypeAwareOperatorNewOrDelete(
16777 SemaRef, FD, /*WasMalformed=*/nullptr);
16778 unsigned DestroyingDeleteIdx = IsPotentiallyTypeAware + /* address */ 1;
16779 return isa<CXXMethodDecl>(Val: FD) && FD->getOverloadedOperator() == OO_Delete &&
16780 FD->getNumParams() > DestroyingDeleteIdx &&
16781 isDestroyingDeleteT(Type: FD->getParamDecl(i: DestroyingDeleteIdx)->getType());
16782}
16783
16784static inline bool CheckOperatorNewDeleteTypes(
16785 Sema &SemaRef, FunctionDecl *FnDecl, AllocationOperatorKind OperatorKind,
16786 CanQualType ExpectedResultType, CanQualType ExpectedSizeOrAddressParamType,
16787 unsigned DependentParamTypeDiag, unsigned InvalidParamTypeDiag) {
16788 auto NormalizeType = [&SemaRef](QualType T) {
16789 if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
16790 // The operator is valid on any address space for OpenCL.
16791 // Drop address space from actual and expected result types.
16792 if (const auto PtrTy = T->template getAs<PointerType>())
16793 T = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
16794 }
16795 return SemaRef.Context.getCanonicalType(T);
16796 };
16797
16798 const unsigned NumParams = FnDecl->getNumParams();
16799 unsigned FirstNonTypeParam = 0;
16800 bool MalformedTypeIdentity = false;
16801 bool IsPotentiallyTypeAware = IsPotentiallyTypeAwareOperatorNewOrDelete(
16802 SemaRef, FD: FnDecl, WasMalformed: &MalformedTypeIdentity);
16803 unsigned MinimumMandatoryArgumentCount = 1;
16804 unsigned SizeParameterIndex = 0;
16805 if (IsPotentiallyTypeAware) {
16806 // We don't emit this diagnosis for template instantiations as we will
16807 // have already emitted it for the original template declaration.
16808 if (!FnDecl->isTemplateInstantiation())
16809 SemaRef.Diag(Loc: FnDecl->getLocation(), DiagID: diag::warn_ext_type_aware_allocators);
16810
16811 if (OperatorKind == AllocationOperatorKind::New) {
16812 SizeParameterIndex = 1;
16813 MinimumMandatoryArgumentCount =
16814 FunctionDecl::RequiredTypeAwareNewParameterCount;
16815 } else {
16816 SizeParameterIndex = 2;
16817 MinimumMandatoryArgumentCount =
16818 FunctionDecl::RequiredTypeAwareDeleteParameterCount;
16819 }
16820 FirstNonTypeParam = 1;
16821 }
16822
16823 bool IsPotentiallyDestroyingDelete =
16824 IsPotentiallyDestroyingOperatorDelete(SemaRef, FD: FnDecl);
16825
16826 if (IsPotentiallyDestroyingDelete) {
16827 ++MinimumMandatoryArgumentCount;
16828 ++SizeParameterIndex;
16829 }
16830
16831 if (NumParams < MinimumMandatoryArgumentCount)
16832 return SemaRef.Diag(Loc: FnDecl->getLocation(),
16833 DiagID: diag::err_operator_new_delete_too_few_parameters)
16834 << IsPotentiallyTypeAware << IsPotentiallyDestroyingDelete
16835 << FnDecl->getDeclName() << MinimumMandatoryArgumentCount;
16836
16837 for (unsigned Idx = 0; Idx < MinimumMandatoryArgumentCount; ++Idx) {
16838 const ParmVarDecl *ParamDecl = FnDecl->getParamDecl(i: Idx);
16839 if (ParamDecl->hasDefaultArg())
16840 return SemaRef.Diag(Loc: FnDecl->getLocation(),
16841 DiagID: diag::err_operator_new_default_arg)
16842 << FnDecl->getDeclName() << Idx << ParamDecl->getDefaultArgRange();
16843 }
16844
16845 auto *FnType = FnDecl->getType()->castAs<FunctionType>();
16846 QualType CanResultType = NormalizeType(FnType->getReturnType());
16847 QualType CanExpectedResultType = NormalizeType(ExpectedResultType);
16848 QualType CanExpectedSizeOrAddressParamType =
16849 NormalizeType(ExpectedSizeOrAddressParamType);
16850
16851 // Check that the result type is what we expect.
16852 if (CanResultType != CanExpectedResultType) {
16853 // Reject even if the type is dependent; an operator delete function is
16854 // required to have a non-dependent result type.
16855 return SemaRef.Diag(
16856 Loc: FnDecl->getLocation(),
16857 DiagID: CanResultType->isDependentType()
16858 ? diag::err_operator_new_delete_dependent_result_type
16859 : diag::err_operator_new_delete_invalid_result_type)
16860 << FnDecl->getDeclName() << ExpectedResultType;
16861 }
16862
16863 // A function template must have at least 2 parameters.
16864 if (FnDecl->getDescribedFunctionTemplate() && NumParams < 2)
16865 return SemaRef.Diag(Loc: FnDecl->getLocation(),
16866 DiagID: diag::err_operator_new_delete_template_too_few_parameters)
16867 << FnDecl->getDeclName();
16868
16869 auto CheckType = [&](unsigned ParamIdx, QualType ExpectedType,
16870 auto FallbackType) -> bool {
16871 const ParmVarDecl *ParamDecl = FnDecl->getParamDecl(i: ParamIdx);
16872 if (ExpectedType.isNull()) {
16873 return SemaRef.Diag(Loc: FnDecl->getLocation(), DiagID: InvalidParamTypeDiag)
16874 << IsPotentiallyTypeAware << IsPotentiallyDestroyingDelete
16875 << FnDecl->getDeclName() << (1 + ParamIdx) << FallbackType
16876 << ParamDecl->getSourceRange();
16877 }
16878 CanQualType CanExpectedTy =
16879 NormalizeType(SemaRef.Context.getCanonicalType(T: ExpectedType));
16880 auto ActualParamType =
16881 NormalizeType(ParamDecl->getType().getUnqualifiedType());
16882 if (ActualParamType == CanExpectedTy)
16883 return false;
16884 unsigned Diagnostic = ActualParamType->isDependentType()
16885 ? DependentParamTypeDiag
16886 : InvalidParamTypeDiag;
16887 return SemaRef.Diag(Loc: FnDecl->getLocation(), DiagID: Diagnostic)
16888 << IsPotentiallyTypeAware << IsPotentiallyDestroyingDelete
16889 << FnDecl->getDeclName() << (1 + ParamIdx) << ExpectedType
16890 << FallbackType << ParamDecl->getSourceRange();
16891 };
16892
16893 // Check that the first parameter type is what we expect.
16894 if (CheckType(FirstNonTypeParam, CanExpectedSizeOrAddressParamType, "size_t"))
16895 return true;
16896
16897 FnDecl->setIsDestroyingOperatorDelete(IsPotentiallyDestroyingDelete);
16898
16899 // If the first parameter type is not a type-identity we're done, otherwise
16900 // we need to ensure the size and alignment parameters have the correct type
16901 if (!IsPotentiallyTypeAware)
16902 return false;
16903
16904 if (CheckType(SizeParameterIndex, SemaRef.Context.getSizeType(), "size_t"))
16905 return true;
16906 TagDecl *StdAlignValTDecl = SemaRef.getStdAlignValT();
16907 CanQualType StdAlignValT =
16908 StdAlignValTDecl ? SemaRef.Context.getCanonicalTagType(TD: StdAlignValTDecl)
16909 : CanQualType();
16910 if (CheckType(SizeParameterIndex + 1, StdAlignValT, "std::align_val_t"))
16911 return true;
16912
16913 FnDecl->setIsTypeAwareOperatorNewOrDelete();
16914 return MalformedTypeIdentity;
16915}
16916
16917static bool CheckOperatorNewDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
16918 // C++ [basic.stc.dynamic.allocation]p1:
16919 // A program is ill-formed if an allocation function is declared in a
16920 // namespace scope other than global scope or declared static in global
16921 // scope.
16922 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
16923 return true;
16924
16925 CanQualType SizeTy =
16926 SemaRef.Context.getCanonicalType(T: SemaRef.Context.getSizeType());
16927
16928 // C++ [basic.stc.dynamic.allocation]p1:
16929 // The return type shall be void*. The first parameter shall have type
16930 // std::size_t.
16931 return CheckOperatorNewDeleteTypes(
16932 SemaRef, FnDecl, OperatorKind: AllocationOperatorKind::New, ExpectedResultType: SemaRef.Context.VoidPtrTy,
16933 ExpectedSizeOrAddressParamType: SizeTy, DependentParamTypeDiag: diag::err_operator_new_dependent_param_type,
16934 InvalidParamTypeDiag: diag::err_operator_new_param_type);
16935}
16936
16937static bool
16938CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
16939 // C++ [basic.stc.dynamic.deallocation]p1:
16940 // A program is ill-formed if deallocation functions are declared in a
16941 // namespace scope other than global scope or declared static in global
16942 // scope.
16943 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
16944 return true;
16945
16946 auto *MD = dyn_cast<CXXMethodDecl>(Val: FnDecl);
16947 auto ConstructDestroyingDeleteAddressType = [&]() {
16948 assert(MD);
16949 return SemaRef.Context.getPointerType(
16950 T: SemaRef.Context.getCanonicalTagType(TD: MD->getParent()));
16951 };
16952
16953 // C++ P2719: A destroying operator delete cannot be type aware
16954 // so for QoL we actually check for this explicitly by considering
16955 // an destroying-delete appropriate address type and the presence of
16956 // any parameter of type destroying_delete_t as an erroneous attempt
16957 // to declare a type aware destroying delete, rather than emitting a
16958 // pile of incorrect parameter type errors.
16959 if (MD && IsPotentiallyTypeAwareOperatorNewOrDelete(
16960 SemaRef, FD: MD, /*WasMalformed=*/nullptr)) {
16961 QualType AddressParamType =
16962 SemaRef.Context.getCanonicalType(T: MD->getParamDecl(i: 1)->getType());
16963 if (AddressParamType != SemaRef.Context.VoidPtrTy &&
16964 AddressParamType == ConstructDestroyingDeleteAddressType()) {
16965 // The address parameter type implies an author trying to construct a
16966 // type aware destroying delete, so we'll see if we can find a parameter
16967 // of type `std::destroying_delete_t`, and if we find it we'll report
16968 // this as being an attempt at a type aware destroying delete just stop
16969 // here. If we don't do this, the resulting incorrect parameter ordering
16970 // results in a pile mismatched argument type errors that don't explain
16971 // the core problem.
16972 for (auto Param : MD->parameters()) {
16973 if (isDestroyingDeleteT(Type: Param->getType())) {
16974 SemaRef.Diag(Loc: MD->getLocation(),
16975 DiagID: diag::err_type_aware_destroying_operator_delete)
16976 << Param->getSourceRange();
16977 return true;
16978 }
16979 }
16980 }
16981 }
16982
16983 // C++ P0722:
16984 // Within a class C, the first parameter of a destroying operator delete
16985 // shall be of type C *. The first parameter of any other deallocation
16986 // function shall be of type void *.
16987 CanQualType ExpectedAddressParamType =
16988 MD && IsPotentiallyDestroyingOperatorDelete(SemaRef, FD: MD)
16989 ? SemaRef.Context.getPointerType(
16990 T: SemaRef.Context.getCanonicalTagType(TD: MD->getParent()))
16991 : SemaRef.Context.VoidPtrTy;
16992
16993 // C++ [basic.stc.dynamic.deallocation]p2:
16994 // Each deallocation function shall return void
16995 if (CheckOperatorNewDeleteTypes(
16996 SemaRef, FnDecl, OperatorKind: AllocationOperatorKind::Delete,
16997 ExpectedResultType: SemaRef.Context.VoidTy, ExpectedSizeOrAddressParamType: ExpectedAddressParamType,
16998 DependentParamTypeDiag: diag::err_operator_delete_dependent_param_type,
16999 InvalidParamTypeDiag: diag::err_operator_delete_param_type))
17000 return true;
17001
17002 // C++ P0722:
17003 // A destroying operator delete shall be a usual deallocation function.
17004 if (MD && !MD->getParent()->isDependentContext() &&
17005 MD->isDestroyingOperatorDelete()) {
17006 if (!SemaRef.isUsualDeallocationFunction(FD: MD)) {
17007 SemaRef.Diag(Loc: MD->getLocation(),
17008 DiagID: diag::err_destroying_operator_delete_not_usual);
17009 return true;
17010 }
17011 }
17012
17013 return false;
17014}
17015
17016bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
17017 assert(FnDecl && FnDecl->isOverloadedOperator() &&
17018 "Expected an overloaded operator declaration");
17019
17020 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
17021
17022 // C++ [over.oper]p5:
17023 // The allocation and deallocation functions, operator new,
17024 // operator new[], operator delete and operator delete[], are
17025 // described completely in 3.7.3. The attributes and restrictions
17026 // found in the rest of this subclause do not apply to them unless
17027 // explicitly stated in 3.7.3.
17028 if (Op == OO_Delete || Op == OO_Array_Delete)
17029 return CheckOperatorDeleteDeclaration(SemaRef&: *this, FnDecl);
17030
17031 if (Op == OO_New || Op == OO_Array_New)
17032 return CheckOperatorNewDeclaration(SemaRef&: *this, FnDecl);
17033
17034 // C++ [over.oper]p7:
17035 // An operator function shall either be a member function or
17036 // be a non-member function and have at least one parameter
17037 // whose type is a class, a reference to a class, an enumeration,
17038 // or a reference to an enumeration.
17039 // Note: Before C++23, a member function could not be static. The only member
17040 // function allowed to be static is the call operator function.
17041 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Val: FnDecl)) {
17042 if (MethodDecl->isStatic()) {
17043 if (Op == OO_Call || Op == OO_Subscript)
17044 DiagCompat(Loc: FnDecl->getLocation(), CompatDiagId: diag_compat::operator_overload_static)
17045 << FnDecl;
17046 else
17047 return Diag(Loc: FnDecl->getLocation(), DiagID: diag::err_operator_overload_static)
17048 << FnDecl;
17049 }
17050 } else {
17051 bool ClassOrEnumParam = false;
17052 for (auto *Param : FnDecl->parameters()) {
17053 QualType ParamType = Param->getType().getNonReferenceType();
17054 if (ParamType->isDependentType() || ParamType->isRecordType() ||
17055 ParamType->isEnumeralType()) {
17056 ClassOrEnumParam = true;
17057 break;
17058 }
17059 }
17060
17061 if (!ClassOrEnumParam)
17062 return Diag(Loc: FnDecl->getLocation(),
17063 DiagID: diag::err_operator_overload_needs_class_or_enum)
17064 << FnDecl->getDeclName();
17065 }
17066
17067 // C++ [over.oper]p8:
17068 // An operator function cannot have default arguments (8.3.6),
17069 // except where explicitly stated below.
17070 //
17071 // Only the function-call operator (C++ [over.call]p1) and the subscript
17072 // operator (CWG2507) allow default arguments.
17073 if (Op != OO_Call) {
17074 ParmVarDecl *FirstDefaultedParam = nullptr;
17075 for (auto *Param : FnDecl->parameters()) {
17076 if (Param->hasDefaultArg()) {
17077 FirstDefaultedParam = Param;
17078 break;
17079 }
17080 }
17081 if (FirstDefaultedParam) {
17082 if (Op == OO_Subscript) {
17083 Diag(Loc: FnDecl->getLocation(), DiagID: LangOpts.CPlusPlus23
17084 ? diag::ext_subscript_overload
17085 : diag::error_subscript_overload)
17086 << FnDecl->getDeclName() << 1
17087 << FirstDefaultedParam->getDefaultArgRange();
17088 } else {
17089 return Diag(Loc: FirstDefaultedParam->getLocation(),
17090 DiagID: diag::err_operator_overload_default_arg)
17091 << FnDecl->getDeclName()
17092 << FirstDefaultedParam->getDefaultArgRange();
17093 }
17094 }
17095 }
17096
17097 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
17098 { false, false, false }
17099#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
17100 , { Unary, Binary, MemberOnly }
17101#include "clang/Basic/OperatorKinds.def"
17102 };
17103
17104 bool CanBeUnaryOperator = OperatorUses[Op][0];
17105 bool CanBeBinaryOperator = OperatorUses[Op][1];
17106 bool MustBeMemberOperator = OperatorUses[Op][2];
17107
17108 // C++ [over.oper]p8:
17109 // [...] Operator functions cannot have more or fewer parameters
17110 // than the number required for the corresponding operator, as
17111 // described in the rest of this subclause.
17112 unsigned NumParams = FnDecl->getNumParams() +
17113 (isa<CXXMethodDecl>(Val: FnDecl) &&
17114 !FnDecl->hasCXXExplicitFunctionObjectParameter()
17115 ? 1
17116 : 0);
17117 if (Op != OO_Call && Op != OO_Subscript &&
17118 ((NumParams == 1 && !CanBeUnaryOperator) ||
17119 (NumParams == 2 && !CanBeBinaryOperator) || (NumParams < 1) ||
17120 (NumParams > 2))) {
17121 // We have the wrong number of parameters.
17122 unsigned ErrorKind;
17123 if (CanBeUnaryOperator && CanBeBinaryOperator) {
17124 ErrorKind = 2; // 2 -> unary or binary.
17125 } else if (CanBeUnaryOperator) {
17126 ErrorKind = 0; // 0 -> unary
17127 } else {
17128 assert(CanBeBinaryOperator &&
17129 "All non-call overloaded operators are unary or binary!");
17130 ErrorKind = 1; // 1 -> binary
17131 }
17132 return Diag(Loc: FnDecl->getLocation(), DiagID: diag::err_operator_overload_must_be)
17133 << FnDecl->getDeclName() << NumParams << ErrorKind;
17134 }
17135
17136 if (Op == OO_Subscript && NumParams != 2) {
17137 Diag(Loc: FnDecl->getLocation(), DiagID: LangOpts.CPlusPlus23
17138 ? diag::ext_subscript_overload
17139 : diag::error_subscript_overload)
17140 << FnDecl->getDeclName() << (NumParams == 1 ? 0 : 2);
17141 }
17142
17143 // Overloaded operators other than operator() and operator[] cannot be
17144 // variadic.
17145 if (Op != OO_Call &&
17146 FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) {
17147 return Diag(Loc: FnDecl->getLocation(), DiagID: diag::err_operator_overload_variadic)
17148 << FnDecl->getDeclName();
17149 }
17150
17151 // Some operators must be member functions.
17152 if (MustBeMemberOperator && !isa<CXXMethodDecl>(Val: FnDecl)) {
17153 return Diag(Loc: FnDecl->getLocation(),
17154 DiagID: diag::err_operator_overload_must_be_member)
17155 << FnDecl->getDeclName();
17156 }
17157
17158 // C++ [over.inc]p1:
17159 // The user-defined function called operator++ implements the
17160 // prefix and postfix ++ operator. If this function is a member
17161 // function with no parameters, or a non-member function with one
17162 // parameter of class or enumeration type, it defines the prefix
17163 // increment operator ++ for objects of that type. If the function
17164 // is a member function with one parameter (which shall be of type
17165 // int) or a non-member function with two parameters (the second
17166 // of which shall be of type int), it defines the postfix
17167 // increment operator ++ for objects of that type.
17168 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
17169 ParmVarDecl *LastParam = FnDecl->getParamDecl(i: FnDecl->getNumParams() - 1);
17170 QualType ParamType = LastParam->getType();
17171
17172 if (!ParamType->isSpecificBuiltinType(K: BuiltinType::Int) &&
17173 !ParamType->isDependentType())
17174 return Diag(Loc: LastParam->getLocation(),
17175 DiagID: diag::err_operator_overload_post_incdec_must_be_int)
17176 << LastParam->getType() << (Op == OO_MinusMinus);
17177 }
17178
17179 return false;
17180}
17181
17182static bool
17183checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
17184 FunctionTemplateDecl *TpDecl) {
17185 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
17186
17187 // Must have one or two template parameters.
17188 if (TemplateParams->size() == 1) {
17189 NonTypeTemplateParmDecl *PmDecl =
17190 dyn_cast<NonTypeTemplateParmDecl>(Val: TemplateParams->getParam(Idx: 0));
17191
17192 // The template parameter must be a char parameter pack.
17193 if (PmDecl && PmDecl->isTemplateParameterPack() &&
17194 SemaRef.Context.hasSameType(T1: PmDecl->getType(), T2: SemaRef.Context.CharTy))
17195 return false;
17196
17197 // C++20 [over.literal]p5:
17198 // A string literal operator template is a literal operator template
17199 // whose template-parameter-list comprises a single non-type
17200 // template-parameter of class type.
17201 //
17202 // As a DR resolution, we also allow placeholders for deduced class
17203 // template specializations.
17204 if (SemaRef.getLangOpts().CPlusPlus20 && PmDecl &&
17205 !PmDecl->isTemplateParameterPack() &&
17206 (PmDecl->getType()->isRecordType() ||
17207 PmDecl->getType()->getAs<DeducedTemplateSpecializationType>()))
17208 return false;
17209 } else if (TemplateParams->size() == 2) {
17210 TemplateTypeParmDecl *PmType =
17211 dyn_cast<TemplateTypeParmDecl>(Val: TemplateParams->getParam(Idx: 0));
17212 NonTypeTemplateParmDecl *PmArgs =
17213 dyn_cast<NonTypeTemplateParmDecl>(Val: TemplateParams->getParam(Idx: 1));
17214
17215 // The second template parameter must be a parameter pack with the
17216 // first template parameter as its type.
17217 if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
17218 PmArgs->isTemplateParameterPack()) {
17219 if (const auto *TArgs =
17220 PmArgs->getType()->getAsCanonical<TemplateTypeParmType>();
17221 TArgs && TArgs->getDepth() == PmType->getDepth() &&
17222 TArgs->getIndex() == PmType->getIndex()) {
17223 if (!SemaRef.inTemplateInstantiation())
17224 SemaRef.Diag(Loc: TpDecl->getLocation(),
17225 DiagID: diag::ext_string_literal_operator_template);
17226 return false;
17227 }
17228 }
17229 }
17230
17231 SemaRef.Diag(Loc: TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
17232 DiagID: diag::err_literal_operator_template)
17233 << TpDecl->getTemplateParameters()->getSourceRange();
17234 return true;
17235}
17236
17237bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
17238 if (isa<CXXMethodDecl>(Val: FnDecl)) {
17239 Diag(Loc: FnDecl->getLocation(), DiagID: diag::err_literal_operator_outside_namespace)
17240 << FnDecl->getDeclName();
17241 return true;
17242 }
17243
17244 if (FnDecl->isExternC()) {
17245 Diag(Loc: FnDecl->getLocation(), DiagID: diag::err_literal_operator_extern_c);
17246 if (const LinkageSpecDecl *LSD =
17247 FnDecl->getDeclContext()->getExternCContext())
17248 Diag(Loc: LSD->getExternLoc(), DiagID: diag::note_extern_c_begins_here);
17249 return true;
17250 }
17251
17252 // This might be the definition of a literal operator template.
17253 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
17254
17255 // This might be a specialization of a literal operator template.
17256 if (!TpDecl)
17257 TpDecl = FnDecl->getPrimaryTemplate();
17258
17259 // template <char...> type operator "" name() and
17260 // template <class T, T...> type operator "" name() are the only valid
17261 // template signatures, and the only valid signatures with no parameters.
17262 //
17263 // C++20 also allows template <SomeClass T> type operator "" name().
17264 if (TpDecl) {
17265 if (FnDecl->param_size() != 0) {
17266 Diag(Loc: FnDecl->getLocation(),
17267 DiagID: diag::err_literal_operator_template_with_params);
17268 return true;
17269 }
17270
17271 if (checkLiteralOperatorTemplateParameterList(SemaRef&: *this, TpDecl))
17272 return true;
17273
17274 } else if (FnDecl->param_size() == 1) {
17275 const ParmVarDecl *Param = FnDecl->getParamDecl(i: 0);
17276
17277 QualType ParamType = Param->getType().getUnqualifiedType();
17278
17279 // Only unsigned long long int, long double, any character type, and const
17280 // char * are allowed as the only parameters.
17281 if (ParamType->isSpecificBuiltinType(K: BuiltinType::ULongLong) ||
17282 ParamType->isSpecificBuiltinType(K: BuiltinType::LongDouble) ||
17283 Context.hasSameType(T1: ParamType, T2: Context.CharTy) ||
17284 Context.hasSameType(T1: ParamType, T2: Context.WideCharTy) ||
17285 Context.hasSameType(T1: ParamType, T2: Context.Char8Ty) ||
17286 Context.hasSameType(T1: ParamType, T2: Context.Char16Ty) ||
17287 Context.hasSameType(T1: ParamType, T2: Context.Char32Ty)) {
17288 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
17289 QualType InnerType = Ptr->getPointeeType();
17290
17291 // Pointer parameter must be a const char *.
17292 if (!(Context.hasSameType(T1: InnerType.getUnqualifiedType(),
17293 T2: Context.CharTy) &&
17294 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
17295 Diag(Loc: Param->getSourceRange().getBegin(),
17296 DiagID: diag::err_literal_operator_param)
17297 << ParamType << "'const char *'" << Param->getSourceRange();
17298 return true;
17299 }
17300
17301 } else if (ParamType->isRealFloatingType()) {
17302 Diag(Loc: Param->getSourceRange().getBegin(), DiagID: diag::err_literal_operator_param)
17303 << ParamType << Context.LongDoubleTy << Param->getSourceRange();
17304 return true;
17305
17306 } else if (ParamType->isIntegerType()) {
17307 Diag(Loc: Param->getSourceRange().getBegin(), DiagID: diag::err_literal_operator_param)
17308 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
17309 return true;
17310
17311 } else {
17312 Diag(Loc: Param->getSourceRange().getBegin(),
17313 DiagID: diag::err_literal_operator_invalid_param)
17314 << ParamType << Param->getSourceRange();
17315 return true;
17316 }
17317
17318 } else if (FnDecl->param_size() == 2) {
17319 FunctionDecl::param_iterator Param = FnDecl->param_begin();
17320
17321 // First, verify that the first parameter is correct.
17322
17323 QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
17324
17325 // Two parameter function must have a pointer to const as a
17326 // first parameter; let's strip those qualifiers.
17327 const PointerType *PT = FirstParamType->getAs<PointerType>();
17328
17329 if (!PT) {
17330 Diag(Loc: (*Param)->getSourceRange().getBegin(),
17331 DiagID: diag::err_literal_operator_param)
17332 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
17333 return true;
17334 }
17335
17336 QualType PointeeType = PT->getPointeeType();
17337 // First parameter must be const
17338 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
17339 Diag(Loc: (*Param)->getSourceRange().getBegin(),
17340 DiagID: diag::err_literal_operator_param)
17341 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
17342 return true;
17343 }
17344
17345 QualType InnerType = PointeeType.getUnqualifiedType();
17346 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
17347 // const char32_t* are allowed as the first parameter to a two-parameter
17348 // function
17349 if (!(Context.hasSameType(T1: InnerType, T2: Context.CharTy) ||
17350 Context.hasSameType(T1: InnerType, T2: Context.WideCharTy) ||
17351 Context.hasSameType(T1: InnerType, T2: Context.Char8Ty) ||
17352 Context.hasSameType(T1: InnerType, T2: Context.Char16Ty) ||
17353 Context.hasSameType(T1: InnerType, T2: Context.Char32Ty))) {
17354 Diag(Loc: (*Param)->getSourceRange().getBegin(),
17355 DiagID: diag::err_literal_operator_param)
17356 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
17357 return true;
17358 }
17359
17360 // Move on to the second and final parameter.
17361 ++Param;
17362
17363 // The second parameter must be a std::size_t.
17364 QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
17365 if (!Context.hasSameType(T1: SecondParamType, T2: Context.getSizeType())) {
17366 Diag(Loc: (*Param)->getSourceRange().getBegin(),
17367 DiagID: diag::err_literal_operator_param)
17368 << SecondParamType << Context.getSizeType()
17369 << (*Param)->getSourceRange();
17370 return true;
17371 }
17372 } else {
17373 Diag(Loc: FnDecl->getLocation(), DiagID: diag::err_literal_operator_bad_param_count);
17374 return true;
17375 }
17376
17377 // Parameters are good.
17378
17379 // A parameter-declaration-clause containing a default argument is not
17380 // equivalent to any of the permitted forms.
17381 for (auto *Param : FnDecl->parameters()) {
17382 if (Param->hasDefaultArg()) {
17383 Diag(Loc: Param->getDefaultArgRange().getBegin(),
17384 DiagID: diag::err_literal_operator_default_argument)
17385 << Param->getDefaultArgRange();
17386 break;
17387 }
17388 }
17389
17390 const IdentifierInfo *II = FnDecl->getDeclName().getCXXLiteralIdentifier();
17391 ReservedLiteralSuffixIdStatus Status = II->isReservedLiteralSuffixId();
17392 if (Status != ReservedLiteralSuffixIdStatus::NotReserved &&
17393 !getSourceManager().isInSystemHeader(Loc: FnDecl->getLocation())) {
17394 // C++23 [usrlit.suffix]p1:
17395 // Literal suffix identifiers that do not start with an underscore are
17396 // reserved for future standardization. Literal suffix identifiers that
17397 // contain a double underscore __ are reserved for use by C++
17398 // implementations.
17399 Diag(Loc: FnDecl->getLocation(), DiagID: diag::warn_user_literal_reserved)
17400 << static_cast<int>(Status)
17401 << StringLiteralParser::isValidUDSuffix(LangOpts: getLangOpts(), Suffix: II->getName());
17402 }
17403
17404 return false;
17405}
17406
17407Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
17408 Expr *LangStr,
17409 SourceLocation LBraceLoc) {
17410 StringLiteral *Lit = cast<StringLiteral>(Val: LangStr);
17411 assert(Lit->isUnevaluated() && "Unexpected string literal kind");
17412
17413 StringRef Lang = Lit->getString();
17414 LinkageSpecLanguageIDs Language;
17415 if (Lang == "C")
17416 Language = LinkageSpecLanguageIDs::C;
17417 else if (Lang == "C++")
17418 Language = LinkageSpecLanguageIDs::CXX;
17419 else {
17420 Diag(Loc: LangStr->getExprLoc(), DiagID: diag::err_language_linkage_spec_unknown)
17421 << LangStr->getSourceRange();
17422 return nullptr;
17423 }
17424
17425 // FIXME: Add all the various semantics of linkage specifications
17426
17427 LinkageSpecDecl *D = LinkageSpecDecl::Create(C&: Context, DC: CurContext, ExternLoc,
17428 LangLoc: LangStr->getExprLoc(), Lang: Language,
17429 HasBraces: LBraceLoc.isValid());
17430
17431 /// C++ [module.unit]p7.2.3
17432 /// - Otherwise, if the declaration
17433 /// - ...
17434 /// - ...
17435 /// - appears within a linkage-specification,
17436 /// it is attached to the global module.
17437 ///
17438 /// If the declaration is already in global module fragment, we don't
17439 /// need to attach it again.
17440 if (getLangOpts().CPlusPlusModules && isCurrentModulePurview()) {
17441 Module *GlobalModule = PushImplicitGlobalModuleFragment(BeginLoc: ExternLoc);
17442 D->setLocalOwningModule(GlobalModule);
17443 }
17444
17445 CurContext->addDecl(D);
17446 PushDeclContext(S, DC: D);
17447 return D;
17448}
17449
17450Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
17451 Decl *LinkageSpec,
17452 SourceLocation RBraceLoc) {
17453 if (RBraceLoc.isValid()) {
17454 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(Val: LinkageSpec);
17455 LSDecl->setRBraceLoc(RBraceLoc);
17456 }
17457
17458 // If the current module doesn't has Parent, it implies that the
17459 // LinkageSpec isn't in the module created by itself. So we don't
17460 // need to pop it.
17461 if (getLangOpts().CPlusPlusModules && getCurrentModule() &&
17462 getCurrentModule()->isImplicitGlobalModule() &&
17463 getCurrentModule()->Parent)
17464 PopImplicitGlobalModuleFragment();
17465
17466 PopDeclContext();
17467 return LinkageSpec;
17468}
17469
17470Decl *Sema::ActOnEmptyDeclaration(Scope *S,
17471 const ParsedAttributesView &AttrList,
17472 SourceLocation SemiLoc) {
17473 Decl *ED = EmptyDecl::Create(C&: Context, DC: CurContext, L: SemiLoc);
17474 // Attribute declarations appertain to empty declaration so we handle
17475 // them here.
17476 ProcessDeclAttributeList(S, D: ED, AttrList);
17477
17478 CurContext->addDecl(D: ED);
17479 return ED;
17480}
17481
17482VarDecl *Sema::BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
17483 SourceLocation StartLoc,
17484 SourceLocation Loc,
17485 const IdentifierInfo *Name) {
17486 bool Invalid = false;
17487 QualType ExDeclType = TInfo->getType();
17488
17489 // Arrays and functions decay.
17490 if (ExDeclType->isArrayType())
17491 ExDeclType = Context.getArrayDecayedType(T: ExDeclType);
17492 else if (ExDeclType->isFunctionType())
17493 ExDeclType = Context.getPointerType(T: ExDeclType);
17494
17495 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
17496 // The exception-declaration shall not denote a pointer or reference to an
17497 // incomplete type, other than [cv] void*.
17498 // N2844 forbids rvalue references.
17499 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
17500 Diag(Loc, DiagID: diag::err_catch_rvalue_ref);
17501 Invalid = true;
17502 }
17503
17504 if (ExDeclType->isVariablyModifiedType()) {
17505 Diag(Loc, DiagID: diag::err_catch_variably_modified) << ExDeclType;
17506 Invalid = true;
17507 }
17508
17509 QualType BaseType = ExDeclType;
17510 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
17511 unsigned DK = diag::err_catch_incomplete;
17512 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
17513 BaseType = Ptr->getPointeeType();
17514 Mode = 1;
17515 DK = diag::err_catch_incomplete_ptr;
17516 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
17517 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
17518 BaseType = Ref->getPointeeType();
17519 Mode = 2;
17520 DK = diag::err_catch_incomplete_ref;
17521 }
17522 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
17523 !BaseType->isDependentType() && RequireCompleteType(Loc, T: BaseType, DiagID: DK))
17524 Invalid = true;
17525
17526 if (!Invalid && BaseType.isWebAssemblyReferenceType()) {
17527 Diag(Loc, DiagID: diag::err_wasm_reftype_tc) << 1;
17528 Invalid = true;
17529 }
17530
17531 if (!Invalid && Mode != 1 && BaseType->isSizelessType()) {
17532 Diag(Loc, DiagID: diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType;
17533 Invalid = true;
17534 }
17535
17536 if (!Invalid && !ExDeclType->isDependentType() &&
17537 RequireNonAbstractType(Loc, T: ExDeclType,
17538 DiagID: diag::err_abstract_type_in_decl,
17539 Args: AbstractVariableType))
17540 Invalid = true;
17541
17542 // Only the non-fragile NeXT runtime currently supports C++ catches
17543 // of ObjC types, and no runtime supports catching ObjC types by value.
17544 if (!Invalid && getLangOpts().ObjC) {
17545 QualType T = ExDeclType;
17546 if (const ReferenceType *RT = T->getAs<ReferenceType>())
17547 T = RT->getPointeeType();
17548
17549 if (T->isObjCObjectType()) {
17550 Diag(Loc, DiagID: diag::err_objc_object_catch);
17551 Invalid = true;
17552 } else if (T->isObjCObjectPointerType()) {
17553 // FIXME: should this be a test for macosx-fragile specifically?
17554 if (getLangOpts().ObjCRuntime.isFragile())
17555 Diag(Loc, DiagID: diag::warn_objc_pointer_cxx_catch_fragile);
17556 }
17557 }
17558
17559 VarDecl *ExDecl = VarDecl::Create(C&: Context, DC: CurContext, StartLoc, IdLoc: Loc, Id: Name,
17560 T: ExDeclType, TInfo, S: SC_None);
17561 ExDecl->setExceptionVariable(true);
17562
17563 // In ARC, infer 'retaining' for variables of retainable type.
17564 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(decl: ExDecl))
17565 Invalid = true;
17566
17567 if (!Invalid && !ExDeclType->isDependentType()) {
17568 if (auto *ClassDecl = ExDeclType->getAsCXXRecordDecl()) {
17569 // Insulate this from anything else we might currently be parsing.
17570 EnterExpressionEvaluationContext scope(
17571 *this, ExpressionEvaluationContext::PotentiallyEvaluated);
17572
17573 // C++ [except.handle]p16:
17574 // The object declared in an exception-declaration or, if the
17575 // exception-declaration does not specify a name, a temporary (12.2) is
17576 // copy-initialized (8.5) from the exception object. [...]
17577 // The object is destroyed when the handler exits, after the destruction
17578 // of any automatic objects initialized within the handler.
17579 //
17580 // We just pretend to initialize the object with itself, then make sure
17581 // it can be destroyed later.
17582 QualType initType = Context.getExceptionObjectType(T: ExDeclType);
17583
17584 InitializedEntity entity =
17585 InitializedEntity::InitializeVariable(Var: ExDecl);
17586 InitializationKind initKind =
17587 InitializationKind::CreateCopy(InitLoc: Loc, EqualLoc: SourceLocation());
17588
17589 Expr *opaqueValue =
17590 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
17591 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
17592 ExprResult result = sequence.Perform(S&: *this, Entity: entity, Kind: initKind, Args: opaqueValue);
17593 if (result.isInvalid())
17594 Invalid = true;
17595 else {
17596 // If the constructor used was non-trivial, set this as the
17597 // "initializer".
17598 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
17599 if (!construct->getConstructor()->isTrivial()) {
17600 Expr *init = MaybeCreateExprWithCleanups(SubExpr: construct);
17601 ExDecl->setInit(init);
17602 }
17603
17604 // And make sure it's destructable.
17605 FinalizeVarWithDestructor(VD: ExDecl, ClassDecl);
17606 }
17607 }
17608 }
17609
17610 if (Invalid)
17611 ExDecl->setInvalidDecl();
17612
17613 return ExDecl;
17614}
17615
17616Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
17617 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
17618 bool Invalid = D.isInvalidType();
17619
17620 // Check for unexpanded parameter packs.
17621 if (DiagnoseUnexpandedParameterPack(Loc: D.getIdentifierLoc(), T: TInfo,
17622 UPPC: UPPC_ExceptionType)) {
17623 TInfo = Context.getTrivialTypeSourceInfo(T: Context.IntTy,
17624 Loc: D.getIdentifierLoc());
17625 Invalid = true;
17626 }
17627
17628 const IdentifierInfo *II = D.getIdentifier();
17629 if (NamedDecl *PrevDecl =
17630 LookupSingleName(S, Name: II, Loc: D.getIdentifierLoc(), NameKind: LookupOrdinaryName,
17631 Redecl: RedeclarationKind::ForVisibleRedeclaration)) {
17632 // The scope should be freshly made just for us. There is just no way
17633 // it contains any previous declaration, except for function parameters in
17634 // a function-try-block's catch statement.
17635 assert(!S->isDeclScope(PrevDecl));
17636 if (isDeclInScope(D: PrevDecl, Ctx: CurContext, S)) {
17637 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_redefinition)
17638 << D.getIdentifier();
17639 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_definition);
17640 Invalid = true;
17641 } else if (PrevDecl->isTemplateParameter())
17642 // Maybe we will complain about the shadowed template parameter.
17643 DiagnoseTemplateParameterShadow(Loc: D.getIdentifierLoc(), PrevDecl);
17644 }
17645
17646 if (D.getCXXScopeSpec().isSet() && !Invalid) {
17647 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_qualified_catch_declarator)
17648 << D.getCXXScopeSpec().getRange();
17649 Invalid = true;
17650 }
17651
17652 VarDecl *ExDecl = BuildExceptionDeclaration(
17653 S, TInfo, StartLoc: D.getBeginLoc(), Loc: D.getIdentifierLoc(), Name: D.getIdentifier());
17654 if (Invalid)
17655 ExDecl->setInvalidDecl();
17656
17657 // Add the exception declaration into this scope.
17658 if (II)
17659 PushOnScopeChains(D: ExDecl, S);
17660 else
17661 CurContext->addDecl(D: ExDecl);
17662
17663 ProcessDeclAttributes(S, D: ExDecl, PD: D);
17664 return ExDecl;
17665}
17666
17667Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
17668 Expr *AssertExpr,
17669 Expr *AssertMessageExpr,
17670 SourceLocation RParenLoc) {
17671 if (DiagnoseUnexpandedParameterPack(E: AssertExpr, UPPC: UPPC_StaticAssertExpression))
17672 return nullptr;
17673
17674 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
17675 AssertMessageExpr, RParenLoc, Failed: false);
17676}
17677
17678static void WriteCharTypePrefix(BuiltinType::Kind BTK, llvm::raw_ostream &OS) {
17679 switch (BTK) {
17680 case BuiltinType::Char_S:
17681 case BuiltinType::Char_U:
17682 break;
17683 case BuiltinType::Char8:
17684 OS << "u8";
17685 break;
17686 case BuiltinType::Char16:
17687 OS << 'u';
17688 break;
17689 case BuiltinType::Char32:
17690 OS << 'U';
17691 break;
17692 case BuiltinType::WChar_S:
17693 case BuiltinType::WChar_U:
17694 OS << 'L';
17695 break;
17696 default:
17697 llvm_unreachable("Non-character type");
17698 }
17699}
17700
17701/// Convert character's value, interpreted as a code unit, to a string.
17702/// The value needs to be zero-extended to 32-bits.
17703/// FIXME: This assumes Unicode literal encodings
17704static void WriteCharValueForDiagnostic(uint32_t Value, const BuiltinType *BTy,
17705 unsigned TyWidth,
17706 SmallVectorImpl<char> &Str) {
17707 char Arr[UNI_MAX_UTF8_BYTES_PER_CODE_POINT];
17708 char *Ptr = Arr;
17709 BuiltinType::Kind K = BTy->getKind();
17710 llvm::raw_svector_ostream OS(Str);
17711
17712 // This should catch Char_S, Char_U, Char8, and use of escaped characters in
17713 // other types.
17714 if (K == BuiltinType::Char_S || K == BuiltinType::Char_U ||
17715 K == BuiltinType::Char8 || Value <= 0x7F) {
17716 StringRef Escaped = escapeCStyle<EscapeChar::Single>(Ch: Value);
17717 if (!Escaped.empty())
17718 EscapeStringForDiagnostic(Str: Escaped, OutStr&: Str);
17719 else
17720 OS << static_cast<char>(Value);
17721 return;
17722 }
17723
17724 switch (K) {
17725 case BuiltinType::Char16:
17726 case BuiltinType::Char32:
17727 case BuiltinType::WChar_S:
17728 case BuiltinType::WChar_U: {
17729 if (llvm::ConvertCodePointToUTF8(Source: Value, ResultPtr&: Ptr))
17730 EscapeStringForDiagnostic(Str: StringRef(Arr, Ptr - Arr), OutStr&: Str);
17731 else
17732 OS << "\\x"
17733 << llvm::format_hex_no_prefix(N: Value, Width: TyWidth / 4, /*Upper=*/true);
17734 break;
17735 }
17736 default:
17737 llvm_unreachable("Non-character type is passed");
17738 }
17739}
17740
17741/// Convert \V to a string we can present to the user in a diagnostic
17742/// \T is the type of the expression that has been evaluated into \V
17743static bool ConvertAPValueToString(const APValue &V, QualType T,
17744 SmallVectorImpl<char> &Str,
17745 ASTContext &Context) {
17746 if (!V.hasValue())
17747 return false;
17748
17749 switch (V.getKind()) {
17750 case APValue::ValueKind::Int:
17751 if (T->isBooleanType()) {
17752 // Bools are reduced to ints during evaluation, but for
17753 // diagnostic purposes we want to print them as
17754 // true or false.
17755 int64_t BoolValue = V.getInt().getExtValue();
17756 assert((BoolValue == 0 || BoolValue == 1) &&
17757 "Bool type, but value is not 0 or 1");
17758 llvm::raw_svector_ostream OS(Str);
17759 OS << (BoolValue ? "true" : "false");
17760 } else {
17761 llvm::raw_svector_ostream OS(Str);
17762 // Same is true for chars.
17763 // We want to print the character representation for textual types
17764 const auto *BTy = T->getAs<BuiltinType>();
17765 if (BTy) {
17766 switch (BTy->getKind()) {
17767 case BuiltinType::Char_S:
17768 case BuiltinType::Char_U:
17769 case BuiltinType::Char8:
17770 case BuiltinType::Char16:
17771 case BuiltinType::Char32:
17772 case BuiltinType::WChar_S:
17773 case BuiltinType::WChar_U: {
17774 unsigned TyWidth = Context.getIntWidth(T);
17775 assert(8 <= TyWidth && TyWidth <= 32 && "Unexpected integer width");
17776 uint32_t CodeUnit = static_cast<uint32_t>(V.getInt().getZExtValue());
17777 WriteCharTypePrefix(BTK: BTy->getKind(), OS);
17778 OS << '\'';
17779 WriteCharValueForDiagnostic(Value: CodeUnit, BTy, TyWidth, Str);
17780 OS << "' (0x"
17781 << llvm::format_hex_no_prefix(N: CodeUnit, /*Width=*/2,
17782 /*Upper=*/true)
17783 << ", " << V.getInt() << ')';
17784 return true;
17785 }
17786 default:
17787 break;
17788 }
17789 }
17790 V.getInt().toString(Str);
17791 }
17792
17793 break;
17794
17795 case APValue::ValueKind::Float:
17796 V.getFloat().toString(Str);
17797 break;
17798
17799 case APValue::ValueKind::LValue:
17800 if (V.isNullPointer()) {
17801 llvm::raw_svector_ostream OS(Str);
17802 OS << "nullptr";
17803 } else
17804 return false;
17805 break;
17806
17807 case APValue::ValueKind::ComplexFloat: {
17808 llvm::raw_svector_ostream OS(Str);
17809 OS << '(';
17810 V.getComplexFloatReal().toString(Str);
17811 OS << " + ";
17812 V.getComplexFloatImag().toString(Str);
17813 OS << "i)";
17814 } break;
17815
17816 case APValue::ValueKind::ComplexInt: {
17817 llvm::raw_svector_ostream OS(Str);
17818 OS << '(';
17819 V.getComplexIntReal().toString(Str);
17820 OS << " + ";
17821 V.getComplexIntImag().toString(Str);
17822 OS << "i)";
17823 } break;
17824
17825 default:
17826 return false;
17827 }
17828
17829 return true;
17830}
17831
17832/// Some Expression types are not useful to print notes about,
17833/// e.g. literals and values that have already been expanded
17834/// before such as int-valued template parameters.
17835static bool UsefulToPrintExpr(const Expr *E) {
17836 E = E->IgnoreParenImpCasts();
17837 // Literals are pretty easy for humans to understand.
17838 if (isa<IntegerLiteral, FloatingLiteral, CharacterLiteral, CXXBoolLiteralExpr,
17839 CXXNullPtrLiteralExpr, FixedPointLiteral, ImaginaryLiteral>(Val: E))
17840 return false;
17841
17842 // These have been substituted from template parameters
17843 // and appear as literals in the static assert error.
17844 if (isa<SubstNonTypeTemplateParmExpr>(Val: E))
17845 return false;
17846
17847 // -5 is also simple to understand.
17848 if (const auto *UnaryOp = dyn_cast<UnaryOperator>(Val: E))
17849 return UsefulToPrintExpr(E: UnaryOp->getSubExpr());
17850
17851 // Only print nested arithmetic operators.
17852 if (const auto *BO = dyn_cast<BinaryOperator>(Val: E))
17853 return (BO->isShiftOp() || BO->isAdditiveOp() || BO->isMultiplicativeOp() ||
17854 BO->isBitwiseOp());
17855
17856 return true;
17857}
17858
17859void Sema::DiagnoseStaticAssertDetails(const Expr *E) {
17860 // FIXME: Should we also ignore explicit casts?
17861 E = E->IgnoreParenImpCasts();
17862 if (const auto *Op = dyn_cast<BinaryOperator>(Val: E);
17863 Op && Op->getOpcode() != BO_LOr) {
17864 const Expr *LHS = Op->getLHS()->IgnoreParenImpCasts();
17865 const Expr *RHS = Op->getRHS()->IgnoreParenImpCasts();
17866
17867 // Ignore comparisons of boolean expressions with a boolean literal.
17868 if ((isa<CXXBoolLiteralExpr>(Val: LHS) && RHS->getType()->isBooleanType()) ||
17869 (isa<CXXBoolLiteralExpr>(Val: RHS) && LHS->getType()->isBooleanType()))
17870 return;
17871
17872 // Don't print obvious expressions.
17873 if (!UsefulToPrintExpr(E: LHS) && !UsefulToPrintExpr(E: RHS))
17874 return;
17875
17876 struct {
17877 const clang::Expr *Cond;
17878 Expr::EvalResult Result;
17879 SmallString<12> ValueString;
17880 bool Print;
17881 } DiagSides[2] = {{.Cond: LHS, .Result: Expr::EvalResult(), .ValueString: {}, .Print: false},
17882 {.Cond: RHS, .Result: Expr::EvalResult(), .ValueString: {}, .Print: false}};
17883 for (auto &DiagSide : DiagSides) {
17884 const Expr *Side = DiagSide.Cond;
17885
17886 Side->EvaluateAsRValue(Result&: DiagSide.Result, Ctx: Context, InConstantContext: true);
17887
17888 DiagSide.Print = ConvertAPValueToString(
17889 V: DiagSide.Result.Val, T: Side->getType(), Str&: DiagSide.ValueString, Context);
17890 }
17891 if (DiagSides[0].Print && DiagSides[1].Print) {
17892 Diag(Loc: Op->getExprLoc(), DiagID: diag::note_expr_evaluates_to)
17893 << DiagSides[0].ValueString << Op->getOpcodeStr()
17894 << DiagSides[1].ValueString << Op->getSourceRange();
17895 }
17896 } else if (const auto *RE = dyn_cast<RequiresExpr>(Val: E)) {
17897 DiagnoseUnsatisfiedRequiresExpr(RequiresExpr: RE);
17898 } else {
17899 DiagnoseTypeTraitDetails(E);
17900 }
17901}
17902
17903template <typename ResultType>
17904static bool EvaluateAsStringImpl(Sema &SemaRef, Expr *Message,
17905 ResultType &Result, ASTContext &Ctx,
17906 Sema::StringEvaluationContext EvalContext,
17907 bool ErrorOnInvalidMessage) {
17908
17909 assert(Message);
17910 assert(!Message->isTypeDependent() && !Message->isValueDependent() &&
17911 "can't evaluate a dependant static assert message");
17912
17913 if (const auto *SL = dyn_cast<StringLiteral>(Val: Message)) {
17914 assert(SL->isUnevaluated() && "expected an unevaluated string");
17915 if constexpr (std::is_same_v<APValue, ResultType>) {
17916 Result =
17917 APValue(APValue::UninitArray{}, SL->getLength(), SL->getLength());
17918 const ConstantArrayType *CAT =
17919 SemaRef.getASTContext().getAsConstantArrayType(T: SL->getType());
17920 assert(CAT && "string literal isn't an array");
17921 QualType CharType = CAT->getElementType();
17922 llvm::APSInt Value(SemaRef.getASTContext().getTypeSize(T: CharType),
17923 CharType->isUnsignedIntegerType());
17924 for (unsigned I = 0; I < SL->getLength(); I++) {
17925 Value = SL->getCodeUnit(I);
17926 Result.getArrayInitializedElt(I) = APValue(Value);
17927 }
17928 } else {
17929 Result.assign(SL->getString().begin(), SL->getString().end());
17930 }
17931 return true;
17932 }
17933
17934 SourceLocation Loc = Message->getBeginLoc();
17935 QualType T = Message->getType().getNonReferenceType();
17936 auto *RD = T->getAsCXXRecordDecl();
17937 if (!RD) {
17938 SemaRef.Diag(Loc, DiagID: diag::err_user_defined_msg_invalid) << EvalContext;
17939 return false;
17940 }
17941
17942 auto FindMember = [&](StringRef Member) -> std::optional<LookupResult> {
17943 DeclarationName DN = SemaRef.PP.getIdentifierInfo(Name: Member);
17944 LookupResult MemberLookup(SemaRef, DN, Loc, Sema::LookupMemberName);
17945 SemaRef.LookupQualifiedName(R&: MemberLookup, LookupCtx: RD);
17946 OverloadCandidateSet Candidates(MemberLookup.getNameLoc(),
17947 OverloadCandidateSet::CSK_Normal);
17948 if (MemberLookup.empty())
17949 return std::nullopt;
17950 return std::move(MemberLookup);
17951 };
17952
17953 std::optional<LookupResult> SizeMember = FindMember("size");
17954 std::optional<LookupResult> DataMember = FindMember("data");
17955 if (!SizeMember || !DataMember) {
17956 SemaRef.Diag(Loc, DiagID: diag::err_user_defined_msg_missing_member_function)
17957 << EvalContext
17958 << ((!SizeMember && !DataMember) ? 2
17959 : !SizeMember ? 0
17960 : 1);
17961 return false;
17962 }
17963
17964 auto BuildExpr = [&](LookupResult &LR) {
17965 ExprResult Res = SemaRef.BuildMemberReferenceExpr(
17966 Base: Message, BaseType: Message->getType(), OpLoc: Message->getBeginLoc(), IsArrow: false,
17967 SS: CXXScopeSpec(), TemplateKWLoc: SourceLocation(), FirstQualifierInScope: nullptr, R&: LR, TemplateArgs: nullptr, S: nullptr);
17968 if (Res.isInvalid())
17969 return ExprError();
17970 Res = SemaRef.BuildCallExpr(S: nullptr, Fn: Res.get(), LParenLoc: Loc, ArgExprs: {}, RParenLoc: Loc, ExecConfig: nullptr,
17971 IsExecConfig: false, AllowRecovery: true);
17972 if (Res.isInvalid())
17973 return ExprError();
17974 if (Res.get()->isTypeDependent() || Res.get()->isValueDependent())
17975 return ExprError();
17976 return SemaRef.TemporaryMaterializationConversion(E: Res.get());
17977 };
17978
17979 ExprResult SizeE = BuildExpr(*SizeMember);
17980 ExprResult DataE = BuildExpr(*DataMember);
17981
17982 QualType SizeT = SemaRef.Context.getSizeType();
17983 QualType ConstCharPtr = SemaRef.Context.getPointerType(
17984 T: SemaRef.Context.getConstType(T: SemaRef.Context.CharTy));
17985
17986 ExprResult EvaluatedSize =
17987 SizeE.isInvalid()
17988 ? ExprError()
17989 : SemaRef.BuildConvertedConstantExpression(
17990 From: SizeE.get(), T: SizeT, CCE: CCEKind::StaticAssertMessageSize);
17991 if (EvaluatedSize.isInvalid()) {
17992 SemaRef.Diag(Loc, DiagID: diag::err_user_defined_msg_invalid_mem_fn_ret_ty)
17993 << EvalContext << /*size*/ 0;
17994 return false;
17995 }
17996
17997 ExprResult EvaluatedData =
17998 DataE.isInvalid()
17999 ? ExprError()
18000 : SemaRef.BuildConvertedConstantExpression(
18001 From: DataE.get(), T: ConstCharPtr, CCE: CCEKind::StaticAssertMessageData);
18002 if (EvaluatedData.isInvalid()) {
18003 SemaRef.Diag(Loc, DiagID: diag::err_user_defined_msg_invalid_mem_fn_ret_ty)
18004 << EvalContext << /*data*/ 1;
18005 return false;
18006 }
18007
18008 if (!ErrorOnInvalidMessage &&
18009 SemaRef.Diags.isIgnored(DiagID: diag::warn_user_defined_msg_constexpr, Loc))
18010 return true;
18011
18012 Expr::EvalResult Status;
18013 SmallVector<PartialDiagnosticAt, 8> Notes;
18014 Status.Diag = &Notes;
18015 if (!Message->EvaluateCharRangeAsString(Result, EvaluatedSize.get(),
18016 EvaluatedData.get(), Ctx, Status) ||
18017 !Notes.empty()) {
18018 SemaRef.Diag(Loc: Message->getBeginLoc(),
18019 DiagID: ErrorOnInvalidMessage ? diag::err_user_defined_msg_constexpr
18020 : diag::warn_user_defined_msg_constexpr)
18021 << EvalContext;
18022 for (const auto &Note : Notes)
18023 SemaRef.Diag(Loc: Note.first, PD: Note.second);
18024 return !ErrorOnInvalidMessage;
18025 }
18026 return true;
18027}
18028
18029bool Sema::EvaluateAsString(Expr *Message, APValue &Result, ASTContext &Ctx,
18030 StringEvaluationContext EvalContext,
18031 bool ErrorOnInvalidMessage) {
18032 return EvaluateAsStringImpl(SemaRef&: *this, Message, Result, Ctx, EvalContext,
18033 ErrorOnInvalidMessage);
18034}
18035
18036bool Sema::EvaluateAsString(Expr *Message, std::string &Result, ASTContext &Ctx,
18037 StringEvaluationContext EvalContext,
18038 bool ErrorOnInvalidMessage) {
18039 return EvaluateAsStringImpl(SemaRef&: *this, Message, Result, Ctx, EvalContext,
18040 ErrorOnInvalidMessage);
18041}
18042
18043Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
18044 Expr *AssertExpr, Expr *AssertMessage,
18045 SourceLocation RParenLoc,
18046 bool Failed) {
18047 assert(AssertExpr != nullptr && "Expected non-null condition");
18048 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
18049 (!AssertMessage || (!AssertMessage->isTypeDependent() &&
18050 !AssertMessage->isValueDependent())) &&
18051 !Failed) {
18052 // In a static_assert-declaration, the constant-expression shall be a
18053 // constant expression that can be contextually converted to bool.
18054 ExprResult Converted = PerformContextuallyConvertToBool(From: AssertExpr);
18055 if (Converted.isInvalid())
18056 Failed = true;
18057
18058 ExprResult FullAssertExpr =
18059 ActOnFinishFullExpr(Expr: Converted.get(), CC: StaticAssertLoc,
18060 /*DiscardedValue*/ false,
18061 /*IsConstexpr*/ true);
18062 if (FullAssertExpr.isInvalid())
18063 Failed = true;
18064 else
18065 AssertExpr = FullAssertExpr.get();
18066
18067 llvm::APSInt Cond;
18068 Expr *BaseExpr = AssertExpr;
18069 AllowFoldKind FoldKind = AllowFoldKind::No;
18070
18071 if (!getLangOpts().CPlusPlus) {
18072 // In C mode, allow folding as an extension for better compatibility with
18073 // C++ in terms of expressions like static_assert("test") or
18074 // static_assert(nullptr).
18075 FoldKind = AllowFoldKind::Allow;
18076 }
18077
18078 if (!Failed && VerifyIntegerConstantExpression(
18079 E: BaseExpr, Result: &Cond,
18080 DiagID: diag::err_static_assert_expression_is_not_constant,
18081 CanFold: FoldKind).isInvalid())
18082 Failed = true;
18083
18084 // If the static_assert passes, only verify that
18085 // the message is grammatically valid without evaluating it.
18086 if (!Failed && AssertMessage && Cond.getBoolValue()) {
18087 std::string Str;
18088 EvaluateAsString(Message: AssertMessage, Result&: Str, Ctx&: Context,
18089 EvalContext: StringEvaluationContext::StaticAssert,
18090 /*ErrorOnInvalidMessage=*/false);
18091 }
18092
18093 // CWG2518
18094 // [dcl.pre]/p10 If [...] the expression is evaluated in the context of a
18095 // template definition, the declaration has no effect.
18096 bool InTemplateDefinition =
18097 getLangOpts().CPlusPlus && CurContext->isDependentContext();
18098
18099 if (!Failed && !Cond && !InTemplateDefinition) {
18100 SmallString<256> MsgBuffer;
18101 llvm::raw_svector_ostream Msg(MsgBuffer);
18102 bool HasMessage = AssertMessage;
18103 if (AssertMessage) {
18104 std::string Str;
18105 HasMessage = EvaluateAsString(Message: AssertMessage, Result&: Str, Ctx&: Context,
18106 EvalContext: StringEvaluationContext::StaticAssert,
18107 /*ErrorOnInvalidMessage=*/true) ||
18108 !Str.empty();
18109 Msg << Str;
18110 }
18111 Expr *InnerCond = nullptr;
18112 std::string InnerCondDescription;
18113 std::tie(args&: InnerCond, args&: InnerCondDescription) =
18114 findFailedBooleanCondition(Cond: Converted.get());
18115 if (const auto *ConceptIDExpr =
18116 dyn_cast_or_null<ConceptSpecializationExpr>(Val: InnerCond)) {
18117 const ASTConstraintSatisfaction &Satisfaction =
18118 ConceptIDExpr->getSatisfaction();
18119 if (!Satisfaction.ContainsErrors || Satisfaction.NumRecords) {
18120 Diag(Loc: AssertExpr->getBeginLoc(), DiagID: diag::err_static_assert_failed)
18121 << !HasMessage << Msg.str() << AssertExpr->getSourceRange();
18122 // Drill down into concept specialization expressions to see why they
18123 // weren't satisfied.
18124 DiagnoseUnsatisfiedConstraint(ConstraintExpr: ConceptIDExpr);
18125 }
18126 } else if (InnerCond && !isa<CXXBoolLiteralExpr>(Val: InnerCond) &&
18127 !isa<IntegerLiteral>(Val: InnerCond)) {
18128 Diag(Loc: InnerCond->getBeginLoc(),
18129 DiagID: diag::err_static_assert_requirement_failed)
18130 << InnerCondDescription << !HasMessage << Msg.str()
18131 << InnerCond->getSourceRange();
18132 DiagnoseStaticAssertDetails(E: InnerCond);
18133 } else {
18134 Diag(Loc: AssertExpr->getBeginLoc(), DiagID: diag::err_static_assert_failed)
18135 << !HasMessage << Msg.str() << AssertExpr->getSourceRange();
18136 PrintContextStack();
18137 }
18138 Failed = true;
18139 }
18140 } else {
18141 ExprResult FullAssertExpr = ActOnFinishFullExpr(Expr: AssertExpr, CC: StaticAssertLoc,
18142 /*DiscardedValue*/false,
18143 /*IsConstexpr*/true);
18144 if (FullAssertExpr.isInvalid())
18145 Failed = true;
18146 else
18147 AssertExpr = FullAssertExpr.get();
18148 }
18149
18150 Decl *Decl = StaticAssertDecl::Create(C&: Context, DC: CurContext, StaticAssertLoc,
18151 AssertExpr, Message: AssertMessage, RParenLoc,
18152 Failed);
18153
18154 CurContext->addDecl(D: Decl);
18155 return Decl;
18156}
18157
18158static QualType IgnorePackIndexing(QualType T) {
18159 if (const auto *PIT = dyn_cast<PackIndexingType>(Val&: T))
18160 return PIT->getPattern();
18161 return T;
18162}
18163
18164static const TemplateSpecializationType *
18165GetClassTemplateSpecializationType(ASTContext &Context, QualType T) {
18166 T = IgnorePackIndexing(T);
18167 if (const auto *ICNT = dyn_cast<InjectedClassNameType>(Val&: T))
18168 T = ICNT->getDecl()->getCanonicalTemplateSpecializationType(Ctx: Context);
18169
18170 const auto *TST = dyn_cast<TemplateSpecializationType>(Val&: T);
18171 if (!TST)
18172 return nullptr;
18173
18174 TemplateDecl *TD = TST->getTemplateName().getAsTemplateDecl();
18175 if (!TD || isa<ClassTemplateDecl>(Val: TD))
18176 return TST;
18177 return nullptr;
18178}
18179
18180bool Sema::DiagnosePackIndexingInFriendNNS(SourceLocation Loc,
18181 NestedNameSpecifierLoc NNSLoc) {
18182 for (TypeLoc TL = NNSLoc.getAsTypeLoc(); TL;
18183 TL = TL.getPrefix().getAsTypeLoc()) {
18184 if (TL.getTypeLocClass() != TypeLoc::PackIndexing)
18185 continue;
18186
18187 Diag(Loc, DiagID: diag::err_pack_indexing_in_friend) << TL.getSourceRange();
18188 return true;
18189 }
18190 return false;
18191}
18192
18193static void DiagnoseDependentFriendNotMember(Sema &S, SourceLocation Loc,
18194 NestedNameSpecifier NNS) {
18195 QualType T(NNS.getAsType(), 0);
18196 if (const auto *TST =
18197 dyn_cast<TemplateSpecializationType>(Val: IgnorePackIndexing(T))) {
18198 if (isa_and_nonnull<TypeAliasTemplateDecl>(
18199 Val: TST->getTemplateName().getAsTemplateDecl())) {
18200 S.Diag(Loc, DiagID: diag::err_dependent_friend_not_member_of_template_spec)
18201 << NNS;
18202 return;
18203 }
18204 }
18205
18206 if (NNS.getAsRecordDecl()) {
18207 S.Diag(Loc, DiagID: diag::err_dependent_friend_not_member_of_template_spec) << NNS;
18208 } else {
18209 S.Diag(Loc, DiagID: diag::err_dependent_friend_not_member);
18210 }
18211}
18212
18213bool Sema::CheckDependentFriend(SourceLocation Loc,
18214 NestedNameSpecifierLoc NNSLoc,
18215 ArrayRef<TemplateParameterList *> TPLs,
18216 bool IsInstantiation) {
18217 NestedNameSpecifier NNS = NNSLoc.getNestedNameSpecifier();
18218 if (!NNS.isDependent() && !IsInstantiation)
18219 return false;
18220
18221 assert(NNS.getKind() == NestedNameSpecifier::Kind::Type &&
18222 "nested-name-specifier of dependent friend must be a type");
18223
18224 QualType T(NNS.getAsType(), 0);
18225 if (DiagnosePackIndexingInFriendNNS(Loc, NNSLoc))
18226 return true;
18227
18228 const TemplateSpecializationType *TST =
18229 GetClassTemplateSpecializationType(Context, T);
18230 if (!TST) {
18231 DiagnoseDependentFriendNotMember(S&: *this, Loc, NNS);
18232 return true;
18233 }
18234
18235 if (TPLs.empty())
18236 return false;
18237
18238 SmallVector<NamedDecl *, 4> UndeducedParameters;
18239 for (TemplateParameterList *Params : TPLs) {
18240 llvm::SmallBitVector UsedParameters(Params->size());
18241 MarkUsedTemplateParameters(TemplateArgs: TST->template_arguments(),
18242 /*OnlyDeduced=*/true, Depth: Params->getDepth(),
18243 Used&: UsedParameters);
18244
18245 for (unsigned I = 0, N = UsedParameters.size(); I != N; ++I)
18246 if (!UsedParameters[I])
18247 UndeducedParameters.push_back(Elt: Params->getParam(Idx: I));
18248 }
18249
18250 if (UndeducedParameters.empty())
18251 return false;
18252
18253 Diag(Loc, DiagID: diag::err_dependent_friend_undeduced_params)
18254 << (UndeducedParameters.size() > 1) << QualType(TST, 0);
18255
18256 for (NamedDecl *Param : UndeducedParameters) {
18257 if (Param->getDeclName())
18258 Diag(Loc: Param->getLocation(), DiagID: diag::note_non_deducible_parameter)
18259 << Param->getDeclName();
18260 else
18261 Diag(Loc: Param->getLocation(), DiagID: diag::note_non_deducible_parameter)
18262 << "(anonymous)";
18263 }
18264
18265 return true;
18266}
18267
18268DeclResult Sema::ActOnTemplatedFriendTag(
18269 Scope *S, SourceLocation FriendLoc, unsigned TagSpec, SourceLocation TagLoc,
18270 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
18271 SourceLocation EllipsisLoc, const ParsedAttributesView &Attr,
18272 MultiTemplateParamsArg TempParamLists, TemplateIdAnnotation *TemplateId) {
18273 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
18274
18275 bool IsMemberSpecialization = false;
18276 bool Invalid = false;
18277
18278 TemplateParameterList *TemplateParams =
18279 MatchTemplateParametersToScopeSpecifier(DeclStartLoc: TagLoc, DeclLoc: NameLoc, SS, TemplateId,
18280 ParamLists: TempParamLists, /*friend*/ IsFriend: true,
18281 IsMemberSpecialization, Invalid);
18282 if (TemplateId) {
18283 if (Invalid)
18284 return true;
18285
18286 if (TemplateParams) {
18287 Diag(Loc: NameLoc, DiagID: diag::err_not_class_template_specialization) << 0;
18288 return true;
18289 }
18290 }
18291
18292 if (TemplateParams) {
18293 if (TemplateParams->size() > 0) {
18294 if (Invalid)
18295 return true;
18296
18297 if (SS.isEmpty() || !SS.getScopeRep().isDependent()) {
18298 DeclResult Result = CheckClassTemplate(
18299 S, TagSpec, TUK: TagUseKind::Friend, KWLoc: TagLoc, SS, Name, NameLoc, Attr,
18300 TemplateParams, AS: AS_public, /*ModulePrivateLoc=*/SourceLocation(),
18301 FriendLoc, NumOuterTemplateParamLists: TempParamLists.size() - 1, OuterTemplateParamLists: TempParamLists.data(),
18302 IsMemberSpecialization);
18303 return Result.get();
18304 }
18305 } else {
18306 // The "template<>" header is extraneous.
18307 Diag(Loc: TemplateParams->getTemplateLoc(), DiagID: diag::err_template_tag_noparams)
18308 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
18309 }
18310 }
18311
18312 if (Invalid)
18313 return true;
18314
18315 bool IsAllExplicitSpecializations =
18316 llvm::all_of(Range&: TempParamLists, P: [](const TemplateParameterList *List) {
18317 return List->size() == 0;
18318 });
18319
18320 // FIXME: don't ignore attributes.
18321
18322 // If it's explicit specializations all the way down, just forget
18323 // about the template header and build an appropriate non-templated
18324 // friend. TODO: for source fidelity, remember the headers.
18325 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
18326 if (!TemplateId && IsAllExplicitSpecializations) {
18327 if (SS.isEmpty()) {
18328 bool Owned = false;
18329 bool IsDependent = false;
18330 return ActOnTag(S, TagSpec, TUK: TagUseKind::Friend, KWLoc: TagLoc, SS, Name, NameLoc,
18331 Attr, AS: AS_public,
18332 /*ModulePrivateLoc=*/SourceLocation(),
18333 TemplateParameterLists: MultiTemplateParamsArg(), OwnedDecl&: Owned, IsDependent,
18334 /*ScopedEnumKWLoc=*/SourceLocation(),
18335 /*ScopedEnumUsesClassTag=*/false,
18336 /*UnderlyingType=*/TypeResult(),
18337 /*IsTypeSpecifier=*/false,
18338 /*IsTemplateParamOrArg=*/false,
18339 /*OOK=*/OffsetOfKind::Outside);
18340 }
18341
18342 TypeSourceInfo *TSI = nullptr;
18343 ElaboratedTypeKeyword Keyword =
18344 TypeWithKeyword::getKeywordForTagTypeKind(Tag: Kind);
18345 QualType T = CheckTypenameType(Keyword, KeywordLoc: TagLoc, QualifierLoc, II: *Name,
18346 IILoc: NameLoc, TSI: &TSI, /*DeducedTSTContext=*/true);
18347 if (T.isNull())
18348 return true;
18349
18350 FriendDecl *Friend = FriendDecl::Create(C&: Context, DC: CurContext, L: NameLoc, Friend: TSI,
18351 FriendL: FriendLoc, EllipsisLoc);
18352 Friend->setAccess(AS_public);
18353 CurContext->addDecl(D: Friend);
18354 return Friend;
18355 }
18356
18357 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
18358
18359 ArrayRef<TemplateParameterList *> TPLs = TempParamLists;
18360 if (TemplateParams)
18361 TPLs = TPLs.drop_back();
18362 if (CheckDependentFriend(Loc: TagLoc, NNSLoc: QualifierLoc, TPLs,
18363 /*IsInstantiation=*/false))
18364 return true;
18365
18366 TypeSourceInfo *TSI = nullptr;
18367 if (TemplateId) {
18368 ASTTemplateArgsPtr ParsedArgs(TemplateId->getTemplateArgs(),
18369 TemplateId->NumArgs);
18370 TypeResult ParsedType = ActOnTagTemplateIdType(
18371 TUK: TagUseKind::Friend, TagSpec: static_cast<TypeSpecifierType>(TagSpec), TagLoc, SS,
18372 TemplateKWLoc: TemplateId->TemplateKWLoc, TemplateD: TemplateId->Template, TemplateLoc: NameLoc,
18373 LAngleLoc: TemplateId->LAngleLoc, TemplateArgsIn: ParsedArgs, RAngleLoc: TemplateId->RAngleLoc);
18374 if (ParsedType.isInvalid())
18375 return true;
18376
18377 GetTypeFromParser(Ty: ParsedType.get(), TInfo: &TSI);
18378 } else {
18379 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Tag: Kind);
18380 QualType T = Context.getDependentNameType(Keyword: ETK, NNS: SS.getScopeRep(), Name);
18381 TSI = Context.CreateTypeSourceInfo(T);
18382
18383 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
18384 TL.setElaboratedKeywordLoc(TagLoc);
18385 TL.setQualifierLoc(QualifierLoc);
18386 TL.setNameLoc(NameLoc);
18387 }
18388
18389 SmallVector<UnexpandedParameterPack, 1> Unexpanded;
18390 collectUnexpandedParameterPacks(TL: TSI->getTypeLoc(), Unexpanded);
18391 if (EllipsisLoc.isInvalid()) {
18392 if (DiagnoseUnexpandedParameterPack(Loc: TagLoc, T: TSI, UPPC: UPPC_FriendDeclaration))
18393 return true;
18394 } else if (Unexpanded.empty()) {
18395 Diag(Loc: EllipsisLoc, DiagID: diag::err_pack_expansion_without_parameter_packs)
18396 << TSI->getTypeLoc().getSourceRange();
18397 return true;
18398 } else {
18399 // CWG 2917: a pack expanded by a friend-type-specifier cannot have been
18400 // introduced by the template-declaration containing that specifier.
18401 if (!TempParamLists.empty()) {
18402 unsigned FriendDeclDepth = TempParamLists.front()->getDepth();
18403 for (UnexpandedParameterPack &U : Unexpanded) {
18404 if (std::optional<std::pair<unsigned, unsigned>> DI =
18405 getDepthAndIndex(UPP: U);
18406 DI && DI->first >= FriendDeclDepth) {
18407 auto *ND = dyn_cast<NamedDecl *>(Val&: U.first);
18408 if (!ND)
18409 ND = cast<const TemplateTypeParmType *>(Val&: U.first)->getDecl();
18410 Diag(Loc: U.second, DiagID: diag::friend_template_decl_malformed_pack_expansion)
18411 << ND->getDeclName()
18412 << SourceRange(TSI->getTypeLoc().getBeginLoc(), EllipsisLoc);
18413 return true;
18414 }
18415 }
18416 }
18417 }
18418
18419 FriendDecl *Friend;
18420 if (TempParamLists.empty())
18421 Friend = FriendDecl::Create(C&: Context, DC: CurContext, L: NameLoc, Friend: TSI, FriendL: FriendLoc,
18422 EllipsisLoc);
18423 else {
18424 if (CheckTemplateDeclScope(S, TemplateParams: TempParamLists.back()))
18425 return true;
18426
18427 TemplateName FriendTemplate;
18428 if (TemplateParams)
18429 FriendTemplate = Context.getDependentTemplateName(
18430 Name: {SS.getScopeRep(), Name, /*HasTemplateKeyword=*/false});
18431 Friend =
18432 FriendTemplateDecl::Create(Context, DC: CurContext, Loc: NameLoc, Friend: TSI, FriendLoc,
18433 FriendTPLists: TempParamLists, EllipsisLoc, Template: FriendTemplate);
18434 }
18435
18436 Friend->setAccess(AS_public);
18437 CurContext->addDecl(D: Friend);
18438
18439 return Friend;
18440}
18441
18442Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
18443 MultiTemplateParamsArg TempParams,
18444 SourceLocation EllipsisLoc) {
18445 SourceLocation Loc = DS.getBeginLoc();
18446 SourceLocation FriendLoc = DS.getFriendSpecLoc();
18447
18448 assert(DS.isFriendSpecified());
18449 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
18450
18451 // C++ [class.friend]p3:
18452 // A friend declaration that does not declare a function shall have one of
18453 // the following forms:
18454 // friend elaborated-type-specifier ;
18455 // friend simple-type-specifier ;
18456 // friend typename-specifier ;
18457 //
18458 // If the friend keyword isn't first, or if the declarations has any type
18459 // qualifiers, then the declaration doesn't have that form.
18460 if (getLangOpts().CPlusPlus11 && !DS.isFriendSpecifiedFirst())
18461 Diag(Loc: FriendLoc, DiagID: diag::err_friend_not_first_in_declaration);
18462 if (DS.getTypeQualifiers()) {
18463 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
18464 Diag(Loc: DS.getConstSpecLoc(), DiagID: diag::err_friend_decl_spec) << "const";
18465 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
18466 Diag(Loc: DS.getVolatileSpecLoc(), DiagID: diag::err_friend_decl_spec) << "volatile";
18467 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
18468 Diag(Loc: DS.getRestrictSpecLoc(), DiagID: diag::err_friend_decl_spec) << "restrict";
18469 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
18470 Diag(Loc: DS.getAtomicSpecLoc(), DiagID: diag::err_friend_decl_spec) << "_Atomic";
18471 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
18472 Diag(Loc: DS.getUnalignedSpecLoc(), DiagID: diag::err_friend_decl_spec) << "__unaligned";
18473 }
18474
18475 // Try to convert the decl specifier to a type. This works for
18476 // friend templates because ActOnTag never produces a ClassTemplateDecl
18477 // for a TagUseKind::Friend.
18478 Declarator TheDeclarator(DS, ParsedAttributesView::none(),
18479 DeclaratorContext::Member);
18480 TypeSourceInfo *TSI = GetTypeForDeclarator(D&: TheDeclarator);
18481 QualType T = TSI->getType();
18482 if (TheDeclarator.isInvalidType())
18483 return nullptr;
18484
18485 // If '...' is present, the type must contain an unexpanded parameter
18486 // pack, and vice versa.
18487 bool Invalid = false;
18488 if (EllipsisLoc.isInvalid() &&
18489 DiagnoseUnexpandedParameterPack(Loc, T: TSI, UPPC: UPPC_FriendDeclaration))
18490 return nullptr;
18491 if (EllipsisLoc.isValid() &&
18492 !TSI->getType()->containsUnexpandedParameterPack()) {
18493 Diag(Loc: EllipsisLoc, DiagID: diag::err_pack_expansion_without_parameter_packs)
18494 << TSI->getTypeLoc().getSourceRange();
18495 Invalid = true;
18496 }
18497
18498 if (!T->isElaboratedTypeSpecifier()) {
18499 if (TempParams.size()) {
18500 // C++23 [dcl.pre]p5:
18501 // In a simple-declaration, the optional init-declarator-list can be
18502 // omitted only when declaring a class or enumeration, that is, when
18503 // the decl-specifier-seq contains either a class-specifier, an
18504 // elaborated-type-specifier with a class-key, or an enum-specifier.
18505 //
18506 // The declaration of a template-declaration or explicit-specialization
18507 // is never a member-declaration, so this must be a simple-declaration
18508 // with no init-declarator-list. Therefore, this is ill-formed.
18509 Diag(Loc, DiagID: diag::err_tagless_friend_type_template) << DS.getSourceRange();
18510 return nullptr;
18511 } else if (const RecordDecl *RD = T->getAsRecordDecl()) {
18512 SmallString<16> InsertionText(" ");
18513 InsertionText += RD->getKindName();
18514
18515 Diag(Loc, DiagID: getLangOpts().CPlusPlus11
18516 ? diag::warn_cxx98_compat_unelaborated_friend_type
18517 : diag::ext_unelaborated_friend_type)
18518 << (unsigned)RD->getTagKind() << T
18519 << FixItHint::CreateInsertion(InsertionLoc: getLocForEndOfToken(Loc: FriendLoc),
18520 Code: InsertionText);
18521 } else {
18522 DiagCompat(Loc: FriendLoc, CompatDiagId: diag_compat::nonclass_type_friend)
18523 << T << DS.getSourceRange();
18524 }
18525 }
18526
18527 // C++98 [class.friend]p1: A friend of a class is a function
18528 // or class that is not a member of the class . . .
18529 // This is fixed in DR77, which just barely didn't make the C++03
18530 // deadline. It's also a very silly restriction that seriously
18531 // affects inner classes and which nobody else seems to implement;
18532 // thus we never diagnose it, not even in -pedantic.
18533 //
18534 // But note that we could warn about it: it's always useless to
18535 // friend one of your own members (it's not, however, worthless to
18536 // friend a member of an arbitrary specialization of your template).
18537
18538 Decl *D;
18539 if (!TempParams.empty()) {
18540 if (CheckTemplateDeclScope(S, TemplateParams: TempParams.back()))
18541 return nullptr;
18542
18543 // TODO: Support variadic friend template decls?
18544 D = FriendTemplateDecl::Create(Context, DC: CurContext, Loc, Friend: TSI, FriendLoc,
18545 FriendTPLists: TempParams, EllipsisLoc);
18546 } else
18547 D = FriendDecl::Create(C&: Context, DC: CurContext, L: TSI->getTypeLoc().getBeginLoc(),
18548 Friend: TSI, FriendL: FriendLoc, EllipsisLoc);
18549
18550 if (!D)
18551 return nullptr;
18552
18553 D->setAccess(AS_public);
18554 CurContext->addDecl(D);
18555
18556 if (Invalid)
18557 D->setInvalidDecl();
18558
18559 return D;
18560}
18561
18562NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
18563 MultiTemplateParamsArg TemplateParams) {
18564 const DeclSpec &DS = D.getDeclSpec();
18565
18566 assert(DS.isFriendSpecified());
18567 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
18568
18569 SourceLocation Loc = D.getIdentifierLoc();
18570 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
18571
18572 // C++ [class.friend]p1
18573 // A friend of a class is a function or class....
18574 // Note that this sees through typedefs, which is intended.
18575 // It *doesn't* see through dependent types, which is correct
18576 // according to [temp.arg.type]p3:
18577 // If a declaration acquires a function type through a
18578 // type dependent on a template-parameter and this causes
18579 // a declaration that does not use the syntactic form of a
18580 // function declarator to have a function type, the program
18581 // is ill-formed.
18582 if (!TInfo->getType()->isFunctionType()) {
18583 Diag(Loc, DiagID: diag::err_unexpected_friend);
18584
18585 // It might be worthwhile to try to recover by creating an
18586 // appropriate declaration.
18587 return nullptr;
18588 }
18589
18590 // C++ [namespace.memdef]p3
18591 // - If a friend declaration in a non-local class first declares a
18592 // class or function, the friend class or function is a member
18593 // of the innermost enclosing namespace.
18594 // - The name of the friend is not found by simple name lookup
18595 // until a matching declaration is provided in that namespace
18596 // scope (either before or after the class declaration granting
18597 // friendship).
18598 // - If a friend function is called, its name may be found by the
18599 // name lookup that considers functions from namespaces and
18600 // classes associated with the types of the function arguments.
18601 // - When looking for a prior declaration of a class or a function
18602 // declared as a friend, scopes outside the innermost enclosing
18603 // namespace scope are not considered.
18604
18605 CXXScopeSpec &SS = D.getCXXScopeSpec();
18606 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
18607 assert(NameInfo.getName());
18608
18609 if (SS.isValid() && DiagnosePackIndexingInFriendNNS(
18610 Loc: NameInfo.getLoc(), NNSLoc: SS.getWithLocInContext(Context)))
18611 return nullptr;
18612
18613 // Check for unexpanded parameter packs.
18614 if (DiagnoseUnexpandedParameterPack(Loc, T: TInfo, UPPC: UPPC_FriendDeclaration) ||
18615 DiagnoseUnexpandedParameterPack(NameInfo, UPPC: UPPC_FriendDeclaration) ||
18616 DiagnoseUnexpandedParameterPack(SS, UPPC: UPPC_FriendDeclaration))
18617 return nullptr;
18618
18619 bool isTemplateId = D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
18620
18621 if (D.isFunctionDefinition() && SS.isNotEmpty() && !isTemplateId) {
18622 auto Kind = SS.getScopeRep().getKind();
18623 bool IsNamespaceOrGlobal = Kind == NestedNameSpecifier::Kind::Global ||
18624 Kind == NestedNameSpecifier::Kind::Namespace;
18625 if (IsNamespaceOrGlobal) {
18626 Diag(Loc: SS.getRange().getBegin(), DiagID: diag::err_qualified_friend_def)
18627 << SS.getScopeRep();
18628 SS.clear();
18629 }
18630 }
18631
18632 // The context we found the declaration in, or in which we should
18633 // create the declaration.
18634 DeclContext *DC;
18635 Scope *DCScope = S;
18636 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
18637 RedeclarationKind::ForExternalRedeclaration);
18638
18639 // There are five cases here.
18640 // - There's no scope specifier and we're in a local class. Only look
18641 // for functions declared in the immediately-enclosing block scope.
18642 // We recover from invalid scope qualifiers as if they just weren't there.
18643 FunctionDecl *FunctionContainingLocalClass = nullptr;
18644 if ((SS.isInvalid() || !SS.isSet()) &&
18645 (FunctionContainingLocalClass =
18646 cast<CXXRecordDecl>(Val: CurContext)->isLocalClass())) {
18647 // C++11 [class.friend]p11:
18648 // If a friend declaration appears in a local class and the name
18649 // specified is an unqualified name, a prior declaration is
18650 // looked up without considering scopes that are outside the
18651 // innermost enclosing non-class scope. For a friend function
18652 // declaration, if there is no prior declaration, the program is
18653 // ill-formed.
18654
18655 // Find the innermost enclosing non-class scope. This is the block
18656 // scope containing the local class definition (or for a nested class,
18657 // the outer local class).
18658 DCScope = S->getFnParent();
18659
18660 // Look up the function name in the scope.
18661 Previous.clear(Kind: LookupLocalFriendName);
18662 LookupName(R&: Previous, S, /*AllowBuiltinCreation*/false);
18663
18664 if (!Previous.empty()) {
18665 // All possible previous declarations must have the same context:
18666 // either they were declared at block scope or they are members of
18667 // one of the enclosing local classes.
18668 DC = Previous.getRepresentativeDecl()->getDeclContext();
18669 } else {
18670 // This is ill-formed, but provide the context that we would have
18671 // declared the function in, if we were permitted to, for error recovery.
18672 DC = FunctionContainingLocalClass;
18673 }
18674 adjustContextForLocalExternDecl(DC);
18675
18676 // - There's no scope specifier, in which case we just go to the
18677 // appropriate scope and look for a function or function template
18678 // there as appropriate.
18679 } else if (SS.isInvalid() || !SS.isSet()) {
18680 // C++11 [namespace.memdef]p3:
18681 // If the name in a friend declaration is neither qualified nor
18682 // a template-id and the declaration is a function or an
18683 // elaborated-type-specifier, the lookup to determine whether
18684 // the entity has been previously declared shall not consider
18685 // any scopes outside the innermost enclosing namespace.
18686
18687 // Find the appropriate context according to the above.
18688 DC = CurContext;
18689
18690 // Skip class contexts. If someone can cite chapter and verse
18691 // for this behavior, that would be nice --- it's what GCC and
18692 // EDG do, and it seems like a reasonable intent, but the spec
18693 // really only says that checks for unqualified existing
18694 // declarations should stop at the nearest enclosing namespace,
18695 // not that they should only consider the nearest enclosing
18696 // namespace.
18697 while (DC->isRecord())
18698 DC = DC->getParent();
18699
18700 DeclContext *LookupDC = DC->getNonTransparentContext();
18701 while (true) {
18702 LookupQualifiedName(R&: Previous, LookupCtx: LookupDC);
18703
18704 if (!Previous.empty()) {
18705 DC = LookupDC;
18706 break;
18707 }
18708
18709 if (isTemplateId) {
18710 if (isa<TranslationUnitDecl>(Val: LookupDC)) break;
18711 } else {
18712 if (LookupDC->isFileContext()) break;
18713 }
18714 LookupDC = LookupDC->getParent();
18715 }
18716
18717 DCScope = getScopeForDeclContext(S, DC);
18718
18719 // - There's a non-dependent scope specifier, in which case we
18720 // compute it and do a previous lookup there for a function
18721 // or function template.
18722 } else if (!SS.getScopeRep().isDependent()) {
18723 DC = computeDeclContext(SS);
18724 if (!DC) return nullptr;
18725
18726 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
18727
18728 LookupQualifiedName(R&: Previous, LookupCtx: DC);
18729
18730 // C++ [class.friend]p1: A friend of a class is a function or
18731 // class that is not a member of the class . . .
18732 if (DC->Equals(DC: CurContext))
18733 Diag(Loc: DS.getFriendSpecLoc(),
18734 DiagID: getLangOpts().CPlusPlus11 ?
18735 diag::warn_cxx98_compat_friend_is_member :
18736 diag::err_friend_is_member);
18737
18738 // - There's a dependent scope specifier, in which case we use an
18739 // arbitrary context and wait for instantiation.
18740 } else {
18741 DC = CurContext;
18742 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
18743 }
18744
18745 if (!DC->isRecord()) {
18746 int DiagArg = -1;
18747 switch (D.getName().getKind()) {
18748 case UnqualifiedIdKind::IK_ConstructorTemplateId:
18749 case UnqualifiedIdKind::IK_ConstructorName:
18750 DiagArg = 0;
18751 break;
18752 case UnqualifiedIdKind::IK_DestructorName:
18753 DiagArg = 1;
18754 break;
18755 case UnqualifiedIdKind::IK_ConversionFunctionId:
18756 DiagArg = 2;
18757 break;
18758 case UnqualifiedIdKind::IK_DeductionGuideName:
18759 DiagArg = 3;
18760 break;
18761 case UnqualifiedIdKind::IK_Identifier:
18762 case UnqualifiedIdKind::IK_ImplicitSelfParam:
18763 case UnqualifiedIdKind::IK_LiteralOperatorId:
18764 case UnqualifiedIdKind::IK_OperatorFunctionId:
18765 case UnqualifiedIdKind::IK_TemplateId:
18766 break;
18767 }
18768 // This implies that it has to be an operator or function.
18769 if (DiagArg >= 0) {
18770 Diag(Loc, DiagID: diag::err_introducing_special_friend) << DiagArg;
18771 return nullptr;
18772 }
18773 } else {
18774 CXXRecordDecl *RC = dyn_cast<CXXRecordDecl>(Val: DC);
18775 if (RC->isLambda()) {
18776 Diag(Loc: NameInfo.getBeginLoc(), DiagID: diag::err_friend_lambda_decl);
18777 }
18778 }
18779
18780 // FIXME: This is an egregious hack to cope with cases where the scope stack
18781 // does not contain the declaration context, i.e., in an out-of-line
18782 // definition of a class.
18783 Scope FakeDCScope(S, Scope::DeclScope, Diags);
18784 if (!DCScope) {
18785 FakeDCScope.setEntity(DC);
18786 DCScope = &FakeDCScope;
18787 }
18788
18789 bool AddToScope = true;
18790 NamedDecl *ND = ActOnFunctionDeclarator(S: DCScope, D, DC, TInfo, Previous,
18791 TemplateParamLists: TemplateParams, AddToScope);
18792 if (!ND) return nullptr;
18793
18794 assert(ND->getLexicalDeclContext() == CurContext);
18795
18796 // If we performed typo correction, we might have added a scope specifier
18797 // and changed the decl context.
18798 DC = ND->getDeclContext();
18799
18800 // Add the function declaration to the appropriate lookup tables,
18801 // adjusting the redeclarations list as necessary. We don't
18802 // want to do this yet if the friending class is dependent.
18803 //
18804 // Also update the scope-based lookup if the target context's
18805 // lookup context is in lexical scope.
18806 if (!CurContext->isDependentContext()) {
18807 DC = DC->getRedeclContext();
18808 DC->makeDeclVisibleInContext(D: ND);
18809 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
18810 PushOnScopeChains(D: ND, S: EnclosingScope, /*AddToContext=*/ false);
18811 }
18812
18813 warnOnReservedIdentifier(D: ND);
18814
18815 if (ND->isInvalidDecl()) {
18816 FriendDecl *Friend = FriendDecl::Create(
18817 C&: Context, DC: CurContext, L: D.getIdentifierLoc(), Friend: ND, FriendL: DS.getFriendSpecLoc());
18818 Friend->setAccess(AS_public);
18819 if (!isa<FunctionTemplateDecl>(Val: ND))
18820 Friend->setInvalidDecl();
18821 CurContext->addDecl(D: Friend);
18822 return ND;
18823 }
18824
18825 FunctionDecl *FD = ND->getAsFunction();
18826 assert(FD && "Expected a function declaration!");
18827
18828 ArrayRef<TemplateParameterList *> TPLs = FD->getTemplateParameterLists();
18829 if (!TPLs.empty() && SS.isValid() && CheckTemplateDeclScope(S, TemplateParams: TPLs.back()))
18830 return nullptr;
18831
18832 FriendDecl *Friend;
18833 if (!TPLs.empty() && SS.isValid())
18834 Friend =
18835 FriendTemplateDecl::Create(Context, DC: CurContext, Loc: D.getIdentifierLoc(),
18836 Friend: ND, FriendLoc: DS.getFriendSpecLoc(), FriendTPLists: TPLs);
18837 else
18838 Friend = FriendDecl::Create(C&: Context, DC: CurContext, L: D.getIdentifierLoc(), Friend: ND,
18839 FriendL: DS.getFriendSpecLoc());
18840
18841 Friend->setAccess(AS_public);
18842 CurContext->addDecl(D: Friend);
18843
18844 if (DC->isRecord())
18845 CheckFriendAccess(D: ND);
18846
18847 if (!TemplateParams.empty() && SS.isValid() &&
18848 CheckDependentFriend(Loc: NameInfo.getLoc(), NNSLoc: SS.getWithLocInContext(Context),
18849 TPLs: FD->getTemplateParameterLists(),
18850 /*IsInstantiation=*/false))
18851 return ND;
18852
18853 // C++ [class.friend]p6:
18854 // A function may be defined in a friend declaration of a class if and
18855 // only if the class is a non-local class, and the function name is
18856 // unqualified.
18857 if (D.isFunctionDefinition()) {
18858 // Qualified friend function definition.
18859 if (SS.isNotEmpty()) {
18860 SemaDiagnosticBuilder DB =
18861 Diag(Loc: SS.getRange().getBegin(), DiagID: diag::err_qualified_friend_def);
18862
18863 DB << SS.getScopeRep();
18864
18865 // Friend function defined in a local class.
18866 } else if (FunctionContainingLocalClass) {
18867 Diag(Loc: NameInfo.getBeginLoc(), DiagID: diag::err_friend_def_in_local_class);
18868
18869 // Per [basic.pre]p4, a template-id is not a name. Therefore, if we have
18870 // a template-id, the function name is not unqualified because these is
18871 // no name. While the wording requires some reading in-between the
18872 // lines, GCC, MSVC, and EDG all consider a friend function
18873 // specialization definitions to be de facto explicit specialization
18874 // and diagnose them as such.
18875 } else if (isTemplateId) {
18876 Diag(Loc: NameInfo.getBeginLoc(), DiagID: diag::err_friend_specialization_def);
18877 }
18878 }
18879
18880 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
18881 // default argument expression, that declaration shall be a definition
18882 // and shall be the only declaration of the function or function
18883 // template in the translation unit.
18884 if (functionDeclHasDefaultArgument(FD)) {
18885 // We can't look at FD->getPreviousDecl() because it may not have been set
18886 // if we're in a dependent context. If the function is known to be a
18887 // redeclaration, we will have narrowed Previous down to the right decl.
18888 if (D.isRedeclaration()) {
18889 Diag(Loc: FD->getLocation(), DiagID: diag::err_friend_decl_with_def_arg_redeclared);
18890 Diag(Loc: Previous.getRepresentativeDecl()->getLocation(),
18891 DiagID: diag::note_previous_declaration);
18892 } else if (!D.isFunctionDefinition())
18893 Diag(Loc: FD->getLocation(), DiagID: diag::err_friend_decl_with_def_arg_must_be_def);
18894 }
18895
18896 return ND;
18897}
18898
18899void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc,
18900 StringLiteral *Message) {
18901 AdjustDeclIfTemplate(Decl&: Dcl);
18902
18903 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Val: Dcl);
18904 if (!Fn) {
18905 Diag(Loc: DelLoc, DiagID: diag::err_deleted_non_function);
18906 return;
18907 }
18908
18909 // Deleted function does not have a body.
18910 Fn->setWillHaveBody(false);
18911
18912 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
18913 // Don't consider the implicit declaration we generate for explicit
18914 // specializations. FIXME: Do not generate these implicit declarations.
18915 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
18916 Prev->getPreviousDecl()) &&
18917 !Prev->isDefined()) {
18918 Diag(Loc: DelLoc, DiagID: diag::err_deleted_decl_not_first);
18919 Diag(Loc: Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
18920 DiagID: Prev->isImplicit() ? diag::note_previous_implicit_declaration
18921 : diag::note_previous_declaration);
18922 // We can't recover from this; the declaration might have already
18923 // been used.
18924 Fn->setInvalidDecl();
18925 return;
18926 }
18927
18928 // To maintain the invariant that functions are only deleted on their first
18929 // declaration, mark the implicitly-instantiated declaration of the
18930 // explicitly-specialized function as deleted instead of marking the
18931 // instantiated redeclaration.
18932 Fn = Fn->getCanonicalDecl();
18933 }
18934
18935 // dllimport/dllexport cannot be deleted.
18936 if (const InheritableAttr *DLLAttr = getDLLAttr(D: Fn)) {
18937 Diag(Loc: Fn->getLocation(), DiagID: diag::err_attribute_dll_deleted) << DLLAttr;
18938 Fn->setInvalidDecl();
18939 }
18940
18941 // C++11 [basic.start.main]p3:
18942 // A program that defines main as deleted [...] is ill-formed.
18943 if (Fn->isMain())
18944 Diag(Loc: DelLoc, DiagID: diag::err_deleted_main);
18945
18946 // C++11 [dcl.fct.def.delete]p4:
18947 // A deleted function is implicitly inline.
18948 Fn->setImplicitlyInline();
18949 Fn->setDeletedAsWritten(D: true, Message);
18950}
18951
18952void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
18953 if (!Dcl || Dcl->isInvalidDecl())
18954 return;
18955
18956 auto *FD = dyn_cast<FunctionDecl>(Val: Dcl);
18957 if (!FD) {
18958 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Val: Dcl)) {
18959 if (FTD->getTemplatedDecl()->getDefaultedFunctionKind().isComparison()) {
18960 Diag(Loc: DefaultLoc, DiagID: diag::err_defaulted_comparison_template);
18961 return;
18962 }
18963 }
18964
18965 Diag(Loc: DefaultLoc, DiagID: diag::err_default_special_members)
18966 << getLangOpts().CPlusPlus20;
18967 return;
18968 }
18969
18970 // Reject if this can't possibly be a defaultable function.
18971 FunctionDecl::DefaultedFunctionKind DefKind = FD->getDefaultedFunctionKind();
18972 if (!DefKind &&
18973 // A dependent function that doesn't locally look defaultable can
18974 // still instantiate to a defaultable function if it's a constructor
18975 // or assignment operator.
18976 (!FD->isDependentContext() ||
18977 (!isa<CXXConstructorDecl>(Val: FD) &&
18978 FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) {
18979 Diag(Loc: DefaultLoc, DiagID: diag::err_default_special_members)
18980 << getLangOpts().CPlusPlus20;
18981 return;
18982 }
18983
18984 // Issue compatibility warning. We already warned if the operator is
18985 // 'operator<=>' when parsing the '<=>' token.
18986 if (DefKind.isComparison() &&
18987 DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) {
18988 DiagCompat(Loc: DefaultLoc, CompatDiagId: diag_compat::defaulted_comparison);
18989 }
18990
18991 FD->setDefaulted();
18992 FD->setExplicitlyDefaulted();
18993 FD->setDefaultLoc(DefaultLoc);
18994
18995 // Defer checking functions that are defaulted in a dependent context.
18996 if (FD->isDependentContext())
18997 return;
18998
18999 // Unset that we will have a body for this function. We might not,
19000 // if it turns out to be trivial, and we don't need this marking now
19001 // that we've marked it as defaulted.
19002 FD->setWillHaveBody(false);
19003
19004 if (DefKind.isComparison()) {
19005 // If this comparison's defaulting occurs within the definition of its
19006 // lexical class context, we have to do the checking when complete.
19007 if (auto const *RD = dyn_cast<CXXRecordDecl>(Val: FD->getLexicalDeclContext()))
19008 if (!RD->isCompleteDefinition())
19009 return;
19010 }
19011
19012 // If this member fn was defaulted on its first declaration, we will have
19013 // already performed the checking in CheckCompletedCXXClass. Such a
19014 // declaration doesn't trigger an implicit definition.
19015 if (isa<CXXMethodDecl>(Val: FD)) {
19016 const FunctionDecl *Primary = FD;
19017 if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
19018 // Ask the template instantiation pattern that actually had the
19019 // '= default' on it.
19020 Primary = Pattern;
19021 if (Primary->getCanonicalDecl()->isDefaulted())
19022 return;
19023 }
19024
19025 // Only allocate DefaultedOrDeletedFunctionInfo if we actually have
19026 // non-default FP features to stash. This avoids memory overhead for
19027 // the vast majority of defaulted functions.
19028 if (!FD->getDefaultedOrDeletedInfo() &&
19029 CurFPFeatureOverrides().requiresTrailingStorage()) {
19030 FD->setDefaultedOrDeletedInfo(
19031 FunctionDecl::DefaultedOrDeletedFunctionInfo::Create(
19032 Context, /*Lookups=*/{}, FPFeatures: CurFPFeatureOverrides()));
19033 }
19034
19035 if (DefKind.isComparison()) {
19036 if (CheckExplicitlyDefaultedComparison(S: nullptr, FD, DCK: DefKind.asComparison()))
19037 FD->setInvalidDecl();
19038 else
19039 DefineDefaultedComparison(UseLoc: DefaultLoc, FD, DCK: DefKind.asComparison());
19040 } else {
19041 auto *MD = cast<CXXMethodDecl>(Val: FD);
19042
19043 if (CheckExplicitlyDefaultedSpecialMember(MD, CSM: DefKind.asSpecialMember(),
19044 DefaultLoc))
19045 MD->setInvalidDecl();
19046 else
19047 DefineDefaultedFunction(S&: *this, FD: MD, DefaultLoc);
19048 }
19049}
19050
19051static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
19052 for (Stmt *SubStmt : S->children()) {
19053 if (!SubStmt)
19054 continue;
19055 if (isa<ReturnStmt>(Val: SubStmt))
19056 Self.Diag(Loc: SubStmt->getBeginLoc(),
19057 DiagID: diag::err_return_in_constructor_handler);
19058 if (!isa<Expr>(Val: SubStmt))
19059 SearchForReturnInStmt(Self, S: SubStmt);
19060 }
19061}
19062
19063void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
19064 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
19065 CXXCatchStmt *Handler = TryBlock->getHandler(i: I);
19066 SearchForReturnInStmt(Self&: *this, S: Handler);
19067 }
19068}
19069
19070void Sema::SetFunctionBodyKind(Decl *D, SourceLocation Loc, FnBodyKind BodyKind,
19071 StringLiteral *DeletedMessage) {
19072 switch (BodyKind) {
19073 case FnBodyKind::Delete:
19074 SetDeclDeleted(Dcl: D, DelLoc: Loc, Message: DeletedMessage);
19075 break;
19076 case FnBodyKind::Default:
19077 SetDeclDefaulted(Dcl: D, DefaultLoc: Loc);
19078 break;
19079 case FnBodyKind::Other:
19080 llvm_unreachable(
19081 "Parsed function body should be '= delete;' or '= default;'");
19082 }
19083}
19084
19085bool Sema::CheckOverridingFunctionAttributes(CXXMethodDecl *New,
19086 const CXXMethodDecl *Old) {
19087 const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
19088 const auto *OldFT = Old->getType()->castAs<FunctionProtoType>();
19089
19090 if (OldFT->hasExtParameterInfos()) {
19091 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
19092 // A parameter of the overriding method should be annotated with noescape
19093 // if the corresponding parameter of the overridden method is annotated.
19094 if (OldFT->getExtParameterInfo(I).isNoEscape() &&
19095 !NewFT->getExtParameterInfo(I).isNoEscape()) {
19096 Diag(Loc: New->getParamDecl(i: I)->getLocation(),
19097 DiagID: diag::warn_overriding_method_missing_noescape);
19098 Diag(Loc: Old->getParamDecl(i: I)->getLocation(),
19099 DiagID: diag::note_overridden_marked_noescape);
19100 }
19101 }
19102
19103 // SME attributes must match when overriding a function declaration.
19104 if (IsInvalidSMECallConversion(FromType: Old->getType(), ToType: New->getType())) {
19105 Diag(Loc: New->getLocation(), DiagID: diag::err_conflicting_overriding_attributes)
19106 << New << New->getType() << Old->getType();
19107 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function);
19108 return true;
19109 }
19110
19111 // Virtual overrides must have the same code_seg.
19112 const auto *OldCSA = Old->getAttr<CodeSegAttr>();
19113 const auto *NewCSA = New->getAttr<CodeSegAttr>();
19114 if ((NewCSA || OldCSA) &&
19115 (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
19116 Diag(Loc: New->getLocation(), DiagID: diag::err_mismatched_code_seg_override);
19117 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
19118 return true;
19119 }
19120
19121 // Virtual overrides: check for matching effects.
19122 if (Context.hasAnyFunctionEffects()) {
19123 const auto OldFX = Old->getFunctionEffects();
19124 const auto NewFXOrig = New->getFunctionEffects();
19125
19126 if (OldFX != NewFXOrig) {
19127 FunctionEffectSet NewFX(NewFXOrig);
19128 const auto Diffs = FunctionEffectDiffVector(OldFX, NewFX);
19129 FunctionEffectSet::Conflicts Errs;
19130 for (const auto &Diff : Diffs) {
19131 switch (Diff.shouldDiagnoseMethodOverride(OldMethod: *Old, OldFX, NewMethod: *New, NewFX)) {
19132 case FunctionEffectDiff::OverrideResult::NoAction:
19133 break;
19134 case FunctionEffectDiff::OverrideResult::Warn:
19135 Diag(Loc: New->getLocation(), DiagID: diag::warn_conflicting_func_effect_override)
19136 << Diff.effectName();
19137 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function)
19138 << Old->getReturnTypeSourceRange();
19139 break;
19140 case FunctionEffectDiff::OverrideResult::Merge: {
19141 NewFX.insert(NewEC: Diff.Old.value(), Errs);
19142 const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
19143 FunctionProtoType::ExtProtoInfo EPI = NewFT->getExtProtoInfo();
19144 EPI.FunctionEffects = FunctionEffectsRef(NewFX);
19145 QualType ModQT = Context.getFunctionType(ResultTy: NewFT->getReturnType(),
19146 Args: NewFT->getParamTypes(), EPI);
19147 New->setType(ModQT);
19148 if (Errs.empty()) {
19149 // A warning here is somewhat pedantic. Skip this if there was
19150 // already a merge conflict, which is more serious.
19151 Diag(Loc: New->getLocation(), DiagID: diag::warn_mismatched_func_effect_override)
19152 << Diff.effectName();
19153 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function)
19154 << Old->getReturnTypeSourceRange();
19155 }
19156 break;
19157 }
19158 }
19159 }
19160 if (!Errs.empty())
19161 diagnoseFunctionEffectMergeConflicts(Errs, NewLoc: New->getLocation(),
19162 OldLoc: Old->getLocation());
19163 }
19164 }
19165
19166 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
19167
19168 // If the calling conventions match, everything is fine
19169 if (NewCC == OldCC)
19170 return false;
19171
19172 // If the calling conventions mismatch because the new function is static,
19173 // suppress the calling convention mismatch error; the error about static
19174 // function override (err_static_overrides_virtual from
19175 // Sema::CheckFunctionDeclaration) is more clear.
19176 if (New->getStorageClass() == SC_Static)
19177 return false;
19178
19179 Diag(Loc: New->getLocation(),
19180 DiagID: diag::err_conflicting_overriding_cc_attributes)
19181 << New->getDeclName() << New->getType() << Old->getType();
19182 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function);
19183 return true;
19184}
19185
19186bool Sema::CheckExplicitObjectOverride(CXXMethodDecl *New,
19187 const CXXMethodDecl *Old) {
19188 // CWG2553
19189 // A virtual function shall not be an explicit object member function.
19190 if (!New->isExplicitObjectMemberFunction())
19191 return true;
19192 Diag(Loc: New->getParamDecl(i: 0)->getBeginLoc(),
19193 DiagID: diag::err_explicit_object_parameter_nonmember)
19194 << New->getSourceRange() << /*virtual*/ 1 << /*IsLambda*/ false;
19195 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function);
19196 New->setInvalidDecl();
19197 return false;
19198}
19199
19200bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
19201 const CXXMethodDecl *Old) {
19202 QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType();
19203 QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType();
19204
19205 if (Context.hasSameType(T1: NewTy, T2: OldTy) ||
19206 NewTy->isDependentType() || OldTy->isDependentType())
19207 return false;
19208
19209 // Check if the return types are covariant
19210 QualType NewClassTy, OldClassTy;
19211
19212 /// Both types must be pointers or references to classes.
19213 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
19214 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
19215 NewClassTy = NewPT->getPointeeType();
19216 OldClassTy = OldPT->getPointeeType();
19217 }
19218 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
19219 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
19220 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
19221 NewClassTy = NewRT->getPointeeType();
19222 OldClassTy = OldRT->getPointeeType();
19223 }
19224 }
19225 }
19226
19227 // The return types aren't either both pointers or references to a class type.
19228 if (NewClassTy.isNull() || !NewClassTy->isStructureOrClassType()) {
19229 Diag(Loc: New->getLocation(),
19230 DiagID: diag::err_different_return_type_for_overriding_virtual_function)
19231 << New->getDeclName() << NewTy << OldTy
19232 << New->getReturnTypeSourceRange();
19233 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function)
19234 << Old->getReturnTypeSourceRange();
19235
19236 return true;
19237 }
19238
19239 if (!Context.hasSameUnqualifiedType(T1: NewClassTy, T2: OldClassTy)) {
19240 // C++14 [class.virtual]p8:
19241 // If the class type in the covariant return type of D::f differs from
19242 // that of B::f, the class type in the return type of D::f shall be
19243 // complete at the point of declaration of D::f or shall be the class
19244 // type D.
19245 if (const auto *RD = NewClassTy->getAsCXXRecordDecl()) {
19246 if (!RD->isBeingDefined() &&
19247 RequireCompleteType(Loc: New->getLocation(), T: NewClassTy,
19248 DiagID: diag::err_covariant_return_incomplete,
19249 Args: New->getDeclName()))
19250 return true;
19251 }
19252
19253 // Check if the new class derives from the old class.
19254 if (!IsDerivedFrom(Loc: New->getLocation(), Derived: NewClassTy, Base: OldClassTy)) {
19255 Diag(Loc: New->getLocation(), DiagID: diag::err_covariant_return_not_derived)
19256 << New->getDeclName() << NewTy << OldTy
19257 << New->getReturnTypeSourceRange();
19258 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function)
19259 << Old->getReturnTypeSourceRange();
19260 return true;
19261 }
19262
19263 // Check if we the conversion from derived to base is valid.
19264 if (CheckDerivedToBaseConversion(
19265 Derived: NewClassTy, Base: OldClassTy,
19266 InaccessibleBaseID: diag::err_covariant_return_inaccessible_base,
19267 AmbiguousBaseConvID: diag::err_covariant_return_ambiguous_derived_to_base_conv,
19268 Loc: New->getLocation(), Range: New->getReturnTypeSourceRange(),
19269 Name: New->getDeclName(), BasePath: nullptr)) {
19270 // FIXME: this note won't trigger for delayed access control
19271 // diagnostics, and it's impossible to get an undelayed error
19272 // here from access control during the original parse because
19273 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
19274 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function)
19275 << Old->getReturnTypeSourceRange();
19276 return true;
19277 }
19278 }
19279
19280 // The qualifiers of the return types must be the same.
19281 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
19282 Diag(Loc: New->getLocation(),
19283 DiagID: diag::err_covariant_return_type_different_qualifications)
19284 << New->getDeclName() << NewTy << OldTy
19285 << New->getReturnTypeSourceRange();
19286 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function)
19287 << Old->getReturnTypeSourceRange();
19288 return true;
19289 }
19290
19291
19292 // The new class type must have the same or less qualifiers as the old type.
19293 if (!OldClassTy.isAtLeastAsQualifiedAs(other: NewClassTy, Ctx: getASTContext())) {
19294 Diag(Loc: New->getLocation(),
19295 DiagID: diag::err_covariant_return_type_class_type_not_same_or_less_qualified)
19296 << New->getDeclName() << NewTy << OldTy
19297 << New->getReturnTypeSourceRange();
19298 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function)
19299 << Old->getReturnTypeSourceRange();
19300 return true;
19301 }
19302
19303 return false;
19304}
19305
19306bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
19307 SourceLocation EndLoc = InitRange.getEnd();
19308 if (EndLoc.isValid())
19309 Method->setRangeEnd(EndLoc);
19310
19311 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
19312 Method->setIsPureVirtual();
19313 return false;
19314 }
19315
19316 if (!Method->isInvalidDecl())
19317 Diag(Loc: Method->getLocation(), DiagID: diag::err_non_virtual_pure)
19318 << Method->getDeclName() << InitRange;
19319 return true;
19320}
19321
19322void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
19323 if (D->getFriendObjectKind())
19324 Diag(Loc: D->getLocation(), DiagID: diag::err_pure_friend);
19325 else if (auto *M = dyn_cast<CXXMethodDecl>(Val: D))
19326 CheckPureMethod(Method: M, InitRange: ZeroLoc);
19327 else
19328 Diag(Loc: D->getLocation(), DiagID: diag::err_illegal_initializer);
19329}
19330
19331/// Invoked when we are about to parse an initializer for the declaration
19332/// 'Dcl'.
19333///
19334/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
19335/// static data member of class X, names should be looked up in the scope of
19336/// class X. If the declaration had a scope specifier, a scope will have
19337/// been created and passed in for this purpose. Otherwise, S will be null.
19338void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
19339 assert(D && !D->isInvalidDecl());
19340
19341 // We will always have a nested name specifier here, but this declaration
19342 // might not be out of line if the specifier names the current namespace:
19343 // extern int n;
19344 // int ::n = 0;
19345 if (S && D->isOutOfLine())
19346 EnterDeclaratorContext(S, DC: D->getDeclContext());
19347
19348 PushExpressionEvaluationContext(
19349 NewContext: ExpressionEvaluationContext::PotentiallyEvaluated, LambdaContextDecl: D,
19350 Type: ExpressionEvaluationContextRecord::EK_VariableInit);
19351}
19352
19353void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
19354 assert(D);
19355
19356 if (S && D->isOutOfLine())
19357 ExitDeclaratorContext(S);
19358
19359 PopExpressionEvaluationContext();
19360}
19361
19362DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
19363 // C++ 6.4p2:
19364 // The declarator shall not specify a function or an array.
19365 // The type-specifier-seq shall not contain typedef and shall not declare a
19366 // new class or enumeration.
19367 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
19368 "Parser allowed 'typedef' as storage class of condition decl.");
19369
19370 Decl *Dcl = ActOnDeclarator(S, D);
19371 if (!Dcl)
19372 return true;
19373
19374 if (isa<FunctionDecl>(Val: Dcl)) { // The declarator shall not specify a function.
19375 Diag(Loc: Dcl->getLocation(), DiagID: diag::err_invalid_use_of_function_type)
19376 << D.getSourceRange();
19377 return true;
19378 }
19379
19380 if (auto *VD = dyn_cast<VarDecl>(Val: Dcl))
19381 VD->setCXXCondDecl();
19382
19383 return Dcl;
19384}
19385
19386void Sema::LoadExternalVTableUses() {
19387 if (!ExternalSource)
19388 return;
19389
19390 SmallVector<ExternalVTableUse, 4> VTables;
19391 ExternalSource->ReadUsedVTables(VTables);
19392 SmallVector<VTableUse, 4> NewUses;
19393 for (const ExternalVTableUse &VTable : VTables) {
19394 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos =
19395 VTablesUsed.find(Val: VTable.Record);
19396 // Even if a definition wasn't required before, it may be required now.
19397 if (Pos != VTablesUsed.end()) {
19398 if (!Pos->second && VTable.DefinitionRequired)
19399 Pos->second = true;
19400 continue;
19401 }
19402
19403 VTablesUsed[VTable.Record] = VTable.DefinitionRequired;
19404 NewUses.push_back(Elt: VTableUse(VTable.Record, VTable.Location));
19405 }
19406
19407 VTableUses.insert(I: VTableUses.begin(), From: NewUses.begin(), To: NewUses.end());
19408}
19409
19410void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
19411 bool DefinitionRequired) {
19412 // Ignore any vtable uses in unevaluated operands or for classes that do
19413 // not have a vtable.
19414 if (!Class->isDynamicClass() || Class->isDependentContext() ||
19415 CurContext->isDependentContext() || isUnevaluatedContext())
19416 return;
19417 // Do not mark as used if compiling for the device outside of the target
19418 // region.
19419 if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice &&
19420 !OpenMP().isInOpenMPDeclareTargetContext() &&
19421 !OpenMP().isInOpenMPTargetExecutionDirective()) {
19422 if (!DefinitionRequired)
19423 MarkVirtualMembersReferenced(Loc, RD: Class);
19424 return;
19425 }
19426
19427 // Try to insert this class into the map.
19428 LoadExternalVTableUses();
19429 Class = Class->getCanonicalDecl();
19430 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
19431 Pos = VTablesUsed.insert(KV: std::make_pair(x&: Class, y&: DefinitionRequired));
19432 if (!Pos.second) {
19433 // If we already had an entry, check to see if we are promoting this vtable
19434 // to require a definition. If so, we need to reappend to the VTableUses
19435 // list, since we may have already processed the first entry.
19436 if (DefinitionRequired && !Pos.first->second) {
19437 Pos.first->second = true;
19438 } else {
19439 // Otherwise, we can early exit.
19440 return;
19441 }
19442 } else {
19443 // The Microsoft ABI requires that we perform the destructor body
19444 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
19445 // the deleting destructor is emitted with the vtable, not with the
19446 // destructor definition as in the Itanium ABI.
19447 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
19448 CXXDestructorDecl *DD = Class->getDestructor();
19449 if (DD && DD->isVirtual() && !DD->isDeleted()) {
19450 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
19451 // If this is an out-of-line declaration, marking it referenced will
19452 // not do anything. Manually call CheckDestructor to look up operator
19453 // delete().
19454 ContextRAII SavedContext(*this, DD);
19455 CheckDestructor(Destructor: DD);
19456 if (!DD->getOperatorDelete())
19457 DD->setInvalidDecl();
19458 } else {
19459 MarkFunctionReferenced(Loc, Func: Class->getDestructor());
19460 }
19461 }
19462 }
19463 }
19464
19465 // Local classes need to have their virtual members marked
19466 // immediately. For all other classes, we mark their virtual members
19467 // at the end of the translation unit.
19468 if (Class->isLocalClass())
19469 MarkVirtualMembersReferenced(Loc, RD: Class->getDefinition());
19470 else
19471 VTableUses.push_back(Elt: std::make_pair(x&: Class, y&: Loc));
19472}
19473
19474bool Sema::DefineUsedVTables() {
19475 LoadExternalVTableUses();
19476 if (VTableUses.empty())
19477 return false;
19478
19479 // Note: The VTableUses vector could grow as a result of marking
19480 // the members of a class as "used", so we check the size each
19481 // time through the loop and prefer indices (which are stable) to
19482 // iterators (which are not).
19483 bool DefinedAnything = false;
19484 for (unsigned I = 0; I != VTableUses.size(); ++I) {
19485 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
19486 if (!Class)
19487 continue;
19488 TemplateSpecializationKind ClassTSK =
19489 Class->getTemplateSpecializationKind();
19490
19491 SourceLocation Loc = VTableUses[I].second;
19492
19493 bool DefineVTable = true;
19494
19495 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(RD: Class);
19496 // V-tables for non-template classes with an owning module are always
19497 // uniquely emitted in that module.
19498 if (Class->isInCurrentModuleUnit()) {
19499 DefineVTable = true;
19500 } else if (KeyFunction && !KeyFunction->hasBody()) {
19501 // If this class has a key function, but that key function is
19502 // defined in another translation unit, we don't need to emit the
19503 // vtable even though we're using it.
19504 // The key function is in another translation unit.
19505 DefineVTable = false;
19506 TemplateSpecializationKind TSK =
19507 KeyFunction->getTemplateSpecializationKind();
19508 assert(TSK != TSK_ExplicitInstantiationDefinition &&
19509 TSK != TSK_ImplicitInstantiation &&
19510 "Instantiations don't have key functions");
19511 (void)TSK;
19512 } else if (!KeyFunction) {
19513 // If we have a class with no key function that is the subject
19514 // of an explicit instantiation declaration, suppress the
19515 // vtable; it will live with the explicit instantiation
19516 // definition.
19517 bool IsExplicitInstantiationDeclaration =
19518 ClassTSK == TSK_ExplicitInstantiationDeclaration;
19519 for (auto *R : Class->redecls()) {
19520 TemplateSpecializationKind TSK
19521 = cast<CXXRecordDecl>(Val: R)->getTemplateSpecializationKind();
19522 if (TSK == TSK_ExplicitInstantiationDeclaration)
19523 IsExplicitInstantiationDeclaration = true;
19524 else if (TSK == TSK_ExplicitInstantiationDefinition) {
19525 IsExplicitInstantiationDeclaration = false;
19526 break;
19527 }
19528 }
19529
19530 if (IsExplicitInstantiationDeclaration) {
19531 const bool HasExcludeFromExplicitInstantiation =
19532 llvm::any_of(Range: Class->methods(), P: [](CXXMethodDecl *method) {
19533 // If the class has a member function declared with
19534 // `__attribute__((exclude_from_explicit_instantiation))`, the
19535 // explicit instantiation declaration should not suppress emitting
19536 // the vtable, since the corresponding explicit instantiation
19537 // definition might not emit the vtable if a triggering method is
19538 // excluded.
19539 return method->hasAttr<ExcludeFromExplicitInstantiationAttr>();
19540 });
19541 if (!HasExcludeFromExplicitInstantiation)
19542 DefineVTable = false;
19543 }
19544 }
19545
19546 // The exception specifications for all virtual members may be needed even
19547 // if we are not providing an authoritative form of the vtable in this TU.
19548 // We may choose to emit it available_externally anyway.
19549 if (!DefineVTable) {
19550 MarkVirtualMemberExceptionSpecsNeeded(Loc, RD: Class);
19551 continue;
19552 }
19553
19554 // Mark all of the virtual members of this class as referenced, so
19555 // that we can build a vtable. Then, tell the AST consumer that a
19556 // vtable for this class is required.
19557 DefinedAnything = true;
19558 MarkVirtualMembersReferenced(Loc, RD: Class);
19559 CXXRecordDecl *Canonical = Class->getCanonicalDecl();
19560 // The vtable is assumed to be emitted in an external source only for
19561 // classes attached to a named module, which is guaranteed to have an object
19562 // file. This isn't true for -fmodules-debuginfo, which still has
19563 // shouldEmitInExternalSource as true so that debug info gets supressed.
19564 if (VTablesUsed[Canonical] &&
19565 !(Class->isInNamedModule() && Class->shouldEmitInExternalSource()))
19566 Consumer.HandleVTable(RD: Class);
19567
19568 // Warn if we're emitting a weak vtable. The vtable will be weak if there is
19569 // no key function or the key function is inlined. Don't warn in C++ ABIs
19570 // that lack key functions, since the user won't be able to make one.
19571 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
19572 Class->isExternallyVisible() &&
19573 !(Class->getOwningModule() &&
19574 Class->getOwningModule()->isInterfaceOrPartition()) &&
19575 ClassTSK != TSK_ImplicitInstantiation &&
19576 ClassTSK != TSK_ExplicitInstantiationDeclaration &&
19577 ClassTSK != TSK_ExplicitInstantiationDefinition) {
19578 const FunctionDecl *KeyFunctionDef = nullptr;
19579 if (!KeyFunction || (KeyFunction->hasBody(Definition&: KeyFunctionDef) &&
19580 KeyFunctionDef->isInlined()))
19581 Diag(Loc: Class->getLocation(), DiagID: diag::warn_weak_vtable) << Class;
19582 }
19583 }
19584 VTableUses.clear();
19585
19586 return DefinedAnything;
19587}
19588
19589void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
19590 const CXXRecordDecl *RD) {
19591 for (const auto *I : RD->methods())
19592 if (I->isVirtual() && !I->isPureVirtual())
19593 ResolveExceptionSpec(Loc, FPT: I->getType()->castAs<FunctionProtoType>());
19594}
19595
19596void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
19597 const CXXRecordDecl *RD,
19598 bool ConstexprOnly) {
19599 // Mark all functions which will appear in RD's vtable as used.
19600 CXXFinalOverriderMap FinalOverriders;
19601 RD->getFinalOverriders(FinaOverriders&: FinalOverriders);
19602 for (const auto &FinalOverrider : FinalOverriders) {
19603 for (const auto &OverridingMethod : FinalOverrider.second) {
19604 assert(OverridingMethod.second.size() > 0 && "no final overrider");
19605 CXXMethodDecl *Overrider = OverridingMethod.second.front().Method;
19606
19607 // C++ [basic.def.odr]p2:
19608 // [...] A virtual member function is used if it is not pure. [...]
19609 if (!Overrider->isPureVirtual() &&
19610 (!ConstexprOnly || Overrider->isConstexpr()))
19611 MarkFunctionReferenced(Loc, Func: Overrider);
19612 }
19613 }
19614
19615 // Only classes that have virtual bases need a VTT.
19616 if (RD->getNumVBases() == 0)
19617 return;
19618
19619 for (const auto &I : RD->bases()) {
19620 const auto *Base = I.getType()->castAsCXXRecordDecl();
19621 if (Base->getNumVBases() == 0)
19622 continue;
19623 MarkVirtualMembersReferenced(Loc, RD: Base);
19624 }
19625}
19626
19627static
19628void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
19629 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
19630 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
19631 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
19632 Sema &S) {
19633 if (Ctor->isInvalidDecl())
19634 return;
19635
19636 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
19637
19638 // Target may not be determinable yet, for instance if this is a dependent
19639 // call in an uninstantiated template.
19640 if (Target) {
19641 const FunctionDecl *FNTarget = nullptr;
19642 (void)Target->hasBody(Definition&: FNTarget);
19643 Target = const_cast<CXXConstructorDecl*>(
19644 cast_or_null<CXXConstructorDecl>(Val: FNTarget));
19645 }
19646
19647 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
19648 // Avoid dereferencing a null pointer here.
19649 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
19650
19651 if (!Current.insert(Ptr: Canonical).second)
19652 return;
19653
19654 // We know that beyond here, we aren't chaining into a cycle.
19655 if (!Target || !Target->isDelegatingConstructor() ||
19656 Target->isInvalidDecl() || Valid.count(Ptr: TCanonical)) {
19657 Valid.insert_range(R&: Current);
19658 Current.clear();
19659 // We've hit a cycle.
19660 } else if (TCanonical == Canonical || Invalid.count(Ptr: TCanonical) ||
19661 Current.count(Ptr: TCanonical)) {
19662 // If we haven't diagnosed this cycle yet, do so now.
19663 if (!Invalid.count(Ptr: TCanonical)) {
19664 S.Diag(Loc: (*Ctor->init_begin())->getSourceLocation(),
19665 DiagID: diag::warn_delegating_ctor_cycle)
19666 << Ctor;
19667
19668 // Don't add a note for a function delegating directly to itself.
19669 if (TCanonical != Canonical)
19670 S.Diag(Loc: Target->getLocation(), DiagID: diag::note_it_delegates_to);
19671
19672 CXXConstructorDecl *C = Target;
19673 while (C->getCanonicalDecl() != Canonical) {
19674 const FunctionDecl *FNTarget = nullptr;
19675 (void)C->getTargetConstructor()->hasBody(Definition&: FNTarget);
19676 assert(FNTarget && "Ctor cycle through bodiless function");
19677
19678 C = const_cast<CXXConstructorDecl*>(
19679 cast<CXXConstructorDecl>(Val: FNTarget));
19680 S.Diag(Loc: C->getLocation(), DiagID: diag::note_which_delegates_to);
19681 }
19682 }
19683
19684 Invalid.insert_range(R&: Current);
19685 Current.clear();
19686 } else {
19687 DelegatingCycleHelper(Ctor: Target, Valid, Invalid, Current, S);
19688 }
19689}
19690
19691
19692void Sema::CheckDelegatingCtorCycles() {
19693 llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
19694
19695 for (DelegatingCtorDeclsType::iterator
19696 I = DelegatingCtorDecls.begin(source: ExternalSource.get()),
19697 E = DelegatingCtorDecls.end();
19698 I != E; ++I)
19699 DelegatingCycleHelper(Ctor: *I, Valid, Invalid, Current, S&: *this);
19700
19701 for (CXXConstructorDecl *CI : Invalid)
19702 CI->setInvalidDecl();
19703}
19704
19705namespace {
19706 /// AST visitor that finds references to the 'this' expression.
19707class FindCXXThisExpr : public DynamicRecursiveASTVisitor {
19708 Sema &S;
19709
19710public:
19711 explicit FindCXXThisExpr(Sema &S) : S(S) {}
19712
19713 bool VisitCXXThisExpr(CXXThisExpr *E) override {
19714 S.Diag(Loc: E->getLocation(), DiagID: diag::err_this_static_member_func)
19715 << E->isImplicit();
19716 return false;
19717 }
19718};
19719}
19720
19721bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
19722 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
19723 if (!TSInfo)
19724 return false;
19725
19726 TypeLoc TL = TSInfo->getTypeLoc();
19727 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
19728 if (!ProtoTL)
19729 return false;
19730
19731 // C++11 [expr.prim.general]p3:
19732 // [The expression this] shall not appear before the optional
19733 // cv-qualifier-seq and it shall not appear within the declaration of a
19734 // static member function (although its type and value category are defined
19735 // within a static member function as they are within a non-static member
19736 // function). [ Note: this is because declaration matching does not occur
19737 // until the complete declarator is known. - end note ]
19738 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
19739 FindCXXThisExpr Finder(*this);
19740
19741 // If the return type came after the cv-qualifier-seq, check it now.
19742 if (Proto->hasTrailingReturn() &&
19743 !Finder.TraverseTypeLoc(TL: ProtoTL.getReturnLoc()))
19744 return true;
19745
19746 // Check the exception specification.
19747 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
19748 return true;
19749
19750 // Check the trailing requires clause
19751 if (const AssociatedConstraint &TRC = Method->getTrailingRequiresClause())
19752 if (!Finder.TraverseStmt(S: const_cast<Expr *>(TRC.ConstraintExpr)))
19753 return true;
19754
19755 return checkThisInStaticMemberFunctionAttributes(Method);
19756}
19757
19758bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
19759 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
19760 if (!TSInfo)
19761 return false;
19762
19763 TypeLoc TL = TSInfo->getTypeLoc();
19764 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
19765 if (!ProtoTL)
19766 return false;
19767
19768 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
19769 FindCXXThisExpr Finder(*this);
19770
19771 switch (Proto->getExceptionSpecType()) {
19772 case EST_Unparsed:
19773 case EST_Uninstantiated:
19774 case EST_Unevaluated:
19775 case EST_BasicNoexcept:
19776 case EST_NoThrow:
19777 case EST_DynamicNone:
19778 case EST_MSAny:
19779 case EST_None:
19780 break;
19781
19782 case EST_DependentNoexcept:
19783 case EST_NoexceptFalse:
19784 case EST_NoexceptTrue:
19785 if (!Finder.TraverseStmt(S: Proto->getNoexceptExpr()))
19786 return true;
19787 [[fallthrough]];
19788
19789 case EST_Dynamic:
19790 for (const auto &E : Proto->exceptions()) {
19791 if (!Finder.TraverseType(T: E))
19792 return true;
19793 }
19794 break;
19795 }
19796
19797 return false;
19798}
19799
19800bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
19801 FindCXXThisExpr Finder(*this);
19802
19803 // Check attributes.
19804 for (const auto *A : Method->attrs()) {
19805 // FIXME: This should be emitted by tblgen.
19806 Expr *Arg = nullptr;
19807 ArrayRef<Expr *> Args;
19808 if (const auto *G = dyn_cast<GuardedByAttr>(Val: A))
19809 Args = llvm::ArrayRef(G->args_begin(), G->args_size());
19810 else if (const auto *G = dyn_cast<PtGuardedByAttr>(Val: A))
19811 Args = llvm::ArrayRef(G->args_begin(), G->args_size());
19812 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(Val: A))
19813 Args = llvm::ArrayRef(AA->args_begin(), AA->args_size());
19814 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(Val: A))
19815 Args = llvm::ArrayRef(AB->args_begin(), AB->args_size());
19816 else if (const auto *LR = dyn_cast<LockReturnedAttr>(Val: A))
19817 Arg = LR->getArg();
19818 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(Val: A))
19819 Args = llvm::ArrayRef(LE->args_begin(), LE->args_size());
19820 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(Val: A))
19821 Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());
19822 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(Val: A))
19823 Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());
19824 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(Val: A)) {
19825 Arg = AC->getSuccessValue();
19826 Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());
19827 } else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(Val: A))
19828 Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());
19829
19830 if (Arg && !Finder.TraverseStmt(S: Arg))
19831 return true;
19832
19833 for (Expr *A : Args) {
19834 if (!Finder.TraverseStmt(S: A))
19835 return true;
19836 }
19837 }
19838
19839 return false;
19840}
19841
19842void Sema::checkExceptionSpecification(
19843 bool IsTopLevel, ExceptionSpecificationType EST,
19844 ArrayRef<ParsedType> DynamicExceptions,
19845 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
19846 SmallVectorImpl<QualType> &Exceptions,
19847 FunctionProtoType::ExceptionSpecInfo &ESI) {
19848 Exceptions.clear();
19849 ESI.Type = EST;
19850 if (EST == EST_Dynamic) {
19851 Exceptions.reserve(N: DynamicExceptions.size());
19852 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
19853 // FIXME: Preserve type source info.
19854 QualType ET = GetTypeFromParser(Ty: DynamicExceptions[ei]);
19855
19856 if (IsTopLevel) {
19857 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
19858 collectUnexpandedParameterPacks(T: ET, Unexpanded);
19859 if (!Unexpanded.empty()) {
19860 DiagnoseUnexpandedParameterPacks(
19861 Loc: DynamicExceptionRanges[ei].getBegin(), UPPC: UPPC_ExceptionType,
19862 Unexpanded);
19863 continue;
19864 }
19865 }
19866
19867 // Check that the type is valid for an exception spec, and
19868 // drop it if not.
19869 if (!CheckSpecifiedExceptionType(T&: ET, Range: DynamicExceptionRanges[ei]))
19870 Exceptions.push_back(Elt: ET);
19871 }
19872 ESI.Exceptions = Exceptions;
19873 return;
19874 }
19875
19876 if (isComputedNoexcept(ESpecType: EST)) {
19877 assert((NoexceptExpr->isTypeDependent() ||
19878 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
19879 Context.BoolTy) &&
19880 "Parser should have made sure that the expression is boolean");
19881 if (IsTopLevel && DiagnoseUnexpandedParameterPack(E: NoexceptExpr)) {
19882 ESI.Type = EST_BasicNoexcept;
19883 return;
19884 }
19885
19886 ESI.NoexceptExpr = NoexceptExpr;
19887 return;
19888 }
19889}
19890
19891void Sema::actOnDelayedExceptionSpecification(
19892 Decl *D, ExceptionSpecificationType EST, SourceRange SpecificationRange,
19893 ArrayRef<ParsedType> DynamicExceptions,
19894 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr) {
19895 if (!D)
19896 return;
19897
19898 // Dig out the function we're referring to.
19899 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(Val: D))
19900 D = FTD->getTemplatedDecl();
19901
19902 FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D);
19903 if (!FD)
19904 return;
19905
19906 // Check the exception specification.
19907 llvm::SmallVector<QualType, 4> Exceptions;
19908 FunctionProtoType::ExceptionSpecInfo ESI;
19909 checkExceptionSpecification(/*IsTopLevel=*/true, EST, DynamicExceptions,
19910 DynamicExceptionRanges, NoexceptExpr, Exceptions,
19911 ESI);
19912
19913 // Update the exception specification on the function type.
19914 Context.adjustExceptionSpec(FD, ESI, /*AsWritten=*/true);
19915
19916 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: D)) {
19917 if (MD->isStatic())
19918 checkThisInStaticMemberFunctionExceptionSpec(Method: MD);
19919
19920 if (MD->isVirtual()) {
19921 // Check overrides, which we previously had to delay.
19922 for (const CXXMethodDecl *O : MD->overridden_methods())
19923 CheckOverridingFunctionExceptionSpec(New: MD, Old: O);
19924 }
19925 }
19926}
19927
19928/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
19929///
19930MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
19931 SourceLocation DeclStart, Declarator &D,
19932 Expr *BitWidth,
19933 InClassInitStyle InitStyle,
19934 AccessSpecifier AS,
19935 const ParsedAttr &MSPropertyAttr) {
19936 const IdentifierInfo *II = D.getIdentifier();
19937 if (!II) {
19938 Diag(Loc: DeclStart, DiagID: diag::err_anonymous_property);
19939 return nullptr;
19940 }
19941 SourceLocation Loc = D.getIdentifierLoc();
19942
19943 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
19944 QualType T = TInfo->getType();
19945 if (getLangOpts().CPlusPlus) {
19946 CheckExtraCXXDefaultArguments(D);
19947
19948 if (DiagnoseUnexpandedParameterPack(Loc: D.getIdentifierLoc(), T: TInfo,
19949 UPPC: UPPC_DataMemberType)) {
19950 D.setInvalidType();
19951 T = Context.IntTy;
19952 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
19953 }
19954 }
19955
19956 DiagnoseFunctionSpecifiers(DS: D.getDeclSpec());
19957
19958 if (D.getDeclSpec().isInlineSpecified())
19959 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(), DiagID: diag::err_inline_non_function)
19960 << getLangOpts().CPlusPlus17;
19961 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
19962 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
19963 DiagID: diag::err_invalid_thread)
19964 << DeclSpec::getSpecifierName(S: TSCS);
19965
19966 // Check to see if this name was declared as a member previously
19967 NamedDecl *PrevDecl = nullptr;
19968 LookupResult Previous(*this, II, Loc, LookupMemberName,
19969 RedeclarationKind::ForVisibleRedeclaration);
19970 LookupName(R&: Previous, S);
19971 switch (Previous.getResultKind()) {
19972 case LookupResultKind::Found:
19973 case LookupResultKind::FoundUnresolvedValue:
19974 PrevDecl = Previous.getAsSingle<NamedDecl>();
19975 break;
19976
19977 case LookupResultKind::FoundOverloaded:
19978 PrevDecl = Previous.getRepresentativeDecl();
19979 break;
19980
19981 case LookupResultKind::NotFound:
19982 case LookupResultKind::NotFoundInCurrentInstantiation:
19983 case LookupResultKind::Ambiguous:
19984 break;
19985 }
19986
19987 if (PrevDecl && PrevDecl->isTemplateParameter()) {
19988 // Maybe we will complain about the shadowed template parameter.
19989 DiagnoseTemplateParameterShadow(Loc: D.getIdentifierLoc(), PrevDecl);
19990 // Just pretend that we didn't see the previous declaration.
19991 PrevDecl = nullptr;
19992 }
19993
19994 if (PrevDecl && !isDeclInScope(D: PrevDecl, Ctx: Record, S))
19995 PrevDecl = nullptr;
19996
19997 SourceLocation TSSL = D.getBeginLoc();
19998 MSPropertyDecl *NewPD =
19999 MSPropertyDecl::Create(C&: Context, DC: Record, L: Loc, N: II, T, TInfo, StartL: TSSL,
20000 Getter: MSPropertyAttr.getPropertyDataGetter(),
20001 Setter: MSPropertyAttr.getPropertyDataSetter());
20002 ProcessDeclAttributes(S: TUScope, D: NewPD, PD: D);
20003 NewPD->setAccess(AS);
20004
20005 if (NewPD->isInvalidDecl())
20006 Record->setInvalidDecl();
20007
20008 if (D.getDeclSpec().isModulePrivateSpecified())
20009 NewPD->setModulePrivate();
20010
20011 if (NewPD->isInvalidDecl() && PrevDecl) {
20012 // Don't introduce NewFD into scope; there's already something
20013 // with the same name in the same scope.
20014 } else if (II) {
20015 PushOnScopeChains(D: NewPD, S);
20016 } else
20017 Record->addDecl(D: NewPD);
20018
20019 return NewPD;
20020}
20021
20022void Sema::ActOnStartFunctionDeclarationDeclarator(
20023 Declarator &Declarator, unsigned TemplateParameterDepth) {
20024 auto &Info = InventedParameterInfos.emplace_back();
20025 TemplateParameterList *ExplicitParams = nullptr;
20026 ArrayRef<TemplateParameterList *> ExplicitLists =
20027 Declarator.getTemplateParameterLists();
20028 if (!ExplicitLists.empty()) {
20029 bool IsMemberSpecialization, IsInvalid;
20030 ExplicitParams = MatchTemplateParametersToScopeSpecifier(
20031 DeclStartLoc: Declarator.getBeginLoc(), DeclLoc: Declarator.getIdentifierLoc(),
20032 SS: Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr,
20033 ParamLists: ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, Invalid&: IsInvalid,
20034 /*SuppressDiagnostic=*/true);
20035 }
20036 // C++23 [dcl.fct]p23:
20037 // An abbreviated function template can have a template-head. The invented
20038 // template-parameters are appended to the template-parameter-list after
20039 // the explicitly declared template-parameters.
20040 //
20041 // A template-head must have one or more template-parameters (read:
20042 // 'template<>' is *not* a template-head). Only append the invented
20043 // template parameters if we matched the nested-name-specifier to a non-empty
20044 // TemplateParameterList.
20045 if (ExplicitParams && !ExplicitParams->empty()) {
20046 Info.AutoTemplateParameterDepth = ExplicitParams->getDepth();
20047 llvm::append_range(C&: Info.TemplateParams, R&: *ExplicitParams);
20048 Info.NumExplicitTemplateParams = ExplicitParams->size();
20049 } else {
20050 Info.AutoTemplateParameterDepth = TemplateParameterDepth;
20051 Info.NumExplicitTemplateParams = 0;
20052 }
20053}
20054
20055void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator &Declarator) {
20056 auto &FSI = InventedParameterInfos.back();
20057 if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) {
20058 if (FSI.NumExplicitTemplateParams != 0) {
20059 TemplateParameterList *ExplicitParams =
20060 Declarator.getTemplateParameterLists().back();
20061 Declarator.setInventedTemplateParameterList(
20062 TemplateParameterList::Create(
20063 C: Context, TemplateLoc: ExplicitParams->getTemplateLoc(),
20064 LAngleLoc: ExplicitParams->getLAngleLoc(), Params: FSI.TemplateParams,
20065 RAngleLoc: ExplicitParams->getRAngleLoc(),
20066 RequiresClause: ExplicitParams->getRequiresClause()));
20067 } else {
20068 Declarator.setInventedTemplateParameterList(TemplateParameterList::Create(
20069 C: Context, TemplateLoc: Declarator.getBeginLoc(), LAngleLoc: SourceLocation(),
20070 Params: FSI.TemplateParams, RAngleLoc: Declarator.getEndLoc(),
20071 /*RequiresClause=*/nullptr));
20072 }
20073 }
20074 InventedParameterInfos.pop_back();
20075}
20076
20077bool Sema::BuildCtorClosureDefaultArgs(SourceLocation Loc,
20078 CXXConstructorDecl *Ctor, bool IsCopy) {
20079 assert(Context.getTargetInfo().getCXXABI().isMicrosoft());
20080
20081 if (!Ctor->getCtorClosureDefaultArgs().empty()) {
20082 // If we build args for default constructor closures, those will have
20083 // been generated *before* building args for any copy constructor closures.
20084 assert(IsCopy || Ctor->getCtorClosureDefaultArgs()[0] != nullptr);
20085 return false;
20086 }
20087
20088 unsigned NumParams = Ctor->getNumParams();
20089 if (NumParams == 0)
20090 return false;
20091
20092 CXXDefaultArgExpr **Args =
20093 new (getASTContext()) CXXDefaultArgExpr *[NumParams];
20094
20095 if (IsCopy)
20096 Args[0] = nullptr; // Copy ctor closure will provide the first argument.
20097
20098 for (unsigned I = IsCopy ? 1 : 0; I != NumParams; ++I) {
20099 ExprResult R = BuildCXXDefaultArgExpr(CallLoc: Loc, FD: Ctor, Param: Ctor->getParamDecl(i: I));
20100 CleanupVarDeclMarking();
20101 if (R.isInvalid())
20102 return true;
20103 Args[I] = cast<CXXDefaultArgExpr>(Val: R.get());
20104 }
20105
20106 Ctor->setCtorClosureDefaultArgs(ArrayRef(Args, NumParams));
20107 return false;
20108}
20109