clang 24.0.0git
SemaDeclCXX.cpp
Go to the documentation of this file.
1//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for C++ declarations.
10//
11//===----------------------------------------------------------------------===//
12
13#include "TypeLocBuilder.h"
18#include "clang/AST/CharUnits.h"
20#include "clang/AST/DeclCXX.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/ExprCXX.h"
28#include "clang/AST/TypeLoc.h"
37#include "clang/Sema/DeclSpec.h"
40#include "clang/Sema/Lookup.h"
43#include "clang/Sema/Scope.h"
45#include "clang/Sema/SemaCUDA.h"
47#include "clang/Sema/SemaObjC.h"
50#include "clang/Sema/Template.h"
52#include "llvm/ADT/ArrayRef.h"
53#include "llvm/ADT/STLExtras.h"
54#include "llvm/ADT/StringExtras.h"
55#include "llvm/Support/ConvertUTF.h"
56#include "llvm/Support/SaveAndRestore.h"
57#include <map>
58#include <optional>
59#include <set>
60
61using namespace clang;
62
63//===----------------------------------------------------------------------===//
64// CheckDefaultArgumentVisitor
65//===----------------------------------------------------------------------===//
66
67namespace {
68/// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
69/// the default argument of a parameter to determine whether it
70/// contains any ill-formed subexpressions. For example, this will
71/// diagnose the use of local variables or parameters within the
72/// default argument expression.
73class CheckDefaultArgumentVisitor
74 : public ConstStmtVisitor<CheckDefaultArgumentVisitor, bool> {
75 Sema &S;
76 const Expr *DefaultArg;
77
78public:
79 CheckDefaultArgumentVisitor(Sema &S, const Expr *DefaultArg)
80 : S(S), DefaultArg(DefaultArg) {}
81
82 bool VisitExpr(const Expr *Node);
83 bool VisitDeclRefExpr(const DeclRefExpr *DRE);
84 bool VisitCXXThisExpr(const CXXThisExpr *ThisE);
85 bool VisitLambdaExpr(const LambdaExpr *Lambda);
86 bool VisitPseudoObjectExpr(const PseudoObjectExpr *POE);
87 bool VisitCoawaitExpr(const CoawaitExpr *E);
88 bool VisitCoyieldExpr(const CoyieldExpr *E);
89};
90
91/// VisitExpr - Visit all of the children of this expression.
92bool CheckDefaultArgumentVisitor::VisitExpr(const Expr *Node) {
93 bool IsInvalid = false;
94 for (const Stmt *SubStmt : Node->children())
95 if (SubStmt)
96 IsInvalid |= Visit(SubStmt);
97 return IsInvalid;
98}
99
100/// VisitDeclRefExpr - Visit a reference to a declaration, to
101/// determine whether this declaration can be used in the default
102/// argument expression.
103bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(const DeclRefExpr *DRE) {
104 const ValueDecl *Decl = DRE->getDecl();
105
106 if (!isa<VarDecl, BindingDecl>(Decl))
107 return false;
108
109 if (const auto *Param = dyn_cast<ParmVarDecl>(Decl)) {
110 // C++ [dcl.fct.default]p9:
111 // [...] parameters of a function shall not be used in default
112 // argument expressions, even if they are not evaluated. [...]
113 //
114 // C++17 [dcl.fct.default]p9 (by CWG 2082):
115 // [...] A parameter shall not appear as a potentially-evaluated
116 // expression in a default argument. [...]
117 //
118 if (DRE->isNonOdrUse() != NOUR_Unevaluated)
119 return S.Diag(DRE->getBeginLoc(),
120 diag::err_param_default_argument_references_param)
121 << Param->getDeclName() << DefaultArg->getSourceRange();
122 } else if (auto *VD = Decl->getPotentiallyDecomposedVarDecl()) {
123 // C++ [dcl.fct.default]p7:
124 // Local variables shall not be used in default argument
125 // expressions.
126 //
127 // C++17 [dcl.fct.default]p7 (by CWG 2082):
128 // A local variable shall not appear as a potentially-evaluated
129 // expression in a default argument.
130 //
131 // C++20 [dcl.fct.default]p7 (DR as part of P0588R1, see also CWG 2346):
132 // Note: A local variable cannot be odr-used (6.3) in a default
133 // argument.
134 //
135 if (VD->isLocalVarDecl() && !DRE->isNonOdrUse())
136 return S.Diag(DRE->getBeginLoc(),
137 diag::err_param_default_argument_references_local)
138 << Decl << DefaultArg->getSourceRange();
139 }
140 return false;
141}
142
143/// VisitCXXThisExpr - Visit a C++ "this" expression.
144bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(const CXXThisExpr *ThisE) {
145 // C++ [dcl.fct.default]p8:
146 // The keyword this shall not be used in a default argument of a
147 // member function.
148 return S.Diag(ThisE->getBeginLoc(),
149 diag::err_param_default_argument_references_this)
150 << ThisE->getSourceRange();
151}
152
153bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(
154 const PseudoObjectExpr *POE) {
155 bool Invalid = false;
156 for (const Expr *E : POE->semantics()) {
157 // Look through bindings.
158 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) {
159 E = OVE->getSourceExpr();
160 assert(E && "pseudo-object binding without source expression?");
161 }
162
163 Invalid |= Visit(E);
164 }
165 return Invalid;
166}
167
168bool CheckDefaultArgumentVisitor::VisitLambdaExpr(const LambdaExpr *Lambda) {
169 // [expr.prim.lambda.capture]p9
170 // a lambda-expression appearing in a default argument cannot implicitly or
171 // explicitly capture any local entity. Such a lambda-expression can still
172 // have an init-capture if any full-expression in its initializer satisfies
173 // the constraints of an expression appearing in a default argument.
174 bool Invalid = false;
175 for (const LambdaCapture &LC : Lambda->captures()) {
176 if (!Lambda->isInitCapture(&LC))
177 return S.Diag(LC.getLocation(), diag::err_lambda_capture_default_arg);
178 // Init captures are always VarDecl.
179 auto *D = cast<VarDecl>(LC.getCapturedVar());
180 Invalid |= Visit(D->getInit());
181 }
182 return Invalid;
183}
184
185bool CheckDefaultArgumentVisitor::VisitCoawaitExpr(const CoawaitExpr *E) {
186 // [expr.await] An await-expression shall not appear in a default argument.
187 // Note that this is generally diagnosed by isValidCoroutineContext,
188 // however isValidCoroutineContext misses default argument in nested
189 // function declarations.
190 S.Diag(E->getBeginLoc(), diag::err_coroutine_outside_function)
191 << "co_await" << E->getSourceRange();
192 return true;
193}
194
195bool CheckDefaultArgumentVisitor::VisitCoyieldExpr(const CoyieldExpr *E) {
196 S.Diag(E->getBeginLoc(), diag::err_coroutine_outside_function)
197 << "co_yield" << E->getSourceRange();
198 return true;
199}
200
201} // namespace
202
203void
205 const CXXMethodDecl *Method) {
206 // If we have an MSAny spec already, don't bother.
207 if (!Method || ComputedEST == EST_MSAny)
208 return;
209
210 const FunctionProtoType *Proto
211 = Method->getType()->getAs<FunctionProtoType>();
212 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
213 if (!Proto)
214 return;
215
217
218 // If we have a throw-all spec at this point, ignore the function.
219 if (ComputedEST == EST_None)
220 return;
221
222 if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
223 EST = EST_BasicNoexcept;
224
225 switch (EST) {
226 case EST_Unparsed:
228 case EST_Unevaluated:
229 llvm_unreachable("should not see unresolved exception specs here");
230
231 // If this function can throw any exceptions, make a note of that.
232 case EST_MSAny:
233 case EST_None:
234 // FIXME: Whichever we see last of MSAny and None determines our result.
235 // We should make a consistent, order-independent choice here.
236 ClearExceptions();
237 ComputedEST = EST;
238 return;
240 ClearExceptions();
241 ComputedEST = EST_None;
242 return;
243 // FIXME: If the call to this decl is using any of its default arguments, we
244 // need to search them for potentially-throwing calls.
245 // If this function has a basic noexcept, it doesn't affect the outcome.
247 case EST_NoexceptTrue:
248 case EST_NoThrow:
249 return;
250 // If we're still at noexcept(true) and there's a throw() callee,
251 // change to that specification.
252 case EST_DynamicNone:
253 if (ComputedEST == EST_BasicNoexcept)
254 ComputedEST = EST_DynamicNone;
255 return;
257 llvm_unreachable(
258 "should not generate implicit declarations for dependent cases");
259 case EST_Dynamic:
260 break;
261 }
262 assert(EST == EST_Dynamic && "EST case not considered earlier.");
263 assert(ComputedEST != EST_None &&
264 "Shouldn't collect exceptions when throw-all is guaranteed.");
265 ComputedEST = EST_Dynamic;
266 // Record the exceptions in this function's exception specification.
267 for (const auto &E : Proto->exceptions())
268 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
269 Exceptions.push_back(E);
270}
271
273 if (!S || ComputedEST == EST_MSAny)
274 return;
275
276 // FIXME:
277 //
278 // C++0x [except.spec]p14:
279 // [An] implicit exception-specification specifies the type-id T if and
280 // only if T is allowed by the exception-specification of a function directly
281 // invoked by f's implicit definition; f shall allow all exceptions if any
282 // function it directly invokes allows all exceptions, and f shall allow no
283 // exceptions if every function it directly invokes allows no exceptions.
284 //
285 // Note in particular that if an implicit exception-specification is generated
286 // for a function containing a throw-expression, that specification can still
287 // be noexcept(true).
288 //
289 // Note also that 'directly invoked' is not defined in the standard, and there
290 // is no indication that we should only consider potentially-evaluated calls.
291 //
292 // Ultimately we should implement the intent of the standard: the exception
293 // specification should be the set of exceptions which can be thrown by the
294 // implicit definition. For now, we assume that any non-nothrow expression can
295 // throw any exception.
296
297 if (Self->canThrow(S))
298 ComputedEST = EST_None;
299}
300
302 SourceLocation EqualLoc) {
303 if (RequireCompleteType(Param->getLocation(), Param->getType(),
304 diag::err_typecheck_decl_incomplete_type))
305 return true;
306
307 // C++ [dcl.fct.default]p5
308 // A default argument expression is implicitly converted (clause
309 // 4) to the parameter type. The default argument expression has
310 // the same semantic constraints as the initializer expression in
311 // a declaration of a variable of the parameter type, using the
312 // copy-initialization semantics (8.5).
314 Param);
315 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
316 EqualLoc);
317 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
318 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
319 if (Result.isInvalid())
320 return true;
321 Arg = Result.getAs<Expr>();
322
323 CheckCompletedExpr(Arg, EqualLoc);
325
326 return Arg;
327}
328
330 SourceLocation EqualLoc) {
331 // Add the default argument to the parameter
332 Param->setDefaultArg(Arg);
333
334 // We have already instantiated this parameter; provide each of the
335 // instantiations with the uninstantiated default argument.
336 UnparsedDefaultArgInstantiationsMap::iterator InstPos
338 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
339 for (auto &Instantiation : InstPos->second)
340 Instantiation->setUninstantiatedDefaultArg(Arg);
341
342 // We're done tracking this parameter's instantiations.
344 }
345}
346
347void
349 Expr *DefaultArg) {
350 if (!param || !DefaultArg)
351 return;
352
353 ParmVarDecl *Param = cast<ParmVarDecl>(param);
354 UnparsedDefaultArgLocs.erase(Param);
355
356 // Default arguments are only permitted in C++
357 if (!getLangOpts().CPlusPlus) {
358 Diag(EqualLoc, diag::err_param_default_argument)
359 << DefaultArg->getSourceRange();
360 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
361 }
362
363 // C++11 [dcl.fct.default]p3
364 // A default argument expression [...] shall not be specified for a
365 // parameter pack.
366 //
367 // Check this before looking for unexpanded parameter packs in DefaultArg:
368 // if DefaultArg references a pack from an enclosing lambda/block, that
369 // check would (incorrectly) mark the lambda as containing an unexpanded
370 // pack that never actually appears in the final AST once we discard
371 // DefaultArg below.
372 if (Param->isParameterPack()) {
373 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
374 << DefaultArg->getSourceRange();
375 // Recover by discarding the default argument.
376 Param->setDefaultArg(nullptr);
377 return;
378 }
379
380 // Check for unexpanded parameter packs.
382 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
383
384 ExprResult Result = ConvertParamDefaultArgument(Param, DefaultArg, EqualLoc);
385 if (Result.isInvalid())
386 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
387
388 DefaultArg = Result.getAs<Expr>();
389
390 // Check that the default argument is well-formed
391 CheckDefaultArgumentVisitor DefaultArgChecker(*this, DefaultArg);
392 if (DefaultArgChecker.Visit(DefaultArg))
393 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
394
395 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
396}
397
399 SourceLocation EqualLoc,
400 SourceLocation ArgLoc) {
401 if (!param)
402 return;
403
404 ParmVarDecl *Param = cast<ParmVarDecl>(param);
405 Param->setUnparsedDefaultArg();
406 UnparsedDefaultArgLocs[Param] = ArgLoc;
407}
408
410 Expr *DefaultArg) {
411 if (!param)
412 return;
413
414 ParmVarDecl *Param = cast<ParmVarDecl>(param);
415 Param->setInvalidDecl();
416 UnparsedDefaultArgLocs.erase(Param);
417 ExprResult RE;
418 if (DefaultArg) {
419 RE = CreateRecoveryExpr(EqualLoc, DefaultArg->getEndLoc(), {DefaultArg},
420 Param->getType().getNonReferenceType());
421 } else {
422 RE = CreateRecoveryExpr(EqualLoc, EqualLoc, {},
423 Param->getType().getNonReferenceType());
424 }
425 Param->setDefaultArg(RE.get());
426}
427
429 // C++ [dcl.fct.default]p3
430 // A default argument expression shall be specified only in the
431 // parameter-declaration-clause of a function declaration or in a
432 // template-parameter (14.1). It shall not be specified for a
433 // parameter pack. If it is specified in a
434 // parameter-declaration-clause, it shall not occur within a
435 // declarator or abstract-declarator of a parameter-declaration.
436 bool MightBeFunction = D.isFunctionDeclarationContext();
437 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
438 DeclaratorChunk &chunk = D.getTypeObject(i);
439 if (chunk.Kind == DeclaratorChunk::Function) {
440 if (MightBeFunction) {
441 // This is a function declaration. It can have default arguments, but
442 // keep looking in case its return type is a function type with default
443 // arguments.
444 MightBeFunction = false;
445 continue;
446 }
447 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
448 ++argIdx) {
449 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
450 if (Param->hasUnparsedDefaultArg()) {
451 std::unique_ptr<CachedTokens> Toks =
452 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
453 SourceRange SR;
454 if (Toks->size() > 1)
455 SR = SourceRange((*Toks)[1].getLocation(),
456 Toks->back().getLocation());
457 else
458 SR = UnparsedDefaultArgLocs[Param];
459 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
460 << SR;
461 } else if (Param->getDefaultArg()) {
462 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
463 << Param->getDefaultArg()->getSourceRange();
464 Param->setDefaultArg(nullptr);
465 }
466 }
467 } else if (chunk.Kind != DeclaratorChunk::Paren) {
468 MightBeFunction = false;
469 }
470 }
471}
472
474 return llvm::any_of(FD->parameters(), [](ParmVarDecl *P) {
475 return P->hasDefaultArg() && !P->hasInheritedDefaultArg();
476 });
477}
478
480 Scope *S) {
481 bool Invalid = false;
482
483 // The declaration context corresponding to the scope is the semantic
484 // parent, unless this is a local function declaration, in which case
485 // it is that surrounding function.
486 DeclContext *ScopeDC = New->isLocalExternDecl()
487 ? New->getLexicalDeclContext()
488 : New->getDeclContext();
489
490 // Find the previous declaration for the purpose of default arguments.
491 FunctionDecl *PrevForDefaultArgs = Old;
492 for (/**/; PrevForDefaultArgs;
493 // Don't bother looking back past the latest decl if this is a local
494 // extern declaration; nothing else could work.
495 PrevForDefaultArgs = New->isLocalExternDecl()
496 ? nullptr
497 : PrevForDefaultArgs->getPreviousDecl()) {
498 // Ignore hidden declarations.
499 if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
500 continue;
501
502 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
503 !New->isCXXClassMember()) {
504 // Ignore default arguments of old decl if they are not in
505 // the same scope and this is not an out-of-line definition of
506 // a member function.
507 continue;
508 }
509
510 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
511 // If only one of these is a local function declaration, then they are
512 // declared in different scopes, even though isDeclInScope may think
513 // they're in the same scope. (If both are local, the scope check is
514 // sufficient, and if neither is local, then they are in the same scope.)
515 continue;
516 }
517
518 if (PrevForDefaultArgs->getFriendObjectKind()) {
519 // Don't inherit default arguments from a friend declaration. It's invalid
520 // to redeclare such a function at all if it owns the default arguments;
521 // we check for that later. Otherwise, it's not the declaration that we're
522 // inheriting them from.
523 continue;
524 }
525
526 // We found the right previous declaration.
527 break;
528 }
529
530 // C++ [dcl.fct.default]p4:
531 // For non-template functions, default arguments can be added in
532 // later declarations of a function in the same
533 // scope. Declarations in different scopes have completely
534 // distinct sets of default arguments. That is, declarations in
535 // inner scopes do not acquire default arguments from
536 // declarations in outer scopes, and vice versa. In a given
537 // function declaration, all parameters subsequent to a
538 // parameter with a default argument shall have default
539 // arguments supplied in this or previous declarations. A
540 // default argument shall not be redefined by a later
541 // declaration (not even to the same value).
542 //
543 // C++ [dcl.fct.default]p6:
544 // Except for member functions of class templates, the default arguments
545 // in a member function definition that appears outside of the class
546 // definition are added to the set of default arguments provided by the
547 // member function declaration in the class definition.
548 for (unsigned p = 0, NumParams = PrevForDefaultArgs
549 ? PrevForDefaultArgs->getNumParams()
550 : 0;
551 p < NumParams; ++p) {
552 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
553 ParmVarDecl *NewParam = New->getParamDecl(p);
554
555 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
556 bool NewParamHasDfl = NewParam->hasDefaultArg();
557
558 if (OldParamHasDfl && NewParamHasDfl) {
559 unsigned DiagDefaultParamID =
560 diag::err_param_default_argument_redefinition;
561
562 // MSVC accepts that default parameters be redefined for member functions
563 // of template class. The new default parameter's value is ignored.
564 Invalid = true;
565 if (getLangOpts().MicrosoftExt) {
566 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
567 if (MD && MD->getParent()->getDescribedClassTemplate()) {
568 // Merge the old default argument into the new parameter.
569 NewParam->setHasInheritedDefaultArg();
570 if (OldParam->hasUninstantiatedDefaultArg())
572 OldParam->getUninstantiatedDefaultArg());
573 else
574 NewParam->setDefaultArg(OldParam->getInit());
575 DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
576 Invalid = false;
577 }
578 }
579
580 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
581 // hint here. Alternatively, we could walk the type-source information
582 // for NewParam to find the last source location in the type... but it
583 // isn't worth the effort right now. This is the kind of test case that
584 // is hard to get right:
585 // int f(int);
586 // void g(int (*fp)(int) = f);
587 // void g(int (*fp)(int) = &f);
588 Diag(NewParam->getLocation(), DiagDefaultParamID)
589 << NewParam->getDefaultArgRange();
590
591 // Look for the function declaration where the default argument was
592 // actually written, which may be a declaration prior to Old.
593 for (auto Older = PrevForDefaultArgs;
594 OldParam->hasInheritedDefaultArg(); /**/) {
595 Older = Older->getPreviousDecl();
596 OldParam = Older->getParamDecl(p);
597 }
598
599 Diag(OldParam->getLocation(), diag::note_previous_definition)
600 << OldParam->getDefaultArgRange();
601 } else if (OldParamHasDfl) {
602 // Merge the old default argument into the new parameter unless the new
603 // function is a friend declaration in a template class. In the latter
604 // case the default arguments will be inherited when the friend
605 // declaration will be instantiated.
606 if (New->getFriendObjectKind() == Decl::FOK_None ||
607 !New->getLexicalDeclContext()->isDependentContext()) {
608 // It's important to use getInit() here; getDefaultArg()
609 // strips off any top-level ExprWithCleanups.
610 NewParam->setHasInheritedDefaultArg();
611 if (OldParam->hasUnparsedDefaultArg())
612 NewParam->setUnparsedDefaultArg();
613 else if (OldParam->hasUninstantiatedDefaultArg())
615 OldParam->getUninstantiatedDefaultArg());
616 else
617 NewParam->setDefaultArg(OldParam->getInit());
618 }
619 } else if (NewParamHasDfl) {
620 if (New->getDescribedFunctionTemplate()) {
621 // Paragraph 4, quoted above, only applies to non-template functions.
622 Diag(NewParam->getLocation(),
623 diag::err_param_default_argument_template_redecl)
624 << NewParam->getDefaultArgRange();
625 Diag(PrevForDefaultArgs->getLocation(),
626 diag::note_template_prev_declaration)
627 << false;
628 } else if (New->getTemplateSpecializationKind()
630 New->getTemplateSpecializationKind() != TSK_Undeclared) {
631 // C++ [temp.expr.spec]p21:
632 // Default function arguments shall not be specified in a declaration
633 // or a definition for one of the following explicit specializations:
634 // - the explicit specialization of a function template;
635 // - the explicit specialization of a member function template;
636 // - the explicit specialization of a member function of a class
637 // template where the class template specialization to which the
638 // member function specialization belongs is implicitly
639 // instantiated.
640 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
641 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
642 << New->getDeclName()
643 << NewParam->getDefaultArgRange();
644 } else if (New->getDeclContext()
645 ->getEnclosingNonExpansionStatementContext()
646 ->isDependentContext()) {
647 // C++ [dcl.fct.default]p6 (DR217):
648 // Default arguments for a member function of a class template shall
649 // be specified on the initial declaration of the member function
650 // within the class template.
651 //
652 // Reading the tea leaves a bit in DR217 and its reference to DR205
653 // leads me to the conclusion that one cannot add default function
654 // arguments for an out-of-line definition of a member function of a
655 // dependent type.
656 int WhichKind = 2;
658 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
659 if (Record->getDescribedClassTemplate())
660 WhichKind = 0;
662 WhichKind = 1;
663 else
664 WhichKind = 2;
665 }
666
667 Diag(NewParam->getLocation(),
668 diag::err_param_default_argument_member_template_redecl)
669 << WhichKind
670 << NewParam->getDefaultArgRange();
671 }
672 }
673 }
674
675 // DR1344: If a default argument is added outside a class definition and that
676 // default argument makes the function a special member function, the program
677 // is ill-formed. This can only happen for constructors.
679 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
681 cast<CXXMethodDecl>(New)->getSpecialMemberKind(),
682 OldSM =
683 cast<CXXMethodDecl>(Old)->getSpecialMemberKind();
684 if (NewSM != OldSM) {
685 auto It = llvm::find_if(New->parameters(), [](const ParmVarDecl *P) {
686 return P->hasDefaultArg();
687 });
688 assert(It != New->param_end());
689 ParmVarDecl *NewParam = *It;
690 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
691 << NewParam->getDefaultArgRange() << NewSM;
692 Diag(Old->getLocation(), diag::note_previous_declaration);
693 }
694 }
695
696 const FunctionDecl *Def;
697 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
698 // template has a constexpr specifier then all its declarations shall
699 // contain the constexpr specifier.
700 if (New->getConstexprKind() != Old->getConstexprKind()) {
701 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
702 << New << static_cast<int>(New->getConstexprKind())
703 << static_cast<int>(Old->getConstexprKind());
704 Diag(Old->getLocation(), diag::note_previous_declaration);
705 Invalid = true;
706 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
707 Old->isDefined(Def) &&
708 // If a friend function is inlined but does not have 'inline'
709 // specifier, it is a definition. Do not report attribute conflict
710 // in this case, redefinition will be diagnosed later.
711 (New->isInlineSpecified() ||
712 New->getFriendObjectKind() == Decl::FOK_None)) {
713 // C++11 [dcl.fcn.spec]p4:
714 // If the definition of a function appears in a translation unit before its
715 // first declaration as inline, the program is ill-formed.
716 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
717 Diag(Def->getLocation(), diag::note_previous_definition);
718 Invalid = true;
719 }
720
721 // C++17 [temp.deduct.guide]p3:
722 // Two deduction guide declarations in the same translation unit
723 // for the same class template shall not have equivalent
724 // parameter-declaration-clauses.
726 !New->isFunctionTemplateSpecialization() && isVisible(Old)) {
727 Diag(New->getLocation(), diag::err_deduction_guide_redeclared);
728 Diag(Old->getLocation(), diag::note_previous_declaration);
729 }
730
731 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
732 // argument expression, that declaration shall be a definition and shall be
733 // the only declaration of the function or function template in the
734 // translation unit.
737 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
738 Diag(Old->getLocation(), diag::note_previous_declaration);
739 Invalid = true;
740 }
741
742 // C++11 [temp.friend]p4 (DR329):
743 // When a function is defined in a friend function declaration in a class
744 // template, the function is instantiated when the function is odr-used.
745 // The same restrictions on multiple declarations and definitions that
746 // apply to non-template function declarations and definitions also apply
747 // to these implicit definitions.
748 const FunctionDecl *OldDefinition = nullptr;
749 if (New->isThisDeclarationInstantiatedFromAFriendDefinition() &&
750 Old->isDefined(OldDefinition, true))
751 CheckForFunctionRedefinition(New, OldDefinition);
752
753 return Invalid;
754}
755
757 DiagCompat(Loc, diag_compat::placeholder_var_definition);
758}
759
760NamedDecl *
762 MultiTemplateParamsArg TemplateParamLists) {
763 assert(D.isDecompositionDeclarator());
765
766 // The syntax only allows a decomposition declarator as a simple-declaration,
767 // a for-range-declaration, or a condition in Clang, but we parse it in more
768 // cases than that.
770 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
771 << Decomp.getSourceRange();
772 return nullptr;
773 }
774
775 if (!TemplateParamLists.empty()) {
776 // C++17 [temp]/1:
777 // A template defines a family of class, functions, or variables, or an
778 // alias for a family of types.
779 //
780 // Structured bindings are not included.
781 Diag(TemplateParamLists.front()->getTemplateLoc(),
782 diag::err_decomp_decl_template);
783 return nullptr;
784 }
785
786 unsigned DiagID;
788 DiagID = diag::compat_pre_cxx17_decomp_decl;
790 DiagID = getLangOpts().CPlusPlus26
791 ? diag::compat_cxx26_decomp_decl_cond
792 : diag::compat_pre_cxx26_decomp_decl_cond;
793 else
794 DiagID = diag::compat_cxx17_decomp_decl;
795
796 Diag(Decomp.getLSquareLoc(), DiagID) << Decomp.getSourceRange();
797
798 // The semantic context is always just the current context.
799 DeclContext *const DC = CurContext;
800
801 // C++17 [dcl.dcl]/8:
802 // The decl-specifier-seq shall contain only the type-specifier auto
803 // and cv-qualifiers.
804 // C++20 [dcl.dcl]/8:
805 // If decl-specifier-seq contains any decl-specifier other than static,
806 // thread_local, auto, or cv-qualifiers, the program is ill-formed.
807 // C++23 [dcl.pre]/6:
808 // Each decl-specifier in the decl-specifier-seq shall be static,
809 // thread_local, auto (9.2.9.6 [dcl.spec.auto]), or a cv-qualifier.
810 // C++23 [dcl.pre]/7:
811 // Each decl-specifier in the decl-specifier-seq shall be constexpr,
812 // constinit, static, thread_local, auto, or a cv-qualifier
813 auto &DS = D.getDeclSpec();
814 auto DiagBadSpecifier = [&](StringRef Name, SourceLocation Loc) {
815 Diag(Loc, diag::err_decomp_decl_spec) << Name;
816 };
817
818 auto DiagCpp20Specifier = [&](StringRef Name, SourceLocation Loc) {
819 DiagCompat(Loc, diag_compat::decomp_decl_spec) << Name;
820 };
821
822 if (auto SCS = DS.getStorageClassSpec()) {
823 if (SCS == DeclSpec::SCS_static)
824 DiagCpp20Specifier(DeclSpec::getSpecifierName(SCS),
825 DS.getStorageClassSpecLoc());
826 else
827 DiagBadSpecifier(DeclSpec::getSpecifierName(SCS),
828 DS.getStorageClassSpecLoc());
829 }
830 if (auto TSCS = DS.getThreadStorageClassSpec())
831 DiagCpp20Specifier(DeclSpec::getSpecifierName(TSCS),
832 DS.getThreadStorageClassSpecLoc());
833
834 if (DS.isInlineSpecified())
835 DiagBadSpecifier("inline", DS.getInlineSpecLoc());
836
837 if (ConstexprSpecKind ConstexprSpec = DS.getConstexprSpecifier();
838 ConstexprSpec != ConstexprSpecKind::Unspecified) {
839 if (ConstexprSpec == ConstexprSpecKind::Consteval ||
841 DiagBadSpecifier(DeclSpec::getSpecifierName(ConstexprSpec),
842 DS.getConstexprSpecLoc());
843 }
844
845 // We can't recover from it being declared as a typedef.
846 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
847 return nullptr;
848
849 // C++2a [dcl.struct.bind]p1:
850 // A cv that includes volatile is deprecated
851 if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) &&
853 Diag(DS.getVolatileSpecLoc(),
854 diag::warn_deprecated_volatile_structured_binding);
855
857 QualType R = TInfo->getType();
858
861 D.setInvalidType();
862
863 // The syntax only allows a single ref-qualifier prior to the decomposition
864 // declarator. No other declarator chunks are permitted. Also check the type
865 // specifier here.
866 if (DS.getTypeSpecType() != DeclSpec::TST_auto || D.hasGroupingParens() ||
867 D.getNumTypeObjects() > 1 ||
868 (D.getNumTypeObjects() == 1 &&
870 Diag(Decomp.getLSquareLoc(),
871 (D.hasGroupingParens() ||
872 (D.getNumTypeObjects() &&
874 ? diag::err_decomp_decl_parens
875 : diag::err_decomp_decl_type)
876 << R;
877
878 // In most cases, there's no actual problem with an explicitly-specified
879 // type, but a function type won't work here, and ActOnVariableDeclarator
880 // shouldn't be called for such a type.
881 if (R->isFunctionType())
882 D.setInvalidType();
883
884 // Recover from an invalid 'auto *' structured binding by removing the
885 // pointer declarator. This allows type deduction to proceed and keeps
886 // the bindings usable in subsequent code.
887 if (D.getNumTypeObjects() == 1 &&
889 D.getTypeObject(0).Ptr.TypeQuals == 0) {
891 TInfo = GetTypeForDeclarator(D);
892 R = TInfo->getType();
893 }
894 }
895
896 // Constrained auto is prohibited by [decl.pre]p6, so check that here.
897 if (DS.isConstrainedAuto()) {
898 TemplateIdAnnotation *TemplRep = DS.getRepAsTemplateId();
899 assert(TemplRep->Kind == TNK_Concept_template &&
900 "No other template kind should be possible for a constrained auto");
901
902 SourceRange TemplRange{TemplRep->TemplateNameLoc,
903 TemplRep->RAngleLoc.isValid()
904 ? TemplRep->RAngleLoc
905 : TemplRep->TemplateNameLoc};
906 Diag(TemplRep->TemplateNameLoc, diag::err_decomp_decl_constraint)
907 << TemplRange << FixItHint::CreateRemoval(TemplRange);
908 }
909
910 // Build the BindingDecls.
912
913 // Build the BindingDecls.
914 for (auto &B : D.getDecompositionDeclarator().bindings()) {
915 // Check for name conflicts.
916 DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
917 IdentifierInfo *VarName = B.Name;
918 assert(VarName && "Cannot have an unnamed binding declaration");
919
923 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
924
925 // It's not permitted to shadow a template parameter name.
926 if (Previous.isSingleResult() &&
927 Previous.getFoundDecl()->isTemplateParameter()) {
928 DiagnoseTemplateParameterShadow(B.NameLoc, Previous.getFoundDecl());
929 Previous.clear();
930 }
931
932 QualType QT;
933 if (B.EllipsisLoc.isValid()) {
934 if (!cast<Decl>(DC)->isTemplated())
935 Diag(B.EllipsisLoc, diag::err_pack_outside_template);
936 QT = Context.getPackExpansionType(Context.DependentTy, std::nullopt,
937 /*ExpectsPackInType=*/false);
938 }
939
940 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name, QT);
941
942 if (BD->isParameterPack()) {
944 CSI->LocalPacks.push_back(BD);
945 }
946
947 ProcessDeclAttributeList(S, BD, *B.Attrs);
948
949 // Find the shadowed declaration before filtering for scope.
950 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
952 : nullptr;
953
954 bool ConsiderLinkage = DC->isFunctionOrMethod() &&
955 DS.getStorageClassSpec() == DeclSpec::SCS_extern;
956 FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
957 /*AllowInlineNamespace*/false);
958
959 bool IsPlaceholder = DS.getStorageClassSpec() != DeclSpec::SCS_static &&
960 DC->isFunctionOrMethod() && VarName->isPlaceholder();
961 if (!Previous.empty()) {
962 if (IsPlaceholder) {
963 bool sameDC = (Previous.end() - 1)
964 ->getDeclContext()
965 ->getRedeclContext()
966 ->Equals(DC->getRedeclContext());
967 if (sameDC &&
968 isDeclInScope(*(Previous.end() - 1), CurContext, S, false)) {
969 Previous.clear();
971 }
972 } else {
973 auto *Old = Previous.getRepresentativeDecl();
974 Diag(B.NameLoc, diag::err_redefinition) << B.Name;
975 Diag(Old->getLocation(), diag::note_previous_definition);
976 }
977 } else if (ShadowedDecl && !D.isRedeclaration()) {
978 CheckShadow(BD, ShadowedDecl, Previous);
979 }
980 PushOnScopeChains(BD, S, true);
981 Bindings.push_back(BD);
982 ParsingInitForAutoVars.insert(BD);
983 }
984
985 // There are no prior lookup results for the variable itself, because it
986 // is unnamed.
987 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
988 Decomp.getLSquareLoc());
991
992 // Build the variable that holds the non-decomposed object.
993 bool AddToScope = true;
994 NamedDecl *New =
995 ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
996 MultiTemplateParamsArg(), AddToScope, Bindings);
997 if (AddToScope) {
998 S->AddDecl(New);
999 CurContext->addHiddenDecl(New);
1000 }
1001
1002 if (OpenMP().isInOpenMPDeclareTargetContext())
1003 OpenMP().checkDeclIsAllowedInOpenMPTarget(nullptr, New);
1004
1005 return New;
1006}
1007
1008// Check the arity of the structured bindings.
1009// Create the resolved pack expr if needed.
1011 QualType DecompType,
1013 unsigned MemberCount) {
1014 auto BindingWithPackItr = llvm::find_if(
1015 Bindings, [](BindingDecl *D) -> bool { return D->isParameterPack(); });
1016 bool HasPack = BindingWithPackItr != Bindings.end();
1017 bool IsValid;
1018 if (!HasPack) {
1019 IsValid = Bindings.size() == MemberCount;
1020 } else {
1021 // There may not be more members than non-pack bindings.
1022 IsValid = MemberCount >= Bindings.size() - 1;
1023 }
1024
1025 if (IsValid && HasPack) {
1026 // Create the pack expr and assign it to the binding.
1027 unsigned PackSize = MemberCount - Bindings.size() + 1;
1028
1029 BindingDecl *BPack = *BindingWithPackItr;
1030 BPack->setDecomposedDecl(DD);
1031 SmallVector<ValueDecl *, 8> NestedBDs(PackSize);
1032 // Create the nested BindingDecls.
1033 for (unsigned I = 0; I < PackSize; ++I) {
1034 BindingDecl *NestedBD = BindingDecl::Create(
1035 S.Context, BPack->getDeclContext(), BPack->getLocation(),
1036 BPack->getIdentifier(), QualType());
1037 NestedBD->setDecomposedDecl(DD);
1038 NestedBDs[I] = NestedBD;
1039 }
1040
1042 S.Context.DependentTy, PackSize, /*ExpectsPackInType=*/false);
1043 auto *PackExpr = FunctionParmPackExpr::Create(
1044 S.Context, PackType, BPack, BPack->getBeginLoc(), NestedBDs);
1045 BPack->setBinding(PackType, PackExpr);
1046 }
1047
1048 if (IsValid)
1049 return false;
1050
1051 S.Diag(DD->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1052 << DecompType << (unsigned)Bindings.size() << MemberCount << MemberCount
1053 << (MemberCount < Bindings.size());
1054 return true;
1055}
1056
1059 QualType DecompType, const llvm::APSInt &NumElemsAPS, QualType ElemType,
1060 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
1061 unsigned NumElems = (unsigned)NumElemsAPS.getLimitedValue(UINT_MAX);
1062 auto *DD = cast<DecompositionDecl>(Src);
1063
1064 if (CheckBindingsCount(S, DD, DecompType, Bindings, NumElems))
1065 return true;
1066
1067 unsigned I = 0;
1068 for (auto *B : DD->flat_bindings()) {
1069 SourceLocation Loc = B->getLocation();
1070 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1071 if (E.isInvalid())
1072 return true;
1073 E = GetInit(Loc, E.get(), I++);
1074 if (E.isInvalid())
1075 return true;
1076 B->setBinding(ElemType, E.get());
1077 }
1078
1079 return false;
1080}
1081
1084 ValueDecl *Src, QualType DecompType,
1085 const llvm::APSInt &NumElems,
1086 QualType ElemType) {
1088 S, Bindings, Src, DecompType, NumElems, ElemType,
1089 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
1090 ExprResult E = S.ActOnIntegerConstant(Loc, I);
1091 if (E.isInvalid())
1092 return ExprError();
1093 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
1094 });
1095}
1096
1098 ValueDecl *Src, QualType DecompType,
1099 const ConstantArrayType *CAT) {
1100 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
1101 llvm::APSInt(CAT->getSize()),
1102 CAT->getElementType());
1103}
1104
1106 ValueDecl *Src, QualType DecompType,
1107 const VectorType *VT) {
1109 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
1111 DecompType.getQualifiers()));
1112}
1113
1116 ValueDecl *Src, QualType DecompType,
1117 const ComplexType *CT) {
1119 S, Bindings, Src, DecompType, llvm::APSInt::get(2),
1121 DecompType.getQualifiers()),
1122 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
1123 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
1124 });
1125}
1126
1129 const TemplateParameterList *Params) {
1131 llvm::raw_svector_ostream OS(SS);
1132 bool First = true;
1133 unsigned I = 0;
1134 for (auto &Arg : Args.arguments()) {
1135 if (!First)
1136 OS << ", ";
1137 Arg.getArgument().print(PrintingPolicy, OS,
1139 PrintingPolicy, Params, I));
1140 First = false;
1141 I++;
1142 }
1143 return std::string(OS.str());
1144}
1145
1146static QualType getStdTrait(Sema &S, SourceLocation Loc, StringRef Trait,
1147 TemplateArgumentListInfo &Args, unsigned DiagID) {
1148 auto DiagnoseMissing = [&] {
1149 if (DiagID)
1150 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
1151 Args, /*Params*/ nullptr);
1152 return QualType();
1153 };
1154
1155 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
1156 NamespaceDecl *Std = S.getStdNamespace();
1157 if (!Std)
1158 return DiagnoseMissing();
1159
1160 // Look up the trait itself, within namespace std. We can diagnose various
1161 // problems with this lookup even if we've been asked to not diagnose a
1162 // missing specialization, because this can only fail if the user has been
1163 // declaring their own names in namespace std or we don't support the
1164 // standard library implementation in use.
1165 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait), Loc,
1167 if (!S.LookupQualifiedName(Result, Std))
1168 return DiagnoseMissing();
1169 if (Result.isAmbiguous())
1170 return QualType();
1171
1172 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
1173 if (!TraitTD) {
1174 Result.suppressDiagnostics();
1175 NamedDecl *Found = *Result.begin();
1176 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
1177 S.Diag(Found->getLocation(), diag::note_declared_at);
1178 return QualType();
1179 }
1180
1181 // Build the template-id.
1182 QualType TraitTy = S.CheckTemplateIdType(
1183 ElaboratedTypeKeyword::None, TemplateName(TraitTD), Loc, Args,
1184 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
1185 if (TraitTy.isNull())
1186 return QualType();
1187
1188 if (!S.isCompleteType(Loc, TraitTy)) {
1189 if (DiagID)
1191 Loc, TraitTy, DiagID,
1193 TraitTD->getTemplateParameters()));
1194 return QualType();
1195 }
1196 return TraitTy;
1197}
1198
1199static bool lookupMember(Sema &S, CXXRecordDecl *RD,
1200 LookupResult &MemberLookup) {
1201 assert(RD && "specialization of class template is not a class?");
1202 S.LookupQualifiedName(MemberLookup, RD);
1203 return MemberLookup.isAmbiguous();
1204}
1205
1206static TemplateArgumentLoc
1212
1213static TemplateArgumentLoc
1217
1218namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1219
1220static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1221 unsigned &OutSize) {
1224
1225 // Form template argument list for tuple_size<T>.
1226 TemplateArgumentListInfo Args(Loc, Loc);
1228
1229 QualType TraitTy = getStdTrait(S, Loc, "tuple_size", Args, /*DiagID=*/0);
1230 if (TraitTy.isNull())
1231 return IsTupleLike::NotTupleLike;
1232
1235
1236 // If there's no tuple_size specialization or the lookup of 'value' is empty,
1237 // it's not tuple-like.
1238 if (lookupMember(S, TraitTy->getAsCXXRecordDecl(), R) || R.empty())
1239 return IsTupleLike::NotTupleLike;
1240
1241 // If we get this far, we've committed to the tuple interpretation, but
1242 // we can still fail if there actually isn't a usable ::value.
1243
1244 struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1245 LookupResult &R;
1247 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1248 : R(R), Args(Args) {}
1249 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
1250 SourceLocation Loc) override {
1251 return S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1253 /*Params*/ nullptr);
1254 }
1255 } Diagnoser(R, Args);
1256
1257 ExprResult E =
1258 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1259 if (E.isInvalid())
1260 return IsTupleLike::Error;
1261
1262 llvm::APSInt Size;
1263 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser);
1264 if (E.isInvalid())
1265 return IsTupleLike::Error;
1266
1267 // The implementation limit is UINT_MAX-1, to allow this to be passed down on
1268 // an UnsignedOrNone.
1269 if (Size < 0 || Size >= UINT_MAX) {
1271 Size.toString(Str);
1272 S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_invalid)
1274 /*Params=*/nullptr)
1275 << StringRef(Str.data(), Str.size());
1276 return IsTupleLike::Error;
1277 }
1278
1279 OutSize = Size.getExtValue();
1280 return IsTupleLike::TupleLike;
1281}
1282
1283/// \return std::tuple_element<I, T>::type.
1285 unsigned I, QualType T) {
1286 // Form template argument list for tuple_element<I, T>.
1287 TemplateArgumentListInfo Args(Loc, Loc);
1288 Args.addArgument(
1291
1292 QualType TraitTy =
1293 getStdTrait(S, Loc, "tuple_element", Args,
1294 diag::err_decomp_decl_std_tuple_element_not_specialized);
1295 if (TraitTy.isNull())
1296 return QualType();
1297
1298 DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1299 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1300 if (lookupMember(S, TraitTy->getAsCXXRecordDecl(), R))
1301 return QualType();
1302
1303 auto *TD = R.getAsSingle<TypeDecl>();
1304 if (!TD) {
1305 R.suppressDiagnostics();
1306 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1308 /*Params*/ nullptr);
1309 if (!R.empty())
1310 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1311 return QualType();
1312 }
1313
1314 NestedNameSpecifier Qualifier(TraitTy.getTypePtr());
1315 return S.Context.getTypeDeclType(ElaboratedTypeKeyword::None, Qualifier, TD);
1316}
1317
1318namespace {
1319struct InitializingBinding {
1320 Sema &S;
1321 InitializingBinding(Sema &S, BindingDecl *BD) : S(S) {
1322 Sema::CodeSynthesisContext Ctx;
1325 Ctx.Entity = BD;
1327 }
1328 ~InitializingBinding() {
1330 }
1331};
1332}
1333
1336 VarDecl *Src, QualType DecompType,
1337 unsigned NumElems) {
1338 auto *DD = cast<DecompositionDecl>(Src);
1339 if (CheckBindingsCount(S, DD, DecompType, Bindings, NumElems))
1340 return true;
1341
1342 if (Bindings.empty())
1343 return false;
1344
1345 DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1346
1347 // [dcl.decomp]p3:
1348 // The unqualified-id get is looked up in the scope of E by class member
1349 // access lookup ...
1350 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1351 bool UseMemberGet = false;
1352 if (S.isCompleteType(Src->getLocation(), DecompType)) {
1353 if (auto *RD = DecompType->getAsCXXRecordDecl())
1354 S.LookupQualifiedName(MemberGet, RD);
1355 if (MemberGet.isAmbiguous())
1356 return true;
1357 // ... and if that finds at least one declaration that is a function
1358 // template whose first template parameter is a non-type parameter ...
1359 for (NamedDecl *D : MemberGet) {
1360 if (FunctionTemplateDecl *FTD =
1361 dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
1362 TemplateParameterList *TPL = FTD->getTemplateParameters();
1363 if (TPL->size() != 0 &&
1365 // ... the initializer is e.get<i>().
1366 UseMemberGet = true;
1367 break;
1368 }
1369 }
1370 }
1371 }
1372
1373 unsigned I = 0;
1374 for (auto *B : DD->flat_bindings()) {
1375 InitializingBinding InitContext(S, B);
1376 SourceLocation Loc = B->getLocation();
1377
1378 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1379 if (E.isInvalid())
1380 return true;
1381
1382 // e is an lvalue if the type of the entity is an lvalue reference and
1383 // an xvalue otherwise
1384 if (!Src->getType()->isLValueReferenceType())
1385 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1386 E.get(), nullptr, VK_XValue,
1388
1389 TemplateArgumentListInfo Args(Loc, Loc);
1390 Args.addArgument(
1392
1393 if (UseMemberGet) {
1394 // if [lookup of member get] finds at least one declaration, the
1395 // initializer is e.get<i-1>().
1396 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1397 CXXScopeSpec(), SourceLocation(), nullptr,
1398 MemberGet, &Args, nullptr);
1399 if (E.isInvalid())
1400 return true;
1401
1402 E = S.BuildCallExpr(nullptr, E.get(), Loc, {}, Loc);
1403 } else {
1404 // Otherwise, the initializer is get<i-1>(e), where get is looked up
1405 // in the associated namespaces.
1408 DeclarationNameInfo(GetDN, Loc), /*RequiresADL=*/true, &Args,
1410 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
1411
1412 Expr *Arg = E.get();
1413 E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc);
1414 }
1415 if (E.isInvalid())
1416 return true;
1417 Expr *Init = E.get();
1418
1419 // Given the type T designated by std::tuple_element<i - 1, E>::type
1420 QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1421 if (T.isNull())
1422 return true;
1423
1424 // C++26 [dcl.struct.bind]p7:
1425 // and the type Ui, defined as Ti if the initializer is a prvalue,
1426 // as "lvalue reference to Ti" if the initializer is an lvalue,
1427 // or as "rvalue reference to Ti" otherwise
1428 // "defined as Ti if the initializer is a prvalue" was introduced by CWG3135
1429 QualType U = E.get()->isPRValue()
1430 ? T
1431 : S.BuildReferenceType(T, E.get()->isLValue(), Loc,
1432 B->getDeclName());
1433 if (U.isNull())
1434 return true;
1435
1436 // Don't give this VarDecl a TypeSourceInfo, since this is a synthesized
1437 // entity and this type was never written in source code.
1438 auto *BindingVD =
1439 VarDecl::Create(S.Context, Src->getDeclContext(), Loc, Loc,
1440 B->getDeclName().getAsIdentifierInfo(), U,
1441 /*TInfo=*/nullptr, Src->getStorageClass());
1442 BindingVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1443 BindingVD->setTSCSpec(Src->getTSCSpec());
1444 BindingVD->setConstexpr(Src->isConstexpr());
1445 if (const auto *CIAttr = Src->getAttr<ConstInitAttr>())
1446 BindingVD->addAttr(CIAttr->clone(S.Context));
1447 BindingVD->setImplicit();
1448 if (Src->isInlineSpecified())
1449 BindingVD->setInlineSpecified();
1450 BindingVD->getLexicalDeclContext()->addHiddenDecl(BindingVD);
1451
1454 InitializationSequence Seq(S, Entity, Kind, Init);
1455 E = Seq.Perform(S, Entity, Kind, Init);
1456 if (E.isInvalid())
1457 return true;
1458 E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
1459 if (E.isInvalid())
1460 return true;
1461 BindingVD->setInit(E.get());
1463
1465 CXXScopeSpec(), DeclarationNameInfo(B->getDeclName(), Loc), BindingVD);
1466 if (E.isInvalid())
1467 return true;
1468
1469 B->setBinding(T, E.get());
1470 I++;
1471 }
1472
1473 return false;
1474}
1475
1476/// Find the base class to decompose in a built-in decomposition of a class type.
1477/// This base class search is, unfortunately, not quite like any other that we
1478/// perform anywhere else in C++.
1480 const CXXRecordDecl *RD,
1481 CXXCastPath &BasePath) {
1482 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1483 CXXBasePath &Path) {
1484 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1485 };
1486
1487 const CXXRecordDecl *ClassWithFields = nullptr;
1489 if (RD->hasDirectFields())
1490 // [dcl.decomp]p4:
1491 // Otherwise, all of E's non-static data members shall be public direct
1492 // members of E ...
1493 ClassWithFields = RD;
1494 else {
1495 // ... or of ...
1496 CXXBasePaths Paths;
1497 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1498 if (!RD->lookupInBases(BaseHasFields, Paths)) {
1499 // If no classes have fields, just decompose RD itself. (This will work
1500 // if and only if zero bindings were provided.)
1501 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
1502 }
1503
1504 CXXBasePath *BestPath = nullptr;
1505 for (auto &P : Paths) {
1506 if (!BestPath)
1507 BestPath = &P;
1508 else if (!S.Context.hasSameType(P.back().Base->getType(),
1509 BestPath->back().Base->getType())) {
1510 // ... the same ...
1511 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1512 << false << RD << BestPath->back().Base->getType()
1513 << P.back().Base->getType();
1514 return DeclAccessPair();
1515 } else if (P.Access < BestPath->Access) {
1516 BestPath = &P;
1517 }
1518 }
1519
1520 // ... unambiguous ...
1521 QualType BaseType = BestPath->back().Base->getType();
1522 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1523 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1524 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1525 return DeclAccessPair();
1526 }
1527
1528 // ... [accessible, implied by other rules] base class of E.
1529 S.CheckBaseClassAccess(Loc, BaseType, S.Context.getCanonicalTagType(RD),
1530 *BestPath, diag::err_decomp_decl_inaccessible_base);
1531 AS = BestPath->Access;
1532
1533 ClassWithFields = BaseType->getAsCXXRecordDecl();
1534 S.BuildBasePathArray(Paths, BasePath);
1535 }
1536
1537 // The above search did not check whether the selected class itself has base
1538 // classes with fields, so check that now.
1539 CXXBasePaths Paths;
1540 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1541 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1542 << (ClassWithFields == RD) << RD << ClassWithFields
1543 << Paths.front().back().Base->getType();
1544 return DeclAccessPair();
1545 }
1546
1547 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1548}
1549
1551 const CXXRecordDecl *OrigRD,
1552 QualType DecompType,
1553 DeclAccessPair BasePair) {
1554 const auto *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1555 if (!RD)
1556 return true;
1557
1558 for (auto *FD : RD->fields()) {
1559 if (FD->isUnnamedBitField())
1560 continue;
1561
1562 // All the non-static data members are required to be nameable, so they
1563 // must all have names.
1564 if (!FD->getDeclName()) {
1565 if (RD->isLambda()) {
1566 S.Diag(Loc, diag::err_decomp_decl_lambda);
1567 S.Diag(RD->getLocation(), diag::note_lambda_decl);
1568 return true;
1569 }
1570
1571 if (FD->isAnonymousStructOrUnion()) {
1572 S.Diag(Loc, diag::err_decomp_decl_anon_union_member)
1573 << DecompType << FD->getType()->isUnionType();
1574 S.Diag(FD->getLocation(), diag::note_declared_at);
1575 return true;
1576 }
1577
1578 // FIXME: Are there any other ways we could have an anonymous member?
1579 }
1580 // The field must be accessible in the context of the structured binding.
1581 // We already checked that the base class is accessible.
1582 // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1583 // const_cast here.
1585 Loc, const_cast<CXXRecordDecl *>(OrigRD),
1587 BasePair.getAccess(), FD->getAccess())));
1588 }
1589 return false;
1590}
1591
1593 ValueDecl *Src, QualType DecompType,
1594 const CXXRecordDecl *OrigRD) {
1595 if (S.RequireCompleteType(Src->getLocation(), DecompType,
1596 diag::err_incomplete_type))
1597 return true;
1598
1599 CXXCastPath BasePath;
1600 DeclAccessPair BasePair =
1601 findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1602 const auto *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1603 if (!RD)
1604 return true;
1605 QualType BaseType = S.Context.getQualifiedType(
1606 S.Context.getCanonicalTagType(RD), DecompType.getQualifiers());
1607
1608 auto *DD = cast<DecompositionDecl>(Src);
1609 unsigned NumFields = llvm::count_if(
1610 RD->fields(), [](FieldDecl *FD) { return !FD->isUnnamedBitField(); });
1611 if (CheckBindingsCount(S, DD, DecompType, Bindings, NumFields))
1612 return true;
1613
1614 // all of E's non-static data members shall be [...] well-formed
1615 // when named as e.name in the context of the structured binding,
1616 // E shall not have an anonymous union member, ...
1617 auto FlatBindings = DD->flat_bindings();
1618 assert(llvm::range_size(FlatBindings) == NumFields);
1619 auto FlatBindingsItr = FlatBindings.begin();
1620
1621 if (CheckMemberDecompositionFields(S, Src->getLocation(), OrigRD, DecompType,
1622 BasePair))
1623 return true;
1624
1625 for (auto *FD : RD->fields()) {
1626 if (FD->isUnnamedBitField())
1627 continue;
1628
1629 // We have a real field to bind.
1630 assert(FlatBindingsItr != FlatBindings.end());
1631 BindingDecl *B = *(FlatBindingsItr++);
1632 SourceLocation Loc = B->getLocation();
1633
1634 // Initialize the binding to Src.FD.
1635 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1636 if (E.isInvalid())
1637 return true;
1638 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1639 VK_LValue, &BasePath);
1640 if (E.isInvalid())
1641 return true;
1642 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1643 CXXScopeSpec(), FD,
1645 DeclarationNameInfo(FD->getDeclName(), Loc));
1646 if (E.isInvalid())
1647 return true;
1648
1649 // If the type of the member is T, the referenced type is cv T, where cv is
1650 // the cv-qualification of the decomposition expression.
1651 //
1652 // FIXME: We resolve a defect here: if the field is mutable, we do not add
1653 // 'const' to the type of the field.
1654 Qualifiers Q = DecompType.getQualifiers();
1655 if (FD->isMutable())
1656 Q.removeConst();
1657 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1658 }
1659
1660 return false;
1661}
1662
1664 QualType DecompType = DD->getType();
1665
1666 // If the type of the decomposition is dependent, then so is the type of
1667 // each binding.
1668 if (DecompType->isDependentType()) {
1669 // Note that all of the types are still Null or PackExpansionType.
1670 for (auto *B : DD->bindings()) {
1671 // Do not overwrite any pack type.
1672 if (B->getType().isNull())
1673 B->setType(Context.DependentTy);
1674 }
1675 return;
1676 }
1677
1678 DecompType = DecompType.getNonReferenceType();
1680
1681 // C++1z [dcl.decomp]/2:
1682 // If E is an array type [...]
1683 // As an extension, we also support decomposition of built-in complex and
1684 // vector types.
1685 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1686 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1687 DD->setInvalidDecl();
1688 return;
1689 }
1690 if (auto *VT = DecompType->getAs<VectorType>()) {
1691 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1692 DD->setInvalidDecl();
1693 return;
1694 }
1695 if (auto *CT = DecompType->getAs<ComplexType>()) {
1696 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1697 DD->setInvalidDecl();
1698 return;
1699 }
1700
1701 // C++1z [dcl.decomp]/3:
1702 // if the expression std::tuple_size<E>::value is a well-formed integral
1703 // constant expression, [...]
1704 unsigned TupleSize;
1705 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1706 case IsTupleLike::Error:
1707 DD->setInvalidDecl();
1708 return;
1709
1710 case IsTupleLike::TupleLike:
1711 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1712 DD->setInvalidDecl();
1713 return;
1714
1715 case IsTupleLike::NotTupleLike:
1716 break;
1717 }
1718
1719 // C++1z [dcl.dcl]/8:
1720 // [E shall be of array or non-union class type]
1721 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1722 if (!RD || RD->isUnion()) {
1723 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1724 << DD << !RD << DecompType;
1725 DD->setInvalidDecl();
1726 return;
1727 }
1728
1729 // C++1z [dcl.decomp]/4:
1730 // all of E's non-static data members shall be [...] direct members of
1731 // E or of the same unambiguous public base class of E, ...
1732 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1733 DD->setInvalidDecl();
1734}
1735
1737 SourceLocation Loc) {
1738 const ASTContext &Ctx = getASTContext();
1739 assert(!T->isDependentType());
1740
1741 Qualifiers Quals;
1742 QualType Unqual = Context.getUnqualifiedArrayType(T, Quals);
1743 Quals.removeCVRQualifiers();
1744 T = Context.getQualifiedType(Unqual, Quals);
1745
1746 if (auto *CAT = Ctx.getAsConstantArrayType(T))
1747 return static_cast<unsigned>(CAT->getSize().getZExtValue());
1748 if (auto *VT = T->getAs<VectorType>())
1749 return VT->getNumElements();
1750 if (T->getAs<ComplexType>())
1751 return 2u;
1752
1753 unsigned TupleSize;
1754 switch (isTupleLike(*this, Loc, T, TupleSize)) {
1755 case IsTupleLike::Error:
1756 return std::nullopt;
1757 case IsTupleLike::TupleLike:
1758 return TupleSize;
1759 case IsTupleLike::NotTupleLike:
1760 break;
1761 }
1762
1763 const CXXRecordDecl *OrigRD = T->getAsCXXRecordDecl();
1764 if (!OrigRD || OrigRD->isUnion())
1765 return std::nullopt;
1766
1767 if (RequireCompleteType(Loc, T, diag::err_incomplete_type))
1768 return std::nullopt;
1769
1770 CXXCastPath BasePath;
1771 DeclAccessPair BasePair =
1772 findDecomposableBaseClass(*this, Loc, OrigRD, BasePath);
1773 const auto *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1774 if (!RD)
1775 return std::nullopt;
1776
1777 unsigned NumFields = llvm::count_if(
1778 RD->fields(), [](FieldDecl *FD) { return !FD->isUnnamedBitField(); });
1779
1780 if (CheckMemberDecompositionFields(*this, Loc, OrigRD, T, BasePair))
1781 return std::nullopt;
1782
1783 return NumFields;
1784}
1785
1787 // Shortcut if exceptions are disabled.
1788 if (!getLangOpts().CXXExceptions)
1789 return;
1790
1791 assert(Context.hasSameType(New->getType(), Old->getType()) &&
1792 "Should only be called if types are otherwise the same.");
1793
1794 QualType NewType = New->getType();
1795 QualType OldType = Old->getType();
1796
1797 // We're only interested in pointers and references to functions, as well
1798 // as pointers to member functions.
1799 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1800 NewType = R->getPointeeType();
1801 OldType = OldType->castAs<ReferenceType>()->getPointeeType();
1802 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1803 NewType = P->getPointeeType();
1804 OldType = OldType->castAs<PointerType>()->getPointeeType();
1805 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1806 NewType = M->getPointeeType();
1807 OldType = OldType->castAs<MemberPointerType>()->getPointeeType();
1808 }
1809
1810 if (!NewType->isFunctionProtoType())
1811 return;
1812
1813 // There's lots of special cases for functions. For function pointers, system
1814 // libraries are hopefully not as broken so that we don't need these
1815 // workarounds.
1817 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1818 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1819 New->setInvalidDecl();
1820 }
1821}
1822
1823/// CheckCXXDefaultArguments - Verify that the default arguments for a
1824/// function declaration are well-formed according to C++
1825/// [dcl.fct.default].
1827 // This checking doesn't make sense for explicit specializations; their
1828 // default arguments are determined by the declaration we're specializing,
1829 // not by FD.
1831 return;
1832 if (auto *FTD = FD->getDescribedFunctionTemplate())
1833 if (FTD->isMemberSpecialization())
1834 return;
1835
1836 unsigned NumParams = FD->getNumParams();
1837 unsigned ParamIdx = 0;
1838
1839 // Find first parameter with a default argument
1840 for (; ParamIdx < NumParams; ++ParamIdx) {
1841 ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1842 if (Param->hasDefaultArg())
1843 break;
1844 }
1845
1846 // C++20 [dcl.fct.default]p4:
1847 // In a given function declaration, each parameter subsequent to a parameter
1848 // with a default argument shall have a default argument supplied in this or
1849 // a previous declaration, unless the parameter was expanded from a
1850 // parameter pack, or shall be a function parameter pack.
1851 for (++ParamIdx; ParamIdx < NumParams; ++ParamIdx) {
1852 ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1853 if (Param->hasDefaultArg() || Param->isParameterPack() ||
1855 CurrentInstantiationScope->isLocalPackExpansion(Param)))
1856 continue;
1857 if (Param->isInvalidDecl())
1858 /* We already complained about this parameter. */;
1859 else if (Param->getIdentifier())
1860 Diag(Param->getLocation(), diag::err_param_default_argument_missing_name)
1861 << Param->getIdentifier();
1862 else
1863 Diag(Param->getLocation(), diag::err_param_default_argument_missing);
1864 }
1865}
1866
1867/// Check that the given type is a literal type. Issue a diagnostic if not,
1868/// if Kind is Diagnose.
1869/// \return \c true if a problem has been found (and optionally diagnosed).
1870template <typename... Ts>
1872 SourceLocation Loc, QualType T, unsigned DiagID,
1873 Ts &&...DiagArgs) {
1874 if (T->isDependentType())
1875 return false;
1876
1877 switch (Kind) {
1879 return SemaRef.RequireLiteralType(Loc, T, DiagID,
1880 std::forward<Ts>(DiagArgs)...);
1881
1883 return !T->isLiteralType(SemaRef.Context);
1884 }
1885
1886 llvm_unreachable("unknown CheckConstexprKind");
1887}
1888
1889/// Determine whether a destructor cannot be constexpr due to
1891 const CXXDestructorDecl *DD,
1893 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1894 "this check is obsolete for C++23");
1895 auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) {
1896 const CXXRecordDecl *RD =
1897 T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1898 if (!RD || RD->hasConstexprDestructor())
1899 return true;
1900
1902 SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject)
1903 << static_cast<int>(DD->getConstexprKind()) << !FD
1904 << (FD ? FD->getDeclName() : DeclarationName()) << T;
1905 SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject)
1906 << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T;
1907 }
1908 return false;
1909 };
1910
1911 const CXXRecordDecl *RD = DD->getParent();
1912 for (const CXXBaseSpecifier &B : RD->bases())
1913 if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr))
1914 return false;
1915 for (const FieldDecl *FD : RD->fields())
1916 if (!Check(FD->getLocation(), FD->getType(), FD))
1917 return false;
1918 return true;
1919}
1920
1921/// Check whether a function's parameter types are all literal types. If so,
1922/// return true. If not, produce a suitable diagnostic and return false.
1924 const FunctionDecl *FD,
1926 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1927 "this check is obsolete for C++23");
1928 unsigned ArgIndex = 0;
1929 const auto *FT = FD->getType()->castAs<FunctionProtoType>();
1930 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1931 e = FT->param_type_end();
1932 i != e; ++i, ++ArgIndex) {
1933 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1934 assert(PD && "null in a parameter list");
1935 SourceLocation ParamLoc = PD->getLocation();
1936 if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i,
1937 diag::err_constexpr_non_literal_param, ArgIndex + 1,
1939 FD->isConsteval()))
1940 return false;
1941 }
1942 return true;
1943}
1944
1945/// Check whether a function's return type is a literal type. If so, return
1946/// true. If not, produce a suitable diagnostic and return false.
1947static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD,
1949 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1950 "this check is obsolete for C++23");
1951 if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(),
1952 diag::err_constexpr_non_literal_return,
1953 FD->isConsteval()))
1954 return false;
1955 return true;
1956}
1957
1958/// Get diagnostic %select index for tag kind for
1959/// record diagnostic message.
1960/// WARNING: Indexes apply to particular diagnostics only!
1961///
1962/// \returns diagnostic %select index.
1964 switch (Tag) {
1966 return 0;
1968 return 1;
1969 case TagTypeKind::Class:
1970 return 2;
1971 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1972 }
1973}
1974
1975static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
1976 Stmt *Body,
1978static bool CheckConstexprMissingReturn(Sema &SemaRef, const FunctionDecl *Dcl);
1979
1981 CheckConstexprKind Kind) {
1982 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1983 if (!getLangOpts().CPlusPlus26 && MD && MD->isInstance()) {
1984 // C++11 [dcl.constexpr]p4:
1985 // The definition of a constexpr constructor shall satisfy the following
1986 // constraints:
1987 // - the class shall not have any virtual base classes;
1988 //
1989 // FIXME: This only applies to constructors and destructors, not arbitrary
1990 // member functions.
1991 const CXXRecordDecl *RD = MD->getParent();
1992 if (RD->getNumVBases()) {
1994 return false;
1995
1996 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1997 << isa<CXXConstructorDecl>(NewFD)
1999 for (const auto &I : RD->vbases())
2000 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
2001 << I.getSourceRange();
2002 return false;
2003 }
2004 }
2005
2006 if (!isa<CXXConstructorDecl>(NewFD)) {
2007 // C++11 [dcl.constexpr]p3:
2008 // The definition of a constexpr function shall satisfy the following
2009 // constraints:
2010 // - it shall not be virtual; (removed in C++20)
2011 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
2012 if (Method && Method->isVirtual()) {
2013 if (getLangOpts().CPlusPlus20) {
2014 if (Kind == CheckConstexprKind::Diagnose)
2015 Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
2016 } else {
2018 return false;
2019
2020 Method = Method->getCanonicalDecl();
2021 Diag(Method->getLocation(), diag::err_constexpr_virtual);
2022
2023 // If it's not obvious why this function is virtual, find an overridden
2024 // function which uses the 'virtual' keyword.
2025 const CXXMethodDecl *WrittenVirtual = Method;
2026 while (!WrittenVirtual->isVirtualAsWritten())
2027 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
2028 if (WrittenVirtual != Method)
2029 Diag(WrittenVirtual->getLocation(),
2030 diag::note_overridden_virtual_function);
2031 return false;
2032 }
2033 }
2034
2035 // - its return type shall be a literal type; (removed in C++23)
2036 if (!getLangOpts().CPlusPlus23 &&
2037 !CheckConstexprReturnType(*this, NewFD, Kind))
2038 return false;
2039 }
2040
2041 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) {
2042 // A destructor can be constexpr only if the defaulted destructor could be;
2043 // we don't need to check the members and bases if we already know they all
2044 // have constexpr destructors. (removed in C++23)
2045 if (!getLangOpts().CPlusPlus23 &&
2046 !Dtor->getParent()->defaultedDestructorIsConstexpr()) {
2048 return false;
2049 if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind))
2050 return false;
2051 }
2052 }
2053
2054 // - each of its parameter types shall be a literal type; (removed in C++23)
2055 if (!getLangOpts().CPlusPlus23 &&
2056 !CheckConstexprParameterTypes(*this, NewFD, Kind))
2057 return false;
2058
2059 Stmt *Body = NewFD->getBody();
2060 assert(Body &&
2061 "CheckConstexprFunctionDefinition called on function with no body");
2062 return CheckConstexprFunctionBody(*this, NewFD, Body, Kind);
2063}
2064
2065/// Check the given declaration statement is legal within a constexpr function
2066/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
2067///
2068/// \return true if the body is OK (maybe only as an extension), false if we
2069/// have diagnosed a problem.
2070static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
2071 DeclStmt *DS, SourceLocation &Cxx1yLoc,
2073 // C++11 [dcl.constexpr]p3 and p4:
2074 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
2075 // contain only
2076 for (const auto *DclIt : DS->decls()) {
2077 switch (DclIt->getKind()) {
2078 case Decl::StaticAssert:
2079 case Decl::Using:
2080 case Decl::UsingShadow:
2081 case Decl::UsingDirective:
2082 case Decl::UnresolvedUsingTypename:
2083 case Decl::UnresolvedUsingValue:
2084 case Decl::UsingEnum:
2085 // - static_assert-declarations
2086 // - using-declarations,
2087 // - using-directives,
2088 // - using-enum-declaration
2089 continue;
2090
2091 case Decl::Typedef:
2092 case Decl::TypeAlias: {
2093 // - typedef declarations and alias-declarations that do not define
2094 // classes or enumerations,
2095 const auto *TN = cast<TypedefNameDecl>(DclIt);
2096 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
2097 // Don't allow variably-modified types in constexpr functions.
2099 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
2100 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
2101 << TL.getSourceRange() << TL.getType()
2103 }
2104 return false;
2105 }
2106 continue;
2107 }
2108
2109 case Decl::Enum:
2110 case Decl::CXXRecord:
2111 // C++1y allows types to be defined, not just declared.
2112 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) {
2114 SemaRef.DiagCompat(DS->getBeginLoc(),
2115 diag_compat::constexpr_type_definition)
2117 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
2118 return false;
2119 }
2120 }
2121 continue;
2122
2123 case Decl::EnumConstant:
2124 case Decl::IndirectField:
2125 case Decl::ParmVar:
2126 // These can only appear with other declarations which are banned in
2127 // C++11 and permitted in C++1y, so ignore them.
2128 continue;
2129
2130 case Decl::Var:
2131 case Decl::Decomposition: {
2132 // C++1y [dcl.constexpr]p3 allows anything except:
2133 // a definition of a variable of non-literal type or of static or
2134 // thread storage duration or [before C++2a] for which no
2135 // initialization is performed.
2136 const auto *VD = cast<VarDecl>(DclIt);
2137 if (VD->isThisDeclarationADefinition()) {
2138 if (VD->isStaticLocal()) {
2140 SemaRef.DiagCompat(VD->getLocation(),
2141 diag_compat::constexpr_static_var)
2143 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
2144 } else if (!SemaRef.getLangOpts().CPlusPlus23) {
2145 return false;
2146 }
2147 }
2148 if (SemaRef.LangOpts.CPlusPlus23) {
2149 CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(),
2150 diag::warn_cxx20_compat_constexpr_var,
2152 } else if (CheckLiteralType(
2153 SemaRef, Kind, VD->getLocation(), VD->getType(),
2154 diag::err_constexpr_local_var_non_literal_type,
2156 return false;
2157 }
2158 if (!VD->getType()->isDependentType() &&
2159 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
2161 SemaRef.DiagCompat(VD->getLocation(),
2162 diag_compat::constexpr_local_var_no_init)
2164 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2165 return false;
2166 }
2167 continue;
2168 }
2169 }
2171 SemaRef.DiagCompat(VD->getLocation(), diag_compat::constexpr_local_var)
2173 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
2174 return false;
2175 }
2176 continue;
2177 }
2178
2179 case Decl::NamespaceAlias:
2180 case Decl::Function:
2181 // These are disallowed in C++11 and permitted in C++1y. Allow them
2182 // everywhere as an extension.
2183 if (!Cxx1yLoc.isValid())
2184 Cxx1yLoc = DS->getBeginLoc();
2185 continue;
2186
2187 default:
2189 SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2190 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2191 }
2192 return false;
2193 }
2194 }
2195
2196 return true;
2197}
2198
2199/// Check that the given field is initialized within a constexpr constructor.
2200///
2201/// \param Dcl The constexpr constructor being checked.
2202/// \param Field The field being checked. This may be a member of an anonymous
2203/// struct or union nested within the class being checked.
2204/// \param Inits All declarations, including anonymous struct/union members and
2205/// indirect members, for which any initialization was provided.
2206/// \param Diagnosed Whether we've emitted the error message yet. Used to attach
2207/// multiple notes for different members to the same error.
2208/// \param Kind Whether we're diagnosing a constructor as written or determining
2209/// whether the formal requirements are satisfied.
2210/// \return \c false if we're checking for validity and the constructor does
2211/// not satisfy the requirements on a constexpr constructor.
2213 const FunctionDecl *Dcl,
2214 FieldDecl *Field,
2216 bool &Diagnosed,
2218 // In C++20 onwards, there's nothing to check for validity.
2220 SemaRef.getLangOpts().CPlusPlus20)
2221 return true;
2222
2223 if (Field->isInvalidDecl())
2224 return true;
2225
2226 if (Field->isUnnamedBitField())
2227 return true;
2228
2229 // Anonymous unions with no variant members and empty anonymous structs do not
2230 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
2231 // indirect fields don't need initializing.
2232 if (Field->isAnonymousStructOrUnion() &&
2233 (Field->getType()->isUnionType()
2234 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
2235 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
2236 return true;
2237
2238 if (!Inits.count(Field)) {
2240 if (!Diagnosed) {
2241 SemaRef.DiagCompat(Dcl->getLocation(),
2242 diag_compat::constexpr_ctor_missing_init);
2243 Diagnosed = true;
2244 }
2245 SemaRef.Diag(Field->getLocation(),
2246 diag::note_constexpr_ctor_missing_init);
2247 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2248 return false;
2249 }
2250 } else if (Field->isAnonymousStructOrUnion()) {
2251 const auto *RD = Field->getType()->castAsRecordDecl();
2252 for (auto *I : RD->fields())
2253 // If an anonymous union contains an anonymous struct of which any member
2254 // is initialized, all members must be initialized.
2255 if (!RD->isUnion() || Inits.count(I))
2256 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2257 Kind))
2258 return false;
2259 }
2260 return true;
2261}
2262
2263/// Check the provided statement is allowed in a constexpr function
2264/// definition.
2265static bool
2268 SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
2269 SourceLocation &Cxx2bLoc,
2271 auto CheckChildren = [&] {
2272 for (Stmt *SubStmt : S->children()) {
2273 if (SubStmt &&
2274 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2275 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2276 return false;
2277 }
2278 return true;
2279 };
2280
2281 // - its function-body shall be [...] a compound-statement that contains only
2282 switch (S->getStmtClass()) {
2283 case Stmt::NullStmtClass:
2284 // - null statements,
2285 return true;
2286
2287 case Stmt::DeclStmtClass: {
2288 auto *DS = cast<DeclStmt>(S);
2289
2290 // Expansion statement 'declarations' have substatements, so we need to
2291 // handle them separately.
2292 if (DS->isSingleDecl()) {
2293 if (auto *ESD = dyn_cast<CXXExpansionStmtDecl>(DS->getSingleDecl())) {
2294 // Don't check unexpanded expansion statements.
2295 if (!ESD->getInstantiations())
2296 return true;
2297 for (auto *BodyIt : ESD->getInstantiations()->getInstantiations()) {
2298 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
2299 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2300 return false;
2301 }
2302 return true;
2303 }
2304 }
2305
2306 // - static_assert-declarations
2307 // - using-declarations,
2308 // - using-directives,
2309 // - typedef declarations and alias-declarations that do not define
2310 // classes or enumerations,
2311 return CheckConstexprDeclStmt(SemaRef, Dcl, DS, Cxx1yLoc, Kind);
2312 }
2313
2314 case Stmt::ReturnStmtClass:
2315 // - and exactly one return statement;
2316 if (isa<CXXConstructorDecl>(Dcl)) {
2317 // C++1y allows return statements in constexpr constructors.
2318 if (!Cxx1yLoc.isValid())
2319 Cxx1yLoc = S->getBeginLoc();
2320 return true;
2321 }
2322
2323 ReturnStmts.push_back(S->getBeginLoc());
2324 return true;
2325
2326 case Stmt::AttributedStmtClass:
2327 // Attributes on a statement don't affect its formal kind and hence don't
2328 // affect its validity in a constexpr function.
2330 SemaRef, Dcl, cast<AttributedStmt>(S)->getSubStmt(), ReturnStmts,
2331 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind);
2332
2333 case Stmt::CompoundStmtClass:
2334 // C++1y allows compound-statements.
2335 if (!Cxx1yLoc.isValid())
2336 Cxx1yLoc = S->getBeginLoc();
2337 return CheckChildren();
2338
2339 case Stmt::IfStmtClass: {
2340 // C++1y allows if-statements.
2341 if (!Cxx1yLoc.isValid())
2342 Cxx1yLoc = S->getBeginLoc();
2343
2344 IfStmt *If = cast<IfStmt>(S);
2345 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
2346 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2347 return false;
2348 if (If->getElse() &&
2349 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
2350 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2351 return false;
2352 return true;
2353 }
2354
2355 case Stmt::WhileStmtClass:
2356 case Stmt::DoStmtClass:
2357 case Stmt::ForStmtClass:
2358 case Stmt::CXXForRangeStmtClass:
2359 case Stmt::ContinueStmtClass:
2360 // C++1y allows all of these. We don't allow them as extensions in C++11,
2361 // because they don't make sense without variable mutation.
2362 if (!SemaRef.getLangOpts().CPlusPlus14)
2363 break;
2364 [[fallthrough]];
2365
2366 case Stmt::SwitchStmtClass:
2367 case Stmt::CaseStmtClass:
2368 case Stmt::DefaultStmtClass:
2369 case Stmt::BreakStmtClass:
2370 // C++1y allows switch-statements, and since they don't need variable
2371 // mutation, we can reasonably allow them in C++11 as an extension.
2372 if (!Cxx1yLoc.isValid())
2373 Cxx1yLoc = S->getBeginLoc();
2374 return CheckChildren();
2375
2376 case Stmt::LabelStmtClass:
2377 case Stmt::GotoStmtClass:
2378 case Stmt::IndirectGotoStmtClass:
2379 if (Cxx2bLoc.isInvalid())
2380 Cxx2bLoc = S->getBeginLoc();
2381 return CheckChildren();
2382
2383 case Stmt::GCCAsmStmtClass:
2384 case Stmt::MSAsmStmtClass:
2385 // C++2a allows inline assembly statements.
2386 case Stmt::CXXTryStmtClass:
2387 if (Cxx2aLoc.isInvalid())
2388 Cxx2aLoc = S->getBeginLoc();
2389 return CheckChildren();
2390
2391 case Stmt::CXXCatchStmtClass:
2392 // Do not bother checking the language mode (already covered by the
2393 // try block check).
2395 SemaRef, Dcl, cast<CXXCatchStmt>(S)->getHandlerBlock(), ReturnStmts,
2396 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind);
2397
2398 default:
2399 if (!isa<Expr>(S))
2400 break;
2401
2402 // C++1y allows expression-statements.
2403 if (!Cxx1yLoc.isValid())
2404 Cxx1yLoc = S->getBeginLoc();
2405 return true;
2406 }
2407
2409 SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2410 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2411 }
2412 return false;
2413}
2414
2415/// Check the body for the given constexpr function declaration only contains
2416/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
2417///
2418/// \return true if the body is OK, false if we have found or diagnosed a
2419/// problem.
2420static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
2421 Stmt *Body,
2424
2425 if (isa<CXXTryStmt>(Body)) {
2426 // C++11 [dcl.constexpr]p3:
2427 // The definition of a constexpr function shall satisfy the following
2428 // constraints: [...]
2429 // - its function-body shall be = delete, = default, or a
2430 // compound-statement
2431 //
2432 // C++11 [dcl.constexpr]p4:
2433 // In the definition of a constexpr constructor, [...]
2434 // - its function-body shall not be a function-try-block;
2435 //
2436 // This restriction is lifted in C++2a, as long as inner statements also
2437 // apply the general constexpr rules.
2438 switch (Kind) {
2440 if (!SemaRef.getLangOpts().CPlusPlus20)
2441 return false;
2442 break;
2443
2445 SemaRef.DiagCompat(Body->getBeginLoc(),
2446 diag_compat::constexpr_function_try_block)
2448 break;
2449 }
2450 }
2451
2452 // - its function-body shall be [...] a compound-statement that contains only
2453 // [... list of cases ...]
2454 //
2455 // Note that walking the children here is enough to properly check for
2456 // CompoundStmt and CXXTryStmt body.
2457 SourceLocation Cxx1yLoc, Cxx2aLoc, Cxx2bLoc;
2458 for (Stmt *SubStmt : Body->children()) {
2459 if (SubStmt &&
2460 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2461 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2462 return false;
2463 }
2464
2466 // If this is only valid as an extension, report that we don't satisfy the
2467 // constraints of the current language.
2468 if ((Cxx2bLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus23) ||
2469 (Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) ||
2470 (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
2471 return false;
2472 } else if (Cxx2bLoc.isValid()) {
2473 SemaRef.DiagCompat(Cxx2bLoc, diag_compat::cxx23_constexpr_body_invalid_stmt)
2475 } else if (Cxx2aLoc.isValid()) {
2476 SemaRef.DiagCompat(Cxx2aLoc, diag_compat::cxx20_constexpr_body_invalid_stmt)
2478 } else if (Cxx1yLoc.isValid()) {
2479 SemaRef.DiagCompat(Cxx1yLoc, diag_compat::cxx14_constexpr_body_invalid_stmt)
2481 }
2482
2484 = dyn_cast<CXXConstructorDecl>(Dcl)) {
2485 const CXXRecordDecl *RD = Constructor->getParent();
2486 // DR1359:
2487 // - every non-variant non-static data member and base class sub-object
2488 // shall be initialized;
2489 // DR1460:
2490 // - if the class is a union having variant members, exactly one of them
2491 // shall be initialized;
2492 if (RD->isUnion()) {
2493 if (Constructor->getNumCtorInitializers() == 0 &&
2494 RD->hasVariantMembers()) {
2496 SemaRef.DiagCompat(Dcl->getLocation(),
2497 diag_compat::constexpr_union_ctor_no_init);
2498 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2499 return false;
2500 }
2501 }
2502 } else if (!Constructor->isDependentContext() &&
2503 !Constructor->isDelegatingConstructor()) {
2504 // Skip detailed checking if we have enough initializers, and we would
2505 // allow at most one initializer per member.
2506 bool AnyAnonStructUnionMembers = false;
2507 unsigned Fields = 0;
2509 E = RD->field_end(); I != E; ++I, ++Fields) {
2510 if (I->isAnonymousStructOrUnion()) {
2511 AnyAnonStructUnionMembers = true;
2512 break;
2513 }
2514 }
2515 // DR1460:
2516 // - if the class is a union-like class, but is not a union, for each of
2517 // its anonymous union members having variant members, exactly one of
2518 // them shall be initialized;
2519 if (AnyAnonStructUnionMembers ||
2520 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2521 // Check initialization of non-static data members. Base classes are
2522 // always initialized so do not need to be checked. Dependent bases
2523 // might not have initializers in the member initializer list.
2525 for (const auto *I: Constructor->inits()) {
2526 if (FieldDecl *FD = I->getMember())
2527 Inits.insert(FD);
2528 else if (IndirectFieldDecl *ID = I->getIndirectMember())
2529 Inits.insert(ID->chain_begin(), ID->chain_end());
2530 }
2531
2532 bool Diagnosed = false;
2533 for (auto *I : RD->fields())
2534 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2535 Kind))
2536 return false;
2537 }
2538 }
2539 } else {
2540 if (ReturnStmts.empty()) {
2541 switch (Kind) {
2543 if (!CheckConstexprMissingReturn(SemaRef, Dcl))
2544 return false;
2545 break;
2546
2548 // The formal requirements don't include this rule in C++14, even
2549 // though the "must be able to produce a constant expression" rules
2550 // still imply it in some cases.
2551 if (!SemaRef.getLangOpts().CPlusPlus14)
2552 return false;
2553 break;
2554 }
2555 } else if (ReturnStmts.size() > 1) {
2556 switch (Kind) {
2558 SemaRef.DiagCompat(ReturnStmts.back(),
2559 diag_compat::constexpr_body_multiple_return);
2560 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2561 SemaRef.Diag(ReturnStmts[I],
2562 diag::note_constexpr_body_previous_return);
2563 break;
2564
2566 if (!SemaRef.getLangOpts().CPlusPlus14)
2567 return false;
2568 break;
2569 }
2570 }
2571 }
2572
2573 // C++11 [dcl.constexpr]p5:
2574 // if no function argument values exist such that the function invocation
2575 // substitution would produce a constant expression, the program is
2576 // ill-formed; no diagnostic required.
2577 // C++11 [dcl.constexpr]p3:
2578 // - every constructor call and implicit conversion used in initializing the
2579 // return value shall be one of those allowed in a constant expression.
2580 // C++11 [dcl.constexpr]p4:
2581 // - every constructor involved in initializing non-static data members and
2582 // base class sub-objects shall be a constexpr constructor.
2583 //
2584 // Note that this rule is distinct from the "requirements for a constexpr
2585 // function", so is not checked in CheckValid mode. Because the check for
2586 // constexpr potential is expensive, skip the check if the diagnostic is
2587 // disabled, the function is declared in a system header, or we're in C++23
2588 // or later mode (see https://wg21.link/P2448).
2589 bool SkipCheck =
2590 !SemaRef.getLangOpts().CheckConstexprFunctionBodies ||
2591 SemaRef.getSourceManager().isInSystemHeader(Dcl->getLocation()) ||
2592 SemaRef.getDiagnostics().isIgnored(
2593 diag::ext_constexpr_function_never_constant_expr, Dcl->getLocation());
2595 if (Kind == Sema::CheckConstexprKind::Diagnose && !SkipCheck &&
2596 !Expr::isPotentialConstantExpr(Dcl, Diags)) {
2597 SemaRef.Diag(Dcl->getLocation(),
2598 diag::ext_constexpr_function_never_constant_expr)
2599 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval()
2600 << Dcl->getNameInfo().getSourceRange();
2601 for (const auto &Diag : Diags)
2602 SemaRef.Diag(Diag.first, Diag.second);
2603 // Don't return false here: we allow this for compatibility in
2604 // system headers.
2605 }
2606
2607 return true;
2608}
2609
2611 const FunctionDecl *Dcl) {
2612 bool IsVoidOrDependentType = Dcl->getReturnType()->isVoidType() ||
2614 // Skip emitting a missing return error diagnostic for non-void functions
2615 // since C++23 no longer mandates constexpr functions to yield constant
2616 // expressions.
2617 if (SemaRef.getLangOpts().CPlusPlus23 && !IsVoidOrDependentType)
2618 return true;
2619
2620 // C++14 doesn't require constexpr functions to contain a 'return'
2621 // statement. We still do, unless the return type might be void, because
2622 // otherwise if there's no return statement, the function cannot
2623 // be used in a core constant expression.
2624 bool OK = SemaRef.getLangOpts().CPlusPlus14 && IsVoidOrDependentType;
2625 SemaRef.Diag(Dcl->getLocation(),
2626 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2627 : diag::err_constexpr_body_no_return)
2628 << Dcl->isConsteval();
2629 return OK;
2630}
2631
2633 FunctionDecl *FD, const sema::FunctionScopeInfo *FSI) {
2635 return true;
2639 auto it = UndefinedButUsed.find(FD->getCanonicalDecl());
2640 if (it != UndefinedButUsed.end()) {
2641 Diag(it->second, diag::err_immediate_function_used_before_definition)
2642 << it->first;
2643 Diag(FD->getLocation(), diag::note_defined_here) << FD;
2644 if (FD->isImmediateFunction() && !FD->isConsteval())
2646 return false;
2647 }
2648 }
2649 return true;
2650}
2651
2653 assert(FD->isImmediateEscalating() && !FD->isConsteval() &&
2654 "expected an immediate function");
2655 assert(FD->hasBody() && "expected the function to have a body");
2656 struct ImmediateEscalatingExpressionsVisitor : DynamicRecursiveASTVisitor {
2657 Sema &SemaRef;
2658
2659 const FunctionDecl *ImmediateFn;
2660 bool ImmediateFnIsConstructor;
2661 CXXConstructorDecl *CurrentConstructor = nullptr;
2662 CXXCtorInitializer *CurrentInit = nullptr;
2663
2664 ImmediateEscalatingExpressionsVisitor(Sema &SemaRef, FunctionDecl *FD)
2665 : SemaRef(SemaRef), ImmediateFn(FD),
2666 ImmediateFnIsConstructor(isa<CXXConstructorDecl>(FD)) {
2667 ShouldVisitImplicitCode = true;
2668 ShouldVisitLambdaBody = false;
2669 }
2670
2671 void Diag(const Expr *E, const FunctionDecl *Fn, bool IsCall) {
2672 SourceLocation Loc = E->getBeginLoc();
2673 SourceRange Range = E->getSourceRange();
2674 if (CurrentConstructor && CurrentInit) {
2675 Loc = CurrentConstructor->getLocation();
2676 Range = CurrentInit->isWritten() ? CurrentInit->getSourceRange()
2677 : SourceRange();
2678 }
2679
2680 FieldDecl* InitializedField = CurrentInit ? CurrentInit->getAnyMember() : nullptr;
2681
2682 SemaRef.Diag(Loc, diag::note_immediate_function_reason)
2683 << ImmediateFn << Fn << Fn->isConsteval() << IsCall
2684 << isa<CXXConstructorDecl>(Fn) << ImmediateFnIsConstructor
2685 << (InitializedField != nullptr)
2686 << (CurrentInit && !CurrentInit->isWritten())
2687 << InitializedField << Range;
2688 }
2689 bool TraverseCallExpr(CallExpr *E) override {
2690 if (const auto *DR =
2691 dyn_cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit());
2692 DR && DR->isImmediateEscalating()) {
2693 Diag(E, E->getDirectCallee(), /*IsCall=*/true);
2694 return false;
2695 }
2696
2697 for (Expr *A : E->arguments())
2698 if (!TraverseStmt(A))
2699 return false;
2700
2701 return true;
2702 }
2703
2704 bool VisitDeclRefExpr(DeclRefExpr *E) override {
2705 if (const auto *ReferencedFn = dyn_cast<FunctionDecl>(E->getDecl());
2706 ReferencedFn && E->isImmediateEscalating()) {
2707 Diag(E, ReferencedFn, /*IsCall=*/false);
2708 return false;
2709 }
2710
2711 return true;
2712 }
2713
2714 bool VisitCXXConstructExpr(CXXConstructExpr *E) override {
2716 if (E->isImmediateEscalating()) {
2717 Diag(E, D, /*IsCall=*/true);
2718 return false;
2719 }
2720 return true;
2721 }
2722
2723 bool TraverseConstructorInitializer(CXXCtorInitializer *Init) override {
2724 llvm::SaveAndRestore RAII(CurrentInit, Init);
2726 }
2727
2728 bool TraverseCXXConstructorDecl(CXXConstructorDecl *Ctr) override {
2729 llvm::SaveAndRestore RAII(CurrentConstructor, Ctr);
2730 return DynamicRecursiveASTVisitor::TraverseCXXConstructorDecl(Ctr);
2731 }
2732
2733 bool TraverseType(QualType T, bool TraverseQualifier) override {
2734 return true;
2735 }
2736 bool VisitBlockExpr(BlockExpr *T) override { return true; }
2737
2738 } Visitor(*this, FD);
2739 Visitor.TraverseDecl(FD);
2740}
2741
2743 assert(getLangOpts().CPlusPlus && "No class names in C!");
2744
2745 if (SS && SS->isInvalid())
2746 return nullptr;
2747
2748 if (SS && SS->isNotEmpty()) {
2749 DeclContext *DC = computeDeclContext(*SS, true);
2750 return dyn_cast_or_null<CXXRecordDecl>(DC);
2751 }
2752
2753 return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2754}
2755
2757 const CXXScopeSpec *SS) {
2758 CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2759 return CurDecl && &II == CurDecl->getIdentifier();
2760}
2761
2763 assert(getLangOpts().CPlusPlus && "No class names in C!");
2764
2765 if (!getLangOpts().SpellChecking)
2766 return false;
2767
2768 CXXRecordDecl *CurDecl;
2769 if (SS && SS->isSet() && !SS->isInvalid()) {
2770 DeclContext *DC = computeDeclContext(*SS, true);
2771 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2772 } else
2773 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2774
2775 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2776 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2777 < II->getLength()) {
2778 II = CurDecl->getIdentifier();
2779 return true;
2780 }
2781
2782 return false;
2783}
2784
2786 SourceRange SpecifierRange,
2787 bool Virtual, AccessSpecifier Access,
2788 TypeSourceInfo *TInfo,
2789 SourceLocation EllipsisLoc) {
2790 QualType BaseType = TInfo->getType();
2791 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2792 if (BaseType->containsErrors()) {
2793 // Already emitted a diagnostic when parsing the error type.
2794 return nullptr;
2795 }
2796
2797 if (EllipsisLoc.isValid() && !BaseType->containsUnexpandedParameterPack()) {
2798 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2799 << TInfo->getTypeLoc().getSourceRange();
2800 EllipsisLoc = SourceLocation();
2801 }
2802
2803 auto *BaseDecl =
2804 dyn_cast_if_present<CXXRecordDecl>(computeDeclContext(BaseType));
2805 // C++ [class.derived.general]p2:
2806 // A class-or-decltype shall denote a (possibly cv-qualified) class type
2807 // that is not an incompletely defined class; any cv-qualifiers are
2808 // ignored.
2809 if (BaseDecl) {
2810 // C++ [class.union.general]p4:
2811 // [...] A union shall not be used as a base class.
2812 if (BaseDecl->isUnion()) {
2813 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2814 return nullptr;
2815 }
2816
2817 if (BaseType.hasQualifiers()) {
2818 std::string Quals =
2819 BaseType.getQualifiers().getAsString(Context.getPrintingPolicy());
2820 Diag(BaseLoc, diag::warn_qual_base_type)
2821 << Quals << llvm::count(Quals, ' ') + 1 << BaseType;
2822 Diag(BaseLoc, diag::note_base_class_specified_here) << BaseType;
2823 }
2824
2825 // For the MS ABI, propagate DLL attributes to base class templates.
2826 if (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
2827 Context.getTargetInfo().getTriple().isPS()) {
2828 if (Attr *ClassAttr = getDLLAttr(Class)) {
2829 if (auto *BaseSpec =
2830 dyn_cast<ClassTemplateSpecializationDecl>(BaseDecl)) {
2831 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseSpec,
2832 BaseLoc);
2833 }
2834 }
2835 }
2836
2837 if (RequireCompleteType(BaseLoc, BaseType, diag::err_incomplete_base_class,
2838 SpecifierRange)) {
2839 Class->setInvalidDecl();
2840 return nullptr;
2841 }
2842
2843 BaseDecl = BaseDecl->getDefinition();
2844 assert(BaseDecl && "Base type is not incomplete, but has no definition");
2845
2846 // Microsoft docs say:
2847 // "If a base-class has a code_seg attribute, derived classes must have the
2848 // same attribute."
2849 const auto *BaseCSA = BaseDecl->getAttr<CodeSegAttr>();
2850 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2851 if ((DerivedCSA || BaseCSA) &&
2852 (!BaseCSA || !DerivedCSA ||
2853 BaseCSA->getName() != DerivedCSA->getName())) {
2854 Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2855 Diag(BaseDecl->getLocation(), diag::note_base_class_specified_here)
2856 << BaseDecl;
2857 return nullptr;
2858 }
2859
2860 // A class which contains a flexible array member is not suitable for use as
2861 // a base class:
2862 // - If the layout determines that a base comes before another base,
2863 // the flexible array member would index into the subsequent base.
2864 // - If the layout determines that base comes before the derived class,
2865 // the flexible array member would index into the derived class.
2866 if (BaseDecl->hasFlexibleArrayMember()) {
2867 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2868 << BaseDecl->getDeclName();
2869 return nullptr;
2870 }
2871
2872 // C++ [class]p3:
2873 // If a class is marked final and it appears as a base-type-specifier in
2874 // base-clause, the program is ill-formed.
2875 if (FinalAttr *FA = BaseDecl->getAttr<FinalAttr>()) {
2876 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2877 << BaseDecl->getDeclName() << FA->isSpelledAsSealed();
2878 Diag(BaseDecl->getLocation(), diag::note_entity_declared_at)
2879 << BaseDecl->getDeclName() << FA->getRange();
2880 return nullptr;
2881 }
2882
2883 // If the base class is invalid the derived class is as well.
2884 if (BaseDecl->isInvalidDecl())
2885 Class->setInvalidDecl();
2886 } else if (BaseType->isDependentType()) {
2887 // Make sure that we don't make an ill-formed AST where the type of the
2888 // Class is non-dependent and its attached base class specifier is an
2889 // dependent type, which violates invariants in many clang code paths (e.g.
2890 // constexpr evaluator). If this case happens (in errory-recovery mode), we
2891 // explicitly mark the Class decl invalid. The diagnostic was already
2892 // emitted.
2893 if (!Class->isDependentContext())
2894 Class->setInvalidDecl();
2895 } else {
2896 // The base class is some non-dependent non-class type.
2897 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2898 return nullptr;
2899 }
2900
2901 // In HLSL, unspecified class access is public rather than private.
2902 if (getLangOpts().HLSL && Class->getTagKind() == TagTypeKind::Class &&
2903 Access == AS_none)
2904 Access = AS_public;
2905
2906 // Create the base specifier.
2907 return new (Context) CXXBaseSpecifier(
2908 SpecifierRange, Virtual, Class->getTagKind() == TagTypeKind::Class,
2909 Access, TInfo, EllipsisLoc);
2910}
2911
2913 const ParsedAttributesView &Attributes,
2914 bool Virtual, AccessSpecifier Access,
2915 ParsedType basetype, SourceLocation BaseLoc,
2916 SourceLocation EllipsisLoc) {
2917 if (!classdecl)
2918 return true;
2919
2920 AdjustDeclIfTemplate(classdecl);
2921 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2922 if (!Class)
2923 return true;
2924
2925 // We haven't yet attached the base specifiers.
2926 Class->setIsParsingBaseSpecifiers();
2927
2928 // We do not support any C++11 attributes on base-specifiers yet.
2929 // Diagnose any attributes we see.
2930 for (const ParsedAttr &AL : Attributes) {
2931 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2932 continue;
2933 if (AL.getKind() == ParsedAttr::UnknownAttribute)
2935 else
2936 Diag(AL.getLoc(), diag::err_base_specifier_attribute)
2937 << AL << AL.isRegularKeywordAttribute() << AL.getRange();
2938 }
2939
2940 TypeSourceInfo *TInfo = nullptr;
2941 GetTypeFromParser(basetype, &TInfo);
2942
2943 if (EllipsisLoc.isInvalid() &&
2944 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2946 return true;
2947
2948 // C++ [class.union.general]p4:
2949 // [...] A union shall not have base classes.
2950 if (Class->isUnion()) {
2951 Diag(Class->getLocation(), diag::err_base_clause_on_union)
2952 << SpecifierRange;
2953 return true;
2954 }
2955
2956 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2957 Virtual, Access, TInfo,
2958 EllipsisLoc))
2959 return BaseSpec;
2960
2961 Class->setInvalidDecl();
2962 return true;
2963}
2964
2965/// Use small set to collect indirect bases. As this is only used
2966/// locally, there's no need to abstract the small size parameter.
2968
2969/// Recursively add the bases of Type. Don't add Type itself.
2970static void
2972 const QualType &Type)
2973{
2974 // Even though the incoming type is a base, it might not be
2975 // a class -- it could be a template parm, for instance.
2976 if (const auto *Decl = Type->getAsCXXRecordDecl()) {
2977 // Iterate over its bases.
2978 for (const auto &BaseSpec : Decl->bases()) {
2979 QualType Base = Context.getCanonicalType(BaseSpec.getType())
2980 .getUnqualifiedType();
2981 if (Set.insert(Base).second)
2982 // If we've not already seen it, recurse.
2983 NoteIndirectBases(Context, Set, Base);
2984 }
2985 }
2986}
2987
2990 if (Bases.empty())
2991 return false;
2992
2993 // Used to keep track of which base types we have already seen, so
2994 // that we can properly diagnose redundant direct base types. Note
2995 // that the key is always the unqualified canonical type of the base
2996 // class.
2997 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2998
2999 // Used to track indirect bases so we can see if a direct base is
3000 // ambiguous.
3001 IndirectBaseSet IndirectBaseTypes;
3002
3003 // Copy non-redundant base specifiers into permanent storage.
3004 unsigned NumGoodBases = 0;
3005 bool Invalid = false;
3006
3007 if (getLangOpts().HLSL && Bases.size() > 1) {
3008 Diag(Bases[1]->getBeginLoc(), diag::err_hlsl_mult_inheritance);
3009 // To prevent producing error messages about the additional base classes
3010 Bases = Bases.take_front();
3011 Invalid = true;
3012 }
3013
3014 for (unsigned idx = 0; idx < Bases.size(); ++idx) {
3015 QualType NewBaseType
3016 = Context.getCanonicalType(Bases[idx]->getType());
3017 NewBaseType = NewBaseType.getLocalUnqualifiedType();
3018
3019 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
3020 if (KnownBase) {
3021 // C++ [class.mi]p3:
3022 // A class shall not be specified as a direct base class of a
3023 // derived class more than once.
3024 Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
3025 << KnownBase->getType() << Bases[idx]->getSourceRange();
3026
3027 // Delete the duplicate base class specifier; we're going to
3028 // overwrite its pointer later.
3029 Context.Deallocate(Bases[idx]);
3030
3031 Invalid = true;
3032 } else {
3033 // Okay, add this new base class.
3034 KnownBase = Bases[idx];
3035 Bases[NumGoodBases++] = Bases[idx];
3036
3037 if (NewBaseType->isDependentType())
3038 continue;
3039 // Note this base's direct & indirect bases, if there could be ambiguity.
3040 if (Bases.size() > 1)
3041 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
3042
3043 if (const auto *RD = NewBaseType->getAsCXXRecordDecl()) {
3044 if (Class->isInterface() &&
3045 (!RD->isInterfaceLike() ||
3046 KnownBase->getAccessSpecifier() != AS_public)) {
3047 // The Microsoft extension __interface does not permit bases that
3048 // are not themselves public interfaces.
3049 Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
3050 << getRecordDiagFromTagKind(RD->getTagKind()) << RD
3051 << RD->getSourceRange();
3052 Invalid = true;
3053 }
3054 if (RD->hasAttr<WeakAttr>())
3055 Class->addAttr(WeakAttr::CreateImplicit(Context));
3056 }
3057 }
3058 }
3059
3060 // Attach the remaining base class specifiers to the derived class.
3061 Class->setBases(Bases.data(), NumGoodBases);
3062
3063 // Check that the only base classes that are duplicate are virtual.
3064 for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
3065 // Check whether this direct base is inaccessible due to ambiguity.
3066 QualType BaseType = Bases[idx]->getType();
3067
3068 // Skip all dependent types in templates being used as base specifiers.
3069 // Checks below assume that the base specifier is a CXXRecord.
3070 if (BaseType->isDependentType())
3071 continue;
3072
3073 CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
3074 .getUnqualifiedType();
3075
3076 if (IndirectBaseTypes.count(CanonicalBase)) {
3077 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3078 /*DetectVirtual=*/true);
3079 bool found
3080 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
3081 assert(found);
3082 (void)found;
3083
3084 if (Paths.isAmbiguous(CanonicalBase))
3085 Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
3086 << BaseType << getAmbiguousPathsDisplayString(Paths)
3087 << Bases[idx]->getSourceRange();
3088 else
3089 assert(Bases[idx]->isVirtual());
3090 }
3091
3092 // Delete the base class specifier, since its data has been copied
3093 // into the CXXRecordDecl.
3094 Context.Deallocate(Bases[idx]);
3095 }
3096
3097 return Invalid;
3098}
3099
3102 if (!ClassDecl || Bases.empty())
3103 return;
3104
3105 AdjustDeclIfTemplate(ClassDecl);
3106 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
3107}
3108
3110 CXXRecordDecl *Base, CXXBasePaths &Paths) {
3111 if (!getLangOpts().CPlusPlus)
3112 return false;
3113
3114 if (!Base || !Derived)
3115 return false;
3116
3117 // If either the base or the derived type is invalid, don't try to
3118 // check whether one is derived from the other.
3119 if (Base->isInvalidDecl() || Derived->isInvalidDecl())
3120 return false;
3121
3122 // FIXME: In a modules build, do we need the entire path to be visible for us
3123 // to be able to use the inheritance relationship?
3124 if (!isCompleteType(Loc, Context.getCanonicalTagType(Derived)) &&
3125 !Derived->isBeingDefined())
3126 return false;
3127
3128 return Derived->isDerivedFrom(Base, Paths);
3129}
3130
3133 CXXBasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/false,
3134 /*DetectVirtual=*/false);
3135 return IsDerivedFrom(Loc, Derived, Base, Paths);
3136}
3137
3139 CXXBasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/false,
3140 /*DetectVirtual=*/false);
3141 return IsDerivedFrom(Loc, Derived->getAsCXXRecordDecl(),
3142 Base->getAsCXXRecordDecl(), Paths);
3143}
3144
3146 CXXBasePaths &Paths) {
3147 return IsDerivedFrom(Loc, Derived->getAsCXXRecordDecl(),
3148 Base->getAsCXXRecordDecl(), Paths);
3149}
3150
3151static void BuildBasePathArray(const CXXBasePath &Path,
3152 CXXCastPath &BasePathArray) {
3153 // We first go backward and check if we have a virtual base.
3154 // FIXME: It would be better if CXXBasePath had the base specifier for
3155 // the nearest virtual base.
3156 unsigned Start = 0;
3157 for (unsigned I = Path.size(); I != 0; --I) {
3158 if (Path[I - 1].Base->isVirtual()) {
3159 Start = I - 1;
3160 break;
3161 }
3162 }
3163
3164 // Now add all bases.
3165 for (unsigned I = Start, E = Path.size(); I != E; ++I)
3166 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
3167}
3168
3169
3171 CXXCastPath &BasePathArray) {
3172 assert(BasePathArray.empty() && "Base path array must be empty!");
3173 assert(Paths.isRecordingPaths() && "Must record paths!");
3174 return ::BuildBasePathArray(Paths.front(), BasePathArray);
3175}
3176
3177bool
3179 unsigned InaccessibleBaseID,
3180 unsigned AmbiguousBaseConvID,
3181 SourceLocation Loc, SourceRange Range,
3182 DeclarationName Name,
3183 CXXCastPath *BasePath,
3184 bool IgnoreAccess) {
3185 // First, determine whether the path from Derived to Base is
3186 // ambiguous. This is slightly more expensive than checking whether
3187 // the Derived to Base conversion exists, because here we need to
3188 // explore multiple paths to determine if there is an ambiguity.
3189 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3190 /*DetectVirtual=*/false);
3191 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
3192 if (!DerivationOkay)
3193 return true;
3194
3195 const CXXBasePath *Path = nullptr;
3196 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
3197 Path = &Paths.front();
3198
3199 // For MSVC compatibility, check if Derived directly inherits from Base. Clang
3200 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
3201 // user to access such bases.
3202 if (!Path && getLangOpts().MSVCCompat) {
3203 for (const CXXBasePath &PossiblePath : Paths) {
3204 if (PossiblePath.size() == 1) {
3205 Path = &PossiblePath;
3206 if (AmbiguousBaseConvID)
3207 Diag(Loc, diag::ext_ms_ambiguous_direct_base)
3208 << Base << Derived << Range;
3209 break;
3210 }
3211 }
3212 }
3213
3214 if (Path) {
3215 if (!IgnoreAccess) {
3216 // Check that the base class can be accessed.
3217 switch (
3218 CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
3219 case AR_inaccessible:
3220 return true;
3221 case AR_accessible:
3222 case AR_dependent:
3223 case AR_delayed:
3224 break;
3225 }
3226 }
3227
3228 // Build a base path if necessary.
3229 if (BasePath)
3230 ::BuildBasePathArray(*Path, *BasePath);
3231 return false;
3232 }
3233
3234 if (AmbiguousBaseConvID) {
3235 // We know that the derived-to-base conversion is ambiguous, and
3236 // we're going to produce a diagnostic. Perform the derived-to-base
3237 // search just one more time to compute all of the possible paths so
3238 // that we can print them out. This is more expensive than any of
3239 // the previous derived-to-base checks we've done, but at this point
3240 // performance isn't as much of an issue.
3241 Paths.clear();
3242 Paths.setRecordingPaths(true);
3243 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
3244 assert(StillOkay && "Can only be used with a derived-to-base conversion");
3245 (void)StillOkay;
3246
3247 // Build up a textual representation of the ambiguous paths, e.g.,
3248 // D -> B -> A, that will be used to illustrate the ambiguous
3249 // conversions in the diagnostic. We only print one of the paths
3250 // to each base class subobject.
3251 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3252
3253 Diag(Loc, AmbiguousBaseConvID)
3254 << Derived << Base << PathDisplayStr << Range << Name;
3255 }
3256 return true;
3257}
3258
3259bool
3261 SourceLocation Loc, SourceRange Range,
3262 CXXCastPath *BasePath,
3263 bool IgnoreAccess) {
3265 Derived, Base, diag::err_upcast_to_inaccessible_base,
3266 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
3267 BasePath, IgnoreAccess);
3268}
3269
3271 std::string PathDisplayStr;
3272 std::set<unsigned> DisplayedPaths;
3273 for (const CXXBasePath &Path : Paths) {
3274 if (DisplayedPaths.insert(Path.back().SubobjectNumber).second) {
3275 // We haven't displayed a path to this particular base
3276 // class subobject yet.
3277 PathDisplayStr += "\n ";
3278 PathDisplayStr += QualType(Context.getCanonicalTagType(Paths.getOrigin()))
3279 .getAsString();
3280 for (const CXXBasePathElement &Element : Path)
3281 PathDisplayStr += " -> " + Element.Base->getType().getAsString();
3282 }
3283 }
3284
3285 return PathDisplayStr;
3286}
3287
3288//===----------------------------------------------------------------------===//
3289// C++ class member Handling
3290//===----------------------------------------------------------------------===//
3291
3293 SourceLocation ColonLoc,
3294 const ParsedAttributesView &Attrs) {
3295 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
3297 ASLoc, ColonLoc);
3298 CurContext->addHiddenDecl(ASDecl);
3299 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
3300}
3301
3303 if (D->isInvalidDecl())
3304 return;
3305
3306 // We only care about "override" and "final" declarations.
3307 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
3308 return;
3309
3310 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3311
3312 // We can't check dependent instance methods.
3313 if (MD && MD->isInstance() &&
3314 (MD->getParent()->hasAnyDependentBases() ||
3315 MD->getType()->isDependentType()))
3316 return;
3317
3318 if (MD && !MD->isVirtual()) {
3319 // If we have a non-virtual method, check if it hides a virtual method.
3320 // (In that case, it's most likely the method has the wrong type.)
3321 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3322 FindHiddenVirtualMethods(MD, OverloadedMethods);
3323
3324 if (!OverloadedMethods.empty()) {
3325 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3326 Diag(OA->getLocation(),
3327 diag::override_keyword_hides_virtual_member_function)
3328 << "override" << (OverloadedMethods.size() > 1);
3329 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3330 Diag(FA->getLocation(),
3331 diag::override_keyword_hides_virtual_member_function)
3332 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3333 << (OverloadedMethods.size() > 1);
3334 }
3335 NoteHiddenVirtualMethods(MD, OverloadedMethods);
3336 MD->setInvalidDecl();
3337 return;
3338 }
3339 // Fall through into the general case diagnostic.
3340 // FIXME: We might want to attempt typo correction here.
3341 }
3342
3343 if (!MD || !MD->isVirtual()) {
3344 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3345 Diag(OA->getLocation(),
3346 diag::override_keyword_only_allowed_on_virtual_member_functions)
3347 << "override" << FixItHint::CreateRemoval(OA->getLocation());
3348 D->dropAttr<OverrideAttr>();
3349 }
3350 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3351 Diag(FA->getLocation(),
3352 diag::override_keyword_only_allowed_on_virtual_member_functions)
3353 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3354 << FixItHint::CreateRemoval(FA->getLocation());
3355 D->dropAttr<FinalAttr>();
3356 }
3357 return;
3358 }
3359
3360 // C++11 [class.virtual]p5:
3361 // If a function is marked with the virt-specifier override and
3362 // does not override a member function of a base class, the program is
3363 // ill-formed.
3364 bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
3365 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
3366 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
3367 << MD->getDeclName();
3368}
3369
3371 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
3372 return;
3373 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3374 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
3375 return;
3376
3377 SourceLocation Loc = MD->getLocation();
3378 SourceLocation SpellingLoc = Loc;
3379 if (getSourceManager().isMacroArgExpansion(Loc))
3380 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
3381 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
3382 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
3383 return;
3384
3385 if (MD->size_overridden_methods() > 0) {
3386 auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) {
3387 unsigned DiagID =
3388 Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation())
3389 ? DiagInconsistent
3390 : DiagSuggest;
3391 Diag(MD->getLocation(), DiagID) << MD->getDeclName();
3392 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
3393 Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
3394 };
3395 if (isa<CXXDestructorDecl>(MD))
3396 EmitDiag(
3397 diag::warn_inconsistent_destructor_marked_not_override_overriding,
3398 diag::warn_suggest_destructor_marked_not_override_overriding);
3399 else
3400 EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding,
3401 diag::warn_suggest_function_marked_not_override_overriding);
3402 }
3403}
3404
3406 const CXXMethodDecl *Old) {
3407 FinalAttr *FA = Old->getAttr<FinalAttr>();
3408 if (!FA)
3409 return false;
3410
3411 Diag(New->getLocation(), diag::err_final_function_overridden)
3412 << New->getDeclName()
3413 << FA->isSpelledAsSealed();
3414 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3415 return true;
3416}
3417
3419 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
3420 // FIXME: Destruction of ObjC lifetime types has side-effects.
3421 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3422 return !RD->isCompleteDefinition() || !RD->hasTrivialDefaultConstructor() ||
3423 !RD->hasTrivialDestructor();
3424 return false;
3425}
3426
3427void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
3428 DeclarationName FieldName,
3429 const CXXRecordDecl *RD,
3430 bool DeclIsField) {
3431 if (Diags.isIgnored(diag::warn_shadow_field, Loc))
3432 return;
3433
3434 // To record a shadowed field in a base
3435 std::map<CXXRecordDecl*, NamedDecl*> Bases;
3436 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
3437 CXXBasePath &Path) {
3438 const auto Base = Specifier->getType()->getAsCXXRecordDecl();
3439 // Record an ambiguous path directly
3440 if (Bases.find(Base) != Bases.end())
3441 return true;
3442 for (const auto Field : Base->lookup(FieldName)) {
3443 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
3444 Field->getAccess() != AS_private) {
3445 assert(Field->getAccess() != AS_none);
3446 assert(Bases.find(Base) == Bases.end());
3447 Bases[Base] = Field;
3448 return true;
3449 }
3450 }
3451 return false;
3452 };
3453
3454 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3455 /*DetectVirtual=*/true);
3456 if (!RD->lookupInBases(FieldShadowed, Paths))
3457 return;
3458
3459 for (const auto &P : Paths) {
3460 auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
3461 auto It = Bases.find(Base);
3462 // Skip duplicated bases
3463 if (It == Bases.end())
3464 continue;
3465 auto BaseField = It->second;
3466 assert(BaseField->getAccess() != AS_private);
3467 if (AS_none !=
3468 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
3469 Diag(Loc, diag::warn_shadow_field)
3470 << FieldName << RD << Base << DeclIsField;
3471 Diag(BaseField->getLocation(), diag::note_shadow_field);
3472 Bases.erase(It);
3473 }
3474 }
3475}
3476
3477template <typename AttrType>
3478inline static bool HasAttribute(const QualType &T) {
3479 if (const TagDecl *TD = T->getAsTagDecl())
3480 return TD->hasAttr<AttrType>();
3481 if (const TypedefType *TDT = T->getAs<TypedefType>())
3482 return TDT->getDecl()->hasAttr<AttrType>();
3483 return false;
3484}
3485
3486static bool IsUnusedPrivateField(const FieldDecl *FD) {
3487 if (FD->getAccess() == AS_private && FD->getDeclName()) {
3488 QualType FieldType = FD->getType();
3489 if (HasAttribute<WarnUnusedAttr>(FieldType))
3490 return true;
3491
3492 return !FD->isImplicit() && !FD->hasAttr<UnusedAttr>() &&
3493 !FD->getParent()->isDependentContext() &&
3494 !HasAttribute<UnusedAttr>(FieldType) &&
3496 }
3497 return false;
3498}
3499
3500NamedDecl *
3502 MultiTemplateParamsArg TemplateParameterLists,
3503 Expr *BitWidth, const VirtSpecifiers &VS,
3504 InClassInitStyle InitStyle) {
3505 const DeclSpec &DS = D.getDeclSpec();
3507 DeclarationName Name = NameInfo.getName();
3508 SourceLocation Loc = NameInfo.getLoc();
3509
3510 // For anonymous bitfields, the location should point to the type.
3511 if (Loc.isInvalid())
3512 Loc = D.getBeginLoc();
3513
3515 assert(!DS.isFriendSpecified());
3516
3517 bool isFunc = D.isDeclarationOfFunction();
3518 const ParsedAttr *MSPropertyAttr =
3520
3521 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
3522 // The Microsoft extension __interface only permits public member functions
3523 // and prohibits constructors, destructors, operators, non-public member
3524 // functions, static methods and data members.
3525 unsigned InvalidDecl;
3526 bool ShowDeclName = true;
3527 if (!isFunc &&
3528 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
3529 InvalidDecl = 0;
3530 else if (!isFunc)
3531 InvalidDecl = 1;
3532 else if (AS != AS_public)
3533 InvalidDecl = 2;
3535 InvalidDecl = 3;
3536 else switch (Name.getNameKind()) {
3538 InvalidDecl = 4;
3539 ShowDeclName = false;
3540 break;
3541
3543 InvalidDecl = 5;
3544 ShowDeclName = false;
3545 break;
3546
3549 InvalidDecl = 6;
3550 break;
3551
3552 default:
3553 InvalidDecl = 0;
3554 break;
3555 }
3556
3557 if (InvalidDecl) {
3558 if (ShowDeclName)
3559 Diag(Loc, diag::err_invalid_member_in_interface)
3560 << (InvalidDecl-1) << Name;
3561 else
3562 Diag(Loc, diag::err_invalid_member_in_interface)
3563 << (InvalidDecl-1) << "";
3564 return nullptr;
3565 }
3566 }
3567
3568 // HLSL prohibits user defined constructors and destructors.
3569 if (getLangOpts().HLSL) {
3570 switch (Name.getNameKind()) {
3573 Diag(Loc, diag::err_hlsl_cstor_dstor);
3574 return nullptr;
3575 default:
3576 break;
3577 }
3578 }
3579
3580 // C++ 9.2p6: A member shall not be declared to have automatic storage
3581 // duration (auto, register) or with the extern storage-class-specifier.
3582 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3583 // data members and cannot be applied to names declared const or static,
3584 // and cannot be applied to reference members.
3585 switch (DS.getStorageClassSpec()) {
3589 break;
3591 if (isFunc) {
3592 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3593
3594 // FIXME: It would be nicer if the keyword was ignored only for this
3595 // declarator. Otherwise we could get follow-up errors.
3597 }
3598 break;
3599 default:
3601 diag::err_storageclass_invalid_for_member);
3603 break;
3604 }
3605
3606 bool isInstField = (DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3608 !isFunc && TemplateParameterLists.empty();
3609
3610 if (DS.hasConstexprSpecifier() && isInstField) {
3612 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3613 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3614 if (InitStyle == ICIS_NoInit) {
3615 B << 0 << 0;
3617 B << FixItHint::CreateRemoval(ConstexprLoc);
3618 else {
3619 B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3621 const char *PrevSpec;
3622 unsigned DiagID;
3623 bool Failed = D.getMutableDeclSpec().SetTypeQual(
3624 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3625 (void)Failed;
3626 assert(!Failed && "Making a constexpr member const shouldn't fail");
3627 }
3628 } else {
3629 B << 1;
3630 const char *PrevSpec;
3631 unsigned DiagID;
3633 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3634 Context.getPrintingPolicy())) {
3636 "This is the only DeclSpec that should fail to be applied");
3637 B << 1;
3638 } else {
3639 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3640 isInstField = false;
3641 }
3642 }
3643 }
3644
3646 if (isInstField) {
3647 CXXScopeSpec &SS = D.getCXXScopeSpec();
3648
3649 // Data members must have identifiers for names.
3650 if (!Name.isIdentifier()) {
3651 Diag(Loc, diag::err_bad_variable_name)
3652 << Name;
3653 return nullptr;
3654 }
3655
3658 Diag(D.getIdentifierLoc(), diag::err_member_with_template_arguments)
3659 << II
3663 D.SetIdentifier(II, Loc);
3664 }
3665
3666 if (SS.isSet() && !SS.isInvalid()) {
3667 // The user provided a superfluous scope specifier inside a class
3668 // definition:
3669 //
3670 // class X {
3671 // int X::member;
3672 // };
3673 if (DeclContext *DC = computeDeclContext(SS, false)) {
3674 TemplateIdAnnotation *TemplateId =
3676 ? D.getName().TemplateId
3677 : nullptr;
3679 TemplateId,
3680 /*IsMemberSpecialization=*/false);
3681 } else {
3682 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3683 << Name << SS.getRange();
3684 }
3685 SS.clear();
3686 }
3687
3688 if (MSPropertyAttr) {
3690 BitWidth, InitStyle, AS, *MSPropertyAttr);
3691 if (!Member)
3692 return nullptr;
3693 isInstField = false;
3694 } else {
3696 BitWidth, InitStyle, AS);
3697 if (!Member)
3698 return nullptr;
3699 }
3700
3701 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3702 } else {
3703 Member = HandleDeclarator(S, D, TemplateParameterLists);
3704 if (!Member)
3705 return nullptr;
3706
3707 // Non-instance-fields can't have a bitfield.
3708 if (BitWidth) {
3709 if (Member->isInvalidDecl()) {
3710 // don't emit another diagnostic.
3712 // C++ 9.6p3: A bit-field shall not be a static member.
3713 // "static member 'A' cannot be a bit-field"
3714 Diag(Loc, diag::err_static_not_bitfield)
3715 << Name << BitWidth->getSourceRange();
3716 } else if (isa<TypedefDecl>(Member)) {
3717 // "typedef member 'x' cannot be a bit-field"
3718 Diag(Loc, diag::err_typedef_not_bitfield)
3719 << Name << BitWidth->getSourceRange();
3720 } else {
3721 // A function typedef ("typedef int f(); f a;").
3722 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3723 Diag(Loc, diag::err_not_integral_type_bitfield)
3724 << Name << cast<ValueDecl>(Member)->getType()
3725 << BitWidth->getSourceRange();
3726 }
3727
3728 BitWidth = nullptr;
3729 Member->setInvalidDecl();
3730 }
3731
3732 NamedDecl *NonTemplateMember = Member;
3733 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3734 NonTemplateMember = FunTmpl->getTemplatedDecl();
3735 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3736 NonTemplateMember = VarTmpl->getTemplatedDecl();
3737
3738 Member->setAccess(AS);
3739
3740 // If we have declared a member function template or static data member
3741 // template, set the access of the templated declaration as well.
3742 if (NonTemplateMember != Member)
3743 NonTemplateMember->setAccess(AS);
3744
3745 // C++ [temp.deduct.guide]p3:
3746 // A deduction guide [...] for a member class template [shall be
3747 // declared] with the same access [as the template].
3748 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3749 auto *TD = DG->getDeducedTemplate();
3750 // Access specifiers are only meaningful if both the template and the
3751 // deduction guide are from the same scope.
3752 if (AS != TD->getAccess() &&
3753 TD->getDeclContext()->getRedeclContext()->Equals(
3754 DG->getDeclContext()->getRedeclContext())) {
3755 Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3756 Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3757 << TD->getAccess();
3758 const AccessSpecDecl *LastAccessSpec = nullptr;
3759 for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3760 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3761 LastAccessSpec = AccessSpec;
3762 }
3763 assert(LastAccessSpec && "differing access with no access specifier");
3764 Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3765 << AS;
3766 }
3767 }
3768 }
3769
3770 if (VS.isOverrideSpecified())
3771 Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc()));
3772 if (VS.isFinalSpecified())
3773 Member->addAttr(FinalAttr::Create(Context, VS.getFinalLoc(),
3775 ? FinalAttr::Keyword_sealed
3776 : FinalAttr::Keyword_final));
3777
3778 if (VS.getLastLocation().isValid()) {
3779 // Update the end location of a method that has a virt-specifiers.
3780 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3781 MD->setRangeEnd(VS.getLastLocation());
3782 }
3783
3785
3786 assert((Name || isInstField) && "No identifier for non-field ?");
3787
3788 if (isInstField) {
3790 FieldCollector->Add(FD);
3791
3792 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation()) &&
3794 // Remember all explicit private FieldDecls that have a name, no side
3795 // effects and are not part of a dependent type declaration.
3796 UnusedPrivateFields.insert(FD);
3797 }
3798 }
3799
3800 return Member;
3801}
3802
3803namespace {
3804 class UninitializedFieldVisitor
3805 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3806 Sema &S;
3807 // List of Decls to generate a warning on. Also remove Decls that become
3808 // initialized.
3809 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3810 // List of base classes of the record. Classes are removed after their
3811 // initializers.
3812 llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3813 // Vector of decls to be removed from the Decl set prior to visiting the
3814 // nodes. These Decls may have been initialized in the prior initializer.
3816 // If non-null, add a note to the warning pointing back to the constructor.
3818 // Variables to hold state when processing an initializer list. When
3819 // InitList is true, special case initialization of FieldDecls matching
3820 // InitListFieldDecl.
3821 bool InitList;
3822 FieldDecl *InitListFieldDecl;
3823 llvm::SmallVector<unsigned, 4> InitFieldIndex;
3824
3825 public:
3827 UninitializedFieldVisitor(Sema &S,
3828 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3829 llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3830 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3831 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3832
3833 // Returns true if the use of ME is not an uninitialized use.
3834 bool IsInitListMemberExprInitialized(MemberExpr *ME,
3835 bool CheckReferenceOnly) {
3837 bool ReferenceField = false;
3838 while (ME) {
3839 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3840 if (!FD)
3841 return false;
3842 Fields.push_back(FD);
3843 if (FD->getType()->isReferenceType())
3844 ReferenceField = true;
3845 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3846 }
3847
3848 // Binding a reference to an uninitialized field is not an
3849 // uninitialized use.
3850 if (CheckReferenceOnly && !ReferenceField)
3851 return true;
3852
3853 // Discard the first field since it is the field decl that is being
3854 // initialized.
3855 auto UsedFields = llvm::drop_begin(llvm::reverse(Fields));
3856 auto UsedIter = UsedFields.begin();
3857 const auto UsedEnd = UsedFields.end();
3858
3859 for (const unsigned Orig : InitFieldIndex) {
3860 if (UsedIter == UsedEnd)
3861 break;
3862 const unsigned UsedIndex = (*UsedIter)->getFieldIndex();
3863 if (UsedIndex < Orig)
3864 return true;
3865 if (UsedIndex > Orig)
3866 break;
3867 ++UsedIter;
3868 }
3869
3870 return false;
3871 }
3872
3873 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3874 bool AddressOf) {
3876 return;
3877
3878 // FieldME is the inner-most MemberExpr that is not an anonymous struct
3879 // or union.
3880 MemberExpr *FieldME = ME;
3881
3882 bool AllPODFields = FieldME->getType().isPODType(S.Context);
3883
3884 Expr *Base = ME;
3885 while (MemberExpr *SubME =
3886 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3887
3888 if (isa<VarDecl>(SubME->getMemberDecl()))
3889 return;
3890
3891 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3892 if (!FD->isAnonymousStructOrUnion())
3893 FieldME = SubME;
3894
3895 if (!FieldME->getType().isPODType(S.Context))
3896 AllPODFields = false;
3897
3898 Base = SubME->getBase();
3899 }
3900
3901 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) {
3902 Visit(Base);
3903 return;
3904 }
3905
3906 if (AddressOf && AllPODFields)
3907 return;
3908
3909 ValueDecl* FoundVD = FieldME->getMemberDecl();
3910
3911 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3912 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3913 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3914 }
3915
3916 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3917 QualType T = BaseCast->getType();
3918 if (T->isPointerType() &&
3919 BaseClasses.count(T->getPointeeType())) {
3920 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3921 << T->getPointeeType() << FoundVD;
3922 }
3923 }
3924 }
3925
3926 if (!Decls.count(FoundVD))
3927 return;
3928
3929 const bool IsReference = FoundVD->getType()->isReferenceType();
3930
3931 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3932 // Special checking for initializer lists.
3933 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3934 return;
3935 }
3936 } else {
3937 // Prevent double warnings on use of unbounded references.
3938 if (CheckReferenceOnly && !IsReference)
3939 return;
3940 }
3941
3942 unsigned diag = IsReference
3943 ? diag::warn_reference_field_is_uninit
3944 : diag::warn_field_is_uninit;
3945 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3946 if (Constructor)
3947 S.Diag(Constructor->getLocation(),
3948 diag::note_uninit_in_this_constructor)
3949 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3950
3951 }
3952
3953 void HandleValue(Expr *E, bool AddressOf) {
3954 E = E->IgnoreParens();
3955
3956 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3957 HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3958 AddressOf /*AddressOf*/);
3959 return;
3960 }
3961
3962 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3963 Visit(CO->getCond());
3964 HandleValue(CO->getTrueExpr(), AddressOf);
3965 HandleValue(CO->getFalseExpr(), AddressOf);
3966 return;
3967 }
3968
3969 if (BinaryConditionalOperator *BCO =
3970 dyn_cast<BinaryConditionalOperator>(E)) {
3971 Visit(BCO->getCond());
3972 HandleValue(BCO->getFalseExpr(), AddressOf);
3973 return;
3974 }
3975
3976 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3977 HandleValue(OVE->getSourceExpr(), AddressOf);
3978 return;
3979 }
3980
3981 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3982 switch (BO->getOpcode()) {
3983 default:
3984 break;
3985 case(BO_PtrMemD):
3986 case(BO_PtrMemI):
3987 HandleValue(BO->getLHS(), AddressOf);
3988 Visit(BO->getRHS());
3989 return;
3990 case(BO_Comma):
3991 Visit(BO->getLHS());
3992 HandleValue(BO->getRHS(), AddressOf);
3993 return;
3994 }
3995 }
3996
3997 Visit(E);
3998 }
3999
4000 void CheckInitListExpr(InitListExpr *ILE) {
4001 InitFieldIndex.push_back(0);
4002 for (auto *Child : ILE->children()) {
4003 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
4004 CheckInitListExpr(SubList);
4005 } else {
4006 Visit(Child);
4007 }
4008 ++InitFieldIndex.back();
4009 }
4010 InitFieldIndex.pop_back();
4011 }
4012
4013 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
4014 FieldDecl *Field, const Type *BaseClass) {
4015 // Remove Decls that may have been initialized in the previous
4016 // initializer.
4017 for (ValueDecl* VD : DeclsToRemove)
4018 Decls.erase(VD);
4019 DeclsToRemove.clear();
4020
4021 Constructor = FieldConstructor;
4022 InitListExpr *ILE = dyn_cast<InitListExpr>(E);
4023
4024 if (ILE && Field) {
4025 InitList = true;
4026 InitListFieldDecl = Field;
4027 InitFieldIndex.clear();
4028 CheckInitListExpr(ILE);
4029 } else {
4030 InitList = false;
4031 Visit(E);
4032 }
4033
4034 if (Field)
4035 Decls.erase(Field);
4036 if (BaseClass)
4037 BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
4038 }
4039
4040 void VisitMemberExpr(MemberExpr *ME) {
4041 // All uses of unbounded reference fields will warn.
4042 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
4043 }
4044
4045 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
4046 if (E->getCastKind() == CK_LValueToRValue) {
4047 HandleValue(E->getSubExpr(), false /*AddressOf*/);
4048 return;
4049 }
4050
4051 Inherited::VisitImplicitCastExpr(E);
4052 }
4053
4054 void VisitCXXConstructExpr(CXXConstructExpr *E) {
4055 if (E->getConstructor()->isCopyConstructor()) {
4056 Expr *ArgExpr = E->getArg(0);
4057 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
4058 if (ILE->getNumInits() == 1)
4059 ArgExpr = ILE->getInit(0);
4060 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
4061 if (ICE->getCastKind() == CK_NoOp)
4062 ArgExpr = ICE->getSubExpr();
4063 HandleValue(ArgExpr, false /*AddressOf*/);
4064 return;
4065 }
4066 Inherited::VisitCXXConstructExpr(E);
4067 }
4068
4069 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
4070 Expr *Callee = E->getCallee();
4071 if (isa<MemberExpr>(Callee)) {
4072 HandleValue(Callee, false /*AddressOf*/);
4073 for (auto *Arg : E->arguments())
4074 Visit(Arg);
4075 return;
4076 }
4077
4078 Inherited::VisitCXXMemberCallExpr(E);
4079 }
4080
4081 void VisitCallExpr(CallExpr *E) {
4082 // Treat std::move as a use.
4083 if (E->isCallToStdMove()) {
4084 HandleValue(E->getArg(0), /*AddressOf=*/false);
4085 return;
4086 }
4087
4088 Inherited::VisitCallExpr(E);
4089 }
4090
4091 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
4092 Expr *Callee = E->getCallee();
4093
4094 if (isa<UnresolvedLookupExpr>(Callee))
4095 return Inherited::VisitCXXOperatorCallExpr(E);
4096
4097 Visit(Callee);
4098 for (auto *Arg : E->arguments())
4099 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
4100 }
4101
4102 void VisitBinaryOperator(BinaryOperator *E) {
4103 // If a field assignment is detected, remove the field from the
4104 // uninitiailized field set.
4105 if (E->getOpcode() == BO_Assign)
4106 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
4107 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
4108 if (!FD->getType()->isReferenceType())
4109 DeclsToRemove.push_back(FD);
4110
4111 if (E->isCompoundAssignmentOp()) {
4112 HandleValue(E->getLHS(), false /*AddressOf*/);
4113 Visit(E->getRHS());
4114 return;
4115 }
4116
4117 Inherited::VisitBinaryOperator(E);
4118 }
4119
4120 void VisitUnaryOperator(UnaryOperator *E) {
4121 if (E->isIncrementDecrementOp()) {
4122 HandleValue(E->getSubExpr(), false /*AddressOf*/);
4123 return;
4124 }
4125 if (E->getOpcode() == UO_AddrOf) {
4126 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
4127 HandleValue(ME->getBase(), true /*AddressOf*/);
4128 return;
4129 }
4130 }
4131
4132 Inherited::VisitUnaryOperator(E);
4133 }
4134 };
4135
4136 // Diagnose value-uses of fields to initialize themselves, e.g.
4137 // foo(foo)
4138 // where foo is not also a parameter to the constructor.
4139 // Also diagnose across field uninitialized use such as
4140 // x(y), y(x)
4141 // TODO: implement -Wuninitialized and fold this into that framework.
4142 static void DiagnoseUninitializedFields(
4143 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
4144
4145 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
4146 Constructor->getLocation())) {
4147 return;
4148 }
4149
4150 if (Constructor->isInvalidDecl())
4151 return;
4152
4153 const CXXRecordDecl *RD = Constructor->getParent();
4154
4155 if (RD->isDependentContext())
4156 return;
4157
4158 // Holds fields that are uninitialized.
4159 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
4160
4161 // At the beginning, all fields are uninitialized.
4162 for (auto *I : RD->decls()) {
4163 if (auto *FD = dyn_cast<FieldDecl>(I)) {
4164 UninitializedFields.insert(FD);
4165 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
4166 UninitializedFields.insert(IFD->getAnonField());
4167 }
4168 }
4169
4170 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
4171 for (const auto &I : RD->bases()) {
4172 // Virtual bases are initialized from the most derived class, so an
4173 // abstract base class constructor can assume it to be initialized.
4174 if (I.isVirtual() && RD->isAbstract())
4175 continue;
4176 UninitializedBaseClasses.insert(I.getType().getCanonicalType());
4177 }
4178
4179 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
4180 return;
4181
4182 UninitializedFieldVisitor UninitializedChecker(SemaRef,
4183 UninitializedFields,
4184 UninitializedBaseClasses);
4185
4186 for (const auto *FieldInit : Constructor->inits()) {
4187 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
4188 break;
4189
4190 Expr *InitExpr = FieldInit->getInit();
4191 if (!InitExpr)
4192 continue;
4193
4194 if (CXXDefaultInitExpr *Default =
4195 dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
4196 InitExpr = Default->getExpr();
4197 if (!InitExpr)
4198 continue;
4199 // In class initializers will point to the constructor.
4200 UninitializedChecker.CheckInitializer(InitExpr, Constructor,
4201 FieldInit->getAnyMember(),
4202 FieldInit->getBaseClass());
4203 } else {
4204 UninitializedChecker.CheckInitializer(InitExpr, nullptr,
4205 FieldInit->getAnyMember(),
4206 FieldInit->getBaseClass());
4207 }
4208 }
4209 }
4210} // namespace
4211
4213 // Create a synthetic function scope to represent the call to the constructor
4214 // that notionally surrounds a use of this initializer.
4216}
4217
4219 if (!D.isFunctionDeclarator())
4220 return;
4221 auto &FTI = D.getFunctionTypeInfo();
4222 if (!FTI.Params)
4223 return;
4224 for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params,
4225 FTI.NumParams)) {
4226 auto *ParamDecl = cast<NamedDecl>(Param.Param);
4227 if (ParamDecl->getDeclName())
4228 PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false);
4229 }
4230}
4231
4233 return ActOnRequiresClause(ConstraintExpr);
4234}
4235
4237 if (ConstraintExpr.isInvalid())
4238 return ExprError();
4239
4240 if (DiagnoseUnexpandedParameterPack(ConstraintExpr.get(),
4242 return ExprError();
4243
4244 return ConstraintExpr;
4245}
4246
4254
4256 FieldDecl *FD, const InitializedEntity &Entity, Expr *InitExpr,
4257 SourceLocation InitLoc) {
4258 InitializationKind Kind =
4261 InitExpr->getBeginLoc(),
4262 InitExpr->getEndLoc())
4263 : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
4264 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
4265 return Seq.Perform(*this, Entity, Kind, InitExpr);
4266}
4267
4269 SourceLocation InitLoc,
4270 ExprResult InitExpr) {
4271 // Pop the notional constructor scope we created earlier.
4272 PopFunctionScopeInfo(nullptr, D);
4273
4274 // Microsoft C++'s property declaration cannot have a default member
4275 // initializer.
4276 if (isa<MSPropertyDecl>(D)) {
4277 D->setInvalidDecl();
4278 return;
4279 }
4280
4281 FieldDecl *FD = dyn_cast<FieldDecl>(D);
4282 assert((FD && FD->getInClassInitStyle() != ICIS_NoInit) &&
4283 "must set init style when field is created");
4284
4285 if (!InitExpr.isUsable() ||
4287 FD->setInvalidDecl();
4288 ExprResult RecoveryInit =
4289 CreateRecoveryExpr(InitLoc, InitLoc, {}, FD->getType());
4290 if (RecoveryInit.isUsable())
4291 FD->setInClassInitializer(RecoveryInit.get());
4292 return;
4293 }
4294
4295 if (!FD->getType()->isDependentType() && !InitExpr.get()->isTypeDependent()) {
4296 InitExpr = ConvertMemberDefaultInitExpression(FD, InitExpr.get(), InitLoc);
4297 // C++11 [class.base.init]p7:
4298 // The initialization of each base and member constitutes a
4299 // full-expression.
4300 if (!InitExpr.isInvalid())
4301 InitExpr = ActOnFinishFullExpr(InitExpr.get(), /*DiscarededValue=*/false);
4302 if (InitExpr.isInvalid()) {
4303 FD->setInvalidDecl();
4304 return;
4305 }
4306 }
4307
4308 FD->setInClassInitializer(InitExpr.get());
4309}
4310
4311/// Find the direct and/or virtual base specifiers that
4312/// correspond to the given base type, for use in base initialization
4313/// within a constructor.
4314static bool FindBaseInitializer(Sema &SemaRef,
4315 CXXRecordDecl *ClassDecl,
4316 QualType BaseType,
4317 const CXXBaseSpecifier *&DirectBaseSpec,
4318 const CXXBaseSpecifier *&VirtualBaseSpec) {
4319 // First, check for a direct base class.
4320 DirectBaseSpec = nullptr;
4321 for (const auto &Base : ClassDecl->bases()) {
4322 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
4323 // We found a direct base of this type. That's what we're
4324 // initializing.
4325 DirectBaseSpec = &Base;
4326 break;
4327 }
4328 }
4329
4330 // Check for a virtual base class.
4331 // FIXME: We might be able to short-circuit this if we know in advance that
4332 // there are no virtual bases.
4333 VirtualBaseSpec = nullptr;
4334 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
4335 // We haven't found a base yet; search the class hierarchy for a
4336 // virtual base class.
4337 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
4338 /*DetectVirtual=*/false);
4339 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
4340 SemaRef.Context.getCanonicalTagType(ClassDecl),
4341 BaseType, Paths)) {
4342 for (const CXXBasePath &Path : Paths) {
4343 if (Path.back().Base->isVirtual()) {
4344 VirtualBaseSpec = Path.back().Base;
4345 break;
4346 }
4347 }
4348 }
4349 }
4350
4351 return DirectBaseSpec || VirtualBaseSpec;
4352}
4353
4356 Scope *S,
4357 CXXScopeSpec &SS,
4358 IdentifierInfo *MemberOrBase,
4359 ParsedType TemplateTypeTy,
4360 const DeclSpec &DS,
4361 SourceLocation IdLoc,
4362 Expr *InitList,
4363 SourceLocation EllipsisLoc) {
4364 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4365 DS, IdLoc, InitList,
4366 EllipsisLoc);
4367}
4368
4371 Scope *S,
4372 CXXScopeSpec &SS,
4373 IdentifierInfo *MemberOrBase,
4374 ParsedType TemplateTypeTy,
4375 const DeclSpec &DS,
4376 SourceLocation IdLoc,
4377 SourceLocation LParenLoc,
4378 ArrayRef<Expr *> Args,
4379 SourceLocation RParenLoc,
4380 SourceLocation EllipsisLoc) {
4381 Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
4382 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4383 DS, IdLoc, List, EllipsisLoc);
4384}
4385
4386namespace {
4387
4388// Callback to only accept typo corrections that can be a valid C++ member
4389// initializer: either a non-static field member or a base class.
4390class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
4391public:
4392 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
4393 : ClassDecl(ClassDecl) {}
4394
4395 bool ValidateCandidate(const TypoCorrection &candidate) override {
4396 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
4397 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
4398 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
4399 return isa<TypeDecl>(ND);
4400 }
4401 return false;
4402 }
4403
4404 std::unique_ptr<CorrectionCandidateCallback> clone() override {
4405 return std::make_unique<MemInitializerValidatorCCC>(*this);
4406 }
4407
4408private:
4409 CXXRecordDecl *ClassDecl;
4410};
4411
4412}
4413
4415 RecordDecl *ClassDecl,
4416 const IdentifierInfo *Name) {
4417 DeclContextLookupResult Result = ClassDecl->lookup(Name);
4419 llvm::find_if(Result, [this](const NamedDecl *Elem) {
4420 return isa<FieldDecl, IndirectFieldDecl>(Elem) &&
4422 });
4423 // We did not find a placeholder variable
4424 if (Found == Result.end())
4425 return false;
4426 Diag(Loc, diag::err_using_placeholder_variable) << Name;
4427 for (DeclContextLookupResult::iterator It = Found; It != Result.end(); It++) {
4428 const NamedDecl *ND = *It;
4429 if (ND->getDeclContext() != ND->getDeclContext())
4430 break;
4433 Diag(ND->getLocation(), diag::note_reference_placeholder) << ND;
4434 }
4435 return true;
4436}
4437
4438ValueDecl *
4440 const IdentifierInfo *MemberOrBase) {
4441 ValueDecl *ND = nullptr;
4442 for (auto *D : ClassDecl->lookup(MemberOrBase)) {
4444 bool IsPlaceholder = D->isPlaceholderVar(getLangOpts());
4445 if (ND) {
4446 if (IsPlaceholder && D->getDeclContext() == ND->getDeclContext())
4447 return nullptr;
4448 break;
4449 }
4450 if (!IsPlaceholder)
4451 return cast<ValueDecl>(D);
4452 ND = cast<ValueDecl>(D);
4453 }
4454 }
4455 return ND;
4456}
4457
4459 CXXScopeSpec &SS,
4460 ParsedType TemplateTypeTy,
4461 IdentifierInfo *MemberOrBase) {
4462 if (SS.getScopeRep() || TemplateTypeTy)
4463 return nullptr;
4464 return tryLookupUnambiguousFieldDecl(ClassDecl, MemberOrBase);
4465}
4466
4469 Scope *S,
4470 CXXScopeSpec &SS,
4471 IdentifierInfo *MemberOrBase,
4472 ParsedType TemplateTypeTy,
4473 const DeclSpec &DS,
4474 SourceLocation IdLoc,
4475 Expr *Init,
4476 SourceLocation EllipsisLoc) {
4477 if (!ConstructorD || !Init)
4478 return true;
4479
4480 AdjustDeclIfTemplate(ConstructorD);
4481
4483 = dyn_cast<CXXConstructorDecl>(ConstructorD);
4484 if (!Constructor) {
4485 // The user wrote a constructor initializer on a function that is
4486 // not a C++ constructor. Ignore the error for now, because we may
4487 // have more member initializers coming; we'll diagnose it just
4488 // once in ActOnMemInitializers.
4489 return true;
4490 }
4491
4492 CXXRecordDecl *ClassDecl = Constructor->getParent();
4493
4494 // C++ [class.base.init]p2:
4495 // Names in a mem-initializer-id are looked up in the scope of the
4496 // constructor's class and, if not found in that scope, are looked
4497 // up in the scope containing the constructor's definition.
4498 // [Note: if the constructor's class contains a member with the
4499 // same name as a direct or virtual base class of the class, a
4500 // mem-initializer-id naming the member or base class and composed
4501 // of a single identifier refers to the class member. A
4502 // mem-initializer-id for the hidden base class may be specified
4503 // using a qualified name. ]
4504
4505 // Look for a member, first.
4507 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
4508 if (EllipsisLoc.isValid())
4509 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
4510 << MemberOrBase
4511 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4512
4513 return BuildMemberInitializer(Member, Init, IdLoc);
4514 }
4515 // It didn't name a member, so see if it names a class.
4516 QualType BaseType;
4517 TypeSourceInfo *TInfo = nullptr;
4518
4519 if (TemplateTypeTy) {
4520 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
4521 if (BaseType.isNull())
4522 return true;
4523 } else if (DS.getTypeSpecType() == TST_decltype) {
4524 BaseType = BuildDecltypeType(DS.getRepAsExpr());
4525 } else if (DS.getTypeSpecType() == TST_decltype_auto) {
4526 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
4527 return true;
4528 } else if (DS.getTypeSpecType() == TST_typename_pack_indexing) {
4529 BaseType = GetTypeFromParser(DS.getRepAsType(), &TInfo);
4530 if (BaseType.isNull())
4531 return true;
4532 } else {
4533 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
4534 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
4535
4536 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
4537 if (!TyD) {
4538 if (R.isAmbiguous()) return true;
4539
4540 // We don't want access-control diagnostics here.
4541 R.suppressDiagnostics();
4542
4543 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
4544 bool NotUnknownSpecialization = false;
4545 DeclContext *DC = computeDeclContext(SS, false);
4546 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
4547 NotUnknownSpecialization = !Record->hasAnyDependentBases();
4548
4549 if (!NotUnknownSpecialization) {
4550 // When the scope specifier can refer to a member of an unknown
4551 // specialization, we take it as a type name.
4552 BaseType = CheckTypenameType(
4554 SS.getWithLocInContext(Context), *MemberOrBase, IdLoc);
4555 if (BaseType.isNull())
4556 return true;
4557
4558 TInfo = Context.CreateTypeSourceInfo(BaseType);
4561 if (!TL.isNull()) {
4562 TL.setNameLoc(IdLoc);
4565 }
4566
4567 R.clear();
4568 R.setLookupName(MemberOrBase);
4569 }
4570 }
4571
4572 if (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus20) {
4573 if (auto UnqualifiedBase = R.getAsSingle<ClassTemplateDecl>()) {
4574 auto *TempSpec = cast<TemplateSpecializationType>(
4575 UnqualifiedBase->getCanonicalInjectedSpecializationType(Context));
4576 TemplateName TN = TempSpec->getTemplateName();
4577 for (auto const &Base : ClassDecl->bases()) {
4578 auto BaseTemplate =
4579 Base.getType()->getAs<TemplateSpecializationType>();
4580 if (BaseTemplate &&
4581 Context.hasSameTemplateName(BaseTemplate->getTemplateName(), TN,
4582 /*IgnoreDeduced=*/true)) {
4583 Diag(IdLoc, diag::ext_unqualified_base_class)
4584 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4585 BaseType = Base.getType();
4586 break;
4587 }
4588 }
4589 }
4590 }
4591
4592 // If no results were found, try to correct typos.
4593 TypoCorrection Corr;
4594 MemInitializerValidatorCCC CCC(ClassDecl);
4595 if (R.empty() && BaseType.isNull() &&
4596 (Corr =
4597 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
4598 CCC, CorrectTypoKind::ErrorRecovery, ClassDecl))) {
4600 // We have found a non-static data member with a similar
4601 // name to what was typed; complain and initialize that
4602 // member.
4603 diagnoseTypo(Corr,
4604 PDiag(diag::err_mem_init_not_member_or_class_suggest)
4605 << MemberOrBase << true);
4606 return BuildMemberInitializer(Member, Init, IdLoc);
4607 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
4608 const CXXBaseSpecifier *DirectBaseSpec;
4609 const CXXBaseSpecifier *VirtualBaseSpec;
4610 if (FindBaseInitializer(*this, ClassDecl,
4611 Context.getTypeDeclType(Type),
4612 DirectBaseSpec, VirtualBaseSpec)) {
4613 // We have found a direct or virtual base class with a
4614 // similar name to what was typed; complain and initialize
4615 // that base class.
4616 diagnoseTypo(Corr,
4617 PDiag(diag::err_mem_init_not_member_or_class_suggest)
4618 << MemberOrBase << false,
4619 PDiag() /*Suppress note, we provide our own.*/);
4620
4621 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
4622 : VirtualBaseSpec;
4623 Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
4624 << BaseSpec->getType() << BaseSpec->getSourceRange();
4625
4626 TyD = Type;
4627 }
4628 }
4629 }
4630
4631 if (!TyD && BaseType.isNull()) {
4632 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
4633 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4634 return true;
4635 }
4636 }
4637
4638 if (BaseType.isNull()) {
4639 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
4640
4641 TypeLocBuilder TLB;
4642 // FIXME: This is missing building the UsingType for TyD, if any.
4643 if (const auto *TD = dyn_cast<TagDecl>(TyD)) {
4644 BaseType = Context.getTagType(ElaboratedTypeKeyword::None,
4645 SS.getScopeRep(), TD, /*OwnsTag=*/false);
4646 auto TL = TLB.push<TagTypeLoc>(BaseType);
4648 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4649 TL.setNameLoc(IdLoc);
4650 } else if (auto *TN = dyn_cast<TypedefNameDecl>(TyD)) {
4651 BaseType = Context.getTypedefType(ElaboratedTypeKeyword::None,
4652 SS.getScopeRep(), TN);
4653 TLB.push<TypedefTypeLoc>(BaseType).set(
4654 /*ElaboratedKeywordLoc=*/SourceLocation(),
4655 SS.getWithLocInContext(Context), IdLoc);
4656 } else if (auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(TyD)) {
4657 BaseType = Context.getUnresolvedUsingType(ElaboratedTypeKeyword::None,
4658 SS.getScopeRep(), UD);
4659 TLB.push<UnresolvedUsingTypeLoc>(BaseType).set(
4660 /*ElaboratedKeywordLoc=*/SourceLocation(),
4661 SS.getWithLocInContext(Context), IdLoc);
4662 } else {
4663 // FIXME: What else can appear here?
4664 assert(SS.isEmpty());
4665 BaseType = Context.getTypeDeclType(TyD);
4666 TLB.pushTypeSpec(BaseType).setNameLoc(IdLoc);
4667 }
4668 TInfo = TLB.getTypeSourceInfo(Context, BaseType);
4669 }
4670 }
4671
4672 if (!TInfo)
4673 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
4674
4675 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
4676}
4677
4680 SourceLocation IdLoc) {
4681 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
4682 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
4683 assert((DirectMember || IndirectMember) &&
4684 "Member must be a FieldDecl or IndirectFieldDecl");
4685
4687 return true;
4688
4689 if (Member->isInvalidDecl())
4690 return true;
4691
4692 MultiExprArg Args;
4693 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4694 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4695 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4696 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4697 } else if (auto *ParenListInit = dyn_cast<CXXParenListInitExpr>(Init)) {
4698 // Template instantiation reverts the elements to their syntactic form;
4699 // redo the initialization from the written arguments.
4700 Args = ParenListInit->getUserSpecifiedInitExprs();
4701 } else {
4702 // Template instantiation doesn't reconstruct ParenListExprs for us.
4703 Args = Init;
4704 }
4705
4706 SourceRange InitRange = Init->getSourceRange();
4707
4708 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4709 // Can't check initialization for a member of dependent type or when
4710 // any of the arguments are type-dependent expressions.
4712 } else {
4713 bool InitList = false;
4714 if (isa<InitListExpr>(Init)) {
4715 InitList = true;
4716 Args = Init;
4717 }
4718
4719 // Initialize the member.
4720 InitializedEntity MemberEntity =
4721 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4722 : InitializedEntity::InitializeMember(IndirectMember,
4723 nullptr);
4724 InitializationKind Kind =
4726 IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4727 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4728 InitRange.getEnd());
4729
4730 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4731 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4732 nullptr);
4733 if (!MemberInit.isInvalid()) {
4734 // C++11 [class.base.init]p7:
4735 // The initialization of each base and member constitutes a
4736 // full-expression.
4737 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
4738 /*DiscardedValue*/ false);
4739 }
4740
4741 if (MemberInit.isInvalid()) {
4742 // Args were sensible expressions but we couldn't initialize the member
4743 // from them. Preserve them in a RecoveryExpr instead.
4744 Init = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,
4745 Member->getType())
4746 .get();
4747 if (!Init)
4748 return true;
4749 } else {
4750 Init = MemberInit.get();
4751 }
4752 }
4753
4754 if (DirectMember) {
4755 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4756 InitRange.getBegin(), Init,
4757 InitRange.getEnd());
4758 } else {
4759 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4760 InitRange.getBegin(), Init,
4761 InitRange.getEnd());
4762 }
4763}
4764
4767 CXXRecordDecl *ClassDecl) {
4768 SourceLocation NameLoc = TInfo->getTypeLoc().getSourceRange().getBegin();
4769 if (!LangOpts.CPlusPlus11)
4770 return Diag(NameLoc, diag::err_delegating_ctor)
4771 << TInfo->getTypeLoc().getSourceRange();
4772 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4773
4774 bool InitList = true;
4775 MultiExprArg Args = Init;
4776 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4777 InitList = false;
4778 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4779 }
4780
4781 CanQualType ClassType = Context.getCanonicalTagType(ClassDecl);
4782
4783 SourceRange InitRange = Init->getSourceRange();
4784 // Initialize the object.
4785 InitializedEntity DelegationEntity =
4787 InitializationKind Kind =
4789 NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4790 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4791 InitRange.getEnd());
4792 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4793 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4794 Args, nullptr);
4795 if (!DelegationInit.isInvalid()) {
4796 assert((DelegationInit.get()->containsErrors() ||
4797 cast<CXXConstructExpr>(DelegationInit.get())->getConstructor()) &&
4798 "Delegating constructor with no target?");
4799
4800 // C++11 [class.base.init]p7:
4801 // The initialization of each base and member constitutes a
4802 // full-expression.
4803 DelegationInit = ActOnFinishFullExpr(
4804 DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
4805 }
4806
4807 if (DelegationInit.isInvalid()) {
4808 DelegationInit = CreateRecoveryExpr(InitRange.getBegin(),
4809 InitRange.getEnd(), Args, ClassType);
4810 if (DelegationInit.isInvalid())
4811 return true;
4812 } else {
4813 // If we are in a dependent context, template instantiation will
4814 // perform this type-checking again. Just save the arguments that we
4815 // received in a ParenListExpr.
4816 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4817 // of the information that we have about the base
4818 // initializer. However, deconstructing the ASTs is a dicey process,
4819 // and this approach is far more likely to get the corner cases right.
4820 if (CurContext->isDependentContext())
4821 DelegationInit = Init;
4822 }
4823
4824 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4825 DelegationInit.getAs<Expr>(),
4826 InitRange.getEnd());
4827}
4828
4831 Expr *Init, CXXRecordDecl *ClassDecl,
4832 SourceLocation EllipsisLoc) {
4833 SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getBeginLoc();
4834
4835 if (!BaseType->isDependentType() && !BaseType->isRecordType())
4836 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4837 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
4838
4839 // C++ [class.base.init]p2:
4840 // [...] Unless the mem-initializer-id names a nonstatic data
4841 // member of the constructor's class or a direct or virtual base
4842 // of that class, the mem-initializer is ill-formed. A
4843 // mem-initializer-list can initialize a base class using any
4844 // name that denotes that base class type.
4845
4846 // We can store the initializers in "as-written" form and delay analysis until
4847 // instantiation if the constructor is dependent. But not for dependent
4848 // (broken) code in a non-template! SetCtorInitializers does not expect this.
4849 bool Dependent = CurContext->isDependentContext() &&
4850 (BaseType->isDependentType() || Init->isTypeDependent());
4851
4852 SourceRange InitRange = Init->getSourceRange();
4853 if (EllipsisLoc.isValid()) {
4854 // This is a pack expansion.
4855 if (!BaseType->containsUnexpandedParameterPack()) {
4856 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4857 << SourceRange(BaseLoc, InitRange.getEnd());
4858
4859 EllipsisLoc = SourceLocation();
4860 }
4861 } else {
4862 // Check for any unexpanded parameter packs.
4863 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4864 return true;
4865
4867 return true;
4868 }
4869
4870 // Check for direct and virtual base classes.
4871 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4872 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4873 if (!Dependent) {
4874 if (declaresSameEntity(ClassDecl, BaseType->getAsCXXRecordDecl()))
4875 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4876
4877 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4878 VirtualBaseSpec);
4879
4880 // C++ [base.class.init]p2:
4881 // Unless the mem-initializer-id names a nonstatic data member of the
4882 // constructor's class or a direct or virtual base of that class, the
4883 // mem-initializer is ill-formed.
4884 if (!DirectBaseSpec && !VirtualBaseSpec) {
4885 // If the class has any dependent bases, then it's possible that
4886 // one of those types will resolve to the same type as
4887 // BaseType. Therefore, just treat this as a dependent base
4888 // class initialization. FIXME: Should we try to check the
4889 // initialization anyway? It seems odd.
4890 if (ClassDecl->hasAnyDependentBases())
4891 Dependent = true;
4892 else
4893 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4894 << BaseType << Context.getCanonicalTagType(ClassDecl)
4895 << BaseTInfo->getTypeLoc().getSourceRange();
4896 }
4897 }
4898
4899 if (Dependent) {
4901
4902 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4903 /*IsVirtual=*/false,
4904 InitRange.getBegin(), Init,
4905 InitRange.getEnd(), EllipsisLoc);
4906 }
4907
4908 // C++ [base.class.init]p2:
4909 // If a mem-initializer-id is ambiguous because it designates both
4910 // a direct non-virtual base class and an inherited virtual base
4911 // class, the mem-initializer is ill-formed.
4912 if (DirectBaseSpec && VirtualBaseSpec)
4913 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4914 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4915
4916 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4917 if (!BaseSpec)
4918 BaseSpec = VirtualBaseSpec;
4919
4920 // Initialize the base.
4921 bool InitList = true;
4922 MultiExprArg Args = Init;
4923 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4924 InitList = false;
4925 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4926 }
4927
4928 InitializedEntity BaseEntity =
4929 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4930 InitializationKind Kind =
4931 InitList ? InitializationKind::CreateDirectList(BaseLoc)
4932 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4933 InitRange.getEnd());
4934 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4935 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4936 if (!BaseInit.isInvalid()) {
4937 // C++11 [class.base.init]p7:
4938 // The initialization of each base and member constitutes a
4939 // full-expression.
4940 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
4941 /*DiscardedValue*/ false);
4942 }
4943
4944 if (BaseInit.isInvalid()) {
4945 BaseInit = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(),
4946 Args, BaseType);
4947 if (BaseInit.isInvalid())
4948 return true;
4949 } else {
4950 // If we are in a dependent context, template instantiation will
4951 // perform this type-checking again. Just save the arguments that we
4952 // received in a ParenListExpr.
4953 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4954 // of the information that we have about the base
4955 // initializer. However, deconstructing the ASTs is a dicey process,
4956 // and this approach is far more likely to get the corner cases right.
4957 if (CurContext->isDependentContext())
4958 BaseInit = Init;
4959 }
4960
4961 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4962 BaseSpec->isVirtual(),
4963 InitRange.getBegin(),
4964 BaseInit.getAs<Expr>(),
4965 InitRange.getEnd(), EllipsisLoc);
4966}
4967
4968// Create a static_cast<T&&>(expr).
4969static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
4970 QualType TargetType =
4971 SemaRef.BuildReferenceType(E->getType(), /*SpelledAsLValue*/ false,
4973 SourceLocation ExprLoc = E->getBeginLoc();
4974 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4975 TargetType, ExprLoc);
4976
4977 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4978 SourceRange(ExprLoc, ExprLoc),
4979 E->getSourceRange()).get();
4980}
4981
4982/// ImplicitInitializerKind - How an implicit base or member initializer should
4983/// initialize its base or member.
4990
4991static bool
4993 ImplicitInitializerKind ImplicitInitKind,
4994 CXXBaseSpecifier *BaseSpec,
4995 bool IsInheritedVirtualBase,
4996 CXXCtorInitializer *&CXXBaseInit) {
4997 InitializedEntity InitEntity
4998 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4999 IsInheritedVirtualBase);
5000
5001 ExprResult BaseInit;
5002
5003 switch (ImplicitInitKind) {
5004 case IIK_Inherit:
5005 case IIK_Default: {
5006 InitializationKind InitKind
5008 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, {});
5009 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, {});
5010 break;
5011 }
5012
5013 case IIK_Move:
5014 case IIK_Copy: {
5015 bool Moving = ImplicitInitKind == IIK_Move;
5016 ParmVarDecl *Param = Constructor->getParamDecl(0);
5017 QualType ParamType = Param->getType().getNonReferenceType();
5018
5019 Expr *CopyCtorArg =
5021 SourceLocation(), Param, false,
5022 Constructor->getLocation(), ParamType,
5023 VK_LValue, nullptr);
5024
5025 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
5026
5027 // Cast to the base class to avoid ambiguities.
5028 QualType ArgTy =
5029 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
5030 ParamType.getQualifiers());
5031
5032 if (Moving) {
5033 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
5034 }
5035
5036 CXXCastPath BasePath;
5037 BasePath.push_back(BaseSpec);
5038 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
5039 CK_UncheckedDerivedToBase,
5040 Moving ? VK_XValue : VK_LValue,
5041 &BasePath).get();
5042
5043 InitializationKind InitKind
5046 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
5047 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
5048 break;
5049 }
5050 }
5051
5052 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
5053 if (BaseInit.isInvalid())
5054 return true;
5055
5056 CXXBaseInit =
5057 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5058 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
5059 SourceLocation()),
5060 BaseSpec->isVirtual(),
5062 BaseInit.getAs<Expr>(),
5064 SourceLocation());
5065
5066 return false;
5067}
5068
5069static bool RefersToRValueRef(Expr *MemRef) {
5070 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
5071 return Referenced->getType()->isRValueReferenceType();
5072}
5073
5074static bool
5076 ImplicitInitializerKind ImplicitInitKind,
5077 FieldDecl *Field, IndirectFieldDecl *Indirect,
5078 CXXCtorInitializer *&CXXMemberInit) {
5079 if (Field->isInvalidDecl())
5080 return true;
5081
5082 SourceLocation Loc = Constructor->getLocation();
5083
5084 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
5085 bool Moving = ImplicitInitKind == IIK_Move;
5086 ParmVarDecl *Param = Constructor->getParamDecl(0);
5087 QualType ParamType = Param->getType().getNonReferenceType();
5088
5089 // Suppress copying zero-width bitfields.
5090 if (Field->isZeroLengthBitField())
5091 return false;
5092
5093 Expr *MemberExprBase =
5095 SourceLocation(), Param, false,
5096 Loc, ParamType, VK_LValue, nullptr);
5097
5098 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
5099
5100 if (Moving) {
5101 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
5102 }
5103
5104 // Build a reference to this field within the parameter.
5105 CXXScopeSpec SS;
5106 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
5108 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
5109 : cast<ValueDecl>(Field), AS_public);
5110 MemberLookup.resolveKind();
5111 ExprResult CtorArg
5112 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
5113 ParamType, Loc,
5114 /*IsArrow=*/false,
5115 SS,
5116 /*TemplateKWLoc=*/SourceLocation(),
5117 /*FirstQualifierInScope=*/nullptr,
5118 MemberLookup,
5119 /*TemplateArgs=*/nullptr,
5120 /*S*/nullptr);
5121 if (CtorArg.isInvalid())
5122 return true;
5123
5124 // C++11 [class.copy]p15:
5125 // - if a member m has rvalue reference type T&&, it is direct-initialized
5126 // with static_cast<T&&>(x.m);
5127 if (RefersToRValueRef(CtorArg.get())) {
5128 CtorArg = CastForMoving(SemaRef, CtorArg.get());
5129 }
5130
5131 InitializedEntity Entity =
5134
5135 // Direct-initialize to use the copy constructor.
5136 InitializationKind InitKind =
5138
5139 Expr *CtorArgE = CtorArg.getAs<Expr>();
5140 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
5141 ExprResult MemberInit =
5142 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
5143 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
5144 if (MemberInit.isInvalid())
5145 return true;
5146
5147 if (Indirect)
5148 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
5149 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
5150 else
5151 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
5152 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
5153 return false;
5154 }
5155
5156 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
5157 "Unhandled implicit init kind!");
5158
5159 QualType FieldBaseElementType =
5160 SemaRef.Context.getBaseElementType(Field->getType());
5161
5162 if (FieldBaseElementType->isRecordType()) {
5163 InitializedEntity InitEntity =
5166 InitializationKind InitKind =
5168
5169 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, {});
5170 ExprResult MemberInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, {});
5171
5172 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
5173 if (MemberInit.isInvalid())
5174 return true;
5175
5176 if (Indirect)
5177 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5178 Indirect, Loc,
5179 Loc,
5180 MemberInit.get(),
5181 Loc);
5182 else
5183 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5184 Field, Loc, Loc,
5185 MemberInit.get(),
5186 Loc);
5187 return false;
5188 }
5189
5190 if (!Field->getParent()->isUnion()) {
5191 if (FieldBaseElementType->isReferenceType()) {
5192 SemaRef.Diag(Constructor->getLocation(),
5193 diag::err_uninitialized_member_in_ctor)
5194 << (int)Constructor->isImplicit()
5195 << SemaRef.Context.getCanonicalTagType(Constructor->getParent()) << 0
5196 << Field->getDeclName();
5197 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
5198 return true;
5199 }
5200
5201 if (FieldBaseElementType.isConstQualified()) {
5202 SemaRef.Diag(Constructor->getLocation(),
5203 diag::err_uninitialized_member_in_ctor)
5204 << (int)Constructor->isImplicit()
5205 << SemaRef.Context.getCanonicalTagType(Constructor->getParent()) << 1
5206 << Field->getDeclName();
5207 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
5208 return true;
5209 }
5210 }
5211
5212 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
5213 // ARC and Weak:
5214 // Default-initialize Objective-C pointers to NULL.
5215 CXXMemberInit
5216 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
5217 Loc, Loc,
5218 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
5219 Loc);
5220 return false;
5221 }
5222
5223 // Nothing to initialize.
5224 CXXMemberInit = nullptr;
5225 return false;
5226}
5227
5228namespace {
5229struct BaseAndFieldInfo {
5230 Sema &S;
5231 CXXConstructorDecl *Ctor;
5232 bool AnyErrorsInInits;
5234 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
5235 SmallVector<CXXCtorInitializer*, 8> AllToInit;
5236 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
5237
5238 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
5239 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
5240 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
5241 if (Ctor->getInheritedConstructor())
5242 IIK = IIK_Inherit;
5243 else if (Generated && Ctor->isCopyConstructor())
5244 IIK = IIK_Copy;
5245 else if (Generated && Ctor->isMoveConstructor())
5246 IIK = IIK_Move;
5247 else
5248 IIK = IIK_Default;
5249 }
5250
5251 bool isImplicitCopyOrMove() const {
5252 switch (IIK) {
5253 case IIK_Copy:
5254 case IIK_Move:
5255 return true;
5256
5257 case IIK_Default:
5258 case IIK_Inherit:
5259 return false;
5260 }
5261
5262 llvm_unreachable("Invalid ImplicitInitializerKind!");
5263 }
5264
5265 bool addFieldInitializer(CXXCtorInitializer *Init) {
5266 AllToInit.push_back(Init);
5267
5268 // Check whether this initializer makes the field "used".
5269 if (Init->getInit()->HasSideEffects(S.Context))
5270 S.UnusedPrivateFields.remove(Init->getAnyMember());
5271
5272 return false;
5273 }
5274
5275 bool isInactiveUnionMember(FieldDecl *Field) {
5276 RecordDecl *Record = Field->getParent();
5277 if (!Record->isUnion())
5278 return false;
5279
5280 if (FieldDecl *Active =
5281 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
5282 return Active != Field->getCanonicalDecl();
5283
5284 // In an implicit copy or move constructor, ignore any in-class initializer.
5285 if (isImplicitCopyOrMove())
5286 return true;
5287
5288 // If there's no explicit initialization, the field is active only if it
5289 // has an in-class initializer...
5290 if (Field->hasInClassInitializer())
5291 return false;
5292 // ... or it's an anonymous struct or union whose class has an in-class
5293 // initializer.
5294 if (!Field->isAnonymousStructOrUnion())
5295 return true;
5296 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
5297 return !FieldRD->hasInClassInitializer();
5298 }
5299
5300 /// Determine whether the given field is, or is within, a union member
5301 /// that is inactive (because there was an initializer given for a different
5302 /// member of the union, or because the union was not initialized at all).
5303 bool isWithinInactiveUnionMember(FieldDecl *Field,
5304 IndirectFieldDecl *Indirect) {
5305 if (!Indirect)
5306 return isInactiveUnionMember(Field);
5307
5308 for (auto *C : Indirect->chain()) {
5309 FieldDecl *Field = dyn_cast<FieldDecl>(C);
5310 if (Field && isInactiveUnionMember(Field))
5311 return true;
5312 }
5313 return false;
5314 }
5315};
5316}
5317
5318/// Determine whether the given type is an incomplete or zero-lenfgth
5319/// array type.
5321 if (T->isIncompleteArrayType())
5322 return true;
5323
5324 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
5325 if (ArrayT->isZeroSize())
5326 return true;
5327
5328 T = ArrayT->getElementType();
5329 }
5330
5331 return false;
5332}
5333
5334static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
5335 FieldDecl *Field,
5336 IndirectFieldDecl *Indirect = nullptr) {
5337 if (Field->isInvalidDecl())
5338 return false;
5339
5340 // Overwhelmingly common case: we have a direct initializer for this field.
5342 Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
5343 return Info.addFieldInitializer(Init);
5344
5345 // C++11 [class.base.init]p8:
5346 // if the entity is a non-static data member that has a
5347 // brace-or-equal-initializer and either
5348 // -- the constructor's class is a union and no other variant member of that
5349 // union is designated by a mem-initializer-id or
5350 // -- the constructor's class is not a union, and, if the entity is a member
5351 // of an anonymous union, no other member of that union is designated by
5352 // a mem-initializer-id,
5353 // the entity is initialized as specified in [dcl.init].
5354 //
5355 // We also apply the same rules to handle anonymous structs within anonymous
5356 // unions.
5357 if (Info.isWithinInactiveUnionMember(Field, Indirect))
5358 return false;
5359
5360 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
5361 ExprResult DIE =
5362 SemaRef.BuildCXXCtorDefaultInitExpr(Info.Ctor->getLocation(), Field);
5363 if (DIE.isInvalid())
5364 return true;
5365
5367 SemaRef.checkInitializerLifetime(Entity, DIE.get());
5368
5370 if (Indirect)
5371 Init = new (SemaRef.Context)
5372 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
5373 SourceLocation(), DIE.get(), SourceLocation());
5374 else
5375 Init = new (SemaRef.Context)
5376 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
5377 SourceLocation(), DIE.get(), SourceLocation());
5378 return Info.addFieldInitializer(Init);
5379 }
5380
5381 // Don't initialize incomplete or zero-length arrays.
5382 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
5383 return false;
5384
5385 // Don't try to build an implicit initializer if there were semantic
5386 // errors in any of the initializers (and therefore we might be
5387 // missing some that the user actually wrote).
5388 if (Info.AnyErrorsInInits)
5389 return false;
5390
5391 CXXCtorInitializer *Init = nullptr;
5392 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
5393 Indirect, Init))
5394 return true;
5395
5396 if (!Init)
5397 return false;
5398
5399 return Info.addFieldInitializer(Init);
5400}
5401
5402bool
5405 assert(Initializer->isDelegatingInitializer());
5406 Constructor->setNumCtorInitializers(1);
5407 CXXCtorInitializer **initializer =
5408 new (Context) CXXCtorInitializer*[1];
5409 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
5410 Constructor->setCtorInitializers(initializer);
5411
5412 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
5413 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
5414 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
5415 }
5416
5418
5419 DiagnoseUninitializedFields(*this, Constructor);
5420
5421 return false;
5422}
5423
5425 CXXRecordDecl *Class) {
5426 if (Class->isInvalidDecl())
5427 return nullptr;
5428 if (Class->hasIrrelevantDestructor())
5429 return nullptr;
5430
5431 // Dtor might still be missing, e.g because it's invalid.
5432 return S.LookupDestructor(Class);
5433}
5434
5436 FieldDecl *Field) {
5437 if (Field->isInvalidDecl())
5438 return;
5439
5440 // Don't destroy incomplete or zero-length arrays.
5441 if (isIncompleteOrZeroLengthArrayType(S.Context, Field->getType()))
5442 return;
5443
5444 QualType FieldType = S.Context.getBaseElementType(Field->getType());
5445
5446 auto *FieldClassDecl = FieldType->getAsCXXRecordDecl();
5447 if (!FieldClassDecl)
5448 return;
5449
5450 // The destructor for an implicit anonymous union member is never invoked.
5451 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5452 return;
5453
5454 auto *Dtor = LookupDestructorIfRelevant(S, FieldClassDecl);
5455 if (!Dtor)
5456 return;
5457
5458 S.CheckDestructorAccess(Field->getLocation(), Dtor,
5459 S.PDiag(diag::err_access_dtor_field)
5460 << Field->getDeclName() << FieldType);
5461
5462 S.MarkFunctionReferenced(Location, Dtor);
5463 S.DiagnoseUseOfDecl(Dtor, Location);
5464}
5465
5467 CXXRecordDecl *ClassDecl) {
5468 if (ClassDecl->isDependentContext())
5469 return;
5470
5471 // We only potentially invoke the destructors of potentially constructed
5472 // subobjects.
5473 bool VisitVirtualBases = !ClassDecl->isAbstract();
5474
5475 // If the destructor exists and has already been marked used in the MS ABI,
5476 // then virtual base destructors have already been checked and marked used.
5477 // Skip checking them again to avoid duplicate diagnostics.
5479 CXXDestructorDecl *Dtor = ClassDecl->getDestructor();
5480 if (Dtor && Dtor->isUsed())
5481 VisitVirtualBases = false;
5482 }
5483
5485
5486 // Bases.
5487 for (const auto &Base : ClassDecl->bases()) {
5488 auto *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
5489 if (!BaseClassDecl)
5490 continue;
5491
5492 // Remember direct virtual bases.
5493 if (Base.isVirtual()) {
5494 if (!VisitVirtualBases)
5495 continue;
5496 DirectVirtualBases.insert(BaseClassDecl);
5497 }
5498
5499 auto *Dtor = LookupDestructorIfRelevant(S, BaseClassDecl);
5500 if (!Dtor)
5501 continue;
5502
5503 // FIXME: caret should be on the start of the class name
5504 S.CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5505 S.PDiag(diag::err_access_dtor_base)
5506 << Base.getType() << Base.getSourceRange(),
5507 S.Context.getCanonicalTagType(ClassDecl));
5508
5509 S.MarkFunctionReferenced(Location, Dtor);
5510 S.DiagnoseUseOfDecl(Dtor, Location);
5511 }
5512
5513 if (VisitVirtualBases)
5514 S.MarkVirtualBaseDestructorsReferenced(Location, ClassDecl,
5515 &DirectVirtualBases);
5516}
5517
5519 ArrayRef<CXXCtorInitializer *> Initializers) {
5520 if (Constructor->isDependentContext()) {
5521 // Just store the initializers as written, they will be checked during
5522 // instantiation.
5523 if (!Initializers.empty()) {
5524 Constructor->setNumCtorInitializers(Initializers.size());
5525 CXXCtorInitializer **baseOrMemberInitializers =
5526 new (Context) CXXCtorInitializer*[Initializers.size()];
5527 memcpy(baseOrMemberInitializers, Initializers.data(),
5528 Initializers.size() * sizeof(CXXCtorInitializer*));
5529 Constructor->setCtorInitializers(baseOrMemberInitializers);
5530 }
5531
5532 // Let template instantiation know whether we had errors.
5533 if (AnyErrors)
5534 Constructor->setInvalidDecl();
5535
5536 return false;
5537 }
5538
5539 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
5540
5541 // We need to build the initializer AST according to order of construction
5542 // and not what user specified in the Initializers list.
5543 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
5544 if (!ClassDecl)
5545 return true;
5546
5547 bool HadError = false;
5548
5549 for (CXXCtorInitializer *Member : Initializers) {
5550 if (Member->isBaseInitializer())
5551 Info.AllBaseFields[Member->getBaseClass()->getAsCanonical<RecordType>()] =
5552 Member;
5553 else {
5554 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
5555
5556 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
5557 for (auto *C : F->chain()) {
5558 FieldDecl *FD = dyn_cast<FieldDecl>(C);
5559 if (FD && FD->getParent()->isUnion())
5560 Info.ActiveUnionMember.insert(std::make_pair(
5562 }
5563 } else if (FieldDecl *FD = Member->getMember()) {
5564 if (FD->getParent()->isUnion())
5565 Info.ActiveUnionMember.insert(std::make_pair(
5567 }
5568 }
5569 }
5570
5571 // Keep track of the direct virtual bases.
5573 for (auto &I : ClassDecl->bases()) {
5574 if (I.isVirtual())
5575 DirectVBases.insert(&I);
5576 }
5577
5578 // Push virtual bases before others.
5579 for (auto &VBase : ClassDecl->vbases()) {
5580 if (CXXCtorInitializer *Value = Info.AllBaseFields.lookup(
5581 VBase.getType()->getAsCanonical<RecordType>())) {
5582 // [class.base.init]p7, per DR257:
5583 // A mem-initializer where the mem-initializer-id names a virtual base
5584 // class is ignored during execution of a constructor of any class that
5585 // is not the most derived class.
5586 if (ClassDecl->isAbstract()) {
5587 // FIXME: Provide a fixit to remove the base specifier. This requires
5588 // tracking the location of the associated comma for a base specifier.
5589 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
5590 << VBase.getType() << ClassDecl;
5591 DiagnoseAbstractType(ClassDecl);
5592 }
5593
5594 Info.AllToInit.push_back(Value);
5595 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
5596 // [class.base.init]p8, per DR257:
5597 // If a given [...] base class is not named by a mem-initializer-id
5598 // [...] and the entity is not a virtual base class of an abstract
5599 // class, then [...] the entity is default-initialized.
5600 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
5601 CXXCtorInitializer *CXXBaseInit;
5602 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5603 &VBase, IsInheritedVirtualBase,
5604 CXXBaseInit)) {
5605 HadError = true;
5606 continue;
5607 }
5608
5609 Info.AllToInit.push_back(CXXBaseInit);
5610 }
5611 }
5612
5613 // Non-virtual bases.
5614 for (auto &Base : ClassDecl->bases()) {
5615 // Virtuals are in the virtual base list and already constructed.
5616 if (Base.isVirtual())
5617 continue;
5618
5619 if (CXXCtorInitializer *Value = Info.AllBaseFields.lookup(
5620 Base.getType()->getAsCanonical<RecordType>())) {
5621 Info.AllToInit.push_back(Value);
5622 } else if (!AnyErrors) {
5623 CXXCtorInitializer *CXXBaseInit;
5624 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5625 &Base, /*IsInheritedVirtualBase=*/false,
5626 CXXBaseInit)) {
5627 HadError = true;
5628 continue;
5629 }
5630
5631 Info.AllToInit.push_back(CXXBaseInit);
5632 }
5633 }
5634
5635 // Fields.
5636 for (auto *Mem : ClassDecl->decls()) {
5637 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
5638 // C++ [class.bit]p2:
5639 // A declaration for a bit-field that omits the identifier declares an
5640 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
5641 // initialized.
5642 if (F->isUnnamedBitField())
5643 continue;
5644
5645 // If we're not generating the implicit copy/move constructor, then we'll
5646 // handle anonymous struct/union fields based on their individual
5647 // indirect fields.
5648 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
5649 continue;
5650
5651 if (CollectFieldInitializer(*this, Info, F))
5652 HadError = true;
5653 continue;
5654 }
5655
5656 // Beyond this point, we only consider default initialization.
5657 if (Info.isImplicitCopyOrMove())
5658 continue;
5659
5660 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
5661 if (F->getType()->isIncompleteArrayType()) {
5662 assert(ClassDecl->hasFlexibleArrayMember() &&
5663 "Incomplete array type is not valid");
5664 continue;
5665 }
5666
5667 // Initialize each field of an anonymous struct individually.
5668 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
5669 HadError = true;
5670
5671 continue;
5672 }
5673 }
5674
5675 unsigned NumInitializers = Info.AllToInit.size();
5676 if (NumInitializers > 0) {
5677 Constructor->setNumCtorInitializers(NumInitializers);
5678 CXXCtorInitializer **baseOrMemberInitializers =
5679 new (Context) CXXCtorInitializer*[NumInitializers];
5680 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
5681 NumInitializers * sizeof(CXXCtorInitializer*));
5682 Constructor->setCtorInitializers(baseOrMemberInitializers);
5683
5684 SourceLocation Location = Constructor->getLocation();
5685
5686 // Constructors implicitly reference the base and member
5687 // destructors.
5688
5689 for (CXXCtorInitializer *Initializer : Info.AllToInit) {
5690 FieldDecl *Field = Initializer->getAnyMember();
5691 if (!Field)
5692 continue;
5693
5694 // C++ [class.base.init]p12:
5695 // In a non-delegating constructor, the destructor for each
5696 // potentially constructed subobject of class type is potentially
5697 // invoked.
5698 MarkFieldDestructorReferenced(*this, Location, Field);
5699 }
5700
5701 MarkBaseDestructorsReferenced(*this, Location, Constructor->getParent());
5702 }
5703
5704 return HadError;
5705}
5706
5708 if (const RecordType *RT = Field->getType()->getAsCanonical<RecordType>()) {
5709 const RecordDecl *RD = RT->getDecl();
5710 if (RD->isAnonymousStructOrUnion()) {
5711 for (auto *Field : RD->getDefinitionOrSelf()->fields())
5712 PopulateKeysForFields(Field, IdealInits);
5713 return;
5714 }
5715 }
5716 IdealInits.push_back(Field->getCanonicalDecl());
5717}
5718
5719static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
5720 return Context.getCanonicalType(BaseType).getTypePtr();
5721}
5722
5723static const void *GetKeyForMember(ASTContext &Context,
5725 if (!Member->isAnyMemberInitializer())
5726 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
5727
5728 return Member->getAnyMember()->getCanonicalDecl();
5729}
5730
5733 const CXXCtorInitializer *Current) {
5734 if (Previous->isAnyMemberInitializer())
5735 Diag << 0 << Previous->getAnyMember();
5736 else
5737 Diag << 1 << Previous->getTypeSourceInfo()->getType();
5738
5739 if (Current->isAnyMemberInitializer())
5740 Diag << 0 << Current->getAnyMember();
5741 else
5742 Diag << 1 << Current->getTypeSourceInfo()->getType();
5743}
5744
5746 Sema &SemaRef, const CXXConstructorDecl *Constructor,
5748 if (Constructor->getDeclContext()->isDependentContext())
5749 return;
5750
5751 // Don't check initializers order unless the warning is enabled at the
5752 // location of at least one initializer.
5753 bool ShouldCheckOrder = false;
5754 for (const CXXCtorInitializer *Init : Inits) {
5755 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
5756 Init->getSourceLocation())) {
5757 ShouldCheckOrder = true;
5758 break;
5759 }
5760 }
5761 if (!ShouldCheckOrder)
5762 return;
5763
5764 // Build the list of bases and members in the order that they'll
5765 // actually be initialized. The explicit initializers should be in
5766 // this same order but may be missing things.
5767 SmallVector<const void*, 32> IdealInitKeys;
5768
5769 const CXXRecordDecl *ClassDecl = Constructor->getParent();
5770
5771 // 1. Virtual bases.
5772 for (const auto &VBase : ClassDecl->vbases())
5773 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
5774
5775 // 2. Non-virtual bases.
5776 for (const auto &Base : ClassDecl->bases()) {
5777 if (Base.isVirtual())
5778 continue;
5779 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
5780 }
5781
5782 // 3. Direct fields.
5783 for (auto *Field : ClassDecl->fields()) {
5784 if (Field->isUnnamedBitField())
5785 continue;
5786
5787 PopulateKeysForFields(Field, IdealInitKeys);
5788 }
5789
5790 unsigned NumIdealInits = IdealInitKeys.size();
5791 unsigned IdealIndex = 0;
5792
5793 // Track initializers that are in an incorrect order for either a warning or
5794 // note if multiple ones occur.
5795 SmallVector<unsigned> WarnIndexes;
5796 // Correlates the index of an initializer in the init-list to the index of
5797 // the field/base in the class.
5798 SmallVector<std::pair<unsigned, unsigned>, 32> CorrelatedInitOrder;
5799
5800 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5801 const void *InitKey = GetKeyForMember(SemaRef.Context, Inits[InitIndex]);
5802
5803 // Scan forward to try to find this initializer in the idealized
5804 // initializers list.
5805 for (; IdealIndex != NumIdealInits; ++IdealIndex)
5806 if (InitKey == IdealInitKeys[IdealIndex])
5807 break;
5808
5809 // If we didn't find this initializer, it must be because we
5810 // scanned past it on a previous iteration. That can only
5811 // happen if we're out of order; emit a warning.
5812 if (IdealIndex == NumIdealInits && InitIndex) {
5813 WarnIndexes.push_back(InitIndex);
5814
5815 // Move back to the initializer's location in the ideal list.
5816 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5817 if (InitKey == IdealInitKeys[IdealIndex])
5818 break;
5819
5820 assert(IdealIndex < NumIdealInits &&
5821 "initializer not found in initializer list");
5822 }
5823 CorrelatedInitOrder.emplace_back(IdealIndex, InitIndex);
5824 }
5825
5826 if (WarnIndexes.empty())
5827 return;
5828
5829 // Sort based on the ideal order, first in the pair.
5830 llvm::sort(CorrelatedInitOrder, llvm::less_first());
5831
5832 // Introduce a new scope as SemaDiagnosticBuilder needs to be destroyed to
5833 // emit the diagnostic before we can try adding notes.
5834 {
5836 Inits[WarnIndexes.front() - 1]->getSourceLocation(),
5837 WarnIndexes.size() == 1 ? diag::warn_initializer_out_of_order
5838 : diag::warn_some_initializers_out_of_order);
5839
5840 for (unsigned I = 0; I < CorrelatedInitOrder.size(); ++I) {
5841 if (CorrelatedInitOrder[I].second == I)
5842 continue;
5843 // Ideally we would be using InsertFromRange here, but clang doesn't
5844 // appear to handle InsertFromRange correctly when the source range is
5845 // modified by another fix-it.
5847 Inits[I]->getSourceRange(),
5850 Inits[CorrelatedInitOrder[I].second]->getSourceRange()),
5851 SemaRef.getSourceManager(), SemaRef.getLangOpts()));
5852 }
5853
5854 // If there is only 1 item out of order, the warning expects the name and
5855 // type of each being added to it.
5856 if (WarnIndexes.size() == 1) {
5857 AddInitializerToDiag(D, Inits[WarnIndexes.front() - 1],
5858 Inits[WarnIndexes.front()]);
5859 return;
5860 }
5861 }
5862 // More than 1 item to warn, create notes letting the user know which ones
5863 // are bad.
5864 for (unsigned WarnIndex : WarnIndexes) {
5865 const clang::CXXCtorInitializer *PrevInit = Inits[WarnIndex - 1];
5866 auto D = SemaRef.Diag(PrevInit->getSourceLocation(),
5867 diag::note_initializer_out_of_order);
5868 AddInitializerToDiag(D, PrevInit, Inits[WarnIndex]);
5869 D << PrevInit->getSourceRange();
5870 }
5871}
5872
5873namespace {
5874bool CheckRedundantInit(Sema &S,
5875 CXXCtorInitializer *Init,
5876 CXXCtorInitializer *&PrevInit) {
5877 if (!PrevInit) {
5878 PrevInit = Init;
5879 return false;
5880 }
5881
5882 if (FieldDecl *Field = Init->getAnyMember())
5883 S.Diag(Init->getSourceLocation(),
5884 diag::err_multiple_mem_initialization)
5885 << Field->getDeclName()
5886 << Init->getSourceRange();
5887 else {
5888 const Type *BaseClass = Init->getBaseClass();
5889 assert(BaseClass && "neither field nor base");
5890 S.Diag(Init->getSourceLocation(),
5891 diag::err_multiple_base_initialization)
5892 << QualType(BaseClass, 0)
5893 << Init->getSourceRange();
5894 }
5895 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5896 << 0 << PrevInit->getSourceRange();
5897
5898 return true;
5899}
5900
5901typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5902typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5903
5904bool CheckRedundantUnionInit(Sema &S,
5905 CXXCtorInitializer *Init,
5906 RedundantUnionMap &Unions) {
5907 FieldDecl *Field = Init->getAnyMember();
5908 RecordDecl *Parent = Field->getParent();
5909 NamedDecl *Child = Field;
5910
5911 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5912 if (Parent->isUnion()) {
5913 UnionEntry &En = Unions[Parent];
5914 if (En.first && En.first != Child) {
5915 S.Diag(Init->getSourceLocation(),
5916 diag::err_multiple_mem_union_initialization)
5917 << Field->getDeclName()
5918 << Init->getSourceRange();
5919 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5920 << 0 << En.second->getSourceRange();
5921 return true;
5922 }
5923 if (!En.first) {
5924 En.first = Child;
5925 En.second = Init;
5926 }
5927 if (!Parent->isAnonymousStructOrUnion())
5928 return false;
5929 }
5930
5931 Child = Parent;
5932 Parent = cast<RecordDecl>(Parent->getDeclContext());
5933 }
5934
5935 return false;
5936}
5937} // namespace
5938
5939void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5940 SourceLocation ColonLoc,
5942 bool AnyErrors) {
5943 if (!ConstructorDecl)
5944 return;
5945
5946 AdjustDeclIfTemplate(ConstructorDecl);
5947
5949 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5950
5951 if (!Constructor) {
5952 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5953 return;
5954 }
5955
5956 // Mapping for the duplicate initializers check.
5957 // For member initializers, this is keyed with a FieldDecl*.
5958 // For base initializers, this is keyed with a Type*.
5959 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5960
5961 // Mapping for the inconsistent anonymous-union initializers check.
5962 RedundantUnionMap MemberUnions;
5963
5964 bool HadError = false;
5965 for (unsigned i = 0; i < MemInits.size(); i++) {
5966 CXXCtorInitializer *Init = MemInits[i];
5967
5968 // Set the source order index.
5969 Init->setSourceOrder(i);
5970
5971 if (Init->isAnyMemberInitializer()) {
5972 const void *Key = GetKeyForMember(Context, Init);
5973 if (CheckRedundantInit(*this, Init, Members[Key]) ||
5974 CheckRedundantUnionInit(*this, Init, MemberUnions))
5975 HadError = true;
5976 } else if (Init->isBaseInitializer()) {
5977 const void *Key = GetKeyForMember(Context, Init);
5978 if (CheckRedundantInit(*this, Init, Members[Key]))
5979 HadError = true;
5980 } else {
5981 assert(Init->isDelegatingInitializer());
5982 // This must be the only initializer
5983 if (MemInits.size() != 1) {
5984 Diag(Init->getSourceLocation(),
5985 diag::err_delegating_initializer_alone)
5986 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5987 // We will treat this as being the only initializer.
5988 }
5990 // Return immediately as the initializer is set.
5991 return;
5992 }
5993 }
5994
5995 if (HadError)
5996 return;
5997
5999
6000 SetCtorInitializers(Constructor, AnyErrors, MemInits);
6001
6002 DiagnoseUninitializedFields(*this, Constructor);
6003}
6004
6006 CXXRecordDecl *ClassDecl) {
6007 // Ignore dependent contexts. Also ignore unions, since their members never
6008 // have destructors implicitly called.
6009 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
6010 return;
6011
6012 // FIXME: all the access-control diagnostics are positioned on the
6013 // field/base declaration. That's probably good; that said, the
6014 // user might reasonably want to know why the destructor is being
6015 // emitted, and we currently don't say.
6016
6017 // Non-static data members.
6018 for (auto *Field : ClassDecl->fields()) {
6019 MarkFieldDestructorReferenced(*this, Location, Field);
6020 }
6021
6022 MarkBaseDestructorsReferenced(*this, Location, ClassDecl);
6023}
6024
6026 SourceLocation Location, CXXRecordDecl *ClassDecl,
6027 llvm::SmallPtrSetImpl<const CXXRecordDecl *> *DirectVirtualBases) {
6028 // Virtual bases.
6029 for (const auto &VBase : ClassDecl->vbases()) {
6030 auto *BaseClassDecl = VBase.getType()->getAsCXXRecordDecl();
6031 if (!BaseClassDecl)
6032 continue;
6033
6034 // Ignore already visited direct virtual bases.
6035 if (DirectVirtualBases && DirectVirtualBases->count(BaseClassDecl))
6036 continue;
6037
6038 auto *Dtor = LookupDestructorIfRelevant(*this, BaseClassDecl);
6039 if (!Dtor)
6040 continue;
6041
6042 CanQualType CT = Context.getCanonicalTagType(ClassDecl);
6043 if (CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
6044 PDiag(diag::err_access_dtor_vbase)
6045 << CT << VBase.getType(),
6046 CT) == AR_accessible) {
6048 CT, VBase.getType(), diag::err_access_dtor_vbase, 0,
6049 ClassDecl->getLocation(), SourceRange(), DeclarationName(), nullptr);
6050 }
6051
6052 MarkFunctionReferenced(Location, Dtor);
6053 DiagnoseUseOfDecl(Dtor, Location);
6054 }
6055}
6056
6058 if (!CDtorDecl)
6059 return;
6060
6062 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
6063 if (CXXRecordDecl *ClassDecl = Constructor->getParent();
6064 !ClassDecl || ClassDecl->isInvalidDecl()) {
6065 return;
6066 }
6067 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
6068 DiagnoseUninitializedFields(*this, Constructor);
6069 }
6070}
6071
6073 if (!getLangOpts().CPlusPlus)
6074 return false;
6075
6076 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
6077 if (!RD)
6078 return false;
6079
6080 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
6081 // class template specialization here, but doing so breaks a lot of code.
6082
6083 // We can't answer whether something is abstract until it has a
6084 // definition. If it's currently being defined, we'll walk back
6085 // over all the declarations when we have a full definition.
6086 const CXXRecordDecl *Def = RD->getDefinition();
6087 if (!Def || Def->isBeingDefined())
6088 return false;
6089
6090 return RD->isAbstract();
6091}
6092
6094 TypeDiagnoser &Diagnoser) {
6095 if (!isAbstractType(Loc, T))
6096 return false;
6097
6098 T = Context.getBaseElementType(T);
6099 Diagnoser.diagnose(*this, Loc, T);
6100 DiagnoseAbstractType(T->getAsCXXRecordDecl());
6101 return true;
6102}
6103
6105 // Check if we've already emitted the list of pure virtual functions
6106 // for this class.
6108 return;
6109
6110 // If the diagnostic is suppressed, don't emit the notes. We're only
6111 // going to emit them once, so try to attach them to a diagnostic we're
6112 // actually going to show.
6113 if (Diags.isLastDiagnosticIgnored())
6114 return;
6115
6116 CXXFinalOverriderMap FinalOverriders;
6117 RD->getFinalOverriders(FinalOverriders);
6118
6119 // Keep a set of seen pure methods so we won't diagnose the same method
6120 // more than once.
6122
6123 for (const auto &M : FinalOverriders) {
6124 for (const auto &SO : M.second) {
6125 // C++ [class.abstract]p4:
6126 // A class is abstract if it contains or inherits at least one
6127 // pure virtual function for which the final overrider is pure
6128 // virtual.
6129
6130 if (SO.second.size() != 1)
6131 continue;
6132 const CXXMethodDecl *Method = SO.second.front().Method;
6133
6134 if (!Method->isPureVirtual())
6135 continue;
6136
6137 if (!SeenPureMethods.insert(Method).second)
6138 continue;
6139
6140 Diag(Method->getLocation(), diag::note_pure_virtual_function)
6141 << Method->getDeclName() << RD->getDeclName();
6142 }
6143 }
6144
6147 PureVirtualClassDiagSet->insert(RD);
6148}
6149
6150namespace {
6151struct AbstractUsageInfo {
6152 Sema &S;
6154 CanQualType AbstractType;
6155 bool Invalid;
6156
6157 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
6158 : S(S), Record(Record),
6159 AbstractType(S.Context.getCanonicalTagType(Record)), Invalid(false) {}
6160
6161 void DiagnoseAbstractType() {
6162 if (Invalid) return;
6164 Invalid = true;
6165 }
6166
6167 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
6168};
6169
6170struct CheckAbstractUsage {
6171 AbstractUsageInfo &Info;
6172 const NamedDecl *Ctx;
6173
6174 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
6175 : Info(Info), Ctx(Ctx) {}
6176
6177 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
6178 switch (TL.getTypeLocClass()) {
6179#define ABSTRACT_TYPELOC(CLASS, PARENT)
6180#define TYPELOC(CLASS, PARENT) \
6181 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
6182#include "clang/AST/TypeLocNodes.def"
6183 }
6184 }
6185
6186 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6188 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
6189 if (!TL.getParam(I))
6190 continue;
6191
6192 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
6193 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
6194 }
6195 }
6196
6197 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6199 }
6200
6201 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6202 // Visit the type parameters from a permissive context.
6203 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
6204 TemplateArgumentLoc TAL = TL.getArgLoc(I);
6206 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
6207 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
6208 // TODO: other template argument types?
6209 }
6210 }
6211
6212 // Visit pointee types from a permissive context.
6213#define CheckPolymorphic(Type) \
6214 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
6215 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
6216 }
6222
6223 /// Handle all the types we haven't given a more specific
6224 /// implementation for above.
6225 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
6226 // Every other kind of type that we haven't called out already
6227 // that has an inner type is either (1) sugar or (2) contains that
6228 // inner type in some way as a subobject.
6229 if (TypeLoc Next = TL.getNextTypeLoc())
6230 return Visit(Next, Sel);
6231
6232 // If there's no inner type and we're in a permissive context,
6233 // don't diagnose.
6234 if (Sel == Sema::AbstractNone) return;
6235
6236 // Check whether the type matches the abstract type.
6237 QualType T = TL.getType();
6238 if (T->isArrayType()) {
6240 T = Info.S.Context.getBaseElementType(T);
6241 }
6242 CanQualType CT = T->getCanonicalTypeUnqualified();
6243 if (CT != Info.AbstractType) return;
6244
6245 // It matched; do some magic.
6246 // FIXME: These should be at most warnings. See P0929R2, CWG1640, CWG1646.
6247 if (Sel == Sema::AbstractArrayType) {
6248 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
6249 << T << TL.getSourceRange();
6250 } else {
6251 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
6252 << Sel << T << TL.getSourceRange();
6253 }
6254 Info.DiagnoseAbstractType();
6255 }
6256};
6257
6258void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
6260 CheckAbstractUsage(*this, D).Visit(TL, Sel);
6261}
6262
6263}
6264
6265/// Check for invalid uses of an abstract type in a function declaration.
6266static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6267 FunctionDecl *FD) {
6268 // Only definitions are required to refer to complete and
6269 // non-abstract types.
6271 return;
6272
6273 // For safety's sake, just ignore it if we don't have type source
6274 // information. This should never happen for non-implicit methods,
6275 // but...
6276 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6277 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractNone);
6278}
6279
6280/// Check for invalid uses of an abstract type in a variable0 declaration.
6281static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6282 VarDecl *VD) {
6283 // No need to do the check on definitions, which require that
6284 // the type is complete.
6286 return;
6287
6288 Info.CheckType(VD, VD->getTypeSourceInfo()->getTypeLoc(),
6290}
6291
6292/// Check for invalid uses of an abstract type within a class definition.
6293static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6294 CXXRecordDecl *RD) {
6295 for (auto *D : RD->decls()) {
6296 if (D->isImplicit()) continue;
6297
6298 // Step through friends to the befriended declaration.
6299 if (auto *FD = dyn_cast<FriendDecl>(D)) {
6300 D = FD->getFriendDecl();
6301 if (!D) continue;
6302 }
6303
6304 // Functions and function templates.
6305 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6306 CheckAbstractClassUsage(Info, FD);
6307 } else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) {
6308 CheckAbstractClassUsage(Info, FTD->getTemplatedDecl());
6309
6310 // Fields and static variables.
6311 } else if (auto *FD = dyn_cast<FieldDecl>(D)) {
6312 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6313 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
6314 } else if (auto *VD = dyn_cast<VarDecl>(D)) {
6315 CheckAbstractClassUsage(Info, VD);
6316 } else if (auto *VTD = dyn_cast<VarTemplateDecl>(D)) {
6317 CheckAbstractClassUsage(Info, VTD->getTemplatedDecl());
6318
6319 // Nested classes and class templates.
6320 } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
6321 CheckAbstractClassUsage(Info, RD);
6322 } else if (auto *CTD = dyn_cast<ClassTemplateDecl>(D)) {
6323 CheckAbstractClassUsage(Info, CTD->getTemplatedDecl());
6324 }
6325 }
6326}
6327
6329 Attr *ClassAttr = getDLLAttr(Class);
6330 if (!ClassAttr)
6331 return;
6332
6333 assert(ClassAttr->getKind() == attr::DLLExport);
6334
6335 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6336
6338 // Don't go any further if this is just an explicit instantiation
6339 // declaration.
6340 return;
6341
6342 // Add a context note to explain how we got to any diagnostics produced below.
6343 struct MarkingClassDllexported {
6344 Sema &S;
6345 MarkingClassDllexported(Sema &S, CXXRecordDecl *Class,
6346 SourceLocation AttrLoc)
6347 : S(S) {
6350 Ctx.PointOfInstantiation = AttrLoc;
6351 Ctx.Entity = Class;
6353 }
6354 ~MarkingClassDllexported() {
6356 }
6357 } MarkingDllexportedContext(S, Class, ClassAttr->getLocation());
6358
6359 if (S.Context.getTargetInfo().getTriple().isOSCygMing())
6360 S.MarkVTableUsed(Class->getLocation(), Class, true);
6361
6362 for (Decl *Member : Class->decls()) {
6363 // Skip members that were not marked exported.
6364 if (!Member->hasAttr<DLLExportAttr>())
6365 continue;
6366
6367 // Defined static variables that are members of an exported base
6368 // class must be marked export too.
6369 auto *VD = dyn_cast<VarDecl>(Member);
6370 if (VD && VD->getStorageClass() == SC_Static &&
6372 S.MarkVariableReferenced(VD->getLocation(), VD);
6373
6374 auto *MD = dyn_cast<CXXMethodDecl>(Member);
6375 if (!MD)
6376 continue;
6377
6378 if (MD->isUserProvided()) {
6379 // Instantiate non-default class member functions ...
6380
6381 // .. except for certain kinds of template specializations.
6382 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
6383 continue;
6384
6385 // If this is an MS ABI dllexport default constructor, instantiate any
6386 // default arguments.
6388 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6389 if (CD && CD->isDefaultConstructor() && TSK == TSK_Undeclared) {
6391 CD->getAttr<DLLExportAttr>()->getLocation(), CD);
6392 }
6393 }
6394
6395 S.MarkFunctionReferenced(Class->getLocation(), MD);
6396
6397 // The function will be passed to the consumer when its definition is
6398 // encountered.
6399 } else if (MD->isExplicitlyDefaulted()) {
6400 // Synthesize and instantiate explicitly defaulted methods.
6401 S.MarkFunctionReferenced(Class->getLocation(), MD);
6402
6404 // Except for explicit instantiation defs, we will not see the
6405 // definition again later, so pass it to the consumer now.
6407 }
6408 } else if (!MD->isTrivial() ||
6409 MD->isCopyAssignmentOperator() ||
6410 MD->isMoveAssignmentOperator()) {
6411 // Synthesize and instantiate non-trivial implicit methods, and the copy
6412 // and move assignment operators. The latter are exported even if they
6413 // are trivial, because the address of an operator can be taken and
6414 // should compare equal across libraries.
6415 S.MarkFunctionReferenced(Class->getLocation(), MD);
6416
6417 // There is no later point when we will see the definition of this
6418 // function, so pass it to the consumer now.
6420 }
6421 }
6422}
6423
6425 CXXRecordDecl *Class) {
6426 // Only the MS ABI has default constructor closures, so we don't need to do
6427 // this semantic checking anywhere else.
6429 return;
6430
6431 if (Class->isInvalidDecl())
6432 return;
6433
6434 CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
6435 for (Decl *Member : Class->decls()) {
6436 // Nested classes finish delayed default argument parsing with the outermost
6437 // class, so check each nested definition here.
6438 if (auto *NestedClass = dyn_cast<CXXRecordDecl>(Member)) {
6439 if (NestedClass->isThisDeclarationADefinition())
6441 continue;
6442 }
6443
6444 // Look for exported default constructors.
6445 auto *CD = dyn_cast<CXXConstructorDecl>(Member);
6446 if (!CD || !CD->isDefaultConstructor())
6447 continue;
6448 auto *Attr = CD->getAttr<DLLExportAttr>();
6449 if (!Attr)
6450 continue;
6451
6452 // If the class is non-dependent, mark the default arguments as ODR-used so
6453 // that we can properly codegen the constructor closure.
6454 if (!Class->isDependentContext()) {
6457 }
6458
6459 if (LastExportedDefaultCtor) {
6460 S.Diag(LastExportedDefaultCtor->getLocation(),
6461 diag::err_attribute_dll_ambiguous_default_ctor)
6462 << Class;
6463 S.Diag(CD->getLocation(), diag::note_entity_declared_at)
6464 << CD->getDeclName();
6465 return;
6466 }
6467 LastExportedDefaultCtor = CD;
6468 }
6469}
6470
6472 CXXRecordDecl *Class) {
6473 bool ErrorReported = false;
6474 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6475 ClassTemplateDecl *TD) {
6476 if (ErrorReported)
6477 return;
6478 S.Diag(TD->getLocation(),
6479 diag::err_cuda_device_builtin_surftex_cls_template)
6480 << /*surface*/ 0 << TD;
6481 ErrorReported = true;
6482 };
6483
6484 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6485 if (!TD) {
6486 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6487 if (!SD) {
6488 S.Diag(Class->getLocation(),
6489 diag::err_cuda_device_builtin_surftex_ref_decl)
6490 << /*surface*/ 0 << Class;
6491 S.Diag(Class->getLocation(),
6492 diag::note_cuda_device_builtin_surftex_should_be_template_class)
6493 << Class;
6494 return;
6495 }
6496 TD = SD->getSpecializedTemplate();
6497 }
6498
6500 unsigned N = Params->size();
6501
6502 if (N != 2) {
6503 reportIllegalClassTemplate(S, TD);
6504 S.Diag(TD->getLocation(),
6505 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6506 << TD << 2;
6507 }
6508 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6509 reportIllegalClassTemplate(S, TD);
6510 S.Diag(TD->getLocation(),
6511 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6512 << TD << /*1st*/ 0 << /*type*/ 0;
6513 }
6514 if (N > 1) {
6515 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6516 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6517 reportIllegalClassTemplate(S, TD);
6518 S.Diag(TD->getLocation(),
6519 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6520 << TD << /*2nd*/ 1 << /*integer*/ 1;
6521 }
6522 }
6523}
6524
6526 CXXRecordDecl *Class) {
6527 bool ErrorReported = false;
6528 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6529 ClassTemplateDecl *TD) {
6530 if (ErrorReported)
6531 return;
6532 S.Diag(TD->getLocation(),
6533 diag::err_cuda_device_builtin_surftex_cls_template)
6534 << /*texture*/ 1 << TD;
6535 ErrorReported = true;
6536 };
6537
6538 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6539 if (!TD) {
6540 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6541 if (!SD) {
6542 S.Diag(Class->getLocation(),
6543 diag::err_cuda_device_builtin_surftex_ref_decl)
6544 << /*texture*/ 1 << Class;
6545 S.Diag(Class->getLocation(),
6546 diag::note_cuda_device_builtin_surftex_should_be_template_class)
6547 << Class;
6548 return;
6549 }
6550 TD = SD->getSpecializedTemplate();
6551 }
6552
6554 unsigned N = Params->size();
6555
6556 if (N != 3) {
6557 reportIllegalClassTemplate(S, TD);
6558 S.Diag(TD->getLocation(),
6559 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6560 << TD << 3;
6561 }
6562 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6563 reportIllegalClassTemplate(S, TD);
6564 S.Diag(TD->getLocation(),
6565 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6566 << TD << /*1st*/ 0 << /*type*/ 0;
6567 }
6568 if (N > 1) {
6569 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6570 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6571 reportIllegalClassTemplate(S, TD);
6572 S.Diag(TD->getLocation(),
6573 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6574 << TD << /*2nd*/ 1 << /*integer*/ 1;
6575 }
6576 }
6577 if (N > 2) {
6578 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2));
6579 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6580 reportIllegalClassTemplate(S, TD);
6581 S.Diag(TD->getLocation(),
6582 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6583 << TD << /*3rd*/ 2 << /*integer*/ 1;
6584 }
6585 }
6586}
6587
6589 // Mark any compiler-generated routines with the implicit code_seg attribute.
6590 for (auto *Method : Class->methods()) {
6591 if (Method->isUserProvided())
6592 continue;
6593 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
6594 Method->addAttr(A);
6595 }
6596}
6597
6599 Attr *ClassAttr = getDLLAttr(Class);
6600
6601 // MSVC inherits DLL attributes to partial class template specializations.
6602 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) {
6603 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
6604 if (Attr *TemplateAttr =
6605 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
6606 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
6607 A->setInherited(true);
6608 ClassAttr = A;
6609 }
6610 }
6611 }
6612
6613 if (!ClassAttr)
6614 return;
6615
6616 // MSVC allows imported or exported template classes that have UniqueExternal
6617 // linkage. This occurs when the template class has been instantiated with
6618 // a template parameter which itself has internal linkage.
6619 // We drop the attribute to avoid exporting or importing any members.
6620 if ((Context.getTargetInfo().getCXXABI().isMicrosoft() ||
6621 Context.getTargetInfo().getTriple().isPS()) &&
6622 (!Class->isExternallyVisible() && Class->hasExternalFormalLinkage())) {
6623 Class->dropAttrs<DLLExportAttr, DLLImportAttr>();
6624 return;
6625 }
6626
6627 if (!Class->isExternallyVisible()) {
6628 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
6629 << Class << ClassAttr;
6630 return;
6631 }
6632
6633 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6634 !ClassAttr->isInherited()) {
6635 // Diagnose dll attributes on members of class with dll attribute.
6636 for (Decl *Member : Class->decls()) {
6638 continue;
6639 InheritableAttr *MemberAttr = getDLLAttr(Member);
6640 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
6641 continue;
6642
6643 Diag(MemberAttr->getLocation(),
6644 diag::err_attribute_dll_member_of_dll_class)
6645 << MemberAttr << ClassAttr;
6646 Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
6647 Member->setInvalidDecl();
6648 }
6649 }
6650
6651 if (Class->getDescribedClassTemplate())
6652 // Don't inherit dll attribute until the template is instantiated.
6653 return;
6654
6655 // The class is either imported or exported.
6656 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
6657
6658 // Check if this was a dllimport attribute propagated from a derived class to
6659 // a base class template specialization. We don't apply these attributes to
6660 // static data members.
6661 const bool PropagatedImport =
6662 !ClassExported &&
6663 cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
6664
6665 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6666
6667 // Ignore explicit dllexport on explicit class template instantiation
6668 // declarations, except in MinGW mode.
6669 if (ClassExported && !ClassAttr->isInherited() &&
6671 !Context.getTargetInfo().getTriple().isOSCygMing()) {
6672 if (auto *DEA = Class->getAttr<DLLExportAttr>()) {
6673 Class->addAttr(DLLExportOnDeclAttr::Create(Context, DEA->getLoc()));
6674 Class->dropAttr<DLLExportAttr>();
6675 }
6676 return;
6677 }
6678
6679 // Force declaration of implicit members so they can inherit the attribute.
6681
6682 // Inherited constructors are created lazily; force their creation now so the
6683 // loop below can propagate the DLL attribute to them.
6684 if (ClassExported && getLangOpts().DllExportInlines) {
6686 for (Decl *D : Class->decls())
6687 if (auto *S = dyn_cast<ConstructorUsingShadowDecl>(D))
6688 Shadows.push_back(S);
6689 for (ConstructorUsingShadowDecl *S : Shadows) {
6690 CXXConstructorDecl *BC = dyn_cast<CXXConstructorDecl>(S->getTargetDecl());
6691 if (!BC || BC->isDeleted())
6692 continue;
6693 // Skip constructors whose requires clause is not satisfied.
6694 // Normally overload resolution filters these, but we are bypassing
6695 // it to eagerly create inherited constructors for dllexport.
6696 if (BC->getTrailingRequiresClause()) {
6697 ConstraintSatisfaction Satisfaction;
6698 if (CheckFunctionConstraints(BC, Satisfaction) ||
6699 !Satisfaction.IsSatisfied)
6700 continue;
6701 }
6702 findInheritingConstructor(Class->getLocation(), BC, S);
6703 }
6704 }
6705
6706 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
6707 // seem to be true in practice?
6708
6709 for (Decl *Member : Class->decls()) {
6710 if (Member->hasAttr<ExcludeFromExplicitInstantiationAttr>())
6711 continue;
6712
6713 VarDecl *VD = dyn_cast<VarDecl>(Member);
6714 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
6715
6716 // Only methods and static fields inherit the attributes.
6717 if (!VD && !MD)
6718 continue;
6719
6720 if (MD) {
6721 // Don't process deleted methods.
6722 if (MD->isDeleted())
6723 continue;
6724
6725 if (ClassExported && getLangOpts().DllExportInlines) {
6726 CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(MD);
6727 if (CD && CD->getInheritedConstructor()) {
6728 // Inherited constructors already had their base constructor's
6729 // constraints checked before creation via
6730 // findInheritingConstructor, so only ABI-compatibility checks
6731 // are needed here.
6732 //
6733 // Don't export inherited constructors whose parameters prevent
6734 // ABI-compatible forwarding. When canEmitDelegateCallArgs (in
6735 // CodeGen) returns false, Clang inlines the constructor body
6736 // instead of emitting a forwarding thunk, producing code that
6737 // is not ABI-compatible with MSVC. Suppress the export and warn
6738 // so the user gets a linker error rather than a silent runtime
6739 // mismatch.
6740 if (CD->isVariadic()) {
6741 Diag(CD->getLocation(),
6742 diag::warn_dllexport_inherited_ctor_unsupported)
6743 << /*variadic=*/0;
6744 continue;
6745 }
6746 if (Context.getTargetInfo()
6747 .getCXXABI()
6748 .areArgsDestroyedLeftToRightInCallee()) {
6749 bool HasCalleeCleanupParam = false;
6750 for (const ParmVarDecl *P : CD->parameters())
6751 if (P->needsDestruction(Context)) {
6752 HasCalleeCleanupParam = true;
6753 break;
6754 }
6755 if (HasCalleeCleanupParam) {
6756 Diag(CD->getLocation(),
6757 diag::warn_dllexport_inherited_ctor_unsupported)
6758 << /*callee-cleanup=*/1;
6759 continue;
6760 }
6761 }
6762 } else if (MD->getTrailingRequiresClause()) {
6763 // Don't export methods whose requires clause is not satisfied.
6764 // For class template specializations, member constraints may
6765 // depend on template arguments and an unsatisfied constraint
6766 // means the member should not be available in this
6767 // specialization.
6768 ConstraintSatisfaction Satisfaction;
6769 if (CheckFunctionConstraints(MD, Satisfaction) ||
6770 !Satisfaction.IsSatisfied)
6771 continue;
6772 }
6773 }
6774
6775 if (MD->isInlined()) {
6776 // MinGW does not import or export inline methods. But do it for
6777 // template instantiations and inherited constructors (which are
6778 // marked inline but must be exported to match MSVC behavior).
6779 if (!Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6782 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6783 !CD || !CD->getInheritedConstructor())
6784 continue;
6785 }
6786
6787 // MSVC versions before 2015 don't export the move assignment operators
6788 // and move constructor, so don't attempt to import/export them if
6789 // we have a definition.
6790 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
6791 if ((MD->isMoveAssignmentOperator() ||
6792 (Ctor && Ctor->isMoveConstructor())) &&
6793 getLangOpts().isCompatibleWithMSVC() &&
6794 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
6795 continue;
6796
6797 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
6798 // operator is exported anyway.
6799 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6800 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
6801 continue;
6802 }
6803 }
6804
6805 // Don't apply dllimport attributes to static data members of class template
6806 // instantiations when the attribute is propagated from a derived class.
6807 if (VD && PropagatedImport)
6808 continue;
6809
6811 continue;
6812
6813 if (!getDLLAttr(Member)) {
6814 InheritableAttr *NewAttr = nullptr;
6815
6816 // Do not export/import inline function when -fno-dllexport-inlines is
6817 // passed. But add attribute for later local static var check.
6818 if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
6821 if (ClassExported) {
6822 NewAttr = ::new (getASTContext())
6823 DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);
6824 } else {
6825 NewAttr = ::new (getASTContext())
6826 DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);
6827 }
6828 } else {
6829 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6830 }
6831
6832 NewAttr->setInherited(true);
6833 Member->addAttr(NewAttr);
6834
6835 if (MD) {
6836 // Propagate DLLAttr to friend re-declarations of MD that have already
6837 // been constructed.
6838 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
6839 FD = FD->getPreviousDecl()) {
6841 continue;
6842 assert(!getDLLAttr(FD) &&
6843 "friend re-decl should not already have a DLLAttr");
6844 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6845 NewAttr->setInherited(true);
6846 FD->addAttr(NewAttr);
6847 }
6848 }
6849 }
6850 }
6851
6852 if (ClassExported)
6853 DelayedDllExportClasses.push_back(Class);
6854}
6855
6857 CXXRecordDecl *Class, Attr *ClassAttr,
6858 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
6859 if (getDLLAttr(
6860 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
6861 // If the base class template has a DLL attribute, don't try to change it.
6862 return;
6863 }
6864
6865 auto TSK = BaseTemplateSpec->getSpecializationKind();
6866 if (!getDLLAttr(BaseTemplateSpec) &&
6868 TSK == TSK_ImplicitInstantiation)) {
6869 // The template hasn't been instantiated yet (or it has, but only as an
6870 // explicit instantiation declaration or implicit instantiation, which means
6871 // we haven't codegenned any members yet), so propagate the attribute.
6872 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6873 NewAttr->setInherited(true);
6874 BaseTemplateSpec->addAttr(NewAttr);
6875
6876 // If this was an import, mark that we propagated it from a derived class to
6877 // a base class template specialization.
6878 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
6879 ImportAttr->setPropagatedToBaseTemplate();
6880
6881 // If the template is already instantiated, checkDLLAttributeRedeclaration()
6882 // needs to be run again to work see the new attribute. Otherwise this will
6883 // get run whenever the template is instantiated.
6884 if (TSK != TSK_Undeclared)
6885 checkClassLevelDLLAttribute(BaseTemplateSpec);
6886
6887 return;
6888 }
6889
6890 if (getDLLAttr(BaseTemplateSpec)) {
6891 // The template has already been specialized or instantiated with an
6892 // attribute, explicitly or through propagation. We should not try to change
6893 // it.
6894 return;
6895 }
6896
6897 // The template was previously instantiated or explicitly specialized without
6898 // a dll attribute, It's too late for us to add an attribute, so warn that
6899 // this is unsupported.
6900 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
6901 << BaseTemplateSpec->isExplicitSpecialization();
6902 Diag(ClassAttr->getLocation(), diag::note_attribute);
6903 if (BaseTemplateSpec->isExplicitSpecialization()) {
6904 Diag(BaseTemplateSpec->getLocation(),
6905 diag::note_template_class_explicit_specialization_was_here)
6906 << BaseTemplateSpec;
6907 } else {
6908 Diag(BaseTemplateSpec->getPointOfInstantiation(),
6909 diag::note_template_class_instantiation_was_here)
6910 << BaseTemplateSpec;
6911 }
6912}
6913
6914namespace {
6915/// RAII object to restore the floating-point (FP) features active at the time
6916/// a defaulted function was declared. This ensures that the synthesized body
6917/// of the function respects the FP pragmas (e.g., #pragma STDC FENV_ACCESS)
6918/// that were in effect when the function was explicitly defaulted.
6919struct DefaultedFunctionFPFeaturesRAII {
6920 Sema::FPFeaturesStateRAII SavedFPFeatures;
6921 DefaultedFunctionFPFeaturesRAII(Sema &S, FunctionDecl *FD)
6922 : SavedFPFeatures(S) {
6923 auto *Info = FD->getDefaultedOrDeletedInfo();
6924 FPOptionsOverride FPO = Info ? Info->getFPFeatures() : FPOptionsOverride();
6926 S.FpPragmaStack.CurrentValue = FPO;
6927 }
6928
6929 ~DefaultedFunctionFPFeaturesRAII() = default;
6930};
6931} // namespace
6932
6934 SourceLocation DefaultLoc) {
6936 if (DFK.isComparison())
6937 return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison());
6938 if (DFK.isPostfixOperator())
6939 return S.DefineDefaultedPostfixOperator(DefaultLoc, FD,
6940 DFK.asPostfixOperator());
6941
6942 switch (DFK.asSpecialMember()) {
6946 break;
6949 break;
6952 break;
6955 break;
6958 break;
6961 break;
6963 llvm_unreachable("Invalid special member.");
6964 }
6965}
6966
6967/// Determine whether a type is permitted to be passed or returned in
6968/// registers, per C++ [class.temporary]p3.
6971 if (D->isDependentType() || D->isInvalidDecl())
6972 return false;
6973
6974 // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
6975 // The PS4 platform ABI follows the behavior of Clang 3.2.
6977 return !D->hasNonTrivialDestructorForCall() &&
6979
6980 if (CCK == TargetInfo::CCK_MicrosoftWin64) {
6981 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
6982 bool DtorIsTrivialForCall = false;
6983
6984 // If a class has at least one eligible, trivial copy constructor, it
6985 // is passed according to the C ABI. Otherwise, it is passed indirectly.
6986 //
6987 // Note: This permits classes with non-trivial copy or move ctors to be
6988 // passed in registers, so long as they *also* have a trivial copy ctor,
6989 // which is non-conforming.
6993 CopyCtorIsTrivial = true;
6995 CopyCtorIsTrivialForCall = true;
6996 }
6997 } else {
6998 for (const CXXConstructorDecl *CD : D->ctors()) {
6999 if (CD->isCopyConstructor() && !CD->isDeleted() &&
7000 !CD->isIneligibleOrNotSelected()) {
7001 if (CD->isTrivial())
7002 CopyCtorIsTrivial = true;
7003 if (CD->isTrivialForCall())
7004 CopyCtorIsTrivialForCall = true;
7005 }
7006 }
7007 }
7008
7009 if (D->needsImplicitDestructor()) {
7010 if (!D->defaultedDestructorIsDeleted() &&
7012 DtorIsTrivialForCall = true;
7013 } else if (const auto *DD = D->getDestructor()) {
7014 if (!DD->isDeleted() && DD->isTrivialForCall())
7015 DtorIsTrivialForCall = true;
7016 }
7017
7018 // If the copy ctor and dtor are both trivial-for-calls, pass direct.
7019 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
7020 return true;
7021
7022 // If a class has a destructor, we'd really like to pass it indirectly
7023 // because it allows us to elide copies. Unfortunately, MSVC makes that
7024 // impossible for small types, which it will pass in a single register or
7025 // stack slot. Most objects with dtors are large-ish, so handle that early.
7026 // We can't call out all large objects as being indirect because there are
7027 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
7028 // how we pass large POD types.
7029
7030 // Note: This permits small classes with nontrivial destructors to be
7031 // passed in registers, which is non-conforming.
7032 bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
7033 uint64_t TypeSize = isAArch64 ? 128 : 64;
7034
7035 if (CopyCtorIsTrivial && S.getASTContext().getTypeSize(
7036 S.Context.getCanonicalTagType(D)) <= TypeSize)
7037 return true;
7038 return false;
7039 }
7040
7041 // Per C++ [class.temporary]p3, the relevant condition is:
7042 // each copy constructor, move constructor, and destructor of X is
7043 // either trivial or deleted, and X has at least one non-deleted copy
7044 // or move constructor
7045 bool HasNonDeletedCopyOrMove = false;
7046
7050 return false;
7051 HasNonDeletedCopyOrMove = true;
7052 }
7053
7054 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
7057 return false;
7058 HasNonDeletedCopyOrMove = true;
7059 }
7060
7063 return false;
7064
7065 for (const CXXMethodDecl *MD : D->methods()) {
7066 if (MD->isDeleted() || MD->isIneligibleOrNotSelected())
7067 continue;
7068
7069 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
7070 if (CD && CD->isCopyOrMoveConstructor())
7071 HasNonDeletedCopyOrMove = true;
7072 else if (!isa<CXXDestructorDecl>(MD))
7073 continue;
7074
7075 if (!MD->isTrivialForCall())
7076 return false;
7077 }
7078
7079 return HasNonDeletedCopyOrMove;
7080}
7081
7082/// Report an error regarding overriding, along with any relevant
7083/// overridden methods.
7084///
7085/// \param DiagID the primary error to report.
7086/// \param MD the overriding method.
7087static bool
7088ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD,
7089 llvm::function_ref<bool(const CXXMethodDecl *)> Report) {
7090 bool IssuedDiagnostic = false;
7091 for (const CXXMethodDecl *O : MD->overridden_methods()) {
7092 if (Report(O)) {
7093 if (!IssuedDiagnostic) {
7094 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7095 IssuedDiagnostic = true;
7096 }
7097 S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
7098 }
7099 }
7100 return IssuedDiagnostic;
7101}
7102
7104 if (!Record)
7105 return;
7106
7107 if (Record->isAbstract() && !Record->isInvalidDecl()) {
7108 AbstractUsageInfo Info(*this, Record);
7110 }
7111
7112 // If this is not an aggregate type and has no user-declared constructor,
7113 // complain about any non-static data members of reference or const scalar
7114 // type, since they will never get initializers.
7115 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
7116 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
7117 !Record->isLambda()) {
7118 bool Complained = false;
7119 for (const auto *F : Record->fields()) {
7120 if (F->hasInClassInitializer() || F->isUnnamedBitField())
7121 continue;
7122
7123 if (F->getType()->isReferenceType() ||
7124 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
7125 if (!Complained) {
7126 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
7127 << Record->getTagKind() << Record;
7128 Complained = true;
7129 }
7130
7131 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
7132 << F->getType()->isReferenceType()
7133 << F->getDeclName();
7134 }
7135 }
7136 }
7137
7138 if (Record->getIdentifier()) {
7139 // C++ [class.mem]p13:
7140 // If T is the name of a class, then each of the following shall have a
7141 // name different from T:
7142 // - every member of every anonymous union that is a member of class T.
7143 //
7144 // C++ [class.mem]p14:
7145 // In addition, if class T has a user-declared constructor (12.1), every
7146 // non-static data member of class T shall have a name different from T.
7147 for (const NamedDecl *Element : Record->lookup(Record->getDeclName())) {
7148 const NamedDecl *D = Element->getUnderlyingDecl();
7149 // Invalid IndirectFieldDecls have already been diagnosed with
7150 // err_anonymous_record_member_redecl in
7151 // SemaDecl.cpp:CheckAnonMemberRedeclaration.
7153 Record->hasUserDeclaredConstructor()) ||
7154 (isa<IndirectFieldDecl>(D) && !D->isInvalidDecl())) {
7155 Diag(Element->getLocation(), diag::err_member_name_of_class)
7156 << D->getDeclName();
7157 break;
7158 }
7159 }
7160 }
7161
7162 // Warn if the class has virtual methods but non-virtual public destructor.
7163 if (Record->isPolymorphic() && !Record->isDependentType()) {
7164 CXXDestructorDecl *dtor = Record->getDestructor();
7165 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
7166 !Record->hasAttr<FinalAttr>())
7167 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
7168 diag::warn_non_virtual_dtor)
7169 << Context.getCanonicalTagType(Record);
7170 }
7171
7172 if (Record->isAbstract()) {
7173 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
7174 Diag(Record->getLocation(), diag::warn_abstract_final_class)
7175 << FA->isSpelledAsSealed();
7177 }
7178 }
7179
7180 // Warn if the class has a final destructor but is not itself marked final.
7181 if (!Record->hasAttr<FinalAttr>()) {
7182 if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
7183 if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
7184 Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class)
7185 << FA->isSpelledAsSealed()
7187 getLocForEndOfToken(Record->getLocation()),
7188 (FA->isSpelledAsSealed() ? " sealed" : " final"));
7189 Diag(Record->getLocation(),
7190 diag::note_final_dtor_non_final_class_silence)
7191 << Context.getCanonicalTagType(Record) << FA->isSpelledAsSealed();
7192 }
7193 }
7194 }
7195
7196 // See if trivial_abi has to be dropped.
7197 if (Record->hasAttr<TrivialABIAttr>())
7199
7200 // Set HasTrivialSpecialMemberForCall if the record has attribute
7201 // "trivial_abi".
7202 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
7203
7204 if (HasTrivialABI)
7205 Record->setHasTrivialSpecialMemberForCall();
7206
7207 // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=).
7208 // We check these last because they can depend on the properties of the
7209 // primary comparison functions (==, <=>).
7210 llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons;
7211
7212 // Perform checks that can't be done until we know all the properties of a
7213 // member function (whether it's defaulted, deleted, virtual, overriding,
7214 // ...).
7215 auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) {
7216 // A static function cannot override anything.
7217 if (MD->getStorageClass() == SC_Static) {
7218 if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD,
7219 [](const CXXMethodDecl *) { return true; }))
7220 return;
7221 }
7222
7223 // A deleted function cannot override a non-deleted function and vice
7224 // versa.
7225 if (ReportOverrides(*this,
7226 MD->isDeleted() ? diag::err_deleted_override
7227 : diag::err_non_deleted_override,
7228 MD, [&](const CXXMethodDecl *V) {
7229 return MD->isDeleted() != V->isDeleted();
7230 })) {
7231 if (MD->isDefaulted() && MD->isDeleted())
7232 // Explain why this defaulted function was deleted.
7234 return;
7235 }
7236
7237 // A consteval function cannot override a non-consteval function and vice
7238 // versa.
7239 if (ReportOverrides(*this,
7240 MD->isConsteval() ? diag::err_consteval_override
7241 : diag::err_non_consteval_override,
7242 MD, [&](const CXXMethodDecl *V) {
7243 return MD->isConsteval() != V->isConsteval();
7244 })) {
7245 if (MD->isDefaulted() && MD->isDeleted())
7246 // Explain why this defaulted function was deleted.
7248 return;
7249 }
7250 };
7251
7252 auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool {
7253 if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted())
7254 return false;
7255
7259 DefaultedSecondaryComparisons.push_back(FD);
7260 return true;
7261 }
7262
7264 return false;
7265 };
7266
7267 if (!Record->isInvalidDecl() &&
7268 Record->hasAttr<VTablePointerAuthenticationAttr>())
7270
7271 auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
7272 // Check whether the explicitly-defaulted members are valid.
7273 bool Incomplete = CheckForDefaultedFunction(M);
7274
7275 // Skip the rest of the checks for a member of a dependent class.
7276 if (Record->isDependentType())
7277 return;
7278
7279 // For an explicitly defaulted or deleted special member, we defer
7280 // determining triviality until the class is complete. That time is now!
7281 CXXSpecialMemberKind CSM = M->getSpecialMemberKind();
7282 if (!M->isImplicit() && !M->isUserProvided()) {
7283 if (CSM != CXXSpecialMemberKind::Invalid) {
7284 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
7285 // Inform the class that we've finished declaring this member.
7286 Record->finishedDefaultedOrDeletedMember(M);
7287 M->setTrivialForCall(
7288 HasTrivialABI ||
7291 Record->setTrivialForCallFlags(M);
7292 }
7293 }
7294
7295 // Set triviality for the purpose of calls if this is a user-provided
7296 // copy/move constructor or destructor.
7300 M->isUserProvided()) {
7301 M->setTrivialForCall(HasTrivialABI);
7302 Record->setTrivialForCallFlags(M);
7303 }
7304
7305 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
7306 M->hasAttr<DLLExportAttr>()) {
7307 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
7308 M->isTrivial() &&
7312 M->dropAttr<DLLExportAttr>();
7313
7314 if (M->hasAttr<DLLExportAttr>()) {
7315 // Define after any fields with in-class initializers have been parsed.
7317 }
7318 }
7319
7320 bool EffectivelyConstexprDestructor = true;
7321 // Avoid triggering vtable instantiation due to a dtor that is not
7322 // "effectively constexpr" for better compatibility.
7323 // See https://github.com/llvm/llvm-project/issues/102293 for more info.
7324 if (isa<CXXDestructorDecl>(M)) {
7325 llvm::SmallDenseSet<QualType> Visited;
7326 auto Check = [&Visited](QualType T, auto &&Check) -> bool {
7327 if (!Visited.insert(T->getCanonicalTypeUnqualified()).second)
7328 return false;
7329 const CXXRecordDecl *RD =
7330 T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
7331 if (!RD || !RD->isCompleteDefinition())
7332 return true;
7333
7334 if (!RD->hasConstexprDestructor())
7335 return false;
7336
7337 for (const CXXBaseSpecifier &B : RD->bases())
7338 if (!Check(B.getType(), Check))
7339 return false;
7340 for (const FieldDecl *FD : RD->fields())
7341 if (!Check(FD->getType(), Check))
7342 return false;
7343 return true;
7344 };
7345 EffectivelyConstexprDestructor =
7346 Check(Context.getCanonicalTagType(Record), Check);
7347 }
7348
7349 // Define defaulted constexpr virtual functions that override a base class
7350 // function right away.
7351 // FIXME: We can defer doing this until the vtable is marked as used.
7352 if (CSM != CXXSpecialMemberKind::Invalid && !M->isDeleted() &&
7353 M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods() &&
7354 EffectivelyConstexprDestructor)
7355 DefineDefaultedFunction(*this, M, M->getLocation());
7356
7357 if (!Incomplete)
7358 CheckCompletedMemberFunction(M);
7359 };
7360
7361 // Check the destructor before any other member function. We need to
7362 // determine whether it's trivial in order to determine whether the claas
7363 // type is a literal type, which is a prerequisite for determining whether
7364 // other special member functions are valid and whether they're implicitly
7365 // 'constexpr'.
7366 if (CXXDestructorDecl *Dtor = Record->getDestructor())
7367 CompleteMemberFunction(Dtor);
7368
7369 bool HasMethodWithOverrideControl = false,
7370 HasOverridingMethodWithoutOverrideControl = false;
7371 for (auto *D : Record->decls()) {
7372 if (auto *M = dyn_cast<CXXMethodDecl>(D)) {
7373 // FIXME: We could do this check for dependent types with non-dependent
7374 // bases.
7375 if (!Record->isDependentType()) {
7376 // See if a method overloads virtual methods in a base
7377 // class without overriding any.
7378 if (!M->isStatic())
7380
7381 if (M->hasAttr<OverrideAttr>()) {
7382 HasMethodWithOverrideControl = true;
7383 } else if (M->size_overridden_methods() > 0) {
7384 HasOverridingMethodWithoutOverrideControl = true;
7385 } else {
7386 // Warn on newly-declared virtual methods in `final` classes
7387 if (M->isVirtualAsWritten() && Record->isEffectivelyFinal()) {
7388 Diag(M->getLocation(), diag::warn_unnecessary_virtual_specifier)
7389 << M;
7390 }
7391 }
7392 }
7393
7394 if (!isa<CXXDestructorDecl>(M))
7395 CompleteMemberFunction(M);
7396 } else if (auto *F = dyn_cast<FriendDecl>(D)) {
7397 CheckForDefaultedFunction(
7398 dyn_cast_or_null<FunctionDecl>(F->getFriendDecl()));
7399 }
7400 }
7401
7402 if (HasOverridingMethodWithoutOverrideControl) {
7403 bool HasInconsistentOverrideControl = HasMethodWithOverrideControl;
7404 for (auto *M : Record->methods())
7405 DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl);
7406 }
7407
7408 // Check the defaulted secondary comparisons after any other member functions.
7409 for (FunctionDecl *FD : DefaultedSecondaryComparisons) {
7411
7412 // If this is a member function, we deferred checking it until now.
7413 if (auto *MD = dyn_cast<CXXMethodDecl>(FD))
7414 CheckCompletedMemberFunction(MD);
7415 }
7416
7417 // {ms,gcc}_struct is a request to change ABI rules to either follow
7418 // Microsoft or Itanium C++ ABI. However, even if these attributes are
7419 // present, we do not layout classes following foreign ABI rules, but
7420 // instead enter a special "compatibility mode", which only changes
7421 // alignments of fundamental types and layout of bit fields.
7422 // Check whether this class uses any C++ features that are implemented
7423 // completely differently in the requested ABI, and if so, emit a
7424 // diagnostic. That diagnostic defaults to an error, but we allow
7425 // projects to map it down to a warning (or ignore it). It's a fairly
7426 // common practice among users of the ms_struct pragma to
7427 // mass-annotate headers, sweeping up a bunch of types that the
7428 // project doesn't really rely on MSVC-compatible layout for. We must
7429 // therefore support "ms_struct except for C++ stuff" as a secondary
7430 // ABI.
7431 // Don't emit this diagnostic if the feature was enabled as a
7432 // language option (as opposed to via a pragma or attribute), as
7433 // the option -mms-bitfields otherwise essentially makes it impossible
7434 // to build C++ code, unless this diagnostic is turned off.
7435 if (Context.getLangOpts().getLayoutCompatibility() ==
7437 Record->isMsStruct(Context) != Context.defaultsToMsStruct() &&
7438 (Record->isPolymorphic() || Record->getNumBases())) {
7439 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
7440 }
7441
7444
7445 bool ClangABICompat4 =
7446 Context.getLangOpts().isCompatibleWith(LangOptions::ClangABI::Ver4);
7448 Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
7449 bool CanPass = canPassInRegisters(*this, Record, CCK);
7450
7451 // Do not change ArgPassingRestrictions if it has already been set to
7452 // RecordArgPassingKind::CanNeverPassInRegs.
7453 if (Record->getArgPassingRestrictions() !=
7455 Record->setArgPassingRestrictions(
7458
7459 // If canPassInRegisters returns true despite the record having a non-trivial
7460 // destructor, the record is destructed in the callee. This happens only when
7461 // the record or one of its subobjects has a field annotated with trivial_abi
7462 // or a field qualified with ObjC __strong/__weak.
7463 if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
7464 Record->setParamDestroyedInCallee(true);
7465 else if (Record->hasNonTrivialDestructor())
7466 Record->setParamDestroyedInCallee(CanPass);
7467
7468 if (getLangOpts().ForceEmitVTables) {
7469 // If we want to emit all the vtables, we need to mark it as used. This
7470 // is especially required for cases like vtable assumption loads.
7471 MarkVTableUsed(Record->getInnerLocStart(), Record);
7472 }
7473
7474 if (getLangOpts().CUDA) {
7475 if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>())
7477 else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>())
7479 }
7480
7481 llvm::SmallDenseMap<OverloadedOperatorKind,
7483 TypeAwareDecls{{OO_New, {}},
7484 {OO_Array_New, {}},
7485 {OO_Delete, {}},
7486 {OO_Array_New, {}}};
7487 for (auto *D : Record->decls()) {
7488 const FunctionDecl *FnDecl = D->getAsFunction();
7489 if (!FnDecl || !FnDecl->isTypeAwareOperatorNewOrDelete())
7490 continue;
7491 assert(FnDecl->getDeclName().isAnyOperatorNewOrDelete());
7492 TypeAwareDecls[FnDecl->getOverloadedOperator()].push_back(FnDecl);
7493 }
7494 auto CheckMismatchedTypeAwareAllocators =
7495 [this, &TypeAwareDecls, Record](OverloadedOperatorKind NewKind,
7496 OverloadedOperatorKind DeleteKind) {
7497 auto &NewDecls = TypeAwareDecls[NewKind];
7498 auto &DeleteDecls = TypeAwareDecls[DeleteKind];
7499 if (NewDecls.empty() == DeleteDecls.empty())
7500 return;
7501 DeclarationName FoundOperator =
7502 Context.DeclarationNames.getCXXOperatorName(
7503 NewDecls.empty() ? DeleteKind : NewKind);
7504 DeclarationName MissingOperator =
7505 Context.DeclarationNames.getCXXOperatorName(
7506 NewDecls.empty() ? NewKind : DeleteKind);
7507 Diag(Record->getLocation(),
7508 diag::err_type_aware_allocator_missing_matching_operator)
7509 << FoundOperator << Context.getCanonicalTagType(Record)
7510 << MissingOperator;
7511 for (auto MD : NewDecls)
7512 Diag(MD->getLocation(),
7513 diag::note_unmatched_type_aware_allocator_declared)
7514 << MD;
7515 for (auto MD : DeleteDecls)
7516 Diag(MD->getLocation(),
7517 diag::note_unmatched_type_aware_allocator_declared)
7518 << MD;
7519 };
7520 CheckMismatchedTypeAwareAllocators(OO_New, OO_Delete);
7521 CheckMismatchedTypeAwareAllocators(OO_Array_New, OO_Array_Delete);
7522}
7523
7524/// Look up the special member function that would be called by a special
7525/// member function for a subobject of class type.
7526///
7527/// \param Class The class type of the subobject.
7528/// \param CSM The kind of special member function.
7529/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
7530/// \param ConstRHS True if this is a copy operation with a const object
7531/// on its RHS, that is, if the argument to the outer special member
7532/// function is 'const' and this is not a field marked 'mutable'.
7535 CXXSpecialMemberKind CSM, unsigned FieldQuals,
7536 bool ConstRHS) {
7537 unsigned LHSQuals = 0;
7540 LHSQuals = FieldQuals;
7541
7542 unsigned RHSQuals = FieldQuals;
7545 RHSQuals = 0;
7546 else if (ConstRHS)
7547 RHSQuals |= Qualifiers::Const;
7548
7549 return S.LookupSpecialMember(Class, CSM,
7550 RHSQuals & Qualifiers::Const,
7551 RHSQuals & Qualifiers::Volatile,
7552 false,
7553 LHSQuals & Qualifiers::Const,
7554 LHSQuals & Qualifiers::Volatile);
7555}
7556
7558 Sema &S;
7559 SourceLocation UseLoc;
7560
7561 /// A mapping from the base classes through which the constructor was
7562 /// inherited to the using shadow declaration in that base class (or a null
7563 /// pointer if the constructor was declared in that base class).
7564 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
7565 InheritedFromBases;
7566
7567public:
7570 : S(S), UseLoc(UseLoc) {
7571 bool DiagnosedMultipleConstructedBases = false;
7572 CXXRecordDecl *ConstructedBase = nullptr;
7573 BaseUsingDecl *ConstructedBaseIntroducer = nullptr;
7574
7575 // Find the set of such base class subobjects and check that there's a
7576 // unique constructed subobject.
7577 for (auto *D : Shadow->redecls()) {
7578 auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
7579 auto *DNominatedBase = DShadow->getNominatedBaseClass();
7580 auto *DConstructedBase = DShadow->getConstructedBaseClass();
7581
7582 InheritedFromBases.insert(
7583 std::make_pair(DNominatedBase->getCanonicalDecl(),
7584 DShadow->getNominatedBaseClassShadowDecl()));
7585 if (DShadow->constructsVirtualBase())
7586 InheritedFromBases.insert(
7587 std::make_pair(DConstructedBase->getCanonicalDecl(),
7588 DShadow->getConstructedBaseClassShadowDecl()));
7589 else
7590 assert(DNominatedBase == DConstructedBase);
7591
7592 // [class.inhctor.init]p2:
7593 // If the constructor was inherited from multiple base class subobjects
7594 // of type B, the program is ill-formed.
7595 if (!ConstructedBase) {
7596 ConstructedBase = DConstructedBase;
7597 ConstructedBaseIntroducer = D->getIntroducer();
7598 } else if (ConstructedBase != DConstructedBase &&
7599 !Shadow->isInvalidDecl()) {
7600 if (!DiagnosedMultipleConstructedBases) {
7601 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
7602 << Shadow->getTargetDecl();
7603 S.Diag(ConstructedBaseIntroducer->getLocation(),
7604 diag::note_ambiguous_inherited_constructor_using)
7605 << ConstructedBase;
7606 DiagnosedMultipleConstructedBases = true;
7607 }
7608 S.Diag(D->getIntroducer()->getLocation(),
7609 diag::note_ambiguous_inherited_constructor_using)
7610 << DConstructedBase;
7611 }
7612 }
7613
7614 if (DiagnosedMultipleConstructedBases)
7615 Shadow->setInvalidDecl();
7616 }
7617
7618 /// Find the constructor to use for inherited construction of a base class,
7619 /// and whether that base class constructor inherits the constructor from a
7620 /// virtual base class (in which case it won't actually invoke it).
7621 std::pair<CXXConstructorDecl *, bool>
7623 auto It = InheritedFromBases.find(Base->getCanonicalDecl());
7624 if (It == InheritedFromBases.end())
7625 return std::make_pair(nullptr, false);
7626
7627 // This is an intermediary class.
7628 if (It->second)
7629 return std::make_pair(
7630 S.findInheritingConstructor(UseLoc, Ctor, It->second),
7631 It->second->constructsVirtualBase());
7632
7633 // This is the base class from which the constructor was inherited.
7634 return std::make_pair(Ctor, false);
7635 }
7636};
7637
7638/// Is the special member function which would be selected to perform the
7639/// specified operation on the specified class type a constexpr constructor?
7641 Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, unsigned Quals,
7642 bool ConstRHS, CXXConstructorDecl *InheritedCtor = nullptr,
7643 Sema::InheritedConstructorInfo *Inherited = nullptr) {
7644 // Suppress duplicate constraint checking here, in case a constraint check
7645 // caused us to decide to do this. Any truely recursive checks will get
7646 // caught during these checks anyway.
7648
7649 // If we're inheriting a constructor, see if we need to call it for this base
7650 // class.
7651 if (InheritedCtor) {
7653 auto BaseCtor =
7654 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
7655 if (BaseCtor)
7656 return BaseCtor->isConstexpr();
7657 }
7658
7660 return ClassDecl->hasConstexprDefaultConstructor();
7662 return ClassDecl->hasConstexprDestructor();
7663
7665 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
7666 if (!SMOR.getMethod())
7667 // A constructor we wouldn't select can't be "involved in initializing"
7668 // anything.
7669 return true;
7670 return SMOR.getMethod()->isConstexpr();
7671}
7672
7673/// Determine whether the specified special member function would be constexpr
7674/// if it were implicitly defined.
7676 Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, bool ConstArg,
7677 CXXConstructorDecl *InheritedCtor = nullptr,
7678 Sema::InheritedConstructorInfo *Inherited = nullptr) {
7679 if (!S.getLangOpts().CPlusPlus11)
7680 return false;
7681
7682 // C++11 [dcl.constexpr]p4:
7683 // In the definition of a constexpr constructor [...]
7684 bool Ctor = true;
7685 switch (CSM) {
7687 if (Inherited)
7688 break;
7689 // Since default constructor lookup is essentially trivial (and cannot
7690 // involve, for instance, template instantiation), we compute whether a
7691 // defaulted default constructor is constexpr directly within CXXRecordDecl.
7692 //
7693 // This is important for performance; we need to know whether the default
7694 // constructor is constexpr to determine whether the type is a literal type.
7695 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
7696
7699 // For copy or move constructors, we need to perform overload resolution.
7700 break;
7701
7704 if (!S.getLangOpts().CPlusPlus14)
7705 return false;
7706 // In C++1y, we need to perform overload resolution.
7707 Ctor = false;
7708 break;
7709
7711 return ClassDecl->defaultedDestructorIsConstexpr();
7712
7714 return false;
7715 }
7716
7717 // -- if the class is a non-empty union, or for each non-empty anonymous
7718 // union member of a non-union class, exactly one non-static data member
7719 // shall be initialized; [DR1359]
7720 //
7721 // If we squint, this is guaranteed, since exactly one non-static data member
7722 // will be initialized (if the constructor isn't deleted), we just don't know
7723 // which one.
7724 if (Ctor && ClassDecl->isUnion())
7726 ? ClassDecl->hasInClassInitializer() ||
7727 !ClassDecl->hasVariantMembers()
7728 : true;
7729
7730 // -- the class shall not have any virtual base classes;
7731 if (!S.getLangOpts().CPlusPlus26 && Ctor && ClassDecl->getNumVBases())
7732 return false;
7733
7734 // C++1y [class.copy]p26:
7735 // -- [the class] is a literal type, and
7736 if (!S.getLangOpts().CPlusPlus23 && !Ctor && !ClassDecl->isLiteral())
7737 return false;
7738
7739 // -- every constructor involved in initializing [...] base class
7740 // sub-objects shall be a constexpr constructor;
7741 // -- the assignment operator selected to copy/move each direct base
7742 // class is a constexpr function, and
7743 if (!S.getLangOpts().CPlusPlus23) {
7744 for (const auto &B : ClassDecl->bases()) {
7745 auto *BaseClassDecl = B.getType()->getAsCXXRecordDecl();
7746 if (!BaseClassDecl)
7747 continue;
7748 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
7749 InheritedCtor, Inherited))
7750 return false;
7751 }
7752 }
7753
7754 // -- every constructor involved in initializing non-static data members
7755 // [...] shall be a constexpr constructor;
7756 // -- every non-static data member and base class sub-object shall be
7757 // initialized
7758 // -- for each non-static data member of X that is of class type (or array
7759 // thereof), the assignment operator selected to copy/move that member is
7760 // a constexpr function
7761 if (!S.getLangOpts().CPlusPlus23) {
7762 for (const auto *F : ClassDecl->fields()) {
7763 if (F->isInvalidDecl())
7764 continue;
7766 F->hasInClassInitializer())
7767 continue;
7768 QualType BaseType = S.Context.getBaseElementType(F->getType());
7769 if (const RecordType *RecordTy = BaseType->getAsCanonical<RecordType>()) {
7770 auto *FieldRecDecl =
7771 cast<CXXRecordDecl>(RecordTy->getDecl())->getDefinitionOrSelf();
7772 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
7773 BaseType.getCVRQualifiers(),
7774 ConstArg && !F->isMutable()))
7775 return false;
7776 } else if (CSM == CXXSpecialMemberKind::DefaultConstructor) {
7777 return false;
7778 }
7779 }
7780 }
7781
7782 // All OK, it's constexpr!
7783 return true;
7784}
7785
7786namespace {
7787/// RAII object to register a defaulted function as having its exception
7788/// specification computed.
7789struct ComputingExceptionSpec {
7790 Sema &S;
7791
7792 ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc)
7793 : S(S) {
7794 Sema::CodeSynthesisContext Ctx;
7796 Ctx.PointOfInstantiation = Loc;
7797 Ctx.Entity = FD;
7799 }
7800 ~ComputingExceptionSpec() {
7802 }
7803};
7804}
7805
7806static Sema::ImplicitExceptionSpecification
7807ComputeDefaultedSpecialMemberExceptionSpec(Sema &S, SourceLocation Loc,
7808 CXXMethodDecl *MD,
7810 Sema::InheritedConstructorInfo *ICI);
7811
7812static Sema::ImplicitExceptionSpecification
7813ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
7814 FunctionDecl *FD,
7816
7817static Sema::ImplicitExceptionSpecification
7818ComputeDefaultedPostfixOperatorExceptionSpec(Sema &S, SourceLocation Loc,
7819 FunctionDecl *FD,
7820 PostfixOperatorKind Kind);
7821
7822static Sema::ImplicitExceptionSpecification
7824 auto DFK = FD->getDefaultedFunctionKind();
7825 if (DFK.isSpecialMember())
7827 S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr);
7828 if (DFK.isComparison())
7830 DFK.asComparison());
7831 if (DFK.isPostfixOperator())
7833 S, Loc, FD, DFK.asPostfixOperator());
7834
7835 auto *CD = cast<CXXConstructorDecl>(FD);
7836 assert(CD->getInheritedConstructor() &&
7837 "only defaulted functions and inherited constructors have implicit "
7838 "exception specs");
7840 S, Loc, CD->getInheritedConstructor().getShadowDecl());
7843}
7844
7846 CXXMethodDecl *MD) {
7848
7849 // Build an exception specification pointing back at this member.
7851 EPI.ExceptionSpec.SourceDecl = MD;
7852
7853 // Set the calling convention to the default for C++ instance methods.
7855 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
7856 /*IsCXXMethod=*/true));
7857 return EPI;
7858}
7859
7861 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
7863 return;
7864
7865 // Evaluate the exception specification.
7866 auto IES = computeImplicitExceptionSpec(*this, Loc, FD);
7867 auto ESI = IES.getExceptionSpec();
7868
7869 // Update the type of the special member to use it.
7870 UpdateExceptionSpec(FD, ESI);
7871}
7872
7874 assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted");
7875
7877 if (!DefKind) {
7878 assert(FD->getDeclContext()->isDependentContext());
7879 return;
7880 }
7881
7882 if (DefKind.isComparison()) {
7883 auto PT = FD->getParamDecl(0)->getType();
7884 if (const CXXRecordDecl *RD =
7885 PT.getNonReferenceType()->getAsCXXRecordDecl()) {
7886 for (FieldDecl *Field : RD->fields()) {
7887 UnusedPrivateFields.remove(Field);
7888 }
7889 }
7890 }
7891
7892 if (DefKind.isPostfixOperator()) {
7894 DefKind.asPostfixOperator()))
7895 FD->setInvalidDecl();
7896 return;
7897 }
7898
7899 if (DefKind.isSpecialMember()
7901 DefKind.asSpecialMember(),
7902 FD->getDefaultLoc())
7904 FD->setInvalidDecl();
7905}
7906
7909 SourceLocation DefaultLoc) {
7910 CXXRecordDecl *RD = MD->getParent();
7911
7913 "not an explicitly-defaulted special member");
7914
7915 // Defer all checking for special members of a dependent type.
7916 if (RD->isDependentType())
7917 return false;
7918
7919 // Whether this was the first-declared instance of the constructor.
7920 // This affects whether we implicitly add an exception spec and constexpr.
7921 bool First = MD == MD->getCanonicalDecl();
7922
7923 bool HadError = false;
7924
7925 // C++11 [dcl.fct.def.default]p1:
7926 // A function that is explicitly defaulted shall
7927 // -- be a special member function [...] (checked elsewhere),
7928 // -- have the same type (except for ref-qualifiers, and except that a
7929 // copy operation can take a non-const reference) as an implicit
7930 // declaration, and
7931 // -- not have default arguments.
7932 // C++2a changes the second bullet to instead delete the function if it's
7933 // defaulted on its first declaration, unless it's "an assignment operator,
7934 // and its return type differs or its parameter type is not a reference".
7935 bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First;
7936 bool ShouldDeleteForTypeMismatch = false;
7937 unsigned ExpectedParams = 1;
7940 ExpectedParams = 0;
7941 if (MD->getNumExplicitParams() != ExpectedParams) {
7942 // This checks for default arguments: a copy or move constructor with a
7943 // default argument is classified as a default constructor, and assignment
7944 // operations and destructors can't have default arguments.
7945 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
7946 << CSM << MD->getSourceRange();
7947 HadError = true;
7948 } else if (MD->isVariadic()) {
7949 if (DeleteOnTypeMismatch)
7950 ShouldDeleteForTypeMismatch = true;
7951 else {
7952 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
7953 << CSM << MD->getSourceRange();
7954 HadError = true;
7955 }
7956 }
7957
7959
7960 bool CanHaveConstParam = false;
7962 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
7964 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
7965
7966 QualType ReturnType = Context.VoidTy;
7969 // Check for return type matching.
7970 ReturnType = Type->getReturnType();
7972
7973 QualType DeclType =
7975 /*Qualifier=*/std::nullopt, RD, /*OwnsTag=*/false);
7976 DeclType = Context.getAddrSpaceQualType(
7977 DeclType, ThisType.getQualifiers().getAddressSpace());
7978 QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
7979
7980 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
7981 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
7983 << ExpectedReturnType;
7984 HadError = true;
7985 }
7986
7987 // A defaulted special member cannot have cv-qualifiers.
7988 if (ThisType.isConstQualified() || ThisType.isVolatileQualified()) {
7989 if (DeleteOnTypeMismatch)
7990 ShouldDeleteForTypeMismatch = true;
7991 else {
7992 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
7994 << getLangOpts().CPlusPlus14;
7995 HadError = true;
7996 }
7997 }
7998 // [C++23][dcl.fct.def.default]/p2.2
7999 // if F2 has an implicit object parameter of type “reference to C”,
8000 // F1 may be an explicit object member function whose explicit object
8001 // parameter is of (possibly different) type “reference to C”,
8002 // in which case the type of F1 would differ from the type of F2
8003 // in that the type of F1 has an additional parameter;
8004 QualType ExplicitObjectParameter = MD->isExplicitObjectMemberFunction()
8005 ? MD->getParamDecl(0)->getType()
8006 : QualType();
8007 if (!ExplicitObjectParameter.isNull() &&
8008 (!ExplicitObjectParameter->isReferenceType() ||
8009 !Context.hasSameType(ExplicitObjectParameter.getNonReferenceType(),
8010 Context.getCanonicalTagType(RD)))) {
8011 if (DeleteOnTypeMismatch)
8012 ShouldDeleteForTypeMismatch = true;
8013 else {
8014 Diag(MD->getLocation(),
8015 diag::err_defaulted_special_member_explicit_object_mismatch)
8016 << (CSM == CXXSpecialMemberKind::MoveAssignment) << RD
8017 << MD->getSourceRange();
8018 HadError = true;
8019 }
8020 }
8021 }
8022
8023 // Check for parameter type matching.
8025 ExpectedParams
8026 ? Type->getParamType(MD->isExplicitObjectMemberFunction() ? 1 : 0)
8027 : QualType();
8028 bool HasConstParam = false;
8029 if (ExpectedParams && ArgType->isReferenceType()) {
8030 // Argument must be reference to possibly-const T.
8031 QualType ReferentType = ArgType->getPointeeType();
8032 HasConstParam = ReferentType.isConstQualified();
8033
8034 if (ReferentType.isVolatileQualified()) {
8035 if (DeleteOnTypeMismatch)
8036 ShouldDeleteForTypeMismatch = true;
8037 else {
8038 Diag(MD->getLocation(),
8039 diag::err_defaulted_special_member_volatile_param)
8040 << CSM;
8041 HadError = true;
8042 }
8043 }
8044
8045 if (HasConstParam && !CanHaveConstParam) {
8046 if (DeleteOnTypeMismatch)
8047 ShouldDeleteForTypeMismatch = true;
8048 else if (CSM == CXXSpecialMemberKind::CopyConstructor ||
8050 Diag(MD->getLocation(),
8051 diag::err_defaulted_special_member_copy_const_param)
8053 // FIXME: Explain why this special member can't be const.
8054 HadError = true;
8055 } else {
8056 Diag(MD->getLocation(),
8057 diag::err_defaulted_special_member_move_const_param)
8059 HadError = true;
8060 }
8061 }
8062 } else if (ExpectedParams) {
8063 // A copy assignment operator can take its argument by value, but a
8064 // defaulted one cannot.
8066 "unexpected non-ref argument");
8067 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
8068 HadError = true;
8069 }
8070
8071 // C++11 [dcl.fct.def.default]p2:
8072 // An explicitly-defaulted function may be declared constexpr only if it
8073 // would have been implicitly declared as constexpr,
8074 // Do not apply this rule to members of class templates, since core issue 1358
8075 // makes such functions always instantiate to constexpr functions. For
8076 // functions which cannot be constexpr (for non-constructors in C++11 and for
8077 // destructors in C++14 and C++17), this is checked elsewhere.
8078 //
8079 // FIXME: This should not apply if the member is deleted.
8080 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
8081 HasConstParam);
8082
8083 // C++14 [dcl.constexpr]p6 (CWG DR647/CWG DR1358):
8084 // If the instantiated template specialization of a constexpr function
8085 // template or member function of a class template would fail to satisfy
8086 // the requirements for a constexpr function or constexpr constructor, that
8087 // specialization is still a constexpr function or constexpr constructor,
8088 // even though a call to such a function cannot appear in a constant
8089 // expression.
8090 if (MD->isTemplateInstantiation() && MD->isConstexpr())
8091 Constexpr = true;
8092
8093 if ((getLangOpts().CPlusPlus20 ||
8095 : isa<CXXConstructorDecl>(MD))) &&
8096 MD->isConstexpr() && !Constexpr &&
8098 if (!MD->isConsteval() && RD->getNumVBases()) {
8099 Diag(MD->getBeginLoc(),
8100 diag::err_incorrect_defaulted_constexpr_with_vb)
8101 << CSM;
8102 for (const auto &I : RD->vbases())
8103 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here);
8104 } else {
8105 Diag(MD->getBeginLoc(), diag::err_incorrect_defaulted_constexpr)
8106 << CSM << MD->isConsteval();
8107 }
8108 HadError = true;
8109 // FIXME: Explain why the special member can't be constexpr.
8110 }
8111 if (First) {
8112 // C++2a [dcl.fct.def.default]p3:
8113 // If a function is explicitly defaulted on its first declaration, it is
8114 // implicitly considered to be constexpr if the implicit declaration
8115 // would be.
8120
8121 if (!Type->hasExceptionSpec()) {
8122 // C++2a [except.spec]p3:
8123 // If a declaration of a function does not have a noexcept-specifier
8124 // [and] is defaulted on its first declaration, [...] the exception
8125 // specification is as specified below
8126 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
8128 EPI.ExceptionSpec.SourceDecl = MD;
8129 MD->setType(
8130 Context.getFunctionType(ReturnType, Type->getParamTypes(), EPI));
8131 }
8132 }
8133
8134 if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
8135 if (First) {
8136 SetDeclDeleted(MD, MD->getLocation());
8137 if (!inTemplateInstantiation() && !HadError) {
8138 Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
8139 if (ShouldDeleteForTypeMismatch) {
8140 Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
8141 } else if (ShouldDeleteSpecialMember(MD, CSM, nullptr,
8142 /*Diagnose*/ true) &&
8143 DefaultLoc.isValid()) {
8144 Diag(DefaultLoc, diag::note_replace_equals_default_to_delete)
8145 << FixItHint::CreateReplacement(DefaultLoc, "delete");
8146 }
8147 }
8148 if (ShouldDeleteForTypeMismatch && !HadError) {
8149 Diag(MD->getLocation(),
8150 diag::warn_cxx17_compat_defaulted_method_type_mismatch)
8151 << CSM;
8152 }
8153 } else {
8154 // C++11 [dcl.fct.def.default]p4:
8155 // [For a] user-provided explicitly-defaulted function [...] if such a
8156 // function is implicitly defined as deleted, the program is ill-formed.
8157 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
8158 assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
8159 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
8160 HadError = true;
8161 }
8162 }
8163
8164 return HadError;
8165}
8166
8167namespace {
8168/// Helper class for building and checking a defaulted comparison.
8169///
8170/// Defaulted functions are built in two phases:
8171///
8172/// * First, the set of operations that the function will perform are
8173/// identified, and some of them are checked. If any of the checked
8174/// operations is invalid in certain ways, the comparison function is
8175/// defined as deleted and no body is built.
8176/// * Then, if the function is not defined as deleted, the body is built.
8177///
8178/// This is accomplished by performing two visitation steps over the eventual
8179/// body of the function.
8180template<typename Derived, typename ResultList, typename Result,
8181 typename Subobject>
8182class DefaultedComparisonVisitor {
8183public:
8184 DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8186 : S(S), RD(RD), FD(FD), DCK(DCK) {
8187 if (auto *Info = FD->getDefaultedOrDeletedInfo()) {
8188 // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an
8189 // UnresolvedSet to avoid this copy.
8190 Fns.assign(Info->getUnqualifiedLookups().begin(),
8191 Info->getUnqualifiedLookups().end());
8192 }
8193 }
8194
8195 ResultList visit() {
8196 // The type of an lvalue naming a parameter of this function.
8197 QualType ParamLvalType =
8199
8200 ResultList Results;
8201
8202 switch (DCK) {
8204 llvm_unreachable("not a defaulted comparison");
8205
8208 getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers());
8209 return Results;
8210
8213 Results.add(getDerived().visitExpandedSubobject(
8214 ParamLvalType, getDerived().getCompleteObject()));
8215 return Results;
8216 }
8217 llvm_unreachable("");
8218 }
8219
8220protected:
8221 Derived &getDerived() { return static_cast<Derived&>(*this); }
8222
8223 /// Visit the expanded list of subobjects of the given type, as specified in
8224 /// C++2a [class.compare.default].
8225 ///
8226 /// \return \c true if the ResultList object said we're done, \c false if not.
8227 bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record,
8228 Qualifiers Quals) {
8229 // C++2a [class.compare.default]p4:
8230 // The direct base class subobjects of C
8231 for (CXXBaseSpecifier &Base : Record->bases())
8232 if (Results.add(getDerived().visitSubobject(
8233 S.Context.getQualifiedType(Base.getType(), Quals),
8234 getDerived().getBase(&Base))))
8235 return true;
8236
8237 // followed by the non-static data members of C
8238 for (FieldDecl *Field : Record->fields()) {
8239 // C++23 [class.bit]p2:
8240 // Unnamed bit-fields are not members ...
8241 if (Field->isUnnamedBitField())
8242 continue;
8243 if (Field->isInvalidDecl())
8244 continue;
8245 // Recursively expand anonymous structs.
8246 if (Field->isAnonymousStructOrUnion()) {
8247 if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(),
8248 Quals))
8249 return true;
8250 continue;
8251 }
8252
8253 // Figure out the type of an lvalue denoting this field.
8254 Qualifiers FieldQuals = Quals;
8255 if (Field->isMutable())
8256 FieldQuals.removeConst();
8257 QualType FieldType =
8258 S.Context.getQualifiedType(Field->getType(), FieldQuals);
8259
8260 if (Results.add(getDerived().visitSubobject(
8261 FieldType, getDerived().getField(Field))))
8262 return true;
8263 }
8264
8265 // form a list of subobjects.
8266 return false;
8267 }
8268
8269 Result visitSubobject(QualType Type, Subobject Subobj) {
8270 // In that list, any subobject of array type is recursively expanded
8271 const ArrayType *AT = S.Context.getAsArrayType(Type);
8272 if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT))
8273 return getDerived().visitSubobjectArray(CAT->getElementType(),
8274 CAT->getSize(), Subobj);
8275 return getDerived().visitExpandedSubobject(Type, Subobj);
8276 }
8277
8278 Result visitSubobjectArray(QualType Type, const llvm::APInt &Size,
8279 Subobject Subobj) {
8280 return getDerived().visitSubobject(Type, Subobj);
8281 }
8282
8283protected:
8284 Sema &S;
8285 CXXRecordDecl *RD;
8286 FunctionDecl *FD;
8288 UnresolvedSet<16> Fns;
8289};
8290
8291/// Information about a defaulted comparison, as determined by
8292/// DefaultedComparisonAnalyzer.
8293struct DefaultedComparisonInfo {
8294 bool Deleted = false;
8295 bool Constexpr = true;
8296 ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering;
8297
8298 static DefaultedComparisonInfo deleted() {
8299 DefaultedComparisonInfo Deleted;
8300 Deleted.Deleted = true;
8301 return Deleted;
8302 }
8303
8304 bool add(const DefaultedComparisonInfo &R) {
8305 Deleted |= R.Deleted;
8306 Constexpr &= R.Constexpr;
8307 Category = commonComparisonType(Category, R.Category);
8308 return Deleted;
8309 }
8310};
8311
8312/// An element in the expanded list of subobjects of a defaulted comparison, as
8313/// specified in C++2a [class.compare.default]p4.
8314struct DefaultedComparisonSubobject {
8315 enum { CompleteObject, Member, Base } Kind;
8316 NamedDecl *Decl;
8317 SourceLocation Loc;
8318};
8319
8320/// A visitor over the notional body of a defaulted comparison that determines
8321/// whether that body would be deleted or constexpr.
8322class DefaultedComparisonAnalyzer
8323 : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer,
8324 DefaultedComparisonInfo,
8325 DefaultedComparisonInfo,
8326 DefaultedComparisonSubobject> {
8327public:
8328 enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr };
8329
8330private:
8331 DiagnosticKind Diagnose;
8332
8333public:
8334 using Base = DefaultedComparisonVisitor;
8335 using Result = DefaultedComparisonInfo;
8336 using Subobject = DefaultedComparisonSubobject;
8337
8338 friend Base;
8339
8340 DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8342 DiagnosticKind Diagnose = NoDiagnostics)
8343 : Base(S, RD, FD, DCK), Diagnose(Diagnose) {}
8344
8345 Result visit() {
8346 if ((DCK == DefaultedComparisonKind::Equal ||
8347 DCK == DefaultedComparisonKind::ThreeWay) &&
8348 RD->hasVariantMembers()) {
8349 // C++2a [class.compare.default]p2 [P2002R0]:
8350 // A defaulted comparison operator function for class C is defined as
8351 // deleted if [...] C has variant members.
8352 if (Diagnose == ExplainDeleted) {
8353 S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union)
8354 << FD << RD->isUnion() << RD;
8355 }
8356 return Result::deleted();
8357 }
8358
8359 return Base::visit();
8360 }
8361
8362private:
8363 Subobject getCompleteObject() {
8364 return Subobject{Subobject::CompleteObject, RD, FD->getLocation()};
8365 }
8366
8367 Subobject getBase(CXXBaseSpecifier *Base) {
8368 return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(),
8369 Base->getBaseTypeLoc()};
8370 }
8371
8372 Subobject getField(FieldDecl *Field) {
8373 return Subobject{Subobject::Member, Field, Field->getLocation()};
8374 }
8375
8376 Result visitExpandedSubobject(QualType Type, Subobject Subobj) {
8377 // C++2a [class.compare.default]p2 [P2002R0]:
8378 // A defaulted <=> or == operator function for class C is defined as
8379 // deleted if any non-static data member of C is of reference type
8380 if (Type->isReferenceType()) {
8381 if (Diagnose == ExplainDeleted) {
8382 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member)
8383 << FD << RD;
8384 }
8385 return Result::deleted();
8386 }
8387
8388 // [...] Let xi be an lvalue denoting the ith element [...]
8389 OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue);
8390 Expr *Args[] = {&Xi, &Xi};
8391
8392 // All operators start by trying to apply that same operator recursively.
8394 assert(OO != OO_None && "not an overloaded operator!");
8395 return visitBinaryOperator(OO, Args, Subobj);
8396 }
8397
8398 Result
8399 visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args,
8400 Subobject Subobj,
8401 OverloadCandidateSet *SpaceshipCandidates = nullptr) {
8402 // Note that there is no need to consider rewritten candidates here if
8403 // we've already found there is no viable 'operator<=>' candidate (and are
8404 // considering synthesizing a '<=>' from '==' and '<').
8405 OverloadCandidateSet CandidateSet(
8407 OverloadCandidateSet::OperatorRewriteInfo(
8408 OO, FD->getLocation(),
8409 /*AllowRewrittenCandidates=*/!SpaceshipCandidates));
8410
8411 /// C++2a [class.compare.default]p1 [P2002R0]:
8412 /// [...] the defaulted function itself is never a candidate for overload
8413 /// resolution [...]
8414 CandidateSet.exclude(FD);
8415
8416 if (Args[0]->getType()->isOverloadableType())
8417 S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args);
8418 else
8419 // FIXME: We determine whether this is a valid expression by checking to
8420 // see if there's a viable builtin operator candidate for it. That isn't
8421 // really what the rules ask us to do, but should give the right results.
8422 S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet);
8423
8424 Result R;
8425
8427 switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) {
8428 case OR_Success: {
8429 // C++2a [class.compare.secondary]p2 [P2002R0]:
8430 // The operator function [...] is defined as deleted if [...] the
8431 // candidate selected by overload resolution is not a rewritten
8432 // candidate.
8433 if ((DCK == DefaultedComparisonKind::NotEqual ||
8434 DCK == DefaultedComparisonKind::Relational) &&
8435 !Best->RewriteKind) {
8436 if (Diagnose == ExplainDeleted) {
8437 if (Best->Function) {
8438 S.Diag(Best->Function->getLocation(),
8439 diag::note_defaulted_comparison_not_rewritten_callee)
8440 << FD;
8441 } else {
8442 assert(Best->Conversions.size() == 2 &&
8443 Best->Conversions[0].isUserDefined() &&
8444 "non-user-defined conversion from class to built-in "
8445 "comparison");
8446 S.Diag(Best->Conversions[0]
8447 .UserDefined.FoundConversionFunction.getDecl()
8448 ->getLocation(),
8449 diag::note_defaulted_comparison_not_rewritten_conversion)
8450 << FD;
8451 }
8452 }
8453 return Result::deleted();
8454 }
8455
8456 // Throughout C++2a [class.compare]: if overload resolution does not
8457 // result in a usable function, the candidate function is defined as
8458 // deleted. This requires that we selected an accessible function.
8459 //
8460 // Note that this only considers the access of the function when named
8461 // within the type of the subobject, and not the access path for any
8462 // derived-to-base conversion.
8463 CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl();
8464 if (ArgClass && Best->FoundDecl.getDecl() &&
8465 Best->FoundDecl.getDecl()->isCXXClassMember()) {
8466 QualType ObjectType = Subobj.Kind == Subobject::Member
8467 ? Args[0]->getType()
8470 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc,
8471 Diagnose == ExplainDeleted
8472 ? S.PDiag(diag::note_defaulted_comparison_inaccessible)
8473 << FD << Subobj.Kind << Subobj.Decl
8474 : S.PDiag()))
8475 return Result::deleted();
8476 }
8477
8478 bool NeedsDeducing =
8479 OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType();
8480
8481 if (FunctionDecl *BestFD = Best->Function) {
8482 // C++2a [class.compare.default]p3 [P2002R0]:
8483 // A defaulted comparison function is constexpr-compatible if
8484 // [...] no overlod resolution performed [...] results in a
8485 // non-constexpr function.
8486 assert(!BestFD->isDeleted() && "wrong overload resolution result");
8487 // If it's not constexpr, explain why not.
8488 if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) {
8489 if (Subobj.Kind != Subobject::CompleteObject)
8490 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr)
8491 << Subobj.Kind << Subobj.Decl;
8492 S.Diag(BestFD->getLocation(),
8493 diag::note_defaulted_comparison_not_constexpr_here);
8494 // Bail out after explaining; we don't want any more notes.
8495 return Result::deleted();
8496 }
8497 R.Constexpr &= BestFD->isConstexpr();
8498
8499 if (NeedsDeducing) {
8500 // If any callee has an undeduced return type, deduce it now.
8501 // FIXME: It's not clear how a failure here should be handled. For
8502 // now, we produce an eager diagnostic, because that is forward
8503 // compatible with most (all?) other reasonable options.
8504 if (BestFD->getReturnType()->isUndeducedType() &&
8505 S.DeduceReturnType(BestFD, FD->getLocation(),
8506 /*Diagnose=*/false)) {
8507 // Don't produce a duplicate error when asked to explain why the
8508 // comparison is deleted: we diagnosed that when initially checking
8509 // the defaulted operator.
8510 if (Diagnose == NoDiagnostics) {
8511 S.Diag(
8512 FD->getLocation(),
8513 diag::err_defaulted_comparison_cannot_deduce_undeduced_auto)
8514 << Subobj.Kind << Subobj.Decl;
8515 S.Diag(
8516 Subobj.Loc,
8517 diag::note_defaulted_comparison_cannot_deduce_undeduced_auto)
8518 << Subobj.Kind << Subobj.Decl;
8519 S.Diag(BestFD->getLocation(),
8520 diag::note_defaulted_comparison_cannot_deduce_callee)
8521 << Subobj.Kind << Subobj.Decl;
8522 }
8523 return Result::deleted();
8524 }
8526 BestFD->getCallResultType());
8527 if (!Info) {
8528 if (Diagnose == ExplainDeleted) {
8529 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce)
8530 << Subobj.Kind << Subobj.Decl
8531 << BestFD->getCallResultType().withoutLocalFastQualifiers();
8532 S.Diag(BestFD->getLocation(),
8533 diag::note_defaulted_comparison_cannot_deduce_callee)
8534 << Subobj.Kind << Subobj.Decl;
8535 }
8536 return Result::deleted();
8537 }
8538 R.Category = Info->Kind;
8539 }
8540 } else {
8541 QualType T = Best->BuiltinParamTypes[0];
8542 assert(T == Best->BuiltinParamTypes[1] &&
8543 "builtin comparison for different types?");
8544 assert(Best->BuiltinParamTypes[2].isNull() &&
8545 "invalid builtin comparison");
8546
8547 // FIXME: If the type we deduced is a vector type, we mark the
8548 // comparison as deleted because we don't yet support this.
8549 if (isa<VectorType>(T)) {
8550 if (Diagnose == ExplainDeleted) {
8551 S.Diag(FD->getLocation(),
8552 diag::note_defaulted_comparison_vector_types)
8553 << FD;
8554 S.Diag(Subobj.Decl->getLocation(), diag::note_declared_at);
8555 }
8556 return Result::deleted();
8557 }
8558
8559 if (NeedsDeducing) {
8560 std::optional<ComparisonCategoryType> Cat =
8562 assert(Cat && "no category for builtin comparison?");
8563 R.Category = *Cat;
8564 }
8565 }
8566
8567 // Note that we might be rewriting to a different operator. That call is
8568 // not considered until we come to actually build the comparison function.
8569 break;
8570 }
8571
8572 case OR_Ambiguous:
8573 if (Diagnose == ExplainDeleted) {
8574 unsigned Kind = 0;
8575 if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship)
8576 Kind = OO == OO_EqualEqual ? 1 : 2;
8577 CandidateSet.NoteCandidates(
8579 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous)
8580 << FD << Kind << Subobj.Kind << Subobj.Decl),
8581 S, OCD_AmbiguousCandidates, Args);
8582 }
8583 R = Result::deleted();
8584 break;
8585
8586 case OR_Deleted:
8587 if (Diagnose == ExplainDeleted) {
8588 if ((DCK == DefaultedComparisonKind::NotEqual ||
8589 DCK == DefaultedComparisonKind::Relational) &&
8590 !Best->RewriteKind) {
8591 S.Diag(Best->Function->getLocation(),
8592 diag::note_defaulted_comparison_not_rewritten_callee)
8593 << FD;
8594 } else {
8595 S.Diag(Subobj.Loc, diag::note_defaulted_function_calls_deleted)
8596 << FD << /*comparison function*/ 4 << Subobj.Kind << Subobj.Decl;
8597 S.NoteDeletedFunction(Best->Function);
8598 }
8599 }
8600 R = Result::deleted();
8601 break;
8602
8604 // If there's no usable candidate, we're done unless we can rewrite a
8605 // '<=>' in terms of '==' and '<'.
8606 if (OO == OO_Spaceship &&
8608 // For any kind of comparison category return type, we need a usable
8609 // '==' and a usable '<'.
8610 if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj,
8611 &CandidateSet)))
8612 R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet));
8613 break;
8614 }
8615
8616 if (Diagnose == ExplainDeleted) {
8617 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function)
8618 << FD << (OO == OO_EqualEqual || OO == OO_ExclaimEqual)
8619 << Subobj.Kind << Subobj.Decl;
8620
8621 // For a three-way comparison, list both the candidates for the
8622 // original operator and the candidates for the synthesized operator.
8623 if (SpaceshipCandidates) {
8624 SpaceshipCandidates->NoteCandidates(
8625 S, Args,
8626 SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates,
8627 Args, FD->getLocation()));
8628 S.Diag(Subobj.Loc,
8629 diag::note_defaulted_comparison_no_viable_function_synthesized)
8630 << (OO == OO_EqualEqual ? 0 : 1);
8631 }
8632
8633 CandidateSet.NoteCandidates(
8634 S, Args,
8635 CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args,
8636 FD->getLocation()));
8637 }
8638 R = Result::deleted();
8639 break;
8640 }
8641
8642 return R;
8643 }
8644};
8645
8646/// A list of statements.
8647struct StmtListResult {
8648 bool IsInvalid = false;
8649 llvm::SmallVector<Stmt*, 16> Stmts;
8650
8651 bool add(const StmtResult &S) {
8652 IsInvalid |= S.isInvalid();
8653 if (IsInvalid)
8654 return true;
8655 Stmts.push_back(S.get());
8656 return false;
8657 }
8658};
8659
8660/// A visitor over the notional body of a defaulted comparison that synthesizes
8661/// the actual body.
8662class DefaultedComparisonSynthesizer
8663 : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer,
8664 StmtListResult, StmtResult,
8665 std::pair<ExprResult, ExprResult>> {
8666 SourceLocation Loc;
8667 unsigned ArrayDepth = 0;
8668
8669public:
8670 using Base = DefaultedComparisonVisitor;
8671 using ExprPair = std::pair<ExprResult, ExprResult>;
8672
8673 friend Base;
8674
8675 DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8677 SourceLocation BodyLoc)
8678 : Base(S, RD, FD, DCK), Loc(BodyLoc) {}
8679
8680 /// Build a suitable function body for this defaulted comparison operator.
8681 StmtResult build() {
8682 Sema::CompoundScopeRAII CompoundScope(S);
8683
8684 StmtListResult Stmts = visit();
8685 if (Stmts.IsInvalid)
8686 return StmtError();
8687
8688 ExprResult RetVal;
8689 switch (DCK) {
8690 case DefaultedComparisonKind::None:
8691 llvm_unreachable("not a defaulted comparison");
8692
8693 case DefaultedComparisonKind::Equal: {
8694 // C++2a [class.eq]p3:
8695 // [...] compar[e] the corresponding elements [...] until the first
8696 // index i where xi == yi yields [...] false. If no such index exists,
8697 // V is true. Otherwise, V is false.
8698 //
8699 // Join the comparisons with '&&'s and return the result. Use a right
8700 // fold (traversing the conditions right-to-left), because that
8701 // short-circuits more naturally.
8702 auto OldStmts = std::move(Stmts.Stmts);
8703 Stmts.Stmts.clear();
8704 ExprResult CmpSoFar;
8705 // Finish a particular comparison chain.
8706 auto FinishCmp = [&] {
8707 if (Expr *Prior = CmpSoFar.get()) {
8708 // Convert the last expression to 'return ...;'
8709 if (RetVal.isUnset() && Stmts.Stmts.empty())
8710 RetVal = CmpSoFar;
8711 // Convert any prior comparison to 'if (!(...)) return false;'
8712 else if (Stmts.add(buildIfNotCondReturnFalse(Prior)))
8713 return true;
8714 CmpSoFar = ExprResult();
8715 }
8716 return false;
8717 };
8718 for (Stmt *EAsStmt : llvm::reverse(OldStmts)) {
8719 Expr *E = dyn_cast<Expr>(EAsStmt);
8720 if (!E) {
8721 // Found an array comparison.
8722 if (FinishCmp() || Stmts.add(EAsStmt))
8723 return StmtError();
8724 continue;
8725 }
8726
8727 if (CmpSoFar.isUnset()) {
8728 CmpSoFar = E;
8729 continue;
8730 }
8731 CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get());
8732 if (CmpSoFar.isInvalid())
8733 return StmtError();
8734 }
8735 if (FinishCmp())
8736 return StmtError();
8737 std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end());
8738 // If no such index exists, V is true.
8739 if (RetVal.isUnset())
8740 RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true);
8741 break;
8742 }
8743
8744 case DefaultedComparisonKind::ThreeWay: {
8745 // Per C++2a [class.spaceship]p3, as a fallback add:
8746 // return static_cast<R>(std::strong_ordering::equal);
8747 QualType StrongOrdering = S.CheckComparisonCategoryType(
8748 ComparisonCategoryType::StrongOrdering, Loc,
8749 Sema::ComparisonCategoryUsage::DefaultedOperator);
8750 if (StrongOrdering.isNull())
8751 return StmtError();
8752 VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(StrongOrdering)
8753 .getValueInfo(ComparisonCategoryResult::Equal)
8754 ->VD;
8755 RetVal = getDecl(EqualVD);
8756 if (RetVal.isInvalid())
8757 return StmtError();
8758 RetVal = buildStaticCastToR(RetVal.get());
8759 break;
8760 }
8761
8762 case DefaultedComparisonKind::NotEqual:
8763 case DefaultedComparisonKind::Relational:
8764 RetVal = cast<Expr>(Stmts.Stmts.pop_back_val());
8765 break;
8766 }
8767
8768 // Build the final return statement.
8769 if (RetVal.isInvalid())
8770 return StmtError();
8771 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get());
8772 if (ReturnStmt.isInvalid())
8773 return StmtError();
8774 Stmts.Stmts.push_back(ReturnStmt.get());
8775
8776 return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false);
8777 }
8778
8779private:
8780 ExprResult getDecl(ValueDecl *VD) {
8781 return S.BuildDeclarationNameExpr(
8782 CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD);
8783 }
8784
8785 ExprResult getParam(unsigned I) {
8786 ParmVarDecl *PD = FD->getParamDecl(I);
8787 return getDecl(PD);
8788 }
8789
8790 ExprPair getCompleteObject() {
8791 unsigned Param = 0;
8792 ExprResult LHS;
8793 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD);
8794 MD && MD->isImplicitObjectMemberFunction()) {
8795 // LHS is '*this'.
8796 LHS = S.ActOnCXXThis(Loc);
8797 if (!LHS.isInvalid())
8798 LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get());
8799 } else {
8800 LHS = getParam(Param++);
8801 }
8802 ExprResult RHS = getParam(Param++);
8803 assert(Param == FD->getNumParams());
8804 return {LHS, RHS};
8805 }
8806
8807 ExprPair getBase(CXXBaseSpecifier *Base) {
8808 ExprPair Obj = getCompleteObject();
8809 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8810 return {ExprError(), ExprError()};
8811 CXXCastPath Path = {Base};
8812 const auto CastToBase = [&](Expr *E) {
8813 QualType ToType = S.Context.getQualifiedType(
8814 Base->getType(), E->getType().getQualifiers());
8815 return S.ImpCastExprToType(E, ToType, CK_DerivedToBase, VK_LValue, &Path);
8816 };
8817 return {CastToBase(Obj.first.get()), CastToBase(Obj.second.get())};
8818 }
8819
8820 ExprPair getField(FieldDecl *Field) {
8821 ExprPair Obj = getCompleteObject();
8822 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8823 return {ExprError(), ExprError()};
8824
8825 DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess());
8826 DeclarationNameInfo NameInfo(Field->getDeclName(), Loc);
8827 return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc,
8828 CXXScopeSpec(), Field, Found, NameInfo),
8829 S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc,
8830 CXXScopeSpec(), Field, Found, NameInfo)};
8831 }
8832
8833 // FIXME: When expanding a subobject, register a note in the code synthesis
8834 // stack to say which subobject we're comparing.
8835
8836 StmtResult buildIfNotCondReturnFalse(ExprResult Cond) {
8837 if (Cond.isInvalid())
8838 return StmtError();
8839
8840 ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get());
8841 if (NotCond.isInvalid())
8842 return StmtError();
8843
8844 ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false);
8845 assert(!False.isInvalid() && "should never fail");
8846 StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get());
8847 if (ReturnFalse.isInvalid())
8848 return StmtError();
8849
8850 return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, nullptr,
8851 S.ActOnCondition(nullptr, Loc, NotCond.get(),
8852 Sema::ConditionKind::Boolean),
8853 Loc, ReturnFalse.get(), SourceLocation(), nullptr);
8854 }
8855
8856 StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size,
8857 ExprPair Subobj) {
8858 QualType SizeType = S.Context.getSizeType();
8859 Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType));
8860
8861 // Build 'size_t i$n = 0'.
8862 IdentifierInfo *IterationVarName = nullptr;
8863 {
8864 SmallString<8> Str;
8865 llvm::raw_svector_ostream OS(Str);
8866 OS << "i" << ArrayDepth;
8867 IterationVarName = &S.Context.Idents.get(OS.str());
8868 }
8869 VarDecl *IterationVar = VarDecl::Create(
8870 S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType,
8871 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None);
8872 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
8873 IterationVar->setInit(
8874 IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
8875 Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc);
8876
8877 auto IterRef = [&] {
8878 ExprResult Ref = S.BuildDeclarationNameExpr(
8879 CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc),
8880 IterationVar);
8881 assert(!Ref.isInvalid() && "can't reference our own variable?");
8882 return Ref.get();
8883 };
8884
8885 // Build 'i$n != Size'.
8886 ExprResult Cond = S.CreateBuiltinBinOp(
8887 Loc, BO_NE, IterRef(),
8888 IntegerLiteral::Create(S.Context, Size, SizeType, Loc));
8889 assert(!Cond.isInvalid() && "should never fail");
8890
8891 // Build '++i$n'.
8892 ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef());
8893 assert(!Inc.isInvalid() && "should never fail");
8894
8895 // Build 'a[i$n]' and 'b[i$n]'.
8896 auto Index = [&](ExprResult E) {
8897 if (E.isInvalid())
8898 return ExprError();
8899 return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc);
8900 };
8901 Subobj.first = Index(Subobj.first);
8902 Subobj.second = Index(Subobj.second);
8903
8904 // Compare the array elements.
8905 ++ArrayDepth;
8906 StmtResult Substmt = visitSubobject(Type, Subobj);
8907 --ArrayDepth;
8908
8909 if (Substmt.isInvalid())
8910 return StmtError();
8911
8912 // For the inner level of an 'operator==', build 'if (!cmp) return false;'.
8913 // For outer levels or for an 'operator<=>' we already have a suitable
8914 // statement that returns as necessary.
8915 if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) {
8916 assert(DCK == DefaultedComparisonKind::Equal &&
8917 "should have non-expression statement");
8918 Substmt = buildIfNotCondReturnFalse(ElemCmp);
8919 if (Substmt.isInvalid())
8920 return StmtError();
8921 }
8922
8923 // Build 'for (...) ...'
8924 return S.ActOnForStmt(Loc, Loc, Init,
8925 S.ActOnCondition(nullptr, Loc, Cond.get(),
8926 Sema::ConditionKind::Boolean),
8927 S.MakeFullDiscardedValueExpr(Inc.get()), Loc,
8928 Substmt.get());
8929 }
8930
8931 StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) {
8932 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8933 return StmtError();
8934
8937 ExprResult Op;
8938 if (Type->isOverloadableType())
8939 Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(),
8940 Obj.second.get(), /*PerformADL=*/true,
8941 /*AllowRewrittenCandidates=*/true, FD);
8942 else
8943 Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get());
8944 if (Op.isInvalid())
8945 return StmtError();
8946
8947 switch (DCK) {
8948 case DefaultedComparisonKind::None:
8949 llvm_unreachable("not a defaulted comparison");
8950
8951 case DefaultedComparisonKind::Equal:
8952 // Per C++2a [class.eq]p2, each comparison is individually contextually
8953 // converted to bool.
8954 Op = S.PerformContextuallyConvertToBool(Op.get());
8955 if (Op.isInvalid())
8956 return StmtError();
8957 return Op.get();
8958
8959 case DefaultedComparisonKind::ThreeWay: {
8960 // Per C++2a [class.spaceship]p3, form:
8961 // if (R cmp = static_cast<R>(op); cmp != 0)
8962 // return cmp;
8963 QualType R = FD->getReturnType();
8964 Op = buildStaticCastToR(Op.get());
8965 if (Op.isInvalid())
8966 return StmtError();
8967
8968 // R cmp = ...;
8969 IdentifierInfo *Name = &S.Context.Idents.get("cmp");
8970 VarDecl *VD =
8971 VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R,
8972 S.Context.getTrivialTypeSourceInfo(R, Loc), SC_None);
8973 S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false);
8974 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc);
8975
8976 // cmp != 0
8977 ExprResult VDRef = getDecl(VD);
8978 if (VDRef.isInvalid())
8979 return StmtError();
8980 llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0);
8981 Expr *Zero =
8982 IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc);
8984 if (VDRef.get()->getType()->isOverloadableType())
8985 Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true,
8986 true, FD);
8987 else
8988 Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero);
8989 if (Comp.isInvalid())
8990 return StmtError();
8991 Sema::ConditionResult Cond = S.ActOnCondition(
8992 nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean);
8993 if (Cond.isInvalid())
8994 return StmtError();
8995
8996 // return cmp;
8997 VDRef = getDecl(VD);
8998 if (VDRef.isInvalid())
8999 return StmtError();
9000 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get());
9001 if (ReturnStmt.isInvalid())
9002 return StmtError();
9003
9004 // if (...)
9005 return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, InitStmt, Cond,
9006 Loc, ReturnStmt.get(),
9007 /*ElseLoc=*/SourceLocation(), /*Else=*/nullptr);
9008 }
9009
9010 case DefaultedComparisonKind::NotEqual:
9011 case DefaultedComparisonKind::Relational:
9012 // C++2a [class.compare.secondary]p2:
9013 // Otherwise, the operator function yields x @ y.
9014 return Op.get();
9015 }
9016 llvm_unreachable("");
9017 }
9018
9019 /// Build "static_cast<R>(E)".
9020 ExprResult buildStaticCastToR(Expr *E) {
9021 QualType R = FD->getReturnType();
9022 assert(!R->isUndeducedType() && "type should have been deduced already");
9023
9024 // Don't bother forming a no-op cast in the common case.
9025 if (E->isPRValue() && S.Context.hasSameType(E->getType(), R))
9026 return E;
9027 return S.BuildCXXNamedCast(Loc, tok::kw_static_cast,
9028 S.Context.getTrivialTypeSourceInfo(R, Loc), E,
9029 SourceRange(Loc, Loc), SourceRange(Loc, Loc));
9030 }
9031};
9032}
9033
9034/// Perform the unqualified lookups that might be needed to form a defaulted
9035/// comparison function for the given operator.
9037 UnresolvedSetImpl &Operators,
9039 auto Lookup = [&](OverloadedOperatorKind OO) {
9040 Self.LookupOverloadedOperatorName(OO, S, Operators);
9041 };
9042
9043 // Every defaulted operator looks up itself.
9044 Lookup(Op);
9045 // ... and the rewritten form of itself, if any.
9047 Lookup(ExtraOp);
9048
9049 // For 'operator<=>', we also form a 'cmp != 0' expression, and might
9050 // synthesize a three-way comparison from '<' and '=='. In a dependent
9051 // context, we also need to look up '==' in case we implicitly declare a
9052 // defaulted 'operator=='.
9053 if (Op == OO_Spaceship) {
9054 Lookup(OO_ExclaimEqual);
9055 Lookup(OO_Less);
9056 Lookup(OO_EqualEqual);
9057 }
9058}
9059
9062 assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison");
9063
9064 // Perform any unqualified lookups we're going to need to default this
9065 // function.
9066 if (S) {
9067 UnresolvedSet<32> Operators;
9068 lookupOperatorsForDefaultedComparison(*this, S, Operators,
9069 FD->getOverloadedOperator());
9072 Context, Operators.pairs(), CurFPFeatureOverrides()));
9073 }
9074
9075 // C++2a [class.compare.default]p1:
9076 // A defaulted comparison operator function for some class C shall be a
9077 // non-template function declared in the member-specification of C that is
9078 // -- a non-static const non-volatile member of C having one parameter of
9079 // type const C& and either no ref-qualifier or the ref-qualifier &, or
9080 // -- a friend of C having two parameters of type const C& or two
9081 // parameters of type C.
9082
9083 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext());
9084 bool IsMethod = isa<CXXMethodDecl>(FD);
9085 if (IsMethod) {
9086 auto *MD = cast<CXXMethodDecl>(FD);
9087 assert(!MD->isStatic() && "comparison function cannot be a static member");
9088
9089 if (MD->getRefQualifier() == RQ_RValue) {
9090 Diag(MD->getLocation(), diag::err_ref_qualifier_comparison_operator);
9091
9092 // Remove the ref qualifier to recover.
9093 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
9094 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9095 EPI.RefQualifier = RQ_None;
9096 MD->setType(Context.getFunctionType(FPT->getReturnType(),
9097 FPT->getParamTypes(), EPI));
9098 }
9099
9100 // If we're out-of-class, this is the class we're comparing.
9101 if (!RD)
9102 RD = MD->getParent();
9103 QualType T = MD->getFunctionObjectParameterReferenceType();
9104 if (!T.getNonReferenceType().isConstQualified() &&
9105 (MD->isImplicitObjectMemberFunction() || T->isLValueReferenceType())) {
9106 SourceLocation Loc, InsertLoc;
9107 if (MD->isExplicitObjectMemberFunction()) {
9108 Loc = MD->getParamDecl(0)->getBeginLoc();
9109 InsertLoc = getLocForEndOfToken(
9110 MD->getParamDecl(0)->getExplicitObjectParamThisLoc());
9111 } else {
9112 Loc = MD->getLocation();
9113 if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc())
9114 InsertLoc = getLocForEndOfToken(Loc.getRParenLoc());
9115 }
9116 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
9117 // corresponding defaulted 'operator<=>' already.
9118 if (!MD->isImplicit()) {
9119 Diag(Loc, diag::err_defaulted_comparison_non_const)
9120 << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const");
9121 }
9122
9123 // Add the 'const' to the type to recover.
9124 if (MD->isExplicitObjectMemberFunction()) {
9125 assert(T->isLValueReferenceType());
9126 MD->getParamDecl(0)->setType(Context.getLValueReferenceType(
9127 T.getNonReferenceType().withConst()));
9128 } else {
9129 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
9130 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9131 EPI.TypeQuals.addConst();
9132 MD->setType(Context.getFunctionType(FPT->getReturnType(),
9133 FPT->getParamTypes(), EPI));
9134 }
9135 }
9136
9137 if (MD->isVolatile()) {
9138 Diag(MD->getLocation(), diag::err_volatile_comparison_operator);
9139
9140 // Remove the 'volatile' from the type to recover.
9141 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
9142 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9144 MD->setType(Context.getFunctionType(FPT->getReturnType(),
9145 FPT->getParamTypes(), EPI));
9146 }
9147 }
9148
9149 if ((FD->getNumParams() -
9150 (unsigned)FD->hasCXXExplicitFunctionObjectParameter()) !=
9151 (IsMethod ? 1 : 2)) {
9152 // Let's not worry about using a variadic template pack here -- who would do
9153 // such a thing?
9154 Diag(FD->getLocation(), diag::err_defaulted_comparison_num_args)
9155 << int(IsMethod) << int(DCK);
9156 return true;
9157 }
9158
9159 const ParmVarDecl *KnownParm = nullptr;
9160 for (const ParmVarDecl *Param : FD->parameters()) {
9161 QualType ParmTy = Param->getType();
9162 if (!KnownParm) {
9163 auto CTy = ParmTy;
9164 // Is it `T const &`?
9165 bool Ok = !IsMethod || FD->hasCXXExplicitFunctionObjectParameter();
9166 QualType ExpectedTy;
9167 if (RD)
9168 ExpectedTy = Context.getCanonicalTagType(RD);
9169 if (auto *Ref = CTy->getAs<LValueReferenceType>()) {
9170 CTy = Ref->getPointeeType();
9171 if (RD)
9172 ExpectedTy.addConst();
9173 Ok = true;
9174 }
9175
9176 // Is T a class?
9177 if (RD) {
9178 Ok &= RD->isDependentType() || Context.hasSameType(CTy, ExpectedTy);
9179 } else {
9180 RD = CTy->getAsCXXRecordDecl();
9181 Ok &= RD != nullptr;
9182 }
9183
9184 if (Ok) {
9185 KnownParm = Param;
9186 } else {
9187 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
9188 // corresponding defaulted 'operator<=>' already.
9189 if (!FD->isImplicit()) {
9190 if (RD) {
9191 CanQualType PlainTy = Context.getCanonicalTagType(RD);
9192 QualType RefTy =
9193 Context.getLValueReferenceType(PlainTy.withConst());
9194 Diag(FD->getLocation(), diag::err_defaulted_comparison_param)
9195 << int(DCK) << ParmTy << RefTy << int(!IsMethod) << PlainTy
9196 << Param->getSourceRange();
9197 } else {
9198 assert(!IsMethod && "should know expected type for method");
9199 Diag(FD->getLocation(),
9200 diag::err_defaulted_comparison_param_unknown)
9201 << int(DCK) << ParmTy << Param->getSourceRange();
9202 }
9203 }
9204 return true;
9205 }
9206 } else if (!Context.hasSameType(KnownParm->getType(), ParmTy)) {
9207 Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch)
9208 << int(DCK) << KnownParm->getType() << KnownParm->getSourceRange()
9209 << ParmTy << Param->getSourceRange();
9210 return true;
9211 }
9212 }
9213
9214 assert(RD && "must have determined class");
9215 if (IsMethod) {
9216 } else if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
9217 // In-class, must be a friend decl.
9218 assert(FD->getFriendObjectKind() && "expected a friend declaration");
9219 } else {
9220 // Out of class, require the defaulted comparison to be a friend (of a
9221 // complete type, per CWG2547).
9222 if (RequireCompleteType(FD->getLocation(), Context.getCanonicalTagType(RD),
9223 diag::err_defaulted_comparison_not_friend, int(DCK),
9224 int(1)))
9225 return true;
9226
9227 if (llvm::none_of(RD->friends(), [&](const FriendDecl *F) {
9228 return declaresSameEntity(F->getFriendDecl(), FD);
9229 })) {
9230 Diag(FD->getLocation(), diag::err_defaulted_comparison_not_friend)
9231 << int(DCK) << int(0) << RD;
9232 Diag(RD->getCanonicalDecl()->getLocation(), diag::note_declared_at);
9233 return true;
9234 }
9235 }
9236
9237 // C++2a [class.eq]p1, [class.rel]p1:
9238 // A [defaulted comparison other than <=>] shall have a declared return
9239 // type bool.
9242 !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) {
9243 Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool)
9244 << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy
9245 << FD->getReturnTypeSourceRange();
9246 return true;
9247 }
9248 // C++2a [class.spaceship]p2 [P2002R0]:
9249 // Let R be the declared return type [...]. If R is auto, [...]. Otherwise,
9250 // R shall not contain a placeholder type.
9251 if (QualType RT = FD->getDeclaredReturnType();
9253 RT->getContainedDeducedType() &&
9254 (!Context.hasSameType(RT, Context.getAutoDeductType()) ||
9255 RT->getContainedAutoType()->isConstrained())) {
9256 Diag(FD->getLocation(),
9257 diag::err_defaulted_comparison_deduced_return_type_not_auto)
9258 << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy
9259 << FD->getReturnTypeSourceRange();
9260 return true;
9261 }
9262
9263 // For a defaulted function in a dependent class, defer all remaining checks
9264 // until instantiation.
9265 if (RD->isDependentType())
9266 return false;
9267
9268 // Determine whether the function should be defined as deleted.
9269 DefaultedComparisonInfo Info =
9270 DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit();
9271
9272 bool First = FD == FD->getCanonicalDecl();
9273
9274 if (!First) {
9275 if (Info.Deleted) {
9276 // C++11 [dcl.fct.def.default]p4:
9277 // [For a] user-provided explicitly-defaulted function [...] if such a
9278 // function is implicitly defined as deleted, the program is ill-formed.
9279 //
9280 // This is really just a consequence of the general rule that you can
9281 // only delete a function on its first declaration.
9282 Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes)
9283 << FD->isImplicit() << (int)DCK;
9284 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9285 DefaultedComparisonAnalyzer::ExplainDeleted)
9286 .visit();
9287 return true;
9288 }
9290 // C++20 [class.compare.default]p1:
9291 // [...] A definition of a comparison operator as defaulted that appears
9292 // in a class shall be the first declaration of that function.
9293 Diag(FD->getLocation(), diag::err_non_first_default_compare_in_class)
9294 << (int)DCK;
9296 diag::note_previous_declaration);
9297 return true;
9298 }
9299 }
9300
9301 // If we want to delete the function, then do so; there's nothing else to
9302 // check in that case.
9303 if (Info.Deleted) {
9304 SetDeclDeleted(FD, FD->getLocation());
9305 if (!inTemplateInstantiation() && !FD->isImplicit()) {
9306 Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted)
9307 << (int)DCK;
9308 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9309 DefaultedComparisonAnalyzer::ExplainDeleted)
9310 .visit();
9311 if (FD->getDefaultLoc().isValid())
9312 Diag(FD->getDefaultLoc(), diag::note_replace_equals_default_to_delete)
9313 << FixItHint::CreateReplacement(FD->getDefaultLoc(), "delete");
9314 }
9315 return false;
9316 }
9317
9318 // C++2a [class.spaceship]p2:
9319 // The return type is deduced as the common comparison type of R0, R1, ...
9323 if (RetLoc.isInvalid())
9324 RetLoc = FD->getBeginLoc();
9325 // FIXME: Should we really care whether we have the complete type and the
9326 // 'enumerator' constants here? A forward declaration seems sufficient.
9328 Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator);
9329 if (Cat.isNull())
9330 return true;
9331 Context.adjustDeducedFunctionResultType(
9332 FD, SubstAutoType(FD->getDeclaredReturnType(), Cat));
9333 }
9334
9335 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
9336 // An explicitly-defaulted function that is not defined as deleted may be
9337 // declared constexpr or consteval only if it is constexpr-compatible.
9338 // C++2a [class.compare.default]p3 [P2002R0]:
9339 // A defaulted comparison function is constexpr-compatible if it satisfies
9340 // the requirements for a constexpr function [...]
9341 // The only relevant requirements are that the parameter and return types are
9342 // literal types. The remaining conditions are checked by the analyzer.
9343 //
9344 // We support P2448R2 in language modes earlier than C++23 as an extension.
9345 // The concept of constexpr-compatible was removed.
9346 // C++23 [dcl.fct.def.default]p3 [P2448R2]
9347 // A function explicitly defaulted on its first declaration is implicitly
9348 // inline, and is implicitly constexpr if it is constexpr-suitable.
9349 // C++23 [dcl.constexpr]p3
9350 // A function is constexpr-suitable if
9351 // - it is not a coroutine, and
9352 // - if the function is a constructor or destructor, its class does not
9353 // have any virtual base classes.
9354 if (FD->isConstexpr()) {
9355 if (!getLangOpts().CPlusPlus23 &&
9358 !Info.Constexpr) {
9359 Diag(FD->getBeginLoc(), diag::err_defaulted_comparison_constexpr_mismatch)
9360 << FD->isImplicit() << (int)DCK << FD->isConsteval();
9361 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9362 DefaultedComparisonAnalyzer::ExplainConstexpr)
9363 .visit();
9364 }
9365 }
9366
9367 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
9368 // If a constexpr-compatible function is explicitly defaulted on its first
9369 // declaration, it is implicitly considered to be constexpr.
9370 // FIXME: Only applying this to the first declaration seems problematic, as
9371 // simple reorderings can affect the meaning of the program.
9372 if (First && !FD->isConstexpr() && Info.Constexpr)
9374
9375 // C++2a [except.spec]p3:
9376 // If a declaration of a function does not have a noexcept-specifier
9377 // [and] is defaulted on its first declaration, [...] the exception
9378 // specification is as specified below
9379 if (FD->getExceptionSpecType() == EST_None) {
9380 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9381 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9383 EPI.ExceptionSpec.SourceDecl = FD;
9384 FD->setType(Context.getFunctionType(FPT->getReturnType(),
9385 FPT->getParamTypes(), EPI));
9386 }
9387
9388 return false;
9389}
9390
9392 FunctionDecl *Spaceship) {
9395 Ctx.PointOfInstantiation = Spaceship->getEndLoc();
9396 Ctx.Entity = Spaceship;
9398
9399 if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship))
9400 EqualEqual->setImplicit();
9401
9403}
9404
9405/// Define a defaulted function whose body is synthesized by \p BuildBody: a
9406/// defaulted comparison operator function or a defaulted postfix increment or
9407/// decrement operator function.
9409 Sema &S, SourceLocation UseLoc, FunctionDecl *FD,
9410 llvm::function_ref<StmtResult(SourceLocation BodyLoc)> BuildBody) {
9411 assert(FD->isDefaulted() && !FD->isDeleted() &&
9413 if (FD->willHaveBody() || FD->isInvalidDecl())
9414 return;
9415
9417
9418 // Add a context note for diagnostics produced after this point.
9419 Scope.addContextNote(UseLoc);
9420
9421 DefaultedFunctionFPFeaturesRAII RestoreFP(S, FD);
9422
9423 {
9424 // Build and set up the function body.
9425 SourceLocation BodyLoc =
9426 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
9427 StmtResult Body = BuildBody(BodyLoc);
9428 if (Body.isInvalid()) {
9429 FD->setInvalidDecl();
9430 return;
9431 }
9432 FD->setBody(Body.get());
9433 FD->markUsed(S.Context);
9434 }
9435
9436 // The exception specification is needed because we are defining the
9437 // function. Note that this will reuse the body we just built.
9439
9441 L->CompletedImplicitDefinition(FD);
9442}
9443
9446 auto BuildBody = [&](SourceLocation BodyLoc) {
9447 // The first parameter has type maybe-ref-to maybe-const T, use that to
9448 // get the type of the class being compared.
9449 auto PT = FD->getParamDecl(0)->getType();
9450 CXXRecordDecl *RD = PT.getNonReferenceType()->getAsCXXRecordDecl();
9451 return DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build();
9452 };
9453 defineDefaultedFunctionWithSynthesizedBody(*this, UseLoc, FD, BuildBody);
9454}
9455
9456/// Compute the exception specification of a defaulted function whose body is
9457/// synthesized by \p BuildBody: a defaulted comparison operator function or a
9458/// defaulted postfix increment or decrement operator function.
9461 Sema &S, SourceLocation Loc, FunctionDecl *FD,
9462 llvm::function_ref<StmtResult(SourceLocation BodyLoc)> BuildBody) {
9463 ComputingExceptionSpec CES(S, FD, Loc);
9465
9466 if (FD->isInvalidDecl())
9467 return ExceptSpec;
9468
9469 // The common case is that we just defined the function. In that case, just
9470 // look at whether the body can throw.
9471 if (Stmt *FunctionBody = FD->getBody()) {
9472 ExceptSpec.CalledStmt(FunctionBody);
9473 } else {
9474 // Otherwise, build a body so we can check it. This should ideally only
9475 // happen when we're not actually marking the function referenced. (This is
9476 // only really important for efficiency: we don't want to build and throw
9477 // away bodies for defaulted functions more than we strictly need to.)
9478
9479 // Pretend to synthesize the function body in an unevaluated context.
9480 // Note that we can't actually just go ahead and define the function here:
9481 // we are not permitted to mark its callees as referenced.
9485
9486 SourceLocation BodyLoc =
9487 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
9488 StmtResult Body = BuildBody(BodyLoc);
9489 if (!Body.isInvalid())
9490 ExceptSpec.CalledStmt(Body.get());
9491
9492 // FIXME: Can we hold onto this body and just transform it to potentially
9493 // evaluated when we're asked to define the function rather than rebuilding
9494 // it? Either that, or we should only build the bits of the body that we
9495 // need (the expressions, not the statements).
9496 }
9497
9498 return ExceptSpec;
9499}
9500
9501static Sema::ImplicitExceptionSpecification
9503 FunctionDecl *FD,
9505 auto BuildBody = [&](SourceLocation BodyLoc) {
9506 CXXRecordDecl *RD =
9508 ? FD->getDeclContext()
9509 : FD->getLexicalDeclContext());
9510 return DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build();
9511 };
9512 return computeExceptionSpecFromSynthesizedBody(S, Loc, FD, BuildBody);
9513}
9514
9515// C++2d [over.inc.default]: defaulted postfix increment and decrement operator
9516// functions (P3668R4).
9517
9518namespace {
9519/// Information about a defaulted postfix increment or decrement operator
9520/// function, as determined by analyzeDefaultedPostfixOperator.
9521struct DefaultedPostfixOperatorInfo {
9522 /// Whether the function should be defined as deleted.
9523 bool Deleted = false;
9524 /// Whether every function invoked by the implicit definition is constexpr.
9525 bool Constexpr = true;
9526};
9527} // namespace
9528
9529/// Get the type of the first parameter of a postfix increment or decrement
9530/// operator function, where the implicit object parameter (if any) is
9531/// considered to be the first parameter.
9533 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
9534 return MD->getFunctionObjectParameterReferenceType();
9535 return FD->getParamDecl(0)->getType();
9536}
9537
9538/// Determine whether the implicit definition of the defaulted postfix
9539/// increment or decrement operator function \p FD can direct-initialize a
9540/// variable of class type \p C from the lvalue \p Obj of type \p C, and then
9541/// destroy it, using functions that are usable from the current context.
9542///
9543/// \p CheckConstexpr is called on each constructor the initialization invokes.
9544/// If \p Diagnose is true, explain why the copy or destruction is not possible.
9546 Sema &S, FunctionDecl *FD, CXXRecordDecl *RD, QualType C, Expr *Obj,
9547 bool Diagnose,
9548 llvm::function_ref<void(const FunctionDecl *)> CheckConstexpr) {
9549 SourceLocation Loc = FD->getLocation();
9550 auto InaccessibleDiag = [&](unsigned Step) {
9551 return Diagnose
9552 ? S.PDiag(diag::note_defaulted_postfix_operator_inaccessible)
9553 << FD << Step
9554 : S.PDiag();
9555 };
9556
9558 InitializationKind InitKind = InitializationKind::CreateDirect(Loc, Loc, Loc);
9559 InitializationSequence Seq(S, Entity, InitKind, Obj);
9560 if (Seq.Failed()) {
9561 // FIXME: This emits errors rather than notes explaining why the function
9562 // is deleted.
9563 if (Diagnose)
9564 Seq.Diagnose(S, Entity, InitKind, Obj);
9565 return false;
9566 }
9567 for (const InitializationSequence::Step &Step : Seq.steps()) {
9569 continue;
9571 RD, Step.Function.FoundDecl, C, Loc,
9572 InaccessibleDiag(diag::DefaultedPostfixOperatorStep::Constructor)))
9573 return false;
9574 CheckConstexpr(Step.Function.Function);
9575 }
9576
9577 CXXDestructorDecl *Dtor = S.LookupDestructor(RD);
9578 if (!Dtor)
9579 return true;
9580 if (Dtor->isDeleted()) {
9581 if (Diagnose) {
9582 S.Diag(Loc, diag::note_defaulted_function_calls_deleted)
9583 << FD << diag::DefaultedPostfixOperatorStep::Destructor
9584 << /*complete object*/ 0;
9585 S.NoteDeletedFunction(Dtor);
9586 }
9587 return false;
9588 }
9590 RD, DeclAccessPair::make(Dtor, Dtor->getAccess()), C, Loc,
9591 InaccessibleDiag(diag::DefaultedPostfixOperatorStep::Destructor));
9592}
9593
9594/// Determine whether a defaulted postfix increment or decrement operator
9595/// function for type \p C should be defined as deleted, as specified in C++2d
9596/// [over.inc.default]p2, and whether every function it would invoke is
9597/// constexpr.
9598///
9599/// If \p Diagnose is true, explain why the function is defined as deleted.
9600static DefaultedPostfixOperatorInfo
9603 bool Diagnose) {
9604 DefaultedPostfixOperatorInfo Info;
9605 SourceLocation Loc = FD->getLocation();
9606
9607 // C++2d [over.inc.default]p1:
9608 // Name lookups and access checks in the implicit definition of a defaulted
9609 // postfix increment or decrement operator function are performed from a
9610 // context equivalent to its function-body.
9611 Sema::ContextRAII SavedContext(S, FD);
9612
9613 // Let c be an lvalue of type C. c stands for the first parameter (or the
9614 // implicit object), which is always an lvalue when named in the function
9615 // body, even if it is declared as an rvalue reference.
9616 OpaqueValueExpr Obj(Loc, C, VK_LValue);
9617 Expr *Args[] = {&Obj};
9618
9619 auto Deleted = [&] {
9620 Info.Deleted = true;
9621 return Info;
9622 };
9623 auto InaccessibleDiag = [&](unsigned Step) {
9624 return Diagnose
9625 ? S.PDiag(diag::note_defaulted_postfix_operator_inaccessible)
9626 << FD << Step
9627 : S.PDiag();
9628 };
9629 auto NoteCallsDeleted = [&](unsigned Step, FunctionDecl *Callee) {
9630 if (!Diagnose)
9631 return;
9632 S.Diag(Loc, diag::note_defaulted_function_calls_deleted)
9633 << FD << Step << /*complete object*/ 0;
9634 if (Callee)
9635 S.NoteDeletedFunction(Callee);
9636 };
9637 auto CheckConstexpr = [&](const FunctionDecl *Callee) {
9638 if (!Callee->isConstexpr())
9639 Info.Constexpr = false;
9640 };
9641
9642 // C++2d [over.inc.default]p2:
9643 // A defaulted postfix increment or decrement operator function for a type
9644 // C is defined as deleted if
9645 // -- C is a class type for which overload resolution, as applied to
9646 // direct-initialization of a variable of type C from an lvalue of
9647 // type C, does not result in a usable candidate,
9648 // -- C has a destructor that is deleted or inaccessible from the context
9649 // of the function-body, or
9650 CXXRecordDecl *RD = C->getAsCXXRecordDecl();
9652 S, FD, RD, C, &Obj, Diagnose, CheckConstexpr))
9653 return Deleted();
9654
9655 // -- for an lvalue c of type C, overload resolution as applied to ++c for a
9656 // postfix increment operator function or --c for a postfix decrement
9657 // operator function does not result in a usable candidate.
9658 bool IsIncrement = Kind == PostfixOperatorKind::Increment;
9659 unsigned PrefixStep =
9660 IsIncrement ? diag::DefaultedPostfixOperatorStep::PrefixIncrement
9661 : diag::DefaultedPostfixOperatorStep::PrefixDecrement;
9662 UnresolvedSet<2> Fns;
9663 if (auto *DFI = FD->getDefaultedOrDeletedInfo())
9664 Fns.assign(DFI->getUnqualifiedLookups().begin(),
9665 DFI->getUnqualifiedLookups().end());
9668 CandidateSet, IsIncrement ? OO_PlusPlus : OO_MinusMinus, Fns, Args);
9669
9671 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
9672 case OR_Success:
9673 if (FunctionDecl *Prefix = Best->Function) {
9674 // Only a member of C can be inaccessible here; the non-member
9675 // candidates were found by unqualified lookup and ADL.
9676 if (RD && Best->FoundDecl.getDecl() &&
9677 Best->FoundDecl.getDecl()->isCXXClassMember() &&
9678 !S.isMemberAccessibleForDeletion(RD, Best->FoundDecl, C, Loc,
9679 InaccessibleDiag(PrefixStep)))
9680 return Deleted();
9681 CheckConstexpr(Prefix);
9682 } else if (!Best->Conversions.empty() &&
9683 Best->Conversions[0].isUserDefined()) {
9684 // A built-in candidate, reached through a conversion function.
9685 CheckConstexpr(Best->Conversions[0].UserDefined.ConversionFunction);
9686 }
9687 break;
9688
9689 case OR_Ambiguous:
9690 if (Diagnose)
9691 CandidateSet.NoteCandidates(
9693 Loc, S.PDiag(diag::note_defaulted_postfix_operator_ambiguous)
9694 << FD << !IsIncrement << C),
9695 S, OCD_AmbiguousCandidates, Args, IsIncrement ? "++" : "--", Loc);
9696 return Deleted();
9697
9698 case OR_Deleted:
9699 NoteCallsDeleted(PrefixStep, Best->Function);
9700 return Deleted();
9701
9703 // Don't list the non-viable candidates: like for any other unary operator,
9704 // the candidate notes can't sensibly describe an arity mismatch for a
9705 // member postfix operator (whose object argument is not a parameter).
9706 if (Diagnose)
9707 S.Diag(Loc, diag::note_defaulted_postfix_operator_no_viable)
9708 << FD << !IsIncrement << C;
9709 return Deleted();
9710 }
9711
9712 return Info;
9713}
9714
9716 PostfixOperatorKind Kind) {
9717 assert(Kind != PostfixOperatorKind::None &&
9718 "not a defaulted postfix operator");
9719 bool IsIncrement = Kind == PostfixOperatorKind::Increment;
9720
9721 // Perform the unqualified lookup of the prefix operator that the implicit
9722 // definition needs. C++2d [over.inc.default]p1:
9723 // Name lookups and access checks in the implicit definition of a defaulted
9724 // postfix increment or decrement operator function are performed from a
9725 // context equivalent to its function-body.
9726 // The lookup is performed from S, not from CurContext. S is either the body
9727 // scope of an out-of-line definition, or the scope of the class in which the
9728 // function is defaulted on its first declaration; for a lookup that ignores
9729 // member functions, both are equivalent to the function-body.
9730 if (S) {
9731 assert((S->getEntity() == FD ||
9732 S->getEntity() == FD->getLexicalDeclContext()) &&
9733 "lookup scope is not equivalent to the function-body");
9734 UnresolvedSet<2> Operators;
9735 LookupOverloadedOperatorName(IsIncrement ? OO_PlusPlus : OO_MinusMinus, S,
9736 Operators);
9739 Context, Operators.pairs(), CurFPFeatureOverrides()));
9740 }
9741
9742 // C++2d [over.inc.default]p1:
9743 // A defaulted postfix increment or decrement operator function for a type
9744 // C shall be a non-template function that
9745 // -- has a first parameter of type "reference to C" or a first parameter
9746 // of type "reference to volatile C", where the implicit object
9747 // parameter (if any) is considered to be the first parameter,
9748 // -- is defined as defaulted in C or in a context where C is complete,
9749 // and
9750 // -- has a declared return type of C.
9751 auto *MD = dyn_cast<CXXMethodDecl>(FD);
9752 ParmVarDecl *FirstParam = FD->getParamDecl(0);
9753 QualType FirstParamType = getPostfixOperatorFirstParamType(FD);
9754 QualType ReturnType = FD->getDeclaredReturnType();
9755
9756 // If the first parameter type is dependent, or the function is in a dependent
9757 // context, defer all checks until instantiation.
9758 if (FirstParamType->isDependentType() || FD->isDependentContext())
9759 return false;
9760
9761 // Check the type of the first parameter and determine the type C from it.
9762 // For a member function, C is the enclosing class. For a non-member function,
9763 // C is the class or enumeration type of its first parameter;
9764 // CheckOverloadedOperatorDeclaration has already required it to have one.
9765 QualType Referent = FirstParamType.getNonReferenceType();
9766 QualType C = MD ? Context.getCanonicalTagType(MD->getParent())
9767 : Referent.getUnqualifiedType();
9768 assert((C->isRecordType() || C->isEnumeralType()) &&
9769 "postfix operator for a non-class, non-enumeration type");
9770
9771 // The first parameter must be a reference to C, which may be
9772 // volatile-qualified but not const-qualified.
9773 if (!FirstParamType->isReferenceType() ||
9774 !Context.hasSameUnqualifiedType(Referent, C) ||
9775 Referent.isConstQualified()) {
9776 if (MD && MD->isImplicitObjectMemberFunction()) {
9777 // The implicit object parameter is always a reference to the enclosing
9778 // class, so the only possible problem is a const qualifier.
9779 Diag(MD->getLocation(), diag::err_defaulted_postfix_operator_const)
9780 << (int)Kind;
9781 } else {
9782 Diag(FirstParam->getBeginLoc(),
9783 diag::err_defaulted_postfix_operator_param)
9784 << (int)Kind << !MD << FirstParamType
9785 << Context.getLValueReferenceType(C) << FirstParam->getSourceRange();
9786 }
9787 return true;
9788 }
9789
9790 // A deduced return type is never permitted. Allowing it would need P2952R2
9791 // (auto& operator=(X&&) = default), which is not part of the standard.
9792 if (ReturnType->getContainedDeducedType()) {
9793 Diag(FD->getLocation(),
9794 diag::err_defaulted_postfix_operator_deduced_return_type)
9795 << (int)Kind << FD->getReturnTypeSourceRange();
9796 return true;
9797 }
9798
9799 // -- has a declared return type of C.
9800 if (!Context.hasSameType(ReturnType, C)) {
9801 Diag(FD->getLocation(), diag::err_defaulted_postfix_operator_return_type)
9802 << (int)Kind << C << ReturnType << FD->getReturnTypeSourceRange();
9803 return true;
9804 }
9805
9806 // -- is defined as defaulted in C or in a context where C is complete
9808 diag::err_defaulted_postfix_operator_incomplete,
9809 (int)Kind))
9810 return true;
9811
9812 // Determine whether the function should be defined as deleted.
9813 DefaultedPostfixOperatorInfo Info =
9814 analyzeDefaultedPostfixOperator(*this, FD, Kind, C, /*Diagnose=*/false);
9815
9816 // An instantiated member function has a single declaration; whether it is
9817 // defaulted on its first declaration, and where, is decided by the
9818 // defaulted definition that it is instantiated from.
9819 const FunctionDecl *Defaulted = FD;
9820 if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
9821 if (const FunctionDecl *PatternDef = Pattern->getDefinition())
9822 Defaulted = PatternDef;
9823 bool First = Defaulted == Defaulted->getFirstDecl();
9824
9825 if (!First) {
9826 if (Info.Deleted) {
9827 // C++11 [dcl.fct.def.default]p4:
9828 // [For a] user-provided explicitly-defaulted function [...] if such a
9829 // function is implicitly defined as deleted, the program is ill-formed.
9830 //
9831 // This is really just a consequence of the general rule that you can
9832 // only delete a function on its first declaration.
9833 Diag(FD->getLocation(),
9834 diag::err_non_first_default_postfix_operator_deletes)
9835 << (int)Kind;
9836 analyzeDefaultedPostfixOperator(*this, FD, Kind, C, /*Diagnose=*/true);
9837 return true;
9838 }
9839 if (isa<CXXRecordDecl>(Defaulted->getLexicalDeclContext())) {
9840 // C++2d [over.inc.default]p1:
9841 // A definition of a postfix increment or decrement operator as
9842 // defaulted that appears in a class shall be the first declaration of
9843 // that function.
9844 Diag(FD->getLocation(),
9845 diag::err_non_first_default_postfix_operator_in_class)
9846 << (int)Kind;
9848 diag::note_previous_declaration);
9849 return true;
9850 }
9851 }
9852
9853 // If we want to delete the function, then do so; there's nothing else to
9854 // check in that case.
9855 if (Info.Deleted) {
9856 SetDeclDeleted(FD, FD->getLocation());
9857 if (!inTemplateInstantiation() && !FD->isImplicit()) {
9858 Diag(FD->getLocation(), diag::warn_defaulted_postfix_operator_deleted)
9859 << (int)Kind;
9860 analyzeDefaultedPostfixOperator(*this, FD, Kind, C, /*Diagnose=*/true);
9861 if (FD->getDefaultLoc().isValid())
9862 Diag(FD->getDefaultLoc(), diag::note_replace_equals_default_to_delete)
9863 << FixItHint::CreateReplacement(FD->getDefaultLoc(), "delete");
9864 }
9865 return false;
9866 }
9867
9868 // C++23 [dcl.fct.def.default]p3 [P2448R2] allows any defaulted function to
9869 // be declared constexpr or consteval. Before C++23, it could only be declared
9870 // so if it was constexpr-compatible; we don't apply that restriction to
9871 // defaulted postfix operators, which are an extension before C++2d.
9872
9873 if (First) {
9874 // C++11 [dcl.fct.def.default]p5:
9875 // A function explicitly defaulted on its first declaration is implicitly
9876 // inline.
9877 FD->setImplicitlyInline();
9878
9879 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
9880 // If a constexpr-compatible function is explicitly defaulted on its
9881 // first declaration, it is implicitly considered to be constexpr.
9882 // C++23 [dcl.fct.def.default]p3 [P2448R2]:
9883 // A function explicitly defaulted on its first declaration is [...]
9884 // implicitly constexpr if it is constexpr-suitable.
9885 // A postfix operator function is always constexpr-suitable. The implicit
9886 // definition declares a variable, so it can only be constexpr in C++14
9887 // and later, and a virtual function can only be constexpr in C++20 and
9888 // later.
9889 if (!FD->isConstexpr() && getLangOpts().CPlusPlus14 &&
9890 (getLangOpts().CPlusPlus20 || !MD || !MD->isVirtual()) &&
9892 (Info.Constexpr &&
9897
9898 // C++2d [except.spec]p10:
9899 // The exception specification for [...] a postfix increment or decrement
9900 // operator function without a noexcept-specifier that is defaulted on
9901 // its first declaration is potentially-throwing if and only if any
9902 // expression in the implicit definition is potentially-throwing.
9903 if (FD->getExceptionSpecType() == EST_None) {
9904 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9905 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9907 EPI.ExceptionSpec.SourceDecl = FD;
9908 FD->setType(Context.getFunctionType(FPT->getReturnType(),
9909 FPT->getParamTypes(), EPI));
9910 }
9911 }
9912
9913 return false;
9914}
9915
9916/// Build the body of a defaulted postfix increment or decrement operator
9917/// function. C++2d [over.inc.default]p3:
9918/// The implicit definition of a defaulted postfix increment or decrement
9919/// operator function F that is not defined as deleted for a type C is
9920/// equivalent to:
9921/// C tmp(c);
9922/// ++c; // or --c
9923/// return tmp;
9924/// where tmp is a variable defined for exposition only, and c is an lvalue
9925/// that denotes *this if F is an implicit object member function, or the
9926/// first parameter of F otherwise.
9929 SourceLocation Loc) {
9930 Sema::CompoundScopeRAII CompoundScope(S);
9931
9932 // Build an expression denoting 'c'.
9933 auto BuildObject = [&]() -> Expr * {
9934 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD);
9935 MD && MD->isImplicitObjectMemberFunction()) {
9936 ExprResult This = S.ActOnCXXThis(Loc);
9937 assert(This.isUsable() && "no 'this' in an implicit object member");
9938 return S.CreateBuiltinUnaryOp(Loc, UO_Deref, This.get()).get();
9939 }
9940 // Diagnose the use of an unavailable or deprecated parameter. Nothing else
9941 // can make the use of a parameter in its function's body invalid.
9942 ParmVarDecl *Param = FD->getParamDecl(0);
9943 [[maybe_unused]] bool Invalid = S.DiagnoseUseOfDecl(Param, Loc);
9944 assert(!Invalid && "invalid use of a parameter in its function's body");
9945 return S.BuildDeclRefExpr(Param, Param->getType().getNonReferenceType(),
9946 VK_LValue, Loc);
9947 };
9948
9949 // C tmp(c);
9950 QualType C = FD->getReturnType();
9951 VarDecl *Tmp =
9952 VarDecl::Create(S.Context, S.CurContext, Loc, Loc, /*Id=*/nullptr, C,
9954 Expr *InitArgs[] = {BuildObject()};
9956 ParenListExpr::Create(S.Context, Loc, InitArgs, Loc),
9957 /*DirectInit=*/true);
9958 // A failed initialization doesn't invalidate the variable, but an abstract
9959 // type C does.
9960 if (Tmp->isInvalidDecl())
9961 return StmtError();
9962 StmtResult TmpStmt = S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(Tmp), Loc, Loc);
9963 assert(TmpStmt.isUsable() && "failed to build a declaration statement");
9964
9965 // ++c; or --c;
9966 Expr *Obj = BuildObject();
9967 UnaryOperatorKind Opc =
9968 Kind == PostfixOperatorKind::Increment ? UO_PreInc : UO_PreDec;
9969 UnresolvedSet<2> Fns;
9970 if (auto *DFI = FD->getDefaultedOrDeletedInfo())
9971 Fns.assign(DFI->getUnqualifiedLookups().begin(),
9972 DFI->getUnqualifiedLookups().end());
9973 ExprResult Prefix =
9974 S.CreateOverloadedUnaryOp(Loc, Opc, Fns, Obj, /*RequiresADL=*/true);
9975 if (Prefix.isInvalid())
9976 return StmtError();
9977 StmtResult PrefixStmt = S.ActOnExprStmt(Prefix, /*DiscardedValue=*/true);
9978 if (PrefixStmt.isInvalid())
9979 return StmtError();
9980
9981 // return tmp;
9982 Expr *TmpRef = S.BuildDeclRefExpr(Tmp, C, VK_LValue, Loc);
9983 StmtResult Return = S.BuildReturnStmt(Loc, TmpRef);
9984 if (Return.isInvalid())
9985 return StmtError();
9986 // 'tmp' is the only variable returned by this function, so it qualifies for
9987 // the named return value optimization.
9988 if (cast<ReturnStmt>(Return.get())->getNRVOCandidate() == Tmp)
9989 Tmp->setNRVOVariable(true);
9990
9991 Stmt *Stmts[] = {TmpStmt.get(), PrefixStmt.get(), Return.get()};
9992 return S.ActOnCompoundStmt(Loc, Loc, Stmts, /*IsStmtExpr=*/false);
9993}
9994
9996 FunctionDecl *FD,
9997 PostfixOperatorKind Kind) {
9999 *this, UseLoc, FD, [&](SourceLocation BodyLoc) {
10000 return buildDefaultedPostfixOperatorBody(*this, FD, Kind, BodyLoc);
10001 });
10002}
10003
10006 FunctionDecl *FD,
10007 PostfixOperatorKind Kind) {
10009 S, Loc, FD, [&](SourceLocation BodyLoc) {
10010 return buildDefaultedPostfixOperatorBody(S, FD, Kind, BodyLoc);
10011 });
10012}
10013
10015 decltype(DelayedOverridingExceptionSpecChecks) Overriding;
10017
10018 std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
10020
10021 // Perform any deferred checking of exception specifications for virtual
10022 // destructors.
10023 for (auto &Check : Overriding)
10024 CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
10025
10026 // Perform any deferred checking of exception specifications for befriended
10027 // special members.
10028 for (auto &Check : Equivalent)
10029 CheckEquivalentExceptionSpec(Check.second, Check.first);
10030}
10031
10032namespace {
10033/// CRTP base class for visiting operations performed by a special member
10034/// function (or inherited constructor).
10035template<typename Derived>
10036struct SpecialMemberVisitor {
10037 Sema &S;
10038 CXXMethodDecl *MD;
10041
10042 // Properties of the special member, computed for convenience.
10043 bool IsConstructor = false, IsAssignment = false, ConstArg = false;
10044
10045 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, CXXSpecialMemberKind CSM,
10047 : S(S), MD(MD), CSM(CSM), ICI(ICI) {
10048 switch (CSM) {
10052 IsConstructor = true;
10053 break;
10056 IsAssignment = true;
10057 break;
10059 break;
10061 llvm_unreachable("invalid special member kind");
10062 }
10063
10064 if (MD->getNumExplicitParams()) {
10065 if (const ReferenceType *RT =
10066 MD->getNonObjectParameter(0)->getType()->getAs<ReferenceType>())
10067 ConstArg = RT->getPointeeType().isConstQualified();
10068 }
10069 }
10070
10071 Derived &getDerived() { return static_cast<Derived&>(*this); }
10072
10073 /// Is this a "move" special member?
10074 bool isMove() const {
10075 return CSM == CXXSpecialMemberKind::MoveConstructor ||
10076 CSM == CXXSpecialMemberKind::MoveAssignment;
10077 }
10078
10079 /// Look up the corresponding special member in the given class.
10080 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
10081 unsigned Quals, bool IsMutable) {
10082 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
10083 ConstArg && !IsMutable);
10084 }
10085
10086 /// Look up the constructor for the specified base class to see if it's
10087 /// overridden due to this being an inherited constructor.
10088 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
10089 if (!ICI)
10090 return {};
10091 assert(CSM == CXXSpecialMemberKind::DefaultConstructor);
10092 auto *BaseCtor =
10093 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
10094 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
10095 return MD;
10096 return {};
10097 }
10098
10099 /// A base or member subobject.
10100 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
10101
10102 /// Get the location to use for a subobject in diagnostics.
10103 static SourceLocation getSubobjectLoc(Subobject Subobj) {
10104 // FIXME: For an indirect virtual base, the direct base leading to
10105 // the indirect virtual base would be a more useful choice.
10106 if (auto *B = dyn_cast<CXXBaseSpecifier *>(Subobj))
10107 return B->getBaseTypeLoc();
10108 else
10109 return cast<FieldDecl *>(Subobj)->getLocation();
10110 }
10111
10112 enum BasesToVisit {
10113 /// Visit all non-virtual (direct) bases.
10114 VisitNonVirtualBases,
10115 /// Visit all direct bases, virtual or not.
10116 VisitDirectBases,
10117 /// Visit all non-virtual bases, and all virtual bases if the class
10118 /// is not abstract.
10119 VisitPotentiallyConstructedBases,
10120 /// Visit all direct or virtual bases.
10121 VisitAllBases
10122 };
10123
10124 // Visit the bases and members of the class.
10125 bool visit(BasesToVisit Bases) {
10126 CXXRecordDecl *RD = MD->getParent();
10127
10128 if (Bases == VisitPotentiallyConstructedBases)
10129 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
10130
10131 for (auto &B : RD->bases())
10132 if ((Bases == VisitDirectBases || !B.isVirtual()) &&
10133 getDerived().visitBase(&B))
10134 return true;
10135
10136 if (Bases == VisitAllBases)
10137 for (auto &B : RD->vbases())
10138 if (getDerived().visitBase(&B))
10139 return true;
10140
10141 for (auto *F : RD->fields())
10142 if (!F->isInvalidDecl() && !F->isUnnamedBitField() &&
10143 getDerived().visitField(F))
10144 return true;
10145
10146 return false;
10147 }
10148};
10149}
10150
10151namespace {
10152struct SpecialMemberDeletionInfo
10153 : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
10154 bool Diagnose;
10155
10156 SourceLocation Loc;
10157
10158 bool AllFieldsAreConst;
10159
10160 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
10162 Sema::InheritedConstructorInfo *ICI, bool Diagnose)
10163 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
10164 Loc(MD->getLocation()), AllFieldsAreConst(true) {}
10165
10166 bool inUnion() const { return MD->getParent()->isUnion(); }
10167
10168 CXXSpecialMemberKind getEffectiveCSM() {
10169 return ICI ? CXXSpecialMemberKind::Invalid : CSM;
10170 }
10171
10172 bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
10173
10174 bool shouldDeleteForVariantPtrAuthMember(const FieldDecl *FD);
10175
10176 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
10177 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
10178
10179 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
10180 bool shouldDeleteForField(FieldDecl *FD);
10181 bool shouldDeleteForAllConstMembers();
10182
10183 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
10184 unsigned Quals);
10185 bool shouldDeleteForSubobjectCall(Subobject Subobj,
10186 Sema::SpecialMemberOverloadResult SMOR,
10187 bool IsDtorCallInCtor);
10188
10189 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
10190};
10191}
10192
10193/// Is the given special member inaccessible when used on the given
10194/// sub-object.
10195bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
10196 CXXMethodDecl *target) {
10197 /// If we're operating on a base class, the object type is the
10198 /// type of this special member.
10199 CanQualType objectTy;
10200 AccessSpecifier access = target->getAccess();
10201 if (CXXBaseSpecifier *base = dyn_cast<CXXBaseSpecifier *>(Subobj)) {
10202 objectTy = S.Context.getCanonicalTagType(MD->getParent());
10203 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
10204
10205 // If we're operating on a field, the object type is the type of the field.
10206 } else {
10207 objectTy = S.Context.getCanonicalTagType(target->getParent());
10208 }
10209
10211 target->getParent(), DeclAccessPair::make(target, access), objectTy);
10212}
10213
10214/// Check whether we should delete a special member due to the implicit
10215/// definition containing a call to a special member of a subobject.
10216bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
10217 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
10218 bool IsDtorCallInCtor) {
10219 CXXMethodDecl *Decl = SMOR.getMethod();
10220 FieldDecl *Field = dyn_cast<FieldDecl *>(Subobj);
10221
10222 enum {
10223 NotSet = -1,
10224 NoDecl,
10225 DeletedDecl,
10226 MultipleDecl,
10227 InaccessibleDecl,
10228 NonTrivialDecl
10229 } DiagKind = NotSet;
10230
10232 if (CSM == CXXSpecialMemberKind::DefaultConstructor && Field &&
10233 Field->getParent()->isUnion()) {
10234 // [class.default.ctor]p2:
10235 // A defaulted default constructor for class X is defined as deleted if
10236 // - X is a union that has a variant member with a non-trivial default
10237 // constructor and no variant member of X has a default member
10238 // initializer
10239 const auto *RD = cast<CXXRecordDecl>(Field->getParent());
10240 if (RD->hasInClassInitializer())
10241 return false;
10242 }
10243 DiagKind = !Decl ? NoDecl : DeletedDecl;
10245 DiagKind = MultipleDecl;
10246 else if (!isAccessible(Subobj, Decl))
10247 DiagKind = InaccessibleDecl;
10248 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
10249 !Decl->isTrivial()) {
10250 // A member of a union must have a trivial corresponding special member.
10251 // As a weird special case, a destructor call from a union's constructor
10252 // must be accessible and non-deleted, but need not be trivial. Such a
10253 // destructor is never actually called, but is semantically checked as
10254 // if it were.
10255 if (CSM == CXXSpecialMemberKind::DefaultConstructor) {
10256 // [class.default.ctor]p2:
10257 // A defaulted default constructor for class X is defined as deleted if
10258 // - X is a union that has a variant member with a non-trivial default
10259 // constructor and no variant member of X has a default member
10260 // initializer
10261 const auto *RD = cast<CXXRecordDecl>(Field->getParent());
10262 if (!RD->hasInClassInitializer())
10263 DiagKind = NonTrivialDecl;
10264 } else {
10265 DiagKind = NonTrivialDecl;
10266 }
10267 }
10268
10269 if (DiagKind == NotSet)
10270 return false;
10271
10272 if (Diagnose) {
10273 if (Field) {
10274 S.Diag(Field->getLocation(),
10275 diag::note_deleted_special_member_class_subobject)
10276 << getEffectiveCSM() << MD->getParent() << /*IsField*/ true << Field
10277 << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/ false;
10278 } else {
10279 CXXBaseSpecifier *Base = cast<CXXBaseSpecifier *>(Subobj);
10280 S.Diag(Base->getBeginLoc(),
10281 diag::note_deleted_special_member_class_subobject)
10282 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
10283 << Base->getType() << DiagKind << IsDtorCallInCtor
10284 << /*IsObjCPtr*/ false;
10285 }
10286
10287 if (DiagKind == DeletedDecl)
10288 S.NoteDeletedFunction(Decl);
10289 // FIXME: Explain inaccessibility if DiagKind == InaccessibleDecl.
10290 }
10291
10292 return true;
10293}
10294
10295/// Check whether we should delete a special member function due to having a
10296/// direct or virtual base class or non-static data member of class type M.
10297bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
10298 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
10299 FieldDecl *Field = dyn_cast<FieldDecl *>(Subobj);
10300 bool IsMutable = Field && Field->isMutable();
10301
10302 // C++11 [class.ctor]p5:
10303 // -- any direct or virtual base class, or non-static data member with no
10304 // brace-or-equal-initializer, has class type M (or array thereof) and
10305 // either M has no default constructor or overload resolution as applied
10306 // to M's default constructor results in an ambiguity or in a function
10307 // that is deleted or inaccessible
10308 // C++11 [class.copy]p11, C++11 [class.copy]p23:
10309 // -- a direct or virtual base class B that cannot be copied/moved because
10310 // overload resolution, as applied to B's corresponding special member,
10311 // results in an ambiguity or a function that is deleted or inaccessible
10312 // from the defaulted special member
10313 // C++11 [class.dtor]p5:
10314 // -- any direct or virtual base class [...] has a type with a destructor
10315 // that is deleted or inaccessible
10316 if (!(CSM == CXXSpecialMemberKind::DefaultConstructor && Field &&
10317 Field->hasInClassInitializer()) &&
10318 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
10319 false))
10320 return true;
10321
10322 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
10323 // -- any direct or virtual base class or non-static data member has a
10324 // type with a destructor that is deleted or inaccessible
10325 if (IsConstructor) {
10326 Sema::SpecialMemberOverloadResult SMOR =
10327 S.LookupSpecialMember(Class, CXXSpecialMemberKind::Destructor, false,
10328 false, false, false, false);
10329 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
10330 return true;
10331 }
10332
10333 return false;
10334}
10335
10336bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
10337 FieldDecl *FD, QualType FieldType) {
10338 // The defaulted special functions are defined as deleted if this is a variant
10339 // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
10340 // type under ARC.
10341 if (!FieldType.hasNonTrivialObjCLifetime())
10342 return false;
10343
10344 // Don't make the defaulted default constructor defined as deleted if the
10345 // member has an in-class initializer.
10346 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
10348 return false;
10349
10350 if (Diagnose) {
10351 auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
10352 S.Diag(FD->getLocation(), diag::note_deleted_special_member_class_subobject)
10353 << getEffectiveCSM() << ParentClass << /*IsField*/ true << FD << 4
10354 << /*IsDtorCallInCtor*/ false << /*IsObjCPtr*/ true;
10355 }
10356
10357 return true;
10358}
10359
10360bool SpecialMemberDeletionInfo::shouldDeleteForVariantPtrAuthMember(
10361 const FieldDecl *FD) {
10362 QualType FieldType = S.Context.getBaseElementType(FD->getType());
10363 // Copy/move constructors/assignment operators are deleted if the field has an
10364 // address-discriminated ptrauth qualifier.
10365 PointerAuthQualifier Q = FieldType.getPointerAuth();
10366
10367 if (!Q || !Q.isAddressDiscriminated())
10368 return false;
10369
10370 if (CSM == CXXSpecialMemberKind::DefaultConstructor ||
10371 CSM == CXXSpecialMemberKind::Destructor)
10372 return false;
10373
10374 if (Diagnose) {
10375 auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
10376 S.Diag(FD->getLocation(), diag::note_deleted_special_member_class_subobject)
10377 << getEffectiveCSM() << ParentClass << /*IsField*/ true << FD << 4
10378 << /*IsDtorCallInCtor*/ false << 2;
10379 }
10380
10381 return true;
10382}
10383
10384/// Check whether we should delete a special member function due to the class
10385/// having a particular direct or virtual base class.
10386bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
10387 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
10388 // If program is correct, BaseClass cannot be null, but if it is, the error
10389 // must be reported elsewhere.
10390 if (!BaseClass)
10391 return false;
10392 // If we have an inheriting constructor, check whether we're calling an
10393 // inherited constructor instead of a default constructor.
10394 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
10395 if (auto *BaseCtor = SMOR.getMethod()) {
10396 // Note that we do not check access along this path; other than that,
10397 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
10398 // FIXME: Check that the base has a usable destructor! Sink this into
10399 // shouldDeleteForClassSubobject.
10400 if (BaseCtor->isDeleted() && Diagnose) {
10401 S.Diag(Base->getBeginLoc(),
10402 diag::note_deleted_special_member_class_subobject)
10403 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
10404 << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
10405 << /*IsObjCPtr*/ false;
10406 S.NoteDeletedFunction(BaseCtor);
10407 }
10408 return BaseCtor->isDeleted();
10409 }
10410 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
10411}
10412
10413/// Check whether we should delete a special member function due to the class
10414/// having a particular non-static data member.
10415bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
10416 QualType FieldType = S.Context.getBaseElementType(FD->getType());
10417 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
10418
10419 if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
10420 return true;
10421
10422 if (inUnion() && shouldDeleteForVariantPtrAuthMember(FD))
10423 return true;
10424
10425 if (CSM == CXXSpecialMemberKind::DefaultConstructor) {
10426 // For a default constructor, all references must be initialized in-class
10427 // and, if a union, it must have a non-const member.
10428 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
10429 if (Diagnose)
10430 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
10431 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
10432 return true;
10433 }
10434 // C++11 [class.ctor]p5 (modified by DR2394): any non-variant non-static
10435 // data member of const-qualified type (or array thereof) with no
10436 // brace-or-equal-initializer is not const-default-constructible.
10437 if (!inUnion() && FieldType.isConstQualified() &&
10438 !FD->hasInClassInitializer() &&
10439 (!FieldRecord || !FieldRecord->allowConstDefaultInit())) {
10440 if (Diagnose)
10441 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
10442 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
10443 return true;
10444 }
10445
10446 if (inUnion() && !FieldType.isConstQualified())
10447 AllFieldsAreConst = false;
10448 } else if (CSM == CXXSpecialMemberKind::CopyConstructor) {
10449 // For a copy constructor, data members must not be of rvalue reference
10450 // type.
10451 if (FieldType->isRValueReferenceType()) {
10452 if (Diagnose)
10453 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
10454 << MD->getParent() << FD << FieldType;
10455 return true;
10456 }
10457 } else if (IsAssignment) {
10458 // For an assignment operator, data members must not be of reference type.
10459 if (FieldType->isReferenceType()) {
10460 if (Diagnose)
10461 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
10462 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
10463 return true;
10464 }
10465 if (!FieldRecord && FieldType.isConstQualified()) {
10466 // C++11 [class.copy]p23:
10467 // -- a non-static data member of const non-class type (or array thereof)
10468 if (Diagnose)
10469 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
10470 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
10471 return true;
10472 }
10473 }
10474
10475 if (FieldRecord) {
10476 // Some additional restrictions exist on the variant members.
10477 if (!inUnion() && FieldRecord->isUnion() &&
10478 FieldRecord->isAnonymousStructOrUnion()) {
10479 bool AllVariantFieldsAreConst = true;
10480
10481 // FIXME: Handle anonymous unions declared within anonymous unions.
10482 for (auto *UI : FieldRecord->fields()) {
10483 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
10484
10485 if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
10486 return true;
10487
10488 if (shouldDeleteForVariantPtrAuthMember(&*UI))
10489 return true;
10490
10491 if (!UnionFieldType.isConstQualified())
10492 AllVariantFieldsAreConst = false;
10493
10494 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
10495 if (UnionFieldRecord &&
10496 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
10497 UnionFieldType.getCVRQualifiers()))
10498 return true;
10499 }
10500
10501 // At least one member in each anonymous union must be non-const
10502 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
10503 AllVariantFieldsAreConst && !FieldRecord->field_empty()) {
10504 if (Diagnose)
10505 S.Diag(FieldRecord->getLocation(),
10506 diag::note_deleted_default_ctor_all_const)
10507 << !!ICI << MD->getParent() << /*anonymous union*/1;
10508 return true;
10509 }
10510
10511 // Don't check the implicit member of the anonymous union type.
10512 // This is technically non-conformant but supported, and we have a
10513 // diagnostic for this elsewhere.
10514 return false;
10515 }
10516
10517 if (shouldDeleteForClassSubobject(FieldRecord, FD,
10518 FieldType.getCVRQualifiers()))
10519 return true;
10520 }
10521
10522 return false;
10523}
10524
10525/// C++11 [class.ctor] p5:
10526/// A defaulted default constructor for a class X is defined as deleted if
10527/// X is a union and all of its variant members are of const-qualified type.
10528bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
10529 // This is a silly definition, because it gives an empty union a deleted
10530 // default constructor. Don't do that.
10531 if (CSM == CXXSpecialMemberKind::DefaultConstructor && inUnion() &&
10532 AllFieldsAreConst) {
10533 bool AnyFields = false;
10534 for (auto *F : MD->getParent()->fields())
10535 if ((AnyFields = !F->isUnnamedBitField()))
10536 break;
10537 if (!AnyFields)
10538 return false;
10539 if (Diagnose)
10540 S.Diag(MD->getParent()->getLocation(),
10541 diag::note_deleted_default_ctor_all_const)
10542 << !!ICI << MD->getParent() << /*not anonymous union*/0;
10543 return true;
10544 }
10545 return false;
10546}
10547
10548/// Determine whether a defaulted special member function should be defined as
10549/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
10550/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
10554 bool Diagnose) {
10555 if (MD->isInvalidDecl())
10556 return false;
10557 CXXRecordDecl *RD = MD->getParent();
10558 assert(!RD->isDependentType() && "do deletion after instantiation");
10559 if (!LangOpts.CPlusPlus || (!LangOpts.CPlusPlus11 && !RD->isLambda()) ||
10560 RD->isInvalidDecl())
10561 return false;
10562
10563 // C++11 [expr.lambda.prim]p19:
10564 // The closure type associated with a lambda-expression has a
10565 // deleted (8.4.3) default constructor and a deleted copy
10566 // assignment operator.
10567 // C++2a adds back these operators if the lambda has no lambda-capture.
10571 if (Diagnose)
10572 Diag(RD->getLocation(), diag::note_lambda_decl);
10573 return true;
10574 }
10575
10576 // C++11 [class.copy]p7, p18:
10577 // If the class definition declares a move constructor or move assignment
10578 // operator, an implicitly declared copy constructor or copy assignment
10579 // operator is defined as deleted.
10582 CXXMethodDecl *UserDeclaredMove = nullptr;
10583
10584 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
10585 // deletion of the corresponding copy operation, not both copy operations.
10586 // MSVC 2015 has adopted the standards conforming behavior.
10587 bool DeletesOnlyMatchingCopy =
10588 getLangOpts().MSVCCompat &&
10589 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
10590
10592 (!DeletesOnlyMatchingCopy ||
10594 if (!Diagnose) return true;
10595
10596 // Find any user-declared move constructor.
10597 for (auto *I : RD->ctors()) {
10598 if (I->isMoveConstructor()) {
10599 UserDeclaredMove = I;
10600 break;
10601 }
10602 }
10603 assert(UserDeclaredMove);
10604 } else if (RD->hasUserDeclaredMoveAssignment() &&
10605 (!DeletesOnlyMatchingCopy ||
10607 if (!Diagnose) return true;
10608
10609 // Find any user-declared move assignment operator.
10610 for (auto *I : RD->methods()) {
10611 if (I->isMoveAssignmentOperator()) {
10612 UserDeclaredMove = I;
10613 break;
10614 }
10615 }
10616 assert(UserDeclaredMove);
10617 }
10618
10619 if (UserDeclaredMove) {
10620 Diag(UserDeclaredMove->getLocation(),
10621 diag::note_deleted_copy_user_declared_move)
10622 << (CSM == CXXSpecialMemberKind::CopyAssignment) << RD
10623 << UserDeclaredMove->isMoveAssignmentOperator();
10624 return true;
10625 }
10626 }
10627
10628 // Do access control from the special member function
10629 ContextRAII MethodContext(*this, MD);
10630
10631 // C++11 [class.dtor]p5:
10632 // -- for a virtual destructor, lookup of the non-array deallocation function
10633 // results in an ambiguity or in a function that is deleted or inaccessible
10634 if (CSM == CXXSpecialMemberKind::Destructor && MD->isVirtual()) {
10635 FunctionDecl *OperatorDelete = nullptr;
10636 CanQualType DeallocType = Context.getCanonicalTagType(RD);
10637 DeclarationName Name =
10638 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
10642 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
10643 OperatorDelete, IDP,
10644 /*Diagnose=*/false)) {
10645 if (Diagnose)
10646 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
10647 return true;
10648 }
10649 }
10650
10651 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
10652
10653 // Per DR1611, do not consider virtual bases of constructors of abstract
10654 // classes, since we are not going to construct them.
10655 // Per DR1658, do not consider virtual bases of destructors of abstract
10656 // classes either.
10657 // Per DR2180, for assignment operators we only assign (and thus only
10658 // consider) direct bases.
10659 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
10660 : SMI.VisitPotentiallyConstructedBases))
10661 return true;
10662
10663 if (SMI.shouldDeleteForAllConstMembers())
10664 return true;
10665
10666 if (getLangOpts().CUDA) {
10667 // We should delete the special member in CUDA mode if target inference
10668 // failed.
10669 // For inherited constructors (non-null ICI), CSM may be passed so that MD
10670 // is treated as certain special member, which may not reflect what special
10671 // member MD really is. However inferTargetForImplicitSpecialMember
10672 // expects CSM to match MD, therefore recalculate CSM.
10673 assert(ICI || CSM == MD->getSpecialMemberKind());
10674 auto RealCSM = CSM;
10675 if (ICI)
10676 RealCSM = MD->getSpecialMemberKind();
10677
10678 return CUDA().inferTargetForImplicitSpecialMember(RD, RealCSM, MD,
10679 SMI.ConstArg, Diagnose);
10680 }
10681
10682 return false;
10683}
10684
10687 assert(DFK && "not a defaultable function");
10688 assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted");
10689
10690 if (DFK.isSpecialMember()) {
10692 nullptr, /*Diagnose=*/true);
10693 } else if (DFK.isPostfixOperator()) {
10698 /*Diagnose=*/true);
10699 } else {
10700 DefaultedComparisonAnalyzer(
10702 DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted)
10703 .visit();
10704 }
10705}
10706
10707/// Perform lookup for a special member of the specified kind, and determine
10708/// whether it is trivial. If the triviality can be determined without the
10709/// lookup, skip it. This is intended for use when determining whether a
10710/// special member of a containing object is trivial, and thus does not ever
10711/// perform overload resolution for default constructors.
10712///
10713/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
10714/// member that was most likely to be intended to be trivial, if any.
10715///
10716/// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
10717/// determine whether the special member is trivial.
10719 CXXSpecialMemberKind CSM, unsigned Quals,
10720 bool ConstRHS, TrivialABIHandling TAH,
10721 CXXMethodDecl **Selected) {
10722 if (Selected)
10723 *Selected = nullptr;
10724
10725 switch (CSM) {
10727 llvm_unreachable("not a special member");
10728
10730 // C++11 [class.ctor]p5:
10731 // A default constructor is trivial if:
10732 // - all the [direct subobjects] have trivial default constructors
10733 //
10734 // Note, no overload resolution is performed in this case.
10736 return true;
10737
10738 if (Selected) {
10739 // If there's a default constructor which could have been trivial, dig it
10740 // out. Otherwise, if there's any user-provided default constructor, point
10741 // to that as an example of why there's not a trivial one.
10742 CXXConstructorDecl *DefCtor = nullptr;
10745 for (auto *CI : RD->ctors()) {
10746 if (!CI->isDefaultConstructor())
10747 continue;
10748 DefCtor = CI;
10749 if (!DefCtor->isUserProvided())
10750 break;
10751 }
10752
10753 *Selected = DefCtor;
10754 }
10755
10756 return false;
10757
10759 // C++11 [class.dtor]p5:
10760 // A destructor is trivial if:
10761 // - all the direct [subobjects] have trivial destructors
10762 if (RD->hasTrivialDestructor() ||
10765 return true;
10766
10767 if (Selected) {
10768 if (RD->needsImplicitDestructor())
10770 *Selected = RD->getDestructor();
10771 }
10772
10773 return false;
10774
10776 // C++11 [class.copy]p12:
10777 // A copy constructor is trivial if:
10778 // - the constructor selected to copy each direct [subobject] is trivial
10779 if (RD->hasTrivialCopyConstructor() ||
10782 if (Quals == Qualifiers::Const)
10783 // We must either select the trivial copy constructor or reach an
10784 // ambiguity; no need to actually perform overload resolution.
10785 return true;
10786 } else if (!Selected) {
10787 return false;
10788 }
10789 // In C++98, we are not supposed to perform overload resolution here, but we
10790 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
10791 // cases like B as having a non-trivial copy constructor:
10792 // struct A { template<typename T> A(T&); };
10793 // struct B { mutable A a; };
10794 goto NeedOverloadResolution;
10795
10797 // C++11 [class.copy]p25:
10798 // A copy assignment operator is trivial if:
10799 // - the assignment operator selected to copy each direct [subobject] is
10800 // trivial
10801 if (RD->hasTrivialCopyAssignment()) {
10802 if (Quals == Qualifiers::Const)
10803 return true;
10804 } else if (!Selected) {
10805 return false;
10806 }
10807 // In C++98, we are not supposed to perform overload resolution here, but we
10808 // treat that as a language defect.
10809 goto NeedOverloadResolution;
10810
10813 NeedOverloadResolution:
10815 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
10816
10817 // The standard doesn't describe how to behave if the lookup is ambiguous.
10818 // We treat it as not making the member non-trivial, just like the standard
10819 // mandates for the default constructor. This should rarely matter, because
10820 // the member will also be deleted.
10822 return true;
10823
10824 if (!SMOR.getMethod()) {
10825 assert(SMOR.getKind() ==
10827 return false;
10828 }
10829
10830 // We deliberately don't check if we found a deleted special member. We're
10831 // not supposed to!
10832 if (Selected)
10833 *Selected = SMOR.getMethod();
10834
10838 return SMOR.getMethod()->isTrivialForCall();
10839 return SMOR.getMethod()->isTrivial();
10840 }
10841
10842 llvm_unreachable("unknown special method kind");
10843}
10844
10846 for (auto *CI : RD->ctors())
10847 if (!CI->isImplicit())
10848 return CI;
10849
10850 // Look for constructor templates.
10852 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
10853 if (CXXConstructorDecl *CD =
10854 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
10855 return CD;
10856 }
10857
10858 return nullptr;
10859}
10860
10861/// The kind of subobject we are checking for triviality. The values of this
10862/// enumeration are used in diagnostics.
10864 /// The subobject is a base class.
10866 /// The subobject is a non-static data member.
10868 /// The object is actually the complete object.
10870};
10871
10872/// Check whether the special member selected for a given type would be trivial.
10874 QualType SubType, bool ConstRHS,
10877 TrivialABIHandling TAH, bool Diagnose) {
10878 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
10879 if (!SubRD)
10880 return true;
10881
10882 CXXMethodDecl *Selected;
10883 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
10884 ConstRHS, TAH, Diagnose ? &Selected : nullptr))
10885 return true;
10886
10887 if (Diagnose) {
10888 if (ConstRHS)
10889 SubType.addConst();
10890
10891 if (!Selected && CSM == CXXSpecialMemberKind::DefaultConstructor) {
10892 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
10893 << Kind << SubType.getUnqualifiedType();
10895 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
10896 } else if (!Selected)
10897 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
10898 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
10899 else if (Selected->isUserProvided()) {
10900 if (Kind == TSK_CompleteObject)
10901 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
10902 << Kind << SubType.getUnqualifiedType() << CSM;
10903 else {
10904 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
10905 << Kind << SubType.getUnqualifiedType() << CSM;
10906 S.Diag(Selected->getLocation(), diag::note_declared_at);
10907 }
10908 } else {
10909 if (Kind != TSK_CompleteObject)
10910 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
10911 << Kind << SubType.getUnqualifiedType() << CSM;
10912
10913 // Explain why the defaulted or deleted special member isn't trivial.
10914 S.SpecialMemberIsTrivial(Selected, CSM,
10916 }
10917 }
10918
10919 return false;
10920}
10921
10922/// Check whether the members of a class type allow a special member to be
10923/// trivial.
10925 CXXSpecialMemberKind CSM, bool ConstArg,
10926 TrivialABIHandling TAH, bool Diagnose) {
10927 for (const auto *FI : RD->fields()) {
10928 if (FI->isInvalidDecl() || FI->isUnnamedBitField())
10929 continue;
10930
10931 QualType FieldType = S.Context.getBaseElementType(FI->getType());
10932
10933 // Pretend anonymous struct or union members are members of this class.
10934 if (FI->isAnonymousStructOrUnion()) {
10935 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
10936 CSM, ConstArg, TAH, Diagnose))
10937 return false;
10938 continue;
10939 }
10940
10941 // C++11 [class.ctor]p5:
10942 // A default constructor is trivial if [...]
10943 // -- no non-static data member of its class has a
10944 // brace-or-equal-initializer
10946 FI->hasInClassInitializer()) {
10947 if (Diagnose)
10948 S.Diag(FI->getLocation(), diag::note_nontrivial_default_member_init)
10949 << FI;
10950 return false;
10951 }
10952
10953 // Objective C ARC 4.3.5:
10954 // [...] nontrivally ownership-qualified types are [...] not trivially
10955 // default constructible, copy constructible, move constructible, copy
10956 // assignable, move assignable, or destructible [...]
10957 if (FieldType.hasNonTrivialObjCLifetime()) {
10958 if (Diagnose)
10959 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
10960 << RD << FieldType.getObjCLifetime();
10961 return false;
10962 }
10963
10964 bool ConstRHS = ConstArg && !FI->isMutable();
10965 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
10966 CSM, TSK_Field, TAH, Diagnose))
10967 return false;
10968 }
10969
10970 return true;
10971}
10972
10975 CanQualType Ty = Context.getCanonicalTagType(RD);
10976
10977 bool ConstArg = (CSM == CXXSpecialMemberKind::CopyConstructor ||
10979 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
10982 /*Diagnose*/ true);
10983}
10984
10986 TrivialABIHandling TAH, bool Diagnose) {
10987 assert(!MD->isUserProvided() && CSM != CXXSpecialMemberKind::Invalid &&
10988 "not special enough");
10989
10990 CXXRecordDecl *RD = MD->getParent();
10991
10992 bool ConstArg = false;
10993
10994 // C++11 [class.copy]p12, p25: [DR1593]
10995 // A [special member] is trivial if [...] its parameter-type-list is
10996 // equivalent to the parameter-type-list of an implicit declaration [...]
10997 switch (CSM) {
11000 // Trivial default constructors and destructors cannot have parameters.
11001 break;
11002
11005 const ParmVarDecl *Param0 = MD->getNonObjectParameter(0);
11006 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
11007
11008 // When ClangABICompat14 is true, CXX copy constructors will only be trivial
11009 // if they are not user-provided and their parameter-type-list is equivalent
11010 // to the parameter-type-list of an implicit declaration. This maintains the
11011 // behavior before dr2171 was implemented.
11012 //
11013 // Otherwise, if ClangABICompat14 is false, All copy constructors can be
11014 // trivial, if they are not user-provided, regardless of the qualifiers on
11015 // the reference type.
11016 const bool ClangABICompat14 =
11017 Context.getLangOpts().isCompatibleWith(LangOptions::ClangABI::Ver14);
11018 if (!RT ||
11020 ClangABICompat14)) {
11021 if (Diagnose)
11022 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
11023 << Param0->getSourceRange() << Param0->getType()
11024 << Context.getLValueReferenceType(
11025 Context.getCanonicalTagType(RD).withConst());
11026 return false;
11027 }
11028
11029 ConstArg = RT->getPointeeType().isConstQualified();
11030 break;
11031 }
11032
11035 // Trivial move operations always have non-cv-qualified parameters.
11036 const ParmVarDecl *Param0 = MD->getNonObjectParameter(0);
11037 const RValueReferenceType *RT =
11038 Param0->getType()->getAs<RValueReferenceType>();
11039 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
11040 if (Diagnose)
11041 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
11042 << Param0->getSourceRange() << Param0->getType()
11043 << Context.getRValueReferenceType(Context.getCanonicalTagType(RD));
11044 return false;
11045 }
11046 break;
11047 }
11048
11050 llvm_unreachable("not a special member");
11051 }
11052
11053 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
11054 if (Diagnose)
11056 diag::note_nontrivial_default_arg)
11058 return false;
11059 }
11060 if (MD->isVariadic()) {
11061 if (Diagnose)
11062 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
11063 return false;
11064 }
11065
11066 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
11067 // A copy/move [constructor or assignment operator] is trivial if
11068 // -- the [member] selected to copy/move each direct base class subobject
11069 // is trivial
11070 //
11071 // C++11 [class.copy]p12, C++11 [class.copy]p25:
11072 // A [default constructor or destructor] is trivial if
11073 // -- all the direct base classes have trivial [default constructors or
11074 // destructors]
11075 for (const auto &BI : RD->bases())
11076 if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
11077 ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
11078 return false;
11079
11080 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
11081 // A copy/move [constructor or assignment operator] for a class X is
11082 // trivial if
11083 // -- for each non-static data member of X that is of class type (or array
11084 // thereof), the constructor selected to copy/move that member is
11085 // trivial
11086 //
11087 // C++11 [class.copy]p12, C++11 [class.copy]p25:
11088 // A [default constructor or destructor] is trivial if
11089 // -- for all of the non-static data members of its class that are of class
11090 // type (or array thereof), each such class has a trivial [default
11091 // constructor or destructor]
11092 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
11093 return false;
11094
11095 // C++11 [class.dtor]p5:
11096 // A destructor is trivial if [...]
11097 // -- the destructor is not virtual
11098 if (CSM == CXXSpecialMemberKind::Destructor && MD->isVirtual()) {
11099 if (Diagnose)
11100 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
11101 return false;
11102 }
11103
11104 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
11105 // A [special member] for class X is trivial if [...]
11106 // -- class X has no virtual functions and no virtual base classes
11108 MD->getParent()->isDynamicClass()) {
11109 if (!Diagnose)
11110 return false;
11111
11112 if (RD->getNumVBases()) {
11113 // Check for virtual bases. We already know that the corresponding
11114 // member in all bases is trivial, so vbases must all be direct.
11115 CXXBaseSpecifier &BS = *RD->vbases_begin();
11116 assert(BS.isVirtual());
11117 Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
11118 return false;
11119 }
11120
11121 // Must have a virtual method.
11122 for (const auto *MI : RD->methods()) {
11123 if (MI->isVirtual()) {
11124 SourceLocation MLoc = MI->getBeginLoc();
11125 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
11126 return false;
11127 }
11128 }
11129
11130 llvm_unreachable("dynamic class with no vbases and no virtual functions");
11131 }
11132
11133 // Looks like it's trivial!
11134 return true;
11135}
11136
11137namespace {
11138struct FindHiddenVirtualMethod {
11139 Sema *S;
11141 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
11142 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
11143
11144private:
11145 /// Check whether any most overridden method from MD in Methods
11146 static bool CheckMostOverridenMethods(
11147 const CXXMethodDecl *MD,
11148 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
11149 if (MD->size_overridden_methods() == 0)
11150 return Methods.count(MD->getCanonicalDecl());
11151 for (const CXXMethodDecl *O : MD->overridden_methods())
11152 if (CheckMostOverridenMethods(O, Methods))
11153 return true;
11154 return false;
11155 }
11156
11157public:
11158 /// Member lookup function that determines whether a given C++
11159 /// method overloads virtual methods in a base class without overriding any,
11160 /// to be used with CXXRecordDecl::lookupInBases().
11161 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
11162 auto *BaseRecord = Specifier->getType()->castAsRecordDecl();
11163 DeclarationName Name = Method->getDeclName();
11164 assert(Name.getNameKind() == DeclarationName::Identifier);
11165
11166 bool foundSameNameMethod = false;
11167 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
11168 for (Path.Decls = BaseRecord->lookup(Name).begin();
11169 Path.Decls != DeclContext::lookup_iterator(); ++Path.Decls) {
11170 NamedDecl *D = *Path.Decls;
11171 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
11172 MD = MD->getCanonicalDecl();
11173 foundSameNameMethod = true;
11174 // Interested only in hidden virtual methods.
11175 if (!MD->isVirtual())
11176 continue;
11177 // If the method we are checking overrides a method from its base
11178 // don't warn about the other overloaded methods. Clang deviates from
11179 // GCC by only diagnosing overloads of inherited virtual functions that
11180 // do not override any other virtual functions in the base. GCC's
11181 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
11182 // function from a base class. These cases may be better served by a
11183 // warning (not specific to virtual functions) on call sites when the
11184 // call would select a different function from the base class, were it
11185 // visible.
11186 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
11187 if (!S->IsOverload(Method, MD, false))
11188 return true;
11189 // Collect the overload only if its hidden.
11190 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
11191 overloadedMethods.push_back(MD);
11192 }
11193 }
11194
11195 if (foundSameNameMethod)
11196 OverloadedMethods.append(overloadedMethods.begin(),
11197 overloadedMethods.end());
11198 return foundSameNameMethod;
11199 }
11200};
11201} // end anonymous namespace
11202
11203/// Add the most overridden methods from MD to Methods
11205 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
11206 if (MD->size_overridden_methods() == 0)
11207 Methods.insert(MD->getCanonicalDecl());
11208 else
11209 for (const CXXMethodDecl *O : MD->overridden_methods())
11210 AddMostOverridenMethods(O, Methods);
11211}
11212
11214 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
11215 if (!MD->getDeclName().isIdentifier())
11216 return;
11217
11218 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
11219 /*bool RecordPaths=*/false,
11220 /*bool DetectVirtual=*/false);
11221 FindHiddenVirtualMethod FHVM;
11222 FHVM.Method = MD;
11223 FHVM.S = this;
11224
11225 // Keep the base methods that were overridden or introduced in the subclass
11226 // by 'using' in a set. A base method not in this set is hidden.
11227 CXXRecordDecl *DC = MD->getParent();
11228 for (NamedDecl *ND : DC->lookup(MD->getDeclName())) {
11229 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(ND))
11230 ND = shad->getTargetDecl();
11231 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
11232 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
11233 }
11234
11235 if (DC->lookupInBases(FHVM, Paths))
11236 OverloadedMethods = FHVM.OverloadedMethods;
11237}
11238
11240 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
11241 for (const CXXMethodDecl *overloadedMD : OverloadedMethods) {
11243 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
11244 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
11245 Diag(overloadedMD->getLocation(), PD);
11246 }
11247}
11248
11250 if (MD->isInvalidDecl())
11251 return;
11252
11253 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
11254 return;
11255
11256 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
11257 FindHiddenVirtualMethods(MD, OverloadedMethods);
11258 if (!OverloadedMethods.empty()) {
11259 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
11260 << MD << (OverloadedMethods.size() > 1);
11261
11262 NoteHiddenVirtualMethods(MD, OverloadedMethods);
11263 }
11264}
11265
11267 auto PrintDiagAndRemoveAttr = [&](unsigned N) {
11268 // No diagnostics if this is a template instantiation.
11270 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
11271 diag::ext_cannot_use_trivial_abi) << &RD;
11272 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
11273 diag::note_cannot_use_trivial_abi_reason) << &RD << N;
11274 }
11275 RD.dropAttr<TrivialABIAttr>();
11276 };
11277
11278 // Ill-formed if the struct has virtual functions.
11279 if (RD.isPolymorphic()) {
11280 PrintDiagAndRemoveAttr(1);
11281 return;
11282 }
11283
11284 for (const auto &B : RD.bases()) {
11285 // Ill-formed if the base class is non-trivial for the purpose of calls or a
11286 // virtual base.
11287 if (!B.getType()->isDependentType() &&
11288 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) {
11289 PrintDiagAndRemoveAttr(2);
11290 return;
11291 }
11292
11293 if (B.isVirtual()) {
11294 PrintDiagAndRemoveAttr(3);
11295 return;
11296 }
11297 }
11298
11299 for (const auto *FD : RD.fields()) {
11300 // Ill-formed if the field is an ObjectiveC pointer or of a type that is
11301 // non-trivial for the purpose of calls.
11302 QualType FT = FD->getType();
11304 PrintDiagAndRemoveAttr(4);
11305 return;
11306 }
11307
11308 // Ill-formed if the field is an address-discriminated value.
11310 PrintDiagAndRemoveAttr(6);
11311 return;
11312 }
11313
11314 if (const auto *RT =
11315 FT->getBaseElementTypeUnsafe()->getAsCanonical<RecordType>())
11316 if (!RT->isDependentType() &&
11317 !cast<CXXRecordDecl>(RT->getDecl()->getDefinitionOrSelf())
11318 ->canPassInRegisters()) {
11319 PrintDiagAndRemoveAttr(5);
11320 return;
11321 }
11322 }
11323
11325 return;
11326
11327 // Ill-formed if the copy and move constructors are deleted.
11328 auto HasNonDeletedCopyOrMoveConstructor = [&]() {
11329 // If the type is dependent, then assume it might have
11330 // implicit copy or move ctor because we won't know yet at this point.
11331 if (RD.isDependentType())
11332 return true;
11335 return true;
11338 return true;
11339 for (const CXXConstructorDecl *CD : RD.ctors())
11340 if (CD->isCopyOrMoveConstructor() && !CD->isDeleted())
11341 return true;
11342 return false;
11343 };
11344
11345 if (!HasNonDeletedCopyOrMoveConstructor()) {
11346 PrintDiagAndRemoveAttr(0);
11347 return;
11348 }
11349}
11350
11352 CXXRecordDecl &RD) {
11353 if (RequireCompleteType(RD.getLocation(), Context.getCanonicalTagType(&RD),
11354 diag::err_incomplete_type_vtable_pointer_auth))
11355 return;
11356
11357 const CXXRecordDecl *PrimaryBase = &RD;
11358 if (PrimaryBase->hasAnyDependentBases())
11359 return;
11360
11361 while (1) {
11362 assert(PrimaryBase);
11363 const CXXRecordDecl *Base = nullptr;
11364 for (const CXXBaseSpecifier &BasePtr : PrimaryBase->bases()) {
11365 if (!BasePtr.getType()->getAsCXXRecordDecl()->isDynamicClass())
11366 continue;
11367 Base = BasePtr.getType()->getAsCXXRecordDecl();
11368 break;
11369 }
11370 if (!Base || Base == PrimaryBase || !Base->isPolymorphic())
11371 break;
11372 Diag(RD.getAttr<VTablePointerAuthenticationAttr>()->getLocation(),
11373 diag::err_non_top_level_vtable_pointer_auth)
11374 << &RD << Base;
11375 PrimaryBase = Base;
11376 }
11377
11378 if (!RD.isPolymorphic())
11379 Diag(RD.getAttr<VTablePointerAuthenticationAttr>()->getLocation(),
11380 diag::err_non_polymorphic_vtable_pointer_auth)
11381 << &RD;
11382}
11383
11386 SourceLocation RBrac, const ParsedAttributesView &AttrList) {
11387 if (!TagDecl)
11388 return;
11389
11391
11392 for (const ParsedAttr &AL : AttrList) {
11393 if (AL.getKind() != ParsedAttr::AT_Visibility)
11394 continue;
11395 AL.setInvalid();
11396 Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL;
11397 }
11398
11399 ActOnFields(S, RLoc, TagDecl,
11401 // strict aliasing violation!
11402 reinterpret_cast<Decl **>(FieldCollector->getCurFields()),
11403 FieldCollector->getCurNumFields()),
11404 LBrac, RBrac, AttrList);
11405
11407}
11408
11409/// Find the equality comparison functions that should be implicitly declared
11410/// in a given class definition, per C++2a [class.compare.default]p3.
11412 ASTContext &Ctx, CXXRecordDecl *RD,
11414 DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual);
11415 if (!RD->lookup(EqEq).empty())
11416 // Member operator== explicitly declared: no implicit operator==s.
11417 return;
11418
11419 // Traverse friends looking for an '==' or a '<=>'.
11420 for (FriendDecl *Friend : RD->friends()) {
11421 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl());
11422 if (!FD) continue;
11423
11424 if (FD->getOverloadedOperator() == OO_EqualEqual) {
11425 // Friend operator== explicitly declared: no implicit operator==s.
11426 Spaceships.clear();
11427 return;
11428 }
11429
11430 if (FD->getOverloadedOperator() == OO_Spaceship &&
11432 Spaceships.push_back(FD);
11433 }
11434
11435 // Look for members named 'operator<=>'.
11437 for (NamedDecl *ND : RD->lookup(Cmp)) {
11438 // Note that we could find a non-function here (either a function template
11439 // or a using-declaration). Neither case results in an implicit
11440 // 'operator=='.
11441 if (auto *FD = dyn_cast<FunctionDecl>(ND))
11442 if (FD->isExplicitlyDefaulted())
11443 Spaceships.push_back(FD);
11444 }
11445}
11446
11448 // Don't add implicit special members to templated classes.
11449 // FIXME: This means unqualified lookups for 'operator=' within a class
11450 // template don't work properly.
11451 if (!ClassDecl->isDependentType()) {
11452 if (ClassDecl->needsImplicitDefaultConstructor()) {
11453 ++getASTContext().NumImplicitDefaultConstructors;
11454
11455 if (ClassDecl->hasInheritedConstructor())
11457 }
11458
11459 if (ClassDecl->needsImplicitCopyConstructor()) {
11460 ++getASTContext().NumImplicitCopyConstructors;
11461
11462 // If the properties or semantics of the copy constructor couldn't be
11463 // determined while the class was being declared, force a declaration
11464 // of it now.
11466 ClassDecl->hasInheritedConstructor())
11468 // For the MS ABI we need to know whether the copy ctor is deleted. A
11469 // prerequisite for deleting the implicit copy ctor is that the class has
11470 // a move ctor or move assignment that is either user-declared or whose
11471 // semantics are inherited from a subobject. FIXME: We should provide a
11472 // more direct way for CodeGen to ask whether the constructor was deleted.
11473 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
11474 (ClassDecl->hasUserDeclaredMoveConstructor() ||
11476 ClassDecl->hasUserDeclaredMoveAssignment() ||
11479 }
11480
11481 if (getLangOpts().CPlusPlus11 &&
11482 ClassDecl->needsImplicitMoveConstructor()) {
11483 ++getASTContext().NumImplicitMoveConstructors;
11484
11486 ClassDecl->hasInheritedConstructor())
11488 }
11489
11490 if (ClassDecl->needsImplicitCopyAssignment()) {
11491 ++getASTContext().NumImplicitCopyAssignmentOperators;
11492
11493 // If we have a dynamic class, then the copy assignment operator may be
11494 // virtual, so we have to declare it immediately. This ensures that, e.g.,
11495 // it shows up in the right place in the vtable and that we diagnose
11496 // problems with the implicit exception specification.
11497 if (ClassDecl->isDynamicClass() ||
11499 ClassDecl->hasInheritedAssignment())
11501 }
11502
11503 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
11504 ++getASTContext().NumImplicitMoveAssignmentOperators;
11505
11506 // Likewise for the move assignment operator.
11507 if (ClassDecl->isDynamicClass() ||
11509 ClassDecl->hasInheritedAssignment())
11511 }
11512
11513 if (ClassDecl->needsImplicitDestructor()) {
11514 ++getASTContext().NumImplicitDestructors;
11515
11516 // If we have a dynamic class, then the destructor may be virtual, so we
11517 // have to declare the destructor immediately. This ensures that, e.g., it
11518 // shows up in the right place in the vtable and that we diagnose problems
11519 // with the implicit exception specification.
11520 if (ClassDecl->isDynamicClass() ||
11522 DeclareImplicitDestructor(ClassDecl);
11523 }
11524 }
11525
11526 // C++2a [class.compare.default]p3:
11527 // If the member-specification does not explicitly declare any member or
11528 // friend named operator==, an == operator function is declared implicitly
11529 // for each defaulted three-way comparison operator function defined in
11530 // the member-specification
11531 // FIXME: Consider doing this lazily.
11532 // We do this during the initial parse for a class template, not during
11533 // instantiation, so that we can handle unqualified lookups for 'operator=='
11534 // when parsing the template.
11536 llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships;
11538 DefaultedSpaceships);
11539 for (auto *FD : DefaultedSpaceships)
11540 DeclareImplicitEqualityComparison(ClassDecl, FD);
11541 }
11542}
11543
11544unsigned
11546 llvm::function_ref<Scope *()> EnterScope) {
11547 if (!D)
11548 return 0;
11550
11551 // In order to get name lookup right, reenter template scopes in order from
11552 // outermost to innermost.
11554 DeclContext *LookupDC = dyn_cast<DeclContext>(D);
11555
11556 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
11557 for (TemplateParameterList *TPL : DD->getTemplateParameterLists())
11558 ParameterLists.push_back(TPL);
11559
11560 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
11561 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
11562 ParameterLists.push_back(FTD->getTemplateParameters());
11563 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
11564 LookupDC = VD->getDeclContext();
11565
11567 ParameterLists.push_back(VTD->getTemplateParameters());
11568 else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D))
11569 ParameterLists.push_back(PSD->getTemplateParameters());
11570 }
11571 } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
11572 for (TemplateParameterList *TPL : TD->getTemplateParameterLists())
11573 ParameterLists.push_back(TPL);
11574
11575 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
11577 ParameterLists.push_back(CTD->getTemplateParameters());
11578 else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
11579 ParameterLists.push_back(PSD->getTemplateParameters());
11580 }
11581 }
11582 // FIXME: Alias declarations and concepts.
11583
11584 unsigned Count = 0;
11585 Scope *InnermostTemplateScope = nullptr;
11586 for (TemplateParameterList *Params : ParameterLists) {
11587 // Ignore explicit specializations; they don't contribute to the template
11588 // depth.
11589 if (Params->size() == 0)
11590 continue;
11591
11592 InnermostTemplateScope = EnterScope();
11593 for (NamedDecl *Param : *Params) {
11594 if (Param->getDeclName()) {
11595 InnermostTemplateScope->AddDecl(Param);
11596 IdResolver.AddDecl(Param);
11597 }
11598 }
11599 ++Count;
11600 }
11601
11602 // Associate the new template scopes with the corresponding entities.
11603 if (InnermostTemplateScope) {
11604 assert(LookupDC && "no enclosing DeclContext for template lookup");
11605 EnterTemplatedContext(InnermostTemplateScope, LookupDC);
11606 }
11607
11608 return Count;
11609}
11610
11612 if (!RecordD) return;
11613 AdjustDeclIfTemplate(RecordD);
11616}
11617
11619 if (!RecordD) return;
11621}
11622
11624 if (!Param)
11625 return;
11626
11627 S->AddDecl(Param);
11628 if (Param->getDeclName())
11629 IdResolver.AddDecl(Param);
11630}
11631
11634
11635/// ActOnDelayedCXXMethodParameter - We've already started a delayed
11636/// C++ method declaration. We're (re-)introducing the given
11637/// function parameter into scope for use in parsing later parts of
11638/// the method declaration. For example, we could see an
11639/// ActOnParamDefaultArgument event for this parameter.
11641 if (!ParamD)
11642 return;
11643
11644 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
11645
11646 S->AddDecl(Param);
11647 if (Param->getDeclName())
11648 IdResolver.AddDecl(Param);
11649}
11650
11652 if (!MethodD)
11653 return;
11654
11655 AdjustDeclIfTemplate(MethodD);
11656
11658
11659 // Now that we have our default arguments, check the constructor
11660 // again. It could produce additional diagnostics or affect whether
11661 // the class has implicitly-declared destructors, among other
11662 // things.
11663 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
11665
11666 // Check the default arguments, which we may have added.
11667 if (!Method->isInvalidDecl())
11669}
11670
11671// Emit the given diagnostic for each non-address-space qualifier.
11672// Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
11673static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
11675 if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
11676 bool DiagOccurred = false;
11678 [DiagID, &S, &DiagOccurred](DeclSpec::TQ, StringRef QualName,
11679 SourceLocation SL) {
11680 // This diagnostic should be emitted on any qualifier except an addr
11681 // space qualifier. However, forEachQualifier currently doesn't visit
11682 // addr space qualifiers, so there's no way to write this condition
11683 // right now; we just diagnose on everything.
11684 S.Diag(SL, DiagID) << QualName << SourceRange(SL);
11685 DiagOccurred = true;
11686 });
11687 if (DiagOccurred)
11688 D.setInvalidType();
11689 }
11690}
11691
11693 unsigned Kind) {
11694 if (D.isInvalidType() || D.getNumTypeObjects() <= 1)
11695 return;
11696
11698 if (Chunk.Kind == DeclaratorChunk::Paren ||
11700 return;
11701
11702 SourceLocation PointerLoc = Chunk.getSourceRange().getBegin();
11703 S.Diag(PointerLoc, diag::err_invalid_ctor_dtor_decl)
11704 << Kind << Chunk.getSourceRange();
11705 D.setInvalidType();
11706}
11707
11709 StorageClass &SC) {
11710 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
11711
11712 // C++ [class.ctor]p3:
11713 // A constructor shall not be virtual (10.3) or static (9.4). A
11714 // constructor can be invoked for a const, volatile or const
11715 // volatile object. A constructor shall not be declared const,
11716 // volatile, or const volatile (9.3.2).
11717 if (isVirtual) {
11718 if (!D.isInvalidType())
11719 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
11720 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
11722 D.setInvalidType();
11723 }
11724 if (SC == SC_Static) {
11725 if (!D.isInvalidType())
11726 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
11727 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
11729 D.setInvalidType();
11730 SC = SC_None;
11731 }
11732
11733 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
11735 diag::err_constructor_return_type, TypeQuals, SourceLocation(),
11739 D.setInvalidType();
11740 }
11741
11742 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor);
11743 diagnoseInvalidDeclaratorChunks(*this, D, /*constructor*/ 0);
11744
11745 // C++0x [class.ctor]p4:
11746 // A constructor shall not be declared with a ref-qualifier.
11748 if (FTI.hasRefQualifier()) {
11749 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
11752 D.setInvalidType();
11753 }
11754
11755 // Rebuild the function type "R" without any type qualifiers (in
11756 // case any of the errors above fired) and with "void" as the
11757 // return type, since constructors don't have return types.
11758 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
11759 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
11760 return R;
11761
11763 EPI.TypeQuals = Qualifiers();
11764 EPI.RefQualifier = RQ_None;
11765
11766 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
11767}
11768
11770 CXXRecordDecl *ClassDecl
11771 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
11772 if (!ClassDecl)
11773 return Constructor->setInvalidDecl();
11774
11775 // C++ [class.copy]p3:
11776 // A declaration of a constructor for a class X is ill-formed if
11777 // its first parameter is of type (optionally cv-qualified) X and
11778 // either there are no other parameters or else all other
11779 // parameters have default arguments.
11780 if (!Constructor->isInvalidDecl() &&
11781 Constructor->hasOneParamOrDefaultArgs() &&
11782 !Constructor->isFunctionTemplateSpecialization()) {
11783 CanQualType ParamType =
11784 Constructor->getParamDecl(0)->getType()->getCanonicalTypeUnqualified();
11785 CanQualType ClassTy = Context.getCanonicalTagType(ClassDecl);
11786 if (ParamType == ClassTy) {
11787 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
11788 const char *ConstRef
11789 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
11790 : " const &";
11791 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
11792 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
11793
11794 // FIXME: Rather that making the constructor invalid, we should endeavor
11795 // to fix the type.
11796 Constructor->setInvalidDecl();
11797 }
11798 }
11799}
11800
11802 CXXRecordDecl *RD = Destructor->getParent();
11803
11804 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
11805 SourceLocation Loc;
11806
11807 if (!Destructor->isImplicit())
11808 Loc = Destructor->getLocation();
11809 else
11810 Loc = RD->getLocation();
11811
11812 DeclarationName Name =
11813 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
11814 // If we have a virtual destructor, look up the deallocation function
11816 Loc, RD, /*Diagnose=*/true, /*LookForGlobal=*/false, Name)) {
11817 Expr *ThisArg = nullptr;
11818
11819 // If the notional 'delete this' expression requires a non-trivial
11820 // conversion from 'this' to the type of a destroying operator delete's
11821 // first parameter, perform that conversion now.
11822 if (OperatorDelete->isDestroyingOperatorDelete()) {
11823 unsigned AddressParamIndex = 0;
11824 if (OperatorDelete->isTypeAwareOperatorNewOrDelete())
11825 ++AddressParamIndex;
11826 QualType ParamType =
11827 OperatorDelete->getParamDecl(AddressParamIndex)->getType();
11828 if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
11829 // C++ [class.dtor]p13:
11830 // ... as if for the expression 'delete this' appearing in a
11831 // non-virtual destructor of the destructor's class.
11832 ContextRAII SwitchContext(*this, Destructor);
11834 OperatorDelete->getParamDecl(AddressParamIndex)->getLocation());
11835 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
11836 This = PerformImplicitConversion(This.get(), ParamType,
11838 if (This.isInvalid()) {
11839 // FIXME: Register this as a context note so that it comes out
11840 // in the right order.
11841 Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
11842 return true;
11843 }
11844 ThisArg = This.get();
11845 }
11846 }
11847
11848 DiagnoseUseOfDecl(OperatorDelete, Loc);
11849 MarkFunctionReferenced(Loc, OperatorDelete);
11850 Destructor->setOperatorDelete(OperatorDelete, ThisArg);
11851
11852 if (isa<CXXMethodDecl>(OperatorDelete) &&
11853 Context.getTargetInfo().callGlobalDeleteInDeletingDtor(
11854 Context.getLangOpts())) {
11855 // In Microsoft ABI whenever a class has a defined operator delete,
11856 // scalar deleting destructors check the 3rd bit of the implicit
11857 // parameter and if it is set, then, global operator delete must be
11858 // called instead of the class-specific one. Find and save the global
11859 // operator delete for that case. Do not diagnose at this point because
11860 // the lack of a global operator delete is not an error if there are no
11861 // delete calls that require it.
11862 FunctionDecl *GlobalOperatorDelete =
11863 FindDeallocationFunctionForDestructor(Loc, RD, /*Diagnose*/ false,
11864 /*LookForGlobal*/ true, Name);
11865 if (GlobalOperatorDelete) {
11866 MarkFunctionReferenced(Loc, GlobalOperatorDelete);
11867 Destructor->setOperatorGlobalDelete(GlobalOperatorDelete);
11868 }
11869 }
11870
11871 if (Context.getTargetInfo().emitVectorDeletingDtors(
11872 Context.getLangOpts())) {
11873 bool DestructorIsExported = Destructor->hasAttr<DLLExportAttr>();
11874 // Lookup delete[] too in case we have to emit a vector deleting dtor.
11875 DeclarationName VDeleteName =
11876 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
11878 Loc, RD, /*Diagnose*/ false,
11879 /*LookForGlobal*/ false, VDeleteName);
11880 if (ArrOperatorDelete && isa<CXXMethodDecl>(ArrOperatorDelete)) {
11881 FunctionDecl *GlobalArrOperatorDelete =
11882 FindDeallocationFunctionForDestructor(Loc, RD, /*Diagnose*/ false,
11883 /*LookForGlobal*/ true,
11884 VDeleteName);
11885 Destructor->setGlobalOperatorArrayDelete(GlobalArrOperatorDelete);
11886 if (GlobalArrOperatorDelete &&
11887 (Context.classMaybeNeedsVectorDeletingDestructor(RD) ||
11888 DestructorIsExported))
11889 MarkFunctionReferenced(Loc, GlobalArrOperatorDelete);
11890 } else if (!ArrOperatorDelete) {
11891 ArrOperatorDelete = FindDeallocationFunctionForDestructor(
11892 Loc, RD, /*Diagnose*/ false,
11893 /*LookForGlobal*/ true, VDeleteName);
11894 }
11895 Destructor->setOperatorArrayDelete(ArrOperatorDelete);
11896 if (ArrOperatorDelete &&
11897 (Context.classMaybeNeedsVectorDeletingDestructor(RD) ||
11898 DestructorIsExported))
11899 MarkFunctionReferenced(Loc, ArrOperatorDelete);
11900 }
11901 }
11902 }
11903
11904 return false;
11905}
11906
11908 StorageClass& SC) {
11909 // C++ [class.dtor]p1:
11910 // [...] A typedef-name that names a class is a class-name
11911 // (7.1.3); however, a typedef-name that names a class shall not
11912 // be used as the identifier in the declarator for a destructor
11913 // declaration.
11914 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
11915 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
11916 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
11917 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
11918 else if (const TemplateSpecializationType *TST =
11919 DeclaratorType->getAs<TemplateSpecializationType>())
11920 if (TST->isTypeAlias())
11921 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
11922 << DeclaratorType << 1;
11923
11924 // C++ [class.dtor]p2:
11925 // A destructor is used to destroy objects of its class type. A
11926 // destructor takes no parameters, and no return type can be
11927 // specified for it (not even void). The address of a destructor
11928 // shall not be taken. A destructor shall not be static. A
11929 // destructor can be invoked for a const, volatile or const
11930 // volatile object. A destructor shall not be declared const,
11931 // volatile or const volatile (9.3.2).
11932 if (SC == SC_Static) {
11933 if (!D.isInvalidType())
11934 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
11935 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
11938
11939 SC = SC_None;
11940 }
11941 if (!D.isInvalidType()) {
11942 // Destructors don't have return types, but the parser will
11943 // happily parse something like:
11944 //
11945 // class X {
11946 // float ~X();
11947 // };
11948 //
11949 // The return type will be eliminated later.
11950 if (D.getDeclSpec().hasTypeSpecifier())
11951 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
11954 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
11955 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
11961 D.setInvalidType();
11962 }
11963 }
11964
11965 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor);
11966 diagnoseInvalidDeclaratorChunks(*this, D, /*destructor*/ 1);
11967
11968 // C++0x [class.dtor]p2:
11969 // A destructor shall not be declared with a ref-qualifier.
11971 if (FTI.hasRefQualifier()) {
11972 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
11975 D.setInvalidType();
11976 }
11977
11978 // Make sure we don't have any parameters.
11979 if (FTIHasNonVoidParameters(FTI)) {
11980 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
11981
11982 // Delete the parameters.
11983 FTI.freeParams();
11984 D.setInvalidType();
11985 }
11986
11987 // Make sure the destructor isn't variadic.
11988 if (FTI.isVariadic) {
11989 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
11990 D.setInvalidType();
11991 }
11992
11993 // Rebuild the function type "R" without any type qualifiers or
11994 // parameters (in case any of the errors above fired) and with
11995 // "void" as the return type, since destructors don't have return
11996 // types.
11997 if (!D.isInvalidType())
11998 return R;
11999
12000 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
12002 EPI.Variadic = false;
12003 EPI.TypeQuals = Qualifiers();
12004 EPI.RefQualifier = RQ_None;
12005 return Context.getFunctionType(Context.VoidTy, {}, EPI);
12006}
12007
12008static void extendLeft(SourceRange &R, SourceRange Before) {
12009 if (Before.isInvalid())
12010 return;
12011 R.setBegin(Before.getBegin());
12012 if (R.getEnd().isInvalid())
12013 R.setEnd(Before.getEnd());
12014}
12015
12016static void extendRight(SourceRange &R, SourceRange After) {
12017 if (After.isInvalid())
12018 return;
12019 if (R.getBegin().isInvalid())
12020 R.setBegin(After.getBegin());
12021 R.setEnd(After.getEnd());
12022}
12023
12025 StorageClass& SC) {
12026 // C++ [class.conv.fct]p1:
12027 // Neither parameter types nor return type can be specified. The
12028 // type of a conversion function (8.3.5) is "function taking no
12029 // parameter returning conversion-type-id."
12030 if (SC == SC_Static) {
12031 if (!D.isInvalidType())
12032 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
12034 << D.getName().getSourceRange();
12035 D.setInvalidType();
12036 SC = SC_None;
12037 }
12038
12039 TypeSourceInfo *ConvTSI = nullptr;
12040 QualType ConvType =
12042
12043 const DeclSpec &DS = D.getDeclSpec();
12044 if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
12045 // Conversion functions don't have return types, but the parser will
12046 // happily parse something like:
12047 //
12048 // class X {
12049 // float operator bool();
12050 // };
12051 //
12052 // The return type will be changed later anyway.
12053 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
12056 D.setInvalidType();
12057 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
12058 // It's also plausible that the user writes type qualifiers in the wrong
12059 // place, such as:
12060 // struct S { const operator int(); };
12061 // FIXME: we could provide a fixit to move the qualifiers onto the
12062 // conversion type.
12063 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
12064 << SourceRange(D.getIdentifierLoc()) << 0;
12065 D.setInvalidType();
12066 }
12067 const auto *Proto = R->castAs<FunctionProtoType>();
12068 // Make sure we don't have any parameters.
12070 unsigned NumParam = Proto->getNumParams();
12071
12072 // [C++2b]
12073 // A conversion function shall have no non-object parameters.
12074 if (NumParam == 1) {
12076 if (const auto *First =
12077 dyn_cast_if_present<ParmVarDecl>(FTI.Params[0].Param);
12078 First && First->isExplicitObjectParameter())
12079 NumParam--;
12080 }
12081
12082 if (NumParam != 0) {
12083 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
12084 // Delete the parameters.
12085 FTI.freeParams();
12086 D.setInvalidType();
12087 } else if (Proto->isVariadic()) {
12088 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
12089 D.setInvalidType();
12090 }
12091
12092 // Diagnose "&operator bool()" and other such nonsense. This
12093 // is actually a gcc extension which we don't support.
12094 if (Proto->getReturnType() != ConvType) {
12095 bool NeedsTypedef = false;
12096 SourceRange Before, After;
12097
12098 // Walk the chunks and extract information on them for our diagnostic.
12099 bool PastFunctionChunk = false;
12100 for (auto &Chunk : D.type_objects()) {
12101 switch (Chunk.Kind) {
12103 if (!PastFunctionChunk) {
12104 if (Chunk.Fun.HasTrailingReturnType) {
12105 TypeSourceInfo *TRT = nullptr;
12106 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
12107 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
12108 }
12109 PastFunctionChunk = true;
12110 break;
12111 }
12112 [[fallthrough]];
12114 NeedsTypedef = true;
12115 extendRight(After, Chunk.getSourceRange());
12116 break;
12117
12123 extendLeft(Before, Chunk.getSourceRange());
12124 break;
12125
12127 extendLeft(Before, Chunk.Loc);
12128 extendRight(After, Chunk.EndLoc);
12129 break;
12130 }
12131 }
12132
12133 SourceLocation Loc = Before.isValid() ? Before.getBegin() :
12134 After.isValid() ? After.getBegin() :
12135 D.getIdentifierLoc();
12136 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
12137 DB << Before << After;
12138
12139 if (!NeedsTypedef) {
12140 DB << /*don't need a typedef*/0;
12141
12142 // If we can provide a correct fix-it hint, do so.
12143 if (After.isInvalid() && ConvTSI) {
12144 SourceLocation InsertLoc =
12146 DB << FixItHint::CreateInsertion(InsertLoc, " ")
12148 InsertLoc, CharSourceRange::getTokenRange(Before))
12149 << FixItHint::CreateRemoval(Before);
12150 }
12151 } else if (!Proto->getReturnType()->isDependentType()) {
12152 DB << /*typedef*/1 << Proto->getReturnType();
12153 } else if (getLangOpts().CPlusPlus11) {
12154 DB << /*alias template*/2 << Proto->getReturnType();
12155 } else {
12156 DB << /*might not be fixable*/3;
12157 }
12158
12159 // Recover by incorporating the other type chunks into the result type.
12160 // Note, this does *not* change the name of the function. This is compatible
12161 // with the GCC extension:
12162 // struct S { &operator int(); } s;
12163 // int &r = s.operator int(); // ok in GCC
12164 // S::operator int&() {} // error in GCC, function name is 'operator int'.
12165 ConvType = Proto->getReturnType();
12166 }
12167
12168 // C++ [class.conv.fct]p4:
12169 // The conversion-type-id shall not represent a function type nor
12170 // an array type.
12171 if (ConvType->isArrayType()) {
12172 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
12173 ConvType = Context.getPointerType(ConvType);
12174 D.setInvalidType();
12175 } else if (ConvType->isFunctionType()) {
12176 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
12177 ConvType = Context.getPointerType(ConvType);
12178 D.setInvalidType();
12179 }
12180
12181 // Rebuild the function type "R" without any parameters (in case any
12182 // of the errors above fired) and with the conversion type as the
12183 // return type.
12184 if (D.isInvalidType())
12185 R = Context.getFunctionType(ConvType, {}, Proto->getExtProtoInfo());
12186
12187 // C++0x explicit conversion operators.
12188 if (DS.hasExplicitSpecifier())
12190 diag_compat::explicit_conversion_functions)
12192}
12193
12195 assert(Conversion && "Expected to receive a conversion function declaration");
12196
12197 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
12198
12199 // Make sure we aren't redeclaring the conversion function.
12200 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
12201 // C++ [class.conv.fct]p1:
12202 // [...] A conversion function is never used to convert a
12203 // (possibly cv-qualified) object to the (possibly cv-qualified)
12204 // same object type (or a reference to it), to a (possibly
12205 // cv-qualified) base class of that type (or a reference to it),
12206 // or to (possibly cv-qualified) void.
12207 CanQualType ClassType = Context.getCanonicalTagType(ClassDecl);
12208 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
12209 ConvType = ConvTypeRef->getPointeeType();
12210 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
12212 /* Suppress diagnostics for instantiations. */;
12213 else if (Conversion->size_overridden_methods() != 0)
12214 /* Suppress diagnostics for overriding virtual function in a base class. */;
12215 else if (ConvType->isRecordType()) {
12216 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
12217 if (ConvType == ClassType)
12218 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
12219 << ClassType;
12220 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
12221 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
12222 << ClassType << ConvType;
12223 } else if (ConvType->isVoidType()) {
12224 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
12225 << ClassType << ConvType;
12226 }
12227
12228 if (FunctionTemplateDecl *ConversionTemplate =
12229 Conversion->getDescribedFunctionTemplate()) {
12230 if (const auto *ConvTypePtr = ConvType->getAs<PointerType>()) {
12231 ConvType = ConvTypePtr->getPointeeType();
12232 }
12233 if (ConvType->isUndeducedAutoType()) {
12234 Diag(Conversion->getTypeSpecStartLoc(), diag::err_auto_not_allowed)
12235 << getReturnTypeLoc(Conversion).getSourceRange()
12236 << ConvType->castAs<AutoType>()->getKeyword()
12237 << /* in declaration of conversion function template= */ 24;
12238 }
12239
12240 return ConversionTemplate;
12241 }
12242
12243 return Conversion;
12244}
12245
12250
12254
12256 DeclarationName Name, QualType R,
12257 bool IsLambda, DeclContext *DC) {
12258 if (!D.isFunctionDeclarator())
12259 return;
12260
12262 if (FTI.NumParams == 0)
12263 return;
12264 ParmVarDecl *ExplicitObjectParam = nullptr;
12265 for (unsigned Idx = 0; Idx < FTI.NumParams; Idx++) {
12266 const auto &ParamInfo = FTI.Params[Idx];
12267 if (!ParamInfo.Param)
12268 continue;
12269 ParmVarDecl *Param = cast<ParmVarDecl>(ParamInfo.Param);
12270 if (!Param->isExplicitObjectParameter())
12271 continue;
12272 if (Idx == 0) {
12273 ExplicitObjectParam = Param;
12274 continue;
12275 } else {
12276 Diag(Param->getLocation(),
12277 diag::err_explicit_object_parameter_must_be_first)
12278 << IsLambda << Param->getSourceRange();
12279 }
12280 }
12281 if (!ExplicitObjectParam)
12282 return;
12283
12284 if (ExplicitObjectParam->hasDefaultArg()) {
12285 Diag(ExplicitObjectParam->getLocation(),
12286 diag::err_explicit_object_default_arg)
12287 << ExplicitObjectParam->getSourceRange();
12288 D.setInvalidType();
12289 }
12290
12293 D.isStaticMember())) {
12294 Diag(ExplicitObjectParam->getBeginLoc(),
12295 diag::err_explicit_object_parameter_nonmember)
12296 << D.getSourceRange() << /*static=*/0 << IsLambda;
12297 D.setInvalidType();
12298 }
12299
12300 if (D.getDeclSpec().isVirtualSpecified()) {
12301 Diag(ExplicitObjectParam->getBeginLoc(),
12302 diag::err_explicit_object_parameter_nonmember)
12303 << D.getSourceRange() << /*virtual=*/1 << IsLambda;
12304 D.setInvalidType();
12305 }
12306
12307 // Friend declarations require some care. Consider:
12308 //
12309 // namespace N {
12310 // struct A{};
12311 // int f(A);
12312 // }
12313 //
12314 // struct S {
12315 // struct T {
12316 // int f(this T);
12317 // };
12318 //
12319 // friend int T::f(this T); // Allow this.
12320 // friend int f(this S); // But disallow this.
12321 // friend int N::f(this A); // And disallow this.
12322 // };
12323 //
12324 // Here, it seems to suffice to check whether the scope
12325 // specifier designates a class type.
12326 if (D.getDeclSpec().isFriendSpecified() &&
12327 !isa_and_present<CXXRecordDecl>(
12329 Diag(ExplicitObjectParam->getBeginLoc(),
12330 diag::err_explicit_object_parameter_nonmember)
12331 << D.getSourceRange() << /*non-member=*/2 << IsLambda;
12332 D.setInvalidType();
12333 }
12334
12335 if (IsLambda && FTI.hasMutableQualifier()) {
12336 Diag(ExplicitObjectParam->getBeginLoc(),
12337 diag::err_explicit_object_parameter_mutable)
12338 << D.getSourceRange();
12339 }
12340
12341 if (IsLambda)
12342 return;
12343
12344 if (!DC || !DC->isRecord()) {
12345 assert(D.isInvalidType() && "Explicit object parameter in non-member "
12346 "should have been diagnosed already");
12347 return;
12348 }
12349
12350 // CWG2674: constructors and destructors cannot have explicit parameters.
12353 Diag(ExplicitObjectParam->getBeginLoc(),
12354 diag::err_explicit_object_parameter_constructor)
12356 << D.getSourceRange();
12357 D.setInvalidType();
12358 }
12359}
12360
12361namespace {
12362/// Utility class to accumulate and print a diagnostic listing the invalid
12363/// specifier(s) on a declaration.
12364struct BadSpecifierDiagnoser {
12365 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
12366 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
12367 ~BadSpecifierDiagnoser() {
12368 Diagnostic << Specifiers;
12369 }
12370
12371 template<typename T> void check(SourceLocation SpecLoc, T Spec) {
12372 return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
12373 }
12374 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
12375 return check(SpecLoc,
12377 }
12378 void check(SourceLocation SpecLoc, const char *Spec) {
12379 if (SpecLoc.isInvalid()) return;
12380 Diagnostic << SourceRange(SpecLoc, SpecLoc);
12381 if (!Specifiers.empty()) Specifiers += " ";
12382 Specifiers += Spec;
12383 }
12384
12385 Sema &S;
12386 Sema::SemaDiagnosticBuilder Diagnostic;
12387 std::string Specifiers;
12388};
12389}
12390
12392 StorageClass &SC) {
12393 TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
12394 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
12395 assert(GuidedTemplateDecl && "missing template decl for deduction guide");
12396
12397 // C++ [temp.deduct.guide]p3:
12398 // A deduction-gide shall be declared in the same scope as the
12399 // corresponding class template.
12400 if (!CurContext->getRedeclContext()->Equals(
12401 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
12402 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
12403 << GuidedTemplateDecl;
12404 NoteTemplateLocation(*GuidedTemplateDecl);
12405 }
12406
12407 auto &DS = D.getMutableDeclSpec();
12408 // We leave 'friend' and 'virtual' to be rejected in the normal way.
12409 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
12410 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
12411 DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
12412 BadSpecifierDiagnoser Diagnoser(
12413 *this, D.getIdentifierLoc(),
12414 diag::err_deduction_guide_invalid_specifier);
12415
12416 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
12417 DS.ClearStorageClassSpecs();
12418 SC = SC_None;
12419
12420 // 'explicit' is permitted.
12421 Diagnoser.check(DS.getInlineSpecLoc(), "inline");
12422 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
12423 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
12424 DS.ClearConstexprSpec();
12425
12426 Diagnoser.check(DS.getConstSpecLoc(), "const");
12427 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
12428 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
12429 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
12430 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
12431 DS.ClearTypeQualifiers();
12432
12433 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
12434 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
12435 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
12436 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
12437 DS.ClearTypeSpecType();
12438 }
12439
12440 if (D.isInvalidType())
12441 return true;
12442
12443 // Check the declarator is simple enough.
12444 bool FoundFunction = false;
12445 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
12446 if (Chunk.Kind == DeclaratorChunk::Paren)
12447 continue;
12448 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
12450 diag::err_deduction_guide_with_complex_decl)
12451 << D.getSourceRange();
12452 break;
12453 }
12454 if (!Chunk.Fun.hasTrailingReturnType())
12455 return Diag(D.getName().getBeginLoc(),
12456 diag::err_deduction_guide_no_trailing_return_type);
12457
12458 // Check that the return type is written as a specialization of
12459 // the template specified as the deduction-guide's name.
12460 // The template name may not be qualified. [temp.deduct.guide]
12461 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
12462 TypeSourceInfo *TSI = nullptr;
12463 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
12464 assert(TSI && "deduction guide has valid type but invalid return type?");
12465 bool AcceptableReturnType = false;
12466 bool MightInstantiateToSpecialization = false;
12467 if (auto RetTST =
12469 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
12470 bool TemplateMatches = Context.hasSameTemplateName(
12471 SpecifiedName, GuidedTemplate, /*IgnoreDeduced=*/true);
12472
12474 SpecifiedName.getAsQualifiedTemplateName();
12475 // A Template template parameter is never wrapped in a
12476 // QualifiedTemplateName, but it's always simply-written.
12477 bool SimplyWritten = !Qualifiers || (!Qualifiers->hasTemplateKeyword() &&
12478 !Qualifiers->getQualifier());
12479 if (SimplyWritten && TemplateMatches)
12480 AcceptableReturnType = true;
12481 else {
12482 // This could still instantiate to the right type, unless we know it
12483 // names the wrong class template.
12484 auto *TD = SpecifiedName.getAsTemplateDecl();
12485 MightInstantiateToSpecialization =
12486 !(TD && isa<ClassTemplateDecl>(TD) && !TemplateMatches);
12487 }
12488 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
12489 MightInstantiateToSpecialization = true;
12490 }
12491
12492 if (!AcceptableReturnType)
12493 return Diag(TSI->getTypeLoc().getBeginLoc(),
12494 diag::err_deduction_guide_bad_trailing_return_type)
12495 << GuidedTemplate << TSI->getType()
12496 << MightInstantiateToSpecialization
12497 << TSI->getTypeLoc().getSourceRange();
12498
12499 // Keep going to check that we don't have any inner declarator pieces (we
12500 // could still have a function returning a pointer to a function).
12501 FoundFunction = true;
12502 }
12503
12504 if (D.isFunctionDefinition())
12505 // we can still create a valid deduction guide here.
12506 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
12507 return false;
12508}
12509
12510//===----------------------------------------------------------------------===//
12511// Namespace Handling
12512//===----------------------------------------------------------------------===//
12513
12514/// Diagnose a mismatch in 'inline' qualifiers when a namespace is
12515/// reopened.
12517 SourceLocation Loc,
12518 IdentifierInfo *II, bool *IsInline,
12519 NamespaceDecl *PrevNS) {
12520 assert(*IsInline != PrevNS->isInline());
12521
12522 // 'inline' must appear on the original definition, but not necessarily
12523 // on all extension definitions, so the note should point to the first
12524 // definition to avoid confusion.
12525 PrevNS = PrevNS->getFirstDecl();
12526
12527 if (PrevNS->isInline())
12528 // The user probably just forgot the 'inline', so suggest that it
12529 // be added back.
12530 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
12531 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
12532 else
12533 S.Diag(Loc, diag::err_inline_namespace_mismatch);
12534
12535 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
12536 *IsInline = PrevNS->isInline();
12537}
12538
12539/// ActOnStartNamespaceDef - This is called at the start of a namespace
12540/// definition.
12542 SourceLocation InlineLoc,
12543 SourceLocation NamespaceLoc,
12544 SourceLocation IdentLoc, IdentifierInfo *II,
12545 SourceLocation LBrace,
12546 const ParsedAttributesView &AttrList,
12547 UsingDirectiveDecl *&UD, bool IsNested) {
12548 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
12549 // For anonymous namespace, take the location of the left brace.
12550 SourceLocation Loc = II ? IdentLoc : LBrace;
12551 bool IsInline = InlineLoc.isValid();
12552 bool IsInvalid = false;
12553 bool IsStd = false;
12554 bool AddToKnown = false;
12555 Scope *DeclRegionScope = NamespcScope->getParent();
12556
12557 NamespaceDecl *PrevNS = nullptr;
12558 if (II) {
12559 // C++ [namespace.std]p7:
12560 // A translation unit shall not declare namespace std to be an inline
12561 // namespace (9.8.2).
12562 //
12563 // Precondition: the std namespace is in the file scope and is declared to
12564 // be inline
12565 auto DiagnoseInlineStdNS = [&]() {
12566 assert(IsInline && II->isStr("std") &&
12567 CurContext->getRedeclContext()->isTranslationUnit() &&
12568 "Precondition of DiagnoseInlineStdNS not met");
12569 Diag(InlineLoc, diag::err_inline_namespace_std)
12570 << SourceRange(InlineLoc, InlineLoc.getLocWithOffset(6));
12571 IsInline = false;
12572 };
12573 // C++ [namespace.def]p2:
12574 // The identifier in an original-namespace-definition shall not
12575 // have been previously defined in the declarative region in
12576 // which the original-namespace-definition appears. The
12577 // identifier in an original-namespace-definition is the name of
12578 // the namespace. Subsequently in that declarative region, it is
12579 // treated as an original-namespace-name.
12580 //
12581 // Since namespace names are unique in their scope, and we don't
12582 // look through using directives, just look for any ordinary names
12583 // as if by qualified name lookup.
12584 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
12586 LookupQualifiedName(R, CurContext->getRedeclContext());
12587 NamedDecl *PrevDecl =
12588 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
12589 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
12590
12591 if (PrevNS) {
12592 // This is an extended namespace definition.
12593 if (IsInline && II->isStr("std") &&
12594 CurContext->getRedeclContext()->isTranslationUnit())
12595 DiagnoseInlineStdNS();
12596 else if (IsInline != PrevNS->isInline())
12597 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
12598 &IsInline, PrevNS);
12599 } else if (PrevDecl) {
12600 // This is an invalid name redefinition.
12601 Diag(Loc, diag::err_redefinition_different_kind)
12602 << II;
12603 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12604 IsInvalid = true;
12605 // Continue on to push Namespc as current DeclContext and return it.
12606 } else if (II->isStr("std") &&
12607 CurContext->getRedeclContext()->isTranslationUnit()) {
12608 if (IsInline)
12609 DiagnoseInlineStdNS();
12610 // This is the first "real" definition of the namespace "std", so update
12611 // our cache of the "std" namespace to point at this definition.
12612 PrevNS = getStdNamespace();
12613 IsStd = true;
12614 AddToKnown = !IsInline;
12615 } else {
12616 // We've seen this namespace for the first time.
12617 AddToKnown = !IsInline;
12618 }
12619 } else {
12620 // Anonymous namespaces.
12621
12622 // Determine whether the parent already has an anonymous namespace.
12623 DeclContext *Parent = CurContext->getRedeclContext();
12624 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
12625 PrevNS = TU->getAnonymousNamespace();
12626 } else {
12627 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
12628 PrevNS = ND->getAnonymousNamespace();
12629 }
12630
12631 if (PrevNS && IsInline != PrevNS->isInline())
12632 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
12633 &IsInline, PrevNS);
12634 }
12635
12636 // Namespace lookup can find a namespace in an inline namespace. An extension
12637 // of that namespace retains its semantic parent, even when it is written in
12638 // an enclosing namespace.
12639 DeclContext *SemanticContext = CurContext;
12640 if (PrevNS && !CurContext->getRedeclContext()->Equals(
12641 PrevNS->getDeclContext()->getRedeclContext()))
12642 SemanticContext = PrevNS->getDeclContext();
12644 Context, SemanticContext, IsInline, StartLoc, Loc, II, PrevNS, IsNested);
12646 if (IsInvalid)
12647 Namespc->setInvalidDecl();
12648
12649 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
12650 AddPragmaAttributes(DeclRegionScope, Namespc);
12651 ProcessAPINotes(Namespc);
12652
12653 // FIXME: Should we be merging attributes?
12654 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
12656
12657 if (IsStd)
12658 StdNamespace = Namespc;
12659 if (AddToKnown)
12660 KnownNamespaces[Namespc] = false;
12661
12662 if (II) {
12663 PushOnScopeChains(Namespc, DeclRegionScope);
12664 } else {
12665 // Link the anonymous namespace into its parent.
12666 DeclContext *Parent = CurContext->getRedeclContext();
12667 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
12668 TU->setAnonymousNamespace(Namespc);
12669 } else {
12670 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
12671 }
12672
12673 CurContext->addDecl(Namespc);
12674
12675 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
12676 // behaves as if it were replaced by
12677 // namespace unique { /* empty body */ }
12678 // using namespace unique;
12679 // namespace unique { namespace-body }
12680 // where all occurrences of 'unique' in a translation unit are
12681 // replaced by the same identifier and this identifier differs
12682 // from all other identifiers in the entire program.
12683
12684 // We just create the namespace with an empty name and then add an
12685 // implicit using declaration, just like the standard suggests.
12686 //
12687 // CodeGen enforces the "universally unique" aspect by giving all
12688 // declarations semantically contained within an anonymous
12689 // namespace internal linkage.
12690
12691 if (!PrevNS) {
12693 /* 'using' */ LBrace,
12694 /* 'namespace' */ SourceLocation(),
12695 /* qualifier */ NestedNameSpecifierLoc(),
12696 /* identifier */ SourceLocation(),
12697 Namespc,
12698 /* Ancestor */ Parent);
12699 UD->setImplicit();
12700 Parent->addDecl(UD);
12701 }
12702 }
12703
12704 ActOnDocumentableDecl(Namespc);
12705
12706 // Although we could have an invalid decl (i.e. the namespace name is a
12707 // redefinition), push it as current DeclContext and try to continue parsing.
12708 // FIXME: We should be able to push Namespc here, so that the each DeclContext
12709 // for the namespace has the declarations that showed up in that particular
12710 // namespace definition.
12711 PushDeclContext(NamespcScope, Namespc);
12712 return Namespc;
12713}
12714
12715/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
12716/// is a namespace alias, returns the namespace it points to.
12718 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
12719 return AD->getNamespace();
12720 return dyn_cast_or_null<NamespaceDecl>(D);
12721}
12722
12724 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
12725 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
12726 Namespc->setRBraceLoc(RBrace);
12728 if (Namespc->hasAttr<VisibilityAttr>())
12729 PopPragmaVisibility(true, RBrace);
12730 // If this namespace contains an export-declaration, export it now.
12731 if (DeferredExportedNamespaces.erase(Namespc))
12733}
12734
12736 return cast_or_null<CXXRecordDecl>(
12737 StdBadAlloc.get(Context.getExternalSource()));
12738}
12739
12741 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
12742}
12743
12745 return cast_or_null<NamespaceDecl>(
12746 StdNamespace.get(Context.getExternalSource()));
12747}
12748
12749namespace {
12750
12751enum UnsupportedSTLSelect {
12752 USS_InvalidMember,
12753 USS_MissingMember,
12754 USS_NonTrivial,
12755 USS_Other
12756};
12757
12758struct InvalidSTLDiagnoser {
12759 Sema &S;
12760 SourceLocation Loc;
12761 QualType TyForDiags;
12762
12763 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
12764 const VarDecl *VD = nullptr) {
12765 {
12766 auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
12767 << TyForDiags << ((int)Sel);
12768 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
12769 assert(!Name.empty());
12770 D << Name;
12771 }
12772 }
12773 if (Sel == USS_InvalidMember) {
12774 S.Diag(VD->getLocation(), diag::note_var_declared_here)
12775 << VD << VD->getSourceRange();
12776 }
12777 return QualType();
12778 }
12779};
12780} // namespace
12781
12783 SourceLocation Loc,
12785 assert(getLangOpts().CPlusPlus &&
12786 "Looking for comparison category type outside of C++.");
12787
12788 // Use an elaborated type for diagnostics which has a name containing the
12789 // prepended 'std' namespace but not any inline namespace names.
12790 auto TyForDiags = [&](ComparisonCategoryInfo *Info) {
12792 /*Prefix=*/std::nullopt);
12793 return Context.getTagType(ElaboratedTypeKeyword::None, Qualifier,
12794 Info->Record,
12795 /*OwnsTag=*/false);
12796 };
12797
12798 // Check if we've already successfully checked the comparison category type
12799 // before. If so, skip checking it again.
12800 ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
12801 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) {
12802 // The only thing we need to check is that the type has a reachable
12803 // definition in the current context.
12804 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
12805 return QualType();
12806
12807 return Info->getType();
12808 }
12809
12810 // If lookup failed
12811 if (!Info) {
12812 std::string NameForDiags = "std::";
12813 NameForDiags += ComparisonCategories::getCategoryString(Kind);
12814 Diag(Loc, diag::err_implied_comparison_category_type_not_found)
12815 << NameForDiags << (int)Usage;
12816 return QualType();
12817 }
12818
12819 assert(Info->Kind == Kind);
12820 assert(Info->Record);
12821
12822 // Update the Record decl in case we encountered a forward declaration on our
12823 // first pass. FIXME: This is a bit of a hack.
12824 if (Info->Record->hasDefinition())
12825 Info->Record = Info->Record->getDefinition();
12826
12827 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
12828 return QualType();
12829
12830 InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)};
12831
12832 if (!Info->Record->isTriviallyCopyable())
12833 return UnsupportedSTLError(USS_NonTrivial);
12834
12835 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
12836 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
12837 // Tolerate empty base classes.
12838 if (Base->isEmpty())
12839 continue;
12840 // Reject STL implementations which have at least one non-empty base.
12841 return UnsupportedSTLError();
12842 }
12843
12844 // Check that the STL has implemented the types using a single integer field.
12845 // This expectation allows better codegen for builtin operators. We require:
12846 // (1) The class has exactly one field.
12847 // (2) The field is an integral or enumeration type.
12848 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
12849 if (std::distance(FIt, FEnd) != 1 ||
12850 !FIt->getType()->isIntegralOrEnumerationType()) {
12851 return UnsupportedSTLError();
12852 }
12853
12854 // Build each of the require values and store them in Info.
12855 for (ComparisonCategoryResult CCR :
12857 StringRef MemName = ComparisonCategories::getResultString(CCR);
12858 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
12859
12860 if (!ValInfo)
12861 return UnsupportedSTLError(USS_MissingMember, MemName);
12862
12863 VarDecl *VD = ValInfo->VD;
12864 assert(VD && "should not be null!");
12865
12866 // Attempt to diagnose reasons why the STL definition of this type
12867 // might be foobar, including it failing to be a constant expression.
12868 // TODO Handle more ways the lookup or result can be invalid.
12869 if (!VD->isStaticDataMember() ||
12871 return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
12872
12873 // Attempt to evaluate the var decl as a constant expression and extract
12874 // the value of its first field as a ICE. If this fails, the STL
12875 // implementation is not supported.
12876 if (!ValInfo->hasValidIntValue())
12877 return UnsupportedSTLError();
12878
12879 MarkVariableReferenced(Loc, VD);
12880 }
12881
12882 // We've successfully built the required types and expressions. Update
12883 // the cache and return the newly cached value.
12884 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
12885 return Info->getType();
12886}
12887
12889 if (!StdNamespace) {
12890 // The "std" namespace has not yet been defined, so build one implicitly.
12892 Context, Context.getTranslationUnitDecl(),
12893 /*Inline=*/false, SourceLocation(), SourceLocation(),
12894 &PP.getIdentifierTable().get("std"),
12895 /*PrevDecl=*/nullptr, /*Nested=*/false);
12896 getStdNamespace()->setImplicit(true);
12897 // We want the created NamespaceDecl to be available for redeclaration
12898 // lookups, but not for regular name lookups.
12899 Context.getTranslationUnitDecl()->addDecl(getStdNamespace());
12900 getStdNamespace()->clearIdentifierNamespace();
12901 }
12902
12903 return getStdNamespace();
12904}
12905
12906static bool isStdClassTemplate(Sema &S, QualType SugaredType, QualType *TypeArg,
12907 const char *ClassName,
12908 ClassTemplateDecl **CachedDecl,
12909 const Decl **MalformedDecl) {
12910 // We're looking for implicit instantiations of
12911 // template <typename U> class std::{ClassName}.
12912
12913 if (!S.StdNamespace) // If we haven't seen namespace std yet, this can't be
12914 // it.
12915 return false;
12916
12917 auto ReportMatchingNameAsMalformed = [&](NamedDecl *D) {
12918 if (!MalformedDecl)
12919 return;
12920 if (!D)
12921 D = SugaredType->getAsTagDecl();
12922 if (!D || !D->isInStdNamespace())
12923 return;
12924 IdentifierInfo *II = D->getDeclName().getAsIdentifierInfo();
12925 if (II && II == &S.PP.getIdentifierTable().get(ClassName))
12926 *MalformedDecl = D;
12927 };
12928
12929 ClassTemplateDecl *Template = nullptr;
12931 if (const TemplateSpecializationType *TST =
12933 Template = dyn_cast_or_null<ClassTemplateDecl>(
12934 TST->getTemplateName().getAsTemplateDecl());
12935 Arguments = TST->template_arguments();
12936 } else if (const auto *TT = SugaredType->getAs<TagType>()) {
12937 Template = TT->getTemplateDecl();
12938 Arguments = TT->getTemplateArgs(S.Context);
12939 }
12940
12941 if (!Template) {
12942 ReportMatchingNameAsMalformed(SugaredType->getAsTagDecl());
12943 return false;
12944 }
12945
12946 if (!*CachedDecl) {
12947 // Haven't recognized std::{ClassName} yet, maybe this is it.
12948 // FIXME: It seems we should just reuse LookupStdClassTemplate but the
12949 // semantics of this are slightly different, most notably the existing
12950 // "lookup" semantics explicitly diagnose an invalid definition as an
12951 // error.
12952 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
12953 if (TemplateClass->getIdentifier() !=
12954 &S.PP.getIdentifierTable().get(ClassName) ||
12956 TemplateClass->getNonTransparentDeclContext()))
12957 return false;
12958 // This is a template called std::{ClassName}, but is it the right
12959 // template?
12960 TemplateParameterList *Params = Template->getTemplateParameters();
12961 if (Params->getMinRequiredArguments() != 1 ||
12962 !isa<TemplateTypeParmDecl>(Params->getParam(0)) ||
12963 Params->getParam(0)->isTemplateParameterPack()) {
12964 if (MalformedDecl)
12965 *MalformedDecl = TemplateClass;
12966 return false;
12967 }
12968
12969 // It's the right template.
12970 *CachedDecl = Template;
12971 }
12972
12973 if (Template->getCanonicalDecl() != (*CachedDecl)->getCanonicalDecl())
12974 return false;
12975
12976 // This is an instance of std::{ClassName}. Find the argument type.
12977 if (TypeArg) {
12978 QualType ArgType = Arguments[0].getAsType();
12979 // FIXME: Since TST only has as-written arguments, we have to perform the
12980 // only kind of conversion applicable to type arguments; in Objective-C ARC:
12981 // - If an explicitly-specified template argument type is a lifetime type
12982 // with no lifetime qualifier, the __strong lifetime qualifier is
12983 // inferred.
12984 if (S.getLangOpts().ObjCAutoRefCount && ArgType->isObjCLifetimeType() &&
12985 !ArgType.getObjCLifetime()) {
12986 Qualifiers Qs;
12988 ArgType = S.Context.getQualifiedType(ArgType, Qs);
12989 }
12990 *TypeArg = ArgType;
12991 }
12992
12993 return true;
12994}
12995
12997 assert(getLangOpts().CPlusPlus &&
12998 "Looking for std::initializer_list outside of C++.");
12999
13000 // We're looking for implicit instantiations of
13001 // template <typename E> class std::initializer_list.
13002
13003 return isStdClassTemplate(*this, Ty, Element, "initializer_list",
13004 &StdInitializerList, /*MalformedDecl=*/nullptr);
13005}
13006
13008 const Decl **MalformedDecl) {
13009 assert(getLangOpts().CPlusPlus &&
13010 "Looking for std::type_identity outside of C++.");
13011
13012 // We're looking for implicit instantiations of
13013 // template <typename T> struct std::type_identity.
13014
13015 return isStdClassTemplate(*this, Ty, Element, "type_identity",
13016 &StdTypeIdentity, MalformedDecl);
13017}
13018
13020 const char *ClassName,
13021 bool *WasMalformed) {
13022 if (!S.StdNamespace)
13023 return nullptr;
13024
13025 LookupResult Result(S, &S.PP.getIdentifierTable().get(ClassName), Loc,
13028 return nullptr;
13029
13031 if (!Template) {
13032 Result.suppressDiagnostics();
13033 // We found something weird. Complain about the first thing we found.
13034 NamedDecl *Found = *Result.begin();
13035 S.Diag(Found->getLocation(), diag::err_malformed_std_class_template)
13036 << ClassName;
13037 if (WasMalformed)
13038 *WasMalformed = true;
13039 return nullptr;
13040 }
13041
13042 // We found some template with the correct name. Now verify that it's
13043 // correct.
13044 TemplateParameterList *Params = Template->getTemplateParameters();
13045 if (Params->getMinRequiredArguments() != 1 ||
13046 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
13047 S.Diag(Template->getLocation(), diag::err_malformed_std_class_template)
13048 << ClassName;
13049 if (WasMalformed)
13050 *WasMalformed = true;
13051 return nullptr;
13052 }
13053
13054 return Template;
13055}
13056
13058 QualType TypeParam, SourceLocation Loc) {
13059 assert(S.getStdNamespace());
13060 TemplateArgumentListInfo Args(Loc, Loc);
13061 auto TSI = S.Context.getTrivialTypeSourceInfo(TypeParam, Loc);
13062 Args.addArgument(TemplateArgumentLoc(TemplateArgument(TypeParam), TSI));
13063
13065 Loc, Args, /*Scope=*/nullptr,
13066 /*ForNestedNameSpecifier=*/false);
13067}
13068
13070 if (!StdInitializerList) {
13071 bool WasMalformed = false;
13073 LookupStdClassTemplate(*this, Loc, "initializer_list", &WasMalformed);
13074 if (!StdInitializerList) {
13075 if (!WasMalformed)
13076 Diag(Loc, diag::err_implied_std_initializer_list_not_found);
13077 return QualType();
13078 }
13079 }
13080 return BuildStdClassTemplate(*this, StdInitializerList, Element, Loc);
13081}
13082
13084 if (!StdTypeIdentity) {
13085 StdTypeIdentity = LookupStdClassTemplate(*this, Loc, "type_identity",
13086 /*WasMalformed=*/nullptr);
13087 if (!StdTypeIdentity)
13088 return QualType();
13089 }
13090 return BuildStdClassTemplate(*this, StdTypeIdentity, Type, Loc);
13091}
13092
13094 // C++ [dcl.init.list]p2:
13095 // A constructor is an initializer-list constructor if its first parameter
13096 // is of type std::initializer_list<E> or reference to possibly cv-qualified
13097 // std::initializer_list<E> for some type E, and either there are no other
13098 // parameters or else all other parameters have default arguments.
13099 if (!Ctor->hasOneParamOrDefaultArgs())
13100 return false;
13101
13102 QualType ArgType = Ctor->getParamDecl(0)->getType();
13103 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
13104 ArgType = RT->getPointeeType().getUnqualifiedType();
13105
13106 return isStdInitializerList(ArgType, nullptr);
13107}
13108
13109/// Determine whether a using statement is in a context where it will be
13110/// apply in all contexts.
13112 switch (CurContext->getDeclKind()) {
13113 case Decl::TranslationUnit:
13114 return true;
13115 case Decl::LinkageSpec:
13116 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
13117 default:
13118 return false;
13119 }
13120}
13121
13122namespace {
13123
13124// Callback to only accept typo corrections that are namespaces.
13125class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
13126public:
13127 bool ValidateCandidate(const TypoCorrection &candidate) override {
13128 if (NamedDecl *ND = candidate.getCorrectionDecl())
13130 return false;
13131 }
13132
13133 std::unique_ptr<CorrectionCandidateCallback> clone() override {
13134 return std::make_unique<NamespaceValidatorCCC>(*this);
13135 }
13136};
13137
13138}
13139
13140static void DiagnoseInvisibleNamespace(const TypoCorrection &Corrected,
13141 Sema &S) {
13142 auto *ND = cast<NamespaceDecl>(Corrected.getFoundDecl());
13143 Module *M = ND->getOwningModule();
13144 assert(M && "hidden namespace definition not in a module?");
13145
13146 if (M->isExplicitGlobalModule())
13147 S.Diag(Corrected.getCorrectionRange().getBegin(),
13148 diag::err_module_unimported_use_header)
13150 << /*Header Name*/ false;
13151 else
13152 S.Diag(Corrected.getCorrectionRange().getBegin(),
13153 diag::err_module_unimported_use)
13155 << M->getTopLevelModuleName();
13156}
13157
13159 CXXScopeSpec &SS,
13160 SourceLocation IdentLoc,
13161 IdentifierInfo *Ident) {
13162 R.clear();
13163 NamespaceValidatorCCC CCC{};
13164 if (TypoCorrection Corrected =
13165 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
13167 // Generally we find it is confusing more than helpful to diagnose the
13168 // invisible namespace.
13169 // See https://github.com/llvm/llvm-project/issues/73893.
13170 //
13171 // However, we should diagnose when the users are trying to using an
13172 // invisible namespace. So we handle the case specially here.
13173 if (isa_and_nonnull<NamespaceDecl>(Corrected.getFoundDecl()) &&
13174 Corrected.requiresImport()) {
13175 DiagnoseInvisibleNamespace(Corrected, S);
13176 } else if (DeclContext *DC = S.computeDeclContext(SS, false)) {
13177 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
13178 bool DroppedSpecifier =
13179 Corrected.WillReplaceSpecifier() && Ident->getName() == CorrectedStr;
13180 S.diagnoseTypo(Corrected,
13181 S.PDiag(diag::err_using_directive_member_suggest)
13182 << Ident << DC << DroppedSpecifier << SS.getRange(),
13183 S.PDiag(diag::note_namespace_defined_here));
13184 } else {
13185 S.diagnoseTypo(Corrected,
13186 S.PDiag(diag::err_using_directive_suggest) << Ident,
13187 S.PDiag(diag::note_namespace_defined_here));
13188 }
13189 R.addDecl(Corrected.getFoundDecl());
13190 return true;
13191 }
13192 return false;
13193}
13194
13196 SourceLocation NamespcLoc, CXXScopeSpec &SS,
13197 SourceLocation IdentLoc,
13198 IdentifierInfo *NamespcName,
13199 const ParsedAttributesView &AttrList) {
13200 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
13201 assert(NamespcName && "Invalid NamespcName.");
13202 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
13203
13204 // Get the innermost enclosing declaration scope.
13205 S = S->getDeclParent();
13206
13207 UsingDirectiveDecl *UDir = nullptr;
13208 NestedNameSpecifier Qualifier = SS.getScopeRep();
13209
13210 // Lookup namespace name.
13211 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
13212 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
13213 if (R.isAmbiguous())
13214 return nullptr;
13215
13216 if (R.empty()) {
13217 R.clear();
13218 // Allow "using namespace std;" or "using namespace ::std;" even if
13219 // "std" hasn't been defined yet, for GCC compatibility.
13220 if ((!Qualifier ||
13221 Qualifier.getKind() == NestedNameSpecifier::Kind::Global) &&
13222 NamespcName->isStr("std")) {
13223 Diag(IdentLoc, diag::ext_using_undefined_std);
13224 R.addDecl(getOrCreateStdNamespace());
13225 R.resolveKind();
13226 }
13227 // Otherwise, attempt typo correction.
13228 else
13229 TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
13230 }
13231
13232 if (!R.empty()) {
13233 NamedDecl *Named = R.getRepresentativeDecl();
13234 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
13235 assert(NS && "expected namespace decl");
13236
13237 // The use of a nested name specifier may trigger deprecation warnings.
13238 DiagnoseUseOfDecl(Named, IdentLoc);
13239
13240 // C++ [namespace.udir]p1:
13241 // A using-directive specifies that the names in the nominated
13242 // namespace can be used in the scope in which the
13243 // using-directive appears after the using-directive. During
13244 // unqualified name lookup (3.4.1), the names appear as if they
13245 // were declared in the nearest enclosing namespace which
13246 // contains both the using-directive and the nominated
13247 // namespace. [Note: in this context, "contains" means "contains
13248 // directly or indirectly". ]
13249
13250 // Find enclosing context containing both using-directive and
13251 // nominated namespace.
13252 DeclContext *CommonAncestor = NS;
13253 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
13254 CommonAncestor = CommonAncestor->getParent();
13255
13256 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
13258 IdentLoc, Named, CommonAncestor);
13259
13261 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
13262 Diag(IdentLoc, diag::warn_using_directive_in_header);
13263 }
13264
13265 PushUsingDirective(S, UDir);
13266 } else {
13267 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
13268 }
13269
13270 if (UDir) {
13271 ProcessDeclAttributeList(S, UDir, AttrList);
13272 ProcessAPINotes(UDir);
13273 }
13274
13275 return UDir;
13276}
13277
13279 // If the scope has an associated entity and the using directive is at
13280 // namespace or translation unit scope, add the UsingDirectiveDecl into
13281 // its lookup structure so qualified name lookup can find it.
13282 DeclContext *Ctx = S->getEntity();
13283 if (Ctx && !Ctx->isFunctionOrMethod())
13284 Ctx->addDecl(UDir);
13285 else
13286 // Otherwise, it is at block scope. The using-directives will affect lookup
13287 // only to the end of the scope.
13288 S->PushUsingDirective(UDir);
13289}
13290
13292 SourceLocation UsingLoc,
13293 SourceLocation TypenameLoc, CXXScopeSpec &SS,
13294 UnqualifiedId &Name,
13295 SourceLocation EllipsisLoc,
13296 const ParsedAttributesView &AttrList) {
13297 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
13298
13299 if (SS.isEmpty()) {
13300 Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
13301 return nullptr;
13302 }
13303
13304 switch (Name.getKind()) {
13310 break;
13311
13314 // C++11 inheriting constructors.
13315 Diag(Name.getBeginLoc(),
13317 ? diag::warn_cxx98_compat_using_decl_constructor
13318 : diag::err_using_decl_constructor)
13319 << SS.getRange();
13320
13321 if (getLangOpts().CPlusPlus11) break;
13322
13323 return nullptr;
13324
13326 Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
13327 return nullptr;
13328
13330 Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
13332 return nullptr;
13333
13335 llvm_unreachable("cannot parse qualified deduction guide name");
13336 }
13337
13338 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
13339 DeclarationName TargetName = TargetNameInfo.getName();
13340 if (!TargetName)
13341 return nullptr;
13342
13343 // Warn about access declarations.
13344 if (UsingLoc.isInvalid()) {
13346 ? diag::err_access_decl
13347 : diag::warn_access_decl_deprecated)
13348 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
13349 }
13350
13351 if (EllipsisLoc.isInvalid()) {
13354 return nullptr;
13355 } else {
13357 !TargetNameInfo.containsUnexpandedParameterPack()) {
13358 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
13359 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
13360 EllipsisLoc = SourceLocation();
13361 }
13362 }
13363
13364 NamedDecl *UD =
13365 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
13366 SS, TargetNameInfo, EllipsisLoc, AttrList,
13367 /*IsInstantiation*/ false,
13368 AttrList.hasAttribute(ParsedAttr::AT_UsingIfExists));
13369 if (UD)
13370 PushOnScopeChains(UD, S, /*AddToContext*/ false);
13371
13372 return UD;
13373}
13374
13376 SourceLocation UsingLoc,
13377 SourceLocation EnumLoc, SourceRange TyLoc,
13378 const IdentifierInfo &II, ParsedType Ty,
13379 const CXXScopeSpec &SS) {
13380 TypeSourceInfo *TSI = nullptr;
13381 SourceLocation IdentLoc = TyLoc.getBegin();
13382 QualType EnumTy = GetTypeFromParser(Ty, &TSI);
13383 if (EnumTy.isNull()) {
13384 Diag(IdentLoc, isDependentScopeSpecifier(SS)
13385 ? diag::err_using_enum_is_dependent
13386 : diag::err_unknown_typename)
13387 << II.getName()
13388 << SourceRange(SS.isValid() ? SS.getBeginLoc() : IdentLoc,
13389 TyLoc.getEnd());
13390 return nullptr;
13391 }
13392
13393 if (EnumTy->isDependentType()) {
13394 Diag(IdentLoc, diag::err_using_enum_is_dependent);
13395 return nullptr;
13396 }
13397
13398 auto *Enum = EnumTy->getAsEnumDecl();
13399 if (!Enum) {
13400 Diag(IdentLoc, diag::err_using_enum_not_enum) << EnumTy;
13401 return nullptr;
13402 }
13403
13404 if (TSI == nullptr)
13405 TSI = Context.getTrivialTypeSourceInfo(EnumTy, IdentLoc);
13406
13407 auto *UD =
13408 BuildUsingEnumDeclaration(S, AS, UsingLoc, EnumLoc, IdentLoc, TSI, Enum);
13409
13410 if (UD)
13411 PushOnScopeChains(UD, S, /*AddToContext*/ false);
13412
13413 return UD;
13414}
13415
13416/// Determine whether a using declaration considers the given
13417/// declarations as "equivalent", e.g., if they are redeclarations of
13418/// the same entity or are both typedefs of the same type.
13419static bool
13421 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
13422 return true;
13423
13424 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
13425 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
13426 return Context.hasSameType(TD1->getUnderlyingType(),
13427 TD2->getUnderlyingType());
13428
13429 // Two using_if_exists using-declarations are equivalent if both are
13430 // unresolved.
13433 return true;
13434
13435 return false;
13436}
13437
13439 const LookupResult &Previous,
13440 UsingShadowDecl *&PrevShadow) {
13441 // Diagnose finding a decl which is not from a base class of the
13442 // current class. We do this now because there are cases where this
13443 // function will silently decide not to build a shadow decl, which
13444 // will pre-empt further diagnostics.
13445 //
13446 // We don't need to do this in C++11 because we do the check once on
13447 // the qualifier.
13448 //
13449 // FIXME: diagnose the following if we care enough:
13450 // struct A { int foo; };
13451 // struct B : A { using A::foo; };
13452 // template <class T> struct C : A {};
13453 // template <class T> struct D : C<T> { using B::foo; } // <---
13454 // This is invalid (during instantiation) in C++03 because B::foo
13455 // resolves to the using decl in B, which is not a base class of D<T>.
13456 // We can't diagnose it immediately because C<T> is an unknown
13457 // specialization. The UsingShadowDecl in D<T> then points directly
13458 // to A::foo, which will look well-formed when we instantiate.
13459 // The right solution is to not collapse the shadow-decl chain.
13460 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord())
13461 if (auto *Using = dyn_cast<UsingDecl>(BUD)) {
13462 DeclContext *OrigDC = Orig->getDeclContext();
13463
13464 // Handle enums and anonymous structs.
13465 if (isa<EnumDecl>(OrigDC))
13466 OrigDC = OrigDC->getParent();
13467 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
13468 while (OrigRec->isAnonymousStructOrUnion())
13469 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
13470
13472 if (OrigDC == CurContext) {
13473 Diag(Using->getLocation(),
13474 diag::err_using_decl_nested_name_specifier_is_current_class)
13475 << Using->getQualifierLoc().getSourceRange();
13476 Diag(Orig->getLocation(), diag::note_using_decl_target);
13477 Using->setInvalidDecl();
13478 return true;
13479 }
13480
13481 Diag(Using->getQualifierLoc().getBeginLoc(),
13482 diag::err_using_decl_nested_name_specifier_is_not_base_class)
13483 << Using->getQualifier() << cast<CXXRecordDecl>(CurContext)
13484 << Using->getQualifierLoc().getSourceRange();
13485 Diag(Orig->getLocation(), diag::note_using_decl_target);
13486 Using->setInvalidDecl();
13487 return true;
13488 }
13489 }
13490
13491 if (Previous.empty()) return false;
13492
13493 NamedDecl *Target = Orig;
13495 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
13496
13497 // If the target happens to be one of the previous declarations, we
13498 // don't have a conflict.
13499 //
13500 // FIXME: but we might be increasing its access, in which case we
13501 // should redeclare it.
13502 NamedDecl *NonTag = nullptr, *Tag = nullptr;
13503 bool FoundEquivalentDecl = false;
13504 for (NamedDecl *Element : Previous) {
13505 NamedDecl *D = Element->getUnderlyingDecl();
13506 // We can have UsingDecls in our Previous results because we use the same
13507 // LookupResult for checking whether the UsingDecl itself is a valid
13508 // redeclaration.
13510 continue;
13511
13512 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
13513 // C++ [class.mem]p19:
13514 // If T is the name of a class, then [every named member other than
13515 // a non-static data member] shall have a name different from T
13516 if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
13520 CurContext,
13522 return true;
13523 }
13524
13526 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Element))
13527 PrevShadow = Shadow;
13528 FoundEquivalentDecl = true;
13530 // We don't conflict with an existing using shadow decl of an equivalent
13531 // declaration, but we're not a redeclaration of it.
13532 FoundEquivalentDecl = true;
13533 }
13534
13535 if (isVisible(D))
13536 (isa<TagDecl>(D) ? Tag : NonTag) = D;
13537 }
13538
13539 if (FoundEquivalentDecl)
13540 return false;
13541
13542 // Always emit a diagnostic for a mismatch between an unresolved
13543 // using_if_exists and a resolved using declaration in either direction.
13545 (isa_and_nonnull<UnresolvedUsingIfExistsDecl>(NonTag))) {
13546 if (!NonTag && !Tag)
13547 return false;
13548 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
13549 Diag(Target->getLocation(), diag::note_using_decl_target);
13550 Diag((NonTag ? NonTag : Tag)->getLocation(),
13551 diag::note_using_decl_conflict);
13552 BUD->setInvalidDecl();
13553 return true;
13554 }
13555
13556 if (FunctionDecl *FD = Target->getAsFunction()) {
13557 NamedDecl *OldDecl = nullptr;
13558 switch (CheckOverload(nullptr, FD, Previous, OldDecl,
13559 /*IsForUsingDecl*/ true)) {
13561 return false;
13562
13564 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
13565 break;
13566
13567 // We found a decl with the exact signature.
13569 // If we're in a record, we want to hide the target, so we
13570 // return true (without a diagnostic) to tell the caller not to
13571 // build a shadow decl.
13572 if (CurContext->isRecord())
13573 return true;
13574
13575 // If we're not in a record, this is an error.
13576 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
13577 break;
13578 }
13579
13580 Diag(Target->getLocation(), diag::note_using_decl_target);
13581 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
13582 BUD->setInvalidDecl();
13583 return true;
13584 }
13585
13586 // Target is not a function.
13587
13588 if (isa<TagDecl>(Target)) {
13589 // No conflict between a tag and a non-tag.
13590 if (!Tag) return false;
13591
13592 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
13593 Diag(Target->getLocation(), diag::note_using_decl_target);
13594 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
13595 BUD->setInvalidDecl();
13596 return true;
13597 }
13598
13599 // No conflict between a tag and a non-tag.
13600 if (!NonTag) return false;
13601
13602 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
13603 Diag(Target->getLocation(), diag::note_using_decl_target);
13604 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
13605 BUD->setInvalidDecl();
13606 return true;
13607}
13608
13609/// Determine whether a direct base class is a virtual base class.
13611 if (!Derived->getNumVBases())
13612 return false;
13613 for (auto &B : Derived->bases())
13614 if (B.getType()->getAsCXXRecordDecl() == Base)
13615 return B.isVirtual();
13616 llvm_unreachable("not a direct base class");
13617}
13618
13620 NamedDecl *Orig,
13621 UsingShadowDecl *PrevDecl) {
13622 // If we resolved to another shadow declaration, just coalesce them.
13623 NamedDecl *Target = Orig;
13625 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
13626 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
13627 }
13628
13629 NamedDecl *NonTemplateTarget = Target;
13630 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
13631 NonTemplateTarget = TargetTD->getTemplatedDecl();
13632
13633 UsingShadowDecl *Shadow;
13634 if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) {
13635 UsingDecl *Using = cast<UsingDecl>(BUD);
13636 bool IsVirtualBase =
13638 Using->getQualifier().getAsRecordDecl());
13640 Context, CurContext, Using->getLocation(), Using, Orig, IsVirtualBase);
13641 } else {
13643 Target->getDeclName(), BUD, Target);
13644 }
13645 BUD->addShadowDecl(Shadow);
13646
13647 Shadow->setAccess(BUD->getAccess());
13648 if (Orig->isInvalidDecl() || BUD->isInvalidDecl())
13649 Shadow->setInvalidDecl();
13650
13651 Shadow->setPreviousDecl(PrevDecl);
13652
13653 if (S)
13654 PushOnScopeChains(Shadow, S);
13655 else
13656 CurContext->addDecl(Shadow);
13657
13658
13659 return Shadow;
13660}
13661
13663 if (Shadow->getDeclName().getNameKind() ==
13665 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
13666
13667 // Remove it from the DeclContext...
13668 Shadow->getDeclContext()->removeDecl(Shadow);
13669
13670 // ...and the scope, if applicable...
13671 if (S) {
13672 S->RemoveDecl(Shadow);
13673 IdResolver.RemoveDecl(Shadow);
13674 }
13675
13676 // ...and the using decl.
13677 Shadow->getIntroducer()->removeShadowDecl(Shadow);
13678
13679 // TODO: complain somehow if Shadow was used. It shouldn't
13680 // be possible for this to happen, because...?
13681}
13682
13683/// Find the base specifier for a base class with the given type.
13685 QualType DesiredBase,
13686 bool &AnyDependentBases) {
13687 // Check whether the named type is a direct base class.
13688 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
13689 for (auto &Base : Derived->bases()) {
13690 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
13691 if (CanonicalDesiredBase == BaseType)
13692 return &Base;
13693 if (BaseType->isDependentType())
13694 AnyDependentBases = true;
13695 }
13696 return nullptr;
13697}
13698
13699namespace {
13700class UsingValidatorCCC final : public CorrectionCandidateCallback {
13701public:
13702 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
13703 NestedNameSpecifier NNS, CXXRecordDecl *RequireMemberOf)
13704 : HasTypenameKeyword(HasTypenameKeyword),
13705 IsInstantiation(IsInstantiation), OldNNS(NNS),
13706 RequireMemberOf(RequireMemberOf) {}
13707
13708 bool ValidateCandidate(const TypoCorrection &Candidate) override {
13709 NamedDecl *ND = Candidate.getCorrectionDecl();
13710
13711 // Keywords are not valid here.
13712 if (!ND || isa<NamespaceDecl>(ND))
13713 return false;
13714
13715 // Completely unqualified names are invalid for a 'using' declaration.
13716 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
13717 return false;
13718
13719 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
13720 // reject.
13721
13722 if (RequireMemberOf) {
13723 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
13724 if (FoundRecord && FoundRecord->isInjectedClassName()) {
13725 // No-one ever wants a using-declaration to name an injected-class-name
13726 // of a base class, unless they're declaring an inheriting constructor.
13727 ASTContext &Ctx = ND->getASTContext();
13728 if (!Ctx.getLangOpts().CPlusPlus11)
13729 return false;
13730 CanQualType FoundType = Ctx.getCanonicalTagType(FoundRecord);
13731
13732 // Check that the injected-class-name is named as a member of its own
13733 // type; we don't want to suggest 'using Derived::Base;', since that
13734 // means something else.
13735 NestedNameSpecifier Specifier = Candidate.WillReplaceSpecifier()
13736 ? Candidate.getCorrectionSpecifier()
13737 : OldNNS;
13738 if (Specifier.getKind() != NestedNameSpecifier::Kind::Type ||
13739 !Ctx.hasSameType(QualType(Specifier.getAsType(), 0), FoundType))
13740 return false;
13741
13742 // Check that this inheriting constructor declaration actually names a
13743 // direct base class of the current class.
13744 bool AnyDependentBases = false;
13745 if (!findDirectBaseWithType(RequireMemberOf,
13746 Ctx.getCanonicalTagType(FoundRecord),
13747 AnyDependentBases) &&
13748 !AnyDependentBases)
13749 return false;
13750 } else {
13751 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
13752 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
13753 return false;
13754
13755 // FIXME: Check that the base class member is accessible?
13756 }
13757 } else {
13758 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
13759 if (FoundRecord && FoundRecord->isInjectedClassName())
13760 return false;
13761 }
13762
13763 if (isa<TypeDecl>(ND))
13764 return HasTypenameKeyword || !IsInstantiation;
13765
13766 return !HasTypenameKeyword;
13767 }
13768
13769 std::unique_ptr<CorrectionCandidateCallback> clone() override {
13770 return std::make_unique<UsingValidatorCCC>(*this);
13771 }
13772
13773private:
13774 bool HasTypenameKeyword;
13775 bool IsInstantiation;
13776 NestedNameSpecifier OldNNS;
13777 CXXRecordDecl *RequireMemberOf;
13778};
13779} // end anonymous namespace
13780
13782 // It is really dumb that we have to do this.
13783 LookupResult::Filter F = Previous.makeFilter();
13784 while (F.hasNext()) {
13785 NamedDecl *D = F.next();
13786 if (!isDeclInScope(D, CurContext, S))
13787 F.erase();
13788 // If we found a local extern declaration that's not ordinarily visible,
13789 // and this declaration is being added to a non-block scope, ignore it.
13790 // We're only checking for scope conflicts here, not also for violations
13791 // of the linkage rules.
13792 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
13794 F.erase();
13795 }
13796 F.done();
13797}
13798
13800 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
13801 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
13802 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
13803 const ParsedAttributesView &AttrList, bool IsInstantiation,
13804 bool IsUsingIfExists) {
13805 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
13806 SourceLocation IdentLoc = NameInfo.getLoc();
13807 assert(IdentLoc.isValid() && "Invalid TargetName location.");
13808
13809 // FIXME: We ignore attributes for now.
13810
13811 // For an inheriting constructor declaration, the name of the using
13812 // declaration is the name of a constructor in this class, not in the
13813 // base class.
13814 DeclarationNameInfo UsingName = NameInfo;
13816 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
13817 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
13818 Context.getCanonicalTagType(RD)));
13819
13820 // Do the redeclaration lookup in the current scope.
13821 LookupResult Previous(*this, UsingName, LookupUsingDeclName,
13823 Previous.setHideTags(false);
13824 if (S) {
13825 LookupName(Previous, S);
13826
13828 } else {
13829 assert(IsInstantiation && "no scope in non-instantiation");
13830 if (CurContext->isRecord())
13832 else {
13833 // No redeclaration check is needed here; in non-member contexts we
13834 // diagnosed all possible conflicts with other using-declarations when
13835 // building the template:
13836 //
13837 // For a dependent non-type using declaration, the only valid case is
13838 // if we instantiate to a single enumerator. We check for conflicts
13839 // between shadow declarations we introduce, and we check in the template
13840 // definition for conflicts between a non-type using declaration and any
13841 // other declaration, which together covers all cases.
13842 //
13843 // A dependent typename using declaration will never successfully
13844 // instantiate, since it will always name a class member, so we reject
13845 // that in the template definition.
13846 }
13847 }
13848
13849 // Check for invalid redeclarations.
13850 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
13851 SS, IdentLoc, Previous))
13852 return nullptr;
13853
13854 // 'using_if_exists' doesn't make sense on an inherited constructor.
13855 if (IsUsingIfExists && UsingName.getName().getNameKind() ==
13857 Diag(UsingLoc, diag::err_using_if_exists_on_ctor);
13858 return nullptr;
13859 }
13860
13861 DeclContext *LookupContext = computeDeclContext(SS);
13863 if (!LookupContext || EllipsisLoc.isValid()) {
13864 NamedDecl *D;
13865 // Dependent scope, or an unexpanded pack
13866 if (!LookupContext && CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword,
13867 SS, NameInfo, IdentLoc))
13868 return nullptr;
13869
13870 if (Previous.isSingleResult() &&
13871 Previous.getFoundDecl()->isTemplateParameter())
13872 DiagnoseTemplateParameterShadow(IdentLoc, Previous.getFoundDecl());
13873
13874 if (HasTypenameKeyword) {
13875 // FIXME: not all declaration name kinds are legal here
13877 UsingLoc, TypenameLoc,
13878 QualifierLoc,
13879 IdentLoc, NameInfo.getName(),
13880 EllipsisLoc);
13881 } else {
13883 QualifierLoc, NameInfo, EllipsisLoc);
13884 }
13885 D->setAccess(AS);
13886 CurContext->addDecl(D);
13887 ProcessDeclAttributeList(S, D, AttrList);
13888 return D;
13889 }
13890
13891 auto Build = [&](bool Invalid) {
13892 UsingDecl *UD =
13893 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
13894 UsingName, HasTypenameKeyword);
13895 UD->setAccess(AS);
13896 CurContext->addDecl(UD);
13897 ProcessDeclAttributeList(S, UD, AttrList);
13899 return UD;
13900 };
13901 auto BuildInvalid = [&]{ return Build(true); };
13902 auto BuildValid = [&]{ return Build(false); };
13903
13904 if (RequireCompleteDeclContext(SS, LookupContext))
13905 return BuildInvalid();
13906
13907 // Look up the target name.
13908 LookupResult R(*this, NameInfo, LookupOrdinaryName);
13909
13910 // Unlike most lookups, we don't always want to hide tag
13911 // declarations: tag names are visible through the using declaration
13912 // even if hidden by ordinary names, *except* in a dependent context
13913 // where they may be used by two-phase lookup.
13914 if (!IsInstantiation)
13915 R.setHideTags(false);
13916
13917 // For the purposes of this lookup, we have a base object type
13918 // equal to that of the current context.
13919 if (CurContext->isRecord()) {
13920 R.setBaseObjectType(
13921 Context.getCanonicalTagType(cast<CXXRecordDecl>(CurContext)));
13922 }
13923
13924 LookupQualifiedName(R, LookupContext);
13925
13926 // Validate the context, now we have a lookup
13927 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
13928 IdentLoc, &R))
13929 return nullptr;
13930
13931 if (R.empty() && IsUsingIfExists)
13933 UsingName.getName()),
13934 AS_public);
13935
13936 // Try to correct typos if possible. If constructor name lookup finds no
13937 // results, that means the named class has no explicit constructors, and we
13938 // suppressed declaring implicit ones (probably because it's dependent or
13939 // invalid).
13940 if (R.empty() &&
13942 // HACK 2017-01-08: Work around an issue with libstdc++'s detection of
13943 // ::gets. Sometimes it believes that glibc provides a ::gets in cases where
13944 // it does not. The issue was fixed in libstdc++ 6.3 (2016-12-21) and later.
13945 auto *II = NameInfo.getName().getAsIdentifierInfo();
13946 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
13947 CurContext->isStdNamespace() &&
13948 isa<TranslationUnitDecl>(LookupContext) &&
13949 PP.NeedsStdLibCxxWorkaroundBefore(2016'12'21) &&
13950 getSourceManager().isInSystemHeader(UsingLoc))
13951 return nullptr;
13952 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
13953 dyn_cast<CXXRecordDecl>(CurContext));
13954 if (TypoCorrection Corrected =
13955 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
13957 // We reject candidates where DroppedSpecifier == true, hence the
13958 // literal '0' below.
13959 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
13960 << NameInfo.getName() << LookupContext << 0
13961 << SS.getRange());
13962
13963 // If we picked a correction with no attached Decl we can't do anything
13964 // useful with it, bail out.
13965 NamedDecl *ND = Corrected.getCorrectionDecl();
13966 if (!ND)
13967 return BuildInvalid();
13968
13969 // If we corrected to an inheriting constructor, handle it as one.
13970 auto *RD = dyn_cast<CXXRecordDecl>(ND);
13971 if (RD && RD->isInjectedClassName()) {
13972 // The parent of the injected class name is the class itself.
13973 RD = cast<CXXRecordDecl>(RD->getParent());
13974
13975 // Fix up the information we'll use to build the using declaration.
13976 if (Corrected.WillReplaceSpecifier()) {
13978 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
13979 QualifierLoc.getSourceRange());
13980 QualifierLoc = Builder.getWithLocInContext(Context);
13981 }
13982
13983 // In this case, the name we introduce is the name of a derived class
13984 // constructor.
13985 auto *CurClass = cast<CXXRecordDecl>(CurContext);
13986 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
13987 Context.getCanonicalTagType(CurClass)));
13988 UsingName.setNamedTypeInfo(nullptr);
13989 for (auto *Ctor : LookupConstructors(RD))
13990 R.addDecl(Ctor);
13991 R.resolveKind();
13992 } else {
13993 // FIXME: Pick up all the declarations if we found an overloaded
13994 // function.
13995 UsingName.setName(ND->getDeclName());
13996 R.addDecl(ND);
13997 }
13998 } else {
13999 Diag(IdentLoc, diag::err_no_member)
14000 << NameInfo.getName() << LookupContext << SS.getRange();
14001 return BuildInvalid();
14002 }
14003 }
14004
14005 if (R.isAmbiguous())
14006 return BuildInvalid();
14007
14008 if (HasTypenameKeyword) {
14009 // If we asked for a typename and got a non-type decl, error out.
14010 if (!R.getAsSingle<TypeDecl>() &&
14011 !R.getAsSingle<UnresolvedUsingIfExistsDecl>()) {
14012 Diag(IdentLoc, diag::err_using_typename_non_type);
14013 for (const NamedDecl *D : R)
14014 Diag(D->getUnderlyingDecl()->getLocation(),
14015 diag::note_using_decl_target);
14016 return BuildInvalid();
14017 }
14018 } else {
14019 // If we asked for a non-typename and we got a type, error out,
14020 // but only if this is an instantiation of an unresolved using
14021 // decl. Otherwise just silently find the type name.
14022 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
14023 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
14024 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
14025 return BuildInvalid();
14026 }
14027 }
14028
14029 // C++14 [namespace.udecl]p6:
14030 // A using-declaration shall not name a namespace.
14031 if (R.getAsSingle<NamespaceDecl>()) {
14032 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
14033 << SS.getRange();
14034 // Suggest using 'using namespace ...' instead.
14035 Diag(SS.getBeginLoc(), diag::note_namespace_using_decl)
14036 << FixItHint::CreateInsertion(SS.getBeginLoc(), "namespace ");
14037 return BuildInvalid();
14038 }
14039
14040 UsingDecl *UD = BuildValid();
14041
14042 // Some additional rules apply to inheriting constructors.
14043 if (UsingName.getName().getNameKind() ==
14045 // Suppress access diagnostics; the access check is instead performed at the
14046 // point of use for an inheriting constructor.
14047 R.suppressDiagnostics();
14049 return UD;
14050 }
14051
14052 for (NamedDecl *D : R) {
14053 UsingShadowDecl *PrevDecl = nullptr;
14054 if (!CheckUsingShadowDecl(UD, D, Previous, PrevDecl))
14055 BuildUsingShadowDecl(S, UD, D, PrevDecl);
14056 }
14057
14058 return UD;
14059}
14060
14062 SourceLocation UsingLoc,
14063 SourceLocation EnumLoc,
14064 SourceLocation NameLoc,
14065 TypeSourceInfo *EnumType,
14066 EnumDecl *ED) {
14067 bool Invalid = false;
14068
14069 if (CurContext->getRedeclContext()->isRecord()) {
14070 /// In class scope, check if this is a duplicate, for better a diagnostic.
14071 DeclarationNameInfo UsingEnumName(ED->getDeclName(), NameLoc);
14072 LookupResult Previous(*this, UsingEnumName, LookupUsingDeclName,
14074
14076
14077 for (NamedDecl *D : Previous)
14078 if (UsingEnumDecl *UED = dyn_cast<UsingEnumDecl>(D))
14079 if (UED->getEnumDecl() == ED) {
14080 Diag(UsingLoc, diag::err_using_enum_decl_redeclaration)
14081 << SourceRange(EnumLoc, NameLoc);
14082 Diag(D->getLocation(), diag::note_using_enum_decl) << 1;
14083 Invalid = true;
14084 break;
14085 }
14086 }
14087
14088 if (RequireCompleteEnumDecl(ED, NameLoc))
14089 Invalid = true;
14090
14092 EnumLoc, NameLoc, EnumType);
14093 UD->setAccess(AS);
14094 CurContext->addDecl(UD);
14095
14096 if (Invalid) {
14097 UD->setInvalidDecl();
14098 return UD;
14099 }
14100
14101 // Create the shadow decls for each enumerator
14102 for (EnumConstantDecl *EC : ED->enumerators()) {
14103 UsingShadowDecl *PrevDecl = nullptr;
14104 DeclarationNameInfo DNI(EC->getDeclName(), EC->getLocation());
14107 LookupName(Previous, S);
14109
14110 if (!CheckUsingShadowDecl(UD, EC, Previous, PrevDecl))
14111 BuildUsingShadowDecl(S, UD, EC, PrevDecl);
14112 }
14113
14114 return UD;
14115}
14116
14118 ArrayRef<NamedDecl *> Expansions) {
14119 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
14120 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
14121 isa<UsingPackDecl>(InstantiatedFrom));
14122
14123 auto *UPD =
14124 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
14125 UPD->setAccess(InstantiatedFrom->getAccess());
14126 CurContext->addDecl(UPD);
14127 return UPD;
14128}
14129
14131 assert(!UD->hasTypename() && "expecting a constructor name");
14132
14133 QualType SourceType(UD->getQualifier().getAsType(), 0);
14135
14136 // Check whether the named type is a direct base class.
14137 bool AnyDependentBases = false;
14138 auto *Base =
14139 findDirectBaseWithType(TargetClass, SourceType, AnyDependentBases);
14140 if (!Base && !AnyDependentBases) {
14141 Diag(UD->getUsingLoc(), diag::err_using_decl_constructor_not_in_direct_base)
14142 << UD->getNameInfo().getSourceRange() << SourceType << TargetClass;
14143 UD->setInvalidDecl();
14144 return true;
14145 }
14146
14147 if (Base)
14148 Base->setInheritConstructors();
14149
14150 return false;
14151}
14152
14154 bool HasTypenameKeyword,
14155 const CXXScopeSpec &SS,
14156 SourceLocation NameLoc,
14157 const LookupResult &Prev) {
14158 NestedNameSpecifier Qual = SS.getScopeRep();
14159
14160 // C++03 [namespace.udecl]p8:
14161 // C++0x [namespace.udecl]p10:
14162 // A using-declaration is a declaration and can therefore be used
14163 // repeatedly where (and only where) multiple declarations are
14164 // allowed.
14165 //
14166 // That's in non-member contexts.
14167 if (!CurContext->getRedeclContext()->isRecord()) {
14168 // A dependent qualifier outside a class can only ever resolve to an
14169 // enumeration type. Therefore it conflicts with any other non-type
14170 // declaration in the same scope.
14171 // FIXME: How should we check for dependent type-type conflicts at block
14172 // scope?
14173 if (Qual.isDependent() && !HasTypenameKeyword) {
14174 for (auto *D : Prev) {
14175 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
14176 bool OldCouldBeEnumerator =
14178 Diag(NameLoc,
14179 OldCouldBeEnumerator ? diag::err_redefinition
14180 : diag::err_redefinition_different_kind)
14181 << Prev.getLookupName();
14182 Diag(D->getLocation(), diag::note_previous_definition);
14183 return true;
14184 }
14185 }
14186 }
14187 return false;
14188 }
14189
14190 NestedNameSpecifier CNNS = Qual.getCanonical();
14191 for (const NamedDecl *D : Prev) {
14192 bool DTypename;
14193 NestedNameSpecifier DQual = std::nullopt;
14194 if (const auto *UD = dyn_cast<UsingDecl>(D)) {
14195 DTypename = UD->hasTypename();
14196 DQual = UD->getQualifier();
14197 } else if (const auto *UD = dyn_cast<UnresolvedUsingValueDecl>(D)) {
14198 DTypename = false;
14199 DQual = UD->getQualifier();
14200 } else if (const auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
14201 DTypename = true;
14202 DQual = UD->getQualifier();
14203 } else
14204 continue;
14205
14206 // using decls differ if one says 'typename' and the other doesn't.
14207 // FIXME: non-dependent using decls?
14208 if (HasTypenameKeyword != DTypename) continue;
14209
14210 // using decls differ if they name different scopes (but note that
14211 // template instantiation can cause this check to trigger when it
14212 // didn't before instantiation).
14213 if (CNNS != DQual.getCanonical())
14214 continue;
14215
14216 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
14217 Diag(D->getLocation(), diag::note_using_decl) << 1;
14218 return true;
14219 }
14220
14221 return false;
14222}
14223
14224bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
14225 const CXXScopeSpec &SS,
14226 const DeclarationNameInfo &NameInfo,
14227 SourceLocation NameLoc,
14228 const LookupResult *R, const UsingDecl *UD) {
14229 DeclContext *NamedContext = computeDeclContext(SS);
14230 assert(bool(NamedContext) == (R || UD) && !(R && UD) &&
14231 "resolvable context must have exactly one set of decls");
14232
14233 // C++ 20 permits using an enumerator that does not have a class-hierarchy
14234 // relationship.
14235 bool Cxx20Enumerator = false;
14236 if (NamedContext) {
14237 EnumConstantDecl *EC = nullptr;
14238 if (R)
14239 EC = R->getAsSingle<EnumConstantDecl>();
14240 else if (UD && UD->shadow_size() == 1)
14241 EC = dyn_cast<EnumConstantDecl>(UD->shadow_begin()->getTargetDecl());
14242 if (EC)
14243 Cxx20Enumerator = getLangOpts().CPlusPlus20;
14244
14245 if (auto *ED = dyn_cast<EnumDecl>(NamedContext)) {
14246 // C++14 [namespace.udecl]p7:
14247 // A using-declaration shall not name a scoped enumerator.
14248 // C++20 p1099 permits enumerators.
14249 if (EC && R && ED->isScoped())
14250 DiagCompat(SS.getBeginLoc(), diag_compat::using_decl_scoped_enumerator)
14251 << SS.getRange();
14252
14253 // We want to consider the scope of the enumerator
14254 NamedContext = ED->getDeclContext();
14255 }
14256 }
14257
14258 if (!CurContext->isRecord()) {
14259 // C++03 [namespace.udecl]p3:
14260 // C++0x [namespace.udecl]p8:
14261 // A using-declaration for a class member shall be a member-declaration.
14262 // C++20 [namespace.udecl]p7
14263 // ... other than an enumerator ...
14264
14265 // If we weren't able to compute a valid scope, it might validly be a
14266 // dependent class or enumeration scope. If we have a 'typename' keyword,
14267 // the scope must resolve to a class type.
14268 if (NamedContext ? !NamedContext->getRedeclContext()->isRecord()
14269 : !HasTypename)
14270 return false; // OK
14271
14272 Diag(NameLoc,
14273 Cxx20Enumerator
14274 ? diag::warn_cxx17_compat_using_decl_class_member_enumerator
14275 : diag::err_using_decl_can_not_refer_to_class_member)
14276 << SS.getRange();
14277
14278 if (Cxx20Enumerator)
14279 return false; // OK
14280
14281 auto *RD = NamedContext
14282 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
14283 : nullptr;
14284 if (RD && !RequireCompleteDeclContext(const_cast<CXXScopeSpec &>(SS), RD)) {
14285 // See if there's a helpful fixit
14286
14287 if (!R) {
14288 // We will have already diagnosed the problem on the template
14289 // definition, Maybe we should do so again?
14290 } else if (R->getAsSingle<TypeDecl>()) {
14291 if (getLangOpts().CPlusPlus11) {
14292 // Convert 'using X::Y;' to 'using Y = X::Y;'.
14293 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
14294 << diag::MemClassWorkaround::AliasDecl
14296 NameInfo.getName().getAsString() +
14297 " = ");
14298 } else {
14299 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
14300 SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
14301 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
14302 << diag::MemClassWorkaround::TypedefDecl
14303 << FixItHint::CreateReplacement(UsingLoc, "typedef")
14305 InsertLoc, " " + NameInfo.getName().getAsString());
14306 }
14307 } else if (R->getAsSingle<VarDecl>()) {
14308 // Don't provide a fixit outside C++11 mode; we don't want to suggest
14309 // repeating the type of the static data member here.
14310 FixItHint FixIt;
14311 if (getLangOpts().CPlusPlus11) {
14312 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
14314 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
14315 }
14316
14317 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
14318 << diag::MemClassWorkaround::ReferenceDecl << FixIt;
14319 } else if (R->getAsSingle<EnumConstantDecl>()) {
14320 // Don't provide a fixit outside C++11 mode; we don't want to suggest
14321 // repeating the type of the enumeration here, and we can't do so if
14322 // the type is anonymous.
14323 FixItHint FixIt;
14324 if (getLangOpts().CPlusPlus11) {
14325 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
14327 UsingLoc,
14328 "constexpr auto " + NameInfo.getName().getAsString() + " = ");
14329 }
14330
14331 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
14332 << (getLangOpts().CPlusPlus11
14333 ? diag::MemClassWorkaround::ConstexprVar
14334 : diag::MemClassWorkaround::ConstVar)
14335 << FixIt;
14336 }
14337 }
14338
14339 return true; // Fail
14340 }
14341
14342 // If the named context is dependent, we can't decide much.
14343 if (!NamedContext) {
14344 // FIXME: in C++0x, we can diagnose if we can prove that the
14345 // nested-name-specifier does not refer to a base class, which is
14346 // still possible in some cases.
14347
14348 // Otherwise we have to conservatively report that things might be
14349 // okay.
14350 return false;
14351 }
14352
14353 // The current scope is a record.
14354 if (!NamedContext->isRecord()) {
14355 // Ideally this would point at the last name in the specifier,
14356 // but we don't have that level of source info.
14357 Diag(SS.getBeginLoc(),
14358 Cxx20Enumerator
14359 ? diag::warn_cxx17_compat_using_decl_non_member_enumerator
14360 : diag::err_using_decl_nested_name_specifier_is_not_class)
14361 << SS.getScopeRep() << SS.getRange();
14362
14363 if (Cxx20Enumerator)
14364 return false; // OK
14365
14366 return true;
14367 }
14368
14369 if (!NamedContext->isDependentContext() &&
14370 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
14371 return true;
14372
14373 // C++26 [namespace.udecl]p3:
14374 // In a using-declaration used as a member-declaration, each
14375 // using-declarator shall either name an enumerator or have a
14376 // nested-name-specifier naming a base class of the current class
14377 // ([expr.prim.this]). ...
14378 // "have a nested-name-specifier naming a base class of the current class"
14379 // was introduced by CWG400.
14380
14383
14384 if (Cxx20Enumerator) {
14385 Diag(NameLoc, diag::warn_cxx17_compat_using_decl_non_member_enumerator)
14386 << SS.getScopeRep() << SS.getRange();
14387 return false;
14388 }
14389
14390 if (CurContext == NamedContext) {
14391 Diag(SS.getBeginLoc(),
14392 diag::err_using_decl_nested_name_specifier_is_current_class)
14393 << SS.getRange();
14394 return true;
14395 }
14396
14397 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
14398 Diag(SS.getBeginLoc(),
14399 diag::err_using_decl_nested_name_specifier_is_not_base_class)
14401 << SS.getRange();
14402 }
14403 return true;
14404 }
14405
14406 return false;
14407}
14408
14410 MultiTemplateParamsArg TemplateParamLists,
14411 SourceLocation UsingLoc, UnqualifiedId &Name,
14412 const ParsedAttributesView &AttrList,
14413 TypeResult Type, Decl *DeclFromDeclSpec) {
14414
14415 if (Type.isInvalid())
14416 return nullptr;
14417
14418 bool Invalid = false;
14420 TypeSourceInfo *TInfo = nullptr;
14421 GetTypeFromParser(Type.get(), &TInfo);
14422
14423 if (DiagnoseClassNameShadow(CurContext, NameInfo))
14424 return nullptr;
14425
14428 Invalid = true;
14429 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
14430 TInfo->getTypeLoc().getBeginLoc());
14431 }
14432
14433 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
14434 TemplateParamLists.size()
14437 LookupName(Previous, S);
14438
14439 // Warn about shadowing the name of a template parameter.
14440 if (Previous.isSingleResult() &&
14441 Previous.getFoundDecl()->isTemplateParameter()) {
14443 Previous.clear();
14444 }
14445
14446 assert(Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
14447 "name in alias declaration must be an identifier");
14449 Name.StartLocation,
14450 Name.Identifier, TInfo);
14451
14452 NewTD->setAccess(AS);
14453
14454 if (Invalid)
14455 NewTD->setInvalidDecl();
14456
14457 ProcessDeclAttributeList(S, NewTD, AttrList);
14458 AddPragmaAttributes(S, NewTD);
14459 ProcessAPINotes(NewTD);
14460
14462 Invalid |= NewTD->isInvalidDecl();
14463
14464 // Get the innermost enclosing declaration scope.
14465 S = S->getDeclParent();
14466
14467 bool Redeclaration = false;
14468
14469 NamedDecl *NewND;
14470 if (TemplateParamLists.size()) {
14471 TypeAliasTemplateDecl *OldDecl = nullptr;
14472 TemplateParameterList *OldTemplateParams = nullptr;
14473
14474 TemplateParameterList *TemplateParams = TemplateParamLists[0];
14475 if (TemplateParamLists.size() != 1) {
14476 Diag(UsingLoc, diag::err_alias_template_extra_headers)
14477 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
14478 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
14479 Invalid = true;
14480
14481 // Recover by picking the last non-empty template parameter list.
14482 auto It = llvm::find_if(
14483 llvm::reverse(TemplateParamLists),
14484 [](TemplateParameterList *TPL) { return !TPL->empty(); });
14485 assert(It != TemplateParamLists.rend() &&
14486 "if all template parameter lists were empty, this should have "
14487 "been rejected as an explicit specialization");
14488 TemplateParams = *It;
14489 }
14490
14491 // Check that we can declare a template here.
14492 if (CheckTemplateDeclScope(S, TemplateParams))
14493 return nullptr;
14494
14495 // Only consider previous declarations in the same scope.
14496 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
14497 /*ExplicitInstantiationOrSpecialization*/false);
14498 if (!Previous.empty()) {
14499 Redeclaration = true;
14500
14501 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
14502 if (!OldDecl && !Invalid) {
14503 Diag(UsingLoc, diag::err_redefinition_different_kind)
14504 << Name.Identifier;
14505
14506 NamedDecl *OldD = Previous.getRepresentativeDecl();
14507 if (OldD->getLocation().isValid())
14508 Diag(OldD->getLocation(), diag::note_previous_definition);
14509
14510 Invalid = true;
14511 }
14512
14513 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
14514 if (TemplateParameterListsAreEqual(TemplateParams,
14515 OldDecl->getTemplateParameters(),
14516 /*Complain=*/true,
14518 OldTemplateParams =
14520 else
14521 Invalid = true;
14522
14523 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
14524 if (!Invalid &&
14525 !Context.hasSameType(OldTD->getUnderlyingType(),
14526 NewTD->getUnderlyingType())) {
14527 // FIXME: The C++0x standard does not clearly say this is ill-formed,
14528 // but we can't reasonably accept it.
14529 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
14530 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
14531 if (OldTD->getLocation().isValid())
14532 Diag(OldTD->getLocation(), diag::note_previous_definition);
14533 Invalid = true;
14534 }
14535 }
14536 }
14537
14538 // Merge any previous default template arguments into our parameters,
14539 // and check the parameter list.
14540 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
14541 TPC_Other))
14542 return nullptr;
14543
14544 TypeAliasTemplateDecl *NewDecl =
14546 Name.Identifier, TemplateParams,
14547 NewTD);
14548 NewTD->setDescribedAliasTemplate(NewDecl);
14549
14550 NewDecl->setAccess(AS);
14551
14552 if (Invalid)
14553 NewDecl->setInvalidDecl();
14554 else if (OldDecl) {
14555 NewDecl->setPreviousDecl(OldDecl);
14556 CheckRedeclarationInModule(NewDecl, OldDecl);
14557 }
14558
14559 NewND = NewDecl;
14560 } else {
14561 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
14563 handleTagNumbering(TD, S);
14564 }
14566 NewND = NewTD;
14567 }
14568
14569 PushOnScopeChains(NewND, S);
14570 ActOnDocumentableDecl(NewND);
14571 return NewND;
14572}
14573
14575 SourceLocation AliasLoc,
14576 IdentifierInfo *Alias, CXXScopeSpec &SS,
14577 SourceLocation IdentLoc,
14578 IdentifierInfo *Ident) {
14579
14580 // Lookup the namespace name.
14581 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
14582 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
14583
14584 if (R.isAmbiguous())
14585 return nullptr;
14586
14587 if (R.empty()) {
14588 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
14589 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
14590 return nullptr;
14591 }
14592 }
14593 assert(!R.isAmbiguous() && !R.empty());
14594 auto *ND = cast<NamespaceBaseDecl>(R.getRepresentativeDecl());
14595
14596 // Check if we have a previous declaration with the same name.
14597 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
14599 LookupName(PrevR, S);
14600
14601 // Check we're not shadowing a template parameter.
14602 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
14604 PrevR.clear();
14605 }
14606
14607 // Filter out any other lookup result from an enclosing scope.
14608 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
14609 /*AllowInlineNamespace*/false);
14610
14611 // Find the previous declaration and check that we can redeclare it.
14612 NamespaceAliasDecl *Prev = nullptr;
14613 if (PrevR.isSingleResult()) {
14614 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
14615 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
14616 // We already have an alias with the same name that points to the same
14617 // namespace; check that it matches.
14618 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
14619 Prev = AD;
14620 } else if (isVisible(PrevDecl)) {
14621 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
14622 << Alias;
14623 Diag(AD->getLocation(), diag::note_previous_namespace_alias)
14624 << AD->getNamespace();
14625 return nullptr;
14626 }
14627 } else if (isVisible(PrevDecl)) {
14628 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
14629 ? diag::err_redefinition
14630 : diag::err_redefinition_different_kind;
14631 Diag(AliasLoc, DiagID) << Alias;
14632 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
14633 return nullptr;
14634 }
14635 }
14636
14637 // The use of a nested name specifier may trigger deprecation warnings.
14638 DiagnoseUseOfDecl(ND, IdentLoc);
14639
14641 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
14642 Alias, SS.getWithLocInContext(Context),
14643 IdentLoc, ND);
14644 if (Prev)
14645 AliasDecl->setPreviousDecl(Prev);
14646
14648 return AliasDecl;
14649}
14650
14651namespace {
14652struct SpecialMemberExceptionSpecInfo
14653 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
14654 SourceLocation Loc;
14656
14657 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
14660 SourceLocation Loc)
14661 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
14662
14663 bool visitBase(CXXBaseSpecifier *Base);
14664 bool visitField(FieldDecl *FD);
14665
14666 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
14667 unsigned Quals);
14668
14669 void visitSubobjectCall(Subobject Subobj,
14671};
14672}
14673
14674bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
14675 auto *BaseClass = Base->getType()->getAsCXXRecordDecl();
14676 if (!BaseClass)
14677 return false;
14678
14679 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
14680 if (auto *BaseCtor = SMOR.getMethod()) {
14681 visitSubobjectCall(Base, BaseCtor);
14682 return false;
14683 }
14684
14685 visitClassSubobject(BaseClass, Base, 0);
14686 return false;
14687}
14688
14689bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
14690 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
14691 FD->hasInClassInitializer()) {
14692 Expr *E = FD->getInClassInitializer();
14693 if (!E)
14694 // FIXME: It's a little wasteful to build and throw away a
14695 // CXXDefaultInitExpr here.
14696 // FIXME: We should have a single context note pointing at Loc, and
14697 // this location should be MD->getLocation() instead, since that's
14698 // the location where we actually use the default init expression.
14699 E = S.BuildCXXCtorDefaultInitExpr(Loc, FD).get();
14700 if (E)
14701 ExceptSpec.CalledExpr(E);
14702 } else if (auto *RD = S.Context.getBaseElementType(FD->getType())
14703 ->getAsCXXRecordDecl()) {
14704 visitClassSubobject(RD, FD, FD->getType().getCVRQualifiers());
14705 }
14706 return false;
14707}
14708
14709void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
14710 Subobject Subobj,
14711 unsigned Quals) {
14712 FieldDecl *Field = dyn_cast<FieldDecl *>(Subobj);
14713 bool IsMutable = Field && Field->isMutable();
14714 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
14715}
14716
14717void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
14718 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
14719 // Note, if lookup fails, it doesn't matter what exception specification we
14720 // choose because the special member will be deleted.
14721 if (CXXMethodDecl *MD = SMOR.getMethod())
14722 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
14723}
14724
14726 llvm::APSInt Result;
14728 ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEKind::ExplicitBool);
14729 ExplicitSpec.setExpr(Converted.get());
14730 if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
14731 ExplicitSpec.setKind(Result.getBoolValue()
14734 return true;
14735 }
14737 return false;
14738}
14739
14742 if (!ExplicitExpr->isTypeDependent() && !ExplicitExpr->containsErrors())
14744 return ES;
14745}
14746
14751 ComputingExceptionSpec CES(S, MD, Loc);
14752
14753 CXXRecordDecl *ClassDecl = MD->getParent();
14754
14755 // C++ [except.spec]p14:
14756 // An implicitly declared special member function (Clause 12) shall have an
14757 // exception-specification. [...]
14758 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
14759 if (ClassDecl->isInvalidDecl())
14760 return Info.ExceptSpec;
14761
14762 // FIXME: If this diagnostic fires, we're probably missing a check for
14763 // attempting to resolve an exception specification before it's known
14764 // at a higher level.
14765 if (S.RequireCompleteType(MD->getLocation(),
14766 S.Context.getCanonicalTagType(ClassDecl),
14767 diag::err_exception_spec_incomplete_type))
14768 return Info.ExceptSpec;
14769
14770 // C++1z [except.spec]p7:
14771 // [Look for exceptions thrown by] a constructor selected [...] to
14772 // initialize a potentially constructed subobject,
14773 // C++1z [except.spec]p8:
14774 // The exception specification for an implicitly-declared destructor, or a
14775 // destructor without a noexcept-specifier, is potentially-throwing if and
14776 // only if any of the destructors for any of its potentially constructed
14777 // subojects is potentially throwing.
14778 // FIXME: We respect the first rule but ignore the "potentially constructed"
14779 // in the second rule to resolve a core issue (no number yet) that would have
14780 // us reject:
14781 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
14782 // struct B : A {};
14783 // struct C : B { void f(); };
14784 // ... due to giving B::~B() a non-throwing exception specification.
14785 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
14786 : Info.VisitAllBases);
14787
14788 return Info.ExceptSpec;
14789}
14790
14791namespace {
14792/// RAII object to register a special member as being currently declared.
14793struct DeclaringSpecialMember {
14794 Sema &S;
14796 Sema::ContextRAII SavedContext;
14797 bool WasAlreadyBeingDeclared;
14798
14799 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, CXXSpecialMemberKind CSM)
14800 : S(S), D(RD, CSM), SavedContext(S, RD) {
14801 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
14802 if (WasAlreadyBeingDeclared)
14803 // This almost never happens, but if it does, ensure that our cache
14804 // doesn't contain a stale result.
14805 S.SpecialMemberCache.clear();
14806 else {
14807 // Register a note to be produced if we encounter an error while
14808 // declaring the special member.
14809 Sema::CodeSynthesisContext Ctx;
14810 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
14811 // FIXME: We don't have a location to use here. Using the class's
14812 // location maintains the fiction that we declare all special members
14813 // with the class, but (1) it's not clear that lying about that helps our
14814 // users understand what's going on, and (2) there may be outer contexts
14815 // on the stack (some of which are relevant) and printing them exposes
14816 // our lies.
14817 Ctx.PointOfInstantiation = RD->getLocation();
14818 Ctx.Entity = RD;
14819 Ctx.SpecialMember = CSM;
14820 S.pushCodeSynthesisContext(Ctx);
14821 }
14822 }
14823 ~DeclaringSpecialMember() {
14824 if (!WasAlreadyBeingDeclared) {
14825 S.SpecialMembersBeingDeclared.erase(D);
14827 }
14828 }
14829
14830 /// Are we already trying to declare this special member?
14831 bool isAlreadyBeingDeclared() const {
14832 return WasAlreadyBeingDeclared;
14833 }
14834};
14835}
14836
14838 // Look up any existing declarations, but don't trigger declaration of all
14839 // implicit special members with this name.
14840 DeclarationName Name = FD->getDeclName();
14843 for (auto *D : FD->getParent()->lookup(Name))
14844 if (auto *Acceptable = R.getAcceptableDecl(D))
14845 R.addDecl(Acceptable);
14846 R.resolveKind();
14847 R.suppressDiagnostics();
14848
14849 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/ false,
14851}
14852
14853void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
14854 QualType ResultTy,
14855 ArrayRef<QualType> Args) {
14856 // Build an exception specification pointing back at this constructor.
14858
14859 LangAS AS = getDefaultCXXMethodAddrSpace();
14860 if (AS != LangAS::Default) {
14861 EPI.TypeQuals.addAddressSpace(AS);
14862 }
14863
14864 auto QT = Context.getFunctionType(ResultTy, Args, EPI);
14865 SpecialMem->setType(QT);
14866
14867 // During template instantiation of implicit special member functions we need
14868 // a reliable TypeSourceInfo for the function prototype in order to allow
14869 // functions to be substituted.
14870 if (inTemplateInstantiation() && isLambdaMethod(SpecialMem)) {
14871 TypeSourceInfo *TSI =
14872 Context.getTrivialTypeSourceInfo(SpecialMem->getType());
14873 SpecialMem->setTypeSourceInfo(TSI);
14874 }
14875}
14876
14878 CXXRecordDecl *ClassDecl) {
14879 // C++ [class.ctor]p5:
14880 // A default constructor for a class X is a constructor of class X
14881 // that can be called without an argument. If there is no
14882 // user-declared constructor for class X, a default constructor is
14883 // implicitly declared. An implicitly-declared default constructor
14884 // is an inline public member of its class.
14885 assert(ClassDecl->needsImplicitDefaultConstructor() &&
14886 "Should not build implicit default constructor!");
14887
14888 DeclaringSpecialMember DSM(*this, ClassDecl,
14890 if (DSM.isAlreadyBeingDeclared())
14891 return nullptr;
14892
14894 *this, ClassDecl, CXXSpecialMemberKind::DefaultConstructor, false);
14895
14896 // Create the actual constructor declaration.
14897 CanQualType ClassType = Context.getCanonicalTagType(ClassDecl);
14898 SourceLocation ClassLoc = ClassDecl->getLocation();
14899 DeclarationName Name
14900 = Context.DeclarationNames.getCXXConstructorName(ClassType);
14901 DeclarationNameInfo NameInfo(Name, ClassLoc);
14903 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),
14904 /*TInfo=*/nullptr, ExplicitSpecifier(),
14905 getCurFPFeatures().isFPConstrained(),
14906 /*isInline=*/true, /*isImplicitlyDeclared=*/true,
14909 DefaultCon->setAccess(AS_public);
14910 DefaultCon->setDefaulted();
14911
14912 setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, {});
14913
14914 if (getLangOpts().CUDA)
14915 CUDA().inferTargetForImplicitSpecialMember(
14916 ClassDecl, CXXSpecialMemberKind::DefaultConstructor, DefaultCon,
14917 /* ConstRHS */ false,
14918 /* Diagnose */ false);
14919
14920 // We don't need to use SpecialMemberIsTrivial here; triviality for default
14921 // constructors is easy to compute.
14922 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
14923
14924 // Note that we have declared this constructor.
14925 ++getASTContext().NumImplicitDefaultConstructorsDeclared;
14926
14927 Scope *S = getScopeForContext(ClassDecl);
14929
14930 if (ShouldDeleteSpecialMember(DefaultCon,
14932 SetDeclDeleted(DefaultCon, ClassLoc);
14933
14934 if (S)
14935 PushOnScopeChains(DefaultCon, S, false);
14936 ClassDecl->addDecl(DefaultCon);
14937
14938 return DefaultCon;
14939}
14940
14943 DefaultedFunctionFPFeaturesRAII RestoreFP(*this, Constructor);
14944 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
14945 !Constructor->doesThisDeclarationHaveABody() &&
14946 !Constructor->isDeleted()) &&
14947 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
14948 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
14949 return;
14950
14951 CXXRecordDecl *ClassDecl = Constructor->getParent();
14952 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
14953 if (ClassDecl->isInvalidDecl()) {
14954 return;
14955 }
14956
14958
14959 // The exception specification is needed because we are defining the
14960 // function.
14961 ResolveExceptionSpec(CurrentLocation,
14962 Constructor->getType()->castAs<FunctionProtoType>());
14963 MarkVTableUsed(CurrentLocation, ClassDecl);
14964
14965 // Add a context note for diagnostics produced after this point.
14966 Scope.addContextNote(CurrentLocation);
14967
14968 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
14969 Constructor->setInvalidDecl();
14970 return;
14971 }
14972
14973 SourceLocation Loc = Constructor->getEndLoc().isValid()
14974 ? Constructor->getEndLoc()
14975 : Constructor->getLocation();
14976 Constructor->setBody(new (Context) CompoundStmt(Loc));
14977 Constructor->markUsed(Context);
14978
14980 L->CompletedImplicitDefinition(Constructor);
14981 }
14982
14983 DiagnoseUninitializedFields(*this, Constructor);
14984
14985 // The synthesized body applies the class's NSDMIs and never reaches the
14986 // normal IssueWarnings path, so run lifetime safety on it here.
14987 AnalysisWarnings.IssueWarningsForImplicitFunction(Constructor);
14988}
14989
14991 // Perform any delayed checks on exception specifications.
14993}
14994
14995/// Find or create the fake constructor we synthesize to model constructing an
14996/// object of a derived class via a constructor of a base class.
14999 CXXConstructorDecl *BaseCtor,
15001 CXXRecordDecl *Derived = Shadow->getParent();
15002 SourceLocation UsingLoc = Shadow->getLocation();
15003
15004 // FIXME: Add a new kind of DeclarationName for an inherited constructor.
15005 // For now we use the name of the base class constructor as a member of the
15006 // derived class to indicate a (fake) inherited constructor name.
15007 DeclarationName Name = BaseCtor->getDeclName();
15008
15009 // Check to see if we already have a fake constructor for this inherited
15010 // constructor call.
15011 for (NamedDecl *Ctor : Derived->lookup(Name))
15013 ->getInheritedConstructor()
15014 .getConstructor(),
15015 BaseCtor))
15016 return cast<CXXConstructorDecl>(Ctor);
15017
15018 DeclarationNameInfo NameInfo(Name, UsingLoc);
15019 TypeSourceInfo *TInfo =
15020 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
15021 FunctionProtoTypeLoc ProtoLoc =
15023
15024 // Check the inherited constructor is valid and find the list of base classes
15025 // from which it was inherited.
15026 InheritedConstructorInfo ICI(*this, Loc, Shadow);
15027
15028 bool Constexpr = BaseCtor->isConstexpr() &&
15031 false, BaseCtor, &ICI);
15032
15034 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
15035 BaseCtor->getExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
15036 /*isInline=*/true,
15037 /*isImplicitlyDeclared=*/true,
15039 InheritedConstructor(Shadow, BaseCtor),
15040 BaseCtor->getTrailingRequiresClause());
15041 if (Shadow->isInvalidDecl())
15042 DerivedCtor->setInvalidDecl();
15043
15044 // Build an unevaluated exception specification for this fake constructor.
15045 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
15048 EPI.ExceptionSpec.SourceDecl = DerivedCtor;
15049 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
15050 FPT->getParamTypes(), EPI));
15051
15052 // Build the parameter declarations.
15054 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
15055 TypeSourceInfo *TInfo =
15056 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
15058 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
15059 FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr);
15060 PD->setScopeInfo(0, I);
15061 PD->setImplicit();
15062 // Ensure attributes are propagated onto parameters (this matters for
15063 // format, pass_object_size, ...).
15064 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
15065 ParamDecls.push_back(PD);
15066 ProtoLoc.setParam(I, PD);
15067 }
15068
15069 // Set up the new constructor.
15070 assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
15071 DerivedCtor->setAccess(BaseCtor->getAccess());
15072 DerivedCtor->setParams(ParamDecls);
15073 Derived->addDecl(DerivedCtor);
15074
15075 if (ShouldDeleteSpecialMember(DerivedCtor,
15077 SetDeclDeleted(DerivedCtor, UsingLoc);
15078
15079 return DerivedCtor;
15080}
15081
15089
15092 CXXRecordDecl *ClassDecl = Constructor->getParent();
15093 assert(Constructor->getInheritedConstructor() &&
15094 !Constructor->doesThisDeclarationHaveABody() &&
15095 !Constructor->isDeleted());
15096 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
15097 return;
15098
15099 // Initializations are performed "as if by a defaulted default constructor",
15100 // so enter the appropriate scope.
15102
15103 // The exception specification is needed because we are defining the
15104 // function.
15105 ResolveExceptionSpec(CurrentLocation,
15106 Constructor->getType()->castAs<FunctionProtoType>());
15107 MarkVTableUsed(CurrentLocation, ClassDecl);
15108
15109 // Add a context note for diagnostics produced after this point.
15110 Scope.addContextNote(CurrentLocation);
15111
15113 Constructor->getInheritedConstructor().getShadowDecl();
15114 CXXConstructorDecl *InheritedCtor =
15115 Constructor->getInheritedConstructor().getConstructor();
15116
15117 // [class.inhctor.init]p1:
15118 // initialization proceeds as if a defaulted default constructor is used to
15119 // initialize the D object and each base class subobject from which the
15120 // constructor was inherited
15121
15122 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
15123 CXXRecordDecl *RD = Shadow->getParent();
15124 SourceLocation InitLoc = Shadow->getLocation();
15125
15126 // Build explicit initializers for all base classes from which the
15127 // constructor was inherited.
15129 for (bool VBase : {false, true}) {
15130 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
15131 if (B.isVirtual() != VBase)
15132 continue;
15133
15134 auto *BaseRD = B.getType()->getAsCXXRecordDecl();
15135 if (!BaseRD)
15136 continue;
15137
15138 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
15139 if (!BaseCtor.first)
15140 continue;
15141
15142 MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
15144 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
15145
15146 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
15147 Inits.push_back(new (Context) CXXCtorInitializer(
15148 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
15149 SourceLocation()));
15150 }
15151 }
15152
15153 // We now proceed as if for a defaulted default constructor, with the relevant
15154 // initializers replaced.
15155
15156 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
15157 Constructor->setInvalidDecl();
15158 return;
15159 }
15160
15161 Constructor->setBody(new (Context) CompoundStmt(InitLoc));
15162 Constructor->markUsed(Context);
15163
15165 L->CompletedImplicitDefinition(Constructor);
15166 }
15167
15168 DiagnoseUninitializedFields(*this, Constructor);
15169
15170 // The synthesized body applies the class's NSDMIs and never reaches the
15171 // normal IssueWarnings path, so run lifetime safety on it here.
15172 AnalysisWarnings.IssueWarningsForImplicitFunction(Constructor);
15173}
15174
15176 // C++ [class.dtor]p2:
15177 // If a class has no user-declared destructor, a destructor is
15178 // declared implicitly. An implicitly-declared destructor is an
15179 // inline public member of its class.
15180 assert(ClassDecl->needsImplicitDestructor());
15181
15182 DeclaringSpecialMember DSM(*this, ClassDecl,
15184 if (DSM.isAlreadyBeingDeclared())
15185 return nullptr;
15186
15188 *this, ClassDecl, CXXSpecialMemberKind::Destructor, false);
15189
15190 // Create the actual destructor declaration.
15191 CanQualType ClassType = Context.getCanonicalTagType(ClassDecl);
15192 SourceLocation ClassLoc = ClassDecl->getLocation();
15193 DeclarationName Name
15194 = Context.DeclarationNames.getCXXDestructorName(ClassType);
15195 DeclarationNameInfo NameInfo(Name, ClassLoc);
15197 Context, ClassDecl, ClassLoc, NameInfo, QualType(), nullptr,
15198 getCurFPFeatures().isFPConstrained(),
15199 /*isInline=*/true,
15200 /*isImplicitlyDeclared=*/true,
15203 Destructor->setAccess(AS_public);
15204 Destructor->setDefaulted();
15205
15206 setupImplicitSpecialMemberType(Destructor, Context.VoidTy, {});
15207
15208 if (getLangOpts().CUDA)
15209 CUDA().inferTargetForImplicitSpecialMember(
15211 /* ConstRHS */ false,
15212 /* Diagnose */ false);
15213
15214 // We don't need to use SpecialMemberIsTrivial here; triviality for
15215 // destructors is easy to compute.
15216 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
15217 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
15218 ClassDecl->hasTrivialDestructorForCall());
15219
15220 // Note that we have declared this destructor.
15221 ++getASTContext().NumImplicitDestructorsDeclared;
15222
15223 Scope *S = getScopeForContext(ClassDecl);
15225
15226 // We can't check whether an implicit destructor is deleted before we complete
15227 // the definition of the class, because its validity depends on the alignment
15228 // of the class. We'll check this from ActOnFields once the class is complete.
15229 if (ClassDecl->isCompleteDefinition() &&
15231 SetDeclDeleted(Destructor, ClassLoc);
15232
15233 // Introduce this destructor into its scope.
15234 if (S)
15235 PushOnScopeChains(Destructor, S, false);
15236 ClassDecl->addDecl(Destructor);
15237
15238 return Destructor;
15239}
15240
15243 DefaultedFunctionFPFeaturesRAII RestoreFP(*this, Destructor);
15244 assert((Destructor->isDefaulted() &&
15245 !Destructor->doesThisDeclarationHaveABody() &&
15246 !Destructor->isDeleted()) &&
15247 "DefineImplicitDestructor - call it for implicit default dtor");
15248 if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
15249 return;
15250
15251 CXXRecordDecl *ClassDecl = Destructor->getParent();
15252 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
15253
15255
15256 // The exception specification is needed because we are defining the
15257 // function.
15258 ResolveExceptionSpec(CurrentLocation,
15259 Destructor->getType()->castAs<FunctionProtoType>());
15260 MarkVTableUsed(CurrentLocation, ClassDecl);
15261
15262 // Add a context note for diagnostics produced after this point.
15263 Scope.addContextNote(CurrentLocation);
15264
15266 Destructor->getParent());
15267
15269 Destructor->setInvalidDecl();
15270 return;
15271 }
15272
15273 SourceLocation Loc = Destructor->getEndLoc().isValid()
15274 ? Destructor->getEndLoc()
15275 : Destructor->getLocation();
15276 Destructor->setBody(new (Context) CompoundStmt(Loc));
15277 Destructor->markUsed(Context);
15278
15280 L->CompletedImplicitDefinition(Destructor);
15281 }
15282}
15283
15286 if (Destructor->isInvalidDecl())
15287 return;
15288
15289 CXXRecordDecl *ClassDecl = Destructor->getParent();
15290 assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&
15291 "implicit complete dtors unneeded outside MS ABI");
15292 assert(ClassDecl->getNumVBases() > 0 &&
15293 "complete dtor only exists for classes with vbases");
15294
15296
15297 // Add a context note for diagnostics produced after this point.
15298 Scope.addContextNote(CurrentLocation);
15299
15300 MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl);
15301}
15302
15304 // If the context is an invalid C++ class, just suppress these checks.
15305 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
15306 if (Record->isInvalidDecl()) {
15309 return;
15310 }
15312 }
15313}
15314
15317
15318 if (!DelayedDllExportMemberFunctions.empty()) {
15320 std::swap(DelayedDllExportMemberFunctions, WorkList);
15321 for (CXXMethodDecl *M : WorkList) {
15322 DefineDefaultedFunction(*this, M, M->getLocation());
15323
15324 // Pass the method to the consumer to get emitted. This is not necessary
15325 // for explicit instantiation definitions, as they will get emitted
15326 // anyway.
15327 if (M->getParent()->getTemplateSpecializationKind() !=
15330 }
15331 }
15332}
15333
15335 if (!DelayedDllExportClasses.empty()) {
15336 // Calling ReferenceDllExportedMembers might cause the current function to
15337 // be called again, so use a local copy of DelayedDllExportClasses.
15339 std::swap(DelayedDllExportClasses, WorkList);
15340 for (CXXRecordDecl *Class : WorkList)
15342 }
15343}
15344
15346 assert(getLangOpts().CPlusPlus11 &&
15347 "adjusting dtor exception specs was introduced in c++11");
15348
15349 if (Destructor->isDependentContext())
15350 return;
15351
15352 // C++11 [class.dtor]p3:
15353 // A declaration of a destructor that does not have an exception-
15354 // specification is implicitly considered to have the same exception-
15355 // specification as an implicit declaration.
15356 const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>();
15357 if (DtorType->hasExceptionSpec())
15358 return;
15359
15360 // Replace the destructor's type, building off the existing one. Fortunately,
15361 // the only thing of interest in the destructor type is its extended info.
15362 // The return and arguments are fixed.
15363 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
15366 Destructor->setType(Context.getFunctionType(Context.VoidTy, {}, EPI));
15367
15368 // FIXME: If the destructor has a body that could throw, and the newly created
15369 // spec doesn't allow exceptions, we should emit a warning, because this
15370 // change in behavior can break conforming C++03 programs at runtime.
15371 // However, we don't have a body or an exception specification yet, so it
15372 // needs to be done somewhere else.
15373}
15374
15375namespace {
15376/// An abstract base class for all helper classes used in building the
15377// copy/move operators. These classes serve as factory functions and help us
15378// avoid using the same Expr* in the AST twice.
15379class ExprBuilder {
15380 ExprBuilder(const ExprBuilder&) = delete;
15381 ExprBuilder &operator=(const ExprBuilder&) = delete;
15382
15383protected:
15384 static Expr *assertNotNull(Expr *E) {
15385 assert(E && "Expression construction must not fail.");
15386 return E;
15387 }
15388
15389public:
15390 ExprBuilder() {}
15391 virtual ~ExprBuilder() {}
15392
15393 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
15394};
15395
15396class RefBuilder: public ExprBuilder {
15397 VarDecl *Var;
15398 QualType VarType;
15399
15400public:
15401 Expr *build(Sema &S, SourceLocation Loc) const override {
15402 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));
15403 }
15404
15405 RefBuilder(VarDecl *Var, QualType VarType)
15406 : Var(Var), VarType(VarType) {}
15407};
15408
15409class ThisBuilder: public ExprBuilder {
15410public:
15411 Expr *build(Sema &S, SourceLocation Loc) const override {
15412 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
15413 }
15414};
15415
15416class CastBuilder: public ExprBuilder {
15417 const ExprBuilder &Builder;
15418 QualType Type;
15420 const CXXCastPath &Path;
15421
15422public:
15423 Expr *build(Sema &S, SourceLocation Loc) const override {
15424 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
15425 CK_UncheckedDerivedToBase, Kind,
15426 &Path).get());
15427 }
15428
15429 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
15430 const CXXCastPath &Path)
15431 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
15432};
15433
15434class DerefBuilder: public ExprBuilder {
15435 const ExprBuilder &Builder;
15436
15437public:
15438 Expr *build(Sema &S, SourceLocation Loc) const override {
15439 return assertNotNull(
15440 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
15441 }
15442
15443 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
15444};
15445
15446class MemberBuilder: public ExprBuilder {
15447 const ExprBuilder &Builder;
15448 QualType Type;
15449 CXXScopeSpec SS;
15450 bool IsArrow;
15451 LookupResult &MemberLookup;
15452
15453public:
15454 Expr *build(Sema &S, SourceLocation Loc) const override {
15455 return assertNotNull(S.BuildMemberReferenceExpr(
15456 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
15457 nullptr, MemberLookup, nullptr, nullptr).get());
15458 }
15459
15460 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
15461 LookupResult &MemberLookup)
15462 : Builder(Builder), Type(Type), IsArrow(IsArrow),
15463 MemberLookup(MemberLookup) {}
15464};
15465
15466class MoveCastBuilder: public ExprBuilder {
15467 const ExprBuilder &Builder;
15468
15469public:
15470 Expr *build(Sema &S, SourceLocation Loc) const override {
15471 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
15472 }
15473
15474 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
15475};
15476
15477class LvalueConvBuilder: public ExprBuilder {
15478 const ExprBuilder &Builder;
15479
15480public:
15481 Expr *build(Sema &S, SourceLocation Loc) const override {
15482 return assertNotNull(
15483 S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
15484 }
15485
15486 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
15487};
15488
15489class SubscriptBuilder: public ExprBuilder {
15490 const ExprBuilder &Base;
15491 const ExprBuilder &Index;
15492
15493public:
15494 Expr *build(Sema &S, SourceLocation Loc) const override {
15495 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
15496 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
15497 }
15498
15499 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
15500 : Base(Base), Index(Index) {}
15501};
15502
15503} // end anonymous namespace
15504
15505/// When generating a defaulted copy or move assignment operator, if a field
15506/// should be copied with __builtin_memcpy rather than via explicit assignments,
15507/// do so. This optimization only applies for arrays of scalars, and for arrays
15508/// of class type where the selected copy/move-assignment operator is trivial.
15509static StmtResult
15511 const ExprBuilder &ToB, const ExprBuilder &FromB) {
15512 // Compute the size of the memory buffer to be copied.
15513 QualType SizeType = S.Context.getSizeType();
15514 llvm::APInt Size(S.Context.getTypeSize(SizeType),
15516
15517 // Take the address of the field references for "from" and "to". We
15518 // directly construct UnaryOperators here because semantic analysis
15519 // does not permit us to take the address of an xvalue.
15520 Expr *From = FromB.build(S, Loc);
15521 From = UnaryOperator::Create(
15522 S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()),
15523 VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
15524 Expr *To = ToB.build(S, Loc);
15526 S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()),
15527 VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
15528
15529 bool NeedsCollectableMemCpy = false;
15530 if (auto *RD = T->getBaseElementTypeUnsafe()->getAsRecordDecl())
15531 NeedsCollectableMemCpy = RD->hasObjectMember();
15532
15533 // Create a reference to the __builtin_objc_memmove_collectable function
15534 StringRef MemCpyName = NeedsCollectableMemCpy ?
15535 "__builtin_objc_memmove_collectable" :
15536 "__builtin_memcpy";
15537 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
15539 S.LookupName(R, S.TUScope, true);
15540
15541 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
15542 if (!MemCpy)
15543 // Something went horribly wrong earlier, and we will have complained
15544 // about it.
15545 return StmtError();
15546
15547 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
15548 VK_PRValue, Loc, nullptr);
15549 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
15550
15551 Expr *CallArgs[] = {
15552 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
15553 };
15554 ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
15555 Loc, CallArgs, Loc);
15556
15557 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
15558 return Call.getAs<Stmt>();
15559}
15560
15561/// Builds a statement that copies/moves the given entity from \p From to
15562/// \c To.
15563///
15564/// This routine is used to copy/move the members of a class with an
15565/// implicitly-declared copy/move assignment operator. When the entities being
15566/// copied are arrays, this routine builds for loops to copy them.
15567///
15568/// \param S The Sema object used for type-checking.
15569///
15570/// \param Loc The location where the implicit copy/move is being generated.
15571///
15572/// \param T The type of the expressions being copied/moved. Both expressions
15573/// must have this type.
15574///
15575/// \param To The expression we are copying/moving to.
15576///
15577/// \param From The expression we are copying/moving from.
15578///
15579/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
15580/// Otherwise, it's a non-static member subobject.
15581///
15582/// \param Copying Whether we're copying or moving.
15583///
15584/// \param Depth Internal parameter recording the depth of the recursion.
15585///
15586/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
15587/// if a memcpy should be used instead.
15588static StmtResult
15590 const ExprBuilder &To, const ExprBuilder &From,
15591 bool CopyingBaseSubobject, bool Copying,
15592 unsigned Depth = 0) {
15593 // C++11 [class.copy]p28:
15594 // Each subobject is assigned in the manner appropriate to its type:
15595 //
15596 // - if the subobject is of class type, as if by a call to operator= with
15597 // the subobject as the object expression and the corresponding
15598 // subobject of x as a single function argument (as if by explicit
15599 // qualification; that is, ignoring any possible virtual overriding
15600 // functions in more derived classes);
15601 //
15602 // C++03 [class.copy]p13:
15603 // - if the subobject is of class type, the copy assignment operator for
15604 // the class is used (as if by explicit qualification; that is,
15605 // ignoring any possible virtual overriding functions in more derived
15606 // classes);
15607 if (auto *ClassDecl = T->getAsCXXRecordDecl()) {
15608 // Look for operator=.
15609 DeclarationName Name
15611 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
15612 S.LookupQualifiedName(OpLookup, ClassDecl, false);
15613
15614 // Prior to C++11, filter out any result that isn't a copy/move-assignment
15615 // operator.
15616 if (!S.getLangOpts().CPlusPlus11) {
15617 LookupResult::Filter F = OpLookup.makeFilter();
15618 while (F.hasNext()) {
15619 NamedDecl *D = F.next();
15620 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
15621 if (Method->isCopyAssignmentOperator() ||
15622 (!Copying && Method->isMoveAssignmentOperator()))
15623 continue;
15624
15625 F.erase();
15626 }
15627 F.done();
15628 }
15629
15630 // Suppress the protected check (C++ [class.protected]) for each of the
15631 // assignment operators we found. This strange dance is required when
15632 // we're assigning via a base classes's copy-assignment operator. To
15633 // ensure that we're getting the right base class subobject (without
15634 // ambiguities), we need to cast "this" to that subobject type; to
15635 // ensure that we don't go through the virtual call mechanism, we need
15636 // to qualify the operator= name with the base class (see below). However,
15637 // this means that if the base class has a protected copy assignment
15638 // operator, the protected member access check will fail. So, we
15639 // rewrite "protected" access to "public" access in this case, since we
15640 // know by construction that we're calling from a derived class.
15641 if (CopyingBaseSubobject) {
15642 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
15643 L != LEnd; ++L) {
15644 if (L.getAccess() == AS_protected)
15645 L.setAccess(AS_public);
15646 }
15647 }
15648
15649 // Create the nested-name-specifier that will be used to qualify the
15650 // reference to operator=; this is required to suppress the virtual
15651 // call mechanism.
15652 CXXScopeSpec SS;
15653 // FIXME: Don't canonicalize this.
15654 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
15655 SS.MakeTrivial(S.Context, NestedNameSpecifier(CanonicalT), Loc);
15656
15657 // Create the reference to operator=.
15658 ExprResult OpEqualRef
15659 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false,
15660 SS, /*TemplateKWLoc=*/SourceLocation(),
15661 /*FirstQualifierInScope=*/nullptr,
15662 OpLookup,
15663 /*TemplateArgs=*/nullptr, /*S*/nullptr,
15664 /*SuppressQualifierCheck=*/true);
15665 if (OpEqualRef.isInvalid())
15666 return StmtError();
15667
15668 // Build the call to the assignment operator.
15669
15670 Expr *FromInst = From.build(S, Loc);
15671 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
15672 OpEqualRef.getAs<Expr>(),
15673 Loc, FromInst, Loc);
15674 if (Call.isInvalid())
15675 return StmtError();
15676
15677 // If we built a call to a trivial 'operator=' while copying an array,
15678 // bail out. We'll replace the whole shebang with a memcpy.
15679 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
15680 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
15681 return StmtResult((Stmt*)nullptr);
15682
15683 // Convert to an expression-statement, and clean up any produced
15684 // temporaries.
15685 return S.ActOnExprStmt(Call);
15686 }
15687
15688 // - if the subobject is of scalar type, the built-in assignment
15689 // operator is used.
15691 if (!ArrayTy) {
15693 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
15694 if (Assignment.isInvalid())
15695 return StmtError();
15696 return S.ActOnExprStmt(Assignment);
15697 }
15698
15699 // - if the subobject is an array, each element is assigned, in the
15700 // manner appropriate to the element type;
15701
15702 // Construct a loop over the array bounds, e.g.,
15703 //
15704 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
15705 //
15706 // that will copy each of the array elements.
15707 QualType SizeType = S.Context.getSizeType();
15708
15709 // Create the iteration variable.
15710 IdentifierInfo *IterationVarName = nullptr;
15711 {
15712 SmallString<8> Str;
15713 llvm::raw_svector_ostream OS(Str);
15714 OS << "__i" << Depth;
15715 IterationVarName = &S.Context.Idents.get(OS.str());
15716 }
15717 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
15718 IterationVarName, SizeType,
15719 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
15720 SC_None);
15721
15722 // Initialize the iteration variable to zero.
15723 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
15724 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
15725
15726 // Creates a reference to the iteration variable.
15727 RefBuilder IterationVarRef(IterationVar, SizeType);
15728 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
15729
15730 // Create the DeclStmt that holds the iteration variable.
15731 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
15732
15733 // Subscript the "from" and "to" expressions with the iteration variable.
15734 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
15735 MoveCastBuilder FromIndexMove(FromIndexCopy);
15736 const ExprBuilder *FromIndex;
15737 if (Copying)
15738 FromIndex = &FromIndexCopy;
15739 else
15740 FromIndex = &FromIndexMove;
15741
15742 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
15743
15744 // Build the copy/move for an individual element of the array.
15745 StmtResult Copy =
15747 ToIndex, *FromIndex, CopyingBaseSubobject,
15748 Copying, Depth + 1);
15749 // Bail out if copying fails or if we determined that we should use memcpy.
15750 if (Copy.isInvalid() || !Copy.get())
15751 return Copy;
15752
15753 // Create the comparison against the array bound.
15754 llvm::APInt Upper
15755 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
15757 S.Context, IterationVarRefRVal.build(S, Loc),
15758 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE,
15761
15762 // Create the pre-increment of the iteration variable. We can determine
15763 // whether the increment will overflow based on the value of the array
15764 // bound.
15766 S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue,
15767 OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides());
15768
15769 // Construct the loop that copies all elements of this array.
15770 return S.ActOnForStmt(
15771 Loc, Loc, InitStmt,
15774}
15775
15776static StmtResult
15778 const ExprBuilder &To, const ExprBuilder &From,
15779 bool CopyingBaseSubobject, bool Copying) {
15780 // Maybe we should use a memcpy?
15781 if (T->isArrayType() && !T.hasQualifiers() &&
15782 T.isTriviallyCopyableType(S.Context))
15783 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
15784
15785 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
15786 CopyingBaseSubobject,
15787 Copying, 0));
15788
15789 // If we ended up picking a trivial assignment operator for an array of a
15790 // non-trivially-copyable class type, just emit a memcpy.
15791 if (!Result.isInvalid() && !Result.get())
15792 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
15793
15794 return Result;
15795}
15796
15798 // Note: The following rules are largely analoguous to the copy
15799 // constructor rules. Note that virtual bases are not taken into account
15800 // for determining the argument type of the operator. Note also that
15801 // operators taking an object instead of a reference are allowed.
15802 assert(ClassDecl->needsImplicitCopyAssignment());
15803
15804 DeclaringSpecialMember DSM(*this, ClassDecl,
15806 if (DSM.isAlreadyBeingDeclared())
15807 return nullptr;
15808
15810 /*Qualifier=*/std::nullopt, ClassDecl,
15811 /*OwnsTag=*/false);
15813 if (AS != LangAS::Default)
15814 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
15815 QualType RetType = Context.getLValueReferenceType(ArgType);
15816 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
15817 if (Const)
15818 ArgType = ArgType.withConst();
15819
15820 ArgType = Context.getLValueReferenceType(ArgType);
15821
15823 *this, ClassDecl, CXXSpecialMemberKind::CopyAssignment, Const);
15824
15825 // An implicitly-declared copy assignment operator is an inline public
15826 // member of its class.
15827 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
15828 SourceLocation ClassLoc = ClassDecl->getLocation();
15829 DeclarationNameInfo NameInfo(Name, ClassLoc);
15831 Context, ClassDecl, ClassLoc, NameInfo, QualType(),
15832 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
15833 getCurFPFeatures().isFPConstrained(),
15834 /*isInline=*/true,
15836 SourceLocation());
15837 CopyAssignment->setAccess(AS_public);
15838 CopyAssignment->setDefaulted();
15839 CopyAssignment->setImplicit();
15840
15841 setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
15842
15843 if (getLangOpts().CUDA)
15844 CUDA().inferTargetForImplicitSpecialMember(
15846 /* ConstRHS */ Const,
15847 /* Diagnose */ false);
15848
15849 // Add the parameter to the operator.
15851 ClassLoc, ClassLoc,
15852 /*Id=*/nullptr, ArgType,
15853 /*TInfo=*/nullptr, SC_None,
15854 nullptr);
15855 CopyAssignment->setParams(FromParam);
15856
15857 CopyAssignment->setTrivial(
15861 : ClassDecl->hasTrivialCopyAssignment());
15862
15863 // Note that we have added this copy-assignment operator.
15864 ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
15865
15866 Scope *S = getScopeForContext(ClassDecl);
15868
15872 SetDeclDeleted(CopyAssignment, ClassLoc);
15873 }
15874
15875 if (S)
15877 ClassDecl->addDecl(CopyAssignment);
15878
15879 return CopyAssignment;
15880}
15881
15882/// Diagnose an implicit copy operation for a class which is odr-used, but
15883/// which is deprecated because the class has a user-declared copy constructor,
15884/// copy assignment operator, or destructor.
15886 assert(CopyOp->isImplicit());
15887
15888 CXXRecordDecl *RD = CopyOp->getParent();
15889 CXXMethodDecl *UserDeclaredOperation = nullptr;
15890
15891 if (RD->hasUserDeclaredDestructor()) {
15892 UserDeclaredOperation = RD->getDestructor();
15893 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
15895 // Find any user-declared copy constructor.
15896 for (auto *I : RD->ctors()) {
15897 if (I->isCopyConstructor()) {
15898 UserDeclaredOperation = I;
15899 break;
15900 }
15901 }
15902 assert(UserDeclaredOperation);
15903 } else if (isa<CXXConstructorDecl>(CopyOp) &&
15905 // Find any user-declared move assignment operator.
15906 for (auto *I : RD->methods()) {
15907 if (I->isCopyAssignmentOperator()) {
15908 UserDeclaredOperation = I;
15909 break;
15910 }
15911 }
15912 assert(UserDeclaredOperation);
15913 }
15914
15915 if (UserDeclaredOperation) {
15916 bool UDOIsUserProvided = UserDeclaredOperation->isUserProvided();
15917 bool UDOIsDestructor = isa<CXXDestructorDecl>(UserDeclaredOperation);
15918 bool IsCopyAssignment = !isa<CXXConstructorDecl>(CopyOp);
15919 unsigned DiagID =
15920 (UDOIsUserProvided && UDOIsDestructor)
15921 ? diag::warn_deprecated_copy_with_user_provided_dtor
15922 : (UDOIsUserProvided && !UDOIsDestructor)
15923 ? diag::warn_deprecated_copy_with_user_provided_copy
15924 : (!UDOIsUserProvided && UDOIsDestructor)
15925 ? diag::warn_deprecated_copy_with_dtor
15926 : diag::warn_deprecated_copy;
15927 S.Diag(UserDeclaredOperation->getLocation(), DiagID)
15928 << RD << IsCopyAssignment;
15929 }
15930}
15931
15933 CXXMethodDecl *CopyAssignOperator) {
15934 DefaultedFunctionFPFeaturesRAII RestoreFP(*this, CopyAssignOperator);
15935 assert((CopyAssignOperator->isDefaulted() &&
15936 CopyAssignOperator->isOverloadedOperator() &&
15937 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
15938 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
15939 !CopyAssignOperator->isDeleted()) &&
15940 "DefineImplicitCopyAssignment called for wrong function");
15941 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
15942 return;
15943
15944 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
15945 if (ClassDecl->isInvalidDecl()) {
15946 CopyAssignOperator->setInvalidDecl();
15947 return;
15948 }
15949
15950 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
15951
15952 // The exception specification is needed because we are defining the
15953 // function.
15954 ResolveExceptionSpec(CurrentLocation,
15955 CopyAssignOperator->getType()->castAs<FunctionProtoType>());
15956
15957 // Add a context note for diagnostics produced after this point.
15958 Scope.addContextNote(CurrentLocation);
15959
15960 // C++11 [class.copy]p18:
15961 // The [definition of an implicitly declared copy assignment operator] is
15962 // deprecated if the class has a user-declared copy constructor or a
15963 // user-declared destructor.
15964 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
15965 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
15966
15967 // C++0x [class.copy]p30:
15968 // The implicitly-defined or explicitly-defaulted copy assignment operator
15969 // for a non-union class X performs memberwise copy assignment of its
15970 // subobjects. The direct base classes of X are assigned first, in the
15971 // order of their declaration in the base-specifier-list, and then the
15972 // immediate non-static data members of X are assigned, in the order in
15973 // which they were declared in the class definition.
15974
15975 // The statements that form the synthesized function body.
15976 SmallVector<Stmt*, 8> Statements;
15977
15978 // The parameter for the "other" object, which we are copying from.
15979 ParmVarDecl *Other = CopyAssignOperator->getNonObjectParameter(0);
15980 Qualifiers OtherQuals = Other->getType().getQualifiers();
15981 QualType OtherRefType = Other->getType();
15982 if (OtherRefType->isLValueReferenceType()) {
15983 OtherRefType = OtherRefType->getPointeeType();
15984 OtherQuals = OtherRefType.getQualifiers();
15985 }
15986
15987 // Our location for everything implicitly-generated.
15988 SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
15989 ? CopyAssignOperator->getEndLoc()
15990 : CopyAssignOperator->getLocation();
15991
15992 // Builds a DeclRefExpr for the "other" object.
15993 RefBuilder OtherRef(Other, OtherRefType);
15994
15995 // Builds the function object parameter.
15996 std::optional<ThisBuilder> This;
15997 std::optional<DerefBuilder> DerefThis;
15998 std::optional<RefBuilder> ExplicitObject;
15999 bool IsArrow = false;
16000 QualType ObjectType;
16001 if (CopyAssignOperator->isExplicitObjectMemberFunction()) {
16002 ObjectType = CopyAssignOperator->getParamDecl(0)->getType();
16003 if (ObjectType->isReferenceType())
16004 ObjectType = ObjectType->getPointeeType();
16005 ExplicitObject.emplace(CopyAssignOperator->getParamDecl(0), ObjectType);
16006 } else {
16007 ObjectType = getCurrentThisType();
16008 This.emplace();
16009 DerefThis.emplace(*This);
16010 IsArrow = !LangOpts.HLSL;
16011 }
16012 ExprBuilder &ObjectParameter =
16013 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
16014 : static_cast<ExprBuilder &>(*This);
16015
16016 // Assign base classes.
16017 bool Invalid = false;
16018 for (auto &Base : ClassDecl->bases()) {
16019 // Form the assignment:
16020 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
16021 QualType BaseType = Base.getType().getUnqualifiedType();
16022 if (!BaseType->isRecordType()) {
16023 Invalid = true;
16024 continue;
16025 }
16026
16027 CXXCastPath BasePath;
16028 BasePath.push_back(&Base);
16029
16030 // Construct the "from" expression, which is an implicit cast to the
16031 // appropriately-qualified base type.
16032 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
16033 VK_LValue, BasePath);
16034
16035 // Dereference "this".
16036 CastBuilder To(
16037 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
16038 : static_cast<ExprBuilder &>(*DerefThis),
16039 Context.getQualifiedType(BaseType, ObjectType.getQualifiers()),
16040 VK_LValue, BasePath);
16041
16042 // Build the copy.
16043 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
16044 To, From,
16045 /*CopyingBaseSubobject=*/true,
16046 /*Copying=*/true);
16047 if (Copy.isInvalid()) {
16048 CopyAssignOperator->setInvalidDecl();
16049 return;
16050 }
16051
16052 // Success! Record the copy.
16053 Statements.push_back(Copy.getAs<Expr>());
16054 }
16055
16056 // A defaulted copy assignment operator for a union copies the object
16057 // representation as if by a memcpy, the same way the defaulted union copy
16058 // constructor does. The memberwise loop below skips union members.
16059 if (ClassDecl->isUnion()) {
16060 ExprBuilder &To = ExplicitObject
16061 ? static_cast<ExprBuilder &>(*ExplicitObject)
16062 : static_cast<ExprBuilder &>(*DerefThis);
16063 // Copying the object representation is correct even for a union that is
16064 // not trivially copyable, so -Wnontrivial-memcall is a false positive
16065 // here. Ignoring warnings rather than casting the arguments to void*
16066 // keeps them typed, which preserves their address space.
16067 IgnoreAllWarningDiagRAII IgnoreWarnings(Diags);
16069 *this, Loc, Context.getCanonicalTagType(ClassDecl), To, OtherRef);
16070 if (Copy.isInvalid()) {
16071 CopyAssignOperator->setInvalidDecl();
16072 return;
16073 }
16074 Statements.push_back(Copy.getAs<Stmt>());
16075 }
16076
16077 // Assign non-static members.
16078 for (auto *Field : ClassDecl->fields()) {
16079 // Union members are copied by the whole-object memcpy emitted above.
16080 if (Field->isUnnamedBitField() || Field->getParent()->isUnion())
16081 continue;
16082
16083 if (Field->isInvalidDecl()) {
16084 Invalid = true;
16085 continue;
16086 }
16087
16088 // Check for members of reference type; we can't copy those.
16089 if (Field->getType()->isReferenceType()) {
16090 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
16091 << Context.getCanonicalTagType(ClassDecl) << 0
16092 << Field->getDeclName();
16093 Diag(Field->getLocation(), diag::note_declared_at);
16094 Invalid = true;
16095 continue;
16096 }
16097
16098 // Check for members of const-qualified, non-class type.
16099 QualType BaseType = Context.getBaseElementType(Field->getType());
16100 if (!BaseType->isRecordType() && BaseType.isConstQualified()) {
16101 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
16102 << Context.getCanonicalTagType(ClassDecl) << 1
16103 << Field->getDeclName();
16104 Diag(Field->getLocation(), diag::note_declared_at);
16105 Invalid = true;
16106 continue;
16107 }
16108
16109 // Suppress assigning zero-width bitfields.
16110 if (Field->isZeroLengthBitField())
16111 continue;
16112
16113 QualType FieldType = Field->getType().getNonReferenceType();
16114 if (FieldType->isIncompleteArrayType()) {
16115 assert(ClassDecl->hasFlexibleArrayMember() &&
16116 "Incomplete array type is not valid");
16117 continue;
16118 }
16119
16120 // Build references to the field in the object we're copying from and to.
16121 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
16123 MemberLookup.addDecl(Field);
16124 MemberLookup.resolveKind();
16125
16126 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
16127 MemberBuilder To(ObjectParameter, ObjectType, IsArrow, MemberLookup);
16128 // Build the copy of this field.
16129 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
16130 To, From,
16131 /*CopyingBaseSubobject=*/false,
16132 /*Copying=*/true);
16133 if (Copy.isInvalid()) {
16134 CopyAssignOperator->setInvalidDecl();
16135 return;
16136 }
16137
16138 // Success! Record the copy.
16139 Statements.push_back(Copy.getAs<Stmt>());
16140 }
16141
16142 if (!Invalid) {
16143 // Add a "return *this;"
16144 Expr *ThisExpr =
16145 (ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
16146 : LangOpts.HLSL ? static_cast<ExprBuilder &>(*This)
16147 : static_cast<ExprBuilder &>(*DerefThis))
16148 .build(*this, Loc);
16149 StmtResult Return = BuildReturnStmt(Loc, ThisExpr);
16150 if (Return.isInvalid())
16151 Invalid = true;
16152 else
16153 Statements.push_back(Return.getAs<Stmt>());
16154 }
16155
16156 if (Invalid) {
16157 CopyAssignOperator->setInvalidDecl();
16158 return;
16159 }
16160
16161 StmtResult Body;
16162 {
16163 CompoundScopeRAII CompoundScope(*this);
16164 Body = ActOnCompoundStmt(Loc, Loc, Statements,
16165 /*isStmtExpr=*/false);
16166 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
16167 }
16168 CopyAssignOperator->setBody(Body.getAs<Stmt>());
16169 CopyAssignOperator->markUsed(Context);
16170
16172 L->CompletedImplicitDefinition(CopyAssignOperator);
16173 }
16174}
16175
16177 assert(ClassDecl->needsImplicitMoveAssignment());
16178
16179 DeclaringSpecialMember DSM(*this, ClassDecl,
16181 if (DSM.isAlreadyBeingDeclared())
16182 return nullptr;
16183
16184 // Note: The following rules are largely analoguous to the move
16185 // constructor rules.
16186
16188 /*Qualifier=*/std::nullopt, ClassDecl,
16189 /*OwnsTag=*/false);
16191 if (AS != LangAS::Default)
16192 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
16193 QualType RetType = Context.getLValueReferenceType(ArgType);
16194 ArgType = Context.getRValueReferenceType(ArgType);
16195
16197 *this, ClassDecl, CXXSpecialMemberKind::MoveAssignment, false);
16198
16199 // An implicitly-declared move assignment operator is an inline public
16200 // member of its class.
16201 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
16202 SourceLocation ClassLoc = ClassDecl->getLocation();
16203 DeclarationNameInfo NameInfo(Name, ClassLoc);
16205 Context, ClassDecl, ClassLoc, NameInfo, QualType(),
16206 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
16207 getCurFPFeatures().isFPConstrained(),
16208 /*isInline=*/true,
16210 SourceLocation());
16211 MoveAssignment->setAccess(AS_public);
16212 MoveAssignment->setDefaulted();
16213 MoveAssignment->setImplicit();
16214
16215 setupImplicitSpecialMemberType(MoveAssignment, RetType, ArgType);
16216
16217 if (getLangOpts().CUDA)
16218 CUDA().inferTargetForImplicitSpecialMember(
16220 /* ConstRHS */ false,
16221 /* Diagnose */ false);
16222
16223 // Add the parameter to the operator.
16225 ClassLoc, ClassLoc,
16226 /*Id=*/nullptr, ArgType,
16227 /*TInfo=*/nullptr, SC_None,
16228 nullptr);
16229 MoveAssignment->setParams(FromParam);
16230
16231 MoveAssignment->setTrivial(
16235 : ClassDecl->hasTrivialMoveAssignment());
16236
16237 // Note that we have added this copy-assignment operator.
16238 ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
16239
16240 Scope *S = getScopeForContext(ClassDecl);
16242
16246 SetDeclDeleted(MoveAssignment, ClassLoc);
16247 }
16248
16249 if (S)
16251 ClassDecl->addDecl(MoveAssignment);
16252
16253 return MoveAssignment;
16254}
16255
16256/// Check if we're implicitly defining a move assignment operator for a class
16257/// with virtual bases. Such a move assignment might move-assign the virtual
16258/// base multiple times.
16260 SourceLocation CurrentLocation) {
16261 assert(!Class->isDependentContext() && "should not define dependent move");
16262
16263 // Only a virtual base could get implicitly move-assigned multiple times.
16264 // Only a non-trivial move assignment can observe this. We only want to
16265 // diagnose if we implicitly define an assignment operator that assigns
16266 // two base classes, both of which move-assign the same virtual base.
16267 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
16268 Class->getNumBases() < 2)
16269 return;
16270
16272 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
16273 VBaseMap VBases;
16274
16275 for (auto &BI : Class->bases()) {
16276 Worklist.push_back(&BI);
16277 while (!Worklist.empty()) {
16278 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
16279 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
16280
16281 // If the base has no non-trivial move assignment operators,
16282 // we don't care about moves from it.
16283 if (!Base->hasNonTrivialMoveAssignment())
16284 continue;
16285
16286 // If there's nothing virtual here, skip it.
16287 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
16288 continue;
16289
16290 // If we're not actually going to call a move assignment for this base,
16291 // or the selected move assignment is trivial, skip it.
16294 /*ConstArg*/ false, /*VolatileArg*/ false,
16295 /*RValueThis*/ true, /*ConstThis*/ false,
16296 /*VolatileThis*/ false);
16297 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
16299 continue;
16300
16301 if (BaseSpec->isVirtual()) {
16302 // We're going to move-assign this virtual base, and its move
16303 // assignment operator is not trivial. If this can happen for
16304 // multiple distinct direct bases of Class, diagnose it. (If it
16305 // only happens in one base, we'll diagnose it when synthesizing
16306 // that base class's move assignment operator.)
16307 CXXBaseSpecifier *&Existing =
16308 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
16309 .first->second;
16310 if (Existing && Existing != &BI) {
16311 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
16312 << Class << Base;
16313 S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
16314 << (Base->getCanonicalDecl() ==
16316 << Base << Existing->getType() << Existing->getSourceRange();
16317 S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
16318 << (Base->getCanonicalDecl() ==
16319 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
16320 << Base << BI.getType() << BaseSpec->getSourceRange();
16321
16322 // Only diagnose each vbase once.
16323 Existing = nullptr;
16324 }
16325 } else {
16326 // Only walk over bases that have defaulted move assignment operators.
16327 // We assume that any user-provided move assignment operator handles
16328 // the multiple-moves-of-vbase case itself somehow.
16329 if (!SMOR.getMethod()->isDefaulted())
16330 continue;
16331
16332 // We're going to move the base classes of Base. Add them to the list.
16333 llvm::append_range(Worklist, llvm::make_pointer_range(Base->bases()));
16334 }
16335 }
16336 }
16337}
16338
16340 CXXMethodDecl *MoveAssignOperator) {
16341 DefaultedFunctionFPFeaturesRAII RestoreFP(*this, MoveAssignOperator);
16342 assert((MoveAssignOperator->isDefaulted() &&
16343 MoveAssignOperator->isOverloadedOperator() &&
16344 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
16345 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
16346 !MoveAssignOperator->isDeleted()) &&
16347 "DefineImplicitMoveAssignment called for wrong function");
16348 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
16349 return;
16350
16351 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
16352 if (ClassDecl->isInvalidDecl()) {
16353 MoveAssignOperator->setInvalidDecl();
16354 return;
16355 }
16356
16357 // C++0x [class.copy]p28:
16358 // The implicitly-defined or move assignment operator for a non-union class
16359 // X performs memberwise move assignment of its subobjects. The direct base
16360 // classes of X are assigned first, in the order of their declaration in the
16361 // base-specifier-list, and then the immediate non-static data members of X
16362 // are assigned, in the order in which they were declared in the class
16363 // definition.
16364
16365 // Issue a warning if our implicit move assignment operator will move
16366 // from a virtual base more than once.
16367 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
16368
16369 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
16370
16371 // The exception specification is needed because we are defining the
16372 // function.
16373 ResolveExceptionSpec(CurrentLocation,
16374 MoveAssignOperator->getType()->castAs<FunctionProtoType>());
16375
16376 // Add a context note for diagnostics produced after this point.
16377 Scope.addContextNote(CurrentLocation);
16378
16379 // The statements that form the synthesized function body.
16380 SmallVector<Stmt*, 8> Statements;
16381
16382 // The parameter for the "other" object, which we are move from.
16383 ParmVarDecl *Other = MoveAssignOperator->getNonObjectParameter(0);
16384 QualType OtherRefType =
16385 Other->getType()->castAs<RValueReferenceType>()->getPointeeType();
16386
16387 // Our location for everything implicitly-generated.
16388 SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
16389 ? MoveAssignOperator->getEndLoc()
16390 : MoveAssignOperator->getLocation();
16391
16392 // Builds a reference to the "other" object.
16393 RefBuilder OtherRef(Other, OtherRefType);
16394 // Cast to rvalue.
16395 MoveCastBuilder MoveOther(OtherRef);
16396
16397 // Builds the function object parameter.
16398 std::optional<ThisBuilder> This;
16399 std::optional<DerefBuilder> DerefThis;
16400 std::optional<RefBuilder> ExplicitObject;
16401 QualType ObjectType;
16402 bool IsArrow = false;
16403 if (MoveAssignOperator->isExplicitObjectMemberFunction()) {
16404 ObjectType = MoveAssignOperator->getParamDecl(0)->getType();
16405 if (ObjectType->isReferenceType())
16406 ObjectType = ObjectType->getPointeeType();
16407 ExplicitObject.emplace(MoveAssignOperator->getParamDecl(0), ObjectType);
16408 } else {
16409 ObjectType = getCurrentThisType();
16410 This.emplace();
16411 DerefThis.emplace(*This);
16412 IsArrow = !getLangOpts().HLSL;
16413 }
16414 ExprBuilder &ObjectParameter =
16415 ExplicitObject ? *ExplicitObject : static_cast<ExprBuilder &>(*This);
16416
16417 // Assign base classes.
16418 bool Invalid = false;
16419 for (auto &Base : ClassDecl->bases()) {
16420 // C++11 [class.copy]p28:
16421 // It is unspecified whether subobjects representing virtual base classes
16422 // are assigned more than once by the implicitly-defined copy assignment
16423 // operator.
16424 // FIXME: Do not assign to a vbase that will be assigned by some other base
16425 // class. For a move-assignment, this can result in the vbase being moved
16426 // multiple times.
16427
16428 // Form the assignment:
16429 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
16430 QualType BaseType = Base.getType().getUnqualifiedType();
16431 if (!BaseType->isRecordType()) {
16432 Invalid = true;
16433 continue;
16434 }
16435
16436 CXXCastPath BasePath;
16437 BasePath.push_back(&Base);
16438
16439 // Construct the "from" expression, which is an implicit cast to the
16440 // appropriately-qualified base type.
16441 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
16442
16443 // Implicitly cast "this" to the appropriately-qualified base type.
16444 // Dereference "this".
16445 CastBuilder To(
16446 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
16447 : static_cast<ExprBuilder &>(*DerefThis),
16448 Context.getQualifiedType(BaseType, ObjectType.getQualifiers()),
16449 VK_LValue, BasePath);
16450
16451 // Build the move.
16452 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
16453 To, From,
16454 /*CopyingBaseSubobject=*/true,
16455 /*Copying=*/false);
16456 if (Move.isInvalid()) {
16457 MoveAssignOperator->setInvalidDecl();
16458 return;
16459 }
16460
16461 // Success! Record the move.
16462 Statements.push_back(Move.getAs<Expr>());
16463 }
16464
16465 // A defaulted move assignment operator for a union copies the object
16466 // representation as if by a memcpy, the same way the defaulted union copy
16467 // constructor does. The memberwise loop below skips union members.
16468 if (ClassDecl->isUnion()) {
16469 ExprBuilder &To = ExplicitObject
16470 ? static_cast<ExprBuilder &>(*ExplicitObject)
16471 : static_cast<ExprBuilder &>(*DerefThis);
16472 // Copying the object representation is correct even for a union that is
16473 // not trivially copyable, so -Wnontrivial-memcall is a false positive
16474 // here. Ignoring warnings rather than casting the arguments to void*
16475 // keeps them typed, which preserves their address space.
16476 IgnoreAllWarningDiagRAII IgnoreWarnings(Diags);
16478 *this, Loc, Context.getCanonicalTagType(ClassDecl), To, OtherRef);
16479 if (Copy.isInvalid()) {
16480 MoveAssignOperator->setInvalidDecl();
16481 return;
16482 }
16483 Statements.push_back(Copy.getAs<Stmt>());
16484 }
16485
16486 // Assign non-static members.
16487 for (auto *Field : ClassDecl->fields()) {
16488 // Union members are copied by the whole-object memcpy emitted above.
16489 if (Field->isUnnamedBitField() || Field->getParent()->isUnion())
16490 continue;
16491
16492 if (Field->isInvalidDecl()) {
16493 Invalid = true;
16494 continue;
16495 }
16496
16497 // Check for members of reference type; we can't move those.
16498 if (Field->getType()->isReferenceType()) {
16499 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
16500 << Context.getCanonicalTagType(ClassDecl) << 0
16501 << Field->getDeclName();
16502 Diag(Field->getLocation(), diag::note_declared_at);
16503 Invalid = true;
16504 continue;
16505 }
16506
16507 // Check for members of const-qualified, non-class type.
16508 QualType BaseType = Context.getBaseElementType(Field->getType());
16509 if (!BaseType->isRecordType() && BaseType.isConstQualified()) {
16510 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
16511 << Context.getCanonicalTagType(ClassDecl) << 1
16512 << Field->getDeclName();
16513 Diag(Field->getLocation(), diag::note_declared_at);
16514 Invalid = true;
16515 continue;
16516 }
16517
16518 // Suppress assigning zero-width bitfields.
16519 if (Field->isZeroLengthBitField())
16520 continue;
16521
16522 QualType FieldType = Field->getType().getNonReferenceType();
16523 if (FieldType->isIncompleteArrayType()) {
16524 assert(ClassDecl->hasFlexibleArrayMember() &&
16525 "Incomplete array type is not valid");
16526 continue;
16527 }
16528
16529 // Build references to the field in the object we're copying from and to.
16530 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
16532 MemberLookup.addDecl(Field);
16533 MemberLookup.resolveKind();
16534 MemberBuilder From(MoveOther, OtherRefType,
16535 /*IsArrow=*/false, MemberLookup);
16536 MemberBuilder To(ObjectParameter, ObjectType, IsArrow, MemberLookup);
16537
16538 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
16539 "Member reference with rvalue base must be rvalue except for reference "
16540 "members, which aren't allowed for move assignment.");
16541
16542 // Build the move of this field.
16543 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
16544 To, From,
16545 /*CopyingBaseSubobject=*/false,
16546 /*Copying=*/false);
16547 if (Move.isInvalid()) {
16548 MoveAssignOperator->setInvalidDecl();
16549 return;
16550 }
16551
16552 // Success! Record the copy.
16553 Statements.push_back(Move.getAs<Stmt>());
16554 }
16555
16556 if (!Invalid) {
16557 // Add a "return *this;"
16558 Expr *ThisExpr =
16559 (ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
16560 : LangOpts.HLSL ? static_cast<ExprBuilder &>(*This)
16561 : static_cast<ExprBuilder &>(*DerefThis))
16562 .build(*this, Loc);
16563
16564 StmtResult Return = BuildReturnStmt(Loc, ThisExpr);
16565 if (Return.isInvalid())
16566 Invalid = true;
16567 else
16568 Statements.push_back(Return.getAs<Stmt>());
16569 }
16570
16571 if (Invalid) {
16572 MoveAssignOperator->setInvalidDecl();
16573 return;
16574 }
16575
16576 StmtResult Body;
16577 {
16578 CompoundScopeRAII CompoundScope(*this);
16579 Body = ActOnCompoundStmt(Loc, Loc, Statements,
16580 /*isStmtExpr=*/false);
16581 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
16582 }
16583 MoveAssignOperator->setBody(Body.getAs<Stmt>());
16584 MoveAssignOperator->markUsed(Context);
16585
16587 L->CompletedImplicitDefinition(MoveAssignOperator);
16588 }
16589}
16590
16592 CXXRecordDecl *ClassDecl) {
16593 // C++ [class.copy]p4:
16594 // If the class definition does not explicitly declare a copy
16595 // constructor, one is declared implicitly.
16596 assert(ClassDecl->needsImplicitCopyConstructor());
16597
16598 DeclaringSpecialMember DSM(*this, ClassDecl,
16600 if (DSM.isAlreadyBeingDeclared())
16601 return nullptr;
16602
16603 QualType ClassType = Context.getTagType(ElaboratedTypeKeyword::None,
16604 /*Qualifier=*/std::nullopt, ClassDecl,
16605 /*OwnsTag=*/false);
16606 QualType ArgType = ClassType;
16607 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
16608 if (Const)
16609 ArgType = ArgType.withConst();
16610
16612 if (AS != LangAS::Default)
16613 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
16614
16615 ArgType = Context.getLValueReferenceType(ArgType);
16616
16618 *this, ClassDecl, CXXSpecialMemberKind::CopyConstructor, Const);
16619
16620 DeclarationName Name
16621 = Context.DeclarationNames.getCXXConstructorName(
16622 Context.getCanonicalType(ClassType));
16623 SourceLocation ClassLoc = ClassDecl->getLocation();
16624 DeclarationNameInfo NameInfo(Name, ClassLoc);
16625
16626 // An implicitly-declared copy constructor is an inline public
16627 // member of its class.
16629 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
16630 ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
16631 /*isInline=*/true,
16632 /*isImplicitlyDeclared=*/true,
16635 CopyConstructor->setAccess(AS_public);
16636 CopyConstructor->setDefaulted();
16637
16638 setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
16639
16640 if (getLangOpts().CUDA)
16641 CUDA().inferTargetForImplicitSpecialMember(
16643 /* ConstRHS */ Const,
16644 /* Diagnose */ false);
16645
16646 // During template instantiation of special member functions we need a
16647 // reliable TypeSourceInfo for the parameter types in order to allow functions
16648 // to be substituted.
16649 TypeSourceInfo *TSI = nullptr;
16650 if (inTemplateInstantiation() && ClassDecl->isLambda())
16651 TSI = Context.getTrivialTypeSourceInfo(ArgType);
16652
16653 // Add the parameter to the constructor.
16654 ParmVarDecl *FromParam =
16655 ParmVarDecl::Create(Context, CopyConstructor, ClassLoc, ClassLoc,
16656 /*IdentifierInfo=*/nullptr, ArgType,
16657 /*TInfo=*/TSI, SC_None, nullptr);
16658 CopyConstructor->setParams(FromParam);
16659
16660 CopyConstructor->setTrivial(
16664 : ClassDecl->hasTrivialCopyConstructor());
16665
16666 CopyConstructor->setTrivialForCall(
16667 ClassDecl->hasAttr<TrivialABIAttr>() ||
16672 : ClassDecl->hasTrivialCopyConstructorForCall()));
16673
16674 // Note that we have declared this constructor.
16675 ++getASTContext().NumImplicitCopyConstructorsDeclared;
16676
16677 Scope *S = getScopeForContext(ClassDecl);
16679
16684 }
16685
16686 if (S)
16688 ClassDecl->addDecl(CopyConstructor);
16689
16690 return CopyConstructor;
16691}
16692
16695 DefaultedFunctionFPFeaturesRAII RestoreFP(*this, CopyConstructor);
16696 assert((CopyConstructor->isDefaulted() &&
16697 CopyConstructor->isCopyConstructor() &&
16698 !CopyConstructor->doesThisDeclarationHaveABody() &&
16699 !CopyConstructor->isDeleted()) &&
16700 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
16701 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
16702 return;
16703
16704 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
16705 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
16706
16708
16709 // The exception specification is needed because we are defining the
16710 // function.
16711 ResolveExceptionSpec(CurrentLocation,
16712 CopyConstructor->getType()->castAs<FunctionProtoType>());
16713 MarkVTableUsed(CurrentLocation, ClassDecl);
16714
16715 // Add a context note for diagnostics produced after this point.
16716 Scope.addContextNote(CurrentLocation);
16717
16718 // C++11 [class.copy]p7:
16719 // The [definition of an implicitly declared copy constructor] is
16720 // deprecated if the class has a user-declared copy assignment operator
16721 // or a user-declared destructor.
16722 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
16724
16725 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
16726 CopyConstructor->setInvalidDecl();
16727 } else {
16728 SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
16729 ? CopyConstructor->getEndLoc()
16730 : CopyConstructor->getLocation();
16731 Sema::CompoundScopeRAII CompoundScope(*this);
16732 CopyConstructor->setBody(
16733 ActOnCompoundStmt(Loc, Loc, {}, /*isStmtExpr=*/false).getAs<Stmt>());
16734 CopyConstructor->markUsed(Context);
16735 }
16736
16738 L->CompletedImplicitDefinition(CopyConstructor);
16739 }
16740}
16741
16743 CXXRecordDecl *ClassDecl) {
16744 assert(ClassDecl->needsImplicitMoveConstructor());
16745
16746 DeclaringSpecialMember DSM(*this, ClassDecl,
16748 if (DSM.isAlreadyBeingDeclared())
16749 return nullptr;
16750
16751 QualType ClassType = Context.getTagType(ElaboratedTypeKeyword::None,
16752 /*Qualifier=*/std::nullopt, ClassDecl,
16753 /*OwnsTag=*/false);
16754
16755 QualType ArgType = ClassType;
16757 if (AS != LangAS::Default)
16758 ArgType = Context.getAddrSpaceQualType(ClassType, AS);
16759 ArgType = Context.getRValueReferenceType(ArgType);
16760
16762 *this, ClassDecl, CXXSpecialMemberKind::MoveConstructor, false);
16763
16764 DeclarationName Name
16765 = Context.DeclarationNames.getCXXConstructorName(
16766 Context.getCanonicalType(ClassType));
16767 SourceLocation ClassLoc = ClassDecl->getLocation();
16768 DeclarationNameInfo NameInfo(Name, ClassLoc);
16769
16770 // C++11 [class.copy]p11:
16771 // An implicitly-declared copy/move constructor is an inline public
16772 // member of its class.
16774 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
16775 ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
16776 /*isInline=*/true,
16777 /*isImplicitlyDeclared=*/true,
16780 MoveConstructor->setAccess(AS_public);
16781 MoveConstructor->setDefaulted();
16782
16783 setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
16784
16785 if (getLangOpts().CUDA)
16786 CUDA().inferTargetForImplicitSpecialMember(
16788 /* ConstRHS */ false,
16789 /* Diagnose */ false);
16790
16791 // Add the parameter to the constructor.
16793 ClassLoc, ClassLoc,
16794 /*IdentifierInfo=*/nullptr,
16795 ArgType, /*TInfo=*/nullptr,
16796 SC_None, nullptr);
16797 MoveConstructor->setParams(FromParam);
16798
16799 MoveConstructor->setTrivial(
16803 : ClassDecl->hasTrivialMoveConstructor());
16804
16805 MoveConstructor->setTrivialForCall(
16806 ClassDecl->hasAttr<TrivialABIAttr>() ||
16811 : ClassDecl->hasTrivialMoveConstructorForCall()));
16812
16813 // Note that we have declared this constructor.
16814 ++getASTContext().NumImplicitMoveConstructorsDeclared;
16815
16816 Scope *S = getScopeForContext(ClassDecl);
16818
16823 }
16824
16825 if (S)
16827 ClassDecl->addDecl(MoveConstructor);
16828
16829 return MoveConstructor;
16830}
16831
16834 DefaultedFunctionFPFeaturesRAII RestoreFP(*this, MoveConstructor);
16835 assert((MoveConstructor->isDefaulted() &&
16836 MoveConstructor->isMoveConstructor() &&
16837 !MoveConstructor->doesThisDeclarationHaveABody() &&
16838 !MoveConstructor->isDeleted()) &&
16839 "DefineImplicitMoveConstructor - call it for implicit move ctor");
16840 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
16841 return;
16842
16843 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
16844 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
16845
16847
16848 // The exception specification is needed because we are defining the
16849 // function.
16850 ResolveExceptionSpec(CurrentLocation,
16851 MoveConstructor->getType()->castAs<FunctionProtoType>());
16852 MarkVTableUsed(CurrentLocation, ClassDecl);
16853
16854 // Add a context note for diagnostics produced after this point.
16855 Scope.addContextNote(CurrentLocation);
16856
16857 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
16858 MoveConstructor->setInvalidDecl();
16859 } else {
16860 SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
16861 ? MoveConstructor->getEndLoc()
16862 : MoveConstructor->getLocation();
16863 Sema::CompoundScopeRAII CompoundScope(*this);
16864 MoveConstructor->setBody(
16865 ActOnCompoundStmt(Loc, Loc, {}, /*isStmtExpr=*/false).getAs<Stmt>());
16866 MoveConstructor->markUsed(Context);
16867 }
16868
16870 L->CompletedImplicitDefinition(MoveConstructor);
16871 }
16872}
16873
16875 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
16876}
16877
16879 SourceLocation CurrentLocation,
16880 CXXConversionDecl *Conv) {
16881 SynthesizedFunctionScope Scope(*this, Conv);
16882 assert(!Conv->getReturnType()->isUndeducedType());
16883
16884 QualType ConvRT = Conv->getType()->castAs<FunctionType>()->getReturnType();
16885 CallingConv CC =
16886 ConvRT->getPointeeType()->castAs<FunctionType>()->getCallConv();
16887
16888 CXXRecordDecl *Lambda = Conv->getParent();
16889 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
16890 FunctionDecl *Invoker =
16891 CallOp->hasCXXExplicitFunctionObjectParameter() || CallOp->isStatic()
16892 ? CallOp
16893 : Lambda->getLambdaStaticInvoker(CC);
16894
16895 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
16897 CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
16898 if (!CallOp)
16899 return;
16900
16901 if (CallOp != Invoker) {
16903 Invoker->getDescribedFunctionTemplate(), TemplateArgs,
16904 CurrentLocation);
16905 if (!Invoker)
16906 return;
16907 }
16908 }
16909
16910 if (CallOp->isInvalidDecl())
16911 return;
16912
16913 // Mark the call operator referenced (and add to pending instantiations
16914 // if necessary).
16915 // For both the conversion and static-invoker template specializations
16916 // we construct their body's in this function, so no need to add them
16917 // to the PendingInstantiations.
16918 MarkFunctionReferenced(CurrentLocation, CallOp);
16919
16920 if (Invoker != CallOp) {
16921 // Fill in the __invoke function with a dummy implementation. IR generation
16922 // will fill in the actual details. Update its type in case it contained
16923 // an 'auto'.
16924 Invoker->markUsed(Context);
16925 Invoker->setReferenced();
16926 Invoker->setType(Conv->getReturnType()->getPointeeType());
16927 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
16928 }
16929
16930 // Construct the body of the conversion function { return __invoke; }.
16931 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), VK_LValue,
16932 Conv->getLocation());
16933 assert(FunctionRef && "Can't refer to __invoke function?");
16934 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
16936 Conv->getLocation(), Conv->getLocation()));
16937 Conv->markUsed(Context);
16938 Conv->setReferenced();
16939
16941 L->CompletedImplicitDefinition(Conv);
16942 if (Invoker != CallOp)
16943 L->CompletedImplicitDefinition(Invoker);
16944 }
16945}
16946
16948 SourceLocation CurrentLocation, CXXConversionDecl *Conv) {
16949 assert(!Conv->getParent()->isGenericLambda());
16950
16951 SynthesizedFunctionScope Scope(*this, Conv);
16952
16953 // Copy-initialize the lambda object as needed to capture it.
16954 Expr *This = ActOnCXXThis(CurrentLocation).get();
16955 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
16956
16957 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
16958 Conv->getLocation(),
16959 Conv, DerefThis);
16960
16961 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
16962 // behavior. Note that only the general conversion function does this
16963 // (since it's unusable otherwise); in the case where we inline the
16964 // block literal, it has block literal lifetime semantics.
16965 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
16966 BuildBlock = ImplicitCastExpr::Create(
16967 Context, BuildBlock.get()->getType(), CK_CopyAndAutoreleaseBlockObject,
16968 BuildBlock.get(), nullptr, VK_PRValue, FPOptionsOverride());
16969
16970 if (BuildBlock.isInvalid()) {
16971 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
16972 Conv->setInvalidDecl();
16973 return;
16974 }
16975
16976 // Create the return statement that returns the block from the conversion
16977 // function.
16978 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
16979 if (Return.isInvalid()) {
16980 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
16981 Conv->setInvalidDecl();
16982 return;
16983 }
16984
16985 // Set the body of the conversion function.
16986 Stmt *ReturnS = Return.get();
16988 Conv->getLocation(), Conv->getLocation()));
16989 Conv->markUsed(Context);
16990
16991 // We're done; notify the mutation listener, if any.
16993 L->CompletedImplicitDefinition(Conv);
16994 }
16995}
16996
16997/// Determine whether the given list arguments contains exactly one
16998/// "real" (non-default) argument.
17000 switch (Args.size()) {
17001 case 0:
17002 return false;
17003
17004 default:
17005 if (!Args[1]->isDefaultArgument())
17006 return false;
17007
17008 [[fallthrough]];
17009 case 1:
17010 return !Args[0]->isDefaultArgument();
17011 }
17012
17013 return false;
17014}
17015
17017 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
17019 bool HadMultipleCandidates, bool IsListInitialization,
17020 bool IsStdInitListInitialization, bool RequiresZeroInit,
17021 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
17022 bool Elidable = false;
17023
17024 // C++0x [class.copy]p34:
17025 // When certain criteria are met, an implementation is allowed to
17026 // omit the copy/move construction of a class object, even if the
17027 // copy/move constructor and/or destructor for the object have
17028 // side effects. [...]
17029 // - when a temporary class object that has not been bound to a
17030 // reference (12.2) would be copied/moved to a class object
17031 // with the same cv-unqualified type, the copy/move operation
17032 // can be omitted by constructing the temporary object
17033 // directly into the target of the omitted copy/move
17034 if (ConstructKind == CXXConstructionKind::Complete && Constructor &&
17035 // FIXME: Converting constructors should also be accepted.
17036 // But to fix this, the logic that digs down into a CXXConstructExpr
17037 // to find the source object needs to handle it.
17038 // Right now it assumes the source object is passed directly as the
17039 // first argument.
17040 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
17041 Expr *SubExpr = ExprArgs[0];
17042 // FIXME: Per above, this is also incorrect if we want to accept
17043 // converting constructors, as isTemporaryObject will
17044 // reject temporaries with different type from the
17045 // CXXRecord itself.
17046 Elidable = SubExpr->isTemporaryObject(
17048 }
17049
17050 return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
17051 FoundDecl, Constructor,
17052 Elidable, ExprArgs, HadMultipleCandidates,
17053 IsListInitialization,
17054 IsStdInitListInitialization, RequiresZeroInit,
17055 ConstructKind, ParenRange);
17056}
17057
17059 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
17060 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg ExprArgs,
17061 bool HadMultipleCandidates, bool IsListInitialization,
17062 bool IsStdInitListInitialization, bool RequiresZeroInit,
17063 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
17064 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
17065 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
17066 // The only way to get here is if we did overload resolution to find the
17067 // shadow decl, so we don't need to worry about re-checking the trailing
17068 // requires clause.
17069 if (DiagnoseUseOfOverloadedDecl(Constructor, ConstructLoc))
17070 return ExprError();
17071 }
17072
17073 return BuildCXXConstructExpr(
17074 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
17075 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
17076 RequiresZeroInit, ConstructKind, ParenRange);
17077}
17078
17079/// BuildCXXConstructExpr - Creates a complete call to a constructor,
17080/// including handling of its default argument expressions.
17082 SourceLocation ConstructLoc, QualType DeclInitType,
17083 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg ExprArgs,
17084 bool HadMultipleCandidates, bool IsListInitialization,
17085 bool IsStdInitListInitialization, bool RequiresZeroInit,
17086 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
17087 assert(declaresSameEntity(
17088 Constructor->getParent(),
17089 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
17090 "given constructor for wrong type");
17091 MarkFunctionReferenced(ConstructLoc, Constructor);
17092 if (getLangOpts().CUDA && !CUDA().CheckCall(ConstructLoc, Constructor))
17093 return ExprError();
17094
17097 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
17098 HadMultipleCandidates, IsListInitialization,
17099 IsStdInitListInitialization, RequiresZeroInit,
17100 static_cast<CXXConstructionKind>(ConstructKind), ParenRange),
17101 Constructor);
17102}
17103
17105 if (VD->isInvalidDecl()) return;
17106 // If initializing the variable failed, don't also diagnose problems with
17107 // the destructor, they're likely related.
17108 if (VD->getInit() && VD->getInit()->containsErrors())
17109 return;
17110
17111 ClassDecl = ClassDecl->getDefinitionOrSelf();
17112 if (ClassDecl->isInvalidDecl()) return;
17113 if (ClassDecl->hasIrrelevantDestructor()) return;
17114 if (ClassDecl->isDependentContext()) return;
17115
17116 if (VD->isNoDestroy(getASTContext()))
17117 return;
17118
17120 // The result of `LookupDestructor` might be nullptr if the destructor is
17121 // invalid, in which case it is marked as `IneligibleOrNotSelected` and
17122 // will not be selected by `CXXRecordDecl::getDestructor()`.
17123 if (!Destructor)
17124 return;
17125 // If this is an array, we'll require the destructor during initialization, so
17126 // we can skip over this. We still want to emit exit-time destructor warnings
17127 // though.
17128 if (!VD->getType()->isArrayType()) {
17131 PDiag(diag::err_access_dtor_var)
17132 << VD->getDeclName() << VD->getType());
17134 }
17135
17136 if (Destructor->isTrivial()) return;
17137
17138 // If the destructor is constexpr, check whether the variable has constant
17139 // destruction now.
17140 if (Destructor->isConstexpr()) {
17141 bool HasConstantInit = false;
17142 if (VD->getInit() && !VD->getInit()->isValueDependent())
17143 HasConstantInit = VD->evaluateValue();
17145 sema::EvalProxy SProxy(*this);
17146 if (!VD->evaluateConstantDestruction(Notes, SProxy) && VD->isConstexpr() &&
17147 HasConstantInit) {
17148 Diag(VD->getLocation(),
17149 diag::err_constexpr_var_requires_const_destruction) << VD;
17150 for (const PartialDiagnosticAt &Note : Notes)
17151 Diag(Note.first, Note.second);
17152 }
17153 }
17154
17155 if (!VD->hasGlobalStorage() || !VD->needsDestruction(Context))
17156 return;
17157
17158 // Emit warning for non-trivial dtor in global scope (a real global,
17159 // class-static, function-static).
17160 if (!VD->hasAttr<AlwaysDestroyAttr>())
17161 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
17162
17163 // TODO: this should be re-enabled for static locals by !CXAAtExit
17164 if (!VD->isStaticLocal())
17165 Diag(VD->getLocation(), diag::warn_global_destructor);
17166}
17167
17169 QualType DeclInitType, MultiExprArg ArgsPtr,
17170 SourceLocation Loc,
17171 SmallVectorImpl<Expr *> &ConvertedArgs,
17172 bool AllowExplicit,
17173 bool IsListInitialization) {
17174 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
17175 unsigned NumArgs = ArgsPtr.size();
17176 Expr **Args = ArgsPtr.data();
17177
17178 const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>();
17179 unsigned NumParams = Proto->getNumParams();
17180
17181 // If too few arguments are available, we'll fill in the rest with defaults.
17182 if (NumArgs < NumParams)
17183 ConvertedArgs.reserve(NumParams);
17184 else
17185 ConvertedArgs.reserve(NumArgs);
17186
17187 VariadicCallType CallType = Proto->isVariadic()
17190 SmallVector<Expr *, 8> AllArgs;
17192 Loc, Constructor, Proto, 0, llvm::ArrayRef(Args, NumArgs), AllArgs,
17193 CallType, AllowExplicit, IsListInitialization);
17194 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
17195
17196 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
17197
17198 CheckConstructorCall(Constructor, DeclInitType, llvm::ArrayRef(AllArgs),
17199 Proto, Loc);
17200
17201 return Invalid;
17202}
17203
17205 bool SeenTypedOperators = Context.hasSeenTypeAwareOperatorNewOrDelete();
17206 return typeAwareAllocationModeFromBool(SeenTypedOperators);
17207}
17208
17211 QualType DeallocType, SourceLocation Loc) {
17212 if (DeallocType.isNull())
17213 return nullptr;
17214
17215 FunctionDecl *FnDecl = FnTemplateDecl->getTemplatedDecl();
17216 if (!FnDecl->isTypeAwareOperatorNewOrDelete())
17217 return nullptr;
17218
17219 if (FnDecl->isVariadic())
17220 return nullptr;
17221
17222 unsigned NumParams = FnDecl->getNumParams();
17223 constexpr unsigned RequiredParameterCount =
17225 // A usual deallocation function has no placement parameters
17226 if (NumParams != RequiredParameterCount)
17227 return nullptr;
17228
17229 // A type aware allocation is only usual if the only dependent parameter is
17230 // the first parameter.
17231 if (llvm::any_of(FnDecl->parameters().drop_front(),
17232 [](const ParmVarDecl *ParamDecl) {
17233 return ParamDecl->getType()->isDependentType();
17234 }))
17235 return nullptr;
17236
17237 QualType SpecializedTypeIdentity = tryBuildStdTypeIdentity(DeallocType, Loc);
17238 if (SpecializedTypeIdentity.isNull())
17239 return nullptr;
17240
17242 ArgTypes.reserve(NumParams);
17243
17244 // The first parameter to a type aware operator delete is by definition the
17245 // type-identity argument, so we explicitly set this to the target
17246 // type-identity type, the remaining usual parameters should then simply match
17247 // the type declared in the function template.
17248 ArgTypes.push_back(SpecializedTypeIdentity);
17249 for (unsigned ParamIdx = 1; ParamIdx < RequiredParameterCount; ++ParamIdx)
17250 ArgTypes.push_back(FnDecl->getParamDecl(ParamIdx)->getType());
17251
17253 QualType ExpectedFunctionType =
17254 Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
17257 if (DeduceTemplateArguments(FnTemplateDecl, nullptr, ExpectedFunctionType,
17259 return nullptr;
17260 return Result;
17261}
17262
17263static inline bool
17265 const FunctionDecl *FnDecl) {
17266 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
17267 if (isa<NamespaceDecl>(DC)) {
17268 return SemaRef.Diag(FnDecl->getLocation(),
17269 diag::err_operator_new_delete_declared_in_namespace)
17270 << FnDecl->getDeclName();
17271 }
17272
17273 if (isa<TranslationUnitDecl>(DC) &&
17274 FnDecl->getStorageClass() == SC_Static) {
17275 return SemaRef.Diag(FnDecl->getLocation(),
17276 diag::err_operator_new_delete_declared_static)
17277 << FnDecl->getDeclName();
17278 }
17279
17280 return false;
17281}
17282
17284 const PointerType *PtrTy) {
17285 auto &Ctx = SemaRef.Context;
17286 Qualifiers PtrQuals = PtrTy->getPointeeType().getQualifiers();
17287 PtrQuals.removeAddressSpace();
17289 PtrTy->getPointeeType().getUnqualifiedType(), PtrQuals)));
17290}
17291
17293
17295 const FunctionDecl *FD,
17296 bool *WasMalformed) {
17297 const Decl *MalformedDecl = nullptr;
17298 if (FD->getNumParams() > 0 &&
17299 SemaRef.isStdTypeIdentity(FD->getParamDecl(0)->getType(),
17300 /*TypeArgument=*/nullptr, &MalformedDecl))
17301 return true;
17302
17303 if (!MalformedDecl)
17304 return false;
17305
17306 if (WasMalformed)
17307 *WasMalformed = true;
17308
17309 return true;
17310}
17311
17313 auto *RD = Type->getAsCXXRecordDecl();
17314 return RD && RD->isInStdNamespace() && RD->getIdentifier() &&
17315 RD->getIdentifier()->isStr("destroying_delete_t");
17316}
17317
17319 const FunctionDecl *FD) {
17320 // C++ P0722:
17321 // Within a class C, a single object deallocation function with signature
17322 // (T, std::destroying_delete_t, <more params>)
17323 // is a destroying operator delete.
17324 bool IsPotentiallyTypeAware = IsPotentiallyTypeAwareOperatorNewOrDelete(
17325 SemaRef, FD, /*WasMalformed=*/nullptr);
17326 unsigned DestroyingDeleteIdx = IsPotentiallyTypeAware + /* address */ 1;
17327 return isa<CXXMethodDecl>(FD) && FD->getOverloadedOperator() == OO_Delete &&
17328 FD->getNumParams() > DestroyingDeleteIdx &&
17329 isDestroyingDeleteT(FD->getParamDecl(DestroyingDeleteIdx)->getType());
17330}
17331
17333 Sema &SemaRef, FunctionDecl *FnDecl, AllocationOperatorKind OperatorKind,
17334 CanQualType ExpectedResultType, CanQualType ExpectedSizeOrAddressParamType,
17335 unsigned DependentParamTypeDiag, unsigned InvalidParamTypeDiag) {
17336 auto NormalizeType = [&SemaRef](QualType T) {
17337 if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
17338 // The operator is valid on any address space for OpenCL.
17339 // Drop address space from actual and expected result types.
17340 if (const auto PtrTy = T->template getAs<PointerType>())
17341 T = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
17342 }
17343 return SemaRef.Context.getCanonicalType(T);
17344 };
17345
17346 const unsigned NumParams = FnDecl->getNumParams();
17347 unsigned FirstNonTypeParam = 0;
17348 bool MalformedTypeIdentity = false;
17349 bool IsPotentiallyTypeAware = IsPotentiallyTypeAwareOperatorNewOrDelete(
17350 SemaRef, FnDecl, &MalformedTypeIdentity);
17351 unsigned MinimumMandatoryArgumentCount = 1;
17352 unsigned SizeParameterIndex = 0;
17353 if (IsPotentiallyTypeAware) {
17354 // We don't emit this diagnosis for template instantiations as we will
17355 // have already emitted it for the original template declaration.
17356 if (!FnDecl->isTemplateInstantiation())
17357 SemaRef.Diag(FnDecl->getLocation(), diag::warn_ext_type_aware_allocators);
17358
17359 if (OperatorKind == AllocationOperatorKind::New) {
17360 SizeParameterIndex = 1;
17361 MinimumMandatoryArgumentCount =
17363 } else {
17364 SizeParameterIndex = 2;
17365 MinimumMandatoryArgumentCount =
17367 }
17368 FirstNonTypeParam = 1;
17369 }
17370
17371 bool IsPotentiallyDestroyingDelete =
17373
17374 if (IsPotentiallyDestroyingDelete) {
17375 ++MinimumMandatoryArgumentCount;
17376 ++SizeParameterIndex;
17377 }
17378
17379 if (NumParams < MinimumMandatoryArgumentCount)
17380 return SemaRef.Diag(FnDecl->getLocation(),
17381 diag::err_operator_new_delete_too_few_parameters)
17382 << IsPotentiallyTypeAware << IsPotentiallyDestroyingDelete
17383 << FnDecl->getDeclName() << MinimumMandatoryArgumentCount;
17384
17385 for (unsigned Idx = 0; Idx < MinimumMandatoryArgumentCount; ++Idx) {
17386 const ParmVarDecl *ParamDecl = FnDecl->getParamDecl(Idx);
17387 if (ParamDecl->hasDefaultArg())
17388 return SemaRef.Diag(FnDecl->getLocation(),
17389 diag::err_operator_new_default_arg)
17390 << FnDecl->getDeclName() << Idx << ParamDecl->getDefaultArgRange();
17391 }
17392
17393 auto *FnType = FnDecl->getType()->castAs<FunctionType>();
17394 QualType CanResultType = NormalizeType(FnType->getReturnType());
17395 QualType CanExpectedResultType = NormalizeType(ExpectedResultType);
17396 QualType CanExpectedSizeOrAddressParamType =
17397 NormalizeType(ExpectedSizeOrAddressParamType);
17398
17399 // Check that the result type is what we expect.
17400 if (CanResultType != CanExpectedResultType) {
17401 // Reject even if the type is dependent; an operator delete function is
17402 // required to have a non-dependent result type.
17403 return SemaRef.Diag(
17404 FnDecl->getLocation(),
17405 CanResultType->isDependentType()
17406 ? diag::err_operator_new_delete_dependent_result_type
17407 : diag::err_operator_new_delete_invalid_result_type)
17408 << FnDecl->getDeclName() << ExpectedResultType;
17409 }
17410
17411 // A function template must have at least 2 parameters.
17412 if (FnDecl->getDescribedFunctionTemplate() && NumParams < 2)
17413 return SemaRef.Diag(FnDecl->getLocation(),
17414 diag::err_operator_new_delete_template_too_few_parameters)
17415 << FnDecl->getDeclName();
17416
17417 auto CheckType = [&](unsigned ParamIdx, QualType ExpectedType,
17418 auto FallbackType) -> bool {
17419 const ParmVarDecl *ParamDecl = FnDecl->getParamDecl(ParamIdx);
17420 if (ExpectedType.isNull()) {
17421 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
17422 << IsPotentiallyTypeAware << IsPotentiallyDestroyingDelete
17423 << FnDecl->getDeclName() << (1 + ParamIdx) << FallbackType
17424 << ParamDecl->getSourceRange();
17425 }
17426 CanQualType CanExpectedTy =
17427 NormalizeType(SemaRef.Context.getCanonicalType(ExpectedType));
17428 auto ActualParamType =
17429 NormalizeType(ParamDecl->getType().getUnqualifiedType());
17430 if (ActualParamType == CanExpectedTy)
17431 return false;
17432 unsigned Diagnostic = ActualParamType->isDependentType()
17433 ? DependentParamTypeDiag
17434 : InvalidParamTypeDiag;
17435 return SemaRef.Diag(FnDecl->getLocation(), Diagnostic)
17436 << IsPotentiallyTypeAware << IsPotentiallyDestroyingDelete
17437 << FnDecl->getDeclName() << (1 + ParamIdx) << ExpectedType
17438 << FallbackType << ParamDecl->getSourceRange();
17439 };
17440
17441 // Check that the first parameter type is what we expect.
17442 if (CheckType(FirstNonTypeParam, CanExpectedSizeOrAddressParamType, "size_t"))
17443 return true;
17444
17445 FnDecl->setIsDestroyingOperatorDelete(IsPotentiallyDestroyingDelete);
17446
17447 // If the first parameter type is not a type-identity we're done, otherwise
17448 // we need to ensure the size and alignment parameters have the correct type
17449 if (!IsPotentiallyTypeAware)
17450 return false;
17451
17452 if (CheckType(SizeParameterIndex, SemaRef.Context.getSizeType(), "size_t"))
17453 return true;
17454 TagDecl *StdAlignValTDecl = SemaRef.getStdAlignValT();
17455 CanQualType StdAlignValT =
17456 StdAlignValTDecl ? SemaRef.Context.getCanonicalTagType(StdAlignValTDecl)
17457 : CanQualType();
17458 if (CheckType(SizeParameterIndex + 1, StdAlignValT, "std::align_val_t"))
17459 return true;
17460
17462 return MalformedTypeIdentity;
17463}
17464
17465static bool CheckOperatorNewDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
17466 // C++ [basic.stc.dynamic.allocation]p1:
17467 // A program is ill-formed if an allocation function is declared in a
17468 // namespace scope other than global scope or declared static in global
17469 // scope.
17470 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
17471 return true;
17472
17473 CanQualType SizeTy =
17474 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
17475
17476 // C++ [basic.stc.dynamic.allocation]p1:
17477 // The return type shall be void*. The first parameter shall have type
17478 // std::size_t.
17480 SemaRef, FnDecl, AllocationOperatorKind::New, SemaRef.Context.VoidPtrTy,
17481 SizeTy, diag::err_operator_new_dependent_param_type,
17482 diag::err_operator_new_param_type);
17483}
17484
17485static bool
17487 // C++ [basic.stc.dynamic.deallocation]p1:
17488 // A program is ill-formed if deallocation functions are declared in a
17489 // namespace scope other than global scope or declared static in global
17490 // scope.
17491 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
17492 return true;
17493
17494 auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
17495 auto ConstructDestroyingDeleteAddressType = [&]() {
17496 assert(MD);
17497 return SemaRef.Context.getPointerType(
17498 SemaRef.Context.getCanonicalTagType(MD->getParent()));
17499 };
17500
17501 // C++ P2719: A destroying operator delete cannot be type aware
17502 // so for QoL we actually check for this explicitly by considering
17503 // an destroying-delete appropriate address type and the presence of
17504 // any parameter of type destroying_delete_t as an erroneous attempt
17505 // to declare a type aware destroying delete, rather than emitting a
17506 // pile of incorrect parameter type errors.
17508 SemaRef, MD, /*WasMalformed=*/nullptr)) {
17509 QualType AddressParamType =
17510 SemaRef.Context.getCanonicalType(MD->getParamDecl(1)->getType());
17511 if (AddressParamType != SemaRef.Context.VoidPtrTy &&
17512 AddressParamType == ConstructDestroyingDeleteAddressType()) {
17513 // The address parameter type implies an author trying to construct a
17514 // type aware destroying delete, so we'll see if we can find a parameter
17515 // of type `std::destroying_delete_t`, and if we find it we'll report
17516 // this as being an attempt at a type aware destroying delete just stop
17517 // here. If we don't do this, the resulting incorrect parameter ordering
17518 // results in a pile mismatched argument type errors that don't explain
17519 // the core problem.
17520 for (auto Param : MD->parameters()) {
17521 if (isDestroyingDeleteT(Param->getType())) {
17522 SemaRef.Diag(MD->getLocation(),
17523 diag::err_type_aware_destroying_operator_delete)
17524 << Param->getSourceRange();
17525 return true;
17526 }
17527 }
17528 }
17529 }
17530
17531 // C++ P0722:
17532 // Within a class C, the first parameter of a destroying operator delete
17533 // shall be of type C *. The first parameter of any other deallocation
17534 // function shall be of type void *.
17535 CanQualType ExpectedAddressParamType =
17536 MD && IsPotentiallyDestroyingOperatorDelete(SemaRef, MD)
17537 ? SemaRef.Context.getPointerType(
17538 SemaRef.Context.getCanonicalTagType(MD->getParent()))
17539 : SemaRef.Context.VoidPtrTy;
17540
17541 // C++ [basic.stc.dynamic.deallocation]p2:
17542 // Each deallocation function shall return void
17544 SemaRef, FnDecl, AllocationOperatorKind::Delete,
17545 SemaRef.Context.VoidTy, ExpectedAddressParamType,
17546 diag::err_operator_delete_dependent_param_type,
17547 diag::err_operator_delete_param_type))
17548 return true;
17549
17550 // C++ P0722:
17551 // A destroying operator delete shall be a usual deallocation function.
17552 if (MD && !MD->getParent()->isDependentContext() &&
17554 if (!SemaRef.isUsualDeallocationFunction(MD)) {
17555 SemaRef.Diag(MD->getLocation(),
17556 diag::err_destroying_operator_delete_not_usual);
17557 return true;
17558 }
17559 }
17560
17561 return false;
17562}
17563
17565 assert(FnDecl && FnDecl->isOverloadedOperator() &&
17566 "Expected an overloaded operator declaration");
17567
17569
17570 // C++ [over.oper]p5:
17571 // The allocation and deallocation functions, operator new,
17572 // operator new[], operator delete and operator delete[], are
17573 // described completely in 3.7.3. The attributes and restrictions
17574 // found in the rest of this subclause do not apply to them unless
17575 // explicitly stated in 3.7.3.
17576 if (Op == OO_Delete || Op == OO_Array_Delete)
17577 return CheckOperatorDeleteDeclaration(*this, FnDecl);
17578
17579 if (Op == OO_New || Op == OO_Array_New)
17580 return CheckOperatorNewDeclaration(*this, FnDecl);
17581
17582 // C++ [over.oper]p7:
17583 // An operator function shall either be a member function or
17584 // be a non-member function and have at least one parameter
17585 // whose type is a class, a reference to a class, an enumeration,
17586 // or a reference to an enumeration.
17587 // Note: Before C++23, a member function could not be static. The only member
17588 // function allowed to be static is the call operator function.
17589 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
17590 if (MethodDecl->isStatic()) {
17591 if (Op == OO_Call || Op == OO_Subscript)
17592 DiagCompat(FnDecl->getLocation(), diag_compat::operator_overload_static)
17593 << FnDecl;
17594 else
17595 return Diag(FnDecl->getLocation(), diag::err_operator_overload_static)
17596 << FnDecl;
17597 }
17598 } else {
17599 bool ClassOrEnumParam = false;
17600 for (auto *Param : FnDecl->parameters()) {
17601 QualType ParamType = Param->getType().getNonReferenceType();
17602 if (ParamType->isDependentType() || ParamType->isRecordType() ||
17603 ParamType->isEnumeralType()) {
17604 ClassOrEnumParam = true;
17605 break;
17606 }
17607 }
17608
17609 if (!ClassOrEnumParam)
17610 return Diag(FnDecl->getLocation(),
17611 diag::err_operator_overload_needs_class_or_enum)
17612 << FnDecl->getDeclName();
17613 }
17614
17615 // C++ [over.oper]p8:
17616 // An operator function cannot have default arguments (8.3.6),
17617 // except where explicitly stated below.
17618 //
17619 // Only the function-call operator (C++ [over.call]p1) and the subscript
17620 // operator (CWG2507) allow default arguments.
17621 if (Op != OO_Call) {
17622 ParmVarDecl *FirstDefaultedParam = nullptr;
17623 for (auto *Param : FnDecl->parameters()) {
17624 if (Param->hasDefaultArg()) {
17625 FirstDefaultedParam = Param;
17626 break;
17627 }
17628 }
17629 if (FirstDefaultedParam) {
17630 if (Op == OO_Subscript) {
17631 Diag(FnDecl->getLocation(), LangOpts.CPlusPlus23
17632 ? diag::ext_subscript_overload
17633 : diag::error_subscript_overload)
17634 << FnDecl->getDeclName() << 1
17635 << FirstDefaultedParam->getDefaultArgRange();
17636 } else {
17637 return Diag(FirstDefaultedParam->getLocation(),
17638 diag::err_operator_overload_default_arg)
17639 << FnDecl->getDeclName()
17640 << FirstDefaultedParam->getDefaultArgRange();
17641 }
17642 }
17643 }
17644
17645 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
17646 { false, false, false }
17647#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
17648 , { Unary, Binary, MemberOnly }
17649#include "clang/Basic/OperatorKinds.def"
17650 };
17651
17652 bool CanBeUnaryOperator = OperatorUses[Op][0];
17653 bool CanBeBinaryOperator = OperatorUses[Op][1];
17654 bool MustBeMemberOperator = OperatorUses[Op][2];
17655
17656 // C++ [over.oper]p8:
17657 // [...] Operator functions cannot have more or fewer parameters
17658 // than the number required for the corresponding operator, as
17659 // described in the rest of this subclause.
17660 unsigned NumParams = FnDecl->getNumParams() +
17661 (isa<CXXMethodDecl>(FnDecl) &&
17663 ? 1
17664 : 0);
17665 if (Op != OO_Call && Op != OO_Subscript &&
17666 ((NumParams == 1 && !CanBeUnaryOperator) ||
17667 (NumParams == 2 && !CanBeBinaryOperator) || (NumParams < 1) ||
17668 (NumParams > 2))) {
17669 // We have the wrong number of parameters.
17670 unsigned ErrorKind;
17671 if (CanBeUnaryOperator && CanBeBinaryOperator) {
17672 ErrorKind = 2; // 2 -> unary or binary.
17673 } else if (CanBeUnaryOperator) {
17674 ErrorKind = 0; // 0 -> unary
17675 } else {
17676 assert(CanBeBinaryOperator &&
17677 "All non-call overloaded operators are unary or binary!");
17678 ErrorKind = 1; // 1 -> binary
17679 }
17680 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
17681 << FnDecl->getDeclName() << NumParams << ErrorKind;
17682 }
17683
17684 if (Op == OO_Subscript && NumParams != 2) {
17685 Diag(FnDecl->getLocation(), LangOpts.CPlusPlus23
17686 ? diag::ext_subscript_overload
17687 : diag::error_subscript_overload)
17688 << FnDecl->getDeclName() << (NumParams == 1 ? 0 : 2);
17689 }
17690
17691 // Overloaded operators other than operator() and operator[] cannot be
17692 // variadic.
17693 if (Op != OO_Call &&
17694 FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) {
17695 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
17696 << FnDecl->getDeclName();
17697 }
17698
17699 // Some operators must be member functions.
17700 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
17701 return Diag(FnDecl->getLocation(),
17702 diag::err_operator_overload_must_be_member)
17703 << FnDecl->getDeclName();
17704 }
17705
17706 // C++ [over.inc]p1:
17707 // The user-defined function called operator++ implements the
17708 // prefix and postfix ++ operator. If this function is a member
17709 // function with no parameters, or a non-member function with one
17710 // parameter of class or enumeration type, it defines the prefix
17711 // increment operator ++ for objects of that type. If the function
17712 // is a member function with one parameter (which shall be of type
17713 // int) or a non-member function with two parameters (the second
17714 // of which shall be of type int), it defines the postfix
17715 // increment operator ++ for objects of that type.
17716 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
17717 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
17718 QualType ParamType = LastParam->getType();
17719
17720 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
17721 !ParamType->isDependentType())
17722 return Diag(LastParam->getLocation(),
17723 diag::err_operator_overload_post_incdec_must_be_int)
17724 << LastParam->getType() << (Op == OO_MinusMinus);
17725 }
17726
17727 return false;
17728}
17729
17730static bool
17732 FunctionTemplateDecl *TpDecl) {
17733 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
17734
17735 // Must have one or two template parameters.
17736 if (TemplateParams->size() == 1) {
17737 NonTypeTemplateParmDecl *PmDecl =
17738 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
17739
17740 // The template parameter must be a char parameter pack.
17741 if (PmDecl && PmDecl->isTemplateParameterPack() &&
17742 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
17743 return false;
17744
17745 // C++20 [over.literal]p5:
17746 // A string literal operator template is a literal operator template
17747 // whose template-parameter-list comprises a single non-type
17748 // template-parameter of class type.
17749 //
17750 // As a DR resolution, we also allow placeholders for deduced class
17751 // template specializations.
17752 if (SemaRef.getLangOpts().CPlusPlus20 && PmDecl &&
17753 !PmDecl->isTemplateParameterPack() &&
17754 (PmDecl->getType()->isRecordType() ||
17755 PmDecl->getType()->getAs<DeducedTemplateSpecializationType>()))
17756 return false;
17757 } else if (TemplateParams->size() == 2) {
17758 TemplateTypeParmDecl *PmType =
17759 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
17760 NonTypeTemplateParmDecl *PmArgs =
17761 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
17762
17763 // The second template parameter must be a parameter pack with the
17764 // first template parameter as its type.
17765 if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
17766 PmArgs->isTemplateParameterPack()) {
17767 if (const auto *TArgs =
17768 PmArgs->getType()->getAsCanonical<TemplateTypeParmType>();
17769 TArgs && TArgs->getDepth() == PmType->getDepth() &&
17770 TArgs->getIndex() == PmType->getIndex()) {
17771 if (!SemaRef.inTemplateInstantiation())
17772 SemaRef.Diag(TpDecl->getLocation(),
17773 diag::ext_string_literal_operator_template);
17774 return false;
17775 }
17776 }
17777 }
17778
17779 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
17780 diag::err_literal_operator_template)
17781 << TpDecl->getTemplateParameters()->getSourceRange();
17782 return true;
17783}
17784
17786 if (isa<CXXMethodDecl>(FnDecl)) {
17787 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
17788 << FnDecl->getDeclName();
17789 return true;
17790 }
17791
17792 if (FnDecl->isExternC()) {
17793 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
17794 if (const LinkageSpecDecl *LSD =
17795 FnDecl->getDeclContext()->getExternCContext())
17796 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
17797 return true;
17798 }
17799
17800 // This might be the definition of a literal operator template.
17802
17803 // This might be a specialization of a literal operator template.
17804 if (!TpDecl)
17805 TpDecl = FnDecl->getPrimaryTemplate();
17806
17807 // template <char...> type operator "" name() and
17808 // template <class T, T...> type operator "" name() are the only valid
17809 // template signatures, and the only valid signatures with no parameters.
17810 //
17811 // C++20 also allows template <SomeClass T> type operator "" name().
17812 if (TpDecl) {
17813 if (FnDecl->param_size() != 0) {
17814 Diag(FnDecl->getLocation(),
17815 diag::err_literal_operator_template_with_params);
17816 return true;
17817 }
17818
17820 return true;
17821
17822 } else if (FnDecl->param_size() == 1) {
17823 const ParmVarDecl *Param = FnDecl->getParamDecl(0);
17824
17825 QualType ParamType = Param->getType().getUnqualifiedType();
17826
17827 // Only unsigned long long int, long double, any character type, and const
17828 // char * are allowed as the only parameters.
17829 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
17830 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
17831 Context.hasSameType(ParamType, Context.CharTy) ||
17832 Context.hasSameType(ParamType, Context.WideCharTy) ||
17833 Context.hasSameType(ParamType, Context.Char8Ty) ||
17834 Context.hasSameType(ParamType, Context.Char16Ty) ||
17835 Context.hasSameType(ParamType, Context.Char32Ty)) {
17836 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
17837 QualType InnerType = Ptr->getPointeeType();
17838
17839 // Pointer parameter must be a const char *.
17840 if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
17841 Context.CharTy) &&
17842 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
17843 Diag(Param->getSourceRange().getBegin(),
17844 diag::err_literal_operator_param)
17845 << ParamType << "'const char *'" << Param->getSourceRange();
17846 return true;
17847 }
17848
17849 } else if (ParamType->isRealFloatingType()) {
17850 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
17851 << ParamType << Context.LongDoubleTy << Param->getSourceRange();
17852 return true;
17853
17854 } else if (ParamType->isIntegerType()) {
17855 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
17856 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
17857 return true;
17858
17859 } else {
17860 Diag(Param->getSourceRange().getBegin(),
17861 diag::err_literal_operator_invalid_param)
17862 << ParamType << Param->getSourceRange();
17863 return true;
17864 }
17865
17866 } else if (FnDecl->param_size() == 2) {
17867 FunctionDecl::param_iterator Param = FnDecl->param_begin();
17868
17869 // First, verify that the first parameter is correct.
17870
17871 QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
17872
17873 // Two parameter function must have a pointer to const as a
17874 // first parameter; let's strip those qualifiers.
17875 const PointerType *PT = FirstParamType->getAs<PointerType>();
17876
17877 if (!PT) {
17878 Diag((*Param)->getSourceRange().getBegin(),
17879 diag::err_literal_operator_param)
17880 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
17881 return true;
17882 }
17883
17884 QualType PointeeType = PT->getPointeeType();
17885 // First parameter must be const
17886 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
17887 Diag((*Param)->getSourceRange().getBegin(),
17888 diag::err_literal_operator_param)
17889 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
17890 return true;
17891 }
17892
17893 QualType InnerType = PointeeType.getUnqualifiedType();
17894 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
17895 // const char32_t* are allowed as the first parameter to a two-parameter
17896 // function
17897 if (!(Context.hasSameType(InnerType, Context.CharTy) ||
17898 Context.hasSameType(InnerType, Context.WideCharTy) ||
17899 Context.hasSameType(InnerType, Context.Char8Ty) ||
17900 Context.hasSameType(InnerType, Context.Char16Ty) ||
17901 Context.hasSameType(InnerType, Context.Char32Ty))) {
17902 Diag((*Param)->getSourceRange().getBegin(),
17903 diag::err_literal_operator_param)
17904 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
17905 return true;
17906 }
17907
17908 // Move on to the second and final parameter.
17909 ++Param;
17910
17911 // The second parameter must be a std::size_t.
17912 QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
17913 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
17914 Diag((*Param)->getSourceRange().getBegin(),
17915 diag::err_literal_operator_param)
17916 << SecondParamType << Context.getSizeType()
17917 << (*Param)->getSourceRange();
17918 return true;
17919 }
17920 } else {
17921 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
17922 return true;
17923 }
17924
17925 // Parameters are good.
17926
17927 // A parameter-declaration-clause containing a default argument is not
17928 // equivalent to any of the permitted forms.
17929 for (auto *Param : FnDecl->parameters()) {
17930 if (Param->hasDefaultArg()) {
17931 Diag(Param->getDefaultArgRange().getBegin(),
17932 diag::err_literal_operator_default_argument)
17933 << Param->getDefaultArgRange();
17934 break;
17935 }
17936 }
17937
17938 const IdentifierInfo *II = FnDecl->getDeclName().getCXXLiteralIdentifier();
17941 !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
17942 // C++23 [usrlit.suffix]p1:
17943 // Literal suffix identifiers that do not start with an underscore are
17944 // reserved for future standardization. Literal suffix identifiers that
17945 // contain a double underscore __ are reserved for use by C++
17946 // implementations.
17947 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
17948 << static_cast<int>(Status)
17950 }
17951
17952 return false;
17953}
17954
17956 Expr *LangStr,
17957 SourceLocation LBraceLoc) {
17958 StringLiteral *Lit = cast<StringLiteral>(LangStr);
17959 assert(Lit->isUnevaluated() && "Unexpected string literal kind");
17960
17961 StringRef Lang = Lit->getString();
17963 if (Lang == "C")
17965 else if (Lang == "C++")
17967 else {
17968 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
17969 << LangStr->getSourceRange();
17970 return nullptr;
17971 }
17972
17973 // FIXME: Add all the various semantics of linkage specifications
17974
17976 LangStr->getExprLoc(), Language,
17977 LBraceLoc.isValid());
17978
17979 /// C++ [module.unit]p7.2.3
17980 /// - Otherwise, if the declaration
17981 /// - ...
17982 /// - ...
17983 /// - appears within a linkage-specification,
17984 /// it is attached to the global module.
17985 ///
17986 /// If the declaration is already in global module fragment, we don't
17987 /// need to attach it again.
17988 if (getLangOpts().CPlusPlusModules && isCurrentModulePurview()) {
17989 Module *GlobalModule = PushImplicitGlobalModuleFragment(ExternLoc);
17990 D->setLocalOwningModule(GlobalModule);
17991 }
17992
17993 CurContext->addDecl(D);
17994 PushDeclContext(S, D);
17995 return D;
17996}
17997
17999 Decl *LinkageSpec,
18000 SourceLocation RBraceLoc) {
18001 if (RBraceLoc.isValid()) {
18002 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
18003 LSDecl->setRBraceLoc(RBraceLoc);
18004 }
18005
18006 // If the current module doesn't has Parent, it implies that the
18007 // LinkageSpec isn't in the module created by itself. So we don't
18008 // need to pop it.
18009 if (getLangOpts().CPlusPlusModules && getCurrentModule() &&
18010 getCurrentModule()->isImplicitGlobalModule() &&
18011 getCurrentModule()->Parent)
18012 PopImplicitGlobalModuleFragment();
18013
18015 return LinkageSpec;
18016}
18017
18019 const ParsedAttributesView &AttrList,
18020 SourceLocation SemiLoc) {
18021 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
18022 // Attribute declarations appertain to empty declaration so we handle
18023 // them here.
18024 ProcessDeclAttributeList(S, ED, AttrList);
18025
18026 CurContext->addDecl(ED);
18027 return ED;
18028}
18029
18031 SourceLocation StartLoc,
18032 SourceLocation Loc,
18033 const IdentifierInfo *Name) {
18034 bool Invalid = false;
18035 QualType ExDeclType = TInfo->getType();
18036
18037 // Arrays and functions decay.
18038 if (ExDeclType->isArrayType())
18039 ExDeclType = Context.getArrayDecayedType(ExDeclType);
18040 else if (ExDeclType->isFunctionType())
18041 ExDeclType = Context.getPointerType(ExDeclType);
18042
18043 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
18044 // The exception-declaration shall not denote a pointer or reference to an
18045 // incomplete type, other than [cv] void*.
18046 // N2844 forbids rvalue references.
18047 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
18048 Diag(Loc, diag::err_catch_rvalue_ref);
18049 Invalid = true;
18050 }
18051
18052 if (ExDeclType->isVariablyModifiedType()) {
18053 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
18054 Invalid = true;
18055 }
18056
18057 QualType BaseType = ExDeclType;
18058 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
18059 unsigned DK = diag::err_catch_incomplete;
18060 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
18061 BaseType = Ptr->getPointeeType();
18062 Mode = 1;
18063 DK = diag::err_catch_incomplete_ptr;
18064 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
18065 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
18066 BaseType = Ref->getPointeeType();
18067 Mode = 2;
18068 DK = diag::err_catch_incomplete_ref;
18069 }
18070 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
18071 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
18072 Invalid = true;
18073
18074 if (!Invalid && BaseType.isWebAssemblyReferenceType()) {
18075 Diag(Loc, diag::err_wasm_reftype_tc) << 1;
18076 Invalid = true;
18077 }
18078
18079 // Reject catch types that need a cross-AS conversion.
18080 // cause runtimes don't yet support cross-address-
18081 // space conversions
18082 if (Mode == 1) {
18083 if (ExDeclType.getAddressSpace() != LangAS::Default ||
18084 BaseType.getAddressSpace() != LangAS::Default) {
18085 Diag(Loc, diag::err_throw_or_catch_address_space_qualified_ptr)
18086 << /*IsCatch=*/1 << /*IsRef=*/0 << ExDeclType;
18087 Invalid = true;
18088 }
18089 } else if (Mode == 2) {
18090 if (const PointerType *PT = BaseType->getAs<PointerType>();
18091 PT && (BaseType.getAddressSpace() != LangAS::Default ||
18092 PT->getPointeeType().getAddressSpace() != LangAS::Default)) {
18093 Diag(Loc, diag::err_throw_or_catch_address_space_qualified_ptr)
18094 << /*IsCatch=*/1 << /*IsRef=*/0 << ExDeclType;
18095 Invalid = true;
18096 } else if (BaseType.getAddressSpace() != LangAS::Default) {
18097 Diag(Loc, diag::err_throw_or_catch_address_space_qualified_ptr)
18098 << /*IsCatch=*/1 << /*IsRef=*/1 << ExDeclType;
18099 Invalid = true;
18100 }
18101 }
18102
18103 if (!Invalid && Mode != 1 && BaseType->isSizelessType()) {
18104 Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType;
18105 Invalid = true;
18106 }
18107
18108 if (!Invalid && !ExDeclType->isDependentType() &&
18109 RequireNonAbstractType(Loc, ExDeclType,
18110 diag::err_abstract_type_in_decl,
18112 Invalid = true;
18113
18114 // Only the non-fragile NeXT runtime currently supports C++ catches
18115 // of ObjC types, and no runtime supports catching ObjC types by value.
18116 if (!Invalid && getLangOpts().ObjC) {
18117 QualType T = ExDeclType;
18118 if (const ReferenceType *RT = T->getAs<ReferenceType>())
18119 T = RT->getPointeeType();
18120
18121 if (T->isObjCObjectType()) {
18122 Diag(Loc, diag::err_objc_object_catch);
18123 Invalid = true;
18124 } else if (T->isObjCObjectPointerType()) {
18125 // FIXME: should this be a test for macosx-fragile specifically?
18127 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
18128 }
18129 }
18130
18131 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
18132 ExDeclType, TInfo, SC_None);
18133 ExDecl->setExceptionVariable(true);
18134
18135 // In ARC, infer 'retaining' for variables of retainable type.
18136 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(ExDecl))
18137 Invalid = true;
18138
18139 if (!Invalid && !ExDeclType->isDependentType()) {
18140 if (auto *ClassDecl = ExDeclType->getAsCXXRecordDecl()) {
18141 // Insulate this from anything else we might currently be parsing.
18144
18145 // C++ [except.handle]p16:
18146 // The object declared in an exception-declaration or, if the
18147 // exception-declaration does not specify a name, a temporary (12.2) is
18148 // copy-initialized (8.5) from the exception object. [...]
18149 // The object is destroyed when the handler exits, after the destruction
18150 // of any automatic objects initialized within the handler.
18151 //
18152 // We just pretend to initialize the object with itself, then make sure
18153 // it can be destroyed later.
18154 QualType initType = Context.getExceptionObjectType(ExDeclType);
18155
18156 InitializedEntity entity =
18158 InitializationKind initKind =
18160
18161 Expr *opaqueValue =
18162 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
18163 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
18164 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
18165 if (result.isInvalid())
18166 Invalid = true;
18167 else {
18168 // If the constructor used was non-trivial, set this as the
18169 // "initializer".
18170 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
18171 if (!construct->getConstructor()->isTrivial()) {
18172 Expr *init = MaybeCreateExprWithCleanups(construct);
18173 ExDecl->setInit(init);
18174 }
18175
18176 // And make sure it's destructable.
18177 FinalizeVarWithDestructor(ExDecl, ClassDecl);
18178 }
18179 }
18180 }
18181
18182 if (Invalid)
18183 ExDecl->setInvalidDecl();
18184
18185 return ExDecl;
18186}
18187
18190 bool Invalid = D.isInvalidType();
18191
18192 // Check for unexpanded parameter packs.
18195 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
18196 D.getIdentifierLoc());
18197 Invalid = true;
18198 }
18199
18200 const IdentifierInfo *II = D.getIdentifier();
18201 if (NamedDecl *PrevDecl =
18204 // The scope should be freshly made just for us. There is just no way
18205 // it contains any previous declaration, except for function parameters in
18206 // a function-try-block's catch statement.
18207 assert(!S->isDeclScope(PrevDecl));
18208 if (isDeclInScope(PrevDecl, CurContext, S)) {
18209 Diag(D.getIdentifierLoc(), diag::err_redefinition)
18210 << D.getIdentifier();
18211 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
18212 Invalid = true;
18213 } else if (PrevDecl->isTemplateParameter())
18214 // Maybe we will complain about the shadowed template parameter.
18216 }
18217
18218 if (D.getCXXScopeSpec().isSet() && !Invalid) {
18219 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
18220 << D.getCXXScopeSpec().getRange();
18221 Invalid = true;
18222 }
18223
18225 S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
18226 if (Invalid)
18227 ExDecl->setInvalidDecl();
18228
18229 // Add the exception declaration into this scope.
18230 if (II)
18231 PushOnScopeChains(ExDecl, S);
18232 else
18233 CurContext->addDecl(ExDecl);
18234
18235 ProcessDeclAttributes(S, ExDecl, D);
18236 return ExDecl;
18237}
18238
18240 Expr *AssertExpr,
18241 Expr *AssertMessageExpr,
18242 SourceLocation RParenLoc) {
18244 return nullptr;
18245
18246 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
18247 AssertMessageExpr, RParenLoc, false);
18248}
18249
18250static void WriteCharTypePrefix(BuiltinType::Kind BTK, llvm::raw_ostream &OS) {
18251 switch (BTK) {
18252 case BuiltinType::Char_S:
18253 case BuiltinType::Char_U:
18254 break;
18255 case BuiltinType::Char8:
18256 OS << "u8";
18257 break;
18258 case BuiltinType::Char16:
18259 OS << 'u';
18260 break;
18261 case BuiltinType::Char32:
18262 OS << 'U';
18263 break;
18264 case BuiltinType::WChar_S:
18265 case BuiltinType::WChar_U:
18266 OS << 'L';
18267 break;
18268 default:
18269 llvm_unreachable("Non-character type");
18270 }
18271}
18272
18273/// Convert character's value, interpreted as a code unit, to a string.
18274/// The value needs to be zero-extended to 32-bits.
18275/// FIXME: This assumes Unicode literal encodings
18277 unsigned TyWidth,
18278 SmallVectorImpl<char> &Str) {
18279 char Arr[UNI_MAX_UTF8_BYTES_PER_CODE_POINT];
18280 char *Ptr = Arr;
18281 BuiltinType::Kind K = BTy->getKind();
18282 llvm::raw_svector_ostream OS(Str);
18283
18284 // This should catch Char_S, Char_U, Char8, and use of escaped characters in
18285 // other types.
18286 if (K == BuiltinType::Char_S || K == BuiltinType::Char_U ||
18287 K == BuiltinType::Char8 || Value <= 0x7F) {
18288 StringRef Escaped = escapeCStyle<EscapeChar::Single>(Value);
18289 if (!Escaped.empty())
18290 EscapeStringForDiagnostic(Escaped, Str);
18291 else
18292 OS << static_cast<char>(Value);
18293 return;
18294 }
18295
18296 switch (K) {
18297 case BuiltinType::Char16:
18298 case BuiltinType::Char32:
18299 case BuiltinType::WChar_S:
18300 case BuiltinType::WChar_U: {
18301 if (llvm::ConvertCodePointToUTF8(Value, Ptr))
18302 EscapeStringForDiagnostic(StringRef(Arr, Ptr - Arr), Str);
18303 else
18304 OS << "\\x"
18305 << llvm::format_hex_no_prefix(Value, TyWidth / 4, /*Upper=*/true);
18306 break;
18307 }
18308 default:
18309 llvm_unreachable("Non-character type is passed");
18310 }
18311}
18312
18313/// Convert \V to a string we can present to the user in a diagnostic
18314/// \T is the type of the expression that has been evaluated into \V
18317 ASTContext &Context) {
18318 if (!V.hasValue())
18319 return false;
18320
18321 switch (V.getKind()) {
18323 if (T->isBooleanType()) {
18324 // Bools are reduced to ints during evaluation, but for
18325 // diagnostic purposes we want to print them as
18326 // true or false.
18327 int64_t BoolValue = V.getInt().getExtValue();
18328 assert((BoolValue == 0 || BoolValue == 1) &&
18329 "Bool type, but value is not 0 or 1");
18330 llvm::raw_svector_ostream OS(Str);
18331 OS << (BoolValue ? "true" : "false");
18332 } else {
18333 llvm::raw_svector_ostream OS(Str);
18334 // Same is true for chars.
18335 // We want to print the character representation for textual types
18336 const auto *BTy = T->getAs<BuiltinType>();
18337 if (BTy) {
18338 switch (BTy->getKind()) {
18339 case BuiltinType::Char_S:
18340 case BuiltinType::Char_U:
18341 case BuiltinType::Char8:
18342 case BuiltinType::Char16:
18343 case BuiltinType::Char32:
18344 case BuiltinType::WChar_S:
18345 case BuiltinType::WChar_U: {
18346 unsigned TyWidth = Context.getIntWidth(T);
18347 assert(8 <= TyWidth && TyWidth <= 32 && "Unexpected integer width");
18348 uint32_t CodeUnit = static_cast<uint32_t>(V.getInt().getZExtValue());
18349 WriteCharTypePrefix(BTy->getKind(), OS);
18350 OS << '\'';
18351 WriteCharValueForDiagnostic(CodeUnit, BTy, TyWidth, Str);
18352 OS << "' (0x"
18353 << llvm::format_hex_no_prefix(CodeUnit, /*Width=*/2,
18354 /*Upper=*/true)
18355 << ", " << V.getInt() << ')';
18356 return true;
18357 }
18358 default:
18359 break;
18360 }
18361 }
18362 V.getInt().toString(Str);
18363 }
18364
18365 break;
18366
18368 V.getFloat().toString(Str);
18369 break;
18370
18372 if (V.isNullPointer()) {
18373 llvm::raw_svector_ostream OS(Str);
18374 OS << "nullptr";
18375 } else
18376 return false;
18377 break;
18378
18380 llvm::raw_svector_ostream OS(Str);
18381 OS << '(';
18382 V.getComplexFloatReal().toString(Str);
18383 OS << " + ";
18384 V.getComplexFloatImag().toString(Str);
18385 OS << "i)";
18386 } break;
18387
18389 llvm::raw_svector_ostream OS(Str);
18390 OS << '(';
18391 V.getComplexIntReal().toString(Str);
18392 OS << " + ";
18393 V.getComplexIntImag().toString(Str);
18394 OS << "i)";
18395 } break;
18396
18397 default:
18398 return false;
18399 }
18400
18401 return true;
18402}
18403
18404/// Some Expression types are not useful to print notes about,
18405/// e.g. literals and values that have already been expanded
18406/// before such as int-valued template parameters.
18407static bool UsefulToPrintExpr(const Expr *E) {
18408 E = E->IgnoreParenImpCasts();
18409 // Literals are pretty easy for humans to understand.
18412 return false;
18413
18414 // These have been substituted from template parameters
18415 // and appear as literals in the static assert error.
18417 return false;
18418
18419 // -5 is also simple to understand.
18420 if (const auto *UnaryOp = dyn_cast<UnaryOperator>(E))
18421 return UsefulToPrintExpr(UnaryOp->getSubExpr());
18422
18423 // Only print nested arithmetic operators.
18424 if (const auto *BO = dyn_cast<BinaryOperator>(E))
18425 return (BO->isShiftOp() || BO->isAdditiveOp() || BO->isMultiplicativeOp() ||
18426 BO->isBitwiseOp());
18427
18428 return true;
18429}
18430
18432 // FIXME: Should we also ignore explicit casts?
18433 E = E->IgnoreParenImpCasts();
18434 if (const auto *Op = dyn_cast<BinaryOperator>(E);
18435 Op && Op->getOpcode() != BO_LOr) {
18436 const Expr *LHS = Op->getLHS()->IgnoreParenImpCasts();
18437 const Expr *RHS = Op->getRHS()->IgnoreParenImpCasts();
18438
18439 // Ignore comparisons of boolean expressions with a boolean literal.
18440 if ((isa<CXXBoolLiteralExpr>(LHS) && RHS->getType()->isBooleanType()) ||
18441 (isa<CXXBoolLiteralExpr>(RHS) && LHS->getType()->isBooleanType()))
18442 return;
18443
18444 // Don't print obvious expressions.
18445 if (!UsefulToPrintExpr(LHS) && !UsefulToPrintExpr(RHS))
18446 return;
18447
18448 struct {
18449 const clang::Expr *Cond;
18451 SmallString<12> ValueString;
18452 bool Print;
18453 } DiagSides[2] = {{LHS, Expr::EvalResult(), {}, false},
18454 {RHS, Expr::EvalResult(), {}, false}};
18455 for (auto &DiagSide : DiagSides) {
18456 const Expr *Side = DiagSide.Cond;
18457
18458 Side->EvaluateAsRValue(DiagSide.Result, Context, true);
18459
18460 DiagSide.Print = ConvertAPValueToString(
18461 DiagSide.Result.Val, Side->getType(), DiagSide.ValueString, Context);
18462 }
18463 if (DiagSides[0].Print && DiagSides[1].Print) {
18464 Diag(Op->getExprLoc(), diag::note_expr_evaluates_to)
18465 << DiagSides[0].ValueString << Op->getOpcodeStr()
18466 << DiagSides[1].ValueString << Op->getSourceRange();
18467 }
18468 } else if (const auto *RE = dyn_cast<RequiresExpr>(E)) {
18470 } else {
18472 }
18473}
18474
18475template <typename ResultType>
18476static bool EvaluateAsStringImpl(Sema &SemaRef, Expr *Message,
18477 ResultType &Result, ASTContext &Ctx,
18479 bool ErrorOnInvalidMessage) {
18480
18481 assert(Message);
18482 assert(!Message->isTypeDependent() && !Message->isValueDependent() &&
18483 "can't evaluate a dependant static assert message");
18484
18485 if (const auto *SL = dyn_cast<StringLiteral>(Message)) {
18486 assert(SL->isUnevaluated() && "expected an unevaluated string");
18487 if constexpr (std::is_same_v<APValue, ResultType>) {
18488 Result =
18489 APValue(APValue::UninitArray{}, SL->getLength(), SL->getLength());
18490 const ConstantArrayType *CAT =
18491 SemaRef.getASTContext().getAsConstantArrayType(SL->getType());
18492 assert(CAT && "string literal isn't an array");
18493 QualType CharType = CAT->getElementType();
18494 llvm::APSInt Value(SemaRef.getASTContext().getTypeSize(CharType),
18495 CharType->isUnsignedIntegerType());
18496 for (unsigned I = 0; I < SL->getLength(); I++) {
18497 Value = SL->getCodeUnit(I);
18498 Result.getArrayInitializedElt(I) = APValue(Value);
18499 }
18500 } else {
18501 Result.assign(SL->getString().begin(), SL->getString().end());
18502 }
18503 return true;
18504 }
18505
18506 SourceLocation Loc = Message->getBeginLoc();
18507 QualType T = Message->getType().getNonReferenceType();
18508 auto *RD = T->getAsCXXRecordDecl();
18509 if (!RD) {
18510 SemaRef.Diag(Loc, diag::err_user_defined_msg_invalid) << EvalContext;
18511 return false;
18512 }
18513
18514 auto FindMember = [&](StringRef Member) -> std::optional<LookupResult> {
18516 LookupResult MemberLookup(SemaRef, DN, Loc, Sema::LookupMemberName);
18517 SemaRef.LookupQualifiedName(MemberLookup, RD);
18518 if (MemberLookup.empty())
18519 return std::nullopt;
18520 return std::move(MemberLookup);
18521 };
18522
18523 std::optional<LookupResult> SizeMember = FindMember("size");
18524 std::optional<LookupResult> DataMember = FindMember("data");
18525 if (!SizeMember || !DataMember) {
18526 SemaRef.Diag(Loc, diag::err_user_defined_msg_missing_member_function)
18527 << EvalContext
18528 << ((!SizeMember && !DataMember) ? 2
18529 : !SizeMember ? 0
18530 : 1);
18531 return false;
18532 }
18533
18534 auto BuildExpr = [&](LookupResult &LR) {
18536 Message, Message->getType(), Message->getBeginLoc(), false,
18537 CXXScopeSpec(), SourceLocation(), nullptr, LR, nullptr, nullptr);
18538 if (Res.isInvalid())
18539 return ExprError();
18540 Res = SemaRef.BuildCallExpr(nullptr, Res.get(), Loc, {}, Loc, nullptr,
18541 false, true);
18542 if (Res.isInvalid())
18543 return ExprError();
18544 if (Res.get()->isTypeDependent() || Res.get()->isValueDependent())
18545 return ExprError();
18546 return SemaRef.TemporaryMaterializationConversion(Res.get());
18547 };
18548
18549 ExprResult SizeE = BuildExpr(*SizeMember);
18550 ExprResult DataE = BuildExpr(*DataMember);
18551
18552 QualType SizeT = SemaRef.Context.getSizeType();
18553 QualType ConstCharPtr = SemaRef.Context.getPointerType(
18554 SemaRef.Context.getConstType(SemaRef.Context.CharTy));
18555
18556 ExprResult EvaluatedSize =
18557 SizeE.isInvalid()
18558 ? ExprError()
18561 if (EvaluatedSize.isInvalid()) {
18562 SemaRef.Diag(Loc, diag::err_user_defined_msg_invalid_mem_fn_ret_ty)
18563 << EvalContext << /*size*/ 0;
18564 return false;
18565 }
18566
18567 ExprResult EvaluatedData =
18568 DataE.isInvalid()
18569 ? ExprError()
18571 DataE.get(), ConstCharPtr, CCEKind::StaticAssertMessageData);
18572 if (EvaluatedData.isInvalid()) {
18573 SemaRef.Diag(Loc, diag::err_user_defined_msg_invalid_mem_fn_ret_ty)
18574 << EvalContext << /*data*/ 1;
18575 return false;
18576 }
18577
18578 if (!ErrorOnInvalidMessage &&
18579 SemaRef.Diags.isIgnored(diag::warn_user_defined_msg_constexpr, Loc))
18580 return true;
18581
18582 Expr::EvalResult Status;
18584 Status.Diag = &Notes;
18585 sema::EvalProxy SProxy(SemaRef);
18586 if (!Message->EvaluateCharRangeAsString(Result, EvaluatedSize.get(),
18587 EvaluatedData.get(), Ctx, SProxy,
18588 Status) ||
18589 !Notes.empty()) {
18590 SemaRef.Diag(Message->getBeginLoc(),
18591 ErrorOnInvalidMessage ? diag::err_user_defined_msg_constexpr
18592 : diag::warn_user_defined_msg_constexpr)
18593 << EvalContext;
18594 for (const auto &Note : Notes)
18595 SemaRef.Diag(Note.first, Note.second);
18596 return !ErrorOnInvalidMessage;
18597 }
18598 return true;
18599}
18600
18602 StringEvaluationContext EvalContext,
18603 bool ErrorOnInvalidMessage) {
18604 return EvaluateAsStringImpl(*this, Message, Result, Ctx, EvalContext,
18605 ErrorOnInvalidMessage);
18606}
18607
18608bool Sema::EvaluateAsString(Expr *Message, std::string &Result, ASTContext &Ctx,
18609 StringEvaluationContext EvalContext,
18610 bool ErrorOnInvalidMessage) {
18611 return EvaluateAsStringImpl(*this, Message, Result, Ctx, EvalContext,
18612 ErrorOnInvalidMessage);
18613}
18614
18616 Expr *AssertExpr, Expr *AssertMessage,
18617 SourceLocation RParenLoc,
18618 bool Failed) {
18619 assert(AssertExpr != nullptr && "Expected non-null condition");
18620 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
18621 (!AssertMessage || (!AssertMessage->isTypeDependent() &&
18622 !AssertMessage->isValueDependent())) &&
18623 !Failed) {
18624 // In a static_assert-declaration, the constant-expression shall be a
18625 // constant expression that can be contextually converted to bool.
18626 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
18627 if (Converted.isInvalid())
18628 Failed = true;
18629
18630 ExprResult FullAssertExpr =
18631 ActOnFinishFullExpr(Converted.get(), StaticAssertLoc,
18632 /*DiscardedValue*/ false,
18633 /*IsConstexpr*/ true);
18634 if (FullAssertExpr.isInvalid())
18635 Failed = true;
18636 else
18637 AssertExpr = FullAssertExpr.get();
18638
18639 llvm::APSInt Cond;
18640 Expr *BaseExpr = AssertExpr;
18642
18643 if (!getLangOpts().CPlusPlus) {
18644 // In C mode, allow folding as an extension for better compatibility with
18645 // C++ in terms of expressions like static_assert("test") or
18646 // static_assert(nullptr).
18647 FoldKind = AllowFoldKind::Allow;
18648 }
18649
18650 if (!Failed && VerifyIntegerConstantExpression(
18651 BaseExpr, &Cond,
18652 diag::err_static_assert_expression_is_not_constant,
18653 FoldKind).isInvalid())
18654 Failed = true;
18655
18656 // If the static_assert passes, only verify that
18657 // the message is grammatically valid without evaluating it.
18658 if (!Failed && AssertMessage && Cond.getBoolValue()) {
18659 std::string Str;
18660 EvaluateAsString(AssertMessage, Str, Context,
18662 /*ErrorOnInvalidMessage=*/false);
18663 }
18664
18665 // CWG2518
18666 // [dcl.pre]/p10 If [...] the expression is evaluated in the context of a
18667 // template definition, the declaration has no effect.
18668 bool InTemplateDefinition =
18669 getLangOpts().CPlusPlus && CurContext->isDependentContext();
18670
18671 if (!Failed && !Cond && !InTemplateDefinition) {
18672 SmallString<256> MsgBuffer;
18673 llvm::raw_svector_ostream Msg(MsgBuffer);
18674 bool HasMessage = AssertMessage;
18675 if (AssertMessage) {
18676 std::string Str;
18677 HasMessage = EvaluateAsString(AssertMessage, Str, Context,
18679 /*ErrorOnInvalidMessage=*/true) ||
18680 !Str.empty();
18681 Msg << Str;
18682 }
18683 Expr *InnerCond = nullptr;
18684 std::string InnerCondDescription;
18685 std::tie(InnerCond, InnerCondDescription) =
18686 findFailedBooleanCondition(Converted.get());
18687 if (const auto *ConceptIDExpr =
18688 dyn_cast_or_null<ConceptSpecializationExpr>(InnerCond)) {
18689 const ASTConstraintSatisfaction &Satisfaction =
18690 ConceptIDExpr->getSatisfaction();
18691 if (!Satisfaction.containsErrors() || Satisfaction.record_size()) {
18692 Diag(AssertExpr->getBeginLoc(), diag::err_static_assert_failed)
18693 << !HasMessage << Msg.str() << AssertExpr->getSourceRange();
18694 // Drill down into concept specialization expressions to see why they
18695 // weren't satisfied.
18696 DiagnoseUnsatisfiedConstraint(ConceptIDExpr);
18697 }
18698 } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond) &&
18699 !isa<IntegerLiteral>(InnerCond)) {
18700 Diag(InnerCond->getBeginLoc(),
18701 diag::err_static_assert_requirement_failed)
18702 << InnerCondDescription << !HasMessage << Msg.str()
18703 << InnerCond->getSourceRange();
18704 DiagnoseStaticAssertDetails(InnerCond);
18705 } else {
18706 Diag(AssertExpr->getBeginLoc(), diag::err_static_assert_failed)
18707 << !HasMessage << Msg.str() << AssertExpr->getSourceRange();
18709 }
18710 Failed = true;
18711 }
18712 } else {
18713 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
18714 /*DiscardedValue*/false,
18715 /*IsConstexpr*/true);
18716 if (FullAssertExpr.isInvalid())
18717 Failed = true;
18718 else
18719 AssertExpr = FullAssertExpr.get();
18720 }
18721
18723 AssertExpr, AssertMessage, RParenLoc,
18724 Failed);
18725
18726 CurContext->addDecl(Decl);
18727 return Decl;
18728}
18729
18731 if (const auto *PIT = dyn_cast<PackIndexingType>(T))
18732 return PIT->getPattern();
18733 return T;
18734}
18735
18736static const TemplateSpecializationType *
18739 if (const auto *ICNT = dyn_cast<InjectedClassNameType>(T))
18740 T = ICNT->getDecl()->getCanonicalTemplateSpecializationType(Context);
18741
18742 const auto *TST = dyn_cast<TemplateSpecializationType>(T);
18743 if (!TST)
18744 return nullptr;
18745
18746 TemplateDecl *TD = TST->getTemplateName().getAsTemplateDecl();
18747 if (!TD || isa<ClassTemplateDecl>(TD))
18748 return TST;
18749 return nullptr;
18750}
18751
18753 NestedNameSpecifierLoc NNSLoc) {
18754 for (TypeLoc TL = NNSLoc.getAsTypeLoc(); TL;
18755 TL = TL.getPrefix().getAsTypeLoc()) {
18756 if (TL.getTypeLocClass() != TypeLoc::PackIndexing)
18757 continue;
18758
18759 Diag(Loc, diag::err_pack_indexing_in_friend) << TL.getSourceRange();
18760 return true;
18761 }
18762 return false;
18763}
18764
18766 NestedNameSpecifier NNS) {
18767 QualType T(NNS.getAsType(), 0);
18768 if (const auto *TST =
18769 dyn_cast<TemplateSpecializationType>(IgnorePackIndexing(T))) {
18770 if (isa_and_nonnull<TypeAliasTemplateDecl>(
18771 TST->getTemplateName().getAsTemplateDecl())) {
18772 S.Diag(Loc, diag::err_dependent_friend_not_member_of_template_spec)
18773 << NNS;
18774 return;
18775 }
18776 }
18777
18778 if (NNS.getAsRecordDecl()) {
18779 S.Diag(Loc, diag::err_dependent_friend_not_member_of_template_spec) << NNS;
18780 } else {
18781 S.Diag(Loc, diag::err_dependent_friend_not_member);
18782 }
18783}
18784
18788 bool IsInstantiation) {
18790 if (!NNS.isDependent() && !IsInstantiation)
18791 return false;
18792
18793 assert(NNS.getKind() == NestedNameSpecifier::Kind::Type &&
18794 "nested-name-specifier of dependent friend must be a type");
18795
18796 QualType T(NNS.getAsType(), 0);
18797 if (DiagnosePackIndexingInFriendNNS(Loc, NNSLoc))
18798 return true;
18799
18800 const TemplateSpecializationType *TST =
18802 if (!TST) {
18803 DiagnoseDependentFriendNotMember(*this, Loc, NNS);
18804 return true;
18805 }
18806
18807 if (TPLs.empty())
18808 return false;
18809
18810 SmallVector<NamedDecl *, 4> UndeducedParameters;
18811 for (TemplateParameterList *Params : TPLs) {
18812 llvm::SmallBitVector UsedParameters(Params->size());
18813 MarkUsedTemplateParameters(TST->template_arguments(),
18814 /*OnlyDeduced=*/true, Params->getDepth(),
18815 UsedParameters);
18816
18817 for (unsigned I = 0, N = UsedParameters.size(); I != N; ++I)
18818 if (!UsedParameters[I])
18819 UndeducedParameters.push_back(Params->getParam(I));
18820 }
18821
18822 if (UndeducedParameters.empty())
18823 return false;
18824
18825 Diag(Loc, diag::err_dependent_friend_undeduced_params)
18826 << (UndeducedParameters.size() > 1) << QualType(TST, 0);
18827
18828 for (NamedDecl *Param : UndeducedParameters) {
18829 if (Param->getDeclName())
18830 Diag(Param->getLocation(), diag::note_non_deducible_parameter)
18831 << Param->getDeclName();
18832 else
18833 Diag(Param->getLocation(), diag::note_non_deducible_parameter)
18834 << "(anonymous)";
18835 }
18836
18837 return true;
18838}
18839
18841 Scope *S, SourceLocation FriendLoc, unsigned TagSpec, SourceLocation TagLoc,
18842 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
18843 SourceLocation EllipsisLoc, const ParsedAttributesView &Attr,
18844 MultiTemplateParamsArg TempParamLists, TemplateIdAnnotation *TemplateId) {
18846
18847 bool IsMemberSpecialization = false;
18848 bool Invalid = false;
18849
18850 TemplateParameterList *TemplateParams =
18851 MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS, TemplateId,
18852 TempParamLists, /*friend*/ true,
18853 IsMemberSpecialization, Invalid);
18854 if (TemplateId) {
18855 if (Invalid)
18856 return true;
18857
18858 if (TemplateParams) {
18859 Diag(NameLoc, diag::err_not_class_template_specialization) << 0;
18860 return true;
18861 }
18862 }
18863
18864 if (TemplateParams) {
18865 if (TemplateParams->size() > 0) {
18866 if (Invalid)
18867 return true;
18868
18869 if (SS.isEmpty() || !SS.getScopeRep().isDependent()) {
18871 S, TagSpec, TagUseKind::Friend, TagLoc, SS, Name, NameLoc, Attr,
18872 TemplateParams, AS_public, /*ModulePrivateLoc=*/SourceLocation(),
18873 FriendLoc, TempParamLists.size() - 1, TempParamLists.data(),
18874 IsMemberSpecialization);
18875 return Result.get();
18876 }
18877 } else {
18878 // The "template<>" header is extraneous.
18879 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
18880 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
18881 }
18882 }
18883
18884 if (Invalid)
18885 return true;
18886
18887 bool IsAllExplicitSpecializations =
18888 llvm::all_of(TempParamLists, [](const TemplateParameterList *List) {
18889 return List->size() == 0;
18890 });
18891
18892 // FIXME: don't ignore attributes.
18893
18894 // If it's explicit specializations all the way down, just forget
18895 // about the template header and build an appropriate non-templated
18896 // friend. TODO: for source fidelity, remember the headers.
18898 if (!TemplateId && IsAllExplicitSpecializations) {
18899 if (SS.isEmpty()) {
18900 bool Owned = false;
18901 bool IsDependent = false;
18902 return ActOnTag(S, TagSpec, TagUseKind::Friend, TagLoc, SS, Name, NameLoc,
18903 Attr, AS_public,
18904 /*ModulePrivateLoc=*/SourceLocation(),
18905 MultiTemplateParamsArg(), Owned, IsDependent,
18906 /*ScopedEnumKWLoc=*/SourceLocation(),
18907 /*ScopedEnumUsesClassTag=*/false,
18908 /*UnderlyingType=*/TypeResult(),
18909 /*IsTypeSpecifier=*/false,
18910 /*IsTemplateParamOrArg=*/false,
18911 /*OOK=*/OffsetOfKind::Outside);
18912 }
18913
18914 TypeSourceInfo *TSI = nullptr;
18917 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, *Name,
18918 NameLoc, &TSI, /*DeducedTSTContext=*/true);
18919 if (T.isNull())
18920 return true;
18921
18923 FriendLoc, EllipsisLoc);
18924 Friend->setAccess(AS_public);
18925 CurContext->addDecl(Friend);
18926 return Friend;
18927 }
18928
18929 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
18930
18931 ArrayRef<TemplateParameterList *> TPLs = TempParamLists;
18932 if (TemplateParams)
18933 TPLs = TPLs.drop_back();
18934 if (CheckDependentFriend(TagLoc, QualifierLoc, TPLs,
18935 /*IsInstantiation=*/false))
18936 return true;
18937
18938 TypeSourceInfo *TSI = nullptr;
18939 if (TemplateId) {
18940 ASTTemplateArgsPtr ParsedArgs(TemplateId->getTemplateArgs(),
18941 TemplateId->NumArgs);
18943 TagUseKind::Friend, static_cast<TypeSpecifierType>(TagSpec), TagLoc, SS,
18944 TemplateId->TemplateKWLoc, TemplateId->Template, NameLoc,
18945 TemplateId->LAngleLoc, ParsedArgs, TemplateId->RAngleLoc);
18946 if (ParsedType.isInvalid())
18947 return true;
18948
18949 GetTypeFromParser(ParsedType.get(), &TSI);
18950 } else {
18952 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
18953 TSI = Context.CreateTypeSourceInfo(T);
18954
18956 TL.setElaboratedKeywordLoc(TagLoc);
18957 TL.setQualifierLoc(QualifierLoc);
18958 TL.setNameLoc(NameLoc);
18959 }
18960
18962 collectUnexpandedParameterPacks(TSI->getTypeLoc(), Unexpanded);
18963 if (EllipsisLoc.isInvalid()) {
18965 return true;
18966 } else if (Unexpanded.empty()) {
18967 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
18968 << TSI->getTypeLoc().getSourceRange();
18969 return true;
18970 } else {
18971 // CWG 2917: a pack expanded by a friend-type-specifier cannot have been
18972 // introduced by the template-declaration containing that specifier.
18973 if (!TempParamLists.empty()) {
18974 unsigned FriendDeclDepth = TempParamLists.front()->getDepth();
18975 for (UnexpandedParameterPack &U : Unexpanded) {
18976 if (std::optional<std::pair<unsigned, unsigned>> DI =
18978 DI && DI->first >= FriendDeclDepth) {
18979 auto *ND = dyn_cast<NamedDecl *>(U.first);
18980 if (!ND)
18981 ND = cast<const TemplateTypeParmType *>(U.first)->getDecl();
18982 Diag(U.second, diag::friend_template_decl_malformed_pack_expansion)
18983 << ND->getDeclName()
18984 << SourceRange(TSI->getTypeLoc().getBeginLoc(), EllipsisLoc);
18985 return true;
18986 }
18987 }
18988 }
18989 }
18990
18992 if (TempParamLists.empty())
18993 Friend = FriendDecl::Create(Context, CurContext, NameLoc, TSI, FriendLoc,
18994 EllipsisLoc);
18995 else {
18996 if (CheckTemplateDeclScope(S, TempParamLists.back()))
18997 return true;
18998
19000 if (TemplateParams)
19001 FriendTemplate = Context.getDependentTemplateName(
19002 {SS.getScopeRep(), Name, /*HasTemplateKeyword=*/false});
19003 Friend =
19004 FriendTemplateDecl::Create(Context, CurContext, NameLoc, TSI, FriendLoc,
19005 TempParamLists, EllipsisLoc, FriendTemplate);
19006 }
19007
19008 Friend->setAccess(AS_public);
19009 CurContext->addDecl(Friend);
19010
19011 return Friend;
19012}
19013
19015 MultiTemplateParamsArg TempParams,
19016 SourceLocation EllipsisLoc) {
19017 SourceLocation Loc = DS.getBeginLoc();
19018 SourceLocation FriendLoc = DS.getFriendSpecLoc();
19019
19020 assert(DS.isFriendSpecified());
19022
19023 // C++ [class.friend]p3:
19024 // A friend declaration that does not declare a function shall have one of
19025 // the following forms:
19026 // friend elaborated-type-specifier ;
19027 // friend simple-type-specifier ;
19028 // friend typename-specifier ;
19029 //
19030 // If the friend keyword isn't first, or if the declarations has any type
19031 // qualifiers, then the declaration doesn't have that form.
19033 Diag(FriendLoc, diag::err_friend_not_first_in_declaration);
19034 if (DS.getTypeQualifiers()) {
19036 Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
19038 Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
19040 Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
19042 Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
19044 Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
19045 }
19046
19047 // Try to convert the decl specifier to a type. This works for
19048 // friend templates because ActOnTag never produces a ClassTemplateDecl
19049 // for a TagUseKind::Friend.
19050 Declarator TheDeclarator(DS, ParsedAttributesView::none(),
19052 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator);
19053 QualType T = TSI->getType();
19054 if (TheDeclarator.isInvalidType())
19055 return nullptr;
19056
19057 // If '...' is present, the type must contain an unexpanded parameter
19058 // pack, and vice versa.
19059 bool Invalid = false;
19060 if (EllipsisLoc.isInvalid() &&
19062 return nullptr;
19063 if (EllipsisLoc.isValid() &&
19065 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
19066 << TSI->getTypeLoc().getSourceRange();
19067 Invalid = true;
19068 }
19069
19070 if (!T->isElaboratedTypeSpecifier()) {
19071 if (TempParams.size()) {
19072 // C++23 [dcl.pre]p5:
19073 // In a simple-declaration, the optional init-declarator-list can be
19074 // omitted only when declaring a class or enumeration, that is, when
19075 // the decl-specifier-seq contains either a class-specifier, an
19076 // elaborated-type-specifier with a class-key, or an enum-specifier.
19077 //
19078 // The declaration of a template-declaration or explicit-specialization
19079 // is never a member-declaration, so this must be a simple-declaration
19080 // with no init-declarator-list. Therefore, this is ill-formed.
19081 Diag(Loc, diag::err_tagless_friend_type_template) << DS.getSourceRange();
19082 return nullptr;
19083 } else if (const RecordDecl *RD = T->getAsRecordDecl()) {
19084 SmallString<16> InsertionText(" ");
19085 InsertionText += RD->getKindName();
19086
19088 ? diag::warn_cxx98_compat_unelaborated_friend_type
19089 : diag::ext_unelaborated_friend_type)
19090 << (unsigned)RD->getTagKind() << T
19092 InsertionText);
19093 } else {
19094 DiagCompat(FriendLoc, diag_compat::nonclass_type_friend)
19095 << T << DS.getSourceRange();
19096 }
19097 }
19098
19099 // C++98 [class.friend]p1: A friend of a class is a function
19100 // or class that is not a member of the class . . .
19101 // This is fixed in DR77, which just barely didn't make the C++03
19102 // deadline. It's also a very silly restriction that seriously
19103 // affects inner classes and which nobody else seems to implement;
19104 // thus we never diagnose it, not even in -pedantic.
19105 //
19106 // But note that we could warn about it: it's always useless to
19107 // friend one of your own members (it's not, however, worthless to
19108 // friend a member of an arbitrary specialization of your template).
19109
19110 Decl *D;
19111 if (!TempParams.empty()) {
19112 if (CheckTemplateDeclScope(S, TempParams.back()))
19113 return nullptr;
19114
19115 // TODO: Support variadic friend template decls?
19116 D = FriendTemplateDecl::Create(Context, CurContext, Loc, TSI, FriendLoc,
19117 TempParams, EllipsisLoc);
19118 } else
19120 TSI, FriendLoc, EllipsisLoc);
19121
19122 if (!D)
19123 return nullptr;
19124
19125 D->setAccess(AS_public);
19126 CurContext->addDecl(D);
19127
19128 if (Invalid)
19129 D->setInvalidDecl();
19130
19131 return D;
19132}
19133
19135 MultiTemplateParamsArg TemplateParams) {
19136 const DeclSpec &DS = D.getDeclSpec();
19137
19138 assert(DS.isFriendSpecified());
19140
19143
19144 // C++ [class.friend]p1
19145 // A friend of a class is a function or class....
19146 // Note that this sees through typedefs, which is intended.
19147 // It *doesn't* see through dependent types, which is correct
19148 // according to [temp.arg.type]p3:
19149 // If a declaration acquires a function type through a
19150 // type dependent on a template-parameter and this causes
19151 // a declaration that does not use the syntactic form of a
19152 // function declarator to have a function type, the program
19153 // is ill-formed.
19154 if (!TInfo->getType()->isFunctionType()) {
19155 Diag(Loc, diag::err_unexpected_friend);
19156
19157 // It might be worthwhile to try to recover by creating an
19158 // appropriate declaration.
19159 return nullptr;
19160 }
19161
19162 // C++ [namespace.memdef]p3
19163 // - If a friend declaration in a non-local class first declares a
19164 // class or function, the friend class or function is a member
19165 // of the innermost enclosing namespace.
19166 // - The name of the friend is not found by simple name lookup
19167 // until a matching declaration is provided in that namespace
19168 // scope (either before or after the class declaration granting
19169 // friendship).
19170 // - If a friend function is called, its name may be found by the
19171 // name lookup that considers functions from namespaces and
19172 // classes associated with the types of the function arguments.
19173 // - When looking for a prior declaration of a class or a function
19174 // declared as a friend, scopes outside the innermost enclosing
19175 // namespace scope are not considered.
19176
19177 CXXScopeSpec &SS = D.getCXXScopeSpec();
19179 assert(NameInfo.getName());
19180
19182 NameInfo.getLoc(), SS.getWithLocInContext(Context)))
19183 return nullptr;
19184
19185 // Check for unexpanded parameter packs.
19189 return nullptr;
19190
19191 bool isTemplateId = D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
19192
19193 if (D.isFunctionDefinition() && SS.isNotEmpty() && !isTemplateId) {
19194 auto Kind = SS.getScopeRep().getKind();
19195 bool IsNamespaceOrGlobal = Kind == NestedNameSpecifier::Kind::Global ||
19197 if (IsNamespaceOrGlobal) {
19198 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
19199 << SS.getScopeRep();
19200 SS.clear();
19201 }
19202 }
19203
19204 // The context we found the declaration in, or in which we should
19205 // create the declaration.
19206 DeclContext *DC;
19207 Scope *DCScope = S;
19208 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
19210
19211 // There are five cases here.
19212 // - There's no scope specifier and we're in a local class. Only look
19213 // for functions declared in the immediately-enclosing block scope.
19214 // We recover from invalid scope qualifiers as if they just weren't there.
19215 FunctionDecl *FunctionContainingLocalClass = nullptr;
19216 if ((SS.isInvalid() || !SS.isSet()) &&
19217 (FunctionContainingLocalClass =
19218 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
19219 // C++11 [class.friend]p11:
19220 // If a friend declaration appears in a local class and the name
19221 // specified is an unqualified name, a prior declaration is
19222 // looked up without considering scopes that are outside the
19223 // innermost enclosing non-class scope. For a friend function
19224 // declaration, if there is no prior declaration, the program is
19225 // ill-formed.
19226
19227 // Find the innermost enclosing non-class scope. This is the block
19228 // scope containing the local class definition (or for a nested class,
19229 // the outer local class).
19230 DCScope = S->getFnParent();
19231
19232 // Look up the function name in the scope.
19234 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
19235
19236 if (!Previous.empty()) {
19237 // All possible previous declarations must have the same context:
19238 // either they were declared at block scope or they are members of
19239 // one of the enclosing local classes.
19240 DC = Previous.getRepresentativeDecl()->getDeclContext();
19241 } else {
19242 // This is ill-formed, but provide the context that we would have
19243 // declared the function in, if we were permitted to, for error recovery.
19244 DC = FunctionContainingLocalClass;
19245 }
19247
19248 // - There's no scope specifier, in which case we just go to the
19249 // appropriate scope and look for a function or function template
19250 // there as appropriate.
19251 } else if (SS.isInvalid() || !SS.isSet()) {
19252 // C++11 [namespace.memdef]p3:
19253 // If the name in a friend declaration is neither qualified nor
19254 // a template-id and the declaration is a function or an
19255 // elaborated-type-specifier, the lookup to determine whether
19256 // the entity has been previously declared shall not consider
19257 // any scopes outside the innermost enclosing namespace.
19258
19259 // Find the appropriate context according to the above.
19260 DC = CurContext;
19261
19262 // Skip class contexts. If someone can cite chapter and verse
19263 // for this behavior, that would be nice --- it's what GCC and
19264 // EDG do, and it seems like a reasonable intent, but the spec
19265 // really only says that checks for unqualified existing
19266 // declarations should stop at the nearest enclosing namespace,
19267 // not that they should only consider the nearest enclosing
19268 // namespace.
19269 while (DC->isRecord())
19270 DC = DC->getParent();
19271
19272 DeclContext *LookupDC = DC->getNonTransparentContext();
19273 while (true) {
19274 LookupQualifiedName(Previous, LookupDC);
19275
19276 if (!Previous.empty()) {
19277 DC = LookupDC;
19278 break;
19279 }
19280
19281 if (isTemplateId) {
19282 if (isa<TranslationUnitDecl>(LookupDC)) break;
19283 } else {
19284 if (LookupDC->isFileContext()) break;
19285 }
19286 LookupDC = LookupDC->getParent();
19287 }
19288
19289 DCScope = getScopeForDeclContext(S, DC);
19290
19291 // - There's a non-dependent scope specifier, in which case we
19292 // compute it and do a previous lookup there for a function
19293 // or function template.
19294 } else if (!SS.getScopeRep().isDependent()) {
19295 DC = computeDeclContext(SS);
19296 if (!DC) return nullptr;
19297
19298 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
19299
19301
19302 // C++ [class.friend]p1: A friend of a class is a function or
19303 // class that is not a member of the class . . .
19304 if (DC->Equals(CurContext))
19307 diag::warn_cxx98_compat_friend_is_member :
19308 diag::err_friend_is_member);
19309
19310 // - There's a dependent scope specifier, in which case we use an
19311 // arbitrary context and wait for instantiation.
19312 } else {
19313 DC = CurContext;
19314 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
19315 }
19316
19317 if (!DC->isRecord()) {
19318 int DiagArg = -1;
19319 switch (D.getName().getKind()) {
19322 DiagArg = 0;
19323 break;
19325 DiagArg = 1;
19326 break;
19328 DiagArg = 2;
19329 break;
19331 DiagArg = 3;
19332 break;
19338 break;
19339 }
19340 // This implies that it has to be an operator or function.
19341 if (DiagArg >= 0) {
19342 Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
19343 return nullptr;
19344 }
19345 } else {
19346 CXXRecordDecl *RC = dyn_cast<CXXRecordDecl>(DC);
19347 if (RC->isLambda()) {
19348 Diag(NameInfo.getBeginLoc(), diag::err_friend_lambda_decl);
19349 }
19350 }
19351
19352 // FIXME: This is an egregious hack to cope with cases where the scope stack
19353 // does not contain the declaration context, i.e., in an out-of-line
19354 // definition of a class.
19355 Scope FakeDCScope(S, Scope::DeclScope, Diags);
19356 if (!DCScope) {
19357 FakeDCScope.setEntity(DC);
19358 DCScope = &FakeDCScope;
19359 }
19360
19361 bool AddToScope = true;
19362 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
19363 TemplateParams, AddToScope);
19364 if (!ND) return nullptr;
19365
19366 assert(ND->getLexicalDeclContext() == CurContext);
19367
19368 // If we performed typo correction, we might have added a scope specifier
19369 // and changed the decl context.
19370 DC = ND->getDeclContext();
19371
19372 // Add the function declaration to the appropriate lookup tables,
19373 // adjusting the redeclarations list as necessary. We don't
19374 // want to do this yet if the friending class is dependent.
19375 //
19376 // Also update the scope-based lookup if the target context's
19377 // lookup context is in lexical scope.
19378 if (!CurContext->isDependentContext()) {
19379 DC = DC->getRedeclContext();
19381 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
19382 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
19383 }
19384
19386
19387 if (ND->isInvalidDecl()) {
19390 Friend->setAccess(AS_public);
19391 Friend->setInvalidDecl();
19392 CurContext->addDecl(Friend);
19393 return ND;
19394 }
19395
19396 FunctionDecl *FD = ND->getAsFunction();
19397 assert(FD && "Expected a function declaration!");
19398
19400 if (!TPLs.empty() && SS.isValid() && CheckTemplateDeclScope(S, TPLs.back()))
19401 return nullptr;
19402
19404 if (!TPLs.empty() && SS.isValid())
19405 Friend =
19407 ND, DS.getFriendSpecLoc(), TPLs);
19408 else
19410 DS.getFriendSpecLoc());
19411
19412 Friend->setAccess(AS_public);
19413 CurContext->addDecl(Friend);
19414
19415 if (DC->isRecord())
19417
19418 if (!TemplateParams.empty() && SS.isValid() &&
19421 /*IsInstantiation=*/false))
19422 return ND;
19423
19424 // C++ [class.friend]p6:
19425 // A function may be defined in a friend declaration of a class if and
19426 // only if the class is a non-local class, and the function name is
19427 // unqualified.
19428 if (D.isFunctionDefinition()) {
19429 // Qualified friend function definition.
19430 if (SS.isNotEmpty()) {
19432 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
19433
19434 DB << SS.getScopeRep();
19435
19436 // Friend function defined in a local class.
19437 } else if (FunctionContainingLocalClass) {
19438 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
19439
19440 // Per [basic.pre]p4, a template-id is not a name. Therefore, if we have
19441 // a template-id, the function name is not unqualified because these is
19442 // no name. While the wording requires some reading in-between the
19443 // lines, GCC, MSVC, and EDG all consider a friend function
19444 // specialization definitions to be de facto explicit specialization
19445 // and diagnose them as such.
19446 } else if (isTemplateId) {
19447 Diag(NameInfo.getBeginLoc(), diag::err_friend_specialization_def);
19448 }
19449 }
19450
19451 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
19452 // default argument expression, that declaration shall be a definition
19453 // and shall be the only declaration of the function or function
19454 // template in the translation unit.
19456 // We can't look at FD->getPreviousDecl() because it may not have been set
19457 // if we're in a dependent context. If the function is known to be a
19458 // redeclaration, we will have narrowed Previous down to the right decl.
19459 if (D.isRedeclaration()) {
19460 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
19461 Diag(Previous.getRepresentativeDecl()->getLocation(),
19462 diag::note_previous_declaration);
19463 } else if (!D.isFunctionDefinition())
19464 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
19465 }
19466
19467 return ND;
19468}
19469
19471 StringLiteral *Message) {
19473
19474 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
19475 if (!Fn) {
19476 Diag(DelLoc, diag::err_deleted_non_function);
19477 return;
19478 }
19479
19480 // Deleted function does not have a body.
19481 Fn->setWillHaveBody(false);
19482
19483 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
19484 // Don't consider the implicit declaration we generate for explicit
19485 // specializations. FIXME: Do not generate these implicit declarations.
19486 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
19487 Prev->getPreviousDecl()) &&
19488 !Prev->isDefined()) {
19489 Diag(DelLoc, diag::err_deleted_decl_not_first);
19490 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
19491 Prev->isImplicit() ? diag::note_previous_implicit_declaration
19492 : diag::note_previous_declaration);
19493 // We can't recover from this; the declaration might have already
19494 // been used.
19495 Fn->setInvalidDecl();
19496 return;
19497 }
19498
19499 // To maintain the invariant that functions are only deleted on their first
19500 // declaration, mark the implicitly-instantiated declaration of the
19501 // explicitly-specialized function as deleted instead of marking the
19502 // instantiated redeclaration.
19503 Fn = Fn->getCanonicalDecl();
19504 }
19505
19506 // dllimport/dllexport cannot be deleted.
19507 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
19508 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
19509 Fn->setInvalidDecl();
19510 }
19511
19512 // C++11 [basic.start.main]p3:
19513 // A program that defines main as deleted [...] is ill-formed.
19514 if (Fn->isMain())
19515 Diag(DelLoc, diag::err_deleted_main);
19516
19517 // C++11 [dcl.fct.def.delete]p4:
19518 // A deleted function is implicitly inline.
19519 Fn->setImplicitlyInline();
19520 Fn->setDeletedAsWritten(true, Message);
19521}
19522
19524 if (!Dcl || Dcl->isInvalidDecl())
19525 return;
19526
19527 // Which kinds of functions can be defaulted in the current language mode.
19528 unsigned DefaultableKinds = diag::DefaultableFunctionKinds::Default;
19530 DefaultableKinds = diag::DefaultableFunctionKinds::Cxx29;
19531 else if (getLangOpts().CPlusPlus20)
19532 DefaultableKinds = diag::DefaultableFunctionKinds::Cxx20;
19533
19534 auto *FD = dyn_cast<FunctionDecl>(Dcl);
19535 if (!FD) {
19536 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) {
19538 FTD->getTemplatedDecl()->getDefaultedFunctionKind();
19539 if (DFK.isComparison() || DFK.isPostfixOperator()) {
19540 Diag(DefaultLoc, diag::err_defaulted_operator_template)
19541 << DFK.isPostfixOperator() << (int)DFK.asPostfixOperator();
19542 return;
19543 }
19544 }
19545
19546 Diag(DefaultLoc, diag::err_default_special_members) << DefaultableKinds;
19547 return;
19548 }
19549
19550 // Reject if this can't possibly be a defaultable function.
19551 FunctionDecl::DefaultedFunctionKind DefKind = FD->getDefaultedFunctionKind();
19552 if (!DefKind &&
19553 // A dependent function that doesn't locally look defaultable can
19554 // still instantiate to a defaultable function if it's a constructor
19555 // or assignment operator.
19556 (!FD->isDependentContext() ||
19558 FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) {
19560 if (OO == OO_PlusPlus || OO == OO_MinusMinus)
19561 Diag(DefaultLoc, diag::err_defaulted_prefix_operator)
19562 << (OO == OO_MinusMinus);
19563 else
19564 Diag(DefaultLoc, diag::err_default_special_members) << DefaultableKinds;
19565 return;
19566 }
19567
19568 // Issue compatibility warning. We already warned if the operator is
19569 // 'operator<=>' when parsing the '<=>' token.
19570 if (DefKind.isComparison() &&
19572 DiagCompat(DefaultLoc, diag_compat::defaulted_comparison);
19573 }
19574 // Defaulted postfix increment and decrement operators (P3668R4) are a C++2d
19575 // feature that we support in all C++ language modes as an extension.
19576 if (DefKind.isPostfixOperator() && !inTemplateInstantiation())
19577 DiagCompat(DefaultLoc, diag_compat::defaulted_postfix_operator);
19578
19579 FD->setDefaulted();
19580 FD->setExplicitlyDefaulted();
19581 FD->setDefaultLoc(DefaultLoc);
19582
19583 // Defer checking functions that are defaulted in a dependent context.
19584 if (FD->isDependentContext()) {
19585 // A function defaulted outside its class is not defaulted when its
19586 // declaration is instantiated, so record what the instantiation of its
19587 // definition needs from here: the floating-point features in effect and,
19588 // for a postfix operator, the unqualified lookup of the prefix operator,
19589 // which can only be performed now, while we have the scope of the
19590 // function-body. The info is recorded even for default floating-point
19591 // features, so that the instantiation does not take those in effect at its
19592 // point of instantiation. (When the function is defaulted in its class,
19593 // the lookup is performed once the class is complete.)
19595 if (DefKind.isPostfixOperator())
19597 DefKind.asPostfixOperator());
19598 else if (!FD->getDefaultedOrDeletedInfo())
19599 FD->setDefaultedOrDeletedInfo(
19601 Context, /*Lookups=*/{}, CurFPFeatureOverrides()));
19602 }
19603 return;
19604 }
19605
19606 // Unset that we will have a body for this function. We might not,
19607 // if it turns out to be trivial, and we don't need this marking now
19608 // that we've marked it as defaulted.
19609 FD->setWillHaveBody(false);
19610
19611 if (DefKind.isComparison() || DefKind.isPostfixOperator()) {
19612 // If this function's defaulting occurs within the definition of its
19613 // lexical class context, we have to do the checking when complete.
19614 if (auto const *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext()))
19615 if (!RD->isCompleteDefinition())
19616 return;
19617 }
19618
19619 // If this member fn was defaulted on its first declaration, we will have
19620 // already performed the checking in CheckCompletedCXXClass. Such a
19621 // declaration doesn't trigger an implicit definition.
19622 if (isa<CXXMethodDecl>(FD)) {
19623 const FunctionDecl *Primary = FD;
19624 if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
19625 // Ask the template instantiation pattern that actually had the
19626 // '= default' on it.
19627 Primary = Pattern;
19628 if (Primary->getCanonicalDecl()->isDefaulted())
19629 return;
19630 }
19631
19632 // Only allocate DefaultedOrDeletedFunctionInfo if we actually have
19633 // non-default FP features to stash. This avoids memory overhead for
19634 // the vast majority of defaulted functions. A postfix operator defaulted
19635 // with a scope gets its info, which includes these features, when the
19636 // lookup of its prefix operator is performed below.
19637 if (!FD->getDefaultedOrDeletedInfo() && !(DefKind.isPostfixOperator() && S) &&
19638 CurFPFeatureOverrides().requiresTrailingStorage()) {
19639 FD->setDefaultedOrDeletedInfo(
19641 Context, /*Lookups=*/{}, CurFPFeatureOverrides()));
19642 }
19643
19644 if (DefKind.isComparison()) {
19645 if (CheckExplicitlyDefaultedComparison(nullptr, FD, DefKind.asComparison()))
19646 FD->setInvalidDecl();
19647 else
19648 DefineDefaultedComparison(DefaultLoc, FD, DefKind.asComparison());
19649 } else if (DefKind.isPostfixOperator()) {
19651 DefKind.asPostfixOperator()))
19652 FD->setInvalidDecl();
19653 else if (!FD->isDeleted())
19654 DefineDefaultedPostfixOperator(DefaultLoc, FD,
19655 DefKind.asPostfixOperator());
19656 } else {
19657 auto *MD = cast<CXXMethodDecl>(FD);
19658
19660 DefaultLoc))
19661 MD->setInvalidDecl();
19662 else
19663 DefineDefaultedFunction(*this, MD, DefaultLoc);
19664 }
19665}
19666
19668 for (Stmt *SubStmt : S->children()) {
19669 if (!SubStmt)
19670 continue;
19671 if (isa<ReturnStmt>(SubStmt))
19672 Self.Diag(SubStmt->getBeginLoc(),
19673 diag::err_return_in_constructor_handler);
19674 if (!isa<Expr>(SubStmt))
19675 SearchForReturnInStmt(Self, SubStmt);
19676 }
19677}
19678
19680 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
19681 CXXCatchStmt *Handler = TryBlock->getHandler(I);
19682 SearchForReturnInStmt(*this, Handler);
19683 }
19684}
19685
19687 StringLiteral *DeletedMessage, Scope *S) {
19688 switch (BodyKind) {
19689 case FnBodyKind::Delete:
19690 SetDeclDeleted(D, Loc, DeletedMessage);
19691 break;
19693 SetDeclDefaulted(D, Loc, S);
19694 break;
19695 case FnBodyKind::Other:
19696 llvm_unreachable(
19697 "Parsed function body should be '= delete;' or '= default;'");
19698 }
19699}
19700
19702 const CXXMethodDecl *Old) {
19703 const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
19704 const auto *OldFT = Old->getType()->castAs<FunctionProtoType>();
19705
19706 if (OldFT->hasExtParameterInfos()) {
19707 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
19708 // A parameter of the overriding method should be annotated with noescape
19709 // if the corresponding parameter of the overridden method is annotated.
19710 if (OldFT->getExtParameterInfo(I).isNoEscape() &&
19711 !NewFT->getExtParameterInfo(I).isNoEscape()) {
19712 Diag(New->getParamDecl(I)->getLocation(),
19713 diag::warn_overriding_method_missing_noescape);
19714 Diag(Old->getParamDecl(I)->getLocation(),
19715 diag::note_overridden_marked_noescape);
19716 }
19717 }
19718
19719 // SME attributes must match when overriding a function declaration.
19720 if (IsInvalidSMECallConversion(Old->getType(), New->getType())) {
19721 Diag(New->getLocation(), diag::err_conflicting_overriding_attributes)
19722 << New << New->getType() << Old->getType();
19723 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
19724 return true;
19725 }
19726
19727 // Virtual overrides must have the same code_seg.
19728 const auto *OldCSA = Old->getAttr<CodeSegAttr>();
19729 const auto *NewCSA = New->getAttr<CodeSegAttr>();
19730 if ((NewCSA || OldCSA) &&
19731 (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
19732 Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
19733 Diag(Old->getLocation(), diag::note_previous_declaration);
19734 return true;
19735 }
19736
19737 // Virtual overrides: check for matching effects.
19738 if (Context.hasAnyFunctionEffects()) {
19739 const auto OldFX = Old->getFunctionEffects();
19740 const auto NewFXOrig = New->getFunctionEffects();
19741
19742 if (OldFX != NewFXOrig) {
19743 FunctionEffectSet NewFX(NewFXOrig);
19744 const auto Diffs = FunctionEffectDiffVector(OldFX, NewFX);
19746 for (const auto &Diff : Diffs) {
19747 switch (Diff.shouldDiagnoseMethodOverride(*Old, OldFX, *New, NewFX)) {
19749 break;
19751 Diag(New->getLocation(), diag::warn_conflicting_func_effect_override)
19752 << Diff.effectName();
19753 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
19754 << Old->getReturnTypeSourceRange();
19755 break;
19757 NewFX.insert(Diff.Old.value(), Errs);
19758 const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
19759 FunctionProtoType::ExtProtoInfo EPI = NewFT->getExtProtoInfo();
19761 QualType ModQT = Context.getFunctionType(NewFT->getReturnType(),
19762 NewFT->getParamTypes(), EPI);
19763 New->setType(ModQT);
19764 if (Errs.empty()) {
19765 // A warning here is somewhat pedantic. Skip this if there was
19766 // already a merge conflict, which is more serious.
19767 Diag(New->getLocation(), diag::warn_mismatched_func_effect_override)
19768 << Diff.effectName();
19769 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
19770 << Old->getReturnTypeSourceRange();
19771 }
19772 break;
19773 }
19774 }
19775 }
19776 if (!Errs.empty())
19777 diagnoseFunctionEffectMergeConflicts(Errs, New->getLocation(),
19778 Old->getLocation());
19779 }
19780 }
19781
19782 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
19783
19784 // If the calling conventions match, everything is fine
19785 if (NewCC == OldCC)
19786 return false;
19787
19788 // If the calling conventions mismatch because the new function is static,
19789 // suppress the calling convention mismatch error; the error about static
19790 // function override (err_static_overrides_virtual from
19791 // Sema::CheckFunctionDeclaration) is more clear.
19792 if (New->getStorageClass() == SC_Static)
19793 return false;
19794
19795 Diag(New->getLocation(),
19796 diag::err_conflicting_overriding_cc_attributes)
19797 << New->getDeclName() << New->getType() << Old->getType();
19798 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
19799 return true;
19800}
19801
19803 const CXXMethodDecl *Old) {
19804 // CWG2553
19805 // A virtual function shall not be an explicit object member function.
19806 if (!New->isExplicitObjectMemberFunction())
19807 return true;
19808 Diag(New->getParamDecl(0)->getBeginLoc(),
19809 diag::err_explicit_object_parameter_nonmember)
19810 << New->getSourceRange() << /*virtual*/ 1 << /*IsLambda*/ false;
19811 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
19812 New->setInvalidDecl();
19813 return false;
19814}
19815
19817 const CXXMethodDecl *Old) {
19818 QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType();
19819 QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType();
19820
19821 if (Context.hasSameType(NewTy, OldTy) ||
19822 NewTy->isDependentType() || OldTy->isDependentType())
19823 return false;
19824
19825 // Check if the return types are covariant
19826 QualType NewClassTy, OldClassTy;
19827
19828 /// Both types must be pointers or references to classes.
19829 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
19830 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
19831 NewClassTy = NewPT->getPointeeType();
19832 OldClassTy = OldPT->getPointeeType();
19833 }
19834 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
19835 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
19836 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
19837 NewClassTy = NewRT->getPointeeType();
19838 OldClassTy = OldRT->getPointeeType();
19839 }
19840 }
19841 }
19842
19843 // The return types aren't either both pointers or references to a class type.
19844 if (NewClassTy.isNull() || !NewClassTy->isStructureOrClassType()) {
19845 Diag(New->getLocation(),
19846 diag::err_different_return_type_for_overriding_virtual_function)
19847 << New->getDeclName() << NewTy << OldTy
19848 << New->getReturnTypeSourceRange();
19849 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
19850 << Old->getReturnTypeSourceRange();
19851
19852 return true;
19853 }
19854
19855 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
19856 // C++14 [class.virtual]p8:
19857 // If the class type in the covariant return type of D::f differs from
19858 // that of B::f, the class type in the return type of D::f shall be
19859 // complete at the point of declaration of D::f or shall be the class
19860 // type D.
19861 if (const auto *RD = NewClassTy->getAsCXXRecordDecl()) {
19862 if (!RD->isBeingDefined() &&
19863 RequireCompleteType(New->getLocation(), NewClassTy,
19864 diag::err_covariant_return_incomplete,
19865 New->getDeclName()))
19866 return true;
19867 }
19868
19869 // Check if the new class derives from the old class.
19870 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
19871 Diag(New->getLocation(), diag::err_covariant_return_not_derived)
19872 << New->getDeclName() << NewTy << OldTy
19873 << New->getReturnTypeSourceRange();
19874 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
19875 << Old->getReturnTypeSourceRange();
19876 return true;
19877 }
19878
19879 // Check if we the conversion from derived to base is valid.
19881 NewClassTy, OldClassTy,
19882 diag::err_covariant_return_inaccessible_base,
19883 diag::err_covariant_return_ambiguous_derived_to_base_conv,
19884 New->getLocation(), New->getReturnTypeSourceRange(),
19885 New->getDeclName(), nullptr)) {
19886 // FIXME: this note won't trigger for delayed access control
19887 // diagnostics, and it's impossible to get an undelayed error
19888 // here from access control during the original parse because
19889 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
19890 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
19891 << Old->getReturnTypeSourceRange();
19892 return true;
19893 }
19894 }
19895
19896 // The qualifiers of the return types must be the same.
19897 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
19898 Diag(New->getLocation(),
19899 diag::err_covariant_return_type_different_qualifications)
19900 << New->getDeclName() << NewTy << OldTy
19901 << New->getReturnTypeSourceRange();
19902 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
19903 << Old->getReturnTypeSourceRange();
19904 return true;
19905 }
19906
19907
19908 // The new class type must have the same or less qualifiers as the old type.
19909 if (!OldClassTy.isAtLeastAsQualifiedAs(NewClassTy, getASTContext())) {
19910 Diag(New->getLocation(),
19911 diag::err_covariant_return_type_class_type_not_same_or_less_qualified)
19912 << New->getDeclName() << NewTy << OldTy
19913 << New->getReturnTypeSourceRange();
19914 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
19915 << Old->getReturnTypeSourceRange();
19916 return true;
19917 }
19918
19919 return false;
19920}
19921
19923 SourceLocation EndLoc = InitRange.getEnd();
19924 if (EndLoc.isValid())
19925 Method->setRangeEnd(EndLoc);
19926
19927 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
19928 Method->setIsPureVirtual();
19929 return false;
19930 }
19931
19932 if (!Method->isInvalidDecl())
19933 Diag(Method->getLocation(), diag::err_non_virtual_pure)
19934 << Method->getDeclName() << InitRange;
19935 return true;
19936}
19937
19939 if (D->getFriendObjectKind())
19940 Diag(D->getLocation(), diag::err_pure_friend);
19941 else if (auto *M = dyn_cast<CXXMethodDecl>(D))
19942 CheckPureMethod(M, ZeroLoc);
19943 else
19944 Diag(D->getLocation(), diag::err_illegal_initializer);
19945}
19946
19947/// Invoked when we are about to parse an initializer for the declaration
19948/// 'Dcl'.
19949///
19950/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
19951/// static data member of class X, names should be looked up in the scope of
19952/// class X. If the declaration had a scope specifier, a scope will have
19953/// been created and passed in for this purpose. Otherwise, S will be null.
19955 assert(D && !D->isInvalidDecl());
19956
19957 // We will always have a nested name specifier here, but this declaration
19958 // might not be out of line if the specifier names the current namespace:
19959 // extern int n;
19960 // int ::n = 0;
19961 if (S && D->isOutOfLine())
19963
19967}
19968
19970 assert(D);
19971
19972 if (S && D->isOutOfLine())
19974
19976}
19977
19979 // C++ 6.4p2:
19980 // The declarator shall not specify a function or an array.
19981 // The type-specifier-seq shall not contain typedef and shall not declare a
19982 // new class or enumeration.
19984 "Parser allowed 'typedef' as storage class of condition decl.");
19985
19986 Decl *Dcl = ActOnDeclarator(S, D);
19987 if (!Dcl)
19988 return true;
19989
19990 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
19991 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
19992 << D.getSourceRange();
19993 return true;
19994 }
19995
19996 if (auto *VD = dyn_cast<VarDecl>(Dcl))
19997 VD->setCXXCondDecl();
19998
19999 return Dcl;
20000}
20001
20003 if (!ExternalSource)
20004 return;
20005
20007 ExternalSource->ReadUsedVTables(VTables);
20009 for (const ExternalVTableUse &VTable : VTables) {
20010 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos =
20011 VTablesUsed.find(VTable.Record);
20012 // Even if a definition wasn't required before, it may be required now.
20013 if (Pos != VTablesUsed.end()) {
20014 if (!Pos->second && VTable.DefinitionRequired)
20015 Pos->second = true;
20016 continue;
20017 }
20018
20019 VTablesUsed[VTable.Record] = VTable.DefinitionRequired;
20020 NewUses.push_back(VTableUse(VTable.Record, VTable.Location));
20021 }
20022
20023 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
20024}
20025
20027 bool DefinitionRequired) {
20028 // Ignore any vtable uses in unevaluated operands or for classes that do
20029 // not have a vtable.
20030 if (!Class->isDynamicClass() || Class->isDependentContext() ||
20031 CurContext->isDependentContext() || isUnevaluatedContext())
20032 return;
20033 // Do not mark as used if compiling for the device outside of the target
20034 // region.
20035 if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice &&
20036 !OpenMP().isInOpenMPDeclareTargetContext() &&
20037 !OpenMP().isInOpenMPTargetExecutionDirective()) {
20038 if (!DefinitionRequired)
20040 return;
20041 }
20042
20043 // Try to insert this class into the map.
20045 Class = Class->getCanonicalDecl();
20046 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
20047 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
20048 if (!Pos.second) {
20049 // If we already had an entry, check to see if we are promoting this vtable
20050 // to require a definition. If so, we need to reappend to the VTableUses
20051 // list, since we may have already processed the first entry.
20052 if (DefinitionRequired && !Pos.first->second) {
20053 Pos.first->second = true;
20054 } else {
20055 // Otherwise, we can early exit.
20056 return;
20057 }
20058 } else {
20059 // The Microsoft ABI requires that we perform the destructor body
20060 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
20061 // the deleting destructor is emitted with the vtable, not with the
20062 // destructor definition as in the Itanium ABI.
20063 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
20064 CXXDestructorDecl *DD = Class->getDestructor();
20065 if (DD && DD->isVirtual() && !DD->isDeleted()) {
20066 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
20067 // If this is an out-of-line declaration, marking it referenced will
20068 // not do anything. Manually call CheckDestructor to look up operator
20069 // delete().
20070 ContextRAII SavedContext(*this, DD);
20071 CheckDestructor(DD);
20072 if (!DD->getOperatorDelete())
20073 DD->setInvalidDecl();
20074 } else {
20075 MarkFunctionReferenced(Loc, Class->getDestructor());
20076 }
20077 }
20078 }
20079 }
20080
20081 // Local classes need to have their virtual members marked
20082 // immediately. For all other classes, we mark their virtual members
20083 // at the end of the translation unit.
20084 if (Class->isLocalClass())
20085 MarkVirtualMembersReferenced(Loc, Class->getDefinition());
20086 else
20087 VTableUses.push_back(std::make_pair(Class, Loc));
20088}
20089
20092 if (VTableUses.empty())
20093 return false;
20094
20095 // Note: The VTableUses vector could grow as a result of marking
20096 // the members of a class as "used", so we check the size each
20097 // time through the loop and prefer indices (which are stable) to
20098 // iterators (which are not).
20099 bool DefinedAnything = false;
20100 for (unsigned I = 0; I != VTableUses.size(); ++I) {
20101 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
20102 if (!Class)
20103 continue;
20105 Class->getTemplateSpecializationKind();
20106
20107 SourceLocation Loc = VTableUses[I].second;
20108
20109 bool DefineVTable = true;
20110
20111 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
20112 // V-tables for non-template classes with an owning module are always
20113 // uniquely emitted in that module.
20114 if (Class->isInCurrentModuleUnit()) {
20115 DefineVTable = true;
20116 } else if (KeyFunction && !KeyFunction->hasBody()) {
20117 // If this class has a key function, but that key function is
20118 // defined in another translation unit, we don't need to emit the
20119 // vtable even though we're using it.
20120 // The key function is in another translation unit.
20121 DefineVTable = false;
20123 KeyFunction->getTemplateSpecializationKind();
20126 "Instantiations don't have key functions");
20127 (void)TSK;
20128 } else if (!KeyFunction) {
20129 // If we have a class with no key function that is the subject
20130 // of an explicit instantiation declaration, suppress the
20131 // vtable; it will live with the explicit instantiation
20132 // definition.
20133 bool IsExplicitInstantiationDeclaration =
20135 for (auto *R : Class->redecls()) {
20137 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
20139 IsExplicitInstantiationDeclaration = true;
20140 else if (TSK == TSK_ExplicitInstantiationDefinition) {
20141 IsExplicitInstantiationDeclaration = false;
20142 break;
20143 }
20144 }
20145
20146 if (IsExplicitInstantiationDeclaration) {
20147 const bool HasExcludeFromExplicitInstantiation =
20148 llvm::any_of(Class->methods(), [](CXXMethodDecl *method) {
20149 // If the class has a member function declared with
20150 // `__attribute__((exclude_from_explicit_instantiation))`, the
20151 // explicit instantiation declaration should not suppress emitting
20152 // the vtable, since the corresponding explicit instantiation
20153 // definition might not emit the vtable if a triggering method is
20154 // excluded.
20155 return method->hasAttr<ExcludeFromExplicitInstantiationAttr>();
20156 });
20157 if (!HasExcludeFromExplicitInstantiation)
20158 DefineVTable = false;
20159 }
20160 }
20161
20162 // The exception specifications for all virtual members may be needed even
20163 // if we are not providing an authoritative form of the vtable in this TU.
20164 // We may choose to emit it available_externally anyway.
20165 if (!DefineVTable) {
20167 continue;
20168 }
20169
20170 // Mark all of the virtual members of this class as referenced, so
20171 // that we can build a vtable. Then, tell the AST consumer that a
20172 // vtable for this class is required.
20173 DefinedAnything = true;
20175 CXXRecordDecl *Canonical = Class->getCanonicalDecl();
20176 // The vtable is assumed to be emitted in an external source only for
20177 // classes attached to a named module, which is guaranteed to have an object
20178 // file. This isn't true for -fmodules-debuginfo, which still has
20179 // shouldEmitInExternalSource as true so that debug info gets supressed.
20180 if (VTablesUsed[Canonical] &&
20181 !(Class->isInNamedModule() && Class->shouldEmitInExternalSource()))
20182 Consumer.HandleVTable(Class);
20183
20184 // Warn if we're emitting a weak vtable. The vtable will be weak if there is
20185 // no key function or the key function is inlined. Don't warn in C++ ABIs
20186 // that lack key functions, since the user won't be able to make one.
20187 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
20188 Class->isExternallyVisible() &&
20189 !(Class->getOwningModule() &&
20190 Class->getOwningModule()->isInterfaceOrPartition()) &&
20191 ClassTSK != TSK_ImplicitInstantiation &&
20194 const FunctionDecl *KeyFunctionDef = nullptr;
20195 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
20196 KeyFunctionDef->isInlined()))
20197 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
20198 }
20199 }
20200 VTableUses.clear();
20201
20202 return DefinedAnything;
20203}
20204
20206 const CXXRecordDecl *RD) {
20207 for (const auto *I : RD->methods())
20208 if (I->isVirtual() && !I->isPureVirtual())
20209 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
20210}
20211
20213 const CXXRecordDecl *RD,
20214 bool ConstexprOnly) {
20215 // Mark all functions which will appear in RD's vtable as used.
20216 CXXFinalOverriderMap FinalOverriders;
20217 RD->getFinalOverriders(FinalOverriders);
20218 for (const auto &FinalOverrider : FinalOverriders) {
20219 for (const auto &OverridingMethod : FinalOverrider.second) {
20220 assert(OverridingMethod.second.size() > 0 && "no final overrider");
20221 CXXMethodDecl *Overrider = OverridingMethod.second.front().Method;
20222
20223 // C++ [basic.def.odr]p2:
20224 // [...] A virtual member function is used if it is not pure. [...]
20225 if (!Overrider->isPureVirtual() &&
20226 (!ConstexprOnly || Overrider->isConstexpr()))
20227 MarkFunctionReferenced(Loc, Overrider);
20228 }
20229 }
20230
20231 // Only classes that have virtual bases need a VTT.
20232 if (RD->getNumVBases() == 0)
20233 return;
20234
20235 for (const auto &I : RD->bases()) {
20236 const auto *Base = I.getType()->castAsCXXRecordDecl();
20237 if (Base->getNumVBases() == 0)
20238 continue;
20240 }
20241}
20242
20243static
20248 Sema &S) {
20249 if (Ctor->isInvalidDecl())
20250 return;
20251
20253
20254 // Target may not be determinable yet, for instance if this is a dependent
20255 // call in an uninstantiated template.
20256 if (Target) {
20257 const FunctionDecl *FNTarget = nullptr;
20258 (void)Target->hasBody(FNTarget);
20259 Target = const_cast<CXXConstructorDecl*>(
20260 cast_or_null<CXXConstructorDecl>(FNTarget));
20261 }
20262
20263 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
20264 // Avoid dereferencing a null pointer here.
20265 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
20266
20267 if (!Current.insert(Canonical).second)
20268 return;
20269
20270 // We know that beyond here, we aren't chaining into a cycle.
20271 if (!Target || !Target->isDelegatingConstructor() ||
20272 Target->isInvalidDecl() || Valid.count(TCanonical)) {
20273 Valid.insert_range(Current);
20274 Current.clear();
20275 // We've hit a cycle.
20276 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
20277 Current.count(TCanonical)) {
20278 // If we haven't diagnosed this cycle yet, do so now.
20279 if (!Invalid.count(TCanonical)) {
20280 S.Diag((*Ctor->init_begin())->getSourceLocation(),
20281 diag::warn_delegating_ctor_cycle)
20282 << Ctor;
20283
20284 // Don't add a note for a function delegating directly to itself.
20285 if (TCanonical != Canonical)
20286 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
20287
20289 while (C->getCanonicalDecl() != Canonical) {
20290 const FunctionDecl *FNTarget = nullptr;
20291 (void)C->getTargetConstructor()->hasBody(FNTarget);
20292 assert(FNTarget && "Ctor cycle through bodiless function");
20293
20294 C = const_cast<CXXConstructorDecl*>(
20295 cast<CXXConstructorDecl>(FNTarget));
20296 S.Diag(C->getLocation(), diag::note_which_delegates_to);
20297 }
20298 }
20299
20300 Invalid.insert_range(Current);
20301 Current.clear();
20302 } else {
20304 }
20305}
20306
20307
20310
20311 for (DelegatingCtorDeclsType::iterator
20312 I = DelegatingCtorDecls.begin(ExternalSource.get()),
20313 E = DelegatingCtorDecls.end();
20314 I != E; ++I)
20315 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
20316
20317 for (CXXConstructorDecl *CI : Invalid)
20318 CI->setInvalidDecl();
20319}
20320
20321namespace {
20322 /// AST visitor that finds references to the 'this' expression.
20323class FindCXXThisExpr : public DynamicRecursiveASTVisitor {
20324 Sema &S;
20325
20326public:
20327 explicit FindCXXThisExpr(Sema &S) : S(S) {}
20328
20329 bool VisitCXXThisExpr(CXXThisExpr *E) override {
20330 S.Diag(E->getLocation(), diag::err_this_static_member_func)
20331 << E->isImplicit();
20332 return false;
20333 }
20334};
20335}
20336
20338 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
20339 if (!TSInfo)
20340 return false;
20341
20342 TypeLoc TL = TSInfo->getTypeLoc();
20344 if (!ProtoTL)
20345 return false;
20346
20347 // C++11 [expr.prim.general]p3:
20348 // [The expression this] shall not appear before the optional
20349 // cv-qualifier-seq and it shall not appear within the declaration of a
20350 // static member function (although its type and value category are defined
20351 // within a static member function as they are within a non-static member
20352 // function). [ Note: this is because declaration matching does not occur
20353 // until the complete declarator is known. - end note ]
20354 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
20355 FindCXXThisExpr Finder(*this);
20356
20357 // If the return type came after the cv-qualifier-seq, check it now.
20358 if (Proto->hasTrailingReturn() &&
20359 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
20360 return true;
20361
20362 // Check the exception specification.
20364 return true;
20365
20366 // Check the trailing requires clause
20367 if (const AssociatedConstraint &TRC = Method->getTrailingRequiresClause())
20368 if (!Finder.TraverseStmt(const_cast<Expr *>(TRC.ConstraintExpr)))
20369 return true;
20370
20372}
20373
20375 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
20376 if (!TSInfo)
20377 return false;
20378
20379 TypeLoc TL = TSInfo->getTypeLoc();
20381 if (!ProtoTL)
20382 return false;
20383
20384 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
20385 FindCXXThisExpr Finder(*this);
20386
20387 switch (Proto->getExceptionSpecType()) {
20388 case EST_Unparsed:
20389 case EST_Uninstantiated:
20390 case EST_Unevaluated:
20391 case EST_BasicNoexcept:
20392 case EST_NoThrow:
20393 case EST_DynamicNone:
20394 case EST_MSAny:
20395 case EST_None:
20396 break;
20397
20399 case EST_NoexceptFalse:
20400 case EST_NoexceptTrue:
20401 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
20402 return true;
20403 [[fallthrough]];
20404
20405 case EST_Dynamic:
20406 for (const auto &E : Proto->exceptions()) {
20407 if (!Finder.TraverseType(E))
20408 return true;
20409 }
20410 break;
20411 }
20412
20413 return false;
20414}
20415
20417 FindCXXThisExpr Finder(*this);
20418
20419 // Check attributes.
20420 for (const auto *A : Method->attrs()) {
20421 // FIXME: This should be emitted by tblgen.
20422 Expr *Arg = nullptr;
20423 ArrayRef<Expr *> Args;
20424 if (const auto *G = dyn_cast<GuardedByAttr>(A))
20425 Args = llvm::ArrayRef(G->args_begin(), G->args_size());
20426 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
20427 Args = llvm::ArrayRef(G->args_begin(), G->args_size());
20428 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
20429 Args = llvm::ArrayRef(AA->args_begin(), AA->args_size());
20430 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
20431 Args = llvm::ArrayRef(AB->args_begin(), AB->args_size());
20432 else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
20433 Arg = LR->getArg();
20434 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
20435 Args = llvm::ArrayRef(LE->args_begin(), LE->args_size());
20436 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
20437 Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());
20438 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
20439 Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());
20440 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) {
20441 Arg = AC->getSuccessValue();
20442 Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());
20443 } else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
20444 Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());
20445
20446 if (Arg && !Finder.TraverseStmt(Arg))
20447 return true;
20448
20449 for (Expr *A : Args) {
20450 if (!Finder.TraverseStmt(A))
20451 return true;
20452 }
20453 }
20454
20455 return false;
20456}
20457
20459 bool IsTopLevel, ExceptionSpecificationType EST,
20460 ArrayRef<ParsedType> DynamicExceptions,
20461 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
20462 SmallVectorImpl<QualType> &Exceptions,
20464 Exceptions.clear();
20465 ESI.Type = EST;
20466 if (EST == EST_Dynamic) {
20467 Exceptions.reserve(DynamicExceptions.size());
20468 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
20469 // FIXME: Preserve type source info.
20470 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
20471
20472 if (IsTopLevel) {
20474 collectUnexpandedParameterPacks(ET, Unexpanded);
20475 if (!Unexpanded.empty()) {
20477 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
20478 Unexpanded);
20479 continue;
20480 }
20481 }
20482
20483 // Check that the type is valid for an exception spec, and
20484 // drop it if not.
20485 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
20486 Exceptions.push_back(ET);
20487 }
20488 ESI.Exceptions = Exceptions;
20489 return;
20490 }
20491
20492 if (isComputedNoexcept(EST)) {
20493 assert((NoexceptExpr->isTypeDependent() ||
20494 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
20495 Context.BoolTy) &&
20496 "Parser should have made sure that the expression is boolean");
20497 if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
20498 ESI.Type = EST_BasicNoexcept;
20499 return;
20500 }
20501
20502 ESI.NoexceptExpr = NoexceptExpr;
20503 return;
20504 }
20505}
20506
20508 Decl *D, ExceptionSpecificationType EST, SourceRange SpecificationRange,
20509 ArrayRef<ParsedType> DynamicExceptions,
20510 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr) {
20511 if (!D)
20512 return;
20513
20514 // Dig out the function we're referring to.
20515 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
20516 D = FTD->getTemplatedDecl();
20517
20518 FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
20519 if (!FD)
20520 return;
20521
20522 // Check the exception specification.
20525 checkExceptionSpecification(/*IsTopLevel=*/true, EST, DynamicExceptions,
20526 DynamicExceptionRanges, NoexceptExpr, Exceptions,
20527 ESI);
20528
20529 // Update the exception specification on the function type.
20530 Context.adjustExceptionSpec(FD, ESI, /*AsWritten=*/true);
20531
20532 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
20533 if (MD->isStatic())
20535
20536 if (MD->isVirtual()) {
20537 // Check overrides, which we previously had to delay.
20538 for (const CXXMethodDecl *O : MD->overridden_methods())
20540 }
20541 }
20542}
20543
20544/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
20545///
20547 SourceLocation DeclStart, Declarator &D,
20548 Expr *BitWidth,
20549 InClassInitStyle InitStyle,
20550 AccessSpecifier AS,
20551 const ParsedAttr &MSPropertyAttr) {
20552 const IdentifierInfo *II = D.getIdentifier();
20553 if (!II) {
20554 Diag(DeclStart, diag::err_anonymous_property);
20555 return nullptr;
20556 }
20558
20560 QualType T = TInfo->getType();
20561 if (getLangOpts().CPlusPlus) {
20563
20566 D.setInvalidType();
20567 T = Context.IntTy;
20568 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
20569 }
20570 }
20571
20573
20575 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
20576 << getLangOpts().CPlusPlus17;
20579 diag::err_invalid_thread)
20581
20582 // Check to see if this name was declared as a member previously
20583 NamedDecl *PrevDecl = nullptr;
20584 LookupResult Previous(*this, II, Loc, LookupMemberName,
20586 LookupName(Previous, S);
20587 switch (Previous.getResultKind()) {
20590 PrevDecl = Previous.getAsSingle<NamedDecl>();
20591 break;
20592
20594 PrevDecl = Previous.getRepresentativeDecl();
20595 break;
20596
20600 break;
20601 }
20602
20603 if (PrevDecl && PrevDecl->isTemplateParameter()) {
20604 // Maybe we will complain about the shadowed template parameter.
20606 // Just pretend that we didn't see the previous declaration.
20607 PrevDecl = nullptr;
20608 }
20609
20610 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
20611 PrevDecl = nullptr;
20612
20613 SourceLocation TSSL = D.getBeginLoc();
20614 MSPropertyDecl *NewPD =
20615 MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
20616 MSPropertyAttr.getPropertyDataGetter(),
20617 MSPropertyAttr.getPropertyDataSetter());
20618 ProcessDeclAttributes(TUScope, NewPD, D);
20619 NewPD->setAccess(AS);
20620
20621 if (NewPD->isInvalidDecl())
20622 Record->setInvalidDecl();
20623
20625 NewPD->setModulePrivate();
20626
20627 if (NewPD->isInvalidDecl() && PrevDecl) {
20628 // Don't introduce NewFD into scope; there's already something
20629 // with the same name in the same scope.
20630 } else if (II) {
20631 PushOnScopeChains(NewPD, S);
20632 } else
20633 Record->addDecl(NewPD);
20634
20635 return NewPD;
20636}
20637
20639 Declarator &Declarator, unsigned TemplateParameterDepth) {
20640 auto &Info = InventedParameterInfos.emplace_back();
20641 TemplateParameterList *ExplicitParams = nullptr;
20642 ArrayRef<TemplateParameterList *> ExplicitLists =
20644 if (!ExplicitLists.empty()) {
20645 bool IsMemberSpecialization, IsInvalid;
20648 Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr,
20649 ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid,
20650 /*SuppressDiagnostic=*/true);
20651 }
20652 // C++23 [dcl.fct]p23:
20653 // An abbreviated function template can have a template-head. The invented
20654 // template-parameters are appended to the template-parameter-list after
20655 // the explicitly declared template-parameters.
20656 //
20657 // A template-head must have one or more template-parameters (read:
20658 // 'template<>' is *not* a template-head). Only append the invented
20659 // template parameters if we matched the nested-name-specifier to a non-empty
20660 // TemplateParameterList.
20661 if (ExplicitParams && !ExplicitParams->empty()) {
20662 Info.AutoTemplateParameterDepth = ExplicitParams->getDepth();
20663 llvm::append_range(Info.TemplateParams, *ExplicitParams);
20664 Info.NumExplicitTemplateParams = ExplicitParams->size();
20665 } else {
20666 Info.AutoTemplateParameterDepth = TemplateParameterDepth;
20667 Info.NumExplicitTemplateParams = 0;
20668 }
20669}
20670
20672 auto &FSI = InventedParameterInfos.back();
20673 if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) {
20674 if (FSI.NumExplicitTemplateParams != 0) {
20675 TemplateParameterList *ExplicitParams =
20679 Context, ExplicitParams->getTemplateLoc(),
20680 ExplicitParams->getLAngleLoc(), FSI.TemplateParams,
20681 ExplicitParams->getRAngleLoc(),
20682 ExplicitParams->getRequiresClause()));
20683 } else {
20686 FSI.TemplateParams, Declarator.getEndLoc(),
20687 /*RequiresClause=*/nullptr));
20688 }
20689 }
20690 InventedParameterInfos.pop_back();
20691}
20692
20694 CXXConstructorDecl *Ctor, bool IsCopy) {
20695 assert(Context.getTargetInfo().getCXXABI().isMicrosoft());
20696
20697 if (!Ctor->getCtorClosureDefaultArgs().empty()) {
20698 // If we build args for default constructor closures, those will have
20699 // been generated *before* building args for any copy constructor closures.
20700 assert(IsCopy || Ctor->getCtorClosureDefaultArgs()[0] != nullptr);
20701 return false;
20702 }
20703
20704 unsigned NumParams = Ctor->getNumParams();
20705 if (NumParams == 0)
20706 return false;
20707
20708 CXXDefaultArgExpr **Args =
20709 new (getASTContext()) CXXDefaultArgExpr *[NumParams];
20710
20711 if (IsCopy)
20712 Args[0] = nullptr; // Copy ctor closure will provide the first argument.
20713
20714 for (unsigned I = IsCopy ? 1 : 0; I != NumParams; ++I) {
20715 ExprResult R = BuildCXXDefaultArgExpr(Loc, Ctor, Ctor->getParamDecl(I));
20717 if (R.isInvalid())
20718 return true;
20719 Args[I] = cast<CXXDefaultArgExpr>(R.get());
20720 }
20721
20722 Ctor->setCtorClosureDefaultArgs(ArrayRef(Args, NumParams));
20723 return false;
20724}
Defines the clang::ASTContext interface.
#define V(N, I)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
This file defines the classes used to store parsed information about declaration-specifiers and decla...
Defines the C++ template declaration subclasses.
Defines the clang::Expr interface and subclasses for C++ expressions.
static bool CheckLiteralType(EvalInfo &Info, const Expr *E, const LValue *This=nullptr)
Check that this core constant expression is of literal type, and if not, produce an appropriate diagn...
TokenType getType() const
Returns the token's type, e.g.
FormatToken * Previous
The previous token in the unwrapped line.
FormatToken * Next
The next token in the unwrapped line.
Result
Implement __builtin_bit_cast and related operations.
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Target Target
Definition MachO.h:51
llvm::MachO::Record Record
Definition MachO.h:31
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
Defines the clang::Preprocessor interface.
@ ForExternalRedeclaration
The lookup results will be used for redeclaration of a name with external linkage; non-visible lookup...
@ ForVisibleRedeclaration
The lookup results will be used for redeclaration of a name, if an entity by that name already exists...
llvm::SmallVector< std::pair< const MemRegion *, SVal >, 4 > Bindings
static void ProcessAPINotes(Sema &S, Decl *D, const api_notes::CommonEntityInfo &Info, VersionedInfoMetadata Metadata)
static AccessResult DeduceTemplateArguments(Sema &S, FriendTemplateDecl *FTD, DeclContext *DC, const TemplateSpecializationType *TST, ArrayRef< TemplateParameterList * > TPLs, TemplateSpecCandidateSet *FailedTSC, MultiLevelTemplateArgumentList &DeducedArgs)
This file declares semantic analysis for CUDA constructs.
static void DiagnoseUnsatisfiedConstraint(Sema &S, ArrayRef< UnsatisfiedConstraintRecord > Records, SourceLocation Loc, bool First=true, concepts::NestedRequirement *Req=nullptr)
static LookupResult lookupMember(Sema &S, const char *Name, CXXRecordDecl *RD, SourceLocation Loc, bool &Res)
static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, CXXSpecialMemberKind CSM, unsigned Quals, bool ConstRHS, TrivialABIHandling TAH, CXXMethodDecl **Selected)
Perform lookup for a special member of the specified kind, and determine whether it is trivial.
static StmtResult buildDefaultedPostfixOperatorBody(Sema &S, FunctionDecl *FD, PostfixOperatorKind Kind, SourceLocation Loc)
Build the body of a defaulted postfix increment or decrement operator function.
static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, SourceLocation CurrentLocation)
Check if we're implicitly defining a move assignment operator for a class with virtual bases.
static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID)
static void DelegatingCycleHelper(CXXConstructorDecl *Ctor, llvm::SmallPtrSet< CXXConstructorDecl *, 4 > &Valid, llvm::SmallPtrSet< CXXConstructorDecl *, 4 > &Invalid, llvm::SmallPtrSet< CXXConstructorDecl *, 4 > &Current, Sema &S)
static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *Body, Sema::CheckConstexprKind Kind)
Check the body for the given constexpr function declaration only contains the permitted types of stat...
llvm::SmallPtrSet< QualType, 4 > IndirectBaseSet
Use small set to collect indirect bases.
static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S, CXXRecordDecl *Class)
static bool checkVectorDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, ValueDecl *Src, QualType DecompType, const VectorType *VT)
static void SearchForReturnInStmt(Sema &Self, Stmt *S)
static bool checkSimpleDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, ValueDecl *Src, QualType DecompType, const llvm::APSInt &NumElemsAPS, QualType ElemType, llvm::function_ref< ExprResult(SourceLocation, Expr *, unsigned)> GetInit)
static CXXDestructorDecl * LookupDestructorIfRelevant(Sema &S, CXXRecordDecl *Class)
static Sema::ImplicitExceptionSpecification ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD, DefaultedComparisonKind DCK)
static void extendRight(SourceRange &R, SourceRange After)
static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, SourceLocation Loc, IdentifierInfo *II, bool *IsInline, NamespaceDecl *PrevNS)
Diagnose a mismatch in 'inline' qualifiers when a namespace is reopened.
static bool IsPotentiallyTypeAwareOperatorNewOrDelete(Sema &SemaRef, const FunctionDecl *FD, bool *WasMalformed)
static bool RefersToRValueRef(Expr *MemRef)
static bool CheckConstexprCtorInitializer(Sema &SemaRef, const FunctionDecl *Dcl, FieldDecl *Field, llvm::SmallPtrSet< Decl *, 16 > &Inits, bool &Diagnosed, Sema::CheckConstexprKind Kind)
Check that the given field is initialized within a constexpr constructor.
static CanQualType RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy)
static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base)
Determine whether a direct base class is a virtual base class.
#define CheckPolymorphic(Type)
static void BuildBasePathArray(const CXXBasePath &Path, CXXCastPath &BasePathArray)
static void WriteCharValueForDiagnostic(uint32_t Value, const BuiltinType *BTy, unsigned TyWidth, SmallVectorImpl< char > &Str)
Convert character's value, interpreted as a code unit, to a string.
static void CheckAbstractClassUsage(AbstractUsageInfo &Info, FunctionDecl *FD)
Check for invalid uses of an abstract type in a function declaration.
static unsigned getRecordDiagFromTagKind(TagTypeKind Tag)
Get diagnostic select index for tag kind for record diagnostic message.
static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T, unsigned &OutSize)
static Expr * CastForMoving(Sema &SemaRef, Expr *E)
static bool IsPotentiallyDestroyingOperatorDelete(Sema &SemaRef, const FunctionDecl *FD)
static void extendLeft(SourceRange &R, SourceRange Before)
static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, unsigned Quals, bool ConstRHS, CXXConstructorDecl *InheritedCtor=nullptr, Sema::InheritedConstructorInfo *Inherited=nullptr)
Is the special member function which would be selected to perform the specified operation on the spec...
static void diagnoseInvalidDeclaratorChunks(Sema &S, Declarator &D, unsigned Kind)
static bool canPassInRegisters(Sema &S, CXXRecordDecl *D, TargetInfo::CallingConvKind CCK)
Determine whether a type is permitted to be passed or returned in registers, per C++ [class....
static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S, UnresolvedSetImpl &Operators, OverloadedOperatorKind Op)
Perform the unqualified lookups that might be needed to form a defaulted comparison function for the ...
static void WriteCharTypePrefix(BuiltinType::Kind BTK, llvm::raw_ostream &OS)
static bool EvaluateAsStringImpl(Sema &SemaRef, Expr *Message, ResultType &Result, ASTContext &Ctx, Sema::StringEvaluationContext EvalContext, bool ErrorOnInvalidMessage)
static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp)
Diagnose an implicit copy operation for a class which is odr-used, but which is deprecated because th...
static void AddMostOverridenMethods(const CXXMethodDecl *MD, llvm::SmallPtrSetImpl< const CXXMethodDecl * > &Methods)
Add the most overridden methods from MD to Methods.
static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc, const CXXRecordDecl *RD, CXXCastPath &BasePath)
Find the base class to decompose in a built-in decomposition of a class type.
static const void * GetKeyForBase(ASTContext &Context, QualType BaseType)
static QualType BuildStdClassTemplate(Sema &S, ClassTemplateDecl *CTD, QualType TypeParam, SourceLocation Loc)
AllocationOperatorKind
static NamespaceDecl * getNamespaceDecl(NamespaceBaseDecl *D)
getNamespaceDecl - Returns the namespace a decl represents.
static bool isDestroyingDeleteT(QualType Type)
static StmtResult buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, const ExprBuilder &To, const ExprBuilder &From, bool CopyingBaseSubobject, bool Copying, unsigned Depth=0)
Builds a statement that copies/moves the given entity from From to To.
static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S, CXXRecordDecl *Class)
static void AddInitializerToDiag(const Sema::SemaDiagnosticBuilder &Diag, const CXXCtorInitializer *Previous, const CXXCtorInitializer *Current)
static bool BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, ImplicitInitializerKind ImplicitInitKind, CXXBaseSpecifier *BaseSpec, bool IsInheritedVirtualBase, CXXCtorInitializer *&CXXBaseInit)
static bool IsUnusedPrivateField(const FieldDecl *FD)
static void NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set, const QualType &Type)
Recursively add the bases of Type. Don't add Type itself.
static bool CheckConstexprMissingReturn(Sema &SemaRef, const FunctionDecl *Dcl)
static bool CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, SmallVectorImpl< SourceLocation > &ReturnStmts, SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc, SourceLocation &Cxx2bLoc, Sema::CheckConstexprKind Kind)
Check the provided statement is allowed in a constexpr function definition.
static bool functionDeclHasDefaultArgument(const FunctionDecl *FD)
static bool CheckConstexprParameterTypes(Sema &SemaRef, const FunctionDecl *FD, Sema::CheckConstexprKind Kind)
Check whether a function's parameter types are all literal types.
static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext)
Determine whether a using statement is in a context where it will be apply in all contexts.
static const TemplateSpecializationType * GetClassTemplateSpecializationType(ASTContext &Context, QualType T)
static bool checkTupleLikeDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, VarDecl *Src, QualType DecompType, unsigned NumElems)
static void defineDefaultedFunctionWithSynthesizedBody(Sema &S, SourceLocation UseLoc, FunctionDecl *FD, llvm::function_ref< StmtResult(SourceLocation BodyLoc)> BuildBody)
Define a defaulted function whose body is synthesized by BuildBody: a defaulted comparison operator f...
static CXXConstructorDecl * findUserDeclaredCtor(CXXRecordDecl *RD)
static bool checkMemberDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, ValueDecl *Src, QualType DecompType, const CXXRecordDecl *OrigRD)
static bool HasAttribute(const QualType &T)
static bool CheckOperatorNewDeclaration(Sema &SemaRef, FunctionDecl *FnDecl)
static void checkForMultipleExportedDefaultConstructors(Sema &S, CXXRecordDecl *Class)
static bool CheckOperatorNewDeleteTypes(Sema &SemaRef, FunctionDecl *FnDecl, AllocationOperatorKind OperatorKind, CanQualType ExpectedResultType, CanQualType ExpectedSizeOrAddressParamType, unsigned DependentParamTypeDiag, unsigned InvalidParamTypeDiag)
static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, CXXSpecialMemberKind CSM, bool ConstArg, TrivialABIHandling TAH, bool Diagnose)
Check whether the members of a class type allow a special member to be trivial.
static TemplateArgumentLoc getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T)
static void findImplicitlyDeclaredEqualityComparisons(ASTContext &Ctx, CXXRecordDecl *RD, llvm::SmallVectorImpl< FunctionDecl * > &Spaceships)
Find the equality comparison functions that should be implicitly declared in a given class definition...
static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl< const void * > &IdealInits)
static Sema::ImplicitExceptionSpecification ComputeDefaultedPostfixOperatorExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD, PostfixOperatorKind Kind)
ImplicitInitializerKind
ImplicitInitializerKind - How an implicit base or member initializer should initialize its base or me...
@ IIK_Default
@ IIK_Move
@ IIK_Inherit
@ IIK_Copy
static bool ConvertAPValueToString(const APValue &V, QualType T, SmallVectorImpl< char > &Str, ASTContext &Context)
Convert \V to a string we can present to the user in a diagnostic \T is the type of the expression th...
static bool checkArrayDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, ValueDecl *Src, QualType DecompType, const ConstantArrayType *CAT)
static ClassTemplateDecl * LookupStdClassTemplate(Sema &S, SourceLocation Loc, const char *ClassName, bool *WasMalformed)
static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class)
static bool UsefulToPrintExpr(const Expr *E)
Some Expression types are not useful to print notes about, e.g.
static bool FindBaseInitializer(Sema &SemaRef, CXXRecordDecl *ClassDecl, QualType BaseType, const CXXBaseSpecifier *&DirectBaseSpec, const CXXBaseSpecifier *&VirtualBaseSpec)
Find the direct and/or virtual base specifiers that correspond to the given base type,...
static bool checkLiteralOperatorTemplateParameterList(Sema &SemaRef, FunctionTemplateDecl *TpDecl)
static bool ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD, llvm::function_ref< bool(const CXXMethodDecl *)> Report)
Report an error regarding overriding, along with any relevant overridden methods.
static bool CheckBindingsCount(Sema &S, DecompositionDecl *DD, QualType DecompType, ArrayRef< BindingDecl * > Bindings, unsigned MemberCount)
static bool CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl)
static const void * GetKeyForMember(ASTContext &Context, CXXCtorInitializer *Member)
static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy, TemplateArgumentListInfo &Args, const TemplateParameterList *Params)
static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD, Sema::CheckConstexprKind Kind)
Check whether a function's return type is a literal type.
static void DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef, const CXXConstructorDecl *Constructor, ArrayRef< CXXCtorInitializer * > Inits)
static Sema::ImplicitExceptionSpecification computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD)
static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T)
Determine whether the given type is an incomplete or zero-lenfgth array type.
static void MarkFieldDestructorReferenced(Sema &S, SourceLocation Location, FieldDecl *Field)
TrivialSubobjectKind
The kind of subobject we are checking for triviality.
@ TSK_CompleteObject
The object is actually the complete object.
@ TSK_Field
The subobject is a non-static data member.
@ TSK_BaseClass
The subobject is a base class.
static bool hasOneRealArgument(MultiExprArg Args)
Determine whether the given list arguments contains exactly one "real" (non-default) argument.
static StmtResult buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, const ExprBuilder &ToB, const ExprBuilder &FromB)
When generating a defaulted copy or move assignment operator, if a field should be copied with __buil...
static QualType IgnorePackIndexing(QualType T)
static bool isStdClassTemplate(Sema &S, QualType SugaredType, QualType *TypeArg, const char *ClassName, ClassTemplateDecl **CachedDecl, const Decl **MalformedDecl)
static bool canCopyAndDestroyForDefaultedPostfixOperator(Sema &S, FunctionDecl *FD, CXXRecordDecl *RD, QualType C, Expr *Obj, bool Diagnose, llvm::function_ref< void(const FunctionDecl *)> CheckConstexpr)
Determine whether the implicit definition of the defaulted postfix increment or decrement operator fu...
static QualType getPostfixOperatorFirstParamType(const FunctionDecl *FD)
Get the type of the first parameter of a postfix increment or decrement operator function,...
static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD, SourceLocation DefaultLoc)
static bool BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, ImplicitInitializerKind ImplicitInitKind, FieldDecl *Field, IndirectFieldDecl *Indirect, CXXCtorInitializer *&CXXMemberInit)
static DefaultedPostfixOperatorInfo analyzeDefaultedPostfixOperator(Sema &S, FunctionDecl *FD, PostfixOperatorKind Kind, QualType C, bool Diagnose)
Determine whether a defaulted postfix increment or decrement operator function for type C should be d...
static void MarkBaseDestructorsReferenced(Sema &S, SourceLocation Location, CXXRecordDecl *ClassDecl)
static bool CheckMemberDecompositionFields(Sema &S, SourceLocation Loc, const CXXRecordDecl *OrigRD, QualType DecompType, DeclAccessPair BasePair)
static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, FieldDecl *Field, IndirectFieldDecl *Indirect=nullptr)
static CXXBaseSpecifier * findDirectBaseWithType(CXXRecordDecl *Derived, QualType DesiredBase, bool &AnyDependentBases)
Find the base specifier for a base class with the given type.
static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(Sema &S, CXXRecordDecl *Class, CXXSpecialMemberKind CSM, unsigned FieldQuals, bool ConstRHS)
Look up the special member function that would be called by a special member function for a subobject...
static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, bool ConstArg, CXXConstructorDecl *InheritedCtor=nullptr, Sema::InheritedConstructorInfo *Inherited=nullptr)
Determine whether the specified special member function would be constexpr if it were implicitly defi...
static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, QualType SubType, bool ConstRHS, CXXSpecialMemberKind CSM, TrivialSubobjectKind Kind, TrivialABIHandling TAH, bool Diagnose)
Check whether the special member selected for a given type would be trivial.
static void DiagnoseInvisibleNamespace(const TypoCorrection &Corrected, Sema &S)
static StmtResult buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, const ExprBuilder &To, const ExprBuilder &From, bool CopyingBaseSubobject, bool Copying)
static Sema::ImplicitExceptionSpecification computeExceptionSpecFromSynthesizedBody(Sema &S, SourceLocation Loc, FunctionDecl *FD, llvm::function_ref< StmtResult(SourceLocation BodyLoc)> BuildBody)
Compute the exception specification of a defaulted function whose body is synthesized by BuildBody: a...
static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, CXXMethodDecl *MD)
static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc, unsigned I, QualType T)
static Sema::ImplicitExceptionSpecification ComputeDefaultedSpecialMemberExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD, CXXSpecialMemberKind CSM, Sema::InheritedConstructorInfo *ICI)
static QualType getStdTrait(Sema &S, SourceLocation Loc, StringRef Trait, TemplateArgumentListInfo &Args, unsigned DiagID)
static bool checkComplexDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, ValueDecl *Src, QualType DecompType, const ComplexType *CT)
static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, CXXScopeSpec &SS, SourceLocation IdentLoc, IdentifierInfo *Ident)
static bool InitializationHasSideEffects(const FieldDecl &FD)
static bool CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, const FunctionDecl *FnDecl)
static bool checkArrayLikeDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, ValueDecl *Src, QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType)
static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, DeclStmt *DS, SourceLocation &Cxx1yLoc, Sema::CheckConstexprKind Kind)
Check the given declaration statement is legal within a constexpr function body.
static bool IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2)
Determine whether a using declaration considers the given declarations as "equivalent",...
static TemplateArgumentLoc getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T, uint64_t I)
static void DiagnoseDependentFriendNotMember(Sema &S, SourceLocation Loc, NestedNameSpecifier NNS)
static bool CheckConstexprDestructorSubobjects(Sema &SemaRef, const CXXDestructorDecl *DD, Sema::CheckConstexprKind Kind)
Determine whether a destructor cannot be constexpr due to.
static bool isProvablyNotDerivedFrom(Sema &SemaRef, CXXRecordDecl *Record, const BaseSet &Bases)
Determines if the given class is provably not derived from all of the prospective base classes.
This file declares semantic analysis for Objective-C.
This file declares semantic analysis for OpenMP constructs and clauses.
static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, QualType T, APValue &Value, CCEKind CCE, bool RequireInt, NamedDecl *Dest)
CheckConvertedConstantExpression - Check that the expression From is a converted constant expression ...
static void MarkUsedTemplateParameters(ASTContext &Ctx, const TemplateArgument &TemplateArg, bool OnlyDeduced, unsigned Depth, llvm::SmallBitVector &Used)
Mark the template parameters that are used by this template argument.
static void collectUnexpandedParameterPacks(Sema &S, TemplateParameterList *Params, SmallVectorImpl< UnexpandedParameterPack > &Unexpanded)
static bool DiagnoseUnexpandedParameterPacks(Sema &S, TemplateTemplateParmDecl *TTP)
Check for unexpanded parameter packs within the template parameters of a template template parameter,...
static bool isInvalid(LocType Loc, bool *Invalid)
Defines various enumerations that describe declaration and type specifiers.
static QualType getPointeeType(const MemRegion *R)
Defines the clang::TypeLoc interface and its subclasses.
Allows QualTypes to be sorted and hence used in maps and sets.
__DEVICE__ void * memcpy(void *__a, const void *__b, size_t __c)
std::pair< CXXConstructorDecl *, bool > findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const
Find the constructor to use for inherited construction of a base class, and whether that base class c...
InheritedConstructorInfo(Sema &S, SourceLocation UseLoc, ConstructorUsingShadowDecl *Shadow)
a trap message and trap category.
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:158
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition ASTConcept.h:75
virtual bool HandleTopLevelDecl(DeclGroupRef D)
HandleTopLevelDecl - Handle the specified top-level declaration.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:245
const ConstantArrayType * getAsConstantArrayType(QualType T) const
static CanQualType getCanonicalType(QualType T)
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
DeclarationNameTable DeclarationNames
Definition ASTContext.h:859
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
CanQualType VoidPtrTy
CanQualType DependentTy
IdentifierTable & Idents
Definition ASTContext.h:855
const LangOptions & getLangOpts() const
QualType getConstType(QualType T) const
Return the uniqued reference to the type for a const qualified type.
CallingConv getDefaultCallingConvention(bool IsVariadic, bool IsCXXMethod) const
Retrieves the default calling convention for the current context.
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
ComparisonCategories CompCategories
Types and expressions required to build C++2a three-way comparisons using operator<=>,...
CanQualType BoolTy
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
CanQualType CharTy
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
const clang::PrintingPolicy & getPrintingPolicy() const
Definition ASTContext.h:908
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
QualType getTypeDeclType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const TypeDecl *Decl) const
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
CanQualType BuiltinFnTy
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
CanQualType VoidTy
QualType getPackExpansionType(QualType Pattern, UnsignedOrNone NumExpansions, bool ExpectPackInType=true) const
Form a pack expansion type with the given pattern.
static bool hasSameType(QualType T1, QualType T2)
Determine whether the given types T1 and T2 are equivalent.
llvm::APSInt MakeIntValue(uint64_t Value, QualType Type) const
Make an APSInt of the appropriate width and signedness for the given Value and integer Type.
QualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:974
CanQualType getCanonicalTagType(const TagDecl *TD) const
static bool hasSameUnqualifiedType(QualType T1, QualType T2)
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
An abstract interface that should be implemented by listeners that want to be notified when an AST en...
Represents an access specifier followed by colon ':'.
Definition DeclCXX.h:86
static AccessSpecDecl * Create(ASTContext &C, AccessSpecifier AS, DeclContext *DC, SourceLocation ASLoc, SourceLocation ColonLoc)
Definition DeclCXX.h:117
bool isUnset() const
Definition Ownership.h:168
PtrTy get() const
Definition Ownership.h:171
bool isInvalid() const
Definition Ownership.h:167
bool isUsable() const
Definition Ownership.h:169
TypeLoc getElementLoc() const
Definition TypeLoc.h:1838
QualType getElementType() const
Definition TypeBase.h:3832
Attr - This represents one attribute.
Definition Attr.h:47
attr::Kind getKind() const
Definition Attr.h:93
bool isInherited() const
Definition Attr.h:102
Attr * clone(ASTContext &C) const
SourceLocation getLocation() const
Definition Attr.h:100
Represents a C++ declaration that introduces decls from somewhere else.
Definition DeclCXX.h:3543
unsigned shadow_size() const
Return the number of shadowed declarations associated with this using declaration.
Definition DeclCXX.h:3621
void addShadowDecl(UsingShadowDecl *S)
Definition DeclCXX.cpp:3516
shadow_iterator shadow_begin() const
Definition DeclCXX.h:3613
void removeShadowDecl(UsingShadowDecl *S)
Definition DeclCXX.cpp:3525
Expr * getLHS() const
Definition Expr.h:4157
Expr * getRHS() const
Definition Expr.h:4159
static BinaryOperator * Create(const ASTContext &C, Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy, ExprValueKind VK, ExprObjectKind OK, SourceLocation opLoc, FPOptionsOverride FPFeatures)
Definition Expr.cpp:5144
static bool isCompoundAssignmentOp(Opcode Opc)
Definition Expr.h:4248
Opcode getOpcode() const
Definition Expr.h:4152
static Opcode getOverloadedOpcode(OverloadedOperatorKind OO)
Retrieve the binary opcode that corresponds to the given overloaded operator.
Definition Expr.cpp:2179
A binding in a decomposition declaration.
Definition DeclCXX.h:4232
void setDecomposedDecl(DecompositionDecl *Decomposed)
Set the decomposed variable for this BindingDecl.
Definition DeclCXX.h:4276
static BindingDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation IdLoc, IdentifierInfo *Id, QualType T)
Definition DeclCXX.cpp:3707
void setBinding(QualType DeclaredType, Expr *Binding)
Set the binding for this BindingDecl, along with its declared type (which should be a possibly-cv-qua...
Definition DeclCXX.h:4270
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition Expr.h:6758
Wrapper for source info for block pointers.
Definition TypeLoc.h:1557
This class is used for builtin types like 'int'.
Definition TypeBase.h:3245
Kind getKind() const
Definition TypeBase.h:3299
Represents a path from a specific derived class (which is not represented as part of the path) to a p...
DeclContext::lookup_iterator Decls
The declarations found inside this base class subobject.
AccessSpecifier Access
The access along this inheritance path.
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
const CXXRecordDecl * getOrigin() const
Retrieve the type from which this base-paths search began.
CXXBasePath & front()
bool isRecordingPaths() const
Whether we are recording paths.
void setRecordingPaths(bool RP)
Specify whether we should be recording paths or not.
void setOrigin(const CXXRecordDecl *Rec)
void clear()
Clear the base-paths results.
bool isAmbiguous(CanQualType BaseType) const
Determine whether the path from the most-derived type to the given base type is ambiguous (i....
Represents a base class of a C++ class.
Definition DeclCXX.h:146
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclCXX.h:194
bool isVirtual() const
Determines whether the base class is a virtual base class (or not).
Definition DeclCXX.h:203
QualType getType() const
Retrieves the type of the base class.
Definition DeclCXX.h:249
SourceRange getSourceRange() const LLVM_READONLY
Retrieves the source range that contains the entire base specifier.
Definition DeclCXX.h:193
AccessSpecifier getAccessSpecifier() const
Returns the access specifier for this base specifier.
Definition DeclCXX.h:230
A boolean literal, per ([C++ lex.bool] Boolean literals).
Definition ExprCXX.h:728
CXXCatchStmt - This represents a C++ catch block.
Definition StmtCXX.h:29
Represents a call to a C++ constructor.
Definition ExprCXX.h:1553
static CXXConstructExpr * Create(const ASTContext &Ctx, QualType Ty, SourceLocation Loc, CXXConstructorDecl *Ctor, bool Elidable, ArrayRef< Expr * > Args, bool HadMultipleCandidates, bool ListInitialization, bool StdInitListInitialization, bool ZeroInitialization, CXXConstructionKind ConstructKind, SourceRange ParenOrBraceRange)
Create a C++ construction expression.
Definition ExprCXX.cpp:1212
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition ExprCXX.h:1696
bool isImmediateEscalating() const
Definition ExprCXX.h:1711
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition ExprCXX.h:1616
Represents a C++ constructor within a class.
Definition DeclCXX.h:2645
CXXConstructorDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:2899
bool isMoveConstructor(unsigned &TypeQuals) const
Determine whether this constructor is a move constructor (C++11 [class.copy]p3), which can be used to...
Definition DeclCXX.cpp:3063
init_iterator init_begin()
Retrieve an iterator to the first initializer.
Definition DeclCXX.h:2760
CXXConstructorDecl * getTargetConstructor() const
When this constructor delegates to another, retrieve the target.
Definition DeclCXX.cpp:3040
bool isCopyConstructor(unsigned &TypeQuals) const
Whether this constructor is a copy constructor (C++ [class.copy]p2, which can be used to copy the cla...
Definition DeclCXX.cpp:3058
void setCtorClosureDefaultArgs(ArrayRef< CXXDefaultArgExpr * > Args)
Definition DeclCXX.cpp:3143
InheritedConstructor getInheritedConstructor() const
Get the constructor that this inheriting constructor is based on.
Definition DeclCXX.h:2894
static CXXConstructorDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, ExplicitSpecifier ES, bool UsesFPIntrin, bool isInline, bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind, InheritedConstructor Inherited=InheritedConstructor(), const AssociatedConstraint &TrailingRequiresClause={})
Definition DeclCXX.cpp:3018
ArrayRef< CXXDefaultArgExpr * > getCtorClosureDefaultArgs() const
Definition DeclCXX.cpp:3139
ExplicitSpecifier getExplicitSpecifier() const
Definition DeclCXX.h:2738
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2994
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition DeclCXX.h:3030
Represents a C++ base or member initializer.
Definition DeclCXX.h:2410
bool isWritten() const
Determine whether this initializer is explicitly written in the source code.
Definition DeclCXX.h:2582
SourceRange getSourceRange() const LLVM_READONLY
Determine the source range covering the entire initializer.
Definition DeclCXX.cpp:2966
SourceLocation getSourceLocation() const
Determine the source location of the initializer.
Definition DeclCXX.cpp:2953
bool isAnyMemberInitializer() const
Definition DeclCXX.h:2490
TypeSourceInfo * getTypeSourceInfo() const
Returns the declarator information for a base class or delegating initializer.
Definition DeclCXX.h:2544
FieldDecl * getAnyMember() const
Definition DeclCXX.h:2556
A default argument (C++ [dcl.fct.default]).
Definition ExprCXX.h:1275
Represents a C++ destructor within a class.
Definition DeclCXX.h:2924
static CXXDestructorDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, bool UsesFPIntrin, bool isInline, bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind, const AssociatedConstraint &TrailingRequiresClause={})
Definition DeclCXX.cpp:3158
const FunctionDecl * getOperatorDelete() const
Definition DeclCXX.cpp:3230
A mapping from each virtual member function to its set of final overriders.
Represents a call to an inherited base class constructor from an inheriting constructor.
Definition ExprCXX.h:1756
Represents a call to a member function that may be written either with member call syntax (e....
Definition ExprCXX.h:184
CXXMethodDecl * getMethodDecl() const
Retrieve the declaration of the called method.
Definition ExprCXX.cpp:773
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2153
bool isExplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An explicit object member function is a non-static member function with an explic...
Definition DeclCXX.cpp:2719
bool isVirtual() const
Definition DeclCXX.h:2208
CXXSpecialMemberKind getSpecialMemberKind() const
Definition DeclCXX.h:2232
static CXXMethodDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin, bool isInline, ConstexprSpecKind ConstexprKind, SourceLocation EndLocation, const AssociatedConstraint &TrailingRequiresClause={})
Definition DeclCXX.cpp:2504
unsigned getNumExplicitParams() const
Definition DeclCXX.h:2324
CXXMethodDecl * getMostRecentDecl()
Definition DeclCXX.h:2273
overridden_method_range overridden_methods() const
Definition DeclCXX.cpp:2828
unsigned size_overridden_methods() const
Definition DeclCXX.cpp:2822
method_iterator begin_overridden_methods() const
Definition DeclCXX.cpp:2812
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2296
bool isInstance() const
Definition DeclCXX.h:2180
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition DeclCXX.cpp:2751
QualType getFunctionObjectParameterType() const
Definition DeclCXX.h:2320
bool isStatic() const
Definition DeclCXX.cpp:2417
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:2266
The null pointer literal (C++11 [lex.nullptr])
Definition ExprCXX.h:773
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
bool hasConstexprDefaultConstructor() const
Determine whether this class has a constexpr default constructor.
Definition DeclCXX.h:1286
friend_range friends() const
Definition DeclFriend.h:183
bool hasTrivialMoveAssignment() const
Determine whether this class has a trivial move assignment operator (C++11 [class....
Definition DeclCXX.h:1357
bool isTriviallyCopyable() const
Determine whether this class is considered trivially copyable per (C++11 [class]p6).
Definition DeclCXX.cpp:613
bool hasTrivialDefaultConstructor() const
Determine whether this class has a trivial default constructor (C++11 [class.ctor]p5).
Definition DeclCXX.h:1256
bool isGenericLambda() const
Determine whether this class describes a generic lambda function object (i.e.
Definition DeclCXX.cpp:1681
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
Definition DeclCXX.h:1382
bool hasUserDeclaredDestructor() const
Determine whether this class has a user-declared destructor.
Definition DeclCXX.h:1011
bool implicitCopyConstructorHasConstParam() const
Determine whether an implicit copy constructor for this type would have a parameter with a const-qual...
Definition DeclCXX.h:827
bool defaultedDestructorIsDeleted() const
true if a defaulted destructor for this class would be deleted.
Definition DeclCXX.h:719
bool hasInheritedAssignment() const
Determine whether this class has a using-declaration that names a base class assignment operator.
Definition DeclCXX.h:1436
bool allowConstDefaultInit() const
Determine whether declaring a const variable with this type is ok per core issue 253.
Definition DeclCXX.h:1407
bool hasTrivialDestructorForCall() const
Definition DeclCXX.h:1386
bool defaultedMoveConstructorIsDeleted() const
true if a defaulted move constructor for this class would be deleted.
Definition DeclCXX.h:711
bool isLiteral() const
Determine whether this class is a literal type.
Definition DeclCXX.cpp:1508
bool hasUserDeclaredMoveAssignment() const
Determine whether this class has had a move assignment declared by the user.
Definition DeclCXX.h:970
bool defaultedDestructorIsConstexpr() const
Determine whether a defaulted default constructor for this class would be constexpr.
Definition DeclCXX.h:1372
base_class_range bases()
Definition DeclCXX.h:609
bool hasAnyDependentBases() const
Determine whether this class has any dependent base classes which are not the current instantiation.
Definition DeclCXX.cpp:606
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition DeclCXX.h:1028
bool hasTrivialMoveConstructor() const
Determine whether this class has a trivial move constructor (C++11 [class.copy]p12)
Definition DeclCXX.h:1317
bool needsImplicitDefaultConstructor() const
Determine if we need to declare a default constructor for this class.
Definition DeclCXX.h:771
bool needsImplicitMoveConstructor() const
Determine whether this class should get an implicit move constructor or if any existing special membe...
Definition DeclCXX.h:899
bool hasUserDeclaredCopyAssignment() const
Determine whether this class has a user-declared copy assignment operator.
Definition DeclCXX.h:918
bool isProvablyNotDerivedFrom(const CXXRecordDecl *Base) const
Determine whether this class is provably not derived from the type Base.
method_range methods() const
Definition DeclCXX.h:651
CXXRecordDecl * getDefinition() const
Definition DeclCXX.h:549
bool needsOverloadResolutionForCopyAssignment() const
Determine whether we need to eagerly declare a defaulted copy assignment operator for this class.
Definition DeclCXX.h:940
static AccessSpecifier MergeAccess(AccessSpecifier PathAccess, AccessSpecifier DeclAccess)
Calculates the access of a decl that is reached along a path.
Definition DeclCXX.h:1745
bool defaultedDefaultConstructorIsConstexpr() const
Determine whether a defaulted default constructor for this class would be constexpr.
Definition DeclCXX.h:1279
bool hasTrivialCopyConstructor() const
Determine whether this class has a trivial copy constructor (C++ [class.copy]p6, C++11 [class....
Definition DeclCXX.h:1294
void setImplicitMoveAssignmentIsDeleted()
Set that we attempted to declare an implicit move assignment operator, but overload resolution failed...
Definition DeclCXX.h:982
bool hasConstexprDestructor() const
Determine whether this class has a constexpr destructor.
Definition DeclCXX.cpp:601
bool isPolymorphic() const
Whether this class is polymorphic (C++ [class.virtual]), which means that the class contains or inher...
Definition DeclCXX.h:1224
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition DeclCXX.h:603
bool defaultedCopyConstructorIsDeleted() const
true if a defaulted copy constructor for this class would be deleted.
Definition DeclCXX.h:702
bool hasTrivialCopyConstructorForCall() const
Definition DeclCXX.h:1298
bool lookupInBases(BaseMatchesCallback BaseMatches, CXXBasePaths &Paths, bool LookupInDependent=false) const
Look for entities within the base classes of this C++ class, transitively searching all base class su...
bool lambdaIsDefaultConstructibleAndAssignable() const
Determine whether this lambda should have an implicit default constructor and copy and move assignmen...
Definition DeclCXX.cpp:732
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine whether this particular class is a specialization or instantiation of a class template or m...
Definition DeclCXX.cpp:2062
bool hasTrivialCopyAssignment() const
Determine whether this class has a trivial copy assignment operator (C++ [class.copy]p11,...
Definition DeclCXX.h:1344
base_class_range vbases()
Definition DeclCXX.h:626
base_class_iterator vbases_begin()
Definition DeclCXX.h:633
ctor_range ctors() const
Definition DeclCXX.h:671
void setImplicitMoveConstructorIsDeleted()
Set that we attempted to declare an implicit move constructor, but overload resolution failed so we d...
Definition DeclCXX.h:874
bool isAbstract() const
Determine whether this class has a pure virtual function.
Definition DeclCXX.h:1231
bool hasVariantMembers() const
Determine whether this class has any variant members.
Definition DeclCXX.h:1246
void setImplicitCopyConstructorIsDeleted()
Set that we attempted to declare an implicit copy constructor, but overload resolution failed so we d...
Definition DeclCXX.h:865
bool isDynamicClass() const
Definition DeclCXX.h:575
bool hasInClassInitializer() const
Whether this class has any in-class initializers for non-static data members (including those in anon...
Definition DeclCXX.h:1158
bool needsImplicitCopyConstructor() const
Determine whether this class needs an implicit copy constructor to be lazily declared.
Definition DeclCXX.h:805
bool hasIrrelevantDestructor() const
Determine whether this class has a destructor which has no semantic effect.
Definition DeclCXX.h:1418
bool hasNonTrivialCopyConstructorForCall() const
Definition DeclCXX.h:1309
bool hasDirectFields() const
Determine whether this class has direct non-static data members.
Definition DeclCXX.h:1210
bool hasUserDeclaredCopyConstructor() const
Determine whether this class has a user-declared copy constructor.
Definition DeclCXX.h:799
bool hasDefinition() const
Definition DeclCXX.h:562
void setImplicitCopyAssignmentIsDeleted()
Set that we attempted to declare an implicit copy assignment operator, but overload resolution failed...
Definition DeclCXX.h:924
bool needsImplicitDestructor() const
Determine whether this class needs an implicit destructor to be lazily declared.
Definition DeclCXX.h:1017
ClassTemplateDecl * getDescribedClassTemplate() const
Retrieves the class template that is described by this class declaration.
Definition DeclCXX.cpp:2054
void getFinalOverriders(CXXFinalOverriderMap &FinaOverriders) const
Retrieve the final overriders for each virtual member function in the class hierarchy where this clas...
bool needsOverloadResolutionForMoveConstructor() const
Determine whether we need to eagerly declare a defaulted move constructor for this class.
Definition DeclCXX.h:910
bool isInjectedClassName() const
Determines whether this declaration represents the injected class name.
Definition DeclCXX.cpp:2154
bool needsOverloadResolutionForMoveAssignment() const
Determine whether we need to eagerly declare a move assignment operator for this class.
Definition DeclCXX.h:1004
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
Definition DeclCXX.cpp:2129
bool hasNonTrivialDestructorForCall() const
Definition DeclCXX.h:1396
bool needsOverloadResolutionForDestructor() const
Determine whether we need to eagerly declare a destructor for this class.
Definition DeclCXX.h:1023
bool hasInheritedConstructor() const
Determine whether this class has a using-declaration that names a user-declared base class constructo...
Definition DeclCXX.h:1430
CXXMethodDecl * getLambdaStaticInvoker() const
Retrieve the lambda static invoker, the address of which is returned by the conversion operator,...
Definition DeclCXX.cpp:1756
bool needsOverloadResolutionForCopyConstructor() const
Determine whether we need to eagerly declare a defaulted copy constructor for this class.
Definition DeclCXX.h:812
CXXRecordDecl * getDefinitionOrSelf() const
Definition DeclCXX.h:556
bool hasUserDeclaredMoveConstructor() const
Determine whether this class has had a move constructor declared by the user.
Definition DeclCXX.h:853
bool needsImplicitMoveAssignment() const
Determine whether this class should get an implicit move assignment operator or if any existing speci...
Definition DeclCXX.h:992
bool needsImplicitCopyAssignment() const
Determine whether this class needs an implicit copy assignment operator to be lazily declared.
Definition DeclCXX.h:933
bool hasTrivialMoveConstructorForCall() const
Definition DeclCXX.h:1322
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition DeclCXX.cpp:1744
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:523
unsigned getNumVBases() const
Retrieves the number of virtual base classes of this class.
Definition DeclCXX.h:624
bool isDerivedFrom(const CXXRecordDecl *Base) const
Determine whether this class is derived from the class Base.
bool implicitCopyAssignmentHasConstParam() const
Determine whether an implicit copy assignment operator for this type would have a parameter with a co...
Definition DeclCXX.h:955
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:77
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition DeclSpec.h:184
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition DeclSpec.h:189
void MakeTrivial(ASTContext &Context, NestedNameSpecifier Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
Definition DeclSpec.cpp:97
SourceRange getRange() const
Definition DeclSpec.h:83
SourceLocation getBeginLoc() const
Definition DeclSpec.h:87
bool isSet() const
Deprecated.
Definition DeclSpec.h:202
NestedNameSpecifier getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition DeclSpec.h:98
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
Definition DeclSpec.cpp:123
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition DeclSpec.h:187
bool isEmpty() const
No scope specifier.
Definition DeclSpec.h:182
Represents the this expression in C++.
Definition ExprCXX.h:1159
SourceLocation getBeginLoc() const
Definition ExprCXX.h:1179
bool isImplicit() const
Definition ExprCXX.h:1182
SourceLocation getLocation() const
Definition ExprCXX.h:1176
CXXTryStmt - A C++ try block, including all handlers.
Definition StmtCXX.h:70
CXXCatchStmt * getHandler(unsigned i)
Definition StmtCXX.h:109
unsigned getNumHandlers() const
Definition StmtCXX.h:108
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:3012
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3216
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3195
bool isCallToStdMove() const
Definition Expr.cpp:3682
Expr * getCallee()
Definition Expr.h:3159
arg_range arguments()
Definition Expr.h:3264
QualType withConst() const
Retrieves a version of this type with const applied.
CastKind getCastKind() const
Definition Expr.h:3789
Expr * getSubExpr()
Definition Expr.h:3795
static CharSourceRange getTokenRange(SourceRange R)
QuantityType getQuantity() const
Get the raw integer representation of this quantity.
Definition CharUnits.h:155
Declaration of a class template.
CXXRecordDecl * getTemplatedDecl() const
Get the underlying class declarations of the template.
Represents a class template specialization, which refers to a class template with a given set of temp...
TemplateSpecializationKind getSpecializationKind() const
Determine the kind of specialization that this declaration represents.
ClassTemplateDecl * getSpecializedTemplate() const
Retrieve the template that this specialization specializes.
SourceLocation getPointOfInstantiation() const
Get the point of instantiation (if any), or null if none.
const ComparisonCategoryInfo * lookupInfoForType(QualType Ty) const
static StringRef getCategoryString(ComparisonCategoryType Kind)
static StringRef getResultString(ComparisonCategoryResult Kind)
static std::vector< ComparisonCategoryResult > getPossibleResultsForType(ComparisonCategoryType Type)
Return the list of results which are valid for the specified comparison category type.
const CXXRecordDecl * Record
The declaration for the comparison category type from the standard library.
ComparisonCategoryType Kind
The Kind of the comparison category type.
Complex values, per C99 6.2.5p11.
Definition TypeBase.h:3362
QualType getElementType() const
Definition TypeBase.h:3372
static CompoundStmt * Create(const ASTContext &C, ArrayRef< Stmt * > Stmts, FPOptionsOverride FPFeatures, SourceLocation LB, SourceLocation RB)
Definition Stmt.cpp:399
ConstStmtVisitor - This class implements a simple visitor for Stmt subclasses.
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3858
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3914
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition ASTConcept.h:47
Represents a shadow constructor declaration introduced into a class by a C++11 using-declaration that...
Definition DeclCXX.h:3724
const CXXRecordDecl * getParent() const
Returns the parent of this using shadow declaration, which is the class in which this is declared.
Definition DeclCXX.h:3788
static ConstructorUsingShadowDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation Loc, UsingDecl *Using, NamedDecl *Target, bool IsVirtual)
Definition DeclCXX.cpp:3498
SourceLocation getBeginLoc() const LLVM_READONLY
Definition ExprCXX.h:5402
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
A POD class for pairing a NamedDecl* with an access specifier.
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
NamedDecl * getDecl() const
AccessSpecifier getAccess() const
The results of name lookup within a DeclContext.
Definition DeclBase.h:1400
DeclListNode::iterator iterator
Definition DeclBase.h:1410
specific_decl_iterator - Iterates over a subrange of declarations stored in a DeclContext,...
Definition DeclBase.h:2427
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1467
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2110
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition DeclBase.h:2263
lookup_result::iterator lookup_iterator
Definition DeclBase.h:2612
bool isFileContext() const
Definition DeclBase.h:2201
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
bool InEnclosingNamespaceSetOf(const DeclContext *NS) const
Test if this context is part of the enclosing namespace set of the context NS, as defined in C++0x [n...
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
bool isTranslationUnit() const
Definition DeclBase.h:2206
bool isRecord() const
Definition DeclBase.h:2210
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
void removeDecl(Decl *D)
Removes a declaration from this context.
void addDecl(Decl *D)
Add the declaration D into this context.
decl_iterator decls_end() const
Definition DeclBase.h:2409
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition DeclBase.h:2407
bool isFunctionOrMethod() const
Returns true if this DeclContext is a function, Objective-C method, or block, or a DeclContext that c...
Definition DeclBase.h:2165
const LinkageSpecDecl * getExternCContext() const
Retrieve the nearest enclosing C linkage specification context.
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context semantically encloses the declaration context DC.
Decl::Kind getDeclKind() const
Definition DeclBase.h:2103
DeclContext * getNonTransparentContext()
decl_iterator decls_begin() const
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1315
static DeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *D, bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc, QualType T, ExprValueKind VK, NamedDecl *FoundD=nullptr, const TemplateArgumentListInfo *TemplateArgs=nullptr, NonOdrUseReason NOUR=NOUR_None)
Definition Expr.cpp:498
ValueDecl * getDecl()
Definition Expr.h:1383
NonOdrUseReason isNonOdrUse() const
Is this expression a non-odr-use reference, and if so, why?
Definition Expr.h:1513
SourceLocation getBeginLoc() const
Definition Expr.h:1394
bool isImmediateEscalating() const
Definition Expr.h:1523
Captures information about "declaration specifiers".
Definition DeclSpec.h:284
bool isVirtualSpecified() const
Definition DeclSpec.h:725
bool isModulePrivateSpecified() const
Definition DeclSpec.h:906
bool hasTypeSpecifier() const
Return true if any type-specifier has been found.
Definition DeclSpec.h:768
bool SetStorageClassSpec(Sema &S, SCS SC, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
These methods set the specified attribute of the DeclSpec and return false if there was no error.
Definition DeclSpec.cpp:637
ThreadStorageClassSpecifier TSCS
Definition DeclSpec.h:301
void ClearStorageClassSpecs()
Definition DeclSpec.h:570
TST getTypeSpecType() const
Definition DeclSpec.h:592
SourceLocation getStorageClassSpecLoc() const
Definition DeclSpec.h:565
SCS getStorageClassSpec() const
Definition DeclSpec.h:556
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:630
SourceRange getSourceRange() const LLVM_READONLY
Definition DeclSpec.h:629
unsigned getTypeQualifiers() const
getTypeQualifiers - Return a set of TQs.
Definition DeclSpec.h:672
SourceLocation getExplicitSpecLoc() const
Definition DeclSpec.h:731
SourceLocation getFriendSpecLoc() const
Definition DeclSpec.h:904
ParsedType getRepAsType() const
Definition DeclSpec.h:602
TSCS getThreadStorageClassSpec() const
Definition DeclSpec.h:557
bool isFriendSpecifiedFirst() const
Definition DeclSpec.h:902
ParsedAttributes & getAttributes()
Definition DeclSpec.h:950
SourceLocation getConstSpecLoc() const
Definition DeclSpec.h:673
SourceRange getExplicitSpecRange() const
Definition DeclSpec.h:732
Expr * getRepAsExpr() const
Definition DeclSpec.h:610
bool isInlineSpecified() const
Definition DeclSpec.h:714
SourceLocation getRestrictSpecLoc() const
Definition DeclSpec.h:674
TypeSpecifierType TST
Definition DeclSpec.h:314
bool SetTypeQual(TQ T, SourceLocation Loc)
void ClearConstexprSpec()
Definition DeclSpec.h:918
static const char * getSpecifierName(DeclSpec::TST T, const PrintingPolicy &Policy)
Turn a type-specifier-type into a string like "_Bool" or "union".
Definition DeclSpec.cpp:534
SourceLocation getThreadStorageClassSpecLoc() const
Definition DeclSpec.h:566
SourceLocation getAtomicSpecLoc() const
Definition DeclSpec.h:676
SourceLocation getVirtualSpecLoc() const
Definition DeclSpec.h:726
SourceLocation getConstexprSpecLoc() const
Definition DeclSpec.h:913
SourceLocation getTypeSpecTypeLoc() const
Definition DeclSpec.h:637
void forEachQualifier(llvm::function_ref< void(TQ, StringRef, SourceLocation)> Handle)
This method calls the passed in handler on each qual being set.
Definition DeclSpec.cpp:429
SourceLocation getInlineSpecLoc() const
Definition DeclSpec.h:717
SourceLocation getUnalignedSpecLoc() const
Definition DeclSpec.h:677
SourceLocation getVolatileSpecLoc() const
Definition DeclSpec.h:675
FriendSpecified isFriendSpecified() const
Definition DeclSpec.h:898
bool hasExplicitSpecifier() const
Definition DeclSpec.h:728
bool hasConstexprSpecifier() const
Definition DeclSpec.h:914
static const TST TST_auto
Definition DeclSpec.h:355
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Definition Stmt.h:1642
decl_range decls()
Definition Stmt.h:1690
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.h:1668
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
Decl * getPreviousDecl()
Retrieve the previous declaration that declares the same entity as this declaration,...
Definition DeclBase.h:1079
bool isInStdNamespace() const
Definition DeclBase.cpp:453
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclBase.h:444
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition DeclBase.h:1244
T * getAttr() const
Definition DeclBase.h:582
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:550
void addAttr(Attr *A)
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:602
virtual bool isOutOfLine() const
Determine whether this declaration is declared out of line (outside its semantic context).
Definition Decl.cpp:101
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition DeclBase.cpp:178
Kind
Lists the kind of concrete classes of Decl.
Definition DeclBase.h:89
void markUsed(ASTContext &C)
Mark the declaration used, in the sense of odr-use.
Definition DeclBase.cpp:602
@ FOK_Undeclared
A friend of a previously-undeclared entity.
Definition DeclBase.h:1237
@ FOK_None
Not a friend object.
Definition DeclBase.h:1235
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition DeclBase.cpp:273
bool isTemplateParameter() const
isTemplateParameter - Determines whether this declaration is a template parameter.
Definition DeclBase.h:2809
DeclContext * getNonTransparentDeclContext()
Return the non transparent context.
bool isInvalidDecl() const
Definition DeclBase.h:597
unsigned getIdentifierNamespace() const
Definition DeclBase.h:907
bool isLocalExternDecl() const
Determine whether this is a block-scope declaration with linkage.
Definition DeclBase.h:1187
void setAccess(AccessSpecifier AS)
Definition DeclBase.h:511
SourceLocation getLocation() const
Definition DeclBase.h:448
@ IDNS_Ordinary
Ordinary names.
Definition DeclBase.h:144
bool isTemplateParameterPack() const
isTemplateParameter - Determines whether this declaration is a template parameter pack.
Definition DeclBase.cpp:256
void setLocalOwningModule(Module *M)
Definition DeclBase.h:842
void setImplicit(bool I=true)
Definition DeclBase.h:603
void setReferenced(bool R=true)
Definition DeclBase.h:632
DeclContext * getDeclContext()
Definition DeclBase.h:457
AccessSpecifier getAccess() const
Definition DeclBase.h:516
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclBase.h:440
void dropAttr()
Definition DeclBase.h:565
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:936
bool hasAttr() const
Definition DeclBase.h:586
void setLexicalDeclContext(DeclContext *DC)
Definition DeclBase.cpp:389
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:996
@ VisibleWhenImported
This declaration has an owning module, and is visible when that module is imported.
Definition DeclBase.h:229
void setModuleOwnershipKind(ModuleOwnershipKind MOK)
Set whether this declaration is hidden from name lookup.
Definition DeclBase.h:899
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
Get the name of the overloadable C++ operator corresponding to Op.
The name of a declaration.
IdentifierInfo * getAsIdentifierInfo() const
Retrieve the IdentifierInfo * stored in this declaration name, or null if this declaration name isn't...
bool isAnyOperatorNewOrDelete() const
std::string getAsString() const
Retrieve the human-readable string for this name.
const IdentifierInfo * getCXXLiteralIdentifier() const
If this name is the name of a literal operator, retrieve the identifier associated with it.
OverloadedOperatorKind getCXXOverloadedOperator() const
If this name is the name of an overloadable operator in C++ (e.g., operator+), retrieve the kind of o...
NameKind getNameKind() const
Determine what kind of name this is.
bool isIdentifier() const
Predicate functions for querying what type of name this is.
Represents a ValueDecl that came out of a declarator.
Definition Decl.h:782
SourceLocation getTypeSpecStartLoc() const
Definition Decl.cpp:2007
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:833
const AssociatedConstraint & getTrailingRequiresClause() const
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition Decl.h:857
void setTypeSourceInfo(TypeSourceInfo *TI)
Definition Decl.h:816
ArrayRef< TemplateParameterList * > getTemplateParameterLists() const
Definition Decl.h:864
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:811
Information about one declarator, including the parsed type information and the identifier.
Definition DeclSpec.h:2000
bool isFunctionDeclarator(unsigned &idx) const
isFunctionDeclarator - This method returns true if the declarator is a function declarator (looking t...
Definition DeclSpec.h:2568
bool isDeclarationOfFunction() const
Determine whether the declaration that will be produced from this declaration will be a function.
Definition DeclSpec.cpp:296
const DeclaratorChunk & getTypeObject(unsigned i) const
Return the specified TypeInfo from this declarator.
Definition DeclSpec.h:2510
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition DeclSpec.h:2154
bool isFunctionDeclarationContext() const
Return true if this declaration appears in a context where a function declarator would be a function ...
Definition DeclSpec.h:2622
SourceLocation getIdentifierLoc() const
Definition DeclSpec.h:2445
void SetIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Set the name of this declarator to be the given identifier.
Definition DeclSpec.h:2448
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclSpec.h:2191
type_object_range type_objects() const
Returns the range of type objects, from the identifier outwards.
Definition DeclSpec.h:2523
bool hasGroupingParens() const
Definition DeclSpec.h:2843
void setInvalidType(bool Val=true)
Definition DeclSpec.h:2837
void DropFirstTypeObject()
Definition DeclSpec.h:2527
unsigned getNumTypeObjects() const
Return the number of types applied to this declarator.
Definition DeclSpec.h:2506
bool isRedeclaration() const
Definition DeclSpec.h:2889
DeclaratorContext getContext() const
Definition DeclSpec.h:2179
const DecompositionDeclarator & getDecompositionDeclarator() const
Definition DeclSpec.h:2175
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:2190
bool isFunctionDefinition() const
Definition DeclSpec.h:2861
UnqualifiedId & getName()
Retrieve the name specified by this declarator.
Definition DeclSpec.h:2173
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition DeclSpec.h:2169
ArrayRef< TemplateParameterList * > getTemplateParameterLists() const
The template parameter lists that preceded the declarator.
Definition DeclSpec.h:2761
void setInventedTemplateParameterList(TemplateParameterList *Invented)
Sets the template parameter list generated from the explicit template parameters along with any inven...
Definition DeclSpec.h:2768
bool mayHaveDecompositionDeclarator() const
Return true if the context permits a C++17 decomposition declarator.
Definition DeclSpec.h:2320
bool isInvalidType() const
Definition DeclSpec.h:2838
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition DeclSpec.h:2189
bool isDecompositionDeclarator() const
Return whether this declarator is a decomposition declarator.
Definition DeclSpec.h:2435
bool isStaticMember()
Returns true if this declares a static member.
Definition DeclSpec.cpp:391
DeclSpec & getMutableDeclSpec()
getMutableDeclSpec - Return a non-const version of the DeclSpec.
Definition DeclSpec.h:2161
DeclaratorChunk::FunctionTypeInfo & getFunctionTypeInfo()
getFunctionTypeInfo - Retrieves the function type info object (looking through parentheses).
Definition DeclSpec.h:2599
const IdentifierInfo * getIdentifier() const
Definition DeclSpec.h:2439
A decomposition declaration.
Definition DeclCXX.h:4296
ArrayRef< BindingDecl * > bindings() const
Definition DeclCXX.h:4336
A parsed C++17 decomposition declarator of the form '[' identifier-list ']'.
Definition DeclSpec.h:1888
ArrayRef< Binding > bindings() const
Definition DeclSpec.h:1928
SourceRange getSourceRange() const
Definition DeclSpec.h:1936
SourceLocation getLSquareLoc() const
Definition DeclSpec.h:1934
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2653
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:2633
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition TypeLoc.h:2642
A little helper class (which is basically a smart pointer that forwards info from DiagnosticsEngine a...
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
virtual bool TraverseConstructorInitializer(MaybeConst< CXXCtorInitializer > *Init)
static EmptyDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L)
Definition Decl.cpp:6007
RAII object that enters a new expression evaluation context.
An instance of this object exists for each enum constant that is defined.
Definition Decl.h:3604
Represents an enum.
Definition Decl.h:4192
enumerator_range enumerators() const
Definition Decl.h:4338
EvaluatedExprVisitor - This class visits 'Expr *'s.
Store information needed for an explicit specifier.
Definition DeclCXX.h:1949
const Expr * getExpr() const
Definition DeclCXX.h:1958
void setExpr(Expr *E)
Definition DeclCXX.h:1983
void setKind(ExplicitSpecKind Kind)
Definition DeclCXX.h:1982
This represents one expression.
Definition Expr.h:114
static bool isPotentialConstantExpr(const FunctionDecl *FD, SmallVectorImpl< PartialDiagnosticAt > &Diags)
isPotentialConstantExpr - Return true if this function's definition might be usable in a constant exp...
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:179
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:196
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3129
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3117
bool containsErrors() const
Whether this expression contains subexpressions which had errors.
Definition Expr.h:248
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3125
bool isPRValue() const
Definition Expr.h:287
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition Expr.h:286
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const
Determine whether the result of this expression is a temporary object of the given class type.
Definition Expr.cpp:3292
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:283
QualType getType() const
Definition Expr.h:146
Represents difference between two FPOptions values.
FPOptions applyOverrides(FPOptions Base)
Represents a member of a struct/union/class.
Definition Decl.h:3341
bool isMutable() const
Determines whether this field is mutable (C++ only).
Definition Decl.h:3441
Expr * getInClassInitializer() const
Get the C++11 default member initializer for this member, or null if one has not been set.
Definition Decl.cpp:4830
bool hasInClassInitializer() const
Determine whether this member has a C++11 default member initializer.
Definition Decl.h:3521
bool isAnonymousStructOrUnion() const
Determines whether this field is a representative for an anonymous struct or union.
Definition Decl.cpp:4820
InClassInitStyle getInClassInitStyle() const
Get the kind of (C++11) default member initializer that this field has.
Definition Decl.h:3515
void setInClassInitializer(Expr *NewInit)
Set the C++11 in-class initializer for this member.
Definition Decl.cpp:4840
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3577
FieldDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this field.
Definition Decl.h:3588
bool isUnnamedBitField() const
Determines whether this is an unnamed bitfield.
Definition Decl.h:3447
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:78
static FixItHint CreateInsertionFromRange(SourceLocation InsertionLoc, CharSourceRange FromRange, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code from FromRange at a specific location.
Definition Diagnostic.h:115
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition Diagnostic.h:139
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:128
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition Diagnostic.h:102
FriendDecl - Represents the declaration of a friend entity, which can be a function,...
Definition DeclFriend.h:46
static FriendDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, FriendUnion Friend, SourceLocation FriendL, SourceLocation EllipsisLoc={})
static FriendTemplateDecl * Create(ASTContext &Context, DeclContext *DC, SourceLocation Loc, FriendUnion Friend, SourceLocation FriendLoc, ArrayRef< TemplateParameterList * > FriendTPLists, SourceLocation EllipsisLoc={}, TemplateName Template={})
For a defaulted function, the kind of defaulted function that it is.
Definition Decl.h:2146
CXXSpecialMemberKind asSpecialMember() const
Definition Decl.h:2188
PostfixOperatorKind asPostfixOperator() const
Definition Decl.h:2195
DefaultedComparisonKind asComparison() const
Definition Decl.h:2191
static DefaultedOrDeletedFunctionInfo * Create(ASTContext &Context, ArrayRef< DeclAccessPair > Lookups, FPOptionsOverride FPFeatures, StringLiteral *DeletedMessage=nullptr)
Definition Decl.cpp:3146
Represents a function declaration or definition.
Definition Decl.h:2082
static constexpr unsigned RequiredTypeAwareDeleteParameterCount
Count of mandatory parameters for type aware operator delete.
Definition Decl.h:2815
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2974
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition Decl.cpp:3287
ExceptionSpecificationType getExceptionSpecType() const
Gets the ExceptionSpecificationType as declared.
Definition Decl.h:3046
bool isTrivialForCall() const
Definition Decl.h:2549
ConstexprSpecKind getConstexprKind() const
Definition Decl.h:2645
DefaultedOrDeletedFunctionInfo * getDefaultedOrDeletedInfo() const
Definition Decl.cpp:3202
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to call this function.
Definition Decl.cpp:3928
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4271
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
Definition Decl.h:2470
bool isImmediateFunction() const
Definition Decl.cpp:3416
void setDefaultedOrDeletedInfo(DefaultedOrDeletedFunctionInfo *Info)
Definition Decl.cpp:3167
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type.
Definition Decl.cpp:4105
bool isDestroyingOperatorDelete() const
Determine whether this is a destroying operator delete.
Definition Decl.cpp:3627
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3946
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition Decl.h:3098
SourceLocation getDefaultLoc() const
Definition Decl.h:2567
QualType getReturnType() const
Definition Decl.h:3022
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2947
FunctionDecl * getTemplateInstantiationPattern(bool ForDefinition=true) const
Retrieve the function declaration from which this function could be instantiated, if it is an instant...
Definition Decl.cpp:4342
bool isExplicitlyDefaulted() const
Whether this function is explicitly defaulted.
Definition Decl.h:2558
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition Decl.h:2546
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition Decl.cpp:4391
MutableArrayRef< ParmVarDecl * >::iterator param_iterator
Definition Decl.h:2955
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3823
param_iterator param_begin()
Definition Decl.h:2959
const ParmVarDecl * getNonObjectParameter(unsigned I) const
Definition Decl.h:3000
bool isVariadic() const
Whether this function is variadic.
Definition Decl.cpp:3139
bool doesThisDeclarationHaveABody() const
Returns whether this specific declaration of the function has a body.
Definition Decl.h:2482
bool isDeleted() const
Whether this function has been deleted.
Definition Decl.h:2709
void setBodyContainsImmediateEscalatingExpressions(bool Set)
Definition Decl.h:2655
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4407
FunctionEffectsRef getFunctionEffects() const
Definition Decl.h:3315
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition Decl.cpp:4335
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition Decl.h:3065
bool isStatic() const
Definition Decl.h:3106
void setTrivial(bool IT)
Definition Decl.h:2547
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition Decl.cpp:4222
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition Decl.h:2639
static constexpr unsigned RequiredTypeAwareNewParameterCount
Count of mandatory parameters for type aware operator new.
Definition Decl.h:2811
bool isPureVirtual() const
Whether this virtual function is pure, i.e.
Definition Decl.h:2522
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition Decl.cpp:3694
FunctionDecl * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
bool isImmediateEscalating() const
Definition Decl.cpp:3387
void setIsDestroyingOperatorDelete(bool IsDestroyingDelete)
Definition Decl.cpp:3631
FunctionDecl * getDefinition()
Get the definition for this declaration.
Definition Decl.h:2438
bool isTypeAwareOperatorNewOrDelete() const
Determine whether this is a type aware operator new or delete.
Definition Decl.cpp:3635
void setImplicitlyInline(bool I=true)
Flag that this function is implicitly inline.
Definition Decl.h:3093
void setIsTypeAwareOperatorNewOrDelete(bool IsTypeAwareOperator=true)
Definition Decl.cpp:3639
bool isDefaulted() const
Whether this function is defaulted.
Definition Decl.h:2554
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:4648
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
Definition Decl.h:3110
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition Decl.cpp:4208
void setConstexprKind(ConstexprSpecKind CSK)
Definition Decl.h:2642
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition Decl.cpp:4495
void setDefaulted(bool D=true)
Definition Decl.h:2555
bool isConsteval() const
Definition Decl.h:2651
bool isUserProvided() const
True if this method is user-declared and was not deleted or defaulted on its first declaration.
Definition Decl.h:2579
DefaultedFunctionKind getDefaultedFunctionKind() const
Determine the kind of defaulting that would be done for a given function.
Definition Decl.cpp:3307
QualType getDeclaredReturnType() const
Get the declared return type, which may differ from the actual return type if the return type is dedu...
Definition Decl.h:3039
void setBody(Stmt *B)
Definition Decl.cpp:3299
bool isVirtualAsWritten() const
Whether this function is marked as virtual explicitly.
Definition Decl.h:2513
bool hasOneParamOrDefaultArgs() const
Determine whether this function has a single parameter, or multiple parameters where all but the firs...
Definition Decl.cpp:3960
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3902
size_t param_size() const
Definition Decl.h:2963
DeclarationNameInfo getNameInfo() const
Definition Decl.h:2367
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition Decl.cpp:3207
bool isDefined(const FunctionDecl *&Definition, bool CheckForPendingFriendDefinition=false) const
Returns true if the function has a definition that does not need to be instantiated.
Definition Decl.cpp:3254
FunctionDecl * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
void setParams(ArrayRef< ParmVarDecl * > NewParamInfo)
Definition Decl.h:2982
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition Decl.h:2858
A mutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5484
bool insert(const FunctionEffectWithCondition &NewEC, Conflicts &Errs)
Definition Type.cpp:6013
SmallVector< Conflict > Conflicts
Definition TypeBase.h:5516
An immutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5348
static FunctionParmPackExpr * Create(const ASTContext &Context, QualType T, ValueDecl *ParamPack, SourceLocation NameLoc, ArrayRef< ValueDecl * > Params)
Definition ExprCXX.cpp:1832
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5548
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition TypeBase.h:6052
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition TypeBase.h:5855
unsigned getNumParams() const
Definition TypeBase.h:5826
bool hasTrailingReturn() const
Whether this function prototype has a trailing return type.
Definition TypeBase.h:5968
const QualType * param_type_iterator
Definition TypeBase.h:5986
QualType getParamType(unsigned i) const
Definition TypeBase.h:5828
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5952
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5837
Expr * getNoexceptExpr() const
Return the expression inside noexcept(expression), or a null pointer if there is none (because the ex...
Definition TypeBase.h:5913
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5833
ArrayRef< QualType > exceptions() const
Definition TypeBase.h:6002
bool hasExtParameterInfos() const
Is there any interesting extra information for any of the parameters of this function type?
Definition TypeBase.h:6017
Declaration of a template function.
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
Wrapper for source info for functions.
Definition TypeLoc.h:1675
unsigned getNumParams() const
Definition TypeLoc.h:1747
ParmVarDecl * getParam(unsigned i) const
Definition TypeLoc.h:1753
void setParam(unsigned i, ParmVarDecl *VD)
Definition TypeLoc.h:1754
TypeLoc getReturnLoc() const
Definition TypeLoc.h:1756
ExtInfo withCallingConv(CallingConv cc) const
Definition TypeBase.h:4967
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4744
CallingConv getCallConv() const
Definition TypeBase.h:5099
QualType getReturnType() const
Definition TypeBase.h:5084
One of these records is kept for each identifier that is lexed.
unsigned getLength() const
Efficiently return the length of this identifier info.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
ReservedLiteralSuffixIdStatus isReservedLiteralSuffixId() const
Determine whether this is a name reserved for future standardization or the implementation (C++ [usrl...
StringRef getName() const
Return the actual identifier string.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
IfStmt - This represents an if/then/else.
Definition Stmt.h:2270
RAII class that temporarily sets the "ignore all warnings" state on a DiagnosticsEngine and restores ...
ImaginaryLiteral - We support imaginary integer and floating point literals, like "1....
Definition Expr.h:1776
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition Expr.cpp:2109
Represents an implicitly-generated value initialization of an object of a given type.
Definition Expr.h:6143
Represents a field injected from an anonymous union/struct into the parent scope.
Definition Decl.h:3648
ArrayRef< NamedDecl * > chain() const
Definition Decl.h:3669
void setInherited(bool I)
Definition Attr.h:164
Description of a constructor that was inherited from a base class.
Definition DeclCXX.h:2616
ConstructorUsingShadowDecl * getShadowDecl() const
Definition DeclCXX.h:2628
const TypeClass * getTypePtr() const
Definition TypeLoc.h:526
Describes an C or C++ initializer list.
Definition Expr.h:5377
unsigned getNumInits() const
Definition Expr.h:5410
const Expr * getInit(unsigned Init) const
Definition Expr.h:5443
child_range children()
Definition Expr.h:5584
Describes the kind of initialization being performed, along with location information for tokens rela...
static InitializationKind CreateDefault(SourceLocation InitLoc)
Create a default initialization.
static InitializationKind CreateDirect(SourceLocation InitLoc, SourceLocation LParenLoc, SourceLocation RParenLoc)
Create a direct initialization.
static InitializationKind CreateCopy(SourceLocation InitLoc, SourceLocation EqualLoc, bool AllowExplicitConvs=false)
Create a copy initialization.
static InitializationKind CreateDirectList(SourceLocation InitLoc)
A single step in the initialization sequence.
Describes the sequence of initializations required to initialize a given object or reference with a s...
ExprResult Perform(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, QualType *ResultType=nullptr)
Perform the actual initialization of the given entity based on the computed initialization sequence.
@ SK_ConstructorInitialization
Perform initialization via a constructor.
Describes an entity that is being initialized.
static InitializedEntity InitializeBase(ASTContext &Context, const CXXBaseSpecifier *Base, bool IsInheritedVirtualBase, const InitializedEntity *Parent=nullptr)
Create the initialization entity for a base class subobject.
static InitializedEntity InitializeMember(FieldDecl *Member, const InitializedEntity *Parent=nullptr)
Create the initialization entity for a member subobject.
static InitializedEntity InitializeTemporary(QualType Type)
Create the initialization entity for a temporary.
static InitializedEntity InitializeBinding(VarDecl *Binding)
Create the initialization entity for a structured binding.
static InitializedEntity InitializeMemberFromDefaultMemberInitializer(FieldDecl *Member)
Create the initialization entity for a default member initializer.
static InitializedEntity InitializeVariable(VarDecl *Var)
Create the initialization entity for a variable.
static InitializedEntity InitializeParameter(ASTContext &Context, ParmVarDecl *Parm)
Create the initialization entity for a parameter.
static InitializedEntity InitializeMemberImplicit(FieldDecl *Member)
Create the initialization entity for a member subobject with implicit field initializer.
static InitializedEntity InitializeDelegation(QualType Type)
Create the initialization entity for a delegated constructor.
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition Expr.cpp:985
An lvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3715
bool isInitCapture(const LambdaCapture *Capture) const
Determine whether one of this lambda's captures is an init-capture.
Definition ExprCXX.cpp:1390
capture_range captures() const
Retrieve this lambda's captures.
Definition ExprCXX.cpp:1403
@ Default
Use default layout rules of the target.
static StringRef getSourceText(CharSourceRange Range, const SourceManager &SM, const LangOptions &LangOpts, bool *Invalid=nullptr)
Returns a string for the source that the range encompasses.
Definition Lexer.cpp:1075
Represents a linkage specification.
Definition DeclCXX.h:3062
static LinkageSpecDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation ExternLoc, SourceLocation LangLoc, LinkageSpecLanguageIDs Lang, bool HasBraces)
Definition DeclCXX.cpp:3313
void setRBraceLoc(SourceLocation L)
Definition DeclCXX.h:3104
A class for iterating through a result set and possibly filtering out results.
Definition Lookup.h:677
void erase()
Erase the last element returned from this iterator.
Definition Lookup.h:723
Represents the results of name lookup.
Definition Lookup.h:147
LLVM_ATTRIBUTE_REINITIALIZES void clear()
Clears out any current state.
Definition Lookup.h:607
void addDecl(NamedDecl *D)
Add a declaration to these results with its natural access.
Definition Lookup.h:475
bool empty() const
Return true if no decls were found.
Definition Lookup.h:362
void resolveKind()
Resolves the result kind of the lookup, possibly hiding decls.
Filter makeFilter()
Create a filter for this result set.
Definition Lookup.h:751
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition Lookup.h:569
bool isAmbiguous() const
Definition Lookup.h:324
bool isSingleResult() const
Determines if this names a single result which is not an unresolved value using decl.
Definition Lookup.h:331
UnresolvedSetImpl::iterator iterator
Definition Lookup.h:154
NamedDecl * getRepresentativeDecl() const
Fetches a representative decl. Useful for lazy diagnostics.
Definition Lookup.h:576
iterator end() const
Definition Lookup.h:359
static bool isVisible(Sema &SemaRef, NamedDecl *D)
Determine whether the given declaration is visible to the program.
iterator begin() const
Definition Lookup.h:358
An instance of this class represents the declaration of a property member.
Definition DeclCXX.h:4414
static MSPropertyDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName N, QualType T, TypeSourceInfo *TInfo, SourceLocation StartL, IdentifierInfo *Getter, IdentifierInfo *Setter)
Definition DeclCXX.cpp:3839
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3433
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3516
Expr * getBase() const
Definition Expr.h:3510
SourceLocation getExprLoc() const LLVM_READONLY
Definition Expr.h:3628
Wrapper for source info for member pointers.
Definition TypeLoc.h:1575
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3751
Describes a module or submodule.
Definition Module.h:340
StringRef getTopLevelModuleName() const
Retrieve the name of the top-level module.
Definition Module.h:953
bool isExplicitGlobalModule() const
Definition Module.h:444
This represents a decl that may have a name.
Definition Decl.h:276
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:489
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:297
bool isPlaceholderVar(const LangOptions &LangOpts) const
Definition Decl.cpp:1097
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:342
void setModulePrivate()
Specify that this declaration was marked as being private to the module in which it was defined.
Definition DeclBase.h:719
bool isCXXClassMember() const
Determine whether this declaration is a C++ class member.
Definition Decl.h:399
Represents a C++ namespace alias.
Definition DeclCXX.h:3248
static NamespaceAliasDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation NamespaceLoc, SourceLocation AliasLoc, IdentifierInfo *Alias, NestedNameSpecifierLoc QualifierLoc, SourceLocation IdentLoc, NamespaceBaseDecl *Namespace)
Definition DeclCXX.cpp:3414
Represents C++ namespaces and their aliases.
Definition Decl.h:575
NamespaceDecl * getNamespace()
Definition DeclCXX.cpp:3351
Represent a C++ namespace.
Definition Decl.h:594
bool isInline() const
Returns true if this is an inline namespace declaration.
Definition Decl.h:650
static NamespaceDecl * Create(ASTContext &C, DeclContext *DC, bool Inline, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, NamespaceDecl *PrevDecl, bool Nested)
Definition DeclCXX.cpp:3374
NamespaceDecl * getAnonymousNamespace() const
Retrieve the anonymous namespace that inhabits this namespace, if any.
Definition Decl.h:677
void setRBraceLoc(SourceLocation L)
Definition Decl.h:696
Class that aids in the construction of nested-name-specifiers along with source-location information ...
void MakeTrivial(ASTContext &Context, NestedNameSpecifier Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
A C++ nested-name-specifier augmented with source location information.
NestedNameSpecifier getNestedNameSpecifier() const
Retrieve the nested-name-specifier to which this instance refers.
SourceRange getSourceRange() const LLVM_READONLY
Retrieve the source range covering the entirety of this nested-name-specifier.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
NestedNameSpecifier getCanonical() const
Retrieves the "canonical" nested name specifier for a given nested name specifier.
bool containsUnexpandedParameterPack() const
Whether this nested-name-specifier contains an unexpanded parameter pack (for C++11 variadic template...
CXXRecordDecl * getAsRecordDecl() const
Retrieve the record declaration stored in this nested name specifier, or null.
bool isDependent() const
Whether this nested name specifier refers to a dependent type or not.
@ Global
The global specifier '::'. There is no stored value.
@ Namespace
A namespace-like entity, stored as a NamespaceBaseDecl*.
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
The basic abstraction for the target Objective-C runtime.
Definition ObjCRuntime.h:28
bool isFragile() const
The inverse of isNonFragile(): does this runtime follow the set of implied behaviors for a "fragile" ...
Definition ObjCRuntime.h:97
PtrTy get() const
Definition Ownership.h:81
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition Expr.h:1223
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition Overload.h:1162
@ CSK_Operator
C++ [over.match.oper]: Lookup of operator function candidates in a call using operator syntax.
Definition Overload.h:1173
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition Overload.h:1378
void NoteCandidates(PartialDiagnosticAt PA, Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef< Expr * > Args, StringRef Opc="", SourceLocation Loc=SourceLocation(), llvm::function_ref< bool(OverloadCandidate &)> Filter=[](OverloadCandidate &) { return true;})
When overload resolution fails, prints diagnostic messages containing the candidates in the candidate...
OverloadingResult BestViableFunction(Sema &S, SourceLocation Loc, OverloadCandidateSet::iterator &Best)
Find the best viable function on this overload set, if it exists.
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition Attr.h:280
static ParenListExpr * Create(const ASTContext &Ctx, SourceLocation LParenLoc, ArrayRef< Expr * > Exprs, SourceLocation RParenLoc)
Create a paren list.
Definition Expr.cpp:5016
Represents a parameter to a function.
Definition Decl.h:1832
void setDefaultArg(Expr *defarg)
Definition Decl.cpp:3030
void setUnparsedDefaultArg()
Specify that this parameter has an unparsed default argument.
Definition Decl.h:1973
bool hasUnparsedDefaultArg() const
Determines whether this parameter has a default argument that has not yet been parsed.
Definition Decl.h:1961
SourceRange getDefaultArgRange() const
Retrieve the source range that covers the entire default argument.
Definition Decl.cpp:3035
void setUninstantiatedDefaultArg(Expr *arg)
Definition Decl.cpp:3055
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition Decl.h:1865
bool hasUninstantiatedDefaultArg() const
Definition Decl.h:1965
bool hasInheritedDefaultArg() const
Definition Decl.h:1977
static ParmVarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
Definition Decl.cpp:2965
Expr * getUninstantiatedDefaultArg()
Definition Decl.cpp:3060
bool hasDefaultArg() const
Determines whether this parameter has a default argument, either parsed or not.
Definition Decl.cpp:3066
void setHasInheritedDefaultArg(bool I=true)
Definition Decl.h:1981
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:2988
ParsedAttr - Represents a syntactic attribute.
Definition ParsedAttr.h:119
IdentifierInfo * getPropertyDataSetter() const
Definition ParsedAttr.h:470
IdentifierInfo * getPropertyDataGetter() const
Definition ParsedAttr.h:464
static const ParsedAttributesView & none()
Definition ParsedAttr.h:838
const ParsedAttr * getMSPropertyAttr() const
Definition ParsedAttr.h:924
bool hasAttribute(ParsedAttr::Kind K) const
Definition ParsedAttr.h:918
bool isAddressDiscriminated() const
Definition TypeBase.h:266
Wrapper for source info for pointers.
Definition TypeLoc.h:1544
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3403
QualType getPointeeType() const
Definition TypeBase.h:3413
IdentifierInfo * getIdentifierInfo(StringRef Name) const
Return information about the specified preprocessor identifier token.
IdentifierTable & getIdentifierTable()
ArrayRef< Expr * > semantics()
Definition Expr.h:6962
A (possibly-)qualified type.
Definition TypeBase.h:938
bool hasAddressDiscriminatedPointerAuth() const
Definition TypeBase.h:1473
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8662
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8667
PointerAuthQualifier getPointerAuth() const
Definition TypeBase.h:1469
QualType getLocalUnqualifiedType() const
Return this type with all of the instance-specific qualifiers removed, but without removing any quali...
Definition TypeBase.h:1241
void addConst()
Add the const type qualifier to this QualType.
Definition TypeBase.h:1172
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1005
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8578
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8704
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8618
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1454
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition TypeBase.h:8763
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8672
unsigned getLocalCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers local to this particular QualType instan...
Definition TypeBase.h:1090
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8651
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition TypeBase.h:8624
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1348
bool hasNonTrivialObjCLifetime() const
Definition TypeBase.h:1458
bool isPODType(const ASTContext &Context) const
Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
Definition Type.cpp:2921
bool isAtLeastAsQualifiedAs(QualType Other, const ASTContext &Ctx) const
Determine whether this type is at least as qualified as the other given type, requiring exact equalit...
Definition TypeBase.h:8743
Represents a template name as written in source code.
The collection of all-type qualifiers we support.
Definition TypeBase.h:332
void removeCVRQualifiers(unsigned mask)
Definition TypeBase.h:496
void addAddressSpace(LangAS space)
Definition TypeBase.h:598
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition TypeBase.h:362
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition TypeBase.h:365
void removeAddressSpace()
Definition TypeBase.h:597
void removeVolatile()
Definition TypeBase.h:470
LangAS getAddressSpace() const
Definition TypeBase.h:572
void setObjCLifetime(ObjCLifetime type)
Definition TypeBase.h:549
An rvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3733
Represents a struct/union/class.
Definition Decl.h:4506
bool hasFlexibleArrayMember() const
Definition Decl.h:4539
bool hasObjectMember() const
Definition Decl.h:4566
field_iterator field_end() const
Definition Decl.h:4712
field_range fields() const
Definition Decl.h:4709
specific_decl_iterator< FieldDecl > field_iterator
Definition Decl.h:4706
RecordDecl * getDefinitionOrSelf() const
Definition Decl.h:4694
bool isAnonymousStructOrUnion() const
Whether this is an anonymous struct or union.
Definition Decl.h:4558
bool field_empty() const
Definition Decl.h:4717
field_iterator field_begin() const
Definition Decl.cpp:5386
RedeclarableTemplateDecl * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
void setPreviousDecl(decl_type *PrevDecl)
Set the previous declaration.
Definition Decl.h:5517
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3678
QualType getPointeeType() const
Definition TypeBase.h:3700
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
void setEntity(DeclContext *E)
Definition Scope.h:395
const Scope * getFnParent() const
getFnParent - Return the closest scope that is a function body.
Definition Scope.h:284
void AddDecl(Decl *D)
Definition Scope.h:348
unsigned getFlags() const
getFlags - Return the flags for this scope.
Definition Scope.h:269
bool isDeclScope(const Decl *D) const
isDeclScope - Return true if this is the scope that the specified decl is declared in.
Definition Scope.h:384
void RemoveDecl(Decl *D)
Definition Scope.h:356
DeclContext * getEntity() const
Get the entity corresponding to this scope.
Definition Scope.h:387
Scope * getDeclParent()
Definition Scope.h:321
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition Scope.h:280
@ DeclScope
This is a scope that can contain a declaration.
Definition Scope.h:63
void PushUsingDirective(UsingDirectiveDecl *UDir)
Definition Scope.h:639
A generic diagnostic builder for errors which may or may not be deferred.
Definition SemaBase.h:120
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition SemaBase.cpp:33
Sema & SemaRef
Definition SemaBase.h:49
SemaDiagnosticBuilder DiagCompat(SourceLocation Loc, unsigned CompatDiagId)
Emit a compatibility diagnostic.
Definition SemaBase.cpp:98
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition SemaBase.cpp:61
A RAII object to enter scope of a compound statement.
Definition Sema.h:1348
A RAII object to temporarily push a declaration context.
Definition Sema.h:3659
Records and restores the CurFPFeatures state on entry/exit of compound statements.
Definition Sema.h:14392
Helper class that collects exception specifications for implicitly-declared special member functions.
Definition Sema.h:5703
void CalledStmt(Stmt *S)
Integrate an invoked statement into the collected data.
void CalledExpr(Expr *E)
Integrate an invoked expression into the collected data.
Definition Sema.h:5745
void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method)
Integrate another called method into the collected data.
SpecialMemberOverloadResult - The overloading result for a special member function.
Definition Sema.h:9530
CXXMethodDecl * getMethod() const
Definition Sema.h:9542
RAII object to handle the state changes required to synthesize a function body.
Definition Sema.h:13844
Abstract base class used for diagnosing integer constant expression violations.
Definition Sema.h:7937
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:863
void DefineImplicitLambdaToFunctionPointerConversion(SourceLocation CurrentLoc, CXXConversionDecl *Conv)
Define the "body" of the conversion from a lambda object to a function pointer.
QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement)
Substitute Replacement for auto in TypeWithAuto.
CXXConstructorDecl * DeclareImplicitDefaultConstructor(CXXRecordDecl *ClassDecl)
Declare the implicit default constructor for the given class.
bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S)
MergeCXXFunctionDecl - Merge two declarations of the same C++ function, once we already know that the...
Attr * getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, bool IsDefinition)
Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a containing class.
MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, CXXRecordDecl *ClassDecl)
void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D)
QualType getCurrentThisType()
Try to retrieve the type of the 'this' pointer.
bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range)
CheckSpecifiedExceptionType - Check if the given type is valid in an exception specification.
ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation, SourceLocation ConvLocation, CXXConversionDecl *Conv, Expr *Src)
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition Sema.h:13362
sema::CapturingScopeInfo * getEnclosingLambdaOrBlock() const
Get the innermost lambda or block enclosing the current location, if any.
Definition Sema.cpp:2722
Decl * ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS, MultiTemplateParamsArg TemplateParams, SourceLocation UsingLoc, UnqualifiedId &Name, const ParsedAttributesView &AttrList, TypeResult Type, Decl *DeclFromDeclSpec)
NamedDecl * ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope)
void DiagnoseAbstractType(const CXXRecordDecl *RD)
void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow)
Hides a using shadow declaration.
bool CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename, const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, SourceLocation NameLoc, const LookupResult *R=nullptr, const UsingDecl *UD=nullptr)
Checks that the given nested-name qualifier used in a using decl in the current context is appropriat...
bool CheckExplicitObjectOverride(CXXMethodDecl *New, const CXXMethodDecl *Old)
llvm::SmallPtrSet< SpecialMemberDecl, 4 > SpecialMembersBeingDeclared
The C++ special members which we are currently in the process of declaring.
Definition Sema.h:6745
void ActOnParamUnparsedDefaultArgument(Decl *param, SourceLocation EqualLoc, SourceLocation ArgLoc)
ActOnParamUnparsedDefaultArgument - We've seen a default argument for a function parameter,...
ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs, const Scope *S, ActOnMemberAccessExtraArgs *ExtraArgs=nullptr)
bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S=nullptr, bool AllowInlineNamespace=false) const
isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true if 'D' is in Scope 'S',...
bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs=true)
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr, bool IsAfterAmp=false)
void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath)
void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old)
Merge the exception specifications of two variable declarations.
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9568
@ LookupUsingDeclName
Look up all declarations in a scope with the given name, including resolved using declarations.
Definition Sema.h:9595
@ LookupLocalFriendName
Look up a friend of a local class.
Definition Sema.h:9603
@ LookupNamespaceName
Look up a namespace name within a C++ using directive or namespace alias definition,...
Definition Sema.h:9591
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9576
void DiagnoseSentinelCalls(const NamedDecl *D, SourceLocation Loc, ArrayRef< Expr * > Args)
DiagnoseSentinelCalls - This routine checks whether a call or message-send is to a declaration with t...
Definition SemaExpr.cpp:421
void DiagnoseFunctionSpecifiers(const DeclSpec &DS)
Diagnose function specifiers on a declaration of an identifier that does not identify a function.
Decl * BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, Expr *AssertExpr, Expr *AssertMessageExpr, SourceLocation RParenLoc, bool Failed)
void EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD)
Evaluate the implicit exception specification for a defaulted special member function.
void PrintContextStack(InstantiationContextDiagFuncRef DiagFunc)
Definition Sema.h:13981
ExplicitSpecifier ActOnExplicitBoolSpecifier(Expr *E)
ActOnExplicitBoolSpecifier - Build an ExplicitSpecifier from an expression found in an explicit(bool)...
bool DiagRedefinedPlaceholderFieldDecl(SourceLocation Loc, RecordDecl *ClassDecl, const IdentifierInfo *Name)
void ActOnFinishCXXNonNestedClass()
MemInitResult BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, Expr *Init, CXXRecordDecl *ClassDecl, SourceLocation EllipsisLoc)
bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, DeclarationName Name, FunctionDecl *&Operator, ImplicitDeallocationParameters, bool Diagnose=true)
void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class)
Force the declaration of any implicitly-declared members of this class.
void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc, Expr *DefaultArg)
ActOnParamDefaultArgumentError - Parsing or semantic analysis of the default argument for the paramet...
bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, DeclarationName Name, SourceLocation Loc, TemplateIdAnnotation *TemplateId, bool IsMemberSpecialization)
Diagnose a declaration whose declarator-id has the given nested-name-specifier.
void DiagnoseStaticAssertDetails(const Expr *E)
Try to print more useful information about a failed static_assert with expression \E.
void DefineImplicitMoveAssignment(SourceLocation CurrentLocation, CXXMethodDecl *MethodDecl)
Defines an implicitly-declared move assignment operator.
void ActOnFinishDelayedMemberInitializers(Decl *Record)
ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr, bool ForFoldExpression=false)
CreateBuiltinBinOp - Creates a new built-in binary operation with operator Opc at location TokLoc.
NamedDecl * ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope, ArrayRef< BindingDecl * > Bindings={})
SemaOpenMP & OpenMP()
Definition Sema.h:1578
void CheckDelegatingCtorCycles()
SmallVector< CXXMethodDecl *, 4 > DelayedDllExportMemberFunctions
Definition Sema.h:6528
void CheckExplicitObjectMemberFunction(Declarator &D, DeclarationName Name, QualType R, bool IsLambda, DeclContext *DC=nullptr)
bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info)
DiagnoseClassNameShadow - Implement C++ [class.mem]p13: If T is the name of a class,...
AccessResult CheckFriendAccess(NamedDecl *D)
Checks access to the target of a friend declaration.
void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc, CXXRecordDecl *Record)
MarkBaseAndMemberDestructorsReferenced - Given a record decl, mark all the non-trivial destructors of...
const TranslationUnitKind TUKind
The kind of translation unit we are processing.
Definition Sema.h:1293
QualType tryBuildStdTypeIdentity(QualType Type, SourceLocation Loc)
Looks for the std::type_identity template and instantiates it with Type, or returns a null type if ty...
DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D)
ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a C++ if/switch/while/for statem...
void LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet, OverloadedOperatorKind Op, const UnresolvedSetImpl &Fns, ArrayRef< Expr * > Args, bool RequiresADL=true)
Perform lookup for an overloaded binary operator.
DelegatingCtorDeclsType DelegatingCtorDecls
All the delegating constructors seen so far in the file, used for cycle detection at the end of the T...
Definition Sema.h:6718
bool ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc, SourceLocation ColonLoc, const ParsedAttributesView &Attrs)
ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
std::unique_ptr< CXXFieldCollector > FieldCollector
FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
Definition Sema.h:6699
void AddPragmaAttributes(Scope *S, Decl *D)
Adds the attributes that have been specified using the '#pragma clang attribute push' directives to t...
SemaCUDA & CUDA()
Definition Sema.h:1518
TemplateDecl * AdjustDeclIfTemplate(Decl *&Decl)
AdjustDeclIfTemplate - If the given decl happens to be a template, reset the parameter D to reference...
bool isImplicitlyDeleted(FunctionDecl *FD)
Determine whether the given function is an implicitly-deleted special member function.
void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD)
Check a completed declaration of an implicit special member.
void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl=nullptr, ExpressionEvaluationContextRecord::ExpressionKind Type=ExpressionEvaluationContextRecord::EK_Other)
bool CompleteConstructorCall(CXXConstructorDecl *Constructor, QualType DeclInitType, MultiExprArg ArgsPtr, SourceLocation Loc, SmallVectorImpl< Expr * > &ConvertedArgs, bool AllowExplicit=false, bool IsListInitialization=false)
Given a constructor and the set of arguments provided for the constructor, convert the arguments and ...
@ Boolean
A boolean condition, from 'if', 'while', 'for', or 'do'.
Definition Sema.h:8058
bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC)
Require that the context specified by SS be complete.
bool TemplateParameterListsAreEqual(const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New, const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain, TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc=SourceLocation())
Determine whether the given template parameter lists are equivalent.
Decl * ActOnNamespaceAliasDef(Scope *CurScope, SourceLocation NamespaceLoc, SourceLocation AliasLoc, IdentifierInfo *Alias, CXXScopeSpec &SS, SourceLocation IdentLoc, IdentifierInfo *Ident)
void CheckOverrideControl(NamedDecl *D)
CheckOverrideControl - Check C++11 override control semantics.
bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, const FunctionProtoType *Proto, unsigned FirstParam, ArrayRef< Expr * > Args, SmallVectorImpl< Expr * > &AllArgs, VariadicCallType CallType=VariadicCallType::DoesNotApply, bool AllowExplicit=false, bool IsListInitialization=false)
GatherArgumentsForCall - Collector argument expressions for various form of call prototypes.
bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMemberKind CSM, InheritedConstructorInfo *ICI=nullptr, bool Diagnose=false)
Determine if a special member function should have a deleted definition when it is defaulted.
@ AR_dependent
Definition Sema.h:1737
@ AR_accessible
Definition Sema.h:1735
@ AR_inaccessible
Definition Sema.h:1736
@ AR_delayed
Definition Sema.h:1738
Scope * getScopeForContext(DeclContext *Ctx)
Determines the active Scope associated with the given declaration context.
Definition Sema.cpp:2494
CXXConstructorDecl * DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl)
Declare the implicit move constructor for the given class.
bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl, const ParsedAttributesView &AttrList)
Annotation attributes are the only attributes allowed after an access specifier.
PragmaStack< FPOptionsOverride > FpPragmaStack
Definition Sema.h:2125
FunctionDecl * InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD, const TemplateArgumentList *Args, SourceLocation Loc, CodeSynthesisContext::SynthesisKind CSC=CodeSynthesisContext::ExplicitTemplateArgumentSubstitution)
Instantiate (or find existing instantiation of) a function template with a given set of template argu...
void referenceDLLExportedClassMethods()
void CheckCompleteDestructorVariant(SourceLocation CurrentLocation, CXXDestructorDecl *Dtor)
Do semantic checks to allow the complete destructor variant to be emitted when the destructor is defi...
NamedDecl * ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, MultiTemplateParamsArg TemplateParameterLists, Expr *BitfieldWidth, const VirtSpecifiers &VS, InClassInitStyle InitStyle)
ActOnCXXMemberDeclarator - This is invoked when a C++ class member declarator is parsed.
bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, const CXXMethodDecl *Old)
CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member function overrides a virtual...
NamedDecl * HandleDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists)
bool CheckOverridingFunctionAttributes(CXXMethodDecl *New, const CXXMethodDecl *Old)
TemplateParameterList * MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId, ArrayRef< TemplateParameterList * > ParamLists, bool IsFriend, bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic=false)
Match the given template parameter lists to the given scope specifier, returning the template paramet...
void handleTagNumbering(const TagDecl *Tag, Scope *TagScope)
void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl)
AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared special functions,...
bool tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec)
tryResolveExplicitSpecifier - Attempt to resolve the explict specifier.
Decl * ActOnConversionDeclarator(CXXConversionDecl *Conversion)
ActOnConversionDeclarator - Called by ActOnDeclarator to complete the declaration of the given C++ co...
bool IsCXXTriviallyRelocatableType(QualType T)
Determines if a type is trivially relocatable according to the C++26 rules.
@ Other
C++26 [dcl.fct.def.general]p1 function-body: ctor-initializer[opt] compound-statement function-try-bl...
Definition Sema.h:4340
@ Default
= default ;
Definition Sema.h:4342
@ Delete
deleted-function-body
Definition Sema.h:4348
QualType BuildStdInitializerList(QualType Element, SourceLocation Loc)
Looks for the std::initializer_list template and instantiates it with Element, or emits an error if i...
MemInitResult BuildMemberInitializer(ValueDecl *Member, Expr *Init, SourceLocation IdLoc)
StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue=true)
Definition SemaStmt.cpp:50
FieldDecl * HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, InClassInitStyle InitStyle, AccessSpecifier AS)
HandleField - Analyze a field of a C struct or a C++ data member.
FPOptionsOverride CurFPFeatureOverrides()
Definition Sema.h:2126
void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD)
Diagnose methods which overload virtual methods in a base class without overriding any.
UsingShadowDecl * BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD, NamedDecl *Target, UsingShadowDecl *PrevDecl)
Builds a shadow declaration corresponding to a 'using' declaration.
ExprResult BuildCallToMemberFunction(Scope *S, Expr *MemExpr, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false, bool AllowRecovery=false)
BuildCallToMemberFunction - Build a call to a member function.
FunctionDecl * FindDeallocationFunctionForDestructor(SourceLocation StartLoc, CXXRecordDecl *RD, bool Diagnose, bool LookForGlobal, DeclarationName Name)
NamedDecl * LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl=RedeclarationKind::NotForRedeclaration)
Look up a name, looking for a single declaration.
bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass, DeclAccessPair Found, QualType ObjectType, SourceLocation Loc, const PartialDiagnostic &Diag)
Is the given member accessible for the purposes of deciding whether to define a special member functi...
BaseResult ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, const ParsedAttributesView &Attrs, bool Virtual, AccessSpecifier Access, ParsedType basetype, SourceLocation BaseLoc, SourceLocation EllipsisLoc)
ActOnBaseSpecifier - Parsed a base specifier.
void ActOnFinishFunctionDeclarationDeclarator(Declarator &D)
Called after parsing a function declarator belonging to a function declaration.
void ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, Expr *defarg)
ActOnParamDefaultArgument - Check whether the default argument provided for a function parameter is w...
void CheckConversionDeclarator(Declarator &D, QualType &R, StorageClass &SC)
CheckConversionDeclarator - Called by ActOnDeclarator to check the well-formednes of the conversion f...
bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, bool Diagnose=true)
ASTContext & Context
Definition Sema.h:1339
void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method)
ActOnFinishDelayedCXXMethodDeclaration - We have finished processing the delayed method declaration f...
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReceiver=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition SemaExpr.cpp:231
DeclarationNameInfo GetNameForDeclarator(Declarator &D)
GetNameForDeclarator - Determine the full declaration name for the given Declarator.
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:932
void DiagnoseTypeTraitDetails(const Expr *E)
If E represents a built-in type trait, or a known standard type trait, try to print more information ...
AccessResult CheckDestructorAccess(SourceLocation Loc, CXXDestructorDecl *Dtor, const PartialDiagnostic &PDiag, QualType objectType=QualType())
bool isStdTypeIdentity(QualType Ty, QualType *TypeArgument, const Decl **MalformedDecl=nullptr)
Tests whether Ty is an instance of std::type_identity and, if it is and TypeArgument is not NULL,...
SemaObjC & ObjC()
Definition Sema.h:1563
void propagateDLLAttrToBaseClassTemplate(CXXRecordDecl *Class, Attr *ClassAttr, ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc)
Perform propagation of DLL attributes from a derived class to a templated base class for MS compatibi...
bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMemberKind CSM, TrivialABIHandling TAH=TrivialABIHandling::IgnoreTrivialABI, bool Diagnose=false)
Determine whether a defaulted or deleted special member function is trivial, as specified in C++11 [c...
NamedDecl * ActOnFriendFunctionDecl(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParams)
void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, TypedefNameDecl *NewTD)
void CheckDelayedMemberExceptionSpecs()
DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType=nullptr)
Definition SemaDecl.cpp:83
void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param)
This is used to implement the constant expression evaluation part of the attribute enable_if extensio...
void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc, Scope *S=nullptr)
Mark the given declaration as explicitly defaulted.
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S, UnresolvedSetImpl &Functions)
void CleanupVarDeclMarking()
ASTContext & getASTContext() const
Definition Sema.h:935
ClassTemplateDecl * StdInitializerList
The C++ "std::initializer_list" template, which is defined in <initializer_list>.
Definition Sema.h:6725
CXXDestructorDecl * LookupDestructor(CXXRecordDecl *Class)
Look for the destructor of the given class.
void CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *MD)
bool isCurrentClassName(const IdentifierInfo &II, Scope *S, const CXXScopeSpec *SS=nullptr)
isCurrentClassName - Determine whether the identifier II is the name of the class type currently bein...
void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var)
Mark a variable referenced, and check whether it is odr-used (C++ [basic.def.odr]p2,...
void checkExceptionSpecification(bool IsTopLevel, ExceptionSpecificationType EST, ArrayRef< ParsedType > DynamicExceptions, ArrayRef< SourceRange > DynamicExceptionRanges, Expr *NoexceptExpr, SmallVectorImpl< QualType > &Exceptions, FunctionProtoType::ExceptionSpecInfo &ESI)
Check the given exception-specification and update the exception specification information with the r...
SmallVector< std::pair< FunctionDecl *, FunctionDecl * >, 2 > DelayedEquivalentExceptionSpecChecks
All the function redeclarations seen during a class definition that had their exception spec checks d...
Definition Sema.h:6809
bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method)
Check whether 'this' shows up in the type of a static member function after the (naturally empty) cv-...
void PopExpressionEvaluationContext()
NamespaceDecl * getOrCreateStdNamespace()
Retrieve the special "std" namespace, which may require us to implicitly define the namespace.
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition Sema.cpp:774
bool isInitListConstructor(const FunctionDecl *Ctor)
Determine whether Ctor is an initializer-list constructor, as defined in [dcl.init....
void ActOnStartFunctionDeclarationDeclarator(Declarator &D, unsigned TemplateParameterDepth)
Called before parsing a function declarator belonging to a function declaration.
void LookupOverloadedUnaryOp(OverloadCandidateSet &CandidateSet, OverloadedOperatorKind Op, const UnresolvedSetImpl &Fns, ArrayRef< Expr * > Args, bool RequiresADL=true)
Perform lookup for an overloaded unary operator.
std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths)
Builds a string representing ambiguous paths from a specific derived class to different subobjects of...
OverloadKind CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &OldDecls, NamedDecl *&OldDecl, bool UseMemberUsingDeclRules)
Determine whether the given New declaration is an overload of the declarations in Old.
bool RequireLiteralType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Ensure that the type T is a literal type.
llvm::PointerIntPair< CXXRecordDecl *, 3, CXXSpecialMemberKind > SpecialMemberDecl
Definition Sema.h:6740
void ActOnStartCXXInClassMemberInitializer()
Enter a new C++ default initializer scope.
ValueDecl * tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl, CXXScopeSpec &SS, ParsedType TemplateTypeTy, IdentifierInfo *MemberOrBase)
NamedDecl * BuildUsingDeclaration(Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS, DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc, const ParsedAttributesView &AttrList, bool IsInstantiation, bool IsUsingIfExists)
Builds a using declaration.
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition Sema.h:1243
bool pushCodeSynthesisContext(CodeSynthesisContext Ctx)
DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS=nullptr)
void DefineImplicitMoveConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor)
DefineImplicitMoveConstructor - Checks for feasibility of defining this constructor as the move const...
@ TPL_TemplateMatch
We are matching the template parameter lists of two templates that might be redeclarations.
Definition Sema.h:12446
EnumDecl * getStdAlignValT() const
void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record)
LangAS getDefaultCXXMethodAddrSpace() const
Returns default addr space for method qualifiers.
Definition Sema.cpp:1799
LazyDeclPtr StdBadAlloc
The C++ "std::bad_alloc" class, which is defined by the C++ standard library.
Definition Sema.h:8585
QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs, const DeclSpec *DS=nullptr)
void PushFunctionScope()
Enter a new function scope.
Definition Sema.cpp:2513
void DefineImplicitCopyConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor)
DefineImplicitCopyConstructor - Checks for feasibility of defining this constructor as the copy const...
FPOptions & getCurFPFeatures()
Definition Sema.h:930
Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind=TU_Complete, CodeCompleteConsumer *CompletionConsumer=nullptr)
Definition Sema.cpp:278
ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr, ConditionKind CK, bool MissingOK=false)
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:84
void DiagnoseUnsatisfiedRequiresExpr(const RequiresExpr *RequiresExpr, bool First=true)
@ UPPC_RequiresClause
Definition Sema.h:14809
@ UPPC_UsingDeclaration
A using declaration.
Definition Sema.h:14764
@ UPPC_ExceptionType
The type of an exception.
Definition Sema.h:14782
@ UPPC_Initializer
An initializer.
Definition Sema.h:14773
@ UPPC_BaseType
The base type of a class type.
Definition Sema.h:14743
@ UPPC_FriendDeclaration
A friend declaration.
Definition Sema.h:14767
@ UPPC_DefaultArgument
A default argument.
Definition Sema.h:14776
@ UPPC_DeclarationType
The type of an arbitrary declaration.
Definition Sema.h:14746
@ UPPC_DataMemberType
The type of a data member.
Definition Sema.h:14749
@ UPPC_StaticAssertExpression
The expression in a static assertion.
Definition Sema.h:14755
Decl * ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc, SourceLocation NamespaceLoc, SourceLocation IdentLoc, IdentifierInfo *Ident, SourceLocation LBrace, const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UsingDecl, bool IsNested)
ActOnStartNamespaceDef - This is called at the start of a namespace definition.
const LangOptions & getLangOpts() const
Definition Sema.h:928
void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl, bool SupportedForCompatibility=false)
DiagnoseTemplateParameterShadow - Produce a diagnostic complaining that the template parameter 'PrevD...
TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, CorrectTypoKind Mode, DeclContext *MemberContext=nullptr, bool EnteringContext=false, const ObjCObjectPointerType *OPT=nullptr, bool RecordFailure=true)
Try to "correct" a typo in the source code by finding visible declarations whose names are similar to...
QualType CheckComparisonCategoryType(ComparisonCategoryType Kind, SourceLocation Loc, ComparisonCategoryUsage Usage)
Lookup the specified comparison category types in the standard library, an check the VarDecls possibl...
void DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent)
DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was not used in the declaration of ...
SmallVector< VTableUse, 16 > VTableUses
The list of vtables that are required but have not yet been materialized.
Definition Sema.h:6105
PoppedFunctionScopePtr PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP=nullptr, Decl *D=nullptr, QualType BlockType=QualType())
Pop a function (or block or lambda or captured region) scope from the stack.
Definition Sema.cpp:2625
AccessResult CheckStructuredBindingMemberAccess(SourceLocation UseLoc, CXXRecordDecl *DecomposedClass, DeclAccessPair Field)
Checks implicit access to a member in a structured binding.
void EnterTemplatedContext(Scope *S, DeclContext *DC)
Enter a template parameter scope, after it's been associated with a particular DeclContext.
void ActOnBaseSpecifiers(Decl *ClassDecl, MutableArrayRef< CXXBaseSpecifier * > Bases)
ActOnBaseSpecifiers - Attach the given base specifiers to the class, after checking whether there are...
const FunctionProtoType * ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT)
void NoteTemplateLocation(const NamedDecl &Decl, std::optional< SourceRange > ParamRange={})
void DefineDefaultedComparison(SourceLocation Loc, FunctionDecl *FD, DefaultedComparisonKind DCK)
bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A, const NamedDecl *B)
Determine if A and B are equivalent internal linkage declarations from different modules,...
bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, QualType ObjectType, bool AllowBuiltinCreation=false, bool EnteringContext=false)
Performs name lookup for a name that was parsed in the source code, and may contain a C++ scope speci...
Preprocessor & PP
Definition Sema.h:1338
bool CheckConstexprFunctionDefinition(const FunctionDecl *FD, CheckConstexprKind Kind)
ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false, bool AllowRecovery=false)
BuildCallExpr - Handle a call to Fn with the specified array of arguments.
AccessResult CheckBaseClassAccess(SourceLocation AccessLoc, QualType Base, QualType Derived, const CXXBasePath &Path, unsigned DiagID, bool ForceCheck=false, bool ForceUnprivileged=false)
Checks access for a hierarchy conversion.
bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, UnexpandedParameterPackContext UPPC)
If the given type contains an unexpanded parameter pack, diagnose the error.
bool RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
bool BuildCtorClosureDefaultArgs(SourceLocation Loc, CXXConstructorDecl *Ctor, bool IsCopy=false)
NamedDecl * getShadowedDeclaration(const TypedefNameDecl *D, const LookupResult &R)
Return the declaration shadowed by the given typedef D, or null if it doesn't shadow any declaration ...
void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet)
AddBuiltinOperatorCandidates - Add the appropriate built-in operator overloads to the candidate set (...
void CheckExtraCXXDefaultArguments(Declarator &D)
CheckExtraCXXDefaultArguments - Check for any extra default arguments in the declarator,...
void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD)
void checkClassLevelDLLAttribute(CXXRecordDecl *Class)
Check class-level dllimport/dllexport attribute.
const LangOptions & LangOpts
Definition Sema.h:1337
std::pair< Expr *, std::string > findFailedBooleanCondition(Expr *Cond)
Find the failed Boolean condition within a given Boolean constant expression, and describe it with a ...
bool CheckExplicitlyDefaultedPostfixOperator(Scope *S, FunctionDecl *FD, PostfixOperatorKind Kind)
Check a defaulted postfix increment or decrement operator function (C++2d [over.inc....
void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock)
void MarkVirtualMembersReferenced(SourceLocation Loc, const CXXRecordDecl *RD, bool ConstexprOnly=false)
MarkVirtualMembersReferenced - Will mark all members of the given CXXRecordDecl referenced.
ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl)
Wrap the expression in a ConstantExpr if it is a potential immediate invocation.
ExprResult TemporaryMaterializationConversion(Expr *E)
If E is a prvalue denoting an unmaterialized temporary, materialize it as an xvalue.
NamedDeclSetType UnusedPrivateFields
Set containing all declared private fields that are not used.
Definition Sema.h:6703
SemaHLSL & HLSL()
Definition Sema.h:1528
void DefineInheritingConstructor(SourceLocation UseLoc, CXXConstructorDecl *Constructor)
Define the specified inheriting constructor.
bool CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, LookupResult &Previous, bool IsMemberSpecialization, bool DeclIsDefn)
Perform semantic checking of a new function declaration.
CXXRecordDecl * getStdBadAlloc() const
QualType CheckDestructorDeclarator(Declarator &D, QualType R, StorageClass &SC)
CheckDestructorDeclarator - Called by ActOnDeclarator to check the well-formednes of the destructor d...
bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange)
Mark the given method pure.
void SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg, SourceLocation EqualLoc)
void NoteHiddenVirtualMethods(CXXMethodDecl *MD, SmallVectorImpl< CXXMethodDecl * > &OverloadedMethods)
CXXMethodDecl * DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl)
Declare the implicit move assignment operator for the given class.
QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, SourceLocation KeywordLoc, NestedNameSpecifierLoc QualifierLoc, const IdentifierInfo &II, SourceLocation IILoc, TypeSourceInfo **TSI, bool DeducedTSTContext)
llvm::DenseMap< CXXRecordDecl *, bool > VTablesUsed
The set of classes whose vtables have been used within this translation unit, and a bit that will be ...
Definition Sema.h:6111
void CheckCXXDefaultArguments(FunctionDecl *FD)
Helpers for dealing with blocks and functions.
ComparisonCategoryUsage
Definition Sema.h:5479
@ DefaultedOperator
A defaulted 'operator<=>' needed the comparison category.
Definition Sema.h:5486
SmallVector< InventedTemplateParameterInfo, 4 > InventedParameterInfos
Stack containing information needed when in C++2a an 'auto' is encountered in a function declaration ...
Definition Sema.h:6696
void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse)
Perform marking for a reference to an arbitrary declaration.
void ProcessDeclAttributeList(Scope *S, Decl *D, const ParsedAttributesView &AttrList, const ProcessDeclAttributeOptions &Options=ProcessDeclAttributeOptions())
ProcessDeclAttributeList - Apply all the decl attributes in the specified attribute list to the speci...
void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, bool DefinitionRequired=false)
Note that the vtable for the given class was used at the given location.
NamedDecl * BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, SourceLocation EnumLoc, SourceLocation NameLoc, TypeSourceInfo *EnumType, EnumDecl *ED)
TypeLoc getReturnTypeLoc(FunctionDecl *FD) const
SmallVector< std::pair< const CXXMethodDecl *, const CXXMethodDecl * >, 2 > DelayedOverridingExceptionSpecChecks
All the overriding functions seen during a class definition that had their exception spec checks dela...
Definition Sema.h:6801
llvm::DenseMap< ParmVarDecl *, SourceLocation > UnparsedDefaultArgLocs
Definition Sema.h:6733
void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, const CXXRecordDecl *RD)
Mark the exception specifications of all virtual member functions in the given class as needed.
ExprResult BuildConvertedConstantExpression(Expr *From, QualType T, CCEKind CCE, NamedDecl *Dest=nullptr)
bool RequireCompleteEnumDecl(EnumDecl *D, SourceLocation L, CXXScopeSpec *SS=nullptr)
Require that the EnumDecl is completed with its enumerators defined or instantiated.
bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl)
CheckOverloadedOperatorDeclaration - Check whether the declaration of this overloaded operator is wel...
void MarkVirtualBaseDestructorsReferenced(SourceLocation Location, CXXRecordDecl *ClassDecl, llvm::SmallPtrSetImpl< const CXXRecordDecl * > *DirectVirtualBases=nullptr)
Mark destructors of virtual bases of this class referenced.
void ExitDeclaratorContext(Scope *S)
void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir)
void CheckConstructor(CXXConstructorDecl *Constructor)
CheckConstructor - Checks a fully-formed constructor for well-formedness, issuing any diagnostics req...
void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc, CXXConversionDecl *Conv)
Define the "body" of the conversion from a lambda object to a block pointer.
void DefineImplicitDestructor(SourceLocation CurrentLocation, CXXDestructorDecl *Destructor)
DefineImplicitDestructor - Checks for feasibility of defining this destructor as the default destruct...
void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMemberKind CSM)
Diagnose why the specified class does not have a trivial special member of the given kind.
Decl * ActOnUsingEnumDeclaration(Scope *CurScope, AccessSpecifier AS, SourceLocation UsingLoc, SourceLocation EnumLoc, SourceRange TyLoc, const IdentifierInfo &II, ParsedType Ty, const CXXScopeSpec &SS)
CXXRecordDecl * getCurrentClass(Scope *S, const CXXScopeSpec *SS)
Get the class that is directly named by the current context.
bool EvaluateAsString(Expr *Message, APValue &Result, ASTContext &Ctx, StringEvaluationContext EvalContext, bool ErrorOnInvalidMessage)
QualType BuildReferenceType(QualType T, bool LValueRef, SourceLocation Loc, DeclarationName Entity)
Build a reference type.
TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, QualType NTTPType, SourceLocation Loc)
Allocate a TemplateArgumentLoc where all locations have been initialized to the given location.
bool DiagnosePackIndexingInFriendNNS(SourceLocation Loc, NestedNameSpecifierLoc NNSLoc)
ExprResult ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr)
bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method)
Check whether 'this' shows up in the attributes of the given static member function.
ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *input, bool RequiresADL=true)
Create a unary operation that may resolve to an overloaded operator.
CXXBaseSpecifier * CheckBaseSpecifier(CXXRecordDecl *Class, SourceRange SpecifierRange, bool Virtual, AccessSpecifier Access, TypeSourceInfo *TInfo, SourceLocation EllipsisLoc)
Check the validity of a C++ base class specifier.
UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations
A mapping from parameters with unparsed default arguments to the set of instantiations of each parame...
Definition Sema.h:13374
void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor)
DefineImplicitDefaultConstructor - Checks for feasibility of defining this constructor as the default...
std::pair< CXXRecordDecl *, SourceLocation > VTableUse
The list of classes whose vtables have been used within this translation unit, and the source locatio...
Definition Sema.h:6101
ExprResult DefaultLvalueConversion(Expr *E)
Definition SemaExpr.cpp:652
bool CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Target, const LookupResult &PreviousDecls, UsingShadowDecl *&PrevShadow)
Determines whether to create a using shadow decl for a particular decl, given the set of decls existi...
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
bool isVisible(const NamedDecl *D)
Determine whether a declaration is visible to name lookup.
Definition Sema.h:15883
bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, SourceLocation Loc, SourceRange Range, CXXCastPath *BasePath=nullptr, bool IgnoreAccess=false)
Module * getCurrentModule() const
Get the module unit whose scope we are currently within.
Definition Sema.h:10096
bool CheckDeductionGuideDeclarator(Declarator &D, QualType &R, StorageClass &SC)
Check the validity of a declarator that we parsed for a deduction-guide.
void DiagPlaceholderVariableDefinition(SourceLocation Loc)
void CheckForFunctionRedefinition(FunctionDecl *FD, const FunctionDecl *EffectiveDefinition=nullptr, SkipBodyInfo *SkipBody=nullptr)
bool DiagnoseUseOfOverloadedDecl(NamedDecl *D, SourceLocation Loc)
Definition Sema.h:7178
std::unique_ptr< RecordDeclSetTy > PureVirtualClassDiagSet
PureVirtualClassDiagSet - a set of class declarations which we have emitted a list of pure virtual fu...
Definition Sema.h:6710
void ActOnFinishInlineFunctionDef(FunctionDecl *D)
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition Sema.h:1491
VarDecl * BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id)
Perform semantic analysis for the variable declaration that occurs within a C++ catch clause,...
void ActOnDocumentableDecl(Decl *D)
Should be called on all declarations that might have attached documentation comments.
ClassTemplateDecl * StdTypeIdentity
The C++ "std::type_identity" template, which is defined in <type_traits>.
Definition Sema.h:6729
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name)
Retrieves the declaration name from a parsed unqualified-id.
Decl * ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, MultiTemplateParamsArg TemplateParams, SourceLocation EllipsisLoc)
Handle a friend type declaration.
ExprResult PerformContextuallyConvertToBool(Expr *From)
PerformContextuallyConvertToBool - Perform a contextual conversion of the expression From to bool (C+...
void DefineImplicitCopyAssignment(SourceLocation CurrentLocation, CXXMethodDecl *MethodDecl)
Defines an implicitly-declared copy assignment operator.
bool CheckFunctionConstraints(const FunctionDecl *FD, ConstraintSatisfaction &Satisfaction, SourceLocation UsageLoc=SourceLocation(), bool ForOverloadResolution=false)
Check whether the given function decl's trailing requires clause is satisfied, if any.
bool SetDelegatingInitializer(CXXConstructorDecl *Constructor, CXXCtorInitializer *Initializer)
bool IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived, CXXRecordDecl *Base, CXXBasePaths &Paths)
Determine whether the type Derived is a C++ class that is derived from the type Base.
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5.
Definition Sema.h:8400
bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl)
CheckLiteralOperatorDeclaration - Check whether the declaration of this literal operator function is ...
bool DefineUsedVTables()
Define all of the vtables that have been used in this translation unit and reference any virtual memb...
CXXMethodDecl * DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl)
Declare the implicit copy assignment operator for the given class.
void checkIllFormedTrivialABIStruct(CXXRecordDecl &RD)
Check that the C++ class annoated with "trivial_abi" satisfies all the conditions that are needed for...
void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base=nullptr)
Perform reference-marking and odr-use handling for a DeclRefExpr.
StmtResult ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc, Stmt *First, ConditionResult Second, FullExprArg Third, SourceLocation RParenLoc, Stmt *Body)
unsigned ActOnReenterTemplateScope(Decl *Template, llvm::function_ref< Scope *()> EnterScope)
ExprResult BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl, CXXConstructorDecl *Constructor, MultiExprArg Exprs, bool HadMultipleCandidates, bool IsListInitialization, bool IsStdInitListInitialization, bool RequiresZeroInit, CXXConstructionKind ConstructKind, SourceRange ParenRange)
BuildCXXConstructExpr - Creates a complete call to a constructor, including handling of its default a...
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition Sema.h:14292
SourceManager & getSourceManager() const
Definition Sema.h:933
FunctionDecl * SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD, FunctionDecl *Spaceship)
Substitute the name and return type of a defaulted 'operator<=>' to form an implicit 'operator=='.
NamedDecl * ActOnDecompositionDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists)
ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow, SourceLocation OpLoc, const CXXScopeSpec &SS, FieldDecl *Field, DeclAccessPair FoundDecl, const DeclarationNameInfo &MemberNameInfo)
void diagnoseFunctionEffectMergeConflicts(const FunctionEffectSet::Conflicts &Errs, SourceLocation NewLoc, SourceLocation OldLoc)
void EnterDeclaratorContext(Scope *S, DeclContext *DC)
EnterDeclaratorContext - Used when we must lookup names in the context of a declarator's nested name ...
bool CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *MD, DefaultedComparisonKind DCK)
bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method)
Whether this' shows up in the exception specification of a static member function.
void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl, SourceLocation EqualLoc, ExprResult Init)
This is invoked after parsing an in-class initializer for a non-static C++ class member,...
Decl * ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, Expr *LangStr, SourceLocation LBraceLoc)
ActOnStartLinkageSpecification - Parsed the beginning of a C++ linkage specification,...
void FilterUsingLookup(Scope *S, LookupResult &lookup)
Remove decls we can't actually see from a lookup being used to declare shadow using decls.
void SetFunctionBodyKind(Decl *D, SourceLocation Loc, FnBodyKind BodyKind, StringLiteral *DeletedMessage=nullptr, Scope *S=nullptr)
Decl * ActOnExceptionDeclarator(Scope *S, Declarator &D)
ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch handler.
StringEvaluationContext
Definition Sema.h:6221
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param, Expr *Init=nullptr)
BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating the default expr if needed.
void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr, SourceLocation Loc)
PushNamespaceVisibilityAttr - Note that we've entered a namespace with a visibility attribute.
void ActOnDefaultCtorInitializers(Decl *CDtorDecl)
void ActOnMemInitializers(Decl *ConstructorDecl, SourceLocation ColonLoc, ArrayRef< CXXCtorInitializer * > MemInits, bool AnyErrors)
ActOnMemInitializers - Handle the member initializers for a constructor.
bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams)
Check whether a template can be declared within this scope.
ExprResult PerformImplicitConversion(Expr *From, QualType ToType, const ImplicitConversionSequence &ICS, AssignmentAction Action, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
PerformImplicitConversion - Perform an implicit conversion of the expression From to the type ToType ...
void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl)
ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an initializer for the declaration ...
FunctionDecl * BuildTypeAwareUsualDelete(FunctionTemplateDecl *FnDecl, QualType AllocType, SourceLocation)
void ActOnFinishCXXMemberSpecification(Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList)
void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, const LookupResult &R)
Diagnose variable or built-in function shadowing.
void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor)
Build an exception spec for destructors that don't have one.
Decl * ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, Expr *AssertExpr, Expr *AssertMessageExpr, SourceLocation RParenLoc)
void DiagnoseUnknownAttribute(const ParsedAttr &AL)
StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp, bool AllowRecovery=false)
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition Sema.h:15838
bool CheckImmediateEscalatingFunctionDefinition(FunctionDecl *FD, const sema::FunctionScopeInfo *FSI)
void CheckCompleteVariableDeclaration(VarDecl *VD)
ExprResult ActOnRequiresClause(ExprResult ConstraintExpr)
QualType CheckTemplateIdType(ElaboratedTypeKeyword Keyword, TemplateName Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs, Scope *Scope, bool ForNestedNameSpecifier)
void checkClassLevelCodeSegAttribute(CXXRecordDecl *Class)
bool isStdInitializerList(QualType Ty, QualType *Element)
Tests whether Ty is an instance of std::initializer_list and, if it is and Element is not NULL,...
RedeclarationKind forRedeclarationInCurContext() const
LazyDeclPtr StdNamespace
The C++ "std" namespace, where the standard library resides.
Definition Sema.h:6721
bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc, bool HasTypenameKeyword, const CXXScopeSpec &SS, SourceLocation NameLoc, const LookupResult &Previous)
Checks that the given using declaration is not an invalid redeclaration.
void FinalizeVarWithDestructor(VarDecl *VD, CXXRecordDecl *DeclInit)
FinalizeVarWithDestructor - Prepare for calling destructor on the constructed variable.
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, AllowFoldKind CanFold=AllowFoldKind::No)
VerifyIntegerConstantExpression - Verifies that an expression is an ICE, and reports the appropriate ...
IntrusiveRefCntPtr< ExternalSemaSource > ExternalSource
Source of additional semantic information.
Definition Sema.h:1629
ASTConsumer & Consumer
Definition Sema.h:1340
void ActOnFinishCXXMemberDecls()
Perform any semantic analysis which needs to be delayed until all pending class member declarations h...
llvm::SmallPtrSet< const Decl *, 4 > ParsingInitForAutoVars
ParsingInitForAutoVars - a set of declarations with auto types for which we are currently parsing the...
Definition Sema.h:4855
void DefineDefaultedPostfixOperator(SourceLocation Loc, FunctionDecl *FD, PostfixOperatorKind Kind)
Synthesize the body of a defaulted postfix increment or decrement operator function (C++2d [over....
void NoteDeletedFunction(FunctionDecl *FD)
Emit a note explaining that this function is deleted.
Definition SemaExpr.cpp:130
sema::AnalysisBasedWarnings AnalysisWarnings
Worker object for performing CFG-based warnings.
Definition Sema.h:1379
ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc)
Decl * ActOnFinishLinkageSpecification(Scope *S, Decl *LinkageSpec, SourceLocation RBraceLoc)
ActOnFinishLinkageSpecification - Complete the definition of the C++ linkage specification LinkageSpe...
bool CheckInheritingConstructorUsingDecl(UsingDecl *UD)
Additional checks for a using declaration referring to a constructor name.
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
Definition Sema.h:6931
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
Definition Sema.h:6941
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6910
QualType BuildDecltypeType(Expr *E, bool AsUnevaluated=true)
If AsUnevaluated is false, E is treated as though it were an evaluated context, such as when building...
TypeSourceInfo * GetTypeForDeclarator(Declarator &D)
GetTypeForDeclarator - Convert the type for the specified declarator to Type instances.
void diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, bool ErrorRecovery=true)
DeclResult ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, AccessSpecifier AS, SourceLocation ModulePrivateLoc, MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl, bool &IsDependent, SourceLocation ScopedEnumKWLoc, bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, bool IsTypeSpecifier, bool IsTemplateParamOrArg, OffsetOfKind OOK, SkipBodyInfo *SkipBody=nullptr)
This is invoked when we see 'struct foo' or 'struct {'.
void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace)
ActOnFinishNamespaceDef - This callback is called after a namespace is exited.
MemInitResult BuildMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS, IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy, const DeclSpec &DS, SourceLocation IdLoc, Expr *Init, SourceLocation EllipsisLoc)
Handle a C++ member initializer.
StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl, SourceLocation StartLoc, SourceLocation EndLoc)
Definition SemaStmt.cpp:77
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
void actOnDelayedExceptionSpecification(Decl *D, ExceptionSpecificationType EST, SourceRange SpecificationRange, ArrayRef< ParsedType > DynamicExceptions, ArrayRef< SourceRange > DynamicExceptionRanges, Expr *NoexceptExpr)
Add an exception-specification to the given member or friend function (or function template).
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition Sema.h:1298
bool CheckDependentFriend(SourceLocation Loc, NestedNameSpecifierLoc NNSLoc, ArrayRef< TemplateParameterList * > TPLs, bool IsInstantiation)
void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, ArrayRef< Decl * > Fields, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList)
void CheckExplicitObjectLambda(Declarator &D)
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD)
void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc)
PopPragmaVisibility - Pop the top element of the visibility stack; used for '#pragma GCC visibility' ...
Expr * MaybeCreateExprWithCleanups(Expr *SubExpr)
MaybeCreateExprWithCleanups - If the current full-expression requires any cleanups,...
void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init)
Check that the lifetime of the initializer (and its subobjects) is sufficient for initializing the en...
void CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record)
Perform semantic checks on a class definition that has been completing, introducing implicitly-declar...
void DiscardCleanupsInEvaluationContext()
void PushDeclContext(Scope *S, DeclContext *DC)
Set the current declaration context until it gets popped.
bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New)
void mergeDeclAttributes(NamedDecl *New, Decl *Old, AvailabilityMergeKind AMK=AvailabilityMergeKind::Redeclaration)
mergeDeclAttributes - Copy attributes from the Old decl to the New one.
bool isDependentScopeSpecifier(const CXXScopeSpec &SS)
SourceManager & SourceMgr
Definition Sema.h:1342
bool CheckDestructor(CXXDestructorDecl *Destructor)
CheckDestructor - Checks a fully-formed destructor definition for well-formedness,...
NamedDecl * BuildUsingPackDecl(NamedDecl *InstantiatedFrom, ArrayRef< NamedDecl * > Expansions)
MemInitResult ActOnMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS, IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy, const DeclSpec &DS, SourceLocation IdLoc, SourceLocation LParenLoc, ArrayRef< Expr * > Args, SourceLocation RParenLoc, SourceLocation EllipsisLoc)
Handle a C++ member initializer using parentheses syntax.
void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc, StringLiteral *Message=nullptr)
ExprResult BuildCXXCtorDefaultInitExpr(SourceLocation Loc, FieldDecl *Field)
void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method)
ActOnStartDelayedCXXMethodDeclaration - We have completed parsing a top-level (non-nested) C++ class,...
DiagnosticsEngine & Diags
Definition Sema.h:1341
FullExprArg MakeFullDiscardedValueExpr(Expr *Arg)
Definition Sema.h:8007
FPOptions CurFPFeatures
Definition Sema.h:1335
TypeAwareAllocationMode ShouldUseTypeAwareOperatorNewOrDelete() const
CXXConstructorDecl * DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl)
Declare the implicit copy constructor for the given class.
NamespaceDecl * getStdNamespace() const
llvm::SmallPtrSet< const CXXRecordDecl *, 8 > RecordDeclSetTy
Definition Sema.h:6705
void DeclareImplicitEqualityComparison(CXXRecordDecl *RD, FunctionDecl *Spaceship)
bool AttachBaseSpecifiers(CXXRecordDecl *Class, MutableArrayRef< CXXBaseSpecifier * > Bases)
Performs the actual work of attaching the given base class specifiers to a C++ class.
void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl)
ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an initializer for the declaratio...
static bool adjustContextForLocalExternDecl(DeclContext *&DC)
Adjust the DeclContext for a function or variable that might be a function-local external declaration...
SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D, CXXSpecialMemberKind SM, bool ConstArg, bool VolatileArg, bool RValueThis, bool ConstThis, bool VolatileThis)
NamedDecl * ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *D, LookupResult &Previous, bool &Redeclaration)
ActOnTypedefNameDecl - Perform semantic checking for a declaration which declares a typedef-name,...
ExprResult ActOnIntegerConstant(SourceLocation Loc, int64_t Val)
Decl * ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList, SourceLocation SemiLoc)
Handle a C++11 empty-declaration and attribute-declaration.
friend class InitializationSequence
Definition Sema.h:1633
void PopDeclContext()
void diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals, SourceLocation FallbackLoc, SourceLocation ConstQualLoc=SourceLocation(), SourceLocation VolatileQualLoc=SourceLocation(), SourceLocation RestrictQualLoc=SourceLocation(), SourceLocation AtomicQualLoc=SourceLocation(), SourceLocation UnalignedQualLoc=SourceLocation())
llvm::MapVector< NamedDecl *, SourceLocation > UndefinedButUsed
UndefinedInternals - all the used, undefined objects which require a definition in this translation u...
Definition Sema.h:6737
QualType CheckConstructorDeclarator(Declarator &D, QualType R, StorageClass &SC)
CheckConstructorDeclarator - Called by ActOnDeclarator to check the well-formedness of the constructo...
ExprResult ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg, SourceLocation EqualLoc)
void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD)
ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in it, apply them to D.
void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, bool ConsiderLinkage, bool AllowInlineNamespace)
Filters out lookup results that don't fall within the given scope as determined by isDeclInScope.
ExprResult ConvertMemberDefaultInitExpression(FieldDecl *FD, Expr *InitExpr, SourceLocation InitLoc)
bool IsInvalidSMECallConversion(QualType FromType, QualType ToType)
void checkIncorrectVTablePointerAuthenticationAttribute(CXXRecordDecl &RD)
Check that VTable Pointer authentication is only being set on the first first instantiation of the vt...
static Scope * getScopeForDeclContext(Scope *S, DeclContext *DC)
Finds the scope corresponding to the given decl context, if it happens to be an enclosing scope.
void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit)
AddInitializerToDecl - Adds the initializer Init to the declaration dcl.
bool isUsualDeallocationFunction(const CXXMethodDecl *FD)
void DiagnoseDeletedDefaultedFunction(FunctionDecl *FD)
Produce notes explaining why a defaulted function was defined as deleted.
ExprResult BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind, TypeSourceInfo *Ty, Expr *E, SourceRange AngleBrackets, SourceRange Parens)
Definition SemaCast.cpp:340
bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New, const CXXMethodDecl *Old)
CheckOverridingFunctionExceptionSpec - Checks whether the exception spec is a subset of base spec.
SmallVector< CXXRecordDecl *, 4 > DelayedDllExportClasses
Definition Sema.h:6527
void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, bool MightBeOdrUse=true)
Mark a function referenced, and check whether it is odr-used (C++ [basic.def.odr]p2,...
bool CheckTemplateParameterList(TemplateParameterList *NewParams, TemplateParameterList *OldParams, TemplateParamListContext TPC, SkipBodyInfo *SkipBody=nullptr)
Checks the validity of a template parameter list, possibly considering the template parameter list fr...
bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New, const CXXMethodDecl *Old)
CheckOverridingFunctionReturnType - Checks whether the return types are covariant,...
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
UnsignedOrNone GetDecompositionElementCount(QualType DecompType, SourceLocation Loc)
DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams, AccessSpecifier AS, SourceLocation ModulePrivateLoc, SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists, TemplateParameterList **OuterTemplateParamLists, bool IsMemberSpecialization, SkipBodyInfo *SkipBody=nullptr)
Decl * ActOnDeclarator(Scope *S, Declarator &D)
AbstractDiagSelID
Definition Sema.h:6473
@ AbstractVariableType
Definition Sema.h:6477
@ AbstractReturnType
Definition Sema.h:6475
@ AbstractNone
Definition Sema.h:6474
@ AbstractFieldType
Definition Sema.h:6478
@ AbstractArrayType
Definition Sema.h:6481
@ AbstractParamType
Definition Sema.h:6476
MSPropertyDecl * HandleMSProperty(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, InClassInitStyle InitStyle, AccessSpecifier AS, const ParsedAttr &MSPropertyAttr)
HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
void UpdateExceptionSpec(FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI)
bool CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old)
A wrapper function for checking the semantic restrictions of a redeclaration within a module.
LazyDeclPtr StdAlignValT
The C++ "std::align_val_t" enum class, which is defined by the C++ standard library.
Definition Sema.h:8589
llvm::DenseMap< SpecialMemberCacheKey, SpecialMemberOverloadResult > SpecialMemberCache
A cache of special member function overload resolution results for C++ records.
Definition Sema.h:9554
DeclResult ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, unsigned TagSpec, SourceLocation TagLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, SourceLocation EllipsisLoc, const ParsedAttributesView &Attr, MultiTemplateParamsArg TempParamLists, TemplateIdAnnotation *TemplateId)
Handle a friend tag declaration where the scope specifier was templated.
void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc)
CheckConstexprKind
Definition Sema.h:6609
@ CheckValid
Identify whether this function satisfies the formal rules for constexpr functions in the current lanu...
Definition Sema.h:6614
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
Definition Sema.h:6611
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false, bool ForceNoCPlusPlus=false)
Perform unqualified name lookup starting from a given scope.
void LoadExternalVTableUses()
Load any externally-stored vtable uses.
static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo=nullptr)
Decl * ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc, SourceLocation NamespcLoc, CXXScopeSpec &SS, SourceLocation IdentLoc, IdentifierInfo *NamespcName, const ParsedAttributesView &AttrList)
StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R, ArrayRef< Stmt * > Elts, bool isStmtExpr)
Definition SemaStmt.cpp:458
void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, QualType FromType, QualType ToType)
HandleFunctionTypeMismatch - Gives diagnostic information for differeing function types.
void ActOnStartTrailingRequiresClause(Scope *S, Declarator &D)
void FindHiddenVirtualMethods(CXXMethodDecl *MD, SmallVectorImpl< CXXMethodDecl * > &OverloadedMethods)
Check if a method overloads virtual methods in a base class without overriding any.
IdentifierResolver IdResolver
Definition Sema.h:3652
DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class)
Look up the constructors for the given class.
void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record)
TypeResult ActOnTagTemplateIdType(TagUseKind TUK, TypeSpecifierType TagSpec, SourceLocation TagLoc, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy TemplateD, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc)
Parsed an elaborated-type-specifier that refers to a template-id, such as class T::template apply.
ExprResult ActOnCXXThis(SourceLocation Loc)
CXXConstructorDecl * findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor, ConstructorUsingShadowDecl *DerivedShadow)
Given a derived-class using shadow declaration for a constructor and the correspnding base class cons...
void warnOnReservedIdentifier(const NamedDecl *D)
bool CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD, CXXSpecialMemberKind CSM, SourceLocation DefaultLoc)
bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS)
Determine whether the identifier II is a typo for the name of the class type currently being defined.
Decl * ActOnUsingDeclaration(Scope *CurScope, AccessSpecifier AS, SourceLocation UsingLoc, SourceLocation TypenameLoc, CXXScopeSpec &SS, UnqualifiedId &Name, SourceLocation EllipsisLoc, const ParsedAttributesView &AttrList)
void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param)
ActOnDelayedCXXMethodParameter - We've already started a delayed C++ method declaration.
bool isAbstractType(SourceLocation Loc, QualType T)
ValueDecl * tryLookupUnambiguousFieldDecl(RecordDecl *ClassDecl, const IdentifierInfo *MemberOrBase)
ASTMutationListener * getASTMutationListener() const
Definition Sema.cpp:669
bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, ArrayRef< CXXCtorInitializer * > Initializers={})
void DiagnoseImmediateEscalatingReason(FunctionDecl *FD)
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition Sema.h:8884
CXXDestructorDecl * DeclareImplicitDestructor(CXXRecordDecl *ClassDecl)
Declare the implicit destructor for the given class.
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
A trivial tuple used to represent a source range.
bool isInvalid() const
SourceLocation getEnd() const
SourceLocation getBegin() const
static StaticAssertDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StaticAssertLoc, Expr *AssertExpr, Expr *Message, SourceLocation RParenLoc, bool Failed)
Definition DeclCXX.cpp:3680
Stmt - This represents one statement.
Definition Stmt.h:85
SourceLocation getEndLoc() const LLVM_READONLY
Definition Stmt.cpp:367
child_range children()
Definition Stmt.cpp:304
StmtClass getStmtClass() const
Definition Stmt.h:1504
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:355
static bool isValidUDSuffix(const LangOptions &LangOpts, StringRef Suffix)
Determine whether a suffix is a valid ud-suffix.
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1844
bool isUnevaluated() const
Definition Expr.h:1982
StringRef getString() const
Definition Expr.h:1912
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3898
bool isBeingDefined() const
Return true if this decl is currently being defined.
Definition Decl.h:4019
StringRef getKindName() const
Definition Decl.h:4094
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3999
TagDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:5010
bool isUnion() const
Definition Decl.h:4109
TagKind getTagKind() const
Definition Decl.h:4098
bool isDependentType() const
Whether this declaration declares a type that is dependent, i.e., a type that somehow depends on temp...
Definition Decl.h:4044
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:805
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
A convenient class for passing around template argument information.
void addArgument(const TemplateArgumentLoc &Loc)
ArrayRef< TemplateArgumentLoc > arguments() const
Location wrapper for a TemplateArgument.
const TemplateArgument & getArgument() const
TypeSourceInfo * getTypeSourceInfo() const
Represents a template argument.
@ Type
The template argument is a type.
ArgKind getKind() const
Return the kind of stored template argument.
The base class of all kinds of template declarations (e.g., class, function, etc.).
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Represents a C++ template name within the type system.
TemplateDecl * getAsTemplateDecl(bool IgnoreDeduced=false) const
Retrieve the underlying template declaration that this template name refers to, if known.
QualifiedTemplateName * getAsQualifiedTemplateName() const
Retrieve the underlying qualified template name structure, if any.
Stores a list of template parameters for a TemplateDecl and its derived classes.
NamedDecl * getParam(unsigned Idx)
SourceRange getSourceRange() const LLVM_READONLY
unsigned getDepth() const
Get the depth of this template parameter list in the set of template parameter lists.
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to form a template specialization.
static TemplateParameterList * Create(const ASTContext &C, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< NamedDecl * > Params, SourceLocation RAngleLoc, Expr *RequiresClause)
Expr * getRequiresClause()
The constraint-expression of the associated requires-clause.
SourceLocation getRAngleLoc() const
SourceLocation getLAngleLoc() const
static bool shouldIncludeTypeForArgument(const PrintingPolicy &Policy, const TemplateParameterList *TPL, unsigned Idx)
SourceLocation getTemplateLoc() const
TemplateArgumentLoc getArgLoc(unsigned i) const
Definition TypeLoc.h:1948
Declaration of a template type parameter.
unsigned getIndex() const
Retrieve the index of the template parameter.
unsigned getDepth() const
Retrieve the depth of the template parameter.
The top declaration context.
Definition Decl.h:107
Represents the declaration of a typedef-name via a C++11 alias-declaration.
Definition Decl.h:3869
static TypeAliasDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition Decl.cpp:5927
void setDescribedAliasTemplate(TypeAliasTemplateDecl *TAT)
Definition Decl.h:3888
Declaration of an alias template.
static TypeAliasTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, NamedDecl *Decl)
Create a function template node.
TypeAliasDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
Represents a declaration of a type.
Definition Decl.h:3694
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
TypeSpecTypeLoc pushTypeSpec(QualType T)
Pushes space for a typespec TypeLoc.
TypeSourceInfo * getTypeSourceInfo(ASTContext &Context, QualType T)
Creates a TypeSourceInfo for the given type.
Base wrapper for a particular "section" of type source info.
Definition TypeLoc.h:59
QualType getType() const
Get the type for which this source info wrapper provides information.
Definition TypeLoc.h:133
TypeLoc getNextTypeLoc() const
Get the next TypeLoc pointed by this TypeLoc, e.g for "int*" the TypeLoc is a PointerLoc and next Typ...
Definition TypeLoc.h:171
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition TypeLoc.h:89
NestedNameSpecifierLoc getPrefix() const
If this type represents a qualified-id, this returns it's nested name specifier.
Definition TypeLoc.cpp:478
TypeLoc IgnoreParens() const
Definition TypeLoc.h:1468
T castAs() const
Convert to the specified TypeLoc type, asserting that this TypeLoc is of the desired type.
Definition TypeLoc.h:78
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition TypeLoc.h:154
SourceRange getLocalSourceRange() const
Get the local source range.
Definition TypeLoc.h:160
TypeLocClass getTypeLocClass() const
Definition TypeLoc.h:116
bool isNull() const
Definition TypeLoc.h:121
SourceLocation getEndLoc() const
Get the end source location.
Definition TypeLoc.cpp:227
T getAsAdjusted() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition TypeLoc.h:2787
SourceLocation getBeginLoc() const
Get the begin source location.
Definition TypeLoc.cpp:193
A container of type source information.
Definition TypeBase.h:8549
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition TypeLoc.h:267
QualType getType() const
Return the type wrapped by this type source info.
Definition TypeBase.h:8560
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:551
The base class of the type hierarchy.
Definition TypeBase.h:1879
bool isVoidType() const
Definition TypeBase.h:9200
bool isBooleanType() const
Definition TypeBase.h:9341
const TemplateSpecializationType * getAsNonAliasTemplateSpecializationType() const
Look through sugar for an instance of TemplateSpecializationType which is not a type alias,...
Definition Type.cpp:2092
bool isIncompleteArrayType() const
Definition TypeBase.h:8922
bool isUndeducedAutoType() const
Definition TypeBase.h:9011
bool isRValueReferenceType() const
Definition TypeBase.h:8847
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
bool isArrayType() const
Definition TypeBase.h:8914
bool isPointerType() const
Definition TypeBase.h:8815
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9248
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9498
bool isReferenceType() const
Definition TypeBase.h:8839
bool isEnumeralType() const
Definition TypeBase.h:8946
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:885
TagDecl * getAsTagDecl() const
Retrieves the TagDecl that this type refers to, either because the type is a TagType or because it is...
Definition Type.h:63
bool isLValueReferenceType() const
Definition TypeBase.h:8843
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition TypeBase.h:9169
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2863
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type.
Definition Type.cpp:2235
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition TypeBase.h:2469
QualType getCanonicalTypeInternal() const
Definition TypeBase.h:3200
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition TypeBase.h:9384
bool isFunctionProtoType() const
Definition TypeBase.h:2665
bool isOverloadableType() const
Determines whether this is a type for which one can define an overloaded operator.
Definition TypeBase.h:9354
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition TypeBase.h:2881
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9347
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition Type.h:53
bool isFunctionType() const
Definition TypeBase.h:8811
bool isStructureOrClassType() const
Definition Type.cpp:839
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2535
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:3002
bool isUnsignedIntegerType() const
Return true if this is an integer type that is unsigned, according to C99 6.2.5p6 [which returns true...
Definition Type.cpp:2462
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9431
bool isRecordType() const
Definition TypeBase.h:8942
bool isUnionType() const
Definition Type.cpp:851
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3743
QualType getUnderlyingType() const
Definition Decl.h:3798
Wrapper for source info for typedefs.
Definition TypeLoc.h:777
Simple class containing the result of Sema::CorrectTypo.
NamedDecl * getCorrectionDecl() const
Gets the pointer to the declaration of the typo correction.
SourceRange getCorrectionRange() const
void WillReplaceSpecifier(bool ForceReplacement)
DeclClass * getCorrectionDeclAs() const
NestedNameSpecifier getCorrectionSpecifier() const
Gets the NestedNameSpecifier needed to use the typo correction.
NamedDecl * getFoundDecl() const
Get the correction declaration found by name lookup (before we looked through using shadow declaratio...
Expr * getSubExpr() const
Definition Expr.h:2354
Opcode getOpcode() const
Definition Expr.h:2349
static bool isIncrementDecrementOp(Opcode Op)
Definition Expr.h:2409
static UnaryOperator * Create(const ASTContext &C, Expr *input, Opcode opc, QualType type, ExprValueKind VK, ExprObjectKind OK, SourceLocation l, bool CanOverflow, FPOptionsOverride FPFeatures)
Definition Expr.cpp:5201
TypeLocClass getTypeLocClass() const
Definition TypeLoc.h:283
Represents a C++ unqualified-id that has been parsed.
Definition DeclSpec.h:1114
UnionParsedType ConversionFunctionId
When Kind == IK_ConversionFunctionId, the type that the conversion function names.
Definition DeclSpec.h:1150
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:1326
SourceRange getSourceRange() const LLVM_READONLY
Return the source range that covers this unqualified-id.
Definition DeclSpec.h:1323
UnionParsedType DestructorName
When Kind == IK_DestructorName, the type referred to by the class-name.
Definition DeclSpec.h:1158
SourceLocation StartLocation
The location of the first token that describes this unqualified-id, which will be the location of the...
Definition DeclSpec.h:1172
UnionParsedTemplateTy TemplateName
When Kind == IK_DeductionGuideName, the parsed template-name.
Definition DeclSpec.h:1161
const IdentifierInfo * Identifier
When Kind == IK_Identifier, the parsed identifier, or when Kind == IK_UserLiteralId,...
Definition DeclSpec.h:1142
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition DeclSpec.h:1196
TemplateIdAnnotation * TemplateId
When Kind == IK_TemplateId or IK_ConstructorTemplateId, the template-id annotation that contains the ...
Definition DeclSpec.h:1166
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, UnresolvedSetIterator Begin, UnresolvedSetIterator End, bool KnownDependent, bool KnownInstantiationDependent)
Definition ExprCXX.cpp:464
A set of unresolved declarations.
void assign(Iter I, Iter E)
ArrayRef< DeclAccessPair > pairs() const
The iterator over UnresolvedSets.
A set of unresolved declarations.
This node is generated when a using-declaration that was annotated with attribute((using_if_exists)) ...
Definition DeclCXX.h:4165
static UnresolvedUsingIfExistsDecl * Create(ASTContext &Ctx, DeclContext *DC, SourceLocation Loc, DeclarationName Name)
Definition DeclCXX.cpp:3659
Wrapper for source info for unresolved typename using decls.
Definition TypeLoc.h:782
static UnresolvedUsingTypenameDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc, SourceLocation TypenameLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TargetNameLoc, DeclarationName TargetName, SourceLocation EllipsisLoc)
Definition DeclCXX.cpp:3638
static UnresolvedUsingValueDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, SourceLocation EllipsisLoc)
Definition DeclCXX.cpp:3610
Represents a C++ using-declaration.
Definition DeclCXX.h:3638
bool hasTypename() const
Return true if the using declaration has 'typename'.
Definition DeclCXX.h:3687
NestedNameSpecifier getQualifier() const
Retrieve the nested-name-specifier that qualifies the name.
Definition DeclCXX.h:3675
DeclarationNameInfo getNameInfo() const
Definition DeclCXX.h:3679
static UsingDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingL, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool HasTypenameKeyword)
Definition DeclCXX.cpp:3547
SourceLocation getUsingLoc() const
Return the source location of the 'using' keyword.
Definition DeclCXX.h:3665
Represents C++ using-directive.
Definition DeclCXX.h:3143
static UsingDirectiveDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc, SourceLocation NamespaceLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation IdentLoc, NamedDecl *Nominated, DeclContext *CommonAncestor)
Definition DeclCXX.cpp:3330
Represents a C++ using-enum-declaration.
Definition DeclCXX.h:3839
static UsingEnumDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingL, SourceLocation EnumL, SourceLocation NameL, TypeSourceInfo *EnumType)
Definition DeclCXX.cpp:3568
static UsingPackDecl * Create(ASTContext &C, DeclContext *DC, NamedDecl *InstantiatedFrom, ArrayRef< NamedDecl * > UsingDecls)
Definition DeclCXX.cpp:3590
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3446
static UsingShadowDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation Loc, DeclarationName Name, BaseUsingDecl *Introducer, NamedDecl *Target)
Definition DeclCXX.h:3482
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition DeclCXX.h:3510
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
BaseUsingDecl * getIntroducer() const
Gets the (written or instantiated) using declaration that introduced this declaration.
Definition DeclCXX.cpp:3487
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:714
void setType(QualType newType)
Definition Decl.h:726
QualType getType() const
Definition Decl.h:725
bool isParameterPack() const
Determine whether this value is actually a function parameter pack, init-capture pack,...
Definition Decl.cpp:5703
Represents a variable declaration or definition.
Definition Decl.h:934
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition Decl.cpp:2804
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition Decl.cpp:2134
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition Decl.h:1606
DefinitionKind isThisDeclarationADefinition(ASTContext &) const
Check whether this declaration is a definition.
Definition Decl.cpp:2258
bool evaluateConstantDestruction(SmallVectorImpl< PartialDiagnosticAt > &Notes, SemaProxy &SProxy) const
Evaluate the destruction of a variable that is required by the language to have constant destruction.
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:2173
bool isNoDestroy(const ASTContext &) const
Is destruction of this variable entirely suppressed?
Definition Decl.cpp:2830
void setCXXCondDecl()
Definition Decl.h:1652
bool isInlineSpecified() const
Definition Decl.h:1591
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1308
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition Decl.h:1249
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition Decl.h:1216
void setNRVOVariable(bool NRVO)
Definition Decl.h:1552
QualType::DestructionKind needsDestruction(const ASTContext &Ctx) const
Would the destruction of this variable have any effect, and if so, what kind?
Definition Decl.cpp:2845
ThreadStorageClassSpecifier getTSCSpec() const
Definition Decl.h:1185
const Expr * getInit() const
Definition Decl.h:1393
const APValue * evaluateValue() const
Attempt to evaluate the value of the initializer attached to this declaration, and produce notes expl...
Definition Decl.cpp:2570
@ TLS_Dynamic
TLS with a dynamic initializer.
Definition Decl.h:960
void setInit(Expr *I)
Definition Decl.cpp:2472
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition Decl.h:1176
bool isUsableInConstantExpressions(const ASTContext &C) const
Determine whether this variable's value can be used in a constant expression, according to the releva...
Definition Decl.cpp:2523
void setExceptionVariable(bool EV)
Definition Decl.h:1534
Declaration of a variable template.
Represents a GCC generic vector type.
Definition TypeBase.h:4398
unsigned getNumElements() const
Definition TypeBase.h:4413
QualType getElementType() const
Definition TypeBase.h:4412
Represents a C++11 virt-specifier-seq.
Definition DeclSpec.h:2904
SourceLocation getOverrideLoc() const
Definition DeclSpec.h:2924
SourceLocation getLastLocation() const
Definition DeclSpec.h:2936
bool isOverrideSpecified() const
Definition DeclSpec.h:2923
SourceLocation getFinalLoc() const
Definition DeclSpec.h:2928
bool isFinalSpecified() const
Definition DeclSpec.h:2926
bool isFinalSpelledSealed() const
Definition DeclSpec.h:2927
Retains information about a function, method, or block that is currently being parsed.
Definition ScopeInfo.h:104
bool FoundImmediateEscalatingExpression
Whether we found an immediate-escalating expression.
Definition ScopeInfo.h:179
Provides information about an attempted template argument deduction, whose success or failure was des...
Defines the clang::TargetInfo interface.
#define UINT_MAX
Definition limits.h:64
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
bool Comp(InterpState &S)
1) Pops the value from the stack.
Definition Interp.h:1176
bool Inc(InterpState &S, CodePtr OpPC, bool CanOverflow)
1) Pops a pointer from the stack 2) Load the value from the pointer 3) Writes the value increased by ...
Definition Interp.h:960
std::variant< struct RequiresDecl, struct HeaderDecl, struct UmbrellaDirDecl, struct ModuleDecl, struct ExcludeDecl, struct ExportDecl, struct ExportAsDecl, struct ExternModuleDecl, struct UseDecl, struct LinkDecl, struct ConfigMacrosDecl, struct ConflictDecl > Decl
All declarations that can appear in a module declaration.
Stencil access(llvm::StringRef BaseId, Stencil Member)
Constructs a MemberExpr that accesses the named member (Member) of the object bound to BaseId.
Top level wrappers for InstallAPI frontend operations.
bool FTIHasNonVoidParameters(const DeclaratorChunk::FunctionTypeInfo &FTI)
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
TypeSpecifierType
Specifies the kind of type.
Definition Specifiers.h:56
@ TST_decltype
Definition Specifiers.h:90
@ TST_typename_pack_indexing
Definition Specifiers.h:98
@ TST_decltype_auto
Definition Specifiers.h:94
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
@ OO_None
Not an overloaded operator.
@ NUM_OVERLOADED_OPERATORS
@ NonFunction
This is not an overload because the lookup results contain a non-function.
Definition Sema.h:828
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:824
@ Overload
This is a legitimate overload: the existing declarations are functions or function templates with dif...
Definition Sema.h:820
bool isa(CodeGen::Address addr)
Definition Address.h:330
bool isTemplateInstantiation(TemplateSpecializationKind Kind)
Determine whether this template specialization kind refers to an instantiation of an entity (as oppos...
Definition Specifiers.h:216
@ CPlusPlus23
@ CPlusPlus20
@ CPlusPlus
@ CPlusPlus11
@ CPlusPlus29
@ CPlusPlus14
@ CPlusPlus26
@ CPlusPlus17
MutableArrayRef< TemplateParameterList * > MultiTemplateParamsArg
Definition Ownership.h:263
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
@ OR_Deleted
Succeeded, but refers to a deleted function.
Definition Overload.h:61
@ OR_Success
Overload resolution succeeded.
Definition Overload.h:52
@ OR_Ambiguous
Ambiguous candidates found.
Definition Overload.h:58
@ OR_No_Viable_Function
No viable function found.
Definition Overload.h:55
VariadicCallType
Definition Sema.h:507
ConstexprSpecKind
Define the kind of constexpr specifier.
Definition Specifiers.h:36
LinkageSpecLanguageIDs
Represents the language in a linkage specification.
Definition DeclCXX.h:3054
@ Ambiguous
Name lookup results in an ambiguity; use getAmbiguityKind to figure out what kind of ambiguity we hav...
Definition Lookup.h:64
@ NotFound
No entity found met the criteria.
Definition Lookup.h:41
@ FoundOverloaded
Name lookup found a set of overloaded functions that met the criteria.
Definition Lookup.h:54
@ Found
Name lookup found a single declaration that met the criteria.
Definition Lookup.h:50
@ FoundUnresolvedValue
Name lookup found an unresolvable value declaration and cannot yet complete.
Definition Lookup.h:59
@ NotFoundInCurrentInstantiation
No entity found met the criteria within the current instantiation,, but there were dependent base cla...
Definition Lookup.h:46
LLVM_READONLY auto escapeCStyle(CharT Ch) -> StringRef
Return C-style escaped string for special characters, or an empty string if there is no such mapping.
Definition CharInfo.h:191
@ Comparison
A comparison.
Definition Sema.h:661
InClassInitStyle
In-class initialization styles for non-static data members.
Definition Specifiers.h:275
@ ICIS_ListInit
Direct list-initialization.
Definition Specifiers.h:278
@ ICIS_NoInit
No in-class initializer.
Definition Specifiers.h:276
@ RQ_None
No ref-qualifier was provided.
Definition TypeBase.h:1801
@ RQ_RValue
An rvalue ref-qualifier was provided (&&).
Definition TypeBase.h:1807
@ TemplateName
The identifier is a template name. FIXME: Add an annotation for that.
Definition Parser.h:61
@ OCD_AmbiguousCandidates
Requests that only tied-for-best candidates be shown.
Definition Overload.h:73
@ OCD_AllCandidates
Requests that all candidates be shown.
Definition Overload.h:67
CXXConstructionKind
Definition ExprCXX.h:1545
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition Specifiers.h:155
@ Redeclaration
Merge availability attributes for a redeclaration, which requires an exact match.
Definition Sema.h:627
std::pair< llvm::PointerUnion< const TemplateTypeParmType *, NamedDecl *, const TemplateSpecializationType *, const SubstBuiltinTemplatePackType * >, SourceLocation > UnexpandedParameterPack
Definition Sema.h:243
@ If
'if' clause, allowed on all the Compute Constructs, Data Constructs, Executable Constructs,...
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
@ Seq
'seq' clause, allowed on 'loop' and 'routine' directives.
@ Delete
'delete' clause, allowed on the 'exit data' construct.
@ IK_DeductionGuideName
A deduction-guide name (a template-name)
Definition DeclSpec.h:1110
@ IK_ImplicitSelfParam
An implicit 'self' parameter.
Definition DeclSpec.h:1108
@ IK_TemplateId
A template-id, e.g., f<int>.
Definition DeclSpec.h:1106
@ IK_ConstructorTemplateId
A constructor named via a template-id.
Definition DeclSpec.h:1102
@ IK_ConstructorName
A constructor name.
Definition DeclSpec.h:1100
@ IK_LiteralOperatorId
A user-defined literal name, e.g., operator "" _i.
Definition DeclSpec.h:1098
@ IK_Identifier
An identifier.
Definition DeclSpec.h:1092
@ IK_DestructorName
A destructor name.
Definition DeclSpec.h:1104
@ IK_OperatorFunctionId
An overloaded operator name, e.g., operator+.
Definition DeclSpec.h:1094
@ IK_ConversionFunctionId
A conversion function name, e.g., operator int.
Definition DeclSpec.h:1096
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition Specifiers.h:127
@ AS_public
Definition Specifiers.h:128
@ AS_protected
Definition Specifiers.h:129
@ AS_none
Definition Specifiers.h:131
@ AS_private
Definition Specifiers.h:130
std::optional< ComparisonCategoryType > getComparisonCategoryForBuiltinCmp(QualType T)
Get the comparison category that should be used when comparing values of type T.
ActionResult< Decl * > DeclResult
Definition Ownership.h:255
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
StorageClass
Storage classes.
Definition Specifiers.h:252
@ SC_Static
Definition Specifiers.h:256
@ SC_None
Definition Specifiers.h:254
ComparisonCategoryType commonComparisonType(ComparisonCategoryType A, ComparisonCategoryType B)
Determine the common comparison type, as defined in C++2a [class.spaceship]p4.
@ Dependent
Parse the block as a dependent block, which may be used in some template instantiations but not other...
Definition Parser.h:142
ComparisonCategoryResult
An enumeration representing the possible results of a three-way comparison.
MutableArrayRef< Expr * > MultiExprArg
Definition Ownership.h:259
Language
The language for the input, used to select and validate the language standard and possible actions.
@ Default
Set to the current date and time.
StmtResult StmtError()
Definition Ownership.h:266
@ Result
The result type of a method or function.
Definition TypeBase.h:906
ActionResult< ParsedType > TypeResult
Definition Ownership.h:251
std::pair< unsigned, unsigned > getDepthAndIndex(const NamedDecl *ND)
Retrieve the depth and index of a template parameter.
InheritableAttr * getDLLAttr(Decl *D)
Return a DLL attribute from the declaration.
ActionResult< CXXCtorInitializer * > MemInitResult
Definition Ownership.h:253
OptionalUnsigned< unsigned > UnsignedOrNone
const FunctionProtoType * T
llvm::Expected< QualType > ExpectedType
bool isComputedNoexcept(ExceptionSpecificationType ESpecType)
@ Template
We are parsing a template declaration.
Definition Parser.h:81
ActionResult< CXXBaseSpecifier * > BaseResult
Definition Ownership.h:252
void EscapeStringForDiagnostic(StringRef Str, SmallVectorImpl< char > &OutStr)
EscapeStringForDiagnostic - Append Str to the diagnostic buffer, escaping non-printable characters an...
ReservedLiteralSuffixIdStatus
TagTypeKind
The kind of a tag type.
Definition TypeBase.h:6171
@ Interface
The "__interface" keyword.
Definition TypeBase.h:6176
@ Struct
The "struct" keyword.
Definition TypeBase.h:6173
@ Class
The "class" keyword.
Definition TypeBase.h:6182
ExprResult ExprError()
Definition Ownership.h:265
@ Keyword
The name has been typo-corrected to a keyword.
Definition Sema.h:556
DefaultedComparisonKind
Kinds of defaulted comparison operator functions.
Definition Decl.h:2053
@ Relational
This is an <, <=, >, or >= that should be implemented as a rewrite in terms of a <=> comparison.
Definition Decl.h:2067
@ NotEqual
This is an operator!= that should be implemented as a rewrite in terms of a == comparison.
Definition Decl.h:2064
@ ThreeWay
This is an operator<=> that should be implemented as a series of subobject comparisons.
Definition Decl.h:2061
@ None
This is not a defaultable comparison operator.
Definition Decl.h:2055
@ Equal
This is an operator== that should be implemented as a series of subobject comparisons.
Definition Decl.h:2058
LangAS
Defines the address space values used by the address space qualifier of QualType.
@ CanPassInRegs
The argument of this type can be passed directly in registers.
Definition Decl.h:4485
@ CanNeverPassInRegs
The argument of this type cannot be passed directly in registers.
Definition Decl.h:4499
@ CannotPassInRegs
The argument of this type cannot be passed directly in registers.
Definition Decl.h:4494
AllowFoldKind
Definition Sema.h:649
@ TU_Prefix
The translation unit is a prefix to a translation unit, and is not complete.
ComparisonCategoryType
An enumeration representing the different comparison categories types.
MutableArrayRef< ParsedTemplateArgument > ASTTemplateArgsPtr
Definition Ownership.h:261
CXXSpecialMemberKind
Kinds of C++ special members.
Definition Decl.h:2031
OverloadedOperatorKind getRewrittenOverloadedOperator(OverloadedOperatorKind Kind)
Get the other overloaded operator that the given operator can be rewritten into, if any such operator...
@ TNK_Concept_template
The name refers to a concept.
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition Specifiers.h:136
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:139
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition Specifiers.h:148
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition Specifiers.h:143
SmallVector< CXXBaseSpecifier *, 4 > CXXCastPath
A simple array of base specifiers.
Definition ASTContext.h:147
TypeAwareAllocationMode
Definition ExprCXX.h:2256
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition DeclBase.h:1306
DynamicRecursiveASTVisitorBase< false > DynamicRecursiveASTVisitor
TrivialABIHandling
Definition Sema.h:639
@ ConsiderTrivialABI
The triviality of a method affected by "trivial_abi".
Definition Sema.h:644
@ IgnoreTrivialABI
The triviality of a method unaffected by "trivial_abi".
Definition Sema.h:641
@ Incomplete
Template argument deduction did not deduce a value for every template parameter.
Definition Sema.h:384
@ Success
Template argument deduction was successful.
Definition Sema.h:376
@ Inconsistent
Template argument deduction produced inconsistent deduced values for the given template parameter.
Definition Sema.h:390
PostfixOperatorKind
Kinds of defaulted postfix increment and decrement operator functions (C++2d [over....
Definition Decl.h:2043
@ None
This is not a defaultable postfix increment or decrement operator.
Definition Decl.h:2045
@ Increment
This is a postfix increment operator, 'operator++(int)'.
Definition Decl.h:2047
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition Specifiers.h:192
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition Specifiers.h:210
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition Specifiers.h:206
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition Specifiers.h:202
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:198
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition Specifiers.h:195
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:282
TypeAwareAllocationMode typeAwareAllocationModeFromBool(bool IsTypeAwareAllocation)
Definition ExprCXX.h:2263
U cast(CodeGen::Address addr)
Definition Address.h:327
@ StaticAssertMessageData
Call to data() in a static assert message.
Definition Sema.h:843
@ StaticAssertMessageSize
Call to size() in a static assert message.
Definition Sema.h:841
@ ExplicitBool
Condition in an explicit(bool) specifier.
Definition Sema.h:839
OpaquePtr< QualType > ParsedType
An opaque type for threading parsed type information through the parser.
Definition Ownership.h:230
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition TypeBase.h:6146
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:6167
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6157
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6160
bool isLambdaMethod(const DeclContext *DC)
Definition ASTLambda.h:39
bool isExternallyVisible(Linkage L)
Definition Linkage.h:90
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
ExceptionSpecificationType
The various types of exception specifications that exist in C++11.
@ EST_DependentNoexcept
noexcept(expression), value-dependent
@ EST_Uninstantiated
not instantiated yet
@ EST_Unparsed
not parsed yet
@ EST_NoThrow
Microsoft __declspec(nothrow) extension.
@ EST_None
no exception specification
@ EST_MSAny
Microsoft throw(...) extension.
@ EST_BasicNoexcept
noexcept
@ EST_NoexceptFalse
noexcept(expression), evals to 'false'
@ EST_Unevaluated
not evaluated yet, for special member function
@ EST_NoexceptTrue
noexcept(expression), evals to 'true'
@ EST_Dynamic
throw(T1, T2)
ActionResult< Stmt * > StmtResult
Definition Ownership.h:250
@ NOUR_Unevaluated
This name appears in an unevaluated operand.
Definition Specifiers.h:181
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t uint64_t __builtin_riscv_ssha_i32 __builtin_riscv_sshl_u32 unsigned
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t int64_t
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t uint64_t __builtin_riscv_ssha_i32 __builtin_riscv_sshl_u32 uint64_t
#define false
Definition stdbool.h:26
#define true
Definition stdbool.h:25
Represents an element in a path from a derived class to a base class.
bool hasValidIntValue() const
True iff we've successfully evaluated the variable as a constant expression and extracted its integer...
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
DeclarationName getName() const
getName - Returns the embedded declaration name.
void setNamedTypeInfo(TypeSourceInfo *TInfo)
setNamedTypeInfo - Sets the source type info associated to the name.
void setName(DeclarationName N)
setName - Sets the embedded declaration name.
SourceLocation getBeginLoc() const
getBeginLoc - Retrieve the location of the first token.
SourceRange getSourceRange() const LLVM_READONLY
getSourceRange - The range of the declaration name.
SourceLocation getEndLoc() const LLVM_READONLY
bool containsUnexpandedParameterPack() const
Determine whether this name contains an unexpanded parameter pack.
unsigned isVariadic
isVariadic - If this function has a prototype, and if that proto ends with ',...)',...
Definition DeclSpec.h:1460
ParamInfo * Params
Params - This is a pointer to a new[]'d array of ParamInfo objects that describe the parameters speci...
Definition DeclSpec.h:1520
unsigned RefQualifierIsLValueRef
Whether the ref-qualifier (if any) is an lvalue reference.
Definition DeclSpec.h:1469
DeclSpec * MethodQualifiers
DeclSpec for the function with the qualifier related info.
Definition DeclSpec.h:1523
SourceLocation getRefQualifierLoc() const
Retrieve the location of the ref-qualifier, if any.
Definition DeclSpec.h:1621
unsigned NumParams
NumParams - This is the number of formal parameters specified by the declarator.
Definition DeclSpec.h:1495
bool hasMutableQualifier() const
Determine whether this lambda-declarator contains a 'mutable' qualifier.
Definition DeclSpec.h:1650
bool hasMethodTypeQualifiers() const
Determine whether this method has qualifiers.
Definition DeclSpec.h:1653
void freeParams()
Reset the parameter list to having zero parameters.
Definition DeclSpec.h:1559
bool hasRefQualifier() const
Determine whether this function declaration contains a ref-qualifier.
Definition DeclSpec.h:1646
std::unique_ptr< CachedTokens > DefaultArgTokens
DefaultArgTokens - When the parameter's default argument cannot be parsed immediately (because it occ...
Definition DeclSpec.h:1435
unsigned TypeQuals
The type qualifiers: const/volatile/restrict/unaligned/atomic.
Definition DeclSpec.h:1358
One instance of this struct is used for each type in a declarator that is parsed.
Definition DeclSpec.h:1334
SourceRange getSourceRange() const
Definition DeclSpec.h:1346
FunctionTypeInfo Fun
Definition DeclSpec.h:1734
enum clang::DeclaratorChunk::@340323374315200305336204205154073066142310370142 Kind
PointerTypeInfo Ptr
Definition DeclSpec.h:1731
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:667
A simple structure that captures a vtable use for the purposes of the ExternalSemaSource.
Holds information about the various types of exception specification.
Definition TypeBase.h:5605
FunctionDecl * SourceDecl
The function whose exception specification this is, for EST_Unevaluated and EST_Uninstantiated.
Definition TypeBase.h:5617
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition TypeBase.h:5607
ArrayRef< QualType > Exceptions
Explicitly-specified list of exception types.
Definition TypeBase.h:5610
Expr * NoexceptExpr
Noexcept expression, if this is a computed noexcept specification.
Definition TypeBase.h:5613
Extra information about a function prototype.
Definition TypeBase.h:5633
static StringRef getTagTypeKindName(TagTypeKind Kind)
Definition TypeBase.h:6210
static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag)
Converts a TagTypeKind into an elaborated type keyword.
Definition Type.cpp:3525
static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into a tag type kind.
Definition Type.cpp:3507
Describes how types, statements, expressions, and declarations should be printed.
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition Sema.h:13413
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
SourceLocation PointOfInstantiation
The point of instantiation or synthesis within the source code.
Definition Sema.h:13544
@ MarkingClassDllexported
We are marking a class as __dllexport.
Definition Sema.h:13504
@ InitializingStructuredBinding
We are initializing a structured binding.
Definition Sema.h:13501
@ ExceptionSpecEvaluation
We are computing the exception specification for a defaulted special member function.
Definition Sema.h:13457
@ DeclaringImplicitEqualityComparison
We are declaring an implicit 'operator==' for a defaulted 'operator<=>'.
Definition Sema.h:13475
Decl * Entity
The entity that is being synthesized.
Definition Sema.h:13547
Abstract class used to diagnose incomplete types.
Definition Sema.h:8477
virtual void diagnose(Sema &S, SourceLocation Loc, QualType T)=0
Information about a template-id annotation token.
TemplateNameKind Kind
The kind of template that Template refers to.
unsigned NumArgs
NumArgs - The number of template arguments.
SourceLocation TemplateNameLoc
TemplateNameLoc - The location of the template name within the source.
ParsedTemplateArgument * getTemplateArgs()
Retrieves a pointer to the template arguments.
SourceLocation RAngleLoc
The location of the '>' after the template argument list.
SourceLocation LAngleLoc
The location of the '<' before the template argument list.
SourceLocation TemplateKWLoc
TemplateKWLoc - The location of the template keyword.
ParsedTemplateTy Template
The declaration of the template corresponding to the template-name.
OpaquePtr< T > get() const
Definition Ownership.h:105