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};
87
88/// VisitExpr - Visit all of the children of this expression.
89bool CheckDefaultArgumentVisitor::VisitExpr(const Expr *Node) {
90 bool IsInvalid = false;
91 for (const Stmt *SubStmt : Node->children())
92 if (SubStmt)
93 IsInvalid |= Visit(S: SubStmt);
94 return IsInvalid;
95}
96
97/// VisitDeclRefExpr - Visit a reference to a declaration, to
98/// determine whether this declaration can be used in the default
99/// argument expression.
100bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(const DeclRefExpr *DRE) {
101 const ValueDecl *Decl = DRE->getDecl();
102
103 if (!isa<VarDecl, BindingDecl>(Val: Decl))
104 return false;
105
106 if (const auto *Param = dyn_cast<ParmVarDecl>(Val: Decl)) {
107 // C++ [dcl.fct.default]p9:
108 // [...] parameters of a function shall not be used in default
109 // argument expressions, even if they are not evaluated. [...]
110 //
111 // C++17 [dcl.fct.default]p9 (by CWG 2082):
112 // [...] A parameter shall not appear as a potentially-evaluated
113 // expression in a default argument. [...]
114 //
115 if (DRE->isNonOdrUse() != NOUR_Unevaluated)
116 return S.Diag(Loc: DRE->getBeginLoc(),
117 DiagID: diag::err_param_default_argument_references_param)
118 << Param->getDeclName() << DefaultArg->getSourceRange();
119 } else if (auto *VD = Decl->getPotentiallyDecomposedVarDecl()) {
120 // C++ [dcl.fct.default]p7:
121 // Local variables shall not be used in default argument
122 // expressions.
123 //
124 // C++17 [dcl.fct.default]p7 (by CWG 2082):
125 // A local variable shall not appear as a potentially-evaluated
126 // expression in a default argument.
127 //
128 // C++20 [dcl.fct.default]p7 (DR as part of P0588R1, see also CWG 2346):
129 // Note: A local variable cannot be odr-used (6.3) in a default
130 // argument.
131 //
132 if (VD->isLocalVarDecl() && !DRE->isNonOdrUse())
133 return S.Diag(Loc: DRE->getBeginLoc(),
134 DiagID: diag::err_param_default_argument_references_local)
135 << Decl << DefaultArg->getSourceRange();
136 }
137 return false;
138}
139
140/// VisitCXXThisExpr - Visit a C++ "this" expression.
141bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(const CXXThisExpr *ThisE) {
142 // C++ [dcl.fct.default]p8:
143 // The keyword this shall not be used in a default argument of a
144 // member function.
145 return S.Diag(Loc: ThisE->getBeginLoc(),
146 DiagID: diag::err_param_default_argument_references_this)
147 << ThisE->getSourceRange();
148}
149
150bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(
151 const PseudoObjectExpr *POE) {
152 bool Invalid = false;
153 for (const Expr *E : POE->semantics()) {
154 // Look through bindings.
155 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Val: E)) {
156 E = OVE->getSourceExpr();
157 assert(E && "pseudo-object binding without source expression?");
158 }
159
160 Invalid |= Visit(S: E);
161 }
162 return Invalid;
163}
164
165bool CheckDefaultArgumentVisitor::VisitLambdaExpr(const LambdaExpr *Lambda) {
166 // [expr.prim.lambda.capture]p9
167 // a lambda-expression appearing in a default argument cannot implicitly or
168 // explicitly capture any local entity. Such a lambda-expression can still
169 // have an init-capture if any full-expression in its initializer satisfies
170 // the constraints of an expression appearing in a default argument.
171 bool Invalid = false;
172 for (const LambdaCapture &LC : Lambda->captures()) {
173 if (!Lambda->isInitCapture(Capture: &LC))
174 return S.Diag(Loc: LC.getLocation(), DiagID: diag::err_lambda_capture_default_arg);
175 // Init captures are always VarDecl.
176 auto *D = cast<VarDecl>(Val: LC.getCapturedVar());
177 Invalid |= Visit(S: D->getInit());
178 }
179 return Invalid;
180}
181} // namespace
182
183void
184Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
185 const CXXMethodDecl *Method) {
186 // If we have an MSAny spec already, don't bother.
187 if (!Method || ComputedEST == EST_MSAny)
188 return;
189
190 const FunctionProtoType *Proto
191 = Method->getType()->getAs<FunctionProtoType>();
192 Proto = Self->ResolveExceptionSpec(Loc: CallLoc, FPT: Proto);
193 if (!Proto)
194 return;
195
196 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
197
198 // If we have a throw-all spec at this point, ignore the function.
199 if (ComputedEST == EST_None)
200 return;
201
202 if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
203 EST = EST_BasicNoexcept;
204
205 switch (EST) {
206 case EST_Unparsed:
207 case EST_Uninstantiated:
208 case EST_Unevaluated:
209 llvm_unreachable("should not see unresolved exception specs here");
210
211 // If this function can throw any exceptions, make a note of that.
212 case EST_MSAny:
213 case EST_None:
214 // FIXME: Whichever we see last of MSAny and None determines our result.
215 // We should make a consistent, order-independent choice here.
216 ClearExceptions();
217 ComputedEST = EST;
218 return;
219 case EST_NoexceptFalse:
220 ClearExceptions();
221 ComputedEST = EST_None;
222 return;
223 // FIXME: If the call to this decl is using any of its default arguments, we
224 // need to search them for potentially-throwing calls.
225 // If this function has a basic noexcept, it doesn't affect the outcome.
226 case EST_BasicNoexcept:
227 case EST_NoexceptTrue:
228 case EST_NoThrow:
229 return;
230 // If we're still at noexcept(true) and there's a throw() callee,
231 // change to that specification.
232 case EST_DynamicNone:
233 if (ComputedEST == EST_BasicNoexcept)
234 ComputedEST = EST_DynamicNone;
235 return;
236 case EST_DependentNoexcept:
237 llvm_unreachable(
238 "should not generate implicit declarations for dependent cases");
239 case EST_Dynamic:
240 break;
241 }
242 assert(EST == EST_Dynamic && "EST case not considered earlier.");
243 assert(ComputedEST != EST_None &&
244 "Shouldn't collect exceptions when throw-all is guaranteed.");
245 ComputedEST = EST_Dynamic;
246 // Record the exceptions in this function's exception specification.
247 for (const auto &E : Proto->exceptions())
248 if (ExceptionsSeen.insert(Ptr: Self->Context.getCanonicalType(T: E)).second)
249 Exceptions.push_back(Elt: E);
250}
251
252void Sema::ImplicitExceptionSpecification::CalledStmt(Stmt *S) {
253 if (!S || ComputedEST == EST_MSAny)
254 return;
255
256 // FIXME:
257 //
258 // C++0x [except.spec]p14:
259 // [An] implicit exception-specification specifies the type-id T if and
260 // only if T is allowed by the exception-specification of a function directly
261 // invoked by f's implicit definition; f shall allow all exceptions if any
262 // function it directly invokes allows all exceptions, and f shall allow no
263 // exceptions if every function it directly invokes allows no exceptions.
264 //
265 // Note in particular that if an implicit exception-specification is generated
266 // for a function containing a throw-expression, that specification can still
267 // be noexcept(true).
268 //
269 // Note also that 'directly invoked' is not defined in the standard, and there
270 // is no indication that we should only consider potentially-evaluated calls.
271 //
272 // Ultimately we should implement the intent of the standard: the exception
273 // specification should be the set of exceptions which can be thrown by the
274 // implicit definition. For now, we assume that any non-nothrow expression can
275 // throw any exception.
276
277 if (Self->canThrow(E: S))
278 ComputedEST = EST_None;
279}
280
281ExprResult Sema::ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
282 SourceLocation EqualLoc) {
283 if (RequireCompleteType(Loc: Param->getLocation(), T: Param->getType(),
284 DiagID: diag::err_typecheck_decl_incomplete_type))
285 return true;
286
287 // C++ [dcl.fct.default]p5
288 // A default argument expression is implicitly converted (clause
289 // 4) to the parameter type. The default argument expression has
290 // the same semantic constraints as the initializer expression in
291 // a declaration of a variable of the parameter type, using the
292 // copy-initialization semantics (8.5).
293 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
294 Parm: Param);
295 InitializationKind Kind = InitializationKind::CreateCopy(InitLoc: Param->getLocation(),
296 EqualLoc);
297 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
298 ExprResult Result = InitSeq.Perform(S&: *this, Entity, Kind, Args: Arg);
299 if (Result.isInvalid())
300 return true;
301 Arg = Result.getAs<Expr>();
302
303 CheckCompletedExpr(E: Arg, CheckLoc: EqualLoc);
304 Arg = MaybeCreateExprWithCleanups(SubExpr: Arg);
305
306 return Arg;
307}
308
309void Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
310 SourceLocation EqualLoc) {
311 // Add the default argument to the parameter
312 Param->setDefaultArg(Arg);
313
314 // We have already instantiated this parameter; provide each of the
315 // instantiations with the uninstantiated default argument.
316 UnparsedDefaultArgInstantiationsMap::iterator InstPos
317 = UnparsedDefaultArgInstantiations.find(Val: Param);
318 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
319 for (auto &Instantiation : InstPos->second)
320 Instantiation->setUninstantiatedDefaultArg(Arg);
321
322 // We're done tracking this parameter's instantiations.
323 UnparsedDefaultArgInstantiations.erase(I: InstPos);
324 }
325}
326
327void
328Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
329 Expr *DefaultArg) {
330 if (!param || !DefaultArg)
331 return;
332
333 ParmVarDecl *Param = cast<ParmVarDecl>(Val: param);
334 UnparsedDefaultArgLocs.erase(Val: Param);
335
336 // Default arguments are only permitted in C++
337 if (!getLangOpts().CPlusPlus) {
338 Diag(Loc: EqualLoc, DiagID: diag::err_param_default_argument)
339 << DefaultArg->getSourceRange();
340 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
341 }
342
343 // Check for unexpanded parameter packs.
344 if (DiagnoseUnexpandedParameterPack(E: DefaultArg, UPPC: UPPC_DefaultArgument))
345 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
346
347 // C++11 [dcl.fct.default]p3
348 // A default argument expression [...] shall not be specified for a
349 // parameter pack.
350 if (Param->isParameterPack()) {
351 Diag(Loc: EqualLoc, DiagID: diag::err_param_default_argument_on_parameter_pack)
352 << DefaultArg->getSourceRange();
353 // Recover by discarding the default argument.
354 Param->setDefaultArg(nullptr);
355 return;
356 }
357
358 ExprResult Result = ConvertParamDefaultArgument(Param, Arg: DefaultArg, EqualLoc);
359 if (Result.isInvalid())
360 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
361
362 DefaultArg = Result.getAs<Expr>();
363
364 // Check that the default argument is well-formed
365 CheckDefaultArgumentVisitor DefaultArgChecker(*this, DefaultArg);
366 if (DefaultArgChecker.Visit(S: DefaultArg))
367 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
368
369 SetParamDefaultArgument(Param, Arg: DefaultArg, EqualLoc);
370}
371
372void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
373 SourceLocation EqualLoc,
374 SourceLocation ArgLoc) {
375 if (!param)
376 return;
377
378 ParmVarDecl *Param = cast<ParmVarDecl>(Val: param);
379 Param->setUnparsedDefaultArg();
380 UnparsedDefaultArgLocs[Param] = ArgLoc;
381}
382
383void Sema::ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc,
384 Expr *DefaultArg) {
385 if (!param)
386 return;
387
388 ParmVarDecl *Param = cast<ParmVarDecl>(Val: param);
389 Param->setInvalidDecl();
390 UnparsedDefaultArgLocs.erase(Val: Param);
391 ExprResult RE;
392 if (DefaultArg) {
393 RE = CreateRecoveryExpr(Begin: EqualLoc, End: DefaultArg->getEndLoc(), SubExprs: {DefaultArg},
394 T: Param->getType().getNonReferenceType());
395 } else {
396 RE = CreateRecoveryExpr(Begin: EqualLoc, End: EqualLoc, SubExprs: {},
397 T: Param->getType().getNonReferenceType());
398 }
399 Param->setDefaultArg(RE.get());
400}
401
402void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
403 // C++ [dcl.fct.default]p3
404 // A default argument expression shall be specified only in the
405 // parameter-declaration-clause of a function declaration or in a
406 // template-parameter (14.1). It shall not be specified for a
407 // parameter pack. If it is specified in a
408 // parameter-declaration-clause, it shall not occur within a
409 // declarator or abstract-declarator of a parameter-declaration.
410 bool MightBeFunction = D.isFunctionDeclarationContext();
411 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
412 DeclaratorChunk &chunk = D.getTypeObject(i);
413 if (chunk.Kind == DeclaratorChunk::Function) {
414 if (MightBeFunction) {
415 // This is a function declaration. It can have default arguments, but
416 // keep looking in case its return type is a function type with default
417 // arguments.
418 MightBeFunction = false;
419 continue;
420 }
421 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
422 ++argIdx) {
423 ParmVarDecl *Param = cast<ParmVarDecl>(Val: chunk.Fun.Params[argIdx].Param);
424 if (Param->hasUnparsedDefaultArg()) {
425 std::unique_ptr<CachedTokens> Toks =
426 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
427 SourceRange SR;
428 if (Toks->size() > 1)
429 SR = SourceRange((*Toks)[1].getLocation(),
430 Toks->back().getLocation());
431 else
432 SR = UnparsedDefaultArgLocs[Param];
433 Diag(Loc: Param->getLocation(), DiagID: diag::err_param_default_argument_nonfunc)
434 << SR;
435 } else if (Param->getDefaultArg()) {
436 Diag(Loc: Param->getLocation(), DiagID: diag::err_param_default_argument_nonfunc)
437 << Param->getDefaultArg()->getSourceRange();
438 Param->setDefaultArg(nullptr);
439 }
440 }
441 } else if (chunk.Kind != DeclaratorChunk::Paren) {
442 MightBeFunction = false;
443 }
444 }
445}
446
447static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
448 return llvm::any_of(Range: FD->parameters(), P: [](ParmVarDecl *P) {
449 return P->hasDefaultArg() && !P->hasInheritedDefaultArg();
450 });
451}
452
453bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
454 Scope *S) {
455 bool Invalid = false;
456
457 // The declaration context corresponding to the scope is the semantic
458 // parent, unless this is a local function declaration, in which case
459 // it is that surrounding function.
460 DeclContext *ScopeDC = New->isLocalExternDecl()
461 ? New->getLexicalDeclContext()
462 : New->getDeclContext();
463
464 // Find the previous declaration for the purpose of default arguments.
465 FunctionDecl *PrevForDefaultArgs = Old;
466 for (/**/; PrevForDefaultArgs;
467 // Don't bother looking back past the latest decl if this is a local
468 // extern declaration; nothing else could work.
469 PrevForDefaultArgs = New->isLocalExternDecl()
470 ? nullptr
471 : PrevForDefaultArgs->getPreviousDecl()) {
472 // Ignore hidden declarations.
473 if (!LookupResult::isVisible(SemaRef&: *this, D: PrevForDefaultArgs))
474 continue;
475
476 if (S && !isDeclInScope(D: PrevForDefaultArgs, Ctx: ScopeDC, S) &&
477 !New->isCXXClassMember()) {
478 // Ignore default arguments of old decl if they are not in
479 // the same scope and this is not an out-of-line definition of
480 // a member function.
481 continue;
482 }
483
484 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
485 // If only one of these is a local function declaration, then they are
486 // declared in different scopes, even though isDeclInScope may think
487 // they're in the same scope. (If both are local, the scope check is
488 // sufficient, and if neither is local, then they are in the same scope.)
489 continue;
490 }
491
492 // We found the right previous declaration.
493 break;
494 }
495
496 // C++ [dcl.fct.default]p4:
497 // For non-template functions, default arguments can be added in
498 // later declarations of a function in the same
499 // scope. Declarations in different scopes have completely
500 // distinct sets of default arguments. That is, declarations in
501 // inner scopes do not acquire default arguments from
502 // declarations in outer scopes, and vice versa. In a given
503 // function declaration, all parameters subsequent to a
504 // parameter with a default argument shall have default
505 // arguments supplied in this or previous declarations. A
506 // default argument shall not be redefined by a later
507 // declaration (not even to the same value).
508 //
509 // C++ [dcl.fct.default]p6:
510 // Except for member functions of class templates, the default arguments
511 // in a member function definition that appears outside of the class
512 // definition are added to the set of default arguments provided by the
513 // member function declaration in the class definition.
514 for (unsigned p = 0, NumParams = PrevForDefaultArgs
515 ? PrevForDefaultArgs->getNumParams()
516 : 0;
517 p < NumParams; ++p) {
518 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(i: p);
519 ParmVarDecl *NewParam = New->getParamDecl(i: p);
520
521 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
522 bool NewParamHasDfl = NewParam->hasDefaultArg();
523
524 if (OldParamHasDfl && NewParamHasDfl) {
525 unsigned DiagDefaultParamID =
526 diag::err_param_default_argument_redefinition;
527
528 // MSVC accepts that default parameters be redefined for member functions
529 // of template class. The new default parameter's value is ignored.
530 Invalid = true;
531 if (getLangOpts().MicrosoftExt) {
532 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: New);
533 if (MD && MD->getParent()->getDescribedClassTemplate()) {
534 // Merge the old default argument into the new parameter.
535 NewParam->setHasInheritedDefaultArg();
536 if (OldParam->hasUninstantiatedDefaultArg())
537 NewParam->setUninstantiatedDefaultArg(
538 OldParam->getUninstantiatedDefaultArg());
539 else
540 NewParam->setDefaultArg(OldParam->getInit());
541 DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
542 Invalid = false;
543 }
544 }
545
546 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
547 // hint here. Alternatively, we could walk the type-source information
548 // for NewParam to find the last source location in the type... but it
549 // isn't worth the effort right now. This is the kind of test case that
550 // is hard to get right:
551 // int f(int);
552 // void g(int (*fp)(int) = f);
553 // void g(int (*fp)(int) = &f);
554 Diag(Loc: NewParam->getLocation(), DiagID: DiagDefaultParamID)
555 << NewParam->getDefaultArgRange();
556
557 // Look for the function declaration where the default argument was
558 // actually written, which may be a declaration prior to Old.
559 for (auto Older = PrevForDefaultArgs;
560 OldParam->hasInheritedDefaultArg(); /**/) {
561 Older = Older->getPreviousDecl();
562 OldParam = Older->getParamDecl(i: p);
563 }
564
565 Diag(Loc: OldParam->getLocation(), DiagID: diag::note_previous_definition)
566 << OldParam->getDefaultArgRange();
567 } else if (OldParamHasDfl) {
568 // Merge the old default argument into the new parameter unless the new
569 // function is a friend declaration in a template class. In the latter
570 // case the default arguments will be inherited when the friend
571 // declaration will be instantiated.
572 if (New->getFriendObjectKind() == Decl::FOK_None ||
573 !New->getLexicalDeclContext()->isDependentContext()) {
574 // It's important to use getInit() here; getDefaultArg()
575 // strips off any top-level ExprWithCleanups.
576 NewParam->setHasInheritedDefaultArg();
577 if (OldParam->hasUnparsedDefaultArg())
578 NewParam->setUnparsedDefaultArg();
579 else if (OldParam->hasUninstantiatedDefaultArg())
580 NewParam->setUninstantiatedDefaultArg(
581 OldParam->getUninstantiatedDefaultArg());
582 else
583 NewParam->setDefaultArg(OldParam->getInit());
584 }
585 } else if (NewParamHasDfl) {
586 if (New->getDescribedFunctionTemplate()) {
587 // Paragraph 4, quoted above, only applies to non-template functions.
588 Diag(Loc: NewParam->getLocation(),
589 DiagID: diag::err_param_default_argument_template_redecl)
590 << NewParam->getDefaultArgRange();
591 Diag(Loc: PrevForDefaultArgs->getLocation(),
592 DiagID: diag::note_template_prev_declaration)
593 << false;
594 } else if (New->getTemplateSpecializationKind()
595 != TSK_ImplicitInstantiation &&
596 New->getTemplateSpecializationKind() != TSK_Undeclared) {
597 // C++ [temp.expr.spec]p21:
598 // Default function arguments shall not be specified in a declaration
599 // or a definition for one of the following explicit specializations:
600 // - the explicit specialization of a function template;
601 // - the explicit specialization of a member function template;
602 // - the explicit specialization of a member function of a class
603 // template where the class template specialization to which the
604 // member function specialization belongs is implicitly
605 // instantiated.
606 Diag(Loc: NewParam->getLocation(), DiagID: diag::err_template_spec_default_arg)
607 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
608 << New->getDeclName()
609 << NewParam->getDefaultArgRange();
610 } else if (New->getDeclContext()->isDependentContext()) {
611 // C++ [dcl.fct.default]p6 (DR217):
612 // Default arguments for a member function of a class template shall
613 // be specified on the initial declaration of the member function
614 // within the class template.
615 //
616 // Reading the tea leaves a bit in DR217 and its reference to DR205
617 // leads me to the conclusion that one cannot add default function
618 // arguments for an out-of-line definition of a member function of a
619 // dependent type.
620 int WhichKind = 2;
621 if (CXXRecordDecl *Record
622 = dyn_cast<CXXRecordDecl>(Val: New->getDeclContext())) {
623 if (Record->getDescribedClassTemplate())
624 WhichKind = 0;
625 else if (isa<ClassTemplatePartialSpecializationDecl>(Val: Record))
626 WhichKind = 1;
627 else
628 WhichKind = 2;
629 }
630
631 Diag(Loc: NewParam->getLocation(),
632 DiagID: diag::err_param_default_argument_member_template_redecl)
633 << WhichKind
634 << NewParam->getDefaultArgRange();
635 }
636 }
637 }
638
639 // DR1344: If a default argument is added outside a class definition and that
640 // default argument makes the function a special member function, the program
641 // is ill-formed. This can only happen for constructors.
642 if (isa<CXXConstructorDecl>(Val: New) &&
643 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
644 CXXSpecialMemberKind NewSM = getSpecialMember(MD: cast<CXXMethodDecl>(Val: New)),
645 OldSM = getSpecialMember(MD: cast<CXXMethodDecl>(Val: Old));
646 if (NewSM != OldSM) {
647 ParmVarDecl *NewParam = New->getParamDecl(i: New->getMinRequiredArguments());
648 assert(NewParam->hasDefaultArg());
649 Diag(Loc: NewParam->getLocation(), DiagID: diag::err_default_arg_makes_ctor_special)
650 << NewParam->getDefaultArgRange() << NewSM;
651 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
652 }
653 }
654
655 const FunctionDecl *Def;
656 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
657 // template has a constexpr specifier then all its declarations shall
658 // contain the constexpr specifier.
659 if (New->getConstexprKind() != Old->getConstexprKind()) {
660 Diag(Loc: New->getLocation(), DiagID: diag::err_constexpr_redecl_mismatch)
661 << New << static_cast<int>(New->getConstexprKind())
662 << static_cast<int>(Old->getConstexprKind());
663 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
664 Invalid = true;
665 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
666 Old->isDefined(Definition&: Def) &&
667 // If a friend function is inlined but does not have 'inline'
668 // specifier, it is a definition. Do not report attribute conflict
669 // in this case, redefinition will be diagnosed later.
670 (New->isInlineSpecified() ||
671 New->getFriendObjectKind() == Decl::FOK_None)) {
672 // C++11 [dcl.fcn.spec]p4:
673 // If the definition of a function appears in a translation unit before its
674 // first declaration as inline, the program is ill-formed.
675 Diag(Loc: New->getLocation(), DiagID: diag::err_inline_decl_follows_def) << New;
676 Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
677 Invalid = true;
678 }
679
680 // C++17 [temp.deduct.guide]p3:
681 // Two deduction guide declarations in the same translation unit
682 // for the same class template shall not have equivalent
683 // parameter-declaration-clauses.
684 if (isa<CXXDeductionGuideDecl>(Val: New) &&
685 !New->isFunctionTemplateSpecialization() && isVisible(D: Old)) {
686 Diag(Loc: New->getLocation(), DiagID: diag::err_deduction_guide_redeclared);
687 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
688 }
689
690 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
691 // argument expression, that declaration shall be a definition and shall be
692 // the only declaration of the function or function template in the
693 // translation unit.
694 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
695 functionDeclHasDefaultArgument(FD: Old)) {
696 Diag(Loc: New->getLocation(), DiagID: diag::err_friend_decl_with_def_arg_redeclared);
697 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
698 Invalid = true;
699 }
700
701 // C++11 [temp.friend]p4 (DR329):
702 // When a function is defined in a friend function declaration in a class
703 // template, the function is instantiated when the function is odr-used.
704 // The same restrictions on multiple declarations and definitions that
705 // apply to non-template function declarations and definitions also apply
706 // to these implicit definitions.
707 const FunctionDecl *OldDefinition = nullptr;
708 if (New->isThisDeclarationInstantiatedFromAFriendDefinition() &&
709 Old->isDefined(Definition&: OldDefinition, CheckForPendingFriendDefinition: true))
710 CheckForFunctionRedefinition(FD: New, EffectiveDefinition: OldDefinition);
711
712 return Invalid;
713}
714
715void Sema::DiagPlaceholderVariableDefinition(SourceLocation Loc) {
716 Diag(Loc, DiagID: getLangOpts().CPlusPlus26
717 ? diag::warn_cxx23_placeholder_var_definition
718 : diag::ext_placeholder_var_definition);
719}
720
721NamedDecl *
722Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
723 MultiTemplateParamsArg TemplateParamLists) {
724 assert(D.isDecompositionDeclarator());
725 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
726
727 // The syntax only allows a decomposition declarator as a simple-declaration,
728 // a for-range-declaration, or a condition in Clang, but we parse it in more
729 // cases than that.
730 if (!D.mayHaveDecompositionDeclarator()) {
731 Diag(Loc: Decomp.getLSquareLoc(), DiagID: diag::err_decomp_decl_context)
732 << Decomp.getSourceRange();
733 return nullptr;
734 }
735
736 if (!TemplateParamLists.empty()) {
737 // C++17 [temp]/1:
738 // A template defines a family of class, functions, or variables, or an
739 // alias for a family of types.
740 //
741 // Structured bindings are not included.
742 Diag(Loc: TemplateParamLists.front()->getTemplateLoc(),
743 DiagID: diag::err_decomp_decl_template);
744 return nullptr;
745 }
746
747 unsigned DiagID;
748 if (!getLangOpts().CPlusPlus17)
749 DiagID = diag::compat_pre_cxx17_decomp_decl;
750 else if (D.getContext() == DeclaratorContext::Condition)
751 DiagID = getLangOpts().CPlusPlus26
752 ? diag::compat_cxx26_decomp_decl_cond
753 : diag::compat_pre_cxx26_decomp_decl_cond;
754 else
755 DiagID = diag::compat_cxx17_decomp_decl;
756
757 Diag(Loc: Decomp.getLSquareLoc(), DiagID) << Decomp.getSourceRange();
758
759 // The semantic context is always just the current context.
760 DeclContext *const DC = CurContext;
761
762 // C++17 [dcl.dcl]/8:
763 // The decl-specifier-seq shall contain only the type-specifier auto
764 // and cv-qualifiers.
765 // C++20 [dcl.dcl]/8:
766 // If decl-specifier-seq contains any decl-specifier other than static,
767 // thread_local, auto, or cv-qualifiers, the program is ill-formed.
768 // C++23 [dcl.pre]/6:
769 // Each decl-specifier in the decl-specifier-seq shall be static,
770 // thread_local, auto (9.2.9.6 [dcl.spec.auto]), or a cv-qualifier.
771 // C++23 [dcl.pre]/7:
772 // Each decl-specifier in the decl-specifier-seq shall be constexpr,
773 // constinit, static, thread_local, auto, or a cv-qualifier
774 auto &DS = D.getDeclSpec();
775 auto DiagBadSpecifier = [&](StringRef Name, SourceLocation Loc) {
776 Diag(Loc, DiagID: diag::err_decomp_decl_spec) << Name;
777 };
778
779 auto DiagCpp20Specifier = [&](StringRef Name, SourceLocation Loc) {
780 DiagCompat(Loc, CompatDiagId: diag_compat::decomp_decl_spec) << Name;
781 };
782
783 if (auto SCS = DS.getStorageClassSpec()) {
784 if (SCS == DeclSpec::SCS_static)
785 DiagCpp20Specifier(DeclSpec::getSpecifierName(S: SCS),
786 DS.getStorageClassSpecLoc());
787 else
788 DiagBadSpecifier(DeclSpec::getSpecifierName(S: SCS),
789 DS.getStorageClassSpecLoc());
790 }
791 if (auto TSCS = DS.getThreadStorageClassSpec())
792 DiagCpp20Specifier(DeclSpec::getSpecifierName(S: TSCS),
793 DS.getThreadStorageClassSpecLoc());
794
795 if (DS.isInlineSpecified())
796 DiagBadSpecifier("inline", DS.getInlineSpecLoc());
797
798 if (ConstexprSpecKind ConstexprSpec = DS.getConstexprSpecifier();
799 ConstexprSpec != ConstexprSpecKind::Unspecified) {
800 if (ConstexprSpec == ConstexprSpecKind::Consteval ||
801 !getLangOpts().CPlusPlus26)
802 DiagBadSpecifier(DeclSpec::getSpecifierName(C: ConstexprSpec),
803 DS.getConstexprSpecLoc());
804 }
805
806 // We can't recover from it being declared as a typedef.
807 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
808 return nullptr;
809
810 // C++2a [dcl.struct.bind]p1:
811 // A cv that includes volatile is deprecated
812 if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) &&
813 getLangOpts().CPlusPlus20)
814 Diag(Loc: DS.getVolatileSpecLoc(),
815 DiagID: diag::warn_deprecated_volatile_structured_binding);
816
817 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
818 QualType R = TInfo->getType();
819
820 if (DiagnoseUnexpandedParameterPack(Loc: D.getIdentifierLoc(), T: TInfo,
821 UPPC: UPPC_DeclarationType))
822 D.setInvalidType();
823
824 // The syntax only allows a single ref-qualifier prior to the decomposition
825 // declarator. No other declarator chunks are permitted. Also check the type
826 // specifier here.
827 if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
828 D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
829 (D.getNumTypeObjects() == 1 &&
830 D.getTypeObject(i: 0).Kind != DeclaratorChunk::Reference)) {
831 Diag(Loc: Decomp.getLSquareLoc(),
832 DiagID: (D.hasGroupingParens() ||
833 (D.getNumTypeObjects() &&
834 D.getTypeObject(i: 0).Kind == DeclaratorChunk::Paren))
835 ? diag::err_decomp_decl_parens
836 : diag::err_decomp_decl_type)
837 << R;
838
839 // In most cases, there's no actual problem with an explicitly-specified
840 // type, but a function type won't work here, and ActOnVariableDeclarator
841 // shouldn't be called for such a type.
842 if (R->isFunctionType())
843 D.setInvalidType();
844 }
845
846 // Constrained auto is prohibited by [decl.pre]p6, so check that here.
847 if (DS.isConstrainedAuto()) {
848 TemplateIdAnnotation *TemplRep = DS.getRepAsTemplateId();
849 assert(TemplRep->Kind == TNK_Concept_template &&
850 "No other template kind should be possible for a constrained auto");
851
852 SourceRange TemplRange{TemplRep->TemplateNameLoc,
853 TemplRep->RAngleLoc.isValid()
854 ? TemplRep->RAngleLoc
855 : TemplRep->TemplateNameLoc};
856 Diag(Loc: TemplRep->TemplateNameLoc, DiagID: diag::err_decomp_decl_constraint)
857 << TemplRange << FixItHint::CreateRemoval(RemoveRange: TemplRange);
858 }
859
860 // Build the BindingDecls.
861 SmallVector<BindingDecl*, 8> Bindings;
862
863 // Build the BindingDecls.
864 for (auto &B : D.getDecompositionDeclarator().bindings()) {
865 // Check for name conflicts.
866 DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
867 IdentifierInfo *VarName = B.Name;
868 assert(VarName && "Cannot have an unnamed binding declaration");
869
870 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
871 RedeclarationKind::ForVisibleRedeclaration);
872 LookupName(R&: Previous, S,
873 /*CreateBuiltins*/AllowBuiltinCreation: DC->getRedeclContext()->isTranslationUnit());
874
875 // It's not permitted to shadow a template parameter name.
876 if (Previous.isSingleResult() &&
877 Previous.getFoundDecl()->isTemplateParameter()) {
878 DiagnoseTemplateParameterShadow(Loc: B.NameLoc, PrevDecl: Previous.getFoundDecl());
879 Previous.clear();
880 }
881
882 QualType QT;
883 if (B.EllipsisLoc.isValid()) {
884 if (!cast<Decl>(Val: DC)->isTemplated())
885 Diag(Loc: B.EllipsisLoc, DiagID: diag::err_pack_outside_template);
886 QT = Context.getPackExpansionType(Pattern: Context.DependentTy, NumExpansions: std::nullopt,
887 /*ExpectsPackInType=*/ExpectPackInType: false);
888 }
889
890 auto *BD = BindingDecl::Create(C&: Context, DC, IdLoc: B.NameLoc, Id: B.Name, T: QT);
891
892 ProcessDeclAttributeList(S, D: BD, AttrList: *B.Attrs);
893
894 // Find the shadowed declaration before filtering for scope.
895 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
896 ? getShadowedDeclaration(D: BD, R: Previous)
897 : nullptr;
898
899 bool ConsiderLinkage = DC->isFunctionOrMethod() &&
900 DS.getStorageClassSpec() == DeclSpec::SCS_extern;
901 FilterLookupForScope(R&: Previous, Ctx: DC, S, ConsiderLinkage,
902 /*AllowInlineNamespace*/false);
903
904 bool IsPlaceholder = DS.getStorageClassSpec() != DeclSpec::SCS_static &&
905 DC->isFunctionOrMethod() && VarName->isPlaceholder();
906 if (!Previous.empty()) {
907 if (IsPlaceholder) {
908 bool sameDC = (Previous.end() - 1)
909 ->getDeclContext()
910 ->getRedeclContext()
911 ->Equals(DC: DC->getRedeclContext());
912 if (sameDC &&
913 isDeclInScope(D: *(Previous.end() - 1), Ctx: CurContext, S, AllowInlineNamespace: false)) {
914 Previous.clear();
915 DiagPlaceholderVariableDefinition(Loc: B.NameLoc);
916 }
917 } else {
918 auto *Old = Previous.getRepresentativeDecl();
919 Diag(Loc: B.NameLoc, DiagID: diag::err_redefinition) << B.Name;
920 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_definition);
921 }
922 } else if (ShadowedDecl && !D.isRedeclaration()) {
923 CheckShadow(D: BD, ShadowedDecl, R: Previous);
924 }
925 PushOnScopeChains(D: BD, S, AddToContext: true);
926 Bindings.push_back(Elt: BD);
927 ParsingInitForAutoVars.insert(Ptr: BD);
928 }
929
930 // There are no prior lookup results for the variable itself, because it
931 // is unnamed.
932 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
933 Decomp.getLSquareLoc());
934 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
935 RedeclarationKind::ForVisibleRedeclaration);
936
937 // Build the variable that holds the non-decomposed object.
938 bool AddToScope = true;
939 NamedDecl *New =
940 ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
941 TemplateParamLists: MultiTemplateParamsArg(), AddToScope, Bindings);
942 if (AddToScope) {
943 S->AddDecl(D: New);
944 CurContext->addHiddenDecl(D: New);
945 }
946
947 if (OpenMP().isInOpenMPDeclareTargetContext())
948 OpenMP().checkDeclIsAllowedInOpenMPTarget(E: nullptr, D: New);
949
950 return New;
951}
952
953// Check the arity of the structured bindings.
954// Create the resolved pack expr if needed.
955static bool CheckBindingsCount(Sema &S, DecompositionDecl *DD,
956 QualType DecompType,
957 ArrayRef<BindingDecl *> Bindings,
958 unsigned MemberCount) {
959 auto BindingWithPackItr = llvm::find_if(
960 Range&: Bindings, P: [](BindingDecl *D) -> bool { return D->isParameterPack(); });
961 bool HasPack = BindingWithPackItr != Bindings.end();
962 bool IsValid;
963 if (!HasPack) {
964 IsValid = Bindings.size() == MemberCount;
965 } else {
966 // There may not be more members than non-pack bindings.
967 IsValid = MemberCount >= Bindings.size() - 1;
968 }
969
970 if (IsValid && HasPack) {
971 // Create the pack expr and assign it to the binding.
972 unsigned PackSize = MemberCount - Bindings.size() + 1;
973
974 BindingDecl *BPack = *BindingWithPackItr;
975 BPack->setDecomposedDecl(DD);
976 SmallVector<ValueDecl *, 8> NestedBDs(PackSize);
977 // Create the nested BindingDecls.
978 for (unsigned I = 0; I < PackSize; ++I) {
979 BindingDecl *NestedBD = BindingDecl::Create(
980 C&: S.Context, DC: BPack->getDeclContext(), IdLoc: BPack->getLocation(),
981 Id: BPack->getIdentifier(), T: QualType());
982 NestedBD->setDecomposedDecl(DD);
983 NestedBDs[I] = NestedBD;
984 }
985
986 QualType PackType = S.Context.getPackExpansionType(
987 Pattern: S.Context.DependentTy, NumExpansions: PackSize, /*ExpectsPackInType=*/ExpectPackInType: false);
988 auto *PackExpr = FunctionParmPackExpr::Create(
989 Context: S.Context, T: PackType, ParamPack: BPack, NameLoc: BPack->getBeginLoc(), Params: NestedBDs);
990 BPack->setBinding(DeclaredType: PackType, Binding: PackExpr);
991 }
992
993 if (IsValid)
994 return false;
995
996 S.Diag(Loc: DD->getLocation(), DiagID: diag::err_decomp_decl_wrong_number_bindings)
997 << DecompType << (unsigned)Bindings.size() << MemberCount << MemberCount
998 << (MemberCount < Bindings.size());
999 return true;
1000}
1001
1002static bool checkSimpleDecomposition(
1003 Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
1004 QualType DecompType, const llvm::APSInt &NumElemsAPS, QualType ElemType,
1005 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
1006 unsigned NumElems = (unsigned)NumElemsAPS.getLimitedValue(UINT_MAX);
1007 auto *DD = cast<DecompositionDecl>(Val: Src);
1008
1009 if (CheckBindingsCount(S, DD, DecompType, Bindings, MemberCount: NumElems))
1010 return true;
1011
1012 unsigned I = 0;
1013 for (auto *B : DD->flat_bindings()) {
1014 SourceLocation Loc = B->getLocation();
1015 ExprResult E = S.BuildDeclRefExpr(D: Src, Ty: DecompType, VK: VK_LValue, Loc);
1016 if (E.isInvalid())
1017 return true;
1018 E = GetInit(Loc, E.get(), I++);
1019 if (E.isInvalid())
1020 return true;
1021 B->setBinding(DeclaredType: ElemType, Binding: E.get());
1022 }
1023
1024 return false;
1025}
1026
1027static bool checkArrayLikeDecomposition(Sema &S,
1028 ArrayRef<BindingDecl *> Bindings,
1029 ValueDecl *Src, QualType DecompType,
1030 const llvm::APSInt &NumElems,
1031 QualType ElemType) {
1032 return checkSimpleDecomposition(
1033 S, Bindings, Src, DecompType, NumElemsAPS: NumElems, ElemType,
1034 GetInit: [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
1035 ExprResult E = S.ActOnIntegerConstant(Loc, Val: I);
1036 if (E.isInvalid())
1037 return ExprError();
1038 return S.CreateBuiltinArraySubscriptExpr(Base, LLoc: Loc, Idx: E.get(), RLoc: Loc);
1039 });
1040}
1041
1042static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1043 ValueDecl *Src, QualType DecompType,
1044 const ConstantArrayType *CAT) {
1045 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
1046 NumElems: llvm::APSInt(CAT->getSize()),
1047 ElemType: CAT->getElementType());
1048}
1049
1050static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1051 ValueDecl *Src, QualType DecompType,
1052 const VectorType *VT) {
1053 return checkArrayLikeDecomposition(
1054 S, Bindings, Src, DecompType, NumElems: llvm::APSInt::get(X: VT->getNumElements()),
1055 ElemType: S.Context.getQualifiedType(T: VT->getElementType(),
1056 Qs: DecompType.getQualifiers()));
1057}
1058
1059static bool checkComplexDecomposition(Sema &S,
1060 ArrayRef<BindingDecl *> Bindings,
1061 ValueDecl *Src, QualType DecompType,
1062 const ComplexType *CT) {
1063 return checkSimpleDecomposition(
1064 S, Bindings, Src, DecompType, NumElemsAPS: llvm::APSInt::get(X: 2),
1065 ElemType: S.Context.getQualifiedType(T: CT->getElementType(),
1066 Qs: DecompType.getQualifiers()),
1067 GetInit: [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
1068 return S.CreateBuiltinUnaryOp(OpLoc: Loc, Opc: I ? UO_Imag : UO_Real, InputExpr: Base);
1069 });
1070}
1071
1072static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
1073 TemplateArgumentListInfo &Args,
1074 const TemplateParameterList *Params) {
1075 SmallString<128> SS;
1076 llvm::raw_svector_ostream OS(SS);
1077 bool First = true;
1078 unsigned I = 0;
1079 for (auto &Arg : Args.arguments()) {
1080 if (!First)
1081 OS << ", ";
1082 Arg.getArgument().print(Policy: PrintingPolicy, Out&: OS,
1083 IncludeType: TemplateParameterList::shouldIncludeTypeForArgument(
1084 Policy: PrintingPolicy, TPL: Params, Idx: I));
1085 First = false;
1086 I++;
1087 }
1088 return std::string(OS.str());
1089}
1090
1091static QualType getStdTrait(Sema &S, SourceLocation Loc, StringRef Trait,
1092 TemplateArgumentListInfo &Args, unsigned DiagID) {
1093 auto DiagnoseMissing = [&] {
1094 if (DiagID)
1095 S.Diag(Loc, DiagID) << printTemplateArgs(PrintingPolicy: S.Context.getPrintingPolicy(),
1096 Args, /*Params*/ nullptr);
1097 return QualType();
1098 };
1099
1100 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
1101 NamespaceDecl *Std = S.getStdNamespace();
1102 if (!Std)
1103 return DiagnoseMissing();
1104
1105 // Look up the trait itself, within namespace std. We can diagnose various
1106 // problems with this lookup even if we've been asked to not diagnose a
1107 // missing specialization, because this can only fail if the user has been
1108 // declaring their own names in namespace std or we don't support the
1109 // standard library implementation in use.
1110 LookupResult Result(S, &S.PP.getIdentifierTable().get(Name: Trait), Loc,
1111 Sema::LookupOrdinaryName);
1112 if (!S.LookupQualifiedName(R&: Result, LookupCtx: Std))
1113 return DiagnoseMissing();
1114 if (Result.isAmbiguous())
1115 return QualType();
1116
1117 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
1118 if (!TraitTD) {
1119 Result.suppressDiagnostics();
1120 NamedDecl *Found = *Result.begin();
1121 S.Diag(Loc, DiagID: diag::err_std_type_trait_not_class_template) << Trait;
1122 S.Diag(Loc: Found->getLocation(), DiagID: diag::note_declared_at);
1123 return QualType();
1124 }
1125
1126 // Build the template-id.
1127 QualType TraitTy = S.CheckTemplateIdType(
1128 Keyword: ElaboratedTypeKeyword::None, Template: TemplateName(TraitTD), TemplateLoc: Loc, TemplateArgs&: Args,
1129 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
1130 if (TraitTy.isNull())
1131 return QualType();
1132
1133 if (!S.isCompleteType(Loc, T: TraitTy)) {
1134 if (DiagID)
1135 S.RequireCompleteType(
1136 Loc, T: TraitTy, DiagID,
1137 Args: printTemplateArgs(PrintingPolicy: S.Context.getPrintingPolicy(), Args,
1138 Params: TraitTD->getTemplateParameters()));
1139 return QualType();
1140 }
1141 return TraitTy;
1142}
1143
1144static bool lookupMember(Sema &S, CXXRecordDecl *RD,
1145 LookupResult &MemberLookup) {
1146 assert(RD && "specialization of class template is not a class?");
1147 S.LookupQualifiedName(R&: MemberLookup, LookupCtx: RD);
1148 return MemberLookup.isAmbiguous();
1149}
1150
1151static TemplateArgumentLoc
1152getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
1153 uint64_t I) {
1154 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(Value: I, Type: T), T);
1155 return S.getTrivialTemplateArgumentLoc(Arg, NTTPType: T, Loc);
1156}
1157
1158static TemplateArgumentLoc
1159getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
1160 return S.getTrivialTemplateArgumentLoc(Arg: TemplateArgument(T), NTTPType: QualType(), Loc);
1161}
1162
1163namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1164
1165static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1166 unsigned &OutSize) {
1167 EnterExpressionEvaluationContext ContextRAII(
1168 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1169
1170 // Form template argument list for tuple_size<T>.
1171 TemplateArgumentListInfo Args(Loc, Loc);
1172 Args.addArgument(Loc: getTrivialTypeTemplateArgument(S, Loc, T));
1173
1174 QualType TraitTy = getStdTrait(S, Loc, Trait: "tuple_size", Args, /*DiagID=*/0);
1175 if (TraitTy.isNull())
1176 return IsTupleLike::NotTupleLike;
1177
1178 DeclarationName Value = S.PP.getIdentifierInfo(Name: "value");
1179 LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
1180
1181 // If there's no tuple_size specialization or the lookup of 'value' is empty,
1182 // it's not tuple-like.
1183 if (lookupMember(S, RD: TraitTy->getAsCXXRecordDecl(), MemberLookup&: R) || R.empty())
1184 return IsTupleLike::NotTupleLike;
1185
1186 // If we get this far, we've committed to the tuple interpretation, but
1187 // we can still fail if there actually isn't a usable ::value.
1188
1189 struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1190 LookupResult &R;
1191 TemplateArgumentListInfo &Args;
1192 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1193 : R(R), Args(Args) {}
1194 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
1195 SourceLocation Loc) override {
1196 return S.Diag(Loc, DiagID: diag::err_decomp_decl_std_tuple_size_not_constant)
1197 << printTemplateArgs(PrintingPolicy: S.Context.getPrintingPolicy(), Args,
1198 /*Params*/ nullptr);
1199 }
1200 } Diagnoser(R, Args);
1201
1202 ExprResult E =
1203 S.BuildDeclarationNameExpr(SS: CXXScopeSpec(), R, /*NeedsADL*/false);
1204 if (E.isInvalid())
1205 return IsTupleLike::Error;
1206
1207 llvm::APSInt Size;
1208 E = S.VerifyIntegerConstantExpression(E: E.get(), Result: &Size, Diagnoser);
1209 if (E.isInvalid())
1210 return IsTupleLike::Error;
1211
1212 // The implementation limit is UINT_MAX-1, to allow this to be passed down on
1213 // an UnsignedOrNone.
1214 if (Size < 0 || Size >= UINT_MAX) {
1215 llvm::SmallVector<char, 16> Str;
1216 Size.toString(Str);
1217 S.Diag(Loc, DiagID: diag::err_decomp_decl_std_tuple_size_invalid)
1218 << printTemplateArgs(PrintingPolicy: S.Context.getPrintingPolicy(), Args,
1219 /*Params=*/nullptr)
1220 << StringRef(Str.data(), Str.size());
1221 return IsTupleLike::Error;
1222 }
1223
1224 OutSize = Size.getExtValue();
1225 return IsTupleLike::TupleLike;
1226}
1227
1228/// \return std::tuple_element<I, T>::type.
1229static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1230 unsigned I, QualType T) {
1231 // Form template argument list for tuple_element<I, T>.
1232 TemplateArgumentListInfo Args(Loc, Loc);
1233 Args.addArgument(
1234 Loc: getTrivialIntegralTemplateArgument(S, Loc, T: S.Context.getSizeType(), I));
1235 Args.addArgument(Loc: getTrivialTypeTemplateArgument(S, Loc, T));
1236
1237 QualType TraitTy =
1238 getStdTrait(S, Loc, Trait: "tuple_element", Args,
1239 DiagID: diag::err_decomp_decl_std_tuple_element_not_specialized);
1240 if (TraitTy.isNull())
1241 return QualType();
1242
1243 DeclarationName TypeDN = S.PP.getIdentifierInfo(Name: "type");
1244 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1245 if (lookupMember(S, RD: TraitTy->getAsCXXRecordDecl(), MemberLookup&: R))
1246 return QualType();
1247
1248 auto *TD = R.getAsSingle<TypeDecl>();
1249 if (!TD) {
1250 R.suppressDiagnostics();
1251 S.Diag(Loc, DiagID: diag::err_decomp_decl_std_tuple_element_not_specialized)
1252 << printTemplateArgs(PrintingPolicy: S.Context.getPrintingPolicy(), Args,
1253 /*Params*/ nullptr);
1254 if (!R.empty())
1255 S.Diag(Loc: R.getRepresentativeDecl()->getLocation(), DiagID: diag::note_declared_at);
1256 return QualType();
1257 }
1258
1259 NestedNameSpecifier Qualifier(TraitTy.getTypePtr());
1260 return S.Context.getTypeDeclType(Keyword: ElaboratedTypeKeyword::None, Qualifier, Decl: TD);
1261}
1262
1263namespace {
1264struct InitializingBinding {
1265 Sema &S;
1266 InitializingBinding(Sema &S, BindingDecl *BD) : S(S) {
1267 Sema::CodeSynthesisContext Ctx;
1268 Ctx.Kind = Sema::CodeSynthesisContext::InitializingStructuredBinding;
1269 Ctx.PointOfInstantiation = BD->getLocation();
1270 Ctx.Entity = BD;
1271 S.pushCodeSynthesisContext(Ctx);
1272 }
1273 ~InitializingBinding() {
1274 S.popCodeSynthesisContext();
1275 }
1276};
1277}
1278
1279static bool checkTupleLikeDecomposition(Sema &S,
1280 ArrayRef<BindingDecl *> Bindings,
1281 VarDecl *Src, QualType DecompType,
1282 unsigned NumElems) {
1283 auto *DD = cast<DecompositionDecl>(Val: Src);
1284 if (CheckBindingsCount(S, DD, DecompType, Bindings, MemberCount: NumElems))
1285 return true;
1286
1287 if (Bindings.empty())
1288 return false;
1289
1290 DeclarationName GetDN = S.PP.getIdentifierInfo(Name: "get");
1291
1292 // [dcl.decomp]p3:
1293 // The unqualified-id get is looked up in the scope of E by class member
1294 // access lookup ...
1295 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1296 bool UseMemberGet = false;
1297 if (S.isCompleteType(Loc: Src->getLocation(), T: DecompType)) {
1298 if (auto *RD = DecompType->getAsCXXRecordDecl())
1299 S.LookupQualifiedName(R&: MemberGet, LookupCtx: RD);
1300 if (MemberGet.isAmbiguous())
1301 return true;
1302 // ... and if that finds at least one declaration that is a function
1303 // template whose first template parameter is a non-type parameter ...
1304 for (NamedDecl *D : MemberGet) {
1305 if (FunctionTemplateDecl *FTD =
1306 dyn_cast<FunctionTemplateDecl>(Val: D->getUnderlyingDecl())) {
1307 TemplateParameterList *TPL = FTD->getTemplateParameters();
1308 if (TPL->size() != 0 &&
1309 isa<NonTypeTemplateParmDecl>(Val: TPL->getParam(Idx: 0))) {
1310 // ... the initializer is e.get<i>().
1311 UseMemberGet = true;
1312 break;
1313 }
1314 }
1315 }
1316 }
1317
1318 unsigned I = 0;
1319 for (auto *B : DD->flat_bindings()) {
1320 InitializingBinding InitContext(S, B);
1321 SourceLocation Loc = B->getLocation();
1322
1323 ExprResult E = S.BuildDeclRefExpr(D: Src, Ty: DecompType, VK: VK_LValue, Loc);
1324 if (E.isInvalid())
1325 return true;
1326
1327 // e is an lvalue if the type of the entity is an lvalue reference and
1328 // an xvalue otherwise
1329 if (!Src->getType()->isLValueReferenceType())
1330 E = ImplicitCastExpr::Create(Context: S.Context, T: E.get()->getType(), Kind: CK_NoOp,
1331 Operand: E.get(), BasePath: nullptr, Cat: VK_XValue,
1332 FPO: FPOptionsOverride());
1333
1334 TemplateArgumentListInfo Args(Loc, Loc);
1335 Args.addArgument(
1336 Loc: getTrivialIntegralTemplateArgument(S, Loc, T: S.Context.getSizeType(), I));
1337
1338 if (UseMemberGet) {
1339 // if [lookup of member get] finds at least one declaration, the
1340 // initializer is e.get<i-1>().
1341 E = S.BuildMemberReferenceExpr(Base: E.get(), BaseType: DecompType, OpLoc: Loc, IsArrow: false,
1342 SS: CXXScopeSpec(), TemplateKWLoc: SourceLocation(), FirstQualifierInScope: nullptr,
1343 R&: MemberGet, TemplateArgs: &Args, S: nullptr);
1344 if (E.isInvalid())
1345 return true;
1346
1347 E = S.BuildCallExpr(S: nullptr, Fn: E.get(), LParenLoc: Loc, ArgExprs: {}, RParenLoc: Loc);
1348 } else {
1349 // Otherwise, the initializer is get<i-1>(e), where get is looked up
1350 // in the associated namespaces.
1351 Expr *Get = UnresolvedLookupExpr::Create(
1352 Context: S.Context, NamingClass: nullptr, QualifierLoc: NestedNameSpecifierLoc(), TemplateKWLoc: SourceLocation(),
1353 NameInfo: DeclarationNameInfo(GetDN, Loc), /*RequiresADL=*/true, Args: &Args,
1354 Begin: UnresolvedSetIterator(), End: UnresolvedSetIterator(),
1355 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
1356
1357 Expr *Arg = E.get();
1358 E = S.BuildCallExpr(S: nullptr, Fn: Get, LParenLoc: Loc, ArgExprs: Arg, RParenLoc: Loc);
1359 }
1360 if (E.isInvalid())
1361 return true;
1362 Expr *Init = E.get();
1363
1364 // Given the type T designated by std::tuple_element<i - 1, E>::type,
1365 QualType T = getTupleLikeElementType(S, Loc, I, T: DecompType);
1366 if (T.isNull())
1367 return true;
1368
1369 // each vi is a variable of type "reference to T" initialized with the
1370 // initializer, where the reference is an lvalue reference if the
1371 // initializer is an lvalue and an rvalue reference otherwise
1372 QualType RefType =
1373 S.BuildReferenceType(T, LValueRef: E.get()->isLValue(), Loc, Entity: B->getDeclName());
1374 if (RefType.isNull())
1375 return true;
1376
1377 // Don't give this VarDecl a TypeSourceInfo, since this is a synthesized
1378 // entity and this type was never written in source code.
1379 auto *RefVD =
1380 VarDecl::Create(C&: S.Context, DC: Src->getDeclContext(), StartLoc: Loc, IdLoc: Loc,
1381 Id: B->getDeclName().getAsIdentifierInfo(), T: RefType,
1382 /*TInfo=*/nullptr, S: Src->getStorageClass());
1383 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1384 RefVD->setTSCSpec(Src->getTSCSpec());
1385 RefVD->setImplicit();
1386 if (Src->isInlineSpecified())
1387 RefVD->setInlineSpecified();
1388 RefVD->getLexicalDeclContext()->addHiddenDecl(D: RefVD);
1389
1390 InitializedEntity Entity = InitializedEntity::InitializeBinding(Binding: RefVD);
1391 InitializationKind Kind = InitializationKind::CreateCopy(InitLoc: Loc, EqualLoc: Loc);
1392 InitializationSequence Seq(S, Entity, Kind, Init);
1393 E = Seq.Perform(S, Entity, Kind, Args: Init);
1394 if (E.isInvalid())
1395 return true;
1396 E = S.ActOnFinishFullExpr(Expr: E.get(), CC: Loc, /*DiscardedValue*/ false);
1397 if (E.isInvalid())
1398 return true;
1399 RefVD->setInit(E.get());
1400 S.CheckCompleteVariableDeclaration(VD: RefVD);
1401
1402 E = S.BuildDeclarationNameExpr(SS: CXXScopeSpec(),
1403 NameInfo: DeclarationNameInfo(B->getDeclName(), Loc),
1404 D: RefVD);
1405 if (E.isInvalid())
1406 return true;
1407
1408 B->setBinding(DeclaredType: T, Binding: E.get());
1409 I++;
1410 }
1411
1412 return false;
1413}
1414
1415/// Find the base class to decompose in a built-in decomposition of a class type.
1416/// This base class search is, unfortunately, not quite like any other that we
1417/// perform anywhere else in C++.
1418static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc,
1419 const CXXRecordDecl *RD,
1420 CXXCastPath &BasePath) {
1421 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1422 CXXBasePath &Path) {
1423 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1424 };
1425
1426 const CXXRecordDecl *ClassWithFields = nullptr;
1427 AccessSpecifier AS = AS_public;
1428 if (RD->hasDirectFields())
1429 // [dcl.decomp]p4:
1430 // Otherwise, all of E's non-static data members shall be public direct
1431 // members of E ...
1432 ClassWithFields = RD;
1433 else {
1434 // ... or of ...
1435 CXXBasePaths Paths;
1436 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1437 if (!RD->lookupInBases(BaseMatches: BaseHasFields, Paths)) {
1438 // If no classes have fields, just decompose RD itself. (This will work
1439 // if and only if zero bindings were provided.)
1440 return DeclAccessPair::make(D: const_cast<CXXRecordDecl*>(RD), AS: AS_public);
1441 }
1442
1443 CXXBasePath *BestPath = nullptr;
1444 for (auto &P : Paths) {
1445 if (!BestPath)
1446 BestPath = &P;
1447 else if (!S.Context.hasSameType(T1: P.back().Base->getType(),
1448 T2: BestPath->back().Base->getType())) {
1449 // ... the same ...
1450 S.Diag(Loc, DiagID: diag::err_decomp_decl_multiple_bases_with_members)
1451 << false << RD << BestPath->back().Base->getType()
1452 << P.back().Base->getType();
1453 return DeclAccessPair();
1454 } else if (P.Access < BestPath->Access) {
1455 BestPath = &P;
1456 }
1457 }
1458
1459 // ... unambiguous ...
1460 QualType BaseType = BestPath->back().Base->getType();
1461 if (Paths.isAmbiguous(BaseType: S.Context.getCanonicalType(T: BaseType))) {
1462 S.Diag(Loc, DiagID: diag::err_decomp_decl_ambiguous_base)
1463 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1464 return DeclAccessPair();
1465 }
1466
1467 // ... [accessible, implied by other rules] base class of E.
1468 S.CheckBaseClassAccess(AccessLoc: Loc, Base: BaseType, Derived: S.Context.getCanonicalTagType(TD: RD),
1469 Path: *BestPath, DiagID: diag::err_decomp_decl_inaccessible_base);
1470 AS = BestPath->Access;
1471
1472 ClassWithFields = BaseType->getAsCXXRecordDecl();
1473 S.BuildBasePathArray(Paths, BasePath);
1474 }
1475
1476 // The above search did not check whether the selected class itself has base
1477 // classes with fields, so check that now.
1478 CXXBasePaths Paths;
1479 if (ClassWithFields->lookupInBases(BaseMatches: BaseHasFields, Paths)) {
1480 S.Diag(Loc, DiagID: diag::err_decomp_decl_multiple_bases_with_members)
1481 << (ClassWithFields == RD) << RD << ClassWithFields
1482 << Paths.front().back().Base->getType();
1483 return DeclAccessPair();
1484 }
1485
1486 return DeclAccessPair::make(D: const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1487}
1488
1489static bool CheckMemberDecompositionFields(Sema &S, SourceLocation Loc,
1490 const CXXRecordDecl *OrigRD,
1491 QualType DecompType,
1492 DeclAccessPair BasePair) {
1493 const auto *RD = cast_or_null<CXXRecordDecl>(Val: BasePair.getDecl());
1494 if (!RD)
1495 return true;
1496
1497 for (auto *FD : RD->fields()) {
1498 if (FD->isUnnamedBitField())
1499 continue;
1500
1501 // All the non-static data members are required to be nameable, so they
1502 // must all have names.
1503 if (!FD->getDeclName()) {
1504 if (RD->isLambda()) {
1505 S.Diag(Loc, DiagID: diag::err_decomp_decl_lambda);
1506 S.Diag(Loc: RD->getLocation(), DiagID: diag::note_lambda_decl);
1507 return true;
1508 }
1509
1510 if (FD->isAnonymousStructOrUnion()) {
1511 S.Diag(Loc, DiagID: diag::err_decomp_decl_anon_union_member)
1512 << DecompType << FD->getType()->isUnionType();
1513 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_declared_at);
1514 return true;
1515 }
1516
1517 // FIXME: Are there any other ways we could have an anonymous member?
1518 }
1519 // The field must be accessible in the context of the structured binding.
1520 // We already checked that the base class is accessible.
1521 // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1522 // const_cast here.
1523 S.CheckStructuredBindingMemberAccess(
1524 UseLoc: Loc, DecomposedClass: const_cast<CXXRecordDecl *>(OrigRD),
1525 Field: DeclAccessPair::make(D: FD, AS: CXXRecordDecl::MergeAccess(
1526 PathAccess: BasePair.getAccess(), DeclAccess: FD->getAccess())));
1527 }
1528 return false;
1529}
1530
1531static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1532 ValueDecl *Src, QualType DecompType,
1533 const CXXRecordDecl *OrigRD) {
1534 if (S.RequireCompleteType(Loc: Src->getLocation(), T: DecompType,
1535 DiagID: diag::err_incomplete_type))
1536 return true;
1537
1538 CXXCastPath BasePath;
1539 DeclAccessPair BasePair =
1540 findDecomposableBaseClass(S, Loc: Src->getLocation(), RD: OrigRD, BasePath);
1541 const auto *RD = cast_or_null<CXXRecordDecl>(Val: BasePair.getDecl());
1542 if (!RD)
1543 return true;
1544 QualType BaseType = S.Context.getQualifiedType(
1545 T: S.Context.getCanonicalTagType(TD: RD), Qs: DecompType.getQualifiers());
1546
1547 auto *DD = cast<DecompositionDecl>(Val: Src);
1548 unsigned NumFields = llvm::count_if(
1549 Range: RD->fields(), P: [](FieldDecl *FD) { return !FD->isUnnamedBitField(); });
1550 if (CheckBindingsCount(S, DD, DecompType, Bindings, MemberCount: NumFields))
1551 return true;
1552
1553 // all of E's non-static data members shall be [...] well-formed
1554 // when named as e.name in the context of the structured binding,
1555 // E shall not have an anonymous union member, ...
1556 auto FlatBindings = DD->flat_bindings();
1557 assert(llvm::range_size(FlatBindings) == NumFields);
1558 auto FlatBindingsItr = FlatBindings.begin();
1559
1560 if (CheckMemberDecompositionFields(S, Loc: Src->getLocation(), OrigRD, DecompType,
1561 BasePair))
1562 return true;
1563
1564 for (auto *FD : RD->fields()) {
1565 if (FD->isUnnamedBitField())
1566 continue;
1567
1568 // We have a real field to bind.
1569 assert(FlatBindingsItr != FlatBindings.end());
1570 BindingDecl *B = *(FlatBindingsItr++);
1571 SourceLocation Loc = B->getLocation();
1572
1573 // Initialize the binding to Src.FD.
1574 ExprResult E = S.BuildDeclRefExpr(D: Src, Ty: DecompType, VK: VK_LValue, Loc);
1575 if (E.isInvalid())
1576 return true;
1577 E = S.ImpCastExprToType(E: E.get(), Type: BaseType, CK: CK_UncheckedDerivedToBase,
1578 VK: VK_LValue, BasePath: &BasePath);
1579 if (E.isInvalid())
1580 return true;
1581 E = S.BuildFieldReferenceExpr(BaseExpr: E.get(), /*IsArrow*/ false, OpLoc: Loc,
1582 SS: CXXScopeSpec(), Field: FD,
1583 FoundDecl: DeclAccessPair::make(D: FD, AS: FD->getAccess()),
1584 MemberNameInfo: DeclarationNameInfo(FD->getDeclName(), Loc));
1585 if (E.isInvalid())
1586 return true;
1587
1588 // If the type of the member is T, the referenced type is cv T, where cv is
1589 // the cv-qualification of the decomposition expression.
1590 //
1591 // FIXME: We resolve a defect here: if the field is mutable, we do not add
1592 // 'const' to the type of the field.
1593 Qualifiers Q = DecompType.getQualifiers();
1594 if (FD->isMutable())
1595 Q.removeConst();
1596 B->setBinding(DeclaredType: S.BuildQualifiedType(T: FD->getType(), Loc, Qs: Q), Binding: E.get());
1597 }
1598
1599 return false;
1600}
1601
1602void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
1603 QualType DecompType = DD->getType();
1604
1605 // If the type of the decomposition is dependent, then so is the type of
1606 // each binding.
1607 if (DecompType->isDependentType()) {
1608 // Note that all of the types are still Null or PackExpansionType.
1609 for (auto *B : DD->bindings()) {
1610 // Do not overwrite any pack type.
1611 if (B->getType().isNull())
1612 B->setType(Context.DependentTy);
1613 }
1614 return;
1615 }
1616
1617 DecompType = DecompType.getNonReferenceType();
1618 ArrayRef<BindingDecl*> Bindings = DD->bindings();
1619
1620 // C++1z [dcl.decomp]/2:
1621 // If E is an array type [...]
1622 // As an extension, we also support decomposition of built-in complex and
1623 // vector types.
1624 if (auto *CAT = Context.getAsConstantArrayType(T: DecompType)) {
1625 if (checkArrayDecomposition(S&: *this, Bindings, Src: DD, DecompType, CAT))
1626 DD->setInvalidDecl();
1627 return;
1628 }
1629 if (auto *VT = DecompType->getAs<VectorType>()) {
1630 if (checkVectorDecomposition(S&: *this, Bindings, Src: DD, DecompType, VT))
1631 DD->setInvalidDecl();
1632 return;
1633 }
1634 if (auto *CT = DecompType->getAs<ComplexType>()) {
1635 if (checkComplexDecomposition(S&: *this, Bindings, Src: DD, DecompType, CT))
1636 DD->setInvalidDecl();
1637 return;
1638 }
1639
1640 // C++1z [dcl.decomp]/3:
1641 // if the expression std::tuple_size<E>::value is a well-formed integral
1642 // constant expression, [...]
1643 unsigned TupleSize;
1644 switch (isTupleLike(S&: *this, Loc: DD->getLocation(), T: DecompType, OutSize&: TupleSize)) {
1645 case IsTupleLike::Error:
1646 DD->setInvalidDecl();
1647 return;
1648
1649 case IsTupleLike::TupleLike:
1650 if (checkTupleLikeDecomposition(S&: *this, Bindings, Src: DD, DecompType, NumElems: TupleSize))
1651 DD->setInvalidDecl();
1652 return;
1653
1654 case IsTupleLike::NotTupleLike:
1655 break;
1656 }
1657
1658 // C++1z [dcl.dcl]/8:
1659 // [E shall be of array or non-union class type]
1660 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1661 if (!RD || RD->isUnion()) {
1662 Diag(Loc: DD->getLocation(), DiagID: diag::err_decomp_decl_unbindable_type)
1663 << DD << !RD << DecompType;
1664 DD->setInvalidDecl();
1665 return;
1666 }
1667
1668 // C++1z [dcl.decomp]/4:
1669 // all of E's non-static data members shall be [...] direct members of
1670 // E or of the same unambiguous public base class of E, ...
1671 if (checkMemberDecomposition(S&: *this, Bindings, Src: DD, DecompType, OrigRD: RD))
1672 DD->setInvalidDecl();
1673}
1674
1675UnsignedOrNone Sema::GetDecompositionElementCount(QualType T,
1676 SourceLocation Loc) {
1677 const ASTContext &Ctx = getASTContext();
1678 assert(!T->isDependentType());
1679
1680 Qualifiers Quals;
1681 QualType Unqual = Context.getUnqualifiedArrayType(T, Quals);
1682 Quals.removeCVRQualifiers();
1683 T = Context.getQualifiedType(T: Unqual, Qs: Quals);
1684
1685 if (auto *CAT = Ctx.getAsConstantArrayType(T))
1686 return static_cast<unsigned>(CAT->getSize().getZExtValue());
1687 if (auto *VT = T->getAs<VectorType>())
1688 return VT->getNumElements();
1689 if (T->getAs<ComplexType>())
1690 return 2u;
1691
1692 unsigned TupleSize;
1693 switch (isTupleLike(S&: *this, Loc, T, OutSize&: TupleSize)) {
1694 case IsTupleLike::Error:
1695 return std::nullopt;
1696 case IsTupleLike::TupleLike:
1697 return TupleSize;
1698 case IsTupleLike::NotTupleLike:
1699 break;
1700 }
1701
1702 const CXXRecordDecl *OrigRD = T->getAsCXXRecordDecl();
1703 if (!OrigRD || OrigRD->isUnion())
1704 return std::nullopt;
1705
1706 if (RequireCompleteType(Loc, T, DiagID: diag::err_incomplete_type))
1707 return std::nullopt;
1708
1709 CXXCastPath BasePath;
1710 DeclAccessPair BasePair =
1711 findDecomposableBaseClass(S&: *this, Loc, RD: OrigRD, BasePath);
1712 const auto *RD = cast_or_null<CXXRecordDecl>(Val: BasePair.getDecl());
1713 if (!RD)
1714 return std::nullopt;
1715
1716 unsigned NumFields = llvm::count_if(
1717 Range: RD->fields(), P: [](FieldDecl *FD) { return !FD->isUnnamedBitField(); });
1718
1719 if (CheckMemberDecompositionFields(S&: *this, Loc, OrigRD, DecompType: T, BasePair))
1720 return std::nullopt;
1721
1722 return NumFields;
1723}
1724
1725void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1726 // Shortcut if exceptions are disabled.
1727 if (!getLangOpts().CXXExceptions)
1728 return;
1729
1730 assert(Context.hasSameType(New->getType(), Old->getType()) &&
1731 "Should only be called if types are otherwise the same.");
1732
1733 QualType NewType = New->getType();
1734 QualType OldType = Old->getType();
1735
1736 // We're only interested in pointers and references to functions, as well
1737 // as pointers to member functions.
1738 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1739 NewType = R->getPointeeType();
1740 OldType = OldType->castAs<ReferenceType>()->getPointeeType();
1741 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1742 NewType = P->getPointeeType();
1743 OldType = OldType->castAs<PointerType>()->getPointeeType();
1744 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1745 NewType = M->getPointeeType();
1746 OldType = OldType->castAs<MemberPointerType>()->getPointeeType();
1747 }
1748
1749 if (!NewType->isFunctionProtoType())
1750 return;
1751
1752 // There's lots of special cases for functions. For function pointers, system
1753 // libraries are hopefully not as broken so that we don't need these
1754 // workarounds.
1755 if (CheckEquivalentExceptionSpec(
1756 Old: OldType->getAs<FunctionProtoType>(), OldLoc: Old->getLocation(),
1757 New: NewType->getAs<FunctionProtoType>(), NewLoc: New->getLocation())) {
1758 New->setInvalidDecl();
1759 }
1760}
1761
1762/// CheckCXXDefaultArguments - Verify that the default arguments for a
1763/// function declaration are well-formed according to C++
1764/// [dcl.fct.default].
1765void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1766 // This checking doesn't make sense for explicit specializations; their
1767 // default arguments are determined by the declaration we're specializing,
1768 // not by FD.
1769 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1770 return;
1771 if (auto *FTD = FD->getDescribedFunctionTemplate())
1772 if (FTD->isMemberSpecialization())
1773 return;
1774
1775 unsigned NumParams = FD->getNumParams();
1776 unsigned ParamIdx = 0;
1777
1778 // Find first parameter with a default argument
1779 for (; ParamIdx < NumParams; ++ParamIdx) {
1780 ParmVarDecl *Param = FD->getParamDecl(i: ParamIdx);
1781 if (Param->hasDefaultArg())
1782 break;
1783 }
1784
1785 // C++20 [dcl.fct.default]p4:
1786 // In a given function declaration, each parameter subsequent to a parameter
1787 // with a default argument shall have a default argument supplied in this or
1788 // a previous declaration, unless the parameter was expanded from a
1789 // parameter pack, or shall be a function parameter pack.
1790 for (++ParamIdx; ParamIdx < NumParams; ++ParamIdx) {
1791 ParmVarDecl *Param = FD->getParamDecl(i: ParamIdx);
1792 if (Param->hasDefaultArg() || Param->isParameterPack() ||
1793 (CurrentInstantiationScope &&
1794 CurrentInstantiationScope->isLocalPackExpansion(D: Param)))
1795 continue;
1796 if (Param->isInvalidDecl())
1797 /* We already complained about this parameter. */;
1798 else if (Param->getIdentifier())
1799 Diag(Loc: Param->getLocation(), DiagID: diag::err_param_default_argument_missing_name)
1800 << Param->getIdentifier();
1801 else
1802 Diag(Loc: Param->getLocation(), DiagID: diag::err_param_default_argument_missing);
1803 }
1804}
1805
1806/// Check that the given type is a literal type. Issue a diagnostic if not,
1807/// if Kind is Diagnose.
1808/// \return \c true if a problem has been found (and optionally diagnosed).
1809template <typename... Ts>
1810static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind,
1811 SourceLocation Loc, QualType T, unsigned DiagID,
1812 Ts &&...DiagArgs) {
1813 if (T->isDependentType())
1814 return false;
1815
1816 switch (Kind) {
1817 case Sema::CheckConstexprKind::Diagnose:
1818 return SemaRef.RequireLiteralType(Loc, T, DiagID,
1819 std::forward<Ts>(DiagArgs)...);
1820
1821 case Sema::CheckConstexprKind::CheckValid:
1822 return !T->isLiteralType(Ctx: SemaRef.Context);
1823 }
1824
1825 llvm_unreachable("unknown CheckConstexprKind");
1826}
1827
1828/// Determine whether a destructor cannot be constexpr due to
1829static bool CheckConstexprDestructorSubobjects(Sema &SemaRef,
1830 const CXXDestructorDecl *DD,
1831 Sema::CheckConstexprKind Kind) {
1832 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1833 "this check is obsolete for C++23");
1834 auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) {
1835 const CXXRecordDecl *RD =
1836 T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1837 if (!RD || RD->hasConstexprDestructor())
1838 return true;
1839
1840 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1841 SemaRef.Diag(Loc: DD->getLocation(), DiagID: diag::err_constexpr_dtor_subobject)
1842 << static_cast<int>(DD->getConstexprKind()) << !FD
1843 << (FD ? FD->getDeclName() : DeclarationName()) << T;
1844 SemaRef.Diag(Loc, DiagID: diag::note_constexpr_dtor_subobject)
1845 << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T;
1846 }
1847 return false;
1848 };
1849
1850 const CXXRecordDecl *RD = DD->getParent();
1851 for (const CXXBaseSpecifier &B : RD->bases())
1852 if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr))
1853 return false;
1854 for (const FieldDecl *FD : RD->fields())
1855 if (!Check(FD->getLocation(), FD->getType(), FD))
1856 return false;
1857 return true;
1858}
1859
1860/// Check whether a function's parameter types are all literal types. If so,
1861/// return true. If not, produce a suitable diagnostic and return false.
1862static bool CheckConstexprParameterTypes(Sema &SemaRef,
1863 const FunctionDecl *FD,
1864 Sema::CheckConstexprKind Kind) {
1865 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1866 "this check is obsolete for C++23");
1867 unsigned ArgIndex = 0;
1868 const auto *FT = FD->getType()->castAs<FunctionProtoType>();
1869 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1870 e = FT->param_type_end();
1871 i != e; ++i, ++ArgIndex) {
1872 const ParmVarDecl *PD = FD->getParamDecl(i: ArgIndex);
1873 assert(PD && "null in a parameter list");
1874 SourceLocation ParamLoc = PD->getLocation();
1875 if (CheckLiteralType(SemaRef, Kind, Loc: ParamLoc, T: *i,
1876 DiagID: diag::err_constexpr_non_literal_param, DiagArgs: ArgIndex + 1,
1877 DiagArgs: PD->getSourceRange(), DiagArgs: isa<CXXConstructorDecl>(Val: FD),
1878 DiagArgs: FD->isConsteval()))
1879 return false;
1880 }
1881 return true;
1882}
1883
1884/// Check whether a function's return type is a literal type. If so, return
1885/// true. If not, produce a suitable diagnostic and return false.
1886static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD,
1887 Sema::CheckConstexprKind Kind) {
1888 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1889 "this check is obsolete for C++23");
1890 if (CheckLiteralType(SemaRef, Kind, Loc: FD->getLocation(), T: FD->getReturnType(),
1891 DiagID: diag::err_constexpr_non_literal_return,
1892 DiagArgs: FD->isConsteval()))
1893 return false;
1894 return true;
1895}
1896
1897/// Get diagnostic %select index for tag kind for
1898/// record diagnostic message.
1899/// WARNING: Indexes apply to particular diagnostics only!
1900///
1901/// \returns diagnostic %select index.
1902static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1903 switch (Tag) {
1904 case TagTypeKind::Struct:
1905 return 0;
1906 case TagTypeKind::Interface:
1907 return 1;
1908 case TagTypeKind::Class:
1909 return 2;
1910 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1911 }
1912}
1913
1914static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
1915 Stmt *Body,
1916 Sema::CheckConstexprKind Kind);
1917static bool CheckConstexprMissingReturn(Sema &SemaRef, const FunctionDecl *Dcl);
1918
1919bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD,
1920 CheckConstexprKind Kind) {
1921 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: NewFD);
1922 if (MD && MD->isInstance()) {
1923 // C++11 [dcl.constexpr]p4:
1924 // The definition of a constexpr constructor shall satisfy the following
1925 // constraints:
1926 // - the class shall not have any virtual base classes;
1927 //
1928 // FIXME: This only applies to constructors and destructors, not arbitrary
1929 // member functions.
1930 const CXXRecordDecl *RD = MD->getParent();
1931 if (RD->getNumVBases()) {
1932 if (Kind == CheckConstexprKind::CheckValid)
1933 return false;
1934
1935 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_constexpr_virtual_base)
1936 << isa<CXXConstructorDecl>(Val: NewFD)
1937 << getRecordDiagFromTagKind(Tag: RD->getTagKind()) << RD->getNumVBases();
1938 for (const auto &I : RD->vbases())
1939 Diag(Loc: I.getBeginLoc(), DiagID: diag::note_constexpr_virtual_base_here)
1940 << I.getSourceRange();
1941 return false;
1942 }
1943 }
1944
1945 if (!isa<CXXConstructorDecl>(Val: NewFD)) {
1946 // C++11 [dcl.constexpr]p3:
1947 // The definition of a constexpr function shall satisfy the following
1948 // constraints:
1949 // - it shall not be virtual; (removed in C++20)
1950 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: NewFD);
1951 if (Method && Method->isVirtual()) {
1952 if (getLangOpts().CPlusPlus20) {
1953 if (Kind == CheckConstexprKind::Diagnose)
1954 Diag(Loc: Method->getLocation(), DiagID: diag::warn_cxx17_compat_constexpr_virtual);
1955 } else {
1956 if (Kind == CheckConstexprKind::CheckValid)
1957 return false;
1958
1959 Method = Method->getCanonicalDecl();
1960 Diag(Loc: Method->getLocation(), DiagID: diag::err_constexpr_virtual);
1961
1962 // If it's not obvious why this function is virtual, find an overridden
1963 // function which uses the 'virtual' keyword.
1964 const CXXMethodDecl *WrittenVirtual = Method;
1965 while (!WrittenVirtual->isVirtualAsWritten())
1966 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1967 if (WrittenVirtual != Method)
1968 Diag(Loc: WrittenVirtual->getLocation(),
1969 DiagID: diag::note_overridden_virtual_function);
1970 return false;
1971 }
1972 }
1973
1974 // - its return type shall be a literal type; (removed in C++23)
1975 if (!getLangOpts().CPlusPlus23 &&
1976 !CheckConstexprReturnType(SemaRef&: *this, FD: NewFD, Kind))
1977 return false;
1978 }
1979
1980 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Val: NewFD)) {
1981 // A destructor can be constexpr only if the defaulted destructor could be;
1982 // we don't need to check the members and bases if we already know they all
1983 // have constexpr destructors. (removed in C++23)
1984 if (!getLangOpts().CPlusPlus23 &&
1985 !Dtor->getParent()->defaultedDestructorIsConstexpr()) {
1986 if (Kind == CheckConstexprKind::CheckValid)
1987 return false;
1988 if (!CheckConstexprDestructorSubobjects(SemaRef&: *this, DD: Dtor, Kind))
1989 return false;
1990 }
1991 }
1992
1993 // - each of its parameter types shall be a literal type; (removed in C++23)
1994 if (!getLangOpts().CPlusPlus23 &&
1995 !CheckConstexprParameterTypes(SemaRef&: *this, FD: NewFD, Kind))
1996 return false;
1997
1998 Stmt *Body = NewFD->getBody();
1999 assert(Body &&
2000 "CheckConstexprFunctionDefinition called on function with no body");
2001 return CheckConstexprFunctionBody(SemaRef&: *this, Dcl: NewFD, Body, Kind);
2002}
2003
2004/// Check the given declaration statement is legal within a constexpr function
2005/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
2006///
2007/// \return true if the body is OK (maybe only as an extension), false if we
2008/// have diagnosed a problem.
2009static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
2010 DeclStmt *DS, SourceLocation &Cxx1yLoc,
2011 Sema::CheckConstexprKind Kind) {
2012 // C++11 [dcl.constexpr]p3 and p4:
2013 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
2014 // contain only
2015 for (const auto *DclIt : DS->decls()) {
2016 switch (DclIt->getKind()) {
2017 case Decl::StaticAssert:
2018 case Decl::Using:
2019 case Decl::UsingShadow:
2020 case Decl::UsingDirective:
2021 case Decl::UnresolvedUsingTypename:
2022 case Decl::UnresolvedUsingValue:
2023 case Decl::UsingEnum:
2024 // - static_assert-declarations
2025 // - using-declarations,
2026 // - using-directives,
2027 // - using-enum-declaration
2028 continue;
2029
2030 case Decl::Typedef:
2031 case Decl::TypeAlias: {
2032 // - typedef declarations and alias-declarations that do not define
2033 // classes or enumerations,
2034 const auto *TN = cast<TypedefNameDecl>(Val: DclIt);
2035 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
2036 // Don't allow variably-modified types in constexpr functions.
2037 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2038 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
2039 SemaRef.Diag(Loc: TL.getBeginLoc(), DiagID: diag::err_constexpr_vla)
2040 << TL.getSourceRange() << TL.getType()
2041 << isa<CXXConstructorDecl>(Val: Dcl);
2042 }
2043 return false;
2044 }
2045 continue;
2046 }
2047
2048 case Decl::Enum:
2049 case Decl::CXXRecord:
2050 // C++1y allows types to be defined, not just declared.
2051 if (cast<TagDecl>(Val: DclIt)->isThisDeclarationADefinition()) {
2052 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2053 SemaRef.DiagCompat(Loc: DS->getBeginLoc(),
2054 CompatDiagId: diag_compat::constexpr_type_definition)
2055 << isa<CXXConstructorDecl>(Val: Dcl);
2056 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
2057 return false;
2058 }
2059 }
2060 continue;
2061
2062 case Decl::EnumConstant:
2063 case Decl::IndirectField:
2064 case Decl::ParmVar:
2065 // These can only appear with other declarations which are banned in
2066 // C++11 and permitted in C++1y, so ignore them.
2067 continue;
2068
2069 case Decl::Var:
2070 case Decl::Decomposition: {
2071 // C++1y [dcl.constexpr]p3 allows anything except:
2072 // a definition of a variable of non-literal type or of static or
2073 // thread storage duration or [before C++2a] for which no
2074 // initialization is performed.
2075 const auto *VD = cast<VarDecl>(Val: DclIt);
2076 if (VD->isThisDeclarationADefinition()) {
2077 if (VD->isStaticLocal()) {
2078 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2079 SemaRef.DiagCompat(Loc: VD->getLocation(),
2080 CompatDiagId: diag_compat::constexpr_static_var)
2081 << isa<CXXConstructorDecl>(Val: Dcl)
2082 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
2083 } else if (!SemaRef.getLangOpts().CPlusPlus23) {
2084 return false;
2085 }
2086 }
2087 if (SemaRef.LangOpts.CPlusPlus23) {
2088 CheckLiteralType(SemaRef, Kind, Loc: VD->getLocation(), T: VD->getType(),
2089 DiagID: diag::warn_cxx20_compat_constexpr_var,
2090 DiagArgs: isa<CXXConstructorDecl>(Val: Dcl));
2091 } else if (CheckLiteralType(
2092 SemaRef, Kind, Loc: VD->getLocation(), T: VD->getType(),
2093 DiagID: diag::err_constexpr_local_var_non_literal_type,
2094 DiagArgs: isa<CXXConstructorDecl>(Val: Dcl))) {
2095 return false;
2096 }
2097 if (!VD->getType()->isDependentType() &&
2098 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
2099 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2100 SemaRef.DiagCompat(Loc: VD->getLocation(),
2101 CompatDiagId: diag_compat::constexpr_local_var_no_init)
2102 << isa<CXXConstructorDecl>(Val: Dcl);
2103 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2104 return false;
2105 }
2106 continue;
2107 }
2108 }
2109 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2110 SemaRef.DiagCompat(Loc: VD->getLocation(), CompatDiagId: diag_compat::constexpr_local_var)
2111 << isa<CXXConstructorDecl>(Val: Dcl);
2112 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
2113 return false;
2114 }
2115 continue;
2116 }
2117
2118 case Decl::NamespaceAlias:
2119 case Decl::Function:
2120 // These are disallowed in C++11 and permitted in C++1y. Allow them
2121 // everywhere as an extension.
2122 if (!Cxx1yLoc.isValid())
2123 Cxx1yLoc = DS->getBeginLoc();
2124 continue;
2125
2126 default:
2127 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2128 SemaRef.Diag(Loc: DS->getBeginLoc(), DiagID: diag::err_constexpr_body_invalid_stmt)
2129 << isa<CXXConstructorDecl>(Val: Dcl) << Dcl->isConsteval();
2130 }
2131 return false;
2132 }
2133 }
2134
2135 return true;
2136}
2137
2138/// Check that the given field is initialized within a constexpr constructor.
2139///
2140/// \param Dcl The constexpr constructor being checked.
2141/// \param Field The field being checked. This may be a member of an anonymous
2142/// struct or union nested within the class being checked.
2143/// \param Inits All declarations, including anonymous struct/union members and
2144/// indirect members, for which any initialization was provided.
2145/// \param Diagnosed Whether we've emitted the error message yet. Used to attach
2146/// multiple notes for different members to the same error.
2147/// \param Kind Whether we're diagnosing a constructor as written or determining
2148/// whether the formal requirements are satisfied.
2149/// \return \c false if we're checking for validity and the constructor does
2150/// not satisfy the requirements on a constexpr constructor.
2151static bool CheckConstexprCtorInitializer(Sema &SemaRef,
2152 const FunctionDecl *Dcl,
2153 FieldDecl *Field,
2154 llvm::SmallPtrSet<Decl *, 16> &Inits,
2155 bool &Diagnosed,
2156 Sema::CheckConstexprKind Kind) {
2157 // In C++20 onwards, there's nothing to check for validity.
2158 if (Kind == Sema::CheckConstexprKind::CheckValid &&
2159 SemaRef.getLangOpts().CPlusPlus20)
2160 return true;
2161
2162 if (Field->isInvalidDecl())
2163 return true;
2164
2165 if (Field->isUnnamedBitField())
2166 return true;
2167
2168 // Anonymous unions with no variant members and empty anonymous structs do not
2169 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
2170 // indirect fields don't need initializing.
2171 if (Field->isAnonymousStructOrUnion() &&
2172 (Field->getType()->isUnionType()
2173 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
2174 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
2175 return true;
2176
2177 if (!Inits.count(Ptr: Field)) {
2178 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2179 if (!Diagnosed) {
2180 SemaRef.DiagCompat(Loc: Dcl->getLocation(),
2181 CompatDiagId: diag_compat::constexpr_ctor_missing_init);
2182 Diagnosed = true;
2183 }
2184 SemaRef.Diag(Loc: Field->getLocation(),
2185 DiagID: diag::note_constexpr_ctor_missing_init);
2186 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2187 return false;
2188 }
2189 } else if (Field->isAnonymousStructOrUnion()) {
2190 const auto *RD = Field->getType()->castAsRecordDecl();
2191 for (auto *I : RD->fields())
2192 // If an anonymous union contains an anonymous struct of which any member
2193 // is initialized, all members must be initialized.
2194 if (!RD->isUnion() || Inits.count(Ptr: I))
2195 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, Field: I, Inits, Diagnosed,
2196 Kind))
2197 return false;
2198 }
2199 return true;
2200}
2201
2202/// Check the provided statement is allowed in a constexpr function
2203/// definition.
2204static bool
2205CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
2206 SmallVectorImpl<SourceLocation> &ReturnStmts,
2207 SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
2208 SourceLocation &Cxx2bLoc,
2209 Sema::CheckConstexprKind Kind) {
2210 // - its function-body shall be [...] a compound-statement that contains only
2211 switch (S->getStmtClass()) {
2212 case Stmt::NullStmtClass:
2213 // - null statements,
2214 return true;
2215
2216 case Stmt::DeclStmtClass:
2217 // - static_assert-declarations
2218 // - using-declarations,
2219 // - using-directives,
2220 // - typedef declarations and alias-declarations that do not define
2221 // classes or enumerations,
2222 if (!CheckConstexprDeclStmt(SemaRef, Dcl, DS: cast<DeclStmt>(Val: S), Cxx1yLoc, Kind))
2223 return false;
2224 return true;
2225
2226 case Stmt::ReturnStmtClass:
2227 // - and exactly one return statement;
2228 if (isa<CXXConstructorDecl>(Val: Dcl)) {
2229 // C++1y allows return statements in constexpr constructors.
2230 if (!Cxx1yLoc.isValid())
2231 Cxx1yLoc = S->getBeginLoc();
2232 return true;
2233 }
2234
2235 ReturnStmts.push_back(Elt: S->getBeginLoc());
2236 return true;
2237
2238 case Stmt::AttributedStmtClass:
2239 // Attributes on a statement don't affect its formal kind and hence don't
2240 // affect its validity in a constexpr function.
2241 return CheckConstexprFunctionStmt(
2242 SemaRef, Dcl, S: cast<AttributedStmt>(Val: S)->getSubStmt(), ReturnStmts,
2243 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind);
2244
2245 case Stmt::CompoundStmtClass: {
2246 // C++1y allows compound-statements.
2247 if (!Cxx1yLoc.isValid())
2248 Cxx1yLoc = S->getBeginLoc();
2249
2250 CompoundStmt *CompStmt = cast<CompoundStmt>(Val: S);
2251 for (auto *BodyIt : CompStmt->body()) {
2252 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, S: BodyIt, ReturnStmts,
2253 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2254 return false;
2255 }
2256 return true;
2257 }
2258
2259 case Stmt::IfStmtClass: {
2260 // C++1y allows if-statements.
2261 if (!Cxx1yLoc.isValid())
2262 Cxx1yLoc = S->getBeginLoc();
2263
2264 IfStmt *If = cast<IfStmt>(Val: S);
2265 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, S: If->getThen(), ReturnStmts,
2266 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2267 return false;
2268 if (If->getElse() &&
2269 !CheckConstexprFunctionStmt(SemaRef, Dcl, S: If->getElse(), ReturnStmts,
2270 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2271 return false;
2272 return true;
2273 }
2274
2275 case Stmt::WhileStmtClass:
2276 case Stmt::DoStmtClass:
2277 case Stmt::ForStmtClass:
2278 case Stmt::CXXForRangeStmtClass:
2279 case Stmt::ContinueStmtClass:
2280 // C++1y allows all of these. We don't allow them as extensions in C++11,
2281 // because they don't make sense without variable mutation.
2282 if (!SemaRef.getLangOpts().CPlusPlus14)
2283 break;
2284 if (!Cxx1yLoc.isValid())
2285 Cxx1yLoc = S->getBeginLoc();
2286 for (Stmt *SubStmt : S->children()) {
2287 if (SubStmt &&
2288 !CheckConstexprFunctionStmt(SemaRef, Dcl, S: SubStmt, ReturnStmts,
2289 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2290 return false;
2291 }
2292 return true;
2293
2294 case Stmt::SwitchStmtClass:
2295 case Stmt::CaseStmtClass:
2296 case Stmt::DefaultStmtClass:
2297 case Stmt::BreakStmtClass:
2298 // C++1y allows switch-statements, and since they don't need variable
2299 // mutation, we can reasonably allow them in C++11 as an extension.
2300 if (!Cxx1yLoc.isValid())
2301 Cxx1yLoc = S->getBeginLoc();
2302 for (Stmt *SubStmt : S->children()) {
2303 if (SubStmt &&
2304 !CheckConstexprFunctionStmt(SemaRef, Dcl, S: SubStmt, ReturnStmts,
2305 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2306 return false;
2307 }
2308 return true;
2309
2310 case Stmt::LabelStmtClass:
2311 case Stmt::GotoStmtClass:
2312 if (Cxx2bLoc.isInvalid())
2313 Cxx2bLoc = S->getBeginLoc();
2314 for (Stmt *SubStmt : S->children()) {
2315 if (SubStmt &&
2316 !CheckConstexprFunctionStmt(SemaRef, Dcl, S: SubStmt, ReturnStmts,
2317 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2318 return false;
2319 }
2320 return true;
2321
2322 case Stmt::GCCAsmStmtClass:
2323 case Stmt::MSAsmStmtClass:
2324 // C++2a allows inline assembly statements.
2325 case Stmt::CXXTryStmtClass:
2326 if (Cxx2aLoc.isInvalid())
2327 Cxx2aLoc = S->getBeginLoc();
2328 for (Stmt *SubStmt : S->children()) {
2329 if (SubStmt &&
2330 !CheckConstexprFunctionStmt(SemaRef, Dcl, S: SubStmt, ReturnStmts,
2331 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2332 return false;
2333 }
2334 return true;
2335
2336 case Stmt::CXXCatchStmtClass:
2337 // Do not bother checking the language mode (already covered by the
2338 // try block check).
2339 if (!CheckConstexprFunctionStmt(
2340 SemaRef, Dcl, S: cast<CXXCatchStmt>(Val: S)->getHandlerBlock(), ReturnStmts,
2341 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2342 return false;
2343 return true;
2344
2345 default:
2346 if (!isa<Expr>(Val: S))
2347 break;
2348
2349 // C++1y allows expression-statements.
2350 if (!Cxx1yLoc.isValid())
2351 Cxx1yLoc = S->getBeginLoc();
2352 return true;
2353 }
2354
2355 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2356 SemaRef.Diag(Loc: S->getBeginLoc(), DiagID: diag::err_constexpr_body_invalid_stmt)
2357 << isa<CXXConstructorDecl>(Val: Dcl) << Dcl->isConsteval();
2358 }
2359 return false;
2360}
2361
2362/// Check the body for the given constexpr function declaration only contains
2363/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
2364///
2365/// \return true if the body is OK, false if we have found or diagnosed a
2366/// problem.
2367static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
2368 Stmt *Body,
2369 Sema::CheckConstexprKind Kind) {
2370 SmallVector<SourceLocation, 4> ReturnStmts;
2371
2372 if (isa<CXXTryStmt>(Val: Body)) {
2373 // C++11 [dcl.constexpr]p3:
2374 // The definition of a constexpr function shall satisfy the following
2375 // constraints: [...]
2376 // - its function-body shall be = delete, = default, or a
2377 // compound-statement
2378 //
2379 // C++11 [dcl.constexpr]p4:
2380 // In the definition of a constexpr constructor, [...]
2381 // - its function-body shall not be a function-try-block;
2382 //
2383 // This restriction is lifted in C++2a, as long as inner statements also
2384 // apply the general constexpr rules.
2385 switch (Kind) {
2386 case Sema::CheckConstexprKind::CheckValid:
2387 if (!SemaRef.getLangOpts().CPlusPlus20)
2388 return false;
2389 break;
2390
2391 case Sema::CheckConstexprKind::Diagnose:
2392 SemaRef.DiagCompat(Loc: Body->getBeginLoc(),
2393 CompatDiagId: diag_compat::constexpr_function_try_block)
2394 << isa<CXXConstructorDecl>(Val: Dcl);
2395 break;
2396 }
2397 }
2398
2399 // - its function-body shall be [...] a compound-statement that contains only
2400 // [... list of cases ...]
2401 //
2402 // Note that walking the children here is enough to properly check for
2403 // CompoundStmt and CXXTryStmt body.
2404 SourceLocation Cxx1yLoc, Cxx2aLoc, Cxx2bLoc;
2405 for (Stmt *SubStmt : Body->children()) {
2406 if (SubStmt &&
2407 !CheckConstexprFunctionStmt(SemaRef, Dcl, S: SubStmt, ReturnStmts,
2408 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2409 return false;
2410 }
2411
2412 if (Kind == Sema::CheckConstexprKind::CheckValid) {
2413 // If this is only valid as an extension, report that we don't satisfy the
2414 // constraints of the current language.
2415 if ((Cxx2bLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus23) ||
2416 (Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) ||
2417 (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
2418 return false;
2419 } else if (Cxx2bLoc.isValid()) {
2420 SemaRef.DiagCompat(Loc: Cxx2bLoc, CompatDiagId: diag_compat::cxx23_constexpr_body_invalid_stmt)
2421 << isa<CXXConstructorDecl>(Val: Dcl);
2422 } else if (Cxx2aLoc.isValid()) {
2423 SemaRef.DiagCompat(Loc: Cxx2aLoc, CompatDiagId: diag_compat::cxx20_constexpr_body_invalid_stmt)
2424 << isa<CXXConstructorDecl>(Val: Dcl);
2425 } else if (Cxx1yLoc.isValid()) {
2426 SemaRef.DiagCompat(Loc: Cxx1yLoc, CompatDiagId: diag_compat::cxx14_constexpr_body_invalid_stmt)
2427 << isa<CXXConstructorDecl>(Val: Dcl);
2428 }
2429
2430 if (const CXXConstructorDecl *Constructor
2431 = dyn_cast<CXXConstructorDecl>(Val: Dcl)) {
2432 const CXXRecordDecl *RD = Constructor->getParent();
2433 // DR1359:
2434 // - every non-variant non-static data member and base class sub-object
2435 // shall be initialized;
2436 // DR1460:
2437 // - if the class is a union having variant members, exactly one of them
2438 // shall be initialized;
2439 if (RD->isUnion()) {
2440 if (Constructor->getNumCtorInitializers() == 0 &&
2441 RD->hasVariantMembers()) {
2442 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2443 SemaRef.DiagCompat(Loc: Dcl->getLocation(),
2444 CompatDiagId: diag_compat::constexpr_union_ctor_no_init);
2445 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2446 return false;
2447 }
2448 }
2449 } else if (!Constructor->isDependentContext() &&
2450 !Constructor->isDelegatingConstructor()) {
2451 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
2452
2453 // Skip detailed checking if we have enough initializers, and we would
2454 // allow at most one initializer per member.
2455 bool AnyAnonStructUnionMembers = false;
2456 unsigned Fields = 0;
2457 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
2458 E = RD->field_end(); I != E; ++I, ++Fields) {
2459 if (I->isAnonymousStructOrUnion()) {
2460 AnyAnonStructUnionMembers = true;
2461 break;
2462 }
2463 }
2464 // DR1460:
2465 // - if the class is a union-like class, but is not a union, for each of
2466 // its anonymous union members having variant members, exactly one of
2467 // them shall be initialized;
2468 if (AnyAnonStructUnionMembers ||
2469 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2470 // Check initialization of non-static data members. Base classes are
2471 // always initialized so do not need to be checked. Dependent bases
2472 // might not have initializers in the member initializer list.
2473 llvm::SmallPtrSet<Decl *, 16> Inits;
2474 for (const auto *I: Constructor->inits()) {
2475 if (FieldDecl *FD = I->getMember())
2476 Inits.insert(Ptr: FD);
2477 else if (IndirectFieldDecl *ID = I->getIndirectMember())
2478 Inits.insert(I: ID->chain_begin(), E: ID->chain_end());
2479 }
2480
2481 bool Diagnosed = false;
2482 for (auto *I : RD->fields())
2483 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, Field: I, Inits, Diagnosed,
2484 Kind))
2485 return false;
2486 }
2487 }
2488 } else {
2489 if (ReturnStmts.empty()) {
2490 switch (Kind) {
2491 case Sema::CheckConstexprKind::Diagnose:
2492 if (!CheckConstexprMissingReturn(SemaRef, Dcl))
2493 return false;
2494 break;
2495
2496 case Sema::CheckConstexprKind::CheckValid:
2497 // The formal requirements don't include this rule in C++14, even
2498 // though the "must be able to produce a constant expression" rules
2499 // still imply it in some cases.
2500 if (!SemaRef.getLangOpts().CPlusPlus14)
2501 return false;
2502 break;
2503 }
2504 } else if (ReturnStmts.size() > 1) {
2505 switch (Kind) {
2506 case Sema::CheckConstexprKind::Diagnose:
2507 SemaRef.DiagCompat(Loc: ReturnStmts.back(),
2508 CompatDiagId: diag_compat::constexpr_body_multiple_return);
2509 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2510 SemaRef.Diag(Loc: ReturnStmts[I],
2511 DiagID: diag::note_constexpr_body_previous_return);
2512 break;
2513
2514 case Sema::CheckConstexprKind::CheckValid:
2515 if (!SemaRef.getLangOpts().CPlusPlus14)
2516 return false;
2517 break;
2518 }
2519 }
2520 }
2521
2522 // C++11 [dcl.constexpr]p5:
2523 // if no function argument values exist such that the function invocation
2524 // substitution would produce a constant expression, the program is
2525 // ill-formed; no diagnostic required.
2526 // C++11 [dcl.constexpr]p3:
2527 // - every constructor call and implicit conversion used in initializing the
2528 // return value shall be one of those allowed in a constant expression.
2529 // C++11 [dcl.constexpr]p4:
2530 // - every constructor involved in initializing non-static data members and
2531 // base class sub-objects shall be a constexpr constructor.
2532 //
2533 // Note that this rule is distinct from the "requirements for a constexpr
2534 // function", so is not checked in CheckValid mode. Because the check for
2535 // constexpr potential is expensive, skip the check if the diagnostic is
2536 // disabled, the function is declared in a system header, or we're in C++23
2537 // or later mode (see https://wg21.link/P2448).
2538 bool SkipCheck =
2539 !SemaRef.getLangOpts().CheckConstexprFunctionBodies ||
2540 SemaRef.getSourceManager().isInSystemHeader(Loc: Dcl->getLocation()) ||
2541 SemaRef.getDiagnostics().isIgnored(
2542 DiagID: diag::ext_constexpr_function_never_constant_expr, Loc: Dcl->getLocation());
2543 SmallVector<PartialDiagnosticAt, 8> Diags;
2544 if (Kind == Sema::CheckConstexprKind::Diagnose && !SkipCheck &&
2545 !Expr::isPotentialConstantExpr(FD: Dcl, Diags)) {
2546 SemaRef.Diag(Loc: Dcl->getLocation(),
2547 DiagID: diag::ext_constexpr_function_never_constant_expr)
2548 << isa<CXXConstructorDecl>(Val: Dcl) << Dcl->isConsteval()
2549 << Dcl->getNameInfo().getSourceRange();
2550 for (const auto &Diag : Diags)
2551 SemaRef.Diag(Loc: Diag.first, PD: Diag.second);
2552 // Don't return false here: we allow this for compatibility in
2553 // system headers.
2554 }
2555
2556 return true;
2557}
2558
2559static bool CheckConstexprMissingReturn(Sema &SemaRef,
2560 const FunctionDecl *Dcl) {
2561 bool IsVoidOrDependentType = Dcl->getReturnType()->isVoidType() ||
2562 Dcl->getReturnType()->isDependentType();
2563 // Skip emitting a missing return error diagnostic for non-void functions
2564 // since C++23 no longer mandates constexpr functions to yield constant
2565 // expressions.
2566 if (SemaRef.getLangOpts().CPlusPlus23 && !IsVoidOrDependentType)
2567 return true;
2568
2569 // C++14 doesn't require constexpr functions to contain a 'return'
2570 // statement. We still do, unless the return type might be void, because
2571 // otherwise if there's no return statement, the function cannot
2572 // be used in a core constant expression.
2573 bool OK = SemaRef.getLangOpts().CPlusPlus14 && IsVoidOrDependentType;
2574 SemaRef.Diag(Loc: Dcl->getLocation(),
2575 DiagID: OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2576 : diag::err_constexpr_body_no_return)
2577 << Dcl->isConsteval();
2578 return OK;
2579}
2580
2581bool Sema::CheckImmediateEscalatingFunctionDefinition(
2582 FunctionDecl *FD, const sema::FunctionScopeInfo *FSI) {
2583 if (!getLangOpts().CPlusPlus20 || !FD->isImmediateEscalating())
2584 return true;
2585 FD->setBodyContainsImmediateEscalatingExpressions(
2586 FSI->FoundImmediateEscalatingExpression);
2587 if (FSI->FoundImmediateEscalatingExpression) {
2588 auto it = UndefinedButUsed.find(Key: FD->getCanonicalDecl());
2589 if (it != UndefinedButUsed.end()) {
2590 Diag(Loc: it->second, DiagID: diag::err_immediate_function_used_before_definition)
2591 << it->first;
2592 Diag(Loc: FD->getLocation(), DiagID: diag::note_defined_here) << FD;
2593 if (FD->isImmediateFunction() && !FD->isConsteval())
2594 DiagnoseImmediateEscalatingReason(FD);
2595 return false;
2596 }
2597 }
2598 return true;
2599}
2600
2601void Sema::DiagnoseImmediateEscalatingReason(FunctionDecl *FD) {
2602 assert(FD->isImmediateEscalating() && !FD->isConsteval() &&
2603 "expected an immediate function");
2604 assert(FD->hasBody() && "expected the function to have a body");
2605 struct ImmediateEscalatingExpressionsVisitor : DynamicRecursiveASTVisitor {
2606 Sema &SemaRef;
2607
2608 const FunctionDecl *ImmediateFn;
2609 bool ImmediateFnIsConstructor;
2610 CXXConstructorDecl *CurrentConstructor = nullptr;
2611 CXXCtorInitializer *CurrentInit = nullptr;
2612
2613 ImmediateEscalatingExpressionsVisitor(Sema &SemaRef, FunctionDecl *FD)
2614 : SemaRef(SemaRef), ImmediateFn(FD),
2615 ImmediateFnIsConstructor(isa<CXXConstructorDecl>(Val: FD)) {
2616 ShouldVisitImplicitCode = true;
2617 ShouldVisitLambdaBody = false;
2618 }
2619
2620 void Diag(const Expr *E, const FunctionDecl *Fn, bool IsCall) {
2621 SourceLocation Loc = E->getBeginLoc();
2622 SourceRange Range = E->getSourceRange();
2623 if (CurrentConstructor && CurrentInit) {
2624 Loc = CurrentConstructor->getLocation();
2625 Range = CurrentInit->isWritten() ? CurrentInit->getSourceRange()
2626 : SourceRange();
2627 }
2628
2629 FieldDecl* InitializedField = CurrentInit ? CurrentInit->getAnyMember() : nullptr;
2630
2631 SemaRef.Diag(Loc, DiagID: diag::note_immediate_function_reason)
2632 << ImmediateFn << Fn << Fn->isConsteval() << IsCall
2633 << isa<CXXConstructorDecl>(Val: Fn) << ImmediateFnIsConstructor
2634 << (InitializedField != nullptr)
2635 << (CurrentInit && !CurrentInit->isWritten())
2636 << InitializedField << Range;
2637 }
2638 bool TraverseCallExpr(CallExpr *E) override {
2639 if (const auto *DR =
2640 dyn_cast<DeclRefExpr>(Val: E->getCallee()->IgnoreImplicit());
2641 DR && DR->isImmediateEscalating()) {
2642 Diag(E, Fn: E->getDirectCallee(), /*IsCall=*/true);
2643 return false;
2644 }
2645
2646 for (Expr *A : E->arguments())
2647 if (!TraverseStmt(S: A))
2648 return false;
2649
2650 return true;
2651 }
2652
2653 bool VisitDeclRefExpr(DeclRefExpr *E) override {
2654 if (const auto *ReferencedFn = dyn_cast<FunctionDecl>(Val: E->getDecl());
2655 ReferencedFn && E->isImmediateEscalating()) {
2656 Diag(E, Fn: ReferencedFn, /*IsCall=*/false);
2657 return false;
2658 }
2659
2660 return true;
2661 }
2662
2663 bool VisitCXXConstructExpr(CXXConstructExpr *E) override {
2664 CXXConstructorDecl *D = E->getConstructor();
2665 if (E->isImmediateEscalating()) {
2666 Diag(E, Fn: D, /*IsCall=*/true);
2667 return false;
2668 }
2669 return true;
2670 }
2671
2672 bool TraverseConstructorInitializer(CXXCtorInitializer *Init) override {
2673 llvm::SaveAndRestore RAII(CurrentInit, Init);
2674 return DynamicRecursiveASTVisitor::TraverseConstructorInitializer(Init);
2675 }
2676
2677 bool TraverseCXXConstructorDecl(CXXConstructorDecl *Ctr) override {
2678 llvm::SaveAndRestore RAII(CurrentConstructor, Ctr);
2679 return DynamicRecursiveASTVisitor::TraverseCXXConstructorDecl(D: Ctr);
2680 }
2681
2682 bool TraverseType(QualType T, bool TraverseQualifier) override {
2683 return true;
2684 }
2685 bool VisitBlockExpr(BlockExpr *T) override { return true; }
2686
2687 } Visitor(*this, FD);
2688 Visitor.TraverseDecl(D: FD);
2689}
2690
2691CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {
2692 assert(getLangOpts().CPlusPlus && "No class names in C!");
2693
2694 if (SS && SS->isInvalid())
2695 return nullptr;
2696
2697 if (SS && SS->isNotEmpty()) {
2698 DeclContext *DC = computeDeclContext(SS: *SS, EnteringContext: true);
2699 return dyn_cast_or_null<CXXRecordDecl>(Val: DC);
2700 }
2701
2702 return dyn_cast_or_null<CXXRecordDecl>(Val: CurContext);
2703}
2704
2705bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,
2706 const CXXScopeSpec *SS) {
2707 CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2708 return CurDecl && &II == CurDecl->getIdentifier();
2709}
2710
2711bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2712 assert(getLangOpts().CPlusPlus && "No class names in C!");
2713
2714 if (!getLangOpts().SpellChecking)
2715 return false;
2716
2717 CXXRecordDecl *CurDecl;
2718 if (SS && SS->isSet() && !SS->isInvalid()) {
2719 DeclContext *DC = computeDeclContext(SS: *SS, EnteringContext: true);
2720 CurDecl = dyn_cast_or_null<CXXRecordDecl>(Val: DC);
2721 } else
2722 CurDecl = dyn_cast_or_null<CXXRecordDecl>(Val: CurContext);
2723
2724 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2725 3 * II->getName().edit_distance(Other: CurDecl->getIdentifier()->getName())
2726 < II->getLength()) {
2727 II = CurDecl->getIdentifier();
2728 return true;
2729 }
2730
2731 return false;
2732}
2733
2734CXXBaseSpecifier *Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2735 SourceRange SpecifierRange,
2736 bool Virtual, AccessSpecifier Access,
2737 TypeSourceInfo *TInfo,
2738 SourceLocation EllipsisLoc) {
2739 QualType BaseType = TInfo->getType();
2740 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2741 if (BaseType->containsErrors()) {
2742 // Already emitted a diagnostic when parsing the error type.
2743 return nullptr;
2744 }
2745
2746 if (EllipsisLoc.isValid() && !BaseType->containsUnexpandedParameterPack()) {
2747 Diag(Loc: EllipsisLoc, DiagID: diag::err_pack_expansion_without_parameter_packs)
2748 << TInfo->getTypeLoc().getSourceRange();
2749 EllipsisLoc = SourceLocation();
2750 }
2751
2752 auto *BaseDecl =
2753 dyn_cast_if_present<CXXRecordDecl>(Val: computeDeclContext(T: BaseType));
2754 // C++ [class.derived.general]p2:
2755 // A class-or-decltype shall denote a (possibly cv-qualified) class type
2756 // that is not an incompletely defined class; any cv-qualifiers are
2757 // ignored.
2758 if (BaseDecl) {
2759 // C++ [class.union.general]p4:
2760 // [...] A union shall not be used as a base class.
2761 if (BaseDecl->isUnion()) {
2762 Diag(Loc: BaseLoc, DiagID: diag::err_union_as_base_class) << SpecifierRange;
2763 return nullptr;
2764 }
2765
2766 if (BaseType.hasQualifiers()) {
2767 std::string Quals =
2768 BaseType.getQualifiers().getAsString(Policy: Context.getPrintingPolicy());
2769 Diag(Loc: BaseLoc, DiagID: diag::warn_qual_base_type)
2770 << Quals << llvm::count(Range&: Quals, Element: ' ') + 1 << BaseType;
2771 Diag(Loc: BaseLoc, DiagID: diag::note_base_class_specified_here) << BaseType;
2772 }
2773
2774 // For the MS ABI, propagate DLL attributes to base class templates.
2775 if (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
2776 Context.getTargetInfo().getTriple().isPS()) {
2777 if (Attr *ClassAttr = getDLLAttr(D: Class)) {
2778 if (auto *BaseSpec =
2779 dyn_cast<ClassTemplateSpecializationDecl>(Val: BaseDecl)) {
2780 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplateSpec: BaseSpec,
2781 BaseLoc);
2782 }
2783 }
2784 }
2785
2786 if (RequireCompleteType(Loc: BaseLoc, T: BaseType, DiagID: diag::err_incomplete_base_class,
2787 Args: SpecifierRange)) {
2788 Class->setInvalidDecl();
2789 return nullptr;
2790 }
2791
2792 BaseDecl = BaseDecl->getDefinition();
2793 assert(BaseDecl && "Base type is not incomplete, but has no definition");
2794
2795 // Microsoft docs say:
2796 // "If a base-class has a code_seg attribute, derived classes must have the
2797 // same attribute."
2798 const auto *BaseCSA = BaseDecl->getAttr<CodeSegAttr>();
2799 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2800 if ((DerivedCSA || BaseCSA) &&
2801 (!BaseCSA || !DerivedCSA ||
2802 BaseCSA->getName() != DerivedCSA->getName())) {
2803 Diag(Loc: Class->getLocation(), DiagID: diag::err_mismatched_code_seg_base);
2804 Diag(Loc: BaseDecl->getLocation(), DiagID: diag::note_base_class_specified_here)
2805 << BaseDecl;
2806 return nullptr;
2807 }
2808
2809 // A class which contains a flexible array member is not suitable for use as
2810 // a base class:
2811 // - If the layout determines that a base comes before another base,
2812 // the flexible array member would index into the subsequent base.
2813 // - If the layout determines that base comes before the derived class,
2814 // the flexible array member would index into the derived class.
2815 if (BaseDecl->hasFlexibleArrayMember()) {
2816 Diag(Loc: BaseLoc, DiagID: diag::err_base_class_has_flexible_array_member)
2817 << BaseDecl->getDeclName();
2818 return nullptr;
2819 }
2820
2821 // C++ [class]p3:
2822 // If a class is marked final and it appears as a base-type-specifier in
2823 // base-clause, the program is ill-formed.
2824 if (FinalAttr *FA = BaseDecl->getAttr<FinalAttr>()) {
2825 Diag(Loc: BaseLoc, DiagID: diag::err_class_marked_final_used_as_base)
2826 << BaseDecl->getDeclName() << FA->isSpelledAsSealed();
2827 Diag(Loc: BaseDecl->getLocation(), DiagID: diag::note_entity_declared_at)
2828 << BaseDecl->getDeclName() << FA->getRange();
2829 return nullptr;
2830 }
2831
2832 // If the base class is invalid the derived class is as well.
2833 if (BaseDecl->isInvalidDecl())
2834 Class->setInvalidDecl();
2835 } else if (BaseType->isDependentType()) {
2836 // Make sure that we don't make an ill-formed AST where the type of the
2837 // Class is non-dependent and its attached base class specifier is an
2838 // dependent type, which violates invariants in many clang code paths (e.g.
2839 // constexpr evaluator). If this case happens (in errory-recovery mode), we
2840 // explicitly mark the Class decl invalid. The diagnostic was already
2841 // emitted.
2842 if (!Class->isDependentContext())
2843 Class->setInvalidDecl();
2844 } else {
2845 // The base class is some non-dependent non-class type.
2846 Diag(Loc: BaseLoc, DiagID: diag::err_base_must_be_class) << SpecifierRange;
2847 return nullptr;
2848 }
2849
2850 // In HLSL, unspecified class access is public rather than private.
2851 if (getLangOpts().HLSL && Class->getTagKind() == TagTypeKind::Class &&
2852 Access == AS_none)
2853 Access = AS_public;
2854
2855 // Create the base specifier.
2856 return new (Context) CXXBaseSpecifier(
2857 SpecifierRange, Virtual, Class->getTagKind() == TagTypeKind::Class,
2858 Access, TInfo, EllipsisLoc);
2859}
2860
2861BaseResult Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2862 const ParsedAttributesView &Attributes,
2863 bool Virtual, AccessSpecifier Access,
2864 ParsedType basetype, SourceLocation BaseLoc,
2865 SourceLocation EllipsisLoc) {
2866 if (!classdecl)
2867 return true;
2868
2869 AdjustDeclIfTemplate(Decl&: classdecl);
2870 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Val: classdecl);
2871 if (!Class)
2872 return true;
2873
2874 // We haven't yet attached the base specifiers.
2875 Class->setIsParsingBaseSpecifiers();
2876
2877 // We do not support any C++11 attributes on base-specifiers yet.
2878 // Diagnose any attributes we see.
2879 for (const ParsedAttr &AL : Attributes) {
2880 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2881 continue;
2882 if (AL.getKind() == ParsedAttr::UnknownAttribute)
2883 DiagnoseUnknownAttribute(AL);
2884 else
2885 Diag(Loc: AL.getLoc(), DiagID: diag::err_base_specifier_attribute)
2886 << AL << AL.isRegularKeywordAttribute() << AL.getRange();
2887 }
2888
2889 TypeSourceInfo *TInfo = nullptr;
2890 GetTypeFromParser(Ty: basetype, TInfo: &TInfo);
2891
2892 if (EllipsisLoc.isInvalid() &&
2893 DiagnoseUnexpandedParameterPack(Loc: SpecifierRange.getBegin(), T: TInfo,
2894 UPPC: UPPC_BaseType))
2895 return true;
2896
2897 // C++ [class.union.general]p4:
2898 // [...] A union shall not have base classes.
2899 if (Class->isUnion()) {
2900 Diag(Loc: Class->getLocation(), DiagID: diag::err_base_clause_on_union)
2901 << SpecifierRange;
2902 return true;
2903 }
2904
2905 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2906 Virtual, Access, TInfo,
2907 EllipsisLoc))
2908 return BaseSpec;
2909
2910 Class->setInvalidDecl();
2911 return true;
2912}
2913
2914/// Use small set to collect indirect bases. As this is only used
2915/// locally, there's no need to abstract the small size parameter.
2916typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2917
2918/// Recursively add the bases of Type. Don't add Type itself.
2919static void
2920NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2921 const QualType &Type)
2922{
2923 // Even though the incoming type is a base, it might not be
2924 // a class -- it could be a template parm, for instance.
2925 if (const auto *Decl = Type->getAsCXXRecordDecl()) {
2926 // Iterate over its bases.
2927 for (const auto &BaseSpec : Decl->bases()) {
2928 QualType Base = Context.getCanonicalType(T: BaseSpec.getType())
2929 .getUnqualifiedType();
2930 if (Set.insert(Ptr: Base).second)
2931 // If we've not already seen it, recurse.
2932 NoteIndirectBases(Context, Set, Type: Base);
2933 }
2934 }
2935}
2936
2937bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2938 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2939 if (Bases.empty())
2940 return false;
2941
2942 // Used to keep track of which base types we have already seen, so
2943 // that we can properly diagnose redundant direct base types. Note
2944 // that the key is always the unqualified canonical type of the base
2945 // class.
2946 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2947
2948 // Used to track indirect bases so we can see if a direct base is
2949 // ambiguous.
2950 IndirectBaseSet IndirectBaseTypes;
2951
2952 // Copy non-redundant base specifiers into permanent storage.
2953 unsigned NumGoodBases = 0;
2954 bool Invalid = false;
2955 for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2956 QualType NewBaseType
2957 = Context.getCanonicalType(T: Bases[idx]->getType());
2958 NewBaseType = NewBaseType.getLocalUnqualifiedType();
2959
2960 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2961 if (KnownBase) {
2962 // C++ [class.mi]p3:
2963 // A class shall not be specified as a direct base class of a
2964 // derived class more than once.
2965 Diag(Loc: Bases[idx]->getBeginLoc(), DiagID: diag::err_duplicate_base_class)
2966 << KnownBase->getType() << Bases[idx]->getSourceRange();
2967
2968 // Delete the duplicate base class specifier; we're going to
2969 // overwrite its pointer later.
2970 Context.Deallocate(Ptr: Bases[idx]);
2971
2972 Invalid = true;
2973 } else {
2974 // Okay, add this new base class.
2975 KnownBase = Bases[idx];
2976 Bases[NumGoodBases++] = Bases[idx];
2977
2978 if (NewBaseType->isDependentType())
2979 continue;
2980 // Note this base's direct & indirect bases, if there could be ambiguity.
2981 if (Bases.size() > 1)
2982 NoteIndirectBases(Context, Set&: IndirectBaseTypes, Type: NewBaseType);
2983
2984 if (const auto *RD = NewBaseType->getAsCXXRecordDecl()) {
2985 if (Class->isInterface() &&
2986 (!RD->isInterfaceLike() ||
2987 KnownBase->getAccessSpecifier() != AS_public)) {
2988 // The Microsoft extension __interface does not permit bases that
2989 // are not themselves public interfaces.
2990 Diag(Loc: KnownBase->getBeginLoc(), DiagID: diag::err_invalid_base_in_interface)
2991 << getRecordDiagFromTagKind(Tag: RD->getTagKind()) << RD
2992 << RD->getSourceRange();
2993 Invalid = true;
2994 }
2995 if (RD->hasAttr<WeakAttr>())
2996 Class->addAttr(A: WeakAttr::CreateImplicit(Ctx&: Context));
2997 }
2998 }
2999 }
3000
3001 // Attach the remaining base class specifiers to the derived class.
3002 Class->setBases(Bases: Bases.data(), NumBases: NumGoodBases);
3003
3004 // Check that the only base classes that are duplicate are virtual.
3005 for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
3006 // Check whether this direct base is inaccessible due to ambiguity.
3007 QualType BaseType = Bases[idx]->getType();
3008
3009 // Skip all dependent types in templates being used as base specifiers.
3010 // Checks below assume that the base specifier is a CXXRecord.
3011 if (BaseType->isDependentType())
3012 continue;
3013
3014 CanQualType CanonicalBase = Context.getCanonicalType(T: BaseType)
3015 .getUnqualifiedType();
3016
3017 if (IndirectBaseTypes.count(Ptr: CanonicalBase)) {
3018 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3019 /*DetectVirtual=*/true);
3020 bool found
3021 = Class->isDerivedFrom(Base: CanonicalBase->getAsCXXRecordDecl(), Paths);
3022 assert(found);
3023 (void)found;
3024
3025 if (Paths.isAmbiguous(BaseType: CanonicalBase))
3026 Diag(Loc: Bases[idx]->getBeginLoc(), DiagID: diag::warn_inaccessible_base_class)
3027 << BaseType << getAmbiguousPathsDisplayString(Paths)
3028 << Bases[idx]->getSourceRange();
3029 else
3030 assert(Bases[idx]->isVirtual());
3031 }
3032
3033 // Delete the base class specifier, since its data has been copied
3034 // into the CXXRecordDecl.
3035 Context.Deallocate(Ptr: Bases[idx]);
3036 }
3037
3038 return Invalid;
3039}
3040
3041void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
3042 MutableArrayRef<CXXBaseSpecifier *> Bases) {
3043 if (!ClassDecl || Bases.empty())
3044 return;
3045
3046 AdjustDeclIfTemplate(Decl&: ClassDecl);
3047 AttachBaseSpecifiers(Class: cast<CXXRecordDecl>(Val: ClassDecl), Bases);
3048}
3049
3050bool Sema::IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived,
3051 CXXRecordDecl *Base, CXXBasePaths &Paths) {
3052 if (!getLangOpts().CPlusPlus)
3053 return false;
3054
3055 if (!Base || !Derived)
3056 return false;
3057
3058 // If either the base or the derived type is invalid, don't try to
3059 // check whether one is derived from the other.
3060 if (Base->isInvalidDecl() || Derived->isInvalidDecl())
3061 return false;
3062
3063 // FIXME: In a modules build, do we need the entire path to be visible for us
3064 // to be able to use the inheritance relationship?
3065 if (!isCompleteType(Loc, T: Context.getCanonicalTagType(TD: Derived)) &&
3066 !Derived->isBeingDefined())
3067 return false;
3068
3069 return Derived->isDerivedFrom(Base, Paths);
3070}
3071
3072bool Sema::IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived,
3073 CXXRecordDecl *Base) {
3074 CXXBasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/false,
3075 /*DetectVirtual=*/false);
3076 return IsDerivedFrom(Loc, Derived, Base, Paths);
3077}
3078
3079bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
3080 CXXBasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/false,
3081 /*DetectVirtual=*/false);
3082 return IsDerivedFrom(Loc, Derived: Derived->getAsCXXRecordDecl(),
3083 Base: Base->getAsCXXRecordDecl(), Paths);
3084}
3085
3086bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
3087 CXXBasePaths &Paths) {
3088 return IsDerivedFrom(Loc, Derived: Derived->getAsCXXRecordDecl(),
3089 Base: Base->getAsCXXRecordDecl(), Paths);
3090}
3091
3092static void BuildBasePathArray(const CXXBasePath &Path,
3093 CXXCastPath &BasePathArray) {
3094 // We first go backward and check if we have a virtual base.
3095 // FIXME: It would be better if CXXBasePath had the base specifier for
3096 // the nearest virtual base.
3097 unsigned Start = 0;
3098 for (unsigned I = Path.size(); I != 0; --I) {
3099 if (Path[I - 1].Base->isVirtual()) {
3100 Start = I - 1;
3101 break;
3102 }
3103 }
3104
3105 // Now add all bases.
3106 for (unsigned I = Start, E = Path.size(); I != E; ++I)
3107 BasePathArray.push_back(Elt: const_cast<CXXBaseSpecifier*>(Path[I].Base));
3108}
3109
3110
3111void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
3112 CXXCastPath &BasePathArray) {
3113 assert(BasePathArray.empty() && "Base path array must be empty!");
3114 assert(Paths.isRecordingPaths() && "Must record paths!");
3115 return ::BuildBasePathArray(Path: Paths.front(), BasePathArray);
3116}
3117
3118bool
3119Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
3120 unsigned InaccessibleBaseID,
3121 unsigned AmbiguousBaseConvID,
3122 SourceLocation Loc, SourceRange Range,
3123 DeclarationName Name,
3124 CXXCastPath *BasePath,
3125 bool IgnoreAccess) {
3126 // First, determine whether the path from Derived to Base is
3127 // ambiguous. This is slightly more expensive than checking whether
3128 // the Derived to Base conversion exists, because here we need to
3129 // explore multiple paths to determine if there is an ambiguity.
3130 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3131 /*DetectVirtual=*/false);
3132 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
3133 if (!DerivationOkay)
3134 return true;
3135
3136 const CXXBasePath *Path = nullptr;
3137 if (!Paths.isAmbiguous(BaseType: Context.getCanonicalType(T: Base).getUnqualifiedType()))
3138 Path = &Paths.front();
3139
3140 // For MSVC compatibility, check if Derived directly inherits from Base. Clang
3141 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
3142 // user to access such bases.
3143 if (!Path && getLangOpts().MSVCCompat) {
3144 for (const CXXBasePath &PossiblePath : Paths) {
3145 if (PossiblePath.size() == 1) {
3146 Path = &PossiblePath;
3147 if (AmbiguousBaseConvID)
3148 Diag(Loc, DiagID: diag::ext_ms_ambiguous_direct_base)
3149 << Base << Derived << Range;
3150 break;
3151 }
3152 }
3153 }
3154
3155 if (Path) {
3156 if (!IgnoreAccess) {
3157 // Check that the base class can be accessed.
3158 switch (
3159 CheckBaseClassAccess(AccessLoc: Loc, Base, Derived, Path: *Path, DiagID: InaccessibleBaseID)) {
3160 case AR_inaccessible:
3161 return true;
3162 case AR_accessible:
3163 case AR_dependent:
3164 case AR_delayed:
3165 break;
3166 }
3167 }
3168
3169 // Build a base path if necessary.
3170 if (BasePath)
3171 ::BuildBasePathArray(Path: *Path, BasePathArray&: *BasePath);
3172 return false;
3173 }
3174
3175 if (AmbiguousBaseConvID) {
3176 // We know that the derived-to-base conversion is ambiguous, and
3177 // we're going to produce a diagnostic. Perform the derived-to-base
3178 // search just one more time to compute all of the possible paths so
3179 // that we can print them out. This is more expensive than any of
3180 // the previous derived-to-base checks we've done, but at this point
3181 // performance isn't as much of an issue.
3182 Paths.clear();
3183 Paths.setRecordingPaths(true);
3184 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
3185 assert(StillOkay && "Can only be used with a derived-to-base conversion");
3186 (void)StillOkay;
3187
3188 // Build up a textual representation of the ambiguous paths, e.g.,
3189 // D -> B -> A, that will be used to illustrate the ambiguous
3190 // conversions in the diagnostic. We only print one of the paths
3191 // to each base class subobject.
3192 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3193
3194 Diag(Loc, DiagID: AmbiguousBaseConvID)
3195 << Derived << Base << PathDisplayStr << Range << Name;
3196 }
3197 return true;
3198}
3199
3200bool
3201Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
3202 SourceLocation Loc, SourceRange Range,
3203 CXXCastPath *BasePath,
3204 bool IgnoreAccess) {
3205 return CheckDerivedToBaseConversion(
3206 Derived, Base, InaccessibleBaseID: diag::err_upcast_to_inaccessible_base,
3207 AmbiguousBaseConvID: diag::err_ambiguous_derived_to_base_conv, Loc, Range, Name: DeclarationName(),
3208 BasePath, IgnoreAccess);
3209}
3210
3211std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
3212 std::string PathDisplayStr;
3213 std::set<unsigned> DisplayedPaths;
3214 for (const CXXBasePath &Path : Paths) {
3215 if (DisplayedPaths.insert(x: Path.back().SubobjectNumber).second) {
3216 // We haven't displayed a path to this particular base
3217 // class subobject yet.
3218 PathDisplayStr += "\n ";
3219 PathDisplayStr += QualType(Context.getCanonicalTagType(TD: Paths.getOrigin()))
3220 .getAsString();
3221 for (const CXXBasePathElement &Element : Path)
3222 PathDisplayStr += " -> " + Element.Base->getType().getAsString();
3223 }
3224 }
3225
3226 return PathDisplayStr;
3227}
3228
3229//===----------------------------------------------------------------------===//
3230// C++ class member Handling
3231//===----------------------------------------------------------------------===//
3232
3233bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
3234 SourceLocation ColonLoc,
3235 const ParsedAttributesView &Attrs) {
3236 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
3237 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(C&: Context, AS: Access, DC: CurContext,
3238 ASLoc, ColonLoc);
3239 CurContext->addHiddenDecl(D: ASDecl);
3240 return ProcessAccessDeclAttributeList(ASDecl, AttrList: Attrs);
3241}
3242
3243void Sema::CheckOverrideControl(NamedDecl *D) {
3244 if (D->isInvalidDecl())
3245 return;
3246
3247 // We only care about "override" and "final" declarations.
3248 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
3249 return;
3250
3251 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: D);
3252
3253 // We can't check dependent instance methods.
3254 if (MD && MD->isInstance() &&
3255 (MD->getParent()->hasAnyDependentBases() ||
3256 MD->getType()->isDependentType()))
3257 return;
3258
3259 if (MD && !MD->isVirtual()) {
3260 // If we have a non-virtual method, check if it hides a virtual method.
3261 // (In that case, it's most likely the method has the wrong type.)
3262 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3263 FindHiddenVirtualMethods(MD, OverloadedMethods);
3264
3265 if (!OverloadedMethods.empty()) {
3266 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3267 Diag(Loc: OA->getLocation(),
3268 DiagID: diag::override_keyword_hides_virtual_member_function)
3269 << "override" << (OverloadedMethods.size() > 1);
3270 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3271 Diag(Loc: FA->getLocation(),
3272 DiagID: diag::override_keyword_hides_virtual_member_function)
3273 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3274 << (OverloadedMethods.size() > 1);
3275 }
3276 NoteHiddenVirtualMethods(MD, OverloadedMethods);
3277 MD->setInvalidDecl();
3278 return;
3279 }
3280 // Fall through into the general case diagnostic.
3281 // FIXME: We might want to attempt typo correction here.
3282 }
3283
3284 if (!MD || !MD->isVirtual()) {
3285 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3286 Diag(Loc: OA->getLocation(),
3287 DiagID: diag::override_keyword_only_allowed_on_virtual_member_functions)
3288 << "override" << FixItHint::CreateRemoval(RemoveRange: OA->getLocation());
3289 D->dropAttr<OverrideAttr>();
3290 }
3291 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3292 Diag(Loc: FA->getLocation(),
3293 DiagID: diag::override_keyword_only_allowed_on_virtual_member_functions)
3294 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3295 << FixItHint::CreateRemoval(RemoveRange: FA->getLocation());
3296 D->dropAttr<FinalAttr>();
3297 }
3298 return;
3299 }
3300
3301 // C++11 [class.virtual]p5:
3302 // If a function is marked with the virt-specifier override and
3303 // does not override a member function of a base class, the program is
3304 // ill-formed.
3305 bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
3306 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
3307 Diag(Loc: MD->getLocation(), DiagID: diag::err_function_marked_override_not_overriding)
3308 << MD->getDeclName();
3309}
3310
3311void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent) {
3312 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
3313 return;
3314 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: D);
3315 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
3316 return;
3317
3318 SourceLocation Loc = MD->getLocation();
3319 SourceLocation SpellingLoc = Loc;
3320 if (getSourceManager().isMacroArgExpansion(Loc))
3321 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
3322 SpellingLoc = getSourceManager().getSpellingLoc(Loc: SpellingLoc);
3323 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(Loc: SpellingLoc))
3324 return;
3325
3326 if (MD->size_overridden_methods() > 0) {
3327 auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) {
3328 unsigned DiagID =
3329 Inconsistent && !Diags.isIgnored(DiagID: DiagInconsistent, Loc: MD->getLocation())
3330 ? DiagInconsistent
3331 : DiagSuggest;
3332 Diag(Loc: MD->getLocation(), DiagID) << MD->getDeclName();
3333 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
3334 Diag(Loc: OMD->getLocation(), DiagID: diag::note_overridden_virtual_function);
3335 };
3336 if (isa<CXXDestructorDecl>(Val: MD))
3337 EmitDiag(
3338 diag::warn_inconsistent_destructor_marked_not_override_overriding,
3339 diag::warn_suggest_destructor_marked_not_override_overriding);
3340 else
3341 EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding,
3342 diag::warn_suggest_function_marked_not_override_overriding);
3343 }
3344}
3345
3346bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
3347 const CXXMethodDecl *Old) {
3348 FinalAttr *FA = Old->getAttr<FinalAttr>();
3349 if (!FA)
3350 return false;
3351
3352 Diag(Loc: New->getLocation(), DiagID: diag::err_final_function_overridden)
3353 << New->getDeclName()
3354 << FA->isSpelledAsSealed();
3355 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function);
3356 return true;
3357}
3358
3359static bool InitializationHasSideEffects(const FieldDecl &FD) {
3360 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
3361 // FIXME: Destruction of ObjC lifetime types has side-effects.
3362 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3363 return !RD->isCompleteDefinition() ||
3364 !RD->hasTrivialDefaultConstructor() ||
3365 !RD->hasTrivialDestructor();
3366 return false;
3367}
3368
3369void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
3370 DeclarationName FieldName,
3371 const CXXRecordDecl *RD,
3372 bool DeclIsField) {
3373 if (Diags.isIgnored(DiagID: diag::warn_shadow_field, Loc))
3374 return;
3375
3376 // To record a shadowed field in a base
3377 std::map<CXXRecordDecl*, NamedDecl*> Bases;
3378 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
3379 CXXBasePath &Path) {
3380 const auto Base = Specifier->getType()->getAsCXXRecordDecl();
3381 // Record an ambiguous path directly
3382 if (Bases.find(x: Base) != Bases.end())
3383 return true;
3384 for (const auto Field : Base->lookup(Name: FieldName)) {
3385 if ((isa<FieldDecl>(Val: Field) || isa<IndirectFieldDecl>(Val: Field)) &&
3386 Field->getAccess() != AS_private) {
3387 assert(Field->getAccess() != AS_none);
3388 assert(Bases.find(Base) == Bases.end());
3389 Bases[Base] = Field;
3390 return true;
3391 }
3392 }
3393 return false;
3394 };
3395
3396 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3397 /*DetectVirtual=*/true);
3398 if (!RD->lookupInBases(BaseMatches: FieldShadowed, Paths))
3399 return;
3400
3401 for (const auto &P : Paths) {
3402 auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
3403 auto It = Bases.find(x: Base);
3404 // Skip duplicated bases
3405 if (It == Bases.end())
3406 continue;
3407 auto BaseField = It->second;
3408 assert(BaseField->getAccess() != AS_private);
3409 if (AS_none !=
3410 CXXRecordDecl::MergeAccess(PathAccess: P.Access, DeclAccess: BaseField->getAccess())) {
3411 Diag(Loc, DiagID: diag::warn_shadow_field)
3412 << FieldName << RD << Base << DeclIsField;
3413 Diag(Loc: BaseField->getLocation(), DiagID: diag::note_shadow_field);
3414 Bases.erase(position: It);
3415 }
3416 }
3417}
3418
3419template <typename AttrType>
3420inline static bool HasAttribute(const QualType &T) {
3421 if (const TagDecl *TD = T->getAsTagDecl())
3422 return TD->hasAttr<AttrType>();
3423 if (const TypedefType *TDT = T->getAs<TypedefType>())
3424 return TDT->getDecl()->hasAttr<AttrType>();
3425 return false;
3426}
3427
3428static bool IsUnusedPrivateField(const FieldDecl *FD) {
3429 if (FD->getAccess() == AS_private && FD->getDeclName()) {
3430 QualType FieldType = FD->getType();
3431 if (HasAttribute<WarnUnusedAttr>(T: FieldType))
3432 return true;
3433
3434 return !FD->isImplicit() && !FD->hasAttr<UnusedAttr>() &&
3435 !FD->getParent()->isDependentContext() &&
3436 !HasAttribute<UnusedAttr>(T: FieldType) &&
3437 !InitializationHasSideEffects(FD: *FD);
3438 }
3439 return false;
3440}
3441
3442NamedDecl *
3443Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
3444 MultiTemplateParamsArg TemplateParameterLists,
3445 Expr *BitWidth, const VirtSpecifiers &VS,
3446 InClassInitStyle InitStyle) {
3447 const DeclSpec &DS = D.getDeclSpec();
3448 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
3449 DeclarationName Name = NameInfo.getName();
3450 SourceLocation Loc = NameInfo.getLoc();
3451
3452 // For anonymous bitfields, the location should point to the type.
3453 if (Loc.isInvalid())
3454 Loc = D.getBeginLoc();
3455
3456 assert(isa<CXXRecordDecl>(CurContext));
3457 assert(!DS.isFriendSpecified());
3458
3459 bool isFunc = D.isDeclarationOfFunction();
3460 const ParsedAttr *MSPropertyAttr =
3461 D.getDeclSpec().getAttributes().getMSPropertyAttr();
3462
3463 if (cast<CXXRecordDecl>(Val: CurContext)->isInterface()) {
3464 // The Microsoft extension __interface only permits public member functions
3465 // and prohibits constructors, destructors, operators, non-public member
3466 // functions, static methods and data members.
3467 unsigned InvalidDecl;
3468 bool ShowDeclName = true;
3469 if (!isFunc &&
3470 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
3471 InvalidDecl = 0;
3472 else if (!isFunc)
3473 InvalidDecl = 1;
3474 else if (AS != AS_public)
3475 InvalidDecl = 2;
3476 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
3477 InvalidDecl = 3;
3478 else switch (Name.getNameKind()) {
3479 case DeclarationName::CXXConstructorName:
3480 InvalidDecl = 4;
3481 ShowDeclName = false;
3482 break;
3483
3484 case DeclarationName::CXXDestructorName:
3485 InvalidDecl = 5;
3486 ShowDeclName = false;
3487 break;
3488
3489 case DeclarationName::CXXOperatorName:
3490 case DeclarationName::CXXConversionFunctionName:
3491 InvalidDecl = 6;
3492 break;
3493
3494 default:
3495 InvalidDecl = 0;
3496 break;
3497 }
3498
3499 if (InvalidDecl) {
3500 if (ShowDeclName)
3501 Diag(Loc, DiagID: diag::err_invalid_member_in_interface)
3502 << (InvalidDecl-1) << Name;
3503 else
3504 Diag(Loc, DiagID: diag::err_invalid_member_in_interface)
3505 << (InvalidDecl-1) << "";
3506 return nullptr;
3507 }
3508 }
3509
3510 // C++ 9.2p6: A member shall not be declared to have automatic storage
3511 // duration (auto, register) or with the extern storage-class-specifier.
3512 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3513 // data members and cannot be applied to names declared const or static,
3514 // and cannot be applied to reference members.
3515 switch (DS.getStorageClassSpec()) {
3516 case DeclSpec::SCS_unspecified:
3517 case DeclSpec::SCS_typedef:
3518 case DeclSpec::SCS_static:
3519 break;
3520 case DeclSpec::SCS_mutable:
3521 if (isFunc) {
3522 Diag(Loc: DS.getStorageClassSpecLoc(), DiagID: diag::err_mutable_function);
3523
3524 // FIXME: It would be nicer if the keyword was ignored only for this
3525 // declarator. Otherwise we could get follow-up errors.
3526 D.getMutableDeclSpec().ClearStorageClassSpecs();
3527 }
3528 break;
3529 default:
3530 Diag(Loc: DS.getStorageClassSpecLoc(),
3531 DiagID: diag::err_storageclass_invalid_for_member);
3532 D.getMutableDeclSpec().ClearStorageClassSpecs();
3533 break;
3534 }
3535
3536 bool isInstField = (DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3537 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
3538 !isFunc && TemplateParameterLists.empty();
3539
3540 if (DS.hasConstexprSpecifier() && isInstField) {
3541 SemaDiagnosticBuilder B =
3542 Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_invalid_constexpr_member);
3543 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3544 if (InitStyle == ICIS_NoInit) {
3545 B << 0 << 0;
3546 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
3547 B << FixItHint::CreateRemoval(RemoveRange: ConstexprLoc);
3548 else {
3549 B << FixItHint::CreateReplacement(RemoveRange: ConstexprLoc, Code: "const");
3550 D.getMutableDeclSpec().ClearConstexprSpec();
3551 const char *PrevSpec;
3552 unsigned DiagID;
3553 bool Failed = D.getMutableDeclSpec().SetTypeQual(
3554 T: DeclSpec::TQ_const, Loc: ConstexprLoc, PrevSpec, DiagID, Lang: getLangOpts());
3555 (void)Failed;
3556 assert(!Failed && "Making a constexpr member const shouldn't fail");
3557 }
3558 } else {
3559 B << 1;
3560 const char *PrevSpec;
3561 unsigned DiagID;
3562 if (D.getMutableDeclSpec().SetStorageClassSpec(
3563 S&: *this, SC: DeclSpec::SCS_static, Loc: ConstexprLoc, PrevSpec, DiagID,
3564 Policy: Context.getPrintingPolicy())) {
3565 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
3566 "This is the only DeclSpec that should fail to be applied");
3567 B << 1;
3568 } else {
3569 B << 0 << FixItHint::CreateInsertion(InsertionLoc: ConstexprLoc, Code: "static ");
3570 isInstField = false;
3571 }
3572 }
3573 }
3574
3575 NamedDecl *Member;
3576 if (isInstField) {
3577 CXXScopeSpec &SS = D.getCXXScopeSpec();
3578
3579 // Data members must have identifiers for names.
3580 if (!Name.isIdentifier()) {
3581 Diag(Loc, DiagID: diag::err_bad_variable_name)
3582 << Name;
3583 return nullptr;
3584 }
3585
3586 IdentifierInfo *II = Name.getAsIdentifierInfo();
3587 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
3588 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_member_with_template_arguments)
3589 << II
3590 << SourceRange(D.getName().TemplateId->LAngleLoc,
3591 D.getName().TemplateId->RAngleLoc)
3592 << D.getName().TemplateId->LAngleLoc;
3593 D.SetIdentifier(Id: II, IdLoc: Loc);
3594 }
3595
3596 if (SS.isSet() && !SS.isInvalid()) {
3597 // The user provided a superfluous scope specifier inside a class
3598 // definition:
3599 //
3600 // class X {
3601 // int X::member;
3602 // };
3603 if (DeclContext *DC = computeDeclContext(SS, EnteringContext: false)) {
3604 TemplateIdAnnotation *TemplateId =
3605 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
3606 ? D.getName().TemplateId
3607 : nullptr;
3608 diagnoseQualifiedDeclaration(SS, DC, Name, Loc: D.getIdentifierLoc(),
3609 TemplateId,
3610 /*IsMemberSpecialization=*/false);
3611 } else {
3612 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_member_qualification)
3613 << Name << SS.getRange();
3614 }
3615 SS.clear();
3616 }
3617
3618 if (MSPropertyAttr) {
3619 Member = HandleMSProperty(S, TagD: cast<CXXRecordDecl>(Val: CurContext), DeclStart: Loc, D,
3620 BitfieldWidth: BitWidth, InitStyle, AS, MSPropertyAttr: *MSPropertyAttr);
3621 if (!Member)
3622 return nullptr;
3623 isInstField = false;
3624 } else {
3625 Member = HandleField(S, TagD: cast<CXXRecordDecl>(Val: CurContext), DeclStart: Loc, D,
3626 BitfieldWidth: BitWidth, InitStyle, AS);
3627 if (!Member)
3628 return nullptr;
3629 }
3630
3631 CheckShadowInheritedFields(Loc, FieldName: Name, RD: cast<CXXRecordDecl>(Val: CurContext));
3632 } else {
3633 Member = HandleDeclarator(S, D, TemplateParameterLists);
3634 if (!Member)
3635 return nullptr;
3636
3637 // Non-instance-fields can't have a bitfield.
3638 if (BitWidth) {
3639 if (Member->isInvalidDecl()) {
3640 // don't emit another diagnostic.
3641 } else if (isa<VarDecl>(Val: Member) || isa<VarTemplateDecl>(Val: Member)) {
3642 // C++ 9.6p3: A bit-field shall not be a static member.
3643 // "static member 'A' cannot be a bit-field"
3644 Diag(Loc, DiagID: diag::err_static_not_bitfield)
3645 << Name << BitWidth->getSourceRange();
3646 } else if (isa<TypedefDecl>(Val: Member)) {
3647 // "typedef member 'x' cannot be a bit-field"
3648 Diag(Loc, DiagID: diag::err_typedef_not_bitfield)
3649 << Name << BitWidth->getSourceRange();
3650 } else {
3651 // A function typedef ("typedef int f(); f a;").
3652 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3653 Diag(Loc, DiagID: diag::err_not_integral_type_bitfield)
3654 << Name << cast<ValueDecl>(Val: Member)->getType()
3655 << BitWidth->getSourceRange();
3656 }
3657
3658 BitWidth = nullptr;
3659 Member->setInvalidDecl();
3660 }
3661
3662 NamedDecl *NonTemplateMember = Member;
3663 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: Member))
3664 NonTemplateMember = FunTmpl->getTemplatedDecl();
3665 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Val: Member))
3666 NonTemplateMember = VarTmpl->getTemplatedDecl();
3667
3668 Member->setAccess(AS);
3669
3670 // If we have declared a member function template or static data member
3671 // template, set the access of the templated declaration as well.
3672 if (NonTemplateMember != Member)
3673 NonTemplateMember->setAccess(AS);
3674
3675 // C++ [temp.deduct.guide]p3:
3676 // A deduction guide [...] for a member class template [shall be
3677 // declared] with the same access [as the template].
3678 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(Val: NonTemplateMember)) {
3679 auto *TD = DG->getDeducedTemplate();
3680 // Access specifiers are only meaningful if both the template and the
3681 // deduction guide are from the same scope.
3682 if (AS != TD->getAccess() &&
3683 TD->getDeclContext()->getRedeclContext()->Equals(
3684 DC: DG->getDeclContext()->getRedeclContext())) {
3685 Diag(Loc: DG->getBeginLoc(), DiagID: diag::err_deduction_guide_wrong_access);
3686 Diag(Loc: TD->getBeginLoc(), DiagID: diag::note_deduction_guide_template_access)
3687 << TD->getAccess();
3688 const AccessSpecDecl *LastAccessSpec = nullptr;
3689 for (const auto *D : cast<CXXRecordDecl>(Val: CurContext)->decls()) {
3690 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(Val: D))
3691 LastAccessSpec = AccessSpec;
3692 }
3693 assert(LastAccessSpec && "differing access with no access specifier");
3694 Diag(Loc: LastAccessSpec->getBeginLoc(), DiagID: diag::note_deduction_guide_access)
3695 << AS;
3696 }
3697 }
3698 }
3699
3700 if (VS.isOverrideSpecified())
3701 Member->addAttr(A: OverrideAttr::Create(Ctx&: Context, Range: VS.getOverrideLoc()));
3702 if (VS.isFinalSpecified())
3703 Member->addAttr(A: FinalAttr::Create(Ctx&: Context, Range: VS.getFinalLoc(),
3704 S: VS.isFinalSpelledSealed()
3705 ? FinalAttr::Keyword_sealed
3706 : FinalAttr::Keyword_final));
3707
3708 if (VS.getLastLocation().isValid()) {
3709 // Update the end location of a method that has a virt-specifiers.
3710 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Val: Member))
3711 MD->setRangeEnd(VS.getLastLocation());
3712 }
3713
3714 CheckOverrideControl(D: Member);
3715
3716 assert((Name || isInstField) && "No identifier for non-field ?");
3717
3718 if (isInstField) {
3719 FieldDecl *FD = cast<FieldDecl>(Val: Member);
3720 FieldCollector->Add(D: FD);
3721
3722 if (!Diags.isIgnored(DiagID: diag::warn_unused_private_field, Loc: FD->getLocation()) &&
3723 IsUnusedPrivateField(FD)) {
3724 // Remember all explicit private FieldDecls that have a name, no side
3725 // effects and are not part of a dependent type declaration.
3726 UnusedPrivateFields.insert(X: FD);
3727 }
3728 }
3729
3730 return Member;
3731}
3732
3733namespace {
3734 class UninitializedFieldVisitor
3735 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3736 Sema &S;
3737 // List of Decls to generate a warning on. Also remove Decls that become
3738 // initialized.
3739 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3740 // List of base classes of the record. Classes are removed after their
3741 // initializers.
3742 llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3743 // Vector of decls to be removed from the Decl set prior to visiting the
3744 // nodes. These Decls may have been initialized in the prior initializer.
3745 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3746 // If non-null, add a note to the warning pointing back to the constructor.
3747 const CXXConstructorDecl *Constructor;
3748 // Variables to hold state when processing an initializer list. When
3749 // InitList is true, special case initialization of FieldDecls matching
3750 // InitListFieldDecl.
3751 bool InitList;
3752 FieldDecl *InitListFieldDecl;
3753 llvm::SmallVector<unsigned, 4> InitFieldIndex;
3754
3755 public:
3756 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3757 UninitializedFieldVisitor(Sema &S,
3758 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3759 llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3760 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3761 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3762
3763 // Returns true if the use of ME is not an uninitialized use.
3764 bool IsInitListMemberExprInitialized(MemberExpr *ME,
3765 bool CheckReferenceOnly) {
3766 llvm::SmallVector<FieldDecl*, 4> Fields;
3767 bool ReferenceField = false;
3768 while (ME) {
3769 FieldDecl *FD = dyn_cast<FieldDecl>(Val: ME->getMemberDecl());
3770 if (!FD)
3771 return false;
3772 Fields.push_back(Elt: FD);
3773 if (FD->getType()->isReferenceType())
3774 ReferenceField = true;
3775 ME = dyn_cast<MemberExpr>(Val: ME->getBase()->IgnoreParenImpCasts());
3776 }
3777
3778 // Binding a reference to an uninitialized field is not an
3779 // uninitialized use.
3780 if (CheckReferenceOnly && !ReferenceField)
3781 return true;
3782
3783 // Discard the first field since it is the field decl that is being
3784 // initialized.
3785 auto UsedFields = llvm::drop_begin(RangeOrContainer: llvm::reverse(C&: Fields));
3786 auto UsedIter = UsedFields.begin();
3787 const auto UsedEnd = UsedFields.end();
3788
3789 for (const unsigned Orig : InitFieldIndex) {
3790 if (UsedIter == UsedEnd)
3791 break;
3792 const unsigned UsedIndex = (*UsedIter)->getFieldIndex();
3793 if (UsedIndex < Orig)
3794 return true;
3795 if (UsedIndex > Orig)
3796 break;
3797 ++UsedIter;
3798 }
3799
3800 return false;
3801 }
3802
3803 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3804 bool AddressOf) {
3805 if (isa<EnumConstantDecl>(Val: ME->getMemberDecl()))
3806 return;
3807
3808 // FieldME is the inner-most MemberExpr that is not an anonymous struct
3809 // or union.
3810 MemberExpr *FieldME = ME;
3811
3812 bool AllPODFields = FieldME->getType().isPODType(Context: S.Context);
3813
3814 Expr *Base = ME;
3815 while (MemberExpr *SubME =
3816 dyn_cast<MemberExpr>(Val: Base->IgnoreParenImpCasts())) {
3817
3818 if (isa<VarDecl>(Val: SubME->getMemberDecl()))
3819 return;
3820
3821 if (FieldDecl *FD = dyn_cast<FieldDecl>(Val: SubME->getMemberDecl()))
3822 if (!FD->isAnonymousStructOrUnion())
3823 FieldME = SubME;
3824
3825 if (!FieldME->getType().isPODType(Context: S.Context))
3826 AllPODFields = false;
3827
3828 Base = SubME->getBase();
3829 }
3830
3831 if (!isa<CXXThisExpr>(Val: Base->IgnoreParenImpCasts())) {
3832 Visit(S: Base);
3833 return;
3834 }
3835
3836 if (AddressOf && AllPODFields)
3837 return;
3838
3839 ValueDecl* FoundVD = FieldME->getMemberDecl();
3840
3841 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Val: Base)) {
3842 while (isa<ImplicitCastExpr>(Val: BaseCast->getSubExpr())) {
3843 BaseCast = cast<ImplicitCastExpr>(Val: BaseCast->getSubExpr());
3844 }
3845
3846 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3847 QualType T = BaseCast->getType();
3848 if (T->isPointerType() &&
3849 BaseClasses.count(Ptr: T->getPointeeType())) {
3850 S.Diag(Loc: FieldME->getExprLoc(), DiagID: diag::warn_base_class_is_uninit)
3851 << T->getPointeeType() << FoundVD;
3852 }
3853 }
3854 }
3855
3856 if (!Decls.count(Ptr: FoundVD))
3857 return;
3858
3859 const bool IsReference = FoundVD->getType()->isReferenceType();
3860
3861 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3862 // Special checking for initializer lists.
3863 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3864 return;
3865 }
3866 } else {
3867 // Prevent double warnings on use of unbounded references.
3868 if (CheckReferenceOnly && !IsReference)
3869 return;
3870 }
3871
3872 unsigned diag = IsReference
3873 ? diag::warn_reference_field_is_uninit
3874 : diag::warn_field_is_uninit;
3875 S.Diag(Loc: FieldME->getExprLoc(), DiagID: diag) << FoundVD;
3876 if (Constructor)
3877 S.Diag(Loc: Constructor->getLocation(),
3878 DiagID: diag::note_uninit_in_this_constructor)
3879 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3880
3881 }
3882
3883 void HandleValue(Expr *E, bool AddressOf) {
3884 E = E->IgnoreParens();
3885
3886 if (MemberExpr *ME = dyn_cast<MemberExpr>(Val: E)) {
3887 HandleMemberExpr(ME, CheckReferenceOnly: false /*CheckReferenceOnly*/,
3888 AddressOf /*AddressOf*/);
3889 return;
3890 }
3891
3892 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(Val: E)) {
3893 Visit(S: CO->getCond());
3894 HandleValue(E: CO->getTrueExpr(), AddressOf);
3895 HandleValue(E: CO->getFalseExpr(), AddressOf);
3896 return;
3897 }
3898
3899 if (BinaryConditionalOperator *BCO =
3900 dyn_cast<BinaryConditionalOperator>(Val: E)) {
3901 Visit(S: BCO->getCond());
3902 HandleValue(E: BCO->getFalseExpr(), AddressOf);
3903 return;
3904 }
3905
3906 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Val: E)) {
3907 HandleValue(E: OVE->getSourceExpr(), AddressOf);
3908 return;
3909 }
3910
3911 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: E)) {
3912 switch (BO->getOpcode()) {
3913 default:
3914 break;
3915 case(BO_PtrMemD):
3916 case(BO_PtrMemI):
3917 HandleValue(E: BO->getLHS(), AddressOf);
3918 Visit(S: BO->getRHS());
3919 return;
3920 case(BO_Comma):
3921 Visit(S: BO->getLHS());
3922 HandleValue(E: BO->getRHS(), AddressOf);
3923 return;
3924 }
3925 }
3926
3927 Visit(S: E);
3928 }
3929
3930 void CheckInitListExpr(InitListExpr *ILE) {
3931 InitFieldIndex.push_back(Elt: 0);
3932 for (auto *Child : ILE->children()) {
3933 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Val: Child)) {
3934 CheckInitListExpr(ILE: SubList);
3935 } else {
3936 Visit(S: Child);
3937 }
3938 ++InitFieldIndex.back();
3939 }
3940 InitFieldIndex.pop_back();
3941 }
3942
3943 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3944 FieldDecl *Field, const Type *BaseClass) {
3945 // Remove Decls that may have been initialized in the previous
3946 // initializer.
3947 for (ValueDecl* VD : DeclsToRemove)
3948 Decls.erase(Ptr: VD);
3949 DeclsToRemove.clear();
3950
3951 Constructor = FieldConstructor;
3952 InitListExpr *ILE = dyn_cast<InitListExpr>(Val: E);
3953
3954 if (ILE && Field) {
3955 InitList = true;
3956 InitListFieldDecl = Field;
3957 InitFieldIndex.clear();
3958 CheckInitListExpr(ILE);
3959 } else {
3960 InitList = false;
3961 Visit(S: E);
3962 }
3963
3964 if (Field)
3965 Decls.erase(Ptr: Field);
3966 if (BaseClass)
3967 BaseClasses.erase(Ptr: BaseClass->getCanonicalTypeInternal());
3968 }
3969
3970 void VisitMemberExpr(MemberExpr *ME) {
3971 // All uses of unbounded reference fields will warn.
3972 HandleMemberExpr(ME, CheckReferenceOnly: true /*CheckReferenceOnly*/, AddressOf: false /*AddressOf*/);
3973 }
3974
3975 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3976 if (E->getCastKind() == CK_LValueToRValue) {
3977 HandleValue(E: E->getSubExpr(), AddressOf: false /*AddressOf*/);
3978 return;
3979 }
3980
3981 Inherited::VisitImplicitCastExpr(S: E);
3982 }
3983
3984 void VisitCXXConstructExpr(CXXConstructExpr *E) {
3985 if (E->getConstructor()->isCopyConstructor()) {
3986 Expr *ArgExpr = E->getArg(Arg: 0);
3987 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Val: ArgExpr))
3988 if (ILE->getNumInits() == 1)
3989 ArgExpr = ILE->getInit(Init: 0);
3990 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: ArgExpr))
3991 if (ICE->getCastKind() == CK_NoOp)
3992 ArgExpr = ICE->getSubExpr();
3993 HandleValue(E: ArgExpr, AddressOf: false /*AddressOf*/);
3994 return;
3995 }
3996 Inherited::VisitCXXConstructExpr(S: E);
3997 }
3998
3999 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
4000 Expr *Callee = E->getCallee();
4001 if (isa<MemberExpr>(Val: Callee)) {
4002 HandleValue(E: Callee, AddressOf: false /*AddressOf*/);
4003 for (auto *Arg : E->arguments())
4004 Visit(S: Arg);
4005 return;
4006 }
4007
4008 Inherited::VisitCXXMemberCallExpr(S: E);
4009 }
4010
4011 void VisitCallExpr(CallExpr *E) {
4012 // Treat std::move as a use.
4013 if (E->isCallToStdMove()) {
4014 HandleValue(E: E->getArg(Arg: 0), /*AddressOf=*/false);
4015 return;
4016 }
4017
4018 Inherited::VisitCallExpr(CE: E);
4019 }
4020
4021 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
4022 Expr *Callee = E->getCallee();
4023
4024 if (isa<UnresolvedLookupExpr>(Val: Callee))
4025 return Inherited::VisitCXXOperatorCallExpr(S: E);
4026
4027 Visit(S: Callee);
4028 for (auto *Arg : E->arguments())
4029 HandleValue(E: Arg->IgnoreParenImpCasts(), AddressOf: false /*AddressOf*/);
4030 }
4031
4032 void VisitBinaryOperator(BinaryOperator *E) {
4033 // If a field assignment is detected, remove the field from the
4034 // uninitiailized field set.
4035 if (E->getOpcode() == BO_Assign)
4036 if (MemberExpr *ME = dyn_cast<MemberExpr>(Val: E->getLHS()))
4037 if (FieldDecl *FD = dyn_cast<FieldDecl>(Val: ME->getMemberDecl()))
4038 if (!FD->getType()->isReferenceType())
4039 DeclsToRemove.push_back(Elt: FD);
4040
4041 if (E->isCompoundAssignmentOp()) {
4042 HandleValue(E: E->getLHS(), AddressOf: false /*AddressOf*/);
4043 Visit(S: E->getRHS());
4044 return;
4045 }
4046
4047 Inherited::VisitBinaryOperator(S: E);
4048 }
4049
4050 void VisitUnaryOperator(UnaryOperator *E) {
4051 if (E->isIncrementDecrementOp()) {
4052 HandleValue(E: E->getSubExpr(), AddressOf: false /*AddressOf*/);
4053 return;
4054 }
4055 if (E->getOpcode() == UO_AddrOf) {
4056 if (MemberExpr *ME = dyn_cast<MemberExpr>(Val: E->getSubExpr())) {
4057 HandleValue(E: ME->getBase(), AddressOf: true /*AddressOf*/);
4058 return;
4059 }
4060 }
4061
4062 Inherited::VisitUnaryOperator(S: E);
4063 }
4064 };
4065
4066 // Diagnose value-uses of fields to initialize themselves, e.g.
4067 // foo(foo)
4068 // where foo is not also a parameter to the constructor.
4069 // Also diagnose across field uninitialized use such as
4070 // x(y), y(x)
4071 // TODO: implement -Wuninitialized and fold this into that framework.
4072 static void DiagnoseUninitializedFields(
4073 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
4074
4075 if (SemaRef.getDiagnostics().isIgnored(DiagID: diag::warn_field_is_uninit,
4076 Loc: Constructor->getLocation())) {
4077 return;
4078 }
4079
4080 if (Constructor->isInvalidDecl())
4081 return;
4082
4083 const CXXRecordDecl *RD = Constructor->getParent();
4084
4085 if (RD->isDependentContext())
4086 return;
4087
4088 // Holds fields that are uninitialized.
4089 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
4090
4091 // At the beginning, all fields are uninitialized.
4092 for (auto *I : RD->decls()) {
4093 if (auto *FD = dyn_cast<FieldDecl>(Val: I)) {
4094 UninitializedFields.insert(Ptr: FD);
4095 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(Val: I)) {
4096 UninitializedFields.insert(Ptr: IFD->getAnonField());
4097 }
4098 }
4099
4100 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
4101 for (const auto &I : RD->bases())
4102 UninitializedBaseClasses.insert(Ptr: I.getType().getCanonicalType());
4103
4104 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
4105 return;
4106
4107 UninitializedFieldVisitor UninitializedChecker(SemaRef,
4108 UninitializedFields,
4109 UninitializedBaseClasses);
4110
4111 for (const auto *FieldInit : Constructor->inits()) {
4112 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
4113 break;
4114
4115 Expr *InitExpr = FieldInit->getInit();
4116 if (!InitExpr)
4117 continue;
4118
4119 if (CXXDefaultInitExpr *Default =
4120 dyn_cast<CXXDefaultInitExpr>(Val: InitExpr)) {
4121 InitExpr = Default->getExpr();
4122 if (!InitExpr)
4123 continue;
4124 // In class initializers will point to the constructor.
4125 UninitializedChecker.CheckInitializer(E: InitExpr, FieldConstructor: Constructor,
4126 Field: FieldInit->getAnyMember(),
4127 BaseClass: FieldInit->getBaseClass());
4128 } else {
4129 UninitializedChecker.CheckInitializer(E: InitExpr, FieldConstructor: nullptr,
4130 Field: FieldInit->getAnyMember(),
4131 BaseClass: FieldInit->getBaseClass());
4132 }
4133 }
4134 }
4135} // namespace
4136
4137void Sema::ActOnStartCXXInClassMemberInitializer() {
4138 // Create a synthetic function scope to represent the call to the constructor
4139 // that notionally surrounds a use of this initializer.
4140 PushFunctionScope();
4141}
4142
4143void Sema::ActOnStartTrailingRequiresClause(Scope *S, Declarator &D) {
4144 if (!D.isFunctionDeclarator())
4145 return;
4146 auto &FTI = D.getFunctionTypeInfo();
4147 if (!FTI.Params)
4148 return;
4149 for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params,
4150 FTI.NumParams)) {
4151 auto *ParamDecl = cast<NamedDecl>(Val: Param.Param);
4152 if (ParamDecl->getDeclName())
4153 PushOnScopeChains(D: ParamDecl, S, /*AddToContext=*/false);
4154 }
4155}
4156
4157ExprResult Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr) {
4158 return ActOnRequiresClause(ConstraintExpr);
4159}
4160
4161ExprResult Sema::ActOnRequiresClause(ExprResult ConstraintExpr) {
4162 if (ConstraintExpr.isInvalid())
4163 return ExprError();
4164
4165 if (DiagnoseUnexpandedParameterPack(E: ConstraintExpr.get(),
4166 UPPC: UPPC_RequiresClause))
4167 return ExprError();
4168
4169 return ConstraintExpr;
4170}
4171
4172ExprResult Sema::ConvertMemberDefaultInitExpression(FieldDecl *FD,
4173 Expr *InitExpr,
4174 SourceLocation InitLoc) {
4175 InitializedEntity Entity =
4176 InitializedEntity::InitializeMemberFromDefaultMemberInitializer(Member: FD);
4177 InitializationKind Kind =
4178 FD->getInClassInitStyle() == ICIS_ListInit
4179 ? InitializationKind::CreateDirectList(InitLoc: InitExpr->getBeginLoc(),
4180 LBraceLoc: InitExpr->getBeginLoc(),
4181 RBraceLoc: InitExpr->getEndLoc())
4182 : InitializationKind::CreateCopy(InitLoc: InitExpr->getBeginLoc(), EqualLoc: InitLoc);
4183 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
4184 return Seq.Perform(S&: *this, Entity, Kind, Args: InitExpr);
4185}
4186
4187void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
4188 SourceLocation InitLoc,
4189 ExprResult InitExpr) {
4190 // Pop the notional constructor scope we created earlier.
4191 PopFunctionScopeInfo(WP: nullptr, D);
4192
4193 // Microsoft C++'s property declaration cannot have a default member
4194 // initializer.
4195 if (isa<MSPropertyDecl>(Val: D)) {
4196 D->setInvalidDecl();
4197 return;
4198 }
4199
4200 FieldDecl *FD = dyn_cast<FieldDecl>(Val: D);
4201 assert((FD && FD->getInClassInitStyle() != ICIS_NoInit) &&
4202 "must set init style when field is created");
4203
4204 if (!InitExpr.isUsable() ||
4205 DiagnoseUnexpandedParameterPack(E: InitExpr.get(), UPPC: UPPC_Initializer)) {
4206 FD->setInvalidDecl();
4207 ExprResult RecoveryInit =
4208 CreateRecoveryExpr(Begin: InitLoc, End: InitLoc, SubExprs: {}, T: FD->getType());
4209 if (RecoveryInit.isUsable())
4210 FD->setInClassInitializer(RecoveryInit.get());
4211 return;
4212 }
4213
4214 if (!FD->getType()->isDependentType() && !InitExpr.get()->isTypeDependent()) {
4215 InitExpr = ConvertMemberDefaultInitExpression(FD, InitExpr: InitExpr.get(), InitLoc);
4216 // C++11 [class.base.init]p7:
4217 // The initialization of each base and member constitutes a
4218 // full-expression.
4219 if (!InitExpr.isInvalid())
4220 InitExpr = ActOnFinishFullExpr(Expr: InitExpr.get(), /*DiscarededValue=*/DiscardedValue: false);
4221 if (InitExpr.isInvalid()) {
4222 FD->setInvalidDecl();
4223 return;
4224 }
4225 }
4226
4227 FD->setInClassInitializer(InitExpr.get());
4228}
4229
4230/// Find the direct and/or virtual base specifiers that
4231/// correspond to the given base type, for use in base initialization
4232/// within a constructor.
4233static bool FindBaseInitializer(Sema &SemaRef,
4234 CXXRecordDecl *ClassDecl,
4235 QualType BaseType,
4236 const CXXBaseSpecifier *&DirectBaseSpec,
4237 const CXXBaseSpecifier *&VirtualBaseSpec) {
4238 // First, check for a direct base class.
4239 DirectBaseSpec = nullptr;
4240 for (const auto &Base : ClassDecl->bases()) {
4241 if (SemaRef.Context.hasSameUnqualifiedType(T1: BaseType, T2: Base.getType())) {
4242 // We found a direct base of this type. That's what we're
4243 // initializing.
4244 DirectBaseSpec = &Base;
4245 break;
4246 }
4247 }
4248
4249 // Check for a virtual base class.
4250 // FIXME: We might be able to short-circuit this if we know in advance that
4251 // there are no virtual bases.
4252 VirtualBaseSpec = nullptr;
4253 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
4254 // We haven't found a base yet; search the class hierarchy for a
4255 // virtual base class.
4256 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
4257 /*DetectVirtual=*/false);
4258 if (SemaRef.IsDerivedFrom(Loc: ClassDecl->getLocation(),
4259 Derived: SemaRef.Context.getCanonicalTagType(TD: ClassDecl),
4260 Base: BaseType, Paths)) {
4261 for (const CXXBasePath &Path : Paths) {
4262 if (Path.back().Base->isVirtual()) {
4263 VirtualBaseSpec = Path.back().Base;
4264 break;
4265 }
4266 }
4267 }
4268 }
4269
4270 return DirectBaseSpec || VirtualBaseSpec;
4271}
4272
4273MemInitResult
4274Sema::ActOnMemInitializer(Decl *ConstructorD,
4275 Scope *S,
4276 CXXScopeSpec &SS,
4277 IdentifierInfo *MemberOrBase,
4278 ParsedType TemplateTypeTy,
4279 const DeclSpec &DS,
4280 SourceLocation IdLoc,
4281 Expr *InitList,
4282 SourceLocation EllipsisLoc) {
4283 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4284 DS, IdLoc, Init: InitList,
4285 EllipsisLoc);
4286}
4287
4288MemInitResult
4289Sema::ActOnMemInitializer(Decl *ConstructorD,
4290 Scope *S,
4291 CXXScopeSpec &SS,
4292 IdentifierInfo *MemberOrBase,
4293 ParsedType TemplateTypeTy,
4294 const DeclSpec &DS,
4295 SourceLocation IdLoc,
4296 SourceLocation LParenLoc,
4297 ArrayRef<Expr *> Args,
4298 SourceLocation RParenLoc,
4299 SourceLocation EllipsisLoc) {
4300 Expr *List = ParenListExpr::Create(Ctx: Context, LParenLoc, Exprs: Args, RParenLoc);
4301 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4302 DS, IdLoc, Init: List, EllipsisLoc);
4303}
4304
4305namespace {
4306
4307// Callback to only accept typo corrections that can be a valid C++ member
4308// initializer: either a non-static field member or a base class.
4309class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
4310public:
4311 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
4312 : ClassDecl(ClassDecl) {}
4313
4314 bool ValidateCandidate(const TypoCorrection &candidate) override {
4315 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
4316 if (FieldDecl *Member = dyn_cast<FieldDecl>(Val: ND))
4317 return Member->getDeclContext()->getRedeclContext()->Equals(DC: ClassDecl);
4318 return isa<TypeDecl>(Val: ND);
4319 }
4320 return false;
4321 }
4322
4323 std::unique_ptr<CorrectionCandidateCallback> clone() override {
4324 return std::make_unique<MemInitializerValidatorCCC>(args&: *this);
4325 }
4326
4327private:
4328 CXXRecordDecl *ClassDecl;
4329};
4330
4331}
4332
4333bool Sema::DiagRedefinedPlaceholderFieldDecl(SourceLocation Loc,
4334 RecordDecl *ClassDecl,
4335 const IdentifierInfo *Name) {
4336 DeclContextLookupResult Result = ClassDecl->lookup(Name);
4337 DeclContextLookupResult::iterator Found =
4338 llvm::find_if(Range&: Result, P: [this](const NamedDecl *Elem) {
4339 return isa<FieldDecl, IndirectFieldDecl>(Val: Elem) &&
4340 Elem->isPlaceholderVar(LangOpts: getLangOpts());
4341 });
4342 // We did not find a placeholder variable
4343 if (Found == Result.end())
4344 return false;
4345 Diag(Loc, DiagID: diag::err_using_placeholder_variable) << Name;
4346 for (DeclContextLookupResult::iterator It = Found; It != Result.end(); It++) {
4347 const NamedDecl *ND = *It;
4348 if (ND->getDeclContext() != ND->getDeclContext())
4349 break;
4350 if (isa<FieldDecl, IndirectFieldDecl>(Val: ND) &&
4351 ND->isPlaceholderVar(LangOpts: getLangOpts()))
4352 Diag(Loc: ND->getLocation(), DiagID: diag::note_reference_placeholder) << ND;
4353 }
4354 return true;
4355}
4356
4357ValueDecl *
4358Sema::tryLookupUnambiguousFieldDecl(RecordDecl *ClassDecl,
4359 const IdentifierInfo *MemberOrBase) {
4360 ValueDecl *ND = nullptr;
4361 for (auto *D : ClassDecl->lookup(Name: MemberOrBase)) {
4362 if (isa<FieldDecl, IndirectFieldDecl>(Val: D)) {
4363 bool IsPlaceholder = D->isPlaceholderVar(LangOpts: getLangOpts());
4364 if (ND) {
4365 if (IsPlaceholder && D->getDeclContext() == ND->getDeclContext())
4366 return nullptr;
4367 break;
4368 }
4369 if (!IsPlaceholder)
4370 return cast<ValueDecl>(Val: D);
4371 ND = cast<ValueDecl>(Val: D);
4372 }
4373 }
4374 return ND;
4375}
4376
4377ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
4378 CXXScopeSpec &SS,
4379 ParsedType TemplateTypeTy,
4380 IdentifierInfo *MemberOrBase) {
4381 if (SS.getScopeRep() || TemplateTypeTy)
4382 return nullptr;
4383 return tryLookupUnambiguousFieldDecl(ClassDecl, MemberOrBase);
4384}
4385
4386MemInitResult
4387Sema::BuildMemInitializer(Decl *ConstructorD,
4388 Scope *S,
4389 CXXScopeSpec &SS,
4390 IdentifierInfo *MemberOrBase,
4391 ParsedType TemplateTypeTy,
4392 const DeclSpec &DS,
4393 SourceLocation IdLoc,
4394 Expr *Init,
4395 SourceLocation EllipsisLoc) {
4396 if (!ConstructorD || !Init)
4397 return true;
4398
4399 AdjustDeclIfTemplate(Decl&: ConstructorD);
4400
4401 CXXConstructorDecl *Constructor
4402 = dyn_cast<CXXConstructorDecl>(Val: ConstructorD);
4403 if (!Constructor) {
4404 // The user wrote a constructor initializer on a function that is
4405 // not a C++ constructor. Ignore the error for now, because we may
4406 // have more member initializers coming; we'll diagnose it just
4407 // once in ActOnMemInitializers.
4408 return true;
4409 }
4410
4411 CXXRecordDecl *ClassDecl = Constructor->getParent();
4412
4413 // C++ [class.base.init]p2:
4414 // Names in a mem-initializer-id are looked up in the scope of the
4415 // constructor's class and, if not found in that scope, are looked
4416 // up in the scope containing the constructor's definition.
4417 // [Note: if the constructor's class contains a member with the
4418 // same name as a direct or virtual base class of the class, a
4419 // mem-initializer-id naming the member or base class and composed
4420 // of a single identifier refers to the class member. A
4421 // mem-initializer-id for the hidden base class may be specified
4422 // using a qualified name. ]
4423
4424 // Look for a member, first.
4425 if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
4426 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
4427 if (EllipsisLoc.isValid())
4428 Diag(Loc: EllipsisLoc, DiagID: diag::err_pack_expansion_member_init)
4429 << MemberOrBase
4430 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4431
4432 return BuildMemberInitializer(Member, Init, IdLoc);
4433 }
4434 // It didn't name a member, so see if it names a class.
4435 QualType BaseType;
4436 TypeSourceInfo *TInfo = nullptr;
4437
4438 if (TemplateTypeTy) {
4439 BaseType = GetTypeFromParser(Ty: TemplateTypeTy, TInfo: &TInfo);
4440 if (BaseType.isNull())
4441 return true;
4442 } else if (DS.getTypeSpecType() == TST_decltype) {
4443 BaseType = BuildDecltypeType(E: DS.getRepAsExpr());
4444 } else if (DS.getTypeSpecType() == TST_decltype_auto) {
4445 Diag(Loc: DS.getTypeSpecTypeLoc(), DiagID: diag::err_decltype_auto_invalid);
4446 return true;
4447 } else if (DS.getTypeSpecType() == TST_typename_pack_indexing) {
4448 BaseType =
4449 BuildPackIndexingType(Pattern: DS.getRepAsType().get(), IndexExpr: DS.getPackIndexingExpr(),
4450 Loc: DS.getBeginLoc(), EllipsisLoc: DS.getEllipsisLoc());
4451 } else {
4452 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
4453 LookupParsedName(R, S, SS: &SS, /*ObjectType=*/QualType());
4454
4455 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
4456 if (!TyD) {
4457 if (R.isAmbiguous()) return true;
4458
4459 // We don't want access-control diagnostics here.
4460 R.suppressDiagnostics();
4461
4462 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
4463 bool NotUnknownSpecialization = false;
4464 DeclContext *DC = computeDeclContext(SS, EnteringContext: false);
4465 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Val: DC))
4466 NotUnknownSpecialization = !Record->hasAnyDependentBases();
4467
4468 if (!NotUnknownSpecialization) {
4469 // When the scope specifier can refer to a member of an unknown
4470 // specialization, we take it as a type name.
4471 BaseType = CheckTypenameType(
4472 Keyword: ElaboratedTypeKeyword::None, KeywordLoc: SourceLocation(),
4473 QualifierLoc: SS.getWithLocInContext(Context), II: *MemberOrBase, IILoc: IdLoc);
4474 if (BaseType.isNull())
4475 return true;
4476
4477 TInfo = Context.CreateTypeSourceInfo(T: BaseType);
4478 DependentNameTypeLoc TL =
4479 TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
4480 if (!TL.isNull()) {
4481 TL.setNameLoc(IdLoc);
4482 TL.setElaboratedKeywordLoc(SourceLocation());
4483 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4484 }
4485
4486 R.clear();
4487 R.setLookupName(MemberOrBase);
4488 }
4489 }
4490
4491 if (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus20) {
4492 if (auto UnqualifiedBase = R.getAsSingle<ClassTemplateDecl>()) {
4493 auto *TempSpec = cast<TemplateSpecializationType>(
4494 Val: UnqualifiedBase->getCanonicalInjectedSpecializationType(Ctx: Context));
4495 TemplateName TN = TempSpec->getTemplateName();
4496 for (auto const &Base : ClassDecl->bases()) {
4497 auto BaseTemplate =
4498 Base.getType()->getAs<TemplateSpecializationType>();
4499 if (BaseTemplate &&
4500 Context.hasSameTemplateName(X: BaseTemplate->getTemplateName(), Y: TN,
4501 /*IgnoreDeduced=*/true)) {
4502 Diag(Loc: IdLoc, DiagID: diag::ext_unqualified_base_class)
4503 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4504 BaseType = Base.getType();
4505 break;
4506 }
4507 }
4508 }
4509 }
4510
4511 // If no results were found, try to correct typos.
4512 TypoCorrection Corr;
4513 MemInitializerValidatorCCC CCC(ClassDecl);
4514 if (R.empty() && BaseType.isNull() &&
4515 (Corr =
4516 CorrectTypo(Typo: R.getLookupNameInfo(), LookupKind: R.getLookupKind(), S, SS: &SS,
4517 CCC, Mode: CorrectTypoKind::ErrorRecovery, MemberContext: ClassDecl))) {
4518 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
4519 // We have found a non-static data member with a similar
4520 // name to what was typed; complain and initialize that
4521 // member.
4522 diagnoseTypo(Correction: Corr,
4523 TypoDiag: PDiag(DiagID: diag::err_mem_init_not_member_or_class_suggest)
4524 << MemberOrBase << true);
4525 return BuildMemberInitializer(Member, Init, IdLoc);
4526 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
4527 const CXXBaseSpecifier *DirectBaseSpec;
4528 const CXXBaseSpecifier *VirtualBaseSpec;
4529 if (FindBaseInitializer(SemaRef&: *this, ClassDecl,
4530 BaseType: Context.getTypeDeclType(Decl: Type),
4531 DirectBaseSpec, VirtualBaseSpec)) {
4532 // We have found a direct or virtual base class with a
4533 // similar name to what was typed; complain and initialize
4534 // that base class.
4535 diagnoseTypo(Correction: Corr,
4536 TypoDiag: PDiag(DiagID: diag::err_mem_init_not_member_or_class_suggest)
4537 << MemberOrBase << false,
4538 PrevNote: PDiag() /*Suppress note, we provide our own.*/);
4539
4540 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
4541 : VirtualBaseSpec;
4542 Diag(Loc: BaseSpec->getBeginLoc(), DiagID: diag::note_base_class_specified_here)
4543 << BaseSpec->getType() << BaseSpec->getSourceRange();
4544
4545 TyD = Type;
4546 }
4547 }
4548 }
4549
4550 if (!TyD && BaseType.isNull()) {
4551 Diag(Loc: IdLoc, DiagID: diag::err_mem_init_not_member_or_class)
4552 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4553 return true;
4554 }
4555 }
4556
4557 if (BaseType.isNull()) {
4558 MarkAnyDeclReferenced(Loc: TyD->getLocation(), D: TyD, /*OdrUse=*/MightBeOdrUse: false);
4559
4560 TypeLocBuilder TLB;
4561 // FIXME: This is missing building the UsingType for TyD, if any.
4562 if (const auto *TD = dyn_cast<TagDecl>(Val: TyD)) {
4563 BaseType = Context.getTagType(Keyword: ElaboratedTypeKeyword::None,
4564 Qualifier: SS.getScopeRep(), TD, /*OwnsTag=*/false);
4565 auto TL = TLB.push<TagTypeLoc>(T: BaseType);
4566 TL.setElaboratedKeywordLoc(SourceLocation());
4567 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4568 TL.setNameLoc(IdLoc);
4569 } else if (auto *TN = dyn_cast<TypedefNameDecl>(Val: TyD)) {
4570 BaseType = Context.getTypedefType(Keyword: ElaboratedTypeKeyword::None,
4571 Qualifier: SS.getScopeRep(), Decl: TN);
4572 TLB.push<TypedefTypeLoc>(T: BaseType).set(
4573 /*ElaboratedKeywordLoc=*/SourceLocation(),
4574 QualifierLoc: SS.getWithLocInContext(Context), NameLoc: IdLoc);
4575 } else if (auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(Val: TyD)) {
4576 BaseType = Context.getUnresolvedUsingType(Keyword: ElaboratedTypeKeyword::None,
4577 Qualifier: SS.getScopeRep(), D: UD);
4578 TLB.push<UnresolvedUsingTypeLoc>(T: BaseType).set(
4579 /*ElaboratedKeywordLoc=*/SourceLocation(),
4580 QualifierLoc: SS.getWithLocInContext(Context), NameLoc: IdLoc);
4581 } else {
4582 // FIXME: What else can appear here?
4583 assert(SS.isEmpty());
4584 BaseType = Context.getTypeDeclType(Decl: TyD);
4585 TLB.pushTypeSpec(T: BaseType).setNameLoc(IdLoc);
4586 }
4587 TInfo = TLB.getTypeSourceInfo(Context, T: BaseType);
4588 }
4589 }
4590
4591 if (!TInfo)
4592 TInfo = Context.getTrivialTypeSourceInfo(T: BaseType, Loc: IdLoc);
4593
4594 return BuildBaseInitializer(BaseType, BaseTInfo: TInfo, Init, ClassDecl, EllipsisLoc);
4595}
4596
4597MemInitResult
4598Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
4599 SourceLocation IdLoc) {
4600 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Val: Member);
4601 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Val: Member);
4602 assert((DirectMember || IndirectMember) &&
4603 "Member must be a FieldDecl or IndirectFieldDecl");
4604
4605 if (DiagnoseUnexpandedParameterPack(E: Init, UPPC: UPPC_Initializer))
4606 return true;
4607
4608 if (Member->isInvalidDecl())
4609 return true;
4610
4611 MultiExprArg Args;
4612 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Val: Init)) {
4613 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4614 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Val: Init)) {
4615 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4616 } else {
4617 // Template instantiation doesn't reconstruct ParenListExprs for us.
4618 Args = Init;
4619 }
4620
4621 SourceRange InitRange = Init->getSourceRange();
4622
4623 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4624 // Can't check initialization for a member of dependent type or when
4625 // any of the arguments are type-dependent expressions.
4626 DiscardCleanupsInEvaluationContext();
4627 } else {
4628 bool InitList = false;
4629 if (isa<InitListExpr>(Val: Init)) {
4630 InitList = true;
4631 Args = Init;
4632 }
4633
4634 // Initialize the member.
4635 InitializedEntity MemberEntity =
4636 DirectMember ? InitializedEntity::InitializeMember(Member: DirectMember, Parent: nullptr)
4637 : InitializedEntity::InitializeMember(Member: IndirectMember,
4638 Parent: nullptr);
4639 InitializationKind Kind =
4640 InitList ? InitializationKind::CreateDirectList(
4641 InitLoc: IdLoc, LBraceLoc: Init->getBeginLoc(), RBraceLoc: Init->getEndLoc())
4642 : InitializationKind::CreateDirect(InitLoc: IdLoc, LParenLoc: InitRange.getBegin(),
4643 RParenLoc: InitRange.getEnd());
4644
4645 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4646 ExprResult MemberInit = InitSeq.Perform(S&: *this, Entity: MemberEntity, Kind, Args,
4647 ResultType: nullptr);
4648 if (!MemberInit.isInvalid()) {
4649 // C++11 [class.base.init]p7:
4650 // The initialization of each base and member constitutes a
4651 // full-expression.
4652 MemberInit = ActOnFinishFullExpr(Expr: MemberInit.get(), CC: InitRange.getBegin(),
4653 /*DiscardedValue*/ false);
4654 }
4655
4656 if (MemberInit.isInvalid()) {
4657 // Args were sensible expressions but we couldn't initialize the member
4658 // from them. Preserve them in a RecoveryExpr instead.
4659 Init = CreateRecoveryExpr(Begin: InitRange.getBegin(), End: InitRange.getEnd(), SubExprs: Args,
4660 T: Member->getType())
4661 .get();
4662 if (!Init)
4663 return true;
4664 } else {
4665 Init = MemberInit.get();
4666 }
4667 }
4668
4669 if (DirectMember) {
4670 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4671 InitRange.getBegin(), Init,
4672 InitRange.getEnd());
4673 } else {
4674 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4675 InitRange.getBegin(), Init,
4676 InitRange.getEnd());
4677 }
4678}
4679
4680MemInitResult
4681Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
4682 CXXRecordDecl *ClassDecl) {
4683 SourceLocation NameLoc = TInfo->getTypeLoc().getSourceRange().getBegin();
4684 if (!LangOpts.CPlusPlus11)
4685 return Diag(Loc: NameLoc, DiagID: diag::err_delegating_ctor)
4686 << TInfo->getTypeLoc().getSourceRange();
4687 Diag(Loc: NameLoc, DiagID: diag::warn_cxx98_compat_delegating_ctor);
4688
4689 bool InitList = true;
4690 MultiExprArg Args = Init;
4691 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Val: Init)) {
4692 InitList = false;
4693 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4694 }
4695
4696 CanQualType ClassType = Context.getCanonicalTagType(TD: ClassDecl);
4697
4698 SourceRange InitRange = Init->getSourceRange();
4699 // Initialize the object.
4700 InitializedEntity DelegationEntity =
4701 InitializedEntity::InitializeDelegation(Type: ClassType);
4702 InitializationKind Kind =
4703 InitList ? InitializationKind::CreateDirectList(
4704 InitLoc: NameLoc, LBraceLoc: Init->getBeginLoc(), RBraceLoc: Init->getEndLoc())
4705 : InitializationKind::CreateDirect(InitLoc: NameLoc, LParenLoc: InitRange.getBegin(),
4706 RParenLoc: InitRange.getEnd());
4707 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4708 ExprResult DelegationInit = InitSeq.Perform(S&: *this, Entity: DelegationEntity, Kind,
4709 Args, ResultType: nullptr);
4710 if (!DelegationInit.isInvalid()) {
4711 assert((DelegationInit.get()->containsErrors() ||
4712 cast<CXXConstructExpr>(DelegationInit.get())->getConstructor()) &&
4713 "Delegating constructor with no target?");
4714
4715 // C++11 [class.base.init]p7:
4716 // The initialization of each base and member constitutes a
4717 // full-expression.
4718 DelegationInit = ActOnFinishFullExpr(
4719 Expr: DelegationInit.get(), CC: InitRange.getBegin(), /*DiscardedValue*/ false);
4720 }
4721
4722 if (DelegationInit.isInvalid()) {
4723 DelegationInit = CreateRecoveryExpr(Begin: InitRange.getBegin(),
4724 End: InitRange.getEnd(), SubExprs: Args, T: ClassType);
4725 if (DelegationInit.isInvalid())
4726 return true;
4727 } else {
4728 // If we are in a dependent context, template instantiation will
4729 // perform this type-checking again. Just save the arguments that we
4730 // received in a ParenListExpr.
4731 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4732 // of the information that we have about the base
4733 // initializer. However, deconstructing the ASTs is a dicey process,
4734 // and this approach is far more likely to get the corner cases right.
4735 if (CurContext->isDependentContext())
4736 DelegationInit = Init;
4737 }
4738
4739 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4740 DelegationInit.getAs<Expr>(),
4741 InitRange.getEnd());
4742}
4743
4744MemInitResult
4745Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4746 Expr *Init, CXXRecordDecl *ClassDecl,
4747 SourceLocation EllipsisLoc) {
4748 SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getBeginLoc();
4749
4750 if (!BaseType->isDependentType() && !BaseType->isRecordType())
4751 return Diag(Loc: BaseLoc, DiagID: diag::err_base_init_does_not_name_class)
4752 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
4753
4754 // C++ [class.base.init]p2:
4755 // [...] Unless the mem-initializer-id names a nonstatic data
4756 // member of the constructor's class or a direct or virtual base
4757 // of that class, the mem-initializer is ill-formed. A
4758 // mem-initializer-list can initialize a base class using any
4759 // name that denotes that base class type.
4760
4761 // We can store the initializers in "as-written" form and delay analysis until
4762 // instantiation if the constructor is dependent. But not for dependent
4763 // (broken) code in a non-template! SetCtorInitializers does not expect this.
4764 bool Dependent = CurContext->isDependentContext() &&
4765 (BaseType->isDependentType() || Init->isTypeDependent());
4766
4767 SourceRange InitRange = Init->getSourceRange();
4768 if (EllipsisLoc.isValid()) {
4769 // This is a pack expansion.
4770 if (!BaseType->containsUnexpandedParameterPack()) {
4771 Diag(Loc: EllipsisLoc, DiagID: diag::err_pack_expansion_without_parameter_packs)
4772 << SourceRange(BaseLoc, InitRange.getEnd());
4773
4774 EllipsisLoc = SourceLocation();
4775 }
4776 } else {
4777 // Check for any unexpanded parameter packs.
4778 if (DiagnoseUnexpandedParameterPack(Loc: BaseLoc, T: BaseTInfo, UPPC: UPPC_Initializer))
4779 return true;
4780
4781 if (DiagnoseUnexpandedParameterPack(E: Init, UPPC: UPPC_Initializer))
4782 return true;
4783 }
4784
4785 // Check for direct and virtual base classes.
4786 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4787 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4788 if (!Dependent) {
4789 if (declaresSameEntity(D1: ClassDecl, D2: BaseType->getAsCXXRecordDecl()))
4790 return BuildDelegatingInitializer(TInfo: BaseTInfo, Init, ClassDecl);
4791
4792 FindBaseInitializer(SemaRef&: *this, ClassDecl, BaseType, DirectBaseSpec,
4793 VirtualBaseSpec);
4794
4795 // C++ [base.class.init]p2:
4796 // Unless the mem-initializer-id names a nonstatic data member of the
4797 // constructor's class or a direct or virtual base of that class, the
4798 // mem-initializer is ill-formed.
4799 if (!DirectBaseSpec && !VirtualBaseSpec) {
4800 // If the class has any dependent bases, then it's possible that
4801 // one of those types will resolve to the same type as
4802 // BaseType. Therefore, just treat this as a dependent base
4803 // class initialization. FIXME: Should we try to check the
4804 // initialization anyway? It seems odd.
4805 if (ClassDecl->hasAnyDependentBases())
4806 Dependent = true;
4807 else
4808 return Diag(Loc: BaseLoc, DiagID: diag::err_not_direct_base_or_virtual)
4809 << BaseType << Context.getCanonicalTagType(TD: ClassDecl)
4810 << BaseTInfo->getTypeLoc().getSourceRange();
4811 }
4812 }
4813
4814 if (Dependent) {
4815 DiscardCleanupsInEvaluationContext();
4816
4817 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4818 /*IsVirtual=*/false,
4819 InitRange.getBegin(), Init,
4820 InitRange.getEnd(), EllipsisLoc);
4821 }
4822
4823 // C++ [base.class.init]p2:
4824 // If a mem-initializer-id is ambiguous because it designates both
4825 // a direct non-virtual base class and an inherited virtual base
4826 // class, the mem-initializer is ill-formed.
4827 if (DirectBaseSpec && VirtualBaseSpec)
4828 return Diag(Loc: BaseLoc, DiagID: diag::err_base_init_direct_and_virtual)
4829 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4830
4831 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4832 if (!BaseSpec)
4833 BaseSpec = VirtualBaseSpec;
4834
4835 // Initialize the base.
4836 bool InitList = true;
4837 MultiExprArg Args = Init;
4838 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Val: Init)) {
4839 InitList = false;
4840 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4841 }
4842
4843 InitializedEntity BaseEntity =
4844 InitializedEntity::InitializeBase(Context, Base: BaseSpec, IsInheritedVirtualBase: VirtualBaseSpec);
4845 InitializationKind Kind =
4846 InitList ? InitializationKind::CreateDirectList(InitLoc: BaseLoc)
4847 : InitializationKind::CreateDirect(InitLoc: BaseLoc, LParenLoc: InitRange.getBegin(),
4848 RParenLoc: InitRange.getEnd());
4849 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4850 ExprResult BaseInit = InitSeq.Perform(S&: *this, Entity: BaseEntity, Kind, Args, ResultType: nullptr);
4851 if (!BaseInit.isInvalid()) {
4852 // C++11 [class.base.init]p7:
4853 // The initialization of each base and member constitutes a
4854 // full-expression.
4855 BaseInit = ActOnFinishFullExpr(Expr: BaseInit.get(), CC: InitRange.getBegin(),
4856 /*DiscardedValue*/ false);
4857 }
4858
4859 if (BaseInit.isInvalid()) {
4860 BaseInit = CreateRecoveryExpr(Begin: InitRange.getBegin(), End: InitRange.getEnd(),
4861 SubExprs: Args, T: BaseType);
4862 if (BaseInit.isInvalid())
4863 return true;
4864 } else {
4865 // If we are in a dependent context, template instantiation will
4866 // perform this type-checking again. Just save the arguments that we
4867 // received in a ParenListExpr.
4868 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4869 // of the information that we have about the base
4870 // initializer. However, deconstructing the ASTs is a dicey process,
4871 // and this approach is far more likely to get the corner cases right.
4872 if (CurContext->isDependentContext())
4873 BaseInit = Init;
4874 }
4875
4876 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4877 BaseSpec->isVirtual(),
4878 InitRange.getBegin(),
4879 BaseInit.getAs<Expr>(),
4880 InitRange.getEnd(), EllipsisLoc);
4881}
4882
4883// Create a static_cast\<T&&>(expr).
4884static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
4885 QualType TargetType =
4886 SemaRef.BuildReferenceType(T: E->getType(), /*SpelledAsLValue*/ LValueRef: false,
4887 Loc: SourceLocation(), Entity: DeclarationName());
4888 SourceLocation ExprLoc = E->getBeginLoc();
4889 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4890 T: TargetType, Loc: ExprLoc);
4891
4892 return SemaRef.BuildCXXNamedCast(OpLoc: ExprLoc, Kind: tok::kw_static_cast, Ty: TargetLoc, E,
4893 AngleBrackets: SourceRange(ExprLoc, ExprLoc),
4894 Parens: E->getSourceRange()).get();
4895}
4896
4897/// ImplicitInitializerKind - How an implicit base or member initializer should
4898/// initialize its base or member.
4899enum ImplicitInitializerKind {
4900 IIK_Default,
4901 IIK_Copy,
4902 IIK_Move,
4903 IIK_Inherit
4904};
4905
4906static bool
4907BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4908 ImplicitInitializerKind ImplicitInitKind,
4909 CXXBaseSpecifier *BaseSpec,
4910 bool IsInheritedVirtualBase,
4911 CXXCtorInitializer *&CXXBaseInit) {
4912 InitializedEntity InitEntity
4913 = InitializedEntity::InitializeBase(Context&: SemaRef.Context, Base: BaseSpec,
4914 IsInheritedVirtualBase);
4915
4916 ExprResult BaseInit;
4917
4918 switch (ImplicitInitKind) {
4919 case IIK_Inherit:
4920 case IIK_Default: {
4921 InitializationKind InitKind
4922 = InitializationKind::CreateDefault(InitLoc: Constructor->getLocation());
4923 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, {});
4924 BaseInit = InitSeq.Perform(S&: SemaRef, Entity: InitEntity, Kind: InitKind, Args: {});
4925 break;
4926 }
4927
4928 case IIK_Move:
4929 case IIK_Copy: {
4930 bool Moving = ImplicitInitKind == IIK_Move;
4931 ParmVarDecl *Param = Constructor->getParamDecl(i: 0);
4932 QualType ParamType = Param->getType().getNonReferenceType();
4933
4934 Expr *CopyCtorArg =
4935 DeclRefExpr::Create(Context: SemaRef.Context, QualifierLoc: NestedNameSpecifierLoc(),
4936 TemplateKWLoc: SourceLocation(), D: Param, RefersToEnclosingVariableOrCapture: false,
4937 NameLoc: Constructor->getLocation(), T: ParamType,
4938 VK: VK_LValue, FoundD: nullptr);
4939
4940 SemaRef.MarkDeclRefReferenced(E: cast<DeclRefExpr>(Val: CopyCtorArg));
4941
4942 // Cast to the base class to avoid ambiguities.
4943 QualType ArgTy =
4944 SemaRef.Context.getQualifiedType(T: BaseSpec->getType().getUnqualifiedType(),
4945 Qs: ParamType.getQualifiers());
4946
4947 if (Moving) {
4948 CopyCtorArg = CastForMoving(SemaRef, E: CopyCtorArg);
4949 }
4950
4951 CXXCastPath BasePath;
4952 BasePath.push_back(Elt: BaseSpec);
4953 CopyCtorArg = SemaRef.ImpCastExprToType(E: CopyCtorArg, Type: ArgTy,
4954 CK: CK_UncheckedDerivedToBase,
4955 VK: Moving ? VK_XValue : VK_LValue,
4956 BasePath: &BasePath).get();
4957
4958 InitializationKind InitKind
4959 = InitializationKind::CreateDirect(InitLoc: Constructor->getLocation(),
4960 LParenLoc: SourceLocation(), RParenLoc: SourceLocation());
4961 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4962 BaseInit = InitSeq.Perform(S&: SemaRef, Entity: InitEntity, Kind: InitKind, Args: CopyCtorArg);
4963 break;
4964 }
4965 }
4966
4967 BaseInit = SemaRef.MaybeCreateExprWithCleanups(SubExpr: BaseInit);
4968 if (BaseInit.isInvalid())
4969 return true;
4970
4971 CXXBaseInit =
4972 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4973 SemaRef.Context.getTrivialTypeSourceInfo(T: BaseSpec->getType(),
4974 Loc: SourceLocation()),
4975 BaseSpec->isVirtual(),
4976 SourceLocation(),
4977 BaseInit.getAs<Expr>(),
4978 SourceLocation(),
4979 SourceLocation());
4980
4981 return false;
4982}
4983
4984static bool RefersToRValueRef(Expr *MemRef) {
4985 ValueDecl *Referenced = cast<MemberExpr>(Val: MemRef)->getMemberDecl();
4986 return Referenced->getType()->isRValueReferenceType();
4987}
4988
4989static bool
4990BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4991 ImplicitInitializerKind ImplicitInitKind,
4992 FieldDecl *Field, IndirectFieldDecl *Indirect,
4993 CXXCtorInitializer *&CXXMemberInit) {
4994 if (Field->isInvalidDecl())
4995 return true;
4996
4997 SourceLocation Loc = Constructor->getLocation();
4998
4999 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
5000 bool Moving = ImplicitInitKind == IIK_Move;
5001 ParmVarDecl *Param = Constructor->getParamDecl(i: 0);
5002 QualType ParamType = Param->getType().getNonReferenceType();
5003
5004 // Suppress copying zero-width bitfields.
5005 if (Field->isZeroLengthBitField())
5006 return false;
5007
5008 Expr *MemberExprBase =
5009 DeclRefExpr::Create(Context: SemaRef.Context, QualifierLoc: NestedNameSpecifierLoc(),
5010 TemplateKWLoc: SourceLocation(), D: Param, RefersToEnclosingVariableOrCapture: false,
5011 NameLoc: Loc, T: ParamType, VK: VK_LValue, FoundD: nullptr);
5012
5013 SemaRef.MarkDeclRefReferenced(E: cast<DeclRefExpr>(Val: MemberExprBase));
5014
5015 if (Moving) {
5016 MemberExprBase = CastForMoving(SemaRef, E: MemberExprBase);
5017 }
5018
5019 // Build a reference to this field within the parameter.
5020 CXXScopeSpec SS;
5021 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
5022 Sema::LookupMemberName);
5023 MemberLookup.addDecl(D: Indirect ? cast<ValueDecl>(Val: Indirect)
5024 : cast<ValueDecl>(Val: Field), AS: AS_public);
5025 MemberLookup.resolveKind();
5026 ExprResult CtorArg
5027 = SemaRef.BuildMemberReferenceExpr(Base: MemberExprBase,
5028 BaseType: ParamType, OpLoc: Loc,
5029 /*IsArrow=*/false,
5030 SS,
5031 /*TemplateKWLoc=*/SourceLocation(),
5032 /*FirstQualifierInScope=*/nullptr,
5033 R&: MemberLookup,
5034 /*TemplateArgs=*/nullptr,
5035 /*S*/nullptr);
5036 if (CtorArg.isInvalid())
5037 return true;
5038
5039 // C++11 [class.copy]p15:
5040 // - if a member m has rvalue reference type T&&, it is direct-initialized
5041 // with static_cast<T&&>(x.m);
5042 if (RefersToRValueRef(MemRef: CtorArg.get())) {
5043 CtorArg = CastForMoving(SemaRef, E: CtorArg.get());
5044 }
5045
5046 InitializedEntity Entity =
5047 Indirect ? InitializedEntity::InitializeMemberImplicit(Member: Indirect)
5048 : InitializedEntity::InitializeMemberImplicit(Member: Field);
5049
5050 // Direct-initialize to use the copy constructor.
5051 InitializationKind InitKind =
5052 InitializationKind::CreateDirect(InitLoc: Loc, LParenLoc: SourceLocation(), RParenLoc: SourceLocation());
5053
5054 Expr *CtorArgE = CtorArg.getAs<Expr>();
5055 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
5056 ExprResult MemberInit =
5057 InitSeq.Perform(S&: SemaRef, Entity, Kind: InitKind, Args: MultiExprArg(&CtorArgE, 1));
5058 MemberInit = SemaRef.MaybeCreateExprWithCleanups(SubExpr: MemberInit);
5059 if (MemberInit.isInvalid())
5060 return true;
5061
5062 if (Indirect)
5063 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
5064 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
5065 else
5066 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
5067 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
5068 return false;
5069 }
5070
5071 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
5072 "Unhandled implicit init kind!");
5073
5074 QualType FieldBaseElementType =
5075 SemaRef.Context.getBaseElementType(QT: Field->getType());
5076
5077 if (FieldBaseElementType->isRecordType()) {
5078 InitializedEntity InitEntity =
5079 Indirect ? InitializedEntity::InitializeMemberImplicit(Member: Indirect)
5080 : InitializedEntity::InitializeMemberImplicit(Member: Field);
5081 InitializationKind InitKind =
5082 InitializationKind::CreateDefault(InitLoc: Loc);
5083
5084 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, {});
5085 ExprResult MemberInit = InitSeq.Perform(S&: SemaRef, Entity: InitEntity, Kind: InitKind, Args: {});
5086
5087 MemberInit = SemaRef.MaybeCreateExprWithCleanups(SubExpr: MemberInit);
5088 if (MemberInit.isInvalid())
5089 return true;
5090
5091 if (Indirect)
5092 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5093 Indirect, Loc,
5094 Loc,
5095 MemberInit.get(),
5096 Loc);
5097 else
5098 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5099 Field, Loc, Loc,
5100 MemberInit.get(),
5101 Loc);
5102 return false;
5103 }
5104
5105 if (!Field->getParent()->isUnion()) {
5106 if (FieldBaseElementType->isReferenceType()) {
5107 SemaRef.Diag(Loc: Constructor->getLocation(),
5108 DiagID: diag::err_uninitialized_member_in_ctor)
5109 << (int)Constructor->isImplicit()
5110 << SemaRef.Context.getCanonicalTagType(TD: Constructor->getParent()) << 0
5111 << Field->getDeclName();
5112 SemaRef.Diag(Loc: Field->getLocation(), DiagID: diag::note_declared_at);
5113 return true;
5114 }
5115
5116 if (FieldBaseElementType.isConstQualified()) {
5117 SemaRef.Diag(Loc: Constructor->getLocation(),
5118 DiagID: diag::err_uninitialized_member_in_ctor)
5119 << (int)Constructor->isImplicit()
5120 << SemaRef.Context.getCanonicalTagType(TD: Constructor->getParent()) << 1
5121 << Field->getDeclName();
5122 SemaRef.Diag(Loc: Field->getLocation(), DiagID: diag::note_declared_at);
5123 return true;
5124 }
5125 }
5126
5127 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
5128 // ARC and Weak:
5129 // Default-initialize Objective-C pointers to NULL.
5130 CXXMemberInit
5131 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
5132 Loc, Loc,
5133 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
5134 Loc);
5135 return false;
5136 }
5137
5138 // Nothing to initialize.
5139 CXXMemberInit = nullptr;
5140 return false;
5141}
5142
5143namespace {
5144struct BaseAndFieldInfo {
5145 Sema &S;
5146 CXXConstructorDecl *Ctor;
5147 bool AnyErrorsInInits;
5148 ImplicitInitializerKind IIK;
5149 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
5150 SmallVector<CXXCtorInitializer*, 8> AllToInit;
5151 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
5152
5153 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
5154 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
5155 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
5156 if (Ctor->getInheritedConstructor())
5157 IIK = IIK_Inherit;
5158 else if (Generated && Ctor->isCopyConstructor())
5159 IIK = IIK_Copy;
5160 else if (Generated && Ctor->isMoveConstructor())
5161 IIK = IIK_Move;
5162 else
5163 IIK = IIK_Default;
5164 }
5165
5166 bool isImplicitCopyOrMove() const {
5167 switch (IIK) {
5168 case IIK_Copy:
5169 case IIK_Move:
5170 return true;
5171
5172 case IIK_Default:
5173 case IIK_Inherit:
5174 return false;
5175 }
5176
5177 llvm_unreachable("Invalid ImplicitInitializerKind!");
5178 }
5179
5180 bool addFieldInitializer(CXXCtorInitializer *Init) {
5181 AllToInit.push_back(Elt: Init);
5182
5183 // Check whether this initializer makes the field "used".
5184 if (Init->getInit()->HasSideEffects(Ctx: S.Context))
5185 S.UnusedPrivateFields.remove(X: Init->getAnyMember());
5186
5187 return false;
5188 }
5189
5190 bool isInactiveUnionMember(FieldDecl *Field) {
5191 RecordDecl *Record = Field->getParent();
5192 if (!Record->isUnion())
5193 return false;
5194
5195 if (FieldDecl *Active =
5196 ActiveUnionMember.lookup(Val: Record->getCanonicalDecl()))
5197 return Active != Field->getCanonicalDecl();
5198
5199 // In an implicit copy or move constructor, ignore any in-class initializer.
5200 if (isImplicitCopyOrMove())
5201 return true;
5202
5203 // If there's no explicit initialization, the field is active only if it
5204 // has an in-class initializer...
5205 if (Field->hasInClassInitializer())
5206 return false;
5207 // ... or it's an anonymous struct or union whose class has an in-class
5208 // initializer.
5209 if (!Field->isAnonymousStructOrUnion())
5210 return true;
5211 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
5212 return !FieldRD->hasInClassInitializer();
5213 }
5214
5215 /// Determine whether the given field is, or is within, a union member
5216 /// that is inactive (because there was an initializer given for a different
5217 /// member of the union, or because the union was not initialized at all).
5218 bool isWithinInactiveUnionMember(FieldDecl *Field,
5219 IndirectFieldDecl *Indirect) {
5220 if (!Indirect)
5221 return isInactiveUnionMember(Field);
5222
5223 for (auto *C : Indirect->chain()) {
5224 FieldDecl *Field = dyn_cast<FieldDecl>(Val: C);
5225 if (Field && isInactiveUnionMember(Field))
5226 return true;
5227 }
5228 return false;
5229 }
5230};
5231}
5232
5233/// Determine whether the given type is an incomplete or zero-lenfgth
5234/// array type.
5235static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
5236 if (T->isIncompleteArrayType())
5237 return true;
5238
5239 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
5240 if (ArrayT->isZeroSize())
5241 return true;
5242
5243 T = ArrayT->getElementType();
5244 }
5245
5246 return false;
5247}
5248
5249static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
5250 FieldDecl *Field,
5251 IndirectFieldDecl *Indirect = nullptr) {
5252 if (Field->isInvalidDecl())
5253 return false;
5254
5255 // Overwhelmingly common case: we have a direct initializer for this field.
5256 if (CXXCtorInitializer *Init =
5257 Info.AllBaseFields.lookup(Val: Field->getCanonicalDecl()))
5258 return Info.addFieldInitializer(Init);
5259
5260 // C++11 [class.base.init]p8:
5261 // if the entity is a non-static data member that has a
5262 // brace-or-equal-initializer and either
5263 // -- the constructor's class is a union and no other variant member of that
5264 // union is designated by a mem-initializer-id or
5265 // -- the constructor's class is not a union, and, if the entity is a member
5266 // of an anonymous union, no other member of that union is designated by
5267 // a mem-initializer-id,
5268 // the entity is initialized as specified in [dcl.init].
5269 //
5270 // We also apply the same rules to handle anonymous structs within anonymous
5271 // unions.
5272 if (Info.isWithinInactiveUnionMember(Field, Indirect))
5273 return false;
5274
5275 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
5276 ExprResult DIE =
5277 SemaRef.BuildCXXDefaultInitExpr(Loc: Info.Ctor->getLocation(), Field);
5278 if (DIE.isInvalid())
5279 return true;
5280
5281 auto Entity = InitializedEntity::InitializeMemberImplicit(Member: Field);
5282 SemaRef.checkInitializerLifetime(Entity, Init: DIE.get());
5283
5284 CXXCtorInitializer *Init;
5285 if (Indirect)
5286 Init = new (SemaRef.Context)
5287 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
5288 SourceLocation(), DIE.get(), SourceLocation());
5289 else
5290 Init = new (SemaRef.Context)
5291 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
5292 SourceLocation(), DIE.get(), SourceLocation());
5293 return Info.addFieldInitializer(Init);
5294 }
5295
5296 // Don't initialize incomplete or zero-length arrays.
5297 if (isIncompleteOrZeroLengthArrayType(Context&: SemaRef.Context, T: Field->getType()))
5298 return false;
5299
5300 // Don't try to build an implicit initializer if there were semantic
5301 // errors in any of the initializers (and therefore we might be
5302 // missing some that the user actually wrote).
5303 if (Info.AnyErrorsInInits)
5304 return false;
5305
5306 CXXCtorInitializer *Init = nullptr;
5307 if (BuildImplicitMemberInitializer(SemaRef&: Info.S, Constructor: Info.Ctor, ImplicitInitKind: Info.IIK, Field,
5308 Indirect, CXXMemberInit&: Init))
5309 return true;
5310
5311 if (!Init)
5312 return false;
5313
5314 return Info.addFieldInitializer(Init);
5315}
5316
5317bool
5318Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
5319 CXXCtorInitializer *Initializer) {
5320 assert(Initializer->isDelegatingInitializer());
5321 Constructor->setNumCtorInitializers(1);
5322 CXXCtorInitializer **initializer =
5323 new (Context) CXXCtorInitializer*[1];
5324 memcpy(dest: initializer, src: &Initializer, n: sizeof (CXXCtorInitializer*));
5325 Constructor->setCtorInitializers(initializer);
5326
5327 if (CXXDestructorDecl *Dtor = LookupDestructor(Class: Constructor->getParent())) {
5328 MarkFunctionReferenced(Loc: Initializer->getSourceLocation(), Func: Dtor);
5329 DiagnoseUseOfDecl(D: Dtor, Locs: Initializer->getSourceLocation());
5330 }
5331
5332 DelegatingCtorDecls.push_back(LocalValue: Constructor);
5333
5334 DiagnoseUninitializedFields(SemaRef&: *this, Constructor);
5335
5336 return false;
5337}
5338
5339static CXXDestructorDecl *LookupDestructorIfRelevant(Sema &S,
5340 CXXRecordDecl *Class) {
5341 if (Class->isInvalidDecl())
5342 return nullptr;
5343 if (Class->hasIrrelevantDestructor())
5344 return nullptr;
5345
5346 // Dtor might still be missing, e.g because it's invalid.
5347 return S.LookupDestructor(Class);
5348}
5349
5350static void MarkFieldDestructorReferenced(Sema &S, SourceLocation Location,
5351 FieldDecl *Field) {
5352 if (Field->isInvalidDecl())
5353 return;
5354
5355 // Don't destroy incomplete or zero-length arrays.
5356 if (isIncompleteOrZeroLengthArrayType(Context&: S.Context, T: Field->getType()))
5357 return;
5358
5359 QualType FieldType = S.Context.getBaseElementType(QT: Field->getType());
5360
5361 auto *FieldClassDecl = FieldType->getAsCXXRecordDecl();
5362 if (!FieldClassDecl)
5363 return;
5364
5365 // The destructor for an implicit anonymous union member is never invoked.
5366 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5367 return;
5368
5369 auto *Dtor = LookupDestructorIfRelevant(S, Class: FieldClassDecl);
5370 if (!Dtor)
5371 return;
5372
5373 S.CheckDestructorAccess(Loc: Field->getLocation(), Dtor,
5374 PDiag: S.PDiag(DiagID: diag::err_access_dtor_field)
5375 << Field->getDeclName() << FieldType);
5376
5377 S.MarkFunctionReferenced(Loc: Location, Func: Dtor);
5378 S.DiagnoseUseOfDecl(D: Dtor, Locs: Location);
5379}
5380
5381static void MarkBaseDestructorsReferenced(Sema &S, SourceLocation Location,
5382 CXXRecordDecl *ClassDecl) {
5383 if (ClassDecl->isDependentContext())
5384 return;
5385
5386 // We only potentially invoke the destructors of potentially constructed
5387 // subobjects.
5388 bool VisitVirtualBases = !ClassDecl->isAbstract();
5389
5390 // If the destructor exists and has already been marked used in the MS ABI,
5391 // then virtual base destructors have already been checked and marked used.
5392 // Skip checking them again to avoid duplicate diagnostics.
5393 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5394 CXXDestructorDecl *Dtor = ClassDecl->getDestructor();
5395 if (Dtor && Dtor->isUsed())
5396 VisitVirtualBases = false;
5397 }
5398
5399 llvm::SmallPtrSet<const CXXRecordDecl *, 8> DirectVirtualBases;
5400
5401 // Bases.
5402 for (const auto &Base : ClassDecl->bases()) {
5403 auto *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
5404 if (!BaseClassDecl)
5405 continue;
5406
5407 // Remember direct virtual bases.
5408 if (Base.isVirtual()) {
5409 if (!VisitVirtualBases)
5410 continue;
5411 DirectVirtualBases.insert(Ptr: BaseClassDecl);
5412 }
5413
5414 auto *Dtor = LookupDestructorIfRelevant(S, Class: BaseClassDecl);
5415 if (!Dtor)
5416 continue;
5417
5418 // FIXME: caret should be on the start of the class name
5419 S.CheckDestructorAccess(Loc: Base.getBeginLoc(), Dtor,
5420 PDiag: S.PDiag(DiagID: diag::err_access_dtor_base)
5421 << Base.getType() << Base.getSourceRange(),
5422 objectType: S.Context.getCanonicalTagType(TD: ClassDecl));
5423
5424 S.MarkFunctionReferenced(Loc: Location, Func: Dtor);
5425 S.DiagnoseUseOfDecl(D: Dtor, Locs: Location);
5426 }
5427
5428 if (VisitVirtualBases)
5429 S.MarkVirtualBaseDestructorsReferenced(Location, ClassDecl,
5430 DirectVirtualBases: &DirectVirtualBases);
5431}
5432
5433bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5434 ArrayRef<CXXCtorInitializer *> Initializers) {
5435 if (Constructor->isDependentContext()) {
5436 // Just store the initializers as written, they will be checked during
5437 // instantiation.
5438 if (!Initializers.empty()) {
5439 Constructor->setNumCtorInitializers(Initializers.size());
5440 CXXCtorInitializer **baseOrMemberInitializers =
5441 new (Context) CXXCtorInitializer*[Initializers.size()];
5442 memcpy(dest: baseOrMemberInitializers, src: Initializers.data(),
5443 n: Initializers.size() * sizeof(CXXCtorInitializer*));
5444 Constructor->setCtorInitializers(baseOrMemberInitializers);
5445 }
5446
5447 // Let template instantiation know whether we had errors.
5448 if (AnyErrors)
5449 Constructor->setInvalidDecl();
5450
5451 return false;
5452 }
5453
5454 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
5455
5456 // We need to build the initializer AST according to order of construction
5457 // and not what user specified in the Initializers list.
5458 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
5459 if (!ClassDecl)
5460 return true;
5461
5462 bool HadError = false;
5463
5464 for (CXXCtorInitializer *Member : Initializers) {
5465 if (Member->isBaseInitializer())
5466 Info.AllBaseFields[Member->getBaseClass()->getAsCanonical<RecordType>()] =
5467 Member;
5468 else {
5469 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
5470
5471 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
5472 for (auto *C : F->chain()) {
5473 FieldDecl *FD = dyn_cast<FieldDecl>(Val: C);
5474 if (FD && FD->getParent()->isUnion())
5475 Info.ActiveUnionMember.insert(KV: std::make_pair(
5476 x: FD->getParent()->getCanonicalDecl(), y: FD->getCanonicalDecl()));
5477 }
5478 } else if (FieldDecl *FD = Member->getMember()) {
5479 if (FD->getParent()->isUnion())
5480 Info.ActiveUnionMember.insert(KV: std::make_pair(
5481 x: FD->getParent()->getCanonicalDecl(), y: FD->getCanonicalDecl()));
5482 }
5483 }
5484 }
5485
5486 // Keep track of the direct virtual bases.
5487 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
5488 for (auto &I : ClassDecl->bases()) {
5489 if (I.isVirtual())
5490 DirectVBases.insert(Ptr: &I);
5491 }
5492
5493 // Push virtual bases before others.
5494 for (auto &VBase : ClassDecl->vbases()) {
5495 if (CXXCtorInitializer *Value = Info.AllBaseFields.lookup(
5496 Val: VBase.getType()->getAsCanonical<RecordType>())) {
5497 // [class.base.init]p7, per DR257:
5498 // A mem-initializer where the mem-initializer-id names a virtual base
5499 // class is ignored during execution of a constructor of any class that
5500 // is not the most derived class.
5501 if (ClassDecl->isAbstract()) {
5502 // FIXME: Provide a fixit to remove the base specifier. This requires
5503 // tracking the location of the associated comma for a base specifier.
5504 Diag(Loc: Value->getSourceLocation(), DiagID: diag::warn_abstract_vbase_init_ignored)
5505 << VBase.getType() << ClassDecl;
5506 DiagnoseAbstractType(RD: ClassDecl);
5507 }
5508
5509 Info.AllToInit.push_back(Elt: Value);
5510 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
5511 // [class.base.init]p8, per DR257:
5512 // If a given [...] base class is not named by a mem-initializer-id
5513 // [...] and the entity is not a virtual base class of an abstract
5514 // class, then [...] the entity is default-initialized.
5515 bool IsInheritedVirtualBase = !DirectVBases.count(Ptr: &VBase);
5516 CXXCtorInitializer *CXXBaseInit;
5517 if (BuildImplicitBaseInitializer(SemaRef&: *this, Constructor, ImplicitInitKind: Info.IIK,
5518 BaseSpec: &VBase, IsInheritedVirtualBase,
5519 CXXBaseInit)) {
5520 HadError = true;
5521 continue;
5522 }
5523
5524 Info.AllToInit.push_back(Elt: CXXBaseInit);
5525 }
5526 }
5527
5528 // Non-virtual bases.
5529 for (auto &Base : ClassDecl->bases()) {
5530 // Virtuals are in the virtual base list and already constructed.
5531 if (Base.isVirtual())
5532 continue;
5533
5534 if (CXXCtorInitializer *Value = Info.AllBaseFields.lookup(
5535 Val: Base.getType()->getAsCanonical<RecordType>())) {
5536 Info.AllToInit.push_back(Elt: Value);
5537 } else if (!AnyErrors) {
5538 CXXCtorInitializer *CXXBaseInit;
5539 if (BuildImplicitBaseInitializer(SemaRef&: *this, Constructor, ImplicitInitKind: Info.IIK,
5540 BaseSpec: &Base, /*IsInheritedVirtualBase=*/false,
5541 CXXBaseInit)) {
5542 HadError = true;
5543 continue;
5544 }
5545
5546 Info.AllToInit.push_back(Elt: CXXBaseInit);
5547 }
5548 }
5549
5550 // Fields.
5551 for (auto *Mem : ClassDecl->decls()) {
5552 if (auto *F = dyn_cast<FieldDecl>(Val: Mem)) {
5553 // C++ [class.bit]p2:
5554 // A declaration for a bit-field that omits the identifier declares an
5555 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
5556 // initialized.
5557 if (F->isUnnamedBitField())
5558 continue;
5559
5560 // If we're not generating the implicit copy/move constructor, then we'll
5561 // handle anonymous struct/union fields based on their individual
5562 // indirect fields.
5563 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
5564 continue;
5565
5566 if (CollectFieldInitializer(SemaRef&: *this, Info, Field: F))
5567 HadError = true;
5568 continue;
5569 }
5570
5571 // Beyond this point, we only consider default initialization.
5572 if (Info.isImplicitCopyOrMove())
5573 continue;
5574
5575 if (auto *F = dyn_cast<IndirectFieldDecl>(Val: Mem)) {
5576 if (F->getType()->isIncompleteArrayType()) {
5577 assert(ClassDecl->hasFlexibleArrayMember() &&
5578 "Incomplete array type is not valid");
5579 continue;
5580 }
5581
5582 // Initialize each field of an anonymous struct individually.
5583 if (CollectFieldInitializer(SemaRef&: *this, Info, Field: F->getAnonField(), Indirect: F))
5584 HadError = true;
5585
5586 continue;
5587 }
5588 }
5589
5590 unsigned NumInitializers = Info.AllToInit.size();
5591 if (NumInitializers > 0) {
5592 Constructor->setNumCtorInitializers(NumInitializers);
5593 CXXCtorInitializer **baseOrMemberInitializers =
5594 new (Context) CXXCtorInitializer*[NumInitializers];
5595 memcpy(dest: baseOrMemberInitializers, src: Info.AllToInit.data(),
5596 n: NumInitializers * sizeof(CXXCtorInitializer*));
5597 Constructor->setCtorInitializers(baseOrMemberInitializers);
5598
5599 SourceLocation Location = Constructor->getLocation();
5600
5601 // Constructors implicitly reference the base and member
5602 // destructors.
5603
5604 for (CXXCtorInitializer *Initializer : Info.AllToInit) {
5605 FieldDecl *Field = Initializer->getAnyMember();
5606 if (!Field)
5607 continue;
5608
5609 // C++ [class.base.init]p12:
5610 // In a non-delegating constructor, the destructor for each
5611 // potentially constructed subobject of class type is potentially
5612 // invoked.
5613 MarkFieldDestructorReferenced(S&: *this, Location, Field);
5614 }
5615
5616 MarkBaseDestructorsReferenced(S&: *this, Location, ClassDecl: Constructor->getParent());
5617 }
5618
5619 return HadError;
5620}
5621
5622static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
5623 if (const RecordType *RT = Field->getType()->getAsCanonical<RecordType>()) {
5624 const RecordDecl *RD = RT->getDecl();
5625 if (RD->isAnonymousStructOrUnion()) {
5626 for (auto *Field : RD->getDefinitionOrSelf()->fields())
5627 PopulateKeysForFields(Field, IdealInits);
5628 return;
5629 }
5630 }
5631 IdealInits.push_back(Elt: Field->getCanonicalDecl());
5632}
5633
5634static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
5635 return Context.getCanonicalType(T: BaseType).getTypePtr();
5636}
5637
5638static const void *GetKeyForMember(ASTContext &Context,
5639 CXXCtorInitializer *Member) {
5640 if (!Member->isAnyMemberInitializer())
5641 return GetKeyForBase(Context, BaseType: QualType(Member->getBaseClass(), 0));
5642
5643 return Member->getAnyMember()->getCanonicalDecl();
5644}
5645
5646static void AddInitializerToDiag(const Sema::SemaDiagnosticBuilder &Diag,
5647 const CXXCtorInitializer *Previous,
5648 const CXXCtorInitializer *Current) {
5649 if (Previous->isAnyMemberInitializer())
5650 Diag << 0 << Previous->getAnyMember();
5651 else
5652 Diag << 1 << Previous->getTypeSourceInfo()->getType();
5653
5654 if (Current->isAnyMemberInitializer())
5655 Diag << 0 << Current->getAnyMember();
5656 else
5657 Diag << 1 << Current->getTypeSourceInfo()->getType();
5658}
5659
5660static void DiagnoseBaseOrMemInitializerOrder(
5661 Sema &SemaRef, const CXXConstructorDecl *Constructor,
5662 ArrayRef<CXXCtorInitializer *> Inits) {
5663 if (Constructor->getDeclContext()->isDependentContext())
5664 return;
5665
5666 // Don't check initializers order unless the warning is enabled at the
5667 // location of at least one initializer.
5668 bool ShouldCheckOrder = false;
5669 for (const CXXCtorInitializer *Init : Inits) {
5670 if (!SemaRef.Diags.isIgnored(DiagID: diag::warn_initializer_out_of_order,
5671 Loc: Init->getSourceLocation())) {
5672 ShouldCheckOrder = true;
5673 break;
5674 }
5675 }
5676 if (!ShouldCheckOrder)
5677 return;
5678
5679 // Build the list of bases and members in the order that they'll
5680 // actually be initialized. The explicit initializers should be in
5681 // this same order but may be missing things.
5682 SmallVector<const void*, 32> IdealInitKeys;
5683
5684 const CXXRecordDecl *ClassDecl = Constructor->getParent();
5685
5686 // 1. Virtual bases.
5687 for (const auto &VBase : ClassDecl->vbases())
5688 IdealInitKeys.push_back(Elt: GetKeyForBase(Context&: SemaRef.Context, BaseType: VBase.getType()));
5689
5690 // 2. Non-virtual bases.
5691 for (const auto &Base : ClassDecl->bases()) {
5692 if (Base.isVirtual())
5693 continue;
5694 IdealInitKeys.push_back(Elt: GetKeyForBase(Context&: SemaRef.Context, BaseType: Base.getType()));
5695 }
5696
5697 // 3. Direct fields.
5698 for (auto *Field : ClassDecl->fields()) {
5699 if (Field->isUnnamedBitField())
5700 continue;
5701
5702 PopulateKeysForFields(Field, IdealInits&: IdealInitKeys);
5703 }
5704
5705 unsigned NumIdealInits = IdealInitKeys.size();
5706 unsigned IdealIndex = 0;
5707
5708 // Track initializers that are in an incorrect order for either a warning or
5709 // note if multiple ones occur.
5710 SmallVector<unsigned> WarnIndexes;
5711 // Correlates the index of an initializer in the init-list to the index of
5712 // the field/base in the class.
5713 SmallVector<std::pair<unsigned, unsigned>, 32> CorrelatedInitOrder;
5714
5715 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5716 const void *InitKey = GetKeyForMember(Context&: SemaRef.Context, Member: Inits[InitIndex]);
5717
5718 // Scan forward to try to find this initializer in the idealized
5719 // initializers list.
5720 for (; IdealIndex != NumIdealInits; ++IdealIndex)
5721 if (InitKey == IdealInitKeys[IdealIndex])
5722 break;
5723
5724 // If we didn't find this initializer, it must be because we
5725 // scanned past it on a previous iteration. That can only
5726 // happen if we're out of order; emit a warning.
5727 if (IdealIndex == NumIdealInits && InitIndex) {
5728 WarnIndexes.push_back(Elt: InitIndex);
5729
5730 // Move back to the initializer's location in the ideal list.
5731 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5732 if (InitKey == IdealInitKeys[IdealIndex])
5733 break;
5734
5735 assert(IdealIndex < NumIdealInits &&
5736 "initializer not found in initializer list");
5737 }
5738 CorrelatedInitOrder.emplace_back(Args&: IdealIndex, Args&: InitIndex);
5739 }
5740
5741 if (WarnIndexes.empty())
5742 return;
5743
5744 // Sort based on the ideal order, first in the pair.
5745 llvm::sort(C&: CorrelatedInitOrder, Comp: llvm::less_first());
5746
5747 // Introduce a new scope as SemaDiagnosticBuilder needs to be destroyed to
5748 // emit the diagnostic before we can try adding notes.
5749 {
5750 Sema::SemaDiagnosticBuilder D = SemaRef.Diag(
5751 Loc: Inits[WarnIndexes.front() - 1]->getSourceLocation(),
5752 DiagID: WarnIndexes.size() == 1 ? diag::warn_initializer_out_of_order
5753 : diag::warn_some_initializers_out_of_order);
5754
5755 for (unsigned I = 0; I < CorrelatedInitOrder.size(); ++I) {
5756 if (CorrelatedInitOrder[I].second == I)
5757 continue;
5758 // Ideally we would be using InsertFromRange here, but clang doesn't
5759 // appear to handle InsertFromRange correctly when the source range is
5760 // modified by another fix-it.
5761 D << FixItHint::CreateReplacement(
5762 RemoveRange: Inits[I]->getSourceRange(),
5763 Code: Lexer::getSourceText(
5764 Range: CharSourceRange::getTokenRange(
5765 R: Inits[CorrelatedInitOrder[I].second]->getSourceRange()),
5766 SM: SemaRef.getSourceManager(), LangOpts: SemaRef.getLangOpts()));
5767 }
5768
5769 // If there is only 1 item out of order, the warning expects the name and
5770 // type of each being added to it.
5771 if (WarnIndexes.size() == 1) {
5772 AddInitializerToDiag(Diag: D, Previous: Inits[WarnIndexes.front() - 1],
5773 Current: Inits[WarnIndexes.front()]);
5774 return;
5775 }
5776 }
5777 // More than 1 item to warn, create notes letting the user know which ones
5778 // are bad.
5779 for (unsigned WarnIndex : WarnIndexes) {
5780 const clang::CXXCtorInitializer *PrevInit = Inits[WarnIndex - 1];
5781 auto D = SemaRef.Diag(Loc: PrevInit->getSourceLocation(),
5782 DiagID: diag::note_initializer_out_of_order);
5783 AddInitializerToDiag(Diag: D, Previous: PrevInit, Current: Inits[WarnIndex]);
5784 D << PrevInit->getSourceRange();
5785 }
5786}
5787
5788namespace {
5789bool CheckRedundantInit(Sema &S,
5790 CXXCtorInitializer *Init,
5791 CXXCtorInitializer *&PrevInit) {
5792 if (!PrevInit) {
5793 PrevInit = Init;
5794 return false;
5795 }
5796
5797 if (FieldDecl *Field = Init->getAnyMember())
5798 S.Diag(Loc: Init->getSourceLocation(),
5799 DiagID: diag::err_multiple_mem_initialization)
5800 << Field->getDeclName()
5801 << Init->getSourceRange();
5802 else {
5803 const Type *BaseClass = Init->getBaseClass();
5804 assert(BaseClass && "neither field nor base");
5805 S.Diag(Loc: Init->getSourceLocation(),
5806 DiagID: diag::err_multiple_base_initialization)
5807 << QualType(BaseClass, 0)
5808 << Init->getSourceRange();
5809 }
5810 S.Diag(Loc: PrevInit->getSourceLocation(), DiagID: diag::note_previous_initializer)
5811 << 0 << PrevInit->getSourceRange();
5812
5813 return true;
5814}
5815
5816typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5817typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5818
5819bool CheckRedundantUnionInit(Sema &S,
5820 CXXCtorInitializer *Init,
5821 RedundantUnionMap &Unions) {
5822 FieldDecl *Field = Init->getAnyMember();
5823 RecordDecl *Parent = Field->getParent();
5824 NamedDecl *Child = Field;
5825
5826 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5827 if (Parent->isUnion()) {
5828 UnionEntry &En = Unions[Parent];
5829 if (En.first && En.first != Child) {
5830 S.Diag(Loc: Init->getSourceLocation(),
5831 DiagID: diag::err_multiple_mem_union_initialization)
5832 << Field->getDeclName()
5833 << Init->getSourceRange();
5834 S.Diag(Loc: En.second->getSourceLocation(), DiagID: diag::note_previous_initializer)
5835 << 0 << En.second->getSourceRange();
5836 return true;
5837 }
5838 if (!En.first) {
5839 En.first = Child;
5840 En.second = Init;
5841 }
5842 if (!Parent->isAnonymousStructOrUnion())
5843 return false;
5844 }
5845
5846 Child = Parent;
5847 Parent = cast<RecordDecl>(Val: Parent->getDeclContext());
5848 }
5849
5850 return false;
5851}
5852} // namespace
5853
5854void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5855 SourceLocation ColonLoc,
5856 ArrayRef<CXXCtorInitializer*> MemInits,
5857 bool AnyErrors) {
5858 if (!ConstructorDecl)
5859 return;
5860
5861 AdjustDeclIfTemplate(Decl&: ConstructorDecl);
5862
5863 CXXConstructorDecl *Constructor
5864 = dyn_cast<CXXConstructorDecl>(Val: ConstructorDecl);
5865
5866 if (!Constructor) {
5867 Diag(Loc: ColonLoc, DiagID: diag::err_only_constructors_take_base_inits);
5868 return;
5869 }
5870
5871 // Mapping for the duplicate initializers check.
5872 // For member initializers, this is keyed with a FieldDecl*.
5873 // For base initializers, this is keyed with a Type*.
5874 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5875
5876 // Mapping for the inconsistent anonymous-union initializers check.
5877 RedundantUnionMap MemberUnions;
5878
5879 bool HadError = false;
5880 for (unsigned i = 0; i < MemInits.size(); i++) {
5881 CXXCtorInitializer *Init = MemInits[i];
5882
5883 // Set the source order index.
5884 Init->setSourceOrder(i);
5885
5886 if (Init->isAnyMemberInitializer()) {
5887 const void *Key = GetKeyForMember(Context, Member: Init);
5888 if (CheckRedundantInit(S&: *this, Init, PrevInit&: Members[Key]) ||
5889 CheckRedundantUnionInit(S&: *this, Init, Unions&: MemberUnions))
5890 HadError = true;
5891 } else if (Init->isBaseInitializer()) {
5892 const void *Key = GetKeyForMember(Context, Member: Init);
5893 if (CheckRedundantInit(S&: *this, Init, PrevInit&: Members[Key]))
5894 HadError = true;
5895 } else {
5896 assert(Init->isDelegatingInitializer());
5897 // This must be the only initializer
5898 if (MemInits.size() != 1) {
5899 Diag(Loc: Init->getSourceLocation(),
5900 DiagID: diag::err_delegating_initializer_alone)
5901 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5902 // We will treat this as being the only initializer.
5903 }
5904 SetDelegatingInitializer(Constructor, Initializer: MemInits[i]);
5905 // Return immediately as the initializer is set.
5906 return;
5907 }
5908 }
5909
5910 if (HadError)
5911 return;
5912
5913 DiagnoseBaseOrMemInitializerOrder(SemaRef&: *this, Constructor, Inits: MemInits);
5914
5915 SetCtorInitializers(Constructor, AnyErrors, Initializers: MemInits);
5916
5917 DiagnoseUninitializedFields(SemaRef&: *this, Constructor);
5918}
5919
5920void Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5921 CXXRecordDecl *ClassDecl) {
5922 // Ignore dependent contexts. Also ignore unions, since their members never
5923 // have destructors implicitly called.
5924 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5925 return;
5926
5927 // FIXME: all the access-control diagnostics are positioned on the
5928 // field/base declaration. That's probably good; that said, the
5929 // user might reasonably want to know why the destructor is being
5930 // emitted, and we currently don't say.
5931
5932 // Non-static data members.
5933 for (auto *Field : ClassDecl->fields()) {
5934 MarkFieldDestructorReferenced(S&: *this, Location, Field);
5935 }
5936
5937 MarkBaseDestructorsReferenced(S&: *this, Location, ClassDecl);
5938}
5939
5940void Sema::MarkVirtualBaseDestructorsReferenced(
5941 SourceLocation Location, CXXRecordDecl *ClassDecl,
5942 llvm::SmallPtrSetImpl<const CXXRecordDecl *> *DirectVirtualBases) {
5943 // Virtual bases.
5944 for (const auto &VBase : ClassDecl->vbases()) {
5945 auto *BaseClassDecl = VBase.getType()->getAsCXXRecordDecl();
5946 if (!BaseClassDecl)
5947 continue;
5948
5949 // Ignore already visited direct virtual bases.
5950 if (DirectVirtualBases && DirectVirtualBases->count(Ptr: BaseClassDecl))
5951 continue;
5952
5953 auto *Dtor = LookupDestructorIfRelevant(S&: *this, Class: BaseClassDecl);
5954 if (!Dtor)
5955 continue;
5956
5957 CanQualType CT = Context.getCanonicalTagType(TD: ClassDecl);
5958 if (CheckDestructorAccess(Loc: ClassDecl->getLocation(), Dtor,
5959 PDiag: PDiag(DiagID: diag::err_access_dtor_vbase)
5960 << CT << VBase.getType(),
5961 objectType: CT) == AR_accessible) {
5962 CheckDerivedToBaseConversion(
5963 Derived: CT, Base: VBase.getType(), InaccessibleBaseID: diag::err_access_dtor_vbase, AmbiguousBaseConvID: 0,
5964 Loc: ClassDecl->getLocation(), Range: SourceRange(), Name: DeclarationName(), BasePath: nullptr);
5965 }
5966
5967 MarkFunctionReferenced(Loc: Location, Func: Dtor);
5968 DiagnoseUseOfDecl(D: Dtor, Locs: Location);
5969 }
5970}
5971
5972void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5973 if (!CDtorDecl)
5974 return;
5975
5976 if (CXXConstructorDecl *Constructor
5977 = dyn_cast<CXXConstructorDecl>(Val: CDtorDecl)) {
5978 if (CXXRecordDecl *ClassDecl = Constructor->getParent();
5979 !ClassDecl || ClassDecl->isInvalidDecl()) {
5980 return;
5981 }
5982 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5983 DiagnoseUninitializedFields(SemaRef&: *this, Constructor);
5984 }
5985}
5986
5987bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5988 if (!getLangOpts().CPlusPlus)
5989 return false;
5990
5991 const auto *RD = Context.getBaseElementType(QT: T)->getAsCXXRecordDecl();
5992 if (!RD)
5993 return false;
5994
5995 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5996 // class template specialization here, but doing so breaks a lot of code.
5997
5998 // We can't answer whether something is abstract until it has a
5999 // definition. If it's currently being defined, we'll walk back
6000 // over all the declarations when we have a full definition.
6001 const CXXRecordDecl *Def = RD->getDefinition();
6002 if (!Def || Def->isBeingDefined())
6003 return false;
6004
6005 return RD->isAbstract();
6006}
6007
6008bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
6009 TypeDiagnoser &Diagnoser) {
6010 if (!isAbstractType(Loc, T))
6011 return false;
6012
6013 T = Context.getBaseElementType(QT: T);
6014 Diagnoser.diagnose(S&: *this, Loc, T);
6015 DiagnoseAbstractType(RD: T->getAsCXXRecordDecl());
6016 return true;
6017}
6018
6019void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
6020 // Check if we've already emitted the list of pure virtual functions
6021 // for this class.
6022 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(Ptr: RD))
6023 return;
6024
6025 // If the diagnostic is suppressed, don't emit the notes. We're only
6026 // going to emit them once, so try to attach them to a diagnostic we're
6027 // actually going to show.
6028 if (Diags.isLastDiagnosticIgnored())
6029 return;
6030
6031 CXXFinalOverriderMap FinalOverriders;
6032 RD->getFinalOverriders(FinaOverriders&: FinalOverriders);
6033
6034 // Keep a set of seen pure methods so we won't diagnose the same method
6035 // more than once.
6036 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
6037
6038 for (const auto &M : FinalOverriders) {
6039 for (const auto &SO : M.second) {
6040 // C++ [class.abstract]p4:
6041 // A class is abstract if it contains or inherits at least one
6042 // pure virtual function for which the final overrider is pure
6043 // virtual.
6044
6045 if (SO.second.size() != 1)
6046 continue;
6047 const CXXMethodDecl *Method = SO.second.front().Method;
6048
6049 if (!Method->isPureVirtual())
6050 continue;
6051
6052 if (!SeenPureMethods.insert(Ptr: Method).second)
6053 continue;
6054
6055 Diag(Loc: Method->getLocation(), DiagID: diag::note_pure_virtual_function)
6056 << Method->getDeclName() << RD->getDeclName();
6057 }
6058 }
6059
6060 if (!PureVirtualClassDiagSet)
6061 PureVirtualClassDiagSet.reset(p: new RecordDeclSetTy);
6062 PureVirtualClassDiagSet->insert(Ptr: RD);
6063}
6064
6065namespace {
6066struct AbstractUsageInfo {
6067 Sema &S;
6068 CXXRecordDecl *Record;
6069 CanQualType AbstractType;
6070 bool Invalid;
6071
6072 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
6073 : S(S), Record(Record),
6074 AbstractType(S.Context.getCanonicalTagType(TD: Record)), Invalid(false) {}
6075
6076 void DiagnoseAbstractType() {
6077 if (Invalid) return;
6078 S.DiagnoseAbstractType(RD: Record);
6079 Invalid = true;
6080 }
6081
6082 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
6083};
6084
6085struct CheckAbstractUsage {
6086 AbstractUsageInfo &Info;
6087 const NamedDecl *Ctx;
6088
6089 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
6090 : Info(Info), Ctx(Ctx) {}
6091
6092 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
6093 switch (TL.getTypeLocClass()) {
6094#define ABSTRACT_TYPELOC(CLASS, PARENT)
6095#define TYPELOC(CLASS, PARENT) \
6096 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
6097#include "clang/AST/TypeLocNodes.def"
6098 }
6099 }
6100
6101 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6102 Visit(TL: TL.getReturnLoc(), Sel: Sema::AbstractReturnType);
6103 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
6104 if (!TL.getParam(i: I))
6105 continue;
6106
6107 TypeSourceInfo *TSI = TL.getParam(i: I)->getTypeSourceInfo();
6108 if (TSI) Visit(TL: TSI->getTypeLoc(), Sel: Sema::AbstractParamType);
6109 }
6110 }
6111
6112 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6113 Visit(TL: TL.getElementLoc(), Sel: Sema::AbstractArrayType);
6114 }
6115
6116 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6117 // Visit the type parameters from a permissive context.
6118 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
6119 TemplateArgumentLoc TAL = TL.getArgLoc(i: I);
6120 if (TAL.getArgument().getKind() == TemplateArgument::Type)
6121 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
6122 Visit(TL: TSI->getTypeLoc(), Sel: Sema::AbstractNone);
6123 // TODO: other template argument types?
6124 }
6125 }
6126
6127 // Visit pointee types from a permissive context.
6128#define CheckPolymorphic(Type) \
6129 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
6130 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
6131 }
6132 CheckPolymorphic(PointerTypeLoc)
6133 CheckPolymorphic(ReferenceTypeLoc)
6134 CheckPolymorphic(MemberPointerTypeLoc)
6135 CheckPolymorphic(BlockPointerTypeLoc)
6136 CheckPolymorphic(AtomicTypeLoc)
6137
6138 /// Handle all the types we haven't given a more specific
6139 /// implementation for above.
6140 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
6141 // Every other kind of type that we haven't called out already
6142 // that has an inner type is either (1) sugar or (2) contains that
6143 // inner type in some way as a subobject.
6144 if (TypeLoc Next = TL.getNextTypeLoc())
6145 return Visit(TL: Next, Sel);
6146
6147 // If there's no inner type and we're in a permissive context,
6148 // don't diagnose.
6149 if (Sel == Sema::AbstractNone) return;
6150
6151 // Check whether the type matches the abstract type.
6152 QualType T = TL.getType();
6153 if (T->isArrayType()) {
6154 Sel = Sema::AbstractArrayType;
6155 T = Info.S.Context.getBaseElementType(QT: T);
6156 }
6157 CanQualType CT = T->getCanonicalTypeUnqualified();
6158 if (CT != Info.AbstractType) return;
6159
6160 // It matched; do some magic.
6161 // FIXME: These should be at most warnings. See P0929R2, CWG1640, CWG1646.
6162 if (Sel == Sema::AbstractArrayType) {
6163 Info.S.Diag(Loc: Ctx->getLocation(), DiagID: diag::err_array_of_abstract_type)
6164 << T << TL.getSourceRange();
6165 } else {
6166 Info.S.Diag(Loc: Ctx->getLocation(), DiagID: diag::err_abstract_type_in_decl)
6167 << Sel << T << TL.getSourceRange();
6168 }
6169 Info.DiagnoseAbstractType();
6170 }
6171};
6172
6173void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
6174 Sema::AbstractDiagSelID Sel) {
6175 CheckAbstractUsage(*this, D).Visit(TL, Sel);
6176}
6177
6178}
6179
6180/// Check for invalid uses of an abstract type in a function declaration.
6181static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6182 FunctionDecl *FD) {
6183 // Only definitions are required to refer to complete and
6184 // non-abstract types.
6185 if (!FD->doesThisDeclarationHaveABody())
6186 return;
6187
6188 // For safety's sake, just ignore it if we don't have type source
6189 // information. This should never happen for non-implicit methods,
6190 // but...
6191 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6192 Info.CheckType(D: FD, TL: TSI->getTypeLoc(), Sel: Sema::AbstractNone);
6193}
6194
6195/// Check for invalid uses of an abstract type in a variable0 declaration.
6196static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6197 VarDecl *VD) {
6198 // No need to do the check on definitions, which require that
6199 // the type is complete.
6200 if (VD->isThisDeclarationADefinition())
6201 return;
6202
6203 Info.CheckType(D: VD, TL: VD->getTypeSourceInfo()->getTypeLoc(),
6204 Sel: Sema::AbstractVariableType);
6205}
6206
6207/// Check for invalid uses of an abstract type within a class definition.
6208static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6209 CXXRecordDecl *RD) {
6210 for (auto *D : RD->decls()) {
6211 if (D->isImplicit()) continue;
6212
6213 // Step through friends to the befriended declaration.
6214 if (auto *FD = dyn_cast<FriendDecl>(Val: D)) {
6215 D = FD->getFriendDecl();
6216 if (!D) continue;
6217 }
6218
6219 // Functions and function templates.
6220 if (auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
6221 CheckAbstractClassUsage(Info, FD);
6222 } else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Val: D)) {
6223 CheckAbstractClassUsage(Info, FD: FTD->getTemplatedDecl());
6224
6225 // Fields and static variables.
6226 } else if (auto *FD = dyn_cast<FieldDecl>(Val: D)) {
6227 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6228 Info.CheckType(D: FD, TL: TSI->getTypeLoc(), Sel: Sema::AbstractFieldType);
6229 } else if (auto *VD = dyn_cast<VarDecl>(Val: D)) {
6230 CheckAbstractClassUsage(Info, VD);
6231 } else if (auto *VTD = dyn_cast<VarTemplateDecl>(Val: D)) {
6232 CheckAbstractClassUsage(Info, VD: VTD->getTemplatedDecl());
6233
6234 // Nested classes and class templates.
6235 } else if (auto *RD = dyn_cast<CXXRecordDecl>(Val: D)) {
6236 CheckAbstractClassUsage(Info, RD);
6237 } else if (auto *CTD = dyn_cast<ClassTemplateDecl>(Val: D)) {
6238 CheckAbstractClassUsage(Info, RD: CTD->getTemplatedDecl());
6239 }
6240 }
6241}
6242
6243static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
6244 Attr *ClassAttr = getDLLAttr(D: Class);
6245 if (!ClassAttr)
6246 return;
6247
6248 assert(ClassAttr->getKind() == attr::DLLExport);
6249
6250 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6251
6252 if (TSK == TSK_ExplicitInstantiationDeclaration)
6253 // Don't go any further if this is just an explicit instantiation
6254 // declaration.
6255 return;
6256
6257 // Add a context note to explain how we got to any diagnostics produced below.
6258 struct MarkingClassDllexported {
6259 Sema &S;
6260 MarkingClassDllexported(Sema &S, CXXRecordDecl *Class,
6261 SourceLocation AttrLoc)
6262 : S(S) {
6263 Sema::CodeSynthesisContext Ctx;
6264 Ctx.Kind = Sema::CodeSynthesisContext::MarkingClassDllexported;
6265 Ctx.PointOfInstantiation = AttrLoc;
6266 Ctx.Entity = Class;
6267 S.pushCodeSynthesisContext(Ctx);
6268 }
6269 ~MarkingClassDllexported() {
6270 S.popCodeSynthesisContext();
6271 }
6272 } MarkingDllexportedContext(S, Class, ClassAttr->getLocation());
6273
6274 if (S.Context.getTargetInfo().getTriple().isOSCygMing())
6275 S.MarkVTableUsed(Loc: Class->getLocation(), Class, DefinitionRequired: true);
6276
6277 for (Decl *Member : Class->decls()) {
6278 // Skip members that were not marked exported.
6279 if (!Member->hasAttr<DLLExportAttr>())
6280 continue;
6281
6282 // Defined static variables that are members of an exported base
6283 // class must be marked export too.
6284 auto *VD = dyn_cast<VarDecl>(Val: Member);
6285 if (VD && VD->getStorageClass() == SC_Static &&
6286 TSK == TSK_ImplicitInstantiation)
6287 S.MarkVariableReferenced(Loc: VD->getLocation(), Var: VD);
6288
6289 auto *MD = dyn_cast<CXXMethodDecl>(Val: Member);
6290 if (!MD)
6291 continue;
6292
6293 if (MD->isUserProvided()) {
6294 // Instantiate non-default class member functions ...
6295
6296 // .. except for certain kinds of template specializations.
6297 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
6298 continue;
6299
6300 // If this is an MS ABI dllexport default constructor, instantiate any
6301 // default arguments.
6302 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
6303 auto *CD = dyn_cast<CXXConstructorDecl>(Val: MD);
6304 if (CD && CD->isDefaultConstructor() && TSK == TSK_Undeclared) {
6305 S.InstantiateDefaultCtorDefaultArgs(Ctor: CD);
6306 }
6307 }
6308
6309 S.MarkFunctionReferenced(Loc: Class->getLocation(), Func: MD);
6310
6311 // The function will be passed to the consumer when its definition is
6312 // encountered.
6313 } else if (MD->isExplicitlyDefaulted()) {
6314 // Synthesize and instantiate explicitly defaulted methods.
6315 S.MarkFunctionReferenced(Loc: Class->getLocation(), Func: MD);
6316
6317 if (TSK != TSK_ExplicitInstantiationDefinition) {
6318 // Except for explicit instantiation defs, we will not see the
6319 // definition again later, so pass it to the consumer now.
6320 S.Consumer.HandleTopLevelDecl(D: DeclGroupRef(MD));
6321 }
6322 } else if (!MD->isTrivial() ||
6323 MD->isCopyAssignmentOperator() ||
6324 MD->isMoveAssignmentOperator()) {
6325 // Synthesize and instantiate non-trivial implicit methods, and the copy
6326 // and move assignment operators. The latter are exported even if they
6327 // are trivial, because the address of an operator can be taken and
6328 // should compare equal across libraries.
6329 S.MarkFunctionReferenced(Loc: Class->getLocation(), Func: MD);
6330
6331 // There is no later point when we will see the definition of this
6332 // function, so pass it to the consumer now.
6333 S.Consumer.HandleTopLevelDecl(D: DeclGroupRef(MD));
6334 }
6335 }
6336}
6337
6338static void checkForMultipleExportedDefaultConstructors(Sema &S,
6339 CXXRecordDecl *Class) {
6340 // Only the MS ABI has default constructor closures, so we don't need to do
6341 // this semantic checking anywhere else.
6342 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
6343 return;
6344
6345 CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
6346 for (Decl *Member : Class->decls()) {
6347 // Look for exported default constructors.
6348 auto *CD = dyn_cast<CXXConstructorDecl>(Val: Member);
6349 if (!CD || !CD->isDefaultConstructor())
6350 continue;
6351 auto *Attr = CD->getAttr<DLLExportAttr>();
6352 if (!Attr)
6353 continue;
6354
6355 // If the class is non-dependent, mark the default arguments as ODR-used so
6356 // that we can properly codegen the constructor closure.
6357 if (!Class->isDependentContext()) {
6358 for (ParmVarDecl *PD : CD->parameters()) {
6359 (void)S.CheckCXXDefaultArgExpr(CallLoc: Attr->getLocation(), FD: CD, Param: PD);
6360 S.DiscardCleanupsInEvaluationContext();
6361 }
6362 }
6363
6364 if (LastExportedDefaultCtor) {
6365 S.Diag(Loc: LastExportedDefaultCtor->getLocation(),
6366 DiagID: diag::err_attribute_dll_ambiguous_default_ctor)
6367 << Class;
6368 S.Diag(Loc: CD->getLocation(), DiagID: diag::note_entity_declared_at)
6369 << CD->getDeclName();
6370 return;
6371 }
6372 LastExportedDefaultCtor = CD;
6373 }
6374}
6375
6376static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S,
6377 CXXRecordDecl *Class) {
6378 bool ErrorReported = false;
6379 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6380 ClassTemplateDecl *TD) {
6381 if (ErrorReported)
6382 return;
6383 S.Diag(Loc: TD->getLocation(),
6384 DiagID: diag::err_cuda_device_builtin_surftex_cls_template)
6385 << /*surface*/ 0 << TD;
6386 ErrorReported = true;
6387 };
6388
6389 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6390 if (!TD) {
6391 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Val: Class);
6392 if (!SD) {
6393 S.Diag(Loc: Class->getLocation(),
6394 DiagID: diag::err_cuda_device_builtin_surftex_ref_decl)
6395 << /*surface*/ 0 << Class;
6396 S.Diag(Loc: Class->getLocation(),
6397 DiagID: diag::note_cuda_device_builtin_surftex_should_be_template_class)
6398 << Class;
6399 return;
6400 }
6401 TD = SD->getSpecializedTemplate();
6402 }
6403
6404 TemplateParameterList *Params = TD->getTemplateParameters();
6405 unsigned N = Params->size();
6406
6407 if (N != 2) {
6408 reportIllegalClassTemplate(S, TD);
6409 S.Diag(Loc: TD->getLocation(),
6410 DiagID: diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6411 << TD << 2;
6412 }
6413 if (N > 0 && !isa<TemplateTypeParmDecl>(Val: Params->getParam(Idx: 0))) {
6414 reportIllegalClassTemplate(S, TD);
6415 S.Diag(Loc: TD->getLocation(),
6416 DiagID: diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6417 << TD << /*1st*/ 0 << /*type*/ 0;
6418 }
6419 if (N > 1) {
6420 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: Params->getParam(Idx: 1));
6421 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6422 reportIllegalClassTemplate(S, TD);
6423 S.Diag(Loc: TD->getLocation(),
6424 DiagID: diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6425 << TD << /*2nd*/ 1 << /*integer*/ 1;
6426 }
6427 }
6428}
6429
6430static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S,
6431 CXXRecordDecl *Class) {
6432 bool ErrorReported = false;
6433 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6434 ClassTemplateDecl *TD) {
6435 if (ErrorReported)
6436 return;
6437 S.Diag(Loc: TD->getLocation(),
6438 DiagID: diag::err_cuda_device_builtin_surftex_cls_template)
6439 << /*texture*/ 1 << TD;
6440 ErrorReported = true;
6441 };
6442
6443 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6444 if (!TD) {
6445 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Val: Class);
6446 if (!SD) {
6447 S.Diag(Loc: Class->getLocation(),
6448 DiagID: diag::err_cuda_device_builtin_surftex_ref_decl)
6449 << /*texture*/ 1 << Class;
6450 S.Diag(Loc: Class->getLocation(),
6451 DiagID: diag::note_cuda_device_builtin_surftex_should_be_template_class)
6452 << Class;
6453 return;
6454 }
6455 TD = SD->getSpecializedTemplate();
6456 }
6457
6458 TemplateParameterList *Params = TD->getTemplateParameters();
6459 unsigned N = Params->size();
6460
6461 if (N != 3) {
6462 reportIllegalClassTemplate(S, TD);
6463 S.Diag(Loc: TD->getLocation(),
6464 DiagID: diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6465 << TD << 3;
6466 }
6467 if (N > 0 && !isa<TemplateTypeParmDecl>(Val: Params->getParam(Idx: 0))) {
6468 reportIllegalClassTemplate(S, TD);
6469 S.Diag(Loc: TD->getLocation(),
6470 DiagID: diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6471 << TD << /*1st*/ 0 << /*type*/ 0;
6472 }
6473 if (N > 1) {
6474 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: Params->getParam(Idx: 1));
6475 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6476 reportIllegalClassTemplate(S, TD);
6477 S.Diag(Loc: TD->getLocation(),
6478 DiagID: diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6479 << TD << /*2nd*/ 1 << /*integer*/ 1;
6480 }
6481 }
6482 if (N > 2) {
6483 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: Params->getParam(Idx: 2));
6484 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6485 reportIllegalClassTemplate(S, TD);
6486 S.Diag(Loc: TD->getLocation(),
6487 DiagID: diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6488 << TD << /*3rd*/ 2 << /*integer*/ 1;
6489 }
6490 }
6491}
6492
6493void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
6494 // Mark any compiler-generated routines with the implicit code_seg attribute.
6495 for (auto *Method : Class->methods()) {
6496 if (Method->isUserProvided())
6497 continue;
6498 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(FD: Method, /*IsDefinition=*/true))
6499 Method->addAttr(A);
6500 }
6501}
6502
6503void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
6504 Attr *ClassAttr = getDLLAttr(D: Class);
6505
6506 // MSVC inherits DLL attributes to partial class template specializations.
6507 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) {
6508 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Val: Class)) {
6509 if (Attr *TemplateAttr =
6510 getDLLAttr(D: Spec->getSpecializedTemplate()->getTemplatedDecl())) {
6511 auto *A = cast<InheritableAttr>(Val: TemplateAttr->clone(C&: getASTContext()));
6512 A->setInherited(true);
6513 ClassAttr = A;
6514 }
6515 }
6516 }
6517
6518 if (!ClassAttr)
6519 return;
6520
6521 // MSVC allows imported or exported template classes that have UniqueExternal
6522 // linkage. This occurs when the template class has been instantiated with
6523 // a template parameter which itself has internal linkage.
6524 // We drop the attribute to avoid exporting or importing any members.
6525 if ((Context.getTargetInfo().getCXXABI().isMicrosoft() ||
6526 Context.getTargetInfo().getTriple().isPS()) &&
6527 (!Class->isExternallyVisible() && Class->hasExternalFormalLinkage())) {
6528 Class->dropAttrs<DLLExportAttr, DLLImportAttr>();
6529 return;
6530 }
6531
6532 if (!Class->isExternallyVisible()) {
6533 Diag(Loc: Class->getLocation(), DiagID: diag::err_attribute_dll_not_extern)
6534 << Class << ClassAttr;
6535 return;
6536 }
6537
6538 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6539 !ClassAttr->isInherited()) {
6540 // Diagnose dll attributes on members of class with dll attribute.
6541 for (Decl *Member : Class->decls()) {
6542 if (!isa<VarDecl>(Val: Member) && !isa<CXXMethodDecl>(Val: Member))
6543 continue;
6544 InheritableAttr *MemberAttr = getDLLAttr(D: Member);
6545 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
6546 continue;
6547
6548 Diag(Loc: MemberAttr->getLocation(),
6549 DiagID: diag::err_attribute_dll_member_of_dll_class)
6550 << MemberAttr << ClassAttr;
6551 Diag(Loc: ClassAttr->getLocation(), DiagID: diag::note_previous_attribute);
6552 Member->setInvalidDecl();
6553 }
6554 }
6555
6556 if (Class->getDescribedClassTemplate())
6557 // Don't inherit dll attribute until the template is instantiated.
6558 return;
6559
6560 // The class is either imported or exported.
6561 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
6562
6563 // Check if this was a dllimport attribute propagated from a derived class to
6564 // a base class template specialization. We don't apply these attributes to
6565 // static data members.
6566 const bool PropagatedImport =
6567 !ClassExported &&
6568 cast<DLLImportAttr>(Val: ClassAttr)->wasPropagatedToBaseTemplate();
6569
6570 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6571
6572 // Ignore explicit dllexport on explicit class template instantiation
6573 // declarations, except in MinGW mode.
6574 if (ClassExported && !ClassAttr->isInherited() &&
6575 TSK == TSK_ExplicitInstantiationDeclaration &&
6576 !Context.getTargetInfo().getTriple().isOSCygMing()) {
6577 if (auto *DEA = Class->getAttr<DLLExportAttr>()) {
6578 Class->addAttr(A: DLLExportOnDeclAttr::Create(Ctx&: Context, Range: DEA->getLoc()));
6579 Class->dropAttr<DLLExportAttr>();
6580 }
6581 return;
6582 }
6583
6584 // Force declaration of implicit members so they can inherit the attribute.
6585 ForceDeclarationOfImplicitMembers(Class);
6586
6587 // Inherited constructors are created lazily; force their creation now so the
6588 // loop below can propagate the DLL attribute to them.
6589 if (ClassExported && getLangOpts().DllExportInlines) {
6590 SmallVector<ConstructorUsingShadowDecl *, 4> Shadows;
6591 for (Decl *D : Class->decls())
6592 if (auto *S = dyn_cast<ConstructorUsingShadowDecl>(Val: D))
6593 Shadows.push_back(Elt: S);
6594 for (ConstructorUsingShadowDecl *S : Shadows) {
6595 CXXConstructorDecl *BC = dyn_cast<CXXConstructorDecl>(Val: S->getTargetDecl());
6596 if (!BC || BC->isDeleted())
6597 continue;
6598 // Skip constructors whose requires clause is not satisfied.
6599 // Normally overload resolution filters these, but we are bypassing
6600 // it to eagerly create inherited constructors for dllexport.
6601 if (BC->getTrailingRequiresClause()) {
6602 ConstraintSatisfaction Satisfaction;
6603 if (CheckFunctionConstraints(FD: BC, Satisfaction) ||
6604 !Satisfaction.IsSatisfied)
6605 continue;
6606 }
6607 findInheritingConstructor(Loc: Class->getLocation(), BaseCtor: BC, DerivedShadow: S);
6608 }
6609 }
6610
6611 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
6612 // seem to be true in practice?
6613
6614 for (Decl *Member : Class->decls()) {
6615 if (Member->hasAttr<ExcludeFromExplicitInstantiationAttr>())
6616 continue;
6617
6618 VarDecl *VD = dyn_cast<VarDecl>(Val: Member);
6619 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: Member);
6620
6621 // Only methods and static fields inherit the attributes.
6622 if (!VD && !MD)
6623 continue;
6624
6625 if (MD) {
6626 // Don't process deleted methods.
6627 if (MD->isDeleted())
6628 continue;
6629
6630 if (ClassExported && getLangOpts().DllExportInlines) {
6631 CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Val: MD);
6632 if (CD && CD->getInheritedConstructor()) {
6633 // Inherited constructors already had their base constructor's
6634 // constraints checked before creation via
6635 // findInheritingConstructor, so only ABI-compatibility checks
6636 // are needed here.
6637 //
6638 // Don't export inherited constructors whose parameters prevent
6639 // ABI-compatible forwarding. When canEmitDelegateCallArgs (in
6640 // CodeGen) returns false, Clang inlines the constructor body
6641 // instead of emitting a forwarding thunk, producing code that
6642 // is not ABI-compatible with MSVC. Suppress the export and warn
6643 // so the user gets a linker error rather than a silent runtime
6644 // mismatch.
6645 if (CD->isVariadic()) {
6646 Diag(Loc: CD->getLocation(),
6647 DiagID: diag::warn_dllexport_inherited_ctor_unsupported)
6648 << /*variadic=*/0;
6649 continue;
6650 }
6651 if (Context.getTargetInfo()
6652 .getCXXABI()
6653 .areArgsDestroyedLeftToRightInCallee()) {
6654 bool HasCalleeCleanupParam = false;
6655 for (const ParmVarDecl *P : CD->parameters())
6656 if (P->needsDestruction(Ctx: Context)) {
6657 HasCalleeCleanupParam = true;
6658 break;
6659 }
6660 if (HasCalleeCleanupParam) {
6661 Diag(Loc: CD->getLocation(),
6662 DiagID: diag::warn_dllexport_inherited_ctor_unsupported)
6663 << /*callee-cleanup=*/1;
6664 continue;
6665 }
6666 }
6667 } else if (MD->getTrailingRequiresClause()) {
6668 // Don't export methods whose requires clause is not satisfied.
6669 // For class template specializations, member constraints may
6670 // depend on template arguments and an unsatisfied constraint
6671 // means the member should not be available in this
6672 // specialization.
6673 ConstraintSatisfaction Satisfaction;
6674 if (CheckFunctionConstraints(FD: MD, Satisfaction) ||
6675 !Satisfaction.IsSatisfied)
6676 continue;
6677 }
6678 }
6679
6680 if (MD->isInlined()) {
6681 // MinGW does not import or export inline methods. But do it for
6682 // template instantiations and inherited constructors (which are
6683 // marked inline but must be exported to match MSVC behavior).
6684 if (!Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6685 TSK != TSK_ExplicitInstantiationDeclaration &&
6686 TSK != TSK_ExplicitInstantiationDefinition) {
6687 if (auto *CD = dyn_cast<CXXConstructorDecl>(Val: MD);
6688 !CD || !CD->getInheritedConstructor())
6689 continue;
6690 }
6691
6692 // MSVC versions before 2015 don't export the move assignment operators
6693 // and move constructor, so don't attempt to import/export them if
6694 // we have a definition.
6695 auto *Ctor = dyn_cast<CXXConstructorDecl>(Val: MD);
6696 if ((MD->isMoveAssignmentOperator() ||
6697 (Ctor && Ctor->isMoveConstructor())) &&
6698 getLangOpts().isCompatibleWithMSVC() &&
6699 !getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015))
6700 continue;
6701
6702 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
6703 // operator is exported anyway.
6704 if (getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015) &&
6705 (Ctor || isa<CXXDestructorDecl>(Val: MD)) && MD->isTrivial())
6706 continue;
6707 }
6708 }
6709
6710 // Don't apply dllimport attributes to static data members of class template
6711 // instantiations when the attribute is propagated from a derived class.
6712 if (VD && PropagatedImport)
6713 continue;
6714
6715 if (!cast<NamedDecl>(Val: Member)->isExternallyVisible())
6716 continue;
6717
6718 if (!getDLLAttr(D: Member)) {
6719 InheritableAttr *NewAttr = nullptr;
6720
6721 // Do not export/import inline function when -fno-dllexport-inlines is
6722 // passed. But add attribute for later local static var check.
6723 if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
6724 TSK != TSK_ExplicitInstantiationDeclaration &&
6725 TSK != TSK_ExplicitInstantiationDefinition) {
6726 if (ClassExported) {
6727 NewAttr = ::new (getASTContext())
6728 DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);
6729 } else {
6730 NewAttr = ::new (getASTContext())
6731 DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);
6732 }
6733 } else {
6734 NewAttr = cast<InheritableAttr>(Val: ClassAttr->clone(C&: getASTContext()));
6735 }
6736
6737 NewAttr->setInherited(true);
6738 Member->addAttr(A: NewAttr);
6739
6740 if (MD) {
6741 // Propagate DLLAttr to friend re-declarations of MD that have already
6742 // been constructed.
6743 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
6744 FD = FD->getPreviousDecl()) {
6745 if (FD->getFriendObjectKind() == Decl::FOK_None)
6746 continue;
6747 assert(!getDLLAttr(FD) &&
6748 "friend re-decl should not already have a DLLAttr");
6749 NewAttr = cast<InheritableAttr>(Val: ClassAttr->clone(C&: getASTContext()));
6750 NewAttr->setInherited(true);
6751 FD->addAttr(A: NewAttr);
6752 }
6753 }
6754 }
6755 }
6756
6757 if (ClassExported)
6758 DelayedDllExportClasses.push_back(Elt: Class);
6759}
6760
6761void Sema::propagateDLLAttrToBaseClassTemplate(
6762 CXXRecordDecl *Class, Attr *ClassAttr,
6763 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
6764 if (getDLLAttr(
6765 D: BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
6766 // If the base class template has a DLL attribute, don't try to change it.
6767 return;
6768 }
6769
6770 auto TSK = BaseTemplateSpec->getSpecializationKind();
6771 if (!getDLLAttr(D: BaseTemplateSpec) &&
6772 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
6773 TSK == TSK_ImplicitInstantiation)) {
6774 // The template hasn't been instantiated yet (or it has, but only as an
6775 // explicit instantiation declaration or implicit instantiation, which means
6776 // we haven't codegenned any members yet), so propagate the attribute.
6777 auto *NewAttr = cast<InheritableAttr>(Val: ClassAttr->clone(C&: getASTContext()));
6778 NewAttr->setInherited(true);
6779 BaseTemplateSpec->addAttr(A: NewAttr);
6780
6781 // If this was an import, mark that we propagated it from a derived class to
6782 // a base class template specialization.
6783 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(Val: NewAttr))
6784 ImportAttr->setPropagatedToBaseTemplate();
6785
6786 // If the template is already instantiated, checkDLLAttributeRedeclaration()
6787 // needs to be run again to work see the new attribute. Otherwise this will
6788 // get run whenever the template is instantiated.
6789 if (TSK != TSK_Undeclared)
6790 checkClassLevelDLLAttribute(Class: BaseTemplateSpec);
6791
6792 return;
6793 }
6794
6795 if (getDLLAttr(D: BaseTemplateSpec)) {
6796 // The template has already been specialized or instantiated with an
6797 // attribute, explicitly or through propagation. We should not try to change
6798 // it.
6799 return;
6800 }
6801
6802 // The template was previously instantiated or explicitly specialized without
6803 // a dll attribute, It's too late for us to add an attribute, so warn that
6804 // this is unsupported.
6805 Diag(Loc: BaseLoc, DiagID: diag::warn_attribute_dll_instantiated_base_class)
6806 << BaseTemplateSpec->isExplicitSpecialization();
6807 Diag(Loc: ClassAttr->getLocation(), DiagID: diag::note_attribute);
6808 if (BaseTemplateSpec->isExplicitSpecialization()) {
6809 Diag(Loc: BaseTemplateSpec->getLocation(),
6810 DiagID: diag::note_template_class_explicit_specialization_was_here)
6811 << BaseTemplateSpec;
6812 } else {
6813 Diag(Loc: BaseTemplateSpec->getPointOfInstantiation(),
6814 DiagID: diag::note_template_class_instantiation_was_here)
6815 << BaseTemplateSpec;
6816 }
6817}
6818
6819Sema::DefaultedFunctionKind
6820Sema::getDefaultedFunctionKind(const FunctionDecl *FD) {
6821 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: FD)) {
6822 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Val: FD)) {
6823 if (Ctor->isDefaultConstructor())
6824 return CXXSpecialMemberKind::DefaultConstructor;
6825
6826 if (Ctor->isCopyConstructor())
6827 return CXXSpecialMemberKind::CopyConstructor;
6828
6829 if (Ctor->isMoveConstructor())
6830 return CXXSpecialMemberKind::MoveConstructor;
6831 }
6832
6833 if (MD->isCopyAssignmentOperator())
6834 return CXXSpecialMemberKind::CopyAssignment;
6835
6836 if (MD->isMoveAssignmentOperator())
6837 return CXXSpecialMemberKind::MoveAssignment;
6838
6839 if (isa<CXXDestructorDecl>(Val: FD))
6840 return CXXSpecialMemberKind::Destructor;
6841 }
6842
6843 switch (FD->getDeclName().getCXXOverloadedOperator()) {
6844 case OO_EqualEqual:
6845 return DefaultedComparisonKind::Equal;
6846
6847 case OO_ExclaimEqual:
6848 return DefaultedComparisonKind::NotEqual;
6849
6850 case OO_Spaceship:
6851 // No point allowing this if <=> doesn't exist in the current language mode.
6852 if (!getLangOpts().CPlusPlus20)
6853 break;
6854 return DefaultedComparisonKind::ThreeWay;
6855
6856 case OO_Less:
6857 case OO_LessEqual:
6858 case OO_Greater:
6859 case OO_GreaterEqual:
6860 // No point allowing this if <=> doesn't exist in the current language mode.
6861 if (!getLangOpts().CPlusPlus20)
6862 break;
6863 return DefaultedComparisonKind::Relational;
6864
6865 default:
6866 break;
6867 }
6868
6869 // Not defaultable.
6870 return DefaultedFunctionKind();
6871}
6872
6873static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD,
6874 SourceLocation DefaultLoc) {
6875 Sema::DefaultedFunctionKind DFK = S.getDefaultedFunctionKind(FD);
6876 if (DFK.isComparison())
6877 return S.DefineDefaultedComparison(Loc: DefaultLoc, FD, DCK: DFK.asComparison());
6878
6879 switch (DFK.asSpecialMember()) {
6880 case CXXSpecialMemberKind::DefaultConstructor:
6881 S.DefineImplicitDefaultConstructor(CurrentLocation: DefaultLoc,
6882 Constructor: cast<CXXConstructorDecl>(Val: FD));
6883 break;
6884 case CXXSpecialMemberKind::CopyConstructor:
6885 S.DefineImplicitCopyConstructor(CurrentLocation: DefaultLoc, Constructor: cast<CXXConstructorDecl>(Val: FD));
6886 break;
6887 case CXXSpecialMemberKind::CopyAssignment:
6888 S.DefineImplicitCopyAssignment(CurrentLocation: DefaultLoc, MethodDecl: cast<CXXMethodDecl>(Val: FD));
6889 break;
6890 case CXXSpecialMemberKind::Destructor:
6891 S.DefineImplicitDestructor(CurrentLocation: DefaultLoc, Destructor: cast<CXXDestructorDecl>(Val: FD));
6892 break;
6893 case CXXSpecialMemberKind::MoveConstructor:
6894 S.DefineImplicitMoveConstructor(CurrentLocation: DefaultLoc, Constructor: cast<CXXConstructorDecl>(Val: FD));
6895 break;
6896 case CXXSpecialMemberKind::MoveAssignment:
6897 S.DefineImplicitMoveAssignment(CurrentLocation: DefaultLoc, MethodDecl: cast<CXXMethodDecl>(Val: FD));
6898 break;
6899 case CXXSpecialMemberKind::Invalid:
6900 llvm_unreachable("Invalid special member.");
6901 }
6902}
6903
6904/// Determine whether a type is permitted to be passed or returned in
6905/// registers, per C++ [class.temporary]p3.
6906static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
6907 TargetInfo::CallingConvKind CCK) {
6908 if (D->isDependentType() || D->isInvalidDecl())
6909 return false;
6910
6911 // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
6912 // The PS4 platform ABI follows the behavior of Clang 3.2.
6913 if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
6914 return !D->hasNonTrivialDestructorForCall() &&
6915 !D->hasNonTrivialCopyConstructorForCall();
6916
6917 if (CCK == TargetInfo::CCK_MicrosoftWin64) {
6918 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
6919 bool DtorIsTrivialForCall = false;
6920
6921 // If a class has at least one eligible, trivial copy constructor, it
6922 // is passed according to the C ABI. Otherwise, it is passed indirectly.
6923 //
6924 // Note: This permits classes with non-trivial copy or move ctors to be
6925 // passed in registers, so long as they *also* have a trivial copy ctor,
6926 // which is non-conforming.
6927 if (D->needsImplicitCopyConstructor()) {
6928 if (!D->defaultedCopyConstructorIsDeleted()) {
6929 if (D->hasTrivialCopyConstructor())
6930 CopyCtorIsTrivial = true;
6931 if (D->hasTrivialCopyConstructorForCall())
6932 CopyCtorIsTrivialForCall = true;
6933 }
6934 } else {
6935 for (const CXXConstructorDecl *CD : D->ctors()) {
6936 if (CD->isCopyConstructor() && !CD->isDeleted() &&
6937 !CD->isIneligibleOrNotSelected()) {
6938 if (CD->isTrivial())
6939 CopyCtorIsTrivial = true;
6940 if (CD->isTrivialForCall())
6941 CopyCtorIsTrivialForCall = true;
6942 }
6943 }
6944 }
6945
6946 if (D->needsImplicitDestructor()) {
6947 if (!D->defaultedDestructorIsDeleted() &&
6948 D->hasTrivialDestructorForCall())
6949 DtorIsTrivialForCall = true;
6950 } else if (const auto *DD = D->getDestructor()) {
6951 if (!DD->isDeleted() && DD->isTrivialForCall())
6952 DtorIsTrivialForCall = true;
6953 }
6954
6955 // If the copy ctor and dtor are both trivial-for-calls, pass direct.
6956 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
6957 return true;
6958
6959 // If a class has a destructor, we'd really like to pass it indirectly
6960 // because it allows us to elide copies. Unfortunately, MSVC makes that
6961 // impossible for small types, which it will pass in a single register or
6962 // stack slot. Most objects with dtors are large-ish, so handle that early.
6963 // We can't call out all large objects as being indirect because there are
6964 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
6965 // how we pass large POD types.
6966
6967 // Note: This permits small classes with nontrivial destructors to be
6968 // passed in registers, which is non-conforming.
6969 bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
6970 uint64_t TypeSize = isAArch64 ? 128 : 64;
6971
6972 if (CopyCtorIsTrivial && S.getASTContext().getTypeSize(
6973 T: S.Context.getCanonicalTagType(TD: D)) <= TypeSize)
6974 return true;
6975 return false;
6976 }
6977
6978 // Per C++ [class.temporary]p3, the relevant condition is:
6979 // each copy constructor, move constructor, and destructor of X is
6980 // either trivial or deleted, and X has at least one non-deleted copy
6981 // or move constructor
6982 bool HasNonDeletedCopyOrMove = false;
6983
6984 if (D->needsImplicitCopyConstructor() &&
6985 !D->defaultedCopyConstructorIsDeleted()) {
6986 if (!D->hasTrivialCopyConstructorForCall())
6987 return false;
6988 HasNonDeletedCopyOrMove = true;
6989 }
6990
6991 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
6992 !D->defaultedMoveConstructorIsDeleted()) {
6993 if (!D->hasTrivialMoveConstructorForCall())
6994 return false;
6995 HasNonDeletedCopyOrMove = true;
6996 }
6997
6998 if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
6999 !D->hasTrivialDestructorForCall())
7000 return false;
7001
7002 for (const CXXMethodDecl *MD : D->methods()) {
7003 if (MD->isDeleted() || MD->isIneligibleOrNotSelected())
7004 continue;
7005
7006 auto *CD = dyn_cast<CXXConstructorDecl>(Val: MD);
7007 if (CD && CD->isCopyOrMoveConstructor())
7008 HasNonDeletedCopyOrMove = true;
7009 else if (!isa<CXXDestructorDecl>(Val: MD))
7010 continue;
7011
7012 if (!MD->isTrivialForCall())
7013 return false;
7014 }
7015
7016 return HasNonDeletedCopyOrMove;
7017}
7018
7019/// Report an error regarding overriding, along with any relevant
7020/// overridden methods.
7021///
7022/// \param DiagID the primary error to report.
7023/// \param MD the overriding method.
7024static bool
7025ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD,
7026 llvm::function_ref<bool(const CXXMethodDecl *)> Report) {
7027 bool IssuedDiagnostic = false;
7028 for (const CXXMethodDecl *O : MD->overridden_methods()) {
7029 if (Report(O)) {
7030 if (!IssuedDiagnostic) {
7031 S.Diag(Loc: MD->getLocation(), DiagID) << MD->getDeclName();
7032 IssuedDiagnostic = true;
7033 }
7034 S.Diag(Loc: O->getLocation(), DiagID: diag::note_overridden_virtual_function);
7035 }
7036 }
7037 return IssuedDiagnostic;
7038}
7039
7040void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) {
7041 if (!Record)
7042 return;
7043
7044 if (Record->isAbstract() && !Record->isInvalidDecl()) {
7045 AbstractUsageInfo Info(*this, Record);
7046 CheckAbstractClassUsage(Info, RD: Record);
7047 }
7048
7049 // If this is not an aggregate type and has no user-declared constructor,
7050 // complain about any non-static data members of reference or const scalar
7051 // type, since they will never get initializers.
7052 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
7053 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
7054 !Record->isLambda()) {
7055 bool Complained = false;
7056 for (const auto *F : Record->fields()) {
7057 if (F->hasInClassInitializer() || F->isUnnamedBitField())
7058 continue;
7059
7060 if (F->getType()->isReferenceType() ||
7061 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
7062 if (!Complained) {
7063 Diag(Loc: Record->getLocation(), DiagID: diag::warn_no_constructor_for_refconst)
7064 << Record->getTagKind() << Record;
7065 Complained = true;
7066 }
7067
7068 Diag(Loc: F->getLocation(), DiagID: diag::note_refconst_member_not_initialized)
7069 << F->getType()->isReferenceType()
7070 << F->getDeclName();
7071 }
7072 }
7073 }
7074
7075 if (Record->getIdentifier()) {
7076 // C++ [class.mem]p13:
7077 // If T is the name of a class, then each of the following shall have a
7078 // name different from T:
7079 // - every member of every anonymous union that is a member of class T.
7080 //
7081 // C++ [class.mem]p14:
7082 // In addition, if class T has a user-declared constructor (12.1), every
7083 // non-static data member of class T shall have a name different from T.
7084 for (const NamedDecl *Element : Record->lookup(Name: Record->getDeclName())) {
7085 const NamedDecl *D = Element->getUnderlyingDecl();
7086 // Invalid IndirectFieldDecls have already been diagnosed with
7087 // err_anonymous_record_member_redecl in
7088 // SemaDecl.cpp:CheckAnonMemberRedeclaration.
7089 if (((isa<FieldDecl>(Val: D) || isa<UnresolvedUsingValueDecl>(Val: D)) &&
7090 Record->hasUserDeclaredConstructor()) ||
7091 (isa<IndirectFieldDecl>(Val: D) && !D->isInvalidDecl())) {
7092 Diag(Loc: Element->getLocation(), DiagID: diag::err_member_name_of_class)
7093 << D->getDeclName();
7094 break;
7095 }
7096 }
7097 }
7098
7099 // Warn if the class has virtual methods but non-virtual public destructor.
7100 if (Record->isPolymorphic() && !Record->isDependentType()) {
7101 CXXDestructorDecl *dtor = Record->getDestructor();
7102 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
7103 !Record->hasAttr<FinalAttr>())
7104 Diag(Loc: dtor ? dtor->getLocation() : Record->getLocation(),
7105 DiagID: diag::warn_non_virtual_dtor)
7106 << Context.getCanonicalTagType(TD: Record);
7107 }
7108
7109 if (Record->isAbstract()) {
7110 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
7111 Diag(Loc: Record->getLocation(), DiagID: diag::warn_abstract_final_class)
7112 << FA->isSpelledAsSealed();
7113 DiagnoseAbstractType(RD: Record);
7114 }
7115 }
7116
7117 // Warn if the class has a final destructor but is not itself marked final.
7118 if (!Record->hasAttr<FinalAttr>()) {
7119 if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
7120 if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
7121 Diag(Loc: FA->getLocation(), DiagID: diag::warn_final_dtor_non_final_class)
7122 << FA->isSpelledAsSealed()
7123 << FixItHint::CreateInsertion(
7124 InsertionLoc: getLocForEndOfToken(Loc: Record->getLocation()),
7125 Code: (FA->isSpelledAsSealed() ? " sealed" : " final"));
7126 Diag(Loc: Record->getLocation(),
7127 DiagID: diag::note_final_dtor_non_final_class_silence)
7128 << Context.getCanonicalTagType(TD: Record) << FA->isSpelledAsSealed();
7129 }
7130 }
7131 }
7132
7133 // See if trivial_abi has to be dropped.
7134 if (Record->hasAttr<TrivialABIAttr>())
7135 checkIllFormedTrivialABIStruct(RD&: *Record);
7136
7137 // Set HasTrivialSpecialMemberForCall if the record has attribute
7138 // "trivial_abi".
7139 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
7140
7141 if (HasTrivialABI)
7142 Record->setHasTrivialSpecialMemberForCall();
7143
7144 // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=).
7145 // We check these last because they can depend on the properties of the
7146 // primary comparison functions (==, <=>).
7147 llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons;
7148
7149 // Perform checks that can't be done until we know all the properties of a
7150 // member function (whether it's defaulted, deleted, virtual, overriding,
7151 // ...).
7152 auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) {
7153 // A static function cannot override anything.
7154 if (MD->getStorageClass() == SC_Static) {
7155 if (ReportOverrides(S&: *this, DiagID: diag::err_static_overrides_virtual, MD,
7156 Report: [](const CXXMethodDecl *) { return true; }))
7157 return;
7158 }
7159
7160 // A deleted function cannot override a non-deleted function and vice
7161 // versa.
7162 if (ReportOverrides(S&: *this,
7163 DiagID: MD->isDeleted() ? diag::err_deleted_override
7164 : diag::err_non_deleted_override,
7165 MD, Report: [&](const CXXMethodDecl *V) {
7166 return MD->isDeleted() != V->isDeleted();
7167 })) {
7168 if (MD->isDefaulted() && MD->isDeleted())
7169 // Explain why this defaulted function was deleted.
7170 DiagnoseDeletedDefaultedFunction(FD: MD);
7171 return;
7172 }
7173
7174 // A consteval function cannot override a non-consteval function and vice
7175 // versa.
7176 if (ReportOverrides(S&: *this,
7177 DiagID: MD->isConsteval() ? diag::err_consteval_override
7178 : diag::err_non_consteval_override,
7179 MD, Report: [&](const CXXMethodDecl *V) {
7180 return MD->isConsteval() != V->isConsteval();
7181 })) {
7182 if (MD->isDefaulted() && MD->isDeleted())
7183 // Explain why this defaulted function was deleted.
7184 DiagnoseDeletedDefaultedFunction(FD: MD);
7185 return;
7186 }
7187 };
7188
7189 auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool {
7190 if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted())
7191 return false;
7192
7193 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
7194 if (DFK.asComparison() == DefaultedComparisonKind::NotEqual ||
7195 DFK.asComparison() == DefaultedComparisonKind::Relational) {
7196 DefaultedSecondaryComparisons.push_back(Elt: FD);
7197 return true;
7198 }
7199
7200 CheckExplicitlyDefaultedFunction(S, MD: FD);
7201 return false;
7202 };
7203
7204 if (!Record->isInvalidDecl() &&
7205 Record->hasAttr<VTablePointerAuthenticationAttr>())
7206 checkIncorrectVTablePointerAuthenticationAttribute(RD&: *Record);
7207
7208 auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
7209 // Check whether the explicitly-defaulted members are valid.
7210 bool Incomplete = CheckForDefaultedFunction(M);
7211
7212 // Skip the rest of the checks for a member of a dependent class.
7213 if (Record->isDependentType())
7214 return;
7215
7216 // For an explicitly defaulted or deleted special member, we defer
7217 // determining triviality until the class is complete. That time is now!
7218 CXXSpecialMemberKind CSM = getSpecialMember(MD: M);
7219 if (!M->isImplicit() && !M->isUserProvided()) {
7220 if (CSM != CXXSpecialMemberKind::Invalid) {
7221 M->setTrivial(SpecialMemberIsTrivial(MD: M, CSM));
7222 // Inform the class that we've finished declaring this member.
7223 Record->finishedDefaultedOrDeletedMember(MD: M);
7224 M->setTrivialForCall(
7225 HasTrivialABI ||
7226 SpecialMemberIsTrivial(MD: M, CSM,
7227 TAH: TrivialABIHandling::ConsiderTrivialABI));
7228 Record->setTrivialForCallFlags(M);
7229 }
7230 }
7231
7232 // Set triviality for the purpose of calls if this is a user-provided
7233 // copy/move constructor or destructor.
7234 if ((CSM == CXXSpecialMemberKind::CopyConstructor ||
7235 CSM == CXXSpecialMemberKind::MoveConstructor ||
7236 CSM == CXXSpecialMemberKind::Destructor) &&
7237 M->isUserProvided()) {
7238 M->setTrivialForCall(HasTrivialABI);
7239 Record->setTrivialForCallFlags(M);
7240 }
7241
7242 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
7243 M->hasAttr<DLLExportAttr>()) {
7244 if (getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015) &&
7245 M->isTrivial() &&
7246 (CSM == CXXSpecialMemberKind::DefaultConstructor ||
7247 CSM == CXXSpecialMemberKind::CopyConstructor ||
7248 CSM == CXXSpecialMemberKind::Destructor))
7249 M->dropAttr<DLLExportAttr>();
7250
7251 if (M->hasAttr<DLLExportAttr>()) {
7252 // Define after any fields with in-class initializers have been parsed.
7253 DelayedDllExportMemberFunctions.push_back(Elt: M);
7254 }
7255 }
7256
7257 bool EffectivelyConstexprDestructor = true;
7258 // Avoid triggering vtable instantiation due to a dtor that is not
7259 // "effectively constexpr" for better compatibility.
7260 // See https://github.com/llvm/llvm-project/issues/102293 for more info.
7261 if (isa<CXXDestructorDecl>(Val: M)) {
7262 llvm::SmallDenseSet<QualType> Visited;
7263 auto Check = [&Visited](QualType T, auto &&Check) -> bool {
7264 if (!Visited.insert(V: T->getCanonicalTypeUnqualified()).second)
7265 return false;
7266 const CXXRecordDecl *RD =
7267 T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
7268 if (!RD || !RD->isCompleteDefinition())
7269 return true;
7270
7271 if (!RD->hasConstexprDestructor())
7272 return false;
7273
7274 for (const CXXBaseSpecifier &B : RD->bases())
7275 if (!Check(B.getType(), Check))
7276 return false;
7277 for (const FieldDecl *FD : RD->fields())
7278 if (!Check(FD->getType(), Check))
7279 return false;
7280 return true;
7281 };
7282 EffectivelyConstexprDestructor =
7283 Check(Context.getCanonicalTagType(TD: Record), Check);
7284 }
7285
7286 // Define defaulted constexpr virtual functions that override a base class
7287 // function right away.
7288 // FIXME: We can defer doing this until the vtable is marked as used.
7289 if (CSM != CXXSpecialMemberKind::Invalid && !M->isDeleted() &&
7290 M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods() &&
7291 EffectivelyConstexprDestructor)
7292 DefineDefaultedFunction(S&: *this, FD: M, DefaultLoc: M->getLocation());
7293
7294 if (!Incomplete)
7295 CheckCompletedMemberFunction(M);
7296 };
7297
7298 // Check the destructor before any other member function. We need to
7299 // determine whether it's trivial in order to determine whether the claas
7300 // type is a literal type, which is a prerequisite for determining whether
7301 // other special member functions are valid and whether they're implicitly
7302 // 'constexpr'.
7303 if (CXXDestructorDecl *Dtor = Record->getDestructor())
7304 CompleteMemberFunction(Dtor);
7305
7306 bool HasMethodWithOverrideControl = false,
7307 HasOverridingMethodWithoutOverrideControl = false;
7308 for (auto *D : Record->decls()) {
7309 if (auto *M = dyn_cast<CXXMethodDecl>(Val: D)) {
7310 // FIXME: We could do this check for dependent types with non-dependent
7311 // bases.
7312 if (!Record->isDependentType()) {
7313 // See if a method overloads virtual methods in a base
7314 // class without overriding any.
7315 if (!M->isStatic())
7316 DiagnoseHiddenVirtualMethods(MD: M);
7317
7318 if (M->hasAttr<OverrideAttr>()) {
7319 HasMethodWithOverrideControl = true;
7320 } else if (M->size_overridden_methods() > 0) {
7321 HasOverridingMethodWithoutOverrideControl = true;
7322 } else {
7323 // Warn on newly-declared virtual methods in `final` classes
7324 if (M->isVirtualAsWritten() && Record->isEffectivelyFinal()) {
7325 Diag(Loc: M->getLocation(), DiagID: diag::warn_unnecessary_virtual_specifier)
7326 << M;
7327 }
7328 }
7329 }
7330
7331 if (!isa<CXXDestructorDecl>(Val: M))
7332 CompleteMemberFunction(M);
7333 } else if (auto *F = dyn_cast<FriendDecl>(Val: D)) {
7334 CheckForDefaultedFunction(
7335 dyn_cast_or_null<FunctionDecl>(Val: F->getFriendDecl()));
7336 }
7337 }
7338
7339 if (HasOverridingMethodWithoutOverrideControl) {
7340 bool HasInconsistentOverrideControl = HasMethodWithOverrideControl;
7341 for (auto *M : Record->methods())
7342 DiagnoseAbsenceOfOverrideControl(D: M, Inconsistent: HasInconsistentOverrideControl);
7343 }
7344
7345 // Check the defaulted secondary comparisons after any other member functions.
7346 for (FunctionDecl *FD : DefaultedSecondaryComparisons) {
7347 CheckExplicitlyDefaultedFunction(S, MD: FD);
7348
7349 // If this is a member function, we deferred checking it until now.
7350 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: FD))
7351 CheckCompletedMemberFunction(MD);
7352 }
7353
7354 // {ms,gcc}_struct is a request to change ABI rules to either follow
7355 // Microsoft or Itanium C++ ABI. However, even if these attributes are
7356 // present, we do not layout classes following foreign ABI rules, but
7357 // instead enter a special "compatibility mode", which only changes
7358 // alignments of fundamental types and layout of bit fields.
7359 // Check whether this class uses any C++ features that are implemented
7360 // completely differently in the requested ABI, and if so, emit a
7361 // diagnostic. That diagnostic defaults to an error, but we allow
7362 // projects to map it down to a warning (or ignore it). It's a fairly
7363 // common practice among users of the ms_struct pragma to
7364 // mass-annotate headers, sweeping up a bunch of types that the
7365 // project doesn't really rely on MSVC-compatible layout for. We must
7366 // therefore support "ms_struct except for C++ stuff" as a secondary
7367 // ABI.
7368 // Don't emit this diagnostic if the feature was enabled as a
7369 // language option (as opposed to via a pragma or attribute), as
7370 // the option -mms-bitfields otherwise essentially makes it impossible
7371 // to build C++ code, unless this diagnostic is turned off.
7372 if (Context.getLangOpts().getLayoutCompatibility() ==
7373 LangOptions::LayoutCompatibilityKind::Default &&
7374 Record->isMsStruct(C: Context) != Context.defaultsToMsStruct() &&
7375 (Record->isPolymorphic() || Record->getNumBases())) {
7376 Diag(Loc: Record->getLocation(), DiagID: diag::warn_cxx_ms_struct);
7377 }
7378
7379 checkClassLevelDLLAttribute(Class: Record);
7380 checkClassLevelCodeSegAttribute(Class: Record);
7381
7382 bool ClangABICompat4 =
7383 Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
7384 TargetInfo::CallingConvKind CCK =
7385 Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
7386 bool CanPass = canPassInRegisters(S&: *this, D: Record, CCK);
7387
7388 // Do not change ArgPassingRestrictions if it has already been set to
7389 // RecordArgPassingKind::CanNeverPassInRegs.
7390 if (Record->getArgPassingRestrictions() !=
7391 RecordArgPassingKind::CanNeverPassInRegs)
7392 Record->setArgPassingRestrictions(
7393 CanPass ? RecordArgPassingKind::CanPassInRegs
7394 : RecordArgPassingKind::CannotPassInRegs);
7395
7396 // If canPassInRegisters returns true despite the record having a non-trivial
7397 // destructor, the record is destructed in the callee. This happens only when
7398 // the record or one of its subobjects has a field annotated with trivial_abi
7399 // or a field qualified with ObjC __strong/__weak.
7400 if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
7401 Record->setParamDestroyedInCallee(true);
7402 else if (Record->hasNonTrivialDestructor())
7403 Record->setParamDestroyedInCallee(CanPass);
7404
7405 if (getLangOpts().ForceEmitVTables) {
7406 // If we want to emit all the vtables, we need to mark it as used. This
7407 // is especially required for cases like vtable assumption loads.
7408 MarkVTableUsed(Loc: Record->getInnerLocStart(), Class: Record);
7409 }
7410
7411 if (getLangOpts().CUDA) {
7412 if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>())
7413 checkCUDADeviceBuiltinSurfaceClassTemplate(S&: *this, Class: Record);
7414 else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>())
7415 checkCUDADeviceBuiltinTextureClassTemplate(S&: *this, Class: Record);
7416 }
7417
7418 llvm::SmallDenseMap<OverloadedOperatorKind,
7419 llvm::SmallVector<const FunctionDecl *, 2>, 4>
7420 TypeAwareDecls{{OO_New, {}},
7421 {OO_Array_New, {}},
7422 {OO_Delete, {}},
7423 {OO_Array_New, {}}};
7424 for (auto *D : Record->decls()) {
7425 const FunctionDecl *FnDecl = D->getAsFunction();
7426 if (!FnDecl || !FnDecl->isTypeAwareOperatorNewOrDelete())
7427 continue;
7428 assert(FnDecl->getDeclName().isAnyOperatorNewOrDelete());
7429 TypeAwareDecls[FnDecl->getOverloadedOperator()].push_back(Elt: FnDecl);
7430 }
7431 auto CheckMismatchedTypeAwareAllocators =
7432 [this, &TypeAwareDecls, Record](OverloadedOperatorKind NewKind,
7433 OverloadedOperatorKind DeleteKind) {
7434 auto &NewDecls = TypeAwareDecls[NewKind];
7435 auto &DeleteDecls = TypeAwareDecls[DeleteKind];
7436 if (NewDecls.empty() == DeleteDecls.empty())
7437 return;
7438 DeclarationName FoundOperator =
7439 Context.DeclarationNames.getCXXOperatorName(
7440 Op: NewDecls.empty() ? DeleteKind : NewKind);
7441 DeclarationName MissingOperator =
7442 Context.DeclarationNames.getCXXOperatorName(
7443 Op: NewDecls.empty() ? NewKind : DeleteKind);
7444 Diag(Loc: Record->getLocation(),
7445 DiagID: diag::err_type_aware_allocator_missing_matching_operator)
7446 << FoundOperator << Context.getCanonicalTagType(TD: Record)
7447 << MissingOperator;
7448 for (auto MD : NewDecls)
7449 Diag(Loc: MD->getLocation(),
7450 DiagID: diag::note_unmatched_type_aware_allocator_declared)
7451 << MD;
7452 for (auto MD : DeleteDecls)
7453 Diag(Loc: MD->getLocation(),
7454 DiagID: diag::note_unmatched_type_aware_allocator_declared)
7455 << MD;
7456 };
7457 CheckMismatchedTypeAwareAllocators(OO_New, OO_Delete);
7458 CheckMismatchedTypeAwareAllocators(OO_Array_New, OO_Array_Delete);
7459}
7460
7461/// Look up the special member function that would be called by a special
7462/// member function for a subobject of class type.
7463///
7464/// \param Class The class type of the subobject.
7465/// \param CSM The kind of special member function.
7466/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
7467/// \param ConstRHS True if this is a copy operation with a const object
7468/// on its RHS, that is, if the argument to the outer special member
7469/// function is 'const' and this is not a field marked 'mutable'.
7470static Sema::SpecialMemberOverloadResult
7471lookupCallFromSpecialMember(Sema &S, CXXRecordDecl *Class,
7472 CXXSpecialMemberKind CSM, unsigned FieldQuals,
7473 bool ConstRHS) {
7474 unsigned LHSQuals = 0;
7475 if (CSM == CXXSpecialMemberKind::CopyAssignment ||
7476 CSM == CXXSpecialMemberKind::MoveAssignment)
7477 LHSQuals = FieldQuals;
7478
7479 unsigned RHSQuals = FieldQuals;
7480 if (CSM == CXXSpecialMemberKind::DefaultConstructor ||
7481 CSM == CXXSpecialMemberKind::Destructor)
7482 RHSQuals = 0;
7483 else if (ConstRHS)
7484 RHSQuals |= Qualifiers::Const;
7485
7486 return S.LookupSpecialMember(D: Class, SM: CSM,
7487 ConstArg: RHSQuals & Qualifiers::Const,
7488 VolatileArg: RHSQuals & Qualifiers::Volatile,
7489 RValueThis: false,
7490 ConstThis: LHSQuals & Qualifiers::Const,
7491 VolatileThis: LHSQuals & Qualifiers::Volatile);
7492}
7493
7494class Sema::InheritedConstructorInfo {
7495 Sema &S;
7496 SourceLocation UseLoc;
7497
7498 /// A mapping from the base classes through which the constructor was
7499 /// inherited to the using shadow declaration in that base class (or a null
7500 /// pointer if the constructor was declared in that base class).
7501 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
7502 InheritedFromBases;
7503
7504public:
7505 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
7506 ConstructorUsingShadowDecl *Shadow)
7507 : S(S), UseLoc(UseLoc) {
7508 bool DiagnosedMultipleConstructedBases = false;
7509 CXXRecordDecl *ConstructedBase = nullptr;
7510 BaseUsingDecl *ConstructedBaseIntroducer = nullptr;
7511
7512 // Find the set of such base class subobjects and check that there's a
7513 // unique constructed subobject.
7514 for (auto *D : Shadow->redecls()) {
7515 auto *DShadow = cast<ConstructorUsingShadowDecl>(Val: D);
7516 auto *DNominatedBase = DShadow->getNominatedBaseClass();
7517 auto *DConstructedBase = DShadow->getConstructedBaseClass();
7518
7519 InheritedFromBases.insert(
7520 KV: std::make_pair(x: DNominatedBase->getCanonicalDecl(),
7521 y: DShadow->getNominatedBaseClassShadowDecl()));
7522 if (DShadow->constructsVirtualBase())
7523 InheritedFromBases.insert(
7524 KV: std::make_pair(x: DConstructedBase->getCanonicalDecl(),
7525 y: DShadow->getConstructedBaseClassShadowDecl()));
7526 else
7527 assert(DNominatedBase == DConstructedBase);
7528
7529 // [class.inhctor.init]p2:
7530 // If the constructor was inherited from multiple base class subobjects
7531 // of type B, the program is ill-formed.
7532 if (!ConstructedBase) {
7533 ConstructedBase = DConstructedBase;
7534 ConstructedBaseIntroducer = D->getIntroducer();
7535 } else if (ConstructedBase != DConstructedBase &&
7536 !Shadow->isInvalidDecl()) {
7537 if (!DiagnosedMultipleConstructedBases) {
7538 S.Diag(Loc: UseLoc, DiagID: diag::err_ambiguous_inherited_constructor)
7539 << Shadow->getTargetDecl();
7540 S.Diag(Loc: ConstructedBaseIntroducer->getLocation(),
7541 DiagID: diag::note_ambiguous_inherited_constructor_using)
7542 << ConstructedBase;
7543 DiagnosedMultipleConstructedBases = true;
7544 }
7545 S.Diag(Loc: D->getIntroducer()->getLocation(),
7546 DiagID: diag::note_ambiguous_inherited_constructor_using)
7547 << DConstructedBase;
7548 }
7549 }
7550
7551 if (DiagnosedMultipleConstructedBases)
7552 Shadow->setInvalidDecl();
7553 }
7554
7555 /// Find the constructor to use for inherited construction of a base class,
7556 /// and whether that base class constructor inherits the constructor from a
7557 /// virtual base class (in which case it won't actually invoke it).
7558 std::pair<CXXConstructorDecl *, bool>
7559 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
7560 auto It = InheritedFromBases.find(Val: Base->getCanonicalDecl());
7561 if (It == InheritedFromBases.end())
7562 return std::make_pair(x: nullptr, y: false);
7563
7564 // This is an intermediary class.
7565 if (It->second)
7566 return std::make_pair(
7567 x: S.findInheritingConstructor(Loc: UseLoc, BaseCtor: Ctor, DerivedShadow: It->second),
7568 y: It->second->constructsVirtualBase());
7569
7570 // This is the base class from which the constructor was inherited.
7571 return std::make_pair(x&: Ctor, y: false);
7572 }
7573};
7574
7575/// Is the special member function which would be selected to perform the
7576/// specified operation on the specified class type a constexpr constructor?
7577static bool specialMemberIsConstexpr(
7578 Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, unsigned Quals,
7579 bool ConstRHS, CXXConstructorDecl *InheritedCtor = nullptr,
7580 Sema::InheritedConstructorInfo *Inherited = nullptr) {
7581 // Suppress duplicate constraint checking here, in case a constraint check
7582 // caused us to decide to do this. Any truely recursive checks will get
7583 // caught during these checks anyway.
7584 Sema::SatisfactionStackResetRAII SSRAII{S};
7585
7586 // If we're inheriting a constructor, see if we need to call it for this base
7587 // class.
7588 if (InheritedCtor) {
7589 assert(CSM == CXXSpecialMemberKind::DefaultConstructor);
7590 auto BaseCtor =
7591 Inherited->findConstructorForBase(Base: ClassDecl, Ctor: InheritedCtor).first;
7592 if (BaseCtor)
7593 return BaseCtor->isConstexpr();
7594 }
7595
7596 if (CSM == CXXSpecialMemberKind::DefaultConstructor)
7597 return ClassDecl->hasConstexprDefaultConstructor();
7598 if (CSM == CXXSpecialMemberKind::Destructor)
7599 return ClassDecl->hasConstexprDestructor();
7600
7601 Sema::SpecialMemberOverloadResult SMOR =
7602 lookupCallFromSpecialMember(S, Class: ClassDecl, CSM, FieldQuals: Quals, ConstRHS);
7603 if (!SMOR.getMethod())
7604 // A constructor we wouldn't select can't be "involved in initializing"
7605 // anything.
7606 return true;
7607 return SMOR.getMethod()->isConstexpr();
7608}
7609
7610/// Determine whether the specified special member function would be constexpr
7611/// if it were implicitly defined.
7612static bool defaultedSpecialMemberIsConstexpr(
7613 Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, bool ConstArg,
7614 CXXConstructorDecl *InheritedCtor = nullptr,
7615 Sema::InheritedConstructorInfo *Inherited = nullptr) {
7616 if (!S.getLangOpts().CPlusPlus11)
7617 return false;
7618
7619 // C++11 [dcl.constexpr]p4:
7620 // In the definition of a constexpr constructor [...]
7621 bool Ctor = true;
7622 switch (CSM) {
7623 case CXXSpecialMemberKind::DefaultConstructor:
7624 if (Inherited)
7625 break;
7626 // Since default constructor lookup is essentially trivial (and cannot
7627 // involve, for instance, template instantiation), we compute whether a
7628 // defaulted default constructor is constexpr directly within CXXRecordDecl.
7629 //
7630 // This is important for performance; we need to know whether the default
7631 // constructor is constexpr to determine whether the type is a literal type.
7632 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
7633
7634 case CXXSpecialMemberKind::CopyConstructor:
7635 case CXXSpecialMemberKind::MoveConstructor:
7636 // For copy or move constructors, we need to perform overload resolution.
7637 break;
7638
7639 case CXXSpecialMemberKind::CopyAssignment:
7640 case CXXSpecialMemberKind::MoveAssignment:
7641 if (!S.getLangOpts().CPlusPlus14)
7642 return false;
7643 // In C++1y, we need to perform overload resolution.
7644 Ctor = false;
7645 break;
7646
7647 case CXXSpecialMemberKind::Destructor:
7648 return ClassDecl->defaultedDestructorIsConstexpr();
7649
7650 case CXXSpecialMemberKind::Invalid:
7651 return false;
7652 }
7653
7654 // -- if the class is a non-empty union, or for each non-empty anonymous
7655 // union member of a non-union class, exactly one non-static data member
7656 // shall be initialized; [DR1359]
7657 //
7658 // If we squint, this is guaranteed, since exactly one non-static data member
7659 // will be initialized (if the constructor isn't deleted), we just don't know
7660 // which one.
7661 if (Ctor && ClassDecl->isUnion())
7662 return CSM == CXXSpecialMemberKind::DefaultConstructor
7663 ? ClassDecl->hasInClassInitializer() ||
7664 !ClassDecl->hasVariantMembers()
7665 : true;
7666
7667 // -- the class shall not have any virtual base classes;
7668 if (Ctor && ClassDecl->getNumVBases())
7669 return false;
7670
7671 // C++1y [class.copy]p26:
7672 // -- [the class] is a literal type, and
7673 if (!Ctor && !ClassDecl->isLiteral() && !S.getLangOpts().CPlusPlus23)
7674 return false;
7675
7676 // -- every constructor involved in initializing [...] base class
7677 // sub-objects shall be a constexpr constructor;
7678 // -- the assignment operator selected to copy/move each direct base
7679 // class is a constexpr function, and
7680 if (!S.getLangOpts().CPlusPlus23) {
7681 for (const auto &B : ClassDecl->bases()) {
7682 auto *BaseClassDecl = B.getType()->getAsCXXRecordDecl();
7683 if (!BaseClassDecl)
7684 continue;
7685 if (!specialMemberIsConstexpr(S, ClassDecl: BaseClassDecl, CSM, Quals: 0, ConstRHS: ConstArg,
7686 InheritedCtor, Inherited))
7687 return false;
7688 }
7689 }
7690
7691 // -- every constructor involved in initializing non-static data members
7692 // [...] shall be a constexpr constructor;
7693 // -- every non-static data member and base class sub-object shall be
7694 // initialized
7695 // -- for each non-static data member of X that is of class type (or array
7696 // thereof), the assignment operator selected to copy/move that member is
7697 // a constexpr function
7698 if (!S.getLangOpts().CPlusPlus23) {
7699 for (const auto *F : ClassDecl->fields()) {
7700 if (F->isInvalidDecl())
7701 continue;
7702 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
7703 F->hasInClassInitializer())
7704 continue;
7705 QualType BaseType = S.Context.getBaseElementType(QT: F->getType());
7706 if (const RecordType *RecordTy = BaseType->getAsCanonical<RecordType>()) {
7707 auto *FieldRecDecl =
7708 cast<CXXRecordDecl>(Val: RecordTy->getDecl())->getDefinitionOrSelf();
7709 if (!specialMemberIsConstexpr(S, ClassDecl: FieldRecDecl, CSM,
7710 Quals: BaseType.getCVRQualifiers(),
7711 ConstRHS: ConstArg && !F->isMutable()))
7712 return false;
7713 } else if (CSM == CXXSpecialMemberKind::DefaultConstructor) {
7714 return false;
7715 }
7716 }
7717 }
7718
7719 // All OK, it's constexpr!
7720 return true;
7721}
7722
7723namespace {
7724/// RAII object to register a defaulted function as having its exception
7725/// specification computed.
7726struct ComputingExceptionSpec {
7727 Sema &S;
7728
7729 ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc)
7730 : S(S) {
7731 Sema::CodeSynthesisContext Ctx;
7732 Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;
7733 Ctx.PointOfInstantiation = Loc;
7734 Ctx.Entity = FD;
7735 S.pushCodeSynthesisContext(Ctx);
7736 }
7737 ~ComputingExceptionSpec() {
7738 S.popCodeSynthesisContext();
7739 }
7740};
7741}
7742
7743static Sema::ImplicitExceptionSpecification
7744ComputeDefaultedSpecialMemberExceptionSpec(Sema &S, SourceLocation Loc,
7745 CXXMethodDecl *MD,
7746 CXXSpecialMemberKind CSM,
7747 Sema::InheritedConstructorInfo *ICI);
7748
7749static Sema::ImplicitExceptionSpecification
7750ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
7751 FunctionDecl *FD,
7752 Sema::DefaultedComparisonKind DCK);
7753
7754static Sema::ImplicitExceptionSpecification
7755computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD) {
7756 auto DFK = S.getDefaultedFunctionKind(FD);
7757 if (DFK.isSpecialMember())
7758 return ComputeDefaultedSpecialMemberExceptionSpec(
7759 S, Loc, MD: cast<CXXMethodDecl>(Val: FD), CSM: DFK.asSpecialMember(), ICI: nullptr);
7760 if (DFK.isComparison())
7761 return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD,
7762 DCK: DFK.asComparison());
7763
7764 auto *CD = cast<CXXConstructorDecl>(Val: FD);
7765 assert(CD->getInheritedConstructor() &&
7766 "only defaulted functions and inherited constructors have implicit "
7767 "exception specs");
7768 Sema::InheritedConstructorInfo ICI(
7769 S, Loc, CD->getInheritedConstructor().getShadowDecl());
7770 return ComputeDefaultedSpecialMemberExceptionSpec(
7771 S, Loc, MD: CD, CSM: CXXSpecialMemberKind::DefaultConstructor, ICI: &ICI);
7772}
7773
7774static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
7775 CXXMethodDecl *MD) {
7776 FunctionProtoType::ExtProtoInfo EPI;
7777
7778 // Build an exception specification pointing back at this member.
7779 EPI.ExceptionSpec.Type = EST_Unevaluated;
7780 EPI.ExceptionSpec.SourceDecl = MD;
7781
7782 // Set the calling convention to the default for C++ instance methods.
7783 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
7784 cc: S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
7785 /*IsCXXMethod=*/true));
7786 return EPI;
7787}
7788
7789void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD) {
7790 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
7791 if (FPT->getExceptionSpecType() != EST_Unevaluated)
7792 return;
7793
7794 // Evaluate the exception specification.
7795 auto IES = computeImplicitExceptionSpec(S&: *this, Loc, FD);
7796 auto ESI = IES.getExceptionSpec();
7797
7798 // Update the type of the special member to use it.
7799 UpdateExceptionSpec(FD, ESI);
7800}
7801
7802void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) {
7803 assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted");
7804
7805 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
7806 if (!DefKind) {
7807 assert(FD->getDeclContext()->isDependentContext());
7808 return;
7809 }
7810
7811 if (DefKind.isComparison()) {
7812 auto PT = FD->getParamDecl(i: 0)->getType();
7813 if (const CXXRecordDecl *RD =
7814 PT.getNonReferenceType()->getAsCXXRecordDecl()) {
7815 for (FieldDecl *Field : RD->fields()) {
7816 UnusedPrivateFields.remove(X: Field);
7817 }
7818 }
7819 }
7820
7821 if (DefKind.isSpecialMember()
7822 ? CheckExplicitlyDefaultedSpecialMember(MD: cast<CXXMethodDecl>(Val: FD),
7823 CSM: DefKind.asSpecialMember(),
7824 DefaultLoc: FD->getDefaultLoc())
7825 : CheckExplicitlyDefaultedComparison(S, MD: FD, DCK: DefKind.asComparison()))
7826 FD->setInvalidDecl();
7827}
7828
7829bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
7830 CXXSpecialMemberKind CSM,
7831 SourceLocation DefaultLoc) {
7832 CXXRecordDecl *RD = MD->getParent();
7833
7834 assert(MD->isExplicitlyDefaulted() && CSM != CXXSpecialMemberKind::Invalid &&
7835 "not an explicitly-defaulted special member");
7836
7837 // Defer all checking for special members of a dependent type.
7838 if (RD->isDependentType())
7839 return false;
7840
7841 // Whether this was the first-declared instance of the constructor.
7842 // This affects whether we implicitly add an exception spec and constexpr.
7843 bool First = MD == MD->getCanonicalDecl();
7844
7845 bool HadError = false;
7846
7847 // C++11 [dcl.fct.def.default]p1:
7848 // A function that is explicitly defaulted shall
7849 // -- be a special member function [...] (checked elsewhere),
7850 // -- have the same type (except for ref-qualifiers, and except that a
7851 // copy operation can take a non-const reference) as an implicit
7852 // declaration, and
7853 // -- not have default arguments.
7854 // C++2a changes the second bullet to instead delete the function if it's
7855 // defaulted on its first declaration, unless it's "an assignment operator,
7856 // and its return type differs or its parameter type is not a reference".
7857 bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First;
7858 bool ShouldDeleteForTypeMismatch = false;
7859 unsigned ExpectedParams = 1;
7860 if (CSM == CXXSpecialMemberKind::DefaultConstructor ||
7861 CSM == CXXSpecialMemberKind::Destructor)
7862 ExpectedParams = 0;
7863 if (MD->getNumExplicitParams() != ExpectedParams) {
7864 // This checks for default arguments: a copy or move constructor with a
7865 // default argument is classified as a default constructor, and assignment
7866 // operations and destructors can't have default arguments.
7867 Diag(Loc: MD->getLocation(), DiagID: diag::err_defaulted_special_member_params)
7868 << CSM << MD->getSourceRange();
7869 HadError = true;
7870 } else if (MD->isVariadic()) {
7871 if (DeleteOnTypeMismatch)
7872 ShouldDeleteForTypeMismatch = true;
7873 else {
7874 Diag(Loc: MD->getLocation(), DiagID: diag::err_defaulted_special_member_variadic)
7875 << CSM << MD->getSourceRange();
7876 HadError = true;
7877 }
7878 }
7879
7880 const FunctionProtoType *Type = MD->getType()->castAs<FunctionProtoType>();
7881
7882 bool CanHaveConstParam = false;
7883 if (CSM == CXXSpecialMemberKind::CopyConstructor)
7884 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
7885 else if (CSM == CXXSpecialMemberKind::CopyAssignment)
7886 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
7887
7888 QualType ReturnType = Context.VoidTy;
7889 if (CSM == CXXSpecialMemberKind::CopyAssignment ||
7890 CSM == CXXSpecialMemberKind::MoveAssignment) {
7891 // Check for return type matching.
7892 ReturnType = Type->getReturnType();
7893 QualType ThisType = MD->getFunctionObjectParameterType();
7894
7895 QualType DeclType =
7896 Context.getTagType(Keyword: ElaboratedTypeKeyword::None,
7897 /*Qualifier=*/std::nullopt, TD: RD, /*OwnsTag=*/false);
7898 DeclType = Context.getAddrSpaceQualType(
7899 T: DeclType, AddressSpace: ThisType.getQualifiers().getAddressSpace());
7900 QualType ExpectedReturnType = Context.getLValueReferenceType(T: DeclType);
7901
7902 if (!Context.hasSameType(T1: ReturnType, T2: ExpectedReturnType)) {
7903 Diag(Loc: MD->getLocation(), DiagID: diag::err_defaulted_special_member_return_type)
7904 << (CSM == CXXSpecialMemberKind::MoveAssignment)
7905 << ExpectedReturnType;
7906 HadError = true;
7907 }
7908
7909 // A defaulted special member cannot have cv-qualifiers.
7910 if (ThisType.isConstQualified() || ThisType.isVolatileQualified()) {
7911 if (DeleteOnTypeMismatch)
7912 ShouldDeleteForTypeMismatch = true;
7913 else {
7914 Diag(Loc: MD->getLocation(), DiagID: diag::err_defaulted_special_member_quals)
7915 << (CSM == CXXSpecialMemberKind::MoveAssignment)
7916 << getLangOpts().CPlusPlus14;
7917 HadError = true;
7918 }
7919 }
7920 // [C++23][dcl.fct.def.default]/p2.2
7921 // if F2 has an implicit object parameter of type “reference to C”,
7922 // F1 may be an explicit object member function whose explicit object
7923 // parameter is of (possibly different) type “reference to C”,
7924 // in which case the type of F1 would differ from the type of F2
7925 // in that the type of F1 has an additional parameter;
7926 QualType ExplicitObjectParameter = MD->isExplicitObjectMemberFunction()
7927 ? MD->getParamDecl(i: 0)->getType()
7928 : QualType();
7929 if (!ExplicitObjectParameter.isNull() &&
7930 (!ExplicitObjectParameter->isReferenceType() ||
7931 !Context.hasSameType(T1: ExplicitObjectParameter.getNonReferenceType(),
7932 T2: Context.getCanonicalTagType(TD: RD)))) {
7933 if (DeleteOnTypeMismatch)
7934 ShouldDeleteForTypeMismatch = true;
7935 else {
7936 Diag(Loc: MD->getLocation(),
7937 DiagID: diag::err_defaulted_special_member_explicit_object_mismatch)
7938 << (CSM == CXXSpecialMemberKind::MoveAssignment) << RD
7939 << MD->getSourceRange();
7940 HadError = true;
7941 }
7942 }
7943 }
7944
7945 // Check for parameter type matching.
7946 QualType ArgType =
7947 ExpectedParams
7948 ? Type->getParamType(i: MD->isExplicitObjectMemberFunction() ? 1 : 0)
7949 : QualType();
7950 bool HasConstParam = false;
7951 if (ExpectedParams && ArgType->isReferenceType()) {
7952 // Argument must be reference to possibly-const T.
7953 QualType ReferentType = ArgType->getPointeeType();
7954 HasConstParam = ReferentType.isConstQualified();
7955
7956 if (ReferentType.isVolatileQualified()) {
7957 if (DeleteOnTypeMismatch)
7958 ShouldDeleteForTypeMismatch = true;
7959 else {
7960 Diag(Loc: MD->getLocation(),
7961 DiagID: diag::err_defaulted_special_member_volatile_param)
7962 << CSM;
7963 HadError = true;
7964 }
7965 }
7966
7967 if (HasConstParam && !CanHaveConstParam) {
7968 if (DeleteOnTypeMismatch)
7969 ShouldDeleteForTypeMismatch = true;
7970 else if (CSM == CXXSpecialMemberKind::CopyConstructor ||
7971 CSM == CXXSpecialMemberKind::CopyAssignment) {
7972 Diag(Loc: MD->getLocation(),
7973 DiagID: diag::err_defaulted_special_member_copy_const_param)
7974 << (CSM == CXXSpecialMemberKind::CopyAssignment);
7975 // FIXME: Explain why this special member can't be const.
7976 HadError = true;
7977 } else {
7978 Diag(Loc: MD->getLocation(),
7979 DiagID: diag::err_defaulted_special_member_move_const_param)
7980 << (CSM == CXXSpecialMemberKind::MoveAssignment);
7981 HadError = true;
7982 }
7983 }
7984 } else if (ExpectedParams) {
7985 // A copy assignment operator can take its argument by value, but a
7986 // defaulted one cannot.
7987 assert(CSM == CXXSpecialMemberKind::CopyAssignment &&
7988 "unexpected non-ref argument");
7989 Diag(Loc: MD->getLocation(), DiagID: diag::err_defaulted_copy_assign_not_ref);
7990 HadError = true;
7991 }
7992
7993 // C++11 [dcl.fct.def.default]p2:
7994 // An explicitly-defaulted function may be declared constexpr only if it
7995 // would have been implicitly declared as constexpr,
7996 // Do not apply this rule to members of class templates, since core issue 1358
7997 // makes such functions always instantiate to constexpr functions. For
7998 // functions which cannot be constexpr (for non-constructors in C++11 and for
7999 // destructors in C++14 and C++17), this is checked elsewhere.
8000 //
8001 // FIXME: This should not apply if the member is deleted.
8002 bool Constexpr = defaultedSpecialMemberIsConstexpr(S&: *this, ClassDecl: RD, CSM,
8003 ConstArg: HasConstParam);
8004
8005 // C++14 [dcl.constexpr]p6 (CWG DR647/CWG DR1358):
8006 // If the instantiated template specialization of a constexpr function
8007 // template or member function of a class template would fail to satisfy
8008 // the requirements for a constexpr function or constexpr constructor, that
8009 // specialization is still a constexpr function or constexpr constructor,
8010 // even though a call to such a function cannot appear in a constant
8011 // expression.
8012 if (MD->isTemplateInstantiation() && MD->isConstexpr())
8013 Constexpr = true;
8014
8015 if ((getLangOpts().CPlusPlus20 ||
8016 (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(Val: MD)
8017 : isa<CXXConstructorDecl>(Val: MD))) &&
8018 MD->isConstexpr() && !Constexpr &&
8019 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
8020 if (!MD->isConsteval() && RD->getNumVBases()) {
8021 Diag(Loc: MD->getBeginLoc(),
8022 DiagID: diag::err_incorrect_defaulted_constexpr_with_vb)
8023 << CSM;
8024 for (const auto &I : RD->vbases())
8025 Diag(Loc: I.getBeginLoc(), DiagID: diag::note_constexpr_virtual_base_here);
8026 } else {
8027 Diag(Loc: MD->getBeginLoc(), DiagID: diag::err_incorrect_defaulted_constexpr)
8028 << CSM << MD->isConsteval();
8029 }
8030 HadError = true;
8031 // FIXME: Explain why the special member can't be constexpr.
8032 }
8033
8034 if (First) {
8035 // C++2a [dcl.fct.def.default]p3:
8036 // If a function is explicitly defaulted on its first declaration, it is
8037 // implicitly considered to be constexpr if the implicit declaration
8038 // would be.
8039 MD->setConstexprKind(Constexpr ? (MD->isConsteval()
8040 ? ConstexprSpecKind::Consteval
8041 : ConstexprSpecKind::Constexpr)
8042 : ConstexprSpecKind::Unspecified);
8043
8044 if (!Type->hasExceptionSpec()) {
8045 // C++2a [except.spec]p3:
8046 // If a declaration of a function does not have a noexcept-specifier
8047 // [and] is defaulted on its first declaration, [...] the exception
8048 // specification is as specified below
8049 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
8050 EPI.ExceptionSpec.Type = EST_Unevaluated;
8051 EPI.ExceptionSpec.SourceDecl = MD;
8052 MD->setType(
8053 Context.getFunctionType(ResultTy: ReturnType, Args: Type->getParamTypes(), EPI));
8054 }
8055 }
8056
8057 if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
8058 if (First) {
8059 SetDeclDeleted(dcl: MD, DelLoc: MD->getLocation());
8060 if (!inTemplateInstantiation() && !HadError) {
8061 Diag(Loc: MD->getLocation(), DiagID: diag::warn_defaulted_method_deleted) << CSM;
8062 if (ShouldDeleteForTypeMismatch) {
8063 Diag(Loc: MD->getLocation(), DiagID: diag::note_deleted_type_mismatch) << CSM;
8064 } else if (ShouldDeleteSpecialMember(MD, CSM, ICI: nullptr,
8065 /*Diagnose*/ true) &&
8066 DefaultLoc.isValid()) {
8067 Diag(Loc: DefaultLoc, DiagID: diag::note_replace_equals_default_to_delete)
8068 << FixItHint::CreateReplacement(RemoveRange: DefaultLoc, Code: "delete");
8069 }
8070 }
8071 if (ShouldDeleteForTypeMismatch && !HadError) {
8072 Diag(Loc: MD->getLocation(),
8073 DiagID: diag::warn_cxx17_compat_defaulted_method_type_mismatch)
8074 << CSM;
8075 }
8076 } else {
8077 // C++11 [dcl.fct.def.default]p4:
8078 // [For a] user-provided explicitly-defaulted function [...] if such a
8079 // function is implicitly defined as deleted, the program is ill-formed.
8080 Diag(Loc: MD->getLocation(), DiagID: diag::err_out_of_line_default_deletes) << CSM;
8081 assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
8082 ShouldDeleteSpecialMember(MD, CSM, ICI: nullptr, /*Diagnose*/true);
8083 HadError = true;
8084 }
8085 }
8086
8087 return HadError;
8088}
8089
8090namespace {
8091/// Helper class for building and checking a defaulted comparison.
8092///
8093/// Defaulted functions are built in two phases:
8094///
8095/// * First, the set of operations that the function will perform are
8096/// identified, and some of them are checked. If any of the checked
8097/// operations is invalid in certain ways, the comparison function is
8098/// defined as deleted and no body is built.
8099/// * Then, if the function is not defined as deleted, the body is built.
8100///
8101/// This is accomplished by performing two visitation steps over the eventual
8102/// body of the function.
8103template<typename Derived, typename ResultList, typename Result,
8104 typename Subobject>
8105class DefaultedComparisonVisitor {
8106public:
8107 using DefaultedComparisonKind = Sema::DefaultedComparisonKind;
8108
8109 DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8110 DefaultedComparisonKind DCK)
8111 : S(S), RD(RD), FD(FD), DCK(DCK) {
8112 if (auto *Info = FD->getDefaultedOrDeletedInfo()) {
8113 // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an
8114 // UnresolvedSet to avoid this copy.
8115 Fns.assign(I: Info->getUnqualifiedLookups().begin(),
8116 E: Info->getUnqualifiedLookups().end());
8117 }
8118 }
8119
8120 ResultList visit() {
8121 // The type of an lvalue naming a parameter of this function.
8122 QualType ParamLvalType =
8123 FD->getParamDecl(i: 0)->getType().getNonReferenceType();
8124
8125 ResultList Results;
8126
8127 switch (DCK) {
8128 case DefaultedComparisonKind::None:
8129 llvm_unreachable("not a defaulted comparison");
8130
8131 case DefaultedComparisonKind::Equal:
8132 case DefaultedComparisonKind::ThreeWay:
8133 getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers());
8134 return Results;
8135
8136 case DefaultedComparisonKind::NotEqual:
8137 case DefaultedComparisonKind::Relational:
8138 Results.add(getDerived().visitExpandedSubobject(
8139 ParamLvalType, getDerived().getCompleteObject()));
8140 return Results;
8141 }
8142 llvm_unreachable("");
8143 }
8144
8145protected:
8146 Derived &getDerived() { return static_cast<Derived&>(*this); }
8147
8148 /// Visit the expanded list of subobjects of the given type, as specified in
8149 /// C++2a [class.compare.default].
8150 ///
8151 /// \return \c true if the ResultList object said we're done, \c false if not.
8152 bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record,
8153 Qualifiers Quals) {
8154 // C++2a [class.compare.default]p4:
8155 // The direct base class subobjects of C
8156 for (CXXBaseSpecifier &Base : Record->bases())
8157 if (Results.add(getDerived().visitSubobject(
8158 S.Context.getQualifiedType(T: Base.getType(), Qs: Quals),
8159 getDerived().getBase(&Base))))
8160 return true;
8161
8162 // followed by the non-static data members of C
8163 for (FieldDecl *Field : Record->fields()) {
8164 // C++23 [class.bit]p2:
8165 // Unnamed bit-fields are not members ...
8166 if (Field->isUnnamedBitField())
8167 continue;
8168 // Recursively expand anonymous structs.
8169 if (Field->isAnonymousStructOrUnion()) {
8170 if (visitSubobjects(Results, Record: Field->getType()->getAsCXXRecordDecl(),
8171 Quals))
8172 return true;
8173 continue;
8174 }
8175
8176 // Figure out the type of an lvalue denoting this field.
8177 Qualifiers FieldQuals = Quals;
8178 if (Field->isMutable())
8179 FieldQuals.removeConst();
8180 QualType FieldType =
8181 S.Context.getQualifiedType(T: Field->getType(), Qs: FieldQuals);
8182
8183 if (Results.add(getDerived().visitSubobject(
8184 FieldType, getDerived().getField(Field))))
8185 return true;
8186 }
8187
8188 // form a list of subobjects.
8189 return false;
8190 }
8191
8192 Result visitSubobject(QualType Type, Subobject Subobj) {
8193 // In that list, any subobject of array type is recursively expanded
8194 const ArrayType *AT = S.Context.getAsArrayType(T: Type);
8195 if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(Val: AT))
8196 return getDerived().visitSubobjectArray(CAT->getElementType(),
8197 CAT->getSize(), Subobj);
8198 return getDerived().visitExpandedSubobject(Type, Subobj);
8199 }
8200
8201 Result visitSubobjectArray(QualType Type, const llvm::APInt &Size,
8202 Subobject Subobj) {
8203 return getDerived().visitSubobject(Type, Subobj);
8204 }
8205
8206protected:
8207 Sema &S;
8208 CXXRecordDecl *RD;
8209 FunctionDecl *FD;
8210 DefaultedComparisonKind DCK;
8211 UnresolvedSet<16> Fns;
8212};
8213
8214/// Information about a defaulted comparison, as determined by
8215/// DefaultedComparisonAnalyzer.
8216struct DefaultedComparisonInfo {
8217 bool Deleted = false;
8218 bool Constexpr = true;
8219 ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering;
8220
8221 static DefaultedComparisonInfo deleted() {
8222 DefaultedComparisonInfo Deleted;
8223 Deleted.Deleted = true;
8224 return Deleted;
8225 }
8226
8227 bool add(const DefaultedComparisonInfo &R) {
8228 Deleted |= R.Deleted;
8229 Constexpr &= R.Constexpr;
8230 Category = commonComparisonType(A: Category, B: R.Category);
8231 return Deleted;
8232 }
8233};
8234
8235/// An element in the expanded list of subobjects of a defaulted comparison, as
8236/// specified in C++2a [class.compare.default]p4.
8237struct DefaultedComparisonSubobject {
8238 enum { CompleteObject, Member, Base } Kind;
8239 NamedDecl *Decl;
8240 SourceLocation Loc;
8241};
8242
8243/// A visitor over the notional body of a defaulted comparison that determines
8244/// whether that body would be deleted or constexpr.
8245class DefaultedComparisonAnalyzer
8246 : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer,
8247 DefaultedComparisonInfo,
8248 DefaultedComparisonInfo,
8249 DefaultedComparisonSubobject> {
8250public:
8251 enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr };
8252
8253private:
8254 DiagnosticKind Diagnose;
8255
8256public:
8257 using Base = DefaultedComparisonVisitor;
8258 using Result = DefaultedComparisonInfo;
8259 using Subobject = DefaultedComparisonSubobject;
8260
8261 friend Base;
8262
8263 DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8264 DefaultedComparisonKind DCK,
8265 DiagnosticKind Diagnose = NoDiagnostics)
8266 : Base(S, RD, FD, DCK), Diagnose(Diagnose) {}
8267
8268 Result visit() {
8269 if ((DCK == DefaultedComparisonKind::Equal ||
8270 DCK == DefaultedComparisonKind::ThreeWay) &&
8271 RD->hasVariantMembers()) {
8272 // C++2a [class.compare.default]p2 [P2002R0]:
8273 // A defaulted comparison operator function for class C is defined as
8274 // deleted if [...] C has variant members.
8275 if (Diagnose == ExplainDeleted) {
8276 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_defaulted_comparison_union)
8277 << FD << RD->isUnion() << RD;
8278 }
8279 return Result::deleted();
8280 }
8281
8282 return Base::visit();
8283 }
8284
8285private:
8286 Subobject getCompleteObject() {
8287 return Subobject{.Kind: Subobject::CompleteObject, .Decl: RD, .Loc: FD->getLocation()};
8288 }
8289
8290 Subobject getBase(CXXBaseSpecifier *Base) {
8291 return Subobject{.Kind: Subobject::Base, .Decl: Base->getType()->getAsCXXRecordDecl(),
8292 .Loc: Base->getBaseTypeLoc()};
8293 }
8294
8295 Subobject getField(FieldDecl *Field) {
8296 return Subobject{.Kind: Subobject::Member, .Decl: Field, .Loc: Field->getLocation()};
8297 }
8298
8299 Result visitExpandedSubobject(QualType Type, Subobject Subobj) {
8300 // C++2a [class.compare.default]p2 [P2002R0]:
8301 // A defaulted <=> or == operator function for class C is defined as
8302 // deleted if any non-static data member of C is of reference type
8303 if (Type->isReferenceType()) {
8304 if (Diagnose == ExplainDeleted) {
8305 S.Diag(Loc: Subobj.Loc, DiagID: diag::note_defaulted_comparison_reference_member)
8306 << FD << RD;
8307 }
8308 return Result::deleted();
8309 }
8310
8311 // [...] Let xi be an lvalue denoting the ith element [...]
8312 OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue);
8313 Expr *Args[] = {&Xi, &Xi};
8314
8315 // All operators start by trying to apply that same operator recursively.
8316 OverloadedOperatorKind OO = FD->getOverloadedOperator();
8317 assert(OO != OO_None && "not an overloaded operator!");
8318 return visitBinaryOperator(OO, Args, Subobj);
8319 }
8320
8321 Result
8322 visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args,
8323 Subobject Subobj,
8324 OverloadCandidateSet *SpaceshipCandidates = nullptr) {
8325 // Note that there is no need to consider rewritten candidates here if
8326 // we've already found there is no viable 'operator<=>' candidate (and are
8327 // considering synthesizing a '<=>' from '==' and '<').
8328 OverloadCandidateSet CandidateSet(
8329 FD->getLocation(), OverloadCandidateSet::CSK_Operator,
8330 OverloadCandidateSet::OperatorRewriteInfo(
8331 OO, FD->getLocation(),
8332 /*AllowRewrittenCandidates=*/!SpaceshipCandidates));
8333
8334 /// C++2a [class.compare.default]p1 [P2002R0]:
8335 /// [...] the defaulted function itself is never a candidate for overload
8336 /// resolution [...]
8337 CandidateSet.exclude(F: FD);
8338
8339 if (Args[0]->getType()->isOverloadableType())
8340 S.LookupOverloadedBinOp(CandidateSet, Op: OO, Fns, Args);
8341 else
8342 // FIXME: We determine whether this is a valid expression by checking to
8343 // see if there's a viable builtin operator candidate for it. That isn't
8344 // really what the rules ask us to do, but should give the right results.
8345 S.AddBuiltinOperatorCandidates(Op: OO, OpLoc: FD->getLocation(), Args, CandidateSet);
8346
8347 Result R;
8348
8349 OverloadCandidateSet::iterator Best;
8350 switch (CandidateSet.BestViableFunction(S, Loc: FD->getLocation(), Best)) {
8351 case OR_Success: {
8352 // C++2a [class.compare.secondary]p2 [P2002R0]:
8353 // The operator function [...] is defined as deleted if [...] the
8354 // candidate selected by overload resolution is not a rewritten
8355 // candidate.
8356 if ((DCK == DefaultedComparisonKind::NotEqual ||
8357 DCK == DefaultedComparisonKind::Relational) &&
8358 !Best->RewriteKind) {
8359 if (Diagnose == ExplainDeleted) {
8360 if (Best->Function) {
8361 S.Diag(Loc: Best->Function->getLocation(),
8362 DiagID: diag::note_defaulted_comparison_not_rewritten_callee)
8363 << FD;
8364 } else {
8365 assert(Best->Conversions.size() == 2 &&
8366 Best->Conversions[0].isUserDefined() &&
8367 "non-user-defined conversion from class to built-in "
8368 "comparison");
8369 S.Diag(Loc: Best->Conversions[0]
8370 .UserDefined.FoundConversionFunction.getDecl()
8371 ->getLocation(),
8372 DiagID: diag::note_defaulted_comparison_not_rewritten_conversion)
8373 << FD;
8374 }
8375 }
8376 return Result::deleted();
8377 }
8378
8379 // Throughout C++2a [class.compare]: if overload resolution does not
8380 // result in a usable function, the candidate function is defined as
8381 // deleted. This requires that we selected an accessible function.
8382 //
8383 // Note that this only considers the access of the function when named
8384 // within the type of the subobject, and not the access path for any
8385 // derived-to-base conversion.
8386 CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl();
8387 if (ArgClass && Best->FoundDecl.getDecl() &&
8388 Best->FoundDecl.getDecl()->isCXXClassMember()) {
8389 QualType ObjectType = Subobj.Kind == Subobject::Member
8390 ? Args[0]->getType()
8391 : S.Context.getCanonicalTagType(TD: RD);
8392 if (!S.isMemberAccessibleForDeletion(
8393 NamingClass: ArgClass, Found: Best->FoundDecl, ObjectType, Loc: Subobj.Loc,
8394 Diag: Diagnose == ExplainDeleted
8395 ? S.PDiag(DiagID: diag::note_defaulted_comparison_inaccessible)
8396 << FD << Subobj.Kind << Subobj.Decl
8397 : S.PDiag()))
8398 return Result::deleted();
8399 }
8400
8401 bool NeedsDeducing =
8402 OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType();
8403
8404 if (FunctionDecl *BestFD = Best->Function) {
8405 // C++2a [class.compare.default]p3 [P2002R0]:
8406 // A defaulted comparison function is constexpr-compatible if
8407 // [...] no overlod resolution performed [...] results in a
8408 // non-constexpr function.
8409 assert(!BestFD->isDeleted() && "wrong overload resolution result");
8410 // If it's not constexpr, explain why not.
8411 if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) {
8412 if (Subobj.Kind != Subobject::CompleteObject)
8413 S.Diag(Loc: Subobj.Loc, DiagID: diag::note_defaulted_comparison_not_constexpr)
8414 << Subobj.Kind << Subobj.Decl;
8415 S.Diag(Loc: BestFD->getLocation(),
8416 DiagID: diag::note_defaulted_comparison_not_constexpr_here);
8417 // Bail out after explaining; we don't want any more notes.
8418 return Result::deleted();
8419 }
8420 R.Constexpr &= BestFD->isConstexpr();
8421
8422 if (NeedsDeducing) {
8423 // If any callee has an undeduced return type, deduce it now.
8424 // FIXME: It's not clear how a failure here should be handled. For
8425 // now, we produce an eager diagnostic, because that is forward
8426 // compatible with most (all?) other reasonable options.
8427 if (BestFD->getReturnType()->isUndeducedType() &&
8428 S.DeduceReturnType(FD: BestFD, Loc: FD->getLocation(),
8429 /*Diagnose=*/false)) {
8430 // Don't produce a duplicate error when asked to explain why the
8431 // comparison is deleted: we diagnosed that when initially checking
8432 // the defaulted operator.
8433 if (Diagnose == NoDiagnostics) {
8434 S.Diag(
8435 Loc: FD->getLocation(),
8436 DiagID: diag::err_defaulted_comparison_cannot_deduce_undeduced_auto)
8437 << Subobj.Kind << Subobj.Decl;
8438 S.Diag(
8439 Loc: Subobj.Loc,
8440 DiagID: diag::note_defaulted_comparison_cannot_deduce_undeduced_auto)
8441 << Subobj.Kind << Subobj.Decl;
8442 S.Diag(Loc: BestFD->getLocation(),
8443 DiagID: diag::note_defaulted_comparison_cannot_deduce_callee)
8444 << Subobj.Kind << Subobj.Decl;
8445 }
8446 return Result::deleted();
8447 }
8448 auto *Info = S.Context.CompCategories.lookupInfoForType(
8449 Ty: BestFD->getCallResultType());
8450 if (!Info) {
8451 if (Diagnose == ExplainDeleted) {
8452 S.Diag(Loc: Subobj.Loc, DiagID: diag::note_defaulted_comparison_cannot_deduce)
8453 << Subobj.Kind << Subobj.Decl
8454 << BestFD->getCallResultType().withoutLocalFastQualifiers();
8455 S.Diag(Loc: BestFD->getLocation(),
8456 DiagID: diag::note_defaulted_comparison_cannot_deduce_callee)
8457 << Subobj.Kind << Subobj.Decl;
8458 }
8459 return Result::deleted();
8460 }
8461 R.Category = Info->Kind;
8462 }
8463 } else {
8464 QualType T = Best->BuiltinParamTypes[0];
8465 assert(T == Best->BuiltinParamTypes[1] &&
8466 "builtin comparison for different types?");
8467 assert(Best->BuiltinParamTypes[2].isNull() &&
8468 "invalid builtin comparison");
8469
8470 // FIXME: If the type we deduced is a vector type, we mark the
8471 // comparison as deleted because we don't yet support this.
8472 if (isa<VectorType>(Val: T)) {
8473 if (Diagnose == ExplainDeleted) {
8474 S.Diag(Loc: FD->getLocation(),
8475 DiagID: diag::note_defaulted_comparison_vector_types)
8476 << FD;
8477 S.Diag(Loc: Subobj.Decl->getLocation(), DiagID: diag::note_declared_at);
8478 }
8479 return Result::deleted();
8480 }
8481
8482 if (NeedsDeducing) {
8483 std::optional<ComparisonCategoryType> Cat =
8484 getComparisonCategoryForBuiltinCmp(T);
8485 assert(Cat && "no category for builtin comparison?");
8486 R.Category = *Cat;
8487 }
8488 }
8489
8490 // Note that we might be rewriting to a different operator. That call is
8491 // not considered until we come to actually build the comparison function.
8492 break;
8493 }
8494
8495 case OR_Ambiguous:
8496 if (Diagnose == ExplainDeleted) {
8497 unsigned Kind = 0;
8498 if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship)
8499 Kind = OO == OO_EqualEqual ? 1 : 2;
8500 CandidateSet.NoteCandidates(
8501 PA: PartialDiagnosticAt(
8502 Subobj.Loc, S.PDiag(DiagID: diag::note_defaulted_comparison_ambiguous)
8503 << FD << Kind << Subobj.Kind << Subobj.Decl),
8504 S, OCD: OCD_AmbiguousCandidates, Args);
8505 }
8506 R = Result::deleted();
8507 break;
8508
8509 case OR_Deleted:
8510 if (Diagnose == ExplainDeleted) {
8511 if ((DCK == DefaultedComparisonKind::NotEqual ||
8512 DCK == DefaultedComparisonKind::Relational) &&
8513 !Best->RewriteKind) {
8514 S.Diag(Loc: Best->Function->getLocation(),
8515 DiagID: diag::note_defaulted_comparison_not_rewritten_callee)
8516 << FD;
8517 } else {
8518 S.Diag(Loc: Subobj.Loc,
8519 DiagID: diag::note_defaulted_comparison_calls_deleted)
8520 << FD << Subobj.Kind << Subobj.Decl;
8521 S.NoteDeletedFunction(FD: Best->Function);
8522 }
8523 }
8524 R = Result::deleted();
8525 break;
8526
8527 case OR_No_Viable_Function:
8528 // If there's no usable candidate, we're done unless we can rewrite a
8529 // '<=>' in terms of '==' and '<'.
8530 if (OO == OO_Spaceship &&
8531 S.Context.CompCategories.lookupInfoForType(Ty: FD->getReturnType())) {
8532 // For any kind of comparison category return type, we need a usable
8533 // '==' and a usable '<'.
8534 if (!R.add(R: visitBinaryOperator(OO: OO_EqualEqual, Args, Subobj,
8535 SpaceshipCandidates: &CandidateSet)))
8536 R.add(R: visitBinaryOperator(OO: OO_Less, Args, Subobj, SpaceshipCandidates: &CandidateSet));
8537 break;
8538 }
8539
8540 if (Diagnose == ExplainDeleted) {
8541 S.Diag(Loc: Subobj.Loc, DiagID: diag::note_defaulted_comparison_no_viable_function)
8542 << FD << (OO == OO_EqualEqual || OO == OO_ExclaimEqual)
8543 << Subobj.Kind << Subobj.Decl;
8544
8545 // For a three-way comparison, list both the candidates for the
8546 // original operator and the candidates for the synthesized operator.
8547 if (SpaceshipCandidates) {
8548 SpaceshipCandidates->NoteCandidates(
8549 S, Args,
8550 Cands: SpaceshipCandidates->CompleteCandidates(S, OCD: OCD_AllCandidates,
8551 Args, OpLoc: FD->getLocation()));
8552 S.Diag(Loc: Subobj.Loc,
8553 DiagID: diag::note_defaulted_comparison_no_viable_function_synthesized)
8554 << (OO == OO_EqualEqual ? 0 : 1);
8555 }
8556
8557 CandidateSet.NoteCandidates(
8558 S, Args,
8559 Cands: CandidateSet.CompleteCandidates(S, OCD: OCD_AllCandidates, Args,
8560 OpLoc: FD->getLocation()));
8561 }
8562 R = Result::deleted();
8563 break;
8564 }
8565
8566 return R;
8567 }
8568};
8569
8570/// A list of statements.
8571struct StmtListResult {
8572 bool IsInvalid = false;
8573 llvm::SmallVector<Stmt*, 16> Stmts;
8574
8575 bool add(const StmtResult &S) {
8576 IsInvalid |= S.isInvalid();
8577 if (IsInvalid)
8578 return true;
8579 Stmts.push_back(Elt: S.get());
8580 return false;
8581 }
8582};
8583
8584/// A visitor over the notional body of a defaulted comparison that synthesizes
8585/// the actual body.
8586class DefaultedComparisonSynthesizer
8587 : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer,
8588 StmtListResult, StmtResult,
8589 std::pair<ExprResult, ExprResult>> {
8590 SourceLocation Loc;
8591 unsigned ArrayDepth = 0;
8592
8593public:
8594 using Base = DefaultedComparisonVisitor;
8595 using ExprPair = std::pair<ExprResult, ExprResult>;
8596
8597 friend Base;
8598
8599 DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8600 DefaultedComparisonKind DCK,
8601 SourceLocation BodyLoc)
8602 : Base(S, RD, FD, DCK), Loc(BodyLoc) {}
8603
8604 /// Build a suitable function body for this defaulted comparison operator.
8605 StmtResult build() {
8606 Sema::CompoundScopeRAII CompoundScope(S);
8607
8608 StmtListResult Stmts = visit();
8609 if (Stmts.IsInvalid)
8610 return StmtError();
8611
8612 ExprResult RetVal;
8613 switch (DCK) {
8614 case DefaultedComparisonKind::None:
8615 llvm_unreachable("not a defaulted comparison");
8616
8617 case DefaultedComparisonKind::Equal: {
8618 // C++2a [class.eq]p3:
8619 // [...] compar[e] the corresponding elements [...] until the first
8620 // index i where xi == yi yields [...] false. If no such index exists,
8621 // V is true. Otherwise, V is false.
8622 //
8623 // Join the comparisons with '&&'s and return the result. Use a right
8624 // fold (traversing the conditions right-to-left), because that
8625 // short-circuits more naturally.
8626 auto OldStmts = std::move(Stmts.Stmts);
8627 Stmts.Stmts.clear();
8628 ExprResult CmpSoFar;
8629 // Finish a particular comparison chain.
8630 auto FinishCmp = [&] {
8631 if (Expr *Prior = CmpSoFar.get()) {
8632 // Convert the last expression to 'return ...;'
8633 if (RetVal.isUnset() && Stmts.Stmts.empty())
8634 RetVal = CmpSoFar;
8635 // Convert any prior comparison to 'if (!(...)) return false;'
8636 else if (Stmts.add(S: buildIfNotCondReturnFalse(Cond: Prior)))
8637 return true;
8638 CmpSoFar = ExprResult();
8639 }
8640 return false;
8641 };
8642 for (Stmt *EAsStmt : llvm::reverse(C&: OldStmts)) {
8643 Expr *E = dyn_cast<Expr>(Val: EAsStmt);
8644 if (!E) {
8645 // Found an array comparison.
8646 if (FinishCmp() || Stmts.add(S: EAsStmt))
8647 return StmtError();
8648 continue;
8649 }
8650
8651 if (CmpSoFar.isUnset()) {
8652 CmpSoFar = E;
8653 continue;
8654 }
8655 CmpSoFar = S.CreateBuiltinBinOp(OpLoc: Loc, Opc: BO_LAnd, LHSExpr: E, RHSExpr: CmpSoFar.get());
8656 if (CmpSoFar.isInvalid())
8657 return StmtError();
8658 }
8659 if (FinishCmp())
8660 return StmtError();
8661 std::reverse(first: Stmts.Stmts.begin(), last: Stmts.Stmts.end());
8662 // If no such index exists, V is true.
8663 if (RetVal.isUnset())
8664 RetVal = S.ActOnCXXBoolLiteral(OpLoc: Loc, Kind: tok::kw_true);
8665 break;
8666 }
8667
8668 case DefaultedComparisonKind::ThreeWay: {
8669 // Per C++2a [class.spaceship]p3, as a fallback add:
8670 // return static_cast<R>(std::strong_ordering::equal);
8671 QualType StrongOrdering = S.CheckComparisonCategoryType(
8672 Kind: ComparisonCategoryType::StrongOrdering, Loc,
8673 Usage: Sema::ComparisonCategoryUsage::DefaultedOperator);
8674 if (StrongOrdering.isNull())
8675 return StmtError();
8676 VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(Ty: StrongOrdering)
8677 .getValueInfo(ValueKind: ComparisonCategoryResult::Equal)
8678 ->VD;
8679 RetVal = getDecl(VD: EqualVD);
8680 if (RetVal.isInvalid())
8681 return StmtError();
8682 RetVal = buildStaticCastToR(E: RetVal.get());
8683 break;
8684 }
8685
8686 case DefaultedComparisonKind::NotEqual:
8687 case DefaultedComparisonKind::Relational:
8688 RetVal = cast<Expr>(Val: Stmts.Stmts.pop_back_val());
8689 break;
8690 }
8691
8692 // Build the final return statement.
8693 if (RetVal.isInvalid())
8694 return StmtError();
8695 StmtResult ReturnStmt = S.BuildReturnStmt(ReturnLoc: Loc, RetValExp: RetVal.get());
8696 if (ReturnStmt.isInvalid())
8697 return StmtError();
8698 Stmts.Stmts.push_back(Elt: ReturnStmt.get());
8699
8700 return S.ActOnCompoundStmt(L: Loc, R: Loc, Elts: Stmts.Stmts, /*IsStmtExpr=*/isStmtExpr: false);
8701 }
8702
8703private:
8704 ExprResult getDecl(ValueDecl *VD) {
8705 return S.BuildDeclarationNameExpr(
8706 SS: CXXScopeSpec(), NameInfo: DeclarationNameInfo(VD->getDeclName(), Loc), D: VD);
8707 }
8708
8709 ExprResult getParam(unsigned I) {
8710 ParmVarDecl *PD = FD->getParamDecl(i: I);
8711 return getDecl(VD: PD);
8712 }
8713
8714 ExprPair getCompleteObject() {
8715 unsigned Param = 0;
8716 ExprResult LHS;
8717 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: FD);
8718 MD && MD->isImplicitObjectMemberFunction()) {
8719 // LHS is '*this'.
8720 LHS = S.ActOnCXXThis(Loc);
8721 if (!LHS.isInvalid())
8722 LHS = S.CreateBuiltinUnaryOp(OpLoc: Loc, Opc: UO_Deref, InputExpr: LHS.get());
8723 } else {
8724 LHS = getParam(I: Param++);
8725 }
8726 ExprResult RHS = getParam(I: Param++);
8727 assert(Param == FD->getNumParams());
8728 return {LHS, RHS};
8729 }
8730
8731 ExprPair getBase(CXXBaseSpecifier *Base) {
8732 ExprPair Obj = getCompleteObject();
8733 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8734 return {ExprError(), ExprError()};
8735 CXXCastPath Path = {Base};
8736 const auto CastToBase = [&](Expr *E) {
8737 QualType ToType = S.Context.getQualifiedType(
8738 T: Base->getType(), Qs: E->getType().getQualifiers());
8739 return S.ImpCastExprToType(E, Type: ToType, CK: CK_DerivedToBase, VK: VK_LValue, BasePath: &Path);
8740 };
8741 return {CastToBase(Obj.first.get()), CastToBase(Obj.second.get())};
8742 }
8743
8744 ExprPair getField(FieldDecl *Field) {
8745 ExprPair Obj = getCompleteObject();
8746 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8747 return {ExprError(), ExprError()};
8748
8749 DeclAccessPair Found = DeclAccessPair::make(D: Field, AS: Field->getAccess());
8750 DeclarationNameInfo NameInfo(Field->getDeclName(), Loc);
8751 return {S.BuildFieldReferenceExpr(BaseExpr: Obj.first.get(), /*IsArrow=*/false, OpLoc: Loc,
8752 SS: CXXScopeSpec(), Field, FoundDecl: Found, MemberNameInfo: NameInfo),
8753 S.BuildFieldReferenceExpr(BaseExpr: Obj.second.get(), /*IsArrow=*/false, OpLoc: Loc,
8754 SS: CXXScopeSpec(), Field, FoundDecl: Found, MemberNameInfo: NameInfo)};
8755 }
8756
8757 // FIXME: When expanding a subobject, register a note in the code synthesis
8758 // stack to say which subobject we're comparing.
8759
8760 StmtResult buildIfNotCondReturnFalse(ExprResult Cond) {
8761 if (Cond.isInvalid())
8762 return StmtError();
8763
8764 ExprResult NotCond = S.CreateBuiltinUnaryOp(OpLoc: Loc, Opc: UO_LNot, InputExpr: Cond.get());
8765 if (NotCond.isInvalid())
8766 return StmtError();
8767
8768 ExprResult False = S.ActOnCXXBoolLiteral(OpLoc: Loc, Kind: tok::kw_false);
8769 assert(!False.isInvalid() && "should never fail");
8770 StmtResult ReturnFalse = S.BuildReturnStmt(ReturnLoc: Loc, RetValExp: False.get());
8771 if (ReturnFalse.isInvalid())
8772 return StmtError();
8773
8774 return S.ActOnIfStmt(IfLoc: Loc, StatementKind: IfStatementKind::Ordinary, LParenLoc: Loc, InitStmt: nullptr,
8775 Cond: S.ActOnCondition(S: nullptr, Loc, SubExpr: NotCond.get(),
8776 CK: Sema::ConditionKind::Boolean),
8777 RParenLoc: Loc, ThenVal: ReturnFalse.get(), ElseLoc: SourceLocation(), ElseVal: nullptr);
8778 }
8779
8780 StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size,
8781 ExprPair Subobj) {
8782 QualType SizeType = S.Context.getSizeType();
8783 Size = Size.zextOrTrunc(width: S.Context.getTypeSize(T: SizeType));
8784
8785 // Build 'size_t i$n = 0'.
8786 IdentifierInfo *IterationVarName = nullptr;
8787 {
8788 SmallString<8> Str;
8789 llvm::raw_svector_ostream OS(Str);
8790 OS << "i" << ArrayDepth;
8791 IterationVarName = &S.Context.Idents.get(Name: OS.str());
8792 }
8793 VarDecl *IterationVar = VarDecl::Create(
8794 C&: S.Context, DC: S.CurContext, StartLoc: Loc, IdLoc: Loc, Id: IterationVarName, T: SizeType,
8795 TInfo: S.Context.getTrivialTypeSourceInfo(T: SizeType, Loc), S: SC_None);
8796 llvm::APInt Zero(S.Context.getTypeSize(T: SizeType), 0);
8797 IterationVar->setInit(
8798 IntegerLiteral::Create(C: S.Context, V: Zero, type: SizeType, l: Loc));
8799 Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc);
8800
8801 auto IterRef = [&] {
8802 ExprResult Ref = S.BuildDeclarationNameExpr(
8803 SS: CXXScopeSpec(), NameInfo: DeclarationNameInfo(IterationVarName, Loc),
8804 D: IterationVar);
8805 assert(!Ref.isInvalid() && "can't reference our own variable?");
8806 return Ref.get();
8807 };
8808
8809 // Build 'i$n != Size'.
8810 ExprResult Cond = S.CreateBuiltinBinOp(
8811 OpLoc: Loc, Opc: BO_NE, LHSExpr: IterRef(),
8812 RHSExpr: IntegerLiteral::Create(C: S.Context, V: Size, type: SizeType, l: Loc));
8813 assert(!Cond.isInvalid() && "should never fail");
8814
8815 // Build '++i$n'.
8816 ExprResult Inc = S.CreateBuiltinUnaryOp(OpLoc: Loc, Opc: UO_PreInc, InputExpr: IterRef());
8817 assert(!Inc.isInvalid() && "should never fail");
8818
8819 // Build 'a[i$n]' and 'b[i$n]'.
8820 auto Index = [&](ExprResult E) {
8821 if (E.isInvalid())
8822 return ExprError();
8823 return S.CreateBuiltinArraySubscriptExpr(Base: E.get(), LLoc: Loc, Idx: IterRef(), RLoc: Loc);
8824 };
8825 Subobj.first = Index(Subobj.first);
8826 Subobj.second = Index(Subobj.second);
8827
8828 // Compare the array elements.
8829 ++ArrayDepth;
8830 StmtResult Substmt = visitSubobject(Type, Subobj);
8831 --ArrayDepth;
8832
8833 if (Substmt.isInvalid())
8834 return StmtError();
8835
8836 // For the inner level of an 'operator==', build 'if (!cmp) return false;'.
8837 // For outer levels or for an 'operator<=>' we already have a suitable
8838 // statement that returns as necessary.
8839 if (Expr *ElemCmp = dyn_cast<Expr>(Val: Substmt.get())) {
8840 assert(DCK == DefaultedComparisonKind::Equal &&
8841 "should have non-expression statement");
8842 Substmt = buildIfNotCondReturnFalse(Cond: ElemCmp);
8843 if (Substmt.isInvalid())
8844 return StmtError();
8845 }
8846
8847 // Build 'for (...) ...'
8848 return S.ActOnForStmt(ForLoc: Loc, LParenLoc: Loc, First: Init,
8849 Second: S.ActOnCondition(S: nullptr, Loc, SubExpr: Cond.get(),
8850 CK: Sema::ConditionKind::Boolean),
8851 Third: S.MakeFullDiscardedValueExpr(Arg: Inc.get()), RParenLoc: Loc,
8852 Body: Substmt.get());
8853 }
8854
8855 StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) {
8856 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8857 return StmtError();
8858
8859 OverloadedOperatorKind OO = FD->getOverloadedOperator();
8860 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(OO);
8861 ExprResult Op;
8862 if (Type->isOverloadableType())
8863 Op = S.CreateOverloadedBinOp(OpLoc: Loc, Opc, Fns, LHS: Obj.first.get(),
8864 RHS: Obj.second.get(), /*PerformADL=*/RequiresADL: true,
8865 /*AllowRewrittenCandidates=*/true, DefaultedFn: FD);
8866 else
8867 Op = S.CreateBuiltinBinOp(OpLoc: Loc, Opc, LHSExpr: Obj.first.get(), RHSExpr: Obj.second.get());
8868 if (Op.isInvalid())
8869 return StmtError();
8870
8871 switch (DCK) {
8872 case DefaultedComparisonKind::None:
8873 llvm_unreachable("not a defaulted comparison");
8874
8875 case DefaultedComparisonKind::Equal:
8876 // Per C++2a [class.eq]p2, each comparison is individually contextually
8877 // converted to bool.
8878 Op = S.PerformContextuallyConvertToBool(From: Op.get());
8879 if (Op.isInvalid())
8880 return StmtError();
8881 return Op.get();
8882
8883 case DefaultedComparisonKind::ThreeWay: {
8884 // Per C++2a [class.spaceship]p3, form:
8885 // if (R cmp = static_cast<R>(op); cmp != 0)
8886 // return cmp;
8887 QualType R = FD->getReturnType();
8888 Op = buildStaticCastToR(E: Op.get());
8889 if (Op.isInvalid())
8890 return StmtError();
8891
8892 // R cmp = ...;
8893 IdentifierInfo *Name = &S.Context.Idents.get(Name: "cmp");
8894 VarDecl *VD =
8895 VarDecl::Create(C&: S.Context, DC: S.CurContext, StartLoc: Loc, IdLoc: Loc, Id: Name, T: R,
8896 TInfo: S.Context.getTrivialTypeSourceInfo(T: R, Loc), S: SC_None);
8897 S.AddInitializerToDecl(dcl: VD, init: Op.get(), /*DirectInit=*/false);
8898 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc);
8899
8900 // cmp != 0
8901 ExprResult VDRef = getDecl(VD);
8902 if (VDRef.isInvalid())
8903 return StmtError();
8904 llvm::APInt ZeroVal(S.Context.getIntWidth(T: S.Context.IntTy), 0);
8905 Expr *Zero =
8906 IntegerLiteral::Create(C: S.Context, V: ZeroVal, type: S.Context.IntTy, l: Loc);
8907 ExprResult Comp;
8908 if (VDRef.get()->getType()->isOverloadableType())
8909 Comp = S.CreateOverloadedBinOp(OpLoc: Loc, Opc: BO_NE, Fns, LHS: VDRef.get(), RHS: Zero, RequiresADL: true,
8910 AllowRewrittenCandidates: true, DefaultedFn: FD);
8911 else
8912 Comp = S.CreateBuiltinBinOp(OpLoc: Loc, Opc: BO_NE, LHSExpr: VDRef.get(), RHSExpr: Zero);
8913 if (Comp.isInvalid())
8914 return StmtError();
8915 Sema::ConditionResult Cond = S.ActOnCondition(
8916 S: nullptr, Loc, SubExpr: Comp.get(), CK: Sema::ConditionKind::Boolean);
8917 if (Cond.isInvalid())
8918 return StmtError();
8919
8920 // return cmp;
8921 VDRef = getDecl(VD);
8922 if (VDRef.isInvalid())
8923 return StmtError();
8924 StmtResult ReturnStmt = S.BuildReturnStmt(ReturnLoc: Loc, RetValExp: VDRef.get());
8925 if (ReturnStmt.isInvalid())
8926 return StmtError();
8927
8928 // if (...)
8929 return S.ActOnIfStmt(IfLoc: Loc, StatementKind: IfStatementKind::Ordinary, LParenLoc: Loc, InitStmt, Cond,
8930 RParenLoc: Loc, ThenVal: ReturnStmt.get(),
8931 /*ElseLoc=*/SourceLocation(), /*Else=*/ElseVal: nullptr);
8932 }
8933
8934 case DefaultedComparisonKind::NotEqual:
8935 case DefaultedComparisonKind::Relational:
8936 // C++2a [class.compare.secondary]p2:
8937 // Otherwise, the operator function yields x @ y.
8938 return Op.get();
8939 }
8940 llvm_unreachable("");
8941 }
8942
8943 /// Build "static_cast<R>(E)".
8944 ExprResult buildStaticCastToR(Expr *E) {
8945 QualType R = FD->getReturnType();
8946 assert(!R->isUndeducedType() && "type should have been deduced already");
8947
8948 // Don't bother forming a no-op cast in the common case.
8949 if (E->isPRValue() && S.Context.hasSameType(T1: E->getType(), T2: R))
8950 return E;
8951 return S.BuildCXXNamedCast(OpLoc: Loc, Kind: tok::kw_static_cast,
8952 Ty: S.Context.getTrivialTypeSourceInfo(T: R, Loc), E,
8953 AngleBrackets: SourceRange(Loc, Loc), Parens: SourceRange(Loc, Loc));
8954 }
8955};
8956}
8957
8958/// Perform the unqualified lookups that might be needed to form a defaulted
8959/// comparison function for the given operator.
8960static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S,
8961 UnresolvedSetImpl &Operators,
8962 OverloadedOperatorKind Op) {
8963 auto Lookup = [&](OverloadedOperatorKind OO) {
8964 Self.LookupOverloadedOperatorName(Op: OO, S, Functions&: Operators);
8965 };
8966
8967 // Every defaulted operator looks up itself.
8968 Lookup(Op);
8969 // ... and the rewritten form of itself, if any.
8970 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Kind: Op))
8971 Lookup(ExtraOp);
8972
8973 // For 'operator<=>', we also form a 'cmp != 0' expression, and might
8974 // synthesize a three-way comparison from '<' and '=='. In a dependent
8975 // context, we also need to look up '==' in case we implicitly declare a
8976 // defaulted 'operator=='.
8977 if (Op == OO_Spaceship) {
8978 Lookup(OO_ExclaimEqual);
8979 Lookup(OO_Less);
8980 Lookup(OO_EqualEqual);
8981 }
8982}
8983
8984bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *FD,
8985 DefaultedComparisonKind DCK) {
8986 assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison");
8987
8988 // Perform any unqualified lookups we're going to need to default this
8989 // function.
8990 if (S) {
8991 UnresolvedSet<32> Operators;
8992 lookupOperatorsForDefaultedComparison(Self&: *this, S, Operators,
8993 Op: FD->getOverloadedOperator());
8994 FD->setDefaultedOrDeletedInfo(
8995 FunctionDecl::DefaultedOrDeletedFunctionInfo::Create(
8996 Context, Lookups: Operators.pairs()));
8997 }
8998
8999 // C++2a [class.compare.default]p1:
9000 // A defaulted comparison operator function for some class C shall be a
9001 // non-template function declared in the member-specification of C that is
9002 // -- a non-static const non-volatile member of C having one parameter of
9003 // type const C& and either no ref-qualifier or the ref-qualifier &, or
9004 // -- a friend of C having two parameters of type const C& or two
9005 // parameters of type C.
9006
9007 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: FD->getLexicalDeclContext());
9008 bool IsMethod = isa<CXXMethodDecl>(Val: FD);
9009 if (IsMethod) {
9010 auto *MD = cast<CXXMethodDecl>(Val: FD);
9011 assert(!MD->isStatic() && "comparison function cannot be a static member");
9012
9013 if (MD->getRefQualifier() == RQ_RValue) {
9014 Diag(Loc: MD->getLocation(), DiagID: diag::err_ref_qualifier_comparison_operator);
9015
9016 // Remove the ref qualifier to recover.
9017 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
9018 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9019 EPI.RefQualifier = RQ_None;
9020 MD->setType(Context.getFunctionType(ResultTy: FPT->getReturnType(),
9021 Args: FPT->getParamTypes(), EPI));
9022 }
9023
9024 // If we're out-of-class, this is the class we're comparing.
9025 if (!RD)
9026 RD = MD->getParent();
9027 QualType T = MD->getFunctionObjectParameterReferenceType();
9028 if (!T.getNonReferenceType().isConstQualified() &&
9029 (MD->isImplicitObjectMemberFunction() || T->isLValueReferenceType())) {
9030 SourceLocation Loc, InsertLoc;
9031 if (MD->isExplicitObjectMemberFunction()) {
9032 Loc = MD->getParamDecl(i: 0)->getBeginLoc();
9033 InsertLoc = getLocForEndOfToken(
9034 Loc: MD->getParamDecl(i: 0)->getExplicitObjectParamThisLoc());
9035 } else {
9036 Loc = MD->getLocation();
9037 if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc())
9038 InsertLoc = getLocForEndOfToken(Loc: Loc.getRParenLoc());
9039 }
9040 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
9041 // corresponding defaulted 'operator<=>' already.
9042 if (!MD->isImplicit()) {
9043 Diag(Loc, DiagID: diag::err_defaulted_comparison_non_const)
9044 << (int)DCK << FixItHint::CreateInsertion(InsertionLoc: InsertLoc, Code: " const");
9045 }
9046
9047 // Add the 'const' to the type to recover.
9048 if (MD->isExplicitObjectMemberFunction()) {
9049 assert(T->isLValueReferenceType());
9050 MD->getParamDecl(i: 0)->setType(Context.getLValueReferenceType(
9051 T: T.getNonReferenceType().withConst()));
9052 } else {
9053 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
9054 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9055 EPI.TypeQuals.addConst();
9056 MD->setType(Context.getFunctionType(ResultTy: FPT->getReturnType(),
9057 Args: FPT->getParamTypes(), EPI));
9058 }
9059 }
9060
9061 if (MD->isVolatile()) {
9062 Diag(Loc: MD->getLocation(), DiagID: diag::err_volatile_comparison_operator);
9063
9064 // Remove the 'volatile' from the type to recover.
9065 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
9066 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9067 EPI.TypeQuals.removeVolatile();
9068 MD->setType(Context.getFunctionType(ResultTy: FPT->getReturnType(),
9069 Args: FPT->getParamTypes(), EPI));
9070 }
9071 }
9072
9073 if ((FD->getNumParams() -
9074 (unsigned)FD->hasCXXExplicitFunctionObjectParameter()) !=
9075 (IsMethod ? 1 : 2)) {
9076 // Let's not worry about using a variadic template pack here -- who would do
9077 // such a thing?
9078 Diag(Loc: FD->getLocation(), DiagID: diag::err_defaulted_comparison_num_args)
9079 << int(IsMethod) << int(DCK);
9080 return true;
9081 }
9082
9083 const ParmVarDecl *KnownParm = nullptr;
9084 for (const ParmVarDecl *Param : FD->parameters()) {
9085 QualType ParmTy = Param->getType();
9086 if (!KnownParm) {
9087 auto CTy = ParmTy;
9088 // Is it `T const &`?
9089 bool Ok = !IsMethod || FD->hasCXXExplicitFunctionObjectParameter();
9090 QualType ExpectedTy;
9091 if (RD)
9092 ExpectedTy = Context.getCanonicalTagType(TD: RD);
9093 if (auto *Ref = CTy->getAs<LValueReferenceType>()) {
9094 CTy = Ref->getPointeeType();
9095 if (RD)
9096 ExpectedTy.addConst();
9097 Ok = true;
9098 }
9099
9100 // Is T a class?
9101 if (RD) {
9102 Ok &= RD->isDependentType() || Context.hasSameType(T1: CTy, T2: ExpectedTy);
9103 } else {
9104 RD = CTy->getAsCXXRecordDecl();
9105 Ok &= RD != nullptr;
9106 }
9107
9108 if (Ok) {
9109 KnownParm = Param;
9110 } else {
9111 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
9112 // corresponding defaulted 'operator<=>' already.
9113 if (!FD->isImplicit()) {
9114 if (RD) {
9115 CanQualType PlainTy = Context.getCanonicalTagType(TD: RD);
9116 QualType RefTy =
9117 Context.getLValueReferenceType(T: PlainTy.withConst());
9118 Diag(Loc: FD->getLocation(), DiagID: diag::err_defaulted_comparison_param)
9119 << int(DCK) << ParmTy << RefTy << int(!IsMethod) << PlainTy
9120 << Param->getSourceRange();
9121 } else {
9122 assert(!IsMethod && "should know expected type for method");
9123 Diag(Loc: FD->getLocation(),
9124 DiagID: diag::err_defaulted_comparison_param_unknown)
9125 << int(DCK) << ParmTy << Param->getSourceRange();
9126 }
9127 }
9128 return true;
9129 }
9130 } else if (!Context.hasSameType(T1: KnownParm->getType(), T2: ParmTy)) {
9131 Diag(Loc: FD->getLocation(), DiagID: diag::err_defaulted_comparison_param_mismatch)
9132 << int(DCK) << KnownParm->getType() << KnownParm->getSourceRange()
9133 << ParmTy << Param->getSourceRange();
9134 return true;
9135 }
9136 }
9137
9138 assert(RD && "must have determined class");
9139 if (IsMethod) {
9140 } else if (isa<CXXRecordDecl>(Val: FD->getLexicalDeclContext())) {
9141 // In-class, must be a friend decl.
9142 assert(FD->getFriendObjectKind() && "expected a friend declaration");
9143 } else {
9144 // Out of class, require the defaulted comparison to be a friend (of a
9145 // complete type, per CWG2547).
9146 if (RequireCompleteType(Loc: FD->getLocation(), T: Context.getCanonicalTagType(TD: RD),
9147 DiagID: diag::err_defaulted_comparison_not_friend, Args: int(DCK),
9148 Args: int(1)))
9149 return true;
9150
9151 if (llvm::none_of(Range: RD->friends(), P: [&](const FriendDecl *F) {
9152 return declaresSameEntity(D1: F->getFriendDecl(), D2: FD);
9153 })) {
9154 Diag(Loc: FD->getLocation(), DiagID: diag::err_defaulted_comparison_not_friend)
9155 << int(DCK) << int(0) << RD;
9156 Diag(Loc: RD->getCanonicalDecl()->getLocation(), DiagID: diag::note_declared_at);
9157 return true;
9158 }
9159 }
9160
9161 // C++2a [class.eq]p1, [class.rel]p1:
9162 // A [defaulted comparison other than <=>] shall have a declared return
9163 // type bool.
9164 if (DCK != DefaultedComparisonKind::ThreeWay &&
9165 !FD->getDeclaredReturnType()->isDependentType() &&
9166 !Context.hasSameType(T1: FD->getDeclaredReturnType(), T2: Context.BoolTy)) {
9167 Diag(Loc: FD->getLocation(), DiagID: diag::err_defaulted_comparison_return_type_not_bool)
9168 << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy
9169 << FD->getReturnTypeSourceRange();
9170 return true;
9171 }
9172 // C++2a [class.spaceship]p2 [P2002R0]:
9173 // Let R be the declared return type [...]. If R is auto, [...]. Otherwise,
9174 // R shall not contain a placeholder type.
9175 if (QualType RT = FD->getDeclaredReturnType();
9176 DCK == DefaultedComparisonKind::ThreeWay &&
9177 RT->getContainedDeducedType() &&
9178 (!Context.hasSameType(T1: RT, T2: Context.getAutoDeductType()) ||
9179 RT->getContainedAutoType()->isConstrained())) {
9180 Diag(Loc: FD->getLocation(),
9181 DiagID: diag::err_defaulted_comparison_deduced_return_type_not_auto)
9182 << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy
9183 << FD->getReturnTypeSourceRange();
9184 return true;
9185 }
9186
9187 // For a defaulted function in a dependent class, defer all remaining checks
9188 // until instantiation.
9189 if (RD->isDependentType())
9190 return false;
9191
9192 // Determine whether the function should be defined as deleted.
9193 DefaultedComparisonInfo Info =
9194 DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit();
9195
9196 bool First = FD == FD->getCanonicalDecl();
9197
9198 if (!First) {
9199 if (Info.Deleted) {
9200 // C++11 [dcl.fct.def.default]p4:
9201 // [For a] user-provided explicitly-defaulted function [...] if such a
9202 // function is implicitly defined as deleted, the program is ill-formed.
9203 //
9204 // This is really just a consequence of the general rule that you can
9205 // only delete a function on its first declaration.
9206 Diag(Loc: FD->getLocation(), DiagID: diag::err_non_first_default_compare_deletes)
9207 << FD->isImplicit() << (int)DCK;
9208 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9209 DefaultedComparisonAnalyzer::ExplainDeleted)
9210 .visit();
9211 return true;
9212 }
9213 if (isa<CXXRecordDecl>(Val: FD->getLexicalDeclContext())) {
9214 // C++20 [class.compare.default]p1:
9215 // [...] A definition of a comparison operator as defaulted that appears
9216 // in a class shall be the first declaration of that function.
9217 Diag(Loc: FD->getLocation(), DiagID: diag::err_non_first_default_compare_in_class)
9218 << (int)DCK;
9219 Diag(Loc: FD->getCanonicalDecl()->getLocation(),
9220 DiagID: diag::note_previous_declaration);
9221 return true;
9222 }
9223 }
9224
9225 // If we want to delete the function, then do so; there's nothing else to
9226 // check in that case.
9227 if (Info.Deleted) {
9228 SetDeclDeleted(dcl: FD, DelLoc: FD->getLocation());
9229 if (!inTemplateInstantiation() && !FD->isImplicit()) {
9230 Diag(Loc: FD->getLocation(), DiagID: diag::warn_defaulted_comparison_deleted)
9231 << (int)DCK;
9232 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9233 DefaultedComparisonAnalyzer::ExplainDeleted)
9234 .visit();
9235 if (FD->getDefaultLoc().isValid())
9236 Diag(Loc: FD->getDefaultLoc(), DiagID: diag::note_replace_equals_default_to_delete)
9237 << FixItHint::CreateReplacement(RemoveRange: FD->getDefaultLoc(), Code: "delete");
9238 }
9239 return false;
9240 }
9241
9242 // C++2a [class.spaceship]p2:
9243 // The return type is deduced as the common comparison type of R0, R1, ...
9244 if (DCK == DefaultedComparisonKind::ThreeWay &&
9245 FD->getDeclaredReturnType()->isUndeducedAutoType()) {
9246 SourceLocation RetLoc = FD->getReturnTypeSourceRange().getBegin();
9247 if (RetLoc.isInvalid())
9248 RetLoc = FD->getBeginLoc();
9249 // FIXME: Should we really care whether we have the complete type and the
9250 // 'enumerator' constants here? A forward declaration seems sufficient.
9251 QualType Cat = CheckComparisonCategoryType(
9252 Kind: Info.Category, Loc: RetLoc, Usage: ComparisonCategoryUsage::DefaultedOperator);
9253 if (Cat.isNull())
9254 return true;
9255 Context.adjustDeducedFunctionResultType(
9256 FD, ResultType: SubstAutoType(TypeWithAuto: FD->getDeclaredReturnType(), Replacement: Cat));
9257 }
9258
9259 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
9260 // An explicitly-defaulted function that is not defined as deleted may be
9261 // declared constexpr or consteval only if it is constexpr-compatible.
9262 // C++2a [class.compare.default]p3 [P2002R0]:
9263 // A defaulted comparison function is constexpr-compatible if it satisfies
9264 // the requirements for a constexpr function [...]
9265 // The only relevant requirements are that the parameter and return types are
9266 // literal types. The remaining conditions are checked by the analyzer.
9267 //
9268 // We support P2448R2 in language modes earlier than C++23 as an extension.
9269 // The concept of constexpr-compatible was removed.
9270 // C++23 [dcl.fct.def.default]p3 [P2448R2]
9271 // A function explicitly defaulted on its first declaration is implicitly
9272 // inline, and is implicitly constexpr if it is constexpr-suitable.
9273 // C++23 [dcl.constexpr]p3
9274 // A function is constexpr-suitable if
9275 // - it is not a coroutine, and
9276 // - if the function is a constructor or destructor, its class does not
9277 // have any virtual base classes.
9278 if (FD->isConstexpr()) {
9279 if (!getLangOpts().CPlusPlus23 &&
9280 CheckConstexprReturnType(SemaRef&: *this, FD, Kind: CheckConstexprKind::Diagnose) &&
9281 CheckConstexprParameterTypes(SemaRef&: *this, FD, Kind: CheckConstexprKind::Diagnose) &&
9282 !Info.Constexpr) {
9283 Diag(Loc: FD->getBeginLoc(), DiagID: diag::err_defaulted_comparison_constexpr_mismatch)
9284 << FD->isImplicit() << (int)DCK << FD->isConsteval();
9285 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9286 DefaultedComparisonAnalyzer::ExplainConstexpr)
9287 .visit();
9288 }
9289 }
9290
9291 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
9292 // If a constexpr-compatible function is explicitly defaulted on its first
9293 // declaration, it is implicitly considered to be constexpr.
9294 // FIXME: Only applying this to the first declaration seems problematic, as
9295 // simple reorderings can affect the meaning of the program.
9296 if (First && !FD->isConstexpr() && Info.Constexpr)
9297 FD->setConstexprKind(ConstexprSpecKind::Constexpr);
9298
9299 // C++2a [except.spec]p3:
9300 // If a declaration of a function does not have a noexcept-specifier
9301 // [and] is defaulted on its first declaration, [...] the exception
9302 // specification is as specified below
9303 if (FD->getExceptionSpecType() == EST_None) {
9304 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9305 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9306 EPI.ExceptionSpec.Type = EST_Unevaluated;
9307 EPI.ExceptionSpec.SourceDecl = FD;
9308 FD->setType(Context.getFunctionType(ResultTy: FPT->getReturnType(),
9309 Args: FPT->getParamTypes(), EPI));
9310 }
9311
9312 return false;
9313}
9314
9315void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
9316 FunctionDecl *Spaceship) {
9317 Sema::CodeSynthesisContext Ctx;
9318 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison;
9319 Ctx.PointOfInstantiation = Spaceship->getEndLoc();
9320 Ctx.Entity = Spaceship;
9321 pushCodeSynthesisContext(Ctx);
9322
9323 if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship))
9324 EqualEqual->setImplicit();
9325
9326 popCodeSynthesisContext();
9327}
9328
9329void Sema::DefineDefaultedComparison(SourceLocation UseLoc, FunctionDecl *FD,
9330 DefaultedComparisonKind DCK) {
9331 assert(FD->isDefaulted() && !FD->isDeleted() &&
9332 !FD->doesThisDeclarationHaveABody());
9333 if (FD->willHaveBody() || FD->isInvalidDecl())
9334 return;
9335
9336 SynthesizedFunctionScope Scope(*this, FD);
9337
9338 // Add a context note for diagnostics produced after this point.
9339 Scope.addContextNote(UseLoc);
9340
9341 {
9342 // Build and set up the function body.
9343 // The first parameter has type maybe-ref-to maybe-const T, use that to get
9344 // the type of the class being compared.
9345 auto PT = FD->getParamDecl(i: 0)->getType();
9346 CXXRecordDecl *RD = PT.getNonReferenceType()->getAsCXXRecordDecl();
9347 SourceLocation BodyLoc =
9348 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
9349 StmtResult Body =
9350 DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build();
9351 if (Body.isInvalid()) {
9352 FD->setInvalidDecl();
9353 return;
9354 }
9355 FD->setBody(Body.get());
9356 FD->markUsed(C&: Context);
9357 }
9358
9359 // The exception specification is needed because we are defining the
9360 // function. Note that this will reuse the body we just built.
9361 ResolveExceptionSpec(Loc: UseLoc, FPT: FD->getType()->castAs<FunctionProtoType>());
9362
9363 if (ASTMutationListener *L = getASTMutationListener())
9364 L->CompletedImplicitDefinition(D: FD);
9365}
9366
9367static Sema::ImplicitExceptionSpecification
9368ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
9369 FunctionDecl *FD,
9370 Sema::DefaultedComparisonKind DCK) {
9371 ComputingExceptionSpec CES(S, FD, Loc);
9372 Sema::ImplicitExceptionSpecification ExceptSpec(S);
9373
9374 if (FD->isInvalidDecl())
9375 return ExceptSpec;
9376
9377 // The common case is that we just defined the comparison function. In that
9378 // case, just look at whether the body can throw.
9379 if (FD->hasBody()) {
9380 ExceptSpec.CalledStmt(S: FD->getBody());
9381 } else {
9382 // Otherwise, build a body so we can check it. This should ideally only
9383 // happen when we're not actually marking the function referenced. (This is
9384 // only really important for efficiency: we don't want to build and throw
9385 // away bodies for comparison functions more than we strictly need to.)
9386
9387 // Pretend to synthesize the function body in an unevaluated context.
9388 // Note that we can't actually just go ahead and define the function here:
9389 // we are not permitted to mark its callees as referenced.
9390 Sema::SynthesizedFunctionScope Scope(S, FD);
9391 EnterExpressionEvaluationContext Context(
9392 S, Sema::ExpressionEvaluationContext::Unevaluated);
9393
9394 CXXRecordDecl *RD =
9395 cast<CXXRecordDecl>(Val: FD->getFriendObjectKind() == Decl::FOK_None
9396 ? FD->getDeclContext()
9397 : FD->getLexicalDeclContext());
9398 SourceLocation BodyLoc =
9399 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
9400 StmtResult Body =
9401 DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build();
9402 if (!Body.isInvalid())
9403 ExceptSpec.CalledStmt(S: Body.get());
9404
9405 // FIXME: Can we hold onto this body and just transform it to potentially
9406 // evaluated when we're asked to define the function rather than rebuilding
9407 // it? Either that, or we should only build the bits of the body that we
9408 // need (the expressions, not the statements).
9409 }
9410
9411 return ExceptSpec;
9412}
9413
9414void Sema::CheckDelayedMemberExceptionSpecs() {
9415 decltype(DelayedOverridingExceptionSpecChecks) Overriding;
9416 decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
9417
9418 std::swap(LHS&: Overriding, RHS&: DelayedOverridingExceptionSpecChecks);
9419 std::swap(LHS&: Equivalent, RHS&: DelayedEquivalentExceptionSpecChecks);
9420
9421 // Perform any deferred checking of exception specifications for virtual
9422 // destructors.
9423 for (auto &Check : Overriding)
9424 CheckOverridingFunctionExceptionSpec(New: Check.first, Old: Check.second);
9425
9426 // Perform any deferred checking of exception specifications for befriended
9427 // special members.
9428 for (auto &Check : Equivalent)
9429 CheckEquivalentExceptionSpec(Old: Check.second, New: Check.first);
9430}
9431
9432namespace {
9433/// CRTP base class for visiting operations performed by a special member
9434/// function (or inherited constructor).
9435template<typename Derived>
9436struct SpecialMemberVisitor {
9437 Sema &S;
9438 CXXMethodDecl *MD;
9439 CXXSpecialMemberKind CSM;
9440 Sema::InheritedConstructorInfo *ICI;
9441
9442 // Properties of the special member, computed for convenience.
9443 bool IsConstructor = false, IsAssignment = false, ConstArg = false;
9444
9445 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, CXXSpecialMemberKind CSM,
9446 Sema::InheritedConstructorInfo *ICI)
9447 : S(S), MD(MD), CSM(CSM), ICI(ICI) {
9448 switch (CSM) {
9449 case CXXSpecialMemberKind::DefaultConstructor:
9450 case CXXSpecialMemberKind::CopyConstructor:
9451 case CXXSpecialMemberKind::MoveConstructor:
9452 IsConstructor = true;
9453 break;
9454 case CXXSpecialMemberKind::CopyAssignment:
9455 case CXXSpecialMemberKind::MoveAssignment:
9456 IsAssignment = true;
9457 break;
9458 case CXXSpecialMemberKind::Destructor:
9459 break;
9460 case CXXSpecialMemberKind::Invalid:
9461 llvm_unreachable("invalid special member kind");
9462 }
9463
9464 if (MD->getNumExplicitParams()) {
9465 if (const ReferenceType *RT =
9466 MD->getNonObjectParameter(I: 0)->getType()->getAs<ReferenceType>())
9467 ConstArg = RT->getPointeeType().isConstQualified();
9468 }
9469 }
9470
9471 Derived &getDerived() { return static_cast<Derived&>(*this); }
9472
9473 /// Is this a "move" special member?
9474 bool isMove() const {
9475 return CSM == CXXSpecialMemberKind::MoveConstructor ||
9476 CSM == CXXSpecialMemberKind::MoveAssignment;
9477 }
9478
9479 /// Look up the corresponding special member in the given class.
9480 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
9481 unsigned Quals, bool IsMutable) {
9482 return lookupCallFromSpecialMember(S, Class, CSM, FieldQuals: Quals,
9483 ConstRHS: ConstArg && !IsMutable);
9484 }
9485
9486 /// Look up the constructor for the specified base class to see if it's
9487 /// overridden due to this being an inherited constructor.
9488 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
9489 if (!ICI)
9490 return {};
9491 assert(CSM == CXXSpecialMemberKind::DefaultConstructor);
9492 auto *BaseCtor =
9493 cast<CXXConstructorDecl>(Val: MD)->getInheritedConstructor().getConstructor();
9494 if (auto *MD = ICI->findConstructorForBase(Base: Class, Ctor: BaseCtor).first)
9495 return MD;
9496 return {};
9497 }
9498
9499 /// A base or member subobject.
9500 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
9501
9502 /// Get the location to use for a subobject in diagnostics.
9503 static SourceLocation getSubobjectLoc(Subobject Subobj) {
9504 // FIXME: For an indirect virtual base, the direct base leading to
9505 // the indirect virtual base would be a more useful choice.
9506 if (auto *B = dyn_cast<CXXBaseSpecifier *>(Val&: Subobj))
9507 return B->getBaseTypeLoc();
9508 else
9509 return cast<FieldDecl *>(Val&: Subobj)->getLocation();
9510 }
9511
9512 enum BasesToVisit {
9513 /// Visit all non-virtual (direct) bases.
9514 VisitNonVirtualBases,
9515 /// Visit all direct bases, virtual or not.
9516 VisitDirectBases,
9517 /// Visit all non-virtual bases, and all virtual bases if the class
9518 /// is not abstract.
9519 VisitPotentiallyConstructedBases,
9520 /// Visit all direct or virtual bases.
9521 VisitAllBases
9522 };
9523
9524 // Visit the bases and members of the class.
9525 bool visit(BasesToVisit Bases) {
9526 CXXRecordDecl *RD = MD->getParent();
9527
9528 if (Bases == VisitPotentiallyConstructedBases)
9529 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
9530
9531 for (auto &B : RD->bases())
9532 if ((Bases == VisitDirectBases || !B.isVirtual()) &&
9533 getDerived().visitBase(&B))
9534 return true;
9535
9536 if (Bases == VisitAllBases)
9537 for (auto &B : RD->vbases())
9538 if (getDerived().visitBase(&B))
9539 return true;
9540
9541 for (auto *F : RD->fields())
9542 if (!F->isInvalidDecl() && !F->isUnnamedBitField() &&
9543 getDerived().visitField(F))
9544 return true;
9545
9546 return false;
9547 }
9548};
9549}
9550
9551namespace {
9552struct SpecialMemberDeletionInfo
9553 : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
9554 bool Diagnose;
9555
9556 SourceLocation Loc;
9557
9558 bool AllFieldsAreConst;
9559
9560 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
9561 CXXSpecialMemberKind CSM,
9562 Sema::InheritedConstructorInfo *ICI, bool Diagnose)
9563 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
9564 Loc(MD->getLocation()), AllFieldsAreConst(true) {}
9565
9566 bool inUnion() const { return MD->getParent()->isUnion(); }
9567
9568 CXXSpecialMemberKind getEffectiveCSM() {
9569 return ICI ? CXXSpecialMemberKind::Invalid : CSM;
9570 }
9571
9572 bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
9573
9574 bool shouldDeleteForVariantPtrAuthMember(const FieldDecl *FD);
9575
9576 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
9577 bool visitField(FieldDecl *Field) { return shouldDeleteForField(FD: Field); }
9578
9579 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
9580 bool shouldDeleteForField(FieldDecl *FD);
9581 bool shouldDeleteForAllConstMembers();
9582
9583 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
9584 unsigned Quals);
9585 bool shouldDeleteForSubobjectCall(Subobject Subobj,
9586 Sema::SpecialMemberOverloadResult SMOR,
9587 bool IsDtorCallInCtor);
9588
9589 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
9590};
9591}
9592
9593/// Is the given special member inaccessible when used on the given
9594/// sub-object.
9595bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
9596 CXXMethodDecl *target) {
9597 /// If we're operating on a base class, the object type is the
9598 /// type of this special member.
9599 CanQualType objectTy;
9600 AccessSpecifier access = target->getAccess();
9601 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
9602 objectTy = S.Context.getCanonicalTagType(TD: MD->getParent());
9603 access = CXXRecordDecl::MergeAccess(PathAccess: base->getAccessSpecifier(), DeclAccess: access);
9604
9605 // If we're operating on a field, the object type is the type of the field.
9606 } else {
9607 objectTy = S.Context.getCanonicalTagType(TD: target->getParent());
9608 }
9609
9610 return S.isMemberAccessibleForDeletion(
9611 NamingClass: target->getParent(), Found: DeclAccessPair::make(D: target, AS: access), ObjectType: objectTy);
9612}
9613
9614/// Check whether we should delete a special member due to the implicit
9615/// definition containing a call to a special member of a subobject.
9616bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
9617 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
9618 bool IsDtorCallInCtor) {
9619 CXXMethodDecl *Decl = SMOR.getMethod();
9620 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9621
9622 enum {
9623 NotSet = -1,
9624 NoDecl,
9625 DeletedDecl,
9626 MultipleDecl,
9627 InaccessibleDecl,
9628 NonTrivialDecl
9629 } DiagKind = NotSet;
9630
9631 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) {
9632 if (CSM == CXXSpecialMemberKind::DefaultConstructor && Field &&
9633 Field->getParent()->isUnion()) {
9634 // [class.default.ctor]p2:
9635 // A defaulted default constructor for class X is defined as deleted if
9636 // - X is a union that has a variant member with a non-trivial default
9637 // constructor and no variant member of X has a default member
9638 // initializer
9639 const auto *RD = cast<CXXRecordDecl>(Val: Field->getParent());
9640 if (RD->hasInClassInitializer())
9641 return false;
9642 }
9643 DiagKind = !Decl ? NoDecl : DeletedDecl;
9644 } else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
9645 DiagKind = MultipleDecl;
9646 else if (!isAccessible(Subobj, target: Decl))
9647 DiagKind = InaccessibleDecl;
9648 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
9649 !Decl->isTrivial()) {
9650 // A member of a union must have a trivial corresponding special member.
9651 // As a weird special case, a destructor call from a union's constructor
9652 // must be accessible and non-deleted, but need not be trivial. Such a
9653 // destructor is never actually called, but is semantically checked as
9654 // if it were.
9655 if (CSM == CXXSpecialMemberKind::DefaultConstructor) {
9656 // [class.default.ctor]p2:
9657 // A defaulted default constructor for class X is defined as deleted if
9658 // - X is a union that has a variant member with a non-trivial default
9659 // constructor and no variant member of X has a default member
9660 // initializer
9661 const auto *RD = cast<CXXRecordDecl>(Val: Field->getParent());
9662 if (!RD->hasInClassInitializer())
9663 DiagKind = NonTrivialDecl;
9664 } else {
9665 DiagKind = NonTrivialDecl;
9666 }
9667 }
9668
9669 if (DiagKind == NotSet)
9670 return false;
9671
9672 if (Diagnose) {
9673 if (Field) {
9674 S.Diag(Loc: Field->getLocation(),
9675 DiagID: diag::note_deleted_special_member_class_subobject)
9676 << getEffectiveCSM() << MD->getParent() << /*IsField*/ true << Field
9677 << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/ false;
9678 } else {
9679 CXXBaseSpecifier *Base = cast<CXXBaseSpecifier *>(Val&: Subobj);
9680 S.Diag(Loc: Base->getBeginLoc(),
9681 DiagID: diag::note_deleted_special_member_class_subobject)
9682 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9683 << Base->getType() << DiagKind << IsDtorCallInCtor
9684 << /*IsObjCPtr*/ false;
9685 }
9686
9687 if (DiagKind == DeletedDecl)
9688 S.NoteDeletedFunction(FD: Decl);
9689 // FIXME: Explain inaccessibility if DiagKind == InaccessibleDecl.
9690 }
9691
9692 return true;
9693}
9694
9695/// Check whether we should delete a special member function due to having a
9696/// direct or virtual base class or non-static data member of class type M.
9697bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
9698 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
9699 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9700 bool IsMutable = Field && Field->isMutable();
9701
9702 // C++11 [class.ctor]p5:
9703 // -- any direct or virtual base class, or non-static data member with no
9704 // brace-or-equal-initializer, has class type M (or array thereof) and
9705 // either M has no default constructor or overload resolution as applied
9706 // to M's default constructor results in an ambiguity or in a function
9707 // that is deleted or inaccessible
9708 // C++11 [class.copy]p11, C++11 [class.copy]p23:
9709 // -- a direct or virtual base class B that cannot be copied/moved because
9710 // overload resolution, as applied to B's corresponding special member,
9711 // results in an ambiguity or a function that is deleted or inaccessible
9712 // from the defaulted special member
9713 // C++11 [class.dtor]p5:
9714 // -- any direct or virtual base class [...] has a type with a destructor
9715 // that is deleted or inaccessible
9716 if (!(CSM == CXXSpecialMemberKind::DefaultConstructor && Field &&
9717 Field->hasInClassInitializer()) &&
9718 shouldDeleteForSubobjectCall(Subobj, SMOR: lookupIn(Class, Quals, IsMutable),
9719 IsDtorCallInCtor: false))
9720 return true;
9721
9722 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
9723 // -- any direct or virtual base class or non-static data member has a
9724 // type with a destructor that is deleted or inaccessible
9725 if (IsConstructor) {
9726 Sema::SpecialMemberOverloadResult SMOR =
9727 S.LookupSpecialMember(D: Class, SM: CXXSpecialMemberKind::Destructor, ConstArg: false,
9728 VolatileArg: false, RValueThis: false, ConstThis: false, VolatileThis: false);
9729 if (shouldDeleteForSubobjectCall(Subobj, SMOR, IsDtorCallInCtor: true))
9730 return true;
9731 }
9732
9733 return false;
9734}
9735
9736bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
9737 FieldDecl *FD, QualType FieldType) {
9738 // The defaulted special functions are defined as deleted if this is a variant
9739 // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
9740 // type under ARC.
9741 if (!FieldType.hasNonTrivialObjCLifetime())
9742 return false;
9743
9744 // Don't make the defaulted default constructor defined as deleted if the
9745 // member has an in-class initializer.
9746 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
9747 FD->hasInClassInitializer())
9748 return false;
9749
9750 if (Diagnose) {
9751 auto *ParentClass = cast<CXXRecordDecl>(Val: FD->getParent());
9752 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_deleted_special_member_class_subobject)
9753 << getEffectiveCSM() << ParentClass << /*IsField*/ true << FD << 4
9754 << /*IsDtorCallInCtor*/ false << /*IsObjCPtr*/ true;
9755 }
9756
9757 return true;
9758}
9759
9760bool SpecialMemberDeletionInfo::shouldDeleteForVariantPtrAuthMember(
9761 const FieldDecl *FD) {
9762 QualType FieldType = S.Context.getBaseElementType(QT: FD->getType());
9763 // Copy/move constructors/assignment operators are deleted if the field has an
9764 // address-discriminated ptrauth qualifier.
9765 PointerAuthQualifier Q = FieldType.getPointerAuth();
9766
9767 if (!Q || !Q.isAddressDiscriminated())
9768 return false;
9769
9770 if (CSM == CXXSpecialMemberKind::DefaultConstructor ||
9771 CSM == CXXSpecialMemberKind::Destructor)
9772 return false;
9773
9774 if (Diagnose) {
9775 auto *ParentClass = cast<CXXRecordDecl>(Val: FD->getParent());
9776 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_deleted_special_member_class_subobject)
9777 << getEffectiveCSM() << ParentClass << /*IsField*/ true << FD << 4
9778 << /*IsDtorCallInCtor*/ false << 2;
9779 }
9780
9781 return true;
9782}
9783
9784/// Check whether we should delete a special member function due to the class
9785/// having a particular direct or virtual base class.
9786bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
9787 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
9788 // If program is correct, BaseClass cannot be null, but if it is, the error
9789 // must be reported elsewhere.
9790 if (!BaseClass)
9791 return false;
9792 // If we have an inheriting constructor, check whether we're calling an
9793 // inherited constructor instead of a default constructor.
9794 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(Class: BaseClass);
9795 if (auto *BaseCtor = SMOR.getMethod()) {
9796 // Note that we do not check access along this path; other than that,
9797 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
9798 // FIXME: Check that the base has a usable destructor! Sink this into
9799 // shouldDeleteForClassSubobject.
9800 if (BaseCtor->isDeleted() && Diagnose) {
9801 S.Diag(Loc: Base->getBeginLoc(),
9802 DiagID: diag::note_deleted_special_member_class_subobject)
9803 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9804 << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
9805 << /*IsObjCPtr*/ false;
9806 S.NoteDeletedFunction(FD: BaseCtor);
9807 }
9808 return BaseCtor->isDeleted();
9809 }
9810 return shouldDeleteForClassSubobject(Class: BaseClass, Subobj: Base, Quals: 0);
9811}
9812
9813/// Check whether we should delete a special member function due to the class
9814/// having a particular non-static data member.
9815bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
9816 QualType FieldType = S.Context.getBaseElementType(QT: FD->getType());
9817 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
9818
9819 if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
9820 return true;
9821
9822 if (inUnion() && shouldDeleteForVariantPtrAuthMember(FD))
9823 return true;
9824
9825 if (CSM == CXXSpecialMemberKind::DefaultConstructor) {
9826 // For a default constructor, all references must be initialized in-class
9827 // and, if a union, it must have a non-const member.
9828 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
9829 if (Diagnose)
9830 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_deleted_default_ctor_uninit_field)
9831 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
9832 return true;
9833 }
9834 // C++11 [class.ctor]p5 (modified by DR2394): any non-variant non-static
9835 // data member of const-qualified type (or array thereof) with no
9836 // brace-or-equal-initializer is not const-default-constructible.
9837 if (!inUnion() && FieldType.isConstQualified() &&
9838 !FD->hasInClassInitializer() &&
9839 (!FieldRecord || !FieldRecord->allowConstDefaultInit())) {
9840 if (Diagnose)
9841 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_deleted_default_ctor_uninit_field)
9842 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
9843 return true;
9844 }
9845
9846 if (inUnion() && !FieldType.isConstQualified())
9847 AllFieldsAreConst = false;
9848 } else if (CSM == CXXSpecialMemberKind::CopyConstructor) {
9849 // For a copy constructor, data members must not be of rvalue reference
9850 // type.
9851 if (FieldType->isRValueReferenceType()) {
9852 if (Diagnose)
9853 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_deleted_copy_ctor_rvalue_reference)
9854 << MD->getParent() << FD << FieldType;
9855 return true;
9856 }
9857 } else if (IsAssignment) {
9858 // For an assignment operator, data members must not be of reference type.
9859 if (FieldType->isReferenceType()) {
9860 if (Diagnose)
9861 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_deleted_assign_field)
9862 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
9863 return true;
9864 }
9865 if (!FieldRecord && FieldType.isConstQualified()) {
9866 // C++11 [class.copy]p23:
9867 // -- a non-static data member of const non-class type (or array thereof)
9868 if (Diagnose)
9869 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_deleted_assign_field)
9870 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
9871 return true;
9872 }
9873 }
9874
9875 if (FieldRecord) {
9876 // Some additional restrictions exist on the variant members.
9877 if (!inUnion() && FieldRecord->isUnion() &&
9878 FieldRecord->isAnonymousStructOrUnion()) {
9879 bool AllVariantFieldsAreConst = true;
9880
9881 // FIXME: Handle anonymous unions declared within anonymous unions.
9882 for (auto *UI : FieldRecord->fields()) {
9883 QualType UnionFieldType = S.Context.getBaseElementType(QT: UI->getType());
9884
9885 if (shouldDeleteForVariantObjCPtrMember(FD: &*UI, FieldType: UnionFieldType))
9886 return true;
9887
9888 if (shouldDeleteForVariantPtrAuthMember(FD: &*UI))
9889 return true;
9890
9891 if (!UnionFieldType.isConstQualified())
9892 AllVariantFieldsAreConst = false;
9893
9894 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
9895 if (UnionFieldRecord &&
9896 shouldDeleteForClassSubobject(Class: UnionFieldRecord, Subobj: UI,
9897 Quals: UnionFieldType.getCVRQualifiers()))
9898 return true;
9899 }
9900
9901 // At least one member in each anonymous union must be non-const
9902 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
9903 AllVariantFieldsAreConst && !FieldRecord->field_empty()) {
9904 if (Diagnose)
9905 S.Diag(Loc: FieldRecord->getLocation(),
9906 DiagID: diag::note_deleted_default_ctor_all_const)
9907 << !!ICI << MD->getParent() << /*anonymous union*/1;
9908 return true;
9909 }
9910
9911 // Don't check the implicit member of the anonymous union type.
9912 // This is technically non-conformant but supported, and we have a
9913 // diagnostic for this elsewhere.
9914 return false;
9915 }
9916
9917 if (shouldDeleteForClassSubobject(Class: FieldRecord, Subobj: FD,
9918 Quals: FieldType.getCVRQualifiers()))
9919 return true;
9920 }
9921
9922 return false;
9923}
9924
9925/// C++11 [class.ctor] p5:
9926/// A defaulted default constructor for a class X is defined as deleted if
9927/// X is a union and all of its variant members are of const-qualified type.
9928bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
9929 // This is a silly definition, because it gives an empty union a deleted
9930 // default constructor. Don't do that.
9931 if (CSM == CXXSpecialMemberKind::DefaultConstructor && inUnion() &&
9932 AllFieldsAreConst) {
9933 bool AnyFields = false;
9934 for (auto *F : MD->getParent()->fields())
9935 if ((AnyFields = !F->isUnnamedBitField()))
9936 break;
9937 if (!AnyFields)
9938 return false;
9939 if (Diagnose)
9940 S.Diag(Loc: MD->getParent()->getLocation(),
9941 DiagID: diag::note_deleted_default_ctor_all_const)
9942 << !!ICI << MD->getParent() << /*not anonymous union*/0;
9943 return true;
9944 }
9945 return false;
9946}
9947
9948/// Determine whether a defaulted special member function should be defined as
9949/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
9950/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
9951bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD,
9952 CXXSpecialMemberKind CSM,
9953 InheritedConstructorInfo *ICI,
9954 bool Diagnose) {
9955 if (MD->isInvalidDecl())
9956 return false;
9957 CXXRecordDecl *RD = MD->getParent();
9958 assert(!RD->isDependentType() && "do deletion after instantiation");
9959 if (!LangOpts.CPlusPlus || (!LangOpts.CPlusPlus11 && !RD->isLambda()) ||
9960 RD->isInvalidDecl())
9961 return false;
9962
9963 // C++11 [expr.lambda.prim]p19:
9964 // The closure type associated with a lambda-expression has a
9965 // deleted (8.4.3) default constructor and a deleted copy
9966 // assignment operator.
9967 // C++2a adds back these operators if the lambda has no lambda-capture.
9968 if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() &&
9969 (CSM == CXXSpecialMemberKind::DefaultConstructor ||
9970 CSM == CXXSpecialMemberKind::CopyAssignment)) {
9971 if (Diagnose)
9972 Diag(Loc: RD->getLocation(), DiagID: diag::note_lambda_decl);
9973 return true;
9974 }
9975
9976 // C++11 [class.copy]p7, p18:
9977 // If the class definition declares a move constructor or move assignment
9978 // operator, an implicitly declared copy constructor or copy assignment
9979 // operator is defined as deleted.
9980 if (MD->isImplicit() && (CSM == CXXSpecialMemberKind::CopyConstructor ||
9981 CSM == CXXSpecialMemberKind::CopyAssignment)) {
9982 CXXMethodDecl *UserDeclaredMove = nullptr;
9983
9984 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
9985 // deletion of the corresponding copy operation, not both copy operations.
9986 // MSVC 2015 has adopted the standards conforming behavior.
9987 bool DeletesOnlyMatchingCopy =
9988 getLangOpts().MSVCCompat &&
9989 !getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015);
9990
9991 if (RD->hasUserDeclaredMoveConstructor() &&
9992 (!DeletesOnlyMatchingCopy ||
9993 CSM == CXXSpecialMemberKind::CopyConstructor)) {
9994 if (!Diagnose) return true;
9995
9996 // Find any user-declared move constructor.
9997 for (auto *I : RD->ctors()) {
9998 if (I->isMoveConstructor()) {
9999 UserDeclaredMove = I;
10000 break;
10001 }
10002 }
10003 assert(UserDeclaredMove);
10004 } else if (RD->hasUserDeclaredMoveAssignment() &&
10005 (!DeletesOnlyMatchingCopy ||
10006 CSM == CXXSpecialMemberKind::CopyAssignment)) {
10007 if (!Diagnose) return true;
10008
10009 // Find any user-declared move assignment operator.
10010 for (auto *I : RD->methods()) {
10011 if (I->isMoveAssignmentOperator()) {
10012 UserDeclaredMove = I;
10013 break;
10014 }
10015 }
10016 assert(UserDeclaredMove);
10017 }
10018
10019 if (UserDeclaredMove) {
10020 Diag(Loc: UserDeclaredMove->getLocation(),
10021 DiagID: diag::note_deleted_copy_user_declared_move)
10022 << (CSM == CXXSpecialMemberKind::CopyAssignment) << RD
10023 << UserDeclaredMove->isMoveAssignmentOperator();
10024 return true;
10025 }
10026 }
10027
10028 // Do access control from the special member function
10029 ContextRAII MethodContext(*this, MD);
10030
10031 // C++11 [class.dtor]p5:
10032 // -- for a virtual destructor, lookup of the non-array deallocation function
10033 // results in an ambiguity or in a function that is deleted or inaccessible
10034 if (CSM == CXXSpecialMemberKind::Destructor && MD->isVirtual()) {
10035 FunctionDecl *OperatorDelete = nullptr;
10036 CanQualType DeallocType = Context.getCanonicalTagType(TD: RD);
10037 DeclarationName Name =
10038 Context.DeclarationNames.getCXXOperatorName(Op: OO_Delete);
10039 ImplicitDeallocationParameters IDP = {
10040 DeallocType, ShouldUseTypeAwareOperatorNewOrDelete(),
10041 AlignedAllocationMode::No, SizedDeallocationMode::No};
10042 if (FindDeallocationFunction(StartLoc: MD->getLocation(), RD: MD->getParent(), Name,
10043 Operator&: OperatorDelete, IDP,
10044 /*Diagnose=*/false)) {
10045 if (Diagnose)
10046 Diag(Loc: RD->getLocation(), DiagID: diag::note_deleted_dtor_no_operator_delete);
10047 return true;
10048 }
10049 }
10050
10051 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
10052
10053 // Per DR1611, do not consider virtual bases of constructors of abstract
10054 // classes, since we are not going to construct them.
10055 // Per DR1658, do not consider virtual bases of destructors of abstract
10056 // classes either.
10057 // Per DR2180, for assignment operators we only assign (and thus only
10058 // consider) direct bases.
10059 if (SMI.visit(Bases: SMI.IsAssignment ? SMI.VisitDirectBases
10060 : SMI.VisitPotentiallyConstructedBases))
10061 return true;
10062
10063 if (SMI.shouldDeleteForAllConstMembers())
10064 return true;
10065
10066 if (getLangOpts().CUDA) {
10067 // We should delete the special member in CUDA mode if target inference
10068 // failed.
10069 // For inherited constructors (non-null ICI), CSM may be passed so that MD
10070 // is treated as certain special member, which may not reflect what special
10071 // member MD really is. However inferTargetForImplicitSpecialMember
10072 // expects CSM to match MD, therefore recalculate CSM.
10073 assert(ICI || CSM == getSpecialMember(MD));
10074 auto RealCSM = CSM;
10075 if (ICI)
10076 RealCSM = getSpecialMember(MD);
10077
10078 return CUDA().inferTargetForImplicitSpecialMember(ClassDecl: RD, CSM: RealCSM, MemberDecl: MD,
10079 ConstRHS: SMI.ConstArg, Diagnose);
10080 }
10081
10082 return false;
10083}
10084
10085void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl *FD) {
10086 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
10087 assert(DFK && "not a defaultable function");
10088 assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted");
10089
10090 if (DFK.isSpecialMember()) {
10091 ShouldDeleteSpecialMember(MD: cast<CXXMethodDecl>(Val: FD), CSM: DFK.asSpecialMember(),
10092 ICI: nullptr, /*Diagnose=*/true);
10093 } else {
10094 DefaultedComparisonAnalyzer(
10095 *this, cast<CXXRecordDecl>(Val: FD->getLexicalDeclContext()), FD,
10096 DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted)
10097 .visit();
10098 }
10099}
10100
10101/// Perform lookup for a special member of the specified kind, and determine
10102/// whether it is trivial. If the triviality can be determined without the
10103/// lookup, skip it. This is intended for use when determining whether a
10104/// special member of a containing object is trivial, and thus does not ever
10105/// perform overload resolution for default constructors.
10106///
10107/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
10108/// member that was most likely to be intended to be trivial, if any.
10109///
10110/// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
10111/// determine whether the special member is trivial.
10112static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
10113 CXXSpecialMemberKind CSM, unsigned Quals,
10114 bool ConstRHS, TrivialABIHandling TAH,
10115 CXXMethodDecl **Selected) {
10116 if (Selected)
10117 *Selected = nullptr;
10118
10119 switch (CSM) {
10120 case CXXSpecialMemberKind::Invalid:
10121 llvm_unreachable("not a special member");
10122
10123 case CXXSpecialMemberKind::DefaultConstructor:
10124 // C++11 [class.ctor]p5:
10125 // A default constructor is trivial if:
10126 // - all the [direct subobjects] have trivial default constructors
10127 //
10128 // Note, no overload resolution is performed in this case.
10129 if (RD->hasTrivialDefaultConstructor())
10130 return true;
10131
10132 if (Selected) {
10133 // If there's a default constructor which could have been trivial, dig it
10134 // out. Otherwise, if there's any user-provided default constructor, point
10135 // to that as an example of why there's not a trivial one.
10136 CXXConstructorDecl *DefCtor = nullptr;
10137 if (RD->needsImplicitDefaultConstructor())
10138 S.DeclareImplicitDefaultConstructor(ClassDecl: RD);
10139 for (auto *CI : RD->ctors()) {
10140 if (!CI->isDefaultConstructor())
10141 continue;
10142 DefCtor = CI;
10143 if (!DefCtor->isUserProvided())
10144 break;
10145 }
10146
10147 *Selected = DefCtor;
10148 }
10149
10150 return false;
10151
10152 case CXXSpecialMemberKind::Destructor:
10153 // C++11 [class.dtor]p5:
10154 // A destructor is trivial if:
10155 // - all the direct [subobjects] have trivial destructors
10156 if (RD->hasTrivialDestructor() ||
10157 (TAH == TrivialABIHandling::ConsiderTrivialABI &&
10158 RD->hasTrivialDestructorForCall()))
10159 return true;
10160
10161 if (Selected) {
10162 if (RD->needsImplicitDestructor())
10163 S.DeclareImplicitDestructor(ClassDecl: RD);
10164 *Selected = RD->getDestructor();
10165 }
10166
10167 return false;
10168
10169 case CXXSpecialMemberKind::CopyConstructor:
10170 // C++11 [class.copy]p12:
10171 // A copy constructor is trivial if:
10172 // - the constructor selected to copy each direct [subobject] is trivial
10173 if (RD->hasTrivialCopyConstructor() ||
10174 (TAH == TrivialABIHandling::ConsiderTrivialABI &&
10175 RD->hasTrivialCopyConstructorForCall())) {
10176 if (Quals == Qualifiers::Const)
10177 // We must either select the trivial copy constructor or reach an
10178 // ambiguity; no need to actually perform overload resolution.
10179 return true;
10180 } else if (!Selected) {
10181 return false;
10182 }
10183 // In C++98, we are not supposed to perform overload resolution here, but we
10184 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
10185 // cases like B as having a non-trivial copy constructor:
10186 // struct A { template<typename T> A(T&); };
10187 // struct B { mutable A a; };
10188 goto NeedOverloadResolution;
10189
10190 case CXXSpecialMemberKind::CopyAssignment:
10191 // C++11 [class.copy]p25:
10192 // A copy assignment operator is trivial if:
10193 // - the assignment operator selected to copy each direct [subobject] is
10194 // trivial
10195 if (RD->hasTrivialCopyAssignment()) {
10196 if (Quals == Qualifiers::Const)
10197 return true;
10198 } else if (!Selected) {
10199 return false;
10200 }
10201 // In C++98, we are not supposed to perform overload resolution here, but we
10202 // treat that as a language defect.
10203 goto NeedOverloadResolution;
10204
10205 case CXXSpecialMemberKind::MoveConstructor:
10206 case CXXSpecialMemberKind::MoveAssignment:
10207 NeedOverloadResolution:
10208 Sema::SpecialMemberOverloadResult SMOR =
10209 lookupCallFromSpecialMember(S, Class: RD, CSM, FieldQuals: Quals, ConstRHS);
10210
10211 // The standard doesn't describe how to behave if the lookup is ambiguous.
10212 // We treat it as not making the member non-trivial, just like the standard
10213 // mandates for the default constructor. This should rarely matter, because
10214 // the member will also be deleted.
10215 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
10216 return true;
10217
10218 if (!SMOR.getMethod()) {
10219 assert(SMOR.getKind() ==
10220 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
10221 return false;
10222 }
10223
10224 // We deliberately don't check if we found a deleted special member. We're
10225 // not supposed to!
10226 if (Selected)
10227 *Selected = SMOR.getMethod();
10228
10229 if (TAH == TrivialABIHandling::ConsiderTrivialABI &&
10230 (CSM == CXXSpecialMemberKind::CopyConstructor ||
10231 CSM == CXXSpecialMemberKind::MoveConstructor))
10232 return SMOR.getMethod()->isTrivialForCall();
10233 return SMOR.getMethod()->isTrivial();
10234 }
10235
10236 llvm_unreachable("unknown special method kind");
10237}
10238
10239static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
10240 for (auto *CI : RD->ctors())
10241 if (!CI->isImplicit())
10242 return CI;
10243
10244 // Look for constructor templates.
10245 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
10246 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
10247 if (CXXConstructorDecl *CD =
10248 dyn_cast<CXXConstructorDecl>(Val: TI->getTemplatedDecl()))
10249 return CD;
10250 }
10251
10252 return nullptr;
10253}
10254
10255/// The kind of subobject we are checking for triviality. The values of this
10256/// enumeration are used in diagnostics.
10257enum TrivialSubobjectKind {
10258 /// The subobject is a base class.
10259 TSK_BaseClass,
10260 /// The subobject is a non-static data member.
10261 TSK_Field,
10262 /// The object is actually the complete object.
10263 TSK_CompleteObject
10264};
10265
10266/// Check whether the special member selected for a given type would be trivial.
10267static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
10268 QualType SubType, bool ConstRHS,
10269 CXXSpecialMemberKind CSM,
10270 TrivialSubobjectKind Kind,
10271 TrivialABIHandling TAH, bool Diagnose) {
10272 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
10273 if (!SubRD)
10274 return true;
10275
10276 CXXMethodDecl *Selected;
10277 if (findTrivialSpecialMember(S, RD: SubRD, CSM, Quals: SubType.getCVRQualifiers(),
10278 ConstRHS, TAH, Selected: Diagnose ? &Selected : nullptr))
10279 return true;
10280
10281 if (Diagnose) {
10282 if (ConstRHS)
10283 SubType.addConst();
10284
10285 if (!Selected && CSM == CXXSpecialMemberKind::DefaultConstructor) {
10286 S.Diag(Loc: SubobjLoc, DiagID: diag::note_nontrivial_no_def_ctor)
10287 << Kind << SubType.getUnqualifiedType();
10288 if (CXXConstructorDecl *CD = findUserDeclaredCtor(RD: SubRD))
10289 S.Diag(Loc: CD->getLocation(), DiagID: diag::note_user_declared_ctor);
10290 } else if (!Selected)
10291 S.Diag(Loc: SubobjLoc, DiagID: diag::note_nontrivial_no_copy)
10292 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
10293 else if (Selected->isUserProvided()) {
10294 if (Kind == TSK_CompleteObject)
10295 S.Diag(Loc: Selected->getLocation(), DiagID: diag::note_nontrivial_user_provided)
10296 << Kind << SubType.getUnqualifiedType() << CSM;
10297 else {
10298 S.Diag(Loc: SubobjLoc, DiagID: diag::note_nontrivial_user_provided)
10299 << Kind << SubType.getUnqualifiedType() << CSM;
10300 S.Diag(Loc: Selected->getLocation(), DiagID: diag::note_declared_at);
10301 }
10302 } else {
10303 if (Kind != TSK_CompleteObject)
10304 S.Diag(Loc: SubobjLoc, DiagID: diag::note_nontrivial_subobject)
10305 << Kind << SubType.getUnqualifiedType() << CSM;
10306
10307 // Explain why the defaulted or deleted special member isn't trivial.
10308 S.SpecialMemberIsTrivial(MD: Selected, CSM,
10309 TAH: TrivialABIHandling::IgnoreTrivialABI, Diagnose);
10310 }
10311 }
10312
10313 return false;
10314}
10315
10316/// Check whether the members of a class type allow a special member to be
10317/// trivial.
10318static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
10319 CXXSpecialMemberKind CSM, bool ConstArg,
10320 TrivialABIHandling TAH, bool Diagnose) {
10321 for (const auto *FI : RD->fields()) {
10322 if (FI->isInvalidDecl() || FI->isUnnamedBitField())
10323 continue;
10324
10325 QualType FieldType = S.Context.getBaseElementType(QT: FI->getType());
10326
10327 // Pretend anonymous struct or union members are members of this class.
10328 if (FI->isAnonymousStructOrUnion()) {
10329 if (!checkTrivialClassMembers(S, RD: FieldType->getAsCXXRecordDecl(),
10330 CSM, ConstArg, TAH, Diagnose))
10331 return false;
10332 continue;
10333 }
10334
10335 // C++11 [class.ctor]p5:
10336 // A default constructor is trivial if [...]
10337 // -- no non-static data member of its class has a
10338 // brace-or-equal-initializer
10339 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
10340 FI->hasInClassInitializer()) {
10341 if (Diagnose)
10342 S.Diag(Loc: FI->getLocation(), DiagID: diag::note_nontrivial_default_member_init)
10343 << FI;
10344 return false;
10345 }
10346
10347 // Objective C ARC 4.3.5:
10348 // [...] nontrivally ownership-qualified types are [...] not trivially
10349 // default constructible, copy constructible, move constructible, copy
10350 // assignable, move assignable, or destructible [...]
10351 if (FieldType.hasNonTrivialObjCLifetime()) {
10352 if (Diagnose)
10353 S.Diag(Loc: FI->getLocation(), DiagID: diag::note_nontrivial_objc_ownership)
10354 << RD << FieldType.getObjCLifetime();
10355 return false;
10356 }
10357
10358 bool ConstRHS = ConstArg && !FI->isMutable();
10359 if (!checkTrivialSubobjectCall(S, SubobjLoc: FI->getLocation(), SubType: FieldType, ConstRHS,
10360 CSM, Kind: TSK_Field, TAH, Diagnose))
10361 return false;
10362 }
10363
10364 return true;
10365}
10366
10367void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD,
10368 CXXSpecialMemberKind CSM) {
10369 CanQualType Ty = Context.getCanonicalTagType(TD: RD);
10370
10371 bool ConstArg = (CSM == CXXSpecialMemberKind::CopyConstructor ||
10372 CSM == CXXSpecialMemberKind::CopyAssignment);
10373 checkTrivialSubobjectCall(S&: *this, SubobjLoc: RD->getLocation(), SubType: Ty, ConstRHS: ConstArg, CSM,
10374 Kind: TSK_CompleteObject,
10375 TAH: TrivialABIHandling::IgnoreTrivialABI,
10376 /*Diagnose*/ true);
10377}
10378
10379bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMemberKind CSM,
10380 TrivialABIHandling TAH, bool Diagnose) {
10381 assert(!MD->isUserProvided() && CSM != CXXSpecialMemberKind::Invalid &&
10382 "not special enough");
10383
10384 CXXRecordDecl *RD = MD->getParent();
10385
10386 bool ConstArg = false;
10387
10388 // C++11 [class.copy]p12, p25: [DR1593]
10389 // A [special member] is trivial if [...] its parameter-type-list is
10390 // equivalent to the parameter-type-list of an implicit declaration [...]
10391 switch (CSM) {
10392 case CXXSpecialMemberKind::DefaultConstructor:
10393 case CXXSpecialMemberKind::Destructor:
10394 // Trivial default constructors and destructors cannot have parameters.
10395 break;
10396
10397 case CXXSpecialMemberKind::CopyConstructor:
10398 case CXXSpecialMemberKind::CopyAssignment: {
10399 const ParmVarDecl *Param0 = MD->getNonObjectParameter(I: 0);
10400 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
10401
10402 // When ClangABICompat14 is true, CXX copy constructors will only be trivial
10403 // if they are not user-provided and their parameter-type-list is equivalent
10404 // to the parameter-type-list of an implicit declaration. This maintains the
10405 // behavior before dr2171 was implemented.
10406 //
10407 // Otherwise, if ClangABICompat14 is false, All copy constructors can be
10408 // trivial, if they are not user-provided, regardless of the qualifiers on
10409 // the reference type.
10410 const bool ClangABICompat14 = Context.getLangOpts().getClangABICompat() <=
10411 LangOptions::ClangABI::Ver14;
10412 if (!RT ||
10413 ((RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) &&
10414 ClangABICompat14)) {
10415 if (Diagnose)
10416 Diag(Loc: Param0->getLocation(), DiagID: diag::note_nontrivial_param_type)
10417 << Param0->getSourceRange() << Param0->getType()
10418 << Context.getLValueReferenceType(
10419 T: Context.getCanonicalTagType(TD: RD).withConst());
10420 return false;
10421 }
10422
10423 ConstArg = RT->getPointeeType().isConstQualified();
10424 break;
10425 }
10426
10427 case CXXSpecialMemberKind::MoveConstructor:
10428 case CXXSpecialMemberKind::MoveAssignment: {
10429 // Trivial move operations always have non-cv-qualified parameters.
10430 const ParmVarDecl *Param0 = MD->getNonObjectParameter(I: 0);
10431 const RValueReferenceType *RT =
10432 Param0->getType()->getAs<RValueReferenceType>();
10433 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
10434 if (Diagnose)
10435 Diag(Loc: Param0->getLocation(), DiagID: diag::note_nontrivial_param_type)
10436 << Param0->getSourceRange() << Param0->getType()
10437 << Context.getRValueReferenceType(T: Context.getCanonicalTagType(TD: RD));
10438 return false;
10439 }
10440 break;
10441 }
10442
10443 case CXXSpecialMemberKind::Invalid:
10444 llvm_unreachable("not a special member");
10445 }
10446
10447 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
10448 if (Diagnose)
10449 Diag(Loc: MD->getParamDecl(i: MD->getMinRequiredArguments())->getLocation(),
10450 DiagID: diag::note_nontrivial_default_arg)
10451 << MD->getParamDecl(i: MD->getMinRequiredArguments())->getSourceRange();
10452 return false;
10453 }
10454 if (MD->isVariadic()) {
10455 if (Diagnose)
10456 Diag(Loc: MD->getLocation(), DiagID: diag::note_nontrivial_variadic);
10457 return false;
10458 }
10459
10460 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
10461 // A copy/move [constructor or assignment operator] is trivial if
10462 // -- the [member] selected to copy/move each direct base class subobject
10463 // is trivial
10464 //
10465 // C++11 [class.copy]p12, C++11 [class.copy]p25:
10466 // A [default constructor or destructor] is trivial if
10467 // -- all the direct base classes have trivial [default constructors or
10468 // destructors]
10469 for (const auto &BI : RD->bases())
10470 if (!checkTrivialSubobjectCall(S&: *this, SubobjLoc: BI.getBeginLoc(), SubType: BI.getType(),
10471 ConstRHS: ConstArg, CSM, Kind: TSK_BaseClass, TAH, Diagnose))
10472 return false;
10473
10474 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
10475 // A copy/move [constructor or assignment operator] for a class X is
10476 // trivial if
10477 // -- for each non-static data member of X that is of class type (or array
10478 // thereof), the constructor selected to copy/move that member is
10479 // trivial
10480 //
10481 // C++11 [class.copy]p12, C++11 [class.copy]p25:
10482 // A [default constructor or destructor] is trivial if
10483 // -- for all of the non-static data members of its class that are of class
10484 // type (or array thereof), each such class has a trivial [default
10485 // constructor or destructor]
10486 if (!checkTrivialClassMembers(S&: *this, RD, CSM, ConstArg, TAH, Diagnose))
10487 return false;
10488
10489 // C++11 [class.dtor]p5:
10490 // A destructor is trivial if [...]
10491 // -- the destructor is not virtual
10492 if (CSM == CXXSpecialMemberKind::Destructor && MD->isVirtual()) {
10493 if (Diagnose)
10494 Diag(Loc: MD->getLocation(), DiagID: diag::note_nontrivial_virtual_dtor) << RD;
10495 return false;
10496 }
10497
10498 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
10499 // A [special member] for class X is trivial if [...]
10500 // -- class X has no virtual functions and no virtual base classes
10501 if (CSM != CXXSpecialMemberKind::Destructor &&
10502 MD->getParent()->isDynamicClass()) {
10503 if (!Diagnose)
10504 return false;
10505
10506 if (RD->getNumVBases()) {
10507 // Check for virtual bases. We already know that the corresponding
10508 // member in all bases is trivial, so vbases must all be direct.
10509 CXXBaseSpecifier &BS = *RD->vbases_begin();
10510 assert(BS.isVirtual());
10511 Diag(Loc: BS.getBeginLoc(), DiagID: diag::note_nontrivial_has_virtual) << RD << 1;
10512 return false;
10513 }
10514
10515 // Must have a virtual method.
10516 for (const auto *MI : RD->methods()) {
10517 if (MI->isVirtual()) {
10518 SourceLocation MLoc = MI->getBeginLoc();
10519 Diag(Loc: MLoc, DiagID: diag::note_nontrivial_has_virtual) << RD << 0;
10520 return false;
10521 }
10522 }
10523
10524 llvm_unreachable("dynamic class with no vbases and no virtual functions");
10525 }
10526
10527 // Looks like it's trivial!
10528 return true;
10529}
10530
10531namespace {
10532struct FindHiddenVirtualMethod {
10533 Sema *S;
10534 CXXMethodDecl *Method;
10535 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
10536 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10537
10538private:
10539 /// Check whether any most overridden method from MD in Methods
10540 static bool CheckMostOverridenMethods(
10541 const CXXMethodDecl *MD,
10542 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
10543 if (MD->size_overridden_methods() == 0)
10544 return Methods.count(Ptr: MD->getCanonicalDecl());
10545 for (const CXXMethodDecl *O : MD->overridden_methods())
10546 if (CheckMostOverridenMethods(MD: O, Methods))
10547 return true;
10548 return false;
10549 }
10550
10551public:
10552 /// Member lookup function that determines whether a given C++
10553 /// method overloads virtual methods in a base class without overriding any,
10554 /// to be used with CXXRecordDecl::lookupInBases().
10555 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
10556 auto *BaseRecord = Specifier->getType()->castAsRecordDecl();
10557 DeclarationName Name = Method->getDeclName();
10558 assert(Name.getNameKind() == DeclarationName::Identifier);
10559
10560 bool foundSameNameMethod = false;
10561 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
10562 for (Path.Decls = BaseRecord->lookup(Name).begin();
10563 Path.Decls != DeclContext::lookup_iterator(); ++Path.Decls) {
10564 NamedDecl *D = *Path.Decls;
10565 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: D)) {
10566 MD = MD->getCanonicalDecl();
10567 foundSameNameMethod = true;
10568 // Interested only in hidden virtual methods.
10569 if (!MD->isVirtual())
10570 continue;
10571 // If the method we are checking overrides a method from its base
10572 // don't warn about the other overloaded methods. Clang deviates from
10573 // GCC by only diagnosing overloads of inherited virtual functions that
10574 // do not override any other virtual functions in the base. GCC's
10575 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
10576 // function from a base class. These cases may be better served by a
10577 // warning (not specific to virtual functions) on call sites when the
10578 // call would select a different function from the base class, were it
10579 // visible.
10580 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
10581 if (!S->IsOverload(New: Method, Old: MD, UseMemberUsingDeclRules: false))
10582 return true;
10583 // Collect the overload only if its hidden.
10584 if (!CheckMostOverridenMethods(MD, Methods: OverridenAndUsingBaseMethods))
10585 overloadedMethods.push_back(Elt: MD);
10586 }
10587 }
10588
10589 if (foundSameNameMethod)
10590 OverloadedMethods.append(in_start: overloadedMethods.begin(),
10591 in_end: overloadedMethods.end());
10592 return foundSameNameMethod;
10593 }
10594};
10595} // end anonymous namespace
10596
10597/// Add the most overridden methods from MD to Methods
10598static void AddMostOverridenMethods(const CXXMethodDecl *MD,
10599 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
10600 if (MD->size_overridden_methods() == 0)
10601 Methods.insert(Ptr: MD->getCanonicalDecl());
10602 else
10603 for (const CXXMethodDecl *O : MD->overridden_methods())
10604 AddMostOverridenMethods(MD: O, Methods);
10605}
10606
10607void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
10608 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10609 if (!MD->getDeclName().isIdentifier())
10610 return;
10611
10612 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
10613 /*bool RecordPaths=*/false,
10614 /*bool DetectVirtual=*/false);
10615 FindHiddenVirtualMethod FHVM;
10616 FHVM.Method = MD;
10617 FHVM.S = this;
10618
10619 // Keep the base methods that were overridden or introduced in the subclass
10620 // by 'using' in a set. A base method not in this set is hidden.
10621 CXXRecordDecl *DC = MD->getParent();
10622 for (NamedDecl *ND : DC->lookup(Name: MD->getDeclName())) {
10623 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(Val: ND))
10624 ND = shad->getTargetDecl();
10625 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: ND))
10626 AddMostOverridenMethods(MD, Methods&: FHVM.OverridenAndUsingBaseMethods);
10627 }
10628
10629 if (DC->lookupInBases(BaseMatches: FHVM, Paths))
10630 OverloadedMethods = FHVM.OverloadedMethods;
10631}
10632
10633void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
10634 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10635 for (const CXXMethodDecl *overloadedMD : OverloadedMethods) {
10636 PartialDiagnostic PD = PDiag(
10637 DiagID: diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
10638 HandleFunctionTypeMismatch(PDiag&: PD, FromType: MD->getType(), ToType: overloadedMD->getType());
10639 Diag(Loc: overloadedMD->getLocation(), PD);
10640 }
10641}
10642
10643void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
10644 if (MD->isInvalidDecl())
10645 return;
10646
10647 if (Diags.isIgnored(DiagID: diag::warn_overloaded_virtual, Loc: MD->getLocation()))
10648 return;
10649
10650 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10651 FindHiddenVirtualMethods(MD, OverloadedMethods);
10652 if (!OverloadedMethods.empty()) {
10653 Diag(Loc: MD->getLocation(), DiagID: diag::warn_overloaded_virtual)
10654 << MD << (OverloadedMethods.size() > 1);
10655
10656 NoteHiddenVirtualMethods(MD, OverloadedMethods);
10657 }
10658}
10659
10660void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
10661 auto PrintDiagAndRemoveAttr = [&](unsigned N) {
10662 // No diagnostics if this is a template instantiation.
10663 if (!isTemplateInstantiation(Kind: RD.getTemplateSpecializationKind())) {
10664 Diag(Loc: RD.getAttr<TrivialABIAttr>()->getLocation(),
10665 DiagID: diag::ext_cannot_use_trivial_abi) << &RD;
10666 Diag(Loc: RD.getAttr<TrivialABIAttr>()->getLocation(),
10667 DiagID: diag::note_cannot_use_trivial_abi_reason) << &RD << N;
10668 }
10669 RD.dropAttr<TrivialABIAttr>();
10670 };
10671
10672 // Ill-formed if the struct has virtual functions.
10673 if (RD.isPolymorphic()) {
10674 PrintDiagAndRemoveAttr(1);
10675 return;
10676 }
10677
10678 for (const auto &B : RD.bases()) {
10679 // Ill-formed if the base class is non-trivial for the purpose of calls or a
10680 // virtual base.
10681 if (!B.getType()->isDependentType() &&
10682 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) {
10683 PrintDiagAndRemoveAttr(2);
10684 return;
10685 }
10686
10687 if (B.isVirtual()) {
10688 PrintDiagAndRemoveAttr(3);
10689 return;
10690 }
10691 }
10692
10693 for (const auto *FD : RD.fields()) {
10694 // Ill-formed if the field is an ObjectiveC pointer or of a type that is
10695 // non-trivial for the purpose of calls.
10696 QualType FT = FD->getType();
10697 if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
10698 PrintDiagAndRemoveAttr(4);
10699 return;
10700 }
10701
10702 // Ill-formed if the field is an address-discriminated value.
10703 if (FT.hasAddressDiscriminatedPointerAuth()) {
10704 PrintDiagAndRemoveAttr(6);
10705 return;
10706 }
10707
10708 if (const auto *RT =
10709 FT->getBaseElementTypeUnsafe()->getAsCanonical<RecordType>())
10710 if (!RT->isDependentType() &&
10711 !cast<CXXRecordDecl>(Val: RT->getDecl()->getDefinitionOrSelf())
10712 ->canPassInRegisters()) {
10713 PrintDiagAndRemoveAttr(5);
10714 return;
10715 }
10716 }
10717
10718 if (IsCXXTriviallyRelocatableType(RD))
10719 return;
10720
10721 // Ill-formed if the copy and move constructors are deleted.
10722 auto HasNonDeletedCopyOrMoveConstructor = [&]() {
10723 // If the type is dependent, then assume it might have
10724 // implicit copy or move ctor because we won't know yet at this point.
10725 if (RD.isDependentType())
10726 return true;
10727 if (RD.needsImplicitCopyConstructor() &&
10728 !RD.defaultedCopyConstructorIsDeleted())
10729 return true;
10730 if (RD.needsImplicitMoveConstructor() &&
10731 !RD.defaultedMoveConstructorIsDeleted())
10732 return true;
10733 for (const CXXConstructorDecl *CD : RD.ctors())
10734 if (CD->isCopyOrMoveConstructor() && !CD->isDeleted())
10735 return true;
10736 return false;
10737 };
10738
10739 if (!HasNonDeletedCopyOrMoveConstructor()) {
10740 PrintDiagAndRemoveAttr(0);
10741 return;
10742 }
10743}
10744
10745void Sema::checkIncorrectVTablePointerAuthenticationAttribute(
10746 CXXRecordDecl &RD) {
10747 if (RequireCompleteType(Loc: RD.getLocation(), T: Context.getCanonicalTagType(TD: &RD),
10748 DiagID: diag::err_incomplete_type_vtable_pointer_auth))
10749 return;
10750
10751 const CXXRecordDecl *PrimaryBase = &RD;
10752 if (PrimaryBase->hasAnyDependentBases())
10753 return;
10754
10755 while (1) {
10756 assert(PrimaryBase);
10757 const CXXRecordDecl *Base = nullptr;
10758 for (const CXXBaseSpecifier &BasePtr : PrimaryBase->bases()) {
10759 if (!BasePtr.getType()->getAsCXXRecordDecl()->isDynamicClass())
10760 continue;
10761 Base = BasePtr.getType()->getAsCXXRecordDecl();
10762 break;
10763 }
10764 if (!Base || Base == PrimaryBase || !Base->isPolymorphic())
10765 break;
10766 Diag(Loc: RD.getAttr<VTablePointerAuthenticationAttr>()->getLocation(),
10767 DiagID: diag::err_non_top_level_vtable_pointer_auth)
10768 << &RD << Base;
10769 PrimaryBase = Base;
10770 }
10771
10772 if (!RD.isPolymorphic())
10773 Diag(Loc: RD.getAttr<VTablePointerAuthenticationAttr>()->getLocation(),
10774 DiagID: diag::err_non_polymorphic_vtable_pointer_auth)
10775 << &RD;
10776}
10777
10778void Sema::ActOnFinishCXXMemberSpecification(
10779 Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
10780 SourceLocation RBrac, const ParsedAttributesView &AttrList) {
10781 if (!TagDecl)
10782 return;
10783
10784 AdjustDeclIfTemplate(Decl&: TagDecl);
10785
10786 for (const ParsedAttr &AL : AttrList) {
10787 if (AL.getKind() != ParsedAttr::AT_Visibility)
10788 continue;
10789 AL.setInvalid();
10790 Diag(Loc: AL.getLoc(), DiagID: diag::warn_attribute_after_definition_ignored) << AL;
10791 }
10792
10793 ActOnFields(S, RecLoc: RLoc, TagDecl,
10794 Fields: llvm::ArrayRef(
10795 // strict aliasing violation!
10796 reinterpret_cast<Decl **>(FieldCollector->getCurFields()),
10797 FieldCollector->getCurNumFields()),
10798 LBrac, RBrac, AttrList);
10799
10800 CheckCompletedCXXClass(S, Record: cast<CXXRecordDecl>(Val: TagDecl));
10801}
10802
10803/// Find the equality comparison functions that should be implicitly declared
10804/// in a given class definition, per C++2a [class.compare.default]p3.
10805static void findImplicitlyDeclaredEqualityComparisons(
10806 ASTContext &Ctx, CXXRecordDecl *RD,
10807 llvm::SmallVectorImpl<FunctionDecl *> &Spaceships) {
10808 DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(Op: OO_EqualEqual);
10809 if (!RD->lookup(Name: EqEq).empty())
10810 // Member operator== explicitly declared: no implicit operator==s.
10811 return;
10812
10813 // Traverse friends looking for an '==' or a '<=>'.
10814 for (FriendDecl *Friend : RD->friends()) {
10815 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Val: Friend->getFriendDecl());
10816 if (!FD) continue;
10817
10818 if (FD->getOverloadedOperator() == OO_EqualEqual) {
10819 // Friend operator== explicitly declared: no implicit operator==s.
10820 Spaceships.clear();
10821 return;
10822 }
10823
10824 if (FD->getOverloadedOperator() == OO_Spaceship &&
10825 FD->isExplicitlyDefaulted())
10826 Spaceships.push_back(Elt: FD);
10827 }
10828
10829 // Look for members named 'operator<=>'.
10830 DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(Op: OO_Spaceship);
10831 for (NamedDecl *ND : RD->lookup(Name: Cmp)) {
10832 // Note that we could find a non-function here (either a function template
10833 // or a using-declaration). Neither case results in an implicit
10834 // 'operator=='.
10835 if (auto *FD = dyn_cast<FunctionDecl>(Val: ND))
10836 if (FD->isExplicitlyDefaulted())
10837 Spaceships.push_back(Elt: FD);
10838 }
10839}
10840
10841void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
10842 // Don't add implicit special members to templated classes.
10843 // FIXME: This means unqualified lookups for 'operator=' within a class
10844 // template don't work properly.
10845 if (!ClassDecl->isDependentType()) {
10846 if (ClassDecl->needsImplicitDefaultConstructor()) {
10847 ++getASTContext().NumImplicitDefaultConstructors;
10848
10849 if (ClassDecl->hasInheritedConstructor())
10850 DeclareImplicitDefaultConstructor(ClassDecl);
10851 }
10852
10853 if (ClassDecl->needsImplicitCopyConstructor()) {
10854 ++getASTContext().NumImplicitCopyConstructors;
10855
10856 // If the properties or semantics of the copy constructor couldn't be
10857 // determined while the class was being declared, force a declaration
10858 // of it now.
10859 if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
10860 ClassDecl->hasInheritedConstructor())
10861 DeclareImplicitCopyConstructor(ClassDecl);
10862 // For the MS ABI we need to know whether the copy ctor is deleted. A
10863 // prerequisite for deleting the implicit copy ctor is that the class has
10864 // a move ctor or move assignment that is either user-declared or whose
10865 // semantics are inherited from a subobject. FIXME: We should provide a
10866 // more direct way for CodeGen to ask whether the constructor was deleted.
10867 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
10868 (ClassDecl->hasUserDeclaredMoveConstructor() ||
10869 ClassDecl->needsOverloadResolutionForMoveConstructor() ||
10870 ClassDecl->hasUserDeclaredMoveAssignment() ||
10871 ClassDecl->needsOverloadResolutionForMoveAssignment()))
10872 DeclareImplicitCopyConstructor(ClassDecl);
10873 }
10874
10875 if (getLangOpts().CPlusPlus11 &&
10876 ClassDecl->needsImplicitMoveConstructor()) {
10877 ++getASTContext().NumImplicitMoveConstructors;
10878
10879 if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
10880 ClassDecl->hasInheritedConstructor())
10881 DeclareImplicitMoveConstructor(ClassDecl);
10882 }
10883
10884 if (ClassDecl->needsImplicitCopyAssignment()) {
10885 ++getASTContext().NumImplicitCopyAssignmentOperators;
10886
10887 // If we have a dynamic class, then the copy assignment operator may be
10888 // virtual, so we have to declare it immediately. This ensures that, e.g.,
10889 // it shows up in the right place in the vtable and that we diagnose
10890 // problems with the implicit exception specification.
10891 if (ClassDecl->isDynamicClass() ||
10892 ClassDecl->needsOverloadResolutionForCopyAssignment() ||
10893 ClassDecl->hasInheritedAssignment())
10894 DeclareImplicitCopyAssignment(ClassDecl);
10895 }
10896
10897 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
10898 ++getASTContext().NumImplicitMoveAssignmentOperators;
10899
10900 // Likewise for the move assignment operator.
10901 if (ClassDecl->isDynamicClass() ||
10902 ClassDecl->needsOverloadResolutionForMoveAssignment() ||
10903 ClassDecl->hasInheritedAssignment())
10904 DeclareImplicitMoveAssignment(ClassDecl);
10905 }
10906
10907 if (ClassDecl->needsImplicitDestructor()) {
10908 ++getASTContext().NumImplicitDestructors;
10909
10910 // If we have a dynamic class, then the destructor may be virtual, so we
10911 // have to declare the destructor immediately. This ensures that, e.g., it
10912 // shows up in the right place in the vtable and that we diagnose problems
10913 // with the implicit exception specification.
10914 if (ClassDecl->isDynamicClass() ||
10915 ClassDecl->needsOverloadResolutionForDestructor())
10916 DeclareImplicitDestructor(ClassDecl);
10917 }
10918 }
10919
10920 // C++2a [class.compare.default]p3:
10921 // If the member-specification does not explicitly declare any member or
10922 // friend named operator==, an == operator function is declared implicitly
10923 // for each defaulted three-way comparison operator function defined in
10924 // the member-specification
10925 // FIXME: Consider doing this lazily.
10926 // We do this during the initial parse for a class template, not during
10927 // instantiation, so that we can handle unqualified lookups for 'operator=='
10928 // when parsing the template.
10929 if (getLangOpts().CPlusPlus20 && !inTemplateInstantiation()) {
10930 llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships;
10931 findImplicitlyDeclaredEqualityComparisons(Ctx&: Context, RD: ClassDecl,
10932 Spaceships&: DefaultedSpaceships);
10933 for (auto *FD : DefaultedSpaceships)
10934 DeclareImplicitEqualityComparison(RD: ClassDecl, Spaceship: FD);
10935 }
10936}
10937
10938unsigned
10939Sema::ActOnReenterTemplateScope(Decl *D,
10940 llvm::function_ref<Scope *()> EnterScope) {
10941 if (!D)
10942 return 0;
10943 AdjustDeclIfTemplate(Decl&: D);
10944
10945 // In order to get name lookup right, reenter template scopes in order from
10946 // outermost to innermost.
10947 SmallVector<TemplateParameterList *, 4> ParameterLists;
10948 DeclContext *LookupDC = dyn_cast<DeclContext>(Val: D);
10949
10950 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(Val: D)) {
10951 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
10952 ParameterLists.push_back(Elt: DD->getTemplateParameterList(index: i));
10953
10954 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
10955 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
10956 ParameterLists.push_back(Elt: FTD->getTemplateParameters());
10957 } else if (VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
10958 LookupDC = VD->getDeclContext();
10959
10960 if (VarTemplateDecl *VTD = VD->getDescribedVarTemplate())
10961 ParameterLists.push_back(Elt: VTD->getTemplateParameters());
10962 else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(Val: D))
10963 ParameterLists.push_back(Elt: PSD->getTemplateParameters());
10964 }
10965 } else if (TagDecl *TD = dyn_cast<TagDecl>(Val: D)) {
10966 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
10967 ParameterLists.push_back(Elt: TD->getTemplateParameterList(i));
10968
10969 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: TD)) {
10970 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
10971 ParameterLists.push_back(Elt: CTD->getTemplateParameters());
10972 else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(Val: D))
10973 ParameterLists.push_back(Elt: PSD->getTemplateParameters());
10974 }
10975 }
10976 // FIXME: Alias declarations and concepts.
10977
10978 unsigned Count = 0;
10979 Scope *InnermostTemplateScope = nullptr;
10980 for (TemplateParameterList *Params : ParameterLists) {
10981 // Ignore explicit specializations; they don't contribute to the template
10982 // depth.
10983 if (Params->size() == 0)
10984 continue;
10985
10986 InnermostTemplateScope = EnterScope();
10987 for (NamedDecl *Param : *Params) {
10988 if (Param->getDeclName()) {
10989 InnermostTemplateScope->AddDecl(D: Param);
10990 IdResolver.AddDecl(D: Param);
10991 }
10992 }
10993 ++Count;
10994 }
10995
10996 // Associate the new template scopes with the corresponding entities.
10997 if (InnermostTemplateScope) {
10998 assert(LookupDC && "no enclosing DeclContext for template lookup");
10999 EnterTemplatedContext(S: InnermostTemplateScope, DC: LookupDC);
11000 }
11001
11002 return Count;
11003}
11004
11005void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
11006 if (!RecordD) return;
11007 AdjustDeclIfTemplate(Decl&: RecordD);
11008 CXXRecordDecl *Record = cast<CXXRecordDecl>(Val: RecordD);
11009 PushDeclContext(S, DC: Record);
11010}
11011
11012void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
11013 if (!RecordD) return;
11014 PopDeclContext();
11015}
11016
11017void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
11018 if (!Param)
11019 return;
11020
11021 S->AddDecl(D: Param);
11022 if (Param->getDeclName())
11023 IdResolver.AddDecl(D: Param);
11024}
11025
11026void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
11027}
11028
11029/// ActOnDelayedCXXMethodParameter - We've already started a delayed
11030/// C++ method declaration. We're (re-)introducing the given
11031/// function parameter into scope for use in parsing later parts of
11032/// the method declaration. For example, we could see an
11033/// ActOnParamDefaultArgument event for this parameter.
11034void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
11035 if (!ParamD)
11036 return;
11037
11038 ParmVarDecl *Param = cast<ParmVarDecl>(Val: ParamD);
11039
11040 S->AddDecl(D: Param);
11041 if (Param->getDeclName())
11042 IdResolver.AddDecl(D: Param);
11043}
11044
11045void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
11046 if (!MethodD)
11047 return;
11048
11049 AdjustDeclIfTemplate(Decl&: MethodD);
11050
11051 FunctionDecl *Method = cast<FunctionDecl>(Val: MethodD);
11052
11053 // Now that we have our default arguments, check the constructor
11054 // again. It could produce additional diagnostics or affect whether
11055 // the class has implicitly-declared destructors, among other
11056 // things.
11057 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: Method))
11058 CheckConstructor(Constructor);
11059
11060 // Check the default arguments, which we may have added.
11061 if (!Method->isInvalidDecl())
11062 CheckCXXDefaultArguments(FD: Method);
11063}
11064
11065// Emit the given diagnostic for each non-address-space qualifier.
11066// Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
11067static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
11068 const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11069 if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
11070 bool DiagOccurred = false;
11071 FTI.MethodQualifiers->forEachQualifier(
11072 Handle: [DiagID, &S, &DiagOccurred](DeclSpec::TQ, StringRef QualName,
11073 SourceLocation SL) {
11074 // This diagnostic should be emitted on any qualifier except an addr
11075 // space qualifier. However, forEachQualifier currently doesn't visit
11076 // addr space qualifiers, so there's no way to write this condition
11077 // right now; we just diagnose on everything.
11078 S.Diag(Loc: SL, DiagID) << QualName << SourceRange(SL);
11079 DiagOccurred = true;
11080 });
11081 if (DiagOccurred)
11082 D.setInvalidType();
11083 }
11084}
11085
11086static void diagnoseInvalidDeclaratorChunks(Sema &S, Declarator &D,
11087 unsigned Kind) {
11088 if (D.isInvalidType() || D.getNumTypeObjects() <= 1)
11089 return;
11090
11091 DeclaratorChunk &Chunk = D.getTypeObject(i: D.getNumTypeObjects() - 1);
11092 if (Chunk.Kind == DeclaratorChunk::Paren ||
11093 Chunk.Kind == DeclaratorChunk::Function)
11094 return;
11095
11096 SourceLocation PointerLoc = Chunk.getSourceRange().getBegin();
11097 S.Diag(Loc: PointerLoc, DiagID: diag::err_invalid_ctor_dtor_decl)
11098 << Kind << Chunk.getSourceRange();
11099 D.setInvalidType();
11100}
11101
11102QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
11103 StorageClass &SC) {
11104 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
11105
11106 // C++ [class.ctor]p3:
11107 // A constructor shall not be virtual (10.3) or static (9.4). A
11108 // constructor can be invoked for a const, volatile or const
11109 // volatile object. A constructor shall not be declared const,
11110 // volatile, or const volatile (9.3.2).
11111 if (isVirtual) {
11112 if (!D.isInvalidType())
11113 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_constructor_cannot_be)
11114 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
11115 << SourceRange(D.getIdentifierLoc());
11116 D.setInvalidType();
11117 }
11118 if (SC == SC_Static) {
11119 if (!D.isInvalidType())
11120 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_constructor_cannot_be)
11121 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
11122 << SourceRange(D.getIdentifierLoc());
11123 D.setInvalidType();
11124 SC = SC_None;
11125 }
11126
11127 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
11128 diagnoseIgnoredQualifiers(
11129 DiagID: diag::err_constructor_return_type, Quals: TypeQuals, FallbackLoc: SourceLocation(),
11130 ConstQualLoc: D.getDeclSpec().getConstSpecLoc(), VolatileQualLoc: D.getDeclSpec().getVolatileSpecLoc(),
11131 RestrictQualLoc: D.getDeclSpec().getRestrictSpecLoc(),
11132 AtomicQualLoc: D.getDeclSpec().getAtomicSpecLoc());
11133 D.setInvalidType();
11134 }
11135
11136 checkMethodTypeQualifiers(S&: *this, D, DiagID: diag::err_invalid_qualified_constructor);
11137 diagnoseInvalidDeclaratorChunks(S&: *this, D, /*constructor*/ Kind: 0);
11138
11139 // C++0x [class.ctor]p4:
11140 // A constructor shall not be declared with a ref-qualifier.
11141 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11142 if (FTI.hasRefQualifier()) {
11143 Diag(Loc: FTI.getRefQualifierLoc(), DiagID: diag::err_ref_qualifier_constructor)
11144 << FTI.RefQualifierIsLValueRef
11145 << FixItHint::CreateRemoval(RemoveRange: FTI.getRefQualifierLoc());
11146 D.setInvalidType();
11147 }
11148
11149 // Rebuild the function type "R" without any type qualifiers (in
11150 // case any of the errors above fired) and with "void" as the
11151 // return type, since constructors don't have return types.
11152 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
11153 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
11154 return R;
11155
11156 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
11157 EPI.TypeQuals = Qualifiers();
11158 EPI.RefQualifier = RQ_None;
11159
11160 return Context.getFunctionType(ResultTy: Context.VoidTy, Args: Proto->getParamTypes(), EPI);
11161}
11162
11163void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
11164 CXXRecordDecl *ClassDecl
11165 = dyn_cast<CXXRecordDecl>(Val: Constructor->getDeclContext());
11166 if (!ClassDecl)
11167 return Constructor->setInvalidDecl();
11168
11169 // C++ [class.copy]p3:
11170 // A declaration of a constructor for a class X is ill-formed if
11171 // its first parameter is of type (optionally cv-qualified) X and
11172 // either there are no other parameters or else all other
11173 // parameters have default arguments.
11174 if (!Constructor->isInvalidDecl() &&
11175 Constructor->hasOneParamOrDefaultArgs() &&
11176 !Constructor->isFunctionTemplateSpecialization()) {
11177 CanQualType ParamType =
11178 Constructor->getParamDecl(i: 0)->getType()->getCanonicalTypeUnqualified();
11179 CanQualType ClassTy = Context.getCanonicalTagType(TD: ClassDecl);
11180 if (ParamType == ClassTy) {
11181 SourceLocation ParamLoc = Constructor->getParamDecl(i: 0)->getLocation();
11182 const char *ConstRef
11183 = Constructor->getParamDecl(i: 0)->getIdentifier() ? "const &"
11184 : " const &";
11185 Diag(Loc: ParamLoc, DiagID: diag::err_constructor_byvalue_arg)
11186 << FixItHint::CreateInsertion(InsertionLoc: ParamLoc, Code: ConstRef);
11187
11188 // FIXME: Rather that making the constructor invalid, we should endeavor
11189 // to fix the type.
11190 Constructor->setInvalidDecl();
11191 }
11192 }
11193}
11194
11195bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
11196 CXXRecordDecl *RD = Destructor->getParent();
11197
11198 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
11199 SourceLocation Loc;
11200
11201 if (!Destructor->isImplicit())
11202 Loc = Destructor->getLocation();
11203 else
11204 Loc = RD->getLocation();
11205
11206 DeclarationName Name =
11207 Context.DeclarationNames.getCXXOperatorName(Op: OO_Delete);
11208 // If we have a virtual destructor, look up the deallocation function
11209 if (FunctionDecl *OperatorDelete = FindDeallocationFunctionForDestructor(
11210 StartLoc: Loc, RD, /*Diagnose=*/true, /*LookForGlobal=*/false, Name)) {
11211 Expr *ThisArg = nullptr;
11212
11213 // If the notional 'delete this' expression requires a non-trivial
11214 // conversion from 'this' to the type of a destroying operator delete's
11215 // first parameter, perform that conversion now.
11216 if (OperatorDelete->isDestroyingOperatorDelete()) {
11217 unsigned AddressParamIndex = 0;
11218 if (OperatorDelete->isTypeAwareOperatorNewOrDelete())
11219 ++AddressParamIndex;
11220 QualType ParamType =
11221 OperatorDelete->getParamDecl(i: AddressParamIndex)->getType();
11222 if (!declaresSameEntity(D1: ParamType->getAsCXXRecordDecl(), D2: RD)) {
11223 // C++ [class.dtor]p13:
11224 // ... as if for the expression 'delete this' appearing in a
11225 // non-virtual destructor of the destructor's class.
11226 ContextRAII SwitchContext(*this, Destructor);
11227 ExprResult This = ActOnCXXThis(
11228 Loc: OperatorDelete->getParamDecl(i: AddressParamIndex)->getLocation());
11229 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
11230 This = PerformImplicitConversion(From: This.get(), ToType: ParamType,
11231 Action: AssignmentAction::Passing);
11232 if (This.isInvalid()) {
11233 // FIXME: Register this as a context note so that it comes out
11234 // in the right order.
11235 Diag(Loc, DiagID: diag::note_implicit_delete_this_in_destructor_here);
11236 return true;
11237 }
11238 ThisArg = This.get();
11239 }
11240 }
11241
11242 DiagnoseUseOfDecl(D: OperatorDelete, Locs: Loc);
11243 MarkFunctionReferenced(Loc, Func: OperatorDelete);
11244 Destructor->setOperatorDelete(OD: OperatorDelete, ThisArg);
11245
11246 if (isa<CXXMethodDecl>(Val: OperatorDelete) &&
11247 Context.getTargetInfo().callGlobalDeleteInDeletingDtor(
11248 Context.getLangOpts())) {
11249 // In Microsoft ABI whenever a class has a defined operator delete,
11250 // scalar deleting destructors check the 3rd bit of the implicit
11251 // parameter and if it is set, then, global operator delete must be
11252 // called instead of the class-specific one. Find and save the global
11253 // operator delete for that case. Do not diagnose at this point because
11254 // the lack of a global operator delete is not an error if there are no
11255 // delete calls that require it.
11256 FunctionDecl *GlobalOperatorDelete =
11257 FindDeallocationFunctionForDestructor(StartLoc: Loc, RD, /*Diagnose*/ false,
11258 /*LookForGlobal*/ true, Name);
11259 if (GlobalOperatorDelete) {
11260 MarkFunctionReferenced(Loc, Func: GlobalOperatorDelete);
11261 Destructor->setOperatorGlobalDelete(GlobalOperatorDelete);
11262 }
11263 }
11264
11265 if (Context.getTargetInfo().emitVectorDeletingDtors(
11266 Context.getLangOpts())) {
11267 bool DestructorIsExported = Destructor->hasAttr<DLLExportAttr>();
11268 // Lookup delete[] too in case we have to emit a vector deleting dtor.
11269 DeclarationName VDeleteName =
11270 Context.DeclarationNames.getCXXOperatorName(Op: OO_Array_Delete);
11271 FunctionDecl *ArrOperatorDelete = FindDeallocationFunctionForDestructor(
11272 StartLoc: Loc, RD, /*Diagnose*/ false,
11273 /*LookForGlobal*/ false, Name: VDeleteName);
11274 if (ArrOperatorDelete && isa<CXXMethodDecl>(Val: ArrOperatorDelete)) {
11275 FunctionDecl *GlobalArrOperatorDelete =
11276 FindDeallocationFunctionForDestructor(StartLoc: Loc, RD, /*Diagnose*/ false,
11277 /*LookForGlobal*/ true,
11278 Name: VDeleteName);
11279 Destructor->setGlobalOperatorArrayDelete(GlobalArrOperatorDelete);
11280 if (GlobalArrOperatorDelete &&
11281 (Context.classMaybeNeedsVectorDeletingDestructor(RD) ||
11282 DestructorIsExported))
11283 MarkFunctionReferenced(Loc, Func: GlobalArrOperatorDelete);
11284 } else if (!ArrOperatorDelete) {
11285 ArrOperatorDelete = FindDeallocationFunctionForDestructor(
11286 StartLoc: Loc, RD, /*Diagnose*/ false,
11287 /*LookForGlobal*/ true, Name: VDeleteName);
11288 }
11289 Destructor->setOperatorArrayDelete(ArrOperatorDelete);
11290 if (ArrOperatorDelete &&
11291 (Context.classMaybeNeedsVectorDeletingDestructor(RD) ||
11292 DestructorIsExported))
11293 MarkFunctionReferenced(Loc, Func: ArrOperatorDelete);
11294 }
11295 }
11296 }
11297
11298 return false;
11299}
11300
11301QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
11302 StorageClass& SC) {
11303 // C++ [class.dtor]p1:
11304 // [...] A typedef-name that names a class is a class-name
11305 // (7.1.3); however, a typedef-name that names a class shall not
11306 // be used as the identifier in the declarator for a destructor
11307 // declaration.
11308 QualType DeclaratorType = GetTypeFromParser(Ty: D.getName().DestructorName);
11309 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
11310 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::ext_destructor_typedef_name)
11311 << DeclaratorType << isa<TypeAliasDecl>(Val: TT->getDecl());
11312 else if (const TemplateSpecializationType *TST =
11313 DeclaratorType->getAs<TemplateSpecializationType>())
11314 if (TST->isTypeAlias())
11315 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::ext_destructor_typedef_name)
11316 << DeclaratorType << 1;
11317
11318 // C++ [class.dtor]p2:
11319 // A destructor is used to destroy objects of its class type. A
11320 // destructor takes no parameters, and no return type can be
11321 // specified for it (not even void). The address of a destructor
11322 // shall not be taken. A destructor shall not be static. A
11323 // destructor can be invoked for a const, volatile or const
11324 // volatile object. A destructor shall not be declared const,
11325 // volatile or const volatile (9.3.2).
11326 if (SC == SC_Static) {
11327 if (!D.isInvalidType())
11328 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_destructor_cannot_be)
11329 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
11330 << SourceRange(D.getIdentifierLoc())
11331 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
11332
11333 SC = SC_None;
11334 }
11335 if (!D.isInvalidType()) {
11336 // Destructors don't have return types, but the parser will
11337 // happily parse something like:
11338 //
11339 // class X {
11340 // float ~X();
11341 // };
11342 //
11343 // The return type will be eliminated later.
11344 if (D.getDeclSpec().hasTypeSpecifier())
11345 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_destructor_return_type)
11346 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
11347 << SourceRange(D.getIdentifierLoc());
11348 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
11349 diagnoseIgnoredQualifiers(DiagID: diag::err_destructor_return_type, Quals: TypeQuals,
11350 FallbackLoc: SourceLocation(),
11351 ConstQualLoc: D.getDeclSpec().getConstSpecLoc(),
11352 VolatileQualLoc: D.getDeclSpec().getVolatileSpecLoc(),
11353 RestrictQualLoc: D.getDeclSpec().getRestrictSpecLoc(),
11354 AtomicQualLoc: D.getDeclSpec().getAtomicSpecLoc());
11355 D.setInvalidType();
11356 }
11357 }
11358
11359 checkMethodTypeQualifiers(S&: *this, D, DiagID: diag::err_invalid_qualified_destructor);
11360 diagnoseInvalidDeclaratorChunks(S&: *this, D, /*destructor*/ Kind: 1);
11361
11362 // C++0x [class.dtor]p2:
11363 // A destructor shall not be declared with a ref-qualifier.
11364 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11365 if (FTI.hasRefQualifier()) {
11366 Diag(Loc: FTI.getRefQualifierLoc(), DiagID: diag::err_ref_qualifier_destructor)
11367 << FTI.RefQualifierIsLValueRef
11368 << FixItHint::CreateRemoval(RemoveRange: FTI.getRefQualifierLoc());
11369 D.setInvalidType();
11370 }
11371
11372 // Make sure we don't have any parameters.
11373 if (FTIHasNonVoidParameters(FTI)) {
11374 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_destructor_with_params);
11375
11376 // Delete the parameters.
11377 FTI.freeParams();
11378 D.setInvalidType();
11379 }
11380
11381 // Make sure the destructor isn't variadic.
11382 if (FTI.isVariadic) {
11383 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_destructor_variadic);
11384 D.setInvalidType();
11385 }
11386
11387 // Rebuild the function type "R" without any type qualifiers or
11388 // parameters (in case any of the errors above fired) and with
11389 // "void" as the return type, since destructors don't have return
11390 // types.
11391 if (!D.isInvalidType())
11392 return R;
11393
11394 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
11395 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
11396 EPI.Variadic = false;
11397 EPI.TypeQuals = Qualifiers();
11398 EPI.RefQualifier = RQ_None;
11399 return Context.getFunctionType(ResultTy: Context.VoidTy, Args: {}, EPI);
11400}
11401
11402static void extendLeft(SourceRange &R, SourceRange Before) {
11403 if (Before.isInvalid())
11404 return;
11405 R.setBegin(Before.getBegin());
11406 if (R.getEnd().isInvalid())
11407 R.setEnd(Before.getEnd());
11408}
11409
11410static void extendRight(SourceRange &R, SourceRange After) {
11411 if (After.isInvalid())
11412 return;
11413 if (R.getBegin().isInvalid())
11414 R.setBegin(After.getBegin());
11415 R.setEnd(After.getEnd());
11416}
11417
11418void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
11419 StorageClass& SC) {
11420 // C++ [class.conv.fct]p1:
11421 // Neither parameter types nor return type can be specified. The
11422 // type of a conversion function (8.3.5) is "function taking no
11423 // parameter returning conversion-type-id."
11424 if (SC == SC_Static) {
11425 if (!D.isInvalidType())
11426 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_conv_function_not_member)
11427 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
11428 << D.getName().getSourceRange();
11429 D.setInvalidType();
11430 SC = SC_None;
11431 }
11432
11433 TypeSourceInfo *ConvTSI = nullptr;
11434 QualType ConvType =
11435 GetTypeFromParser(Ty: D.getName().ConversionFunctionId, TInfo: &ConvTSI);
11436
11437 const DeclSpec &DS = D.getDeclSpec();
11438 if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
11439 // Conversion functions don't have return types, but the parser will
11440 // happily parse something like:
11441 //
11442 // class X {
11443 // float operator bool();
11444 // };
11445 //
11446 // The return type will be changed later anyway.
11447 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_conv_function_return_type)
11448 << SourceRange(DS.getTypeSpecTypeLoc())
11449 << SourceRange(D.getIdentifierLoc());
11450 D.setInvalidType();
11451 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
11452 // It's also plausible that the user writes type qualifiers in the wrong
11453 // place, such as:
11454 // struct S { const operator int(); };
11455 // FIXME: we could provide a fixit to move the qualifiers onto the
11456 // conversion type.
11457 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_conv_function_with_complex_decl)
11458 << SourceRange(D.getIdentifierLoc()) << 0;
11459 D.setInvalidType();
11460 }
11461 const auto *Proto = R->castAs<FunctionProtoType>();
11462 // Make sure we don't have any parameters.
11463 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11464 unsigned NumParam = Proto->getNumParams();
11465
11466 // [C++2b]
11467 // A conversion function shall have no non-object parameters.
11468 if (NumParam == 1) {
11469 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11470 if (const auto *First =
11471 dyn_cast_if_present<ParmVarDecl>(Val: FTI.Params[0].Param);
11472 First && First->isExplicitObjectParameter())
11473 NumParam--;
11474 }
11475
11476 if (NumParam != 0) {
11477 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_conv_function_with_params);
11478 // Delete the parameters.
11479 FTI.freeParams();
11480 D.setInvalidType();
11481 } else if (Proto->isVariadic()) {
11482 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_conv_function_variadic);
11483 D.setInvalidType();
11484 }
11485
11486 // Diagnose "&operator bool()" and other such nonsense. This
11487 // is actually a gcc extension which we don't support.
11488 if (Proto->getReturnType() != ConvType) {
11489 bool NeedsTypedef = false;
11490 SourceRange Before, After;
11491
11492 // Walk the chunks and extract information on them for our diagnostic.
11493 bool PastFunctionChunk = false;
11494 for (auto &Chunk : D.type_objects()) {
11495 switch (Chunk.Kind) {
11496 case DeclaratorChunk::Function:
11497 if (!PastFunctionChunk) {
11498 if (Chunk.Fun.HasTrailingReturnType) {
11499 TypeSourceInfo *TRT = nullptr;
11500 GetTypeFromParser(Ty: Chunk.Fun.getTrailingReturnType(), TInfo: &TRT);
11501 if (TRT) extendRight(R&: After, After: TRT->getTypeLoc().getSourceRange());
11502 }
11503 PastFunctionChunk = true;
11504 break;
11505 }
11506 [[fallthrough]];
11507 case DeclaratorChunk::Array:
11508 NeedsTypedef = true;
11509 extendRight(R&: After, After: Chunk.getSourceRange());
11510 break;
11511
11512 case DeclaratorChunk::Pointer:
11513 case DeclaratorChunk::BlockPointer:
11514 case DeclaratorChunk::Reference:
11515 case DeclaratorChunk::MemberPointer:
11516 case DeclaratorChunk::Pipe:
11517 extendLeft(R&: Before, Before: Chunk.getSourceRange());
11518 break;
11519
11520 case DeclaratorChunk::Paren:
11521 extendLeft(R&: Before, Before: Chunk.Loc);
11522 extendRight(R&: After, After: Chunk.EndLoc);
11523 break;
11524 }
11525 }
11526
11527 SourceLocation Loc = Before.isValid() ? Before.getBegin() :
11528 After.isValid() ? After.getBegin() :
11529 D.getIdentifierLoc();
11530 auto &&DB = Diag(Loc, DiagID: diag::err_conv_function_with_complex_decl);
11531 DB << Before << After;
11532
11533 if (!NeedsTypedef) {
11534 DB << /*don't need a typedef*/0;
11535
11536 // If we can provide a correct fix-it hint, do so.
11537 if (After.isInvalid() && ConvTSI) {
11538 SourceLocation InsertLoc =
11539 getLocForEndOfToken(Loc: ConvTSI->getTypeLoc().getEndLoc());
11540 DB << FixItHint::CreateInsertion(InsertionLoc: InsertLoc, Code: " ")
11541 << FixItHint::CreateInsertionFromRange(
11542 InsertionLoc: InsertLoc, FromRange: CharSourceRange::getTokenRange(R: Before))
11543 << FixItHint::CreateRemoval(RemoveRange: Before);
11544 }
11545 } else if (!Proto->getReturnType()->isDependentType()) {
11546 DB << /*typedef*/1 << Proto->getReturnType();
11547 } else if (getLangOpts().CPlusPlus11) {
11548 DB << /*alias template*/2 << Proto->getReturnType();
11549 } else {
11550 DB << /*might not be fixable*/3;
11551 }
11552
11553 // Recover by incorporating the other type chunks into the result type.
11554 // Note, this does *not* change the name of the function. This is compatible
11555 // with the GCC extension:
11556 // struct S { &operator int(); } s;
11557 // int &r = s.operator int(); // ok in GCC
11558 // S::operator int&() {} // error in GCC, function name is 'operator int'.
11559 ConvType = Proto->getReturnType();
11560 }
11561
11562 // C++ [class.conv.fct]p4:
11563 // The conversion-type-id shall not represent a function type nor
11564 // an array type.
11565 if (ConvType->isArrayType()) {
11566 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_conv_function_to_array);
11567 ConvType = Context.getPointerType(T: ConvType);
11568 D.setInvalidType();
11569 } else if (ConvType->isFunctionType()) {
11570 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_conv_function_to_function);
11571 ConvType = Context.getPointerType(T: ConvType);
11572 D.setInvalidType();
11573 }
11574
11575 // Rebuild the function type "R" without any parameters (in case any
11576 // of the errors above fired) and with the conversion type as the
11577 // return type.
11578 if (D.isInvalidType())
11579 R = Context.getFunctionType(ResultTy: ConvType, Args: {}, EPI: Proto->getExtProtoInfo());
11580
11581 // C++0x explicit conversion operators.
11582 if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus20)
11583 Diag(Loc: DS.getExplicitSpecLoc(),
11584 DiagID: getLangOpts().CPlusPlus11
11585 ? diag::warn_cxx98_compat_explicit_conversion_functions
11586 : diag::ext_explicit_conversion_functions)
11587 << SourceRange(DS.getExplicitSpecRange());
11588}
11589
11590Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
11591 assert(Conversion && "Expected to receive a conversion function declaration");
11592
11593 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Val: Conversion->getDeclContext());
11594
11595 // Make sure we aren't redeclaring the conversion function.
11596 QualType ConvType = Context.getCanonicalType(T: Conversion->getConversionType());
11597 // C++ [class.conv.fct]p1:
11598 // [...] A conversion function is never used to convert a
11599 // (possibly cv-qualified) object to the (possibly cv-qualified)
11600 // same object type (or a reference to it), to a (possibly
11601 // cv-qualified) base class of that type (or a reference to it),
11602 // or to (possibly cv-qualified) void.
11603 CanQualType ClassType = Context.getCanonicalTagType(TD: ClassDecl);
11604 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
11605 ConvType = ConvTypeRef->getPointeeType();
11606 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
11607 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
11608 /* Suppress diagnostics for instantiations. */;
11609 else if (Conversion->size_overridden_methods() != 0)
11610 /* Suppress diagnostics for overriding virtual function in a base class. */;
11611 else if (ConvType->isRecordType()) {
11612 ConvType = Context.getCanonicalType(T: ConvType).getUnqualifiedType();
11613 if (ConvType == ClassType)
11614 Diag(Loc: Conversion->getLocation(), DiagID: diag::warn_conv_to_self_not_used)
11615 << ClassType;
11616 else if (IsDerivedFrom(Loc: Conversion->getLocation(), Derived: ClassType, Base: ConvType))
11617 Diag(Loc: Conversion->getLocation(), DiagID: diag::warn_conv_to_base_not_used)
11618 << ClassType << ConvType;
11619 } else if (ConvType->isVoidType()) {
11620 Diag(Loc: Conversion->getLocation(), DiagID: diag::warn_conv_to_void_not_used)
11621 << ClassType << ConvType;
11622 }
11623
11624 if (FunctionTemplateDecl *ConversionTemplate =
11625 Conversion->getDescribedFunctionTemplate()) {
11626 if (const auto *ConvTypePtr = ConvType->getAs<PointerType>()) {
11627 ConvType = ConvTypePtr->getPointeeType();
11628 }
11629 if (ConvType->isUndeducedAutoType()) {
11630 Diag(Loc: Conversion->getTypeSpecStartLoc(), DiagID: diag::err_auto_not_allowed)
11631 << getReturnTypeLoc(FD: Conversion).getSourceRange()
11632 << ConvType->castAs<AutoType>()->getKeyword()
11633 << /* in declaration of conversion function template= */ 24;
11634 }
11635
11636 return ConversionTemplate;
11637 }
11638
11639 return Conversion;
11640}
11641
11642void Sema::CheckExplicitObjectMemberFunction(DeclContext *DC, Declarator &D,
11643 DeclarationName Name, QualType R) {
11644 CheckExplicitObjectMemberFunction(D, Name, R, IsLambda: false, DC);
11645}
11646
11647void Sema::CheckExplicitObjectLambda(Declarator &D) {
11648 CheckExplicitObjectMemberFunction(D, Name: {}, R: {}, IsLambda: true);
11649}
11650
11651void Sema::CheckExplicitObjectMemberFunction(Declarator &D,
11652 DeclarationName Name, QualType R,
11653 bool IsLambda, DeclContext *DC) {
11654 if (!D.isFunctionDeclarator())
11655 return;
11656
11657 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11658 if (FTI.NumParams == 0)
11659 return;
11660 ParmVarDecl *ExplicitObjectParam = nullptr;
11661 for (unsigned Idx = 0; Idx < FTI.NumParams; Idx++) {
11662 const auto &ParamInfo = FTI.Params[Idx];
11663 if (!ParamInfo.Param)
11664 continue;
11665 ParmVarDecl *Param = cast<ParmVarDecl>(Val: ParamInfo.Param);
11666 if (!Param->isExplicitObjectParameter())
11667 continue;
11668 if (Idx == 0) {
11669 ExplicitObjectParam = Param;
11670 continue;
11671 } else {
11672 Diag(Loc: Param->getLocation(),
11673 DiagID: diag::err_explicit_object_parameter_must_be_first)
11674 << IsLambda << Param->getSourceRange();
11675 }
11676 }
11677 if (!ExplicitObjectParam)
11678 return;
11679
11680 if (ExplicitObjectParam->hasDefaultArg()) {
11681 Diag(Loc: ExplicitObjectParam->getLocation(),
11682 DiagID: diag::err_explicit_object_default_arg)
11683 << ExplicitObjectParam->getSourceRange();
11684 D.setInvalidType();
11685 }
11686
11687 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static ||
11688 (D.getContext() == clang::DeclaratorContext::Member &&
11689 D.isStaticMember())) {
11690 Diag(Loc: ExplicitObjectParam->getBeginLoc(),
11691 DiagID: diag::err_explicit_object_parameter_nonmember)
11692 << D.getSourceRange() << /*static=*/0 << IsLambda;
11693 D.setInvalidType();
11694 }
11695
11696 if (D.getDeclSpec().isVirtualSpecified()) {
11697 Diag(Loc: ExplicitObjectParam->getBeginLoc(),
11698 DiagID: diag::err_explicit_object_parameter_nonmember)
11699 << D.getSourceRange() << /*virtual=*/1 << IsLambda;
11700 D.setInvalidType();
11701 }
11702
11703 // Friend declarations require some care. Consider:
11704 //
11705 // namespace N {
11706 // struct A{};
11707 // int f(A);
11708 // }
11709 //
11710 // struct S {
11711 // struct T {
11712 // int f(this T);
11713 // };
11714 //
11715 // friend int T::f(this T); // Allow this.
11716 // friend int f(this S); // But disallow this.
11717 // friend int N::f(this A); // And disallow this.
11718 // };
11719 //
11720 // Here, it seems to suffice to check whether the scope
11721 // specifier designates a class type.
11722 if (D.getDeclSpec().isFriendSpecified() &&
11723 !isa_and_present<CXXRecordDecl>(
11724 Val: computeDeclContext(SS: D.getCXXScopeSpec()))) {
11725 Diag(Loc: ExplicitObjectParam->getBeginLoc(),
11726 DiagID: diag::err_explicit_object_parameter_nonmember)
11727 << D.getSourceRange() << /*non-member=*/2 << IsLambda;
11728 D.setInvalidType();
11729 }
11730
11731 if (IsLambda && FTI.hasMutableQualifier()) {
11732 Diag(Loc: ExplicitObjectParam->getBeginLoc(),
11733 DiagID: diag::err_explicit_object_parameter_mutable)
11734 << D.getSourceRange();
11735 }
11736
11737 if (IsLambda)
11738 return;
11739
11740 if (!DC || !DC->isRecord()) {
11741 assert(D.isInvalidType() && "Explicit object parameter in non-member "
11742 "should have been diagnosed already");
11743 return;
11744 }
11745
11746 // CWG2674: constructors and destructors cannot have explicit parameters.
11747 if (Name.getNameKind() == DeclarationName::CXXConstructorName ||
11748 Name.getNameKind() == DeclarationName::CXXDestructorName) {
11749 Diag(Loc: ExplicitObjectParam->getBeginLoc(),
11750 DiagID: diag::err_explicit_object_parameter_constructor)
11751 << (Name.getNameKind() == DeclarationName::CXXDestructorName)
11752 << D.getSourceRange();
11753 D.setInvalidType();
11754 }
11755}
11756
11757namespace {
11758/// Utility class to accumulate and print a diagnostic listing the invalid
11759/// specifier(s) on a declaration.
11760struct BadSpecifierDiagnoser {
11761 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
11762 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
11763 ~BadSpecifierDiagnoser() {
11764 Diagnostic << Specifiers;
11765 }
11766
11767 template<typename T> void check(SourceLocation SpecLoc, T Spec) {
11768 return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
11769 }
11770 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
11771 return check(SpecLoc,
11772 Spec: DeclSpec::getSpecifierName(T: Spec, Policy: S.getPrintingPolicy()));
11773 }
11774 void check(SourceLocation SpecLoc, const char *Spec) {
11775 if (SpecLoc.isInvalid()) return;
11776 Diagnostic << SourceRange(SpecLoc, SpecLoc);
11777 if (!Specifiers.empty()) Specifiers += " ";
11778 Specifiers += Spec;
11779 }
11780
11781 Sema &S;
11782 Sema::SemaDiagnosticBuilder Diagnostic;
11783 std::string Specifiers;
11784};
11785}
11786
11787bool Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
11788 StorageClass &SC) {
11789 TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
11790 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
11791 assert(GuidedTemplateDecl && "missing template decl for deduction guide");
11792
11793 // C++ [temp.deduct.guide]p3:
11794 // A deduction-gide shall be declared in the same scope as the
11795 // corresponding class template.
11796 if (!CurContext->getRedeclContext()->Equals(
11797 DC: GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
11798 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_deduction_guide_wrong_scope)
11799 << GuidedTemplateDecl;
11800 NoteTemplateLocation(Decl: *GuidedTemplateDecl);
11801 }
11802
11803 auto &DS = D.getMutableDeclSpec();
11804 // We leave 'friend' and 'virtual' to be rejected in the normal way.
11805 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
11806 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
11807 DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
11808 BadSpecifierDiagnoser Diagnoser(
11809 *this, D.getIdentifierLoc(),
11810 diag::err_deduction_guide_invalid_specifier);
11811
11812 Diagnoser.check(SpecLoc: DS.getStorageClassSpecLoc(), Spec: DS.getStorageClassSpec());
11813 DS.ClearStorageClassSpecs();
11814 SC = SC_None;
11815
11816 // 'explicit' is permitted.
11817 Diagnoser.check(SpecLoc: DS.getInlineSpecLoc(), Spec: "inline");
11818 Diagnoser.check(SpecLoc: DS.getNoreturnSpecLoc(), Spec: "_Noreturn");
11819 Diagnoser.check(SpecLoc: DS.getConstexprSpecLoc(), Spec: "constexpr");
11820 DS.ClearConstexprSpec();
11821
11822 Diagnoser.check(SpecLoc: DS.getConstSpecLoc(), Spec: "const");
11823 Diagnoser.check(SpecLoc: DS.getRestrictSpecLoc(), Spec: "__restrict");
11824 Diagnoser.check(SpecLoc: DS.getVolatileSpecLoc(), Spec: "volatile");
11825 Diagnoser.check(SpecLoc: DS.getAtomicSpecLoc(), Spec: "_Atomic");
11826 Diagnoser.check(SpecLoc: DS.getUnalignedSpecLoc(), Spec: "__unaligned");
11827 DS.ClearTypeQualifiers();
11828
11829 Diagnoser.check(SpecLoc: DS.getTypeSpecComplexLoc(), Spec: DS.getTypeSpecComplex());
11830 Diagnoser.check(SpecLoc: DS.getTypeSpecSignLoc(), Spec: DS.getTypeSpecSign());
11831 Diagnoser.check(SpecLoc: DS.getTypeSpecWidthLoc(), Spec: DS.getTypeSpecWidth());
11832 Diagnoser.check(SpecLoc: DS.getTypeSpecTypeLoc(), Spec: DS.getTypeSpecType());
11833 DS.ClearTypeSpecType();
11834 }
11835
11836 if (D.isInvalidType())
11837 return true;
11838
11839 // Check the declarator is simple enough.
11840 bool FoundFunction = false;
11841 for (const DeclaratorChunk &Chunk : llvm::reverse(C: D.type_objects())) {
11842 if (Chunk.Kind == DeclaratorChunk::Paren)
11843 continue;
11844 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
11845 Diag(Loc: D.getDeclSpec().getBeginLoc(),
11846 DiagID: diag::err_deduction_guide_with_complex_decl)
11847 << D.getSourceRange();
11848 break;
11849 }
11850 if (!Chunk.Fun.hasTrailingReturnType())
11851 return Diag(Loc: D.getName().getBeginLoc(),
11852 DiagID: diag::err_deduction_guide_no_trailing_return_type);
11853
11854 // Check that the return type is written as a specialization of
11855 // the template specified as the deduction-guide's name.
11856 // The template name may not be qualified. [temp.deduct.guide]
11857 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
11858 TypeSourceInfo *TSI = nullptr;
11859 QualType RetTy = GetTypeFromParser(Ty: TrailingReturnType, TInfo: &TSI);
11860 assert(TSI && "deduction guide has valid type but invalid return type?");
11861 bool AcceptableReturnType = false;
11862 bool MightInstantiateToSpecialization = false;
11863 if (auto RetTST =
11864 TSI->getTypeLoc().getAsAdjusted<TemplateSpecializationTypeLoc>()) {
11865 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
11866 bool TemplateMatches = Context.hasSameTemplateName(
11867 X: SpecifiedName, Y: GuidedTemplate, /*IgnoreDeduced=*/true);
11868
11869 const QualifiedTemplateName *Qualifiers =
11870 SpecifiedName.getAsQualifiedTemplateName();
11871 assert(Qualifiers && "expected QualifiedTemplate");
11872 bool SimplyWritten =
11873 !Qualifiers->hasTemplateKeyword() && !Qualifiers->getQualifier();
11874 if (SimplyWritten && TemplateMatches)
11875 AcceptableReturnType = true;
11876 else {
11877 // This could still instantiate to the right type, unless we know it
11878 // names the wrong class template.
11879 auto *TD = SpecifiedName.getAsTemplateDecl();
11880 MightInstantiateToSpecialization =
11881 !(TD && isa<ClassTemplateDecl>(Val: TD) && !TemplateMatches);
11882 }
11883 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
11884 MightInstantiateToSpecialization = true;
11885 }
11886
11887 if (!AcceptableReturnType)
11888 return Diag(Loc: TSI->getTypeLoc().getBeginLoc(),
11889 DiagID: diag::err_deduction_guide_bad_trailing_return_type)
11890 << GuidedTemplate << TSI->getType()
11891 << MightInstantiateToSpecialization
11892 << TSI->getTypeLoc().getSourceRange();
11893
11894 // Keep going to check that we don't have any inner declarator pieces (we
11895 // could still have a function returning a pointer to a function).
11896 FoundFunction = true;
11897 }
11898
11899 if (D.isFunctionDefinition())
11900 // we can still create a valid deduction guide here.
11901 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_deduction_guide_defines_function);
11902 return false;
11903}
11904
11905//===----------------------------------------------------------------------===//
11906// Namespace Handling
11907//===----------------------------------------------------------------------===//
11908
11909/// Diagnose a mismatch in 'inline' qualifiers when a namespace is
11910/// reopened.
11911static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
11912 SourceLocation Loc,
11913 IdentifierInfo *II, bool *IsInline,
11914 NamespaceDecl *PrevNS) {
11915 assert(*IsInline != PrevNS->isInline());
11916
11917 // 'inline' must appear on the original definition, but not necessarily
11918 // on all extension definitions, so the note should point to the first
11919 // definition to avoid confusion.
11920 PrevNS = PrevNS->getFirstDecl();
11921
11922 if (PrevNS->isInline())
11923 // The user probably just forgot the 'inline', so suggest that it
11924 // be added back.
11925 S.Diag(Loc, DiagID: diag::warn_inline_namespace_reopened_noninline)
11926 << FixItHint::CreateInsertion(InsertionLoc: KeywordLoc, Code: "inline ");
11927 else
11928 S.Diag(Loc, DiagID: diag::err_inline_namespace_mismatch);
11929
11930 S.Diag(Loc: PrevNS->getLocation(), DiagID: diag::note_previous_definition);
11931 *IsInline = PrevNS->isInline();
11932}
11933
11934/// ActOnStartNamespaceDef - This is called at the start of a namespace
11935/// definition.
11936Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
11937 SourceLocation InlineLoc,
11938 SourceLocation NamespaceLoc,
11939 SourceLocation IdentLoc, IdentifierInfo *II,
11940 SourceLocation LBrace,
11941 const ParsedAttributesView &AttrList,
11942 UsingDirectiveDecl *&UD, bool IsNested) {
11943 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
11944 // For anonymous namespace, take the location of the left brace.
11945 SourceLocation Loc = II ? IdentLoc : LBrace;
11946 bool IsInline = InlineLoc.isValid();
11947 bool IsInvalid = false;
11948 bool IsStd = false;
11949 bool AddToKnown = false;
11950 Scope *DeclRegionScope = NamespcScope->getParent();
11951
11952 NamespaceDecl *PrevNS = nullptr;
11953 if (II) {
11954 // C++ [namespace.std]p7:
11955 // A translation unit shall not declare namespace std to be an inline
11956 // namespace (9.8.2).
11957 //
11958 // Precondition: the std namespace is in the file scope and is declared to
11959 // be inline
11960 auto DiagnoseInlineStdNS = [&]() {
11961 assert(IsInline && II->isStr("std") &&
11962 CurContext->getRedeclContext()->isTranslationUnit() &&
11963 "Precondition of DiagnoseInlineStdNS not met");
11964 Diag(Loc: InlineLoc, DiagID: diag::err_inline_namespace_std)
11965 << SourceRange(InlineLoc, InlineLoc.getLocWithOffset(Offset: 6));
11966 IsInline = false;
11967 };
11968 // C++ [namespace.def]p2:
11969 // The identifier in an original-namespace-definition shall not
11970 // have been previously defined in the declarative region in
11971 // which the original-namespace-definition appears. The
11972 // identifier in an original-namespace-definition is the name of
11973 // the namespace. Subsequently in that declarative region, it is
11974 // treated as an original-namespace-name.
11975 //
11976 // Since namespace names are unique in their scope, and we don't
11977 // look through using directives, just look for any ordinary names
11978 // as if by qualified name lookup.
11979 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
11980 RedeclarationKind::ForExternalRedeclaration);
11981 LookupQualifiedName(R, LookupCtx: CurContext->getRedeclContext());
11982 NamedDecl *PrevDecl =
11983 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
11984 PrevNS = dyn_cast_or_null<NamespaceDecl>(Val: PrevDecl);
11985
11986 if (PrevNS) {
11987 // This is an extended namespace definition.
11988 if (IsInline && II->isStr(Str: "std") &&
11989 CurContext->getRedeclContext()->isTranslationUnit())
11990 DiagnoseInlineStdNS();
11991 else if (IsInline != PrevNS->isInline())
11992 DiagnoseNamespaceInlineMismatch(S&: *this, KeywordLoc: NamespaceLoc, Loc, II,
11993 IsInline: &IsInline, PrevNS);
11994 } else if (PrevDecl) {
11995 // This is an invalid name redefinition.
11996 Diag(Loc, DiagID: diag::err_redefinition_different_kind)
11997 << II;
11998 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_definition);
11999 IsInvalid = true;
12000 // Continue on to push Namespc as current DeclContext and return it.
12001 } else if (II->isStr(Str: "std") &&
12002 CurContext->getRedeclContext()->isTranslationUnit()) {
12003 if (IsInline)
12004 DiagnoseInlineStdNS();
12005 // This is the first "real" definition of the namespace "std", so update
12006 // our cache of the "std" namespace to point at this definition.
12007 PrevNS = getStdNamespace();
12008 IsStd = true;
12009 AddToKnown = !IsInline;
12010 } else {
12011 // We've seen this namespace for the first time.
12012 AddToKnown = !IsInline;
12013 }
12014 } else {
12015 // Anonymous namespaces.
12016
12017 // Determine whether the parent already has an anonymous namespace.
12018 DeclContext *Parent = CurContext->getRedeclContext();
12019 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Val: Parent)) {
12020 PrevNS = TU->getAnonymousNamespace();
12021 } else {
12022 NamespaceDecl *ND = cast<NamespaceDecl>(Val: Parent);
12023 PrevNS = ND->getAnonymousNamespace();
12024 }
12025
12026 if (PrevNS && IsInline != PrevNS->isInline())
12027 DiagnoseNamespaceInlineMismatch(S&: *this, KeywordLoc: NamespaceLoc, Loc: NamespaceLoc, II,
12028 IsInline: &IsInline, PrevNS);
12029 }
12030
12031 NamespaceDecl *Namespc = NamespaceDecl::Create(
12032 C&: Context, DC: CurContext, Inline: IsInline, StartLoc, IdLoc: Loc, Id: II, PrevDecl: PrevNS, Nested: IsNested);
12033 if (IsInvalid)
12034 Namespc->setInvalidDecl();
12035
12036 ProcessDeclAttributeList(S: DeclRegionScope, D: Namespc, AttrList);
12037 AddPragmaAttributes(S: DeclRegionScope, D: Namespc);
12038 ProcessAPINotes(D: Namespc);
12039
12040 // FIXME: Should we be merging attributes?
12041 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
12042 PushNamespaceVisibilityAttr(Attr, Loc);
12043
12044 if (IsStd)
12045 StdNamespace = Namespc;
12046 if (AddToKnown)
12047 KnownNamespaces[Namespc] = false;
12048
12049 if (II) {
12050 PushOnScopeChains(D: Namespc, S: DeclRegionScope);
12051 } else {
12052 // Link the anonymous namespace into its parent.
12053 DeclContext *Parent = CurContext->getRedeclContext();
12054 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Val: Parent)) {
12055 TU->setAnonymousNamespace(Namespc);
12056 } else {
12057 cast<NamespaceDecl>(Val: Parent)->setAnonymousNamespace(Namespc);
12058 }
12059
12060 CurContext->addDecl(D: Namespc);
12061
12062 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
12063 // behaves as if it were replaced by
12064 // namespace unique { /* empty body */ }
12065 // using namespace unique;
12066 // namespace unique { namespace-body }
12067 // where all occurrences of 'unique' in a translation unit are
12068 // replaced by the same identifier and this identifier differs
12069 // from all other identifiers in the entire program.
12070
12071 // We just create the namespace with an empty name and then add an
12072 // implicit using declaration, just like the standard suggests.
12073 //
12074 // CodeGen enforces the "universally unique" aspect by giving all
12075 // declarations semantically contained within an anonymous
12076 // namespace internal linkage.
12077
12078 if (!PrevNS) {
12079 UD = UsingDirectiveDecl::Create(C&: Context, DC: Parent,
12080 /* 'using' */ UsingLoc: LBrace,
12081 /* 'namespace' */ NamespaceLoc: SourceLocation(),
12082 /* qualifier */ QualifierLoc: NestedNameSpecifierLoc(),
12083 /* identifier */ IdentLoc: SourceLocation(),
12084 Nominated: Namespc,
12085 /* Ancestor */ CommonAncestor: Parent);
12086 UD->setImplicit();
12087 Parent->addDecl(D: UD);
12088 }
12089 }
12090
12091 ActOnDocumentableDecl(D: Namespc);
12092
12093 // Although we could have an invalid decl (i.e. the namespace name is a
12094 // redefinition), push it as current DeclContext and try to continue parsing.
12095 // FIXME: We should be able to push Namespc here, so that the each DeclContext
12096 // for the namespace has the declarations that showed up in that particular
12097 // namespace definition.
12098 PushDeclContext(S: NamespcScope, DC: Namespc);
12099 return Namespc;
12100}
12101
12102/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
12103/// is a namespace alias, returns the namespace it points to.
12104static inline NamespaceDecl *getNamespaceDecl(NamespaceBaseDecl *D) {
12105 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(Val: D))
12106 return AD->getNamespace();
12107 return dyn_cast_or_null<NamespaceDecl>(Val: D);
12108}
12109
12110void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
12111 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Val: Dcl);
12112 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
12113 Namespc->setRBraceLoc(RBrace);
12114 PopDeclContext();
12115 if (Namespc->hasAttr<VisibilityAttr>())
12116 PopPragmaVisibility(IsNamespaceEnd: true, EndLoc: RBrace);
12117 // If this namespace contains an export-declaration, export it now.
12118 if (DeferredExportedNamespaces.erase(Ptr: Namespc))
12119 Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
12120}
12121
12122CXXRecordDecl *Sema::getStdBadAlloc() const {
12123 return cast_or_null<CXXRecordDecl>(
12124 Val: StdBadAlloc.get(Source: Context.getExternalSource()));
12125}
12126
12127EnumDecl *Sema::getStdAlignValT() const {
12128 return cast_or_null<EnumDecl>(Val: StdAlignValT.get(Source: Context.getExternalSource()));
12129}
12130
12131NamespaceDecl *Sema::getStdNamespace() const {
12132 return cast_or_null<NamespaceDecl>(
12133 Val: StdNamespace.get(Source: Context.getExternalSource()));
12134}
12135
12136namespace {
12137
12138enum UnsupportedSTLSelect {
12139 USS_InvalidMember,
12140 USS_MissingMember,
12141 USS_NonTrivial,
12142 USS_Other
12143};
12144
12145struct InvalidSTLDiagnoser {
12146 Sema &S;
12147 SourceLocation Loc;
12148 QualType TyForDiags;
12149
12150 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
12151 const VarDecl *VD = nullptr) {
12152 {
12153 auto D = S.Diag(Loc, DiagID: diag::err_std_compare_type_not_supported)
12154 << TyForDiags << ((int)Sel);
12155 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
12156 assert(!Name.empty());
12157 D << Name;
12158 }
12159 }
12160 if (Sel == USS_InvalidMember) {
12161 S.Diag(Loc: VD->getLocation(), DiagID: diag::note_var_declared_here)
12162 << VD << VD->getSourceRange();
12163 }
12164 return QualType();
12165 }
12166};
12167} // namespace
12168
12169QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
12170 SourceLocation Loc,
12171 ComparisonCategoryUsage Usage) {
12172 assert(getLangOpts().CPlusPlus &&
12173 "Looking for comparison category type outside of C++.");
12174
12175 // Use an elaborated type for diagnostics which has a name containing the
12176 // prepended 'std' namespace but not any inline namespace names.
12177 auto TyForDiags = [&](ComparisonCategoryInfo *Info) {
12178 NestedNameSpecifier Qualifier(Context, getStdNamespace(),
12179 /*Prefix=*/std::nullopt);
12180 return Context.getTagType(Keyword: ElaboratedTypeKeyword::None, Qualifier,
12181 TD: Info->Record,
12182 /*OwnsTag=*/false);
12183 };
12184
12185 // Check if we've already successfully checked the comparison category type
12186 // before. If so, skip checking it again.
12187 ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
12188 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) {
12189 // The only thing we need to check is that the type has a reachable
12190 // definition in the current context.
12191 if (RequireCompleteType(Loc, T: TyForDiags(Info), DiagID: diag::err_incomplete_type))
12192 return QualType();
12193
12194 return Info->getType();
12195 }
12196
12197 // If lookup failed
12198 if (!Info) {
12199 std::string NameForDiags = "std::";
12200 NameForDiags += ComparisonCategories::getCategoryString(Kind);
12201 Diag(Loc, DiagID: diag::err_implied_comparison_category_type_not_found)
12202 << NameForDiags << (int)Usage;
12203 return QualType();
12204 }
12205
12206 assert(Info->Kind == Kind);
12207 assert(Info->Record);
12208
12209 // Update the Record decl in case we encountered a forward declaration on our
12210 // first pass. FIXME: This is a bit of a hack.
12211 if (Info->Record->hasDefinition())
12212 Info->Record = Info->Record->getDefinition();
12213
12214 if (RequireCompleteType(Loc, T: TyForDiags(Info), DiagID: diag::err_incomplete_type))
12215 return QualType();
12216
12217 InvalidSTLDiagnoser UnsupportedSTLError{.S: *this, .Loc: Loc, .TyForDiags: TyForDiags(Info)};
12218
12219 if (!Info->Record->isTriviallyCopyable())
12220 return UnsupportedSTLError(USS_NonTrivial);
12221
12222 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
12223 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
12224 // Tolerate empty base classes.
12225 if (Base->isEmpty())
12226 continue;
12227 // Reject STL implementations which have at least one non-empty base.
12228 return UnsupportedSTLError();
12229 }
12230
12231 // Check that the STL has implemented the types using a single integer field.
12232 // This expectation allows better codegen for builtin operators. We require:
12233 // (1) The class has exactly one field.
12234 // (2) The field is an integral or enumeration type.
12235 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
12236 if (std::distance(first: FIt, last: FEnd) != 1 ||
12237 !FIt->getType()->isIntegralOrEnumerationType()) {
12238 return UnsupportedSTLError();
12239 }
12240
12241 // Build each of the require values and store them in Info.
12242 for (ComparisonCategoryResult CCR :
12243 ComparisonCategories::getPossibleResultsForType(Type: Kind)) {
12244 StringRef MemName = ComparisonCategories::getResultString(Kind: CCR);
12245 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(ValueKind: CCR);
12246
12247 if (!ValInfo)
12248 return UnsupportedSTLError(USS_MissingMember, MemName);
12249
12250 VarDecl *VD = ValInfo->VD;
12251 assert(VD && "should not be null!");
12252
12253 // Attempt to diagnose reasons why the STL definition of this type
12254 // might be foobar, including it failing to be a constant expression.
12255 // TODO Handle more ways the lookup or result can be invalid.
12256 if (!VD->isStaticDataMember() ||
12257 !VD->isUsableInConstantExpressions(C: Context))
12258 return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
12259
12260 // Attempt to evaluate the var decl as a constant expression and extract
12261 // the value of its first field as a ICE. If this fails, the STL
12262 // implementation is not supported.
12263 if (!ValInfo->hasValidIntValue())
12264 return UnsupportedSTLError();
12265
12266 MarkVariableReferenced(Loc, Var: VD);
12267 }
12268
12269 // We've successfully built the required types and expressions. Update
12270 // the cache and return the newly cached value.
12271 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
12272 return Info->getType();
12273}
12274
12275NamespaceDecl *Sema::getOrCreateStdNamespace() {
12276 if (!StdNamespace) {
12277 // The "std" namespace has not yet been defined, so build one implicitly.
12278 StdNamespace = NamespaceDecl::Create(
12279 C&: Context, DC: Context.getTranslationUnitDecl(),
12280 /*Inline=*/false, StartLoc: SourceLocation(), IdLoc: SourceLocation(),
12281 Id: &PP.getIdentifierTable().get(Name: "std"),
12282 /*PrevDecl=*/nullptr, /*Nested=*/false);
12283 getStdNamespace()->setImplicit(true);
12284 // We want the created NamespaceDecl to be available for redeclaration
12285 // lookups, but not for regular name lookups.
12286 Context.getTranslationUnitDecl()->addDecl(D: getStdNamespace());
12287 getStdNamespace()->clearIdentifierNamespace();
12288 }
12289
12290 return getStdNamespace();
12291}
12292
12293static bool isStdClassTemplate(Sema &S, QualType SugaredType, QualType *TypeArg,
12294 const char *ClassName,
12295 ClassTemplateDecl **CachedDecl,
12296 const Decl **MalformedDecl) {
12297 // We're looking for implicit instantiations of
12298 // template <typename U> class std::{ClassName}.
12299
12300 if (!S.StdNamespace) // If we haven't seen namespace std yet, this can't be
12301 // it.
12302 return false;
12303
12304 auto ReportMatchingNameAsMalformed = [&](NamedDecl *D) {
12305 if (!MalformedDecl)
12306 return;
12307 if (!D)
12308 D = SugaredType->getAsTagDecl();
12309 if (!D || !D->isInStdNamespace())
12310 return;
12311 IdentifierInfo *II = D->getDeclName().getAsIdentifierInfo();
12312 if (II && II == &S.PP.getIdentifierTable().get(Name: ClassName))
12313 *MalformedDecl = D;
12314 };
12315
12316 ClassTemplateDecl *Template = nullptr;
12317 ArrayRef<TemplateArgument> Arguments;
12318 if (const TemplateSpecializationType *TST =
12319 SugaredType->getAsNonAliasTemplateSpecializationType()) {
12320 Template = dyn_cast_or_null<ClassTemplateDecl>(
12321 Val: TST->getTemplateName().getAsTemplateDecl());
12322 Arguments = TST->template_arguments();
12323 } else if (const auto *TT = SugaredType->getAs<TagType>()) {
12324 Template = TT->getTemplateDecl();
12325 Arguments = TT->getTemplateArgs(Ctx: S.Context);
12326 }
12327
12328 if (!Template) {
12329 ReportMatchingNameAsMalformed(SugaredType->getAsTagDecl());
12330 return false;
12331 }
12332
12333 if (!*CachedDecl) {
12334 // Haven't recognized std::{ClassName} yet, maybe this is it.
12335 // FIXME: It seems we should just reuse LookupStdClassTemplate but the
12336 // semantics of this are slightly different, most notably the existing
12337 // "lookup" semantics explicitly diagnose an invalid definition as an
12338 // error.
12339 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
12340 if (TemplateClass->getIdentifier() !=
12341 &S.PP.getIdentifierTable().get(Name: ClassName) ||
12342 !S.getStdNamespace()->InEnclosingNamespaceSetOf(
12343 NS: TemplateClass->getNonTransparentDeclContext()))
12344 return false;
12345 // This is a template called std::{ClassName}, but is it the right
12346 // template?
12347 TemplateParameterList *Params = Template->getTemplateParameters();
12348 if (Params->getMinRequiredArguments() != 1 ||
12349 !isa<TemplateTypeParmDecl>(Val: Params->getParam(Idx: 0)) ||
12350 Params->getParam(Idx: 0)->isTemplateParameterPack()) {
12351 if (MalformedDecl)
12352 *MalformedDecl = TemplateClass;
12353 return false;
12354 }
12355
12356 // It's the right template.
12357 *CachedDecl = Template;
12358 }
12359
12360 if (Template->getCanonicalDecl() != (*CachedDecl)->getCanonicalDecl())
12361 return false;
12362
12363 // This is an instance of std::{ClassName}. Find the argument type.
12364 if (TypeArg) {
12365 QualType ArgType = Arguments[0].getAsType();
12366 // FIXME: Since TST only has as-written arguments, we have to perform the
12367 // only kind of conversion applicable to type arguments; in Objective-C ARC:
12368 // - If an explicitly-specified template argument type is a lifetime type
12369 // with no lifetime qualifier, the __strong lifetime qualifier is
12370 // inferred.
12371 if (S.getLangOpts().ObjCAutoRefCount && ArgType->isObjCLifetimeType() &&
12372 !ArgType.getObjCLifetime()) {
12373 Qualifiers Qs;
12374 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
12375 ArgType = S.Context.getQualifiedType(T: ArgType, Qs);
12376 }
12377 *TypeArg = ArgType;
12378 }
12379
12380 return true;
12381}
12382
12383bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
12384 assert(getLangOpts().CPlusPlus &&
12385 "Looking for std::initializer_list outside of C++.");
12386
12387 // We're looking for implicit instantiations of
12388 // template <typename E> class std::initializer_list.
12389
12390 return isStdClassTemplate(S&: *this, SugaredType: Ty, TypeArg: Element, ClassName: "initializer_list",
12391 CachedDecl: &StdInitializerList, /*MalformedDecl=*/nullptr);
12392}
12393
12394bool Sema::isStdTypeIdentity(QualType Ty, QualType *Element,
12395 const Decl **MalformedDecl) {
12396 assert(getLangOpts().CPlusPlus &&
12397 "Looking for std::type_identity outside of C++.");
12398
12399 // We're looking for implicit instantiations of
12400 // template <typename T> struct std::type_identity.
12401
12402 return isStdClassTemplate(S&: *this, SugaredType: Ty, TypeArg: Element, ClassName: "type_identity",
12403 CachedDecl: &StdTypeIdentity, MalformedDecl);
12404}
12405
12406static ClassTemplateDecl *LookupStdClassTemplate(Sema &S, SourceLocation Loc,
12407 const char *ClassName,
12408 bool *WasMalformed) {
12409 if (!S.StdNamespace)
12410 return nullptr;
12411
12412 LookupResult Result(S, &S.PP.getIdentifierTable().get(Name: ClassName), Loc,
12413 Sema::LookupOrdinaryName);
12414 if (!S.LookupQualifiedName(R&: Result, LookupCtx: S.getStdNamespace()))
12415 return nullptr;
12416
12417 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
12418 if (!Template) {
12419 Result.suppressDiagnostics();
12420 // We found something weird. Complain about the first thing we found.
12421 NamedDecl *Found = *Result.begin();
12422 S.Diag(Loc: Found->getLocation(), DiagID: diag::err_malformed_std_class_template)
12423 << ClassName;
12424 if (WasMalformed)
12425 *WasMalformed = true;
12426 return nullptr;
12427 }
12428
12429 // We found some template with the correct name. Now verify that it's
12430 // correct.
12431 TemplateParameterList *Params = Template->getTemplateParameters();
12432 if (Params->getMinRequiredArguments() != 1 ||
12433 !isa<TemplateTypeParmDecl>(Val: Params->getParam(Idx: 0))) {
12434 S.Diag(Loc: Template->getLocation(), DiagID: diag::err_malformed_std_class_template)
12435 << ClassName;
12436 if (WasMalformed)
12437 *WasMalformed = true;
12438 return nullptr;
12439 }
12440
12441 return Template;
12442}
12443
12444static QualType BuildStdClassTemplate(Sema &S, ClassTemplateDecl *CTD,
12445 QualType TypeParam, SourceLocation Loc) {
12446 assert(S.getStdNamespace());
12447 TemplateArgumentListInfo Args(Loc, Loc);
12448 auto TSI = S.Context.getTrivialTypeSourceInfo(T: TypeParam, Loc);
12449 Args.addArgument(Loc: TemplateArgumentLoc(TemplateArgument(TypeParam), TSI));
12450
12451 return S.CheckTemplateIdType(Keyword: ElaboratedTypeKeyword::None, Template: TemplateName(CTD),
12452 TemplateLoc: Loc, TemplateArgs&: Args, /*Scope=*/nullptr,
12453 /*ForNestedNameSpecifier=*/false);
12454}
12455
12456QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
12457 if (!StdInitializerList) {
12458 bool WasMalformed = false;
12459 StdInitializerList =
12460 LookupStdClassTemplate(S&: *this, Loc, ClassName: "initializer_list", WasMalformed: &WasMalformed);
12461 if (!StdInitializerList) {
12462 if (!WasMalformed)
12463 Diag(Loc, DiagID: diag::err_implied_std_initializer_list_not_found);
12464 return QualType();
12465 }
12466 }
12467 return BuildStdClassTemplate(S&: *this, CTD: StdInitializerList, TypeParam: Element, Loc);
12468}
12469
12470QualType Sema::tryBuildStdTypeIdentity(QualType Type, SourceLocation Loc) {
12471 if (!StdTypeIdentity) {
12472 StdTypeIdentity = LookupStdClassTemplate(S&: *this, Loc, ClassName: "type_identity",
12473 /*WasMalformed=*/nullptr);
12474 if (!StdTypeIdentity)
12475 return QualType();
12476 }
12477 return BuildStdClassTemplate(S&: *this, CTD: StdTypeIdentity, TypeParam: Type, Loc);
12478}
12479
12480bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
12481 // C++ [dcl.init.list]p2:
12482 // A constructor is an initializer-list constructor if its first parameter
12483 // is of type std::initializer_list<E> or reference to possibly cv-qualified
12484 // std::initializer_list<E> for some type E, and either there are no other
12485 // parameters or else all other parameters have default arguments.
12486 if (!Ctor->hasOneParamOrDefaultArgs())
12487 return false;
12488
12489 QualType ArgType = Ctor->getParamDecl(i: 0)->getType();
12490 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
12491 ArgType = RT->getPointeeType().getUnqualifiedType();
12492
12493 return isStdInitializerList(Ty: ArgType, Element: nullptr);
12494}
12495
12496/// Determine whether a using statement is in a context where it will be
12497/// apply in all contexts.
12498static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
12499 switch (CurContext->getDeclKind()) {
12500 case Decl::TranslationUnit:
12501 return true;
12502 case Decl::LinkageSpec:
12503 return IsUsingDirectiveInToplevelContext(CurContext: CurContext->getParent());
12504 default:
12505 return false;
12506 }
12507}
12508
12509namespace {
12510
12511// Callback to only accept typo corrections that are namespaces.
12512class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
12513public:
12514 bool ValidateCandidate(const TypoCorrection &candidate) override {
12515 if (NamedDecl *ND = candidate.getCorrectionDecl())
12516 return isa<NamespaceDecl>(Val: ND) || isa<NamespaceAliasDecl>(Val: ND);
12517 return false;
12518 }
12519
12520 std::unique_ptr<CorrectionCandidateCallback> clone() override {
12521 return std::make_unique<NamespaceValidatorCCC>(args&: *this);
12522 }
12523};
12524
12525}
12526
12527static void DiagnoseInvisibleNamespace(const TypoCorrection &Corrected,
12528 Sema &S) {
12529 auto *ND = cast<NamespaceDecl>(Val: Corrected.getFoundDecl());
12530 Module *M = ND->getOwningModule();
12531 assert(M && "hidden namespace definition not in a module?");
12532
12533 if (M->isExplicitGlobalModule())
12534 S.Diag(Loc: Corrected.getCorrectionRange().getBegin(),
12535 DiagID: diag::err_module_unimported_use_header)
12536 << (int)Sema::MissingImportKind::Declaration << Corrected.getFoundDecl()
12537 << /*Header Name*/ false;
12538 else
12539 S.Diag(Loc: Corrected.getCorrectionRange().getBegin(),
12540 DiagID: diag::err_module_unimported_use)
12541 << (int)Sema::MissingImportKind::Declaration << Corrected.getFoundDecl()
12542 << M->getTopLevelModuleName();
12543}
12544
12545static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
12546 CXXScopeSpec &SS,
12547 SourceLocation IdentLoc,
12548 IdentifierInfo *Ident) {
12549 R.clear();
12550 NamespaceValidatorCCC CCC{};
12551 if (TypoCorrection Corrected =
12552 S.CorrectTypo(Typo: R.getLookupNameInfo(), LookupKind: R.getLookupKind(), S: Sc, SS: &SS, CCC,
12553 Mode: CorrectTypoKind::ErrorRecovery)) {
12554 // Generally we find it is confusing more than helpful to diagnose the
12555 // invisible namespace.
12556 // See https://github.com/llvm/llvm-project/issues/73893.
12557 //
12558 // However, we should diagnose when the users are trying to using an
12559 // invisible namespace. So we handle the case specially here.
12560 if (isa_and_nonnull<NamespaceDecl>(Val: Corrected.getFoundDecl()) &&
12561 Corrected.requiresImport()) {
12562 DiagnoseInvisibleNamespace(Corrected, S);
12563 } else if (DeclContext *DC = S.computeDeclContext(SS, EnteringContext: false)) {
12564 std::string CorrectedStr(Corrected.getAsString(LO: S.getLangOpts()));
12565 bool DroppedSpecifier =
12566 Corrected.WillReplaceSpecifier() && Ident->getName() == CorrectedStr;
12567 S.diagnoseTypo(Correction: Corrected,
12568 TypoDiag: S.PDiag(DiagID: diag::err_using_directive_member_suggest)
12569 << Ident << DC << DroppedSpecifier << SS.getRange(),
12570 PrevNote: S.PDiag(DiagID: diag::note_namespace_defined_here));
12571 } else {
12572 S.diagnoseTypo(Correction: Corrected,
12573 TypoDiag: S.PDiag(DiagID: diag::err_using_directive_suggest) << Ident,
12574 PrevNote: S.PDiag(DiagID: diag::note_namespace_defined_here));
12575 }
12576 R.addDecl(D: Corrected.getFoundDecl());
12577 return true;
12578 }
12579 return false;
12580}
12581
12582Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
12583 SourceLocation NamespcLoc, CXXScopeSpec &SS,
12584 SourceLocation IdentLoc,
12585 IdentifierInfo *NamespcName,
12586 const ParsedAttributesView &AttrList) {
12587 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
12588 assert(NamespcName && "Invalid NamespcName.");
12589 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
12590
12591 // Get the innermost enclosing declaration scope.
12592 S = S->getDeclParent();
12593
12594 UsingDirectiveDecl *UDir = nullptr;
12595 NestedNameSpecifier Qualifier = SS.getScopeRep();
12596
12597 // Lookup namespace name.
12598 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
12599 LookupParsedName(R, S, SS: &SS, /*ObjectType=*/QualType());
12600 if (R.isAmbiguous())
12601 return nullptr;
12602
12603 if (R.empty()) {
12604 R.clear();
12605 // Allow "using namespace std;" or "using namespace ::std;" even if
12606 // "std" hasn't been defined yet, for GCC compatibility.
12607 if ((!Qualifier ||
12608 Qualifier.getKind() == NestedNameSpecifier::Kind::Global) &&
12609 NamespcName->isStr(Str: "std")) {
12610 Diag(Loc: IdentLoc, DiagID: diag::ext_using_undefined_std);
12611 R.addDecl(D: getOrCreateStdNamespace());
12612 R.resolveKind();
12613 }
12614 // Otherwise, attempt typo correction.
12615 else
12616 TryNamespaceTypoCorrection(S&: *this, R, Sc: S, SS, IdentLoc, Ident: NamespcName);
12617 }
12618
12619 if (!R.empty()) {
12620 NamedDecl *Named = R.getRepresentativeDecl();
12621 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
12622 assert(NS && "expected namespace decl");
12623
12624 // The use of a nested name specifier may trigger deprecation warnings.
12625 DiagnoseUseOfDecl(D: Named, Locs: IdentLoc);
12626
12627 // C++ [namespace.udir]p1:
12628 // A using-directive specifies that the names in the nominated
12629 // namespace can be used in the scope in which the
12630 // using-directive appears after the using-directive. During
12631 // unqualified name lookup (3.4.1), the names appear as if they
12632 // were declared in the nearest enclosing namespace which
12633 // contains both the using-directive and the nominated
12634 // namespace. [Note: in this context, "contains" means "contains
12635 // directly or indirectly". ]
12636
12637 // Find enclosing context containing both using-directive and
12638 // nominated namespace.
12639 DeclContext *CommonAncestor = NS;
12640 while (CommonAncestor && !CommonAncestor->Encloses(DC: CurContext))
12641 CommonAncestor = CommonAncestor->getParent();
12642
12643 UDir = UsingDirectiveDecl::Create(C&: Context, DC: CurContext, UsingLoc, NamespaceLoc: NamespcLoc,
12644 QualifierLoc: SS.getWithLocInContext(Context),
12645 IdentLoc, Nominated: Named, CommonAncestor);
12646
12647 if (IsUsingDirectiveInToplevelContext(CurContext) &&
12648 !SourceMgr.isInMainFile(Loc: SourceMgr.getExpansionLoc(Loc: IdentLoc))) {
12649 Diag(Loc: IdentLoc, DiagID: diag::warn_using_directive_in_header);
12650 }
12651
12652 PushUsingDirective(S, UDir);
12653 } else {
12654 Diag(Loc: IdentLoc, DiagID: diag::err_expected_namespace_name) << SS.getRange();
12655 }
12656
12657 if (UDir) {
12658 ProcessDeclAttributeList(S, D: UDir, AttrList);
12659 ProcessAPINotes(D: UDir);
12660 }
12661
12662 return UDir;
12663}
12664
12665void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
12666 // If the scope has an associated entity and the using directive is at
12667 // namespace or translation unit scope, add the UsingDirectiveDecl into
12668 // its lookup structure so qualified name lookup can find it.
12669 DeclContext *Ctx = S->getEntity();
12670 if (Ctx && !Ctx->isFunctionOrMethod())
12671 Ctx->addDecl(D: UDir);
12672 else
12673 // Otherwise, it is at block scope. The using-directives will affect lookup
12674 // only to the end of the scope.
12675 S->PushUsingDirective(UDir);
12676}
12677
12678Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
12679 SourceLocation UsingLoc,
12680 SourceLocation TypenameLoc, CXXScopeSpec &SS,
12681 UnqualifiedId &Name,
12682 SourceLocation EllipsisLoc,
12683 const ParsedAttributesView &AttrList) {
12684 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
12685
12686 if (SS.isEmpty()) {
12687 Diag(Loc: Name.getBeginLoc(), DiagID: diag::err_using_requires_qualname);
12688 return nullptr;
12689 }
12690
12691 switch (Name.getKind()) {
12692 case UnqualifiedIdKind::IK_ImplicitSelfParam:
12693 case UnqualifiedIdKind::IK_Identifier:
12694 case UnqualifiedIdKind::IK_OperatorFunctionId:
12695 case UnqualifiedIdKind::IK_LiteralOperatorId:
12696 case UnqualifiedIdKind::IK_ConversionFunctionId:
12697 break;
12698
12699 case UnqualifiedIdKind::IK_ConstructorName:
12700 case UnqualifiedIdKind::IK_ConstructorTemplateId:
12701 // C++11 inheriting constructors.
12702 Diag(Loc: Name.getBeginLoc(),
12703 DiagID: getLangOpts().CPlusPlus11
12704 ? diag::warn_cxx98_compat_using_decl_constructor
12705 : diag::err_using_decl_constructor)
12706 << SS.getRange();
12707
12708 if (getLangOpts().CPlusPlus11) break;
12709
12710 return nullptr;
12711
12712 case UnqualifiedIdKind::IK_DestructorName:
12713 Diag(Loc: Name.getBeginLoc(), DiagID: diag::err_using_decl_destructor) << SS.getRange();
12714 return nullptr;
12715
12716 case UnqualifiedIdKind::IK_TemplateId:
12717 Diag(Loc: Name.getBeginLoc(), DiagID: diag::err_using_decl_template_id)
12718 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
12719 return nullptr;
12720
12721 case UnqualifiedIdKind::IK_DeductionGuideName:
12722 llvm_unreachable("cannot parse qualified deduction guide name");
12723 }
12724
12725 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
12726 DeclarationName TargetName = TargetNameInfo.getName();
12727 if (!TargetName)
12728 return nullptr;
12729
12730 // Warn about access declarations.
12731 if (UsingLoc.isInvalid()) {
12732 Diag(Loc: Name.getBeginLoc(), DiagID: getLangOpts().CPlusPlus11
12733 ? diag::err_access_decl
12734 : diag::warn_access_decl_deprecated)
12735 << FixItHint::CreateInsertion(InsertionLoc: SS.getRange().getBegin(), Code: "using ");
12736 }
12737
12738 if (EllipsisLoc.isInvalid()) {
12739 if (DiagnoseUnexpandedParameterPack(SS, UPPC: UPPC_UsingDeclaration) ||
12740 DiagnoseUnexpandedParameterPack(NameInfo: TargetNameInfo, UPPC: UPPC_UsingDeclaration))
12741 return nullptr;
12742 } else {
12743 if (!SS.getScopeRep().containsUnexpandedParameterPack() &&
12744 !TargetNameInfo.containsUnexpandedParameterPack()) {
12745 Diag(Loc: EllipsisLoc, DiagID: diag::err_pack_expansion_without_parameter_packs)
12746 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
12747 EllipsisLoc = SourceLocation();
12748 }
12749 }
12750
12751 NamedDecl *UD =
12752 BuildUsingDeclaration(S, AS, UsingLoc, HasTypenameKeyword: TypenameLoc.isValid(), TypenameLoc,
12753 SS, NameInfo: TargetNameInfo, EllipsisLoc, AttrList,
12754 /*IsInstantiation*/ false,
12755 IsUsingIfExists: AttrList.hasAttribute(K: ParsedAttr::AT_UsingIfExists));
12756 if (UD)
12757 PushOnScopeChains(D: UD, S, /*AddToContext*/ false);
12758
12759 return UD;
12760}
12761
12762Decl *Sema::ActOnUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
12763 SourceLocation UsingLoc,
12764 SourceLocation EnumLoc, SourceRange TyLoc,
12765 const IdentifierInfo &II, ParsedType Ty,
12766 const CXXScopeSpec &SS) {
12767 TypeSourceInfo *TSI = nullptr;
12768 SourceLocation IdentLoc = TyLoc.getBegin();
12769 QualType EnumTy = GetTypeFromParser(Ty, TInfo: &TSI);
12770 if (EnumTy.isNull()) {
12771 Diag(Loc: IdentLoc, DiagID: isDependentScopeSpecifier(SS)
12772 ? diag::err_using_enum_is_dependent
12773 : diag::err_unknown_typename)
12774 << II.getName()
12775 << SourceRange(SS.isValid() ? SS.getBeginLoc() : IdentLoc,
12776 TyLoc.getEnd());
12777 return nullptr;
12778 }
12779
12780 if (EnumTy->isDependentType()) {
12781 Diag(Loc: IdentLoc, DiagID: diag::err_using_enum_is_dependent);
12782 return nullptr;
12783 }
12784
12785 auto *Enum = EnumTy->getAsEnumDecl();
12786 if (!Enum) {
12787 Diag(Loc: IdentLoc, DiagID: diag::err_using_enum_not_enum) << EnumTy;
12788 return nullptr;
12789 }
12790
12791 if (TSI == nullptr)
12792 TSI = Context.getTrivialTypeSourceInfo(T: EnumTy, Loc: IdentLoc);
12793
12794 auto *UD =
12795 BuildUsingEnumDeclaration(S, AS, UsingLoc, EnumLoc, NameLoc: IdentLoc, EnumType: TSI, ED: Enum);
12796
12797 if (UD)
12798 PushOnScopeChains(D: UD, S, /*AddToContext*/ false);
12799
12800 return UD;
12801}
12802
12803/// Determine whether a using declaration considers the given
12804/// declarations as "equivalent", e.g., if they are redeclarations of
12805/// the same entity or are both typedefs of the same type.
12806static bool
12807IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
12808 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
12809 return true;
12810
12811 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(Val: D1))
12812 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(Val: D2))
12813 return Context.hasSameType(T1: TD1->getUnderlyingType(),
12814 T2: TD2->getUnderlyingType());
12815
12816 // Two using_if_exists using-declarations are equivalent if both are
12817 // unresolved.
12818 if (isa<UnresolvedUsingIfExistsDecl>(Val: D1) &&
12819 isa<UnresolvedUsingIfExistsDecl>(Val: D2))
12820 return true;
12821
12822 return false;
12823}
12824
12825bool Sema::CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Orig,
12826 const LookupResult &Previous,
12827 UsingShadowDecl *&PrevShadow) {
12828 // Diagnose finding a decl which is not from a base class of the
12829 // current class. We do this now because there are cases where this
12830 // function will silently decide not to build a shadow decl, which
12831 // will pre-empt further diagnostics.
12832 //
12833 // We don't need to do this in C++11 because we do the check once on
12834 // the qualifier.
12835 //
12836 // FIXME: diagnose the following if we care enough:
12837 // struct A { int foo; };
12838 // struct B : A { using A::foo; };
12839 // template <class T> struct C : A {};
12840 // template <class T> struct D : C<T> { using B::foo; } // <---
12841 // This is invalid (during instantiation) in C++03 because B::foo
12842 // resolves to the using decl in B, which is not a base class of D<T>.
12843 // We can't diagnose it immediately because C<T> is an unknown
12844 // specialization. The UsingShadowDecl in D<T> then points directly
12845 // to A::foo, which will look well-formed when we instantiate.
12846 // The right solution is to not collapse the shadow-decl chain.
12847 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord())
12848 if (auto *Using = dyn_cast<UsingDecl>(Val: BUD)) {
12849 DeclContext *OrigDC = Orig->getDeclContext();
12850
12851 // Handle enums and anonymous structs.
12852 if (isa<EnumDecl>(Val: OrigDC))
12853 OrigDC = OrigDC->getParent();
12854 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(Val: OrigDC);
12855 while (OrigRec->isAnonymousStructOrUnion())
12856 OrigRec = cast<CXXRecordDecl>(Val: OrigRec->getDeclContext());
12857
12858 if (cast<CXXRecordDecl>(Val: CurContext)->isProvablyNotDerivedFrom(Base: OrigRec)) {
12859 if (OrigDC == CurContext) {
12860 Diag(Loc: Using->getLocation(),
12861 DiagID: diag::err_using_decl_nested_name_specifier_is_current_class)
12862 << Using->getQualifierLoc().getSourceRange();
12863 Diag(Loc: Orig->getLocation(), DiagID: diag::note_using_decl_target);
12864 Using->setInvalidDecl();
12865 return true;
12866 }
12867
12868 Diag(Loc: Using->getQualifierLoc().getBeginLoc(),
12869 DiagID: diag::err_using_decl_nested_name_specifier_is_not_base_class)
12870 << Using->getQualifier() << cast<CXXRecordDecl>(Val: CurContext)
12871 << Using->getQualifierLoc().getSourceRange();
12872 Diag(Loc: Orig->getLocation(), DiagID: diag::note_using_decl_target);
12873 Using->setInvalidDecl();
12874 return true;
12875 }
12876 }
12877
12878 if (Previous.empty()) return false;
12879
12880 NamedDecl *Target = Orig;
12881 if (isa<UsingShadowDecl>(Val: Target))
12882 Target = cast<UsingShadowDecl>(Val: Target)->getTargetDecl();
12883
12884 // If the target happens to be one of the previous declarations, we
12885 // don't have a conflict.
12886 //
12887 // FIXME: but we might be increasing its access, in which case we
12888 // should redeclare it.
12889 NamedDecl *NonTag = nullptr, *Tag = nullptr;
12890 bool FoundEquivalentDecl = false;
12891 for (NamedDecl *Element : Previous) {
12892 NamedDecl *D = Element->getUnderlyingDecl();
12893 // We can have UsingDecls in our Previous results because we use the same
12894 // LookupResult for checking whether the UsingDecl itself is a valid
12895 // redeclaration.
12896 if (isa<UsingDecl>(Val: D) || isa<UsingPackDecl>(Val: D) || isa<UsingEnumDecl>(Val: D))
12897 continue;
12898
12899 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: D)) {
12900 // C++ [class.mem]p19:
12901 // If T is the name of a class, then [every named member other than
12902 // a non-static data member] shall have a name different from T
12903 if (RD->isInjectedClassName() && !isa<FieldDecl>(Val: Target) &&
12904 !isa<IndirectFieldDecl>(Val: Target) &&
12905 !isa<UnresolvedUsingValueDecl>(Val: Target) &&
12906 DiagnoseClassNameShadow(
12907 DC: CurContext,
12908 Info: DeclarationNameInfo(BUD->getDeclName(), BUD->getLocation())))
12909 return true;
12910 }
12911
12912 if (IsEquivalentForUsingDecl(Context, D1: D, D2: Target)) {
12913 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Val: Element))
12914 PrevShadow = Shadow;
12915 FoundEquivalentDecl = true;
12916 } else if (isEquivalentInternalLinkageDeclaration(A: D, B: Target)) {
12917 // We don't conflict with an existing using shadow decl of an equivalent
12918 // declaration, but we're not a redeclaration of it.
12919 FoundEquivalentDecl = true;
12920 }
12921
12922 if (isVisible(D))
12923 (isa<TagDecl>(Val: D) ? Tag : NonTag) = D;
12924 }
12925
12926 if (FoundEquivalentDecl)
12927 return false;
12928
12929 // Always emit a diagnostic for a mismatch between an unresolved
12930 // using_if_exists and a resolved using declaration in either direction.
12931 if (isa<UnresolvedUsingIfExistsDecl>(Val: Target) !=
12932 (isa_and_nonnull<UnresolvedUsingIfExistsDecl>(Val: NonTag))) {
12933 if (!NonTag && !Tag)
12934 return false;
12935 Diag(Loc: BUD->getLocation(), DiagID: diag::err_using_decl_conflict);
12936 Diag(Loc: Target->getLocation(), DiagID: diag::note_using_decl_target);
12937 Diag(Loc: (NonTag ? NonTag : Tag)->getLocation(),
12938 DiagID: diag::note_using_decl_conflict);
12939 BUD->setInvalidDecl();
12940 return true;
12941 }
12942
12943 if (FunctionDecl *FD = Target->getAsFunction()) {
12944 NamedDecl *OldDecl = nullptr;
12945 switch (CheckOverload(S: nullptr, New: FD, OldDecls: Previous, OldDecl,
12946 /*IsForUsingDecl*/ UseMemberUsingDeclRules: true)) {
12947 case OverloadKind::Overload:
12948 return false;
12949
12950 case OverloadKind::NonFunction:
12951 Diag(Loc: BUD->getLocation(), DiagID: diag::err_using_decl_conflict);
12952 break;
12953
12954 // We found a decl with the exact signature.
12955 case OverloadKind::Match:
12956 // If we're in a record, we want to hide the target, so we
12957 // return true (without a diagnostic) to tell the caller not to
12958 // build a shadow decl.
12959 if (CurContext->isRecord())
12960 return true;
12961
12962 // If we're not in a record, this is an error.
12963 Diag(Loc: BUD->getLocation(), DiagID: diag::err_using_decl_conflict);
12964 break;
12965 }
12966
12967 Diag(Loc: Target->getLocation(), DiagID: diag::note_using_decl_target);
12968 Diag(Loc: OldDecl->getLocation(), DiagID: diag::note_using_decl_conflict);
12969 BUD->setInvalidDecl();
12970 return true;
12971 }
12972
12973 // Target is not a function.
12974
12975 if (isa<TagDecl>(Val: Target)) {
12976 // No conflict between a tag and a non-tag.
12977 if (!Tag) return false;
12978
12979 Diag(Loc: BUD->getLocation(), DiagID: diag::err_using_decl_conflict);
12980 Diag(Loc: Target->getLocation(), DiagID: diag::note_using_decl_target);
12981 Diag(Loc: Tag->getLocation(), DiagID: diag::note_using_decl_conflict);
12982 BUD->setInvalidDecl();
12983 return true;
12984 }
12985
12986 // No conflict between a tag and a non-tag.
12987 if (!NonTag) return false;
12988
12989 Diag(Loc: BUD->getLocation(), DiagID: diag::err_using_decl_conflict);
12990 Diag(Loc: Target->getLocation(), DiagID: diag::note_using_decl_target);
12991 Diag(Loc: NonTag->getLocation(), DiagID: diag::note_using_decl_conflict);
12992 BUD->setInvalidDecl();
12993 return true;
12994}
12995
12996/// Determine whether a direct base class is a virtual base class.
12997static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
12998 if (!Derived->getNumVBases())
12999 return false;
13000 for (auto &B : Derived->bases())
13001 if (B.getType()->getAsCXXRecordDecl() == Base)
13002 return B.isVirtual();
13003 llvm_unreachable("not a direct base class");
13004}
13005
13006UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD,
13007 NamedDecl *Orig,
13008 UsingShadowDecl *PrevDecl) {
13009 // If we resolved to another shadow declaration, just coalesce them.
13010 NamedDecl *Target = Orig;
13011 if (isa<UsingShadowDecl>(Val: Target)) {
13012 Target = cast<UsingShadowDecl>(Val: Target)->getTargetDecl();
13013 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
13014 }
13015
13016 NamedDecl *NonTemplateTarget = Target;
13017 if (auto *TargetTD = dyn_cast<TemplateDecl>(Val: Target))
13018 NonTemplateTarget = TargetTD->getTemplatedDecl();
13019
13020 UsingShadowDecl *Shadow;
13021 if (NonTemplateTarget && isa<CXXConstructorDecl>(Val: NonTemplateTarget)) {
13022 UsingDecl *Using = cast<UsingDecl>(Val: BUD);
13023 bool IsVirtualBase =
13024 isVirtualDirectBase(Derived: cast<CXXRecordDecl>(Val: CurContext),
13025 Base: Using->getQualifier().getAsRecordDecl());
13026 Shadow = ConstructorUsingShadowDecl::Create(
13027 C&: Context, DC: CurContext, Loc: Using->getLocation(), Using, Target: Orig, IsVirtual: IsVirtualBase);
13028 } else {
13029 Shadow = UsingShadowDecl::Create(C&: Context, DC: CurContext, Loc: BUD->getLocation(),
13030 Name: Target->getDeclName(), Introducer: BUD, Target);
13031 }
13032 BUD->addShadowDecl(S: Shadow);
13033
13034 Shadow->setAccess(BUD->getAccess());
13035 if (Orig->isInvalidDecl() || BUD->isInvalidDecl())
13036 Shadow->setInvalidDecl();
13037
13038 Shadow->setPreviousDecl(PrevDecl);
13039
13040 if (S)
13041 PushOnScopeChains(D: Shadow, S);
13042 else
13043 CurContext->addDecl(D: Shadow);
13044
13045
13046 return Shadow;
13047}
13048
13049void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
13050 if (Shadow->getDeclName().getNameKind() ==
13051 DeclarationName::CXXConversionFunctionName)
13052 cast<CXXRecordDecl>(Val: Shadow->getDeclContext())->removeConversion(Old: Shadow);
13053
13054 // Remove it from the DeclContext...
13055 Shadow->getDeclContext()->removeDecl(D: Shadow);
13056
13057 // ...and the scope, if applicable...
13058 if (S) {
13059 S->RemoveDecl(D: Shadow);
13060 IdResolver.RemoveDecl(D: Shadow);
13061 }
13062
13063 // ...and the using decl.
13064 Shadow->getIntroducer()->removeShadowDecl(S: Shadow);
13065
13066 // TODO: complain somehow if Shadow was used. It shouldn't
13067 // be possible for this to happen, because...?
13068}
13069
13070/// Find the base specifier for a base class with the given type.
13071static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
13072 QualType DesiredBase,
13073 bool &AnyDependentBases) {
13074 // Check whether the named type is a direct base class.
13075 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
13076 for (auto &Base : Derived->bases()) {
13077 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
13078 if (CanonicalDesiredBase == BaseType)
13079 return &Base;
13080 if (BaseType->isDependentType())
13081 AnyDependentBases = true;
13082 }
13083 return nullptr;
13084}
13085
13086namespace {
13087class UsingValidatorCCC final : public CorrectionCandidateCallback {
13088public:
13089 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
13090 NestedNameSpecifier NNS, CXXRecordDecl *RequireMemberOf)
13091 : HasTypenameKeyword(HasTypenameKeyword),
13092 IsInstantiation(IsInstantiation), OldNNS(NNS),
13093 RequireMemberOf(RequireMemberOf) {}
13094
13095 bool ValidateCandidate(const TypoCorrection &Candidate) override {
13096 NamedDecl *ND = Candidate.getCorrectionDecl();
13097
13098 // Keywords are not valid here.
13099 if (!ND || isa<NamespaceDecl>(Val: ND))
13100 return false;
13101
13102 // Completely unqualified names are invalid for a 'using' declaration.
13103 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
13104 return false;
13105
13106 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
13107 // reject.
13108
13109 if (RequireMemberOf) {
13110 auto *FoundRecord = dyn_cast<CXXRecordDecl>(Val: ND);
13111 if (FoundRecord && FoundRecord->isInjectedClassName()) {
13112 // No-one ever wants a using-declaration to name an injected-class-name
13113 // of a base class, unless they're declaring an inheriting constructor.
13114 ASTContext &Ctx = ND->getASTContext();
13115 if (!Ctx.getLangOpts().CPlusPlus11)
13116 return false;
13117 CanQualType FoundType = Ctx.getCanonicalTagType(TD: FoundRecord);
13118
13119 // Check that the injected-class-name is named as a member of its own
13120 // type; we don't want to suggest 'using Derived::Base;', since that
13121 // means something else.
13122 NestedNameSpecifier Specifier = Candidate.WillReplaceSpecifier()
13123 ? Candidate.getCorrectionSpecifier()
13124 : OldNNS;
13125 if (Specifier.getKind() != NestedNameSpecifier::Kind::Type ||
13126 !Ctx.hasSameType(T1: QualType(Specifier.getAsType(), 0), T2: FoundType))
13127 return false;
13128
13129 // Check that this inheriting constructor declaration actually names a
13130 // direct base class of the current class.
13131 bool AnyDependentBases = false;
13132 if (!findDirectBaseWithType(Derived: RequireMemberOf,
13133 DesiredBase: Ctx.getCanonicalTagType(TD: FoundRecord),
13134 AnyDependentBases) &&
13135 !AnyDependentBases)
13136 return false;
13137 } else {
13138 auto *RD = dyn_cast<CXXRecordDecl>(Val: ND->getDeclContext());
13139 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(Base: RD))
13140 return false;
13141
13142 // FIXME: Check that the base class member is accessible?
13143 }
13144 } else {
13145 auto *FoundRecord = dyn_cast<CXXRecordDecl>(Val: ND);
13146 if (FoundRecord && FoundRecord->isInjectedClassName())
13147 return false;
13148 }
13149
13150 if (isa<TypeDecl>(Val: ND))
13151 return HasTypenameKeyword || !IsInstantiation;
13152
13153 return !HasTypenameKeyword;
13154 }
13155
13156 std::unique_ptr<CorrectionCandidateCallback> clone() override {
13157 return std::make_unique<UsingValidatorCCC>(args&: *this);
13158 }
13159
13160private:
13161 bool HasTypenameKeyword;
13162 bool IsInstantiation;
13163 NestedNameSpecifier OldNNS;
13164 CXXRecordDecl *RequireMemberOf;
13165};
13166} // end anonymous namespace
13167
13168void Sema::FilterUsingLookup(Scope *S, LookupResult &Previous) {
13169 // It is really dumb that we have to do this.
13170 LookupResult::Filter F = Previous.makeFilter();
13171 while (F.hasNext()) {
13172 NamedDecl *D = F.next();
13173 if (!isDeclInScope(D, Ctx: CurContext, S))
13174 F.erase();
13175 // If we found a local extern declaration that's not ordinarily visible,
13176 // and this declaration is being added to a non-block scope, ignore it.
13177 // We're only checking for scope conflicts here, not also for violations
13178 // of the linkage rules.
13179 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
13180 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
13181 F.erase();
13182 }
13183 F.done();
13184}
13185
13186NamedDecl *Sema::BuildUsingDeclaration(
13187 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
13188 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
13189 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
13190 const ParsedAttributesView &AttrList, bool IsInstantiation,
13191 bool IsUsingIfExists) {
13192 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
13193 SourceLocation IdentLoc = NameInfo.getLoc();
13194 assert(IdentLoc.isValid() && "Invalid TargetName location.");
13195
13196 // FIXME: We ignore attributes for now.
13197
13198 // For an inheriting constructor declaration, the name of the using
13199 // declaration is the name of a constructor in this class, not in the
13200 // base class.
13201 DeclarationNameInfo UsingName = NameInfo;
13202 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
13203 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: CurContext))
13204 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
13205 Ty: Context.getCanonicalTagType(TD: RD)));
13206
13207 // Do the redeclaration lookup in the current scope.
13208 LookupResult Previous(*this, UsingName, LookupUsingDeclName,
13209 RedeclarationKind::ForVisibleRedeclaration);
13210 Previous.setHideTags(false);
13211 if (S) {
13212 LookupName(R&: Previous, S);
13213
13214 FilterUsingLookup(S, Previous);
13215 } else {
13216 assert(IsInstantiation && "no scope in non-instantiation");
13217 if (CurContext->isRecord())
13218 LookupQualifiedName(R&: Previous, LookupCtx: CurContext);
13219 else {
13220 // No redeclaration check is needed here; in non-member contexts we
13221 // diagnosed all possible conflicts with other using-declarations when
13222 // building the template:
13223 //
13224 // For a dependent non-type using declaration, the only valid case is
13225 // if we instantiate to a single enumerator. We check for conflicts
13226 // between shadow declarations we introduce, and we check in the template
13227 // definition for conflicts between a non-type using declaration and any
13228 // other declaration, which together covers all cases.
13229 //
13230 // A dependent typename using declaration will never successfully
13231 // instantiate, since it will always name a class member, so we reject
13232 // that in the template definition.
13233 }
13234 }
13235
13236 // Check for invalid redeclarations.
13237 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
13238 SS, NameLoc: IdentLoc, Previous))
13239 return nullptr;
13240
13241 // 'using_if_exists' doesn't make sense on an inherited constructor.
13242 if (IsUsingIfExists && UsingName.getName().getNameKind() ==
13243 DeclarationName::CXXConstructorName) {
13244 Diag(Loc: UsingLoc, DiagID: diag::err_using_if_exists_on_ctor);
13245 return nullptr;
13246 }
13247
13248 DeclContext *LookupContext = computeDeclContext(SS);
13249 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
13250 if (!LookupContext || EllipsisLoc.isValid()) {
13251 NamedDecl *D;
13252 // Dependent scope, or an unexpanded pack
13253 if (!LookupContext && CheckUsingDeclQualifier(UsingLoc, HasTypename: HasTypenameKeyword,
13254 SS, NameInfo, NameLoc: IdentLoc))
13255 return nullptr;
13256
13257 if (Previous.isSingleResult() &&
13258 Previous.getFoundDecl()->isTemplateParameter())
13259 DiagnoseTemplateParameterShadow(Loc: IdentLoc, PrevDecl: Previous.getFoundDecl());
13260
13261 if (HasTypenameKeyword) {
13262 // FIXME: not all declaration name kinds are legal here
13263 D = UnresolvedUsingTypenameDecl::Create(C&: Context, DC: CurContext,
13264 UsingLoc, TypenameLoc,
13265 QualifierLoc,
13266 TargetNameLoc: IdentLoc, TargetName: NameInfo.getName(),
13267 EllipsisLoc);
13268 } else {
13269 D = UnresolvedUsingValueDecl::Create(C&: Context, DC: CurContext, UsingLoc,
13270 QualifierLoc, NameInfo, EllipsisLoc);
13271 }
13272 D->setAccess(AS);
13273 CurContext->addDecl(D);
13274 ProcessDeclAttributeList(S, D, AttrList);
13275 return D;
13276 }
13277
13278 auto Build = [&](bool Invalid) {
13279 UsingDecl *UD =
13280 UsingDecl::Create(C&: Context, DC: CurContext, UsingL: UsingLoc, QualifierLoc,
13281 NameInfo: UsingName, HasTypenameKeyword);
13282 UD->setAccess(AS);
13283 CurContext->addDecl(D: UD);
13284 ProcessDeclAttributeList(S, D: UD, AttrList);
13285 UD->setInvalidDecl(Invalid);
13286 return UD;
13287 };
13288 auto BuildInvalid = [&]{ return Build(true); };
13289 auto BuildValid = [&]{ return Build(false); };
13290
13291 if (RequireCompleteDeclContext(SS, DC: LookupContext))
13292 return BuildInvalid();
13293
13294 // Look up the target name.
13295 LookupResult R(*this, NameInfo, LookupOrdinaryName);
13296
13297 // Unlike most lookups, we don't always want to hide tag
13298 // declarations: tag names are visible through the using declaration
13299 // even if hidden by ordinary names, *except* in a dependent context
13300 // where they may be used by two-phase lookup.
13301 if (!IsInstantiation)
13302 R.setHideTags(false);
13303
13304 // For the purposes of this lookup, we have a base object type
13305 // equal to that of the current context.
13306 if (CurContext->isRecord()) {
13307 R.setBaseObjectType(
13308 Context.getCanonicalTagType(TD: cast<CXXRecordDecl>(Val: CurContext)));
13309 }
13310
13311 LookupQualifiedName(R, LookupCtx: LookupContext);
13312
13313 // Validate the context, now we have a lookup
13314 if (CheckUsingDeclQualifier(UsingLoc, HasTypename: HasTypenameKeyword, SS, NameInfo,
13315 NameLoc: IdentLoc, R: &R))
13316 return nullptr;
13317
13318 if (R.empty() && IsUsingIfExists)
13319 R.addDecl(D: UnresolvedUsingIfExistsDecl::Create(Ctx&: Context, DC: CurContext, Loc: UsingLoc,
13320 Name: UsingName.getName()),
13321 AS: AS_public);
13322
13323 // Try to correct typos if possible. If constructor name lookup finds no
13324 // results, that means the named class has no explicit constructors, and we
13325 // suppressed declaring implicit ones (probably because it's dependent or
13326 // invalid).
13327 if (R.empty() &&
13328 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
13329 // HACK 2017-01-08: Work around an issue with libstdc++'s detection of
13330 // ::gets. Sometimes it believes that glibc provides a ::gets in cases where
13331 // it does not. The issue was fixed in libstdc++ 6.3 (2016-12-21) and later.
13332 auto *II = NameInfo.getName().getAsIdentifierInfo();
13333 if (getLangOpts().CPlusPlus14 && II && II->isStr(Str: "gets") &&
13334 CurContext->isStdNamespace() &&
13335 isa<TranslationUnitDecl>(Val: LookupContext) &&
13336 PP.NeedsStdLibCxxWorkaroundBefore(FixedVersion: 2016'12'21) &&
13337 getSourceManager().isInSystemHeader(Loc: UsingLoc))
13338 return nullptr;
13339 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
13340 dyn_cast<CXXRecordDecl>(Val: CurContext));
13341 if (TypoCorrection Corrected =
13342 CorrectTypo(Typo: R.getLookupNameInfo(), LookupKind: R.getLookupKind(), S, SS: &SS, CCC,
13343 Mode: CorrectTypoKind::ErrorRecovery)) {
13344 // We reject candidates where DroppedSpecifier == true, hence the
13345 // literal '0' below.
13346 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: diag::err_no_member_suggest)
13347 << NameInfo.getName() << LookupContext << 0
13348 << SS.getRange());
13349
13350 // If we picked a correction with no attached Decl we can't do anything
13351 // useful with it, bail out.
13352 NamedDecl *ND = Corrected.getCorrectionDecl();
13353 if (!ND)
13354 return BuildInvalid();
13355
13356 // If we corrected to an inheriting constructor, handle it as one.
13357 auto *RD = dyn_cast<CXXRecordDecl>(Val: ND);
13358 if (RD && RD->isInjectedClassName()) {
13359 // The parent of the injected class name is the class itself.
13360 RD = cast<CXXRecordDecl>(Val: RD->getParent());
13361
13362 // Fix up the information we'll use to build the using declaration.
13363 if (Corrected.WillReplaceSpecifier()) {
13364 NestedNameSpecifierLocBuilder Builder;
13365 Builder.MakeTrivial(Context, Qualifier: Corrected.getCorrectionSpecifier(),
13366 R: QualifierLoc.getSourceRange());
13367 QualifierLoc = Builder.getWithLocInContext(Context);
13368 }
13369
13370 // In this case, the name we introduce is the name of a derived class
13371 // constructor.
13372 auto *CurClass = cast<CXXRecordDecl>(Val: CurContext);
13373 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
13374 Ty: Context.getCanonicalTagType(TD: CurClass)));
13375 UsingName.setNamedTypeInfo(nullptr);
13376 for (auto *Ctor : LookupConstructors(Class: RD))
13377 R.addDecl(D: Ctor);
13378 R.resolveKind();
13379 } else {
13380 // FIXME: Pick up all the declarations if we found an overloaded
13381 // function.
13382 UsingName.setName(ND->getDeclName());
13383 R.addDecl(D: ND);
13384 }
13385 } else {
13386 Diag(Loc: IdentLoc, DiagID: diag::err_no_member)
13387 << NameInfo.getName() << LookupContext << SS.getRange();
13388 return BuildInvalid();
13389 }
13390 }
13391
13392 if (R.isAmbiguous())
13393 return BuildInvalid();
13394
13395 if (HasTypenameKeyword) {
13396 // If we asked for a typename and got a non-type decl, error out.
13397 if (!R.getAsSingle<TypeDecl>() &&
13398 !R.getAsSingle<UnresolvedUsingIfExistsDecl>()) {
13399 Diag(Loc: IdentLoc, DiagID: diag::err_using_typename_non_type);
13400 for (const NamedDecl *D : R)
13401 Diag(Loc: D->getUnderlyingDecl()->getLocation(),
13402 DiagID: diag::note_using_decl_target);
13403 return BuildInvalid();
13404 }
13405 } else {
13406 // If we asked for a non-typename and we got a type, error out,
13407 // but only if this is an instantiation of an unresolved using
13408 // decl. Otherwise just silently find the type name.
13409 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
13410 Diag(Loc: IdentLoc, DiagID: diag::err_using_dependent_value_is_type);
13411 Diag(Loc: R.getFoundDecl()->getLocation(), DiagID: diag::note_using_decl_target);
13412 return BuildInvalid();
13413 }
13414 }
13415
13416 // C++14 [namespace.udecl]p6:
13417 // A using-declaration shall not name a namespace.
13418 if (R.getAsSingle<NamespaceDecl>()) {
13419 Diag(Loc: IdentLoc, DiagID: diag::err_using_decl_can_not_refer_to_namespace)
13420 << SS.getRange();
13421 // Suggest using 'using namespace ...' instead.
13422 Diag(Loc: SS.getBeginLoc(), DiagID: diag::note_namespace_using_decl)
13423 << FixItHint::CreateInsertion(InsertionLoc: SS.getBeginLoc(), Code: "namespace ");
13424 return BuildInvalid();
13425 }
13426
13427 UsingDecl *UD = BuildValid();
13428
13429 // Some additional rules apply to inheriting constructors.
13430 if (UsingName.getName().getNameKind() ==
13431 DeclarationName::CXXConstructorName) {
13432 // Suppress access diagnostics; the access check is instead performed at the
13433 // point of use for an inheriting constructor.
13434 R.suppressDiagnostics();
13435 if (CheckInheritingConstructorUsingDecl(UD))
13436 return UD;
13437 }
13438
13439 for (NamedDecl *D : R) {
13440 UsingShadowDecl *PrevDecl = nullptr;
13441 if (!CheckUsingShadowDecl(BUD: UD, Orig: D, Previous, PrevShadow&: PrevDecl))
13442 BuildUsingShadowDecl(S, BUD: UD, Orig: D, PrevDecl);
13443 }
13444
13445 return UD;
13446}
13447
13448NamedDecl *Sema::BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
13449 SourceLocation UsingLoc,
13450 SourceLocation EnumLoc,
13451 SourceLocation NameLoc,
13452 TypeSourceInfo *EnumType,
13453 EnumDecl *ED) {
13454 bool Invalid = false;
13455
13456 if (CurContext->getRedeclContext()->isRecord()) {
13457 /// In class scope, check if this is a duplicate, for better a diagnostic.
13458 DeclarationNameInfo UsingEnumName(ED->getDeclName(), NameLoc);
13459 LookupResult Previous(*this, UsingEnumName, LookupUsingDeclName,
13460 RedeclarationKind::ForVisibleRedeclaration);
13461
13462 LookupQualifiedName(R&: Previous, LookupCtx: CurContext);
13463
13464 for (NamedDecl *D : Previous)
13465 if (UsingEnumDecl *UED = dyn_cast<UsingEnumDecl>(Val: D))
13466 if (UED->getEnumDecl() == ED) {
13467 Diag(Loc: UsingLoc, DiagID: diag::err_using_enum_decl_redeclaration)
13468 << SourceRange(EnumLoc, NameLoc);
13469 Diag(Loc: D->getLocation(), DiagID: diag::note_using_enum_decl) << 1;
13470 Invalid = true;
13471 break;
13472 }
13473 }
13474
13475 if (RequireCompleteEnumDecl(D: ED, L: NameLoc))
13476 Invalid = true;
13477
13478 UsingEnumDecl *UD = UsingEnumDecl::Create(C&: Context, DC: CurContext, UsingL: UsingLoc,
13479 EnumL: EnumLoc, NameL: NameLoc, EnumType);
13480 UD->setAccess(AS);
13481 CurContext->addDecl(D: UD);
13482
13483 if (Invalid) {
13484 UD->setInvalidDecl();
13485 return UD;
13486 }
13487
13488 // Create the shadow decls for each enumerator
13489 for (EnumConstantDecl *EC : ED->enumerators()) {
13490 UsingShadowDecl *PrevDecl = nullptr;
13491 DeclarationNameInfo DNI(EC->getDeclName(), EC->getLocation());
13492 LookupResult Previous(*this, DNI, LookupOrdinaryName,
13493 RedeclarationKind::ForVisibleRedeclaration);
13494 LookupName(R&: Previous, S);
13495 FilterUsingLookup(S, Previous);
13496
13497 if (!CheckUsingShadowDecl(BUD: UD, Orig: EC, Previous, PrevShadow&: PrevDecl))
13498 BuildUsingShadowDecl(S, BUD: UD, Orig: EC, PrevDecl);
13499 }
13500
13501 return UD;
13502}
13503
13504NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
13505 ArrayRef<NamedDecl *> Expansions) {
13506 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
13507 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
13508 isa<UsingPackDecl>(InstantiatedFrom));
13509
13510 auto *UPD =
13511 UsingPackDecl::Create(C&: Context, DC: CurContext, InstantiatedFrom, UsingDecls: Expansions);
13512 UPD->setAccess(InstantiatedFrom->getAccess());
13513 CurContext->addDecl(D: UPD);
13514 return UPD;
13515}
13516
13517bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
13518 assert(!UD->hasTypename() && "expecting a constructor name");
13519
13520 QualType SourceType(UD->getQualifier().getAsType(), 0);
13521 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(Val: CurContext);
13522
13523 // Check whether the named type is a direct base class.
13524 bool AnyDependentBases = false;
13525 auto *Base =
13526 findDirectBaseWithType(Derived: TargetClass, DesiredBase: SourceType, AnyDependentBases);
13527 if (!Base && !AnyDependentBases) {
13528 Diag(Loc: UD->getUsingLoc(), DiagID: diag::err_using_decl_constructor_not_in_direct_base)
13529 << UD->getNameInfo().getSourceRange() << SourceType << TargetClass;
13530 UD->setInvalidDecl();
13531 return true;
13532 }
13533
13534 if (Base)
13535 Base->setInheritConstructors();
13536
13537 return false;
13538}
13539
13540bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
13541 bool HasTypenameKeyword,
13542 const CXXScopeSpec &SS,
13543 SourceLocation NameLoc,
13544 const LookupResult &Prev) {
13545 NestedNameSpecifier Qual = SS.getScopeRep();
13546
13547 // C++03 [namespace.udecl]p8:
13548 // C++0x [namespace.udecl]p10:
13549 // A using-declaration is a declaration and can therefore be used
13550 // repeatedly where (and only where) multiple declarations are
13551 // allowed.
13552 //
13553 // That's in non-member contexts.
13554 if (!CurContext->getRedeclContext()->isRecord()) {
13555 // A dependent qualifier outside a class can only ever resolve to an
13556 // enumeration type. Therefore it conflicts with any other non-type
13557 // declaration in the same scope.
13558 // FIXME: How should we check for dependent type-type conflicts at block
13559 // scope?
13560 if (Qual.isDependent() && !HasTypenameKeyword) {
13561 for (auto *D : Prev) {
13562 if (!isa<TypeDecl>(Val: D) && !isa<UsingDecl>(Val: D) && !isa<UsingPackDecl>(Val: D)) {
13563 bool OldCouldBeEnumerator =
13564 isa<UnresolvedUsingValueDecl>(Val: D) || isa<EnumConstantDecl>(Val: D);
13565 Diag(Loc: NameLoc,
13566 DiagID: OldCouldBeEnumerator ? diag::err_redefinition
13567 : diag::err_redefinition_different_kind)
13568 << Prev.getLookupName();
13569 Diag(Loc: D->getLocation(), DiagID: diag::note_previous_definition);
13570 return true;
13571 }
13572 }
13573 }
13574 return false;
13575 }
13576
13577 NestedNameSpecifier CNNS = Qual.getCanonical();
13578 for (const NamedDecl *D : Prev) {
13579 bool DTypename;
13580 NestedNameSpecifier DQual = std::nullopt;
13581 if (const auto *UD = dyn_cast<UsingDecl>(Val: D)) {
13582 DTypename = UD->hasTypename();
13583 DQual = UD->getQualifier();
13584 } else if (const auto *UD = dyn_cast<UnresolvedUsingValueDecl>(Val: D)) {
13585 DTypename = false;
13586 DQual = UD->getQualifier();
13587 } else if (const auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(Val: D)) {
13588 DTypename = true;
13589 DQual = UD->getQualifier();
13590 } else
13591 continue;
13592
13593 // using decls differ if one says 'typename' and the other doesn't.
13594 // FIXME: non-dependent using decls?
13595 if (HasTypenameKeyword != DTypename) continue;
13596
13597 // using decls differ if they name different scopes (but note that
13598 // template instantiation can cause this check to trigger when it
13599 // didn't before instantiation).
13600 if (CNNS != DQual.getCanonical())
13601 continue;
13602
13603 Diag(Loc: NameLoc, DiagID: diag::err_using_decl_redeclaration) << SS.getRange();
13604 Diag(Loc: D->getLocation(), DiagID: diag::note_using_decl) << 1;
13605 return true;
13606 }
13607
13608 return false;
13609}
13610
13611bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
13612 const CXXScopeSpec &SS,
13613 const DeclarationNameInfo &NameInfo,
13614 SourceLocation NameLoc,
13615 const LookupResult *R, const UsingDecl *UD) {
13616 DeclContext *NamedContext = computeDeclContext(SS);
13617 assert(bool(NamedContext) == (R || UD) && !(R && UD) &&
13618 "resolvable context must have exactly one set of decls");
13619
13620 // C++ 20 permits using an enumerator that does not have a class-hierarchy
13621 // relationship.
13622 bool Cxx20Enumerator = false;
13623 if (NamedContext) {
13624 EnumConstantDecl *EC = nullptr;
13625 if (R)
13626 EC = R->getAsSingle<EnumConstantDecl>();
13627 else if (UD && UD->shadow_size() == 1)
13628 EC = dyn_cast<EnumConstantDecl>(Val: UD->shadow_begin()->getTargetDecl());
13629 if (EC)
13630 Cxx20Enumerator = getLangOpts().CPlusPlus20;
13631
13632 if (auto *ED = dyn_cast<EnumDecl>(Val: NamedContext)) {
13633 // C++14 [namespace.udecl]p7:
13634 // A using-declaration shall not name a scoped enumerator.
13635 // C++20 p1099 permits enumerators.
13636 if (EC && R && ED->isScoped())
13637 Diag(Loc: SS.getBeginLoc(),
13638 DiagID: getLangOpts().CPlusPlus20
13639 ? diag::warn_cxx17_compat_using_decl_scoped_enumerator
13640 : diag::ext_using_decl_scoped_enumerator)
13641 << SS.getRange();
13642
13643 // We want to consider the scope of the enumerator
13644 NamedContext = ED->getDeclContext();
13645 }
13646 }
13647
13648 if (!CurContext->isRecord()) {
13649 // C++03 [namespace.udecl]p3:
13650 // C++0x [namespace.udecl]p8:
13651 // A using-declaration for a class member shall be a member-declaration.
13652 // C++20 [namespace.udecl]p7
13653 // ... other than an enumerator ...
13654
13655 // If we weren't able to compute a valid scope, it might validly be a
13656 // dependent class or enumeration scope. If we have a 'typename' keyword,
13657 // the scope must resolve to a class type.
13658 if (NamedContext ? !NamedContext->getRedeclContext()->isRecord()
13659 : !HasTypename)
13660 return false; // OK
13661
13662 Diag(Loc: NameLoc,
13663 DiagID: Cxx20Enumerator
13664 ? diag::warn_cxx17_compat_using_decl_class_member_enumerator
13665 : diag::err_using_decl_can_not_refer_to_class_member)
13666 << SS.getRange();
13667
13668 if (Cxx20Enumerator)
13669 return false; // OK
13670
13671 auto *RD = NamedContext
13672 ? cast<CXXRecordDecl>(Val: NamedContext->getRedeclContext())
13673 : nullptr;
13674 if (RD && !RequireCompleteDeclContext(SS&: const_cast<CXXScopeSpec &>(SS), DC: RD)) {
13675 // See if there's a helpful fixit
13676
13677 if (!R) {
13678 // We will have already diagnosed the problem on the template
13679 // definition, Maybe we should do so again?
13680 } else if (R->getAsSingle<TypeDecl>()) {
13681 if (getLangOpts().CPlusPlus11) {
13682 // Convert 'using X::Y;' to 'using Y = X::Y;'.
13683 Diag(Loc: SS.getBeginLoc(), DiagID: diag::note_using_decl_class_member_workaround)
13684 << diag::MemClassWorkaround::AliasDecl
13685 << FixItHint::CreateInsertion(InsertionLoc: SS.getBeginLoc(),
13686 Code: NameInfo.getName().getAsString() +
13687 " = ");
13688 } else {
13689 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
13690 SourceLocation InsertLoc = getLocForEndOfToken(Loc: NameInfo.getEndLoc());
13691 Diag(Loc: InsertLoc, DiagID: diag::note_using_decl_class_member_workaround)
13692 << diag::MemClassWorkaround::TypedefDecl
13693 << FixItHint::CreateReplacement(RemoveRange: UsingLoc, Code: "typedef")
13694 << FixItHint::CreateInsertion(
13695 InsertionLoc: InsertLoc, Code: " " + NameInfo.getName().getAsString());
13696 }
13697 } else if (R->getAsSingle<VarDecl>()) {
13698 // Don't provide a fixit outside C++11 mode; we don't want to suggest
13699 // repeating the type of the static data member here.
13700 FixItHint FixIt;
13701 if (getLangOpts().CPlusPlus11) {
13702 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
13703 FixIt = FixItHint::CreateReplacement(
13704 RemoveRange: UsingLoc, Code: "auto &" + NameInfo.getName().getAsString() + " = ");
13705 }
13706
13707 Diag(Loc: UsingLoc, DiagID: diag::note_using_decl_class_member_workaround)
13708 << diag::MemClassWorkaround::ReferenceDecl << FixIt;
13709 } else if (R->getAsSingle<EnumConstantDecl>()) {
13710 // Don't provide a fixit outside C++11 mode; we don't want to suggest
13711 // repeating the type of the enumeration here, and we can't do so if
13712 // the type is anonymous.
13713 FixItHint FixIt;
13714 if (getLangOpts().CPlusPlus11) {
13715 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
13716 FixIt = FixItHint::CreateReplacement(
13717 RemoveRange: UsingLoc,
13718 Code: "constexpr auto " + NameInfo.getName().getAsString() + " = ");
13719 }
13720
13721 Diag(Loc: UsingLoc, DiagID: diag::note_using_decl_class_member_workaround)
13722 << (getLangOpts().CPlusPlus11
13723 ? diag::MemClassWorkaround::ConstexprVar
13724 : diag::MemClassWorkaround::ConstVar)
13725 << FixIt;
13726 }
13727 }
13728
13729 return true; // Fail
13730 }
13731
13732 // If the named context is dependent, we can't decide much.
13733 if (!NamedContext) {
13734 // FIXME: in C++0x, we can diagnose if we can prove that the
13735 // nested-name-specifier does not refer to a base class, which is
13736 // still possible in some cases.
13737
13738 // Otherwise we have to conservatively report that things might be
13739 // okay.
13740 return false;
13741 }
13742
13743 // The current scope is a record.
13744 if (!NamedContext->isRecord()) {
13745 // Ideally this would point at the last name in the specifier,
13746 // but we don't have that level of source info.
13747 Diag(Loc: SS.getBeginLoc(),
13748 DiagID: Cxx20Enumerator
13749 ? diag::warn_cxx17_compat_using_decl_non_member_enumerator
13750 : diag::err_using_decl_nested_name_specifier_is_not_class)
13751 << SS.getScopeRep() << SS.getRange();
13752
13753 if (Cxx20Enumerator)
13754 return false; // OK
13755
13756 return true;
13757 }
13758
13759 if (!NamedContext->isDependentContext() &&
13760 RequireCompleteDeclContext(SS&: const_cast<CXXScopeSpec&>(SS), DC: NamedContext))
13761 return true;
13762
13763 // C++26 [namespace.udecl]p3:
13764 // In a using-declaration used as a member-declaration, each
13765 // using-declarator shall either name an enumerator or have a
13766 // nested-name-specifier naming a base class of the current class
13767 // ([expr.prim.this]). ...
13768 // "have a nested-name-specifier naming a base class of the current class"
13769 // was introduced by CWG400.
13770
13771 if (cast<CXXRecordDecl>(Val: CurContext)
13772 ->isProvablyNotDerivedFrom(Base: cast<CXXRecordDecl>(Val: NamedContext))) {
13773
13774 if (Cxx20Enumerator) {
13775 Diag(Loc: NameLoc, DiagID: diag::warn_cxx17_compat_using_decl_non_member_enumerator)
13776 << SS.getScopeRep() << SS.getRange();
13777 return false;
13778 }
13779
13780 if (CurContext == NamedContext) {
13781 Diag(Loc: SS.getBeginLoc(),
13782 DiagID: diag::err_using_decl_nested_name_specifier_is_current_class)
13783 << SS.getRange();
13784 return true;
13785 }
13786
13787 if (!cast<CXXRecordDecl>(Val: NamedContext)->isInvalidDecl()) {
13788 Diag(Loc: SS.getBeginLoc(),
13789 DiagID: diag::err_using_decl_nested_name_specifier_is_not_base_class)
13790 << SS.getScopeRep() << cast<CXXRecordDecl>(Val: CurContext)
13791 << SS.getRange();
13792 }
13793 return true;
13794 }
13795
13796 return false;
13797}
13798
13799Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
13800 MultiTemplateParamsArg TemplateParamLists,
13801 SourceLocation UsingLoc, UnqualifiedId &Name,
13802 const ParsedAttributesView &AttrList,
13803 TypeResult Type, Decl *DeclFromDeclSpec) {
13804
13805 if (Type.isInvalid())
13806 return nullptr;
13807
13808 bool Invalid = false;
13809 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
13810 TypeSourceInfo *TInfo = nullptr;
13811 GetTypeFromParser(Ty: Type.get(), TInfo: &TInfo);
13812
13813 if (DiagnoseClassNameShadow(DC: CurContext, Info: NameInfo))
13814 return nullptr;
13815
13816 if (DiagnoseUnexpandedParameterPack(Loc: Name.StartLocation, T: TInfo,
13817 UPPC: UPPC_DeclarationType)) {
13818 Invalid = true;
13819 TInfo = Context.getTrivialTypeSourceInfo(T: Context.IntTy,
13820 Loc: TInfo->getTypeLoc().getBeginLoc());
13821 }
13822
13823 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
13824 TemplateParamLists.size()
13825 ? forRedeclarationInCurContext()
13826 : RedeclarationKind::ForVisibleRedeclaration);
13827 LookupName(R&: Previous, S);
13828
13829 // Warn about shadowing the name of a template parameter.
13830 if (Previous.isSingleResult() &&
13831 Previous.getFoundDecl()->isTemplateParameter()) {
13832 DiagnoseTemplateParameterShadow(Loc: Name.StartLocation,PrevDecl: Previous.getFoundDecl());
13833 Previous.clear();
13834 }
13835
13836 assert(Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
13837 "name in alias declaration must be an identifier");
13838 TypeAliasDecl *NewTD = TypeAliasDecl::Create(C&: Context, DC: CurContext, StartLoc: UsingLoc,
13839 IdLoc: Name.StartLocation,
13840 Id: Name.Identifier, TInfo);
13841
13842 NewTD->setAccess(AS);
13843
13844 if (Invalid)
13845 NewTD->setInvalidDecl();
13846
13847 ProcessDeclAttributeList(S, D: NewTD, AttrList);
13848 AddPragmaAttributes(S, D: NewTD);
13849 ProcessAPINotes(D: NewTD);
13850
13851 CheckTypedefForVariablyModifiedType(S, D: NewTD);
13852 Invalid |= NewTD->isInvalidDecl();
13853
13854 // Get the innermost enclosing declaration scope.
13855 S = S->getDeclParent();
13856
13857 bool Redeclaration = false;
13858
13859 NamedDecl *NewND;
13860 if (TemplateParamLists.size()) {
13861 TypeAliasTemplateDecl *OldDecl = nullptr;
13862 TemplateParameterList *OldTemplateParams = nullptr;
13863
13864 if (TemplateParamLists.size() != 1) {
13865 Diag(Loc: UsingLoc, DiagID: diag::err_alias_template_extra_headers)
13866 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
13867 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
13868 Invalid = true;
13869 }
13870 TemplateParameterList *TemplateParams = TemplateParamLists[0];
13871
13872 // Check that we can declare a template here.
13873 if (CheckTemplateDeclScope(S, TemplateParams))
13874 return nullptr;
13875
13876 // Only consider previous declarations in the same scope.
13877 FilterLookupForScope(R&: Previous, Ctx: CurContext, S, /*ConsiderLinkage*/false,
13878 /*ExplicitInstantiationOrSpecialization*/AllowInlineNamespace: false);
13879 if (!Previous.empty()) {
13880 Redeclaration = true;
13881
13882 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
13883 if (!OldDecl && !Invalid) {
13884 Diag(Loc: UsingLoc, DiagID: diag::err_redefinition_different_kind)
13885 << Name.Identifier;
13886
13887 NamedDecl *OldD = Previous.getRepresentativeDecl();
13888 if (OldD->getLocation().isValid())
13889 Diag(Loc: OldD->getLocation(), DiagID: diag::note_previous_definition);
13890
13891 Invalid = true;
13892 }
13893
13894 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
13895 if (TemplateParameterListsAreEqual(New: TemplateParams,
13896 Old: OldDecl->getTemplateParameters(),
13897 /*Complain=*/true,
13898 Kind: TPL_TemplateMatch))
13899 OldTemplateParams =
13900 OldDecl->getMostRecentDecl()->getTemplateParameters();
13901 else
13902 Invalid = true;
13903
13904 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
13905 if (!Invalid &&
13906 !Context.hasSameType(T1: OldTD->getUnderlyingType(),
13907 T2: NewTD->getUnderlyingType())) {
13908 // FIXME: The C++0x standard does not clearly say this is ill-formed,
13909 // but we can't reasonably accept it.
13910 Diag(Loc: NewTD->getLocation(), DiagID: diag::err_redefinition_different_typedef)
13911 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
13912 if (OldTD->getLocation().isValid())
13913 Diag(Loc: OldTD->getLocation(), DiagID: diag::note_previous_definition);
13914 Invalid = true;
13915 }
13916 }
13917 }
13918
13919 // Merge any previous default template arguments into our parameters,
13920 // and check the parameter list.
13921 if (CheckTemplateParameterList(NewParams: TemplateParams, OldParams: OldTemplateParams,
13922 TPC: TPC_Other))
13923 return nullptr;
13924
13925 TypeAliasTemplateDecl *NewDecl =
13926 TypeAliasTemplateDecl::Create(C&: Context, DC: CurContext, L: UsingLoc,
13927 Name: Name.Identifier, Params: TemplateParams,
13928 Decl: NewTD);
13929 NewTD->setDescribedAliasTemplate(NewDecl);
13930
13931 NewDecl->setAccess(AS);
13932
13933 if (Invalid)
13934 NewDecl->setInvalidDecl();
13935 else if (OldDecl) {
13936 NewDecl->setPreviousDecl(OldDecl);
13937 CheckRedeclarationInModule(New: NewDecl, Old: OldDecl);
13938 }
13939
13940 NewND = NewDecl;
13941 } else {
13942 if (auto *TD = dyn_cast_or_null<TagDecl>(Val: DeclFromDeclSpec)) {
13943 setTagNameForLinkagePurposes(TagFromDeclSpec: TD, NewTD);
13944 handleTagNumbering(Tag: TD, TagScope: S);
13945 }
13946 ActOnTypedefNameDecl(S, DC: CurContext, D: NewTD, Previous, Redeclaration);
13947 NewND = NewTD;
13948 }
13949
13950 PushOnScopeChains(D: NewND, S);
13951 ActOnDocumentableDecl(D: NewND);
13952 return NewND;
13953}
13954
13955Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
13956 SourceLocation AliasLoc,
13957 IdentifierInfo *Alias, CXXScopeSpec &SS,
13958 SourceLocation IdentLoc,
13959 IdentifierInfo *Ident) {
13960
13961 // Lookup the namespace name.
13962 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
13963 LookupParsedName(R, S, SS: &SS, /*ObjectType=*/QualType());
13964
13965 if (R.isAmbiguous())
13966 return nullptr;
13967
13968 if (R.empty()) {
13969 if (!TryNamespaceTypoCorrection(S&: *this, R, Sc: S, SS, IdentLoc, Ident)) {
13970 Diag(Loc: IdentLoc, DiagID: diag::err_expected_namespace_name) << SS.getRange();
13971 return nullptr;
13972 }
13973 }
13974 assert(!R.isAmbiguous() && !R.empty());
13975 auto *ND = cast<NamespaceBaseDecl>(Val: R.getRepresentativeDecl());
13976
13977 // Check if we have a previous declaration with the same name.
13978 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
13979 RedeclarationKind::ForVisibleRedeclaration);
13980 LookupName(R&: PrevR, S);
13981
13982 // Check we're not shadowing a template parameter.
13983 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
13984 DiagnoseTemplateParameterShadow(Loc: AliasLoc, PrevDecl: PrevR.getFoundDecl());
13985 PrevR.clear();
13986 }
13987
13988 // Filter out any other lookup result from an enclosing scope.
13989 FilterLookupForScope(R&: PrevR, Ctx: CurContext, S, /*ConsiderLinkage*/false,
13990 /*AllowInlineNamespace*/false);
13991
13992 // Find the previous declaration and check that we can redeclare it.
13993 NamespaceAliasDecl *Prev = nullptr;
13994 if (PrevR.isSingleResult()) {
13995 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
13996 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(Val: PrevDecl)) {
13997 // We already have an alias with the same name that points to the same
13998 // namespace; check that it matches.
13999 if (AD->getNamespace()->Equals(DC: getNamespaceDecl(D: ND))) {
14000 Prev = AD;
14001 } else if (isVisible(D: PrevDecl)) {
14002 Diag(Loc: AliasLoc, DiagID: diag::err_redefinition_different_namespace_alias)
14003 << Alias;
14004 Diag(Loc: AD->getLocation(), DiagID: diag::note_previous_namespace_alias)
14005 << AD->getNamespace();
14006 return nullptr;
14007 }
14008 } else if (isVisible(D: PrevDecl)) {
14009 unsigned DiagID = isa<NamespaceDecl>(Val: PrevDecl->getUnderlyingDecl())
14010 ? diag::err_redefinition
14011 : diag::err_redefinition_different_kind;
14012 Diag(Loc: AliasLoc, DiagID) << Alias;
14013 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_definition);
14014 return nullptr;
14015 }
14016 }
14017
14018 // The use of a nested name specifier may trigger deprecation warnings.
14019 DiagnoseUseOfDecl(D: ND, Locs: IdentLoc);
14020
14021 NamespaceAliasDecl *AliasDecl =
14022 NamespaceAliasDecl::Create(C&: Context, DC: CurContext, NamespaceLoc, AliasLoc,
14023 Alias, QualifierLoc: SS.getWithLocInContext(Context),
14024 IdentLoc, Namespace: ND);
14025 if (Prev)
14026 AliasDecl->setPreviousDecl(Prev);
14027
14028 PushOnScopeChains(D: AliasDecl, S);
14029 return AliasDecl;
14030}
14031
14032namespace {
14033struct SpecialMemberExceptionSpecInfo
14034 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
14035 SourceLocation Loc;
14036 Sema::ImplicitExceptionSpecification ExceptSpec;
14037
14038 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
14039 CXXSpecialMemberKind CSM,
14040 Sema::InheritedConstructorInfo *ICI,
14041 SourceLocation Loc)
14042 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
14043
14044 bool visitBase(CXXBaseSpecifier *Base);
14045 bool visitField(FieldDecl *FD);
14046
14047 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
14048 unsigned Quals);
14049
14050 void visitSubobjectCall(Subobject Subobj,
14051 Sema::SpecialMemberOverloadResult SMOR);
14052};
14053}
14054
14055bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
14056 auto *BaseClass = Base->getType()->getAsCXXRecordDecl();
14057 if (!BaseClass)
14058 return false;
14059
14060 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(Class: BaseClass);
14061 if (auto *BaseCtor = SMOR.getMethod()) {
14062 visitSubobjectCall(Subobj: Base, SMOR: BaseCtor);
14063 return false;
14064 }
14065
14066 visitClassSubobject(Class: BaseClass, Subobj: Base, Quals: 0);
14067 return false;
14068}
14069
14070bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
14071 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
14072 FD->hasInClassInitializer()) {
14073 Expr *E = FD->getInClassInitializer();
14074 if (!E)
14075 // FIXME: It's a little wasteful to build and throw away a
14076 // CXXDefaultInitExpr here.
14077 // FIXME: We should have a single context note pointing at Loc, and
14078 // this location should be MD->getLocation() instead, since that's
14079 // the location where we actually use the default init expression.
14080 E = S.BuildCXXDefaultInitExpr(Loc, Field: FD).get();
14081 if (E)
14082 ExceptSpec.CalledExpr(E);
14083 } else if (auto *RD = S.Context.getBaseElementType(QT: FD->getType())
14084 ->getAsCXXRecordDecl()) {
14085 visitClassSubobject(Class: RD, Subobj: FD, Quals: FD->getType().getCVRQualifiers());
14086 }
14087 return false;
14088}
14089
14090void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
14091 Subobject Subobj,
14092 unsigned Quals) {
14093 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
14094 bool IsMutable = Field && Field->isMutable();
14095 visitSubobjectCall(Subobj, SMOR: lookupIn(Class, Quals, IsMutable));
14096}
14097
14098void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
14099 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
14100 // Note, if lookup fails, it doesn't matter what exception specification we
14101 // choose because the special member will be deleted.
14102 if (CXXMethodDecl *MD = SMOR.getMethod())
14103 ExceptSpec.CalledDecl(CallLoc: getSubobjectLoc(Subobj), Method: MD);
14104}
14105
14106bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) {
14107 llvm::APSInt Result;
14108 ExprResult Converted = CheckConvertedConstantExpression(
14109 From: ExplicitSpec.getExpr(), T: Context.BoolTy, Value&: Result, CCE: CCEKind::ExplicitBool);
14110 ExplicitSpec.setExpr(Converted.get());
14111 if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
14112 ExplicitSpec.setKind(Result.getBoolValue()
14113 ? ExplicitSpecKind::ResolvedTrue
14114 : ExplicitSpecKind::ResolvedFalse);
14115 return true;
14116 }
14117 ExplicitSpec.setKind(ExplicitSpecKind::Unresolved);
14118 return false;
14119}
14120
14121ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) {
14122 ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved);
14123 if (!ExplicitExpr->isTypeDependent())
14124 tryResolveExplicitSpecifier(ExplicitSpec&: ES);
14125 return ES;
14126}
14127
14128static Sema::ImplicitExceptionSpecification
14129ComputeDefaultedSpecialMemberExceptionSpec(
14130 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, CXXSpecialMemberKind CSM,
14131 Sema::InheritedConstructorInfo *ICI) {
14132 ComputingExceptionSpec CES(S, MD, Loc);
14133
14134 CXXRecordDecl *ClassDecl = MD->getParent();
14135
14136 // C++ [except.spec]p14:
14137 // An implicitly declared special member function (Clause 12) shall have an
14138 // exception-specification. [...]
14139 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
14140 if (ClassDecl->isInvalidDecl())
14141 return Info.ExceptSpec;
14142
14143 // FIXME: If this diagnostic fires, we're probably missing a check for
14144 // attempting to resolve an exception specification before it's known
14145 // at a higher level.
14146 if (S.RequireCompleteType(Loc: MD->getLocation(),
14147 T: S.Context.getCanonicalTagType(TD: ClassDecl),
14148 DiagID: diag::err_exception_spec_incomplete_type))
14149 return Info.ExceptSpec;
14150
14151 // C++1z [except.spec]p7:
14152 // [Look for exceptions thrown by] a constructor selected [...] to
14153 // initialize a potentially constructed subobject,
14154 // C++1z [except.spec]p8:
14155 // The exception specification for an implicitly-declared destructor, or a
14156 // destructor without a noexcept-specifier, is potentially-throwing if and
14157 // only if any of the destructors for any of its potentially constructed
14158 // subojects is potentially throwing.
14159 // FIXME: We respect the first rule but ignore the "potentially constructed"
14160 // in the second rule to resolve a core issue (no number yet) that would have
14161 // us reject:
14162 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
14163 // struct B : A {};
14164 // struct C : B { void f(); };
14165 // ... due to giving B::~B() a non-throwing exception specification.
14166 Info.visit(Bases: Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
14167 : Info.VisitAllBases);
14168
14169 return Info.ExceptSpec;
14170}
14171
14172namespace {
14173/// RAII object to register a special member as being currently declared.
14174struct DeclaringSpecialMember {
14175 Sema &S;
14176 Sema::SpecialMemberDecl D;
14177 Sema::ContextRAII SavedContext;
14178 bool WasAlreadyBeingDeclared;
14179
14180 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, CXXSpecialMemberKind CSM)
14181 : S(S), D(RD, CSM), SavedContext(S, RD) {
14182 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(Ptr: D).second;
14183 if (WasAlreadyBeingDeclared)
14184 // This almost never happens, but if it does, ensure that our cache
14185 // doesn't contain a stale result.
14186 S.SpecialMemberCache.clear();
14187 else {
14188 // Register a note to be produced if we encounter an error while
14189 // declaring the special member.
14190 Sema::CodeSynthesisContext Ctx;
14191 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
14192 // FIXME: We don't have a location to use here. Using the class's
14193 // location maintains the fiction that we declare all special members
14194 // with the class, but (1) it's not clear that lying about that helps our
14195 // users understand what's going on, and (2) there may be outer contexts
14196 // on the stack (some of which are relevant) and printing them exposes
14197 // our lies.
14198 Ctx.PointOfInstantiation = RD->getLocation();
14199 Ctx.Entity = RD;
14200 Ctx.SpecialMember = CSM;
14201 S.pushCodeSynthesisContext(Ctx);
14202 }
14203 }
14204 ~DeclaringSpecialMember() {
14205 if (!WasAlreadyBeingDeclared) {
14206 S.SpecialMembersBeingDeclared.erase(Ptr: D);
14207 S.popCodeSynthesisContext();
14208 }
14209 }
14210
14211 /// Are we already trying to declare this special member?
14212 bool isAlreadyBeingDeclared() const {
14213 return WasAlreadyBeingDeclared;
14214 }
14215};
14216}
14217
14218void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
14219 // Look up any existing declarations, but don't trigger declaration of all
14220 // implicit special members with this name.
14221 DeclarationName Name = FD->getDeclName();
14222 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
14223 RedeclarationKind::ForExternalRedeclaration);
14224 for (auto *D : FD->getParent()->lookup(Name))
14225 if (auto *Acceptable = R.getAcceptableDecl(D))
14226 R.addDecl(D: Acceptable);
14227 R.resolveKind();
14228 R.suppressDiagnostics();
14229
14230 CheckFunctionDeclaration(S, NewFD: FD, Previous&: R, /*IsMemberSpecialization*/ false,
14231 DeclIsDefn: FD->isThisDeclarationADefinition());
14232}
14233
14234void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
14235 QualType ResultTy,
14236 ArrayRef<QualType> Args) {
14237 // Build an exception specification pointing back at this constructor.
14238 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(S&: *this, MD: SpecialMem);
14239
14240 LangAS AS = getDefaultCXXMethodAddrSpace();
14241 if (AS != LangAS::Default) {
14242 EPI.TypeQuals.addAddressSpace(space: AS);
14243 }
14244
14245 auto QT = Context.getFunctionType(ResultTy, Args, EPI);
14246 SpecialMem->setType(QT);
14247
14248 // During template instantiation of implicit special member functions we need
14249 // a reliable TypeSourceInfo for the function prototype in order to allow
14250 // functions to be substituted.
14251 if (inTemplateInstantiation() && isLambdaMethod(DC: SpecialMem)) {
14252 TypeSourceInfo *TSI =
14253 Context.getTrivialTypeSourceInfo(T: SpecialMem->getType());
14254 SpecialMem->setTypeSourceInfo(TSI);
14255 }
14256}
14257
14258CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
14259 CXXRecordDecl *ClassDecl) {
14260 // C++ [class.ctor]p5:
14261 // A default constructor for a class X is a constructor of class X
14262 // that can be called without an argument. If there is no
14263 // user-declared constructor for class X, a default constructor is
14264 // implicitly declared. An implicitly-declared default constructor
14265 // is an inline public member of its class.
14266 assert(ClassDecl->needsImplicitDefaultConstructor() &&
14267 "Should not build implicit default constructor!");
14268
14269 DeclaringSpecialMember DSM(*this, ClassDecl,
14270 CXXSpecialMemberKind::DefaultConstructor);
14271 if (DSM.isAlreadyBeingDeclared())
14272 return nullptr;
14273
14274 bool Constexpr = defaultedSpecialMemberIsConstexpr(
14275 S&: *this, ClassDecl, CSM: CXXSpecialMemberKind::DefaultConstructor, ConstArg: false);
14276
14277 // Create the actual constructor declaration.
14278 CanQualType ClassType = Context.getCanonicalTagType(TD: ClassDecl);
14279 SourceLocation ClassLoc = ClassDecl->getLocation();
14280 DeclarationName Name
14281 = Context.DeclarationNames.getCXXConstructorName(Ty: ClassType);
14282 DeclarationNameInfo NameInfo(Name, ClassLoc);
14283 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
14284 C&: Context, RD: ClassDecl, StartLoc: ClassLoc, NameInfo, /*Type*/ T: QualType(),
14285 /*TInfo=*/nullptr, ES: ExplicitSpecifier(),
14286 UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
14287 /*isInline=*/true, /*isImplicitlyDeclared=*/true,
14288 ConstexprKind: Constexpr ? ConstexprSpecKind::Constexpr
14289 : ConstexprSpecKind::Unspecified);
14290 DefaultCon->setAccess(AS_public);
14291 DefaultCon->setDefaulted();
14292
14293 setupImplicitSpecialMemberType(SpecialMem: DefaultCon, ResultTy: Context.VoidTy, Args: {});
14294
14295 if (getLangOpts().CUDA)
14296 CUDA().inferTargetForImplicitSpecialMember(
14297 ClassDecl, CSM: CXXSpecialMemberKind::DefaultConstructor, MemberDecl: DefaultCon,
14298 /* ConstRHS */ false,
14299 /* Diagnose */ false);
14300
14301 // We don't need to use SpecialMemberIsTrivial here; triviality for default
14302 // constructors is easy to compute.
14303 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
14304
14305 // Note that we have declared this constructor.
14306 ++getASTContext().NumImplicitDefaultConstructorsDeclared;
14307
14308 Scope *S = getScopeForContext(Ctx: ClassDecl);
14309 CheckImplicitSpecialMemberDeclaration(S, FD: DefaultCon);
14310
14311 if (ShouldDeleteSpecialMember(MD: DefaultCon,
14312 CSM: CXXSpecialMemberKind::DefaultConstructor))
14313 SetDeclDeleted(dcl: DefaultCon, DelLoc: ClassLoc);
14314
14315 if (S)
14316 PushOnScopeChains(D: DefaultCon, S, AddToContext: false);
14317 ClassDecl->addDecl(D: DefaultCon);
14318
14319 return DefaultCon;
14320}
14321
14322void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
14323 CXXConstructorDecl *Constructor) {
14324 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
14325 !Constructor->doesThisDeclarationHaveABody() &&
14326 !Constructor->isDeleted()) &&
14327 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
14328 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
14329 return;
14330
14331 CXXRecordDecl *ClassDecl = Constructor->getParent();
14332 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
14333 if (ClassDecl->isInvalidDecl()) {
14334 return;
14335 }
14336
14337 SynthesizedFunctionScope Scope(*this, Constructor);
14338
14339 // The exception specification is needed because we are defining the
14340 // function.
14341 ResolveExceptionSpec(Loc: CurrentLocation,
14342 FPT: Constructor->getType()->castAs<FunctionProtoType>());
14343 MarkVTableUsed(Loc: CurrentLocation, Class: ClassDecl);
14344
14345 // Add a context note for diagnostics produced after this point.
14346 Scope.addContextNote(UseLoc: CurrentLocation);
14347
14348 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
14349 Constructor->setInvalidDecl();
14350 return;
14351 }
14352
14353 SourceLocation Loc = Constructor->getEndLoc().isValid()
14354 ? Constructor->getEndLoc()
14355 : Constructor->getLocation();
14356 Constructor->setBody(new (Context) CompoundStmt(Loc));
14357 Constructor->markUsed(C&: Context);
14358
14359 if (ASTMutationListener *L = getASTMutationListener()) {
14360 L->CompletedImplicitDefinition(D: Constructor);
14361 }
14362
14363 DiagnoseUninitializedFields(SemaRef&: *this, Constructor);
14364}
14365
14366void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
14367 // Perform any delayed checks on exception specifications.
14368 CheckDelayedMemberExceptionSpecs();
14369}
14370
14371/// Find or create the fake constructor we synthesize to model constructing an
14372/// object of a derived class via a constructor of a base class.
14373CXXConstructorDecl *
14374Sema::findInheritingConstructor(SourceLocation Loc,
14375 CXXConstructorDecl *BaseCtor,
14376 ConstructorUsingShadowDecl *Shadow) {
14377 CXXRecordDecl *Derived = Shadow->getParent();
14378 SourceLocation UsingLoc = Shadow->getLocation();
14379
14380 // FIXME: Add a new kind of DeclarationName for an inherited constructor.
14381 // For now we use the name of the base class constructor as a member of the
14382 // derived class to indicate a (fake) inherited constructor name.
14383 DeclarationName Name = BaseCtor->getDeclName();
14384
14385 // Check to see if we already have a fake constructor for this inherited
14386 // constructor call.
14387 for (NamedDecl *Ctor : Derived->lookup(Name))
14388 if (declaresSameEntity(D1: cast<CXXConstructorDecl>(Val: Ctor)
14389 ->getInheritedConstructor()
14390 .getConstructor(),
14391 D2: BaseCtor))
14392 return cast<CXXConstructorDecl>(Val: Ctor);
14393
14394 DeclarationNameInfo NameInfo(Name, UsingLoc);
14395 TypeSourceInfo *TInfo =
14396 Context.getTrivialTypeSourceInfo(T: BaseCtor->getType(), Loc: UsingLoc);
14397 FunctionProtoTypeLoc ProtoLoc =
14398 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
14399
14400 // Check the inherited constructor is valid and find the list of base classes
14401 // from which it was inherited.
14402 InheritedConstructorInfo ICI(*this, Loc, Shadow);
14403
14404 bool Constexpr = BaseCtor->isConstexpr() &&
14405 defaultedSpecialMemberIsConstexpr(
14406 S&: *this, ClassDecl: Derived, CSM: CXXSpecialMemberKind::DefaultConstructor,
14407 ConstArg: false, InheritedCtor: BaseCtor, Inherited: &ICI);
14408
14409 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
14410 C&: Context, RD: Derived, StartLoc: UsingLoc, NameInfo, T: TInfo->getType(), TInfo,
14411 ES: BaseCtor->getExplicitSpecifier(), UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
14412 /*isInline=*/true,
14413 /*isImplicitlyDeclared=*/true,
14414 ConstexprKind: Constexpr ? BaseCtor->getConstexprKind() : ConstexprSpecKind::Unspecified,
14415 Inherited: InheritedConstructor(Shadow, BaseCtor),
14416 TrailingRequiresClause: BaseCtor->getTrailingRequiresClause());
14417 if (Shadow->isInvalidDecl())
14418 DerivedCtor->setInvalidDecl();
14419
14420 // Build an unevaluated exception specification for this fake constructor.
14421 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
14422 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
14423 EPI.ExceptionSpec.Type = EST_Unevaluated;
14424 EPI.ExceptionSpec.SourceDecl = DerivedCtor;
14425 DerivedCtor->setType(Context.getFunctionType(ResultTy: FPT->getReturnType(),
14426 Args: FPT->getParamTypes(), EPI));
14427
14428 // Build the parameter declarations.
14429 SmallVector<ParmVarDecl *, 16> ParamDecls;
14430 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
14431 TypeSourceInfo *TInfo =
14432 Context.getTrivialTypeSourceInfo(T: FPT->getParamType(i: I), Loc: UsingLoc);
14433 ParmVarDecl *PD = ParmVarDecl::Create(
14434 C&: Context, DC: DerivedCtor, StartLoc: UsingLoc, IdLoc: UsingLoc, /*IdentifierInfo=*/Id: nullptr,
14435 T: FPT->getParamType(i: I), TInfo, S: SC_None, /*DefArg=*/nullptr);
14436 PD->setScopeInfo(scopeDepth: 0, parameterIndex: I);
14437 PD->setImplicit();
14438 // Ensure attributes are propagated onto parameters (this matters for
14439 // format, pass_object_size, ...).
14440 mergeDeclAttributes(New: PD, Old: BaseCtor->getParamDecl(i: I));
14441 ParamDecls.push_back(Elt: PD);
14442 ProtoLoc.setParam(i: I, VD: PD);
14443 }
14444
14445 // Set up the new constructor.
14446 assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
14447 DerivedCtor->setAccess(BaseCtor->getAccess());
14448 DerivedCtor->setParams(ParamDecls);
14449 Derived->addDecl(D: DerivedCtor);
14450
14451 if (ShouldDeleteSpecialMember(MD: DerivedCtor,
14452 CSM: CXXSpecialMemberKind::DefaultConstructor, ICI: &ICI))
14453 SetDeclDeleted(dcl: DerivedCtor, DelLoc: UsingLoc);
14454
14455 return DerivedCtor;
14456}
14457
14458void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
14459 InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
14460 Ctor->getInheritedConstructor().getShadowDecl());
14461 ShouldDeleteSpecialMember(MD: Ctor, CSM: CXXSpecialMemberKind::DefaultConstructor,
14462 ICI: &ICI,
14463 /*Diagnose*/ true);
14464}
14465
14466void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
14467 CXXConstructorDecl *Constructor) {
14468 CXXRecordDecl *ClassDecl = Constructor->getParent();
14469 assert(Constructor->getInheritedConstructor() &&
14470 !Constructor->doesThisDeclarationHaveABody() &&
14471 !Constructor->isDeleted());
14472 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
14473 return;
14474
14475 // Initializations are performed "as if by a defaulted default constructor",
14476 // so enter the appropriate scope.
14477 SynthesizedFunctionScope Scope(*this, Constructor);
14478
14479 // The exception specification is needed because we are defining the
14480 // function.
14481 ResolveExceptionSpec(Loc: CurrentLocation,
14482 FPT: Constructor->getType()->castAs<FunctionProtoType>());
14483 MarkVTableUsed(Loc: CurrentLocation, Class: ClassDecl);
14484
14485 // Add a context note for diagnostics produced after this point.
14486 Scope.addContextNote(UseLoc: CurrentLocation);
14487
14488 ConstructorUsingShadowDecl *Shadow =
14489 Constructor->getInheritedConstructor().getShadowDecl();
14490 CXXConstructorDecl *InheritedCtor =
14491 Constructor->getInheritedConstructor().getConstructor();
14492
14493 // [class.inhctor.init]p1:
14494 // initialization proceeds as if a defaulted default constructor is used to
14495 // initialize the D object and each base class subobject from which the
14496 // constructor was inherited
14497
14498 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
14499 CXXRecordDecl *RD = Shadow->getParent();
14500 SourceLocation InitLoc = Shadow->getLocation();
14501
14502 // Build explicit initializers for all base classes from which the
14503 // constructor was inherited.
14504 SmallVector<CXXCtorInitializer*, 8> Inits;
14505 for (bool VBase : {false, true}) {
14506 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
14507 if (B.isVirtual() != VBase)
14508 continue;
14509
14510 auto *BaseRD = B.getType()->getAsCXXRecordDecl();
14511 if (!BaseRD)
14512 continue;
14513
14514 auto BaseCtor = ICI.findConstructorForBase(Base: BaseRD, Ctor: InheritedCtor);
14515 if (!BaseCtor.first)
14516 continue;
14517
14518 MarkFunctionReferenced(Loc: CurrentLocation, Func: BaseCtor.first);
14519 ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
14520 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
14521
14522 auto *TInfo = Context.getTrivialTypeSourceInfo(T: B.getType(), Loc: InitLoc);
14523 Inits.push_back(Elt: new (Context) CXXCtorInitializer(
14524 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
14525 SourceLocation()));
14526 }
14527 }
14528
14529 // We now proceed as if for a defaulted default constructor, with the relevant
14530 // initializers replaced.
14531
14532 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Initializers: Inits)) {
14533 Constructor->setInvalidDecl();
14534 return;
14535 }
14536
14537 Constructor->setBody(new (Context) CompoundStmt(InitLoc));
14538 Constructor->markUsed(C&: Context);
14539
14540 if (ASTMutationListener *L = getASTMutationListener()) {
14541 L->CompletedImplicitDefinition(D: Constructor);
14542 }
14543
14544 DiagnoseUninitializedFields(SemaRef&: *this, Constructor);
14545}
14546
14547CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
14548 // C++ [class.dtor]p2:
14549 // If a class has no user-declared destructor, a destructor is
14550 // declared implicitly. An implicitly-declared destructor is an
14551 // inline public member of its class.
14552 assert(ClassDecl->needsImplicitDestructor());
14553
14554 DeclaringSpecialMember DSM(*this, ClassDecl,
14555 CXXSpecialMemberKind::Destructor);
14556 if (DSM.isAlreadyBeingDeclared())
14557 return nullptr;
14558
14559 bool Constexpr = defaultedSpecialMemberIsConstexpr(
14560 S&: *this, ClassDecl, CSM: CXXSpecialMemberKind::Destructor, ConstArg: false);
14561
14562 // Create the actual destructor declaration.
14563 CanQualType ClassType = Context.getCanonicalTagType(TD: ClassDecl);
14564 SourceLocation ClassLoc = ClassDecl->getLocation();
14565 DeclarationName Name
14566 = Context.DeclarationNames.getCXXDestructorName(Ty: ClassType);
14567 DeclarationNameInfo NameInfo(Name, ClassLoc);
14568 CXXDestructorDecl *Destructor = CXXDestructorDecl::Create(
14569 C&: Context, RD: ClassDecl, StartLoc: ClassLoc, NameInfo, T: QualType(), TInfo: nullptr,
14570 UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
14571 /*isInline=*/true,
14572 /*isImplicitlyDeclared=*/true,
14573 ConstexprKind: Constexpr ? ConstexprSpecKind::Constexpr
14574 : ConstexprSpecKind::Unspecified);
14575 Destructor->setAccess(AS_public);
14576 Destructor->setDefaulted();
14577
14578 setupImplicitSpecialMemberType(SpecialMem: Destructor, ResultTy: Context.VoidTy, Args: {});
14579
14580 if (getLangOpts().CUDA)
14581 CUDA().inferTargetForImplicitSpecialMember(
14582 ClassDecl, CSM: CXXSpecialMemberKind::Destructor, MemberDecl: Destructor,
14583 /* ConstRHS */ false,
14584 /* Diagnose */ false);
14585
14586 // We don't need to use SpecialMemberIsTrivial here; triviality for
14587 // destructors is easy to compute.
14588 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
14589 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
14590 ClassDecl->hasTrivialDestructorForCall());
14591
14592 // Note that we have declared this destructor.
14593 ++getASTContext().NumImplicitDestructorsDeclared;
14594
14595 Scope *S = getScopeForContext(Ctx: ClassDecl);
14596 CheckImplicitSpecialMemberDeclaration(S, FD: Destructor);
14597
14598 // We can't check whether an implicit destructor is deleted before we complete
14599 // the definition of the class, because its validity depends on the alignment
14600 // of the class. We'll check this from ActOnFields once the class is complete.
14601 if (ClassDecl->isCompleteDefinition() &&
14602 ShouldDeleteSpecialMember(MD: Destructor, CSM: CXXSpecialMemberKind::Destructor))
14603 SetDeclDeleted(dcl: Destructor, DelLoc: ClassLoc);
14604
14605 // Introduce this destructor into its scope.
14606 if (S)
14607 PushOnScopeChains(D: Destructor, S, AddToContext: false);
14608 ClassDecl->addDecl(D: Destructor);
14609
14610 return Destructor;
14611}
14612
14613void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
14614 CXXDestructorDecl *Destructor) {
14615 assert((Destructor->isDefaulted() &&
14616 !Destructor->doesThisDeclarationHaveABody() &&
14617 !Destructor->isDeleted()) &&
14618 "DefineImplicitDestructor - call it for implicit default dtor");
14619 if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
14620 return;
14621
14622 CXXRecordDecl *ClassDecl = Destructor->getParent();
14623 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
14624
14625 SynthesizedFunctionScope Scope(*this, Destructor);
14626
14627 // The exception specification is needed because we are defining the
14628 // function.
14629 ResolveExceptionSpec(Loc: CurrentLocation,
14630 FPT: Destructor->getType()->castAs<FunctionProtoType>());
14631 MarkVTableUsed(Loc: CurrentLocation, Class: ClassDecl);
14632
14633 // Add a context note for diagnostics produced after this point.
14634 Scope.addContextNote(UseLoc: CurrentLocation);
14635
14636 MarkBaseAndMemberDestructorsReferenced(Location: Destructor->getLocation(),
14637 ClassDecl: Destructor->getParent());
14638
14639 if (CheckDestructor(Destructor)) {
14640 Destructor->setInvalidDecl();
14641 return;
14642 }
14643
14644 SourceLocation Loc = Destructor->getEndLoc().isValid()
14645 ? Destructor->getEndLoc()
14646 : Destructor->getLocation();
14647 Destructor->setBody(new (Context) CompoundStmt(Loc));
14648 Destructor->markUsed(C&: Context);
14649
14650 if (ASTMutationListener *L = getASTMutationListener()) {
14651 L->CompletedImplicitDefinition(D: Destructor);
14652 }
14653}
14654
14655void Sema::CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
14656 CXXDestructorDecl *Destructor) {
14657 if (Destructor->isInvalidDecl())
14658 return;
14659
14660 CXXRecordDecl *ClassDecl = Destructor->getParent();
14661 assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&
14662 "implicit complete dtors unneeded outside MS ABI");
14663 assert(ClassDecl->getNumVBases() > 0 &&
14664 "complete dtor only exists for classes with vbases");
14665
14666 SynthesizedFunctionScope Scope(*this, Destructor);
14667
14668 // Add a context note for diagnostics produced after this point.
14669 Scope.addContextNote(UseLoc: CurrentLocation);
14670
14671 MarkVirtualBaseDestructorsReferenced(Location: Destructor->getLocation(), ClassDecl);
14672}
14673
14674void Sema::ActOnFinishCXXMemberDecls() {
14675 // If the context is an invalid C++ class, just suppress these checks.
14676 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: CurContext)) {
14677 if (Record->isInvalidDecl()) {
14678 DelayedOverridingExceptionSpecChecks.clear();
14679 DelayedEquivalentExceptionSpecChecks.clear();
14680 return;
14681 }
14682 checkForMultipleExportedDefaultConstructors(S&: *this, Class: Record);
14683 }
14684}
14685
14686void Sema::ActOnFinishCXXNonNestedClass() {
14687 referenceDLLExportedClassMethods();
14688
14689 if (!DelayedDllExportMemberFunctions.empty()) {
14690 SmallVector<CXXMethodDecl*, 4> WorkList;
14691 std::swap(LHS&: DelayedDllExportMemberFunctions, RHS&: WorkList);
14692 for (CXXMethodDecl *M : WorkList) {
14693 DefineDefaultedFunction(S&: *this, FD: M, DefaultLoc: M->getLocation());
14694
14695 // Pass the method to the consumer to get emitted. This is not necessary
14696 // for explicit instantiation definitions, as they will get emitted
14697 // anyway.
14698 if (M->getParent()->getTemplateSpecializationKind() !=
14699 TSK_ExplicitInstantiationDefinition)
14700 ActOnFinishInlineFunctionDef(D: M);
14701 }
14702 }
14703}
14704
14705void Sema::referenceDLLExportedClassMethods() {
14706 if (!DelayedDllExportClasses.empty()) {
14707 // Calling ReferenceDllExportedMembers might cause the current function to
14708 // be called again, so use a local copy of DelayedDllExportClasses.
14709 SmallVector<CXXRecordDecl *, 4> WorkList;
14710 std::swap(LHS&: DelayedDllExportClasses, RHS&: WorkList);
14711 for (CXXRecordDecl *Class : WorkList)
14712 ReferenceDllExportedMembers(S&: *this, Class);
14713 }
14714}
14715
14716void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
14717 assert(getLangOpts().CPlusPlus11 &&
14718 "adjusting dtor exception specs was introduced in c++11");
14719
14720 if (Destructor->isDependentContext())
14721 return;
14722
14723 // C++11 [class.dtor]p3:
14724 // A declaration of a destructor that does not have an exception-
14725 // specification is implicitly considered to have the same exception-
14726 // specification as an implicit declaration.
14727 const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>();
14728 if (DtorType->hasExceptionSpec())
14729 return;
14730
14731 // Replace the destructor's type, building off the existing one. Fortunately,
14732 // the only thing of interest in the destructor type is its extended info.
14733 // The return and arguments are fixed.
14734 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
14735 EPI.ExceptionSpec.Type = EST_Unevaluated;
14736 EPI.ExceptionSpec.SourceDecl = Destructor;
14737 Destructor->setType(Context.getFunctionType(ResultTy: Context.VoidTy, Args: {}, EPI));
14738
14739 // FIXME: If the destructor has a body that could throw, and the newly created
14740 // spec doesn't allow exceptions, we should emit a warning, because this
14741 // change in behavior can break conforming C++03 programs at runtime.
14742 // However, we don't have a body or an exception specification yet, so it
14743 // needs to be done somewhere else.
14744}
14745
14746namespace {
14747/// An abstract base class for all helper classes used in building the
14748// copy/move operators. These classes serve as factory functions and help us
14749// avoid using the same Expr* in the AST twice.
14750class ExprBuilder {
14751 ExprBuilder(const ExprBuilder&) = delete;
14752 ExprBuilder &operator=(const ExprBuilder&) = delete;
14753
14754protected:
14755 static Expr *assertNotNull(Expr *E) {
14756 assert(E && "Expression construction must not fail.");
14757 return E;
14758 }
14759
14760public:
14761 ExprBuilder() {}
14762 virtual ~ExprBuilder() {}
14763
14764 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
14765};
14766
14767class RefBuilder: public ExprBuilder {
14768 VarDecl *Var;
14769 QualType VarType;
14770
14771public:
14772 Expr *build(Sema &S, SourceLocation Loc) const override {
14773 return assertNotNull(E: S.BuildDeclRefExpr(D: Var, Ty: VarType, VK: VK_LValue, Loc));
14774 }
14775
14776 RefBuilder(VarDecl *Var, QualType VarType)
14777 : Var(Var), VarType(VarType) {}
14778};
14779
14780class ThisBuilder: public ExprBuilder {
14781public:
14782 Expr *build(Sema &S, SourceLocation Loc) const override {
14783 return assertNotNull(E: S.ActOnCXXThis(Loc).getAs<Expr>());
14784 }
14785};
14786
14787class CastBuilder: public ExprBuilder {
14788 const ExprBuilder &Builder;
14789 QualType Type;
14790 ExprValueKind Kind;
14791 const CXXCastPath &Path;
14792
14793public:
14794 Expr *build(Sema &S, SourceLocation Loc) const override {
14795 return assertNotNull(E: S.ImpCastExprToType(E: Builder.build(S, Loc), Type,
14796 CK: CK_UncheckedDerivedToBase, VK: Kind,
14797 BasePath: &Path).get());
14798 }
14799
14800 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
14801 const CXXCastPath &Path)
14802 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
14803};
14804
14805class DerefBuilder: public ExprBuilder {
14806 const ExprBuilder &Builder;
14807
14808public:
14809 Expr *build(Sema &S, SourceLocation Loc) const override {
14810 return assertNotNull(
14811 E: S.CreateBuiltinUnaryOp(OpLoc: Loc, Opc: UO_Deref, InputExpr: Builder.build(S, Loc)).get());
14812 }
14813
14814 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14815};
14816
14817class MemberBuilder: public ExprBuilder {
14818 const ExprBuilder &Builder;
14819 QualType Type;
14820 CXXScopeSpec SS;
14821 bool IsArrow;
14822 LookupResult &MemberLookup;
14823
14824public:
14825 Expr *build(Sema &S, SourceLocation Loc) const override {
14826 return assertNotNull(E: S.BuildMemberReferenceExpr(
14827 Base: Builder.build(S, Loc), BaseType: Type, OpLoc: Loc, IsArrow, SS, TemplateKWLoc: SourceLocation(),
14828 FirstQualifierInScope: nullptr, R&: MemberLookup, TemplateArgs: nullptr, S: nullptr).get());
14829 }
14830
14831 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
14832 LookupResult &MemberLookup)
14833 : Builder(Builder), Type(Type), IsArrow(IsArrow),
14834 MemberLookup(MemberLookup) {}
14835};
14836
14837class MoveCastBuilder: public ExprBuilder {
14838 const ExprBuilder &Builder;
14839
14840public:
14841 Expr *build(Sema &S, SourceLocation Loc) const override {
14842 return assertNotNull(E: CastForMoving(SemaRef&: S, E: Builder.build(S, Loc)));
14843 }
14844
14845 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14846};
14847
14848class LvalueConvBuilder: public ExprBuilder {
14849 const ExprBuilder &Builder;
14850
14851public:
14852 Expr *build(Sema &S, SourceLocation Loc) const override {
14853 return assertNotNull(
14854 E: S.DefaultLvalueConversion(E: Builder.build(S, Loc)).get());
14855 }
14856
14857 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14858};
14859
14860class SubscriptBuilder: public ExprBuilder {
14861 const ExprBuilder &Base;
14862 const ExprBuilder &Index;
14863
14864public:
14865 Expr *build(Sema &S, SourceLocation Loc) const override {
14866 return assertNotNull(E: S.CreateBuiltinArraySubscriptExpr(
14867 Base: Base.build(S, Loc), LLoc: Loc, Idx: Index.build(S, Loc), RLoc: Loc).get());
14868 }
14869
14870 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
14871 : Base(Base), Index(Index) {}
14872};
14873
14874} // end anonymous namespace
14875
14876/// When generating a defaulted copy or move assignment operator, if a field
14877/// should be copied with __builtin_memcpy rather than via explicit assignments,
14878/// do so. This optimization only applies for arrays of scalars, and for arrays
14879/// of class type where the selected copy/move-assignment operator is trivial.
14880static StmtResult
14881buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
14882 const ExprBuilder &ToB, const ExprBuilder &FromB) {
14883 // Compute the size of the memory buffer to be copied.
14884 QualType SizeType = S.Context.getSizeType();
14885 llvm::APInt Size(S.Context.getTypeSize(T: SizeType),
14886 S.Context.getTypeSizeInChars(T).getQuantity());
14887
14888 // Take the address of the field references for "from" and "to". We
14889 // directly construct UnaryOperators here because semantic analysis
14890 // does not permit us to take the address of an xvalue.
14891 Expr *From = FromB.build(S, Loc);
14892 From = UnaryOperator::Create(
14893 C: S.Context, input: From, opc: UO_AddrOf, type: S.Context.getPointerType(T: From->getType()),
14894 VK: VK_PRValue, OK: OK_Ordinary, l: Loc, CanOverflow: false, FPFeatures: S.CurFPFeatureOverrides());
14895 Expr *To = ToB.build(S, Loc);
14896 To = UnaryOperator::Create(
14897 C: S.Context, input: To, opc: UO_AddrOf, type: S.Context.getPointerType(T: To->getType()),
14898 VK: VK_PRValue, OK: OK_Ordinary, l: Loc, CanOverflow: false, FPFeatures: S.CurFPFeatureOverrides());
14899
14900 bool NeedsCollectableMemCpy = false;
14901 if (auto *RD = T->getBaseElementTypeUnsafe()->getAsRecordDecl())
14902 NeedsCollectableMemCpy = RD->hasObjectMember();
14903
14904 // Create a reference to the __builtin_objc_memmove_collectable function
14905 StringRef MemCpyName = NeedsCollectableMemCpy ?
14906 "__builtin_objc_memmove_collectable" :
14907 "__builtin_memcpy";
14908 LookupResult R(S, &S.Context.Idents.get(Name: MemCpyName), Loc,
14909 Sema::LookupOrdinaryName);
14910 S.LookupName(R, S: S.TUScope, AllowBuiltinCreation: true);
14911
14912 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
14913 if (!MemCpy)
14914 // Something went horribly wrong earlier, and we will have complained
14915 // about it.
14916 return StmtError();
14917
14918 ExprResult MemCpyRef = S.BuildDeclRefExpr(D: MemCpy, Ty: S.Context.BuiltinFnTy,
14919 VK: VK_PRValue, Loc, SS: nullptr);
14920 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
14921
14922 Expr *CallArgs[] = {
14923 To, From, IntegerLiteral::Create(C: S.Context, V: Size, type: SizeType, l: Loc)
14924 };
14925 ExprResult Call = S.BuildCallExpr(/*Scope=*/S: nullptr, Fn: MemCpyRef.get(),
14926 LParenLoc: Loc, ArgExprs: CallArgs, RParenLoc: Loc);
14927
14928 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
14929 return Call.getAs<Stmt>();
14930}
14931
14932/// Builds a statement that copies/moves the given entity from \p From to
14933/// \c To.
14934///
14935/// This routine is used to copy/move the members of a class with an
14936/// implicitly-declared copy/move assignment operator. When the entities being
14937/// copied are arrays, this routine builds for loops to copy them.
14938///
14939/// \param S The Sema object used for type-checking.
14940///
14941/// \param Loc The location where the implicit copy/move is being generated.
14942///
14943/// \param T The type of the expressions being copied/moved. Both expressions
14944/// must have this type.
14945///
14946/// \param To The expression we are copying/moving to.
14947///
14948/// \param From The expression we are copying/moving from.
14949///
14950/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
14951/// Otherwise, it's a non-static member subobject.
14952///
14953/// \param Copying Whether we're copying or moving.
14954///
14955/// \param Depth Internal parameter recording the depth of the recursion.
14956///
14957/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
14958/// if a memcpy should be used instead.
14959static StmtResult
14960buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
14961 const ExprBuilder &To, const ExprBuilder &From,
14962 bool CopyingBaseSubobject, bool Copying,
14963 unsigned Depth = 0) {
14964 // C++11 [class.copy]p28:
14965 // Each subobject is assigned in the manner appropriate to its type:
14966 //
14967 // - if the subobject is of class type, as if by a call to operator= with
14968 // the subobject as the object expression and the corresponding
14969 // subobject of x as a single function argument (as if by explicit
14970 // qualification; that is, ignoring any possible virtual overriding
14971 // functions in more derived classes);
14972 //
14973 // C++03 [class.copy]p13:
14974 // - if the subobject is of class type, the copy assignment operator for
14975 // the class is used (as if by explicit qualification; that is,
14976 // ignoring any possible virtual overriding functions in more derived
14977 // classes);
14978 if (auto *ClassDecl = T->getAsCXXRecordDecl()) {
14979 // Look for operator=.
14980 DeclarationName Name
14981 = S.Context.DeclarationNames.getCXXOperatorName(Op: OO_Equal);
14982 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
14983 S.LookupQualifiedName(R&: OpLookup, LookupCtx: ClassDecl, InUnqualifiedLookup: false);
14984
14985 // Prior to C++11, filter out any result that isn't a copy/move-assignment
14986 // operator.
14987 if (!S.getLangOpts().CPlusPlus11) {
14988 LookupResult::Filter F = OpLookup.makeFilter();
14989 while (F.hasNext()) {
14990 NamedDecl *D = F.next();
14991 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: D))
14992 if (Method->isCopyAssignmentOperator() ||
14993 (!Copying && Method->isMoveAssignmentOperator()))
14994 continue;
14995
14996 F.erase();
14997 }
14998 F.done();
14999 }
15000
15001 // Suppress the protected check (C++ [class.protected]) for each of the
15002 // assignment operators we found. This strange dance is required when
15003 // we're assigning via a base classes's copy-assignment operator. To
15004 // ensure that we're getting the right base class subobject (without
15005 // ambiguities), we need to cast "this" to that subobject type; to
15006 // ensure that we don't go through the virtual call mechanism, we need
15007 // to qualify the operator= name with the base class (see below). However,
15008 // this means that if the base class has a protected copy assignment
15009 // operator, the protected member access check will fail. So, we
15010 // rewrite "protected" access to "public" access in this case, since we
15011 // know by construction that we're calling from a derived class.
15012 if (CopyingBaseSubobject) {
15013 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
15014 L != LEnd; ++L) {
15015 if (L.getAccess() == AS_protected)
15016 L.setAccess(AS_public);
15017 }
15018 }
15019
15020 // Create the nested-name-specifier that will be used to qualify the
15021 // reference to operator=; this is required to suppress the virtual
15022 // call mechanism.
15023 CXXScopeSpec SS;
15024 // FIXME: Don't canonicalize this.
15025 const Type *CanonicalT = S.Context.getCanonicalType(T: T.getTypePtr());
15026 SS.MakeTrivial(Context&: S.Context, Qualifier: NestedNameSpecifier(CanonicalT), R: Loc);
15027
15028 // Create the reference to operator=.
15029 ExprResult OpEqualRef
15030 = S.BuildMemberReferenceExpr(Base: To.build(S, Loc), BaseType: T, OpLoc: Loc, /*IsArrow=*/false,
15031 SS, /*TemplateKWLoc=*/SourceLocation(),
15032 /*FirstQualifierInScope=*/nullptr,
15033 R&: OpLookup,
15034 /*TemplateArgs=*/nullptr, /*S*/nullptr,
15035 /*SuppressQualifierCheck=*/true);
15036 if (OpEqualRef.isInvalid())
15037 return StmtError();
15038
15039 // Build the call to the assignment operator.
15040
15041 Expr *FromInst = From.build(S, Loc);
15042 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/S: nullptr,
15043 MemExpr: OpEqualRef.getAs<Expr>(),
15044 LParenLoc: Loc, Args: FromInst, RParenLoc: Loc);
15045 if (Call.isInvalid())
15046 return StmtError();
15047
15048 // If we built a call to a trivial 'operator=' while copying an array,
15049 // bail out. We'll replace the whole shebang with a memcpy.
15050 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Val: Call.get());
15051 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
15052 return StmtResult((Stmt*)nullptr);
15053
15054 // Convert to an expression-statement, and clean up any produced
15055 // temporaries.
15056 return S.ActOnExprStmt(Arg: Call);
15057 }
15058
15059 // - if the subobject is of scalar type, the built-in assignment
15060 // operator is used.
15061 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
15062 if (!ArrayTy) {
15063 ExprResult Assignment = S.CreateBuiltinBinOp(
15064 OpLoc: Loc, Opc: BO_Assign, LHSExpr: To.build(S, Loc), RHSExpr: From.build(S, Loc));
15065 if (Assignment.isInvalid())
15066 return StmtError();
15067 return S.ActOnExprStmt(Arg: Assignment);
15068 }
15069
15070 // - if the subobject is an array, each element is assigned, in the
15071 // manner appropriate to the element type;
15072
15073 // Construct a loop over the array bounds, e.g.,
15074 //
15075 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
15076 //
15077 // that will copy each of the array elements.
15078 QualType SizeType = S.Context.getSizeType();
15079
15080 // Create the iteration variable.
15081 IdentifierInfo *IterationVarName = nullptr;
15082 {
15083 SmallString<8> Str;
15084 llvm::raw_svector_ostream OS(Str);
15085 OS << "__i" << Depth;
15086 IterationVarName = &S.Context.Idents.get(Name: OS.str());
15087 }
15088 VarDecl *IterationVar = VarDecl::Create(C&: S.Context, DC: S.CurContext, StartLoc: Loc, IdLoc: Loc,
15089 Id: IterationVarName, T: SizeType,
15090 TInfo: S.Context.getTrivialTypeSourceInfo(T: SizeType, Loc),
15091 S: SC_None);
15092
15093 // Initialize the iteration variable to zero.
15094 llvm::APInt Zero(S.Context.getTypeSize(T: SizeType), 0);
15095 IterationVar->setInit(IntegerLiteral::Create(C: S.Context, V: Zero, type: SizeType, l: Loc));
15096
15097 // Creates a reference to the iteration variable.
15098 RefBuilder IterationVarRef(IterationVar, SizeType);
15099 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
15100
15101 // Create the DeclStmt that holds the iteration variable.
15102 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
15103
15104 // Subscript the "from" and "to" expressions with the iteration variable.
15105 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
15106 MoveCastBuilder FromIndexMove(FromIndexCopy);
15107 const ExprBuilder *FromIndex;
15108 if (Copying)
15109 FromIndex = &FromIndexCopy;
15110 else
15111 FromIndex = &FromIndexMove;
15112
15113 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
15114
15115 // Build the copy/move for an individual element of the array.
15116 StmtResult Copy =
15117 buildSingleCopyAssignRecursively(S, Loc, T: ArrayTy->getElementType(),
15118 To: ToIndex, From: *FromIndex, CopyingBaseSubobject,
15119 Copying, Depth: Depth + 1);
15120 // Bail out if copying fails or if we determined that we should use memcpy.
15121 if (Copy.isInvalid() || !Copy.get())
15122 return Copy;
15123
15124 // Create the comparison against the array bound.
15125 llvm::APInt Upper
15126 = ArrayTy->getSize().zextOrTrunc(width: S.Context.getTypeSize(T: SizeType));
15127 Expr *Comparison = BinaryOperator::Create(
15128 C: S.Context, lhs: IterationVarRefRVal.build(S, Loc),
15129 rhs: IntegerLiteral::Create(C: S.Context, V: Upper, type: SizeType, l: Loc), opc: BO_NE,
15130 ResTy: S.Context.BoolTy, VK: VK_PRValue, OK: OK_Ordinary, opLoc: Loc,
15131 FPFeatures: S.CurFPFeatureOverrides());
15132
15133 // Create the pre-increment of the iteration variable. We can determine
15134 // whether the increment will overflow based on the value of the array
15135 // bound.
15136 Expr *Increment = UnaryOperator::Create(
15137 C: S.Context, input: IterationVarRef.build(S, Loc), opc: UO_PreInc, type: SizeType, VK: VK_LValue,
15138 OK: OK_Ordinary, l: Loc, CanOverflow: Upper.isMaxValue(), FPFeatures: S.CurFPFeatureOverrides());
15139
15140 // Construct the loop that copies all elements of this array.
15141 return S.ActOnForStmt(
15142 ForLoc: Loc, LParenLoc: Loc, First: InitStmt,
15143 Second: S.ActOnCondition(S: nullptr, Loc, SubExpr: Comparison, CK: Sema::ConditionKind::Boolean),
15144 Third: S.MakeFullDiscardedValueExpr(Arg: Increment), RParenLoc: Loc, Body: Copy.get());
15145}
15146
15147static StmtResult
15148buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
15149 const ExprBuilder &To, const ExprBuilder &From,
15150 bool CopyingBaseSubobject, bool Copying) {
15151 // Maybe we should use a memcpy?
15152 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
15153 T.isTriviallyCopyableType(Context: S.Context))
15154 return buildMemcpyForAssignmentOp(S, Loc, T, ToB: To, FromB: From);
15155
15156 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
15157 CopyingBaseSubobject,
15158 Copying, Depth: 0));
15159
15160 // If we ended up picking a trivial assignment operator for an array of a
15161 // non-trivially-copyable class type, just emit a memcpy.
15162 if (!Result.isInvalid() && !Result.get())
15163 return buildMemcpyForAssignmentOp(S, Loc, T, ToB: To, FromB: From);
15164
15165 return Result;
15166}
15167
15168CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
15169 // Note: The following rules are largely analoguous to the copy
15170 // constructor rules. Note that virtual bases are not taken into account
15171 // for determining the argument type of the operator. Note also that
15172 // operators taking an object instead of a reference are allowed.
15173 assert(ClassDecl->needsImplicitCopyAssignment());
15174
15175 DeclaringSpecialMember DSM(*this, ClassDecl,
15176 CXXSpecialMemberKind::CopyAssignment);
15177 if (DSM.isAlreadyBeingDeclared())
15178 return nullptr;
15179
15180 QualType ArgType = Context.getTagType(Keyword: ElaboratedTypeKeyword::None,
15181 /*Qualifier=*/std::nullopt, TD: ClassDecl,
15182 /*OwnsTag=*/false);
15183 LangAS AS = getDefaultCXXMethodAddrSpace();
15184 if (AS != LangAS::Default)
15185 ArgType = Context.getAddrSpaceQualType(T: ArgType, AddressSpace: AS);
15186 QualType RetType = Context.getLValueReferenceType(T: ArgType);
15187 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
15188 if (Const)
15189 ArgType = ArgType.withConst();
15190
15191 ArgType = Context.getLValueReferenceType(T: ArgType);
15192
15193 bool Constexpr = defaultedSpecialMemberIsConstexpr(
15194 S&: *this, ClassDecl, CSM: CXXSpecialMemberKind::CopyAssignment, ConstArg: Const);
15195
15196 // An implicitly-declared copy assignment operator is an inline public
15197 // member of its class.
15198 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(Op: OO_Equal);
15199 SourceLocation ClassLoc = ClassDecl->getLocation();
15200 DeclarationNameInfo NameInfo(Name, ClassLoc);
15201 CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create(
15202 C&: Context, RD: ClassDecl, StartLoc: ClassLoc, NameInfo, T: QualType(),
15203 /*TInfo=*/nullptr, /*StorageClass=*/SC: SC_None,
15204 UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
15205 /*isInline=*/true,
15206 ConstexprKind: Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
15207 EndLocation: SourceLocation());
15208 CopyAssignment->setAccess(AS_public);
15209 CopyAssignment->setDefaulted();
15210 CopyAssignment->setImplicit();
15211
15212 setupImplicitSpecialMemberType(SpecialMem: CopyAssignment, ResultTy: RetType, Args: ArgType);
15213
15214 if (getLangOpts().CUDA)
15215 CUDA().inferTargetForImplicitSpecialMember(
15216 ClassDecl, CSM: CXXSpecialMemberKind::CopyAssignment, MemberDecl: CopyAssignment,
15217 /* ConstRHS */ Const,
15218 /* Diagnose */ false);
15219
15220 // Add the parameter to the operator.
15221 ParmVarDecl *FromParam = ParmVarDecl::Create(C&: Context, DC: CopyAssignment,
15222 StartLoc: ClassLoc, IdLoc: ClassLoc,
15223 /*Id=*/nullptr, T: ArgType,
15224 /*TInfo=*/nullptr, S: SC_None,
15225 DefArg: nullptr);
15226 CopyAssignment->setParams(FromParam);
15227
15228 CopyAssignment->setTrivial(
15229 ClassDecl->needsOverloadResolutionForCopyAssignment()
15230 ? SpecialMemberIsTrivial(MD: CopyAssignment,
15231 CSM: CXXSpecialMemberKind::CopyAssignment)
15232 : ClassDecl->hasTrivialCopyAssignment());
15233
15234 // Note that we have added this copy-assignment operator.
15235 ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
15236
15237 Scope *S = getScopeForContext(Ctx: ClassDecl);
15238 CheckImplicitSpecialMemberDeclaration(S, FD: CopyAssignment);
15239
15240 if (ShouldDeleteSpecialMember(MD: CopyAssignment,
15241 CSM: CXXSpecialMemberKind::CopyAssignment)) {
15242 ClassDecl->setImplicitCopyAssignmentIsDeleted();
15243 SetDeclDeleted(dcl: CopyAssignment, DelLoc: ClassLoc);
15244 }
15245
15246 if (S)
15247 PushOnScopeChains(D: CopyAssignment, S, AddToContext: false);
15248 ClassDecl->addDecl(D: CopyAssignment);
15249
15250 return CopyAssignment;
15251}
15252
15253/// Diagnose an implicit copy operation for a class which is odr-used, but
15254/// which is deprecated because the class has a user-declared copy constructor,
15255/// copy assignment operator, or destructor.
15256static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
15257 assert(CopyOp->isImplicit());
15258
15259 CXXRecordDecl *RD = CopyOp->getParent();
15260 CXXMethodDecl *UserDeclaredOperation = nullptr;
15261
15262 if (RD->hasUserDeclaredDestructor()) {
15263 UserDeclaredOperation = RD->getDestructor();
15264 } else if (!isa<CXXConstructorDecl>(Val: CopyOp) &&
15265 RD->hasUserDeclaredCopyConstructor()) {
15266 // Find any user-declared copy constructor.
15267 for (auto *I : RD->ctors()) {
15268 if (I->isCopyConstructor()) {
15269 UserDeclaredOperation = I;
15270 break;
15271 }
15272 }
15273 assert(UserDeclaredOperation);
15274 } else if (isa<CXXConstructorDecl>(Val: CopyOp) &&
15275 RD->hasUserDeclaredCopyAssignment()) {
15276 // Find any user-declared move assignment operator.
15277 for (auto *I : RD->methods()) {
15278 if (I->isCopyAssignmentOperator()) {
15279 UserDeclaredOperation = I;
15280 break;
15281 }
15282 }
15283 assert(UserDeclaredOperation);
15284 }
15285
15286 if (UserDeclaredOperation) {
15287 bool UDOIsUserProvided = UserDeclaredOperation->isUserProvided();
15288 bool UDOIsDestructor = isa<CXXDestructorDecl>(Val: UserDeclaredOperation);
15289 bool IsCopyAssignment = !isa<CXXConstructorDecl>(Val: CopyOp);
15290 unsigned DiagID =
15291 (UDOIsUserProvided && UDOIsDestructor)
15292 ? diag::warn_deprecated_copy_with_user_provided_dtor
15293 : (UDOIsUserProvided && !UDOIsDestructor)
15294 ? diag::warn_deprecated_copy_with_user_provided_copy
15295 : (!UDOIsUserProvided && UDOIsDestructor)
15296 ? diag::warn_deprecated_copy_with_dtor
15297 : diag::warn_deprecated_copy;
15298 S.Diag(Loc: UserDeclaredOperation->getLocation(), DiagID)
15299 << RD << IsCopyAssignment;
15300 }
15301}
15302
15303void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
15304 CXXMethodDecl *CopyAssignOperator) {
15305 assert((CopyAssignOperator->isDefaulted() &&
15306 CopyAssignOperator->isOverloadedOperator() &&
15307 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
15308 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
15309 !CopyAssignOperator->isDeleted()) &&
15310 "DefineImplicitCopyAssignment called for wrong function");
15311 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
15312 return;
15313
15314 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
15315 if (ClassDecl->isInvalidDecl()) {
15316 CopyAssignOperator->setInvalidDecl();
15317 return;
15318 }
15319
15320 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
15321
15322 // The exception specification is needed because we are defining the
15323 // function.
15324 ResolveExceptionSpec(Loc: CurrentLocation,
15325 FPT: CopyAssignOperator->getType()->castAs<FunctionProtoType>());
15326
15327 // Add a context note for diagnostics produced after this point.
15328 Scope.addContextNote(UseLoc: CurrentLocation);
15329
15330 // C++11 [class.copy]p18:
15331 // The [definition of an implicitly declared copy assignment operator] is
15332 // deprecated if the class has a user-declared copy constructor or a
15333 // user-declared destructor.
15334 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
15335 diagnoseDeprecatedCopyOperation(S&: *this, CopyOp: CopyAssignOperator);
15336
15337 // C++0x [class.copy]p30:
15338 // The implicitly-defined or explicitly-defaulted copy assignment operator
15339 // for a non-union class X performs memberwise copy assignment of its
15340 // subobjects. The direct base classes of X are assigned first, in the
15341 // order of their declaration in the base-specifier-list, and then the
15342 // immediate non-static data members of X are assigned, in the order in
15343 // which they were declared in the class definition.
15344
15345 // The statements that form the synthesized function body.
15346 SmallVector<Stmt*, 8> Statements;
15347
15348 // The parameter for the "other" object, which we are copying from.
15349 ParmVarDecl *Other = CopyAssignOperator->getNonObjectParameter(I: 0);
15350 Qualifiers OtherQuals = Other->getType().getQualifiers();
15351 QualType OtherRefType = Other->getType();
15352 if (OtherRefType->isLValueReferenceType()) {
15353 OtherRefType = OtherRefType->getPointeeType();
15354 OtherQuals = OtherRefType.getQualifiers();
15355 }
15356
15357 // Our location for everything implicitly-generated.
15358 SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
15359 ? CopyAssignOperator->getEndLoc()
15360 : CopyAssignOperator->getLocation();
15361
15362 // Builds a DeclRefExpr for the "other" object.
15363 RefBuilder OtherRef(Other, OtherRefType);
15364
15365 // Builds the function object parameter.
15366 std::optional<ThisBuilder> This;
15367 std::optional<DerefBuilder> DerefThis;
15368 std::optional<RefBuilder> ExplicitObject;
15369 bool IsArrow = false;
15370 QualType ObjectType;
15371 if (CopyAssignOperator->isExplicitObjectMemberFunction()) {
15372 ObjectType = CopyAssignOperator->getParamDecl(i: 0)->getType();
15373 if (ObjectType->isReferenceType())
15374 ObjectType = ObjectType->getPointeeType();
15375 ExplicitObject.emplace(args: CopyAssignOperator->getParamDecl(i: 0), args&: ObjectType);
15376 } else {
15377 ObjectType = getCurrentThisType();
15378 This.emplace();
15379 DerefThis.emplace(args&: *This);
15380 IsArrow = !LangOpts.HLSL;
15381 }
15382 ExprBuilder &ObjectParameter =
15383 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15384 : static_cast<ExprBuilder &>(*This);
15385
15386 // Assign base classes.
15387 bool Invalid = false;
15388 for (auto &Base : ClassDecl->bases()) {
15389 // Form the assignment:
15390 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
15391 QualType BaseType = Base.getType().getUnqualifiedType();
15392 if (!BaseType->isRecordType()) {
15393 Invalid = true;
15394 continue;
15395 }
15396
15397 CXXCastPath BasePath;
15398 BasePath.push_back(Elt: &Base);
15399
15400 // Construct the "from" expression, which is an implicit cast to the
15401 // appropriately-qualified base type.
15402 CastBuilder From(OtherRef, Context.getQualifiedType(T: BaseType, Qs: OtherQuals),
15403 VK_LValue, BasePath);
15404
15405 // Dereference "this".
15406 CastBuilder To(
15407 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15408 : static_cast<ExprBuilder &>(*DerefThis),
15409 Context.getQualifiedType(T: BaseType, Qs: ObjectType.getQualifiers()),
15410 VK_LValue, BasePath);
15411
15412 // Build the copy.
15413 StmtResult Copy = buildSingleCopyAssign(S&: *this, Loc, T: BaseType,
15414 To, From,
15415 /*CopyingBaseSubobject=*/true,
15416 /*Copying=*/true);
15417 if (Copy.isInvalid()) {
15418 CopyAssignOperator->setInvalidDecl();
15419 return;
15420 }
15421
15422 // Success! Record the copy.
15423 Statements.push_back(Elt: Copy.getAs<Expr>());
15424 }
15425
15426 // Assign non-static members.
15427 for (auto *Field : ClassDecl->fields()) {
15428 // FIXME: We should form some kind of AST representation for the implied
15429 // memcpy in a union copy operation.
15430 if (Field->isUnnamedBitField() || Field->getParent()->isUnion())
15431 continue;
15432
15433 if (Field->isInvalidDecl()) {
15434 Invalid = true;
15435 continue;
15436 }
15437
15438 // Check for members of reference type; we can't copy those.
15439 if (Field->getType()->isReferenceType()) {
15440 Diag(Loc: ClassDecl->getLocation(), DiagID: diag::err_uninitialized_member_for_assign)
15441 << Context.getCanonicalTagType(TD: ClassDecl) << 0
15442 << Field->getDeclName();
15443 Diag(Loc: Field->getLocation(), DiagID: diag::note_declared_at);
15444 Invalid = true;
15445 continue;
15446 }
15447
15448 // Check for members of const-qualified, non-class type.
15449 QualType BaseType = Context.getBaseElementType(QT: Field->getType());
15450 if (!BaseType->isRecordType() && BaseType.isConstQualified()) {
15451 Diag(Loc: ClassDecl->getLocation(), DiagID: diag::err_uninitialized_member_for_assign)
15452 << Context.getCanonicalTagType(TD: ClassDecl) << 1
15453 << Field->getDeclName();
15454 Diag(Loc: Field->getLocation(), DiagID: diag::note_declared_at);
15455 Invalid = true;
15456 continue;
15457 }
15458
15459 // Suppress assigning zero-width bitfields.
15460 if (Field->isZeroLengthBitField())
15461 continue;
15462
15463 QualType FieldType = Field->getType().getNonReferenceType();
15464 if (FieldType->isIncompleteArrayType()) {
15465 assert(ClassDecl->hasFlexibleArrayMember() &&
15466 "Incomplete array type is not valid");
15467 continue;
15468 }
15469
15470 // Build references to the field in the object we're copying from and to.
15471 CXXScopeSpec SS; // Intentionally empty
15472 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
15473 LookupMemberName);
15474 MemberLookup.addDecl(D: Field);
15475 MemberLookup.resolveKind();
15476
15477 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
15478 MemberBuilder To(ObjectParameter, ObjectType, IsArrow, MemberLookup);
15479 // Build the copy of this field.
15480 StmtResult Copy = buildSingleCopyAssign(S&: *this, Loc, T: FieldType,
15481 To, From,
15482 /*CopyingBaseSubobject=*/false,
15483 /*Copying=*/true);
15484 if (Copy.isInvalid()) {
15485 CopyAssignOperator->setInvalidDecl();
15486 return;
15487 }
15488
15489 // Success! Record the copy.
15490 Statements.push_back(Elt: Copy.getAs<Stmt>());
15491 }
15492
15493 if (!Invalid) {
15494 // Add a "return *this;"
15495 Expr *ThisExpr =
15496 (ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15497 : LangOpts.HLSL ? static_cast<ExprBuilder &>(*This)
15498 : static_cast<ExprBuilder &>(*DerefThis))
15499 .build(S&: *this, Loc);
15500 StmtResult Return = BuildReturnStmt(ReturnLoc: Loc, RetValExp: ThisExpr);
15501 if (Return.isInvalid())
15502 Invalid = true;
15503 else
15504 Statements.push_back(Elt: Return.getAs<Stmt>());
15505 }
15506
15507 if (Invalid) {
15508 CopyAssignOperator->setInvalidDecl();
15509 return;
15510 }
15511
15512 StmtResult Body;
15513 {
15514 CompoundScopeRAII CompoundScope(*this);
15515 Body = ActOnCompoundStmt(L: Loc, R: Loc, Elts: Statements,
15516 /*isStmtExpr=*/false);
15517 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
15518 }
15519 CopyAssignOperator->setBody(Body.getAs<Stmt>());
15520 CopyAssignOperator->markUsed(C&: Context);
15521
15522 if (ASTMutationListener *L = getASTMutationListener()) {
15523 L->CompletedImplicitDefinition(D: CopyAssignOperator);
15524 }
15525}
15526
15527CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
15528 assert(ClassDecl->needsImplicitMoveAssignment());
15529
15530 DeclaringSpecialMember DSM(*this, ClassDecl,
15531 CXXSpecialMemberKind::MoveAssignment);
15532 if (DSM.isAlreadyBeingDeclared())
15533 return nullptr;
15534
15535 // Note: The following rules are largely analoguous to the move
15536 // constructor rules.
15537
15538 QualType ArgType = Context.getTagType(Keyword: ElaboratedTypeKeyword::None,
15539 /*Qualifier=*/std::nullopt, TD: ClassDecl,
15540 /*OwnsTag=*/false);
15541 LangAS AS = getDefaultCXXMethodAddrSpace();
15542 if (AS != LangAS::Default)
15543 ArgType = Context.getAddrSpaceQualType(T: ArgType, AddressSpace: AS);
15544 QualType RetType = Context.getLValueReferenceType(T: ArgType);
15545 ArgType = Context.getRValueReferenceType(T: ArgType);
15546
15547 bool Constexpr = defaultedSpecialMemberIsConstexpr(
15548 S&: *this, ClassDecl, CSM: CXXSpecialMemberKind::MoveAssignment, ConstArg: false);
15549
15550 // An implicitly-declared move assignment operator is an inline public
15551 // member of its class.
15552 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(Op: OO_Equal);
15553 SourceLocation ClassLoc = ClassDecl->getLocation();
15554 DeclarationNameInfo NameInfo(Name, ClassLoc);
15555 CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create(
15556 C&: Context, RD: ClassDecl, StartLoc: ClassLoc, NameInfo, T: QualType(),
15557 /*TInfo=*/nullptr, /*StorageClass=*/SC: SC_None,
15558 UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
15559 /*isInline=*/true,
15560 ConstexprKind: Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
15561 EndLocation: SourceLocation());
15562 MoveAssignment->setAccess(AS_public);
15563 MoveAssignment->setDefaulted();
15564 MoveAssignment->setImplicit();
15565
15566 setupImplicitSpecialMemberType(SpecialMem: MoveAssignment, ResultTy: RetType, Args: ArgType);
15567
15568 if (getLangOpts().CUDA)
15569 CUDA().inferTargetForImplicitSpecialMember(
15570 ClassDecl, CSM: CXXSpecialMemberKind::MoveAssignment, MemberDecl: MoveAssignment,
15571 /* ConstRHS */ false,
15572 /* Diagnose */ false);
15573
15574 // Add the parameter to the operator.
15575 ParmVarDecl *FromParam = ParmVarDecl::Create(C&: Context, DC: MoveAssignment,
15576 StartLoc: ClassLoc, IdLoc: ClassLoc,
15577 /*Id=*/nullptr, T: ArgType,
15578 /*TInfo=*/nullptr, S: SC_None,
15579 DefArg: nullptr);
15580 MoveAssignment->setParams(FromParam);
15581
15582 MoveAssignment->setTrivial(
15583 ClassDecl->needsOverloadResolutionForMoveAssignment()
15584 ? SpecialMemberIsTrivial(MD: MoveAssignment,
15585 CSM: CXXSpecialMemberKind::MoveAssignment)
15586 : ClassDecl->hasTrivialMoveAssignment());
15587
15588 // Note that we have added this copy-assignment operator.
15589 ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
15590
15591 Scope *S = getScopeForContext(Ctx: ClassDecl);
15592 CheckImplicitSpecialMemberDeclaration(S, FD: MoveAssignment);
15593
15594 if (ShouldDeleteSpecialMember(MD: MoveAssignment,
15595 CSM: CXXSpecialMemberKind::MoveAssignment)) {
15596 ClassDecl->setImplicitMoveAssignmentIsDeleted();
15597 SetDeclDeleted(dcl: MoveAssignment, DelLoc: ClassLoc);
15598 }
15599
15600 if (S)
15601 PushOnScopeChains(D: MoveAssignment, S, AddToContext: false);
15602 ClassDecl->addDecl(D: MoveAssignment);
15603
15604 return MoveAssignment;
15605}
15606
15607/// Check if we're implicitly defining a move assignment operator for a class
15608/// with virtual bases. Such a move assignment might move-assign the virtual
15609/// base multiple times.
15610static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
15611 SourceLocation CurrentLocation) {
15612 assert(!Class->isDependentContext() && "should not define dependent move");
15613
15614 // Only a virtual base could get implicitly move-assigned multiple times.
15615 // Only a non-trivial move assignment can observe this. We only want to
15616 // diagnose if we implicitly define an assignment operator that assigns
15617 // two base classes, both of which move-assign the same virtual base.
15618 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
15619 Class->getNumBases() < 2)
15620 return;
15621
15622 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
15623 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
15624 VBaseMap VBases;
15625
15626 for (auto &BI : Class->bases()) {
15627 Worklist.push_back(Elt: &BI);
15628 while (!Worklist.empty()) {
15629 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
15630 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
15631
15632 // If the base has no non-trivial move assignment operators,
15633 // we don't care about moves from it.
15634 if (!Base->hasNonTrivialMoveAssignment())
15635 continue;
15636
15637 // If there's nothing virtual here, skip it.
15638 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
15639 continue;
15640
15641 // If we're not actually going to call a move assignment for this base,
15642 // or the selected move assignment is trivial, skip it.
15643 Sema::SpecialMemberOverloadResult SMOR =
15644 S.LookupSpecialMember(D: Base, SM: CXXSpecialMemberKind::MoveAssignment,
15645 /*ConstArg*/ false, /*VolatileArg*/ false,
15646 /*RValueThis*/ true, /*ConstThis*/ false,
15647 /*VolatileThis*/ false);
15648 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
15649 !SMOR.getMethod()->isMoveAssignmentOperator())
15650 continue;
15651
15652 if (BaseSpec->isVirtual()) {
15653 // We're going to move-assign this virtual base, and its move
15654 // assignment operator is not trivial. If this can happen for
15655 // multiple distinct direct bases of Class, diagnose it. (If it
15656 // only happens in one base, we'll diagnose it when synthesizing
15657 // that base class's move assignment operator.)
15658 CXXBaseSpecifier *&Existing =
15659 VBases.insert(KV: std::make_pair(x: Base->getCanonicalDecl(), y: &BI))
15660 .first->second;
15661 if (Existing && Existing != &BI) {
15662 S.Diag(Loc: CurrentLocation, DiagID: diag::warn_vbase_moved_multiple_times)
15663 << Class << Base;
15664 S.Diag(Loc: Existing->getBeginLoc(), DiagID: diag::note_vbase_moved_here)
15665 << (Base->getCanonicalDecl() ==
15666 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
15667 << Base << Existing->getType() << Existing->getSourceRange();
15668 S.Diag(Loc: BI.getBeginLoc(), DiagID: diag::note_vbase_moved_here)
15669 << (Base->getCanonicalDecl() ==
15670 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
15671 << Base << BI.getType() << BaseSpec->getSourceRange();
15672
15673 // Only diagnose each vbase once.
15674 Existing = nullptr;
15675 }
15676 } else {
15677 // Only walk over bases that have defaulted move assignment operators.
15678 // We assume that any user-provided move assignment operator handles
15679 // the multiple-moves-of-vbase case itself somehow.
15680 if (!SMOR.getMethod()->isDefaulted())
15681 continue;
15682
15683 // We're going to move the base classes of Base. Add them to the list.
15684 llvm::append_range(C&: Worklist, R: llvm::make_pointer_range(Range: Base->bases()));
15685 }
15686 }
15687 }
15688}
15689
15690void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
15691 CXXMethodDecl *MoveAssignOperator) {
15692 assert((MoveAssignOperator->isDefaulted() &&
15693 MoveAssignOperator->isOverloadedOperator() &&
15694 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
15695 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
15696 !MoveAssignOperator->isDeleted()) &&
15697 "DefineImplicitMoveAssignment called for wrong function");
15698 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
15699 return;
15700
15701 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
15702 if (ClassDecl->isInvalidDecl()) {
15703 MoveAssignOperator->setInvalidDecl();
15704 return;
15705 }
15706
15707 // C++0x [class.copy]p28:
15708 // The implicitly-defined or move assignment operator for a non-union class
15709 // X performs memberwise move assignment of its subobjects. The direct base
15710 // classes of X are assigned first, in the order of their declaration in the
15711 // base-specifier-list, and then the immediate non-static data members of X
15712 // are assigned, in the order in which they were declared in the class
15713 // definition.
15714
15715 // Issue a warning if our implicit move assignment operator will move
15716 // from a virtual base more than once.
15717 checkMoveAssignmentForRepeatedMove(S&: *this, Class: ClassDecl, CurrentLocation);
15718
15719 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
15720
15721 // The exception specification is needed because we are defining the
15722 // function.
15723 ResolveExceptionSpec(Loc: CurrentLocation,
15724 FPT: MoveAssignOperator->getType()->castAs<FunctionProtoType>());
15725
15726 // Add a context note for diagnostics produced after this point.
15727 Scope.addContextNote(UseLoc: CurrentLocation);
15728
15729 // The statements that form the synthesized function body.
15730 SmallVector<Stmt*, 8> Statements;
15731
15732 // The parameter for the "other" object, which we are move from.
15733 ParmVarDecl *Other = MoveAssignOperator->getNonObjectParameter(I: 0);
15734 QualType OtherRefType =
15735 Other->getType()->castAs<RValueReferenceType>()->getPointeeType();
15736
15737 // Our location for everything implicitly-generated.
15738 SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
15739 ? MoveAssignOperator->getEndLoc()
15740 : MoveAssignOperator->getLocation();
15741
15742 // Builds a reference to the "other" object.
15743 RefBuilder OtherRef(Other, OtherRefType);
15744 // Cast to rvalue.
15745 MoveCastBuilder MoveOther(OtherRef);
15746
15747 // Builds the function object parameter.
15748 std::optional<ThisBuilder> This;
15749 std::optional<DerefBuilder> DerefThis;
15750 std::optional<RefBuilder> ExplicitObject;
15751 QualType ObjectType;
15752 bool IsArrow = false;
15753 if (MoveAssignOperator->isExplicitObjectMemberFunction()) {
15754 ObjectType = MoveAssignOperator->getParamDecl(i: 0)->getType();
15755 if (ObjectType->isReferenceType())
15756 ObjectType = ObjectType->getPointeeType();
15757 ExplicitObject.emplace(args: MoveAssignOperator->getParamDecl(i: 0), args&: ObjectType);
15758 } else {
15759 ObjectType = getCurrentThisType();
15760 This.emplace();
15761 DerefThis.emplace(args&: *This);
15762 IsArrow = !getLangOpts().HLSL;
15763 }
15764 ExprBuilder &ObjectParameter =
15765 ExplicitObject ? *ExplicitObject : static_cast<ExprBuilder &>(*This);
15766
15767 // Assign base classes.
15768 bool Invalid = false;
15769 for (auto &Base : ClassDecl->bases()) {
15770 // C++11 [class.copy]p28:
15771 // It is unspecified whether subobjects representing virtual base classes
15772 // are assigned more than once by the implicitly-defined copy assignment
15773 // operator.
15774 // FIXME: Do not assign to a vbase that will be assigned by some other base
15775 // class. For a move-assignment, this can result in the vbase being moved
15776 // multiple times.
15777
15778 // Form the assignment:
15779 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
15780 QualType BaseType = Base.getType().getUnqualifiedType();
15781 if (!BaseType->isRecordType()) {
15782 Invalid = true;
15783 continue;
15784 }
15785
15786 CXXCastPath BasePath;
15787 BasePath.push_back(Elt: &Base);
15788
15789 // Construct the "from" expression, which is an implicit cast to the
15790 // appropriately-qualified base type.
15791 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
15792
15793 // Implicitly cast "this" to the appropriately-qualified base type.
15794 // Dereference "this".
15795 CastBuilder To(
15796 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15797 : static_cast<ExprBuilder &>(*DerefThis),
15798 Context.getQualifiedType(T: BaseType, Qs: ObjectType.getQualifiers()),
15799 VK_LValue, BasePath);
15800
15801 // Build the move.
15802 StmtResult Move = buildSingleCopyAssign(S&: *this, Loc, T: BaseType,
15803 To, From,
15804 /*CopyingBaseSubobject=*/true,
15805 /*Copying=*/false);
15806 if (Move.isInvalid()) {
15807 MoveAssignOperator->setInvalidDecl();
15808 return;
15809 }
15810
15811 // Success! Record the move.
15812 Statements.push_back(Elt: Move.getAs<Expr>());
15813 }
15814
15815 // Assign non-static members.
15816 for (auto *Field : ClassDecl->fields()) {
15817 // FIXME: We should form some kind of AST representation for the implied
15818 // memcpy in a union copy operation.
15819 if (Field->isUnnamedBitField() || Field->getParent()->isUnion())
15820 continue;
15821
15822 if (Field->isInvalidDecl()) {
15823 Invalid = true;
15824 continue;
15825 }
15826
15827 // Check for members of reference type; we can't move those.
15828 if (Field->getType()->isReferenceType()) {
15829 Diag(Loc: ClassDecl->getLocation(), DiagID: diag::err_uninitialized_member_for_assign)
15830 << Context.getCanonicalTagType(TD: ClassDecl) << 0
15831 << Field->getDeclName();
15832 Diag(Loc: Field->getLocation(), DiagID: diag::note_declared_at);
15833 Invalid = true;
15834 continue;
15835 }
15836
15837 // Check for members of const-qualified, non-class type.
15838 QualType BaseType = Context.getBaseElementType(QT: Field->getType());
15839 if (!BaseType->isRecordType() && BaseType.isConstQualified()) {
15840 Diag(Loc: ClassDecl->getLocation(), DiagID: diag::err_uninitialized_member_for_assign)
15841 << Context.getCanonicalTagType(TD: ClassDecl) << 1
15842 << Field->getDeclName();
15843 Diag(Loc: Field->getLocation(), DiagID: diag::note_declared_at);
15844 Invalid = true;
15845 continue;
15846 }
15847
15848 // Suppress assigning zero-width bitfields.
15849 if (Field->isZeroLengthBitField())
15850 continue;
15851
15852 QualType FieldType = Field->getType().getNonReferenceType();
15853 if (FieldType->isIncompleteArrayType()) {
15854 assert(ClassDecl->hasFlexibleArrayMember() &&
15855 "Incomplete array type is not valid");
15856 continue;
15857 }
15858
15859 // Build references to the field in the object we're copying from and to.
15860 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
15861 LookupMemberName);
15862 MemberLookup.addDecl(D: Field);
15863 MemberLookup.resolveKind();
15864 MemberBuilder From(MoveOther, OtherRefType,
15865 /*IsArrow=*/false, MemberLookup);
15866 MemberBuilder To(ObjectParameter, ObjectType, IsArrow, MemberLookup);
15867
15868 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
15869 "Member reference with rvalue base must be rvalue except for reference "
15870 "members, which aren't allowed for move assignment.");
15871
15872 // Build the move of this field.
15873 StmtResult Move = buildSingleCopyAssign(S&: *this, Loc, T: FieldType,
15874 To, From,
15875 /*CopyingBaseSubobject=*/false,
15876 /*Copying=*/false);
15877 if (Move.isInvalid()) {
15878 MoveAssignOperator->setInvalidDecl();
15879 return;
15880 }
15881
15882 // Success! Record the copy.
15883 Statements.push_back(Elt: Move.getAs<Stmt>());
15884 }
15885
15886 if (!Invalid) {
15887 // Add a "return *this;"
15888 Expr *ThisExpr =
15889 (ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15890 : LangOpts.HLSL ? static_cast<ExprBuilder &>(*This)
15891 : static_cast<ExprBuilder &>(*DerefThis))
15892 .build(S&: *this, Loc);
15893
15894 StmtResult Return = BuildReturnStmt(ReturnLoc: Loc, RetValExp: ThisExpr);
15895 if (Return.isInvalid())
15896 Invalid = true;
15897 else
15898 Statements.push_back(Elt: Return.getAs<Stmt>());
15899 }
15900
15901 if (Invalid) {
15902 MoveAssignOperator->setInvalidDecl();
15903 return;
15904 }
15905
15906 StmtResult Body;
15907 {
15908 CompoundScopeRAII CompoundScope(*this);
15909 Body = ActOnCompoundStmt(L: Loc, R: Loc, Elts: Statements,
15910 /*isStmtExpr=*/false);
15911 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
15912 }
15913 MoveAssignOperator->setBody(Body.getAs<Stmt>());
15914 MoveAssignOperator->markUsed(C&: Context);
15915
15916 if (ASTMutationListener *L = getASTMutationListener()) {
15917 L->CompletedImplicitDefinition(D: MoveAssignOperator);
15918 }
15919}
15920
15921CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
15922 CXXRecordDecl *ClassDecl) {
15923 // C++ [class.copy]p4:
15924 // If the class definition does not explicitly declare a copy
15925 // constructor, one is declared implicitly.
15926 assert(ClassDecl->needsImplicitCopyConstructor());
15927
15928 DeclaringSpecialMember DSM(*this, ClassDecl,
15929 CXXSpecialMemberKind::CopyConstructor);
15930 if (DSM.isAlreadyBeingDeclared())
15931 return nullptr;
15932
15933 QualType ClassType = Context.getTagType(Keyword: ElaboratedTypeKeyword::None,
15934 /*Qualifier=*/std::nullopt, TD: ClassDecl,
15935 /*OwnsTag=*/false);
15936 QualType ArgType = ClassType;
15937 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
15938 if (Const)
15939 ArgType = ArgType.withConst();
15940
15941 LangAS AS = getDefaultCXXMethodAddrSpace();
15942 if (AS != LangAS::Default)
15943 ArgType = Context.getAddrSpaceQualType(T: ArgType, AddressSpace: AS);
15944
15945 ArgType = Context.getLValueReferenceType(T: ArgType);
15946
15947 bool Constexpr = defaultedSpecialMemberIsConstexpr(
15948 S&: *this, ClassDecl, CSM: CXXSpecialMemberKind::CopyConstructor, ConstArg: Const);
15949
15950 DeclarationName Name
15951 = Context.DeclarationNames.getCXXConstructorName(
15952 Ty: Context.getCanonicalType(T: ClassType));
15953 SourceLocation ClassLoc = ClassDecl->getLocation();
15954 DeclarationNameInfo NameInfo(Name, ClassLoc);
15955
15956 // An implicitly-declared copy constructor is an inline public
15957 // member of its class.
15958 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
15959 C&: Context, RD: ClassDecl, StartLoc: ClassLoc, NameInfo, T: QualType(), /*TInfo=*/nullptr,
15960 ES: ExplicitSpecifier(), UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
15961 /*isInline=*/true,
15962 /*isImplicitlyDeclared=*/true,
15963 ConstexprKind: Constexpr ? ConstexprSpecKind::Constexpr
15964 : ConstexprSpecKind::Unspecified);
15965 CopyConstructor->setAccess(AS_public);
15966 CopyConstructor->setDefaulted();
15967
15968 setupImplicitSpecialMemberType(SpecialMem: CopyConstructor, ResultTy: Context.VoidTy, Args: ArgType);
15969
15970 if (getLangOpts().CUDA)
15971 CUDA().inferTargetForImplicitSpecialMember(
15972 ClassDecl, CSM: CXXSpecialMemberKind::CopyConstructor, MemberDecl: CopyConstructor,
15973 /* ConstRHS */ Const,
15974 /* Diagnose */ false);
15975
15976 // During template instantiation of special member functions we need a
15977 // reliable TypeSourceInfo for the parameter types in order to allow functions
15978 // to be substituted.
15979 TypeSourceInfo *TSI = nullptr;
15980 if (inTemplateInstantiation() && ClassDecl->isLambda())
15981 TSI = Context.getTrivialTypeSourceInfo(T: ArgType);
15982
15983 // Add the parameter to the constructor.
15984 ParmVarDecl *FromParam =
15985 ParmVarDecl::Create(C&: Context, DC: CopyConstructor, StartLoc: ClassLoc, IdLoc: ClassLoc,
15986 /*IdentifierInfo=*/Id: nullptr, T: ArgType,
15987 /*TInfo=*/TSI, S: SC_None, DefArg: nullptr);
15988 CopyConstructor->setParams(FromParam);
15989
15990 CopyConstructor->setTrivial(
15991 ClassDecl->needsOverloadResolutionForCopyConstructor()
15992 ? SpecialMemberIsTrivial(MD: CopyConstructor,
15993 CSM: CXXSpecialMemberKind::CopyConstructor)
15994 : ClassDecl->hasTrivialCopyConstructor());
15995
15996 CopyConstructor->setTrivialForCall(
15997 ClassDecl->hasAttr<TrivialABIAttr>() ||
15998 (ClassDecl->needsOverloadResolutionForCopyConstructor()
15999 ? SpecialMemberIsTrivial(MD: CopyConstructor,
16000 CSM: CXXSpecialMemberKind::CopyConstructor,
16001 TAH: TrivialABIHandling::ConsiderTrivialABI)
16002 : ClassDecl->hasTrivialCopyConstructorForCall()));
16003
16004 // Note that we have declared this constructor.
16005 ++getASTContext().NumImplicitCopyConstructorsDeclared;
16006
16007 Scope *S = getScopeForContext(Ctx: ClassDecl);
16008 CheckImplicitSpecialMemberDeclaration(S, FD: CopyConstructor);
16009
16010 if (ShouldDeleteSpecialMember(MD: CopyConstructor,
16011 CSM: CXXSpecialMemberKind::CopyConstructor)) {
16012 ClassDecl->setImplicitCopyConstructorIsDeleted();
16013 SetDeclDeleted(dcl: CopyConstructor, DelLoc: ClassLoc);
16014 }
16015
16016 if (S)
16017 PushOnScopeChains(D: CopyConstructor, S, AddToContext: false);
16018 ClassDecl->addDecl(D: CopyConstructor);
16019
16020 return CopyConstructor;
16021}
16022
16023void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
16024 CXXConstructorDecl *CopyConstructor) {
16025 assert((CopyConstructor->isDefaulted() &&
16026 CopyConstructor->isCopyConstructor() &&
16027 !CopyConstructor->doesThisDeclarationHaveABody() &&
16028 !CopyConstructor->isDeleted()) &&
16029 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
16030 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
16031 return;
16032
16033 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
16034 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
16035
16036 SynthesizedFunctionScope Scope(*this, CopyConstructor);
16037
16038 // The exception specification is needed because we are defining the
16039 // function.
16040 ResolveExceptionSpec(Loc: CurrentLocation,
16041 FPT: CopyConstructor->getType()->castAs<FunctionProtoType>());
16042 MarkVTableUsed(Loc: CurrentLocation, Class: ClassDecl);
16043
16044 // Add a context note for diagnostics produced after this point.
16045 Scope.addContextNote(UseLoc: CurrentLocation);
16046
16047 // C++11 [class.copy]p7:
16048 // The [definition of an implicitly declared copy constructor] is
16049 // deprecated if the class has a user-declared copy assignment operator
16050 // or a user-declared destructor.
16051 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
16052 diagnoseDeprecatedCopyOperation(S&: *this, CopyOp: CopyConstructor);
16053
16054 if (SetCtorInitializers(Constructor: CopyConstructor, /*AnyErrors=*/false)) {
16055 CopyConstructor->setInvalidDecl();
16056 } else {
16057 SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
16058 ? CopyConstructor->getEndLoc()
16059 : CopyConstructor->getLocation();
16060 Sema::CompoundScopeRAII CompoundScope(*this);
16061 CopyConstructor->setBody(
16062 ActOnCompoundStmt(L: Loc, R: Loc, Elts: {}, /*isStmtExpr=*/false).getAs<Stmt>());
16063 CopyConstructor->markUsed(C&: Context);
16064 }
16065
16066 if (ASTMutationListener *L = getASTMutationListener()) {
16067 L->CompletedImplicitDefinition(D: CopyConstructor);
16068 }
16069}
16070
16071CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
16072 CXXRecordDecl *ClassDecl) {
16073 assert(ClassDecl->needsImplicitMoveConstructor());
16074
16075 DeclaringSpecialMember DSM(*this, ClassDecl,
16076 CXXSpecialMemberKind::MoveConstructor);
16077 if (DSM.isAlreadyBeingDeclared())
16078 return nullptr;
16079
16080 QualType ClassType = Context.getTagType(Keyword: ElaboratedTypeKeyword::None,
16081 /*Qualifier=*/std::nullopt, TD: ClassDecl,
16082 /*OwnsTag=*/false);
16083
16084 QualType ArgType = ClassType;
16085 LangAS AS = getDefaultCXXMethodAddrSpace();
16086 if (AS != LangAS::Default)
16087 ArgType = Context.getAddrSpaceQualType(T: ClassType, AddressSpace: AS);
16088 ArgType = Context.getRValueReferenceType(T: ArgType);
16089
16090 bool Constexpr = defaultedSpecialMemberIsConstexpr(
16091 S&: *this, ClassDecl, CSM: CXXSpecialMemberKind::MoveConstructor, ConstArg: false);
16092
16093 DeclarationName Name
16094 = Context.DeclarationNames.getCXXConstructorName(
16095 Ty: Context.getCanonicalType(T: ClassType));
16096 SourceLocation ClassLoc = ClassDecl->getLocation();
16097 DeclarationNameInfo NameInfo(Name, ClassLoc);
16098
16099 // C++11 [class.copy]p11:
16100 // An implicitly-declared copy/move constructor is an inline public
16101 // member of its class.
16102 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
16103 C&: Context, RD: ClassDecl, StartLoc: ClassLoc, NameInfo, T: QualType(), /*TInfo=*/nullptr,
16104 ES: ExplicitSpecifier(), UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
16105 /*isInline=*/true,
16106 /*isImplicitlyDeclared=*/true,
16107 ConstexprKind: Constexpr ? ConstexprSpecKind::Constexpr
16108 : ConstexprSpecKind::Unspecified);
16109 MoveConstructor->setAccess(AS_public);
16110 MoveConstructor->setDefaulted();
16111
16112 setupImplicitSpecialMemberType(SpecialMem: MoveConstructor, ResultTy: Context.VoidTy, Args: ArgType);
16113
16114 if (getLangOpts().CUDA)
16115 CUDA().inferTargetForImplicitSpecialMember(
16116 ClassDecl, CSM: CXXSpecialMemberKind::MoveConstructor, MemberDecl: MoveConstructor,
16117 /* ConstRHS */ false,
16118 /* Diagnose */ false);
16119
16120 // Add the parameter to the constructor.
16121 ParmVarDecl *FromParam = ParmVarDecl::Create(C&: Context, DC: MoveConstructor,
16122 StartLoc: ClassLoc, IdLoc: ClassLoc,
16123 /*IdentifierInfo=*/Id: nullptr,
16124 T: ArgType, /*TInfo=*/nullptr,
16125 S: SC_None, DefArg: nullptr);
16126 MoveConstructor->setParams(FromParam);
16127
16128 MoveConstructor->setTrivial(
16129 ClassDecl->needsOverloadResolutionForMoveConstructor()
16130 ? SpecialMemberIsTrivial(MD: MoveConstructor,
16131 CSM: CXXSpecialMemberKind::MoveConstructor)
16132 : ClassDecl->hasTrivialMoveConstructor());
16133
16134 MoveConstructor->setTrivialForCall(
16135 ClassDecl->hasAttr<TrivialABIAttr>() ||
16136 (ClassDecl->needsOverloadResolutionForMoveConstructor()
16137 ? SpecialMemberIsTrivial(MD: MoveConstructor,
16138 CSM: CXXSpecialMemberKind::MoveConstructor,
16139 TAH: TrivialABIHandling::ConsiderTrivialABI)
16140 : ClassDecl->hasTrivialMoveConstructorForCall()));
16141
16142 // Note that we have declared this constructor.
16143 ++getASTContext().NumImplicitMoveConstructorsDeclared;
16144
16145 Scope *S = getScopeForContext(Ctx: ClassDecl);
16146 CheckImplicitSpecialMemberDeclaration(S, FD: MoveConstructor);
16147
16148 if (ShouldDeleteSpecialMember(MD: MoveConstructor,
16149 CSM: CXXSpecialMemberKind::MoveConstructor)) {
16150 ClassDecl->setImplicitMoveConstructorIsDeleted();
16151 SetDeclDeleted(dcl: MoveConstructor, DelLoc: ClassLoc);
16152 }
16153
16154 if (S)
16155 PushOnScopeChains(D: MoveConstructor, S, AddToContext: false);
16156 ClassDecl->addDecl(D: MoveConstructor);
16157
16158 return MoveConstructor;
16159}
16160
16161void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
16162 CXXConstructorDecl *MoveConstructor) {
16163 assert((MoveConstructor->isDefaulted() &&
16164 MoveConstructor->isMoveConstructor() &&
16165 !MoveConstructor->doesThisDeclarationHaveABody() &&
16166 !MoveConstructor->isDeleted()) &&
16167 "DefineImplicitMoveConstructor - call it for implicit move ctor");
16168 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
16169 return;
16170
16171 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
16172 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
16173
16174 SynthesizedFunctionScope Scope(*this, MoveConstructor);
16175
16176 // The exception specification is needed because we are defining the
16177 // function.
16178 ResolveExceptionSpec(Loc: CurrentLocation,
16179 FPT: MoveConstructor->getType()->castAs<FunctionProtoType>());
16180 MarkVTableUsed(Loc: CurrentLocation, Class: ClassDecl);
16181
16182 // Add a context note for diagnostics produced after this point.
16183 Scope.addContextNote(UseLoc: CurrentLocation);
16184
16185 if (SetCtorInitializers(Constructor: MoveConstructor, /*AnyErrors=*/false)) {
16186 MoveConstructor->setInvalidDecl();
16187 } else {
16188 SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
16189 ? MoveConstructor->getEndLoc()
16190 : MoveConstructor->getLocation();
16191 Sema::CompoundScopeRAII CompoundScope(*this);
16192 MoveConstructor->setBody(
16193 ActOnCompoundStmt(L: Loc, R: Loc, Elts: {}, /*isStmtExpr=*/false).getAs<Stmt>());
16194 MoveConstructor->markUsed(C&: Context);
16195 }
16196
16197 if (ASTMutationListener *L = getASTMutationListener()) {
16198 L->CompletedImplicitDefinition(D: MoveConstructor);
16199 }
16200}
16201
16202bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
16203 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(Val: FD);
16204}
16205
16206void Sema::DefineImplicitLambdaToFunctionPointerConversion(
16207 SourceLocation CurrentLocation,
16208 CXXConversionDecl *Conv) {
16209 SynthesizedFunctionScope Scope(*this, Conv);
16210 assert(!Conv->getReturnType()->isUndeducedType());
16211
16212 QualType ConvRT = Conv->getType()->castAs<FunctionType>()->getReturnType();
16213 CallingConv CC =
16214 ConvRT->getPointeeType()->castAs<FunctionType>()->getCallConv();
16215
16216 CXXRecordDecl *Lambda = Conv->getParent();
16217 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
16218 FunctionDecl *Invoker =
16219 CallOp->hasCXXExplicitFunctionObjectParameter() || CallOp->isStatic()
16220 ? CallOp
16221 : Lambda->getLambdaStaticInvoker(CC);
16222
16223 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
16224 CallOp = InstantiateFunctionDeclaration(
16225 FTD: CallOp->getDescribedFunctionTemplate(), Args: TemplateArgs, Loc: CurrentLocation);
16226 if (!CallOp)
16227 return;
16228
16229 if (CallOp != Invoker) {
16230 Invoker = InstantiateFunctionDeclaration(
16231 FTD: Invoker->getDescribedFunctionTemplate(), Args: TemplateArgs,
16232 Loc: CurrentLocation);
16233 if (!Invoker)
16234 return;
16235 }
16236 }
16237
16238 if (CallOp->isInvalidDecl())
16239 return;
16240
16241 // Mark the call operator referenced (and add to pending instantiations
16242 // if necessary).
16243 // For both the conversion and static-invoker template specializations
16244 // we construct their body's in this function, so no need to add them
16245 // to the PendingInstantiations.
16246 MarkFunctionReferenced(Loc: CurrentLocation, Func: CallOp);
16247
16248 if (Invoker != CallOp) {
16249 // Fill in the __invoke function with a dummy implementation. IR generation
16250 // will fill in the actual details. Update its type in case it contained
16251 // an 'auto'.
16252 Invoker->markUsed(C&: Context);
16253 Invoker->setReferenced();
16254 Invoker->setType(Conv->getReturnType()->getPointeeType());
16255 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
16256 }
16257
16258 // Construct the body of the conversion function { return __invoke; }.
16259 Expr *FunctionRef = BuildDeclRefExpr(D: Invoker, Ty: Invoker->getType(), VK: VK_LValue,
16260 Loc: Conv->getLocation());
16261 assert(FunctionRef && "Can't refer to __invoke function?");
16262 Stmt *Return = BuildReturnStmt(ReturnLoc: Conv->getLocation(), RetValExp: FunctionRef).get();
16263 Conv->setBody(CompoundStmt::Create(C: Context, Stmts: Return, FPFeatures: FPOptionsOverride(),
16264 LB: Conv->getLocation(), RB: Conv->getLocation()));
16265 Conv->markUsed(C&: Context);
16266 Conv->setReferenced();
16267
16268 if (ASTMutationListener *L = getASTMutationListener()) {
16269 L->CompletedImplicitDefinition(D: Conv);
16270 if (Invoker != CallOp)
16271 L->CompletedImplicitDefinition(D: Invoker);
16272 }
16273}
16274
16275void Sema::DefineImplicitLambdaToBlockPointerConversion(
16276 SourceLocation CurrentLocation, CXXConversionDecl *Conv) {
16277 assert(!Conv->getParent()->isGenericLambda());
16278
16279 SynthesizedFunctionScope Scope(*this, Conv);
16280
16281 // Copy-initialize the lambda object as needed to capture it.
16282 Expr *This = ActOnCXXThis(Loc: CurrentLocation).get();
16283 Expr *DerefThis =CreateBuiltinUnaryOp(OpLoc: CurrentLocation, Opc: UO_Deref, InputExpr: This).get();
16284
16285 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
16286 ConvLocation: Conv->getLocation(),
16287 Conv, Src: DerefThis);
16288
16289 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
16290 // behavior. Note that only the general conversion function does this
16291 // (since it's unusable otherwise); in the case where we inline the
16292 // block literal, it has block literal lifetime semantics.
16293 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
16294 BuildBlock = ImplicitCastExpr::Create(
16295 Context, T: BuildBlock.get()->getType(), Kind: CK_CopyAndAutoreleaseBlockObject,
16296 Operand: BuildBlock.get(), BasePath: nullptr, Cat: VK_PRValue, FPO: FPOptionsOverride());
16297
16298 if (BuildBlock.isInvalid()) {
16299 Diag(Loc: CurrentLocation, DiagID: diag::note_lambda_to_block_conv);
16300 Conv->setInvalidDecl();
16301 return;
16302 }
16303
16304 // Create the return statement that returns the block from the conversion
16305 // function.
16306 StmtResult Return = BuildReturnStmt(ReturnLoc: Conv->getLocation(), RetValExp: BuildBlock.get());
16307 if (Return.isInvalid()) {
16308 Diag(Loc: CurrentLocation, DiagID: diag::note_lambda_to_block_conv);
16309 Conv->setInvalidDecl();
16310 return;
16311 }
16312
16313 // Set the body of the conversion function.
16314 Stmt *ReturnS = Return.get();
16315 Conv->setBody(CompoundStmt::Create(C: Context, Stmts: ReturnS, FPFeatures: FPOptionsOverride(),
16316 LB: Conv->getLocation(), RB: Conv->getLocation()));
16317 Conv->markUsed(C&: Context);
16318
16319 // We're done; notify the mutation listener, if any.
16320 if (ASTMutationListener *L = getASTMutationListener()) {
16321 L->CompletedImplicitDefinition(D: Conv);
16322 }
16323}
16324
16325/// Determine whether the given list arguments contains exactly one
16326/// "real" (non-default) argument.
16327static bool hasOneRealArgument(MultiExprArg Args) {
16328 switch (Args.size()) {
16329 case 0:
16330 return false;
16331
16332 default:
16333 if (!Args[1]->isDefaultArgument())
16334 return false;
16335
16336 [[fallthrough]];
16337 case 1:
16338 return !Args[0]->isDefaultArgument();
16339 }
16340
16341 return false;
16342}
16343
16344ExprResult Sema::BuildCXXConstructExpr(
16345 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
16346 CXXConstructorDecl *Constructor, MultiExprArg ExprArgs,
16347 bool HadMultipleCandidates, bool IsListInitialization,
16348 bool IsStdInitListInitialization, bool RequiresZeroInit,
16349 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16350 bool Elidable = false;
16351
16352 // C++0x [class.copy]p34:
16353 // When certain criteria are met, an implementation is allowed to
16354 // omit the copy/move construction of a class object, even if the
16355 // copy/move constructor and/or destructor for the object have
16356 // side effects. [...]
16357 // - when a temporary class object that has not been bound to a
16358 // reference (12.2) would be copied/moved to a class object
16359 // with the same cv-unqualified type, the copy/move operation
16360 // can be omitted by constructing the temporary object
16361 // directly into the target of the omitted copy/move
16362 if (ConstructKind == CXXConstructionKind::Complete && Constructor &&
16363 // FIXME: Converting constructors should also be accepted.
16364 // But to fix this, the logic that digs down into a CXXConstructExpr
16365 // to find the source object needs to handle it.
16366 // Right now it assumes the source object is passed directly as the
16367 // first argument.
16368 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(Args: ExprArgs)) {
16369 Expr *SubExpr = ExprArgs[0];
16370 // FIXME: Per above, this is also incorrect if we want to accept
16371 // converting constructors, as isTemporaryObject will
16372 // reject temporaries with different type from the
16373 // CXXRecord itself.
16374 Elidable = SubExpr->isTemporaryObject(
16375 Ctx&: Context, TempTy: cast<CXXRecordDecl>(Val: FoundDecl->getDeclContext()));
16376 }
16377
16378 return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
16379 FoundDecl, Constructor,
16380 Elidable, Exprs: ExprArgs, HadMultipleCandidates,
16381 IsListInitialization,
16382 IsStdInitListInitialization, RequiresZeroInit,
16383 ConstructKind, ParenRange);
16384}
16385
16386ExprResult Sema::BuildCXXConstructExpr(
16387 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
16388 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg ExprArgs,
16389 bool HadMultipleCandidates, bool IsListInitialization,
16390 bool IsStdInitListInitialization, bool RequiresZeroInit,
16391 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16392 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(Val: FoundDecl)) {
16393 Constructor = findInheritingConstructor(Loc: ConstructLoc, BaseCtor: Constructor, Shadow);
16394 // The only way to get here is if we did overload resolution to find the
16395 // shadow decl, so we don't need to worry about re-checking the trailing
16396 // requires clause.
16397 if (DiagnoseUseOfOverloadedDecl(D: Constructor, Loc: ConstructLoc))
16398 return ExprError();
16399 }
16400
16401 return BuildCXXConstructExpr(
16402 ConstructLoc, DeclInitType, Constructor, Elidable, Exprs: ExprArgs,
16403 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
16404 RequiresZeroInit, ConstructKind, ParenRange);
16405}
16406
16407/// BuildCXXConstructExpr - Creates a complete call to a constructor,
16408/// including handling of its default argument expressions.
16409ExprResult Sema::BuildCXXConstructExpr(
16410 SourceLocation ConstructLoc, QualType DeclInitType,
16411 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg ExprArgs,
16412 bool HadMultipleCandidates, bool IsListInitialization,
16413 bool IsStdInitListInitialization, bool RequiresZeroInit,
16414 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16415 assert(declaresSameEntity(
16416 Constructor->getParent(),
16417 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
16418 "given constructor for wrong type");
16419 MarkFunctionReferenced(Loc: ConstructLoc, Func: Constructor);
16420 if (getLangOpts().CUDA && !CUDA().CheckCall(Loc: ConstructLoc, Callee: Constructor))
16421 return ExprError();
16422
16423 return CheckForImmediateInvocation(
16424 E: CXXConstructExpr::Create(
16425 Ctx: Context, Ty: DeclInitType, Loc: ConstructLoc, Ctor: Constructor, Elidable, Args: ExprArgs,
16426 HadMultipleCandidates, ListInitialization: IsListInitialization,
16427 StdInitListInitialization: IsStdInitListInitialization, ZeroInitialization: RequiresZeroInit,
16428 ConstructKind: static_cast<CXXConstructionKind>(ConstructKind), ParenOrBraceRange: ParenRange),
16429 Decl: Constructor);
16430}
16431
16432void Sema::FinalizeVarWithDestructor(VarDecl *VD, CXXRecordDecl *ClassDecl) {
16433 if (VD->isInvalidDecl()) return;
16434 // If initializing the variable failed, don't also diagnose problems with
16435 // the destructor, they're likely related.
16436 if (VD->getInit() && VD->getInit()->containsErrors())
16437 return;
16438
16439 ClassDecl = ClassDecl->getDefinitionOrSelf();
16440 if (ClassDecl->isInvalidDecl()) return;
16441 if (ClassDecl->hasIrrelevantDestructor()) return;
16442 if (ClassDecl->isDependentContext()) return;
16443
16444 if (VD->isNoDestroy(getASTContext()))
16445 return;
16446
16447 CXXDestructorDecl *Destructor = LookupDestructor(Class: ClassDecl);
16448 // The result of `LookupDestructor` might be nullptr if the destructor is
16449 // invalid, in which case it is marked as `IneligibleOrNotSelected` and
16450 // will not be selected by `CXXRecordDecl::getDestructor()`.
16451 if (!Destructor)
16452 return;
16453 // If this is an array, we'll require the destructor during initialization, so
16454 // we can skip over this. We still want to emit exit-time destructor warnings
16455 // though.
16456 if (!VD->getType()->isArrayType()) {
16457 MarkFunctionReferenced(Loc: VD->getLocation(), Func: Destructor);
16458 CheckDestructorAccess(Loc: VD->getLocation(), Dtor: Destructor,
16459 PDiag: PDiag(DiagID: diag::err_access_dtor_var)
16460 << VD->getDeclName() << VD->getType());
16461 DiagnoseUseOfDecl(D: Destructor, Locs: VD->getLocation());
16462 }
16463
16464 if (Destructor->isTrivial()) return;
16465
16466 // If the destructor is constexpr, check whether the variable has constant
16467 // destruction now.
16468 if (Destructor->isConstexpr()) {
16469 bool HasConstantInit = false;
16470 if (VD->getInit() && !VD->getInit()->isValueDependent())
16471 HasConstantInit = VD->evaluateValue();
16472 SmallVector<PartialDiagnosticAt, 8> Notes;
16473 if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() &&
16474 HasConstantInit) {
16475 Diag(Loc: VD->getLocation(),
16476 DiagID: diag::err_constexpr_var_requires_const_destruction) << VD;
16477 for (const PartialDiagnosticAt &Note : Notes)
16478 Diag(Loc: Note.first, PD: Note.second);
16479 }
16480 }
16481
16482 if (!VD->hasGlobalStorage() || !VD->needsDestruction(Ctx: Context))
16483 return;
16484
16485 // Emit warning for non-trivial dtor in global scope (a real global,
16486 // class-static, function-static).
16487 if (!VD->hasAttr<AlwaysDestroyAttr>())
16488 Diag(Loc: VD->getLocation(), DiagID: diag::warn_exit_time_destructor);
16489
16490 // TODO: this should be re-enabled for static locals by !CXAAtExit
16491 if (!VD->isStaticLocal())
16492 Diag(Loc: VD->getLocation(), DiagID: diag::warn_global_destructor);
16493}
16494
16495bool Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
16496 QualType DeclInitType, MultiExprArg ArgsPtr,
16497 SourceLocation Loc,
16498 SmallVectorImpl<Expr *> &ConvertedArgs,
16499 bool AllowExplicit,
16500 bool IsListInitialization) {
16501 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
16502 unsigned NumArgs = ArgsPtr.size();
16503 Expr **Args = ArgsPtr.data();
16504
16505 const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>();
16506 unsigned NumParams = Proto->getNumParams();
16507
16508 // If too few arguments are available, we'll fill in the rest with defaults.
16509 if (NumArgs < NumParams)
16510 ConvertedArgs.reserve(N: NumParams);
16511 else
16512 ConvertedArgs.reserve(N: NumArgs);
16513
16514 VariadicCallType CallType = Proto->isVariadic()
16515 ? VariadicCallType::Constructor
16516 : VariadicCallType::DoesNotApply;
16517 SmallVector<Expr *, 8> AllArgs;
16518 bool Invalid = GatherArgumentsForCall(
16519 CallLoc: Loc, FDecl: Constructor, Proto, FirstParam: 0, Args: llvm::ArrayRef(Args, NumArgs), AllArgs,
16520 CallType, AllowExplicit, IsListInitialization);
16521 ConvertedArgs.append(in_start: AllArgs.begin(), in_end: AllArgs.end());
16522
16523 DiagnoseSentinelCalls(D: Constructor, Loc, Args: AllArgs);
16524
16525 CheckConstructorCall(FDecl: Constructor, ThisType: DeclInitType, Args: llvm::ArrayRef(AllArgs),
16526 Proto, Loc);
16527
16528 return Invalid;
16529}
16530
16531TypeAwareAllocationMode Sema::ShouldUseTypeAwareOperatorNewOrDelete() const {
16532 bool SeenTypedOperators = Context.hasSeenTypeAwareOperatorNewOrDelete();
16533 return typeAwareAllocationModeFromBool(IsTypeAwareAllocation: SeenTypedOperators);
16534}
16535
16536FunctionDecl *
16537Sema::BuildTypeAwareUsualDelete(FunctionTemplateDecl *FnTemplateDecl,
16538 QualType DeallocType, SourceLocation Loc) {
16539 if (DeallocType.isNull())
16540 return nullptr;
16541
16542 FunctionDecl *FnDecl = FnTemplateDecl->getTemplatedDecl();
16543 if (!FnDecl->isTypeAwareOperatorNewOrDelete())
16544 return nullptr;
16545
16546 if (FnDecl->isVariadic())
16547 return nullptr;
16548
16549 unsigned NumParams = FnDecl->getNumParams();
16550 constexpr unsigned RequiredParameterCount =
16551 FunctionDecl::RequiredTypeAwareDeleteParameterCount;
16552 // A usual deallocation function has no placement parameters
16553 if (NumParams != RequiredParameterCount)
16554 return nullptr;
16555
16556 // A type aware allocation is only usual if the only dependent parameter is
16557 // the first parameter.
16558 if (llvm::any_of(Range: FnDecl->parameters().drop_front(),
16559 P: [](const ParmVarDecl *ParamDecl) {
16560 return ParamDecl->getType()->isDependentType();
16561 }))
16562 return nullptr;
16563
16564 QualType SpecializedTypeIdentity = tryBuildStdTypeIdentity(Type: DeallocType, Loc);
16565 if (SpecializedTypeIdentity.isNull())
16566 return nullptr;
16567
16568 SmallVector<QualType, RequiredParameterCount> ArgTypes;
16569 ArgTypes.reserve(N: NumParams);
16570
16571 // The first parameter to a type aware operator delete is by definition the
16572 // type-identity argument, so we explicitly set this to the target
16573 // type-identity type, the remaining usual parameters should then simply match
16574 // the type declared in the function template.
16575 ArgTypes.push_back(Elt: SpecializedTypeIdentity);
16576 for (unsigned ParamIdx = 1; ParamIdx < RequiredParameterCount; ++ParamIdx)
16577 ArgTypes.push_back(Elt: FnDecl->getParamDecl(i: ParamIdx)->getType());
16578
16579 FunctionProtoType::ExtProtoInfo EPI;
16580 QualType ExpectedFunctionType =
16581 Context.getFunctionType(ResultTy: Context.VoidTy, Args: ArgTypes, EPI);
16582 sema::TemplateDeductionInfo Info(Loc);
16583 FunctionDecl *Result;
16584 if (DeduceTemplateArguments(FunctionTemplate: FnTemplateDecl, ExplicitTemplateArgs: nullptr, ArgFunctionType: ExpectedFunctionType,
16585 Specialization&: Result, Info) != TemplateDeductionResult::Success)
16586 return nullptr;
16587 return Result;
16588}
16589
16590static inline bool
16591CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
16592 const FunctionDecl *FnDecl) {
16593 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
16594 if (isa<NamespaceDecl>(Val: DC)) {
16595 return SemaRef.Diag(Loc: FnDecl->getLocation(),
16596 DiagID: diag::err_operator_new_delete_declared_in_namespace)
16597 << FnDecl->getDeclName();
16598 }
16599
16600 if (isa<TranslationUnitDecl>(Val: DC) &&
16601 FnDecl->getStorageClass() == SC_Static) {
16602 return SemaRef.Diag(Loc: FnDecl->getLocation(),
16603 DiagID: diag::err_operator_new_delete_declared_static)
16604 << FnDecl->getDeclName();
16605 }
16606
16607 return false;
16608}
16609
16610static CanQualType RemoveAddressSpaceFromPtr(Sema &SemaRef,
16611 const PointerType *PtrTy) {
16612 auto &Ctx = SemaRef.Context;
16613 Qualifiers PtrQuals = PtrTy->getPointeeType().getQualifiers();
16614 PtrQuals.removeAddressSpace();
16615 return Ctx.getPointerType(T: Ctx.getCanonicalType(T: Ctx.getQualifiedType(
16616 T: PtrTy->getPointeeType().getUnqualifiedType(), Qs: PtrQuals)));
16617}
16618
16619enum class AllocationOperatorKind { New, Delete };
16620
16621static bool IsPotentiallyTypeAwareOperatorNewOrDelete(Sema &SemaRef,
16622 const FunctionDecl *FD,
16623 bool *WasMalformed) {
16624 const Decl *MalformedDecl = nullptr;
16625 if (FD->getNumParams() > 0 &&
16626 SemaRef.isStdTypeIdentity(Ty: FD->getParamDecl(i: 0)->getType(),
16627 /*TypeArgument=*/Element: nullptr, MalformedDecl: &MalformedDecl))
16628 return true;
16629
16630 if (!MalformedDecl)
16631 return false;
16632
16633 if (WasMalformed)
16634 *WasMalformed = true;
16635
16636 return true;
16637}
16638
16639static bool isDestroyingDeleteT(QualType Type) {
16640 auto *RD = Type->getAsCXXRecordDecl();
16641 return RD && RD->isInStdNamespace() && RD->getIdentifier() &&
16642 RD->getIdentifier()->isStr(Str: "destroying_delete_t");
16643}
16644
16645static bool IsPotentiallyDestroyingOperatorDelete(Sema &SemaRef,
16646 const FunctionDecl *FD) {
16647 // C++ P0722:
16648 // Within a class C, a single object deallocation function with signature
16649 // (T, std::destroying_delete_t, <more params>)
16650 // is a destroying operator delete.
16651 bool IsPotentiallyTypeAware = IsPotentiallyTypeAwareOperatorNewOrDelete(
16652 SemaRef, FD, /*WasMalformed=*/nullptr);
16653 unsigned DestroyingDeleteIdx = IsPotentiallyTypeAware + /* address */ 1;
16654 return isa<CXXMethodDecl>(Val: FD) && FD->getOverloadedOperator() == OO_Delete &&
16655 FD->getNumParams() > DestroyingDeleteIdx &&
16656 isDestroyingDeleteT(Type: FD->getParamDecl(i: DestroyingDeleteIdx)->getType());
16657}
16658
16659static inline bool CheckOperatorNewDeleteTypes(
16660 Sema &SemaRef, FunctionDecl *FnDecl, AllocationOperatorKind OperatorKind,
16661 CanQualType ExpectedResultType, CanQualType ExpectedSizeOrAddressParamType,
16662 unsigned DependentParamTypeDiag, unsigned InvalidParamTypeDiag) {
16663 auto NormalizeType = [&SemaRef](QualType T) {
16664 if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
16665 // The operator is valid on any address space for OpenCL.
16666 // Drop address space from actual and expected result types.
16667 if (const auto PtrTy = T->template getAs<PointerType>())
16668 T = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
16669 }
16670 return SemaRef.Context.getCanonicalType(T);
16671 };
16672
16673 const unsigned NumParams = FnDecl->getNumParams();
16674 unsigned FirstNonTypeParam = 0;
16675 bool MalformedTypeIdentity = false;
16676 bool IsPotentiallyTypeAware = IsPotentiallyTypeAwareOperatorNewOrDelete(
16677 SemaRef, FD: FnDecl, WasMalformed: &MalformedTypeIdentity);
16678 unsigned MinimumMandatoryArgumentCount = 1;
16679 unsigned SizeParameterIndex = 0;
16680 if (IsPotentiallyTypeAware) {
16681 // We don't emit this diagnosis for template instantiations as we will
16682 // have already emitted it for the original template declaration.
16683 if (!FnDecl->isTemplateInstantiation())
16684 SemaRef.Diag(Loc: FnDecl->getLocation(), DiagID: diag::warn_ext_type_aware_allocators);
16685
16686 if (OperatorKind == AllocationOperatorKind::New) {
16687 SizeParameterIndex = 1;
16688 MinimumMandatoryArgumentCount =
16689 FunctionDecl::RequiredTypeAwareNewParameterCount;
16690 } else {
16691 SizeParameterIndex = 2;
16692 MinimumMandatoryArgumentCount =
16693 FunctionDecl::RequiredTypeAwareDeleteParameterCount;
16694 }
16695 FirstNonTypeParam = 1;
16696 }
16697
16698 bool IsPotentiallyDestroyingDelete =
16699 IsPotentiallyDestroyingOperatorDelete(SemaRef, FD: FnDecl);
16700
16701 if (IsPotentiallyDestroyingDelete) {
16702 ++MinimumMandatoryArgumentCount;
16703 ++SizeParameterIndex;
16704 }
16705
16706 if (NumParams < MinimumMandatoryArgumentCount)
16707 return SemaRef.Diag(Loc: FnDecl->getLocation(),
16708 DiagID: diag::err_operator_new_delete_too_few_parameters)
16709 << IsPotentiallyTypeAware << IsPotentiallyDestroyingDelete
16710 << FnDecl->getDeclName() << MinimumMandatoryArgumentCount;
16711
16712 for (unsigned Idx = 0; Idx < MinimumMandatoryArgumentCount; ++Idx) {
16713 const ParmVarDecl *ParamDecl = FnDecl->getParamDecl(i: Idx);
16714 if (ParamDecl->hasDefaultArg())
16715 return SemaRef.Diag(Loc: FnDecl->getLocation(),
16716 DiagID: diag::err_operator_new_default_arg)
16717 << FnDecl->getDeclName() << Idx << ParamDecl->getDefaultArgRange();
16718 }
16719
16720 auto *FnType = FnDecl->getType()->castAs<FunctionType>();
16721 QualType CanResultType = NormalizeType(FnType->getReturnType());
16722 QualType CanExpectedResultType = NormalizeType(ExpectedResultType);
16723 QualType CanExpectedSizeOrAddressParamType =
16724 NormalizeType(ExpectedSizeOrAddressParamType);
16725
16726 // Check that the result type is what we expect.
16727 if (CanResultType != CanExpectedResultType) {
16728 // Reject even if the type is dependent; an operator delete function is
16729 // required to have a non-dependent result type.
16730 return SemaRef.Diag(
16731 Loc: FnDecl->getLocation(),
16732 DiagID: CanResultType->isDependentType()
16733 ? diag::err_operator_new_delete_dependent_result_type
16734 : diag::err_operator_new_delete_invalid_result_type)
16735 << FnDecl->getDeclName() << ExpectedResultType;
16736 }
16737
16738 // A function template must have at least 2 parameters.
16739 if (FnDecl->getDescribedFunctionTemplate() && NumParams < 2)
16740 return SemaRef.Diag(Loc: FnDecl->getLocation(),
16741 DiagID: diag::err_operator_new_delete_template_too_few_parameters)
16742 << FnDecl->getDeclName();
16743
16744 auto CheckType = [&](unsigned ParamIdx, QualType ExpectedType,
16745 auto FallbackType) -> bool {
16746 const ParmVarDecl *ParamDecl = FnDecl->getParamDecl(i: ParamIdx);
16747 if (ExpectedType.isNull()) {
16748 return SemaRef.Diag(Loc: FnDecl->getLocation(), DiagID: InvalidParamTypeDiag)
16749 << IsPotentiallyTypeAware << IsPotentiallyDestroyingDelete
16750 << FnDecl->getDeclName() << (1 + ParamIdx) << FallbackType
16751 << ParamDecl->getSourceRange();
16752 }
16753 CanQualType CanExpectedTy =
16754 NormalizeType(SemaRef.Context.getCanonicalType(T: ExpectedType));
16755 auto ActualParamType =
16756 NormalizeType(ParamDecl->getType().getUnqualifiedType());
16757 if (ActualParamType == CanExpectedTy)
16758 return false;
16759 unsigned Diagnostic = ActualParamType->isDependentType()
16760 ? DependentParamTypeDiag
16761 : InvalidParamTypeDiag;
16762 return SemaRef.Diag(Loc: FnDecl->getLocation(), DiagID: Diagnostic)
16763 << IsPotentiallyTypeAware << IsPotentiallyDestroyingDelete
16764 << FnDecl->getDeclName() << (1 + ParamIdx) << ExpectedType
16765 << FallbackType << ParamDecl->getSourceRange();
16766 };
16767
16768 // Check that the first parameter type is what we expect.
16769 if (CheckType(FirstNonTypeParam, CanExpectedSizeOrAddressParamType, "size_t"))
16770 return true;
16771
16772 FnDecl->setIsDestroyingOperatorDelete(IsPotentiallyDestroyingDelete);
16773
16774 // If the first parameter type is not a type-identity we're done, otherwise
16775 // we need to ensure the size and alignment parameters have the correct type
16776 if (!IsPotentiallyTypeAware)
16777 return false;
16778
16779 if (CheckType(SizeParameterIndex, SemaRef.Context.getSizeType(), "size_t"))
16780 return true;
16781 TagDecl *StdAlignValTDecl = SemaRef.getStdAlignValT();
16782 CanQualType StdAlignValT =
16783 StdAlignValTDecl ? SemaRef.Context.getCanonicalTagType(TD: StdAlignValTDecl)
16784 : CanQualType();
16785 if (CheckType(SizeParameterIndex + 1, StdAlignValT, "std::align_val_t"))
16786 return true;
16787
16788 FnDecl->setIsTypeAwareOperatorNewOrDelete();
16789 return MalformedTypeIdentity;
16790}
16791
16792static bool CheckOperatorNewDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
16793 // C++ [basic.stc.dynamic.allocation]p1:
16794 // A program is ill-formed if an allocation function is declared in a
16795 // namespace scope other than global scope or declared static in global
16796 // scope.
16797 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
16798 return true;
16799
16800 CanQualType SizeTy =
16801 SemaRef.Context.getCanonicalType(T: SemaRef.Context.getSizeType());
16802
16803 // C++ [basic.stc.dynamic.allocation]p1:
16804 // The return type shall be void*. The first parameter shall have type
16805 // std::size_t.
16806 return CheckOperatorNewDeleteTypes(
16807 SemaRef, FnDecl, OperatorKind: AllocationOperatorKind::New, ExpectedResultType: SemaRef.Context.VoidPtrTy,
16808 ExpectedSizeOrAddressParamType: SizeTy, DependentParamTypeDiag: diag::err_operator_new_dependent_param_type,
16809 InvalidParamTypeDiag: diag::err_operator_new_param_type);
16810}
16811
16812static bool
16813CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
16814 // C++ [basic.stc.dynamic.deallocation]p1:
16815 // A program is ill-formed if deallocation functions are declared in a
16816 // namespace scope other than global scope or declared static in global
16817 // scope.
16818 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
16819 return true;
16820
16821 auto *MD = dyn_cast<CXXMethodDecl>(Val: FnDecl);
16822 auto ConstructDestroyingDeleteAddressType = [&]() {
16823 assert(MD);
16824 return SemaRef.Context.getPointerType(
16825 T: SemaRef.Context.getCanonicalTagType(TD: MD->getParent()));
16826 };
16827
16828 // C++ P2719: A destroying operator delete cannot be type aware
16829 // so for QoL we actually check for this explicitly by considering
16830 // an destroying-delete appropriate address type and the presence of
16831 // any parameter of type destroying_delete_t as an erroneous attempt
16832 // to declare a type aware destroying delete, rather than emitting a
16833 // pile of incorrect parameter type errors.
16834 if (MD && IsPotentiallyTypeAwareOperatorNewOrDelete(
16835 SemaRef, FD: MD, /*WasMalformed=*/nullptr)) {
16836 QualType AddressParamType =
16837 SemaRef.Context.getCanonicalType(T: MD->getParamDecl(i: 1)->getType());
16838 if (AddressParamType != SemaRef.Context.VoidPtrTy &&
16839 AddressParamType == ConstructDestroyingDeleteAddressType()) {
16840 // The address parameter type implies an author trying to construct a
16841 // type aware destroying delete, so we'll see if we can find a parameter
16842 // of type `std::destroying_delete_t`, and if we find it we'll report
16843 // this as being an attempt at a type aware destroying delete just stop
16844 // here. If we don't do this, the resulting incorrect parameter ordering
16845 // results in a pile mismatched argument type errors that don't explain
16846 // the core problem.
16847 for (auto Param : MD->parameters()) {
16848 if (isDestroyingDeleteT(Type: Param->getType())) {
16849 SemaRef.Diag(Loc: MD->getLocation(),
16850 DiagID: diag::err_type_aware_destroying_operator_delete)
16851 << Param->getSourceRange();
16852 return true;
16853 }
16854 }
16855 }
16856 }
16857
16858 // C++ P0722:
16859 // Within a class C, the first parameter of a destroying operator delete
16860 // shall be of type C *. The first parameter of any other deallocation
16861 // function shall be of type void *.
16862 CanQualType ExpectedAddressParamType =
16863 MD && IsPotentiallyDestroyingOperatorDelete(SemaRef, FD: MD)
16864 ? SemaRef.Context.getPointerType(
16865 T: SemaRef.Context.getCanonicalTagType(TD: MD->getParent()))
16866 : SemaRef.Context.VoidPtrTy;
16867
16868 // C++ [basic.stc.dynamic.deallocation]p2:
16869 // Each deallocation function shall return void
16870 if (CheckOperatorNewDeleteTypes(
16871 SemaRef, FnDecl, OperatorKind: AllocationOperatorKind::Delete,
16872 ExpectedResultType: SemaRef.Context.VoidTy, ExpectedSizeOrAddressParamType: ExpectedAddressParamType,
16873 DependentParamTypeDiag: diag::err_operator_delete_dependent_param_type,
16874 InvalidParamTypeDiag: diag::err_operator_delete_param_type))
16875 return true;
16876
16877 // C++ P0722:
16878 // A destroying operator delete shall be a usual deallocation function.
16879 if (MD && !MD->getParent()->isDependentContext() &&
16880 MD->isDestroyingOperatorDelete()) {
16881 if (!SemaRef.isUsualDeallocationFunction(FD: MD)) {
16882 SemaRef.Diag(Loc: MD->getLocation(),
16883 DiagID: diag::err_destroying_operator_delete_not_usual);
16884 return true;
16885 }
16886 }
16887
16888 return false;
16889}
16890
16891bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
16892 assert(FnDecl && FnDecl->isOverloadedOperator() &&
16893 "Expected an overloaded operator declaration");
16894
16895 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
16896
16897 // C++ [over.oper]p5:
16898 // The allocation and deallocation functions, operator new,
16899 // operator new[], operator delete and operator delete[], are
16900 // described completely in 3.7.3. The attributes and restrictions
16901 // found in the rest of this subclause do not apply to them unless
16902 // explicitly stated in 3.7.3.
16903 if (Op == OO_Delete || Op == OO_Array_Delete)
16904 return CheckOperatorDeleteDeclaration(SemaRef&: *this, FnDecl);
16905
16906 if (Op == OO_New || Op == OO_Array_New)
16907 return CheckOperatorNewDeclaration(SemaRef&: *this, FnDecl);
16908
16909 // C++ [over.oper]p7:
16910 // An operator function shall either be a member function or
16911 // be a non-member function and have at least one parameter
16912 // whose type is a class, a reference to a class, an enumeration,
16913 // or a reference to an enumeration.
16914 // Note: Before C++23, a member function could not be static. The only member
16915 // function allowed to be static is the call operator function.
16916 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Val: FnDecl)) {
16917 if (MethodDecl->isStatic()) {
16918 if (Op == OO_Call || Op == OO_Subscript)
16919 Diag(Loc: FnDecl->getLocation(),
16920 DiagID: (LangOpts.CPlusPlus23
16921 ? diag::warn_cxx20_compat_operator_overload_static
16922 : diag::ext_operator_overload_static))
16923 << FnDecl;
16924 else
16925 return Diag(Loc: FnDecl->getLocation(), DiagID: diag::err_operator_overload_static)
16926 << FnDecl;
16927 }
16928 } else {
16929 bool ClassOrEnumParam = false;
16930 for (auto *Param : FnDecl->parameters()) {
16931 QualType ParamType = Param->getType().getNonReferenceType();
16932 if (ParamType->isDependentType() || ParamType->isRecordType() ||
16933 ParamType->isEnumeralType()) {
16934 ClassOrEnumParam = true;
16935 break;
16936 }
16937 }
16938
16939 if (!ClassOrEnumParam)
16940 return Diag(Loc: FnDecl->getLocation(),
16941 DiagID: diag::err_operator_overload_needs_class_or_enum)
16942 << FnDecl->getDeclName();
16943 }
16944
16945 // C++ [over.oper]p8:
16946 // An operator function cannot have default arguments (8.3.6),
16947 // except where explicitly stated below.
16948 //
16949 // Only the function-call operator (C++ [over.call]p1) and the subscript
16950 // operator (CWG2507) allow default arguments.
16951 if (Op != OO_Call) {
16952 ParmVarDecl *FirstDefaultedParam = nullptr;
16953 for (auto *Param : FnDecl->parameters()) {
16954 if (Param->hasDefaultArg()) {
16955 FirstDefaultedParam = Param;
16956 break;
16957 }
16958 }
16959 if (FirstDefaultedParam) {
16960 if (Op == OO_Subscript) {
16961 Diag(Loc: FnDecl->getLocation(), DiagID: LangOpts.CPlusPlus23
16962 ? diag::ext_subscript_overload
16963 : diag::error_subscript_overload)
16964 << FnDecl->getDeclName() << 1
16965 << FirstDefaultedParam->getDefaultArgRange();
16966 } else {
16967 return Diag(Loc: FirstDefaultedParam->getLocation(),
16968 DiagID: diag::err_operator_overload_default_arg)
16969 << FnDecl->getDeclName()
16970 << FirstDefaultedParam->getDefaultArgRange();
16971 }
16972 }
16973 }
16974
16975 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
16976 { false, false, false }
16977#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
16978 , { Unary, Binary, MemberOnly }
16979#include "clang/Basic/OperatorKinds.def"
16980 };
16981
16982 bool CanBeUnaryOperator = OperatorUses[Op][0];
16983 bool CanBeBinaryOperator = OperatorUses[Op][1];
16984 bool MustBeMemberOperator = OperatorUses[Op][2];
16985
16986 // C++ [over.oper]p8:
16987 // [...] Operator functions cannot have more or fewer parameters
16988 // than the number required for the corresponding operator, as
16989 // described in the rest of this subclause.
16990 unsigned NumParams = FnDecl->getNumParams() +
16991 (isa<CXXMethodDecl>(Val: FnDecl) &&
16992 !FnDecl->hasCXXExplicitFunctionObjectParameter()
16993 ? 1
16994 : 0);
16995 if (Op != OO_Call && Op != OO_Subscript &&
16996 ((NumParams == 1 && !CanBeUnaryOperator) ||
16997 (NumParams == 2 && !CanBeBinaryOperator) || (NumParams < 1) ||
16998 (NumParams > 2))) {
16999 // We have the wrong number of parameters.
17000 unsigned ErrorKind;
17001 if (CanBeUnaryOperator && CanBeBinaryOperator) {
17002 ErrorKind = 2; // 2 -> unary or binary.
17003 } else if (CanBeUnaryOperator) {
17004 ErrorKind = 0; // 0 -> unary
17005 } else {
17006 assert(CanBeBinaryOperator &&
17007 "All non-call overloaded operators are unary or binary!");
17008 ErrorKind = 1; // 1 -> binary
17009 }
17010 return Diag(Loc: FnDecl->getLocation(), DiagID: diag::err_operator_overload_must_be)
17011 << FnDecl->getDeclName() << NumParams << ErrorKind;
17012 }
17013
17014 if (Op == OO_Subscript && NumParams != 2) {
17015 Diag(Loc: FnDecl->getLocation(), DiagID: LangOpts.CPlusPlus23
17016 ? diag::ext_subscript_overload
17017 : diag::error_subscript_overload)
17018 << FnDecl->getDeclName() << (NumParams == 1 ? 0 : 2);
17019 }
17020
17021 // Overloaded operators other than operator() and operator[] cannot be
17022 // variadic.
17023 if (Op != OO_Call &&
17024 FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) {
17025 return Diag(Loc: FnDecl->getLocation(), DiagID: diag::err_operator_overload_variadic)
17026 << FnDecl->getDeclName();
17027 }
17028
17029 // Some operators must be member functions.
17030 if (MustBeMemberOperator && !isa<CXXMethodDecl>(Val: FnDecl)) {
17031 return Diag(Loc: FnDecl->getLocation(),
17032 DiagID: diag::err_operator_overload_must_be_member)
17033 << FnDecl->getDeclName();
17034 }
17035
17036 // C++ [over.inc]p1:
17037 // The user-defined function called operator++ implements the
17038 // prefix and postfix ++ operator. If this function is a member
17039 // function with no parameters, or a non-member function with one
17040 // parameter of class or enumeration type, it defines the prefix
17041 // increment operator ++ for objects of that type. If the function
17042 // is a member function with one parameter (which shall be of type
17043 // int) or a non-member function with two parameters (the second
17044 // of which shall be of type int), it defines the postfix
17045 // increment operator ++ for objects of that type.
17046 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
17047 ParmVarDecl *LastParam = FnDecl->getParamDecl(i: FnDecl->getNumParams() - 1);
17048 QualType ParamType = LastParam->getType();
17049
17050 if (!ParamType->isSpecificBuiltinType(K: BuiltinType::Int) &&
17051 !ParamType->isDependentType())
17052 return Diag(Loc: LastParam->getLocation(),
17053 DiagID: diag::err_operator_overload_post_incdec_must_be_int)
17054 << LastParam->getType() << (Op == OO_MinusMinus);
17055 }
17056
17057 return false;
17058}
17059
17060static bool
17061checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
17062 FunctionTemplateDecl *TpDecl) {
17063 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
17064
17065 // Must have one or two template parameters.
17066 if (TemplateParams->size() == 1) {
17067 NonTypeTemplateParmDecl *PmDecl =
17068 dyn_cast<NonTypeTemplateParmDecl>(Val: TemplateParams->getParam(Idx: 0));
17069
17070 // The template parameter must be a char parameter pack.
17071 if (PmDecl && PmDecl->isTemplateParameterPack() &&
17072 SemaRef.Context.hasSameType(T1: PmDecl->getType(), T2: SemaRef.Context.CharTy))
17073 return false;
17074
17075 // C++20 [over.literal]p5:
17076 // A string literal operator template is a literal operator template
17077 // whose template-parameter-list comprises a single non-type
17078 // template-parameter of class type.
17079 //
17080 // As a DR resolution, we also allow placeholders for deduced class
17081 // template specializations.
17082 if (SemaRef.getLangOpts().CPlusPlus20 && PmDecl &&
17083 !PmDecl->isTemplateParameterPack() &&
17084 (PmDecl->getType()->isRecordType() ||
17085 PmDecl->getType()->getAs<DeducedTemplateSpecializationType>()))
17086 return false;
17087 } else if (TemplateParams->size() == 2) {
17088 TemplateTypeParmDecl *PmType =
17089 dyn_cast<TemplateTypeParmDecl>(Val: TemplateParams->getParam(Idx: 0));
17090 NonTypeTemplateParmDecl *PmArgs =
17091 dyn_cast<NonTypeTemplateParmDecl>(Val: TemplateParams->getParam(Idx: 1));
17092
17093 // The second template parameter must be a parameter pack with the
17094 // first template parameter as its type.
17095 if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
17096 PmArgs->isTemplateParameterPack()) {
17097 if (const auto *TArgs =
17098 PmArgs->getType()->getAsCanonical<TemplateTypeParmType>();
17099 TArgs && TArgs->getDepth() == PmType->getDepth() &&
17100 TArgs->getIndex() == PmType->getIndex()) {
17101 if (!SemaRef.inTemplateInstantiation())
17102 SemaRef.Diag(Loc: TpDecl->getLocation(),
17103 DiagID: diag::ext_string_literal_operator_template);
17104 return false;
17105 }
17106 }
17107 }
17108
17109 SemaRef.Diag(Loc: TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
17110 DiagID: diag::err_literal_operator_template)
17111 << TpDecl->getTemplateParameters()->getSourceRange();
17112 return true;
17113}
17114
17115bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
17116 if (isa<CXXMethodDecl>(Val: FnDecl)) {
17117 Diag(Loc: FnDecl->getLocation(), DiagID: diag::err_literal_operator_outside_namespace)
17118 << FnDecl->getDeclName();
17119 return true;
17120 }
17121
17122 if (FnDecl->isExternC()) {
17123 Diag(Loc: FnDecl->getLocation(), DiagID: diag::err_literal_operator_extern_c);
17124 if (const LinkageSpecDecl *LSD =
17125 FnDecl->getDeclContext()->getExternCContext())
17126 Diag(Loc: LSD->getExternLoc(), DiagID: diag::note_extern_c_begins_here);
17127 return true;
17128 }
17129
17130 // This might be the definition of a literal operator template.
17131 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
17132
17133 // This might be a specialization of a literal operator template.
17134 if (!TpDecl)
17135 TpDecl = FnDecl->getPrimaryTemplate();
17136
17137 // template <char...> type operator "" name() and
17138 // template <class T, T...> type operator "" name() are the only valid
17139 // template signatures, and the only valid signatures with no parameters.
17140 //
17141 // C++20 also allows template <SomeClass T> type operator "" name().
17142 if (TpDecl) {
17143 if (FnDecl->param_size() != 0) {
17144 Diag(Loc: FnDecl->getLocation(),
17145 DiagID: diag::err_literal_operator_template_with_params);
17146 return true;
17147 }
17148
17149 if (checkLiteralOperatorTemplateParameterList(SemaRef&: *this, TpDecl))
17150 return true;
17151
17152 } else if (FnDecl->param_size() == 1) {
17153 const ParmVarDecl *Param = FnDecl->getParamDecl(i: 0);
17154
17155 QualType ParamType = Param->getType().getUnqualifiedType();
17156
17157 // Only unsigned long long int, long double, any character type, and const
17158 // char * are allowed as the only parameters.
17159 if (ParamType->isSpecificBuiltinType(K: BuiltinType::ULongLong) ||
17160 ParamType->isSpecificBuiltinType(K: BuiltinType::LongDouble) ||
17161 Context.hasSameType(T1: ParamType, T2: Context.CharTy) ||
17162 Context.hasSameType(T1: ParamType, T2: Context.WideCharTy) ||
17163 Context.hasSameType(T1: ParamType, T2: Context.Char8Ty) ||
17164 Context.hasSameType(T1: ParamType, T2: Context.Char16Ty) ||
17165 Context.hasSameType(T1: ParamType, T2: Context.Char32Ty)) {
17166 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
17167 QualType InnerType = Ptr->getPointeeType();
17168
17169 // Pointer parameter must be a const char *.
17170 if (!(Context.hasSameType(T1: InnerType.getUnqualifiedType(),
17171 T2: Context.CharTy) &&
17172 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
17173 Diag(Loc: Param->getSourceRange().getBegin(),
17174 DiagID: diag::err_literal_operator_param)
17175 << ParamType << "'const char *'" << Param->getSourceRange();
17176 return true;
17177 }
17178
17179 } else if (ParamType->isRealFloatingType()) {
17180 Diag(Loc: Param->getSourceRange().getBegin(), DiagID: diag::err_literal_operator_param)
17181 << ParamType << Context.LongDoubleTy << Param->getSourceRange();
17182 return true;
17183
17184 } else if (ParamType->isIntegerType()) {
17185 Diag(Loc: Param->getSourceRange().getBegin(), DiagID: diag::err_literal_operator_param)
17186 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
17187 return true;
17188
17189 } else {
17190 Diag(Loc: Param->getSourceRange().getBegin(),
17191 DiagID: diag::err_literal_operator_invalid_param)
17192 << ParamType << Param->getSourceRange();
17193 return true;
17194 }
17195
17196 } else if (FnDecl->param_size() == 2) {
17197 FunctionDecl::param_iterator Param = FnDecl->param_begin();
17198
17199 // First, verify that the first parameter is correct.
17200
17201 QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
17202
17203 // Two parameter function must have a pointer to const as a
17204 // first parameter; let's strip those qualifiers.
17205 const PointerType *PT = FirstParamType->getAs<PointerType>();
17206
17207 if (!PT) {
17208 Diag(Loc: (*Param)->getSourceRange().getBegin(),
17209 DiagID: diag::err_literal_operator_param)
17210 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
17211 return true;
17212 }
17213
17214 QualType PointeeType = PT->getPointeeType();
17215 // First parameter must be const
17216 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
17217 Diag(Loc: (*Param)->getSourceRange().getBegin(),
17218 DiagID: diag::err_literal_operator_param)
17219 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
17220 return true;
17221 }
17222
17223 QualType InnerType = PointeeType.getUnqualifiedType();
17224 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
17225 // const char32_t* are allowed as the first parameter to a two-parameter
17226 // function
17227 if (!(Context.hasSameType(T1: InnerType, T2: Context.CharTy) ||
17228 Context.hasSameType(T1: InnerType, T2: Context.WideCharTy) ||
17229 Context.hasSameType(T1: InnerType, T2: Context.Char8Ty) ||
17230 Context.hasSameType(T1: InnerType, T2: Context.Char16Ty) ||
17231 Context.hasSameType(T1: InnerType, T2: Context.Char32Ty))) {
17232 Diag(Loc: (*Param)->getSourceRange().getBegin(),
17233 DiagID: diag::err_literal_operator_param)
17234 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
17235 return true;
17236 }
17237
17238 // Move on to the second and final parameter.
17239 ++Param;
17240
17241 // The second parameter must be a std::size_t.
17242 QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
17243 if (!Context.hasSameType(T1: SecondParamType, T2: Context.getSizeType())) {
17244 Diag(Loc: (*Param)->getSourceRange().getBegin(),
17245 DiagID: diag::err_literal_operator_param)
17246 << SecondParamType << Context.getSizeType()
17247 << (*Param)->getSourceRange();
17248 return true;
17249 }
17250 } else {
17251 Diag(Loc: FnDecl->getLocation(), DiagID: diag::err_literal_operator_bad_param_count);
17252 return true;
17253 }
17254
17255 // Parameters are good.
17256
17257 // A parameter-declaration-clause containing a default argument is not
17258 // equivalent to any of the permitted forms.
17259 for (auto *Param : FnDecl->parameters()) {
17260 if (Param->hasDefaultArg()) {
17261 Diag(Loc: Param->getDefaultArgRange().getBegin(),
17262 DiagID: diag::err_literal_operator_default_argument)
17263 << Param->getDefaultArgRange();
17264 break;
17265 }
17266 }
17267
17268 const IdentifierInfo *II = FnDecl->getDeclName().getCXXLiteralIdentifier();
17269 ReservedLiteralSuffixIdStatus Status = II->isReservedLiteralSuffixId();
17270 if (Status != ReservedLiteralSuffixIdStatus::NotReserved &&
17271 !getSourceManager().isInSystemHeader(Loc: FnDecl->getLocation())) {
17272 // C++23 [usrlit.suffix]p1:
17273 // Literal suffix identifiers that do not start with an underscore are
17274 // reserved for future standardization. Literal suffix identifiers that
17275 // contain a double underscore __ are reserved for use by C++
17276 // implementations.
17277 Diag(Loc: FnDecl->getLocation(), DiagID: diag::warn_user_literal_reserved)
17278 << static_cast<int>(Status)
17279 << StringLiteralParser::isValidUDSuffix(LangOpts: getLangOpts(), Suffix: II->getName());
17280 }
17281
17282 return false;
17283}
17284
17285Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
17286 Expr *LangStr,
17287 SourceLocation LBraceLoc) {
17288 StringLiteral *Lit = cast<StringLiteral>(Val: LangStr);
17289 assert(Lit->isUnevaluated() && "Unexpected string literal kind");
17290
17291 StringRef Lang = Lit->getString();
17292 LinkageSpecLanguageIDs Language;
17293 if (Lang == "C")
17294 Language = LinkageSpecLanguageIDs::C;
17295 else if (Lang == "C++")
17296 Language = LinkageSpecLanguageIDs::CXX;
17297 else {
17298 Diag(Loc: LangStr->getExprLoc(), DiagID: diag::err_language_linkage_spec_unknown)
17299 << LangStr->getSourceRange();
17300 return nullptr;
17301 }
17302
17303 // FIXME: Add all the various semantics of linkage specifications
17304
17305 LinkageSpecDecl *D = LinkageSpecDecl::Create(C&: Context, DC: CurContext, ExternLoc,
17306 LangLoc: LangStr->getExprLoc(), Lang: Language,
17307 HasBraces: LBraceLoc.isValid());
17308
17309 /// C++ [module.unit]p7.2.3
17310 /// - Otherwise, if the declaration
17311 /// - ...
17312 /// - ...
17313 /// - appears within a linkage-specification,
17314 /// it is attached to the global module.
17315 ///
17316 /// If the declaration is already in global module fragment, we don't
17317 /// need to attach it again.
17318 if (getLangOpts().CPlusPlusModules && isCurrentModulePurview()) {
17319 Module *GlobalModule = PushImplicitGlobalModuleFragment(BeginLoc: ExternLoc);
17320 D->setLocalOwningModule(GlobalModule);
17321 }
17322
17323 CurContext->addDecl(D);
17324 PushDeclContext(S, DC: D);
17325 return D;
17326}
17327
17328Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
17329 Decl *LinkageSpec,
17330 SourceLocation RBraceLoc) {
17331 if (RBraceLoc.isValid()) {
17332 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(Val: LinkageSpec);
17333 LSDecl->setRBraceLoc(RBraceLoc);
17334 }
17335
17336 // If the current module doesn't has Parent, it implies that the
17337 // LinkageSpec isn't in the module created by itself. So we don't
17338 // need to pop it.
17339 if (getLangOpts().CPlusPlusModules && getCurrentModule() &&
17340 getCurrentModule()->isImplicitGlobalModule() &&
17341 getCurrentModule()->Parent)
17342 PopImplicitGlobalModuleFragment();
17343
17344 PopDeclContext();
17345 return LinkageSpec;
17346}
17347
17348Decl *Sema::ActOnEmptyDeclaration(Scope *S,
17349 const ParsedAttributesView &AttrList,
17350 SourceLocation SemiLoc) {
17351 Decl *ED = EmptyDecl::Create(C&: Context, DC: CurContext, L: SemiLoc);
17352 // Attribute declarations appertain to empty declaration so we handle
17353 // them here.
17354 ProcessDeclAttributeList(S, D: ED, AttrList);
17355
17356 CurContext->addDecl(D: ED);
17357 return ED;
17358}
17359
17360VarDecl *Sema::BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
17361 SourceLocation StartLoc,
17362 SourceLocation Loc,
17363 const IdentifierInfo *Name) {
17364 bool Invalid = false;
17365 QualType ExDeclType = TInfo->getType();
17366
17367 // Arrays and functions decay.
17368 if (ExDeclType->isArrayType())
17369 ExDeclType = Context.getArrayDecayedType(T: ExDeclType);
17370 else if (ExDeclType->isFunctionType())
17371 ExDeclType = Context.getPointerType(T: ExDeclType);
17372
17373 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
17374 // The exception-declaration shall not denote a pointer or reference to an
17375 // incomplete type, other than [cv] void*.
17376 // N2844 forbids rvalue references.
17377 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
17378 Diag(Loc, DiagID: diag::err_catch_rvalue_ref);
17379 Invalid = true;
17380 }
17381
17382 if (ExDeclType->isVariablyModifiedType()) {
17383 Diag(Loc, DiagID: diag::err_catch_variably_modified) << ExDeclType;
17384 Invalid = true;
17385 }
17386
17387 QualType BaseType = ExDeclType;
17388 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
17389 unsigned DK = diag::err_catch_incomplete;
17390 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
17391 BaseType = Ptr->getPointeeType();
17392 Mode = 1;
17393 DK = diag::err_catch_incomplete_ptr;
17394 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
17395 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
17396 BaseType = Ref->getPointeeType();
17397 Mode = 2;
17398 DK = diag::err_catch_incomplete_ref;
17399 }
17400 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
17401 !BaseType->isDependentType() && RequireCompleteType(Loc, T: BaseType, DiagID: DK))
17402 Invalid = true;
17403
17404 if (!Invalid && BaseType.isWebAssemblyReferenceType()) {
17405 Diag(Loc, DiagID: diag::err_wasm_reftype_tc) << 1;
17406 Invalid = true;
17407 }
17408
17409 if (!Invalid && Mode != 1 && BaseType->isSizelessType()) {
17410 Diag(Loc, DiagID: diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType;
17411 Invalid = true;
17412 }
17413
17414 if (!Invalid && !ExDeclType->isDependentType() &&
17415 RequireNonAbstractType(Loc, T: ExDeclType,
17416 DiagID: diag::err_abstract_type_in_decl,
17417 Args: AbstractVariableType))
17418 Invalid = true;
17419
17420 // Only the non-fragile NeXT runtime currently supports C++ catches
17421 // of ObjC types, and no runtime supports catching ObjC types by value.
17422 if (!Invalid && getLangOpts().ObjC) {
17423 QualType T = ExDeclType;
17424 if (const ReferenceType *RT = T->getAs<ReferenceType>())
17425 T = RT->getPointeeType();
17426
17427 if (T->isObjCObjectType()) {
17428 Diag(Loc, DiagID: diag::err_objc_object_catch);
17429 Invalid = true;
17430 } else if (T->isObjCObjectPointerType()) {
17431 // FIXME: should this be a test for macosx-fragile specifically?
17432 if (getLangOpts().ObjCRuntime.isFragile())
17433 Diag(Loc, DiagID: diag::warn_objc_pointer_cxx_catch_fragile);
17434 }
17435 }
17436
17437 VarDecl *ExDecl = VarDecl::Create(C&: Context, DC: CurContext, StartLoc, IdLoc: Loc, Id: Name,
17438 T: ExDeclType, TInfo, S: SC_None);
17439 ExDecl->setExceptionVariable(true);
17440
17441 // In ARC, infer 'retaining' for variables of retainable type.
17442 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(decl: ExDecl))
17443 Invalid = true;
17444
17445 if (!Invalid && !ExDeclType->isDependentType()) {
17446 if (auto *ClassDecl = ExDeclType->getAsCXXRecordDecl()) {
17447 // Insulate this from anything else we might currently be parsing.
17448 EnterExpressionEvaluationContext scope(
17449 *this, ExpressionEvaluationContext::PotentiallyEvaluated);
17450
17451 // C++ [except.handle]p16:
17452 // The object declared in an exception-declaration or, if the
17453 // exception-declaration does not specify a name, a temporary (12.2) is
17454 // copy-initialized (8.5) from the exception object. [...]
17455 // The object is destroyed when the handler exits, after the destruction
17456 // of any automatic objects initialized within the handler.
17457 //
17458 // We just pretend to initialize the object with itself, then make sure
17459 // it can be destroyed later.
17460 QualType initType = Context.getExceptionObjectType(T: ExDeclType);
17461
17462 InitializedEntity entity =
17463 InitializedEntity::InitializeVariable(Var: ExDecl);
17464 InitializationKind initKind =
17465 InitializationKind::CreateCopy(InitLoc: Loc, EqualLoc: SourceLocation());
17466
17467 Expr *opaqueValue =
17468 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
17469 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
17470 ExprResult result = sequence.Perform(S&: *this, Entity: entity, Kind: initKind, Args: opaqueValue);
17471 if (result.isInvalid())
17472 Invalid = true;
17473 else {
17474 // If the constructor used was non-trivial, set this as the
17475 // "initializer".
17476 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
17477 if (!construct->getConstructor()->isTrivial()) {
17478 Expr *init = MaybeCreateExprWithCleanups(SubExpr: construct);
17479 ExDecl->setInit(init);
17480 }
17481
17482 // And make sure it's destructable.
17483 FinalizeVarWithDestructor(VD: ExDecl, ClassDecl);
17484 }
17485 }
17486 }
17487
17488 if (Invalid)
17489 ExDecl->setInvalidDecl();
17490
17491 return ExDecl;
17492}
17493
17494Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
17495 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
17496 bool Invalid = D.isInvalidType();
17497
17498 // Check for unexpanded parameter packs.
17499 if (DiagnoseUnexpandedParameterPack(Loc: D.getIdentifierLoc(), T: TInfo,
17500 UPPC: UPPC_ExceptionType)) {
17501 TInfo = Context.getTrivialTypeSourceInfo(T: Context.IntTy,
17502 Loc: D.getIdentifierLoc());
17503 Invalid = true;
17504 }
17505
17506 const IdentifierInfo *II = D.getIdentifier();
17507 if (NamedDecl *PrevDecl =
17508 LookupSingleName(S, Name: II, Loc: D.getIdentifierLoc(), NameKind: LookupOrdinaryName,
17509 Redecl: RedeclarationKind::ForVisibleRedeclaration)) {
17510 // The scope should be freshly made just for us. There is just no way
17511 // it contains any previous declaration, except for function parameters in
17512 // a function-try-block's catch statement.
17513 assert(!S->isDeclScope(PrevDecl));
17514 if (isDeclInScope(D: PrevDecl, Ctx: CurContext, S)) {
17515 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_redefinition)
17516 << D.getIdentifier();
17517 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_definition);
17518 Invalid = true;
17519 } else if (PrevDecl->isTemplateParameter())
17520 // Maybe we will complain about the shadowed template parameter.
17521 DiagnoseTemplateParameterShadow(Loc: D.getIdentifierLoc(), PrevDecl);
17522 }
17523
17524 if (D.getCXXScopeSpec().isSet() && !Invalid) {
17525 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_qualified_catch_declarator)
17526 << D.getCXXScopeSpec().getRange();
17527 Invalid = true;
17528 }
17529
17530 VarDecl *ExDecl = BuildExceptionDeclaration(
17531 S, TInfo, StartLoc: D.getBeginLoc(), Loc: D.getIdentifierLoc(), Name: D.getIdentifier());
17532 if (Invalid)
17533 ExDecl->setInvalidDecl();
17534
17535 // Add the exception declaration into this scope.
17536 if (II)
17537 PushOnScopeChains(D: ExDecl, S);
17538 else
17539 CurContext->addDecl(D: ExDecl);
17540
17541 ProcessDeclAttributes(S, D: ExDecl, PD: D);
17542 return ExDecl;
17543}
17544
17545Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
17546 Expr *AssertExpr,
17547 Expr *AssertMessageExpr,
17548 SourceLocation RParenLoc) {
17549 if (DiagnoseUnexpandedParameterPack(E: AssertExpr, UPPC: UPPC_StaticAssertExpression))
17550 return nullptr;
17551
17552 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
17553 AssertMessageExpr, RParenLoc, Failed: false);
17554}
17555
17556static void WriteCharTypePrefix(BuiltinType::Kind BTK, llvm::raw_ostream &OS) {
17557 switch (BTK) {
17558 case BuiltinType::Char_S:
17559 case BuiltinType::Char_U:
17560 break;
17561 case BuiltinType::Char8:
17562 OS << "u8";
17563 break;
17564 case BuiltinType::Char16:
17565 OS << 'u';
17566 break;
17567 case BuiltinType::Char32:
17568 OS << 'U';
17569 break;
17570 case BuiltinType::WChar_S:
17571 case BuiltinType::WChar_U:
17572 OS << 'L';
17573 break;
17574 default:
17575 llvm_unreachable("Non-character type");
17576 }
17577}
17578
17579/// Convert character's value, interpreted as a code unit, to a string.
17580/// The value needs to be zero-extended to 32-bits.
17581/// FIXME: This assumes Unicode literal encodings
17582static void WriteCharValueForDiagnostic(uint32_t Value, const BuiltinType *BTy,
17583 unsigned TyWidth,
17584 SmallVectorImpl<char> &Str) {
17585 char Arr[UNI_MAX_UTF8_BYTES_PER_CODE_POINT];
17586 char *Ptr = Arr;
17587 BuiltinType::Kind K = BTy->getKind();
17588 llvm::raw_svector_ostream OS(Str);
17589
17590 // This should catch Char_S, Char_U, Char8, and use of escaped characters in
17591 // other types.
17592 if (K == BuiltinType::Char_S || K == BuiltinType::Char_U ||
17593 K == BuiltinType::Char8 || Value <= 0x7F) {
17594 StringRef Escaped = escapeCStyle<EscapeChar::Single>(Ch: Value);
17595 if (!Escaped.empty())
17596 EscapeStringForDiagnostic(Str: Escaped, OutStr&: Str);
17597 else
17598 OS << static_cast<char>(Value);
17599 return;
17600 }
17601
17602 switch (K) {
17603 case BuiltinType::Char16:
17604 case BuiltinType::Char32:
17605 case BuiltinType::WChar_S:
17606 case BuiltinType::WChar_U: {
17607 if (llvm::ConvertCodePointToUTF8(Source: Value, ResultPtr&: Ptr))
17608 EscapeStringForDiagnostic(Str: StringRef(Arr, Ptr - Arr), OutStr&: Str);
17609 else
17610 OS << "\\x"
17611 << llvm::format_hex_no_prefix(N: Value, Width: TyWidth / 4, /*Upper=*/true);
17612 break;
17613 }
17614 default:
17615 llvm_unreachable("Non-character type is passed");
17616 }
17617}
17618
17619/// Convert \V to a string we can present to the user in a diagnostic
17620/// \T is the type of the expression that has been evaluated into \V
17621static bool ConvertAPValueToString(const APValue &V, QualType T,
17622 SmallVectorImpl<char> &Str,
17623 ASTContext &Context) {
17624 if (!V.hasValue())
17625 return false;
17626
17627 switch (V.getKind()) {
17628 case APValue::ValueKind::Int:
17629 if (T->isBooleanType()) {
17630 // Bools are reduced to ints during evaluation, but for
17631 // diagnostic purposes we want to print them as
17632 // true or false.
17633 int64_t BoolValue = V.getInt().getExtValue();
17634 assert((BoolValue == 0 || BoolValue == 1) &&
17635 "Bool type, but value is not 0 or 1");
17636 llvm::raw_svector_ostream OS(Str);
17637 OS << (BoolValue ? "true" : "false");
17638 } else {
17639 llvm::raw_svector_ostream OS(Str);
17640 // Same is true for chars.
17641 // We want to print the character representation for textual types
17642 const auto *BTy = T->getAs<BuiltinType>();
17643 if (BTy) {
17644 switch (BTy->getKind()) {
17645 case BuiltinType::Char_S:
17646 case BuiltinType::Char_U:
17647 case BuiltinType::Char8:
17648 case BuiltinType::Char16:
17649 case BuiltinType::Char32:
17650 case BuiltinType::WChar_S:
17651 case BuiltinType::WChar_U: {
17652 unsigned TyWidth = Context.getIntWidth(T);
17653 assert(8 <= TyWidth && TyWidth <= 32 && "Unexpected integer width");
17654 uint32_t CodeUnit = static_cast<uint32_t>(V.getInt().getZExtValue());
17655 WriteCharTypePrefix(BTK: BTy->getKind(), OS);
17656 OS << '\'';
17657 WriteCharValueForDiagnostic(Value: CodeUnit, BTy, TyWidth, Str);
17658 OS << "' (0x"
17659 << llvm::format_hex_no_prefix(N: CodeUnit, /*Width=*/2,
17660 /*Upper=*/true)
17661 << ", " << V.getInt() << ')';
17662 return true;
17663 }
17664 default:
17665 break;
17666 }
17667 }
17668 V.getInt().toString(Str);
17669 }
17670
17671 break;
17672
17673 case APValue::ValueKind::Float:
17674 V.getFloat().toString(Str);
17675 break;
17676
17677 case APValue::ValueKind::LValue:
17678 if (V.isNullPointer()) {
17679 llvm::raw_svector_ostream OS(Str);
17680 OS << "nullptr";
17681 } else
17682 return false;
17683 break;
17684
17685 case APValue::ValueKind::ComplexFloat: {
17686 llvm::raw_svector_ostream OS(Str);
17687 OS << '(';
17688 V.getComplexFloatReal().toString(Str);
17689 OS << " + ";
17690 V.getComplexFloatImag().toString(Str);
17691 OS << "i)";
17692 } break;
17693
17694 case APValue::ValueKind::ComplexInt: {
17695 llvm::raw_svector_ostream OS(Str);
17696 OS << '(';
17697 V.getComplexIntReal().toString(Str);
17698 OS << " + ";
17699 V.getComplexIntImag().toString(Str);
17700 OS << "i)";
17701 } break;
17702
17703 default:
17704 return false;
17705 }
17706
17707 return true;
17708}
17709
17710/// Some Expression types are not useful to print notes about,
17711/// e.g. literals and values that have already been expanded
17712/// before such as int-valued template parameters.
17713static bool UsefulToPrintExpr(const Expr *E) {
17714 E = E->IgnoreParenImpCasts();
17715 // Literals are pretty easy for humans to understand.
17716 if (isa<IntegerLiteral, FloatingLiteral, CharacterLiteral, CXXBoolLiteralExpr,
17717 CXXNullPtrLiteralExpr, FixedPointLiteral, ImaginaryLiteral>(Val: E))
17718 return false;
17719
17720 // These have been substituted from template parameters
17721 // and appear as literals in the static assert error.
17722 if (isa<SubstNonTypeTemplateParmExpr>(Val: E))
17723 return false;
17724
17725 // -5 is also simple to understand.
17726 if (const auto *UnaryOp = dyn_cast<UnaryOperator>(Val: E))
17727 return UsefulToPrintExpr(E: UnaryOp->getSubExpr());
17728
17729 // Only print nested arithmetic operators.
17730 if (const auto *BO = dyn_cast<BinaryOperator>(Val: E))
17731 return (BO->isShiftOp() || BO->isAdditiveOp() || BO->isMultiplicativeOp() ||
17732 BO->isBitwiseOp());
17733
17734 return true;
17735}
17736
17737void Sema::DiagnoseStaticAssertDetails(const Expr *E) {
17738 if (const auto *Op = dyn_cast<BinaryOperator>(Val: E);
17739 Op && Op->getOpcode() != BO_LOr) {
17740 const Expr *LHS = Op->getLHS()->IgnoreParenImpCasts();
17741 const Expr *RHS = Op->getRHS()->IgnoreParenImpCasts();
17742
17743 // Ignore comparisons of boolean expressions with a boolean literal.
17744 if ((isa<CXXBoolLiteralExpr>(Val: LHS) && RHS->getType()->isBooleanType()) ||
17745 (isa<CXXBoolLiteralExpr>(Val: RHS) && LHS->getType()->isBooleanType()))
17746 return;
17747
17748 // Don't print obvious expressions.
17749 if (!UsefulToPrintExpr(E: LHS) && !UsefulToPrintExpr(E: RHS))
17750 return;
17751
17752 struct {
17753 const clang::Expr *Cond;
17754 Expr::EvalResult Result;
17755 SmallString<12> ValueString;
17756 bool Print;
17757 } DiagSides[2] = {{.Cond: LHS, .Result: Expr::EvalResult(), .ValueString: {}, .Print: false},
17758 {.Cond: RHS, .Result: Expr::EvalResult(), .ValueString: {}, .Print: false}};
17759 for (auto &DiagSide : DiagSides) {
17760 const Expr *Side = DiagSide.Cond;
17761
17762 Side->EvaluateAsRValue(Result&: DiagSide.Result, Ctx: Context, InConstantContext: true);
17763
17764 DiagSide.Print = ConvertAPValueToString(
17765 V: DiagSide.Result.Val, T: Side->getType(), Str&: DiagSide.ValueString, Context);
17766 }
17767 if (DiagSides[0].Print && DiagSides[1].Print) {
17768 Diag(Loc: Op->getExprLoc(), DiagID: diag::note_expr_evaluates_to)
17769 << DiagSides[0].ValueString << Op->getOpcodeStr()
17770 << DiagSides[1].ValueString << Op->getSourceRange();
17771 }
17772 } else {
17773 DiagnoseTypeTraitDetails(E);
17774 }
17775}
17776
17777template <typename ResultType>
17778static bool EvaluateAsStringImpl(Sema &SemaRef, Expr *Message,
17779 ResultType &Result, ASTContext &Ctx,
17780 Sema::StringEvaluationContext EvalContext,
17781 bool ErrorOnInvalidMessage) {
17782
17783 assert(Message);
17784 assert(!Message->isTypeDependent() && !Message->isValueDependent() &&
17785 "can't evaluate a dependant static assert message");
17786
17787 if (const auto *SL = dyn_cast<StringLiteral>(Val: Message)) {
17788 assert(SL->isUnevaluated() && "expected an unevaluated string");
17789 if constexpr (std::is_same_v<APValue, ResultType>) {
17790 Result =
17791 APValue(APValue::UninitArray{}, SL->getLength(), SL->getLength());
17792 const ConstantArrayType *CAT =
17793 SemaRef.getASTContext().getAsConstantArrayType(T: SL->getType());
17794 assert(CAT && "string literal isn't an array");
17795 QualType CharType = CAT->getElementType();
17796 llvm::APSInt Value(SemaRef.getASTContext().getTypeSize(T: CharType),
17797 CharType->isUnsignedIntegerType());
17798 for (unsigned I = 0; I < SL->getLength(); I++) {
17799 Value = SL->getCodeUnit(i: I);
17800 Result.getArrayInitializedElt(I) = APValue(Value);
17801 }
17802 } else {
17803 Result.assign(SL->getString().begin(), SL->getString().end());
17804 }
17805 return true;
17806 }
17807
17808 SourceLocation Loc = Message->getBeginLoc();
17809 QualType T = Message->getType().getNonReferenceType();
17810 auto *RD = T->getAsCXXRecordDecl();
17811 if (!RD) {
17812 SemaRef.Diag(Loc, DiagID: diag::err_user_defined_msg_invalid) << EvalContext;
17813 return false;
17814 }
17815
17816 auto FindMember = [&](StringRef Member) -> std::optional<LookupResult> {
17817 DeclarationName DN = SemaRef.PP.getIdentifierInfo(Name: Member);
17818 LookupResult MemberLookup(SemaRef, DN, Loc, Sema::LookupMemberName);
17819 SemaRef.LookupQualifiedName(R&: MemberLookup, LookupCtx: RD);
17820 OverloadCandidateSet Candidates(MemberLookup.getNameLoc(),
17821 OverloadCandidateSet::CSK_Normal);
17822 if (MemberLookup.empty())
17823 return std::nullopt;
17824 return std::move(MemberLookup);
17825 };
17826
17827 std::optional<LookupResult> SizeMember = FindMember("size");
17828 std::optional<LookupResult> DataMember = FindMember("data");
17829 if (!SizeMember || !DataMember) {
17830 SemaRef.Diag(Loc, DiagID: diag::err_user_defined_msg_missing_member_function)
17831 << EvalContext
17832 << ((!SizeMember && !DataMember) ? 2
17833 : !SizeMember ? 0
17834 : 1);
17835 return false;
17836 }
17837
17838 auto BuildExpr = [&](LookupResult &LR) {
17839 ExprResult Res = SemaRef.BuildMemberReferenceExpr(
17840 Base: Message, BaseType: Message->getType(), OpLoc: Message->getBeginLoc(), IsArrow: false,
17841 SS: CXXScopeSpec(), TemplateKWLoc: SourceLocation(), FirstQualifierInScope: nullptr, R&: LR, TemplateArgs: nullptr, S: nullptr);
17842 if (Res.isInvalid())
17843 return ExprError();
17844 Res = SemaRef.BuildCallExpr(S: nullptr, Fn: Res.get(), LParenLoc: Loc, ArgExprs: {}, RParenLoc: Loc, ExecConfig: nullptr,
17845 IsExecConfig: false, AllowRecovery: true);
17846 if (Res.isInvalid())
17847 return ExprError();
17848 if (Res.get()->isTypeDependent() || Res.get()->isValueDependent())
17849 return ExprError();
17850 return SemaRef.TemporaryMaterializationConversion(E: Res.get());
17851 };
17852
17853 ExprResult SizeE = BuildExpr(*SizeMember);
17854 ExprResult DataE = BuildExpr(*DataMember);
17855
17856 QualType SizeT = SemaRef.Context.getSizeType();
17857 QualType ConstCharPtr = SemaRef.Context.getPointerType(
17858 T: SemaRef.Context.getConstType(T: SemaRef.Context.CharTy));
17859
17860 ExprResult EvaluatedSize =
17861 SizeE.isInvalid()
17862 ? ExprError()
17863 : SemaRef.BuildConvertedConstantExpression(
17864 From: SizeE.get(), T: SizeT, CCE: CCEKind::StaticAssertMessageSize);
17865 if (EvaluatedSize.isInvalid()) {
17866 SemaRef.Diag(Loc, DiagID: diag::err_user_defined_msg_invalid_mem_fn_ret_ty)
17867 << EvalContext << /*size*/ 0;
17868 return false;
17869 }
17870
17871 ExprResult EvaluatedData =
17872 DataE.isInvalid()
17873 ? ExprError()
17874 : SemaRef.BuildConvertedConstantExpression(
17875 From: DataE.get(), T: ConstCharPtr, CCE: CCEKind::StaticAssertMessageData);
17876 if (EvaluatedData.isInvalid()) {
17877 SemaRef.Diag(Loc, DiagID: diag::err_user_defined_msg_invalid_mem_fn_ret_ty)
17878 << EvalContext << /*data*/ 1;
17879 return false;
17880 }
17881
17882 if (!ErrorOnInvalidMessage &&
17883 SemaRef.Diags.isIgnored(DiagID: diag::warn_user_defined_msg_constexpr, Loc))
17884 return true;
17885
17886 Expr::EvalResult Status;
17887 SmallVector<PartialDiagnosticAt, 8> Notes;
17888 Status.Diag = &Notes;
17889 if (!Message->EvaluateCharRangeAsString(Result, EvaluatedSize.get(),
17890 EvaluatedData.get(), Ctx, Status) ||
17891 !Notes.empty()) {
17892 SemaRef.Diag(Loc: Message->getBeginLoc(),
17893 DiagID: ErrorOnInvalidMessage ? diag::err_user_defined_msg_constexpr
17894 : diag::warn_user_defined_msg_constexpr)
17895 << EvalContext;
17896 for (const auto &Note : Notes)
17897 SemaRef.Diag(Loc: Note.first, PD: Note.second);
17898 return !ErrorOnInvalidMessage;
17899 }
17900 return true;
17901}
17902
17903bool Sema::EvaluateAsString(Expr *Message, APValue &Result, ASTContext &Ctx,
17904 StringEvaluationContext EvalContext,
17905 bool ErrorOnInvalidMessage) {
17906 return EvaluateAsStringImpl(SemaRef&: *this, Message, Result, Ctx, EvalContext,
17907 ErrorOnInvalidMessage);
17908}
17909
17910bool Sema::EvaluateAsString(Expr *Message, std::string &Result, ASTContext &Ctx,
17911 StringEvaluationContext EvalContext,
17912 bool ErrorOnInvalidMessage) {
17913 return EvaluateAsStringImpl(SemaRef&: *this, Message, Result, Ctx, EvalContext,
17914 ErrorOnInvalidMessage);
17915}
17916
17917Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
17918 Expr *AssertExpr, Expr *AssertMessage,
17919 SourceLocation RParenLoc,
17920 bool Failed) {
17921 assert(AssertExpr != nullptr && "Expected non-null condition");
17922 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
17923 (!AssertMessage || (!AssertMessage->isTypeDependent() &&
17924 !AssertMessage->isValueDependent())) &&
17925 !Failed) {
17926 // In a static_assert-declaration, the constant-expression shall be a
17927 // constant expression that can be contextually converted to bool.
17928 ExprResult Converted = PerformContextuallyConvertToBool(From: AssertExpr);
17929 if (Converted.isInvalid())
17930 Failed = true;
17931
17932 ExprResult FullAssertExpr =
17933 ActOnFinishFullExpr(Expr: Converted.get(), CC: StaticAssertLoc,
17934 /*DiscardedValue*/ false,
17935 /*IsConstexpr*/ true);
17936 if (FullAssertExpr.isInvalid())
17937 Failed = true;
17938 else
17939 AssertExpr = FullAssertExpr.get();
17940
17941 llvm::APSInt Cond;
17942 Expr *BaseExpr = AssertExpr;
17943 AllowFoldKind FoldKind = AllowFoldKind::No;
17944
17945 if (!getLangOpts().CPlusPlus) {
17946 // In C mode, allow folding as an extension for better compatibility with
17947 // C++ in terms of expressions like static_assert("test") or
17948 // static_assert(nullptr).
17949 FoldKind = AllowFoldKind::Allow;
17950 }
17951
17952 if (!Failed && VerifyIntegerConstantExpression(
17953 E: BaseExpr, Result: &Cond,
17954 DiagID: diag::err_static_assert_expression_is_not_constant,
17955 CanFold: FoldKind).isInvalid())
17956 Failed = true;
17957
17958 // If the static_assert passes, only verify that
17959 // the message is grammatically valid without evaluating it.
17960 if (!Failed && AssertMessage && Cond.getBoolValue()) {
17961 std::string Str;
17962 EvaluateAsString(Message: AssertMessage, Result&: Str, Ctx&: Context,
17963 EvalContext: StringEvaluationContext::StaticAssert,
17964 /*ErrorOnInvalidMessage=*/false);
17965 }
17966
17967 // CWG2518
17968 // [dcl.pre]/p10 If [...] the expression is evaluated in the context of a
17969 // template definition, the declaration has no effect.
17970 bool InTemplateDefinition =
17971 getLangOpts().CPlusPlus && CurContext->isDependentContext();
17972
17973 if (!Failed && !Cond && !InTemplateDefinition) {
17974 SmallString<256> MsgBuffer;
17975 llvm::raw_svector_ostream Msg(MsgBuffer);
17976 bool HasMessage = AssertMessage;
17977 if (AssertMessage) {
17978 std::string Str;
17979 HasMessage = EvaluateAsString(Message: AssertMessage, Result&: Str, Ctx&: Context,
17980 EvalContext: StringEvaluationContext::StaticAssert,
17981 /*ErrorOnInvalidMessage=*/true) ||
17982 !Str.empty();
17983 Msg << Str;
17984 }
17985 Expr *InnerCond = nullptr;
17986 std::string InnerCondDescription;
17987 std::tie(args&: InnerCond, args&: InnerCondDescription) =
17988 findFailedBooleanCondition(Cond: Converted.get());
17989 if (const auto *ConceptIDExpr =
17990 dyn_cast_or_null<ConceptSpecializationExpr>(Val: InnerCond)) {
17991 const ASTConstraintSatisfaction &Satisfaction =
17992 ConceptIDExpr->getSatisfaction();
17993 if (!Satisfaction.ContainsErrors || Satisfaction.NumRecords) {
17994 Diag(Loc: AssertExpr->getBeginLoc(), DiagID: diag::err_static_assert_failed)
17995 << !HasMessage << Msg.str() << AssertExpr->getSourceRange();
17996 // Drill down into concept specialization expressions to see why they
17997 // weren't satisfied.
17998 DiagnoseUnsatisfiedConstraint(ConstraintExpr: ConceptIDExpr);
17999 }
18000 } else if (InnerCond && !isa<CXXBoolLiteralExpr>(Val: InnerCond) &&
18001 !isa<IntegerLiteral>(Val: InnerCond)) {
18002 Diag(Loc: InnerCond->getBeginLoc(),
18003 DiagID: diag::err_static_assert_requirement_failed)
18004 << InnerCondDescription << !HasMessage << Msg.str()
18005 << InnerCond->getSourceRange();
18006 DiagnoseStaticAssertDetails(E: InnerCond);
18007 } else {
18008 Diag(Loc: AssertExpr->getBeginLoc(), DiagID: diag::err_static_assert_failed)
18009 << !HasMessage << Msg.str() << AssertExpr->getSourceRange();
18010 PrintContextStack();
18011 }
18012 Failed = true;
18013 }
18014 } else {
18015 ExprResult FullAssertExpr = ActOnFinishFullExpr(Expr: AssertExpr, CC: StaticAssertLoc,
18016 /*DiscardedValue*/false,
18017 /*IsConstexpr*/true);
18018 if (FullAssertExpr.isInvalid())
18019 Failed = true;
18020 else
18021 AssertExpr = FullAssertExpr.get();
18022 }
18023
18024 Decl *Decl = StaticAssertDecl::Create(C&: Context, DC: CurContext, StaticAssertLoc,
18025 AssertExpr, Message: AssertMessage, RParenLoc,
18026 Failed);
18027
18028 CurContext->addDecl(D: Decl);
18029 return Decl;
18030}
18031
18032DeclResult Sema::ActOnTemplatedFriendTag(
18033 Scope *S, SourceLocation FriendLoc, unsigned TagSpec, SourceLocation TagLoc,
18034 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
18035 SourceLocation EllipsisLoc, const ParsedAttributesView &Attr,
18036 MultiTemplateParamsArg TempParamLists) {
18037 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
18038
18039 bool IsMemberSpecialization = false;
18040 bool Invalid = false;
18041
18042 if (TemplateParameterList *TemplateParams =
18043 MatchTemplateParametersToScopeSpecifier(
18044 DeclStartLoc: TagLoc, DeclLoc: NameLoc, SS, TemplateId: nullptr, ParamLists: TempParamLists, /*friend*/ IsFriend: true,
18045 IsMemberSpecialization, Invalid)) {
18046 if (TemplateParams->size() > 0) {
18047 // This is a declaration of a class template.
18048 if (Invalid)
18049 return true;
18050
18051 return CheckClassTemplate(S, TagSpec, TUK: TagUseKind::Friend, KWLoc: TagLoc, SS,
18052 Name, NameLoc, Attr, TemplateParams, AS: AS_public,
18053 /*ModulePrivateLoc=*/SourceLocation(),
18054 FriendLoc, NumOuterTemplateParamLists: TempParamLists.size() - 1,
18055 OuterTemplateParamLists: TempParamLists.data())
18056 .get();
18057 } else {
18058 // The "template<>" header is extraneous.
18059 Diag(Loc: TemplateParams->getTemplateLoc(), DiagID: diag::err_template_tag_noparams)
18060 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
18061 IsMemberSpecialization = true;
18062 }
18063 }
18064
18065 if (Invalid) return true;
18066
18067 bool isAllExplicitSpecializations =
18068 llvm::all_of(Range&: TempParamLists, P: [](const TemplateParameterList *List) {
18069 return List->size() == 0;
18070 });
18071
18072 // FIXME: don't ignore attributes.
18073
18074 // If it's explicit specializations all the way down, just forget
18075 // about the template header and build an appropriate non-templated
18076 // friend. TODO: for source fidelity, remember the headers.
18077 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
18078 if (isAllExplicitSpecializations) {
18079 if (SS.isEmpty()) {
18080 bool Owned = false;
18081 bool IsDependent = false;
18082 return ActOnTag(S, TagSpec, TUK: TagUseKind::Friend, KWLoc: TagLoc, SS, Name, NameLoc,
18083 Attr, AS: AS_public,
18084 /*ModulePrivateLoc=*/SourceLocation(),
18085 TemplateParameterLists: MultiTemplateParamsArg(), OwnedDecl&: Owned, IsDependent,
18086 /*ScopedEnumKWLoc=*/SourceLocation(),
18087 /*ScopedEnumUsesClassTag=*/false,
18088 /*UnderlyingType=*/TypeResult(),
18089 /*IsTypeSpecifier=*/false,
18090 /*IsTemplateParamOrArg=*/false,
18091 /*OOK=*/OffsetOfKind::Outside);
18092 }
18093
18094 TypeSourceInfo *TSI = nullptr;
18095 ElaboratedTypeKeyword Keyword
18096 = TypeWithKeyword::getKeywordForTagTypeKind(Tag: Kind);
18097 QualType T = CheckTypenameType(Keyword, KeywordLoc: TagLoc, QualifierLoc, II: *Name,
18098 IILoc: NameLoc, TSI: &TSI, /*DeducedTSTContext=*/true);
18099 if (T.isNull())
18100 return true;
18101
18102 FriendDecl *Friend =
18103 FriendDecl::Create(C&: Context, DC: CurContext, L: NameLoc, Friend_: TSI, FriendL: FriendLoc,
18104 EllipsisLoc, FriendTypeTPLists: TempParamLists);
18105 Friend->setAccess(AS_public);
18106 CurContext->addDecl(D: Friend);
18107 return Friend;
18108 }
18109
18110 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
18111
18112 // CWG 2917: if it (= the friend-type-specifier) is a pack expansion
18113 // (13.7.4 [temp.variadic]), any packs expanded by that pack expansion
18114 // shall not have been introduced by the template-declaration.
18115 SmallVector<UnexpandedParameterPack, 1> Unexpanded;
18116 collectUnexpandedParameterPacks(NNS: QualifierLoc, Unexpanded);
18117 unsigned FriendDeclDepth = TempParamLists.front()->getDepth();
18118 for (UnexpandedParameterPack &U : Unexpanded) {
18119 if (std::optional<std::pair<unsigned, unsigned>> DI = getDepthAndIndex(UPP: U);
18120 DI && DI->first >= FriendDeclDepth) {
18121 auto *ND = dyn_cast<NamedDecl *>(Val&: U.first);
18122 if (!ND)
18123 ND = cast<const TemplateTypeParmType *>(Val&: U.first)->getDecl();
18124 Diag(Loc: U.second, DiagID: diag::friend_template_decl_malformed_pack_expansion)
18125 << ND->getDeclName() << SourceRange(SS.getBeginLoc(), EllipsisLoc);
18126 return true;
18127 }
18128 }
18129
18130 // Handle the case of a templated-scope friend class. e.g.
18131 // template <class T> class A<T>::B;
18132 // FIXME: we don't support these right now.
18133 Diag(Loc: NameLoc, DiagID: diag::warn_template_qualified_friend_unsupported)
18134 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(Val: CurContext);
18135 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Tag: Kind);
18136 QualType T = Context.getDependentNameType(Keyword: ETK, NNS: SS.getScopeRep(), Name);
18137 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
18138 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
18139 TL.setElaboratedKeywordLoc(TagLoc);
18140 TL.setQualifierLoc(SS.getWithLocInContext(Context));
18141 TL.setNameLoc(NameLoc);
18142
18143 FriendDecl *Friend =
18144 FriendDecl::Create(C&: Context, DC: CurContext, L: NameLoc, Friend_: TSI, FriendL: FriendLoc,
18145 EllipsisLoc, FriendTypeTPLists: TempParamLists);
18146 Friend->setAccess(AS_public);
18147 Friend->setUnsupportedFriend(true);
18148 CurContext->addDecl(D: Friend);
18149 return Friend;
18150}
18151
18152Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
18153 MultiTemplateParamsArg TempParams,
18154 SourceLocation EllipsisLoc) {
18155 SourceLocation Loc = DS.getBeginLoc();
18156 SourceLocation FriendLoc = DS.getFriendSpecLoc();
18157
18158 assert(DS.isFriendSpecified());
18159 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
18160
18161 // C++ [class.friend]p3:
18162 // A friend declaration that does not declare a function shall have one of
18163 // the following forms:
18164 // friend elaborated-type-specifier ;
18165 // friend simple-type-specifier ;
18166 // friend typename-specifier ;
18167 //
18168 // If the friend keyword isn't first, or if the declarations has any type
18169 // qualifiers, then the declaration doesn't have that form.
18170 if (getLangOpts().CPlusPlus11 && !DS.isFriendSpecifiedFirst())
18171 Diag(Loc: FriendLoc, DiagID: diag::err_friend_not_first_in_declaration);
18172 if (DS.getTypeQualifiers()) {
18173 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
18174 Diag(Loc: DS.getConstSpecLoc(), DiagID: diag::err_friend_decl_spec) << "const";
18175 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
18176 Diag(Loc: DS.getVolatileSpecLoc(), DiagID: diag::err_friend_decl_spec) << "volatile";
18177 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
18178 Diag(Loc: DS.getRestrictSpecLoc(), DiagID: diag::err_friend_decl_spec) << "restrict";
18179 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
18180 Diag(Loc: DS.getAtomicSpecLoc(), DiagID: diag::err_friend_decl_spec) << "_Atomic";
18181 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
18182 Diag(Loc: DS.getUnalignedSpecLoc(), DiagID: diag::err_friend_decl_spec) << "__unaligned";
18183 }
18184
18185 // Try to convert the decl specifier to a type. This works for
18186 // friend templates because ActOnTag never produces a ClassTemplateDecl
18187 // for a TagUseKind::Friend.
18188 Declarator TheDeclarator(DS, ParsedAttributesView::none(),
18189 DeclaratorContext::Member);
18190 TypeSourceInfo *TSI = GetTypeForDeclarator(D&: TheDeclarator);
18191 QualType T = TSI->getType();
18192 if (TheDeclarator.isInvalidType())
18193 return nullptr;
18194
18195 // If '...' is present, the type must contain an unexpanded parameter
18196 // pack, and vice versa.
18197 bool Invalid = false;
18198 if (EllipsisLoc.isInvalid() &&
18199 DiagnoseUnexpandedParameterPack(Loc, T: TSI, UPPC: UPPC_FriendDeclaration))
18200 return nullptr;
18201 if (EllipsisLoc.isValid() &&
18202 !TSI->getType()->containsUnexpandedParameterPack()) {
18203 Diag(Loc: EllipsisLoc, DiagID: diag::err_pack_expansion_without_parameter_packs)
18204 << TSI->getTypeLoc().getSourceRange();
18205 Invalid = true;
18206 }
18207
18208 if (!T->isElaboratedTypeSpecifier()) {
18209 if (TempParams.size()) {
18210 // C++23 [dcl.pre]p5:
18211 // In a simple-declaration, the optional init-declarator-list can be
18212 // omitted only when declaring a class or enumeration, that is, when
18213 // the decl-specifier-seq contains either a class-specifier, an
18214 // elaborated-type-specifier with a class-key, or an enum-specifier.
18215 //
18216 // The declaration of a template-declaration or explicit-specialization
18217 // is never a member-declaration, so this must be a simple-declaration
18218 // with no init-declarator-list. Therefore, this is ill-formed.
18219 Diag(Loc, DiagID: diag::err_tagless_friend_type_template) << DS.getSourceRange();
18220 return nullptr;
18221 } else if (const RecordDecl *RD = T->getAsRecordDecl()) {
18222 SmallString<16> InsertionText(" ");
18223 InsertionText += RD->getKindName();
18224
18225 Diag(Loc, DiagID: getLangOpts().CPlusPlus11
18226 ? diag::warn_cxx98_compat_unelaborated_friend_type
18227 : diag::ext_unelaborated_friend_type)
18228 << (unsigned)RD->getTagKind() << T
18229 << FixItHint::CreateInsertion(InsertionLoc: getLocForEndOfToken(Loc: FriendLoc),
18230 Code: InsertionText);
18231 } else {
18232 DiagCompat(Loc: FriendLoc, CompatDiagId: diag_compat::nonclass_type_friend)
18233 << T << DS.getSourceRange();
18234 }
18235 }
18236
18237 // C++98 [class.friend]p1: A friend of a class is a function
18238 // or class that is not a member of the class . . .
18239 // This is fixed in DR77, which just barely didn't make the C++03
18240 // deadline. It's also a very silly restriction that seriously
18241 // affects inner classes and which nobody else seems to implement;
18242 // thus we never diagnose it, not even in -pedantic.
18243 //
18244 // But note that we could warn about it: it's always useless to
18245 // friend one of your own members (it's not, however, worthless to
18246 // friend a member of an arbitrary specialization of your template).
18247
18248 Decl *D;
18249 if (!TempParams.empty())
18250 // TODO: Support variadic friend template decls?
18251 D = FriendTemplateDecl::Create(Context, DC: CurContext, Loc, Params: TempParams, Friend: TSI,
18252 FriendLoc);
18253 else
18254 D = FriendDecl::Create(C&: Context, DC: CurContext, L: TSI->getTypeLoc().getBeginLoc(),
18255 Friend_: TSI, FriendL: FriendLoc, EllipsisLoc);
18256
18257 if (!D)
18258 return nullptr;
18259
18260 D->setAccess(AS_public);
18261 CurContext->addDecl(D);
18262
18263 if (Invalid)
18264 D->setInvalidDecl();
18265
18266 return D;
18267}
18268
18269NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
18270 MultiTemplateParamsArg TemplateParams) {
18271 const DeclSpec &DS = D.getDeclSpec();
18272
18273 assert(DS.isFriendSpecified());
18274 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
18275
18276 SourceLocation Loc = D.getIdentifierLoc();
18277 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
18278
18279 // C++ [class.friend]p1
18280 // A friend of a class is a function or class....
18281 // Note that this sees through typedefs, which is intended.
18282 // It *doesn't* see through dependent types, which is correct
18283 // according to [temp.arg.type]p3:
18284 // If a declaration acquires a function type through a
18285 // type dependent on a template-parameter and this causes
18286 // a declaration that does not use the syntactic form of a
18287 // function declarator to have a function type, the program
18288 // is ill-formed.
18289 if (!TInfo->getType()->isFunctionType()) {
18290 Diag(Loc, DiagID: diag::err_unexpected_friend);
18291
18292 // It might be worthwhile to try to recover by creating an
18293 // appropriate declaration.
18294 return nullptr;
18295 }
18296
18297 // C++ [namespace.memdef]p3
18298 // - If a friend declaration in a non-local class first declares a
18299 // class or function, the friend class or function is a member
18300 // of the innermost enclosing namespace.
18301 // - The name of the friend is not found by simple name lookup
18302 // until a matching declaration is provided in that namespace
18303 // scope (either before or after the class declaration granting
18304 // friendship).
18305 // - If a friend function is called, its name may be found by the
18306 // name lookup that considers functions from namespaces and
18307 // classes associated with the types of the function arguments.
18308 // - When looking for a prior declaration of a class or a function
18309 // declared as a friend, scopes outside the innermost enclosing
18310 // namespace scope are not considered.
18311
18312 CXXScopeSpec &SS = D.getCXXScopeSpec();
18313 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
18314 assert(NameInfo.getName());
18315
18316 // Check for unexpanded parameter packs.
18317 if (DiagnoseUnexpandedParameterPack(Loc, T: TInfo, UPPC: UPPC_FriendDeclaration) ||
18318 DiagnoseUnexpandedParameterPack(NameInfo, UPPC: UPPC_FriendDeclaration) ||
18319 DiagnoseUnexpandedParameterPack(SS, UPPC: UPPC_FriendDeclaration))
18320 return nullptr;
18321
18322 // The context we found the declaration in, or in which we should
18323 // create the declaration.
18324 DeclContext *DC;
18325 Scope *DCScope = S;
18326 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
18327 RedeclarationKind::ForExternalRedeclaration);
18328
18329 bool isTemplateId = D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
18330
18331 // There are five cases here.
18332 // - There's no scope specifier and we're in a local class. Only look
18333 // for functions declared in the immediately-enclosing block scope.
18334 // We recover from invalid scope qualifiers as if they just weren't there.
18335 FunctionDecl *FunctionContainingLocalClass = nullptr;
18336 if ((SS.isInvalid() || !SS.isSet()) &&
18337 (FunctionContainingLocalClass =
18338 cast<CXXRecordDecl>(Val: CurContext)->isLocalClass())) {
18339 // C++11 [class.friend]p11:
18340 // If a friend declaration appears in a local class and the name
18341 // specified is an unqualified name, a prior declaration is
18342 // looked up without considering scopes that are outside the
18343 // innermost enclosing non-class scope. For a friend function
18344 // declaration, if there is no prior declaration, the program is
18345 // ill-formed.
18346
18347 // Find the innermost enclosing non-class scope. This is the block
18348 // scope containing the local class definition (or for a nested class,
18349 // the outer local class).
18350 DCScope = S->getFnParent();
18351
18352 // Look up the function name in the scope.
18353 Previous.clear(Kind: LookupLocalFriendName);
18354 LookupName(R&: Previous, S, /*AllowBuiltinCreation*/false);
18355
18356 if (!Previous.empty()) {
18357 // All possible previous declarations must have the same context:
18358 // either they were declared at block scope or they are members of
18359 // one of the enclosing local classes.
18360 DC = Previous.getRepresentativeDecl()->getDeclContext();
18361 } else {
18362 // This is ill-formed, but provide the context that we would have
18363 // declared the function in, if we were permitted to, for error recovery.
18364 DC = FunctionContainingLocalClass;
18365 }
18366 adjustContextForLocalExternDecl(DC);
18367
18368 // - There's no scope specifier, in which case we just go to the
18369 // appropriate scope and look for a function or function template
18370 // there as appropriate.
18371 } else if (SS.isInvalid() || !SS.isSet()) {
18372 // C++11 [namespace.memdef]p3:
18373 // If the name in a friend declaration is neither qualified nor
18374 // a template-id and the declaration is a function or an
18375 // elaborated-type-specifier, the lookup to determine whether
18376 // the entity has been previously declared shall not consider
18377 // any scopes outside the innermost enclosing namespace.
18378
18379 // Find the appropriate context according to the above.
18380 DC = CurContext;
18381
18382 // Skip class contexts. If someone can cite chapter and verse
18383 // for this behavior, that would be nice --- it's what GCC and
18384 // EDG do, and it seems like a reasonable intent, but the spec
18385 // really only says that checks for unqualified existing
18386 // declarations should stop at the nearest enclosing namespace,
18387 // not that they should only consider the nearest enclosing
18388 // namespace.
18389 while (DC->isRecord())
18390 DC = DC->getParent();
18391
18392 DeclContext *LookupDC = DC->getNonTransparentContext();
18393 while (true) {
18394 LookupQualifiedName(R&: Previous, LookupCtx: LookupDC);
18395
18396 if (!Previous.empty()) {
18397 DC = LookupDC;
18398 break;
18399 }
18400
18401 if (isTemplateId) {
18402 if (isa<TranslationUnitDecl>(Val: LookupDC)) break;
18403 } else {
18404 if (LookupDC->isFileContext()) break;
18405 }
18406 LookupDC = LookupDC->getParent();
18407 }
18408
18409 DCScope = getScopeForDeclContext(S, DC);
18410
18411 // - There's a non-dependent scope specifier, in which case we
18412 // compute it and do a previous lookup there for a function
18413 // or function template.
18414 } else if (!SS.getScopeRep().isDependent()) {
18415 DC = computeDeclContext(SS);
18416 if (!DC) return nullptr;
18417
18418 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
18419
18420 LookupQualifiedName(R&: Previous, LookupCtx: DC);
18421
18422 // C++ [class.friend]p1: A friend of a class is a function or
18423 // class that is not a member of the class . . .
18424 if (DC->Equals(DC: CurContext))
18425 Diag(Loc: DS.getFriendSpecLoc(),
18426 DiagID: getLangOpts().CPlusPlus11 ?
18427 diag::warn_cxx98_compat_friend_is_member :
18428 diag::err_friend_is_member);
18429
18430 // - There's a scope specifier that does not match any template
18431 // parameter lists, in which case we use some arbitrary context,
18432 // create a method or method template, and wait for instantiation.
18433 // - There's a scope specifier that does match some template
18434 // parameter lists, which we don't handle right now.
18435 } else {
18436 DC = CurContext;
18437 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
18438 }
18439
18440 if (!DC->isRecord()) {
18441 int DiagArg = -1;
18442 switch (D.getName().getKind()) {
18443 case UnqualifiedIdKind::IK_ConstructorTemplateId:
18444 case UnqualifiedIdKind::IK_ConstructorName:
18445 DiagArg = 0;
18446 break;
18447 case UnqualifiedIdKind::IK_DestructorName:
18448 DiagArg = 1;
18449 break;
18450 case UnqualifiedIdKind::IK_ConversionFunctionId:
18451 DiagArg = 2;
18452 break;
18453 case UnqualifiedIdKind::IK_DeductionGuideName:
18454 DiagArg = 3;
18455 break;
18456 case UnqualifiedIdKind::IK_Identifier:
18457 case UnqualifiedIdKind::IK_ImplicitSelfParam:
18458 case UnqualifiedIdKind::IK_LiteralOperatorId:
18459 case UnqualifiedIdKind::IK_OperatorFunctionId:
18460 case UnqualifiedIdKind::IK_TemplateId:
18461 break;
18462 }
18463 // This implies that it has to be an operator or function.
18464 if (DiagArg >= 0) {
18465 Diag(Loc, DiagID: diag::err_introducing_special_friend) << DiagArg;
18466 return nullptr;
18467 }
18468 }
18469
18470 // FIXME: This is an egregious hack to cope with cases where the scope stack
18471 // does not contain the declaration context, i.e., in an out-of-line
18472 // definition of a class.
18473 Scope FakeDCScope(S, Scope::DeclScope, Diags);
18474 if (!DCScope) {
18475 FakeDCScope.setEntity(DC);
18476 DCScope = &FakeDCScope;
18477 }
18478
18479 bool AddToScope = true;
18480 NamedDecl *ND = ActOnFunctionDeclarator(S: DCScope, D, DC, TInfo, Previous,
18481 TemplateParamLists: TemplateParams, AddToScope);
18482 if (!ND) return nullptr;
18483
18484 assert(ND->getLexicalDeclContext() == CurContext);
18485
18486 // If we performed typo correction, we might have added a scope specifier
18487 // and changed the decl context.
18488 DC = ND->getDeclContext();
18489
18490 // Add the function declaration to the appropriate lookup tables,
18491 // adjusting the redeclarations list as necessary. We don't
18492 // want to do this yet if the friending class is dependent.
18493 //
18494 // Also update the scope-based lookup if the target context's
18495 // lookup context is in lexical scope.
18496 if (!CurContext->isDependentContext()) {
18497 DC = DC->getRedeclContext();
18498 DC->makeDeclVisibleInContext(D: ND);
18499 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
18500 PushOnScopeChains(D: ND, S: EnclosingScope, /*AddToContext=*/ false);
18501 }
18502
18503 FriendDecl *FrD = FriendDecl::Create(C&: Context, DC: CurContext,
18504 L: D.getIdentifierLoc(), Friend_: ND,
18505 FriendL: DS.getFriendSpecLoc());
18506 FrD->setAccess(AS_public);
18507 CurContext->addDecl(D: FrD);
18508
18509 if (ND->isInvalidDecl()) {
18510 FrD->setInvalidDecl();
18511 } else {
18512 if (DC->isRecord()) CheckFriendAccess(D: ND);
18513
18514 FunctionDecl *FD;
18515 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(Val: ND))
18516 FD = FTD->getTemplatedDecl();
18517 else
18518 FD = cast<FunctionDecl>(Val: ND);
18519
18520 // C++ [class.friend]p6:
18521 // A function may be defined in a friend declaration of a class if and
18522 // only if the class is a non-local class, and the function name is
18523 // unqualified.
18524 if (D.isFunctionDefinition()) {
18525 // Qualified friend function definition.
18526 if (SS.isNotEmpty()) {
18527 // FIXME: We should only do this if the scope specifier names the
18528 // innermost enclosing namespace; otherwise the fixit changes the
18529 // meaning of the code.
18530 SemaDiagnosticBuilder DB =
18531 Diag(Loc: SS.getRange().getBegin(), DiagID: diag::err_qualified_friend_def);
18532
18533 DB << SS.getScopeRep();
18534 if (DC->isFileContext())
18535 DB << FixItHint::CreateRemoval(RemoveRange: SS.getRange());
18536
18537 // Friend function defined in a local class.
18538 } else if (FunctionContainingLocalClass) {
18539 Diag(Loc: NameInfo.getBeginLoc(), DiagID: diag::err_friend_def_in_local_class);
18540
18541 // Per [basic.pre]p4, a template-id is not a name. Therefore, if we have
18542 // a template-id, the function name is not unqualified because these is
18543 // no name. While the wording requires some reading in-between the
18544 // lines, GCC, MSVC, and EDG all consider a friend function
18545 // specialization definitions to be de facto explicit specialization
18546 // and diagnose them as such.
18547 } else if (isTemplateId) {
18548 Diag(Loc: NameInfo.getBeginLoc(), DiagID: diag::err_friend_specialization_def);
18549 }
18550 }
18551
18552 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
18553 // default argument expression, that declaration shall be a definition
18554 // and shall be the only declaration of the function or function
18555 // template in the translation unit.
18556 if (functionDeclHasDefaultArgument(FD)) {
18557 // We can't look at FD->getPreviousDecl() because it may not have been set
18558 // if we're in a dependent context. If the function is known to be a
18559 // redeclaration, we will have narrowed Previous down to the right decl.
18560 if (D.isRedeclaration()) {
18561 Diag(Loc: FD->getLocation(), DiagID: diag::err_friend_decl_with_def_arg_redeclared);
18562 Diag(Loc: Previous.getRepresentativeDecl()->getLocation(),
18563 DiagID: diag::note_previous_declaration);
18564 } else if (!D.isFunctionDefinition())
18565 Diag(Loc: FD->getLocation(), DiagID: diag::err_friend_decl_with_def_arg_must_be_def);
18566 }
18567
18568 // Mark templated-scope function declarations as unsupported.
18569 if (FD->getNumTemplateParameterLists() && SS.isValid()) {
18570 Diag(Loc: FD->getLocation(), DiagID: diag::warn_template_qualified_friend_unsupported)
18571 << SS.getScopeRep() << SS.getRange()
18572 << cast<CXXRecordDecl>(Val: CurContext);
18573 FrD->setUnsupportedFriend(true);
18574 }
18575 }
18576
18577 warnOnReservedIdentifier(D: ND);
18578
18579 return ND;
18580}
18581
18582void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc,
18583 StringLiteral *Message) {
18584 AdjustDeclIfTemplate(Decl&: Dcl);
18585
18586 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Val: Dcl);
18587 if (!Fn) {
18588 Diag(Loc: DelLoc, DiagID: diag::err_deleted_non_function);
18589 return;
18590 }
18591
18592 // Deleted function does not have a body.
18593 Fn->setWillHaveBody(false);
18594
18595 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
18596 // Don't consider the implicit declaration we generate for explicit
18597 // specializations. FIXME: Do not generate these implicit declarations.
18598 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
18599 Prev->getPreviousDecl()) &&
18600 !Prev->isDefined()) {
18601 Diag(Loc: DelLoc, DiagID: diag::err_deleted_decl_not_first);
18602 Diag(Loc: Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
18603 DiagID: Prev->isImplicit() ? diag::note_previous_implicit_declaration
18604 : diag::note_previous_declaration);
18605 // We can't recover from this; the declaration might have already
18606 // been used.
18607 Fn->setInvalidDecl();
18608 return;
18609 }
18610
18611 // To maintain the invariant that functions are only deleted on their first
18612 // declaration, mark the implicitly-instantiated declaration of the
18613 // explicitly-specialized function as deleted instead of marking the
18614 // instantiated redeclaration.
18615 Fn = Fn->getCanonicalDecl();
18616 }
18617
18618 // dllimport/dllexport cannot be deleted.
18619 if (const InheritableAttr *DLLAttr = getDLLAttr(D: Fn)) {
18620 Diag(Loc: Fn->getLocation(), DiagID: diag::err_attribute_dll_deleted) << DLLAttr;
18621 Fn->setInvalidDecl();
18622 }
18623
18624 // C++11 [basic.start.main]p3:
18625 // A program that defines main as deleted [...] is ill-formed.
18626 if (Fn->isMain())
18627 Diag(Loc: DelLoc, DiagID: diag::err_deleted_main);
18628
18629 // C++11 [dcl.fct.def.delete]p4:
18630 // A deleted function is implicitly inline.
18631 Fn->setImplicitlyInline();
18632 Fn->setDeletedAsWritten(D: true, Message);
18633}
18634
18635void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
18636 if (!Dcl || Dcl->isInvalidDecl())
18637 return;
18638
18639 auto *FD = dyn_cast<FunctionDecl>(Val: Dcl);
18640 if (!FD) {
18641 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Val: Dcl)) {
18642 if (getDefaultedFunctionKind(FD: FTD->getTemplatedDecl()).isComparison()) {
18643 Diag(Loc: DefaultLoc, DiagID: diag::err_defaulted_comparison_template);
18644 return;
18645 }
18646 }
18647
18648 Diag(Loc: DefaultLoc, DiagID: diag::err_default_special_members)
18649 << getLangOpts().CPlusPlus20;
18650 return;
18651 }
18652
18653 // Reject if this can't possibly be a defaultable function.
18654 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
18655 if (!DefKind &&
18656 // A dependent function that doesn't locally look defaultable can
18657 // still instantiate to a defaultable function if it's a constructor
18658 // or assignment operator.
18659 (!FD->isDependentContext() ||
18660 (!isa<CXXConstructorDecl>(Val: FD) &&
18661 FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) {
18662 Diag(Loc: DefaultLoc, DiagID: diag::err_default_special_members)
18663 << getLangOpts().CPlusPlus20;
18664 return;
18665 }
18666
18667 // Issue compatibility warning. We already warned if the operator is
18668 // 'operator<=>' when parsing the '<=>' token.
18669 if (DefKind.isComparison() &&
18670 DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) {
18671 Diag(Loc: DefaultLoc, DiagID: getLangOpts().CPlusPlus20
18672 ? diag::warn_cxx17_compat_defaulted_comparison
18673 : diag::ext_defaulted_comparison);
18674 }
18675
18676 FD->setDefaulted();
18677 FD->setExplicitlyDefaulted();
18678 FD->setDefaultLoc(DefaultLoc);
18679
18680 // Defer checking functions that are defaulted in a dependent context.
18681 if (FD->isDependentContext())
18682 return;
18683
18684 // Unset that we will have a body for this function. We might not,
18685 // if it turns out to be trivial, and we don't need this marking now
18686 // that we've marked it as defaulted.
18687 FD->setWillHaveBody(false);
18688
18689 if (DefKind.isComparison()) {
18690 // If this comparison's defaulting occurs within the definition of its
18691 // lexical class context, we have to do the checking when complete.
18692 if (auto const *RD = dyn_cast<CXXRecordDecl>(Val: FD->getLexicalDeclContext()))
18693 if (!RD->isCompleteDefinition())
18694 return;
18695 }
18696
18697 // If this member fn was defaulted on its first declaration, we will have
18698 // already performed the checking in CheckCompletedCXXClass. Such a
18699 // declaration doesn't trigger an implicit definition.
18700 if (isa<CXXMethodDecl>(Val: FD)) {
18701 const FunctionDecl *Primary = FD;
18702 if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
18703 // Ask the template instantiation pattern that actually had the
18704 // '= default' on it.
18705 Primary = Pattern;
18706 if (Primary->getCanonicalDecl()->isDefaulted())
18707 return;
18708 }
18709
18710 if (DefKind.isComparison()) {
18711 if (CheckExplicitlyDefaultedComparison(S: nullptr, FD, DCK: DefKind.asComparison()))
18712 FD->setInvalidDecl();
18713 else
18714 DefineDefaultedComparison(UseLoc: DefaultLoc, FD, DCK: DefKind.asComparison());
18715 } else {
18716 auto *MD = cast<CXXMethodDecl>(Val: FD);
18717
18718 if (CheckExplicitlyDefaultedSpecialMember(MD, CSM: DefKind.asSpecialMember(),
18719 DefaultLoc))
18720 MD->setInvalidDecl();
18721 else
18722 DefineDefaultedFunction(S&: *this, FD: MD, DefaultLoc);
18723 }
18724}
18725
18726static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
18727 for (Stmt *SubStmt : S->children()) {
18728 if (!SubStmt)
18729 continue;
18730 if (isa<ReturnStmt>(Val: SubStmt))
18731 Self.Diag(Loc: SubStmt->getBeginLoc(),
18732 DiagID: diag::err_return_in_constructor_handler);
18733 if (!isa<Expr>(Val: SubStmt))
18734 SearchForReturnInStmt(Self, S: SubStmt);
18735 }
18736}
18737
18738void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
18739 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
18740 CXXCatchStmt *Handler = TryBlock->getHandler(i: I);
18741 SearchForReturnInStmt(Self&: *this, S: Handler);
18742 }
18743}
18744
18745void Sema::SetFunctionBodyKind(Decl *D, SourceLocation Loc, FnBodyKind BodyKind,
18746 StringLiteral *DeletedMessage) {
18747 switch (BodyKind) {
18748 case FnBodyKind::Delete:
18749 SetDeclDeleted(Dcl: D, DelLoc: Loc, Message: DeletedMessage);
18750 break;
18751 case FnBodyKind::Default:
18752 SetDeclDefaulted(Dcl: D, DefaultLoc: Loc);
18753 break;
18754 case FnBodyKind::Other:
18755 llvm_unreachable(
18756 "Parsed function body should be '= delete;' or '= default;'");
18757 }
18758}
18759
18760bool Sema::CheckOverridingFunctionAttributes(CXXMethodDecl *New,
18761 const CXXMethodDecl *Old) {
18762 const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
18763 const auto *OldFT = Old->getType()->castAs<FunctionProtoType>();
18764
18765 if (OldFT->hasExtParameterInfos()) {
18766 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
18767 // A parameter of the overriding method should be annotated with noescape
18768 // if the corresponding parameter of the overridden method is annotated.
18769 if (OldFT->getExtParameterInfo(I).isNoEscape() &&
18770 !NewFT->getExtParameterInfo(I).isNoEscape()) {
18771 Diag(Loc: New->getParamDecl(i: I)->getLocation(),
18772 DiagID: diag::warn_overriding_method_missing_noescape);
18773 Diag(Loc: Old->getParamDecl(i: I)->getLocation(),
18774 DiagID: diag::note_overridden_marked_noescape);
18775 }
18776 }
18777
18778 // SME attributes must match when overriding a function declaration.
18779 if (IsInvalidSMECallConversion(FromType: Old->getType(), ToType: New->getType())) {
18780 Diag(Loc: New->getLocation(), DiagID: diag::err_conflicting_overriding_attributes)
18781 << New << New->getType() << Old->getType();
18782 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function);
18783 return true;
18784 }
18785
18786 // Virtual overrides must have the same code_seg.
18787 const auto *OldCSA = Old->getAttr<CodeSegAttr>();
18788 const auto *NewCSA = New->getAttr<CodeSegAttr>();
18789 if ((NewCSA || OldCSA) &&
18790 (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
18791 Diag(Loc: New->getLocation(), DiagID: diag::err_mismatched_code_seg_override);
18792 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
18793 return true;
18794 }
18795
18796 // Virtual overrides: check for matching effects.
18797 if (Context.hasAnyFunctionEffects()) {
18798 const auto OldFX = Old->getFunctionEffects();
18799 const auto NewFXOrig = New->getFunctionEffects();
18800
18801 if (OldFX != NewFXOrig) {
18802 FunctionEffectSet NewFX(NewFXOrig);
18803 const auto Diffs = FunctionEffectDiffVector(OldFX, NewFX);
18804 FunctionEffectSet::Conflicts Errs;
18805 for (const auto &Diff : Diffs) {
18806 switch (Diff.shouldDiagnoseMethodOverride(OldMethod: *Old, OldFX, NewMethod: *New, NewFX)) {
18807 case FunctionEffectDiff::OverrideResult::NoAction:
18808 break;
18809 case FunctionEffectDiff::OverrideResult::Warn:
18810 Diag(Loc: New->getLocation(), DiagID: diag::warn_conflicting_func_effect_override)
18811 << Diff.effectName();
18812 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function)
18813 << Old->getReturnTypeSourceRange();
18814 break;
18815 case FunctionEffectDiff::OverrideResult::Merge: {
18816 NewFX.insert(NewEC: Diff.Old.value(), Errs);
18817 const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
18818 FunctionProtoType::ExtProtoInfo EPI = NewFT->getExtProtoInfo();
18819 EPI.FunctionEffects = FunctionEffectsRef(NewFX);
18820 QualType ModQT = Context.getFunctionType(ResultTy: NewFT->getReturnType(),
18821 Args: NewFT->getParamTypes(), EPI);
18822 New->setType(ModQT);
18823 if (Errs.empty()) {
18824 // A warning here is somewhat pedantic. Skip this if there was
18825 // already a merge conflict, which is more serious.
18826 Diag(Loc: New->getLocation(), DiagID: diag::warn_mismatched_func_effect_override)
18827 << Diff.effectName();
18828 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function)
18829 << Old->getReturnTypeSourceRange();
18830 }
18831 break;
18832 }
18833 }
18834 }
18835 if (!Errs.empty())
18836 diagnoseFunctionEffectMergeConflicts(Errs, NewLoc: New->getLocation(),
18837 OldLoc: Old->getLocation());
18838 }
18839 }
18840
18841 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
18842
18843 // If the calling conventions match, everything is fine
18844 if (NewCC == OldCC)
18845 return false;
18846
18847 // If the calling conventions mismatch because the new function is static,
18848 // suppress the calling convention mismatch error; the error about static
18849 // function override (err_static_overrides_virtual from
18850 // Sema::CheckFunctionDeclaration) is more clear.
18851 if (New->getStorageClass() == SC_Static)
18852 return false;
18853
18854 Diag(Loc: New->getLocation(),
18855 DiagID: diag::err_conflicting_overriding_cc_attributes)
18856 << New->getDeclName() << New->getType() << Old->getType();
18857 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function);
18858 return true;
18859}
18860
18861bool Sema::CheckExplicitObjectOverride(CXXMethodDecl *New,
18862 const CXXMethodDecl *Old) {
18863 // CWG2553
18864 // A virtual function shall not be an explicit object member function.
18865 if (!New->isExplicitObjectMemberFunction())
18866 return true;
18867 Diag(Loc: New->getParamDecl(i: 0)->getBeginLoc(),
18868 DiagID: diag::err_explicit_object_parameter_nonmember)
18869 << New->getSourceRange() << /*virtual*/ 1 << /*IsLambda*/ false;
18870 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function);
18871 New->setInvalidDecl();
18872 return false;
18873}
18874
18875bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
18876 const CXXMethodDecl *Old) {
18877 QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType();
18878 QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType();
18879
18880 if (Context.hasSameType(T1: NewTy, T2: OldTy) ||
18881 NewTy->isDependentType() || OldTy->isDependentType())
18882 return false;
18883
18884 // Check if the return types are covariant
18885 QualType NewClassTy, OldClassTy;
18886
18887 /// Both types must be pointers or references to classes.
18888 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
18889 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
18890 NewClassTy = NewPT->getPointeeType();
18891 OldClassTy = OldPT->getPointeeType();
18892 }
18893 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
18894 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
18895 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
18896 NewClassTy = NewRT->getPointeeType();
18897 OldClassTy = OldRT->getPointeeType();
18898 }
18899 }
18900 }
18901
18902 // The return types aren't either both pointers or references to a class type.
18903 if (NewClassTy.isNull() || !NewClassTy->isStructureOrClassType()) {
18904 Diag(Loc: New->getLocation(),
18905 DiagID: diag::err_different_return_type_for_overriding_virtual_function)
18906 << New->getDeclName() << NewTy << OldTy
18907 << New->getReturnTypeSourceRange();
18908 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function)
18909 << Old->getReturnTypeSourceRange();
18910
18911 return true;
18912 }
18913
18914 if (!Context.hasSameUnqualifiedType(T1: NewClassTy, T2: OldClassTy)) {
18915 // C++14 [class.virtual]p8:
18916 // If the class type in the covariant return type of D::f differs from
18917 // that of B::f, the class type in the return type of D::f shall be
18918 // complete at the point of declaration of D::f or shall be the class
18919 // type D.
18920 if (const auto *RD = NewClassTy->getAsCXXRecordDecl()) {
18921 if (!RD->isBeingDefined() &&
18922 RequireCompleteType(Loc: New->getLocation(), T: NewClassTy,
18923 DiagID: diag::err_covariant_return_incomplete,
18924 Args: New->getDeclName()))
18925 return true;
18926 }
18927
18928 // Check if the new class derives from the old class.
18929 if (!IsDerivedFrom(Loc: New->getLocation(), Derived: NewClassTy, Base: OldClassTy)) {
18930 Diag(Loc: New->getLocation(), DiagID: diag::err_covariant_return_not_derived)
18931 << New->getDeclName() << NewTy << OldTy
18932 << New->getReturnTypeSourceRange();
18933 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function)
18934 << Old->getReturnTypeSourceRange();
18935 return true;
18936 }
18937
18938 // Check if we the conversion from derived to base is valid.
18939 if (CheckDerivedToBaseConversion(
18940 Derived: NewClassTy, Base: OldClassTy,
18941 InaccessibleBaseID: diag::err_covariant_return_inaccessible_base,
18942 AmbiguousBaseConvID: diag::err_covariant_return_ambiguous_derived_to_base_conv,
18943 Loc: New->getLocation(), Range: New->getReturnTypeSourceRange(),
18944 Name: New->getDeclName(), BasePath: nullptr)) {
18945 // FIXME: this note won't trigger for delayed access control
18946 // diagnostics, and it's impossible to get an undelayed error
18947 // here from access control during the original parse because
18948 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
18949 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function)
18950 << Old->getReturnTypeSourceRange();
18951 return true;
18952 }
18953 }
18954
18955 // The qualifiers of the return types must be the same.
18956 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
18957 Diag(Loc: New->getLocation(),
18958 DiagID: diag::err_covariant_return_type_different_qualifications)
18959 << New->getDeclName() << NewTy << OldTy
18960 << New->getReturnTypeSourceRange();
18961 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function)
18962 << Old->getReturnTypeSourceRange();
18963 return true;
18964 }
18965
18966
18967 // The new class type must have the same or less qualifiers as the old type.
18968 if (!OldClassTy.isAtLeastAsQualifiedAs(other: NewClassTy, Ctx: getASTContext())) {
18969 Diag(Loc: New->getLocation(),
18970 DiagID: diag::err_covariant_return_type_class_type_not_same_or_less_qualified)
18971 << New->getDeclName() << NewTy << OldTy
18972 << New->getReturnTypeSourceRange();
18973 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function)
18974 << Old->getReturnTypeSourceRange();
18975 return true;
18976 }
18977
18978 return false;
18979}
18980
18981bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
18982 SourceLocation EndLoc = InitRange.getEnd();
18983 if (EndLoc.isValid())
18984 Method->setRangeEnd(EndLoc);
18985
18986 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
18987 Method->setIsPureVirtual();
18988 return false;
18989 }
18990
18991 if (!Method->isInvalidDecl())
18992 Diag(Loc: Method->getLocation(), DiagID: diag::err_non_virtual_pure)
18993 << Method->getDeclName() << InitRange;
18994 return true;
18995}
18996
18997void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
18998 if (D->getFriendObjectKind())
18999 Diag(Loc: D->getLocation(), DiagID: diag::err_pure_friend);
19000 else if (auto *M = dyn_cast<CXXMethodDecl>(Val: D))
19001 CheckPureMethod(Method: M, InitRange: ZeroLoc);
19002 else
19003 Diag(Loc: D->getLocation(), DiagID: diag::err_illegal_initializer);
19004}
19005
19006/// Invoked when we are about to parse an initializer for the declaration
19007/// 'Dcl'.
19008///
19009/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
19010/// static data member of class X, names should be looked up in the scope of
19011/// class X. If the declaration had a scope specifier, a scope will have
19012/// been created and passed in for this purpose. Otherwise, S will be null.
19013void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
19014 assert(D && !D->isInvalidDecl());
19015
19016 // We will always have a nested name specifier here, but this declaration
19017 // might not be out of line if the specifier names the current namespace:
19018 // extern int n;
19019 // int ::n = 0;
19020 if (S && D->isOutOfLine())
19021 EnterDeclaratorContext(S, DC: D->getDeclContext());
19022
19023 PushExpressionEvaluationContext(
19024 NewContext: ExpressionEvaluationContext::PotentiallyEvaluated, LambdaContextDecl: D,
19025 Type: ExpressionEvaluationContextRecord::EK_VariableInit);
19026}
19027
19028void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
19029 assert(D);
19030
19031 if (S && D->isOutOfLine())
19032 ExitDeclaratorContext(S);
19033
19034 PopExpressionEvaluationContext();
19035}
19036
19037DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
19038 // C++ 6.4p2:
19039 // The declarator shall not specify a function or an array.
19040 // The type-specifier-seq shall not contain typedef and shall not declare a
19041 // new class or enumeration.
19042 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
19043 "Parser allowed 'typedef' as storage class of condition decl.");
19044
19045 Decl *Dcl = ActOnDeclarator(S, D);
19046 if (!Dcl)
19047 return true;
19048
19049 if (isa<FunctionDecl>(Val: Dcl)) { // The declarator shall not specify a function.
19050 Diag(Loc: Dcl->getLocation(), DiagID: diag::err_invalid_use_of_function_type)
19051 << D.getSourceRange();
19052 return true;
19053 }
19054
19055 if (auto *VD = dyn_cast<VarDecl>(Val: Dcl))
19056 VD->setCXXCondDecl();
19057
19058 return Dcl;
19059}
19060
19061void Sema::LoadExternalVTableUses() {
19062 if (!ExternalSource)
19063 return;
19064
19065 SmallVector<ExternalVTableUse, 4> VTables;
19066 ExternalSource->ReadUsedVTables(VTables);
19067 SmallVector<VTableUse, 4> NewUses;
19068 for (const ExternalVTableUse &VTable : VTables) {
19069 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos =
19070 VTablesUsed.find(Val: VTable.Record);
19071 // Even if a definition wasn't required before, it may be required now.
19072 if (Pos != VTablesUsed.end()) {
19073 if (!Pos->second && VTable.DefinitionRequired)
19074 Pos->second = true;
19075 continue;
19076 }
19077
19078 VTablesUsed[VTable.Record] = VTable.DefinitionRequired;
19079 NewUses.push_back(Elt: VTableUse(VTable.Record, VTable.Location));
19080 }
19081
19082 VTableUses.insert(I: VTableUses.begin(), From: NewUses.begin(), To: NewUses.end());
19083}
19084
19085void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
19086 bool DefinitionRequired) {
19087 // Ignore any vtable uses in unevaluated operands or for classes that do
19088 // not have a vtable.
19089 if (!Class->isDynamicClass() || Class->isDependentContext() ||
19090 CurContext->isDependentContext() || isUnevaluatedContext())
19091 return;
19092 // Do not mark as used if compiling for the device outside of the target
19093 // region.
19094 if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice &&
19095 !OpenMP().isInOpenMPDeclareTargetContext() &&
19096 !OpenMP().isInOpenMPTargetExecutionDirective()) {
19097 if (!DefinitionRequired)
19098 MarkVirtualMembersReferenced(Loc, RD: Class);
19099 return;
19100 }
19101
19102 // Try to insert this class into the map.
19103 LoadExternalVTableUses();
19104 Class = Class->getCanonicalDecl();
19105 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
19106 Pos = VTablesUsed.insert(KV: std::make_pair(x&: Class, y&: DefinitionRequired));
19107 if (!Pos.second) {
19108 // If we already had an entry, check to see if we are promoting this vtable
19109 // to require a definition. If so, we need to reappend to the VTableUses
19110 // list, since we may have already processed the first entry.
19111 if (DefinitionRequired && !Pos.first->second) {
19112 Pos.first->second = true;
19113 } else {
19114 // Otherwise, we can early exit.
19115 return;
19116 }
19117 } else {
19118 // The Microsoft ABI requires that we perform the destructor body
19119 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
19120 // the deleting destructor is emitted with the vtable, not with the
19121 // destructor definition as in the Itanium ABI.
19122 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
19123 CXXDestructorDecl *DD = Class->getDestructor();
19124 if (DD && DD->isVirtual() && !DD->isDeleted()) {
19125 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
19126 // If this is an out-of-line declaration, marking it referenced will
19127 // not do anything. Manually call CheckDestructor to look up operator
19128 // delete().
19129 ContextRAII SavedContext(*this, DD);
19130 CheckDestructor(Destructor: DD);
19131 if (!DD->getOperatorDelete())
19132 DD->setInvalidDecl();
19133 } else {
19134 MarkFunctionReferenced(Loc, Func: Class->getDestructor());
19135 }
19136 }
19137 }
19138 }
19139
19140 // Local classes need to have their virtual members marked
19141 // immediately. For all other classes, we mark their virtual members
19142 // at the end of the translation unit.
19143 if (Class->isLocalClass())
19144 MarkVirtualMembersReferenced(Loc, RD: Class->getDefinition());
19145 else
19146 VTableUses.push_back(Elt: std::make_pair(x&: Class, y&: Loc));
19147}
19148
19149bool Sema::DefineUsedVTables() {
19150 LoadExternalVTableUses();
19151 if (VTableUses.empty())
19152 return false;
19153
19154 // Note: The VTableUses vector could grow as a result of marking
19155 // the members of a class as "used", so we check the size each
19156 // time through the loop and prefer indices (which are stable) to
19157 // iterators (which are not).
19158 bool DefinedAnything = false;
19159 for (unsigned I = 0; I != VTableUses.size(); ++I) {
19160 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
19161 if (!Class)
19162 continue;
19163 TemplateSpecializationKind ClassTSK =
19164 Class->getTemplateSpecializationKind();
19165
19166 SourceLocation Loc = VTableUses[I].second;
19167
19168 bool DefineVTable = true;
19169
19170 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(RD: Class);
19171 // V-tables for non-template classes with an owning module are always
19172 // uniquely emitted in that module.
19173 if (Class->isInCurrentModuleUnit()) {
19174 DefineVTable = true;
19175 } else if (KeyFunction && !KeyFunction->hasBody()) {
19176 // If this class has a key function, but that key function is
19177 // defined in another translation unit, we don't need to emit the
19178 // vtable even though we're using it.
19179 // The key function is in another translation unit.
19180 DefineVTable = false;
19181 TemplateSpecializationKind TSK =
19182 KeyFunction->getTemplateSpecializationKind();
19183 assert(TSK != TSK_ExplicitInstantiationDefinition &&
19184 TSK != TSK_ImplicitInstantiation &&
19185 "Instantiations don't have key functions");
19186 (void)TSK;
19187 } else if (!KeyFunction) {
19188 // If we have a class with no key function that is the subject
19189 // of an explicit instantiation declaration, suppress the
19190 // vtable; it will live with the explicit instantiation
19191 // definition.
19192 bool IsExplicitInstantiationDeclaration =
19193 ClassTSK == TSK_ExplicitInstantiationDeclaration;
19194 for (auto *R : Class->redecls()) {
19195 TemplateSpecializationKind TSK
19196 = cast<CXXRecordDecl>(Val: R)->getTemplateSpecializationKind();
19197 if (TSK == TSK_ExplicitInstantiationDeclaration)
19198 IsExplicitInstantiationDeclaration = true;
19199 else if (TSK == TSK_ExplicitInstantiationDefinition) {
19200 IsExplicitInstantiationDeclaration = false;
19201 break;
19202 }
19203 }
19204
19205 if (IsExplicitInstantiationDeclaration) {
19206 const bool HasExcludeFromExplicitInstantiation =
19207 llvm::any_of(Range: Class->methods(), P: [](CXXMethodDecl *method) {
19208 // If the class has a member function declared with
19209 // `__attribute__((exclude_from_explicit_instantiation))`, the
19210 // explicit instantiation declaration should not suppress emitting
19211 // the vtable, since the corresponding explicit instantiation
19212 // definition might not emit the vtable if a triggering method is
19213 // excluded.
19214 return method->hasAttr<ExcludeFromExplicitInstantiationAttr>();
19215 });
19216 if (!HasExcludeFromExplicitInstantiation)
19217 DefineVTable = false;
19218 }
19219 }
19220
19221 // The exception specifications for all virtual members may be needed even
19222 // if we are not providing an authoritative form of the vtable in this TU.
19223 // We may choose to emit it available_externally anyway.
19224 if (!DefineVTable) {
19225 MarkVirtualMemberExceptionSpecsNeeded(Loc, RD: Class);
19226 continue;
19227 }
19228
19229 // Mark all of the virtual members of this class as referenced, so
19230 // that we can build a vtable. Then, tell the AST consumer that a
19231 // vtable for this class is required.
19232 DefinedAnything = true;
19233 MarkVirtualMembersReferenced(Loc, RD: Class);
19234 CXXRecordDecl *Canonical = Class->getCanonicalDecl();
19235 if (VTablesUsed[Canonical] && !Class->shouldEmitInExternalSource())
19236 Consumer.HandleVTable(RD: Class);
19237
19238 // Warn if we're emitting a weak vtable. The vtable will be weak if there is
19239 // no key function or the key function is inlined. Don't warn in C++ ABIs
19240 // that lack key functions, since the user won't be able to make one.
19241 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
19242 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation &&
19243 ClassTSK != TSK_ExplicitInstantiationDefinition) {
19244 const FunctionDecl *KeyFunctionDef = nullptr;
19245 if (!KeyFunction || (KeyFunction->hasBody(Definition&: KeyFunctionDef) &&
19246 KeyFunctionDef->isInlined()))
19247 Diag(Loc: Class->getLocation(), DiagID: diag::warn_weak_vtable) << Class;
19248 }
19249 }
19250 VTableUses.clear();
19251
19252 return DefinedAnything;
19253}
19254
19255void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
19256 const CXXRecordDecl *RD) {
19257 for (const auto *I : RD->methods())
19258 if (I->isVirtual() && !I->isPureVirtual())
19259 ResolveExceptionSpec(Loc, FPT: I->getType()->castAs<FunctionProtoType>());
19260}
19261
19262void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
19263 const CXXRecordDecl *RD,
19264 bool ConstexprOnly) {
19265 // Mark all functions which will appear in RD's vtable as used.
19266 CXXFinalOverriderMap FinalOverriders;
19267 RD->getFinalOverriders(FinaOverriders&: FinalOverriders);
19268 for (const auto &FinalOverrider : FinalOverriders) {
19269 for (const auto &OverridingMethod : FinalOverrider.second) {
19270 assert(OverridingMethod.second.size() > 0 && "no final overrider");
19271 CXXMethodDecl *Overrider = OverridingMethod.second.front().Method;
19272
19273 // C++ [basic.def.odr]p2:
19274 // [...] A virtual member function is used if it is not pure. [...]
19275 if (!Overrider->isPureVirtual() &&
19276 (!ConstexprOnly || Overrider->isConstexpr()))
19277 MarkFunctionReferenced(Loc, Func: Overrider);
19278 }
19279 }
19280
19281 // Only classes that have virtual bases need a VTT.
19282 if (RD->getNumVBases() == 0)
19283 return;
19284
19285 for (const auto &I : RD->bases()) {
19286 const auto *Base = I.getType()->castAsCXXRecordDecl();
19287 if (Base->getNumVBases() == 0)
19288 continue;
19289 MarkVirtualMembersReferenced(Loc, RD: Base);
19290 }
19291}
19292
19293static
19294void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
19295 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
19296 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
19297 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
19298 Sema &S) {
19299 if (Ctor->isInvalidDecl())
19300 return;
19301
19302 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
19303
19304 // Target may not be determinable yet, for instance if this is a dependent
19305 // call in an uninstantiated template.
19306 if (Target) {
19307 const FunctionDecl *FNTarget = nullptr;
19308 (void)Target->hasBody(Definition&: FNTarget);
19309 Target = const_cast<CXXConstructorDecl*>(
19310 cast_or_null<CXXConstructorDecl>(Val: FNTarget));
19311 }
19312
19313 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
19314 // Avoid dereferencing a null pointer here.
19315 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
19316
19317 if (!Current.insert(Ptr: Canonical).second)
19318 return;
19319
19320 // We know that beyond here, we aren't chaining into a cycle.
19321 if (!Target || !Target->isDelegatingConstructor() ||
19322 Target->isInvalidDecl() || Valid.count(Ptr: TCanonical)) {
19323 Valid.insert_range(R&: Current);
19324 Current.clear();
19325 // We've hit a cycle.
19326 } else if (TCanonical == Canonical || Invalid.count(Ptr: TCanonical) ||
19327 Current.count(Ptr: TCanonical)) {
19328 // If we haven't diagnosed this cycle yet, do so now.
19329 if (!Invalid.count(Ptr: TCanonical)) {
19330 S.Diag(Loc: (*Ctor->init_begin())->getSourceLocation(),
19331 DiagID: diag::warn_delegating_ctor_cycle)
19332 << Ctor;
19333
19334 // Don't add a note for a function delegating directly to itself.
19335 if (TCanonical != Canonical)
19336 S.Diag(Loc: Target->getLocation(), DiagID: diag::note_it_delegates_to);
19337
19338 CXXConstructorDecl *C = Target;
19339 while (C->getCanonicalDecl() != Canonical) {
19340 const FunctionDecl *FNTarget = nullptr;
19341 (void)C->getTargetConstructor()->hasBody(Definition&: FNTarget);
19342 assert(FNTarget && "Ctor cycle through bodiless function");
19343
19344 C = const_cast<CXXConstructorDecl*>(
19345 cast<CXXConstructorDecl>(Val: FNTarget));
19346 S.Diag(Loc: C->getLocation(), DiagID: diag::note_which_delegates_to);
19347 }
19348 }
19349
19350 Invalid.insert_range(R&: Current);
19351 Current.clear();
19352 } else {
19353 DelegatingCycleHelper(Ctor: Target, Valid, Invalid, Current, S);
19354 }
19355}
19356
19357
19358void Sema::CheckDelegatingCtorCycles() {
19359 llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
19360
19361 for (DelegatingCtorDeclsType::iterator
19362 I = DelegatingCtorDecls.begin(source: ExternalSource.get()),
19363 E = DelegatingCtorDecls.end();
19364 I != E; ++I)
19365 DelegatingCycleHelper(Ctor: *I, Valid, Invalid, Current, S&: *this);
19366
19367 for (CXXConstructorDecl *CI : Invalid)
19368 CI->setInvalidDecl();
19369}
19370
19371namespace {
19372 /// AST visitor that finds references to the 'this' expression.
19373class FindCXXThisExpr : public DynamicRecursiveASTVisitor {
19374 Sema &S;
19375
19376public:
19377 explicit FindCXXThisExpr(Sema &S) : S(S) {}
19378
19379 bool VisitCXXThisExpr(CXXThisExpr *E) override {
19380 S.Diag(Loc: E->getLocation(), DiagID: diag::err_this_static_member_func)
19381 << E->isImplicit();
19382 return false;
19383 }
19384};
19385}
19386
19387bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
19388 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
19389 if (!TSInfo)
19390 return false;
19391
19392 TypeLoc TL = TSInfo->getTypeLoc();
19393 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
19394 if (!ProtoTL)
19395 return false;
19396
19397 // C++11 [expr.prim.general]p3:
19398 // [The expression this] shall not appear before the optional
19399 // cv-qualifier-seq and it shall not appear within the declaration of a
19400 // static member function (although its type and value category are defined
19401 // within a static member function as they are within a non-static member
19402 // function). [ Note: this is because declaration matching does not occur
19403 // until the complete declarator is known. - end note ]
19404 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
19405 FindCXXThisExpr Finder(*this);
19406
19407 // If the return type came after the cv-qualifier-seq, check it now.
19408 if (Proto->hasTrailingReturn() &&
19409 !Finder.TraverseTypeLoc(TL: ProtoTL.getReturnLoc()))
19410 return true;
19411
19412 // Check the exception specification.
19413 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
19414 return true;
19415
19416 // Check the trailing requires clause
19417 if (const AssociatedConstraint &TRC = Method->getTrailingRequiresClause())
19418 if (!Finder.TraverseStmt(S: const_cast<Expr *>(TRC.ConstraintExpr)))
19419 return true;
19420
19421 return checkThisInStaticMemberFunctionAttributes(Method);
19422}
19423
19424bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
19425 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
19426 if (!TSInfo)
19427 return false;
19428
19429 TypeLoc TL = TSInfo->getTypeLoc();
19430 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
19431 if (!ProtoTL)
19432 return false;
19433
19434 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
19435 FindCXXThisExpr Finder(*this);
19436
19437 switch (Proto->getExceptionSpecType()) {
19438 case EST_Unparsed:
19439 case EST_Uninstantiated:
19440 case EST_Unevaluated:
19441 case EST_BasicNoexcept:
19442 case EST_NoThrow:
19443 case EST_DynamicNone:
19444 case EST_MSAny:
19445 case EST_None:
19446 break;
19447
19448 case EST_DependentNoexcept:
19449 case EST_NoexceptFalse:
19450 case EST_NoexceptTrue:
19451 if (!Finder.TraverseStmt(S: Proto->getNoexceptExpr()))
19452 return true;
19453 [[fallthrough]];
19454
19455 case EST_Dynamic:
19456 for (const auto &E : Proto->exceptions()) {
19457 if (!Finder.TraverseType(T: E))
19458 return true;
19459 }
19460 break;
19461 }
19462
19463 return false;
19464}
19465
19466bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
19467 FindCXXThisExpr Finder(*this);
19468
19469 // Check attributes.
19470 for (const auto *A : Method->attrs()) {
19471 // FIXME: This should be emitted by tblgen.
19472 Expr *Arg = nullptr;
19473 ArrayRef<Expr *> Args;
19474 if (const auto *G = dyn_cast<GuardedByAttr>(Val: A))
19475 Args = llvm::ArrayRef(G->args_begin(), G->args_size());
19476 else if (const auto *G = dyn_cast<PtGuardedByAttr>(Val: A))
19477 Args = llvm::ArrayRef(G->args_begin(), G->args_size());
19478 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(Val: A))
19479 Args = llvm::ArrayRef(AA->args_begin(), AA->args_size());
19480 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(Val: A))
19481 Args = llvm::ArrayRef(AB->args_begin(), AB->args_size());
19482 else if (const auto *LR = dyn_cast<LockReturnedAttr>(Val: A))
19483 Arg = LR->getArg();
19484 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(Val: A))
19485 Args = llvm::ArrayRef(LE->args_begin(), LE->args_size());
19486 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(Val: A))
19487 Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());
19488 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(Val: A))
19489 Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());
19490 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(Val: A)) {
19491 Arg = AC->getSuccessValue();
19492 Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());
19493 } else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(Val: A))
19494 Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());
19495
19496 if (Arg && !Finder.TraverseStmt(S: Arg))
19497 return true;
19498
19499 for (Expr *A : Args) {
19500 if (!Finder.TraverseStmt(S: A))
19501 return true;
19502 }
19503 }
19504
19505 return false;
19506}
19507
19508void Sema::checkExceptionSpecification(
19509 bool IsTopLevel, ExceptionSpecificationType EST,
19510 ArrayRef<ParsedType> DynamicExceptions,
19511 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
19512 SmallVectorImpl<QualType> &Exceptions,
19513 FunctionProtoType::ExceptionSpecInfo &ESI) {
19514 Exceptions.clear();
19515 ESI.Type = EST;
19516 if (EST == EST_Dynamic) {
19517 Exceptions.reserve(N: DynamicExceptions.size());
19518 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
19519 // FIXME: Preserve type source info.
19520 QualType ET = GetTypeFromParser(Ty: DynamicExceptions[ei]);
19521
19522 if (IsTopLevel) {
19523 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
19524 collectUnexpandedParameterPacks(T: ET, Unexpanded);
19525 if (!Unexpanded.empty()) {
19526 DiagnoseUnexpandedParameterPacks(
19527 Loc: DynamicExceptionRanges[ei].getBegin(), UPPC: UPPC_ExceptionType,
19528 Unexpanded);
19529 continue;
19530 }
19531 }
19532
19533 // Check that the type is valid for an exception spec, and
19534 // drop it if not.
19535 if (!CheckSpecifiedExceptionType(T&: ET, Range: DynamicExceptionRanges[ei]))
19536 Exceptions.push_back(Elt: ET);
19537 }
19538 ESI.Exceptions = Exceptions;
19539 return;
19540 }
19541
19542 if (isComputedNoexcept(ESpecType: EST)) {
19543 assert((NoexceptExpr->isTypeDependent() ||
19544 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
19545 Context.BoolTy) &&
19546 "Parser should have made sure that the expression is boolean");
19547 if (IsTopLevel && DiagnoseUnexpandedParameterPack(E: NoexceptExpr)) {
19548 ESI.Type = EST_BasicNoexcept;
19549 return;
19550 }
19551
19552 ESI.NoexceptExpr = NoexceptExpr;
19553 return;
19554 }
19555}
19556
19557void Sema::actOnDelayedExceptionSpecification(
19558 Decl *D, ExceptionSpecificationType EST, SourceRange SpecificationRange,
19559 ArrayRef<ParsedType> DynamicExceptions,
19560 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr) {
19561 if (!D)
19562 return;
19563
19564 // Dig out the function we're referring to.
19565 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(Val: D))
19566 D = FTD->getTemplatedDecl();
19567
19568 FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D);
19569 if (!FD)
19570 return;
19571
19572 // Check the exception specification.
19573 llvm::SmallVector<QualType, 4> Exceptions;
19574 FunctionProtoType::ExceptionSpecInfo ESI;
19575 checkExceptionSpecification(/*IsTopLevel=*/true, EST, DynamicExceptions,
19576 DynamicExceptionRanges, NoexceptExpr, Exceptions,
19577 ESI);
19578
19579 // Update the exception specification on the function type.
19580 Context.adjustExceptionSpec(FD, ESI, /*AsWritten=*/true);
19581
19582 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: D)) {
19583 if (MD->isStatic())
19584 checkThisInStaticMemberFunctionExceptionSpec(Method: MD);
19585
19586 if (MD->isVirtual()) {
19587 // Check overrides, which we previously had to delay.
19588 for (const CXXMethodDecl *O : MD->overridden_methods())
19589 CheckOverridingFunctionExceptionSpec(New: MD, Old: O);
19590 }
19591 }
19592}
19593
19594/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
19595///
19596MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
19597 SourceLocation DeclStart, Declarator &D,
19598 Expr *BitWidth,
19599 InClassInitStyle InitStyle,
19600 AccessSpecifier AS,
19601 const ParsedAttr &MSPropertyAttr) {
19602 const IdentifierInfo *II = D.getIdentifier();
19603 if (!II) {
19604 Diag(Loc: DeclStart, DiagID: diag::err_anonymous_property);
19605 return nullptr;
19606 }
19607 SourceLocation Loc = D.getIdentifierLoc();
19608
19609 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
19610 QualType T = TInfo->getType();
19611 if (getLangOpts().CPlusPlus) {
19612 CheckExtraCXXDefaultArguments(D);
19613
19614 if (DiagnoseUnexpandedParameterPack(Loc: D.getIdentifierLoc(), T: TInfo,
19615 UPPC: UPPC_DataMemberType)) {
19616 D.setInvalidType();
19617 T = Context.IntTy;
19618 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
19619 }
19620 }
19621
19622 DiagnoseFunctionSpecifiers(DS: D.getDeclSpec());
19623
19624 if (D.getDeclSpec().isInlineSpecified())
19625 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(), DiagID: diag::err_inline_non_function)
19626 << getLangOpts().CPlusPlus17;
19627 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
19628 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
19629 DiagID: diag::err_invalid_thread)
19630 << DeclSpec::getSpecifierName(S: TSCS);
19631
19632 // Check to see if this name was declared as a member previously
19633 NamedDecl *PrevDecl = nullptr;
19634 LookupResult Previous(*this, II, Loc, LookupMemberName,
19635 RedeclarationKind::ForVisibleRedeclaration);
19636 LookupName(R&: Previous, S);
19637 switch (Previous.getResultKind()) {
19638 case LookupResultKind::Found:
19639 case LookupResultKind::FoundUnresolvedValue:
19640 PrevDecl = Previous.getAsSingle<NamedDecl>();
19641 break;
19642
19643 case LookupResultKind::FoundOverloaded:
19644 PrevDecl = Previous.getRepresentativeDecl();
19645 break;
19646
19647 case LookupResultKind::NotFound:
19648 case LookupResultKind::NotFoundInCurrentInstantiation:
19649 case LookupResultKind::Ambiguous:
19650 break;
19651 }
19652
19653 if (PrevDecl && PrevDecl->isTemplateParameter()) {
19654 // Maybe we will complain about the shadowed template parameter.
19655 DiagnoseTemplateParameterShadow(Loc: D.getIdentifierLoc(), PrevDecl);
19656 // Just pretend that we didn't see the previous declaration.
19657 PrevDecl = nullptr;
19658 }
19659
19660 if (PrevDecl && !isDeclInScope(D: PrevDecl, Ctx: Record, S))
19661 PrevDecl = nullptr;
19662
19663 SourceLocation TSSL = D.getBeginLoc();
19664 MSPropertyDecl *NewPD =
19665 MSPropertyDecl::Create(C&: Context, DC: Record, L: Loc, N: II, T, TInfo, StartL: TSSL,
19666 Getter: MSPropertyAttr.getPropertyDataGetter(),
19667 Setter: MSPropertyAttr.getPropertyDataSetter());
19668 ProcessDeclAttributes(S: TUScope, D: NewPD, PD: D);
19669 NewPD->setAccess(AS);
19670
19671 if (NewPD->isInvalidDecl())
19672 Record->setInvalidDecl();
19673
19674 if (D.getDeclSpec().isModulePrivateSpecified())
19675 NewPD->setModulePrivate();
19676
19677 if (NewPD->isInvalidDecl() && PrevDecl) {
19678 // Don't introduce NewFD into scope; there's already something
19679 // with the same name in the same scope.
19680 } else if (II) {
19681 PushOnScopeChains(D: NewPD, S);
19682 } else
19683 Record->addDecl(D: NewPD);
19684
19685 return NewPD;
19686}
19687
19688void Sema::ActOnStartFunctionDeclarationDeclarator(
19689 Declarator &Declarator, unsigned TemplateParameterDepth) {
19690 auto &Info = InventedParameterInfos.emplace_back();
19691 TemplateParameterList *ExplicitParams = nullptr;
19692 ArrayRef<TemplateParameterList *> ExplicitLists =
19693 Declarator.getTemplateParameterLists();
19694 if (!ExplicitLists.empty()) {
19695 bool IsMemberSpecialization, IsInvalid;
19696 ExplicitParams = MatchTemplateParametersToScopeSpecifier(
19697 DeclStartLoc: Declarator.getBeginLoc(), DeclLoc: Declarator.getIdentifierLoc(),
19698 SS: Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr,
19699 ParamLists: ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, Invalid&: IsInvalid,
19700 /*SuppressDiagnostic=*/true);
19701 }
19702 // C++23 [dcl.fct]p23:
19703 // An abbreviated function template can have a template-head. The invented
19704 // template-parameters are appended to the template-parameter-list after
19705 // the explicitly declared template-parameters.
19706 //
19707 // A template-head must have one or more template-parameters (read:
19708 // 'template<>' is *not* a template-head). Only append the invented
19709 // template parameters if we matched the nested-name-specifier to a non-empty
19710 // TemplateParameterList.
19711 if (ExplicitParams && !ExplicitParams->empty()) {
19712 Info.AutoTemplateParameterDepth = ExplicitParams->getDepth();
19713 llvm::append_range(C&: Info.TemplateParams, R&: *ExplicitParams);
19714 Info.NumExplicitTemplateParams = ExplicitParams->size();
19715 } else {
19716 Info.AutoTemplateParameterDepth = TemplateParameterDepth;
19717 Info.NumExplicitTemplateParams = 0;
19718 }
19719}
19720
19721void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator &Declarator) {
19722 auto &FSI = InventedParameterInfos.back();
19723 if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) {
19724 if (FSI.NumExplicitTemplateParams != 0) {
19725 TemplateParameterList *ExplicitParams =
19726 Declarator.getTemplateParameterLists().back();
19727 Declarator.setInventedTemplateParameterList(
19728 TemplateParameterList::Create(
19729 C: Context, TemplateLoc: ExplicitParams->getTemplateLoc(),
19730 LAngleLoc: ExplicitParams->getLAngleLoc(), Params: FSI.TemplateParams,
19731 RAngleLoc: ExplicitParams->getRAngleLoc(),
19732 RequiresClause: ExplicitParams->getRequiresClause()));
19733 } else {
19734 Declarator.setInventedTemplateParameterList(TemplateParameterList::Create(
19735 C: Context, TemplateLoc: Declarator.getBeginLoc(), LAngleLoc: SourceLocation(),
19736 Params: FSI.TemplateParams, RAngleLoc: Declarator.getEndLoc(),
19737 /*RequiresClause=*/nullptr));
19738 }
19739 }
19740 InventedParameterInfos.pop_back();
19741}
19742