Debian Codegraph @

clang/lib/Sema/SemaDeclCXX.cpp

raw
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
60 using namespace clang;
61
62 //===----------------------------------------------------------------------===//
63 // CheckDefaultArgumentVisitor
64 //===----------------------------------------------------------------------===//
65
66 namespace {
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.
72 class CheckDefaultArgumentVisitor
73 : public ConstStmtVisitor<CheckDefaultArgumentVisitor, bool> {
74 Sema &S;
75 const Expr *DefaultArg;
76
77 public:
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.
89 bool CheckDefaultArgumentVisitor::VisitExpr(const Expr *Node) {
90 bool IsInvalid = false;
91 for (const Stmt *SubStmt : Node->children())
92 if (SubStmt)
93 IsInvalid |= Visit(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.
100 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(const DeclRefExpr *DRE) {
101 const ValueDecl *Decl = dyn_cast<ValueDecl>(DRE->getDecl());
102
103 if (!isa<VarDecl, BindingDecl>(Decl))
104 return false;
105
106 if (const auto *Param = dyn_cast<ParmVarDecl>(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(DRE->getBeginLoc(),
117 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(DRE->getBeginLoc(),
134 diag::err_param_default_argument_references_local)
135 << Decl << DefaultArg->getSourceRange();
136 }
137 return false;
138 }
139
140 /// VisitCXXThisExpr - Visit a C++ "this" expression.
141 bool 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(ThisE->getBeginLoc(),
146 diag::err_param_default_argument_references_this)
147 << ThisE->getSourceRange();
148 }
149
150 bool 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>(E)) {
156 E = OVE->getSourceExpr();
157 assert(E && "pseudo-object binding without source expression?");
158 }
159
160 Invalid |= Visit(E);
161 }
162 return Invalid;
163 }
164
165 bool 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(&LC))
174 return S.Diag(LC.getLocation(), diag::err_lambda_capture_default_arg);
175 // Init captures are always VarDecl.
176 auto *D = cast<VarDecl>(LC.getCapturedVar());
177 Invalid |= Visit(D->getInit());
178 }
179 return Invalid;
180 }
181 } // namespace
182
183 void
184 Sema::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(CallLoc, 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(Self->Context.getCanonicalType(E)).second)
249 Exceptions.push_back(E);
250 }
251
252 void 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(S))
278 ComputedEST = EST_None;
279 }
280
281 ExprResult Sema::ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
282 SourceLocation EqualLoc) {
283 if (RequireCompleteType(Param->getLocation(), Param->getType(),
284 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 Param);
295 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
296 EqualLoc);
297 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
298 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
299 if (Result.isInvalid())
300 return true;
301 Arg = Result.getAs<Expr>();
302
303 CheckCompletedExpr(Arg, EqualLoc);
304 Arg = MaybeCreateExprWithCleanups(Arg);
305
306 return Arg;
307 }
308
309 void 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(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(InstPos);
324 }
325 }
326
327 void
328 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
329 Expr *DefaultArg) {
330 if (!param || !DefaultArg)
331 return;
332
333 ParmVarDecl *Param = cast<ParmVarDecl>(param);
334 UnparsedDefaultArgLocs.erase(Param);
335
336 // Default arguments are only permitted in C++
337 if (!getLangOpts().CPlusPlus) {
338 Diag(EqualLoc, 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(DefaultArg, 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(EqualLoc, 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, 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(DefaultArg))
367 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
368
369 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
370 }
371
372 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
373 SourceLocation EqualLoc,
374 SourceLocation ArgLoc) {
375 if (!param)
376 return;
377
378 ParmVarDecl *Param = cast<ParmVarDecl>(param);
379 Param->setUnparsedDefaultArg();
380 UnparsedDefaultArgLocs[Param] = ArgLoc;
381 }
382
383 void Sema::ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc,
384 Expr *DefaultArg) {
385 if (!param)
386 return;
387
388 ParmVarDecl *Param = cast<ParmVarDecl>(param);
389 Param->setInvalidDecl();
390 UnparsedDefaultArgLocs.erase(Param);
391 ExprResult RE;
392 if (DefaultArg) {
393 RE = CreateRecoveryExpr(EqualLoc, DefaultArg->getEndLoc(), {DefaultArg},
394 Param->getType().getNonReferenceType());
395 } else {
396 RE = CreateRecoveryExpr(EqualLoc, EqualLoc, {},
397 Param->getType().getNonReferenceType());
398 }
399 Param->setDefaultArg(RE.get());
400 }
401
402 void 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>(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(Param->getLocation(), diag::err_param_default_argument_nonfunc)
434 << SR;
435 } else if (Param->getDefaultArg()) {
436 Diag(Param->getLocation(), 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
447 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
448 return llvm::any_of(FD->parameters(), [](ParmVarDecl *P) {
449 return P->hasDefaultArg() && !P->hasInheritedDefaultArg();
450 });
451 }
452
453 bool 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(*this, PrevForDefaultArgs))
474 continue;
475
476 if (S && !isDeclInScope(PrevForDefaultArgs, 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(p);
519 ParmVarDecl *NewParam = New->getParamDecl(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>(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(NewParam->getLocation(), 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(p);
563 }
564
565 Diag(OldParam->getLocation(), 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(NewParam->getLocation(),
589 diag::err_param_default_argument_template_redecl)
590 << NewParam->getDefaultArgRange();
591 Diag(PrevForDefaultArgs->getLocation(),
592 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(NewParam->getLocation(), 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>(New->getDeclContext())) {
623 if (Record->getDescribedClassTemplate())
624 WhichKind = 0;
625 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
626 WhichKind = 1;
627 else
628 WhichKind = 2;
629 }
630
631 Diag(NewParam->getLocation(),
632 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>(New) &&
643 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
644 CXXSpecialMemberKind NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
645 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
646 if (NewSM != OldSM) {
647 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
648 assert(NewParam->hasDefaultArg());
649 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
650 << NewParam->getDefaultArgRange() << NewSM;
651 Diag(Old->getLocation(), 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(New->getLocation(), diag::err_constexpr_redecl_mismatch)
661 << New << static_cast<int>(New->getConstexprKind())
662 << static_cast<int>(Old->getConstexprKind());
663 Diag(Old->getLocation(), diag::note_previous_declaration);
664 Invalid = true;
665 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
666 Old->isDefined(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(New->getLocation(), diag::err_inline_decl_follows_def) << New;
676 Diag(Def->getLocation(), 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>(New) &&
685 !New->isFunctionTemplateSpecialization() && isVisible(Old)) {
686 Diag(New->getLocation(), diag::err_deduction_guide_redeclared);
687 Diag(Old->getLocation(), 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(Old)) {
696 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
697 Diag(Old->getLocation(), 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(OldDefinition, true))
710 CheckForFunctionRedefinition(New, OldDefinition);
711
712 return Invalid;
713 }
714
715 void Sema::DiagPlaceholderVariableDefinition(SourceLocation Loc) {
716 Diag(Loc, getLangOpts().CPlusPlus26
717 ? diag::warn_cxx23_placeholder_var_definition
718 : diag::ext_placeholder_var_definition);
719 }
720
721 NamedDecl *
722 Sema::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(Decomp.getLSquareLoc(), 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(TemplateParamLists.front()->getTemplateLoc(),
743 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(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, diag::err_decomp_decl_spec) << Name;
777 };
778
779 auto DiagCpp20Specifier = [&](StringRef Name, SourceLocation Loc) {
780 DiagCompat(Loc, diag_compat::decomp_decl_spec) << Name;
781 };
782
783 if (auto SCS = DS.getStorageClassSpec()) {
784 if (SCS == DeclSpec::SCS_static)
785 DiagCpp20Specifier(DeclSpec::getSpecifierName(SCS),
786 DS.getStorageClassSpecLoc());
787 else
788 DiagBadSpecifier(DeclSpec::getSpecifierName(SCS),
789 DS.getStorageClassSpecLoc());
790 }
791 if (auto TSCS = DS.getThreadStorageClassSpec())
792 DiagCpp20Specifier(DeclSpec::getSpecifierName(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(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(DS.getVolatileSpecLoc(),
815 diag::warn_deprecated_volatile_structured_binding);
816
817 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
818 QualType R = TInfo->getType();
819
820 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
821 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(0).Kind != DeclaratorChunk::Reference)) {
831 Diag(Decomp.getLSquareLoc(),
832 (D.hasGroupingParens() ||
833 (D.getNumTypeObjects() &&
834 D.getTypeObject(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(TemplRep->TemplateNameLoc, diag::err_decomp_decl_constraint)
857 << TemplRange << FixItHint::CreateRemoval(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(Previous, S,
873 /*CreateBuiltins*/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(B.NameLoc, Previous.getFoundDecl());
879 Previous.clear();
880 }
881
882 QualType QT;
883 if (B.EllipsisLoc.isValid()) {
884 if (!cast<Decl>(DC)->isTemplated())
885 Diag(B.EllipsisLoc, diag::err_pack_outside_template);
886 QT = Context.getPackExpansionType(Context.DependentTy, std::nullopt,
887 /*ExpectsPackInType=*/false);
888 }
889
890 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name, QT);
891
892 ProcessDeclAttributeList(S, BD, *B.Attrs);
893
894 // Find the shadowed declaration before filtering for scope.
895 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
896 ? getShadowedDeclaration(BD, Previous)
897 : nullptr;
898
899 bool ConsiderLinkage = DC->isFunctionOrMethod() &&
900 DS.getStorageClassSpec() == DeclSpec::SCS_extern;
901 FilterLookupForScope(Previous, 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->getRedeclContext());
912 if (sameDC &&
913 isDeclInScope(*(Previous.end() - 1), CurContext, S, false)) {
914 Previous.clear();
915 DiagPlaceholderVariableDefinition(B.NameLoc);
916 }
917 } else {
918 auto *Old = Previous.getRepresentativeDecl();
919 Diag(B.NameLoc, diag::err_redefinition) << B.Name;
920 Diag(Old->getLocation(), diag::note_previous_definition);
921 }
922 } else if (ShadowedDecl && !D.isRedeclaration()) {
923 CheckShadow(BD, ShadowedDecl, Previous);
924 }
925 PushOnScopeChains(BD, S, true);
926 Bindings.push_back(BD);
927 ParsingInitForAutoVars.insert(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 MultiTemplateParamsArg(), AddToScope, Bindings);
942 if (AddToScope) {
943 S->AddDecl(New);
944 CurContext->addHiddenDecl(New);
945 }
946
947 if (OpenMP().isInOpenMPDeclareTargetContext())
948 OpenMP().checkDeclIsAllowedInOpenMPTarget(nullptr, New);
949
950 return New;
951 }
952
953 // Check the arity of the structured bindings.
954 // Create the resolved pack expr if needed.
955 static bool CheckBindingsCount(Sema &S, DecompositionDecl *DD,
956 QualType DecompType,
957 ArrayRef<BindingDecl *> Bindings,
958 unsigned MemberCount) {
959 auto BindingWithPackItr = llvm::find_if(
960 Bindings, [](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 S.Context, BPack->getDeclContext(), BPack->getLocation(),
981 BPack->getIdentifier(), QualType());
982 NestedBD->setDecomposedDecl(DD);
983 NestedBDs[I] = NestedBD;
984 }
985
986 QualType PackType = S.Context.getPackExpansionType(
987 S.Context.DependentTy, PackSize, /*ExpectsPackInType=*/false);
988 auto *PackExpr = FunctionParmPackExpr::Create(
989 S.Context, PackType, BPack, BPack->getBeginLoc(), NestedBDs);
990 BPack->setBinding(PackType, PackExpr);
991 }
992
993 if (IsValid)
994 return false;
995
996 S.Diag(DD->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
997 << DecompType << (unsigned)Bindings.size() << MemberCount << MemberCount
998 << (MemberCount < Bindings.size());
999 return true;
1000 }
1001
1002 static 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>(Src);
1008
1009 if (CheckBindingsCount(S, DD, DecompType, Bindings, 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(Src, DecompType, 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(ElemType, E.get());
1022 }
1023
1024 return false;
1025 }
1026
1027 static 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, NumElems, ElemType,
1034 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
1035 ExprResult E = S.ActOnIntegerConstant(Loc, I);
1036 if (E.isInvalid())
1037 return ExprError();
1038 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
1039 });
1040 }
1041
1042 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1043 ValueDecl *Src, QualType DecompType,
1044 const ConstantArrayType *CAT) {
1045 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
1046 llvm::APSInt(CAT->getSize()),
1047 CAT->getElementType());
1048 }
1049
1050 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1051 ValueDecl *Src, QualType DecompType,
1052 const VectorType *VT) {
1053 return checkArrayLikeDecomposition(
1054 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
1055 S.Context.getQualifiedType(VT->getElementType(),
1056 DecompType.getQualifiers()));
1057 }
1058
1059 static 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, llvm::APSInt::get(2),
1065 S.Context.getQualifiedType(CT->getElementType(),
1066 DecompType.getQualifiers()),
1067 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
1068 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
1069 });
1070 }
1071
1072 static 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(PrintingPolicy, OS,
1083 TemplateParameterList::shouldIncludeTypeForArgument(
1084 PrintingPolicy, Params, I));
1085 First = false;
1086 I++;
1087 }
1088 return std::string(OS.str());
1089 }
1090
1091 static 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(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(Trait), Loc,
1111 Sema::LookupOrdinaryName);
1112 if (!S.LookupQualifiedName(Result, 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, diag::err_std_type_trait_not_class_template) << Trait;
1122 S.Diag(Found->getLocation(), diag::note_declared_at);
1123 return QualType();
1124 }
1125
1126 // Build the template-id.
1127 QualType TraitTy = S.CheckTemplateIdType(
1128 ElaboratedTypeKeyword::None, TemplateName(TraitTD), Loc, Args,
1129 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
1130 if (TraitTy.isNull())
1131 return QualType();
1132
1133 if (!S.isCompleteType(Loc, TraitTy)) {
1134 if (DiagID)
1135 S.RequireCompleteType(
1136 Loc, TraitTy, DiagID,
1137 printTemplateArgs(S.Context.getPrintingPolicy(), Args,
1138 TraitTD->getTemplateParameters()));
1139 return QualType();
1140 }
1141 return TraitTy;
1142 }
1143
1144 static bool lookupMember(Sema &S, CXXRecordDecl *RD,
1145 LookupResult &MemberLookup) {
1146 assert(RD && "specialization of class template is not a class?");
1147 S.LookupQualifiedName(MemberLookup, RD);
1148 return MemberLookup.isAmbiguous();
1149 }
1150
1151 static TemplateArgumentLoc
1152 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
1153 uint64_t I) {
1154 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
1155 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
1156 }
1157
1158 static TemplateArgumentLoc
1159 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
1160 return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
1161 }
1162
1163 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1164
1165 static 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(getTrivialTypeTemplateArgument(S, Loc, T));
1173
1174 QualType TraitTy = getStdTrait(S, Loc, "tuple_size", Args, /*DiagID=*/0);
1175 if (TraitTy.isNull())
1176 return IsTupleLike::NotTupleLike;
1177
1178 DeclarationName Value = S.PP.getIdentifierInfo("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, TraitTy->getAsCXXRecordDecl(), 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, diag::err_decomp_decl_std_tuple_size_not_constant)
1197 << printTemplateArgs(S.Context.getPrintingPolicy(), Args,
1198 /*Params*/ nullptr);
1199 }
1200 } Diagnoser(R, Args);
1201
1202 ExprResult E =
1203 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1204 if (E.isInvalid())
1205 return IsTupleLike::Error;
1206
1207 llvm::APSInt Size;
1208 E = S.VerifyIntegerConstantExpression(E.get(), &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, diag::err_decomp_decl_std_tuple_size_invalid)
1218 << printTemplateArgs(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.
1229 static 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 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1235 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1236
1237 QualType TraitTy =
1238 getStdTrait(S, Loc, "tuple_element", Args,
1239 diag::err_decomp_decl_std_tuple_element_not_specialized);
1240 if (TraitTy.isNull())
1241 return QualType();
1242
1243 DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1244 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1245 if (lookupMember(S, TraitTy->getAsCXXRecordDecl(), R))
1246 return QualType();
1247
1248 auto *TD = R.getAsSingle<TypeDecl>();
1249 if (!TD) {
1250 R.suppressDiagnostics();
1251 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1252 << printTemplateArgs(S.Context.getPrintingPolicy(), Args,
1253 /*Params*/ nullptr);
1254 if (!R.empty())
1255 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1256 return QualType();
1257 }
1258
1259 NestedNameSpecifier Qualifier(TraitTy.getTypePtr());
1260 return S.Context.getTypeDeclType(ElaboratedTypeKeyword::None, Qualifier, TD);
1261 }
1262
1263 namespace {
1264 struct 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
1279 static bool checkTupleLikeDecomposition(Sema &S,
1280 ArrayRef<BindingDecl *> Bindings,
1281 VarDecl *Src, QualType DecompType,
1282 unsigned NumElems) {
1283 auto *DD = cast<DecompositionDecl>(Src);
1284 if (CheckBindingsCount(S, DD, DecompType, Bindings, NumElems))
1285 return true;
1286
1287 if (Bindings.empty())
1288 return false;
1289
1290 DeclarationName GetDN = S.PP.getIdentifierInfo("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(Src->getLocation(), DecompType)) {
1298 if (auto *RD = DecompType->getAsCXXRecordDecl())
1299 S.LookupQualifiedName(MemberGet, 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>(D->getUnderlyingDecl())) {
1307 TemplateParameterList *TPL = FTD->getTemplateParameters();
1308 if (TPL->size() != 0 &&
1309 isa<NonTypeTemplateParmDecl>(TPL->getParam(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(Src, DecompType, 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(S.Context, E.get()->getType(), CK_NoOp,
1331 E.get(), nullptr, VK_XValue,
1332 FPOptionsOverride());
1333
1334 TemplateArgumentListInfo Args(Loc, Loc);
1335 Args.addArgument(
1336 getTrivialIntegralTemplateArgument(S, Loc, 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(E.get(), DecompType, Loc, false,
1342 CXXScopeSpec(), SourceLocation(), nullptr,
1343 MemberGet, &Args, nullptr);
1344 if (E.isInvalid())
1345 return true;
1346
1347 E = S.BuildCallExpr(nullptr, E.get(), Loc, {}, 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 S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
1353 DeclarationNameInfo(GetDN, Loc), /*RequiresADL=*/true, &Args,
1354 UnresolvedSetIterator(), UnresolvedSetIterator(),
1355 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
1356
1357 Expr *Arg = E.get();
1358 E = S.BuildCallExpr(nullptr, Get, Loc, Arg, 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, 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, E.get()->isLValue(), Loc, 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(S.Context, Src->getDeclContext(), Loc, Loc,
1381 B->getDeclName().getAsIdentifierInfo(), RefType,
1382 /*TInfo=*/nullptr, 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(RefVD);
1389
1390 InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
1391 InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
1392 InitializationSequence Seq(S, Entity, Kind, Init);
1393 E = Seq.Perform(S, Entity, Kind, Init);
1394 if (E.isInvalid())
1395 return true;
1396 E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
1397 if (E.isInvalid())
1398 return true;
1399 RefVD->setInit(E.get());
1400 S.CheckCompleteVariableDeclaration(RefVD);
1401
1402 E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
1403 DeclarationNameInfo(B->getDeclName(), Loc),
1404 RefVD);
1405 if (E.isInvalid())
1406 return true;
1407
1408 B->setBinding(T, 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++.
1418 static 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(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(const_cast<CXXRecordDecl*>(RD), 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(P.back().Base->getType(),
1448 BestPath->back().Base->getType())) {
1449 // ... the same ...
1450 S.Diag(Loc, 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(S.Context.getCanonicalType(BaseType))) {
1462 S.Diag(Loc, 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(Loc, BaseType, S.Context.getCanonicalTagType(RD),
1469 *BestPath, 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(BaseHasFields, Paths)) {
1480 S.Diag(Loc, 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(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1487 }
1488
1489 static bool CheckMemberDecompositionFields(Sema &S, SourceLocation Loc,
1490 const CXXRecordDecl *OrigRD,
1491 QualType DecompType,
1492 DeclAccessPair BasePair) {
1493 const auto *RD = cast_or_null<CXXRecordDecl>(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, diag::err_decomp_decl_lambda);
1506 S.Diag(RD->getLocation(), diag::note_lambda_decl);
1507 return true;
1508 }
1509
1510 if (FD->isAnonymousStructOrUnion()) {
1511 S.Diag(Loc, diag::err_decomp_decl_anon_union_member)
1512 << DecompType << FD->getType()->isUnionType();
1513 S.Diag(FD->getLocation(), 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 Loc, const_cast<CXXRecordDecl *>(OrigRD),
1525 DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess(
1526 BasePair.getAccess(), FD->getAccess())));
1527 }
1528 return false;
1529 }
1530
1531 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1532 ValueDecl *Src, QualType DecompType,
1533 const CXXRecordDecl *OrigRD) {
1534 if (S.RequireCompleteType(Src->getLocation(), DecompType,
1535 diag::err_incomplete_type))
1536 return true;
1537
1538 CXXCastPath BasePath;
1539 DeclAccessPair BasePair =
1540 findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1541 const auto *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1542 if (!RD)
1543 return true;
1544 QualType BaseType = S.Context.getQualifiedType(
1545 S.Context.getCanonicalTagType(RD), DecompType.getQualifiers());
1546
1547 auto *DD = cast<DecompositionDecl>(Src);
1548 unsigned NumFields = llvm::count_if(
1549 RD->fields(), [](FieldDecl *FD) { return !FD->isUnnamedBitField(); });
1550 if (CheckBindingsCount(S, DD, DecompType, Bindings, 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, 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(Src, DecompType, VK_LValue, Loc);
1575 if (E.isInvalid())
1576 return true;
1577 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1578 VK_LValue, &BasePath);
1579 if (E.isInvalid())
1580 return true;
1581 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1582 CXXScopeSpec(), FD,
1583 DeclAccessPair::make(FD, FD->getAccess()),
1584 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(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1597 }
1598
1599 return false;
1600 }
1601
1602 void 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(DecompType)) {
1625 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1626 DD->setInvalidDecl();
1627 return;
1628 }
1629 if (auto *VT = DecompType->getAs<VectorType>()) {
1630 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1631 DD->setInvalidDecl();
1632 return;
1633 }
1634 if (auto *CT = DecompType->getAs<ComplexType>()) {
1635 if (checkComplexDecomposition(*this, Bindings, 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(*this, DD->getLocation(), DecompType, TupleSize)) {
1645 case IsTupleLike::Error:
1646 DD->setInvalidDecl();
1647 return;
1648
1649 case IsTupleLike::TupleLike:
1650 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, 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(DD->getLocation(), 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(*this, Bindings, DD, DecompType, RD))
1672 DD->setInvalidDecl();
1673 }
1674
1675 UnsignedOrNone 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(Unqual, 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(*this, Loc, T, 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, diag::err_incomplete_type))
1707 return std::nullopt;
1708
1709 CXXCastPath BasePath;
1710 DeclAccessPair BasePair =
1711 findDecomposableBaseClass(*this, Loc, OrigRD, BasePath);
1712 const auto *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1713 if (!RD)
1714 return std::nullopt;
1715
1716 unsigned NumFields = llvm::count_if(
1717 RD->fields(), [](FieldDecl *FD) { return !FD->isUnnamedBitField(); });
1718
1719 if (CheckMemberDecompositionFields(*this, Loc, OrigRD, T, BasePair))
1720 return std::nullopt;
1721
1722 return NumFields;
1723 }
1724
1725 void 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 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1757 NewType->getAs<FunctionProtoType>(), 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].
1765 void 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(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(ParamIdx);
1792 if (Param->hasDefaultArg() || Param->isParameterPack() ||
1793 (CurrentInstantiationScope &&
1794 CurrentInstantiationScope->isLocalPackExpansion(Param)))
1795 continue;
1796 if (Param->isInvalidDecl())
1797 /* We already complained about this parameter. */;
1798 else if (Param->getIdentifier())
1799 Diag(Param->getLocation(), diag::err_param_default_argument_missing_name)
1800 << Param->getIdentifier();
1801 else
1802 Diag(Param->getLocation(), 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).
1809 template <typename... Ts>
1810 static 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(SemaRef.Context);
1823 }
1824
1825 llvm_unreachable("unknown CheckConstexprKind");
1826 }
1827
1828 /// Determine whether a destructor cannot be constexpr due to
1829 static 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(DD->getLocation(), diag::err_constexpr_dtor_subobject)
1842 << static_cast<int>(DD->getConstexprKind()) << !FD
1843 << (FD ? FD->getDeclName() : DeclarationName()) << T;
1844 SemaRef.Diag(Loc, 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.
1862 static 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(ArgIndex);
1873 assert(PD && "null in a parameter list");
1874 SourceLocation ParamLoc = PD->getLocation();
1875 if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i,
1876 diag::err_constexpr_non_literal_param, ArgIndex + 1,
1877 PD->getSourceRange(), isa<CXXConstructorDecl>(FD),
1878 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.
1886 static 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, FD->getLocation(), FD->getReturnType(),
1891 diag::err_constexpr_non_literal_return,
1892 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.
1902 static 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
1914 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
1915 Stmt *Body,
1916 Sema::CheckConstexprKind Kind);
1917 static bool CheckConstexprMissingReturn(Sema &SemaRef, const FunctionDecl *Dcl);
1918
1919 bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD,
1920 CheckConstexprKind Kind) {
1921 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(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(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1936 << isa<CXXConstructorDecl>(NewFD)
1937 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
1938 for (const auto &I : RD->vbases())
1939 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1940 << I.getSourceRange();
1941 return false;
1942 }
1943 }
1944
1945 if (!isa<CXXConstructorDecl>(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>(NewFD);
1951 if (Method && Method->isVirtual()) {
1952 if (getLangOpts().CPlusPlus20) {
1953 if (Kind == CheckConstexprKind::Diagnose)
1954 Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
1955 } else {
1956 if (Kind == CheckConstexprKind::CheckValid)
1957 return false;
1958
1959 Method = Method->getCanonicalDecl();
1960 Diag(Method->getLocation(), 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(WrittenVirtual->getLocation(),
1969 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(*this, NewFD, Kind))
1977 return false;
1978 }
1979
1980 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(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(*this, 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(*this, 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(*this, 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.
2009 static 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>(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(TL.getBeginLoc(), diag::err_constexpr_vla)
2040 << TL.getSourceRange() << TL.getType()
2041 << isa<CXXConstructorDecl>(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>(DclIt)->isThisDeclarationADefinition()) {
2052 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2053 SemaRef.DiagCompat(DS->getBeginLoc(),
2054 diag_compat::constexpr_type_definition)
2055 << isa<CXXConstructorDecl>(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>(DclIt);
2076 if (VD->isThisDeclarationADefinition()) {
2077 if (VD->isStaticLocal()) {
2078 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2079 SemaRef.DiagCompat(VD->getLocation(),
2080 diag_compat::constexpr_static_var)
2081 << isa<CXXConstructorDecl>(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, VD->getLocation(), VD->getType(),
2089 diag::warn_cxx20_compat_constexpr_var,
2090 isa<CXXConstructorDecl>(Dcl));
2091 } else if (CheckLiteralType(
2092 SemaRef, Kind, VD->getLocation(), VD->getType(),
2093 diag::err_constexpr_local_var_non_literal_type,
2094 isa<CXXConstructorDecl>(Dcl))) {
2095 return false;
2096 }
2097 if (!VD->getType()->isDependentType() &&
2098 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
2099 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2100 SemaRef.DiagCompat(VD->getLocation(),
2101 diag_compat::constexpr_local_var_no_init)
2102 << isa<CXXConstructorDecl>(Dcl);
2103 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2104 return false;
2105 }
2106 continue;
2107 }
2108 }
2109 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2110 SemaRef.DiagCompat(VD->getLocation(), diag_compat::constexpr_local_var)
2111 << isa<CXXConstructorDecl>(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(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2129 << isa<CXXConstructorDecl>(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.
2151 static 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(Field)) {
2178 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2179 if (!Diagnosed) {
2180 SemaRef.DiagCompat(Dcl->getLocation(),
2181 diag_compat::constexpr_ctor_missing_init);
2182 Diagnosed = true;
2183 }
2184 SemaRef.Diag(Field->getLocation(),
2185 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(I))
2195 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, 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.
2204 static bool
2205 CheckConstexprFunctionStmt(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, cast<DeclStmt>(S), Cxx1yLoc, Kind))
2223 return false;
2224 return true;
2225
2226 case Stmt::ReturnStmtClass:
2227 // - and exactly one return statement;
2228 if (isa<CXXConstructorDecl>(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(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, cast<AttributedStmt>(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>(S);
2251 for (auto *BodyIt : CompStmt->body()) {
2252 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, 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>(S);
2265 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
2266 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2267 return false;
2268 if (If->getElse() &&
2269 !CheckConstexprFunctionStmt(SemaRef, Dcl, 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, 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, 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, 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, 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, cast<CXXCatchStmt>(S)->getHandlerBlock(), ReturnStmts,
2341 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2342 return false;
2343 return true;
2344
2345 default:
2346 if (!isa<Expr>(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(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2357 << isa<CXXConstructorDecl>(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.
2367 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
2368 Stmt *Body,
2369 Sema::CheckConstexprKind Kind) {
2370 SmallVector<SourceLocation, 4> ReturnStmts;
2371
2372 if (isa<CXXTryStmt>(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(Body->getBeginLoc(),
2393 diag_compat::constexpr_function_try_block)
2394 << isa<CXXConstructorDecl>(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, 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(Cxx2bLoc, diag_compat::cxx23_constexpr_body_invalid_stmt)
2421 << isa<CXXConstructorDecl>(Dcl);
2422 } else if (Cxx2aLoc.isValid()) {
2423 SemaRef.DiagCompat(Cxx2aLoc, diag_compat::cxx20_constexpr_body_invalid_stmt)
2424 << isa<CXXConstructorDecl>(Dcl);
2425 } else if (Cxx1yLoc.isValid()) {
2426 SemaRef.DiagCompat(Cxx1yLoc, diag_compat::cxx14_constexpr_body_invalid_stmt)
2427 << isa<CXXConstructorDecl>(Dcl);
2428 }
2429
2430 if (const CXXConstructorDecl *Constructor
2431 = dyn_cast<CXXConstructorDecl>(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(Dcl->getLocation(),
2444 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(FD);
2477 else if (IndirectFieldDecl *ID = I->getIndirectMember())
2478 Inits.insert(ID->chain_begin(), ID->chain_end());
2479 }
2480
2481 bool Diagnosed = false;
2482 for (auto *I : RD->fields())
2483 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, 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(ReturnStmts.back(),
2508 diag_compat::constexpr_body_multiple_return);
2509 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2510 SemaRef.Diag(ReturnStmts[I],
2511 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(Dcl->getLocation()) ||
2541 SemaRef.getDiagnostics().isIgnored(
2542 diag::ext_constexpr_function_never_constant_expr, Dcl->getLocation());
2543 SmallVector<PartialDiagnosticAt, 8> Diags;
2544 if (Kind == Sema::CheckConstexprKind::Diagnose && !SkipCheck &&
2545 !Expr::isPotentialConstantExpr(Dcl, Diags)) {
2546 SemaRef.Diag(Dcl->getLocation(),
2547 diag::ext_constexpr_function_never_constant_expr)
2548 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval()
2549 << Dcl->getNameInfo().getSourceRange();
2550 for (const auto &Diag : Diags)
2551 SemaRef.Diag(Diag.first, Diag.second);
2552 // Don't return false here: we allow this for compatibility in
2553 // system headers.
2554 }
2555
2556 return true;
2557 }
2558
2559 static 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(Dcl->getLocation(),
2575 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2576 : diag::err_constexpr_body_no_return)
2577 << Dcl->isConsteval();
2578 return OK;
2579 }
2580
2581 bool 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(FD->getCanonicalDecl());
2589 if (it != UndefinedButUsed.end()) {
2590 Diag(it->second, diag::err_immediate_function_used_before_definition)
2591 << it->first;
2592 Diag(FD->getLocation(), diag::note_defined_here) << FD;
2593 if (FD->isImmediateFunction() && !FD->isConsteval())
2594 DiagnoseImmediateEscalatingReason(FD);
2595 return false;
2596 }
2597 }
2598 return true;
2599 }
2600
2601 void 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>(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, diag::note_immediate_function_reason)
2632 << ImmediateFn << Fn << Fn->isConsteval() << IsCall
2633 << isa<CXXConstructorDecl>(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>(E->getCallee()->IgnoreImplicit());
2641 DR && DR->isImmediateEscalating()) {
2642 Diag(E, E->getDirectCallee(), /*IsCall=*/true);
2643 return false;
2644 }
2645
2646 for (Expr *A : E->arguments())
2647 if (!TraverseStmt(A))
2648 return false;
2649
2650 return true;
2651 }
2652
2653 bool VisitDeclRefExpr(DeclRefExpr *E) override {
2654 if (const auto *ReferencedFn = dyn_cast<FunctionDecl>(E->getDecl());
2655 ReferencedFn && E->isImmediateEscalating()) {
2656 Diag(E, 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, 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(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(FD);
2689 }
2690
2691 CXXRecordDecl *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, true);
2699 return dyn_cast_or_null<CXXRecordDecl>(DC);
2700 }
2701
2702 return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2703 }
2704
2705 bool 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
2711 bool 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, true);
2720 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2721 } else
2722 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2723
2724 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2725 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2726 < II->getLength()) {
2727 II = CurDecl->getIdentifier();
2728 return true;
2729 }
2730
2731 return false;
2732 }
2733
2734 CXXBaseSpecifier *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(EllipsisLoc, 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>(computeDeclContext(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(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2763 return nullptr;
2764 }
2765
2766 if (BaseType.hasQualifiers()) {
2767 std::string Quals =
2768 BaseType.getQualifiers().getAsString(Context.getPrintingPolicy());
2769 Diag(BaseLoc, diag::warn_qual_base_type)
2770 << Quals << llvm::count(Quals, ' ') + 1 << BaseType;
2771 Diag(BaseLoc, 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(Class)) {
2778 if (auto *BaseSpec =
2779 dyn_cast<ClassTemplateSpecializationDecl>(BaseDecl)) {
2780 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseSpec,
2781 BaseLoc);
2782 }
2783 }
2784 }
2785
2786 if (RequireCompleteType(BaseLoc, BaseType, diag::err_incomplete_base_class,
2787 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(Class->getLocation(), diag::err_mismatched_code_seg_base);
2804 Diag(BaseDecl->getLocation(), 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(BaseLoc, 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(BaseLoc, diag::err_class_marked_final_used_as_base)
2826 << BaseDecl->getDeclName() << FA->isSpelledAsSealed();
2827 Diag(BaseDecl->getLocation(), 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(BaseLoc, 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
2861 BaseResult 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(classdecl);
2870 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(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(AL.getLoc(), diag::err_base_specifier_attribute)
2886 << AL << AL.isRegularKeywordAttribute() << AL.getRange();
2887 }
2888
2889 TypeSourceInfo *TInfo = nullptr;
2890 GetTypeFromParser(basetype, &TInfo);
2891
2892 if (EllipsisLoc.isInvalid() &&
2893 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2894 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(Class->getLocation(), 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.
2916 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2917
2918 /// Recursively add the bases of Type. Don't add Type itself.
2919 static void
2920 NoteIndirectBases(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(BaseSpec.getType())
2929 .getUnqualifiedType();
2930 if (Set.insert(Base).second)
2931 // If we've not already seen it, recurse.
2932 NoteIndirectBases(Context, Set, Base);
2933 }
2934 }
2935 }
2936
2937 bool 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(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(Bases[idx]->getBeginLoc(), 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(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, IndirectBaseTypes, 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(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
2991 << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2992 << RD->getSourceRange();
2993 Invalid = true;
2994 }
2995 if (RD->hasAttr<WeakAttr>())
2996 Class->addAttr(WeakAttr::CreateImplicit(Context));
2997 }
2998 }
2999 }
3000
3001 // Attach the remaining base class specifiers to the derived class.
3002 Class->setBases(Bases.data(), 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(BaseType)
3015 .getUnqualifiedType();
3016
3017 if (IndirectBaseTypes.count(CanonicalBase)) {
3018 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3019 /*DetectVirtual=*/true);
3020 bool found
3021 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
3022 assert(found);
3023 (void)found;
3024
3025 if (Paths.isAmbiguous(CanonicalBase))
3026 Diag(Bases[idx]->getBeginLoc(), 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(Bases[idx]);
3036 }
3037
3038 return Invalid;
3039 }
3040
3041 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
3042 MutableArrayRef<CXXBaseSpecifier *> Bases) {
3043 if (!ClassDecl || Bases.empty())
3044 return;
3045
3046 AdjustDeclIfTemplate(ClassDecl);
3047 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
3048 }
3049
3050 bool 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, Context.getCanonicalTagType(Derived)) &&
3066 !Derived->isBeingDefined())
3067 return false;
3068
3069 return Derived->isDerivedFrom(Base, Paths);
3070 }
3071
3072 bool 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
3079 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
3080 CXXBasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/false,
3081 /*DetectVirtual=*/false);
3082 return IsDerivedFrom(Loc, Derived->getAsCXXRecordDecl(),
3083 Base->getAsCXXRecordDecl(), Paths);
3084 }
3085
3086 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
3087 CXXBasePaths &Paths) {
3088 return IsDerivedFrom(Loc, Derived->getAsCXXRecordDecl(),
3089 Base->getAsCXXRecordDecl(), Paths);
3090 }
3091
3092 static 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(const_cast<CXXBaseSpecifier*>(Path[I].Base));
3108 }
3109
3110
3111 void 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(Paths.front(), BasePathArray);
3116 }
3117
3118 bool
3119 Sema::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(Context.getCanonicalType(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, 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(Loc, Base, Derived, *Path, 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, *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, AmbiguousBaseConvID)
3195 << Derived << Base << PathDisplayStr << Range << Name;
3196 }
3197 return true;
3198 }
3199
3200 bool
3201 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
3202 SourceLocation Loc, SourceRange Range,
3203 CXXCastPath *BasePath,
3204 bool IgnoreAccess) {
3205 return CheckDerivedToBaseConversion(
3206 Derived, Base, diag::err_upcast_to_inaccessible_base,
3207 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
3208 BasePath, IgnoreAccess);
3209 }
3210
3211 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
3212 std::string PathDisplayStr;
3213 std::set<unsigned> DisplayedPaths;
3214 for (const CXXBasePath &Path : Paths) {
3215 if (DisplayedPaths.insert(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(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
3233 bool 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(Context, Access, CurContext,
3238 ASLoc, ColonLoc);
3239 CurContext->addHiddenDecl(ASDecl);
3240 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
3241 }
3242
3243 void 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>(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(OA->getLocation(),
3268 diag::override_keyword_hides_virtual_member_function)
3269 << "override" << (OverloadedMethods.size() > 1);
3270 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3271 Diag(FA->getLocation(),
3272 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(OA->getLocation(),
3287 diag::override_keyword_only_allowed_on_virtual_member_functions)
3288 << "override" << FixItHint::CreateRemoval(OA->getLocation());
3289 D->dropAttr<OverrideAttr>();
3290 }
3291 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3292 Diag(FA->getLocation(),
3293 diag::override_keyword_only_allowed_on_virtual_member_functions)
3294 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3295 << FixItHint::CreateRemoval(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(MD->getLocation(), diag::err_function_marked_override_not_overriding)
3308 << MD->getDeclName();
3309 }
3310
3311 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent) {
3312 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
3313 return;
3314 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(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(SpellingLoc);
3323 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(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(DiagInconsistent, MD->getLocation())
3330 ? DiagInconsistent
3331 : DiagSuggest;
3332 Diag(MD->getLocation(), DiagID) << MD->getDeclName();
3333 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
3334 Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
3335 };
3336 if (isa<CXXDestructorDecl>(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
3346 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
3347 const CXXMethodDecl *Old) {
3348 FinalAttr *FA = Old->getAttr<FinalAttr>();
3349 if (!FA)
3350 return false;
3351
3352 Diag(New->getLocation(), diag::err_final_function_overridden)
3353 << New->getDeclName()
3354 << FA->isSpelledAsSealed();
3355 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3356 return true;
3357 }
3358
3359 static 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
3369 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
3370 DeclarationName FieldName,
3371 const CXXRecordDecl *RD,
3372 bool DeclIsField) {
3373 if (Diags.isIgnored(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(Base) != Bases.end())
3383 return true;
3384 for (const auto Field : Base->lookup(FieldName)) {
3385 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(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(FieldShadowed, Paths))
3399 return;
3400
3401 for (const auto &P : Paths) {
3402 auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
3403 auto It = Bases.find(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(P.Access, BaseField->getAccess())) {
3411 Diag(Loc, diag::warn_shadow_field)
3412 << FieldName << RD << Base << DeclIsField;
3413 Diag(BaseField->getLocation(), diag::note_shadow_field);
3414 Bases.erase(It);
3415 }
3416 }
3417 }
3418
3419 template <typename AttrType>
3420 inline 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
3428 static bool IsUnusedPrivateField(const FieldDecl *FD) {
3429 if (FD->getAccess() == AS_private && FD->getDeclName()) {
3430 QualType FieldType = FD->getType();
3431 if (HasAttribute<WarnUnusedAttr>(FieldType))
3432 return true;
3433
3434 return !FD->isImplicit() && !FD->hasAttr<UnusedAttr>() &&
3435 !FD->getParent()->isDependentContext() &&
3436 !HasAttribute<UnusedAttr>(FieldType) &&
3437 !InitializationHasSideEffects(*FD);
3438 }
3439 return false;
3440 }
3441
3442 NamedDecl *
3443 Sema::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>(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, diag::err_invalid_member_in_interface)
3502 << (InvalidDecl-1) << Name;
3503 else
3504 Diag(Loc, 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(DS.getStorageClassSpecLoc(), 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(DS.getStorageClassSpecLoc(),
3531 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(DS.getConstexprSpecLoc(), 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(ConstexprLoc);
3548 else {
3549 B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3550 D.getMutableDeclSpec().ClearConstexprSpec();
3551 const char *PrevSpec;
3552 unsigned DiagID;
3553 bool Failed = D.getMutableDeclSpec().SetTypeQual(
3554 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, 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 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3564 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(ConstexprLoc, "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, 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(D.getIdentifierLoc(), 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(II, 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, false)) {
3604 TemplateIdAnnotation *TemplateId =
3605 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
3606 ? D.getName().TemplateId
3607 : nullptr;
3608 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
3609 TemplateId,
3610 /*IsMemberSpecialization=*/false);
3611 } else {
3612 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3613 << Name << SS.getRange();
3614 }
3615 SS.clear();
3616 }
3617
3618 if (MSPropertyAttr) {
3619 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3620 BitWidth, InitStyle, AS, *MSPropertyAttr);
3621 if (!Member)
3622 return nullptr;
3623 isInstField = false;
3624 } else {
3625 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3626 BitWidth, InitStyle, AS);
3627 if (!Member)
3628 return nullptr;
3629 }
3630
3631 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(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>(Member) || isa<VarTemplateDecl>(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, diag::err_static_not_bitfield)
3645 << Name << BitWidth->getSourceRange();
3646 } else if (isa<TypedefDecl>(Member)) {
3647 // "typedef member 'x' cannot be a bit-field"
3648 Diag(Loc, 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, diag::err_not_integral_type_bitfield)
3654 << Name << cast<ValueDecl>(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>(Member))
3664 NonTemplateMember = FunTmpl->getTemplatedDecl();
3665 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(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>(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 DG->getDeclContext()->getRedeclContext())) {
3685 Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3686 Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3687 << TD->getAccess();
3688 const AccessSpecDecl *LastAccessSpec = nullptr;
3689 for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3690 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3691 LastAccessSpec = AccessSpec;
3692 }
3693 assert(LastAccessSpec && "differing access with no access specifier");
3694 Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3695 << AS;
3696 }
3697 }
3698 }
3699
3700 if (VS.isOverrideSpecified())
3701 Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc()));
3702 if (VS.isFinalSpecified())
3703 Member->addAttr(FinalAttr::Create(Context, VS.getFinalLoc(),
3704 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>(Member))
3711 MD->setRangeEnd(VS.getLastLocation());
3712 }
3713
3714 CheckOverrideControl(Member);
3715
3716 assert((Name || isInstField) && "No identifier for non-field ?");
3717
3718 if (isInstField) {
3719 FieldDecl *FD = cast<FieldDecl>(Member);
3720 FieldCollector->Add(FD);
3721
3722 if (!Diags.isIgnored(diag::warn_unused_private_field, 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(FD);
3727 }
3728 }
3729
3730 return Member;
3731 }
3732
3733 namespace {
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>(ME->getMemberDecl());
3770 if (!FD)
3771 return false;
3772 Fields.push_back(FD);
3773 if (FD->getType()->isReferenceType())
3774 ReferenceField = true;
3775 ME = dyn_cast<MemberExpr>(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(llvm::reverse(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>(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(S.Context);
3813
3814 Expr *Base = ME;
3815 while (MemberExpr *SubME =
3816 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3817
3818 if (isa<VarDecl>(SubME->getMemberDecl()))
3819 return;
3820
3821 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3822 if (!FD->isAnonymousStructOrUnion())
3823 FieldME = SubME;
3824
3825 if (!FieldME->getType().isPODType(S.Context))
3826 AllPODFields = false;
3827
3828 Base = SubME->getBase();
3829 }
3830
3831 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) {
3832 Visit(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>(Base)) {
3842 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3843 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3844 }
3845
3846 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3847 QualType T = BaseCast->getType();
3848 if (T->isPointerType() &&
3849 BaseClasses.count(T->getPointeeType())) {
3850 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3851 << T->getPointeeType() << FoundVD;
3852 }
3853 }
3854 }
3855
3856 if (!Decls.count(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(FieldME->getExprLoc(), diag) << FoundVD;
3876 if (Constructor)
3877 S.Diag(Constructor->getLocation(),
3878 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>(E)) {
3887 HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3888 AddressOf /*AddressOf*/);
3889 return;
3890 }
3891
3892 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3893 Visit(CO->getCond());
3894 HandleValue(CO->getTrueExpr(), AddressOf);
3895 HandleValue(CO->getFalseExpr(), AddressOf);
3896 return;
3897 }
3898
3899 if (BinaryConditionalOperator *BCO =
3900 dyn_cast<BinaryConditionalOperator>(E)) {
3901 Visit(BCO->getCond());
3902 HandleValue(BCO->getFalseExpr(), AddressOf);
3903 return;
3904 }
3905
3906 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3907 HandleValue(OVE->getSourceExpr(), AddressOf);
3908 return;
3909 }
3910
3911 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3912 switch (BO->getOpcode()) {
3913 default:
3914 break;
3915 case(BO_PtrMemD):
3916 case(BO_PtrMemI):
3917 HandleValue(BO->getLHS(), AddressOf);
3918 Visit(BO->getRHS());
3919 return;
3920 case(BO_Comma):
3921 Visit(BO->getLHS());
3922 HandleValue(BO->getRHS(), AddressOf);
3923 return;
3924 }
3925 }
3926
3927 Visit(E);
3928 }
3929
3930 void CheckInitListExpr(InitListExpr *ILE) {
3931 InitFieldIndex.push_back(0);
3932 for (auto *Child : ILE->children()) {
3933 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3934 CheckInitListExpr(SubList);
3935 } else {
3936 Visit(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(VD);
3949 DeclsToRemove.clear();
3950
3951 Constructor = FieldConstructor;
3952 InitListExpr *ILE = dyn_cast<InitListExpr>(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(E);
3962 }
3963
3964 if (Field)
3965 Decls.erase(Field);
3966 if (BaseClass)
3967 BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3968 }
3969
3970 void VisitMemberExpr(MemberExpr *ME) {
3971 // All uses of unbounded reference fields will warn.
3972 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3973 }
3974
3975 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3976 if (E->getCastKind() == CK_LValueToRValue) {
3977 HandleValue(E->getSubExpr(), false /*AddressOf*/);
3978 return;
3979 }
3980
3981 Inherited::VisitImplicitCastExpr(E);
3982 }
3983
3984 void VisitCXXConstructExpr(CXXConstructExpr *E) {
3985 if (E->getConstructor()->isCopyConstructor()) {
3986 Expr *ArgExpr = E->getArg(0);
3987 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3988 if (ILE->getNumInits() == 1)
3989 ArgExpr = ILE->getInit(0);
3990 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3991 if (ICE->getCastKind() == CK_NoOp)
3992 ArgExpr = ICE->getSubExpr();
3993 HandleValue(ArgExpr, false /*AddressOf*/);
3994 return;
3995 }
3996 Inherited::VisitCXXConstructExpr(E);
3997 }
3998
3999 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
4000 Expr *Callee = E->getCallee();
4001 if (isa<MemberExpr>(Callee)) {
4002 HandleValue(Callee, false /*AddressOf*/);
4003 for (auto *Arg : E->arguments())
4004 Visit(Arg);
4005 return;
4006 }
4007
4008 Inherited::VisitCXXMemberCallExpr(E);
4009 }
4010
4011 void VisitCallExpr(CallExpr *E) {
4012 // Treat std::move as a use.
4013 if (E->isCallToStdMove()) {
4014 HandleValue(E->getArg(0), /*AddressOf=*/false);
4015 return;
4016 }
4017
4018 Inherited::VisitCallExpr(E);
4019 }
4020
4021 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
4022 Expr *Callee = E->getCallee();
4023
4024 if (isa<UnresolvedLookupExpr>(Callee))
4025 return Inherited::VisitCXXOperatorCallExpr(E);
4026
4027 Visit(Callee);
4028 for (auto *Arg : E->arguments())
4029 HandleValue(Arg->IgnoreParenImpCasts(), 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>(E->getLHS()))
4037 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
4038 if (!FD->getType()->isReferenceType())
4039 DeclsToRemove.push_back(FD);
4040
4041 if (E->isCompoundAssignmentOp()) {
4042 HandleValue(E->getLHS(), false /*AddressOf*/);
4043 Visit(E->getRHS());
4044 return;
4045 }
4046
4047 Inherited::VisitBinaryOperator(E);
4048 }
4049
4050 void VisitUnaryOperator(UnaryOperator *E) {
4051 if (E->isIncrementDecrementOp()) {
4052 HandleValue(E->getSubExpr(), false /*AddressOf*/);
4053 return;
4054 }
4055 if (E->getOpcode() == UO_AddrOf) {
4056 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
4057 HandleValue(ME->getBase(), true /*AddressOf*/);
4058 return;
4059 }
4060 }
4061
4062 Inherited::VisitUnaryOperator(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(diag::warn_field_is_uninit,
4076 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>(I)) {
4094 UninitializedFields.insert(FD);
4095 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
4096 UninitializedFields.insert(IFD->getAnonField());
4097 }
4098 }
4099
4100 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
4101 for (const auto &I : RD->bases())
4102 UninitializedBaseClasses.insert(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>(InitExpr)) {
4121 InitExpr = Default->getExpr();
4122 if (!InitExpr)
4123 continue;
4124 // In class initializers will point to the constructor.
4125 UninitializedChecker.CheckInitializer(InitExpr, Constructor,
4126 FieldInit->getAnyMember(),
4127 FieldInit->getBaseClass());
4128 } else {
4129 UninitializedChecker.CheckInitializer(InitExpr, nullptr,
4130 FieldInit->getAnyMember(),
4131 FieldInit->getBaseClass());
4132 }
4133 }
4134 }
4135 } // namespace
4136
4137 void 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
4143 void 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>(Param.Param);
4152 if (ParamDecl->getDeclName())
4153 PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false);
4154 }
4155 }
4156
4157 ExprResult Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr) {
4158 return ActOnRequiresClause(ConstraintExpr);
4159 }
4160
4161 ExprResult Sema::ActOnRequiresClause(ExprResult ConstraintExpr) {
4162 if (ConstraintExpr.isInvalid())
4163 return ExprError();
4164
4165 if (DiagnoseUnexpandedParameterPack(ConstraintExpr.get(),
4166 UPPC_RequiresClause))
4167 return ExprError();
4168
4169 return ConstraintExpr;
4170 }
4171
4172 ExprResult Sema::ConvertMemberDefaultInitExpression(FieldDecl *FD,
4173 Expr *InitExpr,
4174 SourceLocation InitLoc) {
4175 InitializedEntity Entity =
4176 InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD);
4177 InitializationKind Kind =
4178 FD->getInClassInitStyle() == ICIS_ListInit
4179 ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(),
4180 InitExpr->getBeginLoc(),
4181 InitExpr->getEndLoc())
4182 : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
4183 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
4184 return Seq.Perform(*this, Entity, Kind, InitExpr);
4185 }
4186
4187 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
4188 SourceLocation InitLoc,
4189 ExprResult InitExpr) {
4190 // Pop the notional constructor scope we created earlier.
4191 PopFunctionScopeInfo(nullptr, D);
4192
4193 // Microsoft C++'s property declaration cannot have a default member
4194 // initializer.
4195 if (isa<MSPropertyDecl>(D)) {
4196 D->setInvalidDecl();
4197 return;
4198 }
4199
4200 FieldDecl *FD = dyn_cast<FieldDecl>(D);
4201 assert((FD && FD->getInClassInitStyle() != ICIS_NoInit) &&
4202 "must set init style when field is created");
4203
4204 if (!InitExpr.isUsable() ||
4205 DiagnoseUnexpandedParameterPack(InitExpr.get(), UPPC_Initializer)) {
4206 FD->setInvalidDecl();
4207 ExprResult RecoveryInit =
4208 CreateRecoveryExpr(InitLoc, InitLoc, {}, 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.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(InitExpr.get(), /*DiscarededValue=*/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.
4233 static 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(BaseType, 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(ClassDecl->getLocation(),
4259 SemaRef.Context.getCanonicalTagType(ClassDecl),
4260 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
4273 MemInitResult
4274 Sema::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, InitList,
4285 EllipsisLoc);
4286 }
4287
4288 MemInitResult
4289 Sema::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(Context, LParenLoc, Args, RParenLoc);
4301 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4302 DS, IdLoc, List, EllipsisLoc);
4303 }
4304
4305 namespace {
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.
4309 class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
4310 public:
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>(ND))
4317 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
4318 return isa<TypeDecl>(ND);
4319 }
4320 return false;
4321 }
4322
4323 std::unique_ptr<CorrectionCandidateCallback> clone() override {
4324 return std::make_unique<MemInitializerValidatorCCC>(*this);
4325 }
4326
4327 private:
4328 CXXRecordDecl *ClassDecl;
4329 };
4330
4331 }
4332
4333 bool 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(Result, [this](const NamedDecl *Elem) {
4339 return isa<FieldDecl, IndirectFieldDecl>(Elem) &&
4340 Elem->isPlaceholderVar(getLangOpts());
4341 });
4342 // We did not find a placeholder variable
4343 if (Found == Result.end())
4344 return false;
4345 Diag(Loc, 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>(ND) &&
4351 ND->isPlaceholderVar(getLangOpts()))
4352 Diag(ND->getLocation(), diag::note_reference_placeholder) << ND;
4353 }
4354 return true;
4355 }
4356
4357 ValueDecl *
4358 Sema::tryLookupUnambiguousFieldDecl(RecordDecl *ClassDecl,
4359 const IdentifierInfo *MemberOrBase) {
4360 ValueDecl *ND = nullptr;
4361 for (auto *D : ClassDecl->lookup(MemberOrBase)) {
4362 if (isa<FieldDecl, IndirectFieldDecl>(D)) {
4363 bool IsPlaceholder = D->isPlaceholderVar(getLangOpts());
4364 if (ND) {
4365 if (IsPlaceholder && D->getDeclContext() == ND->getDeclContext())
4366 return nullptr;
4367 break;
4368 }
4369 if (!IsPlaceholder)
4370 return cast<ValueDecl>(D);
4371 ND = cast<ValueDecl>(D);
4372 }
4373 }
4374 return ND;
4375 }
4376
4377 ValueDecl *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
4386 MemInitResult
4387 Sema::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(ConstructorD);
4400
4401 CXXConstructorDecl *Constructor
4402 = dyn_cast<CXXConstructorDecl>(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(EllipsisLoc, 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(TemplateTypeTy, &TInfo);
4440 if (BaseType.isNull())
4441 return true;
4442 } else if (DS.getTypeSpecType() == TST_decltype) {
4443 BaseType = BuildDecltypeType(DS.getRepAsExpr());
4444 } else if (DS.getTypeSpecType() == TST_decltype_auto) {
4445 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
4446 return true;
4447 } else if (DS.getTypeSpecType() == TST_typename_pack_indexing) {
4448 BaseType =
4449 BuildPackIndexingType(DS.getRepAsType().get(), DS.getPackIndexingExpr(),
4450 DS.getBeginLoc(), DS.getEllipsisLoc());
4451 } else {
4452 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
4453 LookupParsedName(R, S, &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, false);
4465 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(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 ElaboratedTypeKeyword::None, SourceLocation(),
4473 SS.getWithLocInContext(Context), *MemberOrBase, IdLoc);
4474 if (BaseType.isNull())
4475 return true;
4476
4477 TInfo = Context.CreateTypeSourceInfo(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 UnqualifiedBase->getCanonicalInjectedSpecializationType(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(BaseTemplate->getTemplateName(), TN,
4501 /*IgnoreDeduced=*/true)) {
4502 Diag(IdLoc, 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(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
4517 CCC, CorrectTypoKind::ErrorRecovery, 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(Corr,
4523 PDiag(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(*this, ClassDecl,
4530 Context.getTypeDeclType(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(Corr,
4536 PDiag(diag::err_mem_init_not_member_or_class_suggest)
4537 << MemberOrBase << false,
4538 PDiag() /*Suppress note, we provide our own.*/);
4539
4540 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
4541 : VirtualBaseSpec;
4542 Diag(BaseSpec->getBeginLoc(), 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(IdLoc, 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(TyD->getLocation(), TyD, /*OdrUse=*/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>(TyD)) {
4563 BaseType = Context.getTagType(ElaboratedTypeKeyword::None,
4564 SS.getScopeRep(), TD, /*OwnsTag=*/false);
4565 auto TL = TLB.push<TagTypeLoc>(BaseType);
4566 TL.setElaboratedKeywordLoc(SourceLocation());
4567 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4568 TL.setNameLoc(IdLoc);
4569 } else if (auto *TN = dyn_cast<TypedefNameDecl>(TyD)) {
4570 BaseType = Context.getTypedefType(ElaboratedTypeKeyword::None,
4571 SS.getScopeRep(), TN);
4572 TLB.push<TypedefTypeLoc>(BaseType).set(
4573 /*ElaboratedKeywordLoc=*/SourceLocation(),
4574 SS.getWithLocInContext(Context), IdLoc);
4575 } else if (auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(TyD)) {
4576 BaseType = Context.getUnresolvedUsingType(ElaboratedTypeKeyword::None,
4577 SS.getScopeRep(), UD);
4578 TLB.push<UnresolvedUsingTypeLoc>(BaseType).set(
4579 /*ElaboratedKeywordLoc=*/SourceLocation(),
4580 SS.getWithLocInContext(Context), IdLoc);
4581 } else {
4582 // FIXME: What else can appear here?
4583 assert(SS.isEmpty());
4584 BaseType = Context.getTypeDeclType(TyD);
4585 TLB.pushTypeSpec(BaseType).setNameLoc(IdLoc);
4586 }
4587 TInfo = TLB.getTypeSourceInfo(Context, BaseType);
4588 }
4589 }
4590
4591 if (!TInfo)
4592 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
4593
4594 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
4595 }
4596
4597 MemInitResult
4598 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
4599 SourceLocation IdLoc) {
4600 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
4601 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
4602 assert((DirectMember || IndirectMember) &&
4603 "Member must be a FieldDecl or IndirectFieldDecl");
4604
4605 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4606 return true;
4607
4608 if (Member->isInvalidDecl())
4609 return true;
4610
4611 MultiExprArg Args;
4612 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4613 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4614 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(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>(Init)) {
4630 InitList = true;
4631 Args = Init;
4632 }
4633
4634 // Initialize the member.
4635 InitializedEntity MemberEntity =
4636 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4637 : InitializedEntity::InitializeMember(IndirectMember,
4638 nullptr);
4639 InitializationKind Kind =
4640 InitList ? InitializationKind::CreateDirectList(
4641 IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4642 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4643 InitRange.getEnd());
4644
4645 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4646 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4647 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(MemberInit.get(), 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(InitRange.getBegin(), InitRange.getEnd(), Args,
4660 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
4680 MemInitResult
4681 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
4682 CXXRecordDecl *ClassDecl) {
4683 SourceLocation NameLoc = TInfo->getTypeLoc().getSourceRange().getBegin();
4684 if (!LangOpts.CPlusPlus11)
4685 return Diag(NameLoc, diag::err_delegating_ctor)
4686 << TInfo->getTypeLoc().getSourceRange();
4687 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4688
4689 bool InitList = true;
4690 MultiExprArg Args = Init;
4691 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4692 InitList = false;
4693 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4694 }
4695
4696 CanQualType ClassType = Context.getCanonicalTagType(ClassDecl);
4697
4698 SourceRange InitRange = Init->getSourceRange();
4699 // Initialize the object.
4700 InitializedEntity DelegationEntity =
4701 InitializedEntity::InitializeDelegation(ClassType);
4702 InitializationKind Kind =
4703 InitList ? InitializationKind::CreateDirectList(
4704 NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4705 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4706 InitRange.getEnd());
4707 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4708 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4709 Args, 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 DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
4720 }
4721
4722 if (DelegationInit.isInvalid()) {
4723 DelegationInit = CreateRecoveryExpr(InitRange.getBegin(),
4724 InitRange.getEnd(), Args, 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
4744 MemInitResult
4745 Sema::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(BaseLoc, 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(EllipsisLoc, 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(BaseLoc, BaseTInfo, UPPC_Initializer))
4779 return true;
4780
4781 if (DiagnoseUnexpandedParameterPack(Init, 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(ClassDecl, BaseType->getAsCXXRecordDecl()))
4790 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4791
4792 FindBaseInitializer(*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(BaseLoc, diag::err_not_direct_base_or_virtual)
4809 << BaseType << Context.getCanonicalTagType(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(BaseLoc, 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>(Init)) {
4839 InitList = false;
4840 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4841 }
4842
4843 InitializedEntity BaseEntity =
4844 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4845 InitializationKind Kind =
4846 InitList ? InitializationKind::CreateDirectList(BaseLoc)
4847 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4848 InitRange.getEnd());
4849 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4850 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, 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(BaseInit.get(), InitRange.getBegin(),
4856 /*DiscardedValue*/ false);
4857 }
4858
4859 if (BaseInit.isInvalid()) {
4860 BaseInit = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(),
4861 Args, 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).
4884 static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
4885 QualType TargetType =
4886 SemaRef.BuildReferenceType(E->getType(), /*SpelledAsLValue*/ false,
4887 SourceLocation(), DeclarationName());
4888 SourceLocation ExprLoc = E->getBeginLoc();
4889 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4890 TargetType, ExprLoc);
4891
4892 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4893 SourceRange(ExprLoc, ExprLoc),
4894 E->getSourceRange()).get();
4895 }
4896
4897 /// ImplicitInitializerKind - How an implicit base or member initializer should
4898 /// initialize its base or member.
4899 enum ImplicitInitializerKind {
4900 IIK_Default,
4901 IIK_Copy,
4902 IIK_Move,
4903 IIK_Inherit
4904 };
4905
4906 static bool
4907 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4908 ImplicitInitializerKind ImplicitInitKind,
4909 CXXBaseSpecifier *BaseSpec,
4910 bool IsInheritedVirtualBase,
4911 CXXCtorInitializer *&CXXBaseInit) {
4912 InitializedEntity InitEntity
4913 = InitializedEntity::InitializeBase(SemaRef.Context, 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(Constructor->getLocation());
4923 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, {});
4924 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, {});
4925 break;
4926 }
4927
4928 case IIK_Move:
4929 case IIK_Copy: {
4930 bool Moving = ImplicitInitKind == IIK_Move;
4931 ParmVarDecl *Param = Constructor->getParamDecl(0);
4932 QualType ParamType = Param->getType().getNonReferenceType();
4933
4934 Expr *CopyCtorArg =
4935 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4936 SourceLocation(), Param, false,
4937 Constructor->getLocation(), ParamType,
4938 VK_LValue, nullptr);
4939
4940 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4941
4942 // Cast to the base class to avoid ambiguities.
4943 QualType ArgTy =
4944 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4945 ParamType.getQualifiers());
4946
4947 if (Moving) {
4948 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4949 }
4950
4951 CXXCastPath BasePath;
4952 BasePath.push_back(BaseSpec);
4953 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4954 CK_UncheckedDerivedToBase,
4955 Moving ? VK_XValue : VK_LValue,
4956 &BasePath).get();
4957
4958 InitializationKind InitKind
4959 = InitializationKind::CreateDirect(Constructor->getLocation(),
4960 SourceLocation(), SourceLocation());
4961 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4962 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4963 break;
4964 }
4965 }
4966
4967 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4968 if (BaseInit.isInvalid())
4969 return true;
4970
4971 CXXBaseInit =
4972 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4973 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4974 SourceLocation()),
4975 BaseSpec->isVirtual(),
4976 SourceLocation(),
4977 BaseInit.getAs<Expr>(),
4978 SourceLocation(),
4979 SourceLocation());
4980
4981 return false;
4982 }
4983
4984 static bool RefersToRValueRef(Expr *MemRef) {
4985 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4986 return Referenced->getType()->isRValueReferenceType();
4987 }
4988
4989 static bool
4990 BuildImplicitMemberInitializer(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(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(SemaRef.Context, NestedNameSpecifierLoc(),
5010 SourceLocation(), Param, false,
5011 Loc, ParamType, VK_LValue, nullptr);
5012
5013 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
5014
5015 if (Moving) {
5016 MemberExprBase = CastForMoving(SemaRef, 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(Indirect ? cast<ValueDecl>(Indirect)
5024 : cast<ValueDecl>(Field), AS_public);
5025 MemberLookup.resolveKind();
5026 ExprResult CtorArg
5027 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
5028 ParamType, Loc,
5029 /*IsArrow=*/false,
5030 SS,
5031 /*TemplateKWLoc=*/SourceLocation(),
5032 /*FirstQualifierInScope=*/nullptr,
5033 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(CtorArg.get())) {
5043 CtorArg = CastForMoving(SemaRef, CtorArg.get());
5044 }
5045
5046 InitializedEntity Entity =
5047 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
5048 /*Implicit*/ true)
5049 : InitializedEntity::InitializeMember(Field, nullptr,
5050 /*Implicit*/ true);
5051
5052 // Direct-initialize to use the copy constructor.
5053 InitializationKind InitKind =
5054 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
5055
5056 Expr *CtorArgE = CtorArg.getAs<Expr>();
5057 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
5058 ExprResult MemberInit =
5059 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
5060 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
5061 if (MemberInit.isInvalid())
5062 return true;
5063
5064 if (Indirect)
5065 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
5066 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
5067 else
5068 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
5069 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
5070 return false;
5071 }
5072
5073 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
5074 "Unhandled implicit init kind!");
5075
5076 QualType FieldBaseElementType =
5077 SemaRef.Context.getBaseElementType(Field->getType());
5078
5079 if (FieldBaseElementType->isRecordType()) {
5080 InitializedEntity InitEntity =
5081 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
5082 /*Implicit*/ true)
5083 : InitializedEntity::InitializeMember(Field, nullptr,
5084 /*Implicit*/ true);
5085 InitializationKind InitKind =
5086 InitializationKind::CreateDefault(Loc);
5087
5088 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, {});
5089 ExprResult MemberInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, {});
5090
5091 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
5092 if (MemberInit.isInvalid())
5093 return true;
5094
5095 if (Indirect)
5096 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5097 Indirect, Loc,
5098 Loc,
5099 MemberInit.get(),
5100 Loc);
5101 else
5102 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5103 Field, Loc, Loc,
5104 MemberInit.get(),
5105 Loc);
5106 return false;
5107 }
5108
5109 if (!Field->getParent()->isUnion()) {
5110 if (FieldBaseElementType->isReferenceType()) {
5111 SemaRef.Diag(Constructor->getLocation(),
5112 diag::err_uninitialized_member_in_ctor)
5113 << (int)Constructor->isImplicit()
5114 << SemaRef.Context.getCanonicalTagType(Constructor->getParent()) << 0
5115 << Field->getDeclName();
5116 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
5117 return true;
5118 }
5119
5120 if (FieldBaseElementType.isConstQualified()) {
5121 SemaRef.Diag(Constructor->getLocation(),
5122 diag::err_uninitialized_member_in_ctor)
5123 << (int)Constructor->isImplicit()
5124 << SemaRef.Context.getCanonicalTagType(Constructor->getParent()) << 1
5125 << Field->getDeclName();
5126 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
5127 return true;
5128 }
5129 }
5130
5131 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
5132 // ARC and Weak:
5133 // Default-initialize Objective-C pointers to NULL.
5134 CXXMemberInit
5135 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
5136 Loc, Loc,
5137 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
5138 Loc);
5139 return false;
5140 }
5141
5142 // Nothing to initialize.
5143 CXXMemberInit = nullptr;
5144 return false;
5145 }
5146
5147 namespace {
5148 struct BaseAndFieldInfo {
5149 Sema &S;
5150 CXXConstructorDecl *Ctor;
5151 bool AnyErrorsInInits;
5152 ImplicitInitializerKind IIK;
5153 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
5154 SmallVector<CXXCtorInitializer*, 8> AllToInit;
5155 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
5156
5157 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
5158 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
5159 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
5160 if (Ctor->getInheritedConstructor())
5161 IIK = IIK_Inherit;
5162 else if (Generated && Ctor->isCopyConstructor())
5163 IIK = IIK_Copy;
5164 else if (Generated && Ctor->isMoveConstructor())
5165 IIK = IIK_Move;
5166 else
5167 IIK = IIK_Default;
5168 }
5169
5170 bool isImplicitCopyOrMove() const {
5171 switch (IIK) {
5172 case IIK_Copy:
5173 case IIK_Move:
5174 return true;
5175
5176 case IIK_Default:
5177 case IIK_Inherit:
5178 return false;
5179 }
5180
5181 llvm_unreachable("Invalid ImplicitInitializerKind!");
5182 }
5183
5184 bool addFieldInitializer(CXXCtorInitializer *Init) {
5185 AllToInit.push_back(Init);
5186
5187 // Check whether this initializer makes the field "used".
5188 if (Init->getInit()->HasSideEffects(S.Context))
5189 S.UnusedPrivateFields.remove(Init->getAnyMember());
5190
5191 return false;
5192 }
5193
5194 bool isInactiveUnionMember(FieldDecl *Field) {
5195 RecordDecl *Record = Field->getParent();
5196 if (!Record->isUnion())
5197 return false;
5198
5199 if (FieldDecl *Active =
5200 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
5201 return Active != Field->getCanonicalDecl();
5202
5203 // In an implicit copy or move constructor, ignore any in-class initializer.
5204 if (isImplicitCopyOrMove())
5205 return true;
5206
5207 // If there's no explicit initialization, the field is active only if it
5208 // has an in-class initializer...
5209 if (Field->hasInClassInitializer())
5210 return false;
5211 // ... or it's an anonymous struct or union whose class has an in-class
5212 // initializer.
5213 if (!Field->isAnonymousStructOrUnion())
5214 return true;
5215 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
5216 return !FieldRD->hasInClassInitializer();
5217 }
5218
5219 /// Determine whether the given field is, or is within, a union member
5220 /// that is inactive (because there was an initializer given for a different
5221 /// member of the union, or because the union was not initialized at all).
5222 bool isWithinInactiveUnionMember(FieldDecl *Field,
5223 IndirectFieldDecl *Indirect) {
5224 if (!Indirect)
5225 return isInactiveUnionMember(Field);
5226
5227 for (auto *C : Indirect->chain()) {
5228 FieldDecl *Field = dyn_cast<FieldDecl>(C);
5229 if (Field && isInactiveUnionMember(Field))
5230 return true;
5231 }
5232 return false;
5233 }
5234 };
5235 }
5236
5237 /// Determine whether the given type is an incomplete or zero-lenfgth
5238 /// array type.
5239 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
5240 if (T->isIncompleteArrayType())
5241 return true;
5242
5243 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
5244 if (ArrayT->isZeroSize())
5245 return true;
5246
5247 T = ArrayT->getElementType();
5248 }
5249
5250 return false;
5251 }
5252
5253 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
5254 FieldDecl *Field,
5255 IndirectFieldDecl *Indirect = nullptr) {
5256 if (Field->isInvalidDecl())
5257 return false;
5258
5259 // Overwhelmingly common case: we have a direct initializer for this field.
5260 if (CXXCtorInitializer *Init =
5261 Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
5262 return Info.addFieldInitializer(Init);
5263
5264 // C++11 [class.base.init]p8:
5265 // if the entity is a non-static data member that has a
5266 // brace-or-equal-initializer and either
5267 // -- the constructor's class is a union and no other variant member of that
5268 // union is designated by a mem-initializer-id or
5269 // -- the constructor's class is not a union, and, if the entity is a member
5270 // of an anonymous union, no other member of that union is designated by
5271 // a mem-initializer-id,
5272 // the entity is initialized as specified in [dcl.init].
5273 //
5274 // We also apply the same rules to handle anonymous structs within anonymous
5275 // unions.
5276 if (Info.isWithinInactiveUnionMember(Field, Indirect))
5277 return false;
5278
5279 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
5280 ExprResult DIE =
5281 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
5282 if (DIE.isInvalid())
5283 return true;
5284
5285 auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
5286 SemaRef.checkInitializerLifetime(Entity, DIE.get());
5287
5288 CXXCtorInitializer *Init;
5289 if (Indirect)
5290 Init = new (SemaRef.Context)
5291 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
5292 SourceLocation(), DIE.get(), SourceLocation());
5293 else
5294 Init = new (SemaRef.Context)
5295 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
5296 SourceLocation(), DIE.get(), SourceLocation());
5297 return Info.addFieldInitializer(Init);
5298 }
5299
5300 // Don't initialize incomplete or zero-length arrays.
5301 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
5302 return false;
5303
5304 // Don't try to build an implicit initializer if there were semantic
5305 // errors in any of the initializers (and therefore we might be
5306 // missing some that the user actually wrote).
5307 if (Info.AnyErrorsInInits)
5308 return false;
5309
5310 CXXCtorInitializer *Init = nullptr;
5311 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
5312 Indirect, Init))
5313 return true;
5314
5315 if (!Init)
5316 return false;
5317
5318 return Info.addFieldInitializer(Init);
5319 }
5320
5321 bool
5322 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
5323 CXXCtorInitializer *Initializer) {
5324 assert(Initializer->isDelegatingInitializer());
5325 Constructor->setNumCtorInitializers(1);
5326 CXXCtorInitializer **initializer =
5327 new (Context) CXXCtorInitializer*[1];
5328 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
5329 Constructor->setCtorInitializers(initializer);
5330
5331 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
5332 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
5333 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
5334 }
5335
5336 DelegatingCtorDecls.push_back(Constructor);
5337
5338 DiagnoseUninitializedFields(*this, Constructor);
5339
5340 return false;
5341 }
5342
5343 static CXXDestructorDecl *LookupDestructorIfRelevant(Sema &S,
5344 CXXRecordDecl *Class) {
5345 if (Class->isInvalidDecl())
5346 return nullptr;
5347 if (Class->hasIrrelevantDestructor())
5348 return nullptr;
5349
5350 // Dtor might still be missing, e.g because it's invalid.
5351 return S.LookupDestructor(Class);
5352 }
5353
5354 static void MarkFieldDestructorReferenced(Sema &S, SourceLocation Location,
5355 FieldDecl *Field) {
5356 if (Field->isInvalidDecl())
5357 return;
5358
5359 // Don't destroy incomplete or zero-length arrays.
5360 if (isIncompleteOrZeroLengthArrayType(S.Context, Field->getType()))
5361 return;
5362
5363 QualType FieldType = S.Context.getBaseElementType(Field->getType());
5364
5365 auto *FieldClassDecl = FieldType->getAsCXXRecordDecl();
5366 if (!FieldClassDecl)
5367 return;
5368
5369 // The destructor for an implicit anonymous union member is never invoked.
5370 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5371 return;
5372
5373 auto *Dtor = LookupDestructorIfRelevant(S, FieldClassDecl);
5374 if (!Dtor)
5375 return;
5376
5377 S.CheckDestructorAccess(Field->getLocation(), Dtor,
5378 S.PDiag(diag::err_access_dtor_field)
5379 << Field->getDeclName() << FieldType);
5380
5381 S.MarkFunctionReferenced(Location, Dtor);
5382 S.DiagnoseUseOfDecl(Dtor, Location);
5383 }
5384
5385 static void MarkBaseDestructorsReferenced(Sema &S, SourceLocation Location,
5386 CXXRecordDecl *ClassDecl) {
5387 if (ClassDecl->isDependentContext())
5388 return;
5389
5390 // We only potentially invoke the destructors of potentially constructed
5391 // subobjects.
5392 bool VisitVirtualBases = !ClassDecl->isAbstract();
5393
5394 // If the destructor exists and has already been marked used in the MS ABI,
5395 // then virtual base destructors have already been checked and marked used.
5396 // Skip checking them again to avoid duplicate diagnostics.
5397 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5398 CXXDestructorDecl *Dtor = ClassDecl->getDestructor();
5399 if (Dtor && Dtor->isUsed())
5400 VisitVirtualBases = false;
5401 }
5402
5403 llvm::SmallPtrSet<const CXXRecordDecl *, 8> DirectVirtualBases;
5404
5405 // Bases.
5406 for (const auto &Base : ClassDecl->bases()) {
5407 auto *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
5408 if (!BaseClassDecl)
5409 continue;
5410
5411 // Remember direct virtual bases.
5412 if (Base.isVirtual()) {
5413 if (!VisitVirtualBases)
5414 continue;
5415 DirectVirtualBases.insert(BaseClassDecl);
5416 }
5417
5418 auto *Dtor = LookupDestructorIfRelevant(S, BaseClassDecl);
5419 if (!Dtor)
5420 continue;
5421
5422 // FIXME: caret should be on the start of the class name
5423 S.CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5424 S.PDiag(diag::err_access_dtor_base)
5425 << Base.getType() << Base.getSourceRange(),
5426 S.Context.getCanonicalTagType(ClassDecl));
5427
5428 S.MarkFunctionReferenced(Location, Dtor);
5429 S.DiagnoseUseOfDecl(Dtor, Location);
5430 }
5431
5432 if (VisitVirtualBases)
5433 S.MarkVirtualBaseDestructorsReferenced(Location, ClassDecl,
5434 &DirectVirtualBases);
5435 }
5436
5437 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5438 ArrayRef<CXXCtorInitializer *> Initializers) {
5439 if (Constructor->isDependentContext()) {
5440 // Just store the initializers as written, they will be checked during
5441 // instantiation.
5442 if (!Initializers.empty()) {
5443 Constructor->setNumCtorInitializers(Initializers.size());
5444 CXXCtorInitializer **baseOrMemberInitializers =
5445 new (Context) CXXCtorInitializer*[Initializers.size()];
5446 memcpy(baseOrMemberInitializers, Initializers.data(),
5447 Initializers.size() * sizeof(CXXCtorInitializer*));
5448 Constructor->setCtorInitializers(baseOrMemberInitializers);
5449 }
5450
5451 // Let template instantiation know whether we had errors.
5452 if (AnyErrors)
5453 Constructor->setInvalidDecl();
5454
5455 return false;
5456 }
5457
5458 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
5459
5460 // We need to build the initializer AST according to order of construction
5461 // and not what user specified in the Initializers list.
5462 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
5463 if (!ClassDecl)
5464 return true;
5465
5466 bool HadError = false;
5467
5468 for (CXXCtorInitializer *Member : Initializers) {
5469 if (Member->isBaseInitializer())
5470 Info.AllBaseFields[Member->getBaseClass()->getAsCanonical<RecordType>()] =
5471 Member;
5472 else {
5473 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
5474
5475 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
5476 for (auto *C : F->chain()) {
5477 FieldDecl *FD = dyn_cast<FieldDecl>(C);
5478 if (FD && FD->getParent()->isUnion())
5479 Info.ActiveUnionMember.insert(std::make_pair(
5480 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5481 }
5482 } else if (FieldDecl *FD = Member->getMember()) {
5483 if (FD->getParent()->isUnion())
5484 Info.ActiveUnionMember.insert(std::make_pair(
5485 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5486 }
5487 }
5488 }
5489
5490 // Keep track of the direct virtual bases.
5491 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
5492 for (auto &I : ClassDecl->bases()) {
5493 if (I.isVirtual())
5494 DirectVBases.insert(&I);
5495 }
5496
5497 // Push virtual bases before others.
5498 for (auto &VBase : ClassDecl->vbases()) {
5499 if (CXXCtorInitializer *Value = Info.AllBaseFields.lookup(
5500 VBase.getType()->getAsCanonical<RecordType>())) {
5501 // [class.base.init]p7, per DR257:
5502 // A mem-initializer where the mem-initializer-id names a virtual base
5503 // class is ignored during execution of a constructor of any class that
5504 // is not the most derived class.
5505 if (ClassDecl->isAbstract()) {
5506 // FIXME: Provide a fixit to remove the base specifier. This requires
5507 // tracking the location of the associated comma for a base specifier.
5508 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
5509 << VBase.getType() << ClassDecl;
5510 DiagnoseAbstractType(ClassDecl);
5511 }
5512
5513 Info.AllToInit.push_back(Value);
5514 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
5515 // [class.base.init]p8, per DR257:
5516 // If a given [...] base class is not named by a mem-initializer-id
5517 // [...] and the entity is not a virtual base class of an abstract
5518 // class, then [...] the entity is default-initialized.
5519 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
5520 CXXCtorInitializer *CXXBaseInit;
5521 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5522 &VBase, IsInheritedVirtualBase,
5523 CXXBaseInit)) {
5524 HadError = true;
5525 continue;
5526 }
5527
5528 Info.AllToInit.push_back(CXXBaseInit);
5529 }
5530 }
5531
5532 // Non-virtual bases.
5533 for (auto &Base : ClassDecl->bases()) {
5534 // Virtuals are in the virtual base list and already constructed.
5535 if (Base.isVirtual())
5536 continue;
5537
5538 if (CXXCtorInitializer *Value = Info.AllBaseFields.lookup(
5539 Base.getType()->getAsCanonical<RecordType>())) {
5540 Info.AllToInit.push_back(Value);
5541 } else if (!AnyErrors) {
5542 CXXCtorInitializer *CXXBaseInit;
5543 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5544 &Base, /*IsInheritedVirtualBase=*/false,
5545 CXXBaseInit)) {
5546 HadError = true;
5547 continue;
5548 }
5549
5550 Info.AllToInit.push_back(CXXBaseInit);
5551 }
5552 }
5553
5554 // Fields.
5555 for (auto *Mem : ClassDecl->decls()) {
5556 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
5557 // C++ [class.bit]p2:
5558 // A declaration for a bit-field that omits the identifier declares an
5559 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
5560 // initialized.
5561 if (F->isUnnamedBitField())
5562 continue;
5563
5564 // If we're not generating the implicit copy/move constructor, then we'll
5565 // handle anonymous struct/union fields based on their individual
5566 // indirect fields.
5567 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
5568 continue;
5569
5570 if (CollectFieldInitializer(*this, Info, F))
5571 HadError = true;
5572 continue;
5573 }
5574
5575 // Beyond this point, we only consider default initialization.
5576 if (Info.isImplicitCopyOrMove())
5577 continue;
5578
5579 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
5580 if (F->getType()->isIncompleteArrayType()) {
5581 assert(ClassDecl->hasFlexibleArrayMember() &&
5582 "Incomplete array type is not valid");
5583 continue;
5584 }
5585
5586 // Initialize each field of an anonymous struct individually.
5587 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
5588 HadError = true;
5589
5590 continue;
5591 }
5592 }
5593
5594 unsigned NumInitializers = Info.AllToInit.size();
5595 if (NumInitializers > 0) {
5596 Constructor->setNumCtorInitializers(NumInitializers);
5597 CXXCtorInitializer **baseOrMemberInitializers =
5598 new (Context) CXXCtorInitializer*[NumInitializers];
5599 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
5600 NumInitializers * sizeof(CXXCtorInitializer*));
5601 Constructor->setCtorInitializers(baseOrMemberInitializers);
5602
5603 SourceLocation Location = Constructor->getLocation();
5604
5605 // Constructors implicitly reference the base and member
5606 // destructors.
5607
5608 for (CXXCtorInitializer *Initializer : Info.AllToInit) {
5609 FieldDecl *Field = Initializer->getAnyMember();
5610 if (!Field)
5611 continue;
5612
5613 // C++ [class.base.init]p12:
5614 // In a non-delegating constructor, the destructor for each
5615 // potentially constructed subobject of class type is potentially
5616 // invoked.
5617 MarkFieldDestructorReferenced(*this, Location, Field);
5618 }
5619
5620 MarkBaseDestructorsReferenced(*this, Location, Constructor->getParent());
5621 }
5622
5623 return HadError;
5624 }
5625
5626 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
5627 if (const RecordType *RT = Field->getType()->getAsCanonical<RecordType>()) {
5628 const RecordDecl *RD = RT->getDecl();
5629 if (RD->isAnonymousStructOrUnion()) {
5630 for (auto *Field : RD->getDefinitionOrSelf()->fields())
5631 PopulateKeysForFields(Field, IdealInits);
5632 return;
5633 }
5634 }
5635 IdealInits.push_back(Field->getCanonicalDecl());
5636 }
5637
5638 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
5639 return Context.getCanonicalType(BaseType).getTypePtr();
5640 }
5641
5642 static const void *GetKeyForMember(ASTContext &Context,
5643 CXXCtorInitializer *Member) {
5644 if (!Member->isAnyMemberInitializer())
5645 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
5646
5647 return Member->getAnyMember()->getCanonicalDecl();
5648 }
5649
5650 static void AddInitializerToDiag(const Sema::SemaDiagnosticBuilder &Diag,
5651 const CXXCtorInitializer *Previous,
5652 const CXXCtorInitializer *Current) {
5653 if (Previous->isAnyMemberInitializer())
5654 Diag << 0 << Previous->getAnyMember();
5655 else
5656 Diag << 1 << Previous->getTypeSourceInfo()->getType();
5657
5658 if (Current->isAnyMemberInitializer())
5659 Diag << 0 << Current->getAnyMember();
5660 else
5661 Diag << 1 << Current->getTypeSourceInfo()->getType();
5662 }
5663
5664 static void DiagnoseBaseOrMemInitializerOrder(
5665 Sema &SemaRef, const CXXConstructorDecl *Constructor,
5666 ArrayRef<CXXCtorInitializer *> Inits) {
5667 if (Constructor->getDeclContext()->isDependentContext())
5668 return;
5669
5670 // Don't check initializers order unless the warning is enabled at the
5671 // location of at least one initializer.
5672 bool ShouldCheckOrder = false;
5673 for (const CXXCtorInitializer *Init : Inits) {
5674 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
5675 Init->getSourceLocation())) {
5676 ShouldCheckOrder = true;
5677 break;
5678 }
5679 }
5680 if (!ShouldCheckOrder)
5681 return;
5682
5683 // Build the list of bases and members in the order that they'll
5684 // actually be initialized. The explicit initializers should be in
5685 // this same order but may be missing things.
5686 SmallVector<const void*, 32> IdealInitKeys;
5687
5688 const CXXRecordDecl *ClassDecl = Constructor->getParent();
5689
5690 // 1. Virtual bases.
5691 for (const auto &VBase : ClassDecl->vbases())
5692 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
5693
5694 // 2. Non-virtual bases.
5695 for (const auto &Base : ClassDecl->bases()) {
5696 if (Base.isVirtual())
5697 continue;
5698 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
5699 }
5700
5701 // 3. Direct fields.
5702 for (auto *Field : ClassDecl->fields()) {
5703 if (Field->isUnnamedBitField())
5704 continue;
5705
5706 PopulateKeysForFields(Field, IdealInitKeys);
5707 }
5708
5709 unsigned NumIdealInits = IdealInitKeys.size();
5710 unsigned IdealIndex = 0;
5711
5712 // Track initializers that are in an incorrect order for either a warning or
5713 // note if multiple ones occur.
5714 SmallVector<unsigned> WarnIndexes;
5715 // Correlates the index of an initializer in the init-list to the index of
5716 // the field/base in the class.
5717 SmallVector<std::pair<unsigned, unsigned>, 32> CorrelatedInitOrder;
5718
5719 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5720 const void *InitKey = GetKeyForMember(SemaRef.Context, Inits[InitIndex]);
5721
5722 // Scan forward to try to find this initializer in the idealized
5723 // initializers list.
5724 for (; IdealIndex != NumIdealInits; ++IdealIndex)
5725 if (InitKey == IdealInitKeys[IdealIndex])
5726 break;
5727
5728 // If we didn't find this initializer, it must be because we
5729 // scanned past it on a previous iteration. That can only
5730 // happen if we're out of order; emit a warning.
5731 if (IdealIndex == NumIdealInits && InitIndex) {
5732 WarnIndexes.push_back(InitIndex);
5733
5734 // Move back to the initializer's location in the ideal list.
5735 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5736 if (InitKey == IdealInitKeys[IdealIndex])
5737 break;
5738
5739 assert(IdealIndex < NumIdealInits &&
5740 "initializer not found in initializer list");
5741 }
5742 CorrelatedInitOrder.emplace_back(IdealIndex, InitIndex);
5743 }
5744
5745 if (WarnIndexes.empty())
5746 return;
5747
5748 // Sort based on the ideal order, first in the pair.
5749 llvm::sort(CorrelatedInitOrder, llvm::less_first());
5750
5751 // Introduce a new scope as SemaDiagnosticBuilder needs to be destroyed to
5752 // emit the diagnostic before we can try adding notes.
5753 {
5754 Sema::SemaDiagnosticBuilder D = SemaRef.Diag(
5755 Inits[WarnIndexes.front() - 1]->getSourceLocation(),
5756 WarnIndexes.size() == 1 ? diag::warn_initializer_out_of_order
5757 : diag::warn_some_initializers_out_of_order);
5758
5759 for (unsigned I = 0; I < CorrelatedInitOrder.size(); ++I) {
5760 if (CorrelatedInitOrder[I].second == I)
5761 continue;
5762 // Ideally we would be using InsertFromRange here, but clang doesn't
5763 // appear to handle InsertFromRange correctly when the source range is
5764 // modified by another fix-it.
5765 D << FixItHint::CreateReplacement(
5766 Inits[I]->getSourceRange(),
5767 Lexer::getSourceText(
5768 CharSourceRange::getTokenRange(
5769 Inits[CorrelatedInitOrder[I].second]->getSourceRange()),
5770 SemaRef.getSourceManager(), SemaRef.getLangOpts()));
5771 }
5772
5773 // If there is only 1 item out of order, the warning expects the name and
5774 // type of each being added to it.
5775 if (WarnIndexes.size() == 1) {
5776 AddInitializerToDiag(D, Inits[WarnIndexes.front() - 1],
5777 Inits[WarnIndexes.front()]);
5778 return;
5779 }
5780 }
5781 // More than 1 item to warn, create notes letting the user know which ones
5782 // are bad.
5783 for (unsigned WarnIndex : WarnIndexes) {
5784 const clang::CXXCtorInitializer *PrevInit = Inits[WarnIndex - 1];
5785 auto D = SemaRef.Diag(PrevInit->getSourceLocation(),
5786 diag::note_initializer_out_of_order);
5787 AddInitializerToDiag(D, PrevInit, Inits[WarnIndex]);
5788 D << PrevInit->getSourceRange();
5789 }
5790 }
5791
5792 namespace {
5793 bool CheckRedundantInit(Sema &S,
5794 CXXCtorInitializer *Init,
5795 CXXCtorInitializer *&PrevInit) {
5796 if (!PrevInit) {
5797 PrevInit = Init;
5798 return false;
5799 }
5800
5801 if (FieldDecl *Field = Init->getAnyMember())
5802 S.Diag(Init->getSourceLocation(),
5803 diag::err_multiple_mem_initialization)
5804 << Field->getDeclName()
5805 << Init->getSourceRange();
5806 else {
5807 const Type *BaseClass = Init->getBaseClass();
5808 assert(BaseClass && "neither field nor base");
5809 S.Diag(Init->getSourceLocation(),
5810 diag::err_multiple_base_initialization)
5811 << QualType(BaseClass, 0)
5812 << Init->getSourceRange();
5813 }
5814 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5815 << 0 << PrevInit->getSourceRange();
5816
5817 return true;
5818 }
5819
5820 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5821 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5822
5823 bool CheckRedundantUnionInit(Sema &S,
5824 CXXCtorInitializer *Init,
5825 RedundantUnionMap &Unions) {
5826 FieldDecl *Field = Init->getAnyMember();
5827 RecordDecl *Parent = Field->getParent();
5828 NamedDecl *Child = Field;
5829
5830 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5831 if (Parent->isUnion()) {
5832 UnionEntry &En = Unions[Parent];
5833 if (En.first && En.first != Child) {
5834 S.Diag(Init->getSourceLocation(),
5835 diag::err_multiple_mem_union_initialization)
5836 << Field->getDeclName()
5837 << Init->getSourceRange();
5838 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5839 << 0 << En.second->getSourceRange();
5840 return true;
5841 }
5842 if (!En.first) {
5843 En.first = Child;
5844 En.second = Init;
5845 }
5846 if (!Parent->isAnonymousStructOrUnion())
5847 return false;
5848 }
5849
5850 Child = Parent;
5851 Parent = cast<RecordDecl>(Parent->getDeclContext());
5852 }
5853
5854 return false;
5855 }
5856 } // namespace
5857
5858 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5859 SourceLocation ColonLoc,
5860 ArrayRef<CXXCtorInitializer*> MemInits,
5861 bool AnyErrors) {
5862 if (!ConstructorDecl)
5863 return;
5864
5865 AdjustDeclIfTemplate(ConstructorDecl);
5866
5867 CXXConstructorDecl *Constructor
5868 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5869
5870 if (!Constructor) {
5871 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5872 return;
5873 }
5874
5875 // Mapping for the duplicate initializers check.
5876 // For member initializers, this is keyed with a FieldDecl*.
5877 // For base initializers, this is keyed with a Type*.
5878 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5879
5880 // Mapping for the inconsistent anonymous-union initializers check.
5881 RedundantUnionMap MemberUnions;
5882
5883 bool HadError = false;
5884 for (unsigned i = 0; i < MemInits.size(); i++) {
5885 CXXCtorInitializer *Init = MemInits[i];
5886
5887 // Set the source order index.
5888 Init->setSourceOrder(i);
5889
5890 if (Init->isAnyMemberInitializer()) {
5891 const void *Key = GetKeyForMember(Context, Init);
5892 if (CheckRedundantInit(*this, Init, Members[Key]) ||
5893 CheckRedundantUnionInit(*this, Init, MemberUnions))
5894 HadError = true;
5895 } else if (Init->isBaseInitializer()) {
5896 const void *Key = GetKeyForMember(Context, Init);
5897 if (CheckRedundantInit(*this, Init, Members[Key]))
5898 HadError = true;
5899 } else {
5900 assert(Init->isDelegatingInitializer());
5901 // This must be the only initializer
5902 if (MemInits.size() != 1) {
5903 Diag(Init->getSourceLocation(),
5904 diag::err_delegating_initializer_alone)
5905 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5906 // We will treat this as being the only initializer.
5907 }
5908 SetDelegatingInitializer(Constructor, MemInits[i]);
5909 // Return immediately as the initializer is set.
5910 return;
5911 }
5912 }
5913
5914 if (HadError)
5915 return;
5916
5917 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5918
5919 SetCtorInitializers(Constructor, AnyErrors, MemInits);
5920
5921 DiagnoseUninitializedFields(*this, Constructor);
5922 }
5923
5924 void Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5925 CXXRecordDecl *ClassDecl) {
5926 // Ignore dependent contexts. Also ignore unions, since their members never
5927 // have destructors implicitly called.
5928 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5929 return;
5930
5931 // FIXME: all the access-control diagnostics are positioned on the
5932 // field/base declaration. That's probably good; that said, the
5933 // user might reasonably want to know why the destructor is being
5934 // emitted, and we currently don't say.
5935
5936 // Non-static data members.
5937 for (auto *Field : ClassDecl->fields()) {
5938 MarkFieldDestructorReferenced(*this, Location, Field);
5939 }
5940
5941 MarkBaseDestructorsReferenced(*this, Location, ClassDecl);
5942 }
5943
5944 void Sema::MarkVirtualBaseDestructorsReferenced(
5945 SourceLocation Location, CXXRecordDecl *ClassDecl,
5946 llvm::SmallPtrSetImpl<const CXXRecordDecl *> *DirectVirtualBases) {
5947 // Virtual bases.
5948 for (const auto &VBase : ClassDecl->vbases()) {
5949 auto *BaseClassDecl = VBase.getType()->getAsCXXRecordDecl();
5950 if (!BaseClassDecl)
5951 continue;
5952
5953 // Ignore already visited direct virtual bases.
5954 if (DirectVirtualBases && DirectVirtualBases->count(BaseClassDecl))
5955 continue;
5956
5957 auto *Dtor = LookupDestructorIfRelevant(*this, BaseClassDecl);
5958 if (!Dtor)
5959 continue;
5960
5961 CanQualType CT = Context.getCanonicalTagType(ClassDecl);
5962 if (CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
5963 PDiag(diag::err_access_dtor_vbase)
5964 << CT << VBase.getType(),
5965 CT) == AR_accessible) {
5966 CheckDerivedToBaseConversion(
5967 CT, VBase.getType(), diag::err_access_dtor_vbase, 0,
5968 ClassDecl->getLocation(), SourceRange(), DeclarationName(), nullptr);
5969 }
5970
5971 MarkFunctionReferenced(Location, Dtor);
5972 DiagnoseUseOfDecl(Dtor, Location);
5973 }
5974 }
5975
5976 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5977 if (!CDtorDecl)
5978 return;
5979
5980 if (CXXConstructorDecl *Constructor
5981 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5982 if (CXXRecordDecl *ClassDecl = Constructor->getParent();
5983 !ClassDecl || ClassDecl->isInvalidDecl()) {
5984 return;
5985 }
5986 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5987 DiagnoseUninitializedFields(*this, Constructor);
5988 }
5989 }
5990
5991 bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5992 if (!getLangOpts().CPlusPlus)
5993 return false;
5994
5995 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5996 if (!RD)
5997 return false;
5998
5999 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
6000 // class template specialization here, but doing so breaks a lot of code.
6001
6002 // We can't answer whether something is abstract until it has a
6003 // definition. If it's currently being defined, we'll walk back
6004 // over all the declarations when we have a full definition.
6005 const CXXRecordDecl *Def = RD->getDefinition();
6006 if (!Def || Def->isBeingDefined())
6007 return false;
6008
6009 return RD->isAbstract();
6010 }
6011
6012 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
6013 TypeDiagnoser &Diagnoser) {
6014 if (!isAbstractType(Loc, T))
6015 return false;
6016
6017 T = Context.getBaseElementType(T);
6018 Diagnoser.diagnose(*this, Loc, T);
6019 DiagnoseAbstractType(T->getAsCXXRecordDecl());
6020 return true;
6021 }
6022
6023 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
6024 // Check if we've already emitted the list of pure virtual functions
6025 // for this class.
6026 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
6027 return;
6028
6029 // If the diagnostic is suppressed, don't emit the notes. We're only
6030 // going to emit them once, so try to attach them to a diagnostic we're
6031 // actually going to show.
6032 if (Diags.isLastDiagnosticIgnored())
6033 return;
6034
6035 CXXFinalOverriderMap FinalOverriders;
6036 RD->getFinalOverriders(FinalOverriders);
6037
6038 // Keep a set of seen pure methods so we won't diagnose the same method
6039 // more than once.
6040 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
6041
6042 for (const auto &M : FinalOverriders) {
6043 for (const auto &SO : M.second) {
6044 // C++ [class.abstract]p4:
6045 // A class is abstract if it contains or inherits at least one
6046 // pure virtual function for which the final overrider is pure
6047 // virtual.
6048
6049 if (SO.second.size() != 1)
6050 continue;
6051 const CXXMethodDecl *Method = SO.second.front().Method;
6052
6053 if (!Method->isPureVirtual())
6054 continue;
6055
6056 if (!SeenPureMethods.insert(Method).second)
6057 continue;
6058
6059 Diag(Method->getLocation(), diag::note_pure_virtual_function)
6060 << Method->getDeclName() << RD->getDeclName();
6061 }
6062 }
6063
6064 if (!PureVirtualClassDiagSet)
6065 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
6066 PureVirtualClassDiagSet->insert(RD);
6067 }
6068
6069 namespace {
6070 struct AbstractUsageInfo {
6071 Sema &S;
6072 CXXRecordDecl *Record;
6073 CanQualType AbstractType;
6074 bool Invalid;
6075
6076 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
6077 : S(S), Record(Record),
6078 AbstractType(S.Context.getCanonicalTagType(Record)), Invalid(false) {}
6079
6080 void DiagnoseAbstractType() {
6081 if (Invalid) return;
6082 S.DiagnoseAbstractType(Record);
6083 Invalid = true;
6084 }
6085
6086 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
6087 };
6088
6089 struct CheckAbstractUsage {
6090 AbstractUsageInfo &Info;
6091 const NamedDecl *Ctx;
6092
6093 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
6094 : Info(Info), Ctx(Ctx) {}
6095
6096 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
6097 switch (TL.getTypeLocClass()) {
6098 #define ABSTRACT_TYPELOC(CLASS, PARENT)
6099 #define TYPELOC(CLASS, PARENT) \
6100 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
6101 #include "clang/AST/TypeLocNodes.def"
6102 }
6103 }
6104
6105 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6106 Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
6107 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
6108 if (!TL.getParam(I))
6109 continue;
6110
6111 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
6112 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
6113 }
6114 }
6115
6116 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6117 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
6118 }
6119
6120 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6121 // Visit the type parameters from a permissive context.
6122 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
6123 TemplateArgumentLoc TAL = TL.getArgLoc(I);
6124 if (TAL.getArgument().getKind() == TemplateArgument::Type)
6125 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
6126 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
6127 // TODO: other template argument types?
6128 }
6129 }
6130
6131 // Visit pointee types from a permissive context.
6132 #define CheckPolymorphic(Type) \
6133 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
6134 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
6135 }
6136 CheckPolymorphic(PointerTypeLoc)
6137 CheckPolymorphic(ReferenceTypeLoc)
6138 CheckPolymorphic(MemberPointerTypeLoc)
6139 CheckPolymorphic(BlockPointerTypeLoc)
6140 CheckPolymorphic(AtomicTypeLoc)
6141
6142 /// Handle all the types we haven't given a more specific
6143 /// implementation for above.
6144 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
6145 // Every other kind of type that we haven't called out already
6146 // that has an inner type is either (1) sugar or (2) contains that
6147 // inner type in some way as a subobject.
6148 if (TypeLoc Next = TL.getNextTypeLoc())
6149 return Visit(Next, Sel);
6150
6151 // If there's no inner type and we're in a permissive context,
6152 // don't diagnose.
6153 if (Sel == Sema::AbstractNone) return;
6154
6155 // Check whether the type matches the abstract type.
6156 QualType T = TL.getType();
6157 if (T->isArrayType()) {
6158 Sel = Sema::AbstractArrayType;
6159 T = Info.S.Context.getBaseElementType(T);
6160 }
6161 CanQualType CT = T->getCanonicalTypeUnqualified();
6162 if (CT != Info.AbstractType) return;
6163
6164 // It matched; do some magic.
6165 // FIXME: These should be at most warnings. See P0929R2, CWG1640, CWG1646.
6166 if (Sel == Sema::AbstractArrayType) {
6167 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
6168 << T << TL.getSourceRange();
6169 } else {
6170 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
6171 << Sel << T << TL.getSourceRange();
6172 }
6173 Info.DiagnoseAbstractType();
6174 }
6175 };
6176
6177 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
6178 Sema::AbstractDiagSelID Sel) {
6179 CheckAbstractUsage(*this, D).Visit(TL, Sel);
6180 }
6181
6182 }
6183
6184 /// Check for invalid uses of an abstract type in a function declaration.
6185 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6186 FunctionDecl *FD) {
6187 // Only definitions are required to refer to complete and
6188 // non-abstract types.
6189 if (!FD->doesThisDeclarationHaveABody())
6190 return;
6191
6192 // For safety's sake, just ignore it if we don't have type source
6193 // information. This should never happen for non-implicit methods,
6194 // but...
6195 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6196 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractNone);
6197 }
6198
6199 /// Check for invalid uses of an abstract type in a variable0 declaration.
6200 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6201 VarDecl *VD) {
6202 // No need to do the check on definitions, which require that
6203 // the type is complete.
6204 if (VD->isThisDeclarationADefinition())
6205 return;
6206
6207 Info.CheckType(VD, VD->getTypeSourceInfo()->getTypeLoc(),
6208 Sema::AbstractVariableType);
6209 }
6210
6211 /// Check for invalid uses of an abstract type within a class definition.
6212 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6213 CXXRecordDecl *RD) {
6214 for (auto *D : RD->decls()) {
6215 if (D->isImplicit()) continue;
6216
6217 // Step through friends to the befriended declaration.
6218 if (auto *FD = dyn_cast<FriendDecl>(D)) {
6219 D = FD->getFriendDecl();
6220 if (!D) continue;
6221 }
6222
6223 // Functions and function templates.
6224 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6225 CheckAbstractClassUsage(Info, FD);
6226 } else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) {
6227 CheckAbstractClassUsage(Info, FTD->getTemplatedDecl());
6228
6229 // Fields and static variables.
6230 } else if (auto *FD = dyn_cast<FieldDecl>(D)) {
6231 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6232 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
6233 } else if (auto *VD = dyn_cast<VarDecl>(D)) {
6234 CheckAbstractClassUsage(Info, VD);
6235 } else if (auto *VTD = dyn_cast<VarTemplateDecl>(D)) {
6236 CheckAbstractClassUsage(Info, VTD->getTemplatedDecl());
6237
6238 // Nested classes and class templates.
6239 } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
6240 CheckAbstractClassUsage(Info, RD);
6241 } else if (auto *CTD = dyn_cast<ClassTemplateDecl>(D)) {
6242 CheckAbstractClassUsage(Info, CTD->getTemplatedDecl());
6243 }
6244 }
6245 }
6246
6247 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
6248 Attr *ClassAttr = getDLLAttr(Class);
6249 if (!ClassAttr)
6250 return;
6251
6252 assert(ClassAttr->getKind() == attr::DLLExport);
6253
6254 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6255
6256 if (TSK == TSK_ExplicitInstantiationDeclaration)
6257 // Don't go any further if this is just an explicit instantiation
6258 // declaration.
6259 return;
6260
6261 // Add a context note to explain how we got to any diagnostics produced below.
6262 struct MarkingClassDllexported {
6263 Sema &S;
6264 MarkingClassDllexported(Sema &S, CXXRecordDecl *Class,
6265 SourceLocation AttrLoc)
6266 : S(S) {
6267 Sema::CodeSynthesisContext Ctx;
6268 Ctx.Kind = Sema::CodeSynthesisContext::MarkingClassDllexported;
6269 Ctx.PointOfInstantiation = AttrLoc;
6270 Ctx.Entity = Class;
6271 S.pushCodeSynthesisContext(Ctx);
6272 }
6273 ~MarkingClassDllexported() {
6274 S.popCodeSynthesisContext();
6275 }
6276 } MarkingDllexportedContext(S, Class, ClassAttr->getLocation());
6277
6278 if (S.Context.getTargetInfo().getTriple().isOSCygMing())
6279 S.MarkVTableUsed(Class->getLocation(), Class, true);
6280
6281 for (Decl *Member : Class->decls()) {
6282 // Skip members that were not marked exported.
6283 if (!Member->hasAttr<DLLExportAttr>())
6284 continue;
6285
6286 // Defined static variables that are members of an exported base
6287 // class must be marked export too.
6288 auto *VD = dyn_cast<VarDecl>(Member);
6289 if (VD && VD->getStorageClass() == SC_Static &&
6290 TSK == TSK_ImplicitInstantiation)
6291 S.MarkVariableReferenced(VD->getLocation(), VD);
6292
6293 auto *MD = dyn_cast<CXXMethodDecl>(Member);
6294 if (!MD)
6295 continue;
6296
6297 if (MD->isUserProvided()) {
6298 // Instantiate non-default class member functions ...
6299
6300 // .. except for certain kinds of template specializations.
6301 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
6302 continue;
6303
6304 // If this is an MS ABI dllexport default constructor, instantiate any
6305 // default arguments.
6306 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
6307 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6308 if (CD && CD->isDefaultConstructor() && TSK == TSK_Undeclared) {
6309 S.InstantiateDefaultCtorDefaultArgs(CD);
6310 }
6311 }
6312
6313 S.MarkFunctionReferenced(Class->getLocation(), MD);
6314
6315 // The function will be passed to the consumer when its definition is
6316 // encountered.
6317 } else if (MD->isExplicitlyDefaulted()) {
6318 // Synthesize and instantiate explicitly defaulted methods.
6319 S.MarkFunctionReferenced(Class->getLocation(), MD);
6320
6321 if (TSK != TSK_ExplicitInstantiationDefinition) {
6322 // Except for explicit instantiation defs, we will not see the
6323 // definition again later, so pass it to the consumer now.
6324 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
6325 }
6326 } else if (!MD->isTrivial() ||
6327 MD->isCopyAssignmentOperator() ||
6328 MD->isMoveAssignmentOperator()) {
6329 // Synthesize and instantiate non-trivial implicit methods, and the copy
6330 // and move assignment operators. The latter are exported even if they
6331 // are trivial, because the address of an operator can be taken and
6332 // should compare equal across libraries.
6333 S.MarkFunctionReferenced(Class->getLocation(), MD);
6334
6335 // There is no later point when we will see the definition of this
6336 // function, so pass it to the consumer now.
6337 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
6338 }
6339 }
6340 }
6341
6342 static void checkForMultipleExportedDefaultConstructors(Sema &S,
6343 CXXRecordDecl *Class) {
6344 // Only the MS ABI has default constructor closures, so we don't need to do
6345 // this semantic checking anywhere else.
6346 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
6347 return;
6348
6349 CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
6350 for (Decl *Member : Class->decls()) {
6351 // Look for exported default constructors.
6352 auto *CD = dyn_cast<CXXConstructorDecl>(Member);
6353 if (!CD || !CD->isDefaultConstructor())
6354 continue;
6355 auto *Attr = CD->getAttr<DLLExportAttr>();
6356 if (!Attr)
6357 continue;
6358
6359 // If the class is non-dependent, mark the default arguments as ODR-used so
6360 // that we can properly codegen the constructor closure.
6361 if (!Class->isDependentContext()) {
6362 for (ParmVarDecl *PD : CD->parameters()) {
6363 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
6364 S.DiscardCleanupsInEvaluationContext();
6365 }
6366 }
6367
6368 if (LastExportedDefaultCtor) {
6369 S.Diag(LastExportedDefaultCtor->getLocation(),
6370 diag::err_attribute_dll_ambiguous_default_ctor)
6371 << Class;
6372 S.Diag(CD->getLocation(), diag::note_entity_declared_at)
6373 << CD->getDeclName();
6374 return;
6375 }
6376 LastExportedDefaultCtor = CD;
6377 }
6378 }
6379
6380 static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S,
6381 CXXRecordDecl *Class) {
6382 bool ErrorReported = false;
6383 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6384 ClassTemplateDecl *TD) {
6385 if (ErrorReported)
6386 return;
6387 S.Diag(TD->getLocation(),
6388 diag::err_cuda_device_builtin_surftex_cls_template)
6389 << /*surface*/ 0 << TD;
6390 ErrorReported = true;
6391 };
6392
6393 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6394 if (!TD) {
6395 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6396 if (!SD) {
6397 S.Diag(Class->getLocation(),
6398 diag::err_cuda_device_builtin_surftex_ref_decl)
6399 << /*surface*/ 0 << Class;
6400 S.Diag(Class->getLocation(),
6401 diag::note_cuda_device_builtin_surftex_should_be_template_class)
6402 << Class;
6403 return;
6404 }
6405 TD = SD->getSpecializedTemplate();
6406 }
6407
6408 TemplateParameterList *Params = TD->getTemplateParameters();
6409 unsigned N = Params->size();
6410
6411 if (N != 2) {
6412 reportIllegalClassTemplate(S, TD);
6413 S.Diag(TD->getLocation(),
6414 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6415 << TD << 2;
6416 }
6417 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6418 reportIllegalClassTemplate(S, TD);
6419 S.Diag(TD->getLocation(),
6420 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6421 << TD << /*1st*/ 0 << /*type*/ 0;
6422 }
6423 if (N > 1) {
6424 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6425 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6426 reportIllegalClassTemplate(S, TD);
6427 S.Diag(TD->getLocation(),
6428 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6429 << TD << /*2nd*/ 1 << /*integer*/ 1;
6430 }
6431 }
6432 }
6433
6434 static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S,
6435 CXXRecordDecl *Class) {
6436 bool ErrorReported = false;
6437 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6438 ClassTemplateDecl *TD) {
6439 if (ErrorReported)
6440 return;
6441 S.Diag(TD->getLocation(),
6442 diag::err_cuda_device_builtin_surftex_cls_template)
6443 << /*texture*/ 1 << TD;
6444 ErrorReported = true;
6445 };
6446
6447 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6448 if (!TD) {
6449 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6450 if (!SD) {
6451 S.Diag(Class->getLocation(),
6452 diag::err_cuda_device_builtin_surftex_ref_decl)
6453 << /*texture*/ 1 << Class;
6454 S.Diag(Class->getLocation(),
6455 diag::note_cuda_device_builtin_surftex_should_be_template_class)
6456 << Class;
6457 return;
6458 }
6459 TD = SD->getSpecializedTemplate();
6460 }
6461
6462 TemplateParameterList *Params = TD->getTemplateParameters();
6463 unsigned N = Params->size();
6464
6465 if (N != 3) {
6466 reportIllegalClassTemplate(S, TD);
6467 S.Diag(TD->getLocation(),
6468 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6469 << TD << 3;
6470 }
6471 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6472 reportIllegalClassTemplate(S, TD);
6473 S.Diag(TD->getLocation(),
6474 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6475 << TD << /*1st*/ 0 << /*type*/ 0;
6476 }
6477 if (N > 1) {
6478 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6479 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6480 reportIllegalClassTemplate(S, TD);
6481 S.Diag(TD->getLocation(),
6482 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6483 << TD << /*2nd*/ 1 << /*integer*/ 1;
6484 }
6485 }
6486 if (N > 2) {
6487 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2));
6488 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6489 reportIllegalClassTemplate(S, TD);
6490 S.Diag(TD->getLocation(),
6491 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6492 << TD << /*3rd*/ 2 << /*integer*/ 1;
6493 }
6494 }
6495 }
6496
6497 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
6498 // Mark any compiler-generated routines with the implicit code_seg attribute.
6499 for (auto *Method : Class->methods()) {
6500 if (Method->isUserProvided())
6501 continue;
6502 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
6503 Method->addAttr(A);
6504 }
6505 }
6506
6507 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
6508 Attr *ClassAttr = getDLLAttr(Class);
6509
6510 // MSVC inherits DLL attributes to partial class template specializations.
6511 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) {
6512 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
6513 if (Attr *TemplateAttr =
6514 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
6515 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
6516 A->setInherited(true);
6517 ClassAttr = A;
6518 }
6519 }
6520 }
6521
6522 if (!ClassAttr)
6523 return;
6524
6525 // MSVC allows imported or exported template classes that have UniqueExternal
6526 // linkage. This occurs when the template class has been instantiated with
6527 // a template parameter which itself has internal linkage.
6528 // We drop the attribute to avoid exporting or importing any members.
6529 if ((Context.getTargetInfo().getCXXABI().isMicrosoft() ||
6530 Context.getTargetInfo().getTriple().isPS()) &&
6531 (!Class->isExternallyVisible() && Class->hasExternalFormalLinkage())) {
6532 Class->dropAttrs<DLLExportAttr, DLLImportAttr>();
6533 return;
6534 }
6535
6536 if (!Class->isExternallyVisible()) {
6537 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
6538 << Class << ClassAttr;
6539 return;
6540 }
6541
6542 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6543 !ClassAttr->isInherited()) {
6544 // Diagnose dll attributes on members of class with dll attribute.
6545 for (Decl *Member : Class->decls()) {
6546 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
6547 continue;
6548 InheritableAttr *MemberAttr = getDLLAttr(Member);
6549 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
6550 continue;
6551
6552 Diag(MemberAttr->getLocation(),
6553 diag::err_attribute_dll_member_of_dll_class)
6554 << MemberAttr << ClassAttr;
6555 Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
6556 Member->setInvalidDecl();
6557 }
6558 }
6559
6560 if (Class->getDescribedClassTemplate())
6561 // Don't inherit dll attribute until the template is instantiated.
6562 return;
6563
6564 // The class is either imported or exported.
6565 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
6566
6567 // Check if this was a dllimport attribute propagated from a derived class to
6568 // a base class template specialization. We don't apply these attributes to
6569 // static data members.
6570 const bool PropagatedImport =
6571 !ClassExported &&
6572 cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
6573
6574 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6575
6576 // Ignore explicit dllexport on explicit class template instantiation
6577 // declarations, except in MinGW mode.
6578 if (ClassExported && !ClassAttr->isInherited() &&
6579 TSK == TSK_ExplicitInstantiationDeclaration &&
6580 !Context.getTargetInfo().getTriple().isOSCygMing()) {
6581 if (auto *DEA = Class->getAttr<DLLExportAttr>()) {
6582 Class->addAttr(DLLExportOnDeclAttr::Create(Context, DEA->getLoc()));
6583 Class->dropAttr<DLLExportAttr>();
6584 }
6585 return;
6586 }
6587
6588 // Force declaration of implicit members so they can inherit the attribute.
6589 ForceDeclarationOfImplicitMembers(Class);
6590
6591 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
6592 // seem to be true in practice?
6593
6594 for (Decl *Member : Class->decls()) {
6595 VarDecl *VD = dyn_cast<VarDecl>(Member);
6596 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
6597
6598 // Only methods and static fields inherit the attributes.
6599 if (!VD && !MD)
6600 continue;
6601
6602 if (MD) {
6603 // Don't process deleted methods.
6604 if (MD->isDeleted())
6605 continue;
6606
6607 if (MD->isInlined()) {
6608 // MinGW does not import or export inline methods. But do it for
6609 // template instantiations.
6610 if (!Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6611 TSK != TSK_ExplicitInstantiationDeclaration &&
6612 TSK != TSK_ExplicitInstantiationDefinition)
6613 continue;
6614
6615 // MSVC versions before 2015 don't export the move assignment operators
6616 // and move constructor, so don't attempt to import/export them if
6617 // we have a definition.
6618 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
6619 if ((MD->isMoveAssignmentOperator() ||
6620 (Ctor && Ctor->isMoveConstructor())) &&
6621 getLangOpts().isCompatibleWithMSVC() &&
6622 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
6623 continue;
6624
6625 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
6626 // operator is exported anyway.
6627 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6628 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
6629 continue;
6630 }
6631 }
6632
6633 // Don't apply dllimport attributes to static data members of class template
6634 // instantiations when the attribute is propagated from a derived class.
6635 if (VD && PropagatedImport)
6636 continue;
6637
6638 if (!cast<NamedDecl>(Member)->isExternallyVisible())
6639 continue;
6640
6641 if (!getDLLAttr(Member)) {
6642 InheritableAttr *NewAttr = nullptr;
6643
6644 // Do not export/import inline function when -fno-dllexport-inlines is
6645 // passed. But add attribute for later local static var check.
6646 if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
6647 TSK != TSK_ExplicitInstantiationDeclaration &&
6648 TSK != TSK_ExplicitInstantiationDefinition) {
6649 if (ClassExported) {
6650 NewAttr = ::new (getASTContext())
6651 DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);
6652 } else {
6653 NewAttr = ::new (getASTContext())
6654 DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);
6655 }
6656 } else {
6657 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6658 }
6659
6660 NewAttr->setInherited(true);
6661 Member->addAttr(NewAttr);
6662
6663 if (MD) {
6664 // Propagate DLLAttr to friend re-declarations of MD that have already
6665 // been constructed.
6666 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
6667 FD = FD->getPreviousDecl()) {
6668 if (FD->getFriendObjectKind() == Decl::FOK_None)
6669 continue;
6670 assert(!getDLLAttr(FD) &&
6671 "friend re-decl should not already have a DLLAttr");
6672 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6673 NewAttr->setInherited(true);
6674 FD->addAttr(NewAttr);
6675 }
6676 }
6677 }
6678 }
6679
6680 if (ClassExported)
6681 DelayedDllExportClasses.push_back(Class);
6682 }
6683
6684 void Sema::propagateDLLAttrToBaseClassTemplate(
6685 CXXRecordDecl *Class, Attr *ClassAttr,
6686 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
6687 if (getDLLAttr(
6688 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
6689 // If the base class template has a DLL attribute, don't try to change it.
6690 return;
6691 }
6692
6693 auto TSK = BaseTemplateSpec->getSpecializationKind();
6694 if (!getDLLAttr(BaseTemplateSpec) &&
6695 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
6696 TSK == TSK_ImplicitInstantiation)) {
6697 // The template hasn't been instantiated yet (or it has, but only as an
6698 // explicit instantiation declaration or implicit instantiation, which means
6699 // we haven't codegenned any members yet), so propagate the attribute.
6700 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6701 NewAttr->setInherited(true);
6702 BaseTemplateSpec->addAttr(NewAttr);
6703
6704 // If this was an import, mark that we propagated it from a derived class to
6705 // a base class template specialization.
6706 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
6707 ImportAttr->setPropagatedToBaseTemplate();
6708
6709 // If the template is already instantiated, checkDLLAttributeRedeclaration()
6710 // needs to be run again to work see the new attribute. Otherwise this will
6711 // get run whenever the template is instantiated.
6712 if (TSK != TSK_Undeclared)
6713 checkClassLevelDLLAttribute(BaseTemplateSpec);
6714
6715 return;
6716 }
6717
6718 if (getDLLAttr(BaseTemplateSpec)) {
6719 // The template has already been specialized or instantiated with an
6720 // attribute, explicitly or through propagation. We should not try to change
6721 // it.
6722 return;
6723 }
6724
6725 // The template was previously instantiated or explicitly specialized without
6726 // a dll attribute, It's too late for us to add an attribute, so warn that
6727 // this is unsupported.
6728 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
6729 << BaseTemplateSpec->isExplicitSpecialization();
6730 Diag(ClassAttr->getLocation(), diag::note_attribute);
6731 if (BaseTemplateSpec->isExplicitSpecialization()) {
6732 Diag(BaseTemplateSpec->getLocation(),
6733 diag::note_template_class_explicit_specialization_was_here)
6734 << BaseTemplateSpec;
6735 } else {
6736 Diag(BaseTemplateSpec->getPointOfInstantiation(),
6737 diag::note_template_class_instantiation_was_here)
6738 << BaseTemplateSpec;
6739 }
6740 }
6741
6742 Sema::DefaultedFunctionKind
6743 Sema::getDefaultedFunctionKind(const FunctionDecl *FD) {
6744 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
6745 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
6746 if (Ctor->isDefaultConstructor())
6747 return CXXSpecialMemberKind::DefaultConstructor;
6748
6749 if (Ctor->isCopyConstructor())
6750 return CXXSpecialMemberKind::CopyConstructor;
6751
6752 if (Ctor->isMoveConstructor())
6753 return CXXSpecialMemberKind::MoveConstructor;
6754 }
6755
6756 if (MD->isCopyAssignmentOperator())
6757 return CXXSpecialMemberKind::CopyAssignment;
6758
6759 if (MD->isMoveAssignmentOperator())
6760 return CXXSpecialMemberKind::MoveAssignment;
6761
6762 if (isa<CXXDestructorDecl>(FD))
6763 return CXXSpecialMemberKind::Destructor;
6764 }
6765
6766 switch (FD->getDeclName().getCXXOverloadedOperator()) {
6767 case OO_EqualEqual:
6768 return DefaultedComparisonKind::Equal;
6769
6770 case OO_ExclaimEqual:
6771 return DefaultedComparisonKind::NotEqual;
6772
6773 case OO_Spaceship:
6774 // No point allowing this if <=> doesn't exist in the current language mode.
6775 if (!getLangOpts().CPlusPlus20)
6776 break;
6777 return DefaultedComparisonKind::ThreeWay;
6778
6779 case OO_Less:
6780 case OO_LessEqual:
6781 case OO_Greater:
6782 case OO_GreaterEqual:
6783 // No point allowing this if <=> doesn't exist in the current language mode.
6784 if (!getLangOpts().CPlusPlus20)
6785 break;
6786 return DefaultedComparisonKind::Relational;
6787
6788 default:
6789 break;
6790 }
6791
6792 // Not defaultable.
6793 return DefaultedFunctionKind();
6794 }
6795
6796 static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD,
6797 SourceLocation DefaultLoc) {
6798 Sema::DefaultedFunctionKind DFK = S.getDefaultedFunctionKind(FD);
6799 if (DFK.isComparison())
6800 return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison());
6801
6802 switch (DFK.asSpecialMember()) {
6803 case CXXSpecialMemberKind::DefaultConstructor:
6804 S.DefineImplicitDefaultConstructor(DefaultLoc,
6805 cast<CXXConstructorDecl>(FD));
6806 break;
6807 case CXXSpecialMemberKind::CopyConstructor:
6808 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6809 break;
6810 case CXXSpecialMemberKind::CopyAssignment:
6811 S.DefineImplicitCopyAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6812 break;
6813 case CXXSpecialMemberKind::Destructor:
6814 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(FD));
6815 break;
6816 case CXXSpecialMemberKind::MoveConstructor:
6817 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6818 break;
6819 case CXXSpecialMemberKind::MoveAssignment:
6820 S.DefineImplicitMoveAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6821 break;
6822 case CXXSpecialMemberKind::Invalid:
6823 llvm_unreachable("Invalid special member.");
6824 }
6825 }
6826
6827 /// Determine whether a type is permitted to be passed or returned in
6828 /// registers, per C++ [class.temporary]p3.
6829 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
6830 TargetInfo::CallingConvKind CCK) {
6831 if (D->isDependentType() || D->isInvalidDecl())
6832 return false;
6833
6834 // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
6835 // The PS4 platform ABI follows the behavior of Clang 3.2.
6836 if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
6837 return !D->hasNonTrivialDestructorForCall() &&
6838 !D->hasNonTrivialCopyConstructorForCall();
6839
6840 if (CCK == TargetInfo::CCK_MicrosoftWin64) {
6841 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
6842 bool DtorIsTrivialForCall = false;
6843
6844 // If a class has at least one eligible, trivial copy constructor, it
6845 // is passed according to the C ABI. Otherwise, it is passed indirectly.
6846 //
6847 // Note: This permits classes with non-trivial copy or move ctors to be
6848 // passed in registers, so long as they *also* have a trivial copy ctor,
6849 // which is non-conforming.
6850 if (D->needsImplicitCopyConstructor()) {
6851 if (!D->defaultedCopyConstructorIsDeleted()) {
6852 if (D->hasTrivialCopyConstructor())
6853 CopyCtorIsTrivial = true;
6854 if (D->hasTrivialCopyConstructorForCall())
6855 CopyCtorIsTrivialForCall = true;
6856 }
6857 } else {
6858 for (const CXXConstructorDecl *CD : D->ctors()) {
6859 if (CD->isCopyConstructor() && !CD->isDeleted() &&
6860 !CD->isIneligibleOrNotSelected()) {
6861 if (CD->isTrivial())
6862 CopyCtorIsTrivial = true;
6863 if (CD->isTrivialForCall())
6864 CopyCtorIsTrivialForCall = true;
6865 }
6866 }
6867 }
6868
6869 if (D->needsImplicitDestructor()) {
6870 if (!D->defaultedDestructorIsDeleted() &&
6871 D->hasTrivialDestructorForCall())
6872 DtorIsTrivialForCall = true;
6873 } else if (const auto *DD = D->getDestructor()) {
6874 if (!DD->isDeleted() && DD->isTrivialForCall())
6875 DtorIsTrivialForCall = true;
6876 }
6877
6878 // If the copy ctor and dtor are both trivial-for-calls, pass direct.
6879 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
6880 return true;
6881
6882 // If a class has a destructor, we'd really like to pass it indirectly
6883 // because it allows us to elide copies. Unfortunately, MSVC makes that
6884 // impossible for small types, which it will pass in a single register or
6885 // stack slot. Most objects with dtors are large-ish, so handle that early.
6886 // We can't call out all large objects as being indirect because there are
6887 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
6888 // how we pass large POD types.
6889
6890 // Note: This permits small classes with nontrivial destructors to be
6891 // passed in registers, which is non-conforming.
6892 bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
6893 uint64_t TypeSize = isAArch64 ? 128 : 64;
6894
6895 if (CopyCtorIsTrivial && S.getASTContext().getTypeSize(
6896 S.Context.getCanonicalTagType(D)) <= TypeSize)
6897 return true;
6898 return false;
6899 }
6900
6901 // Per C++ [class.temporary]p3, the relevant condition is:
6902 // each copy constructor, move constructor, and destructor of X is
6903 // either trivial or deleted, and X has at least one non-deleted copy
6904 // or move constructor
6905 bool HasNonDeletedCopyOrMove = false;
6906
6907 if (D->needsImplicitCopyConstructor() &&
6908 !D->defaultedCopyConstructorIsDeleted()) {
6909 if (!D->hasTrivialCopyConstructorForCall())
6910 return false;
6911 HasNonDeletedCopyOrMove = true;
6912 }
6913
6914 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
6915 !D->defaultedMoveConstructorIsDeleted()) {
6916 if (!D->hasTrivialMoveConstructorForCall())
6917 return false;
6918 HasNonDeletedCopyOrMove = true;
6919 }
6920
6921 if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
6922 !D->hasTrivialDestructorForCall())
6923 return false;
6924
6925 for (const CXXMethodDecl *MD : D->methods()) {
6926 if (MD->isDeleted() || MD->isIneligibleOrNotSelected())
6927 continue;
6928
6929 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6930 if (CD && CD->isCopyOrMoveConstructor())
6931 HasNonDeletedCopyOrMove = true;
6932 else if (!isa<CXXDestructorDecl>(MD))
6933 continue;
6934
6935 if (!MD->isTrivialForCall())
6936 return false;
6937 }
6938
6939 return HasNonDeletedCopyOrMove;
6940 }
6941
6942 /// Report an error regarding overriding, along with any relevant
6943 /// overridden methods.
6944 ///
6945 /// \param DiagID the primary error to report.
6946 /// \param MD the overriding method.
6947 static bool
6948 ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD,
6949 llvm::function_ref<bool(const CXXMethodDecl *)> Report) {
6950 bool IssuedDiagnostic = false;
6951 for (const CXXMethodDecl *O : MD->overridden_methods()) {
6952 if (Report(O)) {
6953 if (!IssuedDiagnostic) {
6954 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6955 IssuedDiagnostic = true;
6956 }
6957 S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
6958 }
6959 }
6960 return IssuedDiagnostic;
6961 }
6962
6963 void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) {
6964 if (!Record)
6965 return;
6966
6967 if (Record->isAbstract() && !Record->isInvalidDecl()) {
6968 AbstractUsageInfo Info(*this, Record);
6969 CheckAbstractClassUsage(Info, Record);
6970 }
6971
6972 // If this is not an aggregate type and has no user-declared constructor,
6973 // complain about any non-static data members of reference or const scalar
6974 // type, since they will never get initializers.
6975 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
6976 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
6977 !Record->isLambda()) {
6978 bool Complained = false;
6979 for (const auto *F : Record->fields()) {
6980 if (F->hasInClassInitializer() || F->isUnnamedBitField())
6981 continue;
6982
6983 if (F->getType()->isReferenceType() ||
6984 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
6985 if (!Complained) {
6986 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
6987 << Record->getTagKind() << Record;
6988 Complained = true;
6989 }
6990
6991 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
6992 << F->getType()->isReferenceType()
6993 << F->getDeclName();
6994 }
6995 }
6996 }
6997
6998 if (Record->getIdentifier()) {
6999 // C++ [class.mem]p13:
7000 // If T is the name of a class, then each of the following shall have a
7001 // name different from T:
7002 // - every member of every anonymous union that is a member of class T.
7003 //
7004 // C++ [class.mem]p14:
7005 // In addition, if class T has a user-declared constructor (12.1), every
7006 // non-static data member of class T shall have a name different from T.
7007 for (const NamedDecl *Element : Record->lookup(Record->getDeclName())) {
7008 const NamedDecl *D = Element->getUnderlyingDecl();
7009 // Invalid IndirectFieldDecls have already been diagnosed with
7010 // err_anonymous_record_member_redecl in
7011 // SemaDecl.cpp:CheckAnonMemberRedeclaration.
7012 if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
7013 Record->hasUserDeclaredConstructor()) ||
7014 (isa<IndirectFieldDecl>(D) && !D->isInvalidDecl())) {
7015 Diag(Element->getLocation(), diag::err_member_name_of_class)
7016 << D->getDeclName();
7017 break;
7018 }
7019 }
7020 }
7021
7022 // Warn if the class has virtual methods but non-virtual public destructor.
7023 if (Record->isPolymorphic() && !Record->isDependentType()) {
7024 CXXDestructorDecl *dtor = Record->getDestructor();
7025 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
7026 !Record->hasAttr<FinalAttr>())
7027 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
7028 diag::warn_non_virtual_dtor)
7029 << Context.getCanonicalTagType(Record);
7030 }
7031
7032 if (Record->isAbstract()) {
7033 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
7034 Diag(Record->getLocation(), diag::warn_abstract_final_class)
7035 << FA->isSpelledAsSealed();
7036 DiagnoseAbstractType(Record);
7037 }
7038 }
7039
7040 // Warn if the class has a final destructor but is not itself marked final.
7041 if (!Record->hasAttr<FinalAttr>()) {
7042 if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
7043 if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
7044 Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class)
7045 << FA->isSpelledAsSealed()
7046 << FixItHint::CreateInsertion(
7047 getLocForEndOfToken(Record->getLocation()),
7048 (FA->isSpelledAsSealed() ? " sealed" : " final"));
7049 Diag(Record->getLocation(),
7050 diag::note_final_dtor_non_final_class_silence)
7051 << Context.getCanonicalTagType(Record) << FA->isSpelledAsSealed();
7052 }
7053 }
7054 }
7055
7056 // See if trivial_abi has to be dropped.
7057 if (Record->hasAttr<TrivialABIAttr>())
7058 checkIllFormedTrivialABIStruct(*Record);
7059
7060 // Set HasTrivialSpecialMemberForCall if the record has attribute
7061 // "trivial_abi".
7062 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
7063
7064 if (HasTrivialABI)
7065 Record->setHasTrivialSpecialMemberForCall();
7066
7067 // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=).
7068 // We check these last because they can depend on the properties of the
7069 // primary comparison functions (==, <=>).
7070 llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons;
7071
7072 // Perform checks that can't be done until we know all the properties of a
7073 // member function (whether it's defaulted, deleted, virtual, overriding,
7074 // ...).
7075 auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) {
7076 // A static function cannot override anything.
7077 if (MD->getStorageClass() == SC_Static) {
7078 if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD,
7079 [](const CXXMethodDecl *) { return true; }))
7080 return;
7081 }
7082
7083 // A deleted function cannot override a non-deleted function and vice
7084 // versa.
7085 if (ReportOverrides(*this,
7086 MD->isDeleted() ? diag::err_deleted_override
7087 : diag::err_non_deleted_override,
7088 MD, [&](const CXXMethodDecl *V) {
7089 return MD->isDeleted() != V->isDeleted();
7090 })) {
7091 if (MD->isDefaulted() && MD->isDeleted())
7092 // Explain why this defaulted function was deleted.
7093 DiagnoseDeletedDefaultedFunction(MD);
7094 return;
7095 }
7096
7097 // A consteval function cannot override a non-consteval function and vice
7098 // versa.
7099 if (ReportOverrides(*this,
7100 MD->isConsteval() ? diag::err_consteval_override
7101 : diag::err_non_consteval_override,
7102 MD, [&](const CXXMethodDecl *V) {
7103 return MD->isConsteval() != V->isConsteval();
7104 })) {
7105 if (MD->isDefaulted() && MD->isDeleted())
7106 // Explain why this defaulted function was deleted.
7107 DiagnoseDeletedDefaultedFunction(MD);
7108 return;
7109 }
7110 };
7111
7112 auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool {
7113 if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted())
7114 return false;
7115
7116 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
7117 if (DFK.asComparison() == DefaultedComparisonKind::NotEqual ||
7118 DFK.asComparison() == DefaultedComparisonKind::Relational) {
7119 DefaultedSecondaryComparisons.push_back(FD);
7120 return true;
7121 }
7122
7123 CheckExplicitlyDefaultedFunction(S, FD);
7124 return false;
7125 };
7126
7127 if (!Record->isInvalidDecl() &&
7128 Record->hasAttr<VTablePointerAuthenticationAttr>())
7129 checkIncorrectVTablePointerAuthenticationAttribute(*Record);
7130
7131 auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
7132 // Check whether the explicitly-defaulted members are valid.
7133 bool Incomplete = CheckForDefaultedFunction(M);
7134
7135 // Skip the rest of the checks for a member of a dependent class.
7136 if (Record->isDependentType())
7137 return;
7138
7139 // For an explicitly defaulted or deleted special member, we defer
7140 // determining triviality until the class is complete. That time is now!
7141 CXXSpecialMemberKind CSM = getSpecialMember(M);
7142 if (!M->isImplicit() && !M->isUserProvided()) {
7143 if (CSM != CXXSpecialMemberKind::Invalid) {
7144 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
7145 // Inform the class that we've finished declaring this member.
7146 Record->finishedDefaultedOrDeletedMember(M);
7147 M->setTrivialForCall(
7148 HasTrivialABI ||
7149 SpecialMemberIsTrivial(M, CSM,
7150 TrivialABIHandling::ConsiderTrivialABI));
7151 Record->setTrivialForCallFlags(M);
7152 }
7153 }
7154
7155 // Set triviality for the purpose of calls if this is a user-provided
7156 // copy/move constructor or destructor.
7157 if ((CSM == CXXSpecialMemberKind::CopyConstructor ||
7158 CSM == CXXSpecialMemberKind::MoveConstructor ||
7159 CSM == CXXSpecialMemberKind::Destructor) &&
7160 M->isUserProvided()) {
7161 M->setTrivialForCall(HasTrivialABI);
7162 Record->setTrivialForCallFlags(M);
7163 }
7164
7165 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
7166 M->hasAttr<DLLExportAttr>()) {
7167 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
7168 M->isTrivial() &&
7169 (CSM == CXXSpecialMemberKind::DefaultConstructor ||
7170 CSM == CXXSpecialMemberKind::CopyConstructor ||
7171 CSM == CXXSpecialMemberKind::Destructor))
7172 M->dropAttr<DLLExportAttr>();
7173
7174 if (M->hasAttr<DLLExportAttr>()) {
7175 // Define after any fields with in-class initializers have been parsed.
7176 DelayedDllExportMemberFunctions.push_back(M);
7177 }
7178 }
7179
7180 bool EffectivelyConstexprDestructor = true;
7181 // Avoid triggering vtable instantiation due to a dtor that is not
7182 // "effectively constexpr" for better compatibility.
7183 // See https://github.com/llvm/llvm-project/issues/102293 for more info.
7184 if (isa<CXXDestructorDecl>(M)) {
7185 llvm::SmallDenseSet<QualType> Visited;
7186 auto Check = [&Visited](QualType T, auto &&Check) -> bool {
7187 if (!Visited.insert(T->getCanonicalTypeUnqualified()).second)
7188 return false;
7189 const CXXRecordDecl *RD =
7190 T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
7191 if (!RD || !RD->isCompleteDefinition())
7192 return true;
7193
7194 if (!RD->hasConstexprDestructor())
7195 return false;
7196
7197 for (const CXXBaseSpecifier &B : RD->bases())
7198 if (!Check(B.getType(), Check))
7199 return false;
7200 for (const FieldDecl *FD : RD->fields())
7201 if (!Check(FD->getType(), Check))
7202 return false;
7203 return true;
7204 };
7205 EffectivelyConstexprDestructor =
7206 Check(Context.getCanonicalTagType(Record), Check);
7207 }
7208
7209 // Define defaulted constexpr virtual functions that override a base class
7210 // function right away.
7211 // FIXME: We can defer doing this until the vtable is marked as used.
7212 if (CSM != CXXSpecialMemberKind::Invalid && !M->isDeleted() &&
7213 M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods() &&
7214 EffectivelyConstexprDestructor)
7215 DefineDefaultedFunction(*this, M, M->getLocation());
7216
7217 if (!Incomplete)
7218 CheckCompletedMemberFunction(M);
7219 };
7220
7221 // Check the destructor before any other member function. We need to
7222 // determine whether it's trivial in order to determine whether the claas
7223 // type is a literal type, which is a prerequisite for determining whether
7224 // other special member functions are valid and whether they're implicitly
7225 // 'constexpr'.
7226 if (CXXDestructorDecl *Dtor = Record->getDestructor())
7227 CompleteMemberFunction(Dtor);
7228
7229 bool HasMethodWithOverrideControl = false,
7230 HasOverridingMethodWithoutOverrideControl = false;
7231 for (auto *D : Record->decls()) {
7232 if (auto *M = dyn_cast<CXXMethodDecl>(D)) {
7233 // FIXME: We could do this check for dependent types with non-dependent
7234 // bases.
7235 if (!Record->isDependentType()) {
7236 // See if a method overloads virtual methods in a base
7237 // class without overriding any.
7238 if (!M->isStatic())
7239 DiagnoseHiddenVirtualMethods(M);
7240
7241 if (M->hasAttr<OverrideAttr>()) {
7242 HasMethodWithOverrideControl = true;
7243 } else if (M->size_overridden_methods() > 0) {
7244 HasOverridingMethodWithoutOverrideControl = true;
7245 } else {
7246 // Warn on newly-declared virtual methods in `final` classes
7247 if (M->isVirtualAsWritten() && Record->isEffectivelyFinal()) {
7248 Diag(M->getLocation(), diag::warn_unnecessary_virtual_specifier)
7249 << M;
7250 }
7251 }
7252 }
7253
7254 if (!isa<CXXDestructorDecl>(M))
7255 CompleteMemberFunction(M);
7256 } else if (auto *F = dyn_cast<FriendDecl>(D)) {
7257 CheckForDefaultedFunction(
7258 dyn_cast_or_null<FunctionDecl>(F->getFriendDecl()));
7259 }
7260 }
7261
7262 if (HasOverridingMethodWithoutOverrideControl) {
7263 bool HasInconsistentOverrideControl = HasMethodWithOverrideControl;
7264 for (auto *M : Record->methods())
7265 DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl);
7266 }
7267
7268 // Check the defaulted secondary comparisons after any other member functions.
7269 for (FunctionDecl *FD : DefaultedSecondaryComparisons) {
7270 CheckExplicitlyDefaultedFunction(S, FD);
7271
7272 // If this is a member function, we deferred checking it until now.
7273 if (auto *MD = dyn_cast<CXXMethodDecl>(FD))
7274 CheckCompletedMemberFunction(MD);
7275 }
7276
7277 // {ms,gcc}_struct is a request to change ABI rules to either follow
7278 // Microsoft or Itanium C++ ABI. However, even if these attributes are
7279 // present, we do not layout classes following foreign ABI rules, but
7280 // instead enter a special "compatibility mode", which only changes
7281 // alignments of fundamental types and layout of bit fields.
7282 // Check whether this class uses any C++ features that are implemented
7283 // completely differently in the requested ABI, and if so, emit a
7284 // diagnostic. That diagnostic defaults to an error, but we allow
7285 // projects to map it down to a warning (or ignore it). It's a fairly
7286 // common practice among users of the ms_struct pragma to
7287 // mass-annotate headers, sweeping up a bunch of types that the
7288 // project doesn't really rely on MSVC-compatible layout for. We must
7289 // therefore support "ms_struct except for C++ stuff" as a secondary
7290 // ABI.
7291 // Don't emit this diagnostic if the feature was enabled as a
7292 // language option (as opposed to via a pragma or attribute), as
7293 // the option -mms-bitfields otherwise essentially makes it impossible
7294 // to build C++ code, unless this diagnostic is turned off.
7295 if (Context.getLangOpts().getLayoutCompatibility() ==
7296 LangOptions::LayoutCompatibilityKind::Default &&
7297 Record->isMsStruct(Context) != Context.defaultsToMsStruct() &&
7298 (Record->isPolymorphic() || Record->getNumBases())) {
7299 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
7300 }
7301
7302 checkClassLevelDLLAttribute(Record);
7303 checkClassLevelCodeSegAttribute(Record);
7304
7305 bool ClangABICompat4 =
7306 Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
7307 TargetInfo::CallingConvKind CCK =
7308 Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
7309 bool CanPass = canPassInRegisters(*this, Record, CCK);
7310
7311 // Do not change ArgPassingRestrictions if it has already been set to
7312 // RecordArgPassingKind::CanNeverPassInRegs.
7313 if (Record->getArgPassingRestrictions() !=
7314 RecordArgPassingKind::CanNeverPassInRegs)
7315 Record->setArgPassingRestrictions(
7316 CanPass ? RecordArgPassingKind::CanPassInRegs
7317 : RecordArgPassingKind::CannotPassInRegs);
7318
7319 // If canPassInRegisters returns true despite the record having a non-trivial
7320 // destructor, the record is destructed in the callee. This happens only when
7321 // the record or one of its subobjects has a field annotated with trivial_abi
7322 // or a field qualified with ObjC __strong/__weak.
7323 if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
7324 Record->setParamDestroyedInCallee(true);
7325 else if (Record->hasNonTrivialDestructor())
7326 Record->setParamDestroyedInCallee(CanPass);
7327
7328 if (getLangOpts().ForceEmitVTables) {
7329 // If we want to emit all the vtables, we need to mark it as used. This
7330 // is especially required for cases like vtable assumption loads.
7331 MarkVTableUsed(Record->getInnerLocStart(), Record);
7332 }
7333
7334 if (getLangOpts().CUDA) {
7335 if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>())
7336 checkCUDADeviceBuiltinSurfaceClassTemplate(*this, Record);
7337 else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>())
7338 checkCUDADeviceBuiltinTextureClassTemplate(*this, Record);
7339 }
7340
7341 llvm::SmallDenseMap<OverloadedOperatorKind,
7342 llvm::SmallVector<const FunctionDecl *, 2>, 4>
7343 TypeAwareDecls{{OO_New, {}},
7344 {OO_Array_New, {}},
7345 {OO_Delete, {}},
7346 {OO_Array_New, {}}};
7347 for (auto *D : Record->decls()) {
7348 const FunctionDecl *FnDecl = D->getAsFunction();
7349 if (!FnDecl || !FnDecl->isTypeAwareOperatorNewOrDelete())
7350 continue;
7351 assert(FnDecl->getDeclName().isAnyOperatorNewOrDelete());
7352 TypeAwareDecls[FnDecl->getOverloadedOperator()].push_back(FnDecl);
7353 }
7354 auto CheckMismatchedTypeAwareAllocators =
7355 [this, &TypeAwareDecls, Record](OverloadedOperatorKind NewKind,
7356 OverloadedOperatorKind DeleteKind) {
7357 auto &NewDecls = TypeAwareDecls[NewKind];
7358 auto &DeleteDecls = TypeAwareDecls[DeleteKind];
7359 if (NewDecls.empty() == DeleteDecls.empty())
7360 return;
7361 DeclarationName FoundOperator =
7362 Context.DeclarationNames.getCXXOperatorName(
7363 NewDecls.empty() ? DeleteKind : NewKind);
7364 DeclarationName MissingOperator =
7365 Context.DeclarationNames.getCXXOperatorName(
7366 NewDecls.empty() ? NewKind : DeleteKind);
7367 Diag(Record->getLocation(),
7368 diag::err_type_aware_allocator_missing_matching_operator)
7369 << FoundOperator << Context.getCanonicalTagType(Record)
7370 << MissingOperator;
7371 for (auto MD : NewDecls)
7372 Diag(MD->getLocation(),
7373 diag::note_unmatched_type_aware_allocator_declared)
7374 << MD;
7375 for (auto MD : DeleteDecls)
7376 Diag(MD->getLocation(),
7377 diag::note_unmatched_type_aware_allocator_declared)
7378 << MD;
7379 };
7380 CheckMismatchedTypeAwareAllocators(OO_New, OO_Delete);
7381 CheckMismatchedTypeAwareAllocators(OO_Array_New, OO_Array_Delete);
7382 }
7383
7384 /// Look up the special member function that would be called by a special
7385 /// member function for a subobject of class type.
7386 ///
7387 /// \param Class The class type of the subobject.
7388 /// \param CSM The kind of special member function.
7389 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
7390 /// \param ConstRHS True if this is a copy operation with a const object
7391 /// on its RHS, that is, if the argument to the outer special member
7392 /// function is 'const' and this is not a field marked 'mutable'.
7393 static Sema::SpecialMemberOverloadResult
7394 lookupCallFromSpecialMember(Sema &S, CXXRecordDecl *Class,
7395 CXXSpecialMemberKind CSM, unsigned FieldQuals,
7396 bool ConstRHS) {
7397 unsigned LHSQuals = 0;
7398 if (CSM == CXXSpecialMemberKind::CopyAssignment ||
7399 CSM == CXXSpecialMemberKind::MoveAssignment)
7400 LHSQuals = FieldQuals;
7401
7402 unsigned RHSQuals = FieldQuals;
7403 if (CSM == CXXSpecialMemberKind::DefaultConstructor ||
7404 CSM == CXXSpecialMemberKind::Destructor)
7405 RHSQuals = 0;
7406 else if (ConstRHS)
7407 RHSQuals |= Qualifiers::Const;
7408
7409 return S.LookupSpecialMember(Class, CSM,
7410 RHSQuals & Qualifiers::Const,
7411 RHSQuals & Qualifiers::Volatile,
7412 false,
7413 LHSQuals & Qualifiers::Const,
7414 LHSQuals & Qualifiers::Volatile);
7415 }
7416
7417 class Sema::InheritedConstructorInfo {
7418 Sema &S;
7419 SourceLocation UseLoc;
7420
7421 /// A mapping from the base classes through which the constructor was
7422 /// inherited to the using shadow declaration in that base class (or a null
7423 /// pointer if the constructor was declared in that base class).
7424 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
7425 InheritedFromBases;
7426
7427 public:
7428 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
7429 ConstructorUsingShadowDecl *Shadow)
7430 : S(S), UseLoc(UseLoc) {
7431 bool DiagnosedMultipleConstructedBases = false;
7432 CXXRecordDecl *ConstructedBase = nullptr;
7433 BaseUsingDecl *ConstructedBaseIntroducer = nullptr;
7434
7435 // Find the set of such base class subobjects and check that there's a
7436 // unique constructed subobject.
7437 for (auto *D : Shadow->redecls()) {
7438 auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
7439 auto *DNominatedBase = DShadow->getNominatedBaseClass();
7440 auto *DConstructedBase = DShadow->getConstructedBaseClass();
7441
7442 InheritedFromBases.insert(
7443 std::make_pair(DNominatedBase->getCanonicalDecl(),
7444 DShadow->getNominatedBaseClassShadowDecl()));
7445 if (DShadow->constructsVirtualBase())
7446 InheritedFromBases.insert(
7447 std::make_pair(DConstructedBase->getCanonicalDecl(),
7448 DShadow->getConstructedBaseClassShadowDecl()));
7449 else
7450 assert(DNominatedBase == DConstructedBase);
7451
7452 // [class.inhctor.init]p2:
7453 // If the constructor was inherited from multiple base class subobjects
7454 // of type B, the program is ill-formed.
7455 if (!ConstructedBase) {
7456 ConstructedBase = DConstructedBase;
7457 ConstructedBaseIntroducer = D->getIntroducer();
7458 } else if (ConstructedBase != DConstructedBase &&
7459 !Shadow->isInvalidDecl()) {
7460 if (!DiagnosedMultipleConstructedBases) {
7461 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
7462 << Shadow->getTargetDecl();
7463 S.Diag(ConstructedBaseIntroducer->getLocation(),
7464 diag::note_ambiguous_inherited_constructor_using)
7465 << ConstructedBase;
7466 DiagnosedMultipleConstructedBases = true;
7467 }
7468 S.Diag(D->getIntroducer()->getLocation(),
7469 diag::note_ambiguous_inherited_constructor_using)
7470 << DConstructedBase;
7471 }
7472 }
7473
7474 if (DiagnosedMultipleConstructedBases)
7475 Shadow->setInvalidDecl();
7476 }
7477
7478 /// Find the constructor to use for inherited construction of a base class,
7479 /// and whether that base class constructor inherits the constructor from a
7480 /// virtual base class (in which case it won't actually invoke it).
7481 std::pair<CXXConstructorDecl *, bool>
7482 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
7483 auto It = InheritedFromBases.find(Base->getCanonicalDecl());
7484 if (It == InheritedFromBases.end())
7485 return std::make_pair(nullptr, false);
7486
7487 // This is an intermediary class.
7488 if (It->second)
7489 return std::make_pair(
7490 S.findInheritingConstructor(UseLoc, Ctor, It->second),
7491 It->second->constructsVirtualBase());
7492
7493 // This is the base class from which the constructor was inherited.
7494 return std::make_pair(Ctor, false);
7495 }
7496 };
7497
7498 /// Is the special member function which would be selected to perform the
7499 /// specified operation on the specified class type a constexpr constructor?
7500 static bool specialMemberIsConstexpr(
7501 Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, unsigned Quals,
7502 bool ConstRHS, CXXConstructorDecl *InheritedCtor = nullptr,
7503 Sema::InheritedConstructorInfo *Inherited = nullptr) {
7504 // Suppress duplicate constraint checking here, in case a constraint check
7505 // caused us to decide to do this. Any truely recursive checks will get
7506 // caught during these checks anyway.
7507 Sema::SatisfactionStackResetRAII SSRAII{S};
7508
7509 // If we're inheriting a constructor, see if we need to call it for this base
7510 // class.
7511 if (InheritedCtor) {
7512 assert(CSM == CXXSpecialMemberKind::DefaultConstructor);
7513 auto BaseCtor =
7514 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
7515 if (BaseCtor)
7516 return BaseCtor->isConstexpr();
7517 }
7518
7519 if (CSM == CXXSpecialMemberKind::DefaultConstructor)
7520 return ClassDecl->hasConstexprDefaultConstructor();
7521 if (CSM == CXXSpecialMemberKind::Destructor)
7522 return ClassDecl->hasConstexprDestructor();
7523
7524 Sema::SpecialMemberOverloadResult SMOR =
7525 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
7526 if (!SMOR.getMethod())
7527 // A constructor we wouldn't select can't be "involved in initializing"
7528 // anything.
7529 return true;
7530 return SMOR.getMethod()->isConstexpr();
7531 }
7532
7533 /// Determine whether the specified special member function would be constexpr
7534 /// if it were implicitly defined.
7535 static bool defaultedSpecialMemberIsConstexpr(
7536 Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, bool ConstArg,
7537 CXXConstructorDecl *InheritedCtor = nullptr,
7538 Sema::InheritedConstructorInfo *Inherited = nullptr) {
7539 if (!S.getLangOpts().CPlusPlus11)
7540 return false;
7541
7542 // C++11 [dcl.constexpr]p4:
7543 // In the definition of a constexpr constructor [...]
7544 bool Ctor = true;
7545 switch (CSM) {
7546 case CXXSpecialMemberKind::DefaultConstructor:
7547 if (Inherited)
7548 break;
7549 // Since default constructor lookup is essentially trivial (and cannot
7550 // involve, for instance, template instantiation), we compute whether a
7551 // defaulted default constructor is constexpr directly within CXXRecordDecl.
7552 //
7553 // This is important for performance; we need to know whether the default
7554 // constructor is constexpr to determine whether the type is a literal type.
7555 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
7556
7557 case CXXSpecialMemberKind::CopyConstructor:
7558 case CXXSpecialMemberKind::MoveConstructor:
7559 // For copy or move constructors, we need to perform overload resolution.
7560 break;
7561
7562 case CXXSpecialMemberKind::CopyAssignment:
7563 case CXXSpecialMemberKind::MoveAssignment:
7564 if (!S.getLangOpts().CPlusPlus14)
7565 return false;
7566 // In C++1y, we need to perform overload resolution.
7567 Ctor = false;
7568 break;
7569
7570 case CXXSpecialMemberKind::Destructor:
7571 return ClassDecl->defaultedDestructorIsConstexpr();
7572
7573 case CXXSpecialMemberKind::Invalid:
7574 return false;
7575 }
7576
7577 // -- if the class is a non-empty union, or for each non-empty anonymous
7578 // union member of a non-union class, exactly one non-static data member
7579 // shall be initialized; [DR1359]
7580 //
7581 // If we squint, this is guaranteed, since exactly one non-static data member
7582 // will be initialized (if the constructor isn't deleted), we just don't know
7583 // which one.
7584 if (Ctor && ClassDecl->isUnion())
7585 return CSM == CXXSpecialMemberKind::DefaultConstructor
7586 ? ClassDecl->hasInClassInitializer() ||
7587 !ClassDecl->hasVariantMembers()
7588 : true;
7589
7590 // -- the class shall not have any virtual base classes;
7591 if (Ctor && ClassDecl->getNumVBases())
7592 return false;
7593
7594 // C++1y [class.copy]p26:
7595 // -- [the class] is a literal type, and
7596 if (!Ctor && !ClassDecl->isLiteral() && !S.getLangOpts().CPlusPlus23)
7597 return false;
7598
7599 // -- every constructor involved in initializing [...] base class
7600 // sub-objects shall be a constexpr constructor;
7601 // -- the assignment operator selected to copy/move each direct base
7602 // class is a constexpr function, and
7603 if (!S.getLangOpts().CPlusPlus23) {
7604 for (const auto &B : ClassDecl->bases()) {
7605 auto *BaseClassDecl = B.getType()->getAsCXXRecordDecl();
7606 if (!BaseClassDecl)
7607 continue;
7608 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
7609 InheritedCtor, Inherited))
7610 return false;
7611 }
7612 }
7613
7614 // -- every constructor involved in initializing non-static data members
7615 // [...] shall be a constexpr constructor;
7616 // -- every non-static data member and base class sub-object shall be
7617 // initialized
7618 // -- for each non-static data member of X that is of class type (or array
7619 // thereof), the assignment operator selected to copy/move that member is
7620 // a constexpr function
7621 if (!S.getLangOpts().CPlusPlus23) {
7622 for (const auto *F : ClassDecl->fields()) {
7623 if (F->isInvalidDecl())
7624 continue;
7625 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
7626 F->hasInClassInitializer())
7627 continue;
7628 QualType BaseType = S.Context.getBaseElementType(F->getType());
7629 if (const RecordType *RecordTy = BaseType->getAsCanonical<RecordType>()) {
7630 auto *FieldRecDecl =
7631 cast<CXXRecordDecl>(RecordTy->getDecl())->getDefinitionOrSelf();
7632 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
7633 BaseType.getCVRQualifiers(),
7634 ConstArg && !F->isMutable()))
7635 return false;
7636 } else if (CSM == CXXSpecialMemberKind::DefaultConstructor) {
7637 return false;
7638 }
7639 }
7640 }
7641
7642 // All OK, it's constexpr!
7643 return true;
7644 }
7645
7646 namespace {
7647 /// RAII object to register a defaulted function as having its exception
7648 /// specification computed.
7649 struct ComputingExceptionSpec {
7650 Sema &S;
7651
7652 ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc)
7653 : S(S) {
7654 Sema::CodeSynthesisContext Ctx;
7655 Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;
7656 Ctx.PointOfInstantiation = Loc;
7657 Ctx.Entity = FD;
7658 S.pushCodeSynthesisContext(Ctx);
7659 }
7660 ~ComputingExceptionSpec() {
7661 S.popCodeSynthesisContext();
7662 }
7663 };
7664 }
7665
7666 static Sema::ImplicitExceptionSpecification
7667 ComputeDefaultedSpecialMemberExceptionSpec(Sema &S, SourceLocation Loc,
7668 CXXMethodDecl *MD,
7669 CXXSpecialMemberKind CSM,
7670 Sema::InheritedConstructorInfo *ICI);
7671
7672 static Sema::ImplicitExceptionSpecification
7673 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
7674 FunctionDecl *FD,
7675 Sema::DefaultedComparisonKind DCK);
7676
7677 static Sema::ImplicitExceptionSpecification
7678 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD) {
7679 auto DFK = S.getDefaultedFunctionKind(FD);
7680 if (DFK.isSpecialMember())
7681 return ComputeDefaultedSpecialMemberExceptionSpec(
7682 S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr);
7683 if (DFK.isComparison())
7684 return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD,
7685 DFK.asComparison());
7686
7687 auto *CD = cast<CXXConstructorDecl>(FD);
7688 assert(CD->getInheritedConstructor() &&
7689 "only defaulted functions and inherited constructors have implicit "
7690 "exception specs");
7691 Sema::InheritedConstructorInfo ICI(
7692 S, Loc, CD->getInheritedConstructor().getShadowDecl());
7693 return ComputeDefaultedSpecialMemberExceptionSpec(
7694 S, Loc, CD, CXXSpecialMemberKind::DefaultConstructor, &ICI);
7695 }
7696
7697 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
7698 CXXMethodDecl *MD) {
7699 FunctionProtoType::ExtProtoInfo EPI;
7700
7701 // Build an exception specification pointing back at this member.
7702 EPI.ExceptionSpec.Type = EST_Unevaluated;
7703 EPI.ExceptionSpec.SourceDecl = MD;
7704
7705 // Set the calling convention to the default for C++ instance methods.
7706 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
7707 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
7708 /*IsCXXMethod=*/true));
7709 return EPI;
7710 }
7711
7712 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD) {
7713 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
7714 if (FPT->getExceptionSpecType() != EST_Unevaluated)
7715 return;
7716
7717 // Evaluate the exception specification.
7718 auto IES = computeImplicitExceptionSpec(*this, Loc, FD);
7719 auto ESI = IES.getExceptionSpec();
7720
7721 // Update the type of the special member to use it.
7722 UpdateExceptionSpec(FD, ESI);
7723 }
7724
7725 void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) {
7726 assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted");
7727
7728 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
7729 if (!DefKind) {
7730 assert(FD->getDeclContext()->isDependentContext());
7731 return;
7732 }
7733
7734 if (DefKind.isComparison()) {
7735 auto PT = FD->getParamDecl(0)->getType();
7736 if (const CXXRecordDecl *RD =
7737 PT.getNonReferenceType()->getAsCXXRecordDecl()) {
7738 for (FieldDecl *Field : RD->fields()) {
7739 UnusedPrivateFields.remove(Field);
7740 }
7741 }
7742 }
7743
7744 if (DefKind.isSpecialMember()
7745 ? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD),
7746 DefKind.asSpecialMember(),
7747 FD->getDefaultLoc())
7748 : CheckExplicitlyDefaultedComparison(S, FD, DefKind.asComparison()))
7749 FD->setInvalidDecl();
7750 }
7751
7752 bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
7753 CXXSpecialMemberKind CSM,
7754 SourceLocation DefaultLoc) {
7755 CXXRecordDecl *RD = MD->getParent();
7756
7757 assert(MD->isExplicitlyDefaulted() && CSM != CXXSpecialMemberKind::Invalid &&
7758 "not an explicitly-defaulted special member");
7759
7760 // Defer all checking for special members of a dependent type.
7761 if (RD->isDependentType())
7762 return false;
7763
7764 // Whether this was the first-declared instance of the constructor.
7765 // This affects whether we implicitly add an exception spec and constexpr.
7766 bool First = MD == MD->getCanonicalDecl();
7767
7768 bool HadError = false;
7769
7770 // C++11 [dcl.fct.def.default]p1:
7771 // A function that is explicitly defaulted shall
7772 // -- be a special member function [...] (checked elsewhere),
7773 // -- have the same type (except for ref-qualifiers, and except that a
7774 // copy operation can take a non-const reference) as an implicit
7775 // declaration, and
7776 // -- not have default arguments.
7777 // C++2a changes the second bullet to instead delete the function if it's
7778 // defaulted on its first declaration, unless it's "an assignment operator,
7779 // and its return type differs or its parameter type is not a reference".
7780 bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First;
7781 bool ShouldDeleteForTypeMismatch = false;
7782 unsigned ExpectedParams = 1;
7783 if (CSM == CXXSpecialMemberKind::DefaultConstructor ||
7784 CSM == CXXSpecialMemberKind::Destructor)
7785 ExpectedParams = 0;
7786 if (MD->getNumExplicitParams() != ExpectedParams) {
7787 // This checks for default arguments: a copy or move constructor with a
7788 // default argument is classified as a default constructor, and assignment
7789 // operations and destructors can't have default arguments.
7790 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
7791 << CSM << MD->getSourceRange();
7792 HadError = true;
7793 } else if (MD->isVariadic()) {
7794 if (DeleteOnTypeMismatch)
7795 ShouldDeleteForTypeMismatch = true;
7796 else {
7797 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
7798 << CSM << MD->getSourceRange();
7799 HadError = true;
7800 }
7801 }
7802
7803 const FunctionProtoType *Type = MD->getType()->castAs<FunctionProtoType>();
7804
7805 bool CanHaveConstParam = false;
7806 if (CSM == CXXSpecialMemberKind::CopyConstructor)
7807 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
7808 else if (CSM == CXXSpecialMemberKind::CopyAssignment)
7809 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
7810
7811 QualType ReturnType = Context.VoidTy;
7812 if (CSM == CXXSpecialMemberKind::CopyAssignment ||
7813 CSM == CXXSpecialMemberKind::MoveAssignment) {
7814 // Check for return type matching.
7815 ReturnType = Type->getReturnType();
7816 QualType ThisType = MD->getFunctionObjectParameterType();
7817
7818 QualType DeclType =
7819 Context.getTagType(ElaboratedTypeKeyword::None,
7820 /*Qualifier=*/std::nullopt, RD, /*OwnsTag=*/false);
7821 DeclType = Context.getAddrSpaceQualType(
7822 DeclType, ThisType.getQualifiers().getAddressSpace());
7823 QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
7824
7825 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
7826 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
7827 << (CSM == CXXSpecialMemberKind::MoveAssignment)
7828 << ExpectedReturnType;
7829 HadError = true;
7830 }
7831
7832 // A defaulted special member cannot have cv-qualifiers.
7833 if (ThisType.isConstQualified() || ThisType.isVolatileQualified()) {
7834 if (DeleteOnTypeMismatch)
7835 ShouldDeleteForTypeMismatch = true;
7836 else {
7837 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
7838 << (CSM == CXXSpecialMemberKind::MoveAssignment)
7839 << getLangOpts().CPlusPlus14;
7840 HadError = true;
7841 }
7842 }
7843 // [C++23][dcl.fct.def.default]/p2.2
7844 // if F2 has an implicit object parameter of type “reference to C”,
7845 // F1 may be an explicit object member function whose explicit object
7846 // parameter is of (possibly different) type “reference to C”,
7847 // in which case the type of F1 would differ from the type of F2
7848 // in that the type of F1 has an additional parameter;
7849 QualType ExplicitObjectParameter = MD->isExplicitObjectMemberFunction()
7850 ? MD->getParamDecl(0)->getType()
7851 : QualType();
7852 if (!ExplicitObjectParameter.isNull() &&
7853 (!ExplicitObjectParameter->isReferenceType() ||
7854 !Context.hasSameType(ExplicitObjectParameter.getNonReferenceType(),
7855 Context.getCanonicalTagType(RD)))) {
7856 if (DeleteOnTypeMismatch)
7857 ShouldDeleteForTypeMismatch = true;
7858 else {
7859 Diag(MD->getLocation(),
7860 diag::err_defaulted_special_member_explicit_object_mismatch)
7861 << (CSM == CXXSpecialMemberKind::MoveAssignment) << RD
7862 << MD->getSourceRange();
7863 HadError = true;
7864 }
7865 }
7866 }
7867
7868 // Check for parameter type matching.
7869 QualType ArgType =
7870 ExpectedParams
7871 ? Type->getParamType(MD->isExplicitObjectMemberFunction() ? 1 : 0)
7872 : QualType();
7873 bool HasConstParam = false;
7874 if (ExpectedParams && ArgType->isReferenceType()) {
7875 // Argument must be reference to possibly-const T.
7876 QualType ReferentType = ArgType->getPointeeType();
7877 HasConstParam = ReferentType.isConstQualified();
7878
7879 if (ReferentType.isVolatileQualified()) {
7880 if (DeleteOnTypeMismatch)
7881 ShouldDeleteForTypeMismatch = true;
7882 else {
7883 Diag(MD->getLocation(),
7884 diag::err_defaulted_special_member_volatile_param)
7885 << CSM;
7886 HadError = true;
7887 }
7888 }
7889
7890 if (HasConstParam && !CanHaveConstParam) {
7891 if (DeleteOnTypeMismatch)
7892 ShouldDeleteForTypeMismatch = true;
7893 else if (CSM == CXXSpecialMemberKind::CopyConstructor ||
7894 CSM == CXXSpecialMemberKind::CopyAssignment) {
7895 Diag(MD->getLocation(),
7896 diag::err_defaulted_special_member_copy_const_param)
7897 << (CSM == CXXSpecialMemberKind::CopyAssignment);
7898 // FIXME: Explain why this special member can't be const.
7899 HadError = true;
7900 } else {
7901 Diag(MD->getLocation(),
7902 diag::err_defaulted_special_member_move_const_param)
7903 << (CSM == CXXSpecialMemberKind::MoveAssignment);
7904 HadError = true;
7905 }
7906 }
7907 } else if (ExpectedParams) {
7908 // A copy assignment operator can take its argument by value, but a
7909 // defaulted one cannot.
7910 assert(CSM == CXXSpecialMemberKind::CopyAssignment &&
7911 "unexpected non-ref argument");
7912 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
7913 HadError = true;
7914 }
7915
7916 // C++11 [dcl.fct.def.default]p2:
7917 // An explicitly-defaulted function may be declared constexpr only if it
7918 // would have been implicitly declared as constexpr,
7919 // Do not apply this rule to members of class templates, since core issue 1358
7920 // makes such functions always instantiate to constexpr functions. For
7921 // functions which cannot be constexpr (for non-constructors in C++11 and for
7922 // destructors in C++14 and C++17), this is checked elsewhere.
7923 //
7924 // FIXME: This should not apply if the member is deleted.
7925 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
7926 HasConstParam);
7927
7928 // C++14 [dcl.constexpr]p6 (CWG DR647/CWG DR1358):
7929 // If the instantiated template specialization of a constexpr function
7930 // template or member function of a class template would fail to satisfy
7931 // the requirements for a constexpr function or constexpr constructor, that
7932 // specialization is still a constexpr function or constexpr constructor,
7933 // even though a call to such a function cannot appear in a constant
7934 // expression.
7935 if (MD->isTemplateInstantiation() && MD->isConstexpr())
7936 Constexpr = true;
7937
7938 if ((getLangOpts().CPlusPlus20 ||
7939 (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
7940 : isa<CXXConstructorDecl>(MD))) &&
7941 MD->isConstexpr() && !Constexpr &&
7942 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
7943 if (!MD->isConsteval() && RD->getNumVBases()) {
7944 Diag(MD->getBeginLoc(),
7945 diag::err_incorrect_defaulted_constexpr_with_vb)
7946 << CSM;
7947 for (const auto &I : RD->vbases())
7948 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here);
7949 } else {
7950 Diag(MD->getBeginLoc(), diag::err_incorrect_defaulted_constexpr)
7951 << CSM << MD->isConsteval();
7952 }
7953 HadError = true;
7954 // FIXME: Explain why the special member can't be constexpr.
7955 }
7956
7957 if (First) {
7958 // C++2a [dcl.fct.def.default]p3:
7959 // If a function is explicitly defaulted on its first declaration, it is
7960 // implicitly considered to be constexpr if the implicit declaration
7961 // would be.
7962 MD->setConstexprKind(Constexpr ? (MD->isConsteval()
7963 ? ConstexprSpecKind::Consteval
7964 : ConstexprSpecKind::Constexpr)
7965 : ConstexprSpecKind::Unspecified);
7966
7967 if (!Type->hasExceptionSpec()) {
7968 // C++2a [except.spec]p3:
7969 // If a declaration of a function does not have a noexcept-specifier
7970 // [and] is defaulted on its first declaration, [...] the exception
7971 // specification is as specified below
7972 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
7973 EPI.ExceptionSpec.Type = EST_Unevaluated;
7974 EPI.ExceptionSpec.SourceDecl = MD;
7975 MD->setType(
7976 Context.getFunctionType(ReturnType, Type->getParamTypes(), EPI));
7977 }
7978 }
7979
7980 if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
7981 if (First) {
7982 SetDeclDeleted(MD, MD->getLocation());
7983 if (!inTemplateInstantiation() && !HadError) {
7984 Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
7985 if (ShouldDeleteForTypeMismatch) {
7986 Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
7987 } else if (ShouldDeleteSpecialMember(MD, CSM, nullptr,
7988 /*Diagnose*/ true) &&
7989 DefaultLoc.isValid()) {
7990 Diag(DefaultLoc, diag::note_replace_equals_default_to_delete)
7991 << FixItHint::CreateReplacement(DefaultLoc, "delete");
7992 }
7993 }
7994 if (ShouldDeleteForTypeMismatch && !HadError) {
7995 Diag(MD->getLocation(),
7996 diag::warn_cxx17_compat_defaulted_method_type_mismatch)
7997 << CSM;
7998 }
7999 } else {
8000 // C++11 [dcl.fct.def.default]p4:
8001 // [For a] user-provided explicitly-defaulted function [...] if such a
8002 // function is implicitly defined as deleted, the program is ill-formed.
8003 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
8004 assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
8005 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
8006 HadError = true;
8007 }
8008 }
8009
8010 return HadError;
8011 }
8012
8013 namespace {
8014 /// Helper class for building and checking a defaulted comparison.
8015 ///
8016 /// Defaulted functions are built in two phases:
8017 ///
8018 /// * First, the set of operations that the function will perform are
8019 /// identified, and some of them are checked. If any of the checked
8020 /// operations is invalid in certain ways, the comparison function is
8021 /// defined as deleted and no body is built.
8022 /// * Then, if the function is not defined as deleted, the body is built.
8023 ///
8024 /// This is accomplished by performing two visitation steps over the eventual
8025 /// body of the function.
8026 template<typename Derived, typename ResultList, typename Result,
8027 typename Subobject>
8028 class DefaultedComparisonVisitor {
8029 public:
8030 using DefaultedComparisonKind = Sema::DefaultedComparisonKind;
8031
8032 DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8033 DefaultedComparisonKind DCK)
8034 : S(S), RD(RD), FD(FD), DCK(DCK) {
8035 if (auto *Info = FD->getDefaultedOrDeletedInfo()) {
8036 // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an
8037 // UnresolvedSet to avoid this copy.
8038 Fns.assign(Info->getUnqualifiedLookups().begin(),
8039 Info->getUnqualifiedLookups().end());
8040 }
8041 }
8042
8043 ResultList visit() {
8044 // The type of an lvalue naming a parameter of this function.
8045 QualType ParamLvalType =
8046 FD->getParamDecl(0)->getType().getNonReferenceType();
8047
8048 ResultList Results;
8049
8050 switch (DCK) {
8051 case DefaultedComparisonKind::None:
8052 llvm_unreachable("not a defaulted comparison");
8053
8054 case DefaultedComparisonKind::Equal:
8055 case DefaultedComparisonKind::ThreeWay:
8056 getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers());
8057 return Results;
8058
8059 case DefaultedComparisonKind::NotEqual:
8060 case DefaultedComparisonKind::Relational:
8061 Results.add(getDerived().visitExpandedSubobject(
8062 ParamLvalType, getDerived().getCompleteObject()));
8063 return Results;
8064 }
8065 llvm_unreachable("");
8066 }
8067
8068 protected:
8069 Derived &getDerived() { return static_cast<Derived&>(*this); }
8070
8071 /// Visit the expanded list of subobjects of the given type, as specified in
8072 /// C++2a [class.compare.default].
8073 ///
8074 /// \return \c true if the ResultList object said we're done, \c false if not.
8075 bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record,
8076 Qualifiers Quals) {
8077 // C++2a [class.compare.default]p4:
8078 // The direct base class subobjects of C
8079 for (CXXBaseSpecifier &Base : Record->bases())
8080 if (Results.add(getDerived().visitSubobject(
8081 S.Context.getQualifiedType(Base.getType(), Quals),
8082 getDerived().getBase(&Base))))
8083 return true;
8084
8085 // followed by the non-static data members of C
8086 for (FieldDecl *Field : Record->fields()) {
8087 // C++23 [class.bit]p2:
8088 // Unnamed bit-fields are not members ...
8089 if (Field->isUnnamedBitField())
8090 continue;
8091 // Recursively expand anonymous structs.
8092 if (Field->isAnonymousStructOrUnion()) {
8093 if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(),
8094 Quals))
8095 return true;
8096 continue;
8097 }
8098
8099 // Figure out the type of an lvalue denoting this field.
8100 Qualifiers FieldQuals = Quals;
8101 if (Field->isMutable())
8102 FieldQuals.removeConst();
8103 QualType FieldType =
8104 S.Context.getQualifiedType(Field->getType(), FieldQuals);
8105
8106 if (Results.add(getDerived().visitSubobject(
8107 FieldType, getDerived().getField(Field))))
8108 return true;
8109 }
8110
8111 // form a list of subobjects.
8112 return false;
8113 }
8114
8115 Result visitSubobject(QualType Type, Subobject Subobj) {
8116 // In that list, any subobject of array type is recursively expanded
8117 const ArrayType *AT = S.Context.getAsArrayType(Type);
8118 if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT))
8119 return getDerived().visitSubobjectArray(CAT->getElementType(),
8120 CAT->getSize(), Subobj);
8121 return getDerived().visitExpandedSubobject(Type, Subobj);
8122 }
8123
8124 Result visitSubobjectArray(QualType Type, const llvm::APInt &Size,
8125 Subobject Subobj) {
8126 return getDerived().visitSubobject(Type, Subobj);
8127 }
8128
8129 protected:
8130 Sema &S;
8131 CXXRecordDecl *RD;
8132 FunctionDecl *FD;
8133 DefaultedComparisonKind DCK;
8134 UnresolvedSet<16> Fns;
8135 };
8136
8137 /// Information about a defaulted comparison, as determined by
8138 /// DefaultedComparisonAnalyzer.
8139 struct DefaultedComparisonInfo {
8140 bool Deleted = false;
8141 bool Constexpr = true;
8142 ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering;
8143
8144 static DefaultedComparisonInfo deleted() {
8145 DefaultedComparisonInfo Deleted;
8146 Deleted.Deleted = true;
8147 return Deleted;
8148 }
8149
8150 bool add(const DefaultedComparisonInfo &R) {
8151 Deleted |= R.Deleted;
8152 Constexpr &= R.Constexpr;
8153 Category = commonComparisonType(Category, R.Category);
8154 return Deleted;
8155 }
8156 };
8157
8158 /// An element in the expanded list of subobjects of a defaulted comparison, as
8159 /// specified in C++2a [class.compare.default]p4.
8160 struct DefaultedComparisonSubobject {
8161 enum { CompleteObject, Member, Base } Kind;
8162 NamedDecl *Decl;
8163 SourceLocation Loc;
8164 };
8165
8166 /// A visitor over the notional body of a defaulted comparison that determines
8167 /// whether that body would be deleted or constexpr.
8168 class DefaultedComparisonAnalyzer
8169 : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer,
8170 DefaultedComparisonInfo,
8171 DefaultedComparisonInfo,
8172 DefaultedComparisonSubobject> {
8173 public:
8174 enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr };
8175
8176 private:
8177 DiagnosticKind Diagnose;
8178
8179 public:
8180 using Base = DefaultedComparisonVisitor;
8181 using Result = DefaultedComparisonInfo;
8182 using Subobject = DefaultedComparisonSubobject;
8183
8184 friend Base;
8185
8186 DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8187 DefaultedComparisonKind DCK,
8188 DiagnosticKind Diagnose = NoDiagnostics)
8189 : Base(S, RD, FD, DCK), Diagnose(Diagnose) {}
8190
8191 Result visit() {
8192 if ((DCK == DefaultedComparisonKind::Equal ||
8193 DCK == DefaultedComparisonKind::ThreeWay) &&
8194 RD->hasVariantMembers()) {
8195 // C++2a [class.compare.default]p2 [P2002R0]:
8196 // A defaulted comparison operator function for class C is defined as
8197 // deleted if [...] C has variant members.
8198 if (Diagnose == ExplainDeleted) {
8199 S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union)
8200 << FD << RD->isUnion() << RD;
8201 }
8202 return Result::deleted();
8203 }
8204
8205 return Base::visit();
8206 }
8207
8208 private:
8209 Subobject getCompleteObject() {
8210 return Subobject{Subobject::CompleteObject, RD, FD->getLocation()};
8211 }
8212
8213 Subobject getBase(CXXBaseSpecifier *Base) {
8214 return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(),
8215 Base->getBaseTypeLoc()};
8216 }
8217
8218 Subobject getField(FieldDecl *Field) {
8219 return Subobject{Subobject::Member, Field, Field->getLocation()};
8220 }
8221
8222 Result visitExpandedSubobject(QualType Type, Subobject Subobj) {
8223 // C++2a [class.compare.default]p2 [P2002R0]:
8224 // A defaulted <=> or == operator function for class C is defined as
8225 // deleted if any non-static data member of C is of reference type
8226 if (Type->isReferenceType()) {
8227 if (Diagnose == ExplainDeleted) {
8228 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member)
8229 << FD << RD;
8230 }
8231 return Result::deleted();
8232 }
8233
8234 // [...] Let xi be an lvalue denoting the ith element [...]
8235 OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue);
8236 Expr *Args[] = {&Xi, &Xi};
8237
8238 // All operators start by trying to apply that same operator recursively.
8239 OverloadedOperatorKind OO = FD->getOverloadedOperator();
8240 assert(OO != OO_None && "not an overloaded operator!");
8241 return visitBinaryOperator(OO, Args, Subobj);
8242 }
8243
8244 Result
8245 visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args,
8246 Subobject Subobj,
8247 OverloadCandidateSet *SpaceshipCandidates = nullptr) {
8248 // Note that there is no need to consider rewritten candidates here if
8249 // we've already found there is no viable 'operator<=>' candidate (and are
8250 // considering synthesizing a '<=>' from '==' and '<').
8251 OverloadCandidateSet CandidateSet(
8252 FD->getLocation(), OverloadCandidateSet::CSK_Operator,
8253 OverloadCandidateSet::OperatorRewriteInfo(
8254 OO, FD->getLocation(),
8255 /*AllowRewrittenCandidates=*/!SpaceshipCandidates));
8256
8257 /// C++2a [class.compare.default]p1 [P2002R0]:
8258 /// [...] the defaulted function itself is never a candidate for overload
8259 /// resolution [...]
8260 CandidateSet.exclude(FD);
8261
8262 if (Args[0]->getType()->isOverloadableType())
8263 S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args);
8264 else
8265 // FIXME: We determine whether this is a valid expression by checking to
8266 // see if there's a viable builtin operator candidate for it. That isn't
8267 // really what the rules ask us to do, but should give the right results.
8268 S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet);
8269
8270 Result R;
8271
8272 OverloadCandidateSet::iterator Best;
8273 switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) {
8274 case OR_Success: {
8275 // C++2a [class.compare.secondary]p2 [P2002R0]:
8276 // The operator function [...] is defined as deleted if [...] the
8277 // candidate selected by overload resolution is not a rewritten
8278 // candidate.
8279 if ((DCK == DefaultedComparisonKind::NotEqual ||
8280 DCK == DefaultedComparisonKind::Relational) &&
8281 !Best->RewriteKind) {
8282 if (Diagnose == ExplainDeleted) {
8283 if (Best->Function) {
8284 S.Diag(Best->Function->getLocation(),
8285 diag::note_defaulted_comparison_not_rewritten_callee)
8286 << FD;
8287 } else {
8288 assert(Best->Conversions.size() == 2 &&
8289 Best->Conversions[0].isUserDefined() &&
8290 "non-user-defined conversion from class to built-in "
8291 "comparison");
8292 S.Diag(Best->Conversions[0]
8293 .UserDefined.FoundConversionFunction.getDecl()
8294 ->getLocation(),
8295 diag::note_defaulted_comparison_not_rewritten_conversion)
8296 << FD;
8297 }
8298 }
8299 return Result::deleted();
8300 }
8301
8302 // Throughout C++2a [class.compare]: if overload resolution does not
8303 // result in a usable function, the candidate function is defined as
8304 // deleted. This requires that we selected an accessible function.
8305 //
8306 // Note that this only considers the access of the function when named
8307 // within the type of the subobject, and not the access path for any
8308 // derived-to-base conversion.
8309 CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl();
8310 if (ArgClass && Best->FoundDecl.getDecl() &&
8311 Best->FoundDecl.getDecl()->isCXXClassMember()) {
8312 QualType ObjectType = Subobj.Kind == Subobject::Member
8313 ? Args[0]->getType()
8314 : S.Context.getCanonicalTagType(RD);
8315 if (!S.isMemberAccessibleForDeletion(
8316 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc,
8317 Diagnose == ExplainDeleted
8318 ? S.PDiag(diag::note_defaulted_comparison_inaccessible)
8319 << FD << Subobj.Kind << Subobj.Decl
8320 : S.PDiag()))
8321 return Result::deleted();
8322 }
8323
8324 bool NeedsDeducing =
8325 OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType();
8326
8327 if (FunctionDecl *BestFD = Best->Function) {
8328 // C++2a [class.compare.default]p3 [P2002R0]:
8329 // A defaulted comparison function is constexpr-compatible if
8330 // [...] no overlod resolution performed [...] results in a
8331 // non-constexpr function.
8332 assert(!BestFD->isDeleted() && "wrong overload resolution result");
8333 // If it's not constexpr, explain why not.
8334 if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) {
8335 if (Subobj.Kind != Subobject::CompleteObject)
8336 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr)
8337 << Subobj.Kind << Subobj.Decl;
8338 S.Diag(BestFD->getLocation(),
8339 diag::note_defaulted_comparison_not_constexpr_here);
8340 // Bail out after explaining; we don't want any more notes.
8341 return Result::deleted();
8342 }
8343 R.Constexpr &= BestFD->isConstexpr();
8344
8345 if (NeedsDeducing) {
8346 // If any callee has an undeduced return type, deduce it now.
8347 // FIXME: It's not clear how a failure here should be handled. For
8348 // now, we produce an eager diagnostic, because that is forward
8349 // compatible with most (all?) other reasonable options.
8350 if (BestFD->getReturnType()->isUndeducedType() &&
8351 S.DeduceReturnType(BestFD, FD->getLocation(),
8352 /*Diagnose=*/false)) {
8353 // Don't produce a duplicate error when asked to explain why the
8354 // comparison is deleted: we diagnosed that when initially checking
8355 // the defaulted operator.
8356 if (Diagnose == NoDiagnostics) {
8357 S.Diag(
8358 FD->getLocation(),
8359 diag::err_defaulted_comparison_cannot_deduce_undeduced_auto)
8360 << Subobj.Kind << Subobj.Decl;
8361 S.Diag(
8362 Subobj.Loc,
8363 diag::note_defaulted_comparison_cannot_deduce_undeduced_auto)
8364 << Subobj.Kind << Subobj.Decl;
8365 S.Diag(BestFD->getLocation(),
8366 diag::note_defaulted_comparison_cannot_deduce_callee)
8367 << Subobj.Kind << Subobj.Decl;
8368 }
8369 return Result::deleted();
8370 }
8371 auto *Info = S.Context.CompCategories.lookupInfoForType(
8372 BestFD->getCallResultType());
8373 if (!Info) {
8374 if (Diagnose == ExplainDeleted) {
8375 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce)
8376 << Subobj.Kind << Subobj.Decl
8377 << BestFD->getCallResultType().withoutLocalFastQualifiers();
8378 S.Diag(BestFD->getLocation(),
8379 diag::note_defaulted_comparison_cannot_deduce_callee)
8380 << Subobj.Kind << Subobj.Decl;
8381 }
8382 return Result::deleted();
8383 }
8384 R.Category = Info->Kind;
8385 }
8386 } else {
8387 QualType T = Best->BuiltinParamTypes[0];
8388 assert(T == Best->BuiltinParamTypes[1] &&
8389 "builtin comparison for different types?");
8390 assert(Best->BuiltinParamTypes[2].isNull() &&
8391 "invalid builtin comparison");
8392
8393 // FIXME: If the type we deduced is a vector type, we mark the
8394 // comparison as deleted because we don't yet support this.
8395 if (isa<VectorType>(T)) {
8396 if (Diagnose == ExplainDeleted) {
8397 S.Diag(FD->getLocation(),
8398 diag::note_defaulted_comparison_vector_types)
8399 << FD;
8400 S.Diag(Subobj.Decl->getLocation(), diag::note_declared_at);
8401 }
8402 return Result::deleted();
8403 }
8404
8405 if (NeedsDeducing) {
8406 std::optional<ComparisonCategoryType> Cat =
8407 getComparisonCategoryForBuiltinCmp(T);
8408 assert(Cat && "no category for builtin comparison?");
8409 R.Category = *Cat;
8410 }
8411 }
8412
8413 // Note that we might be rewriting to a different operator. That call is
8414 // not considered until we come to actually build the comparison function.
8415 break;
8416 }
8417
8418 case OR_Ambiguous:
8419 if (Diagnose == ExplainDeleted) {
8420 unsigned Kind = 0;
8421 if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship)
8422 Kind = OO == OO_EqualEqual ? 1 : 2;
8423 CandidateSet.NoteCandidates(
8424 PartialDiagnosticAt(
8425 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous)
8426 << FD << Kind << Subobj.Kind << Subobj.Decl),
8427 S, OCD_AmbiguousCandidates, Args);
8428 }
8429 R = Result::deleted();
8430 break;
8431
8432 case OR_Deleted:
8433 if (Diagnose == ExplainDeleted) {
8434 if ((DCK == DefaultedComparisonKind::NotEqual ||
8435 DCK == DefaultedComparisonKind::Relational) &&
8436 !Best->RewriteKind) {
8437 S.Diag(Best->Function->getLocation(),
8438 diag::note_defaulted_comparison_not_rewritten_callee)
8439 << FD;
8440 } else {
8441 S.Diag(Subobj.Loc,
8442 diag::note_defaulted_comparison_calls_deleted)
8443 << FD << Subobj.Kind << Subobj.Decl;
8444 S.NoteDeletedFunction(Best->Function);
8445 }
8446 }
8447 R = Result::deleted();
8448 break;
8449
8450 case OR_No_Viable_Function:
8451 // If there's no usable candidate, we're done unless we can rewrite a
8452 // '<=>' in terms of '==' and '<'.
8453 if (OO == OO_Spaceship &&
8454 S.Context.CompCategories.lookupInfoForType(FD->getReturnType())) {
8455 // For any kind of comparison category return type, we need a usable
8456 // '==' and a usable '<'.
8457 if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj,
8458 &CandidateSet)))
8459 R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet));
8460 break;
8461 }
8462
8463 if (Diagnose == ExplainDeleted) {
8464 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function)
8465 << FD << (OO == OO_EqualEqual || OO == OO_ExclaimEqual)
8466 << Subobj.Kind << Subobj.Decl;
8467
8468 // For a three-way comparison, list both the candidates for the
8469 // original operator and the candidates for the synthesized operator.
8470 if (SpaceshipCandidates) {
8471 SpaceshipCandidates->NoteCandidates(
8472 S, Args,
8473 SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates,
8474 Args, FD->getLocation()));
8475 S.Diag(Subobj.Loc,
8476 diag::note_defaulted_comparison_no_viable_function_synthesized)
8477 << (OO == OO_EqualEqual ? 0 : 1);
8478 }
8479
8480 CandidateSet.NoteCandidates(
8481 S, Args,
8482 CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args,
8483 FD->getLocation()));
8484 }
8485 R = Result::deleted();
8486 break;
8487 }
8488
8489 return R;
8490 }
8491 };
8492
8493 /// A list of statements.
8494 struct StmtListResult {
8495 bool IsInvalid = false;
8496 llvm::SmallVector<Stmt*, 16> Stmts;
8497
8498 bool add(const StmtResult &S) {
8499 IsInvalid |= S.isInvalid();
8500 if (IsInvalid)
8501 return true;
8502 Stmts.push_back(S.get());
8503 return false;
8504 }
8505 };
8506
8507 /// A visitor over the notional body of a defaulted comparison that synthesizes
8508 /// the actual body.
8509 class DefaultedComparisonSynthesizer
8510 : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer,
8511 StmtListResult, StmtResult,
8512 std::pair<ExprResult, ExprResult>> {
8513 SourceLocation Loc;
8514 unsigned ArrayDepth = 0;
8515
8516 public:
8517 using Base = DefaultedComparisonVisitor;
8518 using ExprPair = std::pair<ExprResult, ExprResult>;
8519
8520 friend Base;
8521
8522 DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8523 DefaultedComparisonKind DCK,
8524 SourceLocation BodyLoc)
8525 : Base(S, RD, FD, DCK), Loc(BodyLoc) {}
8526
8527 /// Build a suitable function body for this defaulted comparison operator.
8528 StmtResult build() {
8529 Sema::CompoundScopeRAII CompoundScope(S);
8530
8531 StmtListResult Stmts = visit();
8532 if (Stmts.IsInvalid)
8533 return StmtError();
8534
8535 ExprResult RetVal;
8536 switch (DCK) {
8537 case DefaultedComparisonKind::None:
8538 llvm_unreachable("not a defaulted comparison");
8539
8540 case DefaultedComparisonKind::Equal: {
8541 // C++2a [class.eq]p3:
8542 // [...] compar[e] the corresponding elements [...] until the first
8543 // index i where xi == yi yields [...] false. If no such index exists,
8544 // V is true. Otherwise, V is false.
8545 //
8546 // Join the comparisons with '&&'s and return the result. Use a right
8547 // fold (traversing the conditions right-to-left), because that
8548 // short-circuits more naturally.
8549 auto OldStmts = std::move(Stmts.Stmts);
8550 Stmts.Stmts.clear();
8551 ExprResult CmpSoFar;
8552 // Finish a particular comparison chain.
8553 auto FinishCmp = [&] {
8554 if (Expr *Prior = CmpSoFar.get()) {
8555 // Convert the last expression to 'return ...;'
8556 if (RetVal.isUnset() && Stmts.Stmts.empty())
8557 RetVal = CmpSoFar;
8558 // Convert any prior comparison to 'if (!(...)) return false;'
8559 else if (Stmts.add(buildIfNotCondReturnFalse(Prior)))
8560 return true;
8561 CmpSoFar = ExprResult();
8562 }
8563 return false;
8564 };
8565 for (Stmt *EAsStmt : llvm::reverse(OldStmts)) {
8566 Expr *E = dyn_cast<Expr>(EAsStmt);
8567 if (!E) {
8568 // Found an array comparison.
8569 if (FinishCmp() || Stmts.add(EAsStmt))
8570 return StmtError();
8571 continue;
8572 }
8573
8574 if (CmpSoFar.isUnset()) {
8575 CmpSoFar = E;
8576 continue;
8577 }
8578 CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get());
8579 if (CmpSoFar.isInvalid())
8580 return StmtError();
8581 }
8582 if (FinishCmp())
8583 return StmtError();
8584 std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end());
8585 // If no such index exists, V is true.
8586 if (RetVal.isUnset())
8587 RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true);
8588 break;
8589 }
8590
8591 case DefaultedComparisonKind::ThreeWay: {
8592 // Per C++2a [class.spaceship]p3, as a fallback add:
8593 // return static_cast<R>(std::strong_ordering::equal);
8594 QualType StrongOrdering = S.CheckComparisonCategoryType(
8595 ComparisonCategoryType::StrongOrdering, Loc,
8596 Sema::ComparisonCategoryUsage::DefaultedOperator);
8597 if (StrongOrdering.isNull())
8598 return StmtError();
8599 VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(StrongOrdering)
8600 .getValueInfo(ComparisonCategoryResult::Equal)
8601 ->VD;
8602 RetVal = getDecl(EqualVD);
8603 if (RetVal.isInvalid())
8604 return StmtError();
8605 RetVal = buildStaticCastToR(RetVal.get());
8606 break;
8607 }
8608
8609 case DefaultedComparisonKind::NotEqual:
8610 case DefaultedComparisonKind::Relational:
8611 RetVal = cast<Expr>(Stmts.Stmts.pop_back_val());
8612 break;
8613 }
8614
8615 // Build the final return statement.
8616 if (RetVal.isInvalid())
8617 return StmtError();
8618 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get());
8619 if (ReturnStmt.isInvalid())
8620 return StmtError();
8621 Stmts.Stmts.push_back(ReturnStmt.get());
8622
8623 return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false);
8624 }
8625
8626 private:
8627 ExprResult getDecl(ValueDecl *VD) {
8628 return S.BuildDeclarationNameExpr(
8629 CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD);
8630 }
8631
8632 ExprResult getParam(unsigned I) {
8633 ParmVarDecl *PD = FD->getParamDecl(I);
8634 return getDecl(PD);
8635 }
8636
8637 ExprPair getCompleteObject() {
8638 unsigned Param = 0;
8639 ExprResult LHS;
8640 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD);
8641 MD && MD->isImplicitObjectMemberFunction()) {
8642 // LHS is '*this'.
8643 LHS = S.ActOnCXXThis(Loc);
8644 if (!LHS.isInvalid())
8645 LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get());
8646 } else {
8647 LHS = getParam(Param++);
8648 }
8649 ExprResult RHS = getParam(Param++);
8650 assert(Param == FD->getNumParams());
8651 return {LHS, RHS};
8652 }
8653
8654 ExprPair getBase(CXXBaseSpecifier *Base) {
8655 ExprPair Obj = getCompleteObject();
8656 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8657 return {ExprError(), ExprError()};
8658 CXXCastPath Path = {Base};
8659 const auto CastToBase = [&](Expr *E) {
8660 QualType ToType = S.Context.getQualifiedType(
8661 Base->getType(), E->getType().getQualifiers());
8662 return S.ImpCastExprToType(E, ToType, CK_DerivedToBase, VK_LValue, &Path);
8663 };
8664 return {CastToBase(Obj.first.get()), CastToBase(Obj.second.get())};
8665 }
8666
8667 ExprPair getField(FieldDecl *Field) {
8668 ExprPair Obj = getCompleteObject();
8669 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8670 return {ExprError(), ExprError()};
8671
8672 DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess());
8673 DeclarationNameInfo NameInfo(Field->getDeclName(), Loc);
8674 return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc,
8675 CXXScopeSpec(), Field, Found, NameInfo),
8676 S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc,
8677 CXXScopeSpec(), Field, Found, NameInfo)};
8678 }
8679
8680 // FIXME: When expanding a subobject, register a note in the code synthesis
8681 // stack to say which subobject we're comparing.
8682
8683 StmtResult buildIfNotCondReturnFalse(ExprResult Cond) {
8684 if (Cond.isInvalid())
8685 return StmtError();
8686
8687 ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get());
8688 if (NotCond.isInvalid())
8689 return StmtError();
8690
8691 ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false);
8692 assert(!False.isInvalid() && "should never fail");
8693 StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get());
8694 if (ReturnFalse.isInvalid())
8695 return StmtError();
8696
8697 return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, nullptr,
8698 S.ActOnCondition(nullptr, Loc, NotCond.get(),
8699 Sema::ConditionKind::Boolean),
8700 Loc, ReturnFalse.get(), SourceLocation(), nullptr);
8701 }
8702
8703 StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size,
8704 ExprPair Subobj) {
8705 QualType SizeType = S.Context.getSizeType();
8706 Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType));
8707
8708 // Build 'size_t i$n = 0'.
8709 IdentifierInfo *IterationVarName = nullptr;
8710 {
8711 SmallString<8> Str;
8712 llvm::raw_svector_ostream OS(Str);
8713 OS << "i" << ArrayDepth;
8714 IterationVarName = &S.Context.Idents.get(OS.str());
8715 }
8716 VarDecl *IterationVar = VarDecl::Create(
8717 S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType,
8718 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None);
8719 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
8720 IterationVar->setInit(
8721 IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
8722 Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc);
8723
8724 auto IterRef = [&] {
8725 ExprResult Ref = S.BuildDeclarationNameExpr(
8726 CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc),
8727 IterationVar);
8728 assert(!Ref.isInvalid() && "can't reference our own variable?");
8729 return Ref.get();
8730 };
8731
8732 // Build 'i$n != Size'.
8733 ExprResult Cond = S.CreateBuiltinBinOp(
8734 Loc, BO_NE, IterRef(),
8735 IntegerLiteral::Create(S.Context, Size, SizeType, Loc));
8736 assert(!Cond.isInvalid() && "should never fail");
8737
8738 // Build '++i$n'.
8739 ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef());
8740 assert(!Inc.isInvalid() && "should never fail");
8741
8742 // Build 'a[i$n]' and 'b[i$n]'.
8743 auto Index = [&](ExprResult E) {
8744 if (E.isInvalid())
8745 return ExprError();
8746 return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc);
8747 };
8748 Subobj.first = Index(Subobj.first);
8749 Subobj.second = Index(Subobj.second);
8750
8751 // Compare the array elements.
8752 ++ArrayDepth;
8753 StmtResult Substmt = visitSubobject(Type, Subobj);
8754 --ArrayDepth;
8755
8756 if (Substmt.isInvalid())
8757 return StmtError();
8758
8759 // For the inner level of an 'operator==', build 'if (!cmp) return false;'.
8760 // For outer levels or for an 'operator<=>' we already have a suitable
8761 // statement that returns as necessary.
8762 if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) {
8763 assert(DCK == DefaultedComparisonKind::Equal &&
8764 "should have non-expression statement");
8765 Substmt = buildIfNotCondReturnFalse(ElemCmp);
8766 if (Substmt.isInvalid())
8767 return StmtError();
8768 }
8769
8770 // Build 'for (...) ...'
8771 return S.ActOnForStmt(Loc, Loc, Init,
8772 S.ActOnCondition(nullptr, Loc, Cond.get(),
8773 Sema::ConditionKind::Boolean),
8774 S.MakeFullDiscardedValueExpr(Inc.get()), Loc,
8775 Substmt.get());
8776 }
8777
8778 StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) {
8779 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8780 return StmtError();
8781
8782 OverloadedOperatorKind OO = FD->getOverloadedOperator();
8783 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(OO);
8784 ExprResult Op;
8785 if (Type->isOverloadableType())
8786 Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(),
8787 Obj.second.get(), /*PerformADL=*/true,
8788 /*AllowRewrittenCandidates=*/true, FD);
8789 else
8790 Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get());
8791 if (Op.isInvalid())
8792 return StmtError();
8793
8794 switch (DCK) {
8795 case DefaultedComparisonKind::None:
8796 llvm_unreachable("not a defaulted comparison");
8797
8798 case DefaultedComparisonKind::Equal:
8799 // Per C++2a [class.eq]p2, each comparison is individually contextually
8800 // converted to bool.
8801 Op = S.PerformContextuallyConvertToBool(Op.get());
8802 if (Op.isInvalid())
8803 return StmtError();
8804 return Op.get();
8805
8806 case DefaultedComparisonKind::ThreeWay: {
8807 // Per C++2a [class.spaceship]p3, form:
8808 // if (R cmp = static_cast<R>(op); cmp != 0)
8809 // return cmp;
8810 QualType R = FD->getReturnType();
8811 Op = buildStaticCastToR(Op.get());
8812 if (Op.isInvalid())
8813 return StmtError();
8814
8815 // R cmp = ...;
8816 IdentifierInfo *Name = &S.Context.Idents.get("cmp");
8817 VarDecl *VD =
8818 VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R,
8819 S.Context.getTrivialTypeSourceInfo(R, Loc), SC_None);
8820 S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false);
8821 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc);
8822
8823 // cmp != 0
8824 ExprResult VDRef = getDecl(VD);
8825 if (VDRef.isInvalid())
8826 return StmtError();
8827 llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0);
8828 Expr *Zero =
8829 IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc);
8830 ExprResult Comp;
8831 if (VDRef.get()->getType()->isOverloadableType())
8832 Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true,
8833 true, FD);
8834 else
8835 Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero);
8836 if (Comp.isInvalid())
8837 return StmtError();
8838 Sema::ConditionResult Cond = S.ActOnCondition(
8839 nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean);
8840 if (Cond.isInvalid())
8841 return StmtError();
8842
8843 // return cmp;
8844 VDRef = getDecl(VD);
8845 if (VDRef.isInvalid())
8846 return StmtError();
8847 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get());
8848 if (ReturnStmt.isInvalid())
8849 return StmtError();
8850
8851 // if (...)
8852 return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, InitStmt, Cond,
8853 Loc, ReturnStmt.get(),
8854 /*ElseLoc=*/SourceLocation(), /*Else=*/nullptr);
8855 }
8856
8857 case DefaultedComparisonKind::NotEqual:
8858 case DefaultedComparisonKind::Relational:
8859 // C++2a [class.compare.secondary]p2:
8860 // Otherwise, the operator function yields x @ y.
8861 return Op.get();
8862 }
8863 llvm_unreachable("");
8864 }
8865
8866 /// Build "static_cast<R>(E)".
8867 ExprResult buildStaticCastToR(Expr *E) {
8868 QualType R = FD->getReturnType();
8869 assert(!R->isUndeducedType() && "type should have been deduced already");
8870
8871 // Don't bother forming a no-op cast in the common case.
8872 if (E->isPRValue() && S.Context.hasSameType(E->getType(), R))
8873 return E;
8874 return S.BuildCXXNamedCast(Loc, tok::kw_static_cast,
8875 S.Context.getTrivialTypeSourceInfo(R, Loc), E,
8876 SourceRange(Loc, Loc), SourceRange(Loc, Loc));
8877 }
8878 };
8879 }
8880
8881 /// Perform the unqualified lookups that might be needed to form a defaulted
8882 /// comparison function for the given operator.
8883 static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S,
8884 UnresolvedSetImpl &Operators,
8885 OverloadedOperatorKind Op) {
8886 auto Lookup = [&](OverloadedOperatorKind OO) {
8887 Self.LookupOverloadedOperatorName(OO, S, Operators);
8888 };
8889
8890 // Every defaulted operator looks up itself.
8891 Lookup(Op);
8892 // ... and the rewritten form of itself, if any.
8893 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Op))
8894 Lookup(ExtraOp);
8895
8896 // For 'operator<=>', we also form a 'cmp != 0' expression, and might
8897 // synthesize a three-way comparison from '<' and '=='. In a dependent
8898 // context, we also need to look up '==' in case we implicitly declare a
8899 // defaulted 'operator=='.
8900 if (Op == OO_Spaceship) {
8901 Lookup(OO_ExclaimEqual);
8902 Lookup(OO_Less);
8903 Lookup(OO_EqualEqual);
8904 }
8905 }
8906
8907 bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *FD,
8908 DefaultedComparisonKind DCK) {
8909 assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison");
8910
8911 // Perform any unqualified lookups we're going to need to default this
8912 // function.
8913 if (S) {
8914 UnresolvedSet<32> Operators;
8915 lookupOperatorsForDefaultedComparison(*this, S, Operators,
8916 FD->getOverloadedOperator());
8917 FD->setDefaultedOrDeletedInfo(
8918 FunctionDecl::DefaultedOrDeletedFunctionInfo::Create(
8919 Context, Operators.pairs()));
8920 }
8921
8922 // C++2a [class.compare.default]p1:
8923 // A defaulted comparison operator function for some class C shall be a
8924 // non-template function declared in the member-specification of C that is
8925 // -- a non-static const non-volatile member of C having one parameter of
8926 // type const C& and either no ref-qualifier or the ref-qualifier &, or
8927 // -- a friend of C having two parameters of type const C& or two
8928 // parameters of type C.
8929
8930 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext());
8931 bool IsMethod = isa<CXXMethodDecl>(FD);
8932 if (IsMethod) {
8933 auto *MD = cast<CXXMethodDecl>(FD);
8934 assert(!MD->isStatic() && "comparison function cannot be a static member");
8935
8936 if (MD->getRefQualifier() == RQ_RValue) {
8937 Diag(MD->getLocation(), diag::err_ref_qualifier_comparison_operator);
8938
8939 // Remove the ref qualifier to recover.
8940 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8941 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8942 EPI.RefQualifier = RQ_None;
8943 MD->setType(Context.getFunctionType(FPT->getReturnType(),
8944 FPT->getParamTypes(), EPI));
8945 }
8946
8947 // If we're out-of-class, this is the class we're comparing.
8948 if (!RD)
8949 RD = MD->getParent();
8950 QualType T = MD->getFunctionObjectParameterReferenceType();
8951 if (!T.getNonReferenceType().isConstQualified() &&
8952 (MD->isImplicitObjectMemberFunction() || T->isLValueReferenceType())) {
8953 SourceLocation Loc, InsertLoc;
8954 if (MD->isExplicitObjectMemberFunction()) {
8955 Loc = MD->getParamDecl(0)->getBeginLoc();
8956 InsertLoc = getLocForEndOfToken(
8957 MD->getParamDecl(0)->getExplicitObjectParamThisLoc());
8958 } else {
8959 Loc = MD->getLocation();
8960 if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc())
8961 InsertLoc = Loc.getRParenLoc();
8962 }
8963 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8964 // corresponding defaulted 'operator<=>' already.
8965 if (!MD->isImplicit()) {
8966 Diag(Loc, diag::err_defaulted_comparison_non_const)
8967 << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const");
8968 }
8969
8970 // Add the 'const' to the type to recover.
8971 if (MD->isExplicitObjectMemberFunction()) {
8972 assert(T->isLValueReferenceType());
8973 MD->getParamDecl(0)->setType(Context.getLValueReferenceType(
8974 T.getNonReferenceType().withConst()));
8975 } else {
8976 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8977 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8978 EPI.TypeQuals.addConst();
8979 MD->setType(Context.getFunctionType(FPT->getReturnType(),
8980 FPT->getParamTypes(), EPI));
8981 }
8982 }
8983
8984 if (MD->isVolatile()) {
8985 Diag(MD->getLocation(), diag::err_volatile_comparison_operator);
8986
8987 // Remove the 'volatile' from the type to recover.
8988 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8989 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8990 EPI.TypeQuals.removeVolatile();
8991 MD->setType(Context.getFunctionType(FPT->getReturnType(),
8992 FPT->getParamTypes(), EPI));
8993 }
8994 }
8995
8996 if ((FD->getNumParams() -
8997 (unsigned)FD->hasCXXExplicitFunctionObjectParameter()) !=
8998 (IsMethod ? 1 : 2)) {
8999 // Let's not worry about using a variadic template pack here -- who would do
9000 // such a thing?
9001 Diag(FD->getLocation(), diag::err_defaulted_comparison_num_args)
9002 << int(IsMethod) << int(DCK);
9003 return true;
9004 }
9005
9006 const ParmVarDecl *KnownParm = nullptr;
9007 for (const ParmVarDecl *Param : FD->parameters()) {
9008 QualType ParmTy = Param->getType();
9009 if (!KnownParm) {
9010 auto CTy = ParmTy;
9011 // Is it `T const &`?
9012 bool Ok = !IsMethod || FD->hasCXXExplicitFunctionObjectParameter();
9013 QualType ExpectedTy;
9014 if (RD)
9015 ExpectedTy = Context.getCanonicalTagType(RD);
9016 if (auto *Ref = CTy->getAs<LValueReferenceType>()) {
9017 CTy = Ref->getPointeeType();
9018 if (RD)
9019 ExpectedTy.addConst();
9020 Ok = true;
9021 }
9022
9023 // Is T a class?
9024 if (RD) {
9025 Ok &= RD->isDependentType() || Context.hasSameType(CTy, ExpectedTy);
9026 } else {
9027 RD = CTy->getAsCXXRecordDecl();
9028 Ok &= RD != nullptr;
9029 }
9030
9031 if (Ok) {
9032 KnownParm = Param;
9033 } else {
9034 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
9035 // corresponding defaulted 'operator<=>' already.
9036 if (!FD->isImplicit()) {
9037 if (RD) {
9038 CanQualType PlainTy = Context.getCanonicalTagType(RD);
9039 QualType RefTy =
9040 Context.getLValueReferenceType(PlainTy.withConst());
9041 Diag(FD->getLocation(), diag::err_defaulted_comparison_param)
9042 << int(DCK) << ParmTy << RefTy << int(!IsMethod) << PlainTy
9043 << Param->getSourceRange();
9044 } else {
9045 assert(!IsMethod && "should know expected type for method");
9046 Diag(FD->getLocation(),
9047 diag::err_defaulted_comparison_param_unknown)
9048 << int(DCK) << ParmTy << Param->getSourceRange();
9049 }
9050 }
9051 return true;
9052 }
9053 } else if (!Context.hasSameType(KnownParm->getType(), ParmTy)) {
9054 Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch)
9055 << int(DCK) << KnownParm->getType() << KnownParm->getSourceRange()
9056 << ParmTy << Param->getSourceRange();
9057 return true;
9058 }
9059 }
9060
9061 assert(RD && "must have determined class");
9062 if (IsMethod) {
9063 } else if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
9064 // In-class, must be a friend decl.
9065 assert(FD->getFriendObjectKind() && "expected a friend declaration");
9066 } else {
9067 // Out of class, require the defaulted comparison to be a friend (of a
9068 // complete type, per CWG2547).
9069 if (RequireCompleteType(FD->getLocation(), Context.getCanonicalTagType(RD),
9070 diag::err_defaulted_comparison_not_friend, int(DCK),
9071 int(1)))
9072 return true;
9073
9074 if (llvm::none_of(RD->friends(), [&](const FriendDecl *F) {
9075 return declaresSameEntity(F->getFriendDecl(), FD);
9076 })) {
9077 Diag(FD->getLocation(), diag::err_defaulted_comparison_not_friend)
9078 << int(DCK) << int(0) << RD;
9079 Diag(RD->getCanonicalDecl()->getLocation(), diag::note_declared_at);
9080 return true;
9081 }
9082 }
9083
9084 // C++2a [class.eq]p1, [class.rel]p1:
9085 // A [defaulted comparison other than <=>] shall have a declared return
9086 // type bool.
9087 if (DCK != DefaultedComparisonKind::ThreeWay &&
9088 !FD->getDeclaredReturnType()->isDependentType() &&
9089 !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) {
9090 Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool)
9091 << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy
9092 << FD->getReturnTypeSourceRange();
9093 return true;
9094 }
9095 // C++2a [class.spaceship]p2 [P2002R0]:
9096 // Let R be the declared return type [...]. If R is auto, [...]. Otherwise,
9097 // R shall not contain a placeholder type.
9098 if (QualType RT = FD->getDeclaredReturnType();
9099 DCK == DefaultedComparisonKind::ThreeWay &&
9100 RT->getContainedDeducedType() &&
9101 (!Context.hasSameType(RT, Context.getAutoDeductType()) ||
9102 RT->getContainedAutoType()->isConstrained())) {
9103 Diag(FD->getLocation(),
9104 diag::err_defaulted_comparison_deduced_return_type_not_auto)
9105 << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy
9106 << FD->getReturnTypeSourceRange();
9107 return true;
9108 }
9109
9110 // For a defaulted function in a dependent class, defer all remaining checks
9111 // until instantiation.
9112 if (RD->isDependentType())
9113 return false;
9114
9115 // Determine whether the function should be defined as deleted.
9116 DefaultedComparisonInfo Info =
9117 DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit();
9118
9119 bool First = FD == FD->getCanonicalDecl();
9120
9121 if (!First) {
9122 if (Info.Deleted) {
9123 // C++11 [dcl.fct.def.default]p4:
9124 // [For a] user-provided explicitly-defaulted function [...] if such a
9125 // function is implicitly defined as deleted, the program is ill-formed.
9126 //
9127 // This is really just a consequence of the general rule that you can
9128 // only delete a function on its first declaration.
9129 Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes)
9130 << FD->isImplicit() << (int)DCK;
9131 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9132 DefaultedComparisonAnalyzer::ExplainDeleted)
9133 .visit();
9134 return true;
9135 }
9136 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
9137 // C++20 [class.compare.default]p1:
9138 // [...] A definition of a comparison operator as defaulted that appears
9139 // in a class shall be the first declaration of that function.
9140 Diag(FD->getLocation(), diag::err_non_first_default_compare_in_class)
9141 << (int)DCK;
9142 Diag(FD->getCanonicalDecl()->getLocation(),
9143 diag::note_previous_declaration);
9144 return true;
9145 }
9146 }
9147
9148 // If we want to delete the function, then do so; there's nothing else to
9149 // check in that case.
9150 if (Info.Deleted) {
9151 SetDeclDeleted(FD, FD->getLocation());
9152 if (!inTemplateInstantiation() && !FD->isImplicit()) {
9153 Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted)
9154 << (int)DCK;
9155 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9156 DefaultedComparisonAnalyzer::ExplainDeleted)
9157 .visit();
9158 if (FD->getDefaultLoc().isValid())
9159 Diag(FD->getDefaultLoc(), diag::note_replace_equals_default_to_delete)
9160 << FixItHint::CreateReplacement(FD->getDefaultLoc(), "delete");
9161 }
9162 return false;
9163 }
9164
9165 // C++2a [class.spaceship]p2:
9166 // The return type is deduced as the common comparison type of R0, R1, ...
9167 if (DCK == DefaultedComparisonKind::ThreeWay &&
9168 FD->getDeclaredReturnType()->isUndeducedAutoType()) {
9169 SourceLocation RetLoc = FD->getReturnTypeSourceRange().getBegin();
9170 if (RetLoc.isInvalid())
9171 RetLoc = FD->getBeginLoc();
9172 // FIXME: Should we really care whether we have the complete type and the
9173 // 'enumerator' constants here? A forward declaration seems sufficient.
9174 QualType Cat = CheckComparisonCategoryType(
9175 Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator);
9176 if (Cat.isNull())
9177 return true;
9178 Context.adjustDeducedFunctionResultType(
9179 FD, SubstAutoType(FD->getDeclaredReturnType(), Cat));
9180 }
9181
9182 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
9183 // An explicitly-defaulted function that is not defined as deleted may be
9184 // declared constexpr or consteval only if it is constexpr-compatible.
9185 // C++2a [class.compare.default]p3 [P2002R0]:
9186 // A defaulted comparison function is constexpr-compatible if it satisfies
9187 // the requirements for a constexpr function [...]
9188 // The only relevant requirements are that the parameter and return types are
9189 // literal types. The remaining conditions are checked by the analyzer.
9190 //
9191 // We support P2448R2 in language modes earlier than C++23 as an extension.
9192 // The concept of constexpr-compatible was removed.
9193 // C++23 [dcl.fct.def.default]p3 [P2448R2]
9194 // A function explicitly defaulted on its first declaration is implicitly
9195 // inline, and is implicitly constexpr if it is constexpr-suitable.
9196 // C++23 [dcl.constexpr]p3
9197 // A function is constexpr-suitable if
9198 // - it is not a coroutine, and
9199 // - if the function is a constructor or destructor, its class does not
9200 // have any virtual base classes.
9201 if (FD->isConstexpr()) {
9202 if (!getLangOpts().CPlusPlus23 &&
9203 CheckConstexprReturnType(*this, FD, CheckConstexprKind::Diagnose) &&
9204 CheckConstexprParameterTypes(*this, FD, CheckConstexprKind::Diagnose) &&
9205 !Info.Constexpr) {
9206 Diag(FD->getBeginLoc(), diag::err_defaulted_comparison_constexpr_mismatch)
9207 << FD->isImplicit() << (int)DCK << FD->isConsteval();
9208 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9209 DefaultedComparisonAnalyzer::ExplainConstexpr)
9210 .visit();
9211 }
9212 }
9213
9214 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
9215 // If a constexpr-compatible function is explicitly defaulted on its first
9216 // declaration, it is implicitly considered to be constexpr.
9217 // FIXME: Only applying this to the first declaration seems problematic, as
9218 // simple reorderings can affect the meaning of the program.
9219 if (First && !FD->isConstexpr() && Info.Constexpr)
9220 FD->setConstexprKind(ConstexprSpecKind::Constexpr);
9221
9222 // C++2a [except.spec]p3:
9223 // If a declaration of a function does not have a noexcept-specifier
9224 // [and] is defaulted on its first declaration, [...] the exception
9225 // specification is as specified below
9226 if (FD->getExceptionSpecType() == EST_None) {
9227 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9228 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9229 EPI.ExceptionSpec.Type = EST_Unevaluated;
9230 EPI.ExceptionSpec.SourceDecl = FD;
9231 FD->setType(Context.getFunctionType(FPT->getReturnType(),
9232 FPT->getParamTypes(), EPI));
9233 }
9234
9235 return false;
9236 }
9237
9238 void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
9239 FunctionDecl *Spaceship) {
9240 Sema::CodeSynthesisContext Ctx;
9241 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison;
9242 Ctx.PointOfInstantiation = Spaceship->getEndLoc();
9243 Ctx.Entity = Spaceship;
9244 pushCodeSynthesisContext(Ctx);
9245
9246 if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship))
9247 EqualEqual->setImplicit();
9248
9249 popCodeSynthesisContext();
9250 }
9251
9252 void Sema::DefineDefaultedComparison(SourceLocation UseLoc, FunctionDecl *FD,
9253 DefaultedComparisonKind DCK) {
9254 assert(FD->isDefaulted() && !FD->isDeleted() &&
9255 !FD->doesThisDeclarationHaveABody());
9256 if (FD->willHaveBody() || FD->isInvalidDecl())
9257 return;
9258
9259 SynthesizedFunctionScope Scope(*this, FD);
9260
9261 // Add a context note for diagnostics produced after this point.
9262 Scope.addContextNote(UseLoc);
9263
9264 {
9265 // Build and set up the function body.
9266 // The first parameter has type maybe-ref-to maybe-const T, use that to get
9267 // the type of the class being compared.
9268 auto PT = FD->getParamDecl(0)->getType();
9269 CXXRecordDecl *RD = PT.getNonReferenceType()->getAsCXXRecordDecl();
9270 SourceLocation BodyLoc =
9271 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
9272 StmtResult Body =
9273 DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build();
9274 if (Body.isInvalid()) {
9275 FD->setInvalidDecl();
9276 return;
9277 }
9278 FD->setBody(Body.get());
9279 FD->markUsed(Context);
9280 }
9281
9282 // The exception specification is needed because we are defining the
9283 // function. Note that this will reuse the body we just built.
9284 ResolveExceptionSpec(UseLoc, FD->getType()->castAs<FunctionProtoType>());
9285
9286 if (ASTMutationListener *L = getASTMutationListener())
9287 L->CompletedImplicitDefinition(FD);
9288 }
9289
9290 static Sema::ImplicitExceptionSpecification
9291 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
9292 FunctionDecl *FD,
9293 Sema::DefaultedComparisonKind DCK) {
9294 ComputingExceptionSpec CES(S, FD, Loc);
9295 Sema::ImplicitExceptionSpecification ExceptSpec(S);
9296
9297 if (FD->isInvalidDecl())
9298 return ExceptSpec;
9299
9300 // The common case is that we just defined the comparison function. In that
9301 // case, just look at whether the body can throw.
9302 if (FD->hasBody()) {
9303 ExceptSpec.CalledStmt(FD->getBody());
9304 } else {
9305 // Otherwise, build a body so we can check it. This should ideally only
9306 // happen when we're not actually marking the function referenced. (This is
9307 // only really important for efficiency: we don't want to build and throw
9308 // away bodies for comparison functions more than we strictly need to.)
9309
9310 // Pretend to synthesize the function body in an unevaluated context.
9311 // Note that we can't actually just go ahead and define the function here:
9312 // we are not permitted to mark its callees as referenced.
9313 Sema::SynthesizedFunctionScope Scope(S, FD);
9314 EnterExpressionEvaluationContext Context(
9315 S, Sema::ExpressionEvaluationContext::Unevaluated);
9316
9317 CXXRecordDecl *RD =
9318 cast<CXXRecordDecl>(FD->getFriendObjectKind() == Decl::FOK_None
9319 ? FD->getDeclContext()
9320 : FD->getLexicalDeclContext());
9321 SourceLocation BodyLoc =
9322 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
9323 StmtResult Body =
9324 DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build();
9325 if (!Body.isInvalid())
9326 ExceptSpec.CalledStmt(Body.get());
9327
9328 // FIXME: Can we hold onto this body and just transform it to potentially
9329 // evaluated when we're asked to define the function rather than rebuilding
9330 // it? Either that, or we should only build the bits of the body that we
9331 // need (the expressions, not the statements).
9332 }
9333
9334 return ExceptSpec;
9335 }
9336
9337 void Sema::CheckDelayedMemberExceptionSpecs() {
9338 decltype(DelayedOverridingExceptionSpecChecks) Overriding;
9339 decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
9340
9341 std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
9342 std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks);
9343
9344 // Perform any deferred checking of exception specifications for virtual
9345 // destructors.
9346 for (auto &Check : Overriding)
9347 CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
9348
9349 // Perform any deferred checking of exception specifications for befriended
9350 // special members.
9351 for (auto &Check : Equivalent)
9352 CheckEquivalentExceptionSpec(Check.second, Check.first);
9353 }
9354
9355 namespace {
9356 /// CRTP base class for visiting operations performed by a special member
9357 /// function (or inherited constructor).
9358 template<typename Derived>
9359 struct SpecialMemberVisitor {
9360 Sema &S;
9361 CXXMethodDecl *MD;
9362 CXXSpecialMemberKind CSM;
9363 Sema::InheritedConstructorInfo *ICI;
9364
9365 // Properties of the special member, computed for convenience.
9366 bool IsConstructor = false, IsAssignment = false, ConstArg = false;
9367
9368 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, CXXSpecialMemberKind CSM,
9369 Sema::InheritedConstructorInfo *ICI)
9370 : S(S), MD(MD), CSM(CSM), ICI(ICI) {
9371 switch (CSM) {
9372 case CXXSpecialMemberKind::DefaultConstructor:
9373 case CXXSpecialMemberKind::CopyConstructor:
9374 case CXXSpecialMemberKind::MoveConstructor:
9375 IsConstructor = true;
9376 break;
9377 case CXXSpecialMemberKind::CopyAssignment:
9378 case CXXSpecialMemberKind::MoveAssignment:
9379 IsAssignment = true;
9380 break;
9381 case CXXSpecialMemberKind::Destructor:
9382 break;
9383 case CXXSpecialMemberKind::Invalid:
9384 llvm_unreachable("invalid special member kind");
9385 }
9386
9387 if (MD->getNumExplicitParams()) {
9388 if (const ReferenceType *RT =
9389 MD->getNonObjectParameter(0)->getType()->getAs<ReferenceType>())
9390 ConstArg = RT->getPointeeType().isConstQualified();
9391 }
9392 }
9393
9394 Derived &getDerived() { return static_cast<Derived&>(*this); }
9395
9396 /// Is this a "move" special member?
9397 bool isMove() const {
9398 return CSM == CXXSpecialMemberKind::MoveConstructor ||
9399 CSM == CXXSpecialMemberKind::MoveAssignment;
9400 }
9401
9402 /// Look up the corresponding special member in the given class.
9403 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
9404 unsigned Quals, bool IsMutable) {
9405 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
9406 ConstArg && !IsMutable);
9407 }
9408
9409 /// Look up the constructor for the specified base class to see if it's
9410 /// overridden due to this being an inherited constructor.
9411 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
9412 if (!ICI)
9413 return {};
9414 assert(CSM == CXXSpecialMemberKind::DefaultConstructor);
9415 auto *BaseCtor =
9416 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
9417 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
9418 return MD;
9419 return {};
9420 }
9421
9422 /// A base or member subobject.
9423 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
9424
9425 /// Get the location to use for a subobject in diagnostics.
9426 static SourceLocation getSubobjectLoc(Subobject Subobj) {
9427 // FIXME: For an indirect virtual base, the direct base leading to
9428 // the indirect virtual base would be a more useful choice.
9429 if (auto *B = dyn_cast<CXXBaseSpecifier *>(Subobj))
9430 return B->getBaseTypeLoc();
9431 else
9432 return cast<FieldDecl *>(Subobj)->getLocation();
9433 }
9434
9435 enum BasesToVisit {
9436 /// Visit all non-virtual (direct) bases.
9437 VisitNonVirtualBases,
9438 /// Visit all direct bases, virtual or not.
9439 VisitDirectBases,
9440 /// Visit all non-virtual bases, and all virtual bases if the class
9441 /// is not abstract.
9442 VisitPotentiallyConstructedBases,
9443 /// Visit all direct or virtual bases.
9444 VisitAllBases
9445 };
9446
9447 // Visit the bases and members of the class.
9448 bool visit(BasesToVisit Bases) {
9449 CXXRecordDecl *RD = MD->getParent();
9450
9451 if (Bases == VisitPotentiallyConstructedBases)
9452 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
9453
9454 for (auto &B : RD->bases())
9455 if ((Bases == VisitDirectBases || !B.isVirtual()) &&
9456 getDerived().visitBase(&B))
9457 return true;
9458
9459 if (Bases == VisitAllBases)
9460 for (auto &B : RD->vbases())
9461 if (getDerived().visitBase(&B))
9462 return true;
9463
9464 for (auto *F : RD->fields())
9465 if (!F->isInvalidDecl() && !F->isUnnamedBitField() &&
9466 getDerived().visitField(F))
9467 return true;
9468
9469 return false;
9470 }
9471 };
9472 }
9473
9474 namespace {
9475 struct SpecialMemberDeletionInfo
9476 : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
9477 bool Diagnose;
9478
9479 SourceLocation Loc;
9480
9481 bool AllFieldsAreConst;
9482
9483 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
9484 CXXSpecialMemberKind CSM,
9485 Sema::InheritedConstructorInfo *ICI, bool Diagnose)
9486 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
9487 Loc(MD->getLocation()), AllFieldsAreConst(true) {}
9488
9489 bool inUnion() const { return MD->getParent()->isUnion(); }
9490
9491 CXXSpecialMemberKind getEffectiveCSM() {
9492 return ICI ? CXXSpecialMemberKind::Invalid : CSM;
9493 }
9494
9495 bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
9496
9497 bool shouldDeleteForVariantPtrAuthMember(const FieldDecl *FD);
9498
9499 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
9500 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
9501
9502 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
9503 bool shouldDeleteForField(FieldDecl *FD);
9504 bool shouldDeleteForAllConstMembers();
9505
9506 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
9507 unsigned Quals);
9508 bool shouldDeleteForSubobjectCall(Subobject Subobj,
9509 Sema::SpecialMemberOverloadResult SMOR,
9510 bool IsDtorCallInCtor);
9511
9512 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
9513 };
9514 }
9515
9516 /// Is the given special member inaccessible when used on the given
9517 /// sub-object.
9518 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
9519 CXXMethodDecl *target) {
9520 /// If we're operating on a base class, the object type is the
9521 /// type of this special member.
9522 CanQualType objectTy;
9523 AccessSpecifier access = target->getAccess();
9524 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
9525 objectTy = S.Context.getCanonicalTagType(MD->getParent());
9526 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
9527
9528 // If we're operating on a field, the object type is the type of the field.
9529 } else {
9530 objectTy = S.Context.getCanonicalTagType(target->getParent());
9531 }
9532
9533 return S.isMemberAccessibleForDeletion(
9534 target->getParent(), DeclAccessPair::make(target, access), objectTy);
9535 }
9536
9537 /// Check whether we should delete a special member due to the implicit
9538 /// definition containing a call to a special member of a subobject.
9539 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
9540 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
9541 bool IsDtorCallInCtor) {
9542 CXXMethodDecl *Decl = SMOR.getMethod();
9543 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9544
9545 enum {
9546 NotSet = -1,
9547 NoDecl,
9548 DeletedDecl,
9549 MultipleDecl,
9550 InaccessibleDecl,
9551 NonTrivialDecl
9552 } DiagKind = NotSet;
9553
9554 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) {
9555 if (CSM == CXXSpecialMemberKind::DefaultConstructor && Field &&
9556 Field->getParent()->isUnion()) {
9557 // [class.default.ctor]p2:
9558 // A defaulted default constructor for class X is defined as deleted if
9559 // - X is a union that has a variant member with a non-trivial default
9560 // constructor and no variant member of X has a default member
9561 // initializer
9562 const auto *RD = cast<CXXRecordDecl>(Field->getParent());
9563 if (RD->hasInClassInitializer())
9564 return false;
9565 }
9566 DiagKind = !Decl ? NoDecl : DeletedDecl;
9567 } else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
9568 DiagKind = MultipleDecl;
9569 else if (!isAccessible(Subobj, Decl))
9570 DiagKind = InaccessibleDecl;
9571 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
9572 !Decl->isTrivial()) {
9573 // A member of a union must have a trivial corresponding special member.
9574 // As a weird special case, a destructor call from a union's constructor
9575 // must be accessible and non-deleted, but need not be trivial. Such a
9576 // destructor is never actually called, but is semantically checked as
9577 // if it were.
9578 if (CSM == CXXSpecialMemberKind::DefaultConstructor) {
9579 // [class.default.ctor]p2:
9580 // A defaulted default constructor for class X is defined as deleted if
9581 // - X is a union that has a variant member with a non-trivial default
9582 // constructor and no variant member of X has a default member
9583 // initializer
9584 const auto *RD = cast<CXXRecordDecl>(Field->getParent());
9585 if (!RD->hasInClassInitializer())
9586 DiagKind = NonTrivialDecl;
9587 } else {
9588 DiagKind = NonTrivialDecl;
9589 }
9590 }
9591
9592 if (DiagKind == NotSet)
9593 return false;
9594
9595 if (Diagnose) {
9596 if (Field) {
9597 S.Diag(Field->getLocation(),
9598 diag::note_deleted_special_member_class_subobject)
9599 << getEffectiveCSM() << MD->getParent() << /*IsField*/ true << Field
9600 << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/ false;
9601 } else {
9602 CXXBaseSpecifier *Base = cast<CXXBaseSpecifier *>(Subobj);
9603 S.Diag(Base->getBeginLoc(),
9604 diag::note_deleted_special_member_class_subobject)
9605 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9606 << Base->getType() << DiagKind << IsDtorCallInCtor
9607 << /*IsObjCPtr*/ false;
9608 }
9609
9610 if (DiagKind == DeletedDecl)
9611 S.NoteDeletedFunction(Decl);
9612 // FIXME: Explain inaccessibility if DiagKind == InaccessibleDecl.
9613 }
9614
9615 return true;
9616 }
9617
9618 /// Check whether we should delete a special member function due to having a
9619 /// direct or virtual base class or non-static data member of class type M.
9620 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
9621 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
9622 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9623 bool IsMutable = Field && Field->isMutable();
9624
9625 // C++11 [class.ctor]p5:
9626 // -- any direct or virtual base class, or non-static data member with no
9627 // brace-or-equal-initializer, has class type M (or array thereof) and
9628 // either M has no default constructor or overload resolution as applied
9629 // to M's default constructor results in an ambiguity or in a function
9630 // that is deleted or inaccessible
9631 // C++11 [class.copy]p11, C++11 [class.copy]p23:
9632 // -- a direct or virtual base class B that cannot be copied/moved because
9633 // overload resolution, as applied to B's corresponding special member,
9634 // results in an ambiguity or a function that is deleted or inaccessible
9635 // from the defaulted special member
9636 // C++11 [class.dtor]p5:
9637 // -- any direct or virtual base class [...] has a type with a destructor
9638 // that is deleted or inaccessible
9639 if (!(CSM == CXXSpecialMemberKind::DefaultConstructor && Field &&
9640 Field->hasInClassInitializer()) &&
9641 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
9642 false))
9643 return true;
9644
9645 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
9646 // -- any direct or virtual base class or non-static data member has a
9647 // type with a destructor that is deleted or inaccessible
9648 if (IsConstructor) {
9649 Sema::SpecialMemberOverloadResult SMOR =
9650 S.LookupSpecialMember(Class, CXXSpecialMemberKind::Destructor, false,
9651 false, false, false, false);
9652 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
9653 return true;
9654 }
9655
9656 return false;
9657 }
9658
9659 bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
9660 FieldDecl *FD, QualType FieldType) {
9661 // The defaulted special functions are defined as deleted if this is a variant
9662 // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
9663 // type under ARC.
9664 if (!FieldType.hasNonTrivialObjCLifetime())
9665 return false;
9666
9667 // Don't make the defaulted default constructor defined as deleted if the
9668 // member has an in-class initializer.
9669 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
9670 FD->hasInClassInitializer())
9671 return false;
9672
9673 if (Diagnose) {
9674 auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
9675 S.Diag(FD->getLocation(), diag::note_deleted_special_member_class_subobject)
9676 << getEffectiveCSM() << ParentClass << /*IsField*/ true << FD << 4
9677 << /*IsDtorCallInCtor*/ false << /*IsObjCPtr*/ true;
9678 }
9679
9680 return true;
9681 }
9682
9683 bool SpecialMemberDeletionInfo::shouldDeleteForVariantPtrAuthMember(
9684 const FieldDecl *FD) {
9685 QualType FieldType = S.Context.getBaseElementType(FD->getType());
9686 // Copy/move constructors/assignment operators are deleted if the field has an
9687 // address-discriminated ptrauth qualifier.
9688 PointerAuthQualifier Q = FieldType.getPointerAuth();
9689
9690 if (!Q || !Q.isAddressDiscriminated())
9691 return false;
9692
9693 if (CSM == CXXSpecialMemberKind::DefaultConstructor ||
9694 CSM == CXXSpecialMemberKind::Destructor)
9695 return false;
9696
9697 if (Diagnose) {
9698 auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
9699 S.Diag(FD->getLocation(), diag::note_deleted_special_member_class_subobject)
9700 << getEffectiveCSM() << ParentClass << /*IsField*/ true << FD << 4
9701 << /*IsDtorCallInCtor*/ false << 2;
9702 }
9703
9704 return true;
9705 }
9706
9707 /// Check whether we should delete a special member function due to the class
9708 /// having a particular direct or virtual base class.
9709 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
9710 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
9711 // If program is correct, BaseClass cannot be null, but if it is, the error
9712 // must be reported elsewhere.
9713 if (!BaseClass)
9714 return false;
9715 // If we have an inheriting constructor, check whether we're calling an
9716 // inherited constructor instead of a default constructor.
9717 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
9718 if (auto *BaseCtor = SMOR.getMethod()) {
9719 // Note that we do not check access along this path; other than that,
9720 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
9721 // FIXME: Check that the base has a usable destructor! Sink this into
9722 // shouldDeleteForClassSubobject.
9723 if (BaseCtor->isDeleted() && Diagnose) {
9724 S.Diag(Base->getBeginLoc(),
9725 diag::note_deleted_special_member_class_subobject)
9726 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9727 << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
9728 << /*IsObjCPtr*/ false;
9729 S.NoteDeletedFunction(BaseCtor);
9730 }
9731 return BaseCtor->isDeleted();
9732 }
9733 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
9734 }
9735
9736 /// Check whether we should delete a special member function due to the class
9737 /// having a particular non-static data member.
9738 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
9739 QualType FieldType = S.Context.getBaseElementType(FD->getType());
9740 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
9741
9742 if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
9743 return true;
9744
9745 if (inUnion() && shouldDeleteForVariantPtrAuthMember(FD))
9746 return true;
9747
9748 if (CSM == CXXSpecialMemberKind::DefaultConstructor) {
9749 // For a default constructor, all references must be initialized in-class
9750 // and, if a union, it must have a non-const member.
9751 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
9752 if (Diagnose)
9753 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9754 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
9755 return true;
9756 }
9757 // C++11 [class.ctor]p5 (modified by DR2394): any non-variant non-static
9758 // data member of const-qualified type (or array thereof) with no
9759 // brace-or-equal-initializer is not const-default-constructible.
9760 if (!inUnion() && FieldType.isConstQualified() &&
9761 !FD->hasInClassInitializer() &&
9762 (!FieldRecord || !FieldRecord->allowConstDefaultInit())) {
9763 if (Diagnose)
9764 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9765 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
9766 return true;
9767 }
9768
9769 if (inUnion() && !FieldType.isConstQualified())
9770 AllFieldsAreConst = false;
9771 } else if (CSM == CXXSpecialMemberKind::CopyConstructor) {
9772 // For a copy constructor, data members must not be of rvalue reference
9773 // type.
9774 if (FieldType->isRValueReferenceType()) {
9775 if (Diagnose)
9776 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
9777 << MD->getParent() << FD << FieldType;
9778 return true;
9779 }
9780 } else if (IsAssignment) {
9781 // For an assignment operator, data members must not be of reference type.
9782 if (FieldType->isReferenceType()) {
9783 if (Diagnose)
9784 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9785 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
9786 return true;
9787 }
9788 if (!FieldRecord && FieldType.isConstQualified()) {
9789 // C++11 [class.copy]p23:
9790 // -- a non-static data member of const non-class type (or array thereof)
9791 if (Diagnose)
9792 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9793 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
9794 return true;
9795 }
9796 }
9797
9798 if (FieldRecord) {
9799 // Some additional restrictions exist on the variant members.
9800 if (!inUnion() && FieldRecord->isUnion() &&
9801 FieldRecord->isAnonymousStructOrUnion()) {
9802 bool AllVariantFieldsAreConst = true;
9803
9804 // FIXME: Handle anonymous unions declared within anonymous unions.
9805 for (auto *UI : FieldRecord->fields()) {
9806 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
9807
9808 if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
9809 return true;
9810
9811 if (shouldDeleteForVariantPtrAuthMember(&*UI))
9812 return true;
9813
9814 if (!UnionFieldType.isConstQualified())
9815 AllVariantFieldsAreConst = false;
9816
9817 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
9818 if (UnionFieldRecord &&
9819 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
9820 UnionFieldType.getCVRQualifiers()))
9821 return true;
9822 }
9823
9824 // At least one member in each anonymous union must be non-const
9825 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
9826 AllVariantFieldsAreConst && !FieldRecord->field_empty()) {
9827 if (Diagnose)
9828 S.Diag(FieldRecord->getLocation(),
9829 diag::note_deleted_default_ctor_all_const)
9830 << !!ICI << MD->getParent() << /*anonymous union*/1;
9831 return true;
9832 }
9833
9834 // Don't check the implicit member of the anonymous union type.
9835 // This is technically non-conformant but supported, and we have a
9836 // diagnostic for this elsewhere.
9837 return false;
9838 }
9839
9840 if (shouldDeleteForClassSubobject(FieldRecord, FD,
9841 FieldType.getCVRQualifiers()))
9842 return true;
9843 }
9844
9845 return false;
9846 }
9847
9848 /// C++11 [class.ctor] p5:
9849 /// A defaulted default constructor for a class X is defined as deleted if
9850 /// X is a union and all of its variant members are of const-qualified type.
9851 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
9852 // This is a silly definition, because it gives an empty union a deleted
9853 // default constructor. Don't do that.
9854 if (CSM == CXXSpecialMemberKind::DefaultConstructor && inUnion() &&
9855 AllFieldsAreConst) {
9856 bool AnyFields = false;
9857 for (auto *F : MD->getParent()->fields())
9858 if ((AnyFields = !F->isUnnamedBitField()))
9859 break;
9860 if (!AnyFields)
9861 return false;
9862 if (Diagnose)
9863 S.Diag(MD->getParent()->getLocation(),
9864 diag::note_deleted_default_ctor_all_const)
9865 << !!ICI << MD->getParent() << /*not anonymous union*/0;
9866 return true;
9867 }
9868 return false;
9869 }
9870
9871 /// Determine whether a defaulted special member function should be defined as
9872 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
9873 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
9874 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD,
9875 CXXSpecialMemberKind CSM,
9876 InheritedConstructorInfo *ICI,
9877 bool Diagnose) {
9878 if (MD->isInvalidDecl())
9879 return false;
9880 CXXRecordDecl *RD = MD->getParent();
9881 assert(!RD->isDependentType() && "do deletion after instantiation");
9882 if (!LangOpts.CPlusPlus || (!LangOpts.CPlusPlus11 && !RD->isLambda()) ||
9883 RD->isInvalidDecl())
9884 return false;
9885
9886 // C++11 [expr.lambda.prim]p19:
9887 // The closure type associated with a lambda-expression has a
9888 // deleted (8.4.3) default constructor and a deleted copy
9889 // assignment operator.
9890 // C++2a adds back these operators if the lambda has no lambda-capture.
9891 if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() &&
9892 (CSM == CXXSpecialMemberKind::DefaultConstructor ||
9893 CSM == CXXSpecialMemberKind::CopyAssignment)) {
9894 if (Diagnose)
9895 Diag(RD->getLocation(), diag::note_lambda_decl);
9896 return true;
9897 }
9898
9899 // C++11 [class.copy]p7, p18:
9900 // If the class definition declares a move constructor or move assignment
9901 // operator, an implicitly declared copy constructor or copy assignment
9902 // operator is defined as deleted.
9903 if (MD->isImplicit() && (CSM == CXXSpecialMemberKind::CopyConstructor ||
9904 CSM == CXXSpecialMemberKind::CopyAssignment)) {
9905 CXXMethodDecl *UserDeclaredMove = nullptr;
9906
9907 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
9908 // deletion of the corresponding copy operation, not both copy operations.
9909 // MSVC 2015 has adopted the standards conforming behavior.
9910 bool DeletesOnlyMatchingCopy =
9911 getLangOpts().MSVCCompat &&
9912 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
9913
9914 if (RD->hasUserDeclaredMoveConstructor() &&
9915 (!DeletesOnlyMatchingCopy ||
9916 CSM == CXXSpecialMemberKind::CopyConstructor)) {
9917 if (!Diagnose) return true;
9918
9919 // Find any user-declared move constructor.
9920 for (auto *I : RD->ctors()) {
9921 if (I->isMoveConstructor()) {
9922 UserDeclaredMove = I;
9923 break;
9924 }
9925 }
9926 assert(UserDeclaredMove);
9927 } else if (RD->hasUserDeclaredMoveAssignment() &&
9928 (!DeletesOnlyMatchingCopy ||
9929 CSM == CXXSpecialMemberKind::CopyAssignment)) {
9930 if (!Diagnose) return true;
9931
9932 // Find any user-declared move assignment operator.
9933 for (auto *I : RD->methods()) {
9934 if (I->isMoveAssignmentOperator()) {
9935 UserDeclaredMove = I;
9936 break;
9937 }
9938 }
9939 assert(UserDeclaredMove);
9940 }
9941
9942 if (UserDeclaredMove) {
9943 Diag(UserDeclaredMove->getLocation(),
9944 diag::note_deleted_copy_user_declared_move)
9945 << (CSM == CXXSpecialMemberKind::CopyAssignment) << RD
9946 << UserDeclaredMove->isMoveAssignmentOperator();
9947 return true;
9948 }
9949 }
9950
9951 // Do access control from the special member function
9952 ContextRAII MethodContext(*this, MD);
9953
9954 // C++11 [class.dtor]p5:
9955 // -- for a virtual destructor, lookup of the non-array deallocation function
9956 // results in an ambiguity or in a function that is deleted or inaccessible
9957 if (CSM == CXXSpecialMemberKind::Destructor && MD->isVirtual()) {
9958 FunctionDecl *OperatorDelete = nullptr;
9959 CanQualType DeallocType = Context.getCanonicalTagType(RD);
9960 DeclarationName Name =
9961 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
9962 ImplicitDeallocationParameters IDP = {
9963 DeallocType, ShouldUseTypeAwareOperatorNewOrDelete(),
9964 AlignedAllocationMode::No, SizedDeallocationMode::No};
9965 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
9966 OperatorDelete, IDP,
9967 /*Diagnose=*/false)) {
9968 if (Diagnose)
9969 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
9970 return true;
9971 }
9972 }
9973
9974 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
9975
9976 // Per DR1611, do not consider virtual bases of constructors of abstract
9977 // classes, since we are not going to construct them.
9978 // Per DR1658, do not consider virtual bases of destructors of abstract
9979 // classes either.
9980 // Per DR2180, for assignment operators we only assign (and thus only
9981 // consider) direct bases.
9982 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
9983 : SMI.VisitPotentiallyConstructedBases))
9984 return true;
9985
9986 if (SMI.shouldDeleteForAllConstMembers())
9987 return true;
9988
9989 if (getLangOpts().CUDA) {
9990 // We should delete the special member in CUDA mode if target inference
9991 // failed.
9992 // For inherited constructors (non-null ICI), CSM may be passed so that MD
9993 // is treated as certain special member, which may not reflect what special
9994 // member MD really is. However inferTargetForImplicitSpecialMember
9995 // expects CSM to match MD, therefore recalculate CSM.
9996 assert(ICI || CSM == getSpecialMember(MD));
9997 auto RealCSM = CSM;
9998 if (ICI)
9999 RealCSM = getSpecialMember(MD);
10000
10001 return CUDA().inferTargetForImplicitSpecialMember(RD, RealCSM, MD,
10002 SMI.ConstArg, Diagnose);
10003 }
10004
10005 return false;
10006 }
10007
10008 void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl *FD) {
10009 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
10010 assert(DFK && "not a defaultable function");
10011 assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted");
10012
10013 if (DFK.isSpecialMember()) {
10014 ShouldDeleteSpecialMember(cast<CXXMethodDecl>(FD), DFK.asSpecialMember(),
10015 nullptr, /*Diagnose=*/true);
10016 } else {
10017 DefaultedComparisonAnalyzer(
10018 *this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD,
10019 DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted)
10020 .visit();
10021 }
10022 }
10023
10024 /// Perform lookup for a special member of the specified kind, and determine
10025 /// whether it is trivial. If the triviality can be determined without the
10026 /// lookup, skip it. This is intended for use when determining whether a
10027 /// special member of a containing object is trivial, and thus does not ever
10028 /// perform overload resolution for default constructors.
10029 ///
10030 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
10031 /// member that was most likely to be intended to be trivial, if any.
10032 ///
10033 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
10034 /// determine whether the special member is trivial.
10035 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
10036 CXXSpecialMemberKind CSM, unsigned Quals,
10037 bool ConstRHS, TrivialABIHandling TAH,
10038 CXXMethodDecl **Selected) {
10039 if (Selected)
10040 *Selected = nullptr;
10041
10042 switch (CSM) {
10043 case CXXSpecialMemberKind::Invalid:
10044 llvm_unreachable("not a special member");
10045
10046 case CXXSpecialMemberKind::DefaultConstructor:
10047 // C++11 [class.ctor]p5:
10048 // A default constructor is trivial if:
10049 // - all the [direct subobjects] have trivial default constructors
10050 //
10051 // Note, no overload resolution is performed in this case.
10052 if (RD->hasTrivialDefaultConstructor())
10053 return true;
10054
10055 if (Selected) {
10056 // If there's a default constructor which could have been trivial, dig it
10057 // out. Otherwise, if there's any user-provided default constructor, point
10058 // to that as an example of why there's not a trivial one.
10059 CXXConstructorDecl *DefCtor = nullptr;
10060 if (RD->needsImplicitDefaultConstructor())
10061 S.DeclareImplicitDefaultConstructor(RD);
10062 for (auto *CI : RD->ctors()) {
10063 if (!CI->isDefaultConstructor())
10064 continue;
10065 DefCtor = CI;
10066 if (!DefCtor->isUserProvided())
10067 break;
10068 }
10069
10070 *Selected = DefCtor;
10071 }
10072
10073 return false;
10074
10075 case CXXSpecialMemberKind::Destructor:
10076 // C++11 [class.dtor]p5:
10077 // A destructor is trivial if:
10078 // - all the direct [subobjects] have trivial destructors
10079 if (RD->hasTrivialDestructor() ||
10080 (TAH == TrivialABIHandling::ConsiderTrivialABI &&
10081 RD->hasTrivialDestructorForCall()))
10082 return true;
10083
10084 if (Selected) {
10085 if (RD->needsImplicitDestructor())
10086 S.DeclareImplicitDestructor(RD);
10087 *Selected = RD->getDestructor();
10088 }
10089
10090 return false;
10091
10092 case CXXSpecialMemberKind::CopyConstructor:
10093 // C++11 [class.copy]p12:
10094 // A copy constructor is trivial if:
10095 // - the constructor selected to copy each direct [subobject] is trivial
10096 if (RD->hasTrivialCopyConstructor() ||
10097 (TAH == TrivialABIHandling::ConsiderTrivialABI &&
10098 RD->hasTrivialCopyConstructorForCall())) {
10099 if (Quals == Qualifiers::Const)
10100 // We must either select the trivial copy constructor or reach an
10101 // ambiguity; no need to actually perform overload resolution.
10102 return true;
10103 } else if (!Selected) {
10104 return false;
10105 }
10106 // In C++98, we are not supposed to perform overload resolution here, but we
10107 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
10108 // cases like B as having a non-trivial copy constructor:
10109 // struct A { template<typename T> A(T&); };
10110 // struct B { mutable A a; };
10111 goto NeedOverloadResolution;
10112
10113 case CXXSpecialMemberKind::CopyAssignment:
10114 // C++11 [class.copy]p25:
10115 // A copy assignment operator is trivial if:
10116 // - the assignment operator selected to copy each direct [subobject] is
10117 // trivial
10118 if (RD->hasTrivialCopyAssignment()) {
10119 if (Quals == Qualifiers::Const)
10120 return true;
10121 } else if (!Selected) {
10122 return false;
10123 }
10124 // In C++98, we are not supposed to perform overload resolution here, but we
10125 // treat that as a language defect.
10126 goto NeedOverloadResolution;
10127
10128 case CXXSpecialMemberKind::MoveConstructor:
10129 case CXXSpecialMemberKind::MoveAssignment:
10130 NeedOverloadResolution:
10131 Sema::SpecialMemberOverloadResult SMOR =
10132 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
10133
10134 // The standard doesn't describe how to behave if the lookup is ambiguous.
10135 // We treat it as not making the member non-trivial, just like the standard
10136 // mandates for the default constructor. This should rarely matter, because
10137 // the member will also be deleted.
10138 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
10139 return true;
10140
10141 if (!SMOR.getMethod()) {
10142 assert(SMOR.getKind() ==
10143 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
10144 return false;
10145 }
10146
10147 // We deliberately don't check if we found a deleted special member. We're
10148 // not supposed to!
10149 if (Selected)
10150 *Selected = SMOR.getMethod();
10151
10152 if (TAH == TrivialABIHandling::ConsiderTrivialABI &&
10153 (CSM == CXXSpecialMemberKind::CopyConstructor ||
10154 CSM == CXXSpecialMemberKind::MoveConstructor))
10155 return SMOR.getMethod()->isTrivialForCall();
10156 return SMOR.getMethod()->isTrivial();
10157 }
10158
10159 llvm_unreachable("unknown special method kind");
10160 }
10161
10162 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
10163 for (auto *CI : RD->ctors())
10164 if (!CI->isImplicit())
10165 return CI;
10166
10167 // Look for constructor templates.
10168 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
10169 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
10170 if (CXXConstructorDecl *CD =
10171 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
10172 return CD;
10173 }
10174
10175 return nullptr;
10176 }
10177
10178 /// The kind of subobject we are checking for triviality. The values of this
10179 /// enumeration are used in diagnostics.
10180 enum TrivialSubobjectKind {
10181 /// The subobject is a base class.
10182 TSK_BaseClass,
10183 /// The subobject is a non-static data member.
10184 TSK_Field,
10185 /// The object is actually the complete object.
10186 TSK_CompleteObject
10187 };
10188
10189 /// Check whether the special member selected for a given type would be trivial.
10190 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
10191 QualType SubType, bool ConstRHS,
10192 CXXSpecialMemberKind CSM,
10193 TrivialSubobjectKind Kind,
10194 TrivialABIHandling TAH, bool Diagnose) {
10195 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
10196 if (!SubRD)
10197 return true;
10198
10199 CXXMethodDecl *Selected;
10200 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
10201 ConstRHS, TAH, Diagnose ? &Selected : nullptr))
10202 return true;
10203
10204 if (Diagnose) {
10205 if (ConstRHS)
10206 SubType.addConst();
10207
10208 if (!Selected && CSM == CXXSpecialMemberKind::DefaultConstructor) {
10209 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
10210 << Kind << SubType.getUnqualifiedType();
10211 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
10212 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
10213 } else if (!Selected)
10214 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
10215 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
10216 else if (Selected->isUserProvided()) {
10217 if (Kind == TSK_CompleteObject)
10218 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
10219 << Kind << SubType.getUnqualifiedType() << CSM;
10220 else {
10221 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
10222 << Kind << SubType.getUnqualifiedType() << CSM;
10223 S.Diag(Selected->getLocation(), diag::note_declared_at);
10224 }
10225 } else {
10226 if (Kind != TSK_CompleteObject)
10227 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
10228 << Kind << SubType.getUnqualifiedType() << CSM;
10229
10230 // Explain why the defaulted or deleted special member isn't trivial.
10231 S.SpecialMemberIsTrivial(Selected, CSM,
10232 TrivialABIHandling::IgnoreTrivialABI, Diagnose);
10233 }
10234 }
10235
10236 return false;
10237 }
10238
10239 /// Check whether the members of a class type allow a special member to be
10240 /// trivial.
10241 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
10242 CXXSpecialMemberKind CSM, bool ConstArg,
10243 TrivialABIHandling TAH, bool Diagnose) {
10244 for (const auto *FI : RD->fields()) {
10245 if (FI->isInvalidDecl() || FI->isUnnamedBitField())
10246 continue;
10247
10248 QualType FieldType = S.Context.getBaseElementType(FI->getType());
10249
10250 // Pretend anonymous struct or union members are members of this class.
10251 if (FI->isAnonymousStructOrUnion()) {
10252 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
10253 CSM, ConstArg, TAH, Diagnose))
10254 return false;
10255 continue;
10256 }
10257
10258 // C++11 [class.ctor]p5:
10259 // A default constructor is trivial if [...]
10260 // -- no non-static data member of its class has a
10261 // brace-or-equal-initializer
10262 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
10263 FI->hasInClassInitializer()) {
10264 if (Diagnose)
10265 S.Diag(FI->getLocation(), diag::note_nontrivial_default_member_init)
10266 << FI;
10267 return false;
10268 }
10269
10270 // Objective C ARC 4.3.5:
10271 // [...] nontrivally ownership-qualified types are [...] not trivially
10272 // default constructible, copy constructible, move constructible, copy
10273 // assignable, move assignable, or destructible [...]
10274 if (FieldType.hasNonTrivialObjCLifetime()) {
10275 if (Diagnose)
10276 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
10277 << RD << FieldType.getObjCLifetime();
10278 return false;
10279 }
10280
10281 bool ConstRHS = ConstArg && !FI->isMutable();
10282 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
10283 CSM, TSK_Field, TAH, Diagnose))
10284 return false;
10285 }
10286
10287 return true;
10288 }
10289
10290 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD,
10291 CXXSpecialMemberKind CSM) {
10292 CanQualType Ty = Context.getCanonicalTagType(RD);
10293
10294 bool ConstArg = (CSM == CXXSpecialMemberKind::CopyConstructor ||
10295 CSM == CXXSpecialMemberKind::CopyAssignment);
10296 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
10297 TSK_CompleteObject,
10298 TrivialABIHandling::IgnoreTrivialABI,
10299 /*Diagnose*/ true);
10300 }
10301
10302 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMemberKind CSM,
10303 TrivialABIHandling TAH, bool Diagnose) {
10304 assert(!MD->isUserProvided() && CSM != CXXSpecialMemberKind::Invalid &&
10305 "not special enough");
10306
10307 CXXRecordDecl *RD = MD->getParent();
10308
10309 bool ConstArg = false;
10310
10311 // C++11 [class.copy]p12, p25: [DR1593]
10312 // A [special member] is trivial if [...] its parameter-type-list is
10313 // equivalent to the parameter-type-list of an implicit declaration [...]
10314 switch (CSM) {
10315 case CXXSpecialMemberKind::DefaultConstructor:
10316 case CXXSpecialMemberKind::Destructor:
10317 // Trivial default constructors and destructors cannot have parameters.
10318 break;
10319
10320 case CXXSpecialMemberKind::CopyConstructor:
10321 case CXXSpecialMemberKind::CopyAssignment: {
10322 const ParmVarDecl *Param0 = MD->getNonObjectParameter(0);
10323 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
10324
10325 // When ClangABICompat14 is true, CXX copy constructors will only be trivial
10326 // if they are not user-provided and their parameter-type-list is equivalent
10327 // to the parameter-type-list of an implicit declaration. This maintains the
10328 // behavior before dr2171 was implemented.
10329 //
10330 // Otherwise, if ClangABICompat14 is false, All copy constructors can be
10331 // trivial, if they are not user-provided, regardless of the qualifiers on
10332 // the reference type.
10333 const bool ClangABICompat14 = Context.getLangOpts().getClangABICompat() <=
10334 LangOptions::ClangABI::Ver14;
10335 if (!RT ||
10336 ((RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) &&
10337 ClangABICompat14)) {
10338 if (Diagnose)
10339 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
10340 << Param0->getSourceRange() << Param0->getType()
10341 << Context.getLValueReferenceType(
10342 Context.getCanonicalTagType(RD).withConst());
10343 return false;
10344 }
10345
10346 ConstArg = RT->getPointeeType().isConstQualified();
10347 break;
10348 }
10349
10350 case CXXSpecialMemberKind::MoveConstructor:
10351 case CXXSpecialMemberKind::MoveAssignment: {
10352 // Trivial move operations always have non-cv-qualified parameters.
10353 const ParmVarDecl *Param0 = MD->getNonObjectParameter(0);
10354 const RValueReferenceType *RT =
10355 Param0->getType()->getAs<RValueReferenceType>();
10356 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
10357 if (Diagnose)
10358 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
10359 << Param0->getSourceRange() << Param0->getType()
10360 << Context.getRValueReferenceType(Context.getCanonicalTagType(RD));
10361 return false;
10362 }
10363 break;
10364 }
10365
10366 case CXXSpecialMemberKind::Invalid:
10367 llvm_unreachable("not a special member");
10368 }
10369
10370 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
10371 if (Diagnose)
10372 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
10373 diag::note_nontrivial_default_arg)
10374 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
10375 return false;
10376 }
10377 if (MD->isVariadic()) {
10378 if (Diagnose)
10379 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
10380 return false;
10381 }
10382
10383 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
10384 // A copy/move [constructor or assignment operator] is trivial if
10385 // -- the [member] selected to copy/move each direct base class subobject
10386 // is trivial
10387 //
10388 // C++11 [class.copy]p12, C++11 [class.copy]p25:
10389 // A [default constructor or destructor] is trivial if
10390 // -- all the direct base classes have trivial [default constructors or
10391 // destructors]
10392 for (const auto &BI : RD->bases())
10393 if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
10394 ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
10395 return false;
10396
10397 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
10398 // A copy/move [constructor or assignment operator] for a class X is
10399 // trivial if
10400 // -- for each non-static data member of X that is of class type (or array
10401 // thereof), the constructor selected to copy/move that member is
10402 // trivial
10403 //
10404 // C++11 [class.copy]p12, C++11 [class.copy]p25:
10405 // A [default constructor or destructor] is trivial if
10406 // -- for all of the non-static data members of its class that are of class
10407 // type (or array thereof), each such class has a trivial [default
10408 // constructor or destructor]
10409 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
10410 return false;
10411
10412 // C++11 [class.dtor]p5:
10413 // A destructor is trivial if [...]
10414 // -- the destructor is not virtual
10415 if (CSM == CXXSpecialMemberKind::Destructor && MD->isVirtual()) {
10416 if (Diagnose)
10417 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
10418 return false;
10419 }
10420
10421 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
10422 // A [special member] for class X is trivial if [...]
10423 // -- class X has no virtual functions and no virtual base classes
10424 if (CSM != CXXSpecialMemberKind::Destructor &&
10425 MD->getParent()->isDynamicClass()) {
10426 if (!Diagnose)
10427 return false;
10428
10429 if (RD->getNumVBases()) {
10430 // Check for virtual bases. We already know that the corresponding
10431 // member in all bases is trivial, so vbases must all be direct.
10432 CXXBaseSpecifier &BS = *RD->vbases_begin();
10433 assert(BS.isVirtual());
10434 Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
10435 return false;
10436 }
10437
10438 // Must have a virtual method.
10439 for (const auto *MI : RD->methods()) {
10440 if (MI->isVirtual()) {
10441 SourceLocation MLoc = MI->getBeginLoc();
10442 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
10443 return false;
10444 }
10445 }
10446
10447 llvm_unreachable("dynamic class with no vbases and no virtual functions");
10448 }
10449
10450 // Looks like it's trivial!
10451 return true;
10452 }
10453
10454 namespace {
10455 struct FindHiddenVirtualMethod {
10456 Sema *S;
10457 CXXMethodDecl *Method;
10458 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
10459 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10460
10461 private:
10462 /// Check whether any most overridden method from MD in Methods
10463 static bool CheckMostOverridenMethods(
10464 const CXXMethodDecl *MD,
10465 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
10466 if (MD->size_overridden_methods() == 0)
10467 return Methods.count(MD->getCanonicalDecl());
10468 for (const CXXMethodDecl *O : MD->overridden_methods())
10469 if (CheckMostOverridenMethods(O, Methods))
10470 return true;
10471 return false;
10472 }
10473
10474 public:
10475 /// Member lookup function that determines whether a given C++
10476 /// method overloads virtual methods in a base class without overriding any,
10477 /// to be used with CXXRecordDecl::lookupInBases().
10478 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
10479 auto *BaseRecord = Specifier->getType()->castAsRecordDecl();
10480 DeclarationName Name = Method->getDeclName();
10481 assert(Name.getNameKind() == DeclarationName::Identifier);
10482
10483 bool foundSameNameMethod = false;
10484 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
10485 for (Path.Decls = BaseRecord->lookup(Name).begin();
10486 Path.Decls != DeclContext::lookup_iterator(); ++Path.Decls) {
10487 NamedDecl *D = *Path.Decls;
10488 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
10489 MD = MD->getCanonicalDecl();
10490 foundSameNameMethod = true;
10491 // Interested only in hidden virtual methods.
10492 if (!MD->isVirtual())
10493 continue;
10494 // If the method we are checking overrides a method from its base
10495 // don't warn about the other overloaded methods. Clang deviates from
10496 // GCC by only diagnosing overloads of inherited virtual functions that
10497 // do not override any other virtual functions in the base. GCC's
10498 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
10499 // function from a base class. These cases may be better served by a
10500 // warning (not specific to virtual functions) on call sites when the
10501 // call would select a different function from the base class, were it
10502 // visible.
10503 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
10504 if (!S->IsOverload(Method, MD, false))
10505 return true;
10506 // Collect the overload only if its hidden.
10507 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
10508 overloadedMethods.push_back(MD);
10509 }
10510 }
10511
10512 if (foundSameNameMethod)
10513 OverloadedMethods.append(overloadedMethods.begin(),
10514 overloadedMethods.end());
10515 return foundSameNameMethod;
10516 }
10517 };
10518 } // end anonymous namespace
10519
10520 /// Add the most overridden methods from MD to Methods
10521 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
10522 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
10523 if (MD->size_overridden_methods() == 0)
10524 Methods.insert(MD->getCanonicalDecl());
10525 else
10526 for (const CXXMethodDecl *O : MD->overridden_methods())
10527 AddMostOverridenMethods(O, Methods);
10528 }
10529
10530 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
10531 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10532 if (!MD->getDeclName().isIdentifier())
10533 return;
10534
10535 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
10536 /*bool RecordPaths=*/false,
10537 /*bool DetectVirtual=*/false);
10538 FindHiddenVirtualMethod FHVM;
10539 FHVM.Method = MD;
10540 FHVM.S = this;
10541
10542 // Keep the base methods that were overridden or introduced in the subclass
10543 // by 'using' in a set. A base method not in this set is hidden.
10544 CXXRecordDecl *DC = MD->getParent();
10545 for (NamedDecl *ND : DC->lookup(MD->getDeclName())) {
10546 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(ND))
10547 ND = shad->getTargetDecl();
10548 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
10549 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
10550 }
10551
10552 if (DC->lookupInBases(FHVM, Paths))
10553 OverloadedMethods = FHVM.OverloadedMethods;
10554 }
10555
10556 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
10557 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10558 for (const CXXMethodDecl *overloadedMD : OverloadedMethods) {
10559 PartialDiagnostic PD = PDiag(
10560 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
10561 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
10562 Diag(overloadedMD->getLocation(), PD);
10563 }
10564 }
10565
10566 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
10567 if (MD->isInvalidDecl())
10568 return;
10569
10570 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
10571 return;
10572
10573 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10574 FindHiddenVirtualMethods(MD, OverloadedMethods);
10575 if (!OverloadedMethods.empty()) {
10576 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
10577 << MD << (OverloadedMethods.size() > 1);
10578
10579 NoteHiddenVirtualMethods(MD, OverloadedMethods);
10580 }
10581 }
10582
10583 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
10584 auto PrintDiagAndRemoveAttr = [&](unsigned N) {
10585 // No diagnostics if this is a template instantiation.
10586 if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) {
10587 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
10588 diag::ext_cannot_use_trivial_abi) << &RD;
10589 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
10590 diag::note_cannot_use_trivial_abi_reason) << &RD << N;
10591 }
10592 RD.dropAttr<TrivialABIAttr>();
10593 };
10594
10595 // Ill-formed if the struct has virtual functions.
10596 if (RD.isPolymorphic()) {
10597 PrintDiagAndRemoveAttr(1);
10598 return;
10599 }
10600
10601 for (const auto &B : RD.bases()) {
10602 // Ill-formed if the base class is non-trivial for the purpose of calls or a
10603 // virtual base.
10604 if (!B.getType()->isDependentType() &&
10605 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) {
10606 PrintDiagAndRemoveAttr(2);
10607 return;
10608 }
10609
10610 if (B.isVirtual()) {
10611 PrintDiagAndRemoveAttr(3);
10612 return;
10613 }
10614 }
10615
10616 for (const auto *FD : RD.fields()) {
10617 // Ill-formed if the field is an ObjectiveC pointer or of a type that is
10618 // non-trivial for the purpose of calls.
10619 QualType FT = FD->getType();
10620 if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
10621 PrintDiagAndRemoveAttr(4);
10622 return;
10623 }
10624
10625 // Ill-formed if the field is an address-discriminated value.
10626 if (FT.hasAddressDiscriminatedPointerAuth()) {
10627 PrintDiagAndRemoveAttr(6);
10628 return;
10629 }
10630
10631 if (const auto *RT =
10632 FT->getBaseElementTypeUnsafe()->getAsCanonical<RecordType>())
10633 if (!RT->isDependentType() &&
10634 !cast<CXXRecordDecl>(RT->getDecl()->getDefinitionOrSelf())
10635 ->canPassInRegisters()) {
10636 PrintDiagAndRemoveAttr(5);
10637 return;
10638 }
10639 }
10640
10641 if (IsCXXTriviallyRelocatableType(RD))
10642 return;
10643
10644 // Ill-formed if the copy and move constructors are deleted.
10645 auto HasNonDeletedCopyOrMoveConstructor = [&]() {
10646 // If the type is dependent, then assume it might have
10647 // implicit copy or move ctor because we won't know yet at this point.
10648 if (RD.isDependentType())
10649 return true;
10650 if (RD.needsImplicitCopyConstructor() &&
10651 !RD.defaultedCopyConstructorIsDeleted())
10652 return true;
10653 if (RD.needsImplicitMoveConstructor() &&
10654 !RD.defaultedMoveConstructorIsDeleted())
10655 return true;
10656 for (const CXXConstructorDecl *CD : RD.ctors())
10657 if (CD->isCopyOrMoveConstructor() && !CD->isDeleted())
10658 return true;
10659 return false;
10660 };
10661
10662 if (!HasNonDeletedCopyOrMoveConstructor()) {
10663 PrintDiagAndRemoveAttr(0);
10664 return;
10665 }
10666 }
10667
10668 void Sema::checkIncorrectVTablePointerAuthenticationAttribute(
10669 CXXRecordDecl &RD) {
10670 if (RequireCompleteType(RD.getLocation(), Context.getCanonicalTagType(&RD),
10671 diag::err_incomplete_type_vtable_pointer_auth))
10672 return;
10673
10674 const CXXRecordDecl *PrimaryBase = &RD;
10675 if (PrimaryBase->hasAnyDependentBases())
10676 return;
10677
10678 while (1) {
10679 assert(PrimaryBase);
10680 const CXXRecordDecl *Base = nullptr;
10681 for (const CXXBaseSpecifier &BasePtr : PrimaryBase->bases()) {
10682 if (!BasePtr.getType()->getAsCXXRecordDecl()->isDynamicClass())
10683 continue;
10684 Base = BasePtr.getType()->getAsCXXRecordDecl();
10685 break;
10686 }
10687 if (!Base || Base == PrimaryBase || !Base->isPolymorphic())
10688 break;
10689 Diag(RD.getAttr<VTablePointerAuthenticationAttr>()->getLocation(),
10690 diag::err_non_top_level_vtable_pointer_auth)
10691 << &RD << Base;
10692 PrimaryBase = Base;
10693 }
10694
10695 if (!RD.isPolymorphic())
10696 Diag(RD.getAttr<VTablePointerAuthenticationAttr>()->getLocation(),
10697 diag::err_non_polymorphic_vtable_pointer_auth)
10698 << &RD;
10699 }
10700
10701 void Sema::ActOnFinishCXXMemberSpecification(
10702 Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
10703 SourceLocation RBrac, const ParsedAttributesView &AttrList) {
10704 if (!TagDecl)
10705 return;
10706
10707 AdjustDeclIfTemplate(TagDecl);
10708
10709 for (const ParsedAttr &AL : AttrList) {
10710 if (AL.getKind() != ParsedAttr::AT_Visibility)
10711 continue;
10712 AL.setInvalid();
10713 Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL;
10714 }
10715
10716 ActOnFields(S, RLoc, TagDecl,
10717 llvm::ArrayRef(
10718 // strict aliasing violation!
10719 reinterpret_cast<Decl **>(FieldCollector->getCurFields()),
10720 FieldCollector->getCurNumFields()),
10721 LBrac, RBrac, AttrList);
10722
10723 CheckCompletedCXXClass(S, cast<CXXRecordDecl>(TagDecl));
10724 }
10725
10726 /// Find the equality comparison functions that should be implicitly declared
10727 /// in a given class definition, per C++2a [class.compare.default]p3.
10728 static void findImplicitlyDeclaredEqualityComparisons(
10729 ASTContext &Ctx, CXXRecordDecl *RD,
10730 llvm::SmallVectorImpl<FunctionDecl *> &Spaceships) {
10731 DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual);
10732 if (!RD->lookup(EqEq).empty())
10733 // Member operator== explicitly declared: no implicit operator==s.
10734 return;
10735
10736 // Traverse friends looking for an '==' or a '<=>'.
10737 for (FriendDecl *Friend : RD->friends()) {
10738 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl());
10739 if (!FD) continue;
10740
10741 if (FD->getOverloadedOperator() == OO_EqualEqual) {
10742 // Friend operator== explicitly declared: no implicit operator==s.
10743 Spaceships.clear();
10744 return;
10745 }
10746
10747 if (FD->getOverloadedOperator() == OO_Spaceship &&
10748 FD->isExplicitlyDefaulted())
10749 Spaceships.push_back(FD);
10750 }
10751
10752 // Look for members named 'operator<=>'.
10753 DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(OO_Spaceship);
10754 for (NamedDecl *ND : RD->lookup(Cmp)) {
10755 // Note that we could find a non-function here (either a function template
10756 // or a using-declaration). Neither case results in an implicit
10757 // 'operator=='.
10758 if (auto *FD = dyn_cast<FunctionDecl>(ND))
10759 if (FD->isExplicitlyDefaulted())
10760 Spaceships.push_back(FD);
10761 }
10762 }
10763
10764 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
10765 // Don't add implicit special members to templated classes.
10766 // FIXME: This means unqualified lookups for 'operator=' within a class
10767 // template don't work properly.
10768 if (!ClassDecl->isDependentType()) {
10769 if (ClassDecl->needsImplicitDefaultConstructor()) {
10770 ++getASTContext().NumImplicitDefaultConstructors;
10771
10772 if (ClassDecl->hasInheritedConstructor())
10773 DeclareImplicitDefaultConstructor(ClassDecl);
10774 }
10775
10776 if (ClassDecl->needsImplicitCopyConstructor()) {
10777 ++getASTContext().NumImplicitCopyConstructors;
10778
10779 // If the properties or semantics of the copy constructor couldn't be
10780 // determined while the class was being declared, force a declaration
10781 // of it now.
10782 if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
10783 ClassDecl->hasInheritedConstructor())
10784 DeclareImplicitCopyConstructor(ClassDecl);
10785 // For the MS ABI we need to know whether the copy ctor is deleted. A
10786 // prerequisite for deleting the implicit copy ctor is that the class has
10787 // a move ctor or move assignment that is either user-declared or whose
10788 // semantics are inherited from a subobject. FIXME: We should provide a
10789 // more direct way for CodeGen to ask whether the constructor was deleted.
10790 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
10791 (ClassDecl->hasUserDeclaredMoveConstructor() ||
10792 ClassDecl->needsOverloadResolutionForMoveConstructor() ||
10793 ClassDecl->hasUserDeclaredMoveAssignment() ||
10794 ClassDecl->needsOverloadResolutionForMoveAssignment()))
10795 DeclareImplicitCopyConstructor(ClassDecl);
10796 }
10797
10798 if (getLangOpts().CPlusPlus11 &&
10799 ClassDecl->needsImplicitMoveConstructor()) {
10800 ++getASTContext().NumImplicitMoveConstructors;
10801
10802 if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
10803 ClassDecl->hasInheritedConstructor())
10804 DeclareImplicitMoveConstructor(ClassDecl);
10805 }
10806
10807 if (ClassDecl->needsImplicitCopyAssignment()) {
10808 ++getASTContext().NumImplicitCopyAssignmentOperators;
10809
10810 // If we have a dynamic class, then the copy assignment operator may be
10811 // virtual, so we have to declare it immediately. This ensures that, e.g.,
10812 // it shows up in the right place in the vtable and that we diagnose
10813 // problems with the implicit exception specification.
10814 if (ClassDecl->isDynamicClass() ||
10815 ClassDecl->needsOverloadResolutionForCopyAssignment() ||
10816 ClassDecl->hasInheritedAssignment())
10817 DeclareImplicitCopyAssignment(ClassDecl);
10818 }
10819
10820 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
10821 ++getASTContext().NumImplicitMoveAssignmentOperators;
10822
10823 // Likewise for the move assignment operator.
10824 if (ClassDecl->isDynamicClass() ||
10825 ClassDecl->needsOverloadResolutionForMoveAssignment() ||
10826 ClassDecl->hasInheritedAssignment())
10827 DeclareImplicitMoveAssignment(ClassDecl);
10828 }
10829
10830 if (ClassDecl->needsImplicitDestructor()) {
10831 ++getASTContext().NumImplicitDestructors;
10832
10833 // If we have a dynamic class, then the destructor may be virtual, so we
10834 // have to declare the destructor immediately. This ensures that, e.g., it
10835 // shows up in the right place in the vtable and that we diagnose problems
10836 // with the implicit exception specification.
10837 if (ClassDecl->isDynamicClass() ||
10838 ClassDecl->needsOverloadResolutionForDestructor())
10839 DeclareImplicitDestructor(ClassDecl);
10840 }
10841 }
10842
10843 // C++2a [class.compare.default]p3:
10844 // If the member-specification does not explicitly declare any member or
10845 // friend named operator==, an == operator function is declared implicitly
10846 // for each defaulted three-way comparison operator function defined in
10847 // the member-specification
10848 // FIXME: Consider doing this lazily.
10849 // We do this during the initial parse for a class template, not during
10850 // instantiation, so that we can handle unqualified lookups for 'operator=='
10851 // when parsing the template.
10852 if (getLangOpts().CPlusPlus20 && !inTemplateInstantiation()) {
10853 llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships;
10854 findImplicitlyDeclaredEqualityComparisons(Context, ClassDecl,
10855 DefaultedSpaceships);
10856 for (auto *FD : DefaultedSpaceships)
10857 DeclareImplicitEqualityComparison(ClassDecl, FD);
10858 }
10859 }
10860
10861 unsigned
10862 Sema::ActOnReenterTemplateScope(Decl *D,
10863 llvm::function_ref<Scope *()> EnterScope) {
10864 if (!D)
10865 return 0;
10866 AdjustDeclIfTemplate(D);
10867
10868 // In order to get name lookup right, reenter template scopes in order from
10869 // outermost to innermost.
10870 SmallVector<TemplateParameterList *, 4> ParameterLists;
10871 DeclContext *LookupDC = dyn_cast<DeclContext>(D);
10872
10873 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
10874 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
10875 ParameterLists.push_back(DD->getTemplateParameterList(i));
10876
10877 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
10878 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
10879 ParameterLists.push_back(FTD->getTemplateParameters());
10880 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
10881 LookupDC = VD->getDeclContext();
10882
10883 if (VarTemplateDecl *VTD = VD->getDescribedVarTemplate())
10884 ParameterLists.push_back(VTD->getTemplateParameters());
10885 else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D))
10886 ParameterLists.push_back(PSD->getTemplateParameters());
10887 }
10888 } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
10889 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
10890 ParameterLists.push_back(TD->getTemplateParameterList(i));
10891
10892 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
10893 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
10894 ParameterLists.push_back(CTD->getTemplateParameters());
10895 else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
10896 ParameterLists.push_back(PSD->getTemplateParameters());
10897 }
10898 }
10899 // FIXME: Alias declarations and concepts.
10900
10901 unsigned Count = 0;
10902 Scope *InnermostTemplateScope = nullptr;
10903 for (TemplateParameterList *Params : ParameterLists) {
10904 // Ignore explicit specializations; they don't contribute to the template
10905 // depth.
10906 if (Params->size() == 0)
10907 continue;
10908
10909 InnermostTemplateScope = EnterScope();
10910 for (NamedDecl *Param : *Params) {
10911 if (Param->getDeclName()) {
10912 InnermostTemplateScope->AddDecl(Param);
10913 IdResolver.AddDecl(Param);
10914 }
10915 }
10916 ++Count;
10917 }
10918
10919 // Associate the new template scopes with the corresponding entities.
10920 if (InnermostTemplateScope) {
10921 assert(LookupDC && "no enclosing DeclContext for template lookup");
10922 EnterTemplatedContext(InnermostTemplateScope, LookupDC);
10923 }
10924
10925 return Count;
10926 }
10927
10928 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
10929 if (!RecordD) return;
10930 AdjustDeclIfTemplate(RecordD);
10931 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
10932 PushDeclContext(S, Record);
10933 }
10934
10935 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
10936 if (!RecordD) return;
10937 PopDeclContext();
10938 }
10939
10940 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
10941 if (!Param)
10942 return;
10943
10944 S->AddDecl(Param);
10945 if (Param->getDeclName())
10946 IdResolver.AddDecl(Param);
10947 }
10948
10949 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
10950 }
10951
10952 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
10953 /// C++ method declaration. We're (re-)introducing the given
10954 /// function parameter into scope for use in parsing later parts of
10955 /// the method declaration. For example, we could see an
10956 /// ActOnParamDefaultArgument event for this parameter.
10957 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
10958 if (!ParamD)
10959 return;
10960
10961 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
10962
10963 S->AddDecl(Param);
10964 if (Param->getDeclName())
10965 IdResolver.AddDecl(Param);
10966 }
10967
10968 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
10969 if (!MethodD)
10970 return;
10971
10972 AdjustDeclIfTemplate(MethodD);
10973
10974 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
10975
10976 // Now that we have our default arguments, check the constructor
10977 // again. It could produce additional diagnostics or affect whether
10978 // the class has implicitly-declared destructors, among other
10979 // things.
10980 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
10981 CheckConstructor(Constructor);
10982
10983 // Check the default arguments, which we may have added.
10984 if (!Method->isInvalidDecl())
10985 CheckCXXDefaultArguments(Method);
10986 }
10987
10988 // Emit the given diagnostic for each non-address-space qualifier.
10989 // Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
10990 static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
10991 const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10992 if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
10993 bool DiagOccured = false;
10994 FTI.MethodQualifiers->forEachQualifier(
10995 [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName,
10996 SourceLocation SL) {
10997 // This diagnostic should be emitted on any qualifier except an addr
10998 // space qualifier. However, forEachQualifier currently doesn't visit
10999 // addr space qualifiers, so there's no way to write this condition
11000 // right now; we just diagnose on everything.
11001 S.Diag(SL, DiagID) << QualName << SourceRange(SL);
11002 DiagOccured = true;
11003 });
11004 if (DiagOccured)
11005 D.setInvalidType();
11006 }
11007 }
11008
11009 static void diagnoseInvalidDeclaratorChunks(Sema &S, Declarator &D,
11010 unsigned Kind) {
11011 if (D.isInvalidType() || D.getNumTypeObjects() <= 1)
11012 return;
11013
11014 DeclaratorChunk &Chunk = D.getTypeObject(D.getNumTypeObjects() - 1);
11015 if (Chunk.Kind == DeclaratorChunk::Paren ||
11016 Chunk.Kind == DeclaratorChunk::Function)
11017 return;
11018
11019 SourceLocation PointerLoc = Chunk.getSourceRange().getBegin();
11020 S.Diag(PointerLoc, diag::err_invalid_ctor_dtor_decl)
11021 << Kind << Chunk.getSourceRange();
11022 D.setInvalidType();
11023 }
11024
11025 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
11026 StorageClass &SC) {
11027 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
11028
11029 // C++ [class.ctor]p3:
11030 // A constructor shall not be virtual (10.3) or static (9.4). A
11031 // constructor can be invoked for a const, volatile or const
11032 // volatile object. A constructor shall not be declared const,
11033 // volatile, or const volatile (9.3.2).
11034 if (isVirtual) {
11035 if (!D.isInvalidType())
11036 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
11037 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
11038 << SourceRange(D.getIdentifierLoc());
11039 D.setInvalidType();
11040 }
11041 if (SC == SC_Static) {
11042 if (!D.isInvalidType())
11043 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
11044 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
11045 << SourceRange(D.getIdentifierLoc());
11046 D.setInvalidType();
11047 SC = SC_None;
11048 }
11049
11050 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
11051 diagnoseIgnoredQualifiers(
11052 diag::err_constructor_return_type, TypeQuals, SourceLocation(),
11053 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
11054 D.getDeclSpec().getRestrictSpecLoc(),
11055 D.getDeclSpec().getAtomicSpecLoc());
11056 D.setInvalidType();
11057 }
11058
11059 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor);
11060 diagnoseInvalidDeclaratorChunks(*this, D, /*constructor*/ 0);
11061
11062 // C++0x [class.ctor]p4:
11063 // A constructor shall not be declared with a ref-qualifier.
11064 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11065 if (FTI.hasRefQualifier()) {
11066 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
11067 << FTI.RefQualifierIsLValueRef
11068 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
11069 D.setInvalidType();
11070 }
11071
11072 // Rebuild the function type "R" without any type qualifiers (in
11073 // case any of the errors above fired) and with "void" as the
11074 // return type, since constructors don't have return types.
11075 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
11076 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
11077 return R;
11078
11079 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
11080 EPI.TypeQuals = Qualifiers();
11081 EPI.RefQualifier = RQ_None;
11082
11083 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
11084 }
11085
11086 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
11087 CXXRecordDecl *ClassDecl
11088 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
11089 if (!ClassDecl)
11090 return Constructor->setInvalidDecl();
11091
11092 // C++ [class.copy]p3:
11093 // A declaration of a constructor for a class X is ill-formed if
11094 // its first parameter is of type (optionally cv-qualified) X and
11095 // either there are no other parameters or else all other
11096 // parameters have default arguments.
11097 if (!Constructor->isInvalidDecl() &&
11098 Constructor->hasOneParamOrDefaultArgs() &&
11099 !Constructor->isFunctionTemplateSpecialization()) {
11100 CanQualType ParamType =
11101 Constructor->getParamDecl(0)->getType()->getCanonicalTypeUnqualified();
11102 CanQualType ClassTy = Context.getCanonicalTagType(ClassDecl);
11103 if (ParamType == ClassTy) {
11104 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
11105 const char *ConstRef
11106 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
11107 : " const &";
11108 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
11109 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
11110
11111 // FIXME: Rather that making the constructor invalid, we should endeavor
11112 // to fix the type.
11113 Constructor->setInvalidDecl();
11114 }
11115 }
11116 }
11117
11118 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
11119 CXXRecordDecl *RD = Destructor->getParent();
11120
11121 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
11122 SourceLocation Loc;
11123
11124 if (!Destructor->isImplicit())
11125 Loc = Destructor->getLocation();
11126 else
11127 Loc = RD->getLocation();
11128
11129 DeclarationName Name =
11130 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
11131 // If we have a virtual destructor, look up the deallocation function
11132 if (FunctionDecl *OperatorDelete = FindDeallocationFunctionForDestructor(
11133 Loc, RD, /*Diagnose=*/true, /*LookForGlobal=*/false, Name)) {
11134 Expr *ThisArg = nullptr;
11135
11136 // If the notional 'delete this' expression requires a non-trivial
11137 // conversion from 'this' to the type of a destroying operator delete's
11138 // first parameter, perform that conversion now.
11139 if (OperatorDelete->isDestroyingOperatorDelete()) {
11140 unsigned AddressParamIndex = 0;
11141 if (OperatorDelete->isTypeAwareOperatorNewOrDelete())
11142 ++AddressParamIndex;
11143 QualType ParamType =
11144 OperatorDelete->getParamDecl(AddressParamIndex)->getType();
11145 if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
11146 // C++ [class.dtor]p13:
11147 // ... as if for the expression 'delete this' appearing in a
11148 // non-virtual destructor of the destructor's class.
11149 ContextRAII SwitchContext(*this, Destructor);
11150 ExprResult This = ActOnCXXThis(
11151 OperatorDelete->getParamDecl(AddressParamIndex)->getLocation());
11152 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
11153 This = PerformImplicitConversion(This.get(), ParamType,
11154 AssignmentAction::Passing);
11155 if (This.isInvalid()) {
11156 // FIXME: Register this as a context note so that it comes out
11157 // in the right order.
11158 Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
11159 return true;
11160 }
11161 ThisArg = This.get();
11162 }
11163 }
11164
11165 DiagnoseUseOfDecl(OperatorDelete, Loc);
11166 MarkFunctionReferenced(Loc, OperatorDelete);
11167 Destructor->setOperatorDelete(OperatorDelete, ThisArg);
11168
11169 if (isa<CXXMethodDecl>(OperatorDelete) &&
11170 Context.getTargetInfo().callGlobalDeleteInDeletingDtor(
11171 Context.getLangOpts())) {
11172 // In Microsoft ABI whenever a class has a defined operator delete,
11173 // scalar deleting destructors check the 3rd bit of the implicit
11174 // parameter and if it is set, then, global operator delete must be
11175 // called instead of the class-specific one. Find and save the global
11176 // operator delete for that case. Do not diagnose at this point because
11177 // the lack of a global operator delete is not an error if there are no
11178 // delete calls that require it.
11179 FunctionDecl *GlobalOperatorDelete =
11180 FindDeallocationFunctionForDestructor(Loc, RD, /*Diagnose*/ false,
11181 /*LookForGlobal*/ true, Name);
11182 if (GlobalOperatorDelete) {
11183 MarkFunctionReferenced(Loc, GlobalOperatorDelete);
11184 Destructor->setOperatorGlobalDelete(GlobalOperatorDelete);
11185 }
11186 }
11187
11188 if (Context.getTargetInfo().emitVectorDeletingDtors(
11189 Context.getLangOpts())) {
11190 // Lookup delete[] too in case we have to emit a vector deleting dtor.
11191 DeclarationName VDeleteName =
11192 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
11193 FunctionDecl *ArrOperatorDelete = FindDeallocationFunctionForDestructor(
11194 Loc, RD, /*Diagnose*/ false,
11195 /*LookForGlobal*/ false, VDeleteName);
11196 if (ArrOperatorDelete && isa<CXXMethodDecl>(ArrOperatorDelete)) {
11197 FunctionDecl *GlobalArrOperatorDelete =
11198 FindDeallocationFunctionForDestructor(Loc, RD, /*Diagnose*/ false,
11199 /*LookForGlobal*/ true,
11200 VDeleteName);
11201 Destructor->setGlobalOperatorArrayDelete(GlobalArrOperatorDelete);
11202 if (GlobalArrOperatorDelete &&
11203 Context.classNeedsVectorDeletingDestructor(RD))
11204 MarkFunctionReferenced(Loc, GlobalArrOperatorDelete);
11205 } else if (!ArrOperatorDelete) {
11206 ArrOperatorDelete = FindDeallocationFunctionForDestructor(
11207 Loc, RD, /*Diagnose*/ false,
11208 /*LookForGlobal*/ true, VDeleteName);
11209 }
11210 Destructor->setOperatorArrayDelete(ArrOperatorDelete);
11211 if (ArrOperatorDelete && Context.classNeedsVectorDeletingDestructor(RD))
11212 MarkFunctionReferenced(Loc, ArrOperatorDelete);
11213 }
11214 }
11215 }
11216
11217 return false;
11218 }
11219
11220 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
11221 StorageClass& SC) {
11222 // C++ [class.dtor]p1:
11223 // [...] A typedef-name that names a class is a class-name
11224 // (7.1.3); however, a typedef-name that names a class shall not
11225 // be used as the identifier in the declarator for a destructor
11226 // declaration.
11227 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
11228 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
11229 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
11230 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
11231 else if (const TemplateSpecializationType *TST =
11232 DeclaratorType->getAs<TemplateSpecializationType>())
11233 if (TST->isTypeAlias())
11234 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
11235 << DeclaratorType << 1;
11236
11237 // C++ [class.dtor]p2:
11238 // A destructor is used to destroy objects of its class type. A
11239 // destructor takes no parameters, and no return type can be
11240 // specified for it (not even void). The address of a destructor
11241 // shall not be taken. A destructor shall not be static. A
11242 // destructor can be invoked for a const, volatile or const
11243 // volatile object. A destructor shall not be declared const,
11244 // volatile or const volatile (9.3.2).
11245 if (SC == SC_Static) {
11246 if (!D.isInvalidType())
11247 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
11248 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
11249 << SourceRange(D.getIdentifierLoc())
11250 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
11251
11252 SC = SC_None;
11253 }
11254 if (!D.isInvalidType()) {
11255 // Destructors don't have return types, but the parser will
11256 // happily parse something like:
11257 //
11258 // class X {
11259 // float ~X();
11260 // };
11261 //
11262 // The return type will be eliminated later.
11263 if (D.getDeclSpec().hasTypeSpecifier())
11264 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
11265 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
11266 << SourceRange(D.getIdentifierLoc());
11267 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
11268 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
11269 SourceLocation(),
11270 D.getDeclSpec().getConstSpecLoc(),
11271 D.getDeclSpec().getVolatileSpecLoc(),
11272 D.getDeclSpec().getRestrictSpecLoc(),
11273 D.getDeclSpec().getAtomicSpecLoc());
11274 D.setInvalidType();
11275 }
11276 }
11277
11278 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor);
11279 diagnoseInvalidDeclaratorChunks(*this, D, /*destructor*/ 1);
11280
11281 // C++0x [class.dtor]p2:
11282 // A destructor shall not be declared with a ref-qualifier.
11283 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11284 if (FTI.hasRefQualifier()) {
11285 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
11286 << FTI.RefQualifierIsLValueRef
11287 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
11288 D.setInvalidType();
11289 }
11290
11291 // Make sure we don't have any parameters.
11292 if (FTIHasNonVoidParameters(FTI)) {
11293 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
11294
11295 // Delete the parameters.
11296 FTI.freeParams();
11297 D.setInvalidType();
11298 }
11299
11300 // Make sure the destructor isn't variadic.
11301 if (FTI.isVariadic) {
11302 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
11303 D.setInvalidType();
11304 }
11305
11306 // Rebuild the function type "R" without any type qualifiers or
11307 // parameters (in case any of the errors above fired) and with
11308 // "void" as the return type, since destructors don't have return
11309 // types.
11310 if (!D.isInvalidType())
11311 return R;
11312
11313 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
11314 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
11315 EPI.Variadic = false;
11316 EPI.TypeQuals = Qualifiers();
11317 EPI.RefQualifier = RQ_None;
11318 return Context.getFunctionType(Context.VoidTy, {}, EPI);
11319 }
11320
11321 static void extendLeft(SourceRange &R, SourceRange Before) {
11322 if (Before.isInvalid())
11323 return;
11324 R.setBegin(Before.getBegin());
11325 if (R.getEnd().isInvalid())
11326 R.setEnd(Before.getEnd());
11327 }
11328
11329 static void extendRight(SourceRange &R, SourceRange After) {
11330 if (After.isInvalid())
11331 return;
11332 if (R.getBegin().isInvalid())
11333 R.setBegin(After.getBegin());
11334 R.setEnd(After.getEnd());
11335 }
11336
11337 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
11338 StorageClass& SC) {
11339 // C++ [class.conv.fct]p1:
11340 // Neither parameter types nor return type can be specified. The
11341 // type of a conversion function (8.3.5) is "function taking no
11342 // parameter returning conversion-type-id."
11343 if (SC == SC_Static) {
11344 if (!D.isInvalidType())
11345 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
11346 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
11347 << D.getName().getSourceRange();
11348 D.setInvalidType();
11349 SC = SC_None;
11350 }
11351
11352 TypeSourceInfo *ConvTSI = nullptr;
11353 QualType ConvType =
11354 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
11355
11356 const DeclSpec &DS = D.getDeclSpec();
11357 if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
11358 // Conversion functions don't have return types, but the parser will
11359 // happily parse something like:
11360 //
11361 // class X {
11362 // float operator bool();
11363 // };
11364 //
11365 // The return type will be changed later anyway.
11366 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
11367 << SourceRange(DS.getTypeSpecTypeLoc())
11368 << SourceRange(D.getIdentifierLoc());
11369 D.setInvalidType();
11370 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
11371 // It's also plausible that the user writes type qualifiers in the wrong
11372 // place, such as:
11373 // struct S { const operator int(); };
11374 // FIXME: we could provide a fixit to move the qualifiers onto the
11375 // conversion type.
11376 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
11377 << SourceRange(D.getIdentifierLoc()) << 0;
11378 D.setInvalidType();
11379 }
11380 const auto *Proto = R->castAs<FunctionProtoType>();
11381 // Make sure we don't have any parameters.
11382 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11383 unsigned NumParam = Proto->getNumParams();
11384
11385 // [C++2b]
11386 // A conversion function shall have no non-object parameters.
11387 if (NumParam == 1) {
11388 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11389 if (const auto *First =
11390 dyn_cast_if_present<ParmVarDecl>(FTI.Params[0].Param);
11391 First && First->isExplicitObjectParameter())
11392 NumParam--;
11393 }
11394
11395 if (NumParam != 0) {
11396 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
11397 // Delete the parameters.
11398 FTI.freeParams();
11399 D.setInvalidType();
11400 } else if (Proto->isVariadic()) {
11401 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
11402 D.setInvalidType();
11403 }
11404
11405 // Diagnose "&operator bool()" and other such nonsense. This
11406 // is actually a gcc extension which we don't support.
11407 if (Proto->getReturnType() != ConvType) {
11408 bool NeedsTypedef = false;
11409 SourceRange Before, After;
11410
11411 // Walk the chunks and extract information on them for our diagnostic.
11412 bool PastFunctionChunk = false;
11413 for (auto &Chunk : D.type_objects()) {
11414 switch (Chunk.Kind) {
11415 case DeclaratorChunk::Function:
11416 if (!PastFunctionChunk) {
11417 if (Chunk.Fun.HasTrailingReturnType) {
11418 TypeSourceInfo *TRT = nullptr;
11419 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
11420 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
11421 }
11422 PastFunctionChunk = true;
11423 break;
11424 }
11425 [[fallthrough]];
11426 case DeclaratorChunk::Array:
11427 NeedsTypedef = true;
11428 extendRight(After, Chunk.getSourceRange());
11429 break;
11430
11431 case DeclaratorChunk::Pointer:
11432 case DeclaratorChunk::BlockPointer:
11433 case DeclaratorChunk::Reference:
11434 case DeclaratorChunk::MemberPointer:
11435 case DeclaratorChunk::Pipe:
11436 extendLeft(Before, Chunk.getSourceRange());
11437 break;
11438
11439 case DeclaratorChunk::Paren:
11440 extendLeft(Before, Chunk.Loc);
11441 extendRight(After, Chunk.EndLoc);
11442 break;
11443 }
11444 }
11445
11446 SourceLocation Loc = Before.isValid() ? Before.getBegin() :
11447 After.isValid() ? After.getBegin() :
11448 D.getIdentifierLoc();
11449 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
11450 DB << Before << After;
11451
11452 if (!NeedsTypedef) {
11453 DB << /*don't need a typedef*/0;
11454
11455 // If we can provide a correct fix-it hint, do so.
11456 if (After.isInvalid() && ConvTSI) {
11457 SourceLocation InsertLoc =
11458 getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc());
11459 DB << FixItHint::CreateInsertion(InsertLoc, " ")
11460 << FixItHint::CreateInsertionFromRange(
11461 InsertLoc, CharSourceRange::getTokenRange(Before))
11462 << FixItHint::CreateRemoval(Before);
11463 }
11464 } else if (!Proto->getReturnType()->isDependentType()) {
11465 DB << /*typedef*/1 << Proto->getReturnType();
11466 } else if (getLangOpts().CPlusPlus11) {
11467 DB << /*alias template*/2 << Proto->getReturnType();
11468 } else {
11469 DB << /*might not be fixable*/3;
11470 }
11471
11472 // Recover by incorporating the other type chunks into the result type.
11473 // Note, this does *not* change the name of the function. This is compatible
11474 // with the GCC extension:
11475 // struct S { &operator int(); } s;
11476 // int &r = s.operator int(); // ok in GCC
11477 // S::operator int&() {} // error in GCC, function name is 'operator int'.
11478 ConvType = Proto->getReturnType();
11479 }
11480
11481 // C++ [class.conv.fct]p4:
11482 // The conversion-type-id shall not represent a function type nor
11483 // an array type.
11484 if (ConvType->isArrayType()) {
11485 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
11486 ConvType = Context.getPointerType(ConvType);
11487 D.setInvalidType();
11488 } else if (ConvType->isFunctionType()) {
11489 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
11490 ConvType = Context.getPointerType(ConvType);
11491 D.setInvalidType();
11492 }
11493
11494 // Rebuild the function type "R" without any parameters (in case any
11495 // of the errors above fired) and with the conversion type as the
11496 // return type.
11497 if (D.isInvalidType())
11498 R = Context.getFunctionType(ConvType, {}, Proto->getExtProtoInfo());
11499
11500 // C++0x explicit conversion operators.
11501 if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus20)
11502 Diag(DS.getExplicitSpecLoc(),
11503 getLangOpts().CPlusPlus11
11504 ? diag::warn_cxx98_compat_explicit_conversion_functions
11505 : diag::ext_explicit_conversion_functions)
11506 << SourceRange(DS.getExplicitSpecRange());
11507 }
11508
11509 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
11510 assert(Conversion && "Expected to receive a conversion function declaration");
11511
11512 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
11513
11514 // Make sure we aren't redeclaring the conversion function.
11515 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
11516 // C++ [class.conv.fct]p1:
11517 // [...] A conversion function is never used to convert a
11518 // (possibly cv-qualified) object to the (possibly cv-qualified)
11519 // same object type (or a reference to it), to a (possibly
11520 // cv-qualified) base class of that type (or a reference to it),
11521 // or to (possibly cv-qualified) void.
11522 CanQualType ClassType = Context.getCanonicalTagType(ClassDecl);
11523 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
11524 ConvType = ConvTypeRef->getPointeeType();
11525 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
11526 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
11527 /* Suppress diagnostics for instantiations. */;
11528 else if (Conversion->size_overridden_methods() != 0)
11529 /* Suppress diagnostics for overriding virtual function in a base class. */;
11530 else if (ConvType->isRecordType()) {
11531 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
11532 if (ConvType == ClassType)
11533 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
11534 << ClassType;
11535 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
11536 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
11537 << ClassType << ConvType;
11538 } else if (ConvType->isVoidType()) {
11539 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
11540 << ClassType << ConvType;
11541 }
11542
11543 if (FunctionTemplateDecl *ConversionTemplate =
11544 Conversion->getDescribedFunctionTemplate()) {
11545 if (const auto *ConvTypePtr = ConvType->getAs<PointerType>()) {
11546 ConvType = ConvTypePtr->getPointeeType();
11547 }
11548 if (ConvType->isUndeducedAutoType()) {
11549 Diag(Conversion->getTypeSpecStartLoc(), diag::err_auto_not_allowed)
11550 << getReturnTypeLoc(Conversion).getSourceRange()
11551 << ConvType->castAs<AutoType>()->getKeyword()
11552 << /* in declaration of conversion function template= */ 24;
11553 }
11554
11555 return ConversionTemplate;
11556 }
11557
11558 return Conversion;
11559 }
11560
11561 void Sema::CheckExplicitObjectMemberFunction(DeclContext *DC, Declarator &D,
11562 DeclarationName Name, QualType R) {
11563 CheckExplicitObjectMemberFunction(D, Name, R, false, DC);
11564 }
11565
11566 void Sema::CheckExplicitObjectLambda(Declarator &D) {
11567 CheckExplicitObjectMemberFunction(D, {}, {}, true);
11568 }
11569
11570 void Sema::CheckExplicitObjectMemberFunction(Declarator &D,
11571 DeclarationName Name, QualType R,
11572 bool IsLambda, DeclContext *DC) {
11573 if (!D.isFunctionDeclarator())
11574 return;
11575
11576 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11577 if (FTI.NumParams == 0)
11578 return;
11579 ParmVarDecl *ExplicitObjectParam = nullptr;
11580 for (unsigned Idx = 0; Idx < FTI.NumParams; Idx++) {
11581 const auto &ParamInfo = FTI.Params[Idx];
11582 if (!ParamInfo.Param)
11583 continue;
11584 ParmVarDecl *Param = cast<ParmVarDecl>(ParamInfo.Param);
11585 if (!Param->isExplicitObjectParameter())
11586 continue;
11587 if (Idx == 0) {
11588 ExplicitObjectParam = Param;
11589 continue;
11590 } else {
11591 Diag(Param->getLocation(),
11592 diag::err_explicit_object_parameter_must_be_first)
11593 << IsLambda << Param->getSourceRange();
11594 }
11595 }
11596 if (!ExplicitObjectParam)
11597 return;
11598
11599 if (ExplicitObjectParam->hasDefaultArg()) {
11600 Diag(ExplicitObjectParam->getLocation(),
11601 diag::err_explicit_object_default_arg)
11602 << ExplicitObjectParam->getSourceRange();
11603 }
11604
11605 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static ||
11606 (D.getContext() == clang::DeclaratorContext::Member &&
11607 D.isStaticMember())) {
11608 Diag(ExplicitObjectParam->getBeginLoc(),
11609 diag::err_explicit_object_parameter_nonmember)
11610 << D.getSourceRange() << /*static=*/0 << IsLambda;
11611 D.setInvalidType();
11612 }
11613
11614 if (D.getDeclSpec().isVirtualSpecified()) {
11615 Diag(ExplicitObjectParam->getBeginLoc(),
11616 diag::err_explicit_object_parameter_nonmember)
11617 << D.getSourceRange() << /*virtual=*/1 << IsLambda;
11618 D.setInvalidType();
11619 }
11620
11621 // Friend declarations require some care. Consider:
11622 //
11623 // namespace N {
11624 // struct A{};
11625 // int f(A);
11626 // }
11627 //
11628 // struct S {
11629 // struct T {
11630 // int f(this T);
11631 // };
11632 //
11633 // friend int T::f(this T); // Allow this.
11634 // friend int f(this S); // But disallow this.
11635 // friend int N::f(this A); // And disallow this.
11636 // };
11637 //
11638 // Here, it seems to suffice to check whether the scope
11639 // specifier designates a class type.
11640 if (D.getDeclSpec().isFriendSpecified() &&
11641 !isa_and_present<CXXRecordDecl>(
11642 computeDeclContext(D.getCXXScopeSpec()))) {
11643 Diag(ExplicitObjectParam->getBeginLoc(),
11644 diag::err_explicit_object_parameter_nonmember)
11645 << D.getSourceRange() << /*non-member=*/2 << IsLambda;
11646 D.setInvalidType();
11647 }
11648
11649 if (IsLambda && FTI.hasMutableQualifier()) {
11650 Diag(ExplicitObjectParam->getBeginLoc(),
11651 diag::err_explicit_object_parameter_mutable)
11652 << D.getSourceRange();
11653 }
11654
11655 if (IsLambda)
11656 return;
11657
11658 if (!DC || !DC->isRecord()) {
11659 assert(D.isInvalidType() && "Explicit object parameter in non-member "
11660 "should have been diagnosed already");
11661 return;
11662 }
11663
11664 // CWG2674: constructors and destructors cannot have explicit parameters.
11665 if (Name.getNameKind() == DeclarationName::CXXConstructorName ||
11666 Name.getNameKind() == DeclarationName::CXXDestructorName) {
11667 Diag(ExplicitObjectParam->getBeginLoc(),
11668 diag::err_explicit_object_parameter_constructor)
11669 << (Name.getNameKind() == DeclarationName::CXXDestructorName)
11670 << D.getSourceRange();
11671 D.setInvalidType();
11672 }
11673 }
11674
11675 namespace {
11676 /// Utility class to accumulate and print a diagnostic listing the invalid
11677 /// specifier(s) on a declaration.
11678 struct BadSpecifierDiagnoser {
11679 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
11680 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
11681 ~BadSpecifierDiagnoser() {
11682 Diagnostic << Specifiers;
11683 }
11684
11685 template<typename T> void check(SourceLocation SpecLoc, T Spec) {
11686 return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
11687 }
11688 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
11689 return check(SpecLoc,
11690 DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
11691 }
11692 void check(SourceLocation SpecLoc, const char *Spec) {
11693 if (SpecLoc.isInvalid()) return;
11694 Diagnostic << SourceRange(SpecLoc, SpecLoc);
11695 if (!Specifiers.empty()) Specifiers += " ";
11696 Specifiers += Spec;
11697 }
11698
11699 Sema &S;
11700 Sema::SemaDiagnosticBuilder Diagnostic;
11701 std::string Specifiers;
11702 };
11703 }
11704
11705 bool Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
11706 StorageClass &SC) {
11707 TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
11708 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
11709 assert(GuidedTemplateDecl && "missing template decl for deduction guide");
11710
11711 // C++ [temp.deduct.guide]p3:
11712 // A deduction-gide shall be declared in the same scope as the
11713 // corresponding class template.
11714 if (!CurContext->getRedeclContext()->Equals(
11715 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
11716 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
11717 << GuidedTemplateDecl;
11718 NoteTemplateLocation(*GuidedTemplateDecl);
11719 }
11720
11721 auto &DS = D.getMutableDeclSpec();
11722 // We leave 'friend' and 'virtual' to be rejected in the normal way.
11723 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
11724 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
11725 DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
11726 BadSpecifierDiagnoser Diagnoser(
11727 *this, D.getIdentifierLoc(),
11728 diag::err_deduction_guide_invalid_specifier);
11729
11730 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
11731 DS.ClearStorageClassSpecs();
11732 SC = SC_None;
11733
11734 // 'explicit' is permitted.
11735 Diagnoser.check(DS.getInlineSpecLoc(), "inline");
11736 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
11737 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
11738 DS.ClearConstexprSpec();
11739
11740 Diagnoser.check(DS.getConstSpecLoc(), "const");
11741 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
11742 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
11743 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
11744 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
11745 DS.ClearTypeQualifiers();
11746
11747 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
11748 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
11749 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
11750 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
11751 DS.ClearTypeSpecType();
11752 }
11753
11754 if (D.isInvalidType())
11755 return true;
11756
11757 // Check the declarator is simple enough.
11758 bool FoundFunction = false;
11759 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
11760 if (Chunk.Kind == DeclaratorChunk::Paren)
11761 continue;
11762 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
11763 Diag(D.getDeclSpec().getBeginLoc(),
11764 diag::err_deduction_guide_with_complex_decl)
11765 << D.getSourceRange();
11766 break;
11767 }
11768 if (!Chunk.Fun.hasTrailingReturnType())
11769 return Diag(D.getName().getBeginLoc(),
11770 diag::err_deduction_guide_no_trailing_return_type);
11771
11772 // Check that the return type is written as a specialization of
11773 // the template specified as the deduction-guide's name.
11774 // The template name may not be qualified. [temp.deduct.guide]
11775 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
11776 TypeSourceInfo *TSI = nullptr;
11777 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
11778 assert(TSI && "deduction guide has valid type but invalid return type?");
11779 bool AcceptableReturnType = false;
11780 bool MightInstantiateToSpecialization = false;
11781 if (auto RetTST =
11782 TSI->getTypeLoc().getAsAdjusted<TemplateSpecializationTypeLoc>()) {
11783 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
11784 bool TemplateMatches = Context.hasSameTemplateName(
11785 SpecifiedName, GuidedTemplate, /*IgnoreDeduced=*/true);
11786
11787 const QualifiedTemplateName *Qualifiers =
11788 SpecifiedName.getAsQualifiedTemplateName();
11789 assert(Qualifiers && "expected QualifiedTemplate");
11790 bool SimplyWritten =
11791 !Qualifiers->hasTemplateKeyword() && !Qualifiers->getQualifier();
11792 if (SimplyWritten && TemplateMatches)
11793 AcceptableReturnType = true;
11794 else {
11795 // This could still instantiate to the right type, unless we know it
11796 // names the wrong class template.
11797 auto *TD = SpecifiedName.getAsTemplateDecl();
11798 MightInstantiateToSpecialization =
11799 !(TD && isa<ClassTemplateDecl>(TD) && !TemplateMatches);
11800 }
11801 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
11802 MightInstantiateToSpecialization = true;
11803 }
11804
11805 if (!AcceptableReturnType)
11806 return Diag(TSI->getTypeLoc().getBeginLoc(),
11807 diag::err_deduction_guide_bad_trailing_return_type)
11808 << GuidedTemplate << TSI->getType()
11809 << MightInstantiateToSpecialization
11810 << TSI->getTypeLoc().getSourceRange();
11811
11812 // Keep going to check that we don't have any inner declarator pieces (we
11813 // could still have a function returning a pointer to a function).
11814 FoundFunction = true;
11815 }
11816
11817 if (D.isFunctionDefinition())
11818 // we can still create a valid deduction guide here.
11819 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
11820 return false;
11821 }
11822
11823 //===----------------------------------------------------------------------===//
11824 // Namespace Handling
11825 //===----------------------------------------------------------------------===//
11826
11827 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is
11828 /// reopened.
11829 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
11830 SourceLocation Loc,
11831 IdentifierInfo *II, bool *IsInline,
11832 NamespaceDecl *PrevNS) {
11833 assert(*IsInline != PrevNS->isInline());
11834
11835 // 'inline' must appear on the original definition, but not necessarily
11836 // on all extension definitions, so the note should point to the first
11837 // definition to avoid confusion.
11838 PrevNS = PrevNS->getFirstDecl();
11839
11840 if (PrevNS->isInline())
11841 // The user probably just forgot the 'inline', so suggest that it
11842 // be added back.
11843 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
11844 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
11845 else
11846 S.Diag(Loc, diag::err_inline_namespace_mismatch);
11847
11848 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
11849 *IsInline = PrevNS->isInline();
11850 }
11851
11852 /// ActOnStartNamespaceDef - This is called at the start of a namespace
11853 /// definition.
11854 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
11855 SourceLocation InlineLoc,
11856 SourceLocation NamespaceLoc,
11857 SourceLocation IdentLoc, IdentifierInfo *II,
11858 SourceLocation LBrace,
11859 const ParsedAttributesView &AttrList,
11860 UsingDirectiveDecl *&UD, bool IsNested) {
11861 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
11862 // For anonymous namespace, take the location of the left brace.
11863 SourceLocation Loc = II ? IdentLoc : LBrace;
11864 bool IsInline = InlineLoc.isValid();
11865 bool IsInvalid = false;
11866 bool IsStd = false;
11867 bool AddToKnown = false;
11868 Scope *DeclRegionScope = NamespcScope->getParent();
11869
11870 NamespaceDecl *PrevNS = nullptr;
11871 if (II) {
11872 // C++ [namespace.std]p7:
11873 // A translation unit shall not declare namespace std to be an inline
11874 // namespace (9.8.2).
11875 //
11876 // Precondition: the std namespace is in the file scope and is declared to
11877 // be inline
11878 auto DiagnoseInlineStdNS = [&]() {
11879 assert(IsInline && II->isStr("std") &&
11880 CurContext->getRedeclContext()->isTranslationUnit() &&
11881 "Precondition of DiagnoseInlineStdNS not met");
11882 Diag(InlineLoc, diag::err_inline_namespace_std)
11883 << SourceRange(InlineLoc, InlineLoc.getLocWithOffset(6));
11884 IsInline = false;
11885 };
11886 // C++ [namespace.def]p2:
11887 // The identifier in an original-namespace-definition shall not
11888 // have been previously defined in the declarative region in
11889 // which the original-namespace-definition appears. The
11890 // identifier in an original-namespace-definition is the name of
11891 // the namespace. Subsequently in that declarative region, it is
11892 // treated as an original-namespace-name.
11893 //
11894 // Since namespace names are unique in their scope, and we don't
11895 // look through using directives, just look for any ordinary names
11896 // as if by qualified name lookup.
11897 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
11898 RedeclarationKind::ForExternalRedeclaration);
11899 LookupQualifiedName(R, CurContext->getRedeclContext());
11900 NamedDecl *PrevDecl =
11901 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
11902 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
11903
11904 if (PrevNS) {
11905 // This is an extended namespace definition.
11906 if (IsInline && II->isStr("std") &&
11907 CurContext->getRedeclContext()->isTranslationUnit())
11908 DiagnoseInlineStdNS();
11909 else if (IsInline != PrevNS->isInline())
11910 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
11911 &IsInline, PrevNS);
11912 } else if (PrevDecl) {
11913 // This is an invalid name redefinition.
11914 Diag(Loc, diag::err_redefinition_different_kind)
11915 << II;
11916 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
11917 IsInvalid = true;
11918 // Continue on to push Namespc as current DeclContext and return it.
11919 } else if (II->isStr("std") &&
11920 CurContext->getRedeclContext()->isTranslationUnit()) {
11921 if (IsInline)
11922 DiagnoseInlineStdNS();
11923 // This is the first "real" definition of the namespace "std", so update
11924 // our cache of the "std" namespace to point at this definition.
11925 PrevNS = getStdNamespace();
11926 IsStd = true;
11927 AddToKnown = !IsInline;
11928 } else {
11929 // We've seen this namespace for the first time.
11930 AddToKnown = !IsInline;
11931 }
11932 } else {
11933 // Anonymous namespaces.
11934
11935 // Determine whether the parent already has an anonymous namespace.
11936 DeclContext *Parent = CurContext->getRedeclContext();
11937 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
11938 PrevNS = TU->getAnonymousNamespace();
11939 } else {
11940 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
11941 PrevNS = ND->getAnonymousNamespace();
11942 }
11943
11944 if (PrevNS && IsInline != PrevNS->isInline())
11945 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
11946 &IsInline, PrevNS);
11947 }
11948
11949 NamespaceDecl *Namespc = NamespaceDecl::Create(
11950 Context, CurContext, IsInline, StartLoc, Loc, II, PrevNS, IsNested);
11951 if (IsInvalid)
11952 Namespc->setInvalidDecl();
11953
11954 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
11955 AddPragmaAttributes(DeclRegionScope, Namespc);
11956 ProcessAPINotes(Namespc);
11957
11958 // FIXME: Should we be merging attributes?
11959 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
11960 PushNamespaceVisibilityAttr(Attr, Loc);
11961
11962 if (IsStd)
11963 StdNamespace = Namespc;
11964 if (AddToKnown)
11965 KnownNamespaces[Namespc] = false;
11966
11967 if (II) {
11968 PushOnScopeChains(Namespc, DeclRegionScope);
11969 } else {
11970 // Link the anonymous namespace into its parent.
11971 DeclContext *Parent = CurContext->getRedeclContext();
11972 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
11973 TU->setAnonymousNamespace(Namespc);
11974 } else {
11975 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
11976 }
11977
11978 CurContext->addDecl(Namespc);
11979
11980 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
11981 // behaves as if it were replaced by
11982 // namespace unique { /* empty body */ }
11983 // using namespace unique;
11984 // namespace unique { namespace-body }
11985 // where all occurrences of 'unique' in a translation unit are
11986 // replaced by the same identifier and this identifier differs
11987 // from all other identifiers in the entire program.
11988
11989 // We just create the namespace with an empty name and then add an
11990 // implicit using declaration, just like the standard suggests.
11991 //
11992 // CodeGen enforces the "universally unique" aspect by giving all
11993 // declarations semantically contained within an anonymous
11994 // namespace internal linkage.
11995
11996 if (!PrevNS) {
11997 UD = UsingDirectiveDecl::Create(Context, Parent,
11998 /* 'using' */ LBrace,
11999 /* 'namespace' */ SourceLocation(),
12000 /* qualifier */ NestedNameSpecifierLoc(),
12001 /* identifier */ SourceLocation(),
12002 Namespc,
12003 /* Ancestor */ Parent);
12004 UD->setImplicit();
12005 Parent->addDecl(UD);
12006 }
12007 }
12008
12009 ActOnDocumentableDecl(Namespc);
12010
12011 // Although we could have an invalid decl (i.e. the namespace name is a
12012 // redefinition), push it as current DeclContext and try to continue parsing.
12013 // FIXME: We should be able to push Namespc here, so that the each DeclContext
12014 // for the namespace has the declarations that showed up in that particular
12015 // namespace definition.
12016 PushDeclContext(NamespcScope, Namespc);
12017 return Namespc;
12018 }
12019
12020 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
12021 /// is a namespace alias, returns the namespace it points to.
12022 static inline NamespaceDecl *getNamespaceDecl(NamespaceBaseDecl *D) {
12023 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
12024 return AD->getNamespace();
12025 return dyn_cast_or_null<NamespaceDecl>(D);
12026 }
12027
12028 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
12029 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
12030 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
12031 Namespc->setRBraceLoc(RBrace);
12032 PopDeclContext();
12033 if (Namespc->hasAttr<VisibilityAttr>())
12034 PopPragmaVisibility(true, RBrace);
12035 // If this namespace contains an export-declaration, export it now.
12036 if (DeferredExportedNamespaces.erase(Namespc))
12037 Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
12038 }
12039
12040 CXXRecordDecl *Sema::getStdBadAlloc() const {
12041 return cast_or_null<CXXRecordDecl>(
12042 StdBadAlloc.get(Context.getExternalSource()));
12043 }
12044
12045 EnumDecl *Sema::getStdAlignValT() const {
12046 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
12047 }
12048
12049 NamespaceDecl *Sema::getStdNamespace() const {
12050 return cast_or_null<NamespaceDecl>(
12051 StdNamespace.get(Context.getExternalSource()));
12052 }
12053
12054 namespace {
12055
12056 enum UnsupportedSTLSelect {
12057 USS_InvalidMember,
12058 USS_MissingMember,
12059 USS_NonTrivial,
12060 USS_Other
12061 };
12062
12063 struct InvalidSTLDiagnoser {
12064 Sema &S;
12065 SourceLocation Loc;
12066 QualType TyForDiags;
12067
12068 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
12069 const VarDecl *VD = nullptr) {
12070 {
12071 auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
12072 << TyForDiags << ((int)Sel);
12073 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
12074 assert(!Name.empty());
12075 D << Name;
12076 }
12077 }
12078 if (Sel == USS_InvalidMember) {
12079 S.Diag(VD->getLocation(), diag::note_var_declared_here)
12080 << VD << VD->getSourceRange();
12081 }
12082 return QualType();
12083 }
12084 };
12085 } // namespace
12086
12087 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
12088 SourceLocation Loc,
12089 ComparisonCategoryUsage Usage) {
12090 assert(getLangOpts().CPlusPlus &&
12091 "Looking for comparison category type outside of C++.");
12092
12093 // Use an elaborated type for diagnostics which has a name containing the
12094 // prepended 'std' namespace but not any inline namespace names.
12095 auto TyForDiags = [&](ComparisonCategoryInfo *Info) {
12096 NestedNameSpecifier Qualifier(Context, getStdNamespace(),
12097 /*Prefix=*/std::nullopt);
12098 return Context.getTagType(ElaboratedTypeKeyword::None, Qualifier,
12099 Info->Record,
12100 /*OwnsTag=*/false);
12101 };
12102
12103 // Check if we've already successfully checked the comparison category type
12104 // before. If so, skip checking it again.
12105 ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
12106 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) {
12107 // The only thing we need to check is that the type has a reachable
12108 // definition in the current context.
12109 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
12110 return QualType();
12111
12112 return Info->getType();
12113 }
12114
12115 // If lookup failed
12116 if (!Info) {
12117 std::string NameForDiags = "std::";
12118 NameForDiags += ComparisonCategories::getCategoryString(Kind);
12119 Diag(Loc, diag::err_implied_comparison_category_type_not_found)
12120 << NameForDiags << (int)Usage;
12121 return QualType();
12122 }
12123
12124 assert(Info->Kind == Kind);
12125 assert(Info->Record);
12126
12127 // Update the Record decl in case we encountered a forward declaration on our
12128 // first pass. FIXME: This is a bit of a hack.
12129 if (Info->Record->hasDefinition())
12130 Info->Record = Info->Record->getDefinition();
12131
12132 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
12133 return QualType();
12134
12135 InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)};
12136
12137 if (!Info->Record->isTriviallyCopyable())
12138 return UnsupportedSTLError(USS_NonTrivial);
12139
12140 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
12141 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
12142 // Tolerate empty base classes.
12143 if (Base->isEmpty())
12144 continue;
12145 // Reject STL implementations which have at least one non-empty base.
12146 return UnsupportedSTLError();
12147 }
12148
12149 // Check that the STL has implemented the types using a single integer field.
12150 // This expectation allows better codegen for builtin operators. We require:
12151 // (1) The class has exactly one field.
12152 // (2) The field is an integral or enumeration type.
12153 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
12154 if (std::distance(FIt, FEnd) != 1 ||
12155 !FIt->getType()->isIntegralOrEnumerationType()) {
12156 return UnsupportedSTLError();
12157 }
12158
12159 // Build each of the require values and store them in Info.
12160 for (ComparisonCategoryResult CCR :
12161 ComparisonCategories::getPossibleResultsForType(Kind)) {
12162 StringRef MemName = ComparisonCategories::getResultString(CCR);
12163 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
12164
12165 if (!ValInfo)
12166 return UnsupportedSTLError(USS_MissingMember, MemName);
12167
12168 VarDecl *VD = ValInfo->VD;
12169 assert(VD && "should not be null!");
12170
12171 // Attempt to diagnose reasons why the STL definition of this type
12172 // might be foobar, including it failing to be a constant expression.
12173 // TODO Handle more ways the lookup or result can be invalid.
12174 if (!VD->isStaticDataMember() ||
12175 !VD->isUsableInConstantExpressions(Context))
12176 return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
12177
12178 // Attempt to evaluate the var decl as a constant expression and extract
12179 // the value of its first field as a ICE. If this fails, the STL
12180 // implementation is not supported.
12181 if (!ValInfo->hasValidIntValue())
12182 return UnsupportedSTLError();
12183
12184 MarkVariableReferenced(Loc, VD);
12185 }
12186
12187 // We've successfully built the required types and expressions. Update
12188 // the cache and return the newly cached value.
12189 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
12190 return Info->getType();
12191 }
12192
12193 NamespaceDecl *Sema::getOrCreateStdNamespace() {
12194 if (!StdNamespace) {
12195 // The "std" namespace has not yet been defined, so build one implicitly.
12196 StdNamespace = NamespaceDecl::Create(
12197 Context, Context.getTranslationUnitDecl(),
12198 /*Inline=*/false, SourceLocation(), SourceLocation(),
12199 &PP.getIdentifierTable().get("std"),
12200 /*PrevDecl=*/nullptr, /*Nested=*/false);
12201 getStdNamespace()->setImplicit(true);
12202 // We want the created NamespaceDecl to be available for redeclaration
12203 // lookups, but not for regular name lookups.
12204 Context.getTranslationUnitDecl()->addDecl(getStdNamespace());
12205 getStdNamespace()->clearIdentifierNamespace();
12206 }
12207
12208 return getStdNamespace();
12209 }
12210
12211 static bool isStdClassTemplate(Sema &S, QualType SugaredType, QualType *TypeArg,
12212 const char *ClassName,
12213 ClassTemplateDecl **CachedDecl,
12214 const Decl **MalformedDecl) {
12215 // We're looking for implicit instantiations of
12216 // template <typename U> class std::{ClassName}.
12217
12218 if (!S.StdNamespace) // If we haven't seen namespace std yet, this can't be
12219 // it.
12220 return false;
12221
12222 auto ReportMatchingNameAsMalformed = [&](NamedDecl *D) {
12223 if (!MalformedDecl)
12224 return;
12225 if (!D)
12226 D = SugaredType->getAsTagDecl();
12227 if (!D || !D->isInStdNamespace())
12228 return;
12229 IdentifierInfo *II = D->getDeclName().getAsIdentifierInfo();
12230 if (II && II == &S.PP.getIdentifierTable().get(ClassName))
12231 *MalformedDecl = D;
12232 };
12233
12234 ClassTemplateDecl *Template = nullptr;
12235 ArrayRef<TemplateArgument> Arguments;
12236 if (const TemplateSpecializationType *TST =
12237 SugaredType->getAsNonAliasTemplateSpecializationType()) {
12238 Template = dyn_cast_or_null<ClassTemplateDecl>(
12239 TST->getTemplateName().getAsTemplateDecl());
12240 Arguments = TST->template_arguments();
12241 } else if (const auto *TT = SugaredType->getAs<TagType>()) {
12242 Template = TT->getTemplateDecl();
12243 Arguments = TT->getTemplateArgs(S.Context);
12244 }
12245
12246 if (!Template) {
12247 ReportMatchingNameAsMalformed(SugaredType->getAsTagDecl());
12248 return false;
12249 }
12250
12251 if (!*CachedDecl) {
12252 // Haven't recognized std::{ClassName} yet, maybe this is it.
12253 // FIXME: It seems we should just reuse LookupStdClassTemplate but the
12254 // semantics of this are slightly different, most notably the existing
12255 // "lookup" semantics explicitly diagnose an invalid definition as an
12256 // error.
12257 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
12258 if (TemplateClass->getIdentifier() !=
12259 &S.PP.getIdentifierTable().get(ClassName) ||
12260 !S.getStdNamespace()->InEnclosingNamespaceSetOf(
12261 TemplateClass->getNonTransparentDeclContext()))
12262 return false;
12263 // This is a template called std::{ClassName}, but is it the right
12264 // template?
12265 TemplateParameterList *Params = Template->getTemplateParameters();
12266 if (Params->getMinRequiredArguments() != 1 ||
12267 !isa<TemplateTypeParmDecl>(Params->getParam(0)) ||
12268 Params->getParam(0)->isTemplateParameterPack()) {
12269 if (MalformedDecl)
12270 *MalformedDecl = TemplateClass;
12271 return false;
12272 }
12273
12274 // It's the right template.
12275 *CachedDecl = Template;
12276 }
12277
12278 if (Template->getCanonicalDecl() != (*CachedDecl)->getCanonicalDecl())
12279 return false;
12280
12281 // This is an instance of std::{ClassName}. Find the argument type.
12282 if (TypeArg) {
12283 QualType ArgType = Arguments[0].getAsType();
12284 // FIXME: Since TST only has as-written arguments, we have to perform the
12285 // only kind of conversion applicable to type arguments; in Objective-C ARC:
12286 // - If an explicitly-specified template argument type is a lifetime type
12287 // with no lifetime qualifier, the __strong lifetime qualifier is
12288 // inferred.
12289 if (S.getLangOpts().ObjCAutoRefCount && ArgType->isObjCLifetimeType() &&
12290 !ArgType.getObjCLifetime()) {
12291 Qualifiers Qs;
12292 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
12293 ArgType = S.Context.getQualifiedType(ArgType, Qs);
12294 }
12295 *TypeArg = ArgType;
12296 }
12297
12298 return true;
12299 }
12300
12301 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
12302 assert(getLangOpts().CPlusPlus &&
12303 "Looking for std::initializer_list outside of C++.");
12304
12305 // We're looking for implicit instantiations of
12306 // template <typename E> class std::initializer_list.
12307
12308 return isStdClassTemplate(*this, Ty, Element, "initializer_list",
12309 &StdInitializerList, /*MalformedDecl=*/nullptr);
12310 }
12311
12312 bool Sema::isStdTypeIdentity(QualType Ty, QualType *Element,
12313 const Decl **MalformedDecl) {
12314 assert(getLangOpts().CPlusPlus &&
12315 "Looking for std::type_identity outside of C++.");
12316
12317 // We're looking for implicit instantiations of
12318 // template <typename T> struct std::type_identity.
12319
12320 return isStdClassTemplate(*this, Ty, Element, "type_identity",
12321 &StdTypeIdentity, MalformedDecl);
12322 }
12323
12324 static ClassTemplateDecl *LookupStdClassTemplate(Sema &S, SourceLocation Loc,
12325 const char *ClassName,
12326 bool *WasMalformed) {
12327 if (!S.StdNamespace)
12328 return nullptr;
12329
12330 LookupResult Result(S, &S.PP.getIdentifierTable().get(ClassName), Loc,
12331 Sema::LookupOrdinaryName);
12332 if (!S.LookupQualifiedName(Result, S.getStdNamespace()))
12333 return nullptr;
12334
12335 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
12336 if (!Template) {
12337 Result.suppressDiagnostics();
12338 // We found something weird. Complain about the first thing we found.
12339 NamedDecl *Found = *Result.begin();
12340 S.Diag(Found->getLocation(), diag::err_malformed_std_class_template)
12341 << ClassName;
12342 if (WasMalformed)
12343 *WasMalformed = true;
12344 return nullptr;
12345 }
12346
12347 // We found some template with the correct name. Now verify that it's
12348 // correct.
12349 TemplateParameterList *Params = Template->getTemplateParameters();
12350 if (Params->getMinRequiredArguments() != 1 ||
12351 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
12352 S.Diag(Template->getLocation(), diag::err_malformed_std_class_template)
12353 << ClassName;
12354 if (WasMalformed)
12355 *WasMalformed = true;
12356 return nullptr;
12357 }
12358
12359 return Template;
12360 }
12361
12362 static QualType BuildStdClassTemplate(Sema &S, ClassTemplateDecl *CTD,
12363 QualType TypeParam, SourceLocation Loc) {
12364 assert(S.getStdNamespace());
12365 TemplateArgumentListInfo Args(Loc, Loc);
12366 auto TSI = S.Context.getTrivialTypeSourceInfo(TypeParam, Loc);
12367 Args.addArgument(TemplateArgumentLoc(TemplateArgument(TypeParam), TSI));
12368
12369 return S.CheckTemplateIdType(ElaboratedTypeKeyword::None, TemplateName(CTD),
12370 Loc, Args, /*Scope=*/nullptr,
12371 /*ForNestedNameSpecifier=*/false);
12372 }
12373
12374 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
12375 if (!StdInitializerList) {
12376 bool WasMalformed = false;
12377 StdInitializerList =
12378 LookupStdClassTemplate(*this, Loc, "initializer_list", &WasMalformed);
12379 if (!StdInitializerList) {
12380 if (!WasMalformed)
12381 Diag(Loc, diag::err_implied_std_initializer_list_not_found);
12382 return QualType();
12383 }
12384 }
12385 return BuildStdClassTemplate(*this, StdInitializerList, Element, Loc);
12386 }
12387
12388 QualType Sema::tryBuildStdTypeIdentity(QualType Type, SourceLocation Loc) {
12389 if (!StdTypeIdentity) {
12390 StdTypeIdentity = LookupStdClassTemplate(*this, Loc, "type_identity",
12391 /*WasMalformed=*/nullptr);
12392 if (!StdTypeIdentity)
12393 return QualType();
12394 }
12395 return BuildStdClassTemplate(*this, StdTypeIdentity, Type, Loc);
12396 }
12397
12398 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
12399 // C++ [dcl.init.list]p2:
12400 // A constructor is an initializer-list constructor if its first parameter
12401 // is of type std::initializer_list<E> or reference to possibly cv-qualified
12402 // std::initializer_list<E> for some type E, and either there are no other
12403 // parameters or else all other parameters have default arguments.
12404 if (!Ctor->hasOneParamOrDefaultArgs())
12405 return false;
12406
12407 QualType ArgType = Ctor->getParamDecl(0)->getType();
12408 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
12409 ArgType = RT->getPointeeType().getUnqualifiedType();
12410
12411 return isStdInitializerList(ArgType, nullptr);
12412 }
12413
12414 /// Determine whether a using statement is in a context where it will be
12415 /// apply in all contexts.
12416 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
12417 switch (CurContext->getDeclKind()) {
12418 case Decl::TranslationUnit:
12419 return true;
12420 case Decl::LinkageSpec:
12421 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
12422 default:
12423 return false;
12424 }
12425 }
12426
12427 namespace {
12428
12429 // Callback to only accept typo corrections that are namespaces.
12430 class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
12431 public:
12432 bool ValidateCandidate(const TypoCorrection &candidate) override {
12433 if (NamedDecl *ND = candidate.getCorrectionDecl())
12434 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
12435 return false;
12436 }
12437
12438 std::unique_ptr<CorrectionCandidateCallback> clone() override {
12439 return std::make_unique<NamespaceValidatorCCC>(*this);
12440 }
12441 };
12442
12443 }
12444
12445 static void DiagnoseInvisibleNamespace(const TypoCorrection &Corrected,
12446 Sema &S) {
12447 auto *ND = cast<NamespaceDecl>(Corrected.getFoundDecl());
12448 Module *M = ND->getOwningModule();
12449 assert(M && "hidden namespace definition not in a module?");
12450
12451 if (M->isExplicitGlobalModule())
12452 S.Diag(Corrected.getCorrectionRange().getBegin(),
12453 diag::err_module_unimported_use_header)
12454 << (int)Sema::MissingImportKind::Declaration << Corrected.getFoundDecl()
12455 << /*Header Name*/ false;
12456 else
12457 S.Diag(Corrected.getCorrectionRange().getBegin(),
12458 diag::err_module_unimported_use)
12459 << (int)Sema::MissingImportKind::Declaration << Corrected.getFoundDecl()
12460 << M->getTopLevelModuleName();
12461 }
12462
12463 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
12464 CXXScopeSpec &SS,
12465 SourceLocation IdentLoc,
12466 IdentifierInfo *Ident) {
12467 R.clear();
12468 NamespaceValidatorCCC CCC{};
12469 if (TypoCorrection Corrected =
12470 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
12471 CorrectTypoKind::ErrorRecovery)) {
12472 // Generally we find it is confusing more than helpful to diagnose the
12473 // invisible namespace.
12474 // See https://github.com/llvm/llvm-project/issues/73893.
12475 //
12476 // However, we should diagnose when the users are trying to using an
12477 // invisible namespace. So we handle the case specially here.
12478 if (isa_and_nonnull<NamespaceDecl>(Corrected.getFoundDecl()) &&
12479 Corrected.requiresImport()) {
12480 DiagnoseInvisibleNamespace(Corrected, S);
12481 } else if (DeclContext *DC = S.computeDeclContext(SS, false)) {
12482 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
12483 bool DroppedSpecifier =
12484 Corrected.WillReplaceSpecifier() && Ident->getName() == CorrectedStr;
12485 S.diagnoseTypo(Corrected,
12486 S.PDiag(diag::err_using_directive_member_suggest)
12487 << Ident << DC << DroppedSpecifier << SS.getRange(),
12488 S.PDiag(diag::note_namespace_defined_here));
12489 } else {
12490 S.diagnoseTypo(Corrected,
12491 S.PDiag(diag::err_using_directive_suggest) << Ident,
12492 S.PDiag(diag::note_namespace_defined_here));
12493 }
12494 R.addDecl(Corrected.getFoundDecl());
12495 return true;
12496 }
12497 return false;
12498 }
12499
12500 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
12501 SourceLocation NamespcLoc, CXXScopeSpec &SS,
12502 SourceLocation IdentLoc,
12503 IdentifierInfo *NamespcName,
12504 const ParsedAttributesView &AttrList) {
12505 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
12506 assert(NamespcName && "Invalid NamespcName.");
12507 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
12508
12509 // Get the innermost enclosing declaration scope.
12510 S = S->getDeclParent();
12511
12512 UsingDirectiveDecl *UDir = nullptr;
12513 NestedNameSpecifier Qualifier = SS.getScopeRep();
12514
12515 // Lookup namespace name.
12516 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
12517 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
12518 if (R.isAmbiguous())
12519 return nullptr;
12520
12521 if (R.empty()) {
12522 R.clear();
12523 // Allow "using namespace std;" or "using namespace ::std;" even if
12524 // "std" hasn't been defined yet, for GCC compatibility.
12525 if ((!Qualifier ||
12526 Qualifier.getKind() == NestedNameSpecifier::Kind::Global) &&
12527 NamespcName->isStr("std")) {
12528 Diag(IdentLoc, diag::ext_using_undefined_std);
12529 R.addDecl(getOrCreateStdNamespace());
12530 R.resolveKind();
12531 }
12532 // Otherwise, attempt typo correction.
12533 else
12534 TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
12535 }
12536
12537 if (!R.empty()) {
12538 NamedDecl *Named = R.getRepresentativeDecl();
12539 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
12540 assert(NS && "expected namespace decl");
12541
12542 // The use of a nested name specifier may trigger deprecation warnings.
12543 DiagnoseUseOfDecl(Named, IdentLoc);
12544
12545 // C++ [namespace.udir]p1:
12546 // A using-directive specifies that the names in the nominated
12547 // namespace can be used in the scope in which the
12548 // using-directive appears after the using-directive. During
12549 // unqualified name lookup (3.4.1), the names appear as if they
12550 // were declared in the nearest enclosing namespace which
12551 // contains both the using-directive and the nominated
12552 // namespace. [Note: in this context, "contains" means "contains
12553 // directly or indirectly". ]
12554
12555 // Find enclosing context containing both using-directive and
12556 // nominated namespace.
12557 DeclContext *CommonAncestor = NS;
12558 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
12559 CommonAncestor = CommonAncestor->getParent();
12560
12561 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
12562 SS.getWithLocInContext(Context),
12563 IdentLoc, Named, CommonAncestor);
12564
12565 if (IsUsingDirectiveInToplevelContext(CurContext) &&
12566 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
12567 Diag(IdentLoc, diag::warn_using_directive_in_header);
12568 }
12569
12570 PushUsingDirective(S, UDir);
12571 } else {
12572 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
12573 }
12574
12575 if (UDir) {
12576 ProcessDeclAttributeList(S, UDir, AttrList);
12577 ProcessAPINotes(UDir);
12578 }
12579
12580 return UDir;
12581 }
12582
12583 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
12584 // If the scope has an associated entity and the using directive is at
12585 // namespace or translation unit scope, add the UsingDirectiveDecl into
12586 // its lookup structure so qualified name lookup can find it.
12587 DeclContext *Ctx = S->getEntity();
12588 if (Ctx && !Ctx->isFunctionOrMethod())
12589 Ctx->addDecl(UDir);
12590 else
12591 // Otherwise, it is at block scope. The using-directives will affect lookup
12592 // only to the end of the scope.
12593 S->PushUsingDirective(UDir);
12594 }
12595
12596 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
12597 SourceLocation UsingLoc,
12598 SourceLocation TypenameLoc, CXXScopeSpec &SS,
12599 UnqualifiedId &Name,
12600 SourceLocation EllipsisLoc,
12601 const ParsedAttributesView &AttrList) {
12602 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
12603
12604 if (SS.isEmpty()) {
12605 Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
12606 return nullptr;
12607 }
12608
12609 switch (Name.getKind()) {
12610 case UnqualifiedIdKind::IK_ImplicitSelfParam:
12611 case UnqualifiedIdKind::IK_Identifier:
12612 case UnqualifiedIdKind::IK_OperatorFunctionId:
12613 case UnqualifiedIdKind::IK_LiteralOperatorId:
12614 case UnqualifiedIdKind::IK_ConversionFunctionId:
12615 break;
12616
12617 case UnqualifiedIdKind::IK_ConstructorName:
12618 case UnqualifiedIdKind::IK_ConstructorTemplateId:
12619 // C++11 inheriting constructors.
12620 Diag(Name.getBeginLoc(),
12621 getLangOpts().CPlusPlus11
12622 ? diag::warn_cxx98_compat_using_decl_constructor
12623 : diag::err_using_decl_constructor)
12624 << SS.getRange();
12625
12626 if (getLangOpts().CPlusPlus11) break;
12627
12628 return nullptr;
12629
12630 case UnqualifiedIdKind::IK_DestructorName:
12631 Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
12632 return nullptr;
12633
12634 case UnqualifiedIdKind::IK_TemplateId:
12635 Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
12636 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
12637 return nullptr;
12638
12639 case UnqualifiedIdKind::IK_DeductionGuideName:
12640 llvm_unreachable("cannot parse qualified deduction guide name");
12641 }
12642
12643 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
12644 DeclarationName TargetName = TargetNameInfo.getName();
12645 if (!TargetName)
12646 return nullptr;
12647
12648 // Warn about access declarations.
12649 if (UsingLoc.isInvalid()) {
12650 Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
12651 ? diag::err_access_decl
12652 : diag::warn_access_decl_deprecated)
12653 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
12654 }
12655
12656 if (EllipsisLoc.isInvalid()) {
12657 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
12658 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
12659 return nullptr;
12660 } else {
12661 if (!SS.getScopeRep().containsUnexpandedParameterPack() &&
12662 !TargetNameInfo.containsUnexpandedParameterPack()) {
12663 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
12664 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
12665 EllipsisLoc = SourceLocation();
12666 }
12667 }
12668
12669 NamedDecl *UD =
12670 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
12671 SS, TargetNameInfo, EllipsisLoc, AttrList,
12672 /*IsInstantiation*/ false,
12673 AttrList.hasAttribute(ParsedAttr::AT_UsingIfExists));
12674 if (UD)
12675 PushOnScopeChains(UD, S, /*AddToContext*/ false);
12676
12677 return UD;
12678 }
12679
12680 Decl *Sema::ActOnUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
12681 SourceLocation UsingLoc,
12682 SourceLocation EnumLoc, SourceRange TyLoc,
12683 const IdentifierInfo &II, ParsedType Ty,
12684 const CXXScopeSpec &SS) {
12685 TypeSourceInfo *TSI = nullptr;
12686 SourceLocation IdentLoc = TyLoc.getBegin();
12687 QualType EnumTy = GetTypeFromParser(Ty, &TSI);
12688 if (EnumTy.isNull()) {
12689 Diag(IdentLoc, isDependentScopeSpecifier(SS)
12690 ? diag::err_using_enum_is_dependent
12691 : diag::err_unknown_typename)
12692 << II.getName()
12693 << SourceRange(SS.isValid() ? SS.getBeginLoc() : IdentLoc,
12694 TyLoc.getEnd());
12695 return nullptr;
12696 }
12697
12698 if (EnumTy->isDependentType()) {
12699 Diag(IdentLoc, diag::err_using_enum_is_dependent);
12700 return nullptr;
12701 }
12702
12703 auto *Enum = EnumTy->getAsEnumDecl();
12704 if (!Enum) {
12705 Diag(IdentLoc, diag::err_using_enum_not_enum) << EnumTy;
12706 return nullptr;
12707 }
12708
12709 if (TSI == nullptr)
12710 TSI = Context.getTrivialTypeSourceInfo(EnumTy, IdentLoc);
12711
12712 auto *UD =
12713 BuildUsingEnumDeclaration(S, AS, UsingLoc, EnumLoc, IdentLoc, TSI, Enum);
12714
12715 if (UD)
12716 PushOnScopeChains(UD, S, /*AddToContext*/ false);
12717
12718 return UD;
12719 }
12720
12721 /// Determine whether a using declaration considers the given
12722 /// declarations as "equivalent", e.g., if they are redeclarations of
12723 /// the same entity or are both typedefs of the same type.
12724 static bool
12725 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
12726 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
12727 return true;
12728
12729 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
12730 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
12731 return Context.hasSameType(TD1->getUnderlyingType(),
12732 TD2->getUnderlyingType());
12733
12734 // Two using_if_exists using-declarations are equivalent if both are
12735 // unresolved.
12736 if (isa<UnresolvedUsingIfExistsDecl>(D1) &&
12737 isa<UnresolvedUsingIfExistsDecl>(D2))
12738 return true;
12739
12740 return false;
12741 }
12742
12743 bool Sema::CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Orig,
12744 const LookupResult &Previous,
12745 UsingShadowDecl *&PrevShadow) {
12746 // Diagnose finding a decl which is not from a base class of the
12747 // current class. We do this now because there are cases where this
12748 // function will silently decide not to build a shadow decl, which
12749 // will pre-empt further diagnostics.
12750 //
12751 // We don't need to do this in C++11 because we do the check once on
12752 // the qualifier.
12753 //
12754 // FIXME: diagnose the following if we care enough:
12755 // struct A { int foo; };
12756 // struct B : A { using A::foo; };
12757 // template <class T> struct C : A {};
12758 // template <class T> struct D : C<T> { using B::foo; } // <---
12759 // This is invalid (during instantiation) in C++03 because B::foo
12760 // resolves to the using decl in B, which is not a base class of D<T>.
12761 // We can't diagnose it immediately because C<T> is an unknown
12762 // specialization. The UsingShadowDecl in D<T> then points directly
12763 // to A::foo, which will look well-formed when we instantiate.
12764 // The right solution is to not collapse the shadow-decl chain.
12765 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord())
12766 if (auto *Using = dyn_cast<UsingDecl>(BUD)) {
12767 DeclContext *OrigDC = Orig->getDeclContext();
12768
12769 // Handle enums and anonymous structs.
12770 if (isa<EnumDecl>(OrigDC))
12771 OrigDC = OrigDC->getParent();
12772 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
12773 while (OrigRec->isAnonymousStructOrUnion())
12774 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
12775
12776 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
12777 if (OrigDC == CurContext) {
12778 Diag(Using->getLocation(),
12779 diag::err_using_decl_nested_name_specifier_is_current_class)
12780 << Using->getQualifierLoc().getSourceRange();
12781 Diag(Orig->getLocation(), diag::note_using_decl_target);
12782 Using->setInvalidDecl();
12783 return true;
12784 }
12785
12786 Diag(Using->getQualifierLoc().getBeginLoc(),
12787 diag::err_using_decl_nested_name_specifier_is_not_base_class)
12788 << Using->getQualifier() << cast<CXXRecordDecl>(CurContext)
12789 << Using->getQualifierLoc().getSourceRange();
12790 Diag(Orig->getLocation(), diag::note_using_decl_target);
12791 Using->setInvalidDecl();
12792 return true;
12793 }
12794 }
12795
12796 if (Previous.empty()) return false;
12797
12798 NamedDecl *Target = Orig;
12799 if (isa<UsingShadowDecl>(Target))
12800 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
12801
12802 // If the target happens to be one of the previous declarations, we
12803 // don't have a conflict.
12804 //
12805 // FIXME: but we might be increasing its access, in which case we
12806 // should redeclare it.
12807 NamedDecl *NonTag = nullptr, *Tag = nullptr;
12808 bool FoundEquivalentDecl = false;
12809 for (NamedDecl *Element : Previous) {
12810 NamedDecl *D = Element->getUnderlyingDecl();
12811 // We can have UsingDecls in our Previous results because we use the same
12812 // LookupResult for checking whether the UsingDecl itself is a valid
12813 // redeclaration.
12814 if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D) || isa<UsingEnumDecl>(D))
12815 continue;
12816
12817 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
12818 // C++ [class.mem]p19:
12819 // If T is the name of a class, then [every named member other than
12820 // a non-static data member] shall have a name different from T
12821 if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
12822 !isa<IndirectFieldDecl>(Target) &&
12823 !isa<UnresolvedUsingValueDecl>(Target) &&
12824 DiagnoseClassNameShadow(
12825 CurContext,
12826 DeclarationNameInfo(BUD->getDeclName(), BUD->getLocation())))
12827 return true;
12828 }
12829
12830 if (IsEquivalentForUsingDecl(Context, D, Target)) {
12831 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Element))
12832 PrevShadow = Shadow;
12833 FoundEquivalentDecl = true;
12834 } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
12835 // We don't conflict with an existing using shadow decl of an equivalent
12836 // declaration, but we're not a redeclaration of it.
12837 FoundEquivalentDecl = true;
12838 }
12839
12840 if (isVisible(D))
12841 (isa<TagDecl>(D) ? Tag : NonTag) = D;
12842 }
12843
12844 if (FoundEquivalentDecl)
12845 return false;
12846
12847 // Always emit a diagnostic for a mismatch between an unresolved
12848 // using_if_exists and a resolved using declaration in either direction.
12849 if (isa<UnresolvedUsingIfExistsDecl>(Target) !=
12850 (isa_and_nonnull<UnresolvedUsingIfExistsDecl>(NonTag))) {
12851 if (!NonTag && !Tag)
12852 return false;
12853 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12854 Diag(Target->getLocation(), diag::note_using_decl_target);
12855 Diag((NonTag ? NonTag : Tag)->getLocation(),
12856 diag::note_using_decl_conflict);
12857 BUD->setInvalidDecl();
12858 return true;
12859 }
12860
12861 if (FunctionDecl *FD = Target->getAsFunction()) {
12862 NamedDecl *OldDecl = nullptr;
12863 switch (CheckOverload(nullptr, FD, Previous, OldDecl,
12864 /*IsForUsingDecl*/ true)) {
12865 case OverloadKind::Overload:
12866 return false;
12867
12868 case OverloadKind::NonFunction:
12869 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12870 break;
12871
12872 // We found a decl with the exact signature.
12873 case OverloadKind::Match:
12874 // If we're in a record, we want to hide the target, so we
12875 // return true (without a diagnostic) to tell the caller not to
12876 // build a shadow decl.
12877 if (CurContext->isRecord())
12878 return true;
12879
12880 // If we're not in a record, this is an error.
12881 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12882 break;
12883 }
12884
12885 Diag(Target->getLocation(), diag::note_using_decl_target);
12886 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
12887 BUD->setInvalidDecl();
12888 return true;
12889 }
12890
12891 // Target is not a function.
12892
12893 if (isa<TagDecl>(Target)) {
12894 // No conflict between a tag and a non-tag.
12895 if (!Tag) return false;
12896
12897 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12898 Diag(Target->getLocation(), diag::note_using_decl_target);
12899 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
12900 BUD->setInvalidDecl();
12901 return true;
12902 }
12903
12904 // No conflict between a tag and a non-tag.
12905 if (!NonTag) return false;
12906
12907 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12908 Diag(Target->getLocation(), diag::note_using_decl_target);
12909 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
12910 BUD->setInvalidDecl();
12911 return true;
12912 }
12913
12914 /// Determine whether a direct base class is a virtual base class.
12915 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
12916 if (!Derived->getNumVBases())
12917 return false;
12918 for (auto &B : Derived->bases())
12919 if (B.getType()->getAsCXXRecordDecl() == Base)
12920 return B.isVirtual();
12921 llvm_unreachable("not a direct base class");
12922 }
12923
12924 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD,
12925 NamedDecl *Orig,
12926 UsingShadowDecl *PrevDecl) {
12927 // If we resolved to another shadow declaration, just coalesce them.
12928 NamedDecl *Target = Orig;
12929 if (isa<UsingShadowDecl>(Target)) {
12930 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
12931 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
12932 }
12933
12934 NamedDecl *NonTemplateTarget = Target;
12935 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
12936 NonTemplateTarget = TargetTD->getTemplatedDecl();
12937
12938 UsingShadowDecl *Shadow;
12939 if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) {
12940 UsingDecl *Using = cast<UsingDecl>(BUD);
12941 bool IsVirtualBase =
12942 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
12943 Using->getQualifier().getAsRecordDecl());
12944 Shadow = ConstructorUsingShadowDecl::Create(
12945 Context, CurContext, Using->getLocation(), Using, Orig, IsVirtualBase);
12946 } else {
12947 Shadow = UsingShadowDecl::Create(Context, CurContext, BUD->getLocation(),
12948 Target->getDeclName(), BUD, Target);
12949 }
12950 BUD->addShadowDecl(Shadow);
12951
12952 Shadow->setAccess(BUD->getAccess());
12953 if (Orig->isInvalidDecl() || BUD->isInvalidDecl())
12954 Shadow->setInvalidDecl();
12955
12956 Shadow->setPreviousDecl(PrevDecl);
12957
12958 if (S)
12959 PushOnScopeChains(Shadow, S);
12960 else
12961 CurContext->addDecl(Shadow);
12962
12963
12964 return Shadow;
12965 }
12966
12967 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
12968 if (Shadow->getDeclName().getNameKind() ==
12969 DeclarationName::CXXConversionFunctionName)
12970 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
12971
12972 // Remove it from the DeclContext...
12973 Shadow->getDeclContext()->removeDecl(Shadow);
12974
12975 // ...and the scope, if applicable...
12976 if (S) {
12977 S->RemoveDecl(Shadow);
12978 IdResolver.RemoveDecl(Shadow);
12979 }
12980
12981 // ...and the using decl.
12982 Shadow->getIntroducer()->removeShadowDecl(Shadow);
12983
12984 // TODO: complain somehow if Shadow was used. It shouldn't
12985 // be possible for this to happen, because...?
12986 }
12987
12988 /// Find the base specifier for a base class with the given type.
12989 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
12990 QualType DesiredBase,
12991 bool &AnyDependentBases) {
12992 // Check whether the named type is a direct base class.
12993 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
12994 for (auto &Base : Derived->bases()) {
12995 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
12996 if (CanonicalDesiredBase == BaseType)
12997 return &Base;
12998 if (BaseType->isDependentType())
12999 AnyDependentBases = true;
13000 }
13001 return nullptr;
13002 }
13003
13004 namespace {
13005 class UsingValidatorCCC final : public CorrectionCandidateCallback {
13006 public:
13007 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
13008 NestedNameSpecifier NNS, CXXRecordDecl *RequireMemberOf)
13009 : HasTypenameKeyword(HasTypenameKeyword),
13010 IsInstantiation(IsInstantiation), OldNNS(NNS),
13011 RequireMemberOf(RequireMemberOf) {}
13012
13013 bool ValidateCandidate(const TypoCorrection &Candidate) override {
13014 NamedDecl *ND = Candidate.getCorrectionDecl();
13015
13016 // Keywords are not valid here.
13017 if (!ND || isa<NamespaceDecl>(ND))
13018 return false;
13019
13020 // Completely unqualified names are invalid for a 'using' declaration.
13021 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
13022 return false;
13023
13024 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
13025 // reject.
13026
13027 if (RequireMemberOf) {
13028 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
13029 if (FoundRecord && FoundRecord->isInjectedClassName()) {
13030 // No-one ever wants a using-declaration to name an injected-class-name
13031 // of a base class, unless they're declaring an inheriting constructor.
13032 ASTContext &Ctx = ND->getASTContext();
13033 if (!Ctx.getLangOpts().CPlusPlus11)
13034 return false;
13035 CanQualType FoundType = Ctx.getCanonicalTagType(FoundRecord);
13036
13037 // Check that the injected-class-name is named as a member of its own
13038 // type; we don't want to suggest 'using Derived::Base;', since that
13039 // means something else.
13040 NestedNameSpecifier Specifier = Candidate.WillReplaceSpecifier()
13041 ? Candidate.getCorrectionSpecifier()
13042 : OldNNS;
13043 if (Specifier.getKind() != NestedNameSpecifier::Kind::Type ||
13044 !Ctx.hasSameType(QualType(Specifier.getAsType(), 0), FoundType))
13045 return false;
13046
13047 // Check that this inheriting constructor declaration actually names a
13048 // direct base class of the current class.
13049 bool AnyDependentBases = false;
13050 if (!findDirectBaseWithType(RequireMemberOf,
13051 Ctx.getCanonicalTagType(FoundRecord),
13052 AnyDependentBases) &&
13053 !AnyDependentBases)
13054 return false;
13055 } else {
13056 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
13057 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
13058 return false;
13059
13060 // FIXME: Check that the base class member is accessible?
13061 }
13062 } else {
13063 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
13064 if (FoundRecord && FoundRecord->isInjectedClassName())
13065 return false;
13066 }
13067
13068 if (isa<TypeDecl>(ND))
13069 return HasTypenameKeyword || !IsInstantiation;
13070
13071 return !HasTypenameKeyword;
13072 }
13073
13074 std::unique_ptr<CorrectionCandidateCallback> clone() override {
13075 return std::make_unique<UsingValidatorCCC>(*this);
13076 }
13077
13078 private:
13079 bool HasTypenameKeyword;
13080 bool IsInstantiation;
13081 NestedNameSpecifier OldNNS;
13082 CXXRecordDecl *RequireMemberOf;
13083 };
13084 } // end anonymous namespace
13085
13086 void Sema::FilterUsingLookup(Scope *S, LookupResult &Previous) {
13087 // It is really dumb that we have to do this.
13088 LookupResult::Filter F = Previous.makeFilter();
13089 while (F.hasNext()) {
13090 NamedDecl *D = F.next();
13091 if (!isDeclInScope(D, CurContext, S))
13092 F.erase();
13093 // If we found a local extern declaration that's not ordinarily visible,
13094 // and this declaration is being added to a non-block scope, ignore it.
13095 // We're only checking for scope conflicts here, not also for violations
13096 // of the linkage rules.
13097 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
13098 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
13099 F.erase();
13100 }
13101 F.done();
13102 }
13103
13104 NamedDecl *Sema::BuildUsingDeclaration(
13105 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
13106 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
13107 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
13108 const ParsedAttributesView &AttrList, bool IsInstantiation,
13109 bool IsUsingIfExists) {
13110 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
13111 SourceLocation IdentLoc = NameInfo.getLoc();
13112 assert(IdentLoc.isValid() && "Invalid TargetName location.");
13113
13114 // FIXME: We ignore attributes for now.
13115
13116 // For an inheriting constructor declaration, the name of the using
13117 // declaration is the name of a constructor in this class, not in the
13118 // base class.
13119 DeclarationNameInfo UsingName = NameInfo;
13120 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
13121 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
13122 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
13123 Context.getCanonicalTagType(RD)));
13124
13125 // Do the redeclaration lookup in the current scope.
13126 LookupResult Previous(*this, UsingName, LookupUsingDeclName,
13127 RedeclarationKind::ForVisibleRedeclaration);
13128 Previous.setHideTags(false);
13129 if (S) {
13130 LookupName(Previous, S);
13131
13132 FilterUsingLookup(S, Previous);
13133 } else {
13134 assert(IsInstantiation && "no scope in non-instantiation");
13135 if (CurContext->isRecord())
13136 LookupQualifiedName(Previous, CurContext);
13137 else {
13138 // No redeclaration check is needed here; in non-member contexts we
13139 // diagnosed all possible conflicts with other using-declarations when
13140 // building the template:
13141 //
13142 // For a dependent non-type using declaration, the only valid case is
13143 // if we instantiate to a single enumerator. We check for conflicts
13144 // between shadow declarations we introduce, and we check in the template
13145 // definition for conflicts between a non-type using declaration and any
13146 // other declaration, which together covers all cases.
13147 //
13148 // A dependent typename using declaration will never successfully
13149 // instantiate, since it will always name a class member, so we reject
13150 // that in the template definition.
13151 }
13152 }
13153
13154 // Check for invalid redeclarations.
13155 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
13156 SS, IdentLoc, Previous))
13157 return nullptr;
13158
13159 // 'using_if_exists' doesn't make sense on an inherited constructor.
13160 if (IsUsingIfExists && UsingName.getName().getNameKind() ==
13161 DeclarationName::CXXConstructorName) {
13162 Diag(UsingLoc, diag::err_using_if_exists_on_ctor);
13163 return nullptr;
13164 }
13165
13166 DeclContext *LookupContext = computeDeclContext(SS);
13167 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
13168 if (!LookupContext || EllipsisLoc.isValid()) {
13169 NamedDecl *D;
13170 // Dependent scope, or an unexpanded pack
13171 if (!LookupContext && CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword,
13172 SS, NameInfo, IdentLoc))
13173 return nullptr;
13174
13175 if (Previous.isSingleResult() &&
13176 Previous.getFoundDecl()->isTemplateParameter())
13177 DiagnoseTemplateParameterShadow(IdentLoc, Previous.getFoundDecl());
13178
13179 if (HasTypenameKeyword) {
13180 // FIXME: not all declaration name kinds are legal here
13181 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
13182 UsingLoc, TypenameLoc,
13183 QualifierLoc,
13184 IdentLoc, NameInfo.getName(),
13185 EllipsisLoc);
13186 } else {
13187 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
13188 QualifierLoc, NameInfo, EllipsisLoc);
13189 }
13190 D->setAccess(AS);
13191 CurContext->addDecl(D);
13192 ProcessDeclAttributeList(S, D, AttrList);
13193 return D;
13194 }
13195
13196 auto Build = [&](bool Invalid) {
13197 UsingDecl *UD =
13198 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
13199 UsingName, HasTypenameKeyword);
13200 UD->setAccess(AS);
13201 CurContext->addDecl(UD);
13202 ProcessDeclAttributeList(S, UD, AttrList);
13203 UD->setInvalidDecl(Invalid);
13204 return UD;
13205 };
13206 auto BuildInvalid = [&]{ return Build(true); };
13207 auto BuildValid = [&]{ return Build(false); };
13208
13209 if (RequireCompleteDeclContext(SS, LookupContext))
13210 return BuildInvalid();
13211
13212 // Look up the target name.
13213 LookupResult R(*this, NameInfo, LookupOrdinaryName);
13214
13215 // Unlike most lookups, we don't always want to hide tag
13216 // declarations: tag names are visible through the using declaration
13217 // even if hidden by ordinary names, *except* in a dependent context
13218 // where they may be used by two-phase lookup.
13219 if (!IsInstantiation)
13220 R.setHideTags(false);
13221
13222 // For the purposes of this lookup, we have a base object type
13223 // equal to that of the current context.
13224 if (CurContext->isRecord()) {
13225 R.setBaseObjectType(
13226 Context.getCanonicalTagType(cast<CXXRecordDecl>(CurContext)));
13227 }
13228
13229 LookupQualifiedName(R, LookupContext);
13230
13231 // Validate the context, now we have a lookup
13232 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
13233 IdentLoc, &R))
13234 return nullptr;
13235
13236 if (R.empty() && IsUsingIfExists)
13237 R.addDecl(UnresolvedUsingIfExistsDecl::Create(Context, CurContext, UsingLoc,
13238 UsingName.getName()),
13239 AS_public);
13240
13241 // Try to correct typos if possible. If constructor name lookup finds no
13242 // results, that means the named class has no explicit constructors, and we
13243 // suppressed declaring implicit ones (probably because it's dependent or
13244 // invalid).
13245 if (R.empty() &&
13246 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
13247 // HACK 2017-01-08: Work around an issue with libstdc++'s detection of
13248 // ::gets. Sometimes it believes that glibc provides a ::gets in cases where
13249 // it does not. The issue was fixed in libstdc++ 6.3 (2016-12-21) and later.
13250 auto *II = NameInfo.getName().getAsIdentifierInfo();
13251 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
13252 CurContext->isStdNamespace() &&
13253 isa<TranslationUnitDecl>(LookupContext) &&
13254 PP.NeedsStdLibCxxWorkaroundBefore(2016'12'21) &&
13255 getSourceManager().isInSystemHeader(UsingLoc))
13256 return nullptr;
13257 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
13258 dyn_cast<CXXRecordDecl>(CurContext));
13259 if (TypoCorrection Corrected =
13260 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
13261 CorrectTypoKind::ErrorRecovery)) {
13262 // We reject candidates where DroppedSpecifier == true, hence the
13263 // literal '0' below.
13264 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
13265 << NameInfo.getName() << LookupContext << 0
13266 << SS.getRange());
13267
13268 // If we picked a correction with no attached Decl we can't do anything
13269 // useful with it, bail out.
13270 NamedDecl *ND = Corrected.getCorrectionDecl();
13271 if (!ND)
13272 return BuildInvalid();
13273
13274 // If we corrected to an inheriting constructor, handle it as one.
13275 auto *RD = dyn_cast<CXXRecordDecl>(ND);
13276 if (RD && RD->isInjectedClassName()) {
13277 // The parent of the injected class name is the class itself.
13278 RD = cast<CXXRecordDecl>(RD->getParent());
13279
13280 // Fix up the information we'll use to build the using declaration.
13281 if (Corrected.WillReplaceSpecifier()) {
13282 NestedNameSpecifierLocBuilder Builder;
13283 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
13284 QualifierLoc.getSourceRange());
13285 QualifierLoc = Builder.getWithLocInContext(Context);
13286 }
13287
13288 // In this case, the name we introduce is the name of a derived class
13289 // constructor.
13290 auto *CurClass = cast<CXXRecordDecl>(CurContext);
13291 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
13292 Context.getCanonicalTagType(CurClass)));
13293 UsingName.setNamedTypeInfo(nullptr);
13294 for (auto *Ctor : LookupConstructors(RD))
13295 R.addDecl(Ctor);
13296 R.resolveKind();
13297 } else {
13298 // FIXME: Pick up all the declarations if we found an overloaded
13299 // function.
13300 UsingName.setName(ND->getDeclName());
13301 R.addDecl(ND);
13302 }
13303 } else {
13304 Diag(IdentLoc, diag::err_no_member)
13305 << NameInfo.getName() << LookupContext << SS.getRange();
13306 return BuildInvalid();
13307 }
13308 }
13309
13310 if (R.isAmbiguous())
13311 return BuildInvalid();
13312
13313 if (HasTypenameKeyword) {
13314 // If we asked for a typename and got a non-type decl, error out.
13315 if (!R.getAsSingle<TypeDecl>() &&
13316 !R.getAsSingle<UnresolvedUsingIfExistsDecl>()) {
13317 Diag(IdentLoc, diag::err_using_typename_non_type);
13318 for (const NamedDecl *D : R)
13319 Diag(D->getUnderlyingDecl()->getLocation(),
13320 diag::note_using_decl_target);
13321 return BuildInvalid();
13322 }
13323 } else {
13324 // If we asked for a non-typename and we got a type, error out,
13325 // but only if this is an instantiation of an unresolved using
13326 // decl. Otherwise just silently find the type name.
13327 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
13328 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
13329 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
13330 return BuildInvalid();
13331 }
13332 }
13333
13334 // C++14 [namespace.udecl]p6:
13335 // A using-declaration shall not name a namespace.
13336 if (R.getAsSingle<NamespaceDecl>()) {
13337 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
13338 << SS.getRange();
13339 // Suggest using 'using namespace ...' instead.
13340 Diag(SS.getBeginLoc(), diag::note_namespace_using_decl)
13341 << FixItHint::CreateInsertion(SS.getBeginLoc(), "namespace ");
13342 return BuildInvalid();
13343 }
13344
13345 UsingDecl *UD = BuildValid();
13346
13347 // Some additional rules apply to inheriting constructors.
13348 if (UsingName.getName().getNameKind() ==
13349 DeclarationName::CXXConstructorName) {
13350 // Suppress access diagnostics; the access check is instead performed at the
13351 // point of use for an inheriting constructor.
13352 R.suppressDiagnostics();
13353 if (CheckInheritingConstructorUsingDecl(UD))
13354 return UD;
13355 }
13356
13357 for (NamedDecl *D : R) {
13358 UsingShadowDecl *PrevDecl = nullptr;
13359 if (!CheckUsingShadowDecl(UD, D, Previous, PrevDecl))
13360 BuildUsingShadowDecl(S, UD, D, PrevDecl);
13361 }
13362
13363 return UD;
13364 }
13365
13366 NamedDecl *Sema::BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
13367 SourceLocation UsingLoc,
13368 SourceLocation EnumLoc,
13369 SourceLocation NameLoc,
13370 TypeSourceInfo *EnumType,
13371 EnumDecl *ED) {
13372 bool Invalid = false;
13373
13374 if (CurContext->getRedeclContext()->isRecord()) {
13375 /// In class scope, check if this is a duplicate, for better a diagnostic.
13376 DeclarationNameInfo UsingEnumName(ED->getDeclName(), NameLoc);
13377 LookupResult Previous(*this, UsingEnumName, LookupUsingDeclName,
13378 RedeclarationKind::ForVisibleRedeclaration);
13379
13380 LookupQualifiedName(Previous, CurContext);
13381
13382 for (NamedDecl *D : Previous)
13383 if (UsingEnumDecl *UED = dyn_cast<UsingEnumDecl>(D))
13384 if (UED->getEnumDecl() == ED) {
13385 Diag(UsingLoc, diag::err_using_enum_decl_redeclaration)
13386 << SourceRange(EnumLoc, NameLoc);
13387 Diag(D->getLocation(), diag::note_using_enum_decl) << 1;
13388 Invalid = true;
13389 break;
13390 }
13391 }
13392
13393 if (RequireCompleteEnumDecl(ED, NameLoc))
13394 Invalid = true;
13395
13396 UsingEnumDecl *UD = UsingEnumDecl::Create(Context, CurContext, UsingLoc,
13397 EnumLoc, NameLoc, EnumType);
13398 UD->setAccess(AS);
13399 CurContext->addDecl(UD);
13400
13401 if (Invalid) {
13402 UD->setInvalidDecl();
13403 return UD;
13404 }
13405
13406 // Create the shadow decls for each enumerator
13407 for (EnumConstantDecl *EC : ED->enumerators()) {
13408 UsingShadowDecl *PrevDecl = nullptr;
13409 DeclarationNameInfo DNI(EC->getDeclName(), EC->getLocation());
13410 LookupResult Previous(*this, DNI, LookupOrdinaryName,
13411 RedeclarationKind::ForVisibleRedeclaration);
13412 LookupName(Previous, S);
13413 FilterUsingLookup(S, Previous);
13414
13415 if (!CheckUsingShadowDecl(UD, EC, Previous, PrevDecl))
13416 BuildUsingShadowDecl(S, UD, EC, PrevDecl);
13417 }
13418
13419 return UD;
13420 }
13421
13422 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
13423 ArrayRef<NamedDecl *> Expansions) {
13424 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
13425 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
13426 isa<UsingPackDecl>(InstantiatedFrom));
13427
13428 auto *UPD =
13429 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
13430 UPD->setAccess(InstantiatedFrom->getAccess());
13431 CurContext->addDecl(UPD);
13432 return UPD;
13433 }
13434
13435 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
13436 assert(!UD->hasTypename() && "expecting a constructor name");
13437
13438 QualType SourceType(UD->getQualifier().getAsType(), 0);
13439 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
13440
13441 // Check whether the named type is a direct base class.
13442 bool AnyDependentBases = false;
13443 auto *Base =
13444 findDirectBaseWithType(TargetClass, SourceType, AnyDependentBases);
13445 if (!Base && !AnyDependentBases) {
13446 Diag(UD->getUsingLoc(), diag::err_using_decl_constructor_not_in_direct_base)
13447 << UD->getNameInfo().getSourceRange() << SourceType << TargetClass;
13448 UD->setInvalidDecl();
13449 return true;
13450 }
13451
13452 if (Base)
13453 Base->setInheritConstructors();
13454
13455 return false;
13456 }
13457
13458 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
13459 bool HasTypenameKeyword,
13460 const CXXScopeSpec &SS,
13461 SourceLocation NameLoc,
13462 const LookupResult &Prev) {
13463 NestedNameSpecifier Qual = SS.getScopeRep();
13464
13465 // C++03 [namespace.udecl]p8:
13466 // C++0x [namespace.udecl]p10:
13467 // A using-declaration is a declaration and can therefore be used
13468 // repeatedly where (and only where) multiple declarations are
13469 // allowed.
13470 //
13471 // That's in non-member contexts.
13472 if (!CurContext->getRedeclContext()->isRecord()) {
13473 // A dependent qualifier outside a class can only ever resolve to an
13474 // enumeration type. Therefore it conflicts with any other non-type
13475 // declaration in the same scope.
13476 // FIXME: How should we check for dependent type-type conflicts at block
13477 // scope?
13478 if (Qual.isDependent() && !HasTypenameKeyword) {
13479 for (auto *D : Prev) {
13480 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
13481 bool OldCouldBeEnumerator =
13482 isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
13483 Diag(NameLoc,
13484 OldCouldBeEnumerator ? diag::err_redefinition
13485 : diag::err_redefinition_different_kind)
13486 << Prev.getLookupName();
13487 Diag(D->getLocation(), diag::note_previous_definition);
13488 return true;
13489 }
13490 }
13491 }
13492 return false;
13493 }
13494
13495 NestedNameSpecifier CNNS = Qual.getCanonical();
13496 for (const NamedDecl *D : Prev) {
13497 bool DTypename;
13498 NestedNameSpecifier DQual = std::nullopt;
13499 if (const auto *UD = dyn_cast<UsingDecl>(D)) {
13500 DTypename = UD->hasTypename();
13501 DQual = UD->getQualifier();
13502 } else if (const auto *UD = dyn_cast<UnresolvedUsingValueDecl>(D)) {
13503 DTypename = false;
13504 DQual = UD->getQualifier();
13505 } else if (const auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
13506 DTypename = true;
13507 DQual = UD->getQualifier();
13508 } else
13509 continue;
13510
13511 // using decls differ if one says 'typename' and the other doesn't.
13512 // FIXME: non-dependent using decls?
13513 if (HasTypenameKeyword != DTypename) continue;
13514
13515 // using decls differ if they name different scopes (but note that
13516 // template instantiation can cause this check to trigger when it
13517 // didn't before instantiation).
13518 if (CNNS != DQual.getCanonical())
13519 continue;
13520
13521 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
13522 Diag(D->getLocation(), diag::note_using_decl) << 1;
13523 return true;
13524 }
13525
13526 return false;
13527 }
13528
13529 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
13530 const CXXScopeSpec &SS,
13531 const DeclarationNameInfo &NameInfo,
13532 SourceLocation NameLoc,
13533 const LookupResult *R, const UsingDecl *UD) {
13534 DeclContext *NamedContext = computeDeclContext(SS);
13535 assert(bool(NamedContext) == (R || UD) && !(R && UD) &&
13536 "resolvable context must have exactly one set of decls");
13537
13538 // C++ 20 permits using an enumerator that does not have a class-hierarchy
13539 // relationship.
13540 bool Cxx20Enumerator = false;
13541 if (NamedContext) {
13542 EnumConstantDecl *EC = nullptr;
13543 if (R)
13544 EC = R->getAsSingle<EnumConstantDecl>();
13545 else if (UD && UD->shadow_size() == 1)
13546 EC = dyn_cast<EnumConstantDecl>(UD->shadow_begin()->getTargetDecl());
13547 if (EC)
13548 Cxx20Enumerator = getLangOpts().CPlusPlus20;
13549
13550 if (auto *ED = dyn_cast<EnumDecl>(NamedContext)) {
13551 // C++14 [namespace.udecl]p7:
13552 // A using-declaration shall not name a scoped enumerator.
13553 // C++20 p1099 permits enumerators.
13554 if (EC && R && ED->isScoped())
13555 Diag(SS.getBeginLoc(),
13556 getLangOpts().CPlusPlus20
13557 ? diag::warn_cxx17_compat_using_decl_scoped_enumerator
13558 : diag::ext_using_decl_scoped_enumerator)
13559 << SS.getRange();
13560
13561 // We want to consider the scope of the enumerator
13562 NamedContext = ED->getDeclContext();
13563 }
13564 }
13565
13566 if (!CurContext->isRecord()) {
13567 // C++03 [namespace.udecl]p3:
13568 // C++0x [namespace.udecl]p8:
13569 // A using-declaration for a class member shall be a member-declaration.
13570 // C++20 [namespace.udecl]p7
13571 // ... other than an enumerator ...
13572
13573 // If we weren't able to compute a valid scope, it might validly be a
13574 // dependent class or enumeration scope. If we have a 'typename' keyword,
13575 // the scope must resolve to a class type.
13576 if (NamedContext ? !NamedContext->getRedeclContext()->isRecord()
13577 : !HasTypename)
13578 return false; // OK
13579
13580 Diag(NameLoc,
13581 Cxx20Enumerator
13582 ? diag::warn_cxx17_compat_using_decl_class_member_enumerator
13583 : diag::err_using_decl_can_not_refer_to_class_member)
13584 << SS.getRange();
13585
13586 if (Cxx20Enumerator)
13587 return false; // OK
13588
13589 auto *RD = NamedContext
13590 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
13591 : nullptr;
13592 if (RD && !RequireCompleteDeclContext(const_cast<CXXScopeSpec &>(SS), RD)) {
13593 // See if there's a helpful fixit
13594
13595 if (!R) {
13596 // We will have already diagnosed the problem on the template
13597 // definition, Maybe we should do so again?
13598 } else if (R->getAsSingle<TypeDecl>()) {
13599 if (getLangOpts().CPlusPlus11) {
13600 // Convert 'using X::Y;' to 'using Y = X::Y;'.
13601 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
13602 << diag::MemClassWorkaround::AliasDecl
13603 << FixItHint::CreateInsertion(SS.getBeginLoc(),
13604 NameInfo.getName().getAsString() +
13605 " = ");
13606 } else {
13607 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
13608 SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
13609 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
13610 << diag::MemClassWorkaround::TypedefDecl
13611 << FixItHint::CreateReplacement(UsingLoc, "typedef")
13612 << FixItHint::CreateInsertion(
13613 InsertLoc, " " + NameInfo.getName().getAsString());
13614 }
13615 } else if (R->getAsSingle<VarDecl>()) {
13616 // Don't provide a fixit outside C++11 mode; we don't want to suggest
13617 // repeating the type of the static data member here.
13618 FixItHint FixIt;
13619 if (getLangOpts().CPlusPlus11) {
13620 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
13621 FixIt = FixItHint::CreateReplacement(
13622 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
13623 }
13624
13625 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
13626 << diag::MemClassWorkaround::ReferenceDecl << FixIt;
13627 } else if (R->getAsSingle<EnumConstantDecl>()) {
13628 // Don't provide a fixit outside C++11 mode; we don't want to suggest
13629 // repeating the type of the enumeration here, and we can't do so if
13630 // the type is anonymous.
13631 FixItHint FixIt;
13632 if (getLangOpts().CPlusPlus11) {
13633 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
13634 FixIt = FixItHint::CreateReplacement(
13635 UsingLoc,
13636 "constexpr auto " + NameInfo.getName().getAsString() + " = ");
13637 }
13638
13639 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
13640 << (getLangOpts().CPlusPlus11
13641 ? diag::MemClassWorkaround::ConstexprVar
13642 : diag::MemClassWorkaround::ConstVar)
13643 << FixIt;
13644 }
13645 }
13646
13647 return true; // Fail
13648 }
13649
13650 // If the named context is dependent, we can't decide much.
13651 if (!NamedContext) {
13652 // FIXME: in C++0x, we can diagnose if we can prove that the
13653 // nested-name-specifier does not refer to a base class, which is
13654 // still possible in some cases.
13655
13656 // Otherwise we have to conservatively report that things might be
13657 // okay.
13658 return false;
13659 }
13660
13661 // The current scope is a record.
13662 if (!NamedContext->isRecord()) {
13663 // Ideally this would point at the last name in the specifier,
13664 // but we don't have that level of source info.
13665 Diag(SS.getBeginLoc(),
13666 Cxx20Enumerator
13667 ? diag::warn_cxx17_compat_using_decl_non_member_enumerator
13668 : diag::err_using_decl_nested_name_specifier_is_not_class)
13669 << SS.getScopeRep() << SS.getRange();
13670
13671 if (Cxx20Enumerator)
13672 return false; // OK
13673
13674 return true;
13675 }
13676
13677 if (!NamedContext->isDependentContext() &&
13678 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
13679 return true;
13680
13681 // C++26 [namespace.udecl]p3:
13682 // In a using-declaration used as a member-declaration, each
13683 // using-declarator shall either name an enumerator or have a
13684 // nested-name-specifier naming a base class of the current class
13685 // ([expr.prim.this]). ...
13686 // "have a nested-name-specifier naming a base class of the current class"
13687 // was introduced by CWG400.
13688
13689 if (cast<CXXRecordDecl>(CurContext)
13690 ->isProvablyNotDerivedFrom(cast<CXXRecordDecl>(NamedContext))) {
13691
13692 if (Cxx20Enumerator) {
13693 Diag(NameLoc, diag::warn_cxx17_compat_using_decl_non_member_enumerator)
13694 << SS.getScopeRep() << SS.getRange();
13695 return false;
13696 }
13697
13698 if (CurContext == NamedContext) {
13699 Diag(SS.getBeginLoc(),
13700 diag::err_using_decl_nested_name_specifier_is_current_class)
13701 << SS.getRange();
13702 return true;
13703 }
13704
13705 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
13706 Diag(SS.getBeginLoc(),
13707 diag::err_using_decl_nested_name_specifier_is_not_base_class)
13708 << SS.getScopeRep() << cast<CXXRecordDecl>(CurContext)
13709 << SS.getRange();
13710 }
13711 return true;
13712 }
13713
13714 return false;
13715 }
13716
13717 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
13718 MultiTemplateParamsArg TemplateParamLists,
13719 SourceLocation UsingLoc, UnqualifiedId &Name,
13720 const ParsedAttributesView &AttrList,
13721 TypeResult Type, Decl *DeclFromDeclSpec) {
13722
13723 if (Type.isInvalid())
13724 return nullptr;
13725
13726 bool Invalid = false;
13727 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
13728 TypeSourceInfo *TInfo = nullptr;
13729 GetTypeFromParser(Type.get(), &TInfo);
13730
13731 if (DiagnoseClassNameShadow(CurContext, NameInfo))
13732 return nullptr;
13733
13734 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
13735 UPPC_DeclarationType)) {
13736 Invalid = true;
13737 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
13738 TInfo->getTypeLoc().getBeginLoc());
13739 }
13740
13741 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
13742 TemplateParamLists.size()
13743 ? forRedeclarationInCurContext()
13744 : RedeclarationKind::ForVisibleRedeclaration);
13745 LookupName(Previous, S);
13746
13747 // Warn about shadowing the name of a template parameter.
13748 if (Previous.isSingleResult() &&
13749 Previous.getFoundDecl()->isTemplateParameter()) {
13750 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
13751 Previous.clear();
13752 }
13753
13754 assert(Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
13755 "name in alias declaration must be an identifier");
13756 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
13757 Name.StartLocation,
13758 Name.Identifier, TInfo);
13759
13760 NewTD->setAccess(AS);
13761
13762 if (Invalid)
13763 NewTD->setInvalidDecl();
13764
13765 ProcessDeclAttributeList(S, NewTD, AttrList);
13766 AddPragmaAttributes(S, NewTD);
13767 ProcessAPINotes(NewTD);
13768
13769 CheckTypedefForVariablyModifiedType(S, NewTD);
13770 Invalid |= NewTD->isInvalidDecl();
13771
13772 // Get the innermost enclosing declaration scope.
13773 S = S->getDeclParent();
13774
13775 bool Redeclaration = false;
13776
13777 NamedDecl *NewND;
13778 if (TemplateParamLists.size()) {
13779 TypeAliasTemplateDecl *OldDecl = nullptr;
13780 TemplateParameterList *OldTemplateParams = nullptr;
13781
13782 if (TemplateParamLists.size() != 1) {
13783 Diag(UsingLoc, diag::err_alias_template_extra_headers)
13784 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
13785 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
13786 Invalid = true;
13787 }
13788 TemplateParameterList *TemplateParams = TemplateParamLists[0];
13789
13790 // Check that we can declare a template here.
13791 if (CheckTemplateDeclScope(S, TemplateParams))
13792 return nullptr;
13793
13794 // Only consider previous declarations in the same scope.
13795 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
13796 /*ExplicitInstantiationOrSpecialization*/false);
13797 if (!Previous.empty()) {
13798 Redeclaration = true;
13799
13800 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
13801 if (!OldDecl && !Invalid) {
13802 Diag(UsingLoc, diag::err_redefinition_different_kind)
13803 << Name.Identifier;
13804
13805 NamedDecl *OldD = Previous.getRepresentativeDecl();
13806 if (OldD->getLocation().isValid())
13807 Diag(OldD->getLocation(), diag::note_previous_definition);
13808
13809 Invalid = true;
13810 }
13811
13812 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
13813 if (TemplateParameterListsAreEqual(TemplateParams,
13814 OldDecl->getTemplateParameters(),
13815 /*Complain=*/true,
13816 TPL_TemplateMatch))
13817 OldTemplateParams =
13818 OldDecl->getMostRecentDecl()->getTemplateParameters();
13819 else
13820 Invalid = true;
13821
13822 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
13823 if (!Invalid &&
13824 !Context.hasSameType(OldTD->getUnderlyingType(),
13825 NewTD->getUnderlyingType())) {
13826 // FIXME: The C++0x standard does not clearly say this is ill-formed,
13827 // but we can't reasonably accept it.
13828 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
13829 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
13830 if (OldTD->getLocation().isValid())
13831 Diag(OldTD->getLocation(), diag::note_previous_definition);
13832 Invalid = true;
13833 }
13834 }
13835 }
13836
13837 // Merge any previous default template arguments into our parameters,
13838 // and check the parameter list.
13839 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
13840 TPC_Other))
13841 return nullptr;
13842
13843 TypeAliasTemplateDecl *NewDecl =
13844 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
13845 Name.Identifier, TemplateParams,
13846 NewTD);
13847 NewTD->setDescribedAliasTemplate(NewDecl);
13848
13849 NewDecl->setAccess(AS);
13850
13851 if (Invalid)
13852 NewDecl->setInvalidDecl();
13853 else if (OldDecl) {
13854 NewDecl->setPreviousDecl(OldDecl);
13855 CheckRedeclarationInModule(NewDecl, OldDecl);
13856 }
13857
13858 NewND = NewDecl;
13859 } else {
13860 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
13861 setTagNameForLinkagePurposes(TD, NewTD);
13862 handleTagNumbering(TD, S);
13863 }
13864 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
13865 NewND = NewTD;
13866 }
13867
13868 PushOnScopeChains(NewND, S);
13869 ActOnDocumentableDecl(NewND);
13870 return NewND;
13871 }
13872
13873 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
13874 SourceLocation AliasLoc,
13875 IdentifierInfo *Alias, CXXScopeSpec &SS,
13876 SourceLocation IdentLoc,
13877 IdentifierInfo *Ident) {
13878
13879 // Lookup the namespace name.
13880 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
13881 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
13882
13883 if (R.isAmbiguous())
13884 return nullptr;
13885
13886 if (R.empty()) {
13887 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
13888 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
13889 return nullptr;
13890 }
13891 }
13892 assert(!R.isAmbiguous() && !R.empty());
13893 auto *ND = cast<NamespaceBaseDecl>(R.getRepresentativeDecl());
13894
13895 // Check if we have a previous declaration with the same name.
13896 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
13897 RedeclarationKind::ForVisibleRedeclaration);
13898 LookupName(PrevR, S);
13899
13900 // Check we're not shadowing a template parameter.
13901 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
13902 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
13903 PrevR.clear();
13904 }
13905
13906 // Filter out any other lookup result from an enclosing scope.
13907 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
13908 /*AllowInlineNamespace*/false);
13909
13910 // Find the previous declaration and check that we can redeclare it.
13911 NamespaceAliasDecl *Prev = nullptr;
13912 if (PrevR.isSingleResult()) {
13913 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
13914 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
13915 // We already have an alias with the same name that points to the same
13916 // namespace; check that it matches.
13917 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
13918 Prev = AD;
13919 } else if (isVisible(PrevDecl)) {
13920 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
13921 << Alias;
13922 Diag(AD->getLocation(), diag::note_previous_namespace_alias)
13923 << AD->getNamespace();
13924 return nullptr;
13925 }
13926 } else if (isVisible(PrevDecl)) {
13927 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
13928 ? diag::err_redefinition
13929 : diag::err_redefinition_different_kind;
13930 Diag(AliasLoc, DiagID) << Alias;
13931 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13932 return nullptr;
13933 }
13934 }
13935
13936 // The use of a nested name specifier may trigger deprecation warnings.
13937 DiagnoseUseOfDecl(ND, IdentLoc);
13938
13939 NamespaceAliasDecl *AliasDecl =
13940 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
13941 Alias, SS.getWithLocInContext(Context),
13942 IdentLoc, ND);
13943 if (Prev)
13944 AliasDecl->setPreviousDecl(Prev);
13945
13946 PushOnScopeChains(AliasDecl, S);
13947 return AliasDecl;
13948 }
13949
13950 namespace {
13951 struct SpecialMemberExceptionSpecInfo
13952 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
13953 SourceLocation Loc;
13954 Sema::ImplicitExceptionSpecification ExceptSpec;
13955
13956 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
13957 CXXSpecialMemberKind CSM,
13958 Sema::InheritedConstructorInfo *ICI,
13959 SourceLocation Loc)
13960 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
13961
13962 bool visitBase(CXXBaseSpecifier *Base);
13963 bool visitField(FieldDecl *FD);
13964
13965 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
13966 unsigned Quals);
13967
13968 void visitSubobjectCall(Subobject Subobj,
13969 Sema::SpecialMemberOverloadResult SMOR);
13970 };
13971 }
13972
13973 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
13974 auto *BaseClass = Base->getType()->getAsCXXRecordDecl();
13975 if (!BaseClass)
13976 return false;
13977
13978 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
13979 if (auto *BaseCtor = SMOR.getMethod()) {
13980 visitSubobjectCall(Base, BaseCtor);
13981 return false;
13982 }
13983
13984 visitClassSubobject(BaseClass, Base, 0);
13985 return false;
13986 }
13987
13988 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
13989 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
13990 FD->hasInClassInitializer()) {
13991 Expr *E = FD->getInClassInitializer();
13992 if (!E)
13993 // FIXME: It's a little wasteful to build and throw away a
13994 // CXXDefaultInitExpr here.
13995 // FIXME: We should have a single context note pointing at Loc, and
13996 // this location should be MD->getLocation() instead, since that's
13997 // the location where we actually use the default init expression.
13998 E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
13999 if (E)
14000 ExceptSpec.CalledExpr(E);
14001 } else if (auto *RD = S.Context.getBaseElementType(FD->getType())
14002 ->getAsCXXRecordDecl()) {
14003 visitClassSubobject(RD, FD, FD->getType().getCVRQualifiers());
14004 }
14005 return false;
14006 }
14007
14008 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
14009 Subobject Subobj,
14010 unsigned Quals) {
14011 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
14012 bool IsMutable = Field && Field->isMutable();
14013 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
14014 }
14015
14016 void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
14017 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
14018 // Note, if lookup fails, it doesn't matter what exception specification we
14019 // choose because the special member will be deleted.
14020 if (CXXMethodDecl *MD = SMOR.getMethod())
14021 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
14022 }
14023
14024 bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) {
14025 llvm::APSInt Result;
14026 ExprResult Converted = CheckConvertedConstantExpression(
14027 ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEKind::ExplicitBool);
14028 ExplicitSpec.setExpr(Converted.get());
14029 if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
14030 ExplicitSpec.setKind(Result.getBoolValue()
14031 ? ExplicitSpecKind::ResolvedTrue
14032 : ExplicitSpecKind::ResolvedFalse);
14033 return true;
14034 }
14035 ExplicitSpec.setKind(ExplicitSpecKind::Unresolved);
14036 return false;
14037 }
14038
14039 ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) {
14040 ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved);
14041 if (!ExplicitExpr->isTypeDependent())
14042 tryResolveExplicitSpecifier(ES);
14043 return ES;
14044 }
14045
14046 static Sema::ImplicitExceptionSpecification
14047 ComputeDefaultedSpecialMemberExceptionSpec(
14048 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, CXXSpecialMemberKind CSM,
14049 Sema::InheritedConstructorInfo *ICI) {
14050 ComputingExceptionSpec CES(S, MD, Loc);
14051
14052 CXXRecordDecl *ClassDecl = MD->getParent();
14053
14054 // C++ [except.spec]p14:
14055 // An implicitly declared special member function (Clause 12) shall have an
14056 // exception-specification. [...]
14057 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
14058 if (ClassDecl->isInvalidDecl())
14059 return Info.ExceptSpec;
14060
14061 // FIXME: If this diagnostic fires, we're probably missing a check for
14062 // attempting to resolve an exception specification before it's known
14063 // at a higher level.
14064 if (S.RequireCompleteType(MD->getLocation(),
14065 S.Context.getCanonicalTagType(ClassDecl),
14066 diag::err_exception_spec_incomplete_type))
14067 return Info.ExceptSpec;
14068
14069 // C++1z [except.spec]p7:
14070 // [Look for exceptions thrown by] a constructor selected [...] to
14071 // initialize a potentially constructed subobject,
14072 // C++1z [except.spec]p8:
14073 // The exception specification for an implicitly-declared destructor, or a
14074 // destructor without a noexcept-specifier, is potentially-throwing if and
14075 // only if any of the destructors for any of its potentially constructed
14076 // subojects is potentially throwing.
14077 // FIXME: We respect the first rule but ignore the "potentially constructed"
14078 // in the second rule to resolve a core issue (no number yet) that would have
14079 // us reject:
14080 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
14081 // struct B : A {};
14082 // struct C : B { void f(); };
14083 // ... due to giving B::~B() a non-throwing exception specification.
14084 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
14085 : Info.VisitAllBases);
14086
14087 return Info.ExceptSpec;
14088 }
14089
14090 namespace {
14091 /// RAII object to register a special member as being currently declared.
14092 struct DeclaringSpecialMember {
14093 Sema &S;
14094 Sema::SpecialMemberDecl D;
14095 Sema::ContextRAII SavedContext;
14096 bool WasAlreadyBeingDeclared;
14097
14098 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, CXXSpecialMemberKind CSM)
14099 : S(S), D(RD, CSM), SavedContext(S, RD) {
14100 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
14101 if (WasAlreadyBeingDeclared)
14102 // This almost never happens, but if it does, ensure that our cache
14103 // doesn't contain a stale result.
14104 S.SpecialMemberCache.clear();
14105 else {
14106 // Register a note to be produced if we encounter an error while
14107 // declaring the special member.
14108 Sema::CodeSynthesisContext Ctx;
14109 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
14110 // FIXME: We don't have a location to use here. Using the class's
14111 // location maintains the fiction that we declare all special members
14112 // with the class, but (1) it's not clear that lying about that helps our
14113 // users understand what's going on, and (2) there may be outer contexts
14114 // on the stack (some of which are relevant) and printing them exposes
14115 // our lies.
14116 Ctx.PointOfInstantiation = RD->getLocation();
14117 Ctx.Entity = RD;
14118 Ctx.SpecialMember = CSM;
14119 S.pushCodeSynthesisContext(Ctx);
14120 }
14121 }
14122 ~DeclaringSpecialMember() {
14123 if (!WasAlreadyBeingDeclared) {
14124 S.SpecialMembersBeingDeclared.erase(D);
14125 S.popCodeSynthesisContext();
14126 }
14127 }
14128
14129 /// Are we already trying to declare this special member?
14130 bool isAlreadyBeingDeclared() const {
14131 return WasAlreadyBeingDeclared;
14132 }
14133 };
14134 }
14135
14136 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
14137 // Look up any existing declarations, but don't trigger declaration of all
14138 // implicit special members with this name.
14139 DeclarationName Name = FD->getDeclName();
14140 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
14141 RedeclarationKind::ForExternalRedeclaration);
14142 for (auto *D : FD->getParent()->lookup(Name))
14143 if (auto *Acceptable = R.getAcceptableDecl(D))
14144 R.addDecl(Acceptable);
14145 R.resolveKind();
14146 R.suppressDiagnostics();
14147
14148 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/ false,
14149 FD->isThisDeclarationADefinition());
14150 }
14151
14152 void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
14153 QualType ResultTy,
14154 ArrayRef<QualType> Args) {
14155 // Build an exception specification pointing back at this constructor.
14156 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem);
14157
14158 LangAS AS = getDefaultCXXMethodAddrSpace();
14159 if (AS != LangAS::Default) {
14160 EPI.TypeQuals.addAddressSpace(AS);
14161 }
14162
14163 auto QT = Context.getFunctionType(ResultTy, Args, EPI);
14164 SpecialMem->setType(QT);
14165
14166 // During template instantiation of implicit special member functions we need
14167 // a reliable TypeSourceInfo for the function prototype in order to allow
14168 // functions to be substituted.
14169 if (inTemplateInstantiation() && isLambdaMethod(SpecialMem)) {
14170 TypeSourceInfo *TSI =
14171 Context.getTrivialTypeSourceInfo(SpecialMem->getType());
14172 SpecialMem->setTypeSourceInfo(TSI);
14173 }
14174 }
14175
14176 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
14177 CXXRecordDecl *ClassDecl) {
14178 // C++ [class.ctor]p5:
14179 // A default constructor for a class X is a constructor of class X
14180 // that can be called without an argument. If there is no
14181 // user-declared constructor for class X, a default constructor is
14182 // implicitly declared. An implicitly-declared default constructor
14183 // is an inline public member of its class.
14184 assert(ClassDecl->needsImplicitDefaultConstructor() &&
14185 "Should not build implicit default constructor!");
14186
14187 DeclaringSpecialMember DSM(*this, ClassDecl,
14188 CXXSpecialMemberKind::DefaultConstructor);
14189 if (DSM.isAlreadyBeingDeclared())
14190 return nullptr;
14191
14192 bool Constexpr = defaultedSpecialMemberIsConstexpr(
14193 *this, ClassDecl, CXXSpecialMemberKind::DefaultConstructor, false);
14194
14195 // Create the actual constructor declaration.
14196 CanQualType ClassType = Context.getCanonicalTagType(ClassDecl);
14197 SourceLocation ClassLoc = ClassDecl->getLocation();
14198 DeclarationName Name
14199 = Context.DeclarationNames.getCXXConstructorName(ClassType);
14200 DeclarationNameInfo NameInfo(Name, ClassLoc);
14201 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
14202 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),
14203 /*TInfo=*/nullptr, ExplicitSpecifier(),
14204 getCurFPFeatures().isFPConstrained(),
14205 /*isInline=*/true, /*isImplicitlyDeclared=*/true,
14206 Constexpr ? ConstexprSpecKind::Constexpr
14207 : ConstexprSpecKind::Unspecified);
14208 DefaultCon->setAccess(AS_public);
14209 DefaultCon->setDefaulted();
14210
14211 setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, {});
14212
14213 if (getLangOpts().CUDA)
14214 CUDA().inferTargetForImplicitSpecialMember(
14215 ClassDecl, CXXSpecialMemberKind::DefaultConstructor, DefaultCon,
14216 /* ConstRHS */ false,
14217 /* Diagnose */ false);
14218
14219 // We don't need to use SpecialMemberIsTrivial here; triviality for default
14220 // constructors is easy to compute.
14221 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
14222
14223 // Note that we have declared this constructor.
14224 ++getASTContext().NumImplicitDefaultConstructorsDeclared;
14225
14226 Scope *S = getScopeForContext(ClassDecl);
14227 CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
14228
14229 if (ShouldDeleteSpecialMember(DefaultCon,
14230 CXXSpecialMemberKind::DefaultConstructor))
14231 SetDeclDeleted(DefaultCon, ClassLoc);
14232
14233 if (S)
14234 PushOnScopeChains(DefaultCon, S, false);
14235 ClassDecl->addDecl(DefaultCon);
14236
14237 return DefaultCon;
14238 }
14239
14240 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
14241 CXXConstructorDecl *Constructor) {
14242 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
14243 !Constructor->doesThisDeclarationHaveABody() &&
14244 !Constructor->isDeleted()) &&
14245 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
14246 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
14247 return;
14248
14249 CXXRecordDecl *ClassDecl = Constructor->getParent();
14250 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
14251 if (ClassDecl->isInvalidDecl()) {
14252 return;
14253 }
14254
14255 SynthesizedFunctionScope Scope(*this, Constructor);
14256
14257 // The exception specification is needed because we are defining the
14258 // function.
14259 ResolveExceptionSpec(CurrentLocation,
14260 Constructor->getType()->castAs<FunctionProtoType>());
14261 MarkVTableUsed(CurrentLocation, ClassDecl);
14262
14263 // Add a context note for diagnostics produced after this point.
14264 Scope.addContextNote(CurrentLocation);
14265
14266 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
14267 Constructor->setInvalidDecl();
14268 return;
14269 }
14270
14271 SourceLocation Loc = Constructor->getEndLoc().isValid()
14272 ? Constructor->getEndLoc()
14273 : Constructor->getLocation();
14274 Constructor->setBody(new (Context) CompoundStmt(Loc));
14275 Constructor->markUsed(Context);
14276
14277 if (ASTMutationListener *L = getASTMutationListener()) {
14278 L->CompletedImplicitDefinition(Constructor);
14279 }
14280
14281 DiagnoseUninitializedFields(*this, Constructor);
14282 }
14283
14284 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
14285 // Perform any delayed checks on exception specifications.
14286 CheckDelayedMemberExceptionSpecs();
14287 }
14288
14289 /// Find or create the fake constructor we synthesize to model constructing an
14290 /// object of a derived class via a constructor of a base class.
14291 CXXConstructorDecl *
14292 Sema::findInheritingConstructor(SourceLocation Loc,
14293 CXXConstructorDecl *BaseCtor,
14294 ConstructorUsingShadowDecl *Shadow) {
14295 CXXRecordDecl *Derived = Shadow->getParent();
14296 SourceLocation UsingLoc = Shadow->getLocation();
14297
14298 // FIXME: Add a new kind of DeclarationName for an inherited constructor.
14299 // For now we use the name of the base class constructor as a member of the
14300 // derived class to indicate a (fake) inherited constructor name.
14301 DeclarationName Name = BaseCtor->getDeclName();
14302
14303 // Check to see if we already have a fake constructor for this inherited
14304 // constructor call.
14305 for (NamedDecl *Ctor : Derived->lookup(Name))
14306 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
14307 ->getInheritedConstructor()
14308 .getConstructor(),
14309 BaseCtor))
14310 return cast<CXXConstructorDecl>(Ctor);
14311
14312 DeclarationNameInfo NameInfo(Name, UsingLoc);
14313 TypeSourceInfo *TInfo =
14314 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
14315 FunctionProtoTypeLoc ProtoLoc =
14316 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
14317
14318 // Check the inherited constructor is valid and find the list of base classes
14319 // from which it was inherited.
14320 InheritedConstructorInfo ICI(*this, Loc, Shadow);
14321
14322 bool Constexpr = BaseCtor->isConstexpr() &&
14323 defaultedSpecialMemberIsConstexpr(
14324 *this, Derived, CXXSpecialMemberKind::DefaultConstructor,
14325 false, BaseCtor, &ICI);
14326
14327 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
14328 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
14329 BaseCtor->getExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
14330 /*isInline=*/true,
14331 /*isImplicitlyDeclared=*/true,
14332 Constexpr ? BaseCtor->getConstexprKind() : ConstexprSpecKind::Unspecified,
14333 InheritedConstructor(Shadow, BaseCtor),
14334 BaseCtor->getTrailingRequiresClause());
14335 if (Shadow->isInvalidDecl())
14336 DerivedCtor->setInvalidDecl();
14337
14338 // Build an unevaluated exception specification for this fake constructor.
14339 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
14340 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
14341 EPI.ExceptionSpec.Type = EST_Unevaluated;
14342 EPI.ExceptionSpec.SourceDecl = DerivedCtor;
14343 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
14344 FPT->getParamTypes(), EPI));
14345
14346 // Build the parameter declarations.
14347 SmallVector<ParmVarDecl *, 16> ParamDecls;
14348 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
14349 TypeSourceInfo *TInfo =
14350 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
14351 ParmVarDecl *PD = ParmVarDecl::Create(
14352 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
14353 FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr);
14354 PD->setScopeInfo(0, I);
14355 PD->setImplicit();
14356 // Ensure attributes are propagated onto parameters (this matters for
14357 // format, pass_object_size, ...).
14358 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
14359 ParamDecls.push_back(PD);
14360 ProtoLoc.setParam(I, PD);
14361 }
14362
14363 // Set up the new constructor.
14364 assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
14365 DerivedCtor->setAccess(BaseCtor->getAccess());
14366 DerivedCtor->setParams(ParamDecls);
14367 Derived->addDecl(DerivedCtor);
14368
14369 if (ShouldDeleteSpecialMember(DerivedCtor,
14370 CXXSpecialMemberKind::DefaultConstructor, &ICI))
14371 SetDeclDeleted(DerivedCtor, UsingLoc);
14372
14373 return DerivedCtor;
14374 }
14375
14376 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
14377 InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
14378 Ctor->getInheritedConstructor().getShadowDecl());
14379 ShouldDeleteSpecialMember(Ctor, CXXSpecialMemberKind::DefaultConstructor,
14380 &ICI,
14381 /*Diagnose*/ true);
14382 }
14383
14384 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
14385 CXXConstructorDecl *Constructor) {
14386 CXXRecordDecl *ClassDecl = Constructor->getParent();
14387 assert(Constructor->getInheritedConstructor() &&
14388 !Constructor->doesThisDeclarationHaveABody() &&
14389 !Constructor->isDeleted());
14390 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
14391 return;
14392
14393 // Initializations are performed "as if by a defaulted default constructor",
14394 // so enter the appropriate scope.
14395 SynthesizedFunctionScope Scope(*this, Constructor);
14396
14397 // The exception specification is needed because we are defining the
14398 // function.
14399 ResolveExceptionSpec(CurrentLocation,
14400 Constructor->getType()->castAs<FunctionProtoType>());
14401 MarkVTableUsed(CurrentLocation, ClassDecl);
14402
14403 // Add a context note for diagnostics produced after this point.
14404 Scope.addContextNote(CurrentLocation);
14405
14406 ConstructorUsingShadowDecl *Shadow =
14407 Constructor->getInheritedConstructor().getShadowDecl();
14408 CXXConstructorDecl *InheritedCtor =
14409 Constructor->getInheritedConstructor().getConstructor();
14410
14411 // [class.inhctor.init]p1:
14412 // initialization proceeds as if a defaulted default constructor is used to
14413 // initialize the D object and each base class subobject from which the
14414 // constructor was inherited
14415
14416 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
14417 CXXRecordDecl *RD = Shadow->getParent();
14418 SourceLocation InitLoc = Shadow->getLocation();
14419
14420 // Build explicit initializers for all base classes from which the
14421 // constructor was inherited.
14422 SmallVector<CXXCtorInitializer*, 8> Inits;
14423 for (bool VBase : {false, true}) {
14424 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
14425 if (B.isVirtual() != VBase)
14426 continue;
14427
14428 auto *BaseRD = B.getType()->getAsCXXRecordDecl();
14429 if (!BaseRD)
14430 continue;
14431
14432 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
14433 if (!BaseCtor.first)
14434 continue;
14435
14436 MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
14437 ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
14438 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
14439
14440 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
14441 Inits.push_back(new (Context) CXXCtorInitializer(
14442 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
14443 SourceLocation()));
14444 }
14445 }
14446
14447 // We now proceed as if for a defaulted default constructor, with the relevant
14448 // initializers replaced.
14449
14450 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
14451 Constructor->setInvalidDecl();
14452 return;
14453 }
14454
14455 Constructor->setBody(new (Context) CompoundStmt(InitLoc));
14456 Constructor->markUsed(Context);
14457
14458 if (ASTMutationListener *L = getASTMutationListener()) {
14459 L->CompletedImplicitDefinition(Constructor);
14460 }
14461
14462 DiagnoseUninitializedFields(*this, Constructor);
14463 }
14464
14465 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
14466 // C++ [class.dtor]p2:
14467 // If a class has no user-declared destructor, a destructor is
14468 // declared implicitly. An implicitly-declared destructor is an
14469 // inline public member of its class.
14470 assert(ClassDecl->needsImplicitDestructor());
14471
14472 DeclaringSpecialMember DSM(*this, ClassDecl,
14473 CXXSpecialMemberKind::Destructor);
14474 if (DSM.isAlreadyBeingDeclared())
14475 return nullptr;
14476
14477 bool Constexpr = defaultedSpecialMemberIsConstexpr(
14478 *this, ClassDecl, CXXSpecialMemberKind::Destructor, false);
14479
14480 // Create the actual destructor declaration.
14481 CanQualType ClassType = Context.getCanonicalTagType(ClassDecl);
14482 SourceLocation ClassLoc = ClassDecl->getLocation();
14483 DeclarationName Name
14484 = Context.DeclarationNames.getCXXDestructorName(ClassType);
14485 DeclarationNameInfo NameInfo(Name, ClassLoc);
14486 CXXDestructorDecl *Destructor = CXXDestructorDecl::Create(
14487 Context, ClassDecl, ClassLoc, NameInfo, QualType(), nullptr,
14488 getCurFPFeatures().isFPConstrained(),
14489 /*isInline=*/true,
14490 /*isImplicitlyDeclared=*/true,
14491 Constexpr ? ConstexprSpecKind::Constexpr
14492 : ConstexprSpecKind::Unspecified);
14493 Destructor->setAccess(AS_public);
14494 Destructor->setDefaulted();
14495
14496 setupImplicitSpecialMemberType(Destructor, Context.VoidTy, {});
14497
14498 if (getLangOpts().CUDA)
14499 CUDA().inferTargetForImplicitSpecialMember(
14500 ClassDecl, CXXSpecialMemberKind::Destructor, Destructor,
14501 /* ConstRHS */ false,
14502 /* Diagnose */ false);
14503
14504 // We don't need to use SpecialMemberIsTrivial here; triviality for
14505 // destructors is easy to compute.
14506 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
14507 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
14508 ClassDecl->hasTrivialDestructorForCall());
14509
14510 // Note that we have declared this destructor.
14511 ++getASTContext().NumImplicitDestructorsDeclared;
14512
14513 Scope *S = getScopeForContext(ClassDecl);
14514 CheckImplicitSpecialMemberDeclaration(S, Destructor);
14515
14516 // We can't check whether an implicit destructor is deleted before we complete
14517 // the definition of the class, because its validity depends on the alignment
14518 // of the class. We'll check this from ActOnFields once the class is complete.
14519 if (ClassDecl->isCompleteDefinition() &&
14520 ShouldDeleteSpecialMember(Destructor, CXXSpecialMemberKind::Destructor))
14521 SetDeclDeleted(Destructor, ClassLoc);
14522
14523 // Introduce this destructor into its scope.
14524 if (S)
14525 PushOnScopeChains(Destructor, S, false);
14526 ClassDecl->addDecl(Destructor);
14527
14528 return Destructor;
14529 }
14530
14531 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
14532 CXXDestructorDecl *Destructor) {
14533 assert((Destructor->isDefaulted() &&
14534 !Destructor->doesThisDeclarationHaveABody() &&
14535 !Destructor->isDeleted()) &&
14536 "DefineImplicitDestructor - call it for implicit default dtor");
14537 if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
14538 return;
14539
14540 CXXRecordDecl *ClassDecl = Destructor->getParent();
14541 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
14542
14543 SynthesizedFunctionScope Scope(*this, Destructor);
14544
14545 // The exception specification is needed because we are defining the
14546 // function.
14547 ResolveExceptionSpec(CurrentLocation,
14548 Destructor->getType()->castAs<FunctionProtoType>());
14549 MarkVTableUsed(CurrentLocation, ClassDecl);
14550
14551 // Add a context note for diagnostics produced after this point.
14552 Scope.addContextNote(CurrentLocation);
14553
14554 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
14555 Destructor->getParent());
14556
14557 if (CheckDestructor(Destructor)) {
14558 Destructor->setInvalidDecl();
14559 return;
14560 }
14561
14562 SourceLocation Loc = Destructor->getEndLoc().isValid()
14563 ? Destructor->getEndLoc()
14564 : Destructor->getLocation();
14565 Destructor->setBody(new (Context) CompoundStmt(Loc));
14566 Destructor->markUsed(Context);
14567
14568 if (ASTMutationListener *L = getASTMutationListener()) {
14569 L->CompletedImplicitDefinition(Destructor);
14570 }
14571 }
14572
14573 void Sema::CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
14574 CXXDestructorDecl *Destructor) {
14575 if (Destructor->isInvalidDecl())
14576 return;
14577
14578 CXXRecordDecl *ClassDecl = Destructor->getParent();
14579 assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&
14580 "implicit complete dtors unneeded outside MS ABI");
14581 assert(ClassDecl->getNumVBases() > 0 &&
14582 "complete dtor only exists for classes with vbases");
14583
14584 SynthesizedFunctionScope Scope(*this, Destructor);
14585
14586 // Add a context note for diagnostics produced after this point.
14587 Scope.addContextNote(CurrentLocation);
14588
14589 MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl);
14590 }
14591
14592 void Sema::ActOnFinishCXXMemberDecls() {
14593 // If the context is an invalid C++ class, just suppress these checks.
14594 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
14595 if (Record->isInvalidDecl()) {
14596 DelayedOverridingExceptionSpecChecks.clear();
14597 DelayedEquivalentExceptionSpecChecks.clear();
14598 return;
14599 }
14600 checkForMultipleExportedDefaultConstructors(*this, Record);
14601 }
14602 }
14603
14604 void Sema::ActOnFinishCXXNonNestedClass() {
14605 referenceDLLExportedClassMethods();
14606
14607 if (!DelayedDllExportMemberFunctions.empty()) {
14608 SmallVector<CXXMethodDecl*, 4> WorkList;
14609 std::swap(DelayedDllExportMemberFunctions, WorkList);
14610 for (CXXMethodDecl *M : WorkList) {
14611 DefineDefaultedFunction(*this, M, M->getLocation());
14612
14613 // Pass the method to the consumer to get emitted. This is not necessary
14614 // for explicit instantiation definitions, as they will get emitted
14615 // anyway.
14616 if (M->getParent()->getTemplateSpecializationKind() !=
14617 TSK_ExplicitInstantiationDefinition)
14618 ActOnFinishInlineFunctionDef(M);
14619 }
14620 }
14621 }
14622
14623 void Sema::referenceDLLExportedClassMethods() {
14624 if (!DelayedDllExportClasses.empty()) {
14625 // Calling ReferenceDllExportedMembers might cause the current function to
14626 // be called again, so use a local copy of DelayedDllExportClasses.
14627 SmallVector<CXXRecordDecl *, 4> WorkList;
14628 std::swap(DelayedDllExportClasses, WorkList);
14629 for (CXXRecordDecl *Class : WorkList)
14630 ReferenceDllExportedMembers(*this, Class);
14631 }
14632 }
14633
14634 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
14635 assert(getLangOpts().CPlusPlus11 &&
14636 "adjusting dtor exception specs was introduced in c++11");
14637
14638 if (Destructor->isDependentContext())
14639 return;
14640
14641 // C++11 [class.dtor]p3:
14642 // A declaration of a destructor that does not have an exception-
14643 // specification is implicitly considered to have the same exception-
14644 // specification as an implicit declaration.
14645 const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>();
14646 if (DtorType->hasExceptionSpec())
14647 return;
14648
14649 // Replace the destructor's type, building off the existing one. Fortunately,
14650 // the only thing of interest in the destructor type is its extended info.
14651 // The return and arguments are fixed.
14652 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
14653 EPI.ExceptionSpec.Type = EST_Unevaluated;
14654 EPI.ExceptionSpec.SourceDecl = Destructor;
14655 Destructor->setType(Context.getFunctionType(Context.VoidTy, {}, EPI));
14656
14657 // FIXME: If the destructor has a body that could throw, and the newly created
14658 // spec doesn't allow exceptions, we should emit a warning, because this
14659 // change in behavior can break conforming C++03 programs at runtime.
14660 // However, we don't have a body or an exception specification yet, so it
14661 // needs to be done somewhere else.
14662 }
14663
14664 namespace {
14665 /// An abstract base class for all helper classes used in building the
14666 // copy/move operators. These classes serve as factory functions and help us
14667 // avoid using the same Expr* in the AST twice.
14668 class ExprBuilder {
14669 ExprBuilder(const ExprBuilder&) = delete;
14670 ExprBuilder &operator=(const ExprBuilder&) = delete;
14671
14672 protected:
14673 static Expr *assertNotNull(Expr *E) {
14674 assert(E && "Expression construction must not fail.");
14675 return E;
14676 }
14677
14678 public:
14679 ExprBuilder() {}
14680 virtual ~ExprBuilder() {}
14681
14682 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
14683 };
14684
14685 class RefBuilder: public ExprBuilder {
14686 VarDecl *Var;
14687 QualType VarType;
14688
14689 public:
14690 Expr *build(Sema &S, SourceLocation Loc) const override {
14691 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));
14692 }
14693
14694 RefBuilder(VarDecl *Var, QualType VarType)
14695 : Var(Var), VarType(VarType) {}
14696 };
14697
14698 class ThisBuilder: public ExprBuilder {
14699 public:
14700 Expr *build(Sema &S, SourceLocation Loc) const override {
14701 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
14702 }
14703 };
14704
14705 class CastBuilder: public ExprBuilder {
14706 const ExprBuilder &Builder;
14707 QualType Type;
14708 ExprValueKind Kind;
14709 const CXXCastPath &Path;
14710
14711 public:
14712 Expr *build(Sema &S, SourceLocation Loc) const override {
14713 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
14714 CK_UncheckedDerivedToBase, Kind,
14715 &Path).get());
14716 }
14717
14718 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
14719 const CXXCastPath &Path)
14720 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
14721 };
14722
14723 class DerefBuilder: public ExprBuilder {
14724 const ExprBuilder &Builder;
14725
14726 public:
14727 Expr *build(Sema &S, SourceLocation Loc) const override {
14728 return assertNotNull(
14729 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
14730 }
14731
14732 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14733 };
14734
14735 class MemberBuilder: public ExprBuilder {
14736 const ExprBuilder &Builder;
14737 QualType Type;
14738 CXXScopeSpec SS;
14739 bool IsArrow;
14740 LookupResult &MemberLookup;
14741
14742 public:
14743 Expr *build(Sema &S, SourceLocation Loc) const override {
14744 return assertNotNull(S.BuildMemberReferenceExpr(
14745 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
14746 nullptr, MemberLookup, nullptr, nullptr).get());
14747 }
14748
14749 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
14750 LookupResult &MemberLookup)
14751 : Builder(Builder), Type(Type), IsArrow(IsArrow),
14752 MemberLookup(MemberLookup) {}
14753 };
14754
14755 class MoveCastBuilder: public ExprBuilder {
14756 const ExprBuilder &Builder;
14757
14758 public:
14759 Expr *build(Sema &S, SourceLocation Loc) const override {
14760 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
14761 }
14762
14763 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14764 };
14765
14766 class LvalueConvBuilder: public ExprBuilder {
14767 const ExprBuilder &Builder;
14768
14769 public:
14770 Expr *build(Sema &S, SourceLocation Loc) const override {
14771 return assertNotNull(
14772 S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
14773 }
14774
14775 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14776 };
14777
14778 class SubscriptBuilder: public ExprBuilder {
14779 const ExprBuilder &Base;
14780 const ExprBuilder &Index;
14781
14782 public:
14783 Expr *build(Sema &S, SourceLocation Loc) const override {
14784 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
14785 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
14786 }
14787
14788 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
14789 : Base(Base), Index(Index) {}
14790 };
14791
14792 } // end anonymous namespace
14793
14794 /// When generating a defaulted copy or move assignment operator, if a field
14795 /// should be copied with __builtin_memcpy rather than via explicit assignments,
14796 /// do so. This optimization only applies for arrays of scalars, and for arrays
14797 /// of class type where the selected copy/move-assignment operator is trivial.
14798 static StmtResult
14799 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
14800 const ExprBuilder &ToB, const ExprBuilder &FromB) {
14801 // Compute the size of the memory buffer to be copied.
14802 QualType SizeType = S.Context.getSizeType();
14803 llvm::APInt Size(S.Context.getTypeSize(SizeType),
14804 S.Context.getTypeSizeInChars(T).getQuantity());
14805
14806 // Take the address of the field references for "from" and "to". We
14807 // directly construct UnaryOperators here because semantic analysis
14808 // does not permit us to take the address of an xvalue.
14809 Expr *From = FromB.build(S, Loc);
14810 From = UnaryOperator::Create(
14811 S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()),
14812 VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
14813 Expr *To = ToB.build(S, Loc);
14814 To = UnaryOperator::Create(
14815 S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()),
14816 VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
14817
14818 bool NeedsCollectableMemCpy = false;
14819 if (auto *RD = T->getBaseElementTypeUnsafe()->getAsRecordDecl())
14820 NeedsCollectableMemCpy = RD->hasObjectMember();
14821
14822 // Create a reference to the __builtin_objc_memmove_collectable function
14823 StringRef MemCpyName = NeedsCollectableMemCpy ?
14824 "__builtin_objc_memmove_collectable" :
14825 "__builtin_memcpy";
14826 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
14827 Sema::LookupOrdinaryName);
14828 S.LookupName(R, S.TUScope, true);
14829
14830 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
14831 if (!MemCpy)
14832 // Something went horribly wrong earlier, and we will have complained
14833 // about it.
14834 return StmtError();
14835
14836 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
14837 VK_PRValue, Loc, nullptr);
14838 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
14839
14840 Expr *CallArgs[] = {
14841 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
14842 };
14843 ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
14844 Loc, CallArgs, Loc);
14845
14846 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
14847 return Call.getAs<Stmt>();
14848 }
14849
14850 /// Builds a statement that copies/moves the given entity from \p From to
14851 /// \c To.
14852 ///
14853 /// This routine is used to copy/move the members of a class with an
14854 /// implicitly-declared copy/move assignment operator. When the entities being
14855 /// copied are arrays, this routine builds for loops to copy them.
14856 ///
14857 /// \param S The Sema object used for type-checking.
14858 ///
14859 /// \param Loc The location where the implicit copy/move is being generated.
14860 ///
14861 /// \param T The type of the expressions being copied/moved. Both expressions
14862 /// must have this type.
14863 ///
14864 /// \param To The expression we are copying/moving to.
14865 ///
14866 /// \param From The expression we are copying/moving from.
14867 ///
14868 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
14869 /// Otherwise, it's a non-static member subobject.
14870 ///
14871 /// \param Copying Whether we're copying or moving.
14872 ///
14873 /// \param Depth Internal parameter recording the depth of the recursion.
14874 ///
14875 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
14876 /// if a memcpy should be used instead.
14877 static StmtResult
14878 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
14879 const ExprBuilder &To, const ExprBuilder &From,
14880 bool CopyingBaseSubobject, bool Copying,
14881 unsigned Depth = 0) {
14882 // C++11 [class.copy]p28:
14883 // Each subobject is assigned in the manner appropriate to its type:
14884 //
14885 // - if the subobject is of class type, as if by a call to operator= with
14886 // the subobject as the object expression and the corresponding
14887 // subobject of x as a single function argument (as if by explicit
14888 // qualification; that is, ignoring any possible virtual overriding
14889 // functions in more derived classes);
14890 //
14891 // C++03 [class.copy]p13:
14892 // - if the subobject is of class type, the copy assignment operator for
14893 // the class is used (as if by explicit qualification; that is,
14894 // ignoring any possible virtual overriding functions in more derived
14895 // classes);
14896 if (auto *ClassDecl = T->getAsCXXRecordDecl()) {
14897 // Look for operator=.
14898 DeclarationName Name
14899 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
14900 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
14901 S.LookupQualifiedName(OpLookup, ClassDecl, false);
14902
14903 // Prior to C++11, filter out any result that isn't a copy/move-assignment
14904 // operator.
14905 if (!S.getLangOpts().CPlusPlus11) {
14906 LookupResult::Filter F = OpLookup.makeFilter();
14907 while (F.hasNext()) {
14908 NamedDecl *D = F.next();
14909 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
14910 if (Method->isCopyAssignmentOperator() ||
14911 (!Copying && Method->isMoveAssignmentOperator()))
14912 continue;
14913
14914 F.erase();
14915 }
14916 F.done();
14917 }
14918
14919 // Suppress the protected check (C++ [class.protected]) for each of the
14920 // assignment operators we found. This strange dance is required when
14921 // we're assigning via a base classes's copy-assignment operator. To
14922 // ensure that we're getting the right base class subobject (without
14923 // ambiguities), we need to cast "this" to that subobject type; to
14924 // ensure that we don't go through the virtual call mechanism, we need
14925 // to qualify the operator= name with the base class (see below). However,
14926 // this means that if the base class has a protected copy assignment
14927 // operator, the protected member access check will fail. So, we
14928 // rewrite "protected" access to "public" access in this case, since we
14929 // know by construction that we're calling from a derived class.
14930 if (CopyingBaseSubobject) {
14931 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
14932 L != LEnd; ++L) {
14933 if (L.getAccess() == AS_protected)
14934 L.setAccess(AS_public);
14935 }
14936 }
14937
14938 // Create the nested-name-specifier that will be used to qualify the
14939 // reference to operator=; this is required to suppress the virtual
14940 // call mechanism.
14941 CXXScopeSpec SS;
14942 // FIXME: Don't canonicalize this.
14943 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
14944 SS.MakeTrivial(S.Context, NestedNameSpecifier(CanonicalT), Loc);
14945
14946 // Create the reference to operator=.
14947 ExprResult OpEqualRef
14948 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false,
14949 SS, /*TemplateKWLoc=*/SourceLocation(),
14950 /*FirstQualifierInScope=*/nullptr,
14951 OpLookup,
14952 /*TemplateArgs=*/nullptr, /*S*/nullptr,
14953 /*SuppressQualifierCheck=*/true);
14954 if (OpEqualRef.isInvalid())
14955 return StmtError();
14956
14957 // Build the call to the assignment operator.
14958
14959 Expr *FromInst = From.build(S, Loc);
14960 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
14961 OpEqualRef.getAs<Expr>(),
14962 Loc, FromInst, Loc);
14963 if (Call.isInvalid())
14964 return StmtError();
14965
14966 // If we built a call to a trivial 'operator=' while copying an array,
14967 // bail out. We'll replace the whole shebang with a memcpy.
14968 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
14969 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
14970 return StmtResult((Stmt*)nullptr);
14971
14972 // Convert to an expression-statement, and clean up any produced
14973 // temporaries.
14974 return S.ActOnExprStmt(Call);
14975 }
14976
14977 // - if the subobject is of scalar type, the built-in assignment
14978 // operator is used.
14979 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
14980 if (!ArrayTy) {
14981 ExprResult Assignment = S.CreateBuiltinBinOp(
14982 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
14983 if (Assignment.isInvalid())
14984 return StmtError();
14985 return S.ActOnExprStmt(Assignment);
14986 }
14987
14988 // - if the subobject is an array, each element is assigned, in the
14989 // manner appropriate to the element type;
14990
14991 // Construct a loop over the array bounds, e.g.,
14992 //
14993 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
14994 //
14995 // that will copy each of the array elements.
14996 QualType SizeType = S.Context.getSizeType();
14997
14998 // Create the iteration variable.
14999 IdentifierInfo *IterationVarName = nullptr;
15000 {
15001 SmallString<8> Str;
15002 llvm::raw_svector_ostream OS(Str);
15003 OS << "__i" << Depth;
15004 IterationVarName = &S.Context.Idents.get(OS.str());
15005 }
15006 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
15007 IterationVarName, SizeType,
15008 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
15009 SC_None);
15010
15011 // Initialize the iteration variable to zero.
15012 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
15013 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
15014
15015 // Creates a reference to the iteration variable.
15016 RefBuilder IterationVarRef(IterationVar, SizeType);
15017 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
15018
15019 // Create the DeclStmt that holds the iteration variable.
15020 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
15021
15022 // Subscript the "from" and "to" expressions with the iteration variable.
15023 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
15024 MoveCastBuilder FromIndexMove(FromIndexCopy);
15025 const ExprBuilder *FromIndex;
15026 if (Copying)
15027 FromIndex = &FromIndexCopy;
15028 else
15029 FromIndex = &FromIndexMove;
15030
15031 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
15032
15033 // Build the copy/move for an individual element of the array.
15034 StmtResult Copy =
15035 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
15036 ToIndex, *FromIndex, CopyingBaseSubobject,
15037 Copying, Depth + 1);
15038 // Bail out if copying fails or if we determined that we should use memcpy.
15039 if (Copy.isInvalid() || !Copy.get())
15040 return Copy;
15041
15042 // Create the comparison against the array bound.
15043 llvm::APInt Upper
15044 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
15045 Expr *Comparison = BinaryOperator::Create(
15046 S.Context, IterationVarRefRVal.build(S, Loc),
15047 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE,
15048 S.Context.BoolTy, VK_PRValue, OK_Ordinary, Loc,
15049 S.CurFPFeatureOverrides());
15050
15051 // Create the pre-increment of the iteration variable. We can determine
15052 // whether the increment will overflow based on the value of the array
15053 // bound.
15054 Expr *Increment = UnaryOperator::Create(
15055 S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue,
15056 OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides());
15057
15058 // Construct the loop that copies all elements of this array.
15059 return S.ActOnForStmt(
15060 Loc, Loc, InitStmt,
15061 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
15062 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
15063 }
15064
15065 static StmtResult
15066 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
15067 const ExprBuilder &To, const ExprBuilder &From,
15068 bool CopyingBaseSubobject, bool Copying) {
15069 // Maybe we should use a memcpy?
15070 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
15071 T.isTriviallyCopyableType(S.Context))
15072 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
15073
15074 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
15075 CopyingBaseSubobject,
15076 Copying, 0));
15077
15078 // If we ended up picking a trivial assignment operator for an array of a
15079 // non-trivially-copyable class type, just emit a memcpy.
15080 if (!Result.isInvalid() && !Result.get())
15081 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
15082
15083 return Result;
15084 }
15085
15086 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
15087 // Note: The following rules are largely analoguous to the copy
15088 // constructor rules. Note that virtual bases are not taken into account
15089 // for determining the argument type of the operator. Note also that
15090 // operators taking an object instead of a reference are allowed.
15091 assert(ClassDecl->needsImplicitCopyAssignment());
15092
15093 DeclaringSpecialMember DSM(*this, ClassDecl,
15094 CXXSpecialMemberKind::CopyAssignment);
15095 if (DSM.isAlreadyBeingDeclared())
15096 return nullptr;
15097
15098 QualType ArgType = Context.getTagType(ElaboratedTypeKeyword::None,
15099 /*Qualifier=*/std::nullopt, ClassDecl,
15100 /*OwnsTag=*/false);
15101 LangAS AS = getDefaultCXXMethodAddrSpace();
15102 if (AS != LangAS::Default)
15103 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
15104 QualType RetType = Context.getLValueReferenceType(ArgType);
15105 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
15106 if (Const)
15107 ArgType = ArgType.withConst();
15108
15109 ArgType = Context.getLValueReferenceType(ArgType);
15110
15111 bool Constexpr = defaultedSpecialMemberIsConstexpr(
15112 *this, ClassDecl, CXXSpecialMemberKind::CopyAssignment, Const);
15113
15114 // An implicitly-declared copy assignment operator is an inline public
15115 // member of its class.
15116 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
15117 SourceLocation ClassLoc = ClassDecl->getLocation();
15118 DeclarationNameInfo NameInfo(Name, ClassLoc);
15119 CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create(
15120 Context, ClassDecl, ClassLoc, NameInfo, QualType(),
15121 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
15122 getCurFPFeatures().isFPConstrained(),
15123 /*isInline=*/true,
15124 Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
15125 SourceLocation());
15126 CopyAssignment->setAccess(AS_public);
15127 CopyAssignment->setDefaulted();
15128 CopyAssignment->setImplicit();
15129
15130 setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
15131
15132 if (getLangOpts().CUDA)
15133 CUDA().inferTargetForImplicitSpecialMember(
15134 ClassDecl, CXXSpecialMemberKind::CopyAssignment, CopyAssignment,
15135 /* ConstRHS */ Const,
15136 /* Diagnose */ false);
15137
15138 // Add the parameter to the operator.
15139 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
15140 ClassLoc, ClassLoc,
15141 /*Id=*/nullptr, ArgType,
15142 /*TInfo=*/nullptr, SC_None,
15143 nullptr);
15144 CopyAssignment->setParams(FromParam);
15145
15146 CopyAssignment->setTrivial(
15147 ClassDecl->needsOverloadResolutionForCopyAssignment()
15148 ? SpecialMemberIsTrivial(CopyAssignment,
15149 CXXSpecialMemberKind::CopyAssignment)
15150 : ClassDecl->hasTrivialCopyAssignment());
15151
15152 // Note that we have added this copy-assignment operator.
15153 ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
15154
15155 Scope *S = getScopeForContext(ClassDecl);
15156 CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
15157
15158 if (ShouldDeleteSpecialMember(CopyAssignment,
15159 CXXSpecialMemberKind::CopyAssignment)) {
15160 ClassDecl->setImplicitCopyAssignmentIsDeleted();
15161 SetDeclDeleted(CopyAssignment, ClassLoc);
15162 }
15163
15164 if (S)
15165 PushOnScopeChains(CopyAssignment, S, false);
15166 ClassDecl->addDecl(CopyAssignment);
15167
15168 return CopyAssignment;
15169 }
15170
15171 /// Diagnose an implicit copy operation for a class which is odr-used, but
15172 /// which is deprecated because the class has a user-declared copy constructor,
15173 /// copy assignment operator, or destructor.
15174 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
15175 assert(CopyOp->isImplicit());
15176
15177 CXXRecordDecl *RD = CopyOp->getParent();
15178 CXXMethodDecl *UserDeclaredOperation = nullptr;
15179
15180 if (RD->hasUserDeclaredDestructor()) {
15181 UserDeclaredOperation = RD->getDestructor();
15182 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
15183 RD->hasUserDeclaredCopyConstructor()) {
15184 // Find any user-declared copy constructor.
15185 for (auto *I : RD->ctors()) {
15186 if (I->isCopyConstructor()) {
15187 UserDeclaredOperation = I;
15188 break;
15189 }
15190 }
15191 assert(UserDeclaredOperation);
15192 } else if (isa<CXXConstructorDecl>(CopyOp) &&
15193 RD->hasUserDeclaredCopyAssignment()) {
15194 // Find any user-declared move assignment operator.
15195 for (auto *I : RD->methods()) {
15196 if (I->isCopyAssignmentOperator()) {
15197 UserDeclaredOperation = I;
15198 break;
15199 }
15200 }
15201 assert(UserDeclaredOperation);
15202 }
15203
15204 if (UserDeclaredOperation) {
15205 bool UDOIsUserProvided = UserDeclaredOperation->isUserProvided();
15206 bool UDOIsDestructor = isa<CXXDestructorDecl>(UserDeclaredOperation);
15207 bool IsCopyAssignment = !isa<CXXConstructorDecl>(CopyOp);
15208 unsigned DiagID =
15209 (UDOIsUserProvided && UDOIsDestructor)
15210 ? diag::warn_deprecated_copy_with_user_provided_dtor
15211 : (UDOIsUserProvided && !UDOIsDestructor)
15212 ? diag::warn_deprecated_copy_with_user_provided_copy
15213 : (!UDOIsUserProvided && UDOIsDestructor)
15214 ? diag::warn_deprecated_copy_with_dtor
15215 : diag::warn_deprecated_copy;
15216 S.Diag(UserDeclaredOperation->getLocation(), DiagID)
15217 << RD << IsCopyAssignment;
15218 }
15219 }
15220
15221 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
15222 CXXMethodDecl *CopyAssignOperator) {
15223 assert((CopyAssignOperator->isDefaulted() &&
15224 CopyAssignOperator->isOverloadedOperator() &&
15225 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
15226 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
15227 !CopyAssignOperator->isDeleted()) &&
15228 "DefineImplicitCopyAssignment called for wrong function");
15229 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
15230 return;
15231
15232 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
15233 if (ClassDecl->isInvalidDecl()) {
15234 CopyAssignOperator->setInvalidDecl();
15235 return;
15236 }
15237
15238 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
15239
15240 // The exception specification is needed because we are defining the
15241 // function.
15242 ResolveExceptionSpec(CurrentLocation,
15243 CopyAssignOperator->getType()->castAs<FunctionProtoType>());
15244
15245 // Add a context note for diagnostics produced after this point.
15246 Scope.addContextNote(CurrentLocation);
15247
15248 // C++11 [class.copy]p18:
15249 // The [definition of an implicitly declared copy assignment operator] is
15250 // deprecated if the class has a user-declared copy constructor or a
15251 // user-declared destructor.
15252 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
15253 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
15254
15255 // C++0x [class.copy]p30:
15256 // The implicitly-defined or explicitly-defaulted copy assignment operator
15257 // for a non-union class X performs memberwise copy assignment of its
15258 // subobjects. The direct base classes of X are assigned first, in the
15259 // order of their declaration in the base-specifier-list, and then the
15260 // immediate non-static data members of X are assigned, in the order in
15261 // which they were declared in the class definition.
15262
15263 // The statements that form the synthesized function body.
15264 SmallVector<Stmt*, 8> Statements;
15265
15266 // The parameter for the "other" object, which we are copying from.
15267 ParmVarDecl *Other = CopyAssignOperator->getNonObjectParameter(0);
15268 Qualifiers OtherQuals = Other->getType().getQualifiers();
15269 QualType OtherRefType = Other->getType();
15270 if (OtherRefType->isLValueReferenceType()) {
15271 OtherRefType = OtherRefType->getPointeeType();
15272 OtherQuals = OtherRefType.getQualifiers();
15273 }
15274
15275 // Our location for everything implicitly-generated.
15276 SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
15277 ? CopyAssignOperator->getEndLoc()
15278 : CopyAssignOperator->getLocation();
15279
15280 // Builds a DeclRefExpr for the "other" object.
15281 RefBuilder OtherRef(Other, OtherRefType);
15282
15283 // Builds the function object parameter.
15284 std::optional<ThisBuilder> This;
15285 std::optional<DerefBuilder> DerefThis;
15286 std::optional<RefBuilder> ExplicitObject;
15287 bool IsArrow = false;
15288 QualType ObjectType;
15289 if (CopyAssignOperator->isExplicitObjectMemberFunction()) {
15290 ObjectType = CopyAssignOperator->getParamDecl(0)->getType();
15291 if (ObjectType->isReferenceType())
15292 ObjectType = ObjectType->getPointeeType();
15293 ExplicitObject.emplace(CopyAssignOperator->getParamDecl(0), ObjectType);
15294 } else {
15295 ObjectType = getCurrentThisType();
15296 This.emplace();
15297 DerefThis.emplace(*This);
15298 IsArrow = !LangOpts.HLSL;
15299 }
15300 ExprBuilder &ObjectParameter =
15301 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15302 : static_cast<ExprBuilder &>(*This);
15303
15304 // Assign base classes.
15305 bool Invalid = false;
15306 for (auto &Base : ClassDecl->bases()) {
15307 // Form the assignment:
15308 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
15309 QualType BaseType = Base.getType().getUnqualifiedType();
15310 if (!BaseType->isRecordType()) {
15311 Invalid = true;
15312 continue;
15313 }
15314
15315 CXXCastPath BasePath;
15316 BasePath.push_back(&Base);
15317
15318 // Construct the "from" expression, which is an implicit cast to the
15319 // appropriately-qualified base type.
15320 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
15321 VK_LValue, BasePath);
15322
15323 // Dereference "this".
15324 CastBuilder To(
15325 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15326 : static_cast<ExprBuilder &>(*DerefThis),
15327 Context.getQualifiedType(BaseType, ObjectType.getQualifiers()),
15328 VK_LValue, BasePath);
15329
15330 // Build the copy.
15331 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
15332 To, From,
15333 /*CopyingBaseSubobject=*/true,
15334 /*Copying=*/true);
15335 if (Copy.isInvalid()) {
15336 CopyAssignOperator->setInvalidDecl();
15337 return;
15338 }
15339
15340 // Success! Record the copy.
15341 Statements.push_back(Copy.getAs<Expr>());
15342 }
15343
15344 // Assign non-static members.
15345 for (auto *Field : ClassDecl->fields()) {
15346 // FIXME: We should form some kind of AST representation for the implied
15347 // memcpy in a union copy operation.
15348 if (Field->isUnnamedBitField() || Field->getParent()->isUnion())
15349 continue;
15350
15351 if (Field->isInvalidDecl()) {
15352 Invalid = true;
15353 continue;
15354 }
15355
15356 // Check for members of reference type; we can't copy those.
15357 if (Field->getType()->isReferenceType()) {
15358 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15359 << Context.getCanonicalTagType(ClassDecl) << 0
15360 << Field->getDeclName();
15361 Diag(Field->getLocation(), diag::note_declared_at);
15362 Invalid = true;
15363 continue;
15364 }
15365
15366 // Check for members of const-qualified, non-class type.
15367 QualType BaseType = Context.getBaseElementType(Field->getType());
15368 if (!BaseType->isRecordType() && BaseType.isConstQualified()) {
15369 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15370 << Context.getCanonicalTagType(ClassDecl) << 1
15371 << Field->getDeclName();
15372 Diag(Field->getLocation(), diag::note_declared_at);
15373 Invalid = true;
15374 continue;
15375 }
15376
15377 // Suppress assigning zero-width bitfields.
15378 if (Field->isZeroLengthBitField())
15379 continue;
15380
15381 QualType FieldType = Field->getType().getNonReferenceType();
15382 if (FieldType->isIncompleteArrayType()) {
15383 assert(ClassDecl->hasFlexibleArrayMember() &&
15384 "Incomplete array type is not valid");
15385 continue;
15386 }
15387
15388 // Build references to the field in the object we're copying from and to.
15389 CXXScopeSpec SS; // Intentionally empty
15390 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
15391 LookupMemberName);
15392 MemberLookup.addDecl(Field);
15393 MemberLookup.resolveKind();
15394
15395 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
15396 MemberBuilder To(ObjectParameter, ObjectType, IsArrow, MemberLookup);
15397 // Build the copy of this field.
15398 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
15399 To, From,
15400 /*CopyingBaseSubobject=*/false,
15401 /*Copying=*/true);
15402 if (Copy.isInvalid()) {
15403 CopyAssignOperator->setInvalidDecl();
15404 return;
15405 }
15406
15407 // Success! Record the copy.
15408 Statements.push_back(Copy.getAs<Stmt>());
15409 }
15410
15411 if (!Invalid) {
15412 // Add a "return *this;"
15413 Expr *ThisExpr =
15414 (ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15415 : LangOpts.HLSL ? static_cast<ExprBuilder &>(*This)
15416 : static_cast<ExprBuilder &>(*DerefThis))
15417 .build(*this, Loc);
15418 StmtResult Return = BuildReturnStmt(Loc, ThisExpr);
15419 if (Return.isInvalid())
15420 Invalid = true;
15421 else
15422 Statements.push_back(Return.getAs<Stmt>());
15423 }
15424
15425 if (Invalid) {
15426 CopyAssignOperator->setInvalidDecl();
15427 return;
15428 }
15429
15430 StmtResult Body;
15431 {
15432 CompoundScopeRAII CompoundScope(*this);
15433 Body = ActOnCompoundStmt(Loc, Loc, Statements,
15434 /*isStmtExpr=*/false);
15435 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
15436 }
15437 CopyAssignOperator->setBody(Body.getAs<Stmt>());
15438 CopyAssignOperator->markUsed(Context);
15439
15440 if (ASTMutationListener *L = getASTMutationListener()) {
15441 L->CompletedImplicitDefinition(CopyAssignOperator);
15442 }
15443 }
15444
15445 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
15446 assert(ClassDecl->needsImplicitMoveAssignment());
15447
15448 DeclaringSpecialMember DSM(*this, ClassDecl,
15449 CXXSpecialMemberKind::MoveAssignment);
15450 if (DSM.isAlreadyBeingDeclared())
15451 return nullptr;
15452
15453 // Note: The following rules are largely analoguous to the move
15454 // constructor rules.
15455
15456 QualType ArgType = Context.getTagType(ElaboratedTypeKeyword::None,
15457 /*Qualifier=*/std::nullopt, ClassDecl,
15458 /*OwnsTag=*/false);
15459 LangAS AS = getDefaultCXXMethodAddrSpace();
15460 if (AS != LangAS::Default)
15461 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
15462 QualType RetType = Context.getLValueReferenceType(ArgType);
15463 ArgType = Context.getRValueReferenceType(ArgType);
15464
15465 bool Constexpr = defaultedSpecialMemberIsConstexpr(
15466 *this, ClassDecl, CXXSpecialMemberKind::MoveAssignment, false);
15467
15468 // An implicitly-declared move assignment operator is an inline public
15469 // member of its class.
15470 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
15471 SourceLocation ClassLoc = ClassDecl->getLocation();
15472 DeclarationNameInfo NameInfo(Name, ClassLoc);
15473 CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create(
15474 Context, ClassDecl, ClassLoc, NameInfo, QualType(),
15475 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
15476 getCurFPFeatures().isFPConstrained(),
15477 /*isInline=*/true,
15478 Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
15479 SourceLocation());
15480 MoveAssignment->setAccess(AS_public);
15481 MoveAssignment->setDefaulted();
15482 MoveAssignment->setImplicit();
15483
15484 setupImplicitSpecialMemberType(MoveAssignment, RetType, ArgType);
15485
15486 if (getLangOpts().CUDA)
15487 CUDA().inferTargetForImplicitSpecialMember(
15488 ClassDecl, CXXSpecialMemberKind::MoveAssignment, MoveAssignment,
15489 /* ConstRHS */ false,
15490 /* Diagnose */ false);
15491
15492 // Add the parameter to the operator.
15493 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
15494 ClassLoc, ClassLoc,
15495 /*Id=*/nullptr, ArgType,
15496 /*TInfo=*/nullptr, SC_None,
15497 nullptr);
15498 MoveAssignment->setParams(FromParam);
15499
15500 MoveAssignment->setTrivial(
15501 ClassDecl->needsOverloadResolutionForMoveAssignment()
15502 ? SpecialMemberIsTrivial(MoveAssignment,
15503 CXXSpecialMemberKind::MoveAssignment)
15504 : ClassDecl->hasTrivialMoveAssignment());
15505
15506 // Note that we have added this copy-assignment operator.
15507 ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
15508
15509 Scope *S = getScopeForContext(ClassDecl);
15510 CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
15511
15512 if (ShouldDeleteSpecialMember(MoveAssignment,
15513 CXXSpecialMemberKind::MoveAssignment)) {
15514 ClassDecl->setImplicitMoveAssignmentIsDeleted();
15515 SetDeclDeleted(MoveAssignment, ClassLoc);
15516 }
15517
15518 if (S)
15519 PushOnScopeChains(MoveAssignment, S, false);
15520 ClassDecl->addDecl(MoveAssignment);
15521
15522 return MoveAssignment;
15523 }
15524
15525 /// Check if we're implicitly defining a move assignment operator for a class
15526 /// with virtual bases. Such a move assignment might move-assign the virtual
15527 /// base multiple times.
15528 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
15529 SourceLocation CurrentLocation) {
15530 assert(!Class->isDependentContext() && "should not define dependent move");
15531
15532 // Only a virtual base could get implicitly move-assigned multiple times.
15533 // Only a non-trivial move assignment can observe this. We only want to
15534 // diagnose if we implicitly define an assignment operator that assigns
15535 // two base classes, both of which move-assign the same virtual base.
15536 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
15537 Class->getNumBases() < 2)
15538 return;
15539
15540 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
15541 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
15542 VBaseMap VBases;
15543
15544 for (auto &BI : Class->bases()) {
15545 Worklist.push_back(&BI);
15546 while (!Worklist.empty()) {
15547 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
15548 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
15549
15550 // If the base has no non-trivial move assignment operators,
15551 // we don't care about moves from it.
15552 if (!Base->hasNonTrivialMoveAssignment())
15553 continue;
15554
15555 // If there's nothing virtual here, skip it.
15556 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
15557 continue;
15558
15559 // If we're not actually going to call a move assignment for this base,
15560 // or the selected move assignment is trivial, skip it.
15561 Sema::SpecialMemberOverloadResult SMOR =
15562 S.LookupSpecialMember(Base, CXXSpecialMemberKind::MoveAssignment,
15563 /*ConstArg*/ false, /*VolatileArg*/ false,
15564 /*RValueThis*/ true, /*ConstThis*/ false,
15565 /*VolatileThis*/ false);
15566 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
15567 !SMOR.getMethod()->isMoveAssignmentOperator())
15568 continue;
15569
15570 if (BaseSpec->isVirtual()) {
15571 // We're going to move-assign this virtual base, and its move
15572 // assignment operator is not trivial. If this can happen for
15573 // multiple distinct direct bases of Class, diagnose it. (If it
15574 // only happens in one base, we'll diagnose it when synthesizing
15575 // that base class's move assignment operator.)
15576 CXXBaseSpecifier *&Existing =
15577 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
15578 .first->second;
15579 if (Existing && Existing != &BI) {
15580 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
15581 << Class << Base;
15582 S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
15583 << (Base->getCanonicalDecl() ==
15584 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
15585 << Base << Existing->getType() << Existing->getSourceRange();
15586 S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
15587 << (Base->getCanonicalDecl() ==
15588 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
15589 << Base << BI.getType() << BaseSpec->getSourceRange();
15590
15591 // Only diagnose each vbase once.
15592 Existing = nullptr;
15593 }
15594 } else {
15595 // Only walk over bases that have defaulted move assignment operators.
15596 // We assume that any user-provided move assignment operator handles
15597 // the multiple-moves-of-vbase case itself somehow.
15598 if (!SMOR.getMethod()->isDefaulted())
15599 continue;
15600
15601 // We're going to move the base classes of Base. Add them to the list.
15602 llvm::append_range(Worklist, llvm::make_pointer_range(Base->bases()));
15603 }
15604 }
15605 }
15606 }
15607
15608 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
15609 CXXMethodDecl *MoveAssignOperator) {
15610 assert((MoveAssignOperator->isDefaulted() &&
15611 MoveAssignOperator->isOverloadedOperator() &&
15612 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
15613 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
15614 !MoveAssignOperator->isDeleted()) &&
15615 "DefineImplicitMoveAssignment called for wrong function");
15616 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
15617 return;
15618
15619 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
15620 if (ClassDecl->isInvalidDecl()) {
15621 MoveAssignOperator->setInvalidDecl();
15622 return;
15623 }
15624
15625 // C++0x [class.copy]p28:
15626 // The implicitly-defined or move assignment operator for a non-union class
15627 // X performs memberwise move assignment of its subobjects. The direct base
15628 // classes of X are assigned first, in the order of their declaration in the
15629 // base-specifier-list, and then the immediate non-static data members of X
15630 // are assigned, in the order in which they were declared in the class
15631 // definition.
15632
15633 // Issue a warning if our implicit move assignment operator will move
15634 // from a virtual base more than once.
15635 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
15636
15637 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
15638
15639 // The exception specification is needed because we are defining the
15640 // function.
15641 ResolveExceptionSpec(CurrentLocation,
15642 MoveAssignOperator->getType()->castAs<FunctionProtoType>());
15643
15644 // Add a context note for diagnostics produced after this point.
15645 Scope.addContextNote(CurrentLocation);
15646
15647 // The statements that form the synthesized function body.
15648 SmallVector<Stmt*, 8> Statements;
15649
15650 // The parameter for the "other" object, which we are move from.
15651 ParmVarDecl *Other = MoveAssignOperator->getNonObjectParameter(0);
15652 QualType OtherRefType =
15653 Other->getType()->castAs<RValueReferenceType>()->getPointeeType();
15654
15655 // Our location for everything implicitly-generated.
15656 SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
15657 ? MoveAssignOperator->getEndLoc()
15658 : MoveAssignOperator->getLocation();
15659
15660 // Builds a reference to the "other" object.
15661 RefBuilder OtherRef(Other, OtherRefType);
15662 // Cast to rvalue.
15663 MoveCastBuilder MoveOther(OtherRef);
15664
15665 // Builds the function object parameter.
15666 std::optional<ThisBuilder> This;
15667 std::optional<DerefBuilder> DerefThis;
15668 std::optional<RefBuilder> ExplicitObject;
15669 QualType ObjectType;
15670 bool IsArrow = false;
15671 if (MoveAssignOperator->isExplicitObjectMemberFunction()) {
15672 ObjectType = MoveAssignOperator->getParamDecl(0)->getType();
15673 if (ObjectType->isReferenceType())
15674 ObjectType = ObjectType->getPointeeType();
15675 ExplicitObject.emplace(MoveAssignOperator->getParamDecl(0), ObjectType);
15676 } else {
15677 ObjectType = getCurrentThisType();
15678 This.emplace();
15679 DerefThis.emplace(*This);
15680 IsArrow = !getLangOpts().HLSL;
15681 }
15682 ExprBuilder &ObjectParameter =
15683 ExplicitObject ? *ExplicitObject : static_cast<ExprBuilder &>(*This);
15684
15685 // Assign base classes.
15686 bool Invalid = false;
15687 for (auto &Base : ClassDecl->bases()) {
15688 // C++11 [class.copy]p28:
15689 // It is unspecified whether subobjects representing virtual base classes
15690 // are assigned more than once by the implicitly-defined copy assignment
15691 // operator.
15692 // FIXME: Do not assign to a vbase that will be assigned by some other base
15693 // class. For a move-assignment, this can result in the vbase being moved
15694 // multiple times.
15695
15696 // Form the assignment:
15697 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
15698 QualType BaseType = Base.getType().getUnqualifiedType();
15699 if (!BaseType->isRecordType()) {
15700 Invalid = true;
15701 continue;
15702 }
15703
15704 CXXCastPath BasePath;
15705 BasePath.push_back(&Base);
15706
15707 // Construct the "from" expression, which is an implicit cast to the
15708 // appropriately-qualified base type.
15709 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
15710
15711 // Implicitly cast "this" to the appropriately-qualified base type.
15712 // Dereference "this".
15713 CastBuilder To(
15714 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15715 : static_cast<ExprBuilder &>(*DerefThis),
15716 Context.getQualifiedType(BaseType, ObjectType.getQualifiers()),
15717 VK_LValue, BasePath);
15718
15719 // Build the move.
15720 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
15721 To, From,
15722 /*CopyingBaseSubobject=*/true,
15723 /*Copying=*/false);
15724 if (Move.isInvalid()) {
15725 MoveAssignOperator->setInvalidDecl();
15726 return;
15727 }
15728
15729 // Success! Record the move.
15730 Statements.push_back(Move.getAs<Expr>());
15731 }
15732
15733 // Assign non-static members.
15734 for (auto *Field : ClassDecl->fields()) {
15735 // FIXME: We should form some kind of AST representation for the implied
15736 // memcpy in a union copy operation.
15737 if (Field->isUnnamedBitField() || Field->getParent()->isUnion())
15738 continue;
15739
15740 if (Field->isInvalidDecl()) {
15741 Invalid = true;
15742 continue;
15743 }
15744
15745 // Check for members of reference type; we can't move those.
15746 if (Field->getType()->isReferenceType()) {
15747 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15748 << Context.getCanonicalTagType(ClassDecl) << 0
15749 << Field->getDeclName();
15750 Diag(Field->getLocation(), diag::note_declared_at);
15751 Invalid = true;
15752 continue;
15753 }
15754
15755 // Check for members of const-qualified, non-class type.
15756 QualType BaseType = Context.getBaseElementType(Field->getType());
15757 if (!BaseType->isRecordType() && BaseType.isConstQualified()) {
15758 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15759 << Context.getCanonicalTagType(ClassDecl) << 1
15760 << Field->getDeclName();
15761 Diag(Field->getLocation(), diag::note_declared_at);
15762 Invalid = true;
15763 continue;
15764 }
15765
15766 // Suppress assigning zero-width bitfields.
15767 if (Field->isZeroLengthBitField())
15768 continue;
15769
15770 QualType FieldType = Field->getType().getNonReferenceType();
15771 if (FieldType->isIncompleteArrayType()) {
15772 assert(ClassDecl->hasFlexibleArrayMember() &&
15773 "Incomplete array type is not valid");
15774 continue;
15775 }
15776
15777 // Build references to the field in the object we're copying from and to.
15778 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
15779 LookupMemberName);
15780 MemberLookup.addDecl(Field);
15781 MemberLookup.resolveKind();
15782 MemberBuilder From(MoveOther, OtherRefType,
15783 /*IsArrow=*/false, MemberLookup);
15784 MemberBuilder To(ObjectParameter, ObjectType, IsArrow, MemberLookup);
15785
15786 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
15787 "Member reference with rvalue base must be rvalue except for reference "
15788 "members, which aren't allowed for move assignment.");
15789
15790 // Build the move of this field.
15791 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
15792 To, From,
15793 /*CopyingBaseSubobject=*/false,
15794 /*Copying=*/false);
15795 if (Move.isInvalid()) {
15796 MoveAssignOperator->setInvalidDecl();
15797 return;
15798 }
15799
15800 // Success! Record the copy.
15801 Statements.push_back(Move.getAs<Stmt>());
15802 }
15803
15804 if (!Invalid) {
15805 // Add a "return *this;"
15806 Expr *ThisExpr =
15807 (ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15808 : LangOpts.HLSL ? static_cast<ExprBuilder &>(*This)
15809 : static_cast<ExprBuilder &>(*DerefThis))
15810 .build(*this, Loc);
15811
15812 StmtResult Return = BuildReturnStmt(Loc, ThisExpr);
15813 if (Return.isInvalid())
15814 Invalid = true;
15815 else
15816 Statements.push_back(Return.getAs<Stmt>());
15817 }
15818
15819 if (Invalid) {
15820 MoveAssignOperator->setInvalidDecl();
15821 return;
15822 }
15823
15824 StmtResult Body;
15825 {
15826 CompoundScopeRAII CompoundScope(*this);
15827 Body = ActOnCompoundStmt(Loc, Loc, Statements,
15828 /*isStmtExpr=*/false);
15829 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
15830 }
15831 MoveAssignOperator->setBody(Body.getAs<Stmt>());
15832 MoveAssignOperator->markUsed(Context);
15833
15834 if (ASTMutationListener *L = getASTMutationListener()) {
15835 L->CompletedImplicitDefinition(MoveAssignOperator);
15836 }
15837 }
15838
15839 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
15840 CXXRecordDecl *ClassDecl) {
15841 // C++ [class.copy]p4:
15842 // If the class definition does not explicitly declare a copy
15843 // constructor, one is declared implicitly.
15844 assert(ClassDecl->needsImplicitCopyConstructor());
15845
15846 DeclaringSpecialMember DSM(*this, ClassDecl,
15847 CXXSpecialMemberKind::CopyConstructor);
15848 if (DSM.isAlreadyBeingDeclared())
15849 return nullptr;
15850
15851 QualType ClassType = Context.getTagType(ElaboratedTypeKeyword::None,
15852 /*Qualifier=*/std::nullopt, ClassDecl,
15853 /*OwnsTag=*/false);
15854 QualType ArgType = ClassType;
15855 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
15856 if (Const)
15857 ArgType = ArgType.withConst();
15858
15859 LangAS AS = getDefaultCXXMethodAddrSpace();
15860 if (AS != LangAS::Default)
15861 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
15862
15863 ArgType = Context.getLValueReferenceType(ArgType);
15864
15865 bool Constexpr = defaultedSpecialMemberIsConstexpr(
15866 *this, ClassDecl, CXXSpecialMemberKind::CopyConstructor, Const);
15867
15868 DeclarationName Name
15869 = Context.DeclarationNames.getCXXConstructorName(
15870 Context.getCanonicalType(ClassType));
15871 SourceLocation ClassLoc = ClassDecl->getLocation();
15872 DeclarationNameInfo NameInfo(Name, ClassLoc);
15873
15874 // An implicitly-declared copy constructor is an inline public
15875 // member of its class.
15876 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
15877 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
15878 ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
15879 /*isInline=*/true,
15880 /*isImplicitlyDeclared=*/true,
15881 Constexpr ? ConstexprSpecKind::Constexpr
15882 : ConstexprSpecKind::Unspecified);
15883 CopyConstructor->setAccess(AS_public);
15884 CopyConstructor->setDefaulted();
15885
15886 setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
15887
15888 if (getLangOpts().CUDA)
15889 CUDA().inferTargetForImplicitSpecialMember(
15890 ClassDecl, CXXSpecialMemberKind::CopyConstructor, CopyConstructor,
15891 /* ConstRHS */ Const,
15892 /* Diagnose */ false);
15893
15894 // During template instantiation of special member functions we need a
15895 // reliable TypeSourceInfo for the parameter types in order to allow functions
15896 // to be substituted.
15897 TypeSourceInfo *TSI = nullptr;
15898 if (inTemplateInstantiation() && ClassDecl->isLambda())
15899 TSI = Context.getTrivialTypeSourceInfo(ArgType);
15900
15901 // Add the parameter to the constructor.
15902 ParmVarDecl *FromParam =
15903 ParmVarDecl::Create(Context, CopyConstructor, ClassLoc, ClassLoc,
15904 /*IdentifierInfo=*/nullptr, ArgType,
15905 /*TInfo=*/TSI, SC_None, nullptr);
15906 CopyConstructor->setParams(FromParam);
15907
15908 CopyConstructor->setTrivial(
15909 ClassDecl->needsOverloadResolutionForCopyConstructor()
15910 ? SpecialMemberIsTrivial(CopyConstructor,
15911 CXXSpecialMemberKind::CopyConstructor)
15912 : ClassDecl->hasTrivialCopyConstructor());
15913
15914 CopyConstructor->setTrivialForCall(
15915 ClassDecl->hasAttr<TrivialABIAttr>() ||
15916 (ClassDecl->needsOverloadResolutionForCopyConstructor()
15917 ? SpecialMemberIsTrivial(CopyConstructor,
15918 CXXSpecialMemberKind::CopyConstructor,
15919 TrivialABIHandling::ConsiderTrivialABI)
15920 : ClassDecl->hasTrivialCopyConstructorForCall()));
15921
15922 // Note that we have declared this constructor.
15923 ++getASTContext().NumImplicitCopyConstructorsDeclared;
15924
15925 Scope *S = getScopeForContext(ClassDecl);
15926 CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
15927
15928 if (ShouldDeleteSpecialMember(CopyConstructor,
15929 CXXSpecialMemberKind::CopyConstructor)) {
15930 ClassDecl->setImplicitCopyConstructorIsDeleted();
15931 SetDeclDeleted(CopyConstructor, ClassLoc);
15932 }
15933
15934 if (S)
15935 PushOnScopeChains(CopyConstructor, S, false);
15936 ClassDecl->addDecl(CopyConstructor);
15937
15938 return CopyConstructor;
15939 }
15940
15941 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
15942 CXXConstructorDecl *CopyConstructor) {
15943 assert((CopyConstructor->isDefaulted() &&
15944 CopyConstructor->isCopyConstructor() &&
15945 !CopyConstructor->doesThisDeclarationHaveABody() &&
15946 !CopyConstructor->isDeleted()) &&
15947 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
15948 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
15949 return;
15950
15951 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
15952 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
15953
15954 SynthesizedFunctionScope Scope(*this, CopyConstructor);
15955
15956 // The exception specification is needed because we are defining the
15957 // function.
15958 ResolveExceptionSpec(CurrentLocation,
15959 CopyConstructor->getType()->castAs<FunctionProtoType>());
15960 MarkVTableUsed(CurrentLocation, ClassDecl);
15961
15962 // Add a context note for diagnostics produced after this point.
15963 Scope.addContextNote(CurrentLocation);
15964
15965 // C++11 [class.copy]p7:
15966 // The [definition of an implicitly declared copy constructor] is
15967 // deprecated if the class has a user-declared copy assignment operator
15968 // or a user-declared destructor.
15969 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
15970 diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
15971
15972 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
15973 CopyConstructor->setInvalidDecl();
15974 } else {
15975 SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
15976 ? CopyConstructor->getEndLoc()
15977 : CopyConstructor->getLocation();
15978 Sema::CompoundScopeRAII CompoundScope(*this);
15979 CopyConstructor->setBody(
15980 ActOnCompoundStmt(Loc, Loc, {}, /*isStmtExpr=*/false).getAs<Stmt>());
15981 CopyConstructor->markUsed(Context);
15982 }
15983
15984 if (ASTMutationListener *L = getASTMutationListener()) {
15985 L->CompletedImplicitDefinition(CopyConstructor);
15986 }
15987 }
15988
15989 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
15990 CXXRecordDecl *ClassDecl) {
15991 assert(ClassDecl->needsImplicitMoveConstructor());
15992
15993 DeclaringSpecialMember DSM(*this, ClassDecl,
15994 CXXSpecialMemberKind::MoveConstructor);
15995 if (DSM.isAlreadyBeingDeclared())
15996 return nullptr;
15997
15998 QualType ClassType = Context.getTagType(ElaboratedTypeKeyword::None,
15999 /*Qualifier=*/std::nullopt, ClassDecl,
16000 /*OwnsTag=*/false);
16001
16002 QualType ArgType = ClassType;
16003 LangAS AS = getDefaultCXXMethodAddrSpace();
16004 if (AS != LangAS::Default)
16005 ArgType = Context.getAddrSpaceQualType(ClassType, AS);
16006 ArgType = Context.getRValueReferenceType(ArgType);
16007
16008 bool Constexpr = defaultedSpecialMemberIsConstexpr(
16009 *this, ClassDecl, CXXSpecialMemberKind::MoveConstructor, false);
16010
16011 DeclarationName Name
16012 = Context.DeclarationNames.getCXXConstructorName(
16013 Context.getCanonicalType(ClassType));
16014 SourceLocation ClassLoc = ClassDecl->getLocation();
16015 DeclarationNameInfo NameInfo(Name, ClassLoc);
16016
16017 // C++11 [class.copy]p11:
16018 // An implicitly-declared copy/move constructor is an inline public
16019 // member of its class.
16020 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
16021 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
16022 ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
16023 /*isInline=*/true,
16024 /*isImplicitlyDeclared=*/true,
16025 Constexpr ? ConstexprSpecKind::Constexpr
16026 : ConstexprSpecKind::Unspecified);
16027 MoveConstructor->setAccess(AS_public);
16028 MoveConstructor->setDefaulted();
16029
16030 setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
16031
16032 if (getLangOpts().CUDA)
16033 CUDA().inferTargetForImplicitSpecialMember(
16034 ClassDecl, CXXSpecialMemberKind::MoveConstructor, MoveConstructor,
16035 /* ConstRHS */ false,
16036 /* Diagnose */ false);
16037
16038 // Add the parameter to the constructor.
16039 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
16040 ClassLoc, ClassLoc,
16041 /*IdentifierInfo=*/nullptr,
16042 ArgType, /*TInfo=*/nullptr,
16043 SC_None, nullptr);
16044 MoveConstructor->setParams(FromParam);
16045
16046 MoveConstructor->setTrivial(
16047 ClassDecl->needsOverloadResolutionForMoveConstructor()
16048 ? SpecialMemberIsTrivial(MoveConstructor,
16049 CXXSpecialMemberKind::MoveConstructor)
16050 : ClassDecl->hasTrivialMoveConstructor());
16051
16052 MoveConstructor->setTrivialForCall(
16053 ClassDecl->hasAttr<TrivialABIAttr>() ||
16054 (ClassDecl->needsOverloadResolutionForMoveConstructor()
16055 ? SpecialMemberIsTrivial(MoveConstructor,
16056 CXXSpecialMemberKind::MoveConstructor,
16057 TrivialABIHandling::ConsiderTrivialABI)
16058 : ClassDecl->hasTrivialMoveConstructorForCall()));
16059
16060 // Note that we have declared this constructor.
16061 ++getASTContext().NumImplicitMoveConstructorsDeclared;
16062
16063 Scope *S = getScopeForContext(ClassDecl);
16064 CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
16065
16066 if (ShouldDeleteSpecialMember(MoveConstructor,
16067 CXXSpecialMemberKind::MoveConstructor)) {
16068 ClassDecl->setImplicitMoveConstructorIsDeleted();
16069 SetDeclDeleted(MoveConstructor, ClassLoc);
16070 }
16071
16072 if (S)
16073 PushOnScopeChains(MoveConstructor, S, false);
16074 ClassDecl->addDecl(MoveConstructor);
16075
16076 return MoveConstructor;
16077 }
16078
16079 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
16080 CXXConstructorDecl *MoveConstructor) {
16081 assert((MoveConstructor->isDefaulted() &&
16082 MoveConstructor->isMoveConstructor() &&
16083 !MoveConstructor->doesThisDeclarationHaveABody() &&
16084 !MoveConstructor->isDeleted()) &&
16085 "DefineImplicitMoveConstructor - call it for implicit move ctor");
16086 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
16087 return;
16088
16089 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
16090 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
16091
16092 SynthesizedFunctionScope Scope(*this, MoveConstructor);
16093
16094 // The exception specification is needed because we are defining the
16095 // function.
16096 ResolveExceptionSpec(CurrentLocation,
16097 MoveConstructor->getType()->castAs<FunctionProtoType>());
16098 MarkVTableUsed(CurrentLocation, ClassDecl);
16099
16100 // Add a context note for diagnostics produced after this point.
16101 Scope.addContextNote(CurrentLocation);
16102
16103 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
16104 MoveConstructor->setInvalidDecl();
16105 } else {
16106 SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
16107 ? MoveConstructor->getEndLoc()
16108 : MoveConstructor->getLocation();
16109 Sema::CompoundScopeRAII CompoundScope(*this);
16110 MoveConstructor->setBody(
16111 ActOnCompoundStmt(Loc, Loc, {}, /*isStmtExpr=*/false).getAs<Stmt>());
16112 MoveConstructor->markUsed(Context);
16113 }
16114
16115 if (ASTMutationListener *L = getASTMutationListener()) {
16116 L->CompletedImplicitDefinition(MoveConstructor);
16117 }
16118 }
16119
16120 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
16121 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
16122 }
16123
16124 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
16125 SourceLocation CurrentLocation,
16126 CXXConversionDecl *Conv) {
16127 SynthesizedFunctionScope Scope(*this, Conv);
16128 assert(!Conv->getReturnType()->isUndeducedType());
16129
16130 QualType ConvRT = Conv->getType()->castAs<FunctionType>()->getReturnType();
16131 CallingConv CC =
16132 ConvRT->getPointeeType()->castAs<FunctionType>()->getCallConv();
16133
16134 CXXRecordDecl *Lambda = Conv->getParent();
16135 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
16136 FunctionDecl *Invoker =
16137 CallOp->hasCXXExplicitFunctionObjectParameter() || CallOp->isStatic()
16138 ? CallOp
16139 : Lambda->getLambdaStaticInvoker(CC);
16140
16141 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
16142 CallOp = InstantiateFunctionDeclaration(
16143 CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
16144 if (!CallOp)
16145 return;
16146
16147 if (CallOp != Invoker) {
16148 Invoker = InstantiateFunctionDeclaration(
16149 Invoker->getDescribedFunctionTemplate(), TemplateArgs,
16150 CurrentLocation);
16151 if (!Invoker)
16152 return;
16153 }
16154 }
16155
16156 if (CallOp->isInvalidDecl())
16157 return;
16158
16159 // Mark the call operator referenced (and add to pending instantiations
16160 // if necessary).
16161 // For both the conversion and static-invoker template specializations
16162 // we construct their body's in this function, so no need to add them
16163 // to the PendingInstantiations.
16164 MarkFunctionReferenced(CurrentLocation, CallOp);
16165
16166 if (Invoker != CallOp) {
16167 // Fill in the __invoke function with a dummy implementation. IR generation
16168 // will fill in the actual details. Update its type in case it contained
16169 // an 'auto'.
16170 Invoker->markUsed(Context);
16171 Invoker->setReferenced();
16172 Invoker->setType(Conv->getReturnType()->getPointeeType());
16173 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
16174 }
16175
16176 // Construct the body of the conversion function { return __invoke; }.
16177 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), VK_LValue,
16178 Conv->getLocation());
16179 assert(FunctionRef && "Can't refer to __invoke function?");
16180 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
16181 Conv->setBody(CompoundStmt::Create(Context, Return, FPOptionsOverride(),
16182 Conv->getLocation(), Conv->getLocation()));
16183 Conv->markUsed(Context);
16184 Conv->setReferenced();
16185
16186 if (ASTMutationListener *L = getASTMutationListener()) {
16187 L->CompletedImplicitDefinition(Conv);
16188 if (Invoker != CallOp)
16189 L->CompletedImplicitDefinition(Invoker);
16190 }
16191 }
16192
16193 void Sema::DefineImplicitLambdaToBlockPointerConversion(
16194 SourceLocation CurrentLocation, CXXConversionDecl *Conv) {
16195 assert(!Conv->getParent()->isGenericLambda());
16196
16197 SynthesizedFunctionScope Scope(*this, Conv);
16198
16199 // Copy-initialize the lambda object as needed to capture it.
16200 Expr *This = ActOnCXXThis(CurrentLocation).get();
16201 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
16202
16203 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
16204 Conv->getLocation(),
16205 Conv, DerefThis);
16206
16207 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
16208 // behavior. Note that only the general conversion function does this
16209 // (since it's unusable otherwise); in the case where we inline the
16210 // block literal, it has block literal lifetime semantics.
16211 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
16212 BuildBlock = ImplicitCastExpr::Create(
16213 Context, BuildBlock.get()->getType(), CK_CopyAndAutoreleaseBlockObject,
16214 BuildBlock.get(), nullptr, VK_PRValue, FPOptionsOverride());
16215
16216 if (BuildBlock.isInvalid()) {
16217 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
16218 Conv->setInvalidDecl();
16219 return;
16220 }
16221
16222 // Create the return statement that returns the block from the conversion
16223 // function.
16224 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
16225 if (Return.isInvalid()) {
16226 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
16227 Conv->setInvalidDecl();
16228 return;
16229 }
16230
16231 // Set the body of the conversion function.
16232 Stmt *ReturnS = Return.get();
16233 Conv->setBody(CompoundStmt::Create(Context, ReturnS, FPOptionsOverride(),
16234 Conv->getLocation(), Conv->getLocation()));
16235 Conv->markUsed(Context);
16236
16237 // We're done; notify the mutation listener, if any.
16238 if (ASTMutationListener *L = getASTMutationListener()) {
16239 L->CompletedImplicitDefinition(Conv);
16240 }
16241 }
16242
16243 /// Determine whether the given list arguments contains exactly one
16244 /// "real" (non-default) argument.
16245 static bool hasOneRealArgument(MultiExprArg Args) {
16246 switch (Args.size()) {
16247 case 0:
16248 return false;
16249
16250 default:
16251 if (!Args[1]->isDefaultArgument())
16252 return false;
16253
16254 [[fallthrough]];
16255 case 1:
16256 return !Args[0]->isDefaultArgument();
16257 }
16258
16259 return false;
16260 }
16261
16262 ExprResult Sema::BuildCXXConstructExpr(
16263 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
16264 CXXConstructorDecl *Constructor, MultiExprArg ExprArgs,
16265 bool HadMultipleCandidates, bool IsListInitialization,
16266 bool IsStdInitListInitialization, bool RequiresZeroInit,
16267 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16268 bool Elidable = false;
16269
16270 // C++0x [class.copy]p34:
16271 // When certain criteria are met, an implementation is allowed to
16272 // omit the copy/move construction of a class object, even if the
16273 // copy/move constructor and/or destructor for the object have
16274 // side effects. [...]
16275 // - when a temporary class object that has not been bound to a
16276 // reference (12.2) would be copied/moved to a class object
16277 // with the same cv-unqualified type, the copy/move operation
16278 // can be omitted by constructing the temporary object
16279 // directly into the target of the omitted copy/move
16280 if (ConstructKind == CXXConstructionKind::Complete && Constructor &&
16281 // FIXME: Converting constructors should also be accepted.
16282 // But to fix this, the logic that digs down into a CXXConstructExpr
16283 // to find the source object needs to handle it.
16284 // Right now it assumes the source object is passed directly as the
16285 // first argument.
16286 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
16287 Expr *SubExpr = ExprArgs[0];
16288 // FIXME: Per above, this is also incorrect if we want to accept
16289 // converting constructors, as isTemporaryObject will
16290 // reject temporaries with different type from the
16291 // CXXRecord itself.
16292 Elidable = SubExpr->isTemporaryObject(
16293 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
16294 }
16295
16296 return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
16297 FoundDecl, Constructor,
16298 Elidable, ExprArgs, HadMultipleCandidates,
16299 IsListInitialization,
16300 IsStdInitListInitialization, RequiresZeroInit,
16301 ConstructKind, ParenRange);
16302 }
16303
16304 ExprResult Sema::BuildCXXConstructExpr(
16305 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
16306 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg ExprArgs,
16307 bool HadMultipleCandidates, bool IsListInitialization,
16308 bool IsStdInitListInitialization, bool RequiresZeroInit,
16309 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16310 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
16311 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
16312 // The only way to get here is if we did overload resolution to find the
16313 // shadow decl, so we don't need to worry about re-checking the trailing
16314 // requires clause.
16315 if (DiagnoseUseOfOverloadedDecl(Constructor, ConstructLoc))
16316 return ExprError();
16317 }
16318
16319 return BuildCXXConstructExpr(
16320 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
16321 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
16322 RequiresZeroInit, ConstructKind, ParenRange);
16323 }
16324
16325 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
16326 /// including handling of its default argument expressions.
16327 ExprResult Sema::BuildCXXConstructExpr(
16328 SourceLocation ConstructLoc, QualType DeclInitType,
16329 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg ExprArgs,
16330 bool HadMultipleCandidates, bool IsListInitialization,
16331 bool IsStdInitListInitialization, bool RequiresZeroInit,
16332 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16333 assert(declaresSameEntity(
16334 Constructor->getParent(),
16335 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
16336 "given constructor for wrong type");
16337 MarkFunctionReferenced(ConstructLoc, Constructor);
16338 if (getLangOpts().CUDA && !CUDA().CheckCall(ConstructLoc, Constructor))
16339 return ExprError();
16340
16341 return CheckForImmediateInvocation(
16342 CXXConstructExpr::Create(
16343 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
16344 HadMultipleCandidates, IsListInitialization,
16345 IsStdInitListInitialization, RequiresZeroInit,
16346 static_cast<CXXConstructionKind>(ConstructKind), ParenRange),
16347 Constructor);
16348 }
16349
16350 void Sema::FinalizeVarWithDestructor(VarDecl *VD, CXXRecordDecl *ClassDecl) {
16351 if (VD->isInvalidDecl()) return;
16352 // If initializing the variable failed, don't also diagnose problems with
16353 // the destructor, they're likely related.
16354 if (VD->getInit() && VD->getInit()->containsErrors())
16355 return;
16356
16357 ClassDecl = ClassDecl->getDefinitionOrSelf();
16358 if (ClassDecl->isInvalidDecl()) return;
16359 if (ClassDecl->hasIrrelevantDestructor()) return;
16360 if (ClassDecl->isDependentContext()) return;
16361
16362 if (VD->isNoDestroy(getASTContext()))
16363 return;
16364
16365 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
16366 // The result of `LookupDestructor` might be nullptr if the destructor is
16367 // invalid, in which case it is marked as `IneligibleOrNotSelected` and
16368 // will not be selected by `CXXRecordDecl::getDestructor()`.
16369 if (!Destructor)
16370 return;
16371 // If this is an array, we'll require the destructor during initialization, so
16372 // we can skip over this. We still want to emit exit-time destructor warnings
16373 // though.
16374 if (!VD->getType()->isArrayType()) {
16375 MarkFunctionReferenced(VD->getLocation(), Destructor);
16376 CheckDestructorAccess(VD->getLocation(), Destructor,
16377 PDiag(diag::err_access_dtor_var)
16378 << VD->getDeclName() << VD->getType());
16379 DiagnoseUseOfDecl(Destructor, VD->getLocation());
16380 }
16381
16382 if (Destructor->isTrivial()) return;
16383
16384 // If the destructor is constexpr, check whether the variable has constant
16385 // destruction now.
16386 if (Destructor->isConstexpr()) {
16387 bool HasConstantInit = false;
16388 if (VD->getInit() && !VD->getInit()->isValueDependent())
16389 HasConstantInit = VD->evaluateValue();
16390 SmallVector<PartialDiagnosticAt, 8> Notes;
16391 if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() &&
16392 HasConstantInit) {
16393 Diag(VD->getLocation(),
16394 diag::err_constexpr_var_requires_const_destruction) << VD;
16395 for (const PartialDiagnosticAt &Note : Notes)
16396 Diag(Note.first, Note.second);
16397 }
16398 }
16399
16400 if (!VD->hasGlobalStorage() || !VD->needsDestruction(Context))
16401 return;
16402
16403 // Emit warning for non-trivial dtor in global scope (a real global,
16404 // class-static, function-static).
16405 if (!VD->hasAttr<AlwaysDestroyAttr>())
16406 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
16407
16408 // TODO: this should be re-enabled for static locals by !CXAAtExit
16409 if (!VD->isStaticLocal())
16410 Diag(VD->getLocation(), diag::warn_global_destructor);
16411 }
16412
16413 bool Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
16414 QualType DeclInitType, MultiExprArg ArgsPtr,
16415 SourceLocation Loc,
16416 SmallVectorImpl<Expr *> &ConvertedArgs,
16417 bool AllowExplicit,
16418 bool IsListInitialization) {
16419 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
16420 unsigned NumArgs = ArgsPtr.size();
16421 Expr **Args = ArgsPtr.data();
16422
16423 const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>();
16424 unsigned NumParams = Proto->getNumParams();
16425
16426 // If too few arguments are available, we'll fill in the rest with defaults.
16427 if (NumArgs < NumParams)
16428 ConvertedArgs.reserve(NumParams);
16429 else
16430 ConvertedArgs.reserve(NumArgs);
16431
16432 VariadicCallType CallType = Proto->isVariadic()
16433 ? VariadicCallType::Constructor
16434 : VariadicCallType::DoesNotApply;
16435 SmallVector<Expr *, 8> AllArgs;
16436 bool Invalid = GatherArgumentsForCall(
16437 Loc, Constructor, Proto, 0, llvm::ArrayRef(Args, NumArgs), AllArgs,
16438 CallType, AllowExplicit, IsListInitialization);
16439 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
16440
16441 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
16442
16443 CheckConstructorCall(Constructor, DeclInitType, llvm::ArrayRef(AllArgs),
16444 Proto, Loc);
16445
16446 return Invalid;
16447 }
16448
16449 TypeAwareAllocationMode Sema::ShouldUseTypeAwareOperatorNewOrDelete() const {
16450 bool SeenTypedOperators = Context.hasSeenTypeAwareOperatorNewOrDelete();
16451 return typeAwareAllocationModeFromBool(SeenTypedOperators);
16452 }
16453
16454 FunctionDecl *
16455 Sema::BuildTypeAwareUsualDelete(FunctionTemplateDecl *FnTemplateDecl,
16456 QualType DeallocType, SourceLocation Loc) {
16457 if (DeallocType.isNull())
16458 return nullptr;
16459
16460 FunctionDecl *FnDecl = FnTemplateDecl->getTemplatedDecl();
16461 if (!FnDecl->isTypeAwareOperatorNewOrDelete())
16462 return nullptr;
16463
16464 if (FnDecl->isVariadic())
16465 return nullptr;
16466
16467 unsigned NumParams = FnDecl->getNumParams();
16468 constexpr unsigned RequiredParameterCount =
16469 FunctionDecl::RequiredTypeAwareDeleteParameterCount;
16470 // A usual deallocation function has no placement parameters
16471 if (NumParams != RequiredParameterCount)
16472 return nullptr;
16473
16474 // A type aware allocation is only usual if the only dependent parameter is
16475 // the first parameter.
16476 if (llvm::any_of(FnDecl->parameters().drop_front(),
16477 [](const ParmVarDecl *ParamDecl) {
16478 return ParamDecl->getType()->isDependentType();
16479 }))
16480 return nullptr;
16481
16482 QualType SpecializedTypeIdentity = tryBuildStdTypeIdentity(DeallocType, Loc);
16483 if (SpecializedTypeIdentity.isNull())
16484 return nullptr;
16485
16486 SmallVector<QualType, RequiredParameterCount> ArgTypes;
16487 ArgTypes.reserve(NumParams);
16488
16489 // The first parameter to a type aware operator delete is by definition the
16490 // type-identity argument, so we explicitly set this to the target
16491 // type-identity type, the remaining usual parameters should then simply match
16492 // the type declared in the function template.
16493 ArgTypes.push_back(SpecializedTypeIdentity);
16494 for (unsigned ParamIdx = 1; ParamIdx < RequiredParameterCount; ++ParamIdx)
16495 ArgTypes.push_back(FnDecl->getParamDecl(ParamIdx)->getType());
16496
16497 FunctionProtoType::ExtProtoInfo EPI;
16498 QualType ExpectedFunctionType =
16499 Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
16500 sema::TemplateDeductionInfo Info(Loc);
16501 FunctionDecl *Result;
16502 if (DeduceTemplateArguments(FnTemplateDecl, nullptr, ExpectedFunctionType,
16503 Result, Info) != TemplateDeductionResult::Success)
16504 return nullptr;
16505 return Result;
16506 }
16507
16508 static inline bool
16509 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
16510 const FunctionDecl *FnDecl) {
16511 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
16512 if (isa<NamespaceDecl>(DC)) {
16513 return SemaRef.Diag(FnDecl->getLocation(),
16514 diag::err_operator_new_delete_declared_in_namespace)
16515 << FnDecl->getDeclName();
16516 }
16517
16518 if (isa<TranslationUnitDecl>(DC) &&
16519 FnDecl->getStorageClass() == SC_Static) {
16520 return SemaRef.Diag(FnDecl->getLocation(),
16521 diag::err_operator_new_delete_declared_static)
16522 << FnDecl->getDeclName();
16523 }
16524
16525 return false;
16526 }
16527
16528 static CanQualType RemoveAddressSpaceFromPtr(Sema &SemaRef,
16529 const PointerType *PtrTy) {
16530 auto &Ctx = SemaRef.Context;
16531 Qualifiers PtrQuals = PtrTy->getPointeeType().getQualifiers();
16532 PtrQuals.removeAddressSpace();
16533 return Ctx.getPointerType(Ctx.getCanonicalType(Ctx.getQualifiedType(
16534 PtrTy->getPointeeType().getUnqualifiedType(), PtrQuals)));
16535 }
16536
16537 enum class AllocationOperatorKind { New, Delete };
16538
16539 static bool IsPotentiallyTypeAwareOperatorNewOrDelete(Sema &SemaRef,
16540 const FunctionDecl *FD,
16541 bool *WasMalformed) {
16542 const Decl *MalformedDecl = nullptr;
16543 if (FD->getNumParams() > 0 &&
16544 SemaRef.isStdTypeIdentity(FD->getParamDecl(0)->getType(),
16545 /*TypeArgument=*/nullptr, &MalformedDecl))
16546 return true;
16547
16548 if (!MalformedDecl)
16549 return false;
16550
16551 if (WasMalformed)
16552 *WasMalformed = true;
16553
16554 return true;
16555 }
16556
16557 static bool isDestroyingDeleteT(QualType Type) {
16558 auto *RD = Type->getAsCXXRecordDecl();
16559 return RD && RD->isInStdNamespace() && RD->getIdentifier() &&
16560 RD->getIdentifier()->isStr("destroying_delete_t");
16561 }
16562
16563 static bool IsPotentiallyDestroyingOperatorDelete(Sema &SemaRef,
16564 const FunctionDecl *FD) {
16565 // C++ P0722:
16566 // Within a class C, a single object deallocation function with signature
16567 // (T, std::destroying_delete_t, <more params>)
16568 // is a destroying operator delete.
16569 bool IsPotentiallyTypeAware = IsPotentiallyTypeAwareOperatorNewOrDelete(
16570 SemaRef, FD, /*WasMalformed=*/nullptr);
16571 unsigned DestroyingDeleteIdx = IsPotentiallyTypeAware + /* address */ 1;
16572 return isa<CXXMethodDecl>(FD) && FD->getOverloadedOperator() == OO_Delete &&
16573 FD->getNumParams() > DestroyingDeleteIdx &&
16574 isDestroyingDeleteT(FD->getParamDecl(DestroyingDeleteIdx)->getType());
16575 }
16576
16577 static inline bool CheckOperatorNewDeleteTypes(
16578 Sema &SemaRef, FunctionDecl *FnDecl, AllocationOperatorKind OperatorKind,
16579 CanQualType ExpectedResultType, CanQualType ExpectedSizeOrAddressParamType,
16580 unsigned DependentParamTypeDiag, unsigned InvalidParamTypeDiag) {
16581 auto NormalizeType = [&SemaRef](QualType T) {
16582 if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
16583 // The operator is valid on any address space for OpenCL.
16584 // Drop address space from actual and expected result types.
16585 if (const auto PtrTy = T->template getAs<PointerType>())
16586 T = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
16587 }
16588 return SemaRef.Context.getCanonicalType(T);
16589 };
16590
16591 const unsigned NumParams = FnDecl->getNumParams();
16592 unsigned FirstNonTypeParam = 0;
16593 bool MalformedTypeIdentity = false;
16594 bool IsPotentiallyTypeAware = IsPotentiallyTypeAwareOperatorNewOrDelete(
16595 SemaRef, FnDecl, &MalformedTypeIdentity);
16596 unsigned MinimumMandatoryArgumentCount = 1;
16597 unsigned SizeParameterIndex = 0;
16598 if (IsPotentiallyTypeAware) {
16599 // We don't emit this diagnosis for template instantiations as we will
16600 // have already emitted it for the original template declaration.
16601 if (!FnDecl->isTemplateInstantiation())
16602 SemaRef.Diag(FnDecl->getLocation(), diag::warn_ext_type_aware_allocators);
16603
16604 if (OperatorKind == AllocationOperatorKind::New) {
16605 SizeParameterIndex = 1;
16606 MinimumMandatoryArgumentCount =
16607 FunctionDecl::RequiredTypeAwareNewParameterCount;
16608 } else {
16609 SizeParameterIndex = 2;
16610 MinimumMandatoryArgumentCount =
16611 FunctionDecl::RequiredTypeAwareDeleteParameterCount;
16612 }
16613 FirstNonTypeParam = 1;
16614 }
16615
16616 bool IsPotentiallyDestroyingDelete =
16617 IsPotentiallyDestroyingOperatorDelete(SemaRef, FnDecl);
16618
16619 if (IsPotentiallyDestroyingDelete) {
16620 ++MinimumMandatoryArgumentCount;
16621 ++SizeParameterIndex;
16622 }
16623
16624 if (NumParams < MinimumMandatoryArgumentCount)
16625 return SemaRef.Diag(FnDecl->getLocation(),
16626 diag::err_operator_new_delete_too_few_parameters)
16627 << IsPotentiallyTypeAware << IsPotentiallyDestroyingDelete
16628 << FnDecl->getDeclName() << MinimumMandatoryArgumentCount;
16629
16630 for (unsigned Idx = 0; Idx < MinimumMandatoryArgumentCount; ++Idx) {
16631 const ParmVarDecl *ParamDecl = FnDecl->getParamDecl(Idx);
16632 if (ParamDecl->hasDefaultArg())
16633 return SemaRef.Diag(FnDecl->getLocation(),
16634 diag::err_operator_new_default_arg)
16635 << FnDecl->getDeclName() << Idx << ParamDecl->getDefaultArgRange();
16636 }
16637
16638 auto *FnType = FnDecl->getType()->castAs<FunctionType>();
16639 QualType CanResultType = NormalizeType(FnType->getReturnType());
16640 QualType CanExpectedResultType = NormalizeType(ExpectedResultType);
16641 QualType CanExpectedSizeOrAddressParamType =
16642 NormalizeType(ExpectedSizeOrAddressParamType);
16643
16644 // Check that the result type is what we expect.
16645 if (CanResultType != CanExpectedResultType) {
16646 // Reject even if the type is dependent; an operator delete function is
16647 // required to have a non-dependent result type.
16648 return SemaRef.Diag(
16649 FnDecl->getLocation(),
16650 CanResultType->isDependentType()
16651 ? diag::err_operator_new_delete_dependent_result_type
16652 : diag::err_operator_new_delete_invalid_result_type)
16653 << FnDecl->getDeclName() << ExpectedResultType;
16654 }
16655
16656 // A function template must have at least 2 parameters.
16657 if (FnDecl->getDescribedFunctionTemplate() && NumParams < 2)
16658 return SemaRef.Diag(FnDecl->getLocation(),
16659 diag::err_operator_new_delete_template_too_few_parameters)
16660 << FnDecl->getDeclName();
16661
16662 auto CheckType = [&](unsigned ParamIdx, QualType ExpectedType,
16663 auto FallbackType) -> bool {
16664 const ParmVarDecl *ParamDecl = FnDecl->getParamDecl(ParamIdx);
16665 if (ExpectedType.isNull()) {
16666 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
16667 << IsPotentiallyTypeAware << IsPotentiallyDestroyingDelete
16668 << FnDecl->getDeclName() << (1 + ParamIdx) << FallbackType
16669 << ParamDecl->getSourceRange();
16670 }
16671 CanQualType CanExpectedTy =
16672 NormalizeType(SemaRef.Context.getCanonicalType(ExpectedType));
16673 auto ActualParamType =
16674 NormalizeType(ParamDecl->getType().getUnqualifiedType());
16675 if (ActualParamType == CanExpectedTy)
16676 return false;
16677 unsigned Diagnostic = ActualParamType->isDependentType()
16678 ? DependentParamTypeDiag
16679 : InvalidParamTypeDiag;
16680 return SemaRef.Diag(FnDecl->getLocation(), Diagnostic)
16681 << IsPotentiallyTypeAware << IsPotentiallyDestroyingDelete
16682 << FnDecl->getDeclName() << (1 + ParamIdx) << ExpectedType
16683 << FallbackType << ParamDecl->getSourceRange();
16684 };
16685
16686 // Check that the first parameter type is what we expect.
16687 if (CheckType(FirstNonTypeParam, CanExpectedSizeOrAddressParamType, "size_t"))
16688 return true;
16689
16690 FnDecl->setIsDestroyingOperatorDelete(IsPotentiallyDestroyingDelete);
16691
16692 // If the first parameter type is not a type-identity we're done, otherwise
16693 // we need to ensure the size and alignment parameters have the correct type
16694 if (!IsPotentiallyTypeAware)
16695 return false;
16696
16697 if (CheckType(SizeParameterIndex, SemaRef.Context.getSizeType(), "size_t"))
16698 return true;
16699 TagDecl *StdAlignValTDecl = SemaRef.getStdAlignValT();
16700 CanQualType StdAlignValT =
16701 StdAlignValTDecl ? SemaRef.Context.getCanonicalTagType(StdAlignValTDecl)
16702 : CanQualType();
16703 if (CheckType(SizeParameterIndex + 1, StdAlignValT, "std::align_val_t"))
16704 return true;
16705
16706 FnDecl->setIsTypeAwareOperatorNewOrDelete();
16707 return MalformedTypeIdentity;
16708 }
16709
16710 static bool CheckOperatorNewDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
16711 // C++ [basic.stc.dynamic.allocation]p1:
16712 // A program is ill-formed if an allocation function is declared in a
16713 // namespace scope other than global scope or declared static in global
16714 // scope.
16715 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
16716 return true;
16717
16718 CanQualType SizeTy =
16719 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
16720
16721 // C++ [basic.stc.dynamic.allocation]p1:
16722 // The return type shall be void*. The first parameter shall have type
16723 // std::size_t.
16724 return CheckOperatorNewDeleteTypes(
16725 SemaRef, FnDecl, AllocationOperatorKind::New, SemaRef.Context.VoidPtrTy,
16726 SizeTy, diag::err_operator_new_dependent_param_type,
16727 diag::err_operator_new_param_type);
16728 }
16729
16730 static bool
16731 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
16732 // C++ [basic.stc.dynamic.deallocation]p1:
16733 // A program is ill-formed if deallocation functions are declared in a
16734 // namespace scope other than global scope or declared static in global
16735 // scope.
16736 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
16737 return true;
16738
16739 auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
16740 auto ConstructDestroyingDeleteAddressType = [&]() {
16741 assert(MD);
16742 return SemaRef.Context.getPointerType(
16743 SemaRef.Context.getCanonicalTagType(MD->getParent()));
16744 };
16745
16746 // C++ P2719: A destroying operator delete cannot be type aware
16747 // so for QoL we actually check for this explicitly by considering
16748 // an destroying-delete appropriate address type and the presence of
16749 // any parameter of type destroying_delete_t as an erroneous attempt
16750 // to declare a type aware destroying delete, rather than emitting a
16751 // pile of incorrect parameter type errors.
16752 if (MD && IsPotentiallyTypeAwareOperatorNewOrDelete(
16753 SemaRef, MD, /*WasMalformed=*/nullptr)) {
16754 QualType AddressParamType =
16755 SemaRef.Context.getCanonicalType(MD->getParamDecl(1)->getType());
16756 if (AddressParamType != SemaRef.Context.VoidPtrTy &&
16757 AddressParamType == ConstructDestroyingDeleteAddressType()) {
16758 // The address parameter type implies an author trying to construct a
16759 // type aware destroying delete, so we'll see if we can find a parameter
16760 // of type `std::destroying_delete_t`, and if we find it we'll report
16761 // this as being an attempt at a type aware destroying delete just stop
16762 // here. If we don't do this, the resulting incorrect parameter ordering
16763 // results in a pile mismatched argument type errors that don't explain
16764 // the core problem.
16765 for (auto Param : MD->parameters()) {
16766 if (isDestroyingDeleteT(Param->getType())) {
16767 SemaRef.Diag(MD->getLocation(),
16768 diag::err_type_aware_destroying_operator_delete)
16769 << Param->getSourceRange();
16770 return true;
16771 }
16772 }
16773 }
16774 }
16775
16776 // C++ P0722:
16777 // Within a class C, the first parameter of a destroying operator delete
16778 // shall be of type C *. The first parameter of any other deallocation
16779 // function shall be of type void *.
16780 CanQualType ExpectedAddressParamType =
16781 MD && IsPotentiallyDestroyingOperatorDelete(SemaRef, MD)
16782 ? SemaRef.Context.getPointerType(
16783 SemaRef.Context.getCanonicalTagType(MD->getParent()))
16784 : SemaRef.Context.VoidPtrTy;
16785
16786 // C++ [basic.stc.dynamic.deallocation]p2:
16787 // Each deallocation function shall return void
16788 if (CheckOperatorNewDeleteTypes(
16789 SemaRef, FnDecl, AllocationOperatorKind::Delete,
16790 SemaRef.Context.VoidTy, ExpectedAddressParamType,
16791 diag::err_operator_delete_dependent_param_type,
16792 diag::err_operator_delete_param_type))
16793 return true;
16794
16795 // C++ P0722:
16796 // A destroying operator delete shall be a usual deallocation function.
16797 if (MD && !MD->getParent()->isDependentContext() &&
16798 MD->isDestroyingOperatorDelete()) {
16799 if (!SemaRef.isUsualDeallocationFunction(MD)) {
16800 SemaRef.Diag(MD->getLocation(),
16801 diag::err_destroying_operator_delete_not_usual);
16802 return true;
16803 }
16804 }
16805
16806 return false;
16807 }
16808
16809 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
16810 assert(FnDecl && FnDecl->isOverloadedOperator() &&
16811 "Expected an overloaded operator declaration");
16812
16813 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
16814
16815 // C++ [over.oper]p5:
16816 // The allocation and deallocation functions, operator new,
16817 // operator new[], operator delete and operator delete[], are
16818 // described completely in 3.7.3. The attributes and restrictions
16819 // found in the rest of this subclause do not apply to them unless
16820 // explicitly stated in 3.7.3.
16821 if (Op == OO_Delete || Op == OO_Array_Delete)
16822 return CheckOperatorDeleteDeclaration(*this, FnDecl);
16823
16824 if (Op == OO_New || Op == OO_Array_New)
16825 return CheckOperatorNewDeclaration(*this, FnDecl);
16826
16827 // C++ [over.oper]p7:
16828 // An operator function shall either be a member function or
16829 // be a non-member function and have at least one parameter
16830 // whose type is a class, a reference to a class, an enumeration,
16831 // or a reference to an enumeration.
16832 // Note: Before C++23, a member function could not be static. The only member
16833 // function allowed to be static is the call operator function.
16834 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
16835 if (MethodDecl->isStatic()) {
16836 if (Op == OO_Call || Op == OO_Subscript)
16837 Diag(FnDecl->getLocation(),
16838 (LangOpts.CPlusPlus23
16839 ? diag::warn_cxx20_compat_operator_overload_static
16840 : diag::ext_operator_overload_static))
16841 << FnDecl;
16842 else
16843 return Diag(FnDecl->getLocation(), diag::err_operator_overload_static)
16844 << FnDecl;
16845 }
16846 } else {
16847 bool ClassOrEnumParam = false;
16848 for (auto *Param : FnDecl->parameters()) {
16849 QualType ParamType = Param->getType().getNonReferenceType();
16850 if (ParamType->isDependentType() || ParamType->isRecordType() ||
16851 ParamType->isEnumeralType()) {
16852 ClassOrEnumParam = true;
16853 break;
16854 }
16855 }
16856
16857 if (!ClassOrEnumParam)
16858 return Diag(FnDecl->getLocation(),
16859 diag::err_operator_overload_needs_class_or_enum)
16860 << FnDecl->getDeclName();
16861 }
16862
16863 // C++ [over.oper]p8:
16864 // An operator function cannot have default arguments (8.3.6),
16865 // except where explicitly stated below.
16866 //
16867 // Only the function-call operator (C++ [over.call]p1) and the subscript
16868 // operator (CWG2507) allow default arguments.
16869 if (Op != OO_Call) {
16870 ParmVarDecl *FirstDefaultedParam = nullptr;
16871 for (auto *Param : FnDecl->parameters()) {
16872 if (Param->hasDefaultArg()) {
16873 FirstDefaultedParam = Param;
16874 break;
16875 }
16876 }
16877 if (FirstDefaultedParam) {
16878 if (Op == OO_Subscript) {
16879 Diag(FnDecl->getLocation(), LangOpts.CPlusPlus23
16880 ? diag::ext_subscript_overload
16881 : diag::error_subscript_overload)
16882 << FnDecl->getDeclName() << 1
16883 << FirstDefaultedParam->getDefaultArgRange();
16884 } else {
16885 return Diag(FirstDefaultedParam->getLocation(),
16886 diag::err_operator_overload_default_arg)
16887 << FnDecl->getDeclName()
16888 << FirstDefaultedParam->getDefaultArgRange();
16889 }
16890 }
16891 }
16892
16893 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
16894 { false, false, false }
16895 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
16896 , { Unary, Binary, MemberOnly }
16897 #include "clang/Basic/OperatorKinds.def"
16898 };
16899
16900 bool CanBeUnaryOperator = OperatorUses[Op][0];
16901 bool CanBeBinaryOperator = OperatorUses[Op][1];
16902 bool MustBeMemberOperator = OperatorUses[Op][2];
16903
16904 // C++ [over.oper]p8:
16905 // [...] Operator functions cannot have more or fewer parameters
16906 // than the number required for the corresponding operator, as
16907 // described in the rest of this subclause.
16908 unsigned NumParams = FnDecl->getNumParams() +
16909 (isa<CXXMethodDecl>(FnDecl) &&
16910 !FnDecl->hasCXXExplicitFunctionObjectParameter()
16911 ? 1
16912 : 0);
16913 if (Op != OO_Call && Op != OO_Subscript &&
16914 ((NumParams == 1 && !CanBeUnaryOperator) ||
16915 (NumParams == 2 && !CanBeBinaryOperator) || (NumParams < 1) ||
16916 (NumParams > 2))) {
16917 // We have the wrong number of parameters.
16918 unsigned ErrorKind;
16919 if (CanBeUnaryOperator && CanBeBinaryOperator) {
16920 ErrorKind = 2; // 2 -> unary or binary.
16921 } else if (CanBeUnaryOperator) {
16922 ErrorKind = 0; // 0 -> unary
16923 } else {
16924 assert(CanBeBinaryOperator &&
16925 "All non-call overloaded operators are unary or binary!");
16926 ErrorKind = 1; // 1 -> binary
16927 }
16928 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
16929 << FnDecl->getDeclName() << NumParams << ErrorKind;
16930 }
16931
16932 if (Op == OO_Subscript && NumParams != 2) {
16933 Diag(FnDecl->getLocation(), LangOpts.CPlusPlus23
16934 ? diag::ext_subscript_overload
16935 : diag::error_subscript_overload)
16936 << FnDecl->getDeclName() << (NumParams == 1 ? 0 : 2);
16937 }
16938
16939 // Overloaded operators other than operator() and operator[] cannot be
16940 // variadic.
16941 if (Op != OO_Call &&
16942 FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) {
16943 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
16944 << FnDecl->getDeclName();
16945 }
16946
16947 // Some operators must be member functions.
16948 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
16949 return Diag(FnDecl->getLocation(),
16950 diag::err_operator_overload_must_be_member)
16951 << FnDecl->getDeclName();
16952 }
16953
16954 // C++ [over.inc]p1:
16955 // The user-defined function called operator++ implements the
16956 // prefix and postfix ++ operator. If this function is a member
16957 // function with no parameters, or a non-member function with one
16958 // parameter of class or enumeration type, it defines the prefix
16959 // increment operator ++ for objects of that type. If the function
16960 // is a member function with one parameter (which shall be of type
16961 // int) or a non-member function with two parameters (the second
16962 // of which shall be of type int), it defines the postfix
16963 // increment operator ++ for objects of that type.
16964 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
16965 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
16966 QualType ParamType = LastParam->getType();
16967
16968 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
16969 !ParamType->isDependentType())
16970 return Diag(LastParam->getLocation(),
16971 diag::err_operator_overload_post_incdec_must_be_int)
16972 << LastParam->getType() << (Op == OO_MinusMinus);
16973 }
16974
16975 return false;
16976 }
16977
16978 static bool
16979 checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
16980 FunctionTemplateDecl *TpDecl) {
16981 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
16982
16983 // Must have one or two template parameters.
16984 if (TemplateParams->size() == 1) {
16985 NonTypeTemplateParmDecl *PmDecl =
16986 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
16987
16988 // The template parameter must be a char parameter pack.
16989 if (PmDecl && PmDecl->isTemplateParameterPack() &&
16990 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
16991 return false;
16992
16993 // C++20 [over.literal]p5:
16994 // A string literal operator template is a literal operator template
16995 // whose template-parameter-list comprises a single non-type
16996 // template-parameter of class type.
16997 //
16998 // As a DR resolution, we also allow placeholders for deduced class
16999 // template specializations.
17000 if (SemaRef.getLangOpts().CPlusPlus20 && PmDecl &&
17001 !PmDecl->isTemplateParameterPack() &&
17002 (PmDecl->getType()->isRecordType() ||
17003 PmDecl->getType()->getAs<DeducedTemplateSpecializationType>()))
17004 return false;
17005 } else if (TemplateParams->size() == 2) {
17006 TemplateTypeParmDecl *PmType =
17007 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
17008 NonTypeTemplateParmDecl *PmArgs =
17009 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
17010
17011 // The second template parameter must be a parameter pack with the
17012 // first template parameter as its type.
17013 if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
17014 PmArgs->isTemplateParameterPack()) {
17015 if (const auto *TArgs =
17016 PmArgs->getType()->getAsCanonical<TemplateTypeParmType>();
17017 TArgs && TArgs->getDepth() == PmType->getDepth() &&
17018 TArgs->getIndex() == PmType->getIndex()) {
17019 if (!SemaRef.inTemplateInstantiation())
17020 SemaRef.Diag(TpDecl->getLocation(),
17021 diag::ext_string_literal_operator_template);
17022 return false;
17023 }
17024 }
17025 }
17026
17027 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
17028 diag::err_literal_operator_template)
17029 << TpDecl->getTemplateParameters()->getSourceRange();
17030 return true;
17031 }
17032
17033 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
17034 if (isa<CXXMethodDecl>(FnDecl)) {
17035 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
17036 << FnDecl->getDeclName();
17037 return true;
17038 }
17039
17040 if (FnDecl->isExternC()) {
17041 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
17042 if (const LinkageSpecDecl *LSD =
17043 FnDecl->getDeclContext()->getExternCContext())
17044 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
17045 return true;
17046 }
17047
17048 // This might be the definition of a literal operator template.
17049 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
17050
17051 // This might be a specialization of a literal operator template.
17052 if (!TpDecl)
17053 TpDecl = FnDecl->getPrimaryTemplate();
17054
17055 // template <char...> type operator "" name() and
17056 // template <class T, T...> type operator "" name() are the only valid
17057 // template signatures, and the only valid signatures with no parameters.
17058 //
17059 // C++20 also allows template <SomeClass T> type operator "" name().
17060 if (TpDecl) {
17061 if (FnDecl->param_size() != 0) {
17062 Diag(FnDecl->getLocation(),
17063 diag::err_literal_operator_template_with_params);
17064 return true;
17065 }
17066
17067 if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
17068 return true;
17069
17070 } else if (FnDecl->param_size() == 1) {
17071 const ParmVarDecl *Param = FnDecl->getParamDecl(0);
17072
17073 QualType ParamType = Param->getType().getUnqualifiedType();
17074
17075 // Only unsigned long long int, long double, any character type, and const
17076 // char * are allowed as the only parameters.
17077 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
17078 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
17079 Context.hasSameType(ParamType, Context.CharTy) ||
17080 Context.hasSameType(ParamType, Context.WideCharTy) ||
17081 Context.hasSameType(ParamType, Context.Char8Ty) ||
17082 Context.hasSameType(ParamType, Context.Char16Ty) ||
17083 Context.hasSameType(ParamType, Context.Char32Ty)) {
17084 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
17085 QualType InnerType = Ptr->getPointeeType();
17086
17087 // Pointer parameter must be a const char *.
17088 if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
17089 Context.CharTy) &&
17090 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
17091 Diag(Param->getSourceRange().getBegin(),
17092 diag::err_literal_operator_param)
17093 << ParamType << "'const char *'" << Param->getSourceRange();
17094 return true;
17095 }
17096
17097 } else if (ParamType->isRealFloatingType()) {
17098 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
17099 << ParamType << Context.LongDoubleTy << Param->getSourceRange();
17100 return true;
17101
17102 } else if (ParamType->isIntegerType()) {
17103 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
17104 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
17105 return true;
17106
17107 } else {
17108 Diag(Param->getSourceRange().getBegin(),
17109 diag::err_literal_operator_invalid_param)
17110 << ParamType << Param->getSourceRange();
17111 return true;
17112 }
17113
17114 } else if (FnDecl->param_size() == 2) {
17115 FunctionDecl::param_iterator Param = FnDecl->param_begin();
17116
17117 // First, verify that the first parameter is correct.
17118
17119 QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
17120
17121 // Two parameter function must have a pointer to const as a
17122 // first parameter; let's strip those qualifiers.
17123 const PointerType *PT = FirstParamType->getAs<PointerType>();
17124
17125 if (!PT) {
17126 Diag((*Param)->getSourceRange().getBegin(),
17127 diag::err_literal_operator_param)
17128 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
17129 return true;
17130 }
17131
17132 QualType PointeeType = PT->getPointeeType();
17133 // First parameter must be const
17134 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
17135 Diag((*Param)->getSourceRange().getBegin(),
17136 diag::err_literal_operator_param)
17137 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
17138 return true;
17139 }
17140
17141 QualType InnerType = PointeeType.getUnqualifiedType();
17142 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
17143 // const char32_t* are allowed as the first parameter to a two-parameter
17144 // function
17145 if (!(Context.hasSameType(InnerType, Context.CharTy) ||
17146 Context.hasSameType(InnerType, Context.WideCharTy) ||
17147 Context.hasSameType(InnerType, Context.Char8Ty) ||
17148 Context.hasSameType(InnerType, Context.Char16Ty) ||
17149 Context.hasSameType(InnerType, Context.Char32Ty))) {
17150 Diag((*Param)->getSourceRange().getBegin(),
17151 diag::err_literal_operator_param)
17152 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
17153 return true;
17154 }
17155
17156 // Move on to the second and final parameter.
17157 ++Param;
17158
17159 // The second parameter must be a std::size_t.
17160 QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
17161 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
17162 Diag((*Param)->getSourceRange().getBegin(),
17163 diag::err_literal_operator_param)
17164 << SecondParamType << Context.getSizeType()
17165 << (*Param)->getSourceRange();
17166 return true;
17167 }
17168 } else {
17169 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
17170 return true;
17171 }
17172
17173 // Parameters are good.
17174
17175 // A parameter-declaration-clause containing a default argument is not
17176 // equivalent to any of the permitted forms.
17177 for (auto *Param : FnDecl->parameters()) {
17178 if (Param->hasDefaultArg()) {
17179 Diag(Param->getDefaultArgRange().getBegin(),
17180 diag::err_literal_operator_default_argument)
17181 << Param->getDefaultArgRange();
17182 break;
17183 }
17184 }
17185
17186 const IdentifierInfo *II = FnDecl->getDeclName().getCXXLiteralIdentifier();
17187 ReservedLiteralSuffixIdStatus Status = II->isReservedLiteralSuffixId();
17188 if (Status != ReservedLiteralSuffixIdStatus::NotReserved &&
17189 !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
17190 // C++23 [usrlit.suffix]p1:
17191 // Literal suffix identifiers that do not start with an underscore are
17192 // reserved for future standardization. Literal suffix identifiers that
17193 // contain a double underscore __ are reserved for use by C++
17194 // implementations.
17195 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
17196 << static_cast<int>(Status)
17197 << StringLiteralParser::isValidUDSuffix(getLangOpts(), II->getName());
17198 }
17199
17200 return false;
17201 }
17202
17203 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
17204 Expr *LangStr,
17205 SourceLocation LBraceLoc) {
17206 StringLiteral *Lit = cast<StringLiteral>(LangStr);
17207 assert(Lit->isUnevaluated() && "Unexpected string literal kind");
17208
17209 StringRef Lang = Lit->getString();
17210 LinkageSpecLanguageIDs Language;
17211 if (Lang == "C")
17212 Language = LinkageSpecLanguageIDs::C;
17213 else if (Lang == "C++")
17214 Language = LinkageSpecLanguageIDs::CXX;
17215 else {
17216 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
17217 << LangStr->getSourceRange();
17218 return nullptr;
17219 }
17220
17221 // FIXME: Add all the various semantics of linkage specifications
17222
17223 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
17224 LangStr->getExprLoc(), Language,
17225 LBraceLoc.isValid());
17226
17227 /// C++ [module.unit]p7.2.3
17228 /// - Otherwise, if the declaration
17229 /// - ...
17230 /// - ...
17231 /// - appears within a linkage-specification,
17232 /// it is attached to the global module.
17233 ///
17234 /// If the declaration is already in global module fragment, we don't
17235 /// need to attach it again.
17236 if (getLangOpts().CPlusPlusModules && isCurrentModulePurview()) {
17237 Module *GlobalModule = PushImplicitGlobalModuleFragment(ExternLoc);
17238 D->setLocalOwningModule(GlobalModule);
17239 }
17240
17241 CurContext->addDecl(D);
17242 PushDeclContext(S, D);
17243 return D;
17244 }
17245
17246 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
17247 Decl *LinkageSpec,
17248 SourceLocation RBraceLoc) {
17249 if (RBraceLoc.isValid()) {
17250 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
17251 LSDecl->setRBraceLoc(RBraceLoc);
17252 }
17253
17254 // If the current module doesn't has Parent, it implies that the
17255 // LinkageSpec isn't in the module created by itself. So we don't
17256 // need to pop it.
17257 if (getLangOpts().CPlusPlusModules && getCurrentModule() &&
17258 getCurrentModule()->isImplicitGlobalModule() &&
17259 getCurrentModule()->Parent)
17260 PopImplicitGlobalModuleFragment();
17261
17262 PopDeclContext();
17263 return LinkageSpec;
17264 }
17265
17266 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
17267 const ParsedAttributesView &AttrList,
17268 SourceLocation SemiLoc) {
17269 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
17270 // Attribute declarations appertain to empty declaration so we handle
17271 // them here.
17272 ProcessDeclAttributeList(S, ED, AttrList);
17273
17274 CurContext->addDecl(ED);
17275 return ED;
17276 }
17277
17278 VarDecl *Sema::BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
17279 SourceLocation StartLoc,
17280 SourceLocation Loc,
17281 const IdentifierInfo *Name) {
17282 bool Invalid = false;
17283 QualType ExDeclType = TInfo->getType();
17284
17285 // Arrays and functions decay.
17286 if (ExDeclType->isArrayType())
17287 ExDeclType = Context.getArrayDecayedType(ExDeclType);
17288 else if (ExDeclType->isFunctionType())
17289 ExDeclType = Context.getPointerType(ExDeclType);
17290
17291 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
17292 // The exception-declaration shall not denote a pointer or reference to an
17293 // incomplete type, other than [cv] void*.
17294 // N2844 forbids rvalue references.
17295 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
17296 Diag(Loc, diag::err_catch_rvalue_ref);
17297 Invalid = true;
17298 }
17299
17300 if (ExDeclType->isVariablyModifiedType()) {
17301 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
17302 Invalid = true;
17303 }
17304
17305 QualType BaseType = ExDeclType;
17306 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
17307 unsigned DK = diag::err_catch_incomplete;
17308 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
17309 BaseType = Ptr->getPointeeType();
17310 Mode = 1;
17311 DK = diag::err_catch_incomplete_ptr;
17312 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
17313 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
17314 BaseType = Ref->getPointeeType();
17315 Mode = 2;
17316 DK = diag::err_catch_incomplete_ref;
17317 }
17318 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
17319 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
17320 Invalid = true;
17321
17322 if (!Invalid && BaseType.isWebAssemblyReferenceType()) {
17323 Diag(Loc, diag::err_wasm_reftype_tc) << 1;
17324 Invalid = true;
17325 }
17326
17327 if (!Invalid && Mode != 1 && BaseType->isSizelessType()) {
17328 Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType;
17329 Invalid = true;
17330 }
17331
17332 if (!Invalid && !ExDeclType->isDependentType() &&
17333 RequireNonAbstractType(Loc, ExDeclType,
17334 diag::err_abstract_type_in_decl,
17335 AbstractVariableType))
17336 Invalid = true;
17337
17338 // Only the non-fragile NeXT runtime currently supports C++ catches
17339 // of ObjC types, and no runtime supports catching ObjC types by value.
17340 if (!Invalid && getLangOpts().ObjC) {
17341 QualType T = ExDeclType;
17342 if (const ReferenceType *RT = T->getAs<ReferenceType>())
17343 T = RT->getPointeeType();
17344
17345 if (T->isObjCObjectType()) {
17346 Diag(Loc, diag::err_objc_object_catch);
17347 Invalid = true;
17348 } else if (T->isObjCObjectPointerType()) {
17349 // FIXME: should this be a test for macosx-fragile specifically?
17350 if (getLangOpts().ObjCRuntime.isFragile())
17351 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
17352 }
17353 }
17354
17355 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
17356 ExDeclType, TInfo, SC_None);
17357 ExDecl->setExceptionVariable(true);
17358
17359 // In ARC, infer 'retaining' for variables of retainable type.
17360 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(ExDecl))
17361 Invalid = true;
17362
17363 if (!Invalid && !ExDeclType->isDependentType()) {
17364 if (auto *ClassDecl = ExDeclType->getAsCXXRecordDecl()) {
17365 // Insulate this from anything else we might currently be parsing.
17366 EnterExpressionEvaluationContext scope(
17367 *this, ExpressionEvaluationContext::PotentiallyEvaluated);
17368
17369 // C++ [except.handle]p16:
17370 // The object declared in an exception-declaration or, if the
17371 // exception-declaration does not specify a name, a temporary (12.2) is
17372 // copy-initialized (8.5) from the exception object. [...]
17373 // The object is destroyed when the handler exits, after the destruction
17374 // of any automatic objects initialized within the handler.
17375 //
17376 // We just pretend to initialize the object with itself, then make sure
17377 // it can be destroyed later.
17378 QualType initType = Context.getExceptionObjectType(ExDeclType);
17379
17380 InitializedEntity entity =
17381 InitializedEntity::InitializeVariable(ExDecl);
17382 InitializationKind initKind =
17383 InitializationKind::CreateCopy(Loc, SourceLocation());
17384
17385 Expr *opaqueValue =
17386 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
17387 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
17388 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
17389 if (result.isInvalid())
17390 Invalid = true;
17391 else {
17392 // If the constructor used was non-trivial, set this as the
17393 // "initializer".
17394 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
17395 if (!construct->getConstructor()->isTrivial()) {
17396 Expr *init = MaybeCreateExprWithCleanups(construct);
17397 ExDecl->setInit(init);
17398 }
17399
17400 // And make sure it's destructable.
17401 FinalizeVarWithDestructor(ExDecl, ClassDecl);
17402 }
17403 }
17404 }
17405
17406 if (Invalid)
17407 ExDecl->setInvalidDecl();
17408
17409 return ExDecl;
17410 }
17411
17412 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
17413 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
17414 bool Invalid = D.isInvalidType();
17415
17416 // Check for unexpanded parameter packs.
17417 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
17418 UPPC_ExceptionType)) {
17419 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
17420 D.getIdentifierLoc());
17421 Invalid = true;
17422 }
17423
17424 const IdentifierInfo *II = D.getIdentifier();
17425 if (NamedDecl *PrevDecl =
17426 LookupSingleName(S, II, D.getIdentifierLoc(), LookupOrdinaryName,
17427 RedeclarationKind::ForVisibleRedeclaration)) {
17428 // The scope should be freshly made just for us. There is just no way
17429 // it contains any previous declaration, except for function parameters in
17430 // a function-try-block's catch statement.
17431 assert(!S->isDeclScope(PrevDecl));
17432 if (isDeclInScope(PrevDecl, CurContext, S)) {
17433 Diag(D.getIdentifierLoc(), diag::err_redefinition)
17434 << D.getIdentifier();
17435 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
17436 Invalid = true;
17437 } else if (PrevDecl->isTemplateParameter())
17438 // Maybe we will complain about the shadowed template parameter.
17439 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
17440 }
17441
17442 if (D.getCXXScopeSpec().isSet() && !Invalid) {
17443 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
17444 << D.getCXXScopeSpec().getRange();
17445 Invalid = true;
17446 }
17447
17448 VarDecl *ExDecl = BuildExceptionDeclaration(
17449 S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
17450 if (Invalid)
17451 ExDecl->setInvalidDecl();
17452
17453 // Add the exception declaration into this scope.
17454 if (II)
17455 PushOnScopeChains(ExDecl, S);
17456 else
17457 CurContext->addDecl(ExDecl);
17458
17459 ProcessDeclAttributes(S, ExDecl, D);
17460 return ExDecl;
17461 }
17462
17463 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
17464 Expr *AssertExpr,
17465 Expr *AssertMessageExpr,
17466 SourceLocation RParenLoc) {
17467 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
17468 return nullptr;
17469
17470 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
17471 AssertMessageExpr, RParenLoc, false);
17472 }
17473
17474 static void WriteCharTypePrefix(BuiltinType::Kind BTK, llvm::raw_ostream &OS) {
17475 switch (BTK) {
17476 case BuiltinType::Char_S:
17477 case BuiltinType::Char_U:
17478 break;
17479 case BuiltinType::Char8:
17480 OS << "u8";
17481 break;
17482 case BuiltinType::Char16:
17483 OS << 'u';
17484 break;
17485 case BuiltinType::Char32:
17486 OS << 'U';
17487 break;
17488 case BuiltinType::WChar_S:
17489 case BuiltinType::WChar_U:
17490 OS << 'L';
17491 break;
17492 default:
17493 llvm_unreachable("Non-character type");
17494 }
17495 }
17496
17497 /// Convert character's value, interpreted as a code unit, to a string.
17498 /// The value needs to be zero-extended to 32-bits.
17499 /// FIXME: This assumes Unicode literal encodings
17500 static void WriteCharValueForDiagnostic(uint32_t Value, const BuiltinType *BTy,
17501 unsigned TyWidth,
17502 SmallVectorImpl<char> &Str) {
17503 char Arr[UNI_MAX_UTF8_BYTES_PER_CODE_POINT];
17504 char *Ptr = Arr;
17505 BuiltinType::Kind K = BTy->getKind();
17506 llvm::raw_svector_ostream OS(Str);
17507
17508 // This should catch Char_S, Char_U, Char8, and use of escaped characters in
17509 // other types.
17510 if (K == BuiltinType::Char_S || K == BuiltinType::Char_U ||
17511 K == BuiltinType::Char8 || Value <= 0x7F) {
17512 StringRef Escaped = escapeCStyle<EscapeChar::Single>(Value);
17513 if (!Escaped.empty())
17514 EscapeStringForDiagnostic(Escaped, Str);
17515 else
17516 OS << static_cast<char>(Value);
17517 return;
17518 }
17519
17520 switch (K) {
17521 case BuiltinType::Char16:
17522 case BuiltinType::Char32:
17523 case BuiltinType::WChar_S:
17524 case BuiltinType::WChar_U: {
17525 if (llvm::ConvertCodePointToUTF8(Value, Ptr))
17526 EscapeStringForDiagnostic(StringRef(Arr, Ptr - Arr), Str);
17527 else
17528 OS << "\\x"
17529 << llvm::format_hex_no_prefix(Value, TyWidth / 4, /*Upper=*/true);
17530 break;
17531 }
17532 default:
17533 llvm_unreachable("Non-character type is passed");
17534 }
17535 }
17536
17537 /// Convert \V to a string we can present to the user in a diagnostic
17538 /// \T is the type of the expression that has been evaluated into \V
17539 static bool ConvertAPValueToString(const APValue &V, QualType T,
17540 SmallVectorImpl<char> &Str,
17541 ASTContext &Context) {
17542 if (!V.hasValue())
17543 return false;
17544
17545 switch (V.getKind()) {
17546 case APValue::ValueKind::Int:
17547 if (T->isBooleanType()) {
17548 // Bools are reduced to ints during evaluation, but for
17549 // diagnostic purposes we want to print them as
17550 // true or false.
17551 int64_t BoolValue = V.getInt().getExtValue();
17552 assert((BoolValue == 0 || BoolValue == 1) &&
17553 "Bool type, but value is not 0 or 1");
17554 llvm::raw_svector_ostream OS(Str);
17555 OS << (BoolValue ? "true" : "false");
17556 } else {
17557 llvm::raw_svector_ostream OS(Str);
17558 // Same is true for chars.
17559 // We want to print the character representation for textual types
17560 const auto *BTy = T->getAs<BuiltinType>();
17561 if (BTy) {
17562 switch (BTy->getKind()) {
17563 case BuiltinType::Char_S:
17564 case BuiltinType::Char_U:
17565 case BuiltinType::Char8:
17566 case BuiltinType::Char16:
17567 case BuiltinType::Char32:
17568 case BuiltinType::WChar_S:
17569 case BuiltinType::WChar_U: {
17570 unsigned TyWidth = Context.getIntWidth(T);
17571 assert(8 <= TyWidth && TyWidth <= 32 && "Unexpected integer width");
17572 uint32_t CodeUnit = static_cast<uint32_t>(V.getInt().getZExtValue());
17573 WriteCharTypePrefix(BTy->getKind(), OS);
17574 OS << '\'';
17575 WriteCharValueForDiagnostic(CodeUnit, BTy, TyWidth, Str);
17576 OS << "' (0x"
17577 << llvm::format_hex_no_prefix(CodeUnit, /*Width=*/2,
17578 /*Upper=*/true)
17579 << ", " << V.getInt() << ')';
17580 return true;
17581 }
17582 default:
17583 break;
17584 }
17585 }
17586 V.getInt().toString(Str);
17587 }
17588
17589 break;
17590
17591 case APValue::ValueKind::Float:
17592 V.getFloat().toString(Str);
17593 break;
17594
17595 case APValue::ValueKind::LValue:
17596 if (V.isNullPointer()) {
17597 llvm::raw_svector_ostream OS(Str);
17598 OS << "nullptr";
17599 } else
17600 return false;
17601 break;
17602
17603 case APValue::ValueKind::ComplexFloat: {
17604 llvm::raw_svector_ostream OS(Str);
17605 OS << '(';
17606 V.getComplexFloatReal().toString(Str);
17607 OS << " + ";
17608 V.getComplexFloatImag().toString(Str);
17609 OS << "i)";
17610 } break;
17611
17612 case APValue::ValueKind::ComplexInt: {
17613 llvm::raw_svector_ostream OS(Str);
17614 OS << '(';
17615 V.getComplexIntReal().toString(Str);
17616 OS << " + ";
17617 V.getComplexIntImag().toString(Str);
17618 OS << "i)";
17619 } break;
17620
17621 default:
17622 return false;
17623 }
17624
17625 return true;
17626 }
17627
17628 /// Some Expression types are not useful to print notes about,
17629 /// e.g. literals and values that have already been expanded
17630 /// before such as int-valued template parameters.
17631 static bool UsefulToPrintExpr(const Expr *E) {
17632 E = E->IgnoreParenImpCasts();
17633 // Literals are pretty easy for humans to understand.
17634 if (isa<IntegerLiteral, FloatingLiteral, CharacterLiteral, CXXBoolLiteralExpr,
17635 CXXNullPtrLiteralExpr, FixedPointLiteral, ImaginaryLiteral>(E))
17636 return false;
17637
17638 // These have been substituted from template parameters
17639 // and appear as literals in the static assert error.
17640 if (isa<SubstNonTypeTemplateParmExpr>(E))
17641 return false;
17642
17643 // -5 is also simple to understand.
17644 if (const auto *UnaryOp = dyn_cast<UnaryOperator>(E))
17645 return UsefulToPrintExpr(UnaryOp->getSubExpr());
17646
17647 // Only print nested arithmetic operators.
17648 if (const auto *BO = dyn_cast<BinaryOperator>(E))
17649 return (BO->isShiftOp() || BO->isAdditiveOp() || BO->isMultiplicativeOp() ||
17650 BO->isBitwiseOp());
17651
17652 return true;
17653 }
17654
17655 void Sema::DiagnoseStaticAssertDetails(const Expr *E) {
17656 if (const auto *Op = dyn_cast<BinaryOperator>(E);
17657 Op && Op->getOpcode() != BO_LOr) {
17658 const Expr *LHS = Op->getLHS()->IgnoreParenImpCasts();
17659 const Expr *RHS = Op->getRHS()->IgnoreParenImpCasts();
17660
17661 // Ignore comparisons of boolean expressions with a boolean literal.
17662 if ((isa<CXXBoolLiteralExpr>(LHS) && RHS->getType()->isBooleanType()) ||
17663 (isa<CXXBoolLiteralExpr>(RHS) && LHS->getType()->isBooleanType()))
17664 return;
17665
17666 // Don't print obvious expressions.
17667 if (!UsefulToPrintExpr(LHS) && !UsefulToPrintExpr(RHS))
17668 return;
17669
17670 struct {
17671 const clang::Expr *Cond;
17672 Expr::EvalResult Result;
17673 SmallString<12> ValueString;
17674 bool Print;
17675 } DiagSides[2] = {{LHS, Expr::EvalResult(), {}, false},
17676 {RHS, Expr::EvalResult(), {}, false}};
17677 for (auto &DiagSide : DiagSides) {
17678 const Expr *Side = DiagSide.Cond;
17679
17680 Side->EvaluateAsRValue(DiagSide.Result, Context, true);
17681
17682 DiagSide.Print = ConvertAPValueToString(
17683 DiagSide.Result.Val, Side->getType(), DiagSide.ValueString, Context);
17684 }
17685 if (DiagSides[0].Print && DiagSides[1].Print) {
17686 Diag(Op->getExprLoc(), diag::note_expr_evaluates_to)
17687 << DiagSides[0].ValueString << Op->getOpcodeStr()
17688 << DiagSides[1].ValueString << Op->getSourceRange();
17689 }
17690 } else {
17691 DiagnoseTypeTraitDetails(E);
17692 }
17693 }
17694
17695 template <typename ResultType>
17696 static bool EvaluateAsStringImpl(Sema &SemaRef, Expr *Message,
17697 ResultType &Result, ASTContext &Ctx,
17698 Sema::StringEvaluationContext EvalContext,
17699 bool ErrorOnInvalidMessage) {
17700
17701 assert(Message);
17702 assert(!Message->isTypeDependent() && !Message->isValueDependent() &&
17703 "can't evaluate a dependant static assert message");
17704
17705 if (const auto *SL = dyn_cast<StringLiteral>(Message)) {
17706 assert(SL->isUnevaluated() && "expected an unevaluated string");
17707 if constexpr (std::is_same_v<APValue, ResultType>) {
17708 Result =
17709 APValue(APValue::UninitArray{}, SL->getLength(), SL->getLength());
17710 const ConstantArrayType *CAT =
17711 SemaRef.getASTContext().getAsConstantArrayType(SL->getType());
17712 assert(CAT && "string literal isn't an array");
17713 QualType CharType = CAT->getElementType();
17714 llvm::APSInt Value(SemaRef.getASTContext().getTypeSize(CharType),
17715 CharType->isUnsignedIntegerType());
17716 for (unsigned I = 0; I < SL->getLength(); I++) {
17717 Value = SL->getCodeUnit(I);
17718 Result.getArrayInitializedElt(I) = APValue(Value);
17719 }
17720 } else {
17721 Result.assign(SL->getString().begin(), SL->getString().end());
17722 }
17723 return true;
17724 }
17725
17726 SourceLocation Loc = Message->getBeginLoc();
17727 QualType T = Message->getType().getNonReferenceType();
17728 auto *RD = T->getAsCXXRecordDecl();
17729 if (!RD) {
17730 SemaRef.Diag(Loc, diag::err_user_defined_msg_invalid) << EvalContext;
17731 return false;
17732 }
17733
17734 auto FindMember = [&](StringRef Member) -> std::optional<LookupResult> {
17735 DeclarationName DN = SemaRef.PP.getIdentifierInfo(Member);
17736 LookupResult MemberLookup(SemaRef, DN, Loc, Sema::LookupMemberName);
17737 SemaRef.LookupQualifiedName(MemberLookup, RD);
17738 OverloadCandidateSet Candidates(MemberLookup.getNameLoc(),
17739 OverloadCandidateSet::CSK_Normal);
17740 if (MemberLookup.empty())
17741 return std::nullopt;
17742 return std::move(MemberLookup);
17743 };
17744
17745 std::optional<LookupResult> SizeMember = FindMember("size");
17746 std::optional<LookupResult> DataMember = FindMember("data");
17747 if (!SizeMember || !DataMember) {
17748 SemaRef.Diag(Loc, diag::err_user_defined_msg_missing_member_function)
17749 << EvalContext
17750 << ((!SizeMember && !DataMember) ? 2
17751 : !SizeMember ? 0
17752 : 1);
17753 return false;
17754 }
17755
17756 auto BuildExpr = [&](LookupResult &LR) {
17757 ExprResult Res = SemaRef.BuildMemberReferenceExpr(
17758 Message, Message->getType(), Message->getBeginLoc(), false,
17759 CXXScopeSpec(), SourceLocation(), nullptr, LR, nullptr, nullptr);
17760 if (Res.isInvalid())
17761 return ExprError();
17762 Res = SemaRef.BuildCallExpr(nullptr, Res.get(), Loc, {}, Loc, nullptr,
17763 false, true);
17764 if (Res.isInvalid())
17765 return ExprError();
17766 if (Res.get()->isTypeDependent() || Res.get()->isValueDependent())
17767 return ExprError();
17768 return SemaRef.TemporaryMaterializationConversion(Res.get());
17769 };
17770
17771 ExprResult SizeE = BuildExpr(*SizeMember);
17772 ExprResult DataE = BuildExpr(*DataMember);
17773
17774 QualType SizeT = SemaRef.Context.getSizeType();
17775 QualType ConstCharPtr = SemaRef.Context.getPointerType(
17776 SemaRef.Context.getConstType(SemaRef.Context.CharTy));
17777
17778 ExprResult EvaluatedSize =
17779 SizeE.isInvalid()
17780 ? ExprError()
17781 : SemaRef.BuildConvertedConstantExpression(
17782 SizeE.get(), SizeT, CCEKind::StaticAssertMessageSize);
17783 if (EvaluatedSize.isInvalid()) {
17784 SemaRef.Diag(Loc, diag::err_user_defined_msg_invalid_mem_fn_ret_ty)
17785 << EvalContext << /*size*/ 0;
17786 return false;
17787 }
17788
17789 ExprResult EvaluatedData =
17790 DataE.isInvalid()
17791 ? ExprError()
17792 : SemaRef.BuildConvertedConstantExpression(
17793 DataE.get(), ConstCharPtr, CCEKind::StaticAssertMessageData);
17794 if (EvaluatedData.isInvalid()) {
17795 SemaRef.Diag(Loc, diag::err_user_defined_msg_invalid_mem_fn_ret_ty)
17796 << EvalContext << /*data*/ 1;
17797 return false;
17798 }
17799
17800 if (!ErrorOnInvalidMessage &&
17801 SemaRef.Diags.isIgnored(diag::warn_user_defined_msg_constexpr, Loc))
17802 return true;
17803
17804 Expr::EvalResult Status;
17805 SmallVector<PartialDiagnosticAt, 8> Notes;
17806 Status.Diag = &Notes;
17807 if (!Message->EvaluateCharRangeAsString(Result, EvaluatedSize.get(),
17808 EvaluatedData.get(), Ctx, Status) ||
17809 !Notes.empty()) {
17810 SemaRef.Diag(Message->getBeginLoc(),
17811 ErrorOnInvalidMessage ? diag::err_user_defined_msg_constexpr
17812 : diag::warn_user_defined_msg_constexpr)
17813 << EvalContext;
17814 for (const auto &Note : Notes)
17815 SemaRef.Diag(Note.first, Note.second);
17816 return !ErrorOnInvalidMessage;
17817 }
17818 return true;
17819 }
17820
17821 bool Sema::EvaluateAsString(Expr *Message, APValue &Result, ASTContext &Ctx,
17822 StringEvaluationContext EvalContext,
17823 bool ErrorOnInvalidMessage) {
17824 return EvaluateAsStringImpl(*this, Message, Result, Ctx, EvalContext,
17825 ErrorOnInvalidMessage);
17826 }
17827
17828 bool Sema::EvaluateAsString(Expr *Message, std::string &Result, ASTContext &Ctx,
17829 StringEvaluationContext EvalContext,
17830 bool ErrorOnInvalidMessage) {
17831 return EvaluateAsStringImpl(*this, Message, Result, Ctx, EvalContext,
17832 ErrorOnInvalidMessage);
17833 }
17834
17835 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
17836 Expr *AssertExpr, Expr *AssertMessage,
17837 SourceLocation RParenLoc,
17838 bool Failed) {
17839 assert(AssertExpr != nullptr && "Expected non-null condition");
17840 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
17841 (!AssertMessage || (!AssertMessage->isTypeDependent() &&
17842 !AssertMessage->isValueDependent())) &&
17843 !Failed) {
17844 // In a static_assert-declaration, the constant-expression shall be a
17845 // constant expression that can be contextually converted to bool.
17846 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
17847 if (Converted.isInvalid())
17848 Failed = true;
17849
17850 ExprResult FullAssertExpr =
17851 ActOnFinishFullExpr(Converted.get(), StaticAssertLoc,
17852 /*DiscardedValue*/ false,
17853 /*IsConstexpr*/ true);
17854 if (FullAssertExpr.isInvalid())
17855 Failed = true;
17856 else
17857 AssertExpr = FullAssertExpr.get();
17858
17859 llvm::APSInt Cond;
17860 Expr *BaseExpr = AssertExpr;
17861 AllowFoldKind FoldKind = AllowFoldKind::No;
17862
17863 if (!getLangOpts().CPlusPlus) {
17864 // In C mode, allow folding as an extension for better compatibility with
17865 // C++ in terms of expressions like static_assert("test") or
17866 // static_assert(nullptr).
17867 FoldKind = AllowFoldKind::Allow;
17868 }
17869
17870 if (!Failed && VerifyIntegerConstantExpression(
17871 BaseExpr, &Cond,
17872 diag::err_static_assert_expression_is_not_constant,
17873 FoldKind).isInvalid())
17874 Failed = true;
17875
17876 // If the static_assert passes, only verify that
17877 // the message is grammatically valid without evaluating it.
17878 if (!Failed && AssertMessage && Cond.getBoolValue()) {
17879 std::string Str;
17880 EvaluateAsString(AssertMessage, Str, Context,
17881 StringEvaluationContext::StaticAssert,
17882 /*ErrorOnInvalidMessage=*/false);
17883 }
17884
17885 // CWG2518
17886 // [dcl.pre]/p10 If [...] the expression is evaluated in the context of a
17887 // template definition, the declaration has no effect.
17888 bool InTemplateDefinition =
17889 getLangOpts().CPlusPlus && CurContext->isDependentContext();
17890
17891 if (!Failed && !Cond && !InTemplateDefinition) {
17892 SmallString<256> MsgBuffer;
17893 llvm::raw_svector_ostream Msg(MsgBuffer);
17894 bool HasMessage = AssertMessage;
17895 if (AssertMessage) {
17896 std::string Str;
17897 HasMessage = EvaluateAsString(AssertMessage, Str, Context,
17898 StringEvaluationContext::StaticAssert,
17899 /*ErrorOnInvalidMessage=*/true) ||
17900 !Str.empty();
17901 Msg << Str;
17902 }
17903 Expr *InnerCond = nullptr;
17904 std::string InnerCondDescription;
17905 std::tie(InnerCond, InnerCondDescription) =
17906 findFailedBooleanCondition(Converted.get());
17907 if (const auto *ConceptIDExpr =
17908 dyn_cast_or_null<ConceptSpecializationExpr>(InnerCond)) {
17909 const ASTConstraintSatisfaction &Satisfaction =
17910 ConceptIDExpr->getSatisfaction();
17911 if (!Satisfaction.ContainsErrors || Satisfaction.NumRecords) {
17912 Diag(AssertExpr->getBeginLoc(), diag::err_static_assert_failed)
17913 << !HasMessage << Msg.str() << AssertExpr->getSourceRange();
17914 // Drill down into concept specialization expressions to see why they
17915 // weren't satisfied.
17916 DiagnoseUnsatisfiedConstraint(ConceptIDExpr);
17917 }
17918 } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond) &&
17919 !isa<IntegerLiteral>(InnerCond)) {
17920 Diag(InnerCond->getBeginLoc(),
17921 diag::err_static_assert_requirement_failed)
17922 << InnerCondDescription << !HasMessage << Msg.str()
17923 << InnerCond->getSourceRange();
17924 DiagnoseStaticAssertDetails(InnerCond);
17925 } else {
17926 Diag(AssertExpr->getBeginLoc(), diag::err_static_assert_failed)
17927 << !HasMessage << Msg.str() << AssertExpr->getSourceRange();
17928 PrintContextStack();
17929 }
17930 Failed = true;
17931 }
17932 } else {
17933 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
17934 /*DiscardedValue*/false,
17935 /*IsConstexpr*/true);
17936 if (FullAssertExpr.isInvalid())
17937 Failed = true;
17938 else
17939 AssertExpr = FullAssertExpr.get();
17940 }
17941
17942 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
17943 AssertExpr, AssertMessage, RParenLoc,
17944 Failed);
17945
17946 CurContext->addDecl(Decl);
17947 return Decl;
17948 }
17949
17950 DeclResult Sema::ActOnTemplatedFriendTag(
17951 Scope *S, SourceLocation FriendLoc, unsigned TagSpec, SourceLocation TagLoc,
17952 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
17953 SourceLocation EllipsisLoc, const ParsedAttributesView &Attr,
17954 MultiTemplateParamsArg TempParamLists) {
17955 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
17956
17957 bool IsMemberSpecialization = false;
17958 bool Invalid = false;
17959
17960 if (TemplateParameterList *TemplateParams =
17961 MatchTemplateParametersToScopeSpecifier(
17962 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
17963 IsMemberSpecialization, Invalid)) {
17964 if (TemplateParams->size() > 0) {
17965 // This is a declaration of a class template.
17966 if (Invalid)
17967 return true;
17968
17969 return CheckClassTemplate(S, TagSpec, TagUseKind::Friend, TagLoc, SS,
17970 Name, NameLoc, Attr, TemplateParams, AS_public,
17971 /*ModulePrivateLoc=*/SourceLocation(),
17972 FriendLoc, TempParamLists.size() - 1,
17973 TempParamLists.data())
17974 .get();
17975 } else {
17976 // The "template<>" header is extraneous.
17977 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
17978 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
17979 IsMemberSpecialization = true;
17980 }
17981 }
17982
17983 if (Invalid) return true;
17984
17985 bool isAllExplicitSpecializations =
17986 llvm::all_of(TempParamLists, [](const TemplateParameterList *List) {
17987 return List->size() == 0;
17988 });
17989
17990 // FIXME: don't ignore attributes.
17991
17992 // If it's explicit specializations all the way down, just forget
17993 // about the template header and build an appropriate non-templated
17994 // friend. TODO: for source fidelity, remember the headers.
17995 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
17996 if (isAllExplicitSpecializations) {
17997 if (SS.isEmpty()) {
17998 bool Owned = false;
17999 bool IsDependent = false;
18000 return ActOnTag(S, TagSpec, TagUseKind::Friend, TagLoc, SS, Name, NameLoc,
18001 Attr, AS_public,
18002 /*ModulePrivateLoc=*/SourceLocation(),
18003 MultiTemplateParamsArg(), Owned, IsDependent,
18004 /*ScopedEnumKWLoc=*/SourceLocation(),
18005 /*ScopedEnumUsesClassTag=*/false,
18006 /*UnderlyingType=*/TypeResult(),
18007 /*IsTypeSpecifier=*/false,
18008 /*IsTemplateParamOrArg=*/false,
18009 /*OOK=*/OffsetOfKind::Outside);
18010 }
18011
18012 TypeSourceInfo *TSI = nullptr;
18013 ElaboratedTypeKeyword Keyword
18014 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
18015 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, *Name,
18016 NameLoc, &TSI, /*DeducedTSTContext=*/true);
18017 if (T.isNull())
18018 return true;
18019
18020 FriendDecl *Friend =
18021 FriendDecl::Create(Context, CurContext, NameLoc, TSI, FriendLoc,
18022 EllipsisLoc, TempParamLists);
18023 Friend->setAccess(AS_public);
18024 CurContext->addDecl(Friend);
18025 return Friend;
18026 }
18027
18028 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
18029
18030 // CWG 2917: if it (= the friend-type-specifier) is a pack expansion
18031 // (13.7.4 [temp.variadic]), any packs expanded by that pack expansion
18032 // shall not have been introduced by the template-declaration.
18033 SmallVector<UnexpandedParameterPack, 1> Unexpanded;
18034 collectUnexpandedParameterPacks(QualifierLoc, Unexpanded);
18035 unsigned FriendDeclDepth = TempParamLists.front()->getDepth();
18036 for (UnexpandedParameterPack &U : Unexpanded) {
18037 if (std::optional<std::pair<unsigned, unsigned>> DI = getDepthAndIndex(U);
18038 DI && DI->first >= FriendDeclDepth) {
18039 auto *ND = dyn_cast<NamedDecl *>(U.first);
18040 if (!ND)
18041 ND = cast<const TemplateTypeParmType *>(U.first)->getDecl();
18042 Diag(U.second, diag::friend_template_decl_malformed_pack_expansion)
18043 << ND->getDeclName() << SourceRange(SS.getBeginLoc(), EllipsisLoc);
18044 return true;
18045 }
18046 }
18047
18048 // Handle the case of a templated-scope friend class. e.g.
18049 // template <class T> class A<T>::B;
18050 // FIXME: we don't support these right now.
18051 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
18052 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
18053 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
18054 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
18055 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
18056 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
18057 TL.setElaboratedKeywordLoc(TagLoc);
18058 TL.setQualifierLoc(SS.getWithLocInContext(Context));
18059 TL.setNameLoc(NameLoc);
18060
18061 FriendDecl *Friend =
18062 FriendDecl::Create(Context, CurContext, NameLoc, TSI, FriendLoc,
18063 EllipsisLoc, TempParamLists);
18064 Friend->setAccess(AS_public);
18065 Friend->setUnsupportedFriend(true);
18066 CurContext->addDecl(Friend);
18067 return Friend;
18068 }
18069
18070 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
18071 MultiTemplateParamsArg TempParams,
18072 SourceLocation EllipsisLoc) {
18073 SourceLocation Loc = DS.getBeginLoc();
18074 SourceLocation FriendLoc = DS.getFriendSpecLoc();
18075
18076 assert(DS.isFriendSpecified());
18077 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
18078
18079 // C++ [class.friend]p3:
18080 // A friend declaration that does not declare a function shall have one of
18081 // the following forms:
18082 // friend elaborated-type-specifier ;
18083 // friend simple-type-specifier ;
18084 // friend typename-specifier ;
18085 //
18086 // If the friend keyword isn't first, or if the declarations has any type
18087 // qualifiers, then the declaration doesn't have that form.
18088 if (getLangOpts().CPlusPlus11 && !DS.isFriendSpecifiedFirst())
18089 Diag(FriendLoc, diag::err_friend_not_first_in_declaration);
18090 if (DS.getTypeQualifiers()) {
18091 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
18092 Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
18093 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
18094 Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
18095 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
18096 Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
18097 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
18098 Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
18099 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
18100 Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
18101 }
18102
18103 // Try to convert the decl specifier to a type. This works for
18104 // friend templates because ActOnTag never produces a ClassTemplateDecl
18105 // for a TagUseKind::Friend.
18106 Declarator TheDeclarator(DS, ParsedAttributesView::none(),
18107 DeclaratorContext::Member);
18108 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator);
18109 QualType T = TSI->getType();
18110 if (TheDeclarator.isInvalidType())
18111 return nullptr;
18112
18113 // If '...' is present, the type must contain an unexpanded parameter
18114 // pack, and vice versa.
18115 bool Invalid = false;
18116 if (EllipsisLoc.isInvalid() &&
18117 DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
18118 return nullptr;
18119 if (EllipsisLoc.isValid() &&
18120 !TSI->getType()->containsUnexpandedParameterPack()) {
18121 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
18122 << TSI->getTypeLoc().getSourceRange();
18123 Invalid = true;
18124 }
18125
18126 if (!T->isElaboratedTypeSpecifier()) {
18127 if (TempParams.size()) {
18128 // C++23 [dcl.pre]p5:
18129 // In a simple-declaration, the optional init-declarator-list can be
18130 // omitted only when declaring a class or enumeration, that is, when
18131 // the decl-specifier-seq contains either a class-specifier, an
18132 // elaborated-type-specifier with a class-key, or an enum-specifier.
18133 //
18134 // The declaration of a template-declaration or explicit-specialization
18135 // is never a member-declaration, so this must be a simple-declaration
18136 // with no init-declarator-list. Therefore, this is ill-formed.
18137 Diag(Loc, diag::err_tagless_friend_type_template) << DS.getSourceRange();
18138 return nullptr;
18139 } else if (const RecordDecl *RD = T->getAsRecordDecl()) {
18140 SmallString<16> InsertionText(" ");
18141 InsertionText += RD->getKindName();
18142
18143 Diag(Loc, getLangOpts().CPlusPlus11
18144 ? diag::warn_cxx98_compat_unelaborated_friend_type
18145 : diag::ext_unelaborated_friend_type)
18146 << (unsigned)RD->getTagKind() << T
18147 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
18148 InsertionText);
18149 } else {
18150 DiagCompat(FriendLoc, diag_compat::nonclass_type_friend)
18151 << T << DS.getSourceRange();
18152 }
18153 }
18154
18155 // C++98 [class.friend]p1: A friend of a class is a function
18156 // or class that is not a member of the class . . .
18157 // This is fixed in DR77, which just barely didn't make the C++03
18158 // deadline. It's also a very silly restriction that seriously
18159 // affects inner classes and which nobody else seems to implement;
18160 // thus we never diagnose it, not even in -pedantic.
18161 //
18162 // But note that we could warn about it: it's always useless to
18163 // friend one of your own members (it's not, however, worthless to
18164 // friend a member of an arbitrary specialization of your template).
18165
18166 Decl *D;
18167 if (!TempParams.empty())
18168 // TODO: Support variadic friend template decls?
18169 D = FriendTemplateDecl::Create(Context, CurContext, Loc, TempParams, TSI,
18170 FriendLoc);
18171 else
18172 D = FriendDecl::Create(Context, CurContext, TSI->getTypeLoc().getBeginLoc(),
18173 TSI, FriendLoc, EllipsisLoc);
18174
18175 if (!D)
18176 return nullptr;
18177
18178 D->setAccess(AS_public);
18179 CurContext->addDecl(D);
18180
18181 if (Invalid)
18182 D->setInvalidDecl();
18183
18184 return D;
18185 }
18186
18187 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
18188 MultiTemplateParamsArg TemplateParams) {
18189 const DeclSpec &DS = D.getDeclSpec();
18190
18191 assert(DS.isFriendSpecified());
18192 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
18193
18194 SourceLocation Loc = D.getIdentifierLoc();
18195 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
18196
18197 // C++ [class.friend]p1
18198 // A friend of a class is a function or class....
18199 // Note that this sees through typedefs, which is intended.
18200 // It *doesn't* see through dependent types, which is correct
18201 // according to [temp.arg.type]p3:
18202 // If a declaration acquires a function type through a
18203 // type dependent on a template-parameter and this causes
18204 // a declaration that does not use the syntactic form of a
18205 // function declarator to have a function type, the program
18206 // is ill-formed.
18207 if (!TInfo->getType()->isFunctionType()) {
18208 Diag(Loc, diag::err_unexpected_friend);
18209
18210 // It might be worthwhile to try to recover by creating an
18211 // appropriate declaration.
18212 return nullptr;
18213 }
18214
18215 // C++ [namespace.memdef]p3
18216 // - If a friend declaration in a non-local class first declares a
18217 // class or function, the friend class or function is a member
18218 // of the innermost enclosing namespace.
18219 // - The name of the friend is not found by simple name lookup
18220 // until a matching declaration is provided in that namespace
18221 // scope (either before or after the class declaration granting
18222 // friendship).
18223 // - If a friend function is called, its name may be found by the
18224 // name lookup that considers functions from namespaces and
18225 // classes associated with the types of the function arguments.
18226 // - When looking for a prior declaration of a class or a function
18227 // declared as a friend, scopes outside the innermost enclosing
18228 // namespace scope are not considered.
18229
18230 CXXScopeSpec &SS = D.getCXXScopeSpec();
18231 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
18232 assert(NameInfo.getName());
18233
18234 // Check for unexpanded parameter packs.
18235 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
18236 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
18237 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
18238 return nullptr;
18239
18240 // The context we found the declaration in, or in which we should
18241 // create the declaration.
18242 DeclContext *DC;
18243 Scope *DCScope = S;
18244 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
18245 RedeclarationKind::ForExternalRedeclaration);
18246
18247 bool isTemplateId = D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
18248
18249 // There are five cases here.
18250 // - There's no scope specifier and we're in a local class. Only look
18251 // for functions declared in the immediately-enclosing block scope.
18252 // We recover from invalid scope qualifiers as if they just weren't there.
18253 FunctionDecl *FunctionContainingLocalClass = nullptr;
18254 if ((SS.isInvalid() || !SS.isSet()) &&
18255 (FunctionContainingLocalClass =
18256 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
18257 // C++11 [class.friend]p11:
18258 // If a friend declaration appears in a local class and the name
18259 // specified is an unqualified name, a prior declaration is
18260 // looked up without considering scopes that are outside the
18261 // innermost enclosing non-class scope. For a friend function
18262 // declaration, if there is no prior declaration, the program is
18263 // ill-formed.
18264
18265 // Find the innermost enclosing non-class scope. This is the block
18266 // scope containing the local class definition (or for a nested class,
18267 // the outer local class).
18268 DCScope = S->getFnParent();
18269
18270 // Look up the function name in the scope.
18271 Previous.clear(LookupLocalFriendName);
18272 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
18273
18274 if (!Previous.empty()) {
18275 // All possible previous declarations must have the same context:
18276 // either they were declared at block scope or they are members of
18277 // one of the enclosing local classes.
18278 DC = Previous.getRepresentativeDecl()->getDeclContext();
18279 } else {
18280 // This is ill-formed, but provide the context that we would have
18281 // declared the function in, if we were permitted to, for error recovery.
18282 DC = FunctionContainingLocalClass;
18283 }
18284 adjustContextForLocalExternDecl(DC);
18285
18286 // - There's no scope specifier, in which case we just go to the
18287 // appropriate scope and look for a function or function template
18288 // there as appropriate.
18289 } else if (SS.isInvalid() || !SS.isSet()) {
18290 // C++11 [namespace.memdef]p3:
18291 // If the name in a friend declaration is neither qualified nor
18292 // a template-id and the declaration is a function or an
18293 // elaborated-type-specifier, the lookup to determine whether
18294 // the entity has been previously declared shall not consider
18295 // any scopes outside the innermost enclosing namespace.
18296
18297 // Find the appropriate context according to the above.
18298 DC = CurContext;
18299
18300 // Skip class contexts. If someone can cite chapter and verse
18301 // for this behavior, that would be nice --- it's what GCC and
18302 // EDG do, and it seems like a reasonable intent, but the spec
18303 // really only says that checks for unqualified existing
18304 // declarations should stop at the nearest enclosing namespace,
18305 // not that they should only consider the nearest enclosing
18306 // namespace.
18307 while (DC->isRecord())
18308 DC = DC->getParent();
18309
18310 DeclContext *LookupDC = DC->getNonTransparentContext();
18311 while (true) {
18312 LookupQualifiedName(Previous, LookupDC);
18313
18314 if (!Previous.empty()) {
18315 DC = LookupDC;
18316 break;
18317 }
18318
18319 if (isTemplateId) {
18320 if (isa<TranslationUnitDecl>(LookupDC)) break;
18321 } else {
18322 if (LookupDC->isFileContext()) break;
18323 }
18324 LookupDC = LookupDC->getParent();
18325 }
18326
18327 DCScope = getScopeForDeclContext(S, DC);
18328
18329 // - There's a non-dependent scope specifier, in which case we
18330 // compute it and do a previous lookup there for a function
18331 // or function template.
18332 } else if (!SS.getScopeRep().isDependent()) {
18333 DC = computeDeclContext(SS);
18334 if (!DC) return nullptr;
18335
18336 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
18337
18338 LookupQualifiedName(Previous, DC);
18339
18340 // C++ [class.friend]p1: A friend of a class is a function or
18341 // class that is not a member of the class . . .
18342 if (DC->Equals(CurContext))
18343 Diag(DS.getFriendSpecLoc(),
18344 getLangOpts().CPlusPlus11 ?
18345 diag::warn_cxx98_compat_friend_is_member :
18346 diag::err_friend_is_member);
18347
18348 // - There's a scope specifier that does not match any template
18349 // parameter lists, in which case we use some arbitrary context,
18350 // create a method or method template, and wait for instantiation.
18351 // - There's a scope specifier that does match some template
18352 // parameter lists, which we don't handle right now.
18353 } else {
18354 DC = CurContext;
18355 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
18356 }
18357
18358 if (!DC->isRecord()) {
18359 int DiagArg = -1;
18360 switch (D.getName().getKind()) {
18361 case UnqualifiedIdKind::IK_ConstructorTemplateId:
18362 case UnqualifiedIdKind::IK_ConstructorName:
18363 DiagArg = 0;
18364 break;
18365 case UnqualifiedIdKind::IK_DestructorName:
18366 DiagArg = 1;
18367 break;
18368 case UnqualifiedIdKind::IK_ConversionFunctionId:
18369 DiagArg = 2;
18370 break;
18371 case UnqualifiedIdKind::IK_DeductionGuideName:
18372 DiagArg = 3;
18373 break;
18374 case UnqualifiedIdKind::IK_Identifier:
18375 case UnqualifiedIdKind::IK_ImplicitSelfParam:
18376 case UnqualifiedIdKind::IK_LiteralOperatorId:
18377 case UnqualifiedIdKind::IK_OperatorFunctionId:
18378 case UnqualifiedIdKind::IK_TemplateId:
18379 break;
18380 }
18381 // This implies that it has to be an operator or function.
18382 if (DiagArg >= 0) {
18383 Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
18384 return nullptr;
18385 }
18386 }
18387
18388 // FIXME: This is an egregious hack to cope with cases where the scope stack
18389 // does not contain the declaration context, i.e., in an out-of-line
18390 // definition of a class.
18391 Scope FakeDCScope(S, Scope::DeclScope, Diags);
18392 if (!DCScope) {
18393 FakeDCScope.setEntity(DC);
18394 DCScope = &FakeDCScope;
18395 }
18396
18397 bool AddToScope = true;
18398 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
18399 TemplateParams, AddToScope);
18400 if (!ND) return nullptr;
18401
18402 assert(ND->getLexicalDeclContext() == CurContext);
18403
18404 // If we performed typo correction, we might have added a scope specifier
18405 // and changed the decl context.
18406 DC = ND->getDeclContext();
18407
18408 // Add the function declaration to the appropriate lookup tables,
18409 // adjusting the redeclarations list as necessary. We don't
18410 // want to do this yet if the friending class is dependent.
18411 //
18412 // Also update the scope-based lookup if the target context's
18413 // lookup context is in lexical scope.
18414 if (!CurContext->isDependentContext()) {
18415 DC = DC->getRedeclContext();
18416 DC->makeDeclVisibleInContext(ND);
18417 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
18418 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
18419 }
18420
18421 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
18422 D.getIdentifierLoc(), ND,
18423 DS.getFriendSpecLoc());
18424 FrD->setAccess(AS_public);
18425 CurContext->addDecl(FrD);
18426
18427 if (ND->isInvalidDecl()) {
18428 FrD->setInvalidDecl();
18429 } else {
18430 if (DC->isRecord()) CheckFriendAccess(ND);
18431
18432 FunctionDecl *FD;
18433 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
18434 FD = FTD->getTemplatedDecl();
18435 else
18436 FD = cast<FunctionDecl>(ND);
18437
18438 // C++ [class.friend]p6:
18439 // A function may be defined in a friend declaration of a class if and
18440 // only if the class is a non-local class, and the function name is
18441 // unqualified.
18442 if (D.isFunctionDefinition()) {
18443 // Qualified friend function definition.
18444 if (SS.isNotEmpty()) {
18445 // FIXME: We should only do this if the scope specifier names the
18446 // innermost enclosing namespace; otherwise the fixit changes the
18447 // meaning of the code.
18448 SemaDiagnosticBuilder DB =
18449 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
18450
18451 DB << SS.getScopeRep();
18452 if (DC->isFileContext())
18453 DB << FixItHint::CreateRemoval(SS.getRange());
18454
18455 // Friend function defined in a local class.
18456 } else if (FunctionContainingLocalClass) {
18457 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
18458
18459 // Per [basic.pre]p4, a template-id is not a name. Therefore, if we have
18460 // a template-id, the function name is not unqualified because these is
18461 // no name. While the wording requires some reading in-between the
18462 // lines, GCC, MSVC, and EDG all consider a friend function
18463 // specialization definitions to be de facto explicit specialization
18464 // and diagnose them as such.
18465 } else if (isTemplateId) {
18466 Diag(NameInfo.getBeginLoc(), diag::err_friend_specialization_def);
18467 }
18468 }
18469
18470 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
18471 // default argument expression, that declaration shall be a definition
18472 // and shall be the only declaration of the function or function
18473 // template in the translation unit.
18474 if (functionDeclHasDefaultArgument(FD)) {
18475 // We can't look at FD->getPreviousDecl() because it may not have been set
18476 // if we're in a dependent context. If the function is known to be a
18477 // redeclaration, we will have narrowed Previous down to the right decl.
18478 if (D.isRedeclaration()) {
18479 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
18480 Diag(Previous.getRepresentativeDecl()->getLocation(),
18481 diag::note_previous_declaration);
18482 } else if (!D.isFunctionDefinition())
18483 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
18484 }
18485
18486 // Mark templated-scope function declarations as unsupported.
18487 if (FD->getNumTemplateParameterLists() && SS.isValid()) {
18488 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
18489 << SS.getScopeRep() << SS.getRange()
18490 << cast<CXXRecordDecl>(CurContext);
18491 FrD->setUnsupportedFriend(true);
18492 }
18493 }
18494
18495 warnOnReservedIdentifier(ND);
18496
18497 return ND;
18498 }
18499
18500 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc,
18501 StringLiteral *Message) {
18502 AdjustDeclIfTemplate(Dcl);
18503
18504 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
18505 if (!Fn) {
18506 Diag(DelLoc, diag::err_deleted_non_function);
18507 return;
18508 }
18509
18510 // Deleted function does not have a body.
18511 Fn->setWillHaveBody(false);
18512
18513 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
18514 // Don't consider the implicit declaration we generate for explicit
18515 // specializations. FIXME: Do not generate these implicit declarations.
18516 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
18517 Prev->getPreviousDecl()) &&
18518 !Prev->isDefined()) {
18519 Diag(DelLoc, diag::err_deleted_decl_not_first);
18520 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
18521 Prev->isImplicit() ? diag::note_previous_implicit_declaration
18522 : diag::note_previous_declaration);
18523 // We can't recover from this; the declaration might have already
18524 // been used.
18525 Fn->setInvalidDecl();
18526 return;
18527 }
18528
18529 // To maintain the invariant that functions are only deleted on their first
18530 // declaration, mark the implicitly-instantiated declaration of the
18531 // explicitly-specialized function as deleted instead of marking the
18532 // instantiated redeclaration.
18533 Fn = Fn->getCanonicalDecl();
18534 }
18535
18536 // dllimport/dllexport cannot be deleted.
18537 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
18538 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
18539 Fn->setInvalidDecl();
18540 }
18541
18542 // C++11 [basic.start.main]p3:
18543 // A program that defines main as deleted [...] is ill-formed.
18544 if (Fn->isMain())
18545 Diag(DelLoc, diag::err_deleted_main);
18546
18547 // C++11 [dcl.fct.def.delete]p4:
18548 // A deleted function is implicitly inline.
18549 Fn->setImplicitlyInline();
18550 Fn->setDeletedAsWritten(true, Message);
18551 }
18552
18553 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
18554 if (!Dcl || Dcl->isInvalidDecl())
18555 return;
18556
18557 auto *FD = dyn_cast<FunctionDecl>(Dcl);
18558 if (!FD) {
18559 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) {
18560 if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) {
18561 Diag(DefaultLoc, diag::err_defaulted_comparison_template);
18562 return;
18563 }
18564 }
18565
18566 Diag(DefaultLoc, diag::err_default_special_members)
18567 << getLangOpts().CPlusPlus20;
18568 return;
18569 }
18570
18571 // Reject if this can't possibly be a defaultable function.
18572 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
18573 if (!DefKind &&
18574 // A dependent function that doesn't locally look defaultable can
18575 // still instantiate to a defaultable function if it's a constructor
18576 // or assignment operator.
18577 (!FD->isDependentContext() ||
18578 (!isa<CXXConstructorDecl>(FD) &&
18579 FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) {
18580 Diag(DefaultLoc, diag::err_default_special_members)
18581 << getLangOpts().CPlusPlus20;
18582 return;
18583 }
18584
18585 // Issue compatibility warning. We already warned if the operator is
18586 // 'operator<=>' when parsing the '<=>' token.
18587 if (DefKind.isComparison() &&
18588 DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) {
18589 Diag(DefaultLoc, getLangOpts().CPlusPlus20
18590 ? diag::warn_cxx17_compat_defaulted_comparison
18591 : diag::ext_defaulted_comparison);
18592 }
18593
18594 FD->setDefaulted();
18595 FD->setExplicitlyDefaulted();
18596 FD->setDefaultLoc(DefaultLoc);
18597
18598 // Defer checking functions that are defaulted in a dependent context.
18599 if (FD->isDependentContext())
18600 return;
18601
18602 // Unset that we will have a body for this function. We might not,
18603 // if it turns out to be trivial, and we don't need this marking now
18604 // that we've marked it as defaulted.
18605 FD->setWillHaveBody(false);
18606
18607 if (DefKind.isComparison()) {
18608 // If this comparison's defaulting occurs within the definition of its
18609 // lexical class context, we have to do the checking when complete.
18610 if (auto const *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext()))
18611 if (!RD->isCompleteDefinition())
18612 return;
18613 }
18614
18615 // If this member fn was defaulted on its first declaration, we will have
18616 // already performed the checking in CheckCompletedCXXClass. Such a
18617 // declaration doesn't trigger an implicit definition.
18618 if (isa<CXXMethodDecl>(FD)) {
18619 const FunctionDecl *Primary = FD;
18620 if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
18621 // Ask the template instantiation pattern that actually had the
18622 // '= default' on it.
18623 Primary = Pattern;
18624 if (Primary->getCanonicalDecl()->isDefaulted())
18625 return;
18626 }
18627
18628 if (DefKind.isComparison()) {
18629 if (CheckExplicitlyDefaultedComparison(nullptr, FD, DefKind.asComparison()))
18630 FD->setInvalidDecl();
18631 else
18632 DefineDefaultedComparison(DefaultLoc, FD, DefKind.asComparison());
18633 } else {
18634 auto *MD = cast<CXXMethodDecl>(FD);
18635
18636 if (CheckExplicitlyDefaultedSpecialMember(MD, DefKind.asSpecialMember(),
18637 DefaultLoc))
18638 MD->setInvalidDecl();
18639 else
18640 DefineDefaultedFunction(*this, MD, DefaultLoc);
18641 }
18642 }
18643
18644 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
18645 for (Stmt *SubStmt : S->children()) {
18646 if (!SubStmt)
18647 continue;
18648 if (isa<ReturnStmt>(SubStmt))
18649 Self.Diag(SubStmt->getBeginLoc(),
18650 diag::err_return_in_constructor_handler);
18651 if (!isa<Expr>(SubStmt))
18652 SearchForReturnInStmt(Self, SubStmt);
18653 }
18654 }
18655
18656 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
18657 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
18658 CXXCatchStmt *Handler = TryBlock->getHandler(I);
18659 SearchForReturnInStmt(*this, Handler);
18660 }
18661 }
18662
18663 void Sema::SetFunctionBodyKind(Decl *D, SourceLocation Loc, FnBodyKind BodyKind,
18664 StringLiteral *DeletedMessage) {
18665 switch (BodyKind) {
18666 case FnBodyKind::Delete:
18667 SetDeclDeleted(D, Loc, DeletedMessage);
18668 break;
18669 case FnBodyKind::Default:
18670 SetDeclDefaulted(D, Loc);
18671 break;
18672 case FnBodyKind::Other:
18673 llvm_unreachable(
18674 "Parsed function body should be '= delete;' or '= default;'");
18675 }
18676 }
18677
18678 bool Sema::CheckOverridingFunctionAttributes(CXXMethodDecl *New,
18679 const CXXMethodDecl *Old) {
18680 const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
18681 const auto *OldFT = Old->getType()->castAs<FunctionProtoType>();
18682
18683 if (OldFT->hasExtParameterInfos()) {
18684 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
18685 // A parameter of the overriding method should be annotated with noescape
18686 // if the corresponding parameter of the overridden method is annotated.
18687 if (OldFT->getExtParameterInfo(I).isNoEscape() &&
18688 !NewFT->getExtParameterInfo(I).isNoEscape()) {
18689 Diag(New->getParamDecl(I)->getLocation(),
18690 diag::warn_overriding_method_missing_noescape);
18691 Diag(Old->getParamDecl(I)->getLocation(),
18692 diag::note_overridden_marked_noescape);
18693 }
18694 }
18695
18696 // SME attributes must match when overriding a function declaration.
18697 if (IsInvalidSMECallConversion(Old->getType(), New->getType())) {
18698 Diag(New->getLocation(), diag::err_conflicting_overriding_attributes)
18699 << New << New->getType() << Old->getType();
18700 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
18701 return true;
18702 }
18703
18704 // Virtual overrides must have the same code_seg.
18705 const auto *OldCSA = Old->getAttr<CodeSegAttr>();
18706 const auto *NewCSA = New->getAttr<CodeSegAttr>();
18707 if ((NewCSA || OldCSA) &&
18708 (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
18709 Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
18710 Diag(Old->getLocation(), diag::note_previous_declaration);
18711 return true;
18712 }
18713
18714 // Virtual overrides: check for matching effects.
18715 if (Context.hasAnyFunctionEffects()) {
18716 const auto OldFX = Old->getFunctionEffects();
18717 const auto NewFXOrig = New->getFunctionEffects();
18718
18719 if (OldFX != NewFXOrig) {
18720 FunctionEffectSet NewFX(NewFXOrig);
18721 const auto Diffs = FunctionEffectDiffVector(OldFX, NewFX);
18722 FunctionEffectSet::Conflicts Errs;
18723 for (const auto &Diff : Diffs) {
18724 switch (Diff.shouldDiagnoseMethodOverride(*Old, OldFX, *New, NewFX)) {
18725 case FunctionEffectDiff::OverrideResult::NoAction:
18726 break;
18727 case FunctionEffectDiff::OverrideResult::Warn:
18728 Diag(New->getLocation(), diag::warn_conflicting_func_effect_override)
18729 << Diff.effectName();
18730 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18731 << Old->getReturnTypeSourceRange();
18732 break;
18733 case FunctionEffectDiff::OverrideResult::Merge: {
18734 NewFX.insert(Diff.Old.value(), Errs);
18735 const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
18736 FunctionProtoType::ExtProtoInfo EPI = NewFT->getExtProtoInfo();
18737 EPI.FunctionEffects = FunctionEffectsRef(NewFX);
18738 QualType ModQT = Context.getFunctionType(NewFT->getReturnType(),
18739 NewFT->getParamTypes(), EPI);
18740 New->setType(ModQT);
18741 if (Errs.empty()) {
18742 // A warning here is somewhat pedantic. Skip this if there was
18743 // already a merge conflict, which is more serious.
18744 Diag(New->getLocation(), diag::warn_mismatched_func_effect_override)
18745 << Diff.effectName();
18746 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18747 << Old->getReturnTypeSourceRange();
18748 }
18749 break;
18750 }
18751 }
18752 }
18753 if (!Errs.empty())
18754 diagnoseFunctionEffectMergeConflicts(Errs, New->getLocation(),
18755 Old->getLocation());
18756 }
18757 }
18758
18759 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
18760
18761 // If the calling conventions match, everything is fine
18762 if (NewCC == OldCC)
18763 return false;
18764
18765 // If the calling conventions mismatch because the new function is static,
18766 // suppress the calling convention mismatch error; the error about static
18767 // function override (err_static_overrides_virtual from
18768 // Sema::CheckFunctionDeclaration) is more clear.
18769 if (New->getStorageClass() == SC_Static)
18770 return false;
18771
18772 Diag(New->getLocation(),
18773 diag::err_conflicting_overriding_cc_attributes)
18774 << New->getDeclName() << New->getType() << Old->getType();
18775 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
18776 return true;
18777 }
18778
18779 bool Sema::CheckExplicitObjectOverride(CXXMethodDecl *New,
18780 const CXXMethodDecl *Old) {
18781 // CWG2553
18782 // A virtual function shall not be an explicit object member function.
18783 if (!New->isExplicitObjectMemberFunction())
18784 return true;
18785 Diag(New->getParamDecl(0)->getBeginLoc(),
18786 diag::err_explicit_object_parameter_nonmember)
18787 << New->getSourceRange() << /*virtual*/ 1 << /*IsLambda*/ false;
18788 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
18789 New->setInvalidDecl();
18790 return false;
18791 }
18792
18793 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
18794 const CXXMethodDecl *Old) {
18795 QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType();
18796 QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType();
18797
18798 if (Context.hasSameType(NewTy, OldTy) ||
18799 NewTy->isDependentType() || OldTy->isDependentType())
18800 return false;
18801
18802 // Check if the return types are covariant
18803 QualType NewClassTy, OldClassTy;
18804
18805 /// Both types must be pointers or references to classes.
18806 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
18807 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
18808 NewClassTy = NewPT->getPointeeType();
18809 OldClassTy = OldPT->getPointeeType();
18810 }
18811 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
18812 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
18813 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
18814 NewClassTy = NewRT->getPointeeType();
18815 OldClassTy = OldRT->getPointeeType();
18816 }
18817 }
18818 }
18819
18820 // The return types aren't either both pointers or references to a class type.
18821 if (NewClassTy.isNull() || !NewClassTy->isStructureOrClassType()) {
18822 Diag(New->getLocation(),
18823 diag::err_different_return_type_for_overriding_virtual_function)
18824 << New->getDeclName() << NewTy << OldTy
18825 << New->getReturnTypeSourceRange();
18826 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18827 << Old->getReturnTypeSourceRange();
18828
18829 return true;
18830 }
18831
18832 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
18833 // C++14 [class.virtual]p8:
18834 // If the class type in the covariant return type of D::f differs from
18835 // that of B::f, the class type in the return type of D::f shall be
18836 // complete at the point of declaration of D::f or shall be the class
18837 // type D.
18838 if (const auto *RD = NewClassTy->getAsCXXRecordDecl()) {
18839 if (!RD->isBeingDefined() &&
18840 RequireCompleteType(New->getLocation(), NewClassTy,
18841 diag::err_covariant_return_incomplete,
18842 New->getDeclName()))
18843 return true;
18844 }
18845
18846 // Check if the new class derives from the old class.
18847 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
18848 Diag(New->getLocation(), diag::err_covariant_return_not_derived)
18849 << New->getDeclName() << NewTy << OldTy
18850 << New->getReturnTypeSourceRange();
18851 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18852 << Old->getReturnTypeSourceRange();
18853 return true;
18854 }
18855
18856 // Check if we the conversion from derived to base is valid.
18857 if (CheckDerivedToBaseConversion(
18858 NewClassTy, OldClassTy,
18859 diag::err_covariant_return_inaccessible_base,
18860 diag::err_covariant_return_ambiguous_derived_to_base_conv,
18861 New->getLocation(), New->getReturnTypeSourceRange(),
18862 New->getDeclName(), nullptr)) {
18863 // FIXME: this note won't trigger for delayed access control
18864 // diagnostics, and it's impossible to get an undelayed error
18865 // here from access control during the original parse because
18866 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
18867 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18868 << Old->getReturnTypeSourceRange();
18869 return true;
18870 }
18871 }
18872
18873 // The qualifiers of the return types must be the same.
18874 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
18875 Diag(New->getLocation(),
18876 diag::err_covariant_return_type_different_qualifications)
18877 << New->getDeclName() << NewTy << OldTy
18878 << New->getReturnTypeSourceRange();
18879 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18880 << Old->getReturnTypeSourceRange();
18881 return true;
18882 }
18883
18884
18885 // The new class type must have the same or less qualifiers as the old type.
18886 if (!OldClassTy.isAtLeastAsQualifiedAs(NewClassTy, getASTContext())) {
18887 Diag(New->getLocation(),
18888 diag::err_covariant_return_type_class_type_not_same_or_less_qualified)
18889 << New->getDeclName() << NewTy << OldTy
18890 << New->getReturnTypeSourceRange();
18891 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18892 << Old->getReturnTypeSourceRange();
18893 return true;
18894 }
18895
18896 return false;
18897 }
18898
18899 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
18900 SourceLocation EndLoc = InitRange.getEnd();
18901 if (EndLoc.isValid())
18902 Method->setRangeEnd(EndLoc);
18903
18904 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
18905 Method->setIsPureVirtual();
18906 return false;
18907 }
18908
18909 if (!Method->isInvalidDecl())
18910 Diag(Method->getLocation(), diag::err_non_virtual_pure)
18911 << Method->getDeclName() << InitRange;
18912 return true;
18913 }
18914
18915 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
18916 if (D->getFriendObjectKind())
18917 Diag(D->getLocation(), diag::err_pure_friend);
18918 else if (auto *M = dyn_cast<CXXMethodDecl>(D))
18919 CheckPureMethod(M, ZeroLoc);
18920 else
18921 Diag(D->getLocation(), diag::err_illegal_initializer);
18922 }
18923
18924 /// Invoked when we are about to parse an initializer for the declaration
18925 /// 'Dcl'.
18926 ///
18927 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
18928 /// static data member of class X, names should be looked up in the scope of
18929 /// class X. If the declaration had a scope specifier, a scope will have
18930 /// been created and passed in for this purpose. Otherwise, S will be null.
18931 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
18932 assert(D && !D->isInvalidDecl());
18933
18934 // We will always have a nested name specifier here, but this declaration
18935 // might not be out of line if the specifier names the current namespace:
18936 // extern int n;
18937 // int ::n = 0;
18938 if (S && D->isOutOfLine())
18939 EnterDeclaratorContext(S, D->getDeclContext());
18940
18941 PushExpressionEvaluationContext(
18942 ExpressionEvaluationContext::PotentiallyEvaluated, D,
18943 ExpressionEvaluationContextRecord::EK_VariableInit);
18944 }
18945
18946 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
18947 assert(D);
18948
18949 if (S && D->isOutOfLine())
18950 ExitDeclaratorContext(S);
18951
18952 PopExpressionEvaluationContext();
18953 }
18954
18955 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
18956 // C++ 6.4p2:
18957 // The declarator shall not specify a function or an array.
18958 // The type-specifier-seq shall not contain typedef and shall not declare a
18959 // new class or enumeration.
18960 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
18961 "Parser allowed 'typedef' as storage class of condition decl.");
18962
18963 Decl *Dcl = ActOnDeclarator(S, D);
18964 if (!Dcl)
18965 return true;
18966
18967 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
18968 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
18969 << D.getSourceRange();
18970 return true;
18971 }
18972
18973 if (auto *VD = dyn_cast<VarDecl>(Dcl))
18974 VD->setCXXCondDecl();
18975
18976 return Dcl;
18977 }
18978
18979 void Sema::LoadExternalVTableUses() {
18980 if (!ExternalSource)
18981 return;
18982
18983 SmallVector<ExternalVTableUse, 4> VTables;
18984 ExternalSource->ReadUsedVTables(VTables);
18985 SmallVector<VTableUse, 4> NewUses;
18986 for (const ExternalVTableUse &VTable : VTables) {
18987 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos =
18988 VTablesUsed.find(VTable.Record);
18989 // Even if a definition wasn't required before, it may be required now.
18990 if (Pos != VTablesUsed.end()) {
18991 if (!Pos->second && VTable.DefinitionRequired)
18992 Pos->second = true;
18993 continue;
18994 }
18995
18996 VTablesUsed[VTable.Record] = VTable.DefinitionRequired;
18997 NewUses.push_back(VTableUse(VTable.Record, VTable.Location));
18998 }
18999
19000 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
19001 }
19002
19003 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
19004 bool DefinitionRequired) {
19005 // Ignore any vtable uses in unevaluated operands or for classes that do
19006 // not have a vtable.
19007 if (!Class->isDynamicClass() || Class->isDependentContext() ||
19008 CurContext->isDependentContext() || isUnevaluatedContext())
19009 return;
19010 // Do not mark as used if compiling for the device outside of the target
19011 // region.
19012 if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice &&
19013 !OpenMP().isInOpenMPDeclareTargetContext() &&
19014 !OpenMP().isInOpenMPTargetExecutionDirective()) {
19015 if (!DefinitionRequired)
19016 MarkVirtualMembersReferenced(Loc, Class);
19017 return;
19018 }
19019
19020 // Try to insert this class into the map.
19021 LoadExternalVTableUses();
19022 Class = Class->getCanonicalDecl();
19023 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
19024 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
19025 if (!Pos.second) {
19026 // If we already had an entry, check to see if we are promoting this vtable
19027 // to require a definition. If so, we need to reappend to the VTableUses
19028 // list, since we may have already processed the first entry.
19029 if (DefinitionRequired && !Pos.first->second) {
19030 Pos.first->second = true;
19031 } else {
19032 // Otherwise, we can early exit.
19033 return;
19034 }
19035 } else {
19036 // The Microsoft ABI requires that we perform the destructor body
19037 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
19038 // the deleting destructor is emitted with the vtable, not with the
19039 // destructor definition as in the Itanium ABI.
19040 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
19041 CXXDestructorDecl *DD = Class->getDestructor();
19042 if (DD && DD->isVirtual() && !DD->isDeleted()) {
19043 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
19044 // If this is an out-of-line declaration, marking it referenced will
19045 // not do anything. Manually call CheckDestructor to look up operator
19046 // delete().
19047 ContextRAII SavedContext(*this, DD);
19048 CheckDestructor(DD);
19049 } else {
19050 MarkFunctionReferenced(Loc, Class->getDestructor());
19051 }
19052 }
19053 }
19054 }
19055
19056 // Local classes need to have their virtual members marked
19057 // immediately. For all other classes, we mark their virtual members
19058 // at the end of the translation unit.
19059 if (Class->isLocalClass())
19060 MarkVirtualMembersReferenced(Loc, Class->getDefinition());
19061 else
19062 VTableUses.push_back(std::make_pair(Class, Loc));
19063 }
19064
19065 bool Sema::DefineUsedVTables() {
19066 LoadExternalVTableUses();
19067 if (VTableUses.empty())
19068 return false;
19069
19070 // Note: The VTableUses vector could grow as a result of marking
19071 // the members of a class as "used", so we check the size each
19072 // time through the loop and prefer indices (which are stable) to
19073 // iterators (which are not).
19074 bool DefinedAnything = false;
19075 for (unsigned I = 0; I != VTableUses.size(); ++I) {
19076 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
19077 if (!Class)
19078 continue;
19079 TemplateSpecializationKind ClassTSK =
19080 Class->getTemplateSpecializationKind();
19081
19082 SourceLocation Loc = VTableUses[I].second;
19083
19084 bool DefineVTable = true;
19085
19086 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
19087 // V-tables for non-template classes with an owning module are always
19088 // uniquely emitted in that module.
19089 if (Class->isInCurrentModuleUnit()) {
19090 DefineVTable = true;
19091 } else if (KeyFunction && !KeyFunction->hasBody()) {
19092 // If this class has a key function, but that key function is
19093 // defined in another translation unit, we don't need to emit the
19094 // vtable even though we're using it.
19095 // The key function is in another translation unit.
19096 DefineVTable = false;
19097 TemplateSpecializationKind TSK =
19098 KeyFunction->getTemplateSpecializationKind();
19099 assert(TSK != TSK_ExplicitInstantiationDefinition &&
19100 TSK != TSK_ImplicitInstantiation &&
19101 "Instantiations don't have key functions");
19102 (void)TSK;
19103 } else if (!KeyFunction) {
19104 // If we have a class with no key function that is the subject
19105 // of an explicit instantiation declaration, suppress the
19106 // vtable; it will live with the explicit instantiation
19107 // definition.
19108 bool IsExplicitInstantiationDeclaration =
19109 ClassTSK == TSK_ExplicitInstantiationDeclaration;
19110 for (auto *R : Class->redecls()) {
19111 TemplateSpecializationKind TSK
19112 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
19113 if (TSK == TSK_ExplicitInstantiationDeclaration)
19114 IsExplicitInstantiationDeclaration = true;
19115 else if (TSK == TSK_ExplicitInstantiationDefinition) {
19116 IsExplicitInstantiationDeclaration = false;
19117 break;
19118 }
19119 }
19120
19121 if (IsExplicitInstantiationDeclaration)
19122 DefineVTable = false;
19123 }
19124
19125 // The exception specifications for all virtual members may be needed even
19126 // if we are not providing an authoritative form of the vtable in this TU.
19127 // We may choose to emit it available_externally anyway.
19128 if (!DefineVTable) {
19129 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
19130 continue;
19131 }
19132
19133 // Mark all of the virtual members of this class as referenced, so
19134 // that we can build a vtable. Then, tell the AST consumer that a
19135 // vtable for this class is required.
19136 DefinedAnything = true;
19137 MarkVirtualMembersReferenced(Loc, Class);
19138 CXXRecordDecl *Canonical = Class->getCanonicalDecl();
19139 if (VTablesUsed[Canonical] && !Class->shouldEmitInExternalSource())
19140 Consumer.HandleVTable(Class);
19141
19142 // Warn if we're emitting a weak vtable. The vtable will be weak if there is
19143 // no key function or the key function is inlined. Don't warn in C++ ABIs
19144 // that lack key functions, since the user won't be able to make one.
19145 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
19146 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation &&
19147 ClassTSK != TSK_ExplicitInstantiationDefinition) {
19148 const FunctionDecl *KeyFunctionDef = nullptr;
19149 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
19150 KeyFunctionDef->isInlined()))
19151 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
19152 }
19153 }
19154 VTableUses.clear();
19155
19156 return DefinedAnything;
19157 }
19158
19159 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
19160 const CXXRecordDecl *RD) {
19161 for (const auto *I : RD->methods())
19162 if (I->isVirtual() && !I->isPureVirtual())
19163 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
19164 }
19165
19166 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
19167 const CXXRecordDecl *RD,
19168 bool ConstexprOnly) {
19169 // Mark all functions which will appear in RD's vtable as used.
19170 CXXFinalOverriderMap FinalOverriders;
19171 RD->getFinalOverriders(FinalOverriders);
19172 for (const auto &FinalOverrider : FinalOverriders) {
19173 for (const auto &OverridingMethod : FinalOverrider.second) {
19174 assert(OverridingMethod.second.size() > 0 && "no final overrider");
19175 CXXMethodDecl *Overrider = OverridingMethod.second.front().Method;
19176
19177 // C++ [basic.def.odr]p2:
19178 // [...] A virtual member function is used if it is not pure. [...]
19179 if (!Overrider->isPureVirtual() &&
19180 (!ConstexprOnly || Overrider->isConstexpr()))
19181 MarkFunctionReferenced(Loc, Overrider);
19182 }
19183 }
19184
19185 // Only classes that have virtual bases need a VTT.
19186 if (RD->getNumVBases() == 0)
19187 return;
19188
19189 for (const auto &I : RD->bases()) {
19190 const auto *Base = I.getType()->castAsCXXRecordDecl();
19191 if (Base->getNumVBases() == 0)
19192 continue;
19193 MarkVirtualMembersReferenced(Loc, Base);
19194 }
19195 }
19196
19197 static
19198 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
19199 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
19200 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
19201 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
19202 Sema &S) {
19203 if (Ctor->isInvalidDecl())
19204 return;
19205
19206 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
19207
19208 // Target may not be determinable yet, for instance if this is a dependent
19209 // call in an uninstantiated template.
19210 if (Target) {
19211 const FunctionDecl *FNTarget = nullptr;
19212 (void)Target->hasBody(FNTarget);
19213 Target = const_cast<CXXConstructorDecl*>(
19214 cast_or_null<CXXConstructorDecl>(FNTarget));
19215 }
19216
19217 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
19218 // Avoid dereferencing a null pointer here.
19219 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
19220
19221 if (!Current.insert(Canonical).second)
19222 return;
19223
19224 // We know that beyond here, we aren't chaining into a cycle.
19225 if (!Target || !Target->isDelegatingConstructor() ||
19226 Target->isInvalidDecl() || Valid.count(TCanonical)) {
19227 Valid.insert_range(Current);
19228 Current.clear();
19229 // We've hit a cycle.
19230 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
19231 Current.count(TCanonical)) {
19232 // If we haven't diagnosed this cycle yet, do so now.
19233 if (!Invalid.count(TCanonical)) {
19234 S.Diag((*Ctor->init_begin())->getSourceLocation(),
19235 diag::warn_delegating_ctor_cycle)
19236 << Ctor;
19237
19238 // Don't add a note for a function delegating directly to itself.
19239 if (TCanonical != Canonical)
19240 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
19241
19242 CXXConstructorDecl *C = Target;
19243 while (C->getCanonicalDecl() != Canonical) {
19244 const FunctionDecl *FNTarget = nullptr;
19245 (void)C->getTargetConstructor()->hasBody(FNTarget);
19246 assert(FNTarget && "Ctor cycle through bodiless function");
19247
19248 C = const_cast<CXXConstructorDecl*>(
19249 cast<CXXConstructorDecl>(FNTarget));
19250 S.Diag(C->getLocation(), diag::note_which_delegates_to);
19251 }
19252 }
19253
19254 Invalid.insert_range(Current);
19255 Current.clear();
19256 } else {
19257 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
19258 }
19259 }
19260
19261
19262 void Sema::CheckDelegatingCtorCycles() {
19263 llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
19264
19265 for (DelegatingCtorDeclsType::iterator
19266 I = DelegatingCtorDecls.begin(ExternalSource.get()),
19267 E = DelegatingCtorDecls.end();
19268 I != E; ++I)
19269 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
19270
19271 for (CXXConstructorDecl *CI : Invalid)
19272 CI->setInvalidDecl();
19273 }
19274
19275 namespace {
19276 /// AST visitor that finds references to the 'this' expression.
19277 class FindCXXThisExpr : public DynamicRecursiveASTVisitor {
19278 Sema &S;
19279
19280 public:
19281 explicit FindCXXThisExpr(Sema &S) : S(S) {}
19282
19283 bool VisitCXXThisExpr(CXXThisExpr *E) override {
19284 S.Diag(E->getLocation(), diag::err_this_static_member_func)
19285 << E->isImplicit();
19286 return false;
19287 }
19288 };
19289 }
19290
19291 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
19292 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
19293 if (!TSInfo)
19294 return false;
19295
19296 TypeLoc TL = TSInfo->getTypeLoc();
19297 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
19298 if (!ProtoTL)
19299 return false;
19300
19301 // C++11 [expr.prim.general]p3:
19302 // [The expression this] shall not appear before the optional
19303 // cv-qualifier-seq and it shall not appear within the declaration of a
19304 // static member function (although its type and value category are defined
19305 // within a static member function as they are within a non-static member
19306 // function). [ Note: this is because declaration matching does not occur
19307 // until the complete declarator is known. - end note ]
19308 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
19309 FindCXXThisExpr Finder(*this);
19310
19311 // If the return type came after the cv-qualifier-seq, check it now.
19312 if (Proto->hasTrailingReturn() &&
19313 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
19314 return true;
19315
19316 // Check the exception specification.
19317 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
19318 return true;
19319
19320 // Check the trailing requires clause
19321 if (const AssociatedConstraint &TRC = Method->getTrailingRequiresClause())
19322 if (!Finder.TraverseStmt(const_cast<Expr *>(TRC.ConstraintExpr)))
19323 return true;
19324
19325 return checkThisInStaticMemberFunctionAttributes(Method);
19326 }
19327
19328 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
19329 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
19330 if (!TSInfo)
19331 return false;
19332
19333 TypeLoc TL = TSInfo->getTypeLoc();
19334 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
19335 if (!ProtoTL)
19336 return false;
19337
19338 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
19339 FindCXXThisExpr Finder(*this);
19340
19341 switch (Proto->getExceptionSpecType()) {
19342 case EST_Unparsed:
19343 case EST_Uninstantiated:
19344 case EST_Unevaluated:
19345 case EST_BasicNoexcept:
19346 case EST_NoThrow:
19347 case EST_DynamicNone:
19348 case EST_MSAny:
19349 case EST_None:
19350 break;
19351
19352 case EST_DependentNoexcept:
19353 case EST_NoexceptFalse:
19354 case EST_NoexceptTrue:
19355 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
19356 return true;
19357 [[fallthrough]];
19358
19359 case EST_Dynamic:
19360 for (const auto &E : Proto->exceptions()) {
19361 if (!Finder.TraverseType(E))
19362 return true;
19363 }
19364 break;
19365 }
19366
19367 return false;
19368 }
19369
19370 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
19371 FindCXXThisExpr Finder(*this);
19372
19373 // Check attributes.
19374 for (const auto *A : Method->attrs()) {
19375 // FIXME: This should be emitted by tblgen.
19376 Expr *Arg = nullptr;
19377 ArrayRef<Expr *> Args;
19378 if (const auto *G = dyn_cast<GuardedByAttr>(A))
19379 Arg = G->getArg();
19380 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
19381 Arg = G->getArg();
19382 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
19383 Args = llvm::ArrayRef(AA->args_begin(), AA->args_size());
19384 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
19385 Args = llvm::ArrayRef(AB->args_begin(), AB->args_size());
19386 else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
19387 Arg = LR->getArg();
19388 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
19389 Args = llvm::ArrayRef(LE->args_begin(), LE->args_size());
19390 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
19391 Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());
19392 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
19393 Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());
19394 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) {
19395 Arg = AC->getSuccessValue();
19396 Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());
19397 } else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
19398 Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());
19399
19400 if (Arg && !Finder.TraverseStmt(Arg))
19401 return true;
19402
19403 for (Expr *A : Args) {
19404 if (!Finder.TraverseStmt(A))
19405 return true;
19406 }
19407 }
19408
19409 return false;
19410 }
19411
19412 void Sema::checkExceptionSpecification(
19413 bool IsTopLevel, ExceptionSpecificationType EST,
19414 ArrayRef<ParsedType> DynamicExceptions,
19415 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
19416 SmallVectorImpl<QualType> &Exceptions,
19417 FunctionProtoType::ExceptionSpecInfo &ESI) {
19418 Exceptions.clear();
19419 ESI.Type = EST;
19420 if (EST == EST_Dynamic) {
19421 Exceptions.reserve(DynamicExceptions.size());
19422 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
19423 // FIXME: Preserve type source info.
19424 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
19425
19426 if (IsTopLevel) {
19427 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
19428 collectUnexpandedParameterPacks(ET, Unexpanded);
19429 if (!Unexpanded.empty()) {
19430 DiagnoseUnexpandedParameterPacks(
19431 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
19432 Unexpanded);
19433 continue;
19434 }
19435 }
19436
19437 // Check that the type is valid for an exception spec, and
19438 // drop it if not.
19439 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
19440 Exceptions.push_back(ET);
19441 }
19442 ESI.Exceptions = Exceptions;
19443 return;
19444 }
19445
19446 if (isComputedNoexcept(EST)) {
19447 assert((NoexceptExpr->isTypeDependent() ||
19448 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
19449 Context.BoolTy) &&
19450 "Parser should have made sure that the expression is boolean");
19451 if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
19452 ESI.Type = EST_BasicNoexcept;
19453 return;
19454 }
19455
19456 ESI.NoexceptExpr = NoexceptExpr;
19457 return;
19458 }
19459 }
19460
19461 void Sema::actOnDelayedExceptionSpecification(
19462 Decl *D, ExceptionSpecificationType EST, SourceRange SpecificationRange,
19463 ArrayRef<ParsedType> DynamicExceptions,
19464 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr) {
19465 if (!D)
19466 return;
19467
19468 // Dig out the function we're referring to.
19469 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
19470 D = FTD->getTemplatedDecl();
19471
19472 FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
19473 if (!FD)
19474 return;
19475
19476 // Check the exception specification.
19477 llvm::SmallVector<QualType, 4> Exceptions;
19478 FunctionProtoType::ExceptionSpecInfo ESI;
19479 checkExceptionSpecification(/*IsTopLevel=*/true, EST, DynamicExceptions,
19480 DynamicExceptionRanges, NoexceptExpr, Exceptions,
19481 ESI);
19482
19483 // Update the exception specification on the function type.
19484 Context.adjustExceptionSpec(FD, ESI, /*AsWritten=*/true);
19485
19486 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
19487 if (MD->isStatic())
19488 checkThisInStaticMemberFunctionExceptionSpec(MD);
19489
19490 if (MD->isVirtual()) {
19491 // Check overrides, which we previously had to delay.
19492 for (const CXXMethodDecl *O : MD->overridden_methods())
19493 CheckOverridingFunctionExceptionSpec(MD, O);
19494 }
19495 }
19496 }
19497
19498 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
19499 ///
19500 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
19501 SourceLocation DeclStart, Declarator &D,
19502 Expr *BitWidth,
19503 InClassInitStyle InitStyle,
19504 AccessSpecifier AS,
19505 const ParsedAttr &MSPropertyAttr) {
19506 const IdentifierInfo *II = D.getIdentifier();
19507 if (!II) {
19508 Diag(DeclStart, diag::err_anonymous_property);
19509 return nullptr;
19510 }
19511 SourceLocation Loc = D.getIdentifierLoc();
19512
19513 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
19514 QualType T = TInfo->getType();
19515 if (getLangOpts().CPlusPlus) {
19516 CheckExtraCXXDefaultArguments(D);
19517
19518 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
19519 UPPC_DataMemberType)) {
19520 D.setInvalidType();
19521 T = Context.IntTy;
19522 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
19523 }
19524 }
19525
19526 DiagnoseFunctionSpecifiers(D.getDeclSpec());
19527
19528 if (D.getDeclSpec().isInlineSpecified())
19529 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
19530 << getLangOpts().CPlusPlus17;
19531 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
19532 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
19533 diag::err_invalid_thread)
19534 << DeclSpec::getSpecifierName(TSCS);
19535
19536 // Check to see if this name was declared as a member previously
19537 NamedDecl *PrevDecl = nullptr;
19538 LookupResult Previous(*this, II, Loc, LookupMemberName,
19539 RedeclarationKind::ForVisibleRedeclaration);
19540 LookupName(Previous, S);
19541 switch (Previous.getResultKind()) {
19542 case LookupResultKind::Found:
19543 case LookupResultKind::FoundUnresolvedValue:
19544 PrevDecl = Previous.getAsSingle<NamedDecl>();
19545 break;
19546
19547 case LookupResultKind::FoundOverloaded:
19548 PrevDecl = Previous.getRepresentativeDecl();
19549 break;
19550
19551 case LookupResultKind::NotFound:
19552 case LookupResultKind::NotFoundInCurrentInstantiation:
19553 case LookupResultKind::Ambiguous:
19554 break;
19555 }
19556
19557 if (PrevDecl && PrevDecl->isTemplateParameter()) {
19558 // Maybe we will complain about the shadowed template parameter.
19559 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
19560 // Just pretend that we didn't see the previous declaration.
19561 PrevDecl = nullptr;
19562 }
19563
19564 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
19565 PrevDecl = nullptr;
19566
19567 SourceLocation TSSL = D.getBeginLoc();
19568 MSPropertyDecl *NewPD =
19569 MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
19570 MSPropertyAttr.getPropertyDataGetter(),
19571 MSPropertyAttr.getPropertyDataSetter());
19572 ProcessDeclAttributes(TUScope, NewPD, D);
19573 NewPD->setAccess(AS);
19574
19575 if (NewPD->isInvalidDecl())
19576 Record->setInvalidDecl();
19577
19578 if (D.getDeclSpec().isModulePrivateSpecified())
19579 NewPD->setModulePrivate();
19580
19581 if (NewPD->isInvalidDecl() && PrevDecl) {
19582 // Don't introduce NewFD into scope; there's already something
19583 // with the same name in the same scope.
19584 } else if (II) {
19585 PushOnScopeChains(NewPD, S);
19586 } else
19587 Record->addDecl(NewPD);
19588
19589 return NewPD;
19590 }
19591
19592 void Sema::ActOnStartFunctionDeclarationDeclarator(
19593 Declarator &Declarator, unsigned TemplateParameterDepth) {
19594 auto &Info = InventedParameterInfos.emplace_back();
19595 TemplateParameterList *ExplicitParams = nullptr;
19596 ArrayRef<TemplateParameterList *> ExplicitLists =
19597 Declarator.getTemplateParameterLists();
19598 if (!ExplicitLists.empty()) {
19599 bool IsMemberSpecialization, IsInvalid;
19600 ExplicitParams = MatchTemplateParametersToScopeSpecifier(
19601 Declarator.getBeginLoc(), Declarator.getIdentifierLoc(),
19602 Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr,
19603 ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid,
19604 /*SuppressDiagnostic=*/true);
19605 }
19606 // C++23 [dcl.fct]p23:
19607 // An abbreviated function template can have a template-head. The invented
19608 // template-parameters are appended to the template-parameter-list after
19609 // the explicitly declared template-parameters.
19610 //
19611 // A template-head must have one or more template-parameters (read:
19612 // 'template<>' is *not* a template-head). Only append the invented
19613 // template parameters if we matched the nested-name-specifier to a non-empty
19614 // TemplateParameterList.
19615 if (ExplicitParams && !ExplicitParams->empty()) {
19616 Info.AutoTemplateParameterDepth = ExplicitParams->getDepth();
19617 llvm::append_range(Info.TemplateParams, *ExplicitParams);
19618 Info.NumExplicitTemplateParams = ExplicitParams->size();
19619 } else {
19620 Info.AutoTemplateParameterDepth = TemplateParameterDepth;
19621 Info.NumExplicitTemplateParams = 0;
19622 }
19623 }
19624
19625 void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator &Declarator) {
19626 auto &FSI = InventedParameterInfos.back();
19627 if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) {
19628 if (FSI.NumExplicitTemplateParams != 0) {
19629 TemplateParameterList *ExplicitParams =
19630 Declarator.getTemplateParameterLists().back();
19631 Declarator.setInventedTemplateParameterList(
19632 TemplateParameterList::Create(
19633 Context, ExplicitParams->getTemplateLoc(),
19634 ExplicitParams->getLAngleLoc(), FSI.TemplateParams,
19635 ExplicitParams->getRAngleLoc(),
19636 ExplicitParams->getRequiresClause()));
19637 } else {
19638 Declarator.setInventedTemplateParameterList(TemplateParameterList::Create(
19639 Context, Declarator.getBeginLoc(), SourceLocation(),
19640 FSI.TemplateParams, Declarator.getEndLoc(),
19641 /*RequiresClause=*/nullptr));
19642 }
19643 }
19644 InventedParameterInfos.pop_back();
19645 }