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"
49#include "clang/Sema/Template.h"
51#include "llvm/ADT/ArrayRef.h"
52#include "llvm/ADT/STLExtras.h"
53#include "llvm/ADT/StringExtras.h"
54#include "llvm/Support/ConvertUTF.h"
55#include "llvm/Support/SaveAndRestore.h"
56#include <map>
57#include <optional>
58#include <set>
59
60using namespace clang;
61
62//===----------------------------------------------------------------------===//
63// CheckDefaultArgumentVisitor
64//===----------------------------------------------------------------------===//
65
66namespace {
67/// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
68/// the default argument of a parameter to determine whether it
69/// contains any ill-formed subexpressions. For example, this will
70/// diagnose the use of local variables or parameters within the
71/// default argument expression.
72class CheckDefaultArgumentVisitor
73 : public ConstStmtVisitor<CheckDefaultArgumentVisitor, bool> {
74 Sema &S;
75 const Expr *DefaultArg;
76
77public:
78 CheckDefaultArgumentVisitor(Sema &S, const Expr *DefaultArg)
79 : S(S), DefaultArg(DefaultArg) {}
80
81 bool VisitExpr(const Expr *Node);
82 bool VisitDeclRefExpr(const DeclRefExpr *DRE);
83 bool VisitCXXThisExpr(const CXXThisExpr *ThisE);
84 bool VisitLambdaExpr(const LambdaExpr *Lambda);
85 bool VisitPseudoObjectExpr(const PseudoObjectExpr *POE);
86 bool VisitCoawaitExpr(const CoawaitExpr *E);
87 bool VisitCoyieldExpr(const CoyieldExpr *E);
88};
89
90/// VisitExpr - Visit all of the children of this expression.
91bool CheckDefaultArgumentVisitor::VisitExpr(const Expr *Node) {
92 bool IsInvalid = false;
93 for (const Stmt *SubStmt : Node->children())
94 if (SubStmt)
95 IsInvalid |= Visit(SubStmt);
96 return IsInvalid;
97}
98
99/// VisitDeclRefExpr - Visit a reference to a declaration, to
100/// determine whether this declaration can be used in the default
101/// argument expression.
102bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(const DeclRefExpr *DRE) {
103 const ValueDecl *Decl = DRE->getDecl();
104
105 if (!isa<VarDecl, BindingDecl>(Decl))
106 return false;
107
108 if (const auto *Param = dyn_cast<ParmVarDecl>(Decl)) {
109 // C++ [dcl.fct.default]p9:
110 // [...] parameters of a function shall not be used in default
111 // argument expressions, even if they are not evaluated. [...]
112 //
113 // C++17 [dcl.fct.default]p9 (by CWG 2082):
114 // [...] A parameter shall not appear as a potentially-evaluated
115 // expression in a default argument. [...]
116 //
117 if (DRE->isNonOdrUse() != NOUR_Unevaluated)
118 return S.Diag(DRE->getBeginLoc(),
119 diag::err_param_default_argument_references_param)
120 << Param->getDeclName() << DefaultArg->getSourceRange();
121 } else if (auto *VD = Decl->getPotentiallyDecomposedVarDecl()) {
122 // C++ [dcl.fct.default]p7:
123 // Local variables shall not be used in default argument
124 // expressions.
125 //
126 // C++17 [dcl.fct.default]p7 (by CWG 2082):
127 // A local variable shall not appear as a potentially-evaluated
128 // expression in a default argument.
129 //
130 // C++20 [dcl.fct.default]p7 (DR as part of P0588R1, see also CWG 2346):
131 // Note: A local variable cannot be odr-used (6.3) in a default
132 // argument.
133 //
134 if (VD->isLocalVarDecl() && !DRE->isNonOdrUse())
135 return S.Diag(DRE->getBeginLoc(),
136 diag::err_param_default_argument_references_local)
137 << Decl << DefaultArg->getSourceRange();
138 }
139 return false;
140}
141
142/// VisitCXXThisExpr - Visit a C++ "this" expression.
143bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(const CXXThisExpr *ThisE) {
144 // C++ [dcl.fct.default]p8:
145 // The keyword this shall not be used in a default argument of a
146 // member function.
147 return S.Diag(ThisE->getBeginLoc(),
148 diag::err_param_default_argument_references_this)
149 << ThisE->getSourceRange();
150}
151
152bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(
153 const PseudoObjectExpr *POE) {
154 bool Invalid = false;
155 for (const Expr *E : POE->semantics()) {
156 // Look through bindings.
157 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) {
158 E = OVE->getSourceExpr();
159 assert(E && "pseudo-object binding without source expression?");
160 }
161
162 Invalid |= Visit(E);
163 }
164 return Invalid;
165}
166
167bool CheckDefaultArgumentVisitor::VisitLambdaExpr(const LambdaExpr *Lambda) {
168 // [expr.prim.lambda.capture]p9
169 // a lambda-expression appearing in a default argument cannot implicitly or
170 // explicitly capture any local entity. Such a lambda-expression can still
171 // have an init-capture if any full-expression in its initializer satisfies
172 // the constraints of an expression appearing in a default argument.
173 bool Invalid = false;
174 for (const LambdaCapture &LC : Lambda->captures()) {
175 if (!Lambda->isInitCapture(&LC))
176 return S.Diag(LC.getLocation(), diag::err_lambda_capture_default_arg);
177 // Init captures are always VarDecl.
178 auto *D = cast<VarDecl>(LC.getCapturedVar());
179 Invalid |= Visit(D->getInit());
180 }
181 return Invalid;
182}
183
184bool CheckDefaultArgumentVisitor::VisitCoawaitExpr(const CoawaitExpr *E) {
185 // [expr.await] An await-expression shall not appear in a default argument.
186 // Note that this is generally diagnosed by isValidCoroutineContext,
187 // however isValidCoroutineContext misses default argument in nested
188 // function declarations.
189 S.Diag(E->getBeginLoc(), diag::err_coroutine_outside_function)
190 << "co_await" << E->getSourceRange();
191 return true;
192}
193
194bool CheckDefaultArgumentVisitor::VisitCoyieldExpr(const CoyieldExpr *E) {
195 S.Diag(E->getBeginLoc(), diag::err_coroutine_outside_function)
196 << "co_yield" << E->getSourceRange();
197 return true;
198}
199
200} // namespace
201
202void
204 const CXXMethodDecl *Method) {
205 // If we have an MSAny spec already, don't bother.
206 if (!Method || ComputedEST == EST_MSAny)
207 return;
208
209 const FunctionProtoType *Proto
210 = Method->getType()->getAs<FunctionProtoType>();
211 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
212 if (!Proto)
213 return;
214
216
217 // If we have a throw-all spec at this point, ignore the function.
218 if (ComputedEST == EST_None)
219 return;
220
221 if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
222 EST = EST_BasicNoexcept;
223
224 switch (EST) {
225 case EST_Unparsed:
227 case EST_Unevaluated:
228 llvm_unreachable("should not see unresolved exception specs here");
229
230 // If this function can throw any exceptions, make a note of that.
231 case EST_MSAny:
232 case EST_None:
233 // FIXME: Whichever we see last of MSAny and None determines our result.
234 // We should make a consistent, order-independent choice here.
235 ClearExceptions();
236 ComputedEST = EST;
237 return;
239 ClearExceptions();
240 ComputedEST = EST_None;
241 return;
242 // FIXME: If the call to this decl is using any of its default arguments, we
243 // need to search them for potentially-throwing calls.
244 // If this function has a basic noexcept, it doesn't affect the outcome.
246 case EST_NoexceptTrue:
247 case EST_NoThrow:
248 return;
249 // If we're still at noexcept(true) and there's a throw() callee,
250 // change to that specification.
251 case EST_DynamicNone:
252 if (ComputedEST == EST_BasicNoexcept)
253 ComputedEST = EST_DynamicNone;
254 return;
256 llvm_unreachable(
257 "should not generate implicit declarations for dependent cases");
258 case EST_Dynamic:
259 break;
260 }
261 assert(EST == EST_Dynamic && "EST case not considered earlier.");
262 assert(ComputedEST != EST_None &&
263 "Shouldn't collect exceptions when throw-all is guaranteed.");
264 ComputedEST = EST_Dynamic;
265 // Record the exceptions in this function's exception specification.
266 for (const auto &E : Proto->exceptions())
267 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
268 Exceptions.push_back(E);
269}
270
272 if (!S || ComputedEST == EST_MSAny)
273 return;
274
275 // FIXME:
276 //
277 // C++0x [except.spec]p14:
278 // [An] implicit exception-specification specifies the type-id T if and
279 // only if T is allowed by the exception-specification of a function directly
280 // invoked by f's implicit definition; f shall allow all exceptions if any
281 // function it directly invokes allows all exceptions, and f shall allow no
282 // exceptions if every function it directly invokes allows no exceptions.
283 //
284 // Note in particular that if an implicit exception-specification is generated
285 // for a function containing a throw-expression, that specification can still
286 // be noexcept(true).
287 //
288 // Note also that 'directly invoked' is not defined in the standard, and there
289 // is no indication that we should only consider potentially-evaluated calls.
290 //
291 // Ultimately we should implement the intent of the standard: the exception
292 // specification should be the set of exceptions which can be thrown by the
293 // implicit definition. For now, we assume that any non-nothrow expression can
294 // throw any exception.
295
296 if (Self->canThrow(S))
297 ComputedEST = EST_None;
298}
299
301 SourceLocation EqualLoc) {
302 if (RequireCompleteType(Param->getLocation(), Param->getType(),
303 diag::err_typecheck_decl_incomplete_type))
304 return true;
305
306 // C++ [dcl.fct.default]p5
307 // A default argument expression is implicitly converted (clause
308 // 4) to the parameter type. The default argument expression has
309 // the same semantic constraints as the initializer expression in
310 // a declaration of a variable of the parameter type, using the
311 // copy-initialization semantics (8.5).
313 Param);
314 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
315 EqualLoc);
316 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
317 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
318 if (Result.isInvalid())
319 return true;
320 Arg = Result.getAs<Expr>();
321
322 CheckCompletedExpr(Arg, EqualLoc);
324
325 return Arg;
326}
327
329 SourceLocation EqualLoc) {
330 // Add the default argument to the parameter
331 Param->setDefaultArg(Arg);
332
333 // We have already instantiated this parameter; provide each of the
334 // instantiations with the uninstantiated default argument.
335 UnparsedDefaultArgInstantiationsMap::iterator InstPos
337 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
338 for (auto &Instantiation : InstPos->second)
339 Instantiation->setUninstantiatedDefaultArg(Arg);
340
341 // We're done tracking this parameter's instantiations.
343 }
344}
345
346void
348 Expr *DefaultArg) {
349 if (!param || !DefaultArg)
350 return;
351
352 ParmVarDecl *Param = cast<ParmVarDecl>(param);
353 UnparsedDefaultArgLocs.erase(Param);
354
355 // Default arguments are only permitted in C++
356 if (!getLangOpts().CPlusPlus) {
357 Diag(EqualLoc, diag::err_param_default_argument)
358 << DefaultArg->getSourceRange();
359 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
360 }
361
362 // C++11 [dcl.fct.default]p3
363 // A default argument expression [...] shall not be specified for a
364 // parameter pack.
365 //
366 // Check this before looking for unexpanded parameter packs in DefaultArg:
367 // if DefaultArg references a pack from an enclosing lambda/block, that
368 // check would (incorrectly) mark the lambda as containing an unexpanded
369 // pack that never actually appears in the final AST once we discard
370 // DefaultArg below.
371 if (Param->isParameterPack()) {
372 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
373 << DefaultArg->getSourceRange();
374 // Recover by discarding the default argument.
375 Param->setDefaultArg(nullptr);
376 return;
377 }
378
379 // Check for unexpanded parameter packs.
381 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
382
383 ExprResult Result = ConvertParamDefaultArgument(Param, DefaultArg, EqualLoc);
384 if (Result.isInvalid())
385 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
386
387 DefaultArg = Result.getAs<Expr>();
388
389 // Check that the default argument is well-formed
390 CheckDefaultArgumentVisitor DefaultArgChecker(*this, DefaultArg);
391 if (DefaultArgChecker.Visit(DefaultArg))
392 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
393
394 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
395}
396
398 SourceLocation EqualLoc,
399 SourceLocation ArgLoc) {
400 if (!param)
401 return;
402
403 ParmVarDecl *Param = cast<ParmVarDecl>(param);
404 Param->setUnparsedDefaultArg();
405 UnparsedDefaultArgLocs[Param] = ArgLoc;
406}
407
409 Expr *DefaultArg) {
410 if (!param)
411 return;
412
413 ParmVarDecl *Param = cast<ParmVarDecl>(param);
414 Param->setInvalidDecl();
415 UnparsedDefaultArgLocs.erase(Param);
416 ExprResult RE;
417 if (DefaultArg) {
418 RE = CreateRecoveryExpr(EqualLoc, DefaultArg->getEndLoc(), {DefaultArg},
419 Param->getType().getNonReferenceType());
420 } else {
421 RE = CreateRecoveryExpr(EqualLoc, EqualLoc, {},
422 Param->getType().getNonReferenceType());
423 }
424 Param->setDefaultArg(RE.get());
425}
426
428 // C++ [dcl.fct.default]p3
429 // A default argument expression shall be specified only in the
430 // parameter-declaration-clause of a function declaration or in a
431 // template-parameter (14.1). It shall not be specified for a
432 // parameter pack. If it is specified in a
433 // parameter-declaration-clause, it shall not occur within a
434 // declarator or abstract-declarator of a parameter-declaration.
435 bool MightBeFunction = D.isFunctionDeclarationContext();
436 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
437 DeclaratorChunk &chunk = D.getTypeObject(i);
438 if (chunk.Kind == DeclaratorChunk::Function) {
439 if (MightBeFunction) {
440 // This is a function declaration. It can have default arguments, but
441 // keep looking in case its return type is a function type with default
442 // arguments.
443 MightBeFunction = false;
444 continue;
445 }
446 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
447 ++argIdx) {
448 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
449 if (Param->hasUnparsedDefaultArg()) {
450 std::unique_ptr<CachedTokens> Toks =
451 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
452 SourceRange SR;
453 if (Toks->size() > 1)
454 SR = SourceRange((*Toks)[1].getLocation(),
455 Toks->back().getLocation());
456 else
457 SR = UnparsedDefaultArgLocs[Param];
458 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
459 << SR;
460 } else if (Param->getDefaultArg()) {
461 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
462 << Param->getDefaultArg()->getSourceRange();
463 Param->setDefaultArg(nullptr);
464 }
465 }
466 } else if (chunk.Kind != DeclaratorChunk::Paren) {
467 MightBeFunction = false;
468 }
469 }
470}
471
473 return llvm::any_of(FD->parameters(), [](ParmVarDecl *P) {
474 return P->hasDefaultArg() && !P->hasInheritedDefaultArg();
475 });
476}
477
479 Scope *S) {
480 bool Invalid = false;
481
482 // The declaration context corresponding to the scope is the semantic
483 // parent, unless this is a local function declaration, in which case
484 // it is that surrounding function.
485 DeclContext *ScopeDC = New->isLocalExternDecl()
486 ? New->getLexicalDeclContext()
487 : New->getDeclContext();
488
489 // Find the previous declaration for the purpose of default arguments.
490 FunctionDecl *PrevForDefaultArgs = Old;
491 for (/**/; PrevForDefaultArgs;
492 // Don't bother looking back past the latest decl if this is a local
493 // extern declaration; nothing else could work.
494 PrevForDefaultArgs = New->isLocalExternDecl()
495 ? nullptr
496 : PrevForDefaultArgs->getPreviousDecl()) {
497 // Ignore hidden declarations.
498 if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
499 continue;
500
501 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
502 !New->isCXXClassMember()) {
503 // Ignore default arguments of old decl if they are not in
504 // the same scope and this is not an out-of-line definition of
505 // a member function.
506 continue;
507 }
508
509 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
510 // If only one of these is a local function declaration, then they are
511 // declared in different scopes, even though isDeclInScope may think
512 // they're in the same scope. (If both are local, the scope check is
513 // sufficient, and if neither is local, then they are in the same scope.)
514 continue;
515 }
516
517 // We found the right previous declaration.
518 break;
519 }
520
521 // C++ [dcl.fct.default]p4:
522 // For non-template functions, default arguments can be added in
523 // later declarations of a function in the same
524 // scope. Declarations in different scopes have completely
525 // distinct sets of default arguments. That is, declarations in
526 // inner scopes do not acquire default arguments from
527 // declarations in outer scopes, and vice versa. In a given
528 // function declaration, all parameters subsequent to a
529 // parameter with a default argument shall have default
530 // arguments supplied in this or previous declarations. A
531 // default argument shall not be redefined by a later
532 // declaration (not even to the same value).
533 //
534 // C++ [dcl.fct.default]p6:
535 // Except for member functions of class templates, the default arguments
536 // in a member function definition that appears outside of the class
537 // definition are added to the set of default arguments provided by the
538 // member function declaration in the class definition.
539 for (unsigned p = 0, NumParams = PrevForDefaultArgs
540 ? PrevForDefaultArgs->getNumParams()
541 : 0;
542 p < NumParams; ++p) {
543 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
544 ParmVarDecl *NewParam = New->getParamDecl(p);
545
546 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
547 bool NewParamHasDfl = NewParam->hasDefaultArg();
548
549 if (OldParamHasDfl && NewParamHasDfl) {
550 unsigned DiagDefaultParamID =
551 diag::err_param_default_argument_redefinition;
552
553 // MSVC accepts that default parameters be redefined for member functions
554 // of template class. The new default parameter's value is ignored.
555 Invalid = true;
556 if (getLangOpts().MicrosoftExt) {
557 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
558 if (MD && MD->getParent()->getDescribedClassTemplate()) {
559 // Merge the old default argument into the new parameter.
560 NewParam->setHasInheritedDefaultArg();
561 if (OldParam->hasUninstantiatedDefaultArg())
563 OldParam->getUninstantiatedDefaultArg());
564 else
565 NewParam->setDefaultArg(OldParam->getInit());
566 DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
567 Invalid = false;
568 }
569 }
570
571 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
572 // hint here. Alternatively, we could walk the type-source information
573 // for NewParam to find the last source location in the type... but it
574 // isn't worth the effort right now. This is the kind of test case that
575 // is hard to get right:
576 // int f(int);
577 // void g(int (*fp)(int) = f);
578 // void g(int (*fp)(int) = &f);
579 Diag(NewParam->getLocation(), DiagDefaultParamID)
580 << NewParam->getDefaultArgRange();
581
582 // Look for the function declaration where the default argument was
583 // actually written, which may be a declaration prior to Old.
584 for (auto Older = PrevForDefaultArgs;
585 OldParam->hasInheritedDefaultArg(); /**/) {
586 Older = Older->getPreviousDecl();
587 OldParam = Older->getParamDecl(p);
588 }
589
590 Diag(OldParam->getLocation(), diag::note_previous_definition)
591 << OldParam->getDefaultArgRange();
592 } else if (OldParamHasDfl) {
593 // Merge the old default argument into the new parameter unless the new
594 // function is a friend declaration in a template class. In the latter
595 // case the default arguments will be inherited when the friend
596 // declaration will be instantiated.
597 if (New->getFriendObjectKind() == Decl::FOK_None ||
598 !New->getLexicalDeclContext()->isDependentContext()) {
599 // It's important to use getInit() here; getDefaultArg()
600 // strips off any top-level ExprWithCleanups.
601 NewParam->setHasInheritedDefaultArg();
602 if (OldParam->hasUnparsedDefaultArg())
603 NewParam->setUnparsedDefaultArg();
604 else if (OldParam->hasUninstantiatedDefaultArg())
606 OldParam->getUninstantiatedDefaultArg());
607 else
608 NewParam->setDefaultArg(OldParam->getInit());
609 }
610 } else if (NewParamHasDfl) {
611 if (New->getDescribedFunctionTemplate()) {
612 // Paragraph 4, quoted above, only applies to non-template functions.
613 Diag(NewParam->getLocation(),
614 diag::err_param_default_argument_template_redecl)
615 << NewParam->getDefaultArgRange();
616 Diag(PrevForDefaultArgs->getLocation(),
617 diag::note_template_prev_declaration)
618 << false;
619 } else if (New->getTemplateSpecializationKind()
621 New->getTemplateSpecializationKind() != TSK_Undeclared) {
622 // C++ [temp.expr.spec]p21:
623 // Default function arguments shall not be specified in a declaration
624 // or a definition for one of the following explicit specializations:
625 // - the explicit specialization of a function template;
626 // - the explicit specialization of a member function template;
627 // - the explicit specialization of a member function of a class
628 // template where the class template specialization to which the
629 // member function specialization belongs is implicitly
630 // instantiated.
631 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
632 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
633 << New->getDeclName()
634 << NewParam->getDefaultArgRange();
635 } else if (New->getDeclContext()->isDependentContext()) {
636 // C++ [dcl.fct.default]p6 (DR217):
637 // Default arguments for a member function of a class template shall
638 // be specified on the initial declaration of the member function
639 // within the class template.
640 //
641 // Reading the tea leaves a bit in DR217 and its reference to DR205
642 // leads me to the conclusion that one cannot add default function
643 // arguments for an out-of-line definition of a member function of a
644 // dependent type.
645 int WhichKind = 2;
647 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
648 if (Record->getDescribedClassTemplate())
649 WhichKind = 0;
651 WhichKind = 1;
652 else
653 WhichKind = 2;
654 }
655
656 Diag(NewParam->getLocation(),
657 diag::err_param_default_argument_member_template_redecl)
658 << WhichKind
659 << NewParam->getDefaultArgRange();
660 }
661 }
662 }
663
664 // DR1344: If a default argument is added outside a class definition and that
665 // default argument makes the function a special member function, the program
666 // is ill-formed. This can only happen for constructors.
668 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
671 if (NewSM != OldSM) {
672 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
673 assert(NewParam->hasDefaultArg());
674 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
675 << NewParam->getDefaultArgRange() << NewSM;
676 Diag(Old->getLocation(), diag::note_previous_declaration);
677 }
678 }
679
680 const FunctionDecl *Def;
681 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
682 // template has a constexpr specifier then all its declarations shall
683 // contain the constexpr specifier.
684 if (New->getConstexprKind() != Old->getConstexprKind()) {
685 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
686 << New << static_cast<int>(New->getConstexprKind())
687 << static_cast<int>(Old->getConstexprKind());
688 Diag(Old->getLocation(), diag::note_previous_declaration);
689 Invalid = true;
690 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
691 Old->isDefined(Def) &&
692 // If a friend function is inlined but does not have 'inline'
693 // specifier, it is a definition. Do not report attribute conflict
694 // in this case, redefinition will be diagnosed later.
695 (New->isInlineSpecified() ||
696 New->getFriendObjectKind() == Decl::FOK_None)) {
697 // C++11 [dcl.fcn.spec]p4:
698 // If the definition of a function appears in a translation unit before its
699 // first declaration as inline, the program is ill-formed.
700 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
701 Diag(Def->getLocation(), diag::note_previous_definition);
702 Invalid = true;
703 }
704
705 // C++17 [temp.deduct.guide]p3:
706 // Two deduction guide declarations in the same translation unit
707 // for the same class template shall not have equivalent
708 // parameter-declaration-clauses.
710 !New->isFunctionTemplateSpecialization() && isVisible(Old)) {
711 Diag(New->getLocation(), diag::err_deduction_guide_redeclared);
712 Diag(Old->getLocation(), diag::note_previous_declaration);
713 }
714
715 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
716 // argument expression, that declaration shall be a definition and shall be
717 // the only declaration of the function or function template in the
718 // translation unit.
721 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
722 Diag(Old->getLocation(), diag::note_previous_declaration);
723 Invalid = true;
724 }
725
726 // C++11 [temp.friend]p4 (DR329):
727 // When a function is defined in a friend function declaration in a class
728 // template, the function is instantiated when the function is odr-used.
729 // The same restrictions on multiple declarations and definitions that
730 // apply to non-template function declarations and definitions also apply
731 // to these implicit definitions.
732 const FunctionDecl *OldDefinition = nullptr;
733 if (New->isThisDeclarationInstantiatedFromAFriendDefinition() &&
734 Old->isDefined(OldDefinition, true))
735 CheckForFunctionRedefinition(New, OldDefinition);
736
737 return Invalid;
738}
739
742 ? diag::warn_cxx23_placeholder_var_definition
743 : diag::ext_placeholder_var_definition);
744}
745
746NamedDecl *
748 MultiTemplateParamsArg TemplateParamLists) {
749 assert(D.isDecompositionDeclarator());
751
752 // The syntax only allows a decomposition declarator as a simple-declaration,
753 // a for-range-declaration, or a condition in Clang, but we parse it in more
754 // cases than that.
756 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
757 << Decomp.getSourceRange();
758 return nullptr;
759 }
760
761 if (!TemplateParamLists.empty()) {
762 // C++17 [temp]/1:
763 // A template defines a family of class, functions, or variables, or an
764 // alias for a family of types.
765 //
766 // Structured bindings are not included.
767 Diag(TemplateParamLists.front()->getTemplateLoc(),
768 diag::err_decomp_decl_template);
769 return nullptr;
770 }
771
772 unsigned DiagID;
774 DiagID = diag::compat_pre_cxx17_decomp_decl;
776 DiagID = getLangOpts().CPlusPlus26
777 ? diag::compat_cxx26_decomp_decl_cond
778 : diag::compat_pre_cxx26_decomp_decl_cond;
779 else
780 DiagID = diag::compat_cxx17_decomp_decl;
781
782 Diag(Decomp.getLSquareLoc(), DiagID) << Decomp.getSourceRange();
783
784 // The semantic context is always just the current context.
785 DeclContext *const DC = CurContext;
786
787 // C++17 [dcl.dcl]/8:
788 // The decl-specifier-seq shall contain only the type-specifier auto
789 // and cv-qualifiers.
790 // C++20 [dcl.dcl]/8:
791 // If decl-specifier-seq contains any decl-specifier other than static,
792 // thread_local, auto, or cv-qualifiers, the program is ill-formed.
793 // C++23 [dcl.pre]/6:
794 // Each decl-specifier in the decl-specifier-seq shall be static,
795 // thread_local, auto (9.2.9.6 [dcl.spec.auto]), or a cv-qualifier.
796 // C++23 [dcl.pre]/7:
797 // Each decl-specifier in the decl-specifier-seq shall be constexpr,
798 // constinit, static, thread_local, auto, or a cv-qualifier
799 auto &DS = D.getDeclSpec();
800 auto DiagBadSpecifier = [&](StringRef Name, SourceLocation Loc) {
801 Diag(Loc, diag::err_decomp_decl_spec) << Name;
802 };
803
804 auto DiagCpp20Specifier = [&](StringRef Name, SourceLocation Loc) {
805 DiagCompat(Loc, diag_compat::decomp_decl_spec) << Name;
806 };
807
808 if (auto SCS = DS.getStorageClassSpec()) {
809 if (SCS == DeclSpec::SCS_static)
810 DiagCpp20Specifier(DeclSpec::getSpecifierName(SCS),
811 DS.getStorageClassSpecLoc());
812 else
813 DiagBadSpecifier(DeclSpec::getSpecifierName(SCS),
814 DS.getStorageClassSpecLoc());
815 }
816 if (auto TSCS = DS.getThreadStorageClassSpec())
817 DiagCpp20Specifier(DeclSpec::getSpecifierName(TSCS),
818 DS.getThreadStorageClassSpecLoc());
819
820 if (DS.isInlineSpecified())
821 DiagBadSpecifier("inline", DS.getInlineSpecLoc());
822
823 if (ConstexprSpecKind ConstexprSpec = DS.getConstexprSpecifier();
824 ConstexprSpec != ConstexprSpecKind::Unspecified) {
825 if (ConstexprSpec == ConstexprSpecKind::Consteval ||
827 DiagBadSpecifier(DeclSpec::getSpecifierName(ConstexprSpec),
828 DS.getConstexprSpecLoc());
829 }
830
831 // We can't recover from it being declared as a typedef.
832 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
833 return nullptr;
834
835 // C++2a [dcl.struct.bind]p1:
836 // A cv that includes volatile is deprecated
837 if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) &&
839 Diag(DS.getVolatileSpecLoc(),
840 diag::warn_deprecated_volatile_structured_binding);
841
843 QualType R = TInfo->getType();
844
847 D.setInvalidType();
848
849 // The syntax only allows a single ref-qualifier prior to the decomposition
850 // declarator. No other declarator chunks are permitted. Also check the type
851 // specifier here.
852 if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
853 D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
854 (D.getNumTypeObjects() == 1 &&
856 Diag(Decomp.getLSquareLoc(),
857 (D.hasGroupingParens() ||
858 (D.getNumTypeObjects() &&
860 ? diag::err_decomp_decl_parens
861 : diag::err_decomp_decl_type)
862 << R;
863
864 // In most cases, there's no actual problem with an explicitly-specified
865 // type, but a function type won't work here, and ActOnVariableDeclarator
866 // shouldn't be called for such a type.
867 if (R->isFunctionType())
868 D.setInvalidType();
869 }
870
871 // Constrained auto is prohibited by [decl.pre]p6, so check that here.
872 if (DS.isConstrainedAuto()) {
873 TemplateIdAnnotation *TemplRep = DS.getRepAsTemplateId();
874 assert(TemplRep->Kind == TNK_Concept_template &&
875 "No other template kind should be possible for a constrained auto");
876
877 SourceRange TemplRange{TemplRep->TemplateNameLoc,
878 TemplRep->RAngleLoc.isValid()
879 ? TemplRep->RAngleLoc
880 : TemplRep->TemplateNameLoc};
881 Diag(TemplRep->TemplateNameLoc, diag::err_decomp_decl_constraint)
882 << TemplRange << FixItHint::CreateRemoval(TemplRange);
883 }
884
885 // Build the BindingDecls.
887
888 // Build the BindingDecls.
889 for (auto &B : D.getDecompositionDeclarator().bindings()) {
890 // Check for name conflicts.
891 DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
892 IdentifierInfo *VarName = B.Name;
893 assert(VarName && "Cannot have an unnamed binding declaration");
894
898 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
899
900 // It's not permitted to shadow a template parameter name.
901 if (Previous.isSingleResult() &&
902 Previous.getFoundDecl()->isTemplateParameter()) {
903 DiagnoseTemplateParameterShadow(B.NameLoc, Previous.getFoundDecl());
904 Previous.clear();
905 }
906
907 QualType QT;
908 if (B.EllipsisLoc.isValid()) {
909 if (!cast<Decl>(DC)->isTemplated())
910 Diag(B.EllipsisLoc, diag::err_pack_outside_template);
911 QT = Context.getPackExpansionType(Context.DependentTy, std::nullopt,
912 /*ExpectsPackInType=*/false);
913 }
914
915 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name, QT);
916
917 ProcessDeclAttributeList(S, BD, *B.Attrs);
918
919 // Find the shadowed declaration before filtering for scope.
920 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
922 : nullptr;
923
924 bool ConsiderLinkage = DC->isFunctionOrMethod() &&
925 DS.getStorageClassSpec() == DeclSpec::SCS_extern;
926 FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
927 /*AllowInlineNamespace*/false);
928
929 bool IsPlaceholder = DS.getStorageClassSpec() != DeclSpec::SCS_static &&
930 DC->isFunctionOrMethod() && VarName->isPlaceholder();
931 if (!Previous.empty()) {
932 if (IsPlaceholder) {
933 bool sameDC = (Previous.end() - 1)
934 ->getDeclContext()
935 ->getRedeclContext()
936 ->Equals(DC->getRedeclContext());
937 if (sameDC &&
938 isDeclInScope(*(Previous.end() - 1), CurContext, S, false)) {
939 Previous.clear();
941 }
942 } else {
943 auto *Old = Previous.getRepresentativeDecl();
944 Diag(B.NameLoc, diag::err_redefinition) << B.Name;
945 Diag(Old->getLocation(), diag::note_previous_definition);
946 }
947 } else if (ShadowedDecl && !D.isRedeclaration()) {
948 CheckShadow(BD, ShadowedDecl, Previous);
949 }
950 PushOnScopeChains(BD, S, true);
951 Bindings.push_back(BD);
952 ParsingInitForAutoVars.insert(BD);
953 }
954
955 // There are no prior lookup results for the variable itself, because it
956 // is unnamed.
957 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
958 Decomp.getLSquareLoc());
961
962 // Build the variable that holds the non-decomposed object.
963 bool AddToScope = true;
964 NamedDecl *New =
965 ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
966 MultiTemplateParamsArg(), AddToScope, Bindings);
967 if (AddToScope) {
968 S->AddDecl(New);
969 CurContext->addHiddenDecl(New);
970 }
971
972 if (OpenMP().isInOpenMPDeclareTargetContext())
973 OpenMP().checkDeclIsAllowedInOpenMPTarget(nullptr, New);
974
975 return New;
976}
977
978// Check the arity of the structured bindings.
979// Create the resolved pack expr if needed.
981 QualType DecompType,
983 unsigned MemberCount) {
984 auto BindingWithPackItr = llvm::find_if(
985 Bindings, [](BindingDecl *D) -> bool { return D->isParameterPack(); });
986 bool HasPack = BindingWithPackItr != Bindings.end();
987 bool IsValid;
988 if (!HasPack) {
989 IsValid = Bindings.size() == MemberCount;
990 } else {
991 // There may not be more members than non-pack bindings.
992 IsValid = MemberCount >= Bindings.size() - 1;
993 }
994
995 if (IsValid && HasPack) {
996 // Create the pack expr and assign it to the binding.
997 unsigned PackSize = MemberCount - Bindings.size() + 1;
998
999 BindingDecl *BPack = *BindingWithPackItr;
1000 BPack->setDecomposedDecl(DD);
1001 SmallVector<ValueDecl *, 8> NestedBDs(PackSize);
1002 // Create the nested BindingDecls.
1003 for (unsigned I = 0; I < PackSize; ++I) {
1004 BindingDecl *NestedBD = BindingDecl::Create(
1005 S.Context, BPack->getDeclContext(), BPack->getLocation(),
1006 BPack->getIdentifier(), QualType());
1007 NestedBD->setDecomposedDecl(DD);
1008 NestedBDs[I] = NestedBD;
1009 }
1010
1012 S.Context.DependentTy, PackSize, /*ExpectsPackInType=*/false);
1013 auto *PackExpr = FunctionParmPackExpr::Create(
1014 S.Context, PackType, BPack, BPack->getBeginLoc(), NestedBDs);
1015 BPack->setBinding(PackType, PackExpr);
1016 }
1017
1018 if (IsValid)
1019 return false;
1020
1021 S.Diag(DD->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1022 << DecompType << (unsigned)Bindings.size() << MemberCount << MemberCount
1023 << (MemberCount < Bindings.size());
1024 return true;
1025}
1026
1029 QualType DecompType, const llvm::APSInt &NumElemsAPS, QualType ElemType,
1030 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
1031 unsigned NumElems = (unsigned)NumElemsAPS.getLimitedValue(UINT_MAX);
1032 auto *DD = cast<DecompositionDecl>(Src);
1033
1034 if (CheckBindingsCount(S, DD, DecompType, Bindings, NumElems))
1035 return true;
1036
1037 unsigned I = 0;
1038 for (auto *B : DD->flat_bindings()) {
1039 SourceLocation Loc = B->getLocation();
1040 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1041 if (E.isInvalid())
1042 return true;
1043 E = GetInit(Loc, E.get(), I++);
1044 if (E.isInvalid())
1045 return true;
1046 B->setBinding(ElemType, E.get());
1047 }
1048
1049 return false;
1050}
1051
1054 ValueDecl *Src, QualType DecompType,
1055 const llvm::APSInt &NumElems,
1056 QualType ElemType) {
1058 S, Bindings, Src, DecompType, NumElems, ElemType,
1059 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
1060 ExprResult E = S.ActOnIntegerConstant(Loc, I);
1061 if (E.isInvalid())
1062 return ExprError();
1063 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
1064 });
1065}
1066
1068 ValueDecl *Src, QualType DecompType,
1069 const ConstantArrayType *CAT) {
1070 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
1071 llvm::APSInt(CAT->getSize()),
1072 CAT->getElementType());
1073}
1074
1076 ValueDecl *Src, QualType DecompType,
1077 const VectorType *VT) {
1079 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
1081 DecompType.getQualifiers()));
1082}
1083
1086 ValueDecl *Src, QualType DecompType,
1087 const ComplexType *CT) {
1089 S, Bindings, Src, DecompType, llvm::APSInt::get(2),
1091 DecompType.getQualifiers()),
1092 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
1093 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
1094 });
1095}
1096
1099 const TemplateParameterList *Params) {
1101 llvm::raw_svector_ostream OS(SS);
1102 bool First = true;
1103 unsigned I = 0;
1104 for (auto &Arg : Args.arguments()) {
1105 if (!First)
1106 OS << ", ";
1107 Arg.getArgument().print(PrintingPolicy, OS,
1109 PrintingPolicy, Params, I));
1110 First = false;
1111 I++;
1112 }
1113 return std::string(OS.str());
1114}
1115
1116static QualType getStdTrait(Sema &S, SourceLocation Loc, StringRef Trait,
1117 TemplateArgumentListInfo &Args, unsigned DiagID) {
1118 auto DiagnoseMissing = [&] {
1119 if (DiagID)
1120 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
1121 Args, /*Params*/ nullptr);
1122 return QualType();
1123 };
1124
1125 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
1126 NamespaceDecl *Std = S.getStdNamespace();
1127 if (!Std)
1128 return DiagnoseMissing();
1129
1130 // Look up the trait itself, within namespace std. We can diagnose various
1131 // problems with this lookup even if we've been asked to not diagnose a
1132 // missing specialization, because this can only fail if the user has been
1133 // declaring their own names in namespace std or we don't support the
1134 // standard library implementation in use.
1135 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait), Loc,
1137 if (!S.LookupQualifiedName(Result, Std))
1138 return DiagnoseMissing();
1139 if (Result.isAmbiguous())
1140 return QualType();
1141
1142 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
1143 if (!TraitTD) {
1144 Result.suppressDiagnostics();
1145 NamedDecl *Found = *Result.begin();
1146 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
1147 S.Diag(Found->getLocation(), diag::note_declared_at);
1148 return QualType();
1149 }
1150
1151 // Build the template-id.
1152 QualType TraitTy = S.CheckTemplateIdType(
1153 ElaboratedTypeKeyword::None, TemplateName(TraitTD), Loc, Args,
1154 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
1155 if (TraitTy.isNull())
1156 return QualType();
1157
1158 if (!S.isCompleteType(Loc, TraitTy)) {
1159 if (DiagID)
1161 Loc, TraitTy, DiagID,
1163 TraitTD->getTemplateParameters()));
1164 return QualType();
1165 }
1166 return TraitTy;
1167}
1168
1169static bool lookupMember(Sema &S, CXXRecordDecl *RD,
1170 LookupResult &MemberLookup) {
1171 assert(RD && "specialization of class template is not a class?");
1172 S.LookupQualifiedName(MemberLookup, RD);
1173 return MemberLookup.isAmbiguous();
1174}
1175
1176static TemplateArgumentLoc
1178 uint64_t I) {
1180 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
1181}
1182
1183static TemplateArgumentLoc
1187
1188namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1189
1190static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1191 unsigned &OutSize) {
1194
1195 // Form template argument list for tuple_size<T>.
1196 TemplateArgumentListInfo Args(Loc, Loc);
1198
1199 QualType TraitTy = getStdTrait(S, Loc, "tuple_size", Args, /*DiagID=*/0);
1200 if (TraitTy.isNull())
1201 return IsTupleLike::NotTupleLike;
1202
1205
1206 // If there's no tuple_size specialization or the lookup of 'value' is empty,
1207 // it's not tuple-like.
1208 if (lookupMember(S, TraitTy->getAsCXXRecordDecl(), R) || R.empty())
1209 return IsTupleLike::NotTupleLike;
1210
1211 // If we get this far, we've committed to the tuple interpretation, but
1212 // we can still fail if there actually isn't a usable ::value.
1213
1214 struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1215 LookupResult &R;
1217 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1218 : R(R), Args(Args) {}
1219 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
1220 SourceLocation Loc) override {
1221 return S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1223 /*Params*/ nullptr);
1224 }
1225 } Diagnoser(R, Args);
1226
1227 ExprResult E =
1228 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1229 if (E.isInvalid())
1230 return IsTupleLike::Error;
1231
1232 llvm::APSInt Size;
1233 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser);
1234 if (E.isInvalid())
1235 return IsTupleLike::Error;
1236
1237 // The implementation limit is UINT_MAX-1, to allow this to be passed down on
1238 // an UnsignedOrNone.
1239 if (Size < 0 || Size >= UINT_MAX) {
1241 Size.toString(Str);
1242 S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_invalid)
1244 /*Params=*/nullptr)
1245 << StringRef(Str.data(), Str.size());
1246 return IsTupleLike::Error;
1247 }
1248
1249 OutSize = Size.getExtValue();
1250 return IsTupleLike::TupleLike;
1251}
1252
1253/// \return std::tuple_element<I, T>::type.
1255 unsigned I, QualType T) {
1256 // Form template argument list for tuple_element<I, T>.
1257 TemplateArgumentListInfo Args(Loc, Loc);
1258 Args.addArgument(
1261
1262 QualType TraitTy =
1263 getStdTrait(S, Loc, "tuple_element", Args,
1264 diag::err_decomp_decl_std_tuple_element_not_specialized);
1265 if (TraitTy.isNull())
1266 return QualType();
1267
1268 DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1269 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1270 if (lookupMember(S, TraitTy->getAsCXXRecordDecl(), R))
1271 return QualType();
1272
1273 auto *TD = R.getAsSingle<TypeDecl>();
1274 if (!TD) {
1275 R.suppressDiagnostics();
1276 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1278 /*Params*/ nullptr);
1279 if (!R.empty())
1280 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1281 return QualType();
1282 }
1283
1284 NestedNameSpecifier Qualifier(TraitTy.getTypePtr());
1285 return S.Context.getTypeDeclType(ElaboratedTypeKeyword::None, Qualifier, TD);
1286}
1287
1288namespace {
1289struct InitializingBinding {
1290 Sema &S;
1291 InitializingBinding(Sema &S, BindingDecl *BD) : S(S) {
1292 Sema::CodeSynthesisContext Ctx;
1295 Ctx.Entity = BD;
1297 }
1298 ~InitializingBinding() {
1300 }
1301};
1302}
1303
1306 VarDecl *Src, QualType DecompType,
1307 unsigned NumElems) {
1308 auto *DD = cast<DecompositionDecl>(Src);
1309 if (CheckBindingsCount(S, DD, DecompType, Bindings, NumElems))
1310 return true;
1311
1312 if (Bindings.empty())
1313 return false;
1314
1315 DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1316
1317 // [dcl.decomp]p3:
1318 // The unqualified-id get is looked up in the scope of E by class member
1319 // access lookup ...
1320 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1321 bool UseMemberGet = false;
1322 if (S.isCompleteType(Src->getLocation(), DecompType)) {
1323 if (auto *RD = DecompType->getAsCXXRecordDecl())
1324 S.LookupQualifiedName(MemberGet, RD);
1325 if (MemberGet.isAmbiguous())
1326 return true;
1327 // ... and if that finds at least one declaration that is a function
1328 // template whose first template parameter is a non-type parameter ...
1329 for (NamedDecl *D : MemberGet) {
1330 if (FunctionTemplateDecl *FTD =
1331 dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
1332 TemplateParameterList *TPL = FTD->getTemplateParameters();
1333 if (TPL->size() != 0 &&
1335 // ... the initializer is e.get<i>().
1336 UseMemberGet = true;
1337 break;
1338 }
1339 }
1340 }
1341 }
1342
1343 unsigned I = 0;
1344 for (auto *B : DD->flat_bindings()) {
1345 InitializingBinding InitContext(S, B);
1346 SourceLocation Loc = B->getLocation();
1347
1348 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1349 if (E.isInvalid())
1350 return true;
1351
1352 // e is an lvalue if the type of the entity is an lvalue reference and
1353 // an xvalue otherwise
1354 if (!Src->getType()->isLValueReferenceType())
1355 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1356 E.get(), nullptr, VK_XValue,
1358
1359 TemplateArgumentListInfo Args(Loc, Loc);
1360 Args.addArgument(
1362
1363 if (UseMemberGet) {
1364 // if [lookup of member get] finds at least one declaration, the
1365 // initializer is e.get<i-1>().
1366 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1367 CXXScopeSpec(), SourceLocation(), nullptr,
1368 MemberGet, &Args, nullptr);
1369 if (E.isInvalid())
1370 return true;
1371
1372 E = S.BuildCallExpr(nullptr, E.get(), Loc, {}, Loc);
1373 } else {
1374 // Otherwise, the initializer is get<i-1>(e), where get is looked up
1375 // in the associated namespaces.
1378 DeclarationNameInfo(GetDN, Loc), /*RequiresADL=*/true, &Args,
1380 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
1381
1382 Expr *Arg = E.get();
1383 E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc);
1384 }
1385 if (E.isInvalid())
1386 return true;
1387 Expr *Init = E.get();
1388
1389 // Given the type T designated by std::tuple_element<i - 1, E>::type
1390 QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1391 if (T.isNull())
1392 return true;
1393
1394 // C++26 [dcl.struct.bind]p7:
1395 // and the type Ui, defined as Ti if the initializer is a prvalue,
1396 // as "lvalue reference to Ti" if the initializer is an lvalue,
1397 // or as "rvalue reference to Ti" otherwise
1398 // "defined as Ti if the initializer is a prvalue" was introduced by CWG3135
1399 QualType U = E.get()->isPRValue()
1400 ? T
1401 : S.BuildReferenceType(T, E.get()->isLValue(), Loc,
1402 B->getDeclName());
1403 if (U.isNull())
1404 return true;
1405
1406 // Don't give this VarDecl a TypeSourceInfo, since this is a synthesized
1407 // entity and this type was never written in source code.
1408 auto *BindingVD =
1409 VarDecl::Create(S.Context, Src->getDeclContext(), Loc, Loc,
1410 B->getDeclName().getAsIdentifierInfo(), U,
1411 /*TInfo=*/nullptr, Src->getStorageClass());
1412 BindingVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1413 BindingVD->setTSCSpec(Src->getTSCSpec());
1414 BindingVD->setConstexpr(Src->isConstexpr());
1415 if (const auto *CIAttr = Src->getAttr<ConstInitAttr>())
1416 BindingVD->addAttr(CIAttr->clone(S.Context));
1417 BindingVD->setImplicit();
1418 if (Src->isInlineSpecified())
1419 BindingVD->setInlineSpecified();
1420 BindingVD->getLexicalDeclContext()->addHiddenDecl(BindingVD);
1421
1424 InitializationSequence Seq(S, Entity, Kind, Init);
1425 E = Seq.Perform(S, Entity, Kind, Init);
1426 if (E.isInvalid())
1427 return true;
1428 E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
1429 if (E.isInvalid())
1430 return true;
1431 BindingVD->setInit(E.get());
1433
1435 CXXScopeSpec(), DeclarationNameInfo(B->getDeclName(), Loc), BindingVD);
1436 if (E.isInvalid())
1437 return true;
1438
1439 B->setBinding(T, E.get());
1440 I++;
1441 }
1442
1443 return false;
1444}
1445
1446/// Find the base class to decompose in a built-in decomposition of a class type.
1447/// This base class search is, unfortunately, not quite like any other that we
1448/// perform anywhere else in C++.
1450 const CXXRecordDecl *RD,
1451 CXXCastPath &BasePath) {
1452 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1453 CXXBasePath &Path) {
1454 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1455 };
1456
1457 const CXXRecordDecl *ClassWithFields = nullptr;
1459 if (RD->hasDirectFields())
1460 // [dcl.decomp]p4:
1461 // Otherwise, all of E's non-static data members shall be public direct
1462 // members of E ...
1463 ClassWithFields = RD;
1464 else {
1465 // ... or of ...
1466 CXXBasePaths Paths;
1467 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1468 if (!RD->lookupInBases(BaseHasFields, Paths)) {
1469 // If no classes have fields, just decompose RD itself. (This will work
1470 // if and only if zero bindings were provided.)
1471 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
1472 }
1473
1474 CXXBasePath *BestPath = nullptr;
1475 for (auto &P : Paths) {
1476 if (!BestPath)
1477 BestPath = &P;
1478 else if (!S.Context.hasSameType(P.back().Base->getType(),
1479 BestPath->back().Base->getType())) {
1480 // ... the same ...
1481 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1482 << false << RD << BestPath->back().Base->getType()
1483 << P.back().Base->getType();
1484 return DeclAccessPair();
1485 } else if (P.Access < BestPath->Access) {
1486 BestPath = &P;
1487 }
1488 }
1489
1490 // ... unambiguous ...
1491 QualType BaseType = BestPath->back().Base->getType();
1492 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1493 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1494 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1495 return DeclAccessPair();
1496 }
1497
1498 // ... [accessible, implied by other rules] base class of E.
1499 S.CheckBaseClassAccess(Loc, BaseType, S.Context.getCanonicalTagType(RD),
1500 *BestPath, diag::err_decomp_decl_inaccessible_base);
1501 AS = BestPath->Access;
1502
1503 ClassWithFields = BaseType->getAsCXXRecordDecl();
1504 S.BuildBasePathArray(Paths, BasePath);
1505 }
1506
1507 // The above search did not check whether the selected class itself has base
1508 // classes with fields, so check that now.
1509 CXXBasePaths Paths;
1510 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1511 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1512 << (ClassWithFields == RD) << RD << ClassWithFields
1513 << Paths.front().back().Base->getType();
1514 return DeclAccessPair();
1515 }
1516
1517 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1518}
1519
1521 const CXXRecordDecl *OrigRD,
1522 QualType DecompType,
1523 DeclAccessPair BasePair) {
1524 const auto *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1525 if (!RD)
1526 return true;
1527
1528 for (auto *FD : RD->fields()) {
1529 if (FD->isUnnamedBitField())
1530 continue;
1531
1532 // All the non-static data members are required to be nameable, so they
1533 // must all have names.
1534 if (!FD->getDeclName()) {
1535 if (RD->isLambda()) {
1536 S.Diag(Loc, diag::err_decomp_decl_lambda);
1537 S.Diag(RD->getLocation(), diag::note_lambda_decl);
1538 return true;
1539 }
1540
1541 if (FD->isAnonymousStructOrUnion()) {
1542 S.Diag(Loc, diag::err_decomp_decl_anon_union_member)
1543 << DecompType << FD->getType()->isUnionType();
1544 S.Diag(FD->getLocation(), diag::note_declared_at);
1545 return true;
1546 }
1547
1548 // FIXME: Are there any other ways we could have an anonymous member?
1549 }
1550 // The field must be accessible in the context of the structured binding.
1551 // We already checked that the base class is accessible.
1552 // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1553 // const_cast here.
1555 Loc, const_cast<CXXRecordDecl *>(OrigRD),
1557 BasePair.getAccess(), FD->getAccess())));
1558 }
1559 return false;
1560}
1561
1563 ValueDecl *Src, QualType DecompType,
1564 const CXXRecordDecl *OrigRD) {
1565 if (S.RequireCompleteType(Src->getLocation(), DecompType,
1566 diag::err_incomplete_type))
1567 return true;
1568
1569 CXXCastPath BasePath;
1570 DeclAccessPair BasePair =
1571 findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1572 const auto *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1573 if (!RD)
1574 return true;
1575 QualType BaseType = S.Context.getQualifiedType(
1576 S.Context.getCanonicalTagType(RD), DecompType.getQualifiers());
1577
1578 auto *DD = cast<DecompositionDecl>(Src);
1579 unsigned NumFields = llvm::count_if(
1580 RD->fields(), [](FieldDecl *FD) { return !FD->isUnnamedBitField(); });
1581 if (CheckBindingsCount(S, DD, DecompType, Bindings, NumFields))
1582 return true;
1583
1584 // all of E's non-static data members shall be [...] well-formed
1585 // when named as e.name in the context of the structured binding,
1586 // E shall not have an anonymous union member, ...
1587 auto FlatBindings = DD->flat_bindings();
1588 assert(llvm::range_size(FlatBindings) == NumFields);
1589 auto FlatBindingsItr = FlatBindings.begin();
1590
1591 if (CheckMemberDecompositionFields(S, Src->getLocation(), OrigRD, DecompType,
1592 BasePair))
1593 return true;
1594
1595 for (auto *FD : RD->fields()) {
1596 if (FD->isUnnamedBitField())
1597 continue;
1598
1599 // We have a real field to bind.
1600 assert(FlatBindingsItr != FlatBindings.end());
1601 BindingDecl *B = *(FlatBindingsItr++);
1602 SourceLocation Loc = B->getLocation();
1603
1604 // Initialize the binding to Src.FD.
1605 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1606 if (E.isInvalid())
1607 return true;
1608 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1609 VK_LValue, &BasePath);
1610 if (E.isInvalid())
1611 return true;
1612 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1613 CXXScopeSpec(), FD,
1615 DeclarationNameInfo(FD->getDeclName(), Loc));
1616 if (E.isInvalid())
1617 return true;
1618
1619 // If the type of the member is T, the referenced type is cv T, where cv is
1620 // the cv-qualification of the decomposition expression.
1621 //
1622 // FIXME: We resolve a defect here: if the field is mutable, we do not add
1623 // 'const' to the type of the field.
1624 Qualifiers Q = DecompType.getQualifiers();
1625 if (FD->isMutable())
1626 Q.removeConst();
1627 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1628 }
1629
1630 return false;
1631}
1632
1634 QualType DecompType = DD->getType();
1635
1636 // If the type of the decomposition is dependent, then so is the type of
1637 // each binding.
1638 if (DecompType->isDependentType()) {
1639 // Note that all of the types are still Null or PackExpansionType.
1640 for (auto *B : DD->bindings()) {
1641 // Do not overwrite any pack type.
1642 if (B->getType().isNull())
1643 B->setType(Context.DependentTy);
1644 }
1645 return;
1646 }
1647
1648 DecompType = DecompType.getNonReferenceType();
1650
1651 // C++1z [dcl.decomp]/2:
1652 // If E is an array type [...]
1653 // As an extension, we also support decomposition of built-in complex and
1654 // vector types.
1655 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1656 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1657 DD->setInvalidDecl();
1658 return;
1659 }
1660 if (auto *VT = DecompType->getAs<VectorType>()) {
1661 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1662 DD->setInvalidDecl();
1663 return;
1664 }
1665 if (auto *CT = DecompType->getAs<ComplexType>()) {
1666 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1667 DD->setInvalidDecl();
1668 return;
1669 }
1670
1671 // C++1z [dcl.decomp]/3:
1672 // if the expression std::tuple_size<E>::value is a well-formed integral
1673 // constant expression, [...]
1674 unsigned TupleSize;
1675 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1676 case IsTupleLike::Error:
1677 DD->setInvalidDecl();
1678 return;
1679
1680 case IsTupleLike::TupleLike:
1681 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1682 DD->setInvalidDecl();
1683 return;
1684
1685 case IsTupleLike::NotTupleLike:
1686 break;
1687 }
1688
1689 // C++1z [dcl.dcl]/8:
1690 // [E shall be of array or non-union class type]
1691 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1692 if (!RD || RD->isUnion()) {
1693 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1694 << DD << !RD << DecompType;
1695 DD->setInvalidDecl();
1696 return;
1697 }
1698
1699 // C++1z [dcl.decomp]/4:
1700 // all of E's non-static data members shall be [...] direct members of
1701 // E or of the same unambiguous public base class of E, ...
1702 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1703 DD->setInvalidDecl();
1704}
1705
1707 SourceLocation Loc) {
1708 const ASTContext &Ctx = getASTContext();
1709 assert(!T->isDependentType());
1710
1711 Qualifiers Quals;
1712 QualType Unqual = Context.getUnqualifiedArrayType(T, Quals);
1713 Quals.removeCVRQualifiers();
1714 T = Context.getQualifiedType(Unqual, Quals);
1715
1716 if (auto *CAT = Ctx.getAsConstantArrayType(T))
1717 return static_cast<unsigned>(CAT->getSize().getZExtValue());
1718 if (auto *VT = T->getAs<VectorType>())
1719 return VT->getNumElements();
1720 if (T->getAs<ComplexType>())
1721 return 2u;
1722
1723 unsigned TupleSize;
1724 switch (isTupleLike(*this, Loc, T, TupleSize)) {
1725 case IsTupleLike::Error:
1726 return std::nullopt;
1727 case IsTupleLike::TupleLike:
1728 return TupleSize;
1729 case IsTupleLike::NotTupleLike:
1730 break;
1731 }
1732
1733 const CXXRecordDecl *OrigRD = T->getAsCXXRecordDecl();
1734 if (!OrigRD || OrigRD->isUnion())
1735 return std::nullopt;
1736
1737 if (RequireCompleteType(Loc, T, diag::err_incomplete_type))
1738 return std::nullopt;
1739
1740 CXXCastPath BasePath;
1741 DeclAccessPair BasePair =
1742 findDecomposableBaseClass(*this, Loc, OrigRD, BasePath);
1743 const auto *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1744 if (!RD)
1745 return std::nullopt;
1746
1747 unsigned NumFields = llvm::count_if(
1748 RD->fields(), [](FieldDecl *FD) { return !FD->isUnnamedBitField(); });
1749
1750 if (CheckMemberDecompositionFields(*this, Loc, OrigRD, T, BasePair))
1751 return std::nullopt;
1752
1753 return NumFields;
1754}
1755
1757 // Shortcut if exceptions are disabled.
1758 if (!getLangOpts().CXXExceptions)
1759 return;
1760
1761 assert(Context.hasSameType(New->getType(), Old->getType()) &&
1762 "Should only be called if types are otherwise the same.");
1763
1764 QualType NewType = New->getType();
1765 QualType OldType = Old->getType();
1766
1767 // We're only interested in pointers and references to functions, as well
1768 // as pointers to member functions.
1769 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1770 NewType = R->getPointeeType();
1771 OldType = OldType->castAs<ReferenceType>()->getPointeeType();
1772 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1773 NewType = P->getPointeeType();
1774 OldType = OldType->castAs<PointerType>()->getPointeeType();
1775 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1776 NewType = M->getPointeeType();
1777 OldType = OldType->castAs<MemberPointerType>()->getPointeeType();
1778 }
1779
1780 if (!NewType->isFunctionProtoType())
1781 return;
1782
1783 // There's lots of special cases for functions. For function pointers, system
1784 // libraries are hopefully not as broken so that we don't need these
1785 // workarounds.
1787 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1788 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1789 New->setInvalidDecl();
1790 }
1791}
1792
1793/// CheckCXXDefaultArguments - Verify that the default arguments for a
1794/// function declaration are well-formed according to C++
1795/// [dcl.fct.default].
1797 // This checking doesn't make sense for explicit specializations; their
1798 // default arguments are determined by the declaration we're specializing,
1799 // not by FD.
1801 return;
1802 if (auto *FTD = FD->getDescribedFunctionTemplate())
1803 if (FTD->isMemberSpecialization())
1804 return;
1805
1806 unsigned NumParams = FD->getNumParams();
1807 unsigned ParamIdx = 0;
1808
1809 // Find first parameter with a default argument
1810 for (; ParamIdx < NumParams; ++ParamIdx) {
1811 ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1812 if (Param->hasDefaultArg())
1813 break;
1814 }
1815
1816 // C++20 [dcl.fct.default]p4:
1817 // In a given function declaration, each parameter subsequent to a parameter
1818 // with a default argument shall have a default argument supplied in this or
1819 // a previous declaration, unless the parameter was expanded from a
1820 // parameter pack, or shall be a function parameter pack.
1821 for (++ParamIdx; ParamIdx < NumParams; ++ParamIdx) {
1822 ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1823 if (Param->hasDefaultArg() || Param->isParameterPack() ||
1825 CurrentInstantiationScope->isLocalPackExpansion(Param)))
1826 continue;
1827 if (Param->isInvalidDecl())
1828 /* We already complained about this parameter. */;
1829 else if (Param->getIdentifier())
1830 Diag(Param->getLocation(), diag::err_param_default_argument_missing_name)
1831 << Param->getIdentifier();
1832 else
1833 Diag(Param->getLocation(), diag::err_param_default_argument_missing);
1834 }
1835}
1836
1837/// Check that the given type is a literal type. Issue a diagnostic if not,
1838/// if Kind is Diagnose.
1839/// \return \c true if a problem has been found (and optionally diagnosed).
1840template <typename... Ts>
1842 SourceLocation Loc, QualType T, unsigned DiagID,
1843 Ts &&...DiagArgs) {
1844 if (T->isDependentType())
1845 return false;
1846
1847 switch (Kind) {
1849 return SemaRef.RequireLiteralType(Loc, T, DiagID,
1850 std::forward<Ts>(DiagArgs)...);
1851
1853 return !T->isLiteralType(SemaRef.Context);
1854 }
1855
1856 llvm_unreachable("unknown CheckConstexprKind");
1857}
1858
1859/// Determine whether a destructor cannot be constexpr due to
1861 const CXXDestructorDecl *DD,
1863 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1864 "this check is obsolete for C++23");
1865 auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) {
1866 const CXXRecordDecl *RD =
1867 T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1868 if (!RD || RD->hasConstexprDestructor())
1869 return true;
1870
1872 SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject)
1873 << static_cast<int>(DD->getConstexprKind()) << !FD
1874 << (FD ? FD->getDeclName() : DeclarationName()) << T;
1875 SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject)
1876 << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T;
1877 }
1878 return false;
1879 };
1880
1881 const CXXRecordDecl *RD = DD->getParent();
1882 for (const CXXBaseSpecifier &B : RD->bases())
1883 if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr))
1884 return false;
1885 for (const FieldDecl *FD : RD->fields())
1886 if (!Check(FD->getLocation(), FD->getType(), FD))
1887 return false;
1888 return true;
1889}
1890
1891/// Check whether a function's parameter types are all literal types. If so,
1892/// return true. If not, produce a suitable diagnostic and return false.
1894 const FunctionDecl *FD,
1896 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1897 "this check is obsolete for C++23");
1898 unsigned ArgIndex = 0;
1899 const auto *FT = FD->getType()->castAs<FunctionProtoType>();
1900 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1901 e = FT->param_type_end();
1902 i != e; ++i, ++ArgIndex) {
1903 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1904 assert(PD && "null in a parameter list");
1905 SourceLocation ParamLoc = PD->getLocation();
1906 if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i,
1907 diag::err_constexpr_non_literal_param, ArgIndex + 1,
1909 FD->isConsteval()))
1910 return false;
1911 }
1912 return true;
1913}
1914
1915/// Check whether a function's return type is a literal type. If so, return
1916/// true. If not, produce a suitable diagnostic and return false.
1917static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD,
1919 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1920 "this check is obsolete for C++23");
1921 if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(),
1922 diag::err_constexpr_non_literal_return,
1923 FD->isConsteval()))
1924 return false;
1925 return true;
1926}
1927
1928/// Get diagnostic %select index for tag kind for
1929/// record diagnostic message.
1930/// WARNING: Indexes apply to particular diagnostics only!
1931///
1932/// \returns diagnostic %select index.
1934 switch (Tag) {
1936 return 0;
1938 return 1;
1939 case TagTypeKind::Class:
1940 return 2;
1941 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1942 }
1943}
1944
1945static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
1946 Stmt *Body,
1948static bool CheckConstexprMissingReturn(Sema &SemaRef, const FunctionDecl *Dcl);
1949
1951 CheckConstexprKind Kind) {
1952 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1953 if (!getLangOpts().CPlusPlus26 && MD && MD->isInstance()) {
1954 // C++11 [dcl.constexpr]p4:
1955 // The definition of a constexpr constructor shall satisfy the following
1956 // constraints:
1957 // - the class shall not have any virtual base classes;
1958 //
1959 // FIXME: This only applies to constructors and destructors, not arbitrary
1960 // member functions.
1961 const CXXRecordDecl *RD = MD->getParent();
1962 if (RD->getNumVBases()) {
1964 return false;
1965
1966 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1967 << isa<CXXConstructorDecl>(NewFD)
1969 for (const auto &I : RD->vbases())
1970 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1971 << I.getSourceRange();
1972 return false;
1973 }
1974 }
1975
1976 if (!isa<CXXConstructorDecl>(NewFD)) {
1977 // C++11 [dcl.constexpr]p3:
1978 // The definition of a constexpr function shall satisfy the following
1979 // constraints:
1980 // - it shall not be virtual; (removed in C++20)
1981 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1982 if (Method && Method->isVirtual()) {
1983 if (getLangOpts().CPlusPlus20) {
1984 if (Kind == CheckConstexprKind::Diagnose)
1985 Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
1986 } else {
1988 return false;
1989
1990 Method = Method->getCanonicalDecl();
1991 Diag(Method->getLocation(), diag::err_constexpr_virtual);
1992
1993 // If it's not obvious why this function is virtual, find an overridden
1994 // function which uses the 'virtual' keyword.
1995 const CXXMethodDecl *WrittenVirtual = Method;
1996 while (!WrittenVirtual->isVirtualAsWritten())
1997 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1998 if (WrittenVirtual != Method)
1999 Diag(WrittenVirtual->getLocation(),
2000 diag::note_overridden_virtual_function);
2001 return false;
2002 }
2003 }
2004
2005 // - its return type shall be a literal type; (removed in C++23)
2006 if (!getLangOpts().CPlusPlus23 &&
2007 !CheckConstexprReturnType(*this, NewFD, Kind))
2008 return false;
2009 }
2010
2011 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) {
2012 // A destructor can be constexpr only if the defaulted destructor could be;
2013 // we don't need to check the members and bases if we already know they all
2014 // have constexpr destructors. (removed in C++23)
2015 if (!getLangOpts().CPlusPlus23 &&
2016 !Dtor->getParent()->defaultedDestructorIsConstexpr()) {
2018 return false;
2019 if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind))
2020 return false;
2021 }
2022 }
2023
2024 // - each of its parameter types shall be a literal type; (removed in C++23)
2025 if (!getLangOpts().CPlusPlus23 &&
2026 !CheckConstexprParameterTypes(*this, NewFD, Kind))
2027 return false;
2028
2029 Stmt *Body = NewFD->getBody();
2030 assert(Body &&
2031 "CheckConstexprFunctionDefinition called on function with no body");
2032 return CheckConstexprFunctionBody(*this, NewFD, Body, Kind);
2033}
2034
2035/// Check the given declaration statement is legal within a constexpr function
2036/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
2037///
2038/// \return true if the body is OK (maybe only as an extension), false if we
2039/// have diagnosed a problem.
2040static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
2041 DeclStmt *DS, SourceLocation &Cxx1yLoc,
2043 // C++11 [dcl.constexpr]p3 and p4:
2044 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
2045 // contain only
2046 for (const auto *DclIt : DS->decls()) {
2047 switch (DclIt->getKind()) {
2048 case Decl::StaticAssert:
2049 case Decl::Using:
2050 case Decl::UsingShadow:
2051 case Decl::UsingDirective:
2052 case Decl::UnresolvedUsingTypename:
2053 case Decl::UnresolvedUsingValue:
2054 case Decl::UsingEnum:
2055 // - static_assert-declarations
2056 // - using-declarations,
2057 // - using-directives,
2058 // - using-enum-declaration
2059 continue;
2060
2061 case Decl::CXXExpansionStmt:
2062 continue;
2063
2064 case Decl::Typedef:
2065 case Decl::TypeAlias: {
2066 // - typedef declarations and alias-declarations that do not define
2067 // classes or enumerations,
2068 const auto *TN = cast<TypedefNameDecl>(DclIt);
2069 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
2070 // Don't allow variably-modified types in constexpr functions.
2072 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
2073 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
2074 << TL.getSourceRange() << TL.getType()
2076 }
2077 return false;
2078 }
2079 continue;
2080 }
2081
2082 case Decl::Enum:
2083 case Decl::CXXRecord:
2084 // C++1y allows types to be defined, not just declared.
2085 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) {
2087 SemaRef.DiagCompat(DS->getBeginLoc(),
2088 diag_compat::constexpr_type_definition)
2090 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
2091 return false;
2092 }
2093 }
2094 continue;
2095
2096 case Decl::EnumConstant:
2097 case Decl::IndirectField:
2098 case Decl::ParmVar:
2099 // These can only appear with other declarations which are banned in
2100 // C++11 and permitted in C++1y, so ignore them.
2101 continue;
2102
2103 case Decl::Var:
2104 case Decl::Decomposition: {
2105 // C++1y [dcl.constexpr]p3 allows anything except:
2106 // a definition of a variable of non-literal type or of static or
2107 // thread storage duration or [before C++2a] for which no
2108 // initialization is performed.
2109 const auto *VD = cast<VarDecl>(DclIt);
2110 if (VD->isThisDeclarationADefinition()) {
2111 if (VD->isStaticLocal()) {
2113 SemaRef.DiagCompat(VD->getLocation(),
2114 diag_compat::constexpr_static_var)
2116 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
2117 } else if (!SemaRef.getLangOpts().CPlusPlus23) {
2118 return false;
2119 }
2120 }
2121 if (SemaRef.LangOpts.CPlusPlus23) {
2122 CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(),
2123 diag::warn_cxx20_compat_constexpr_var,
2125 } else if (CheckLiteralType(
2126 SemaRef, Kind, VD->getLocation(), VD->getType(),
2127 diag::err_constexpr_local_var_non_literal_type,
2129 return false;
2130 }
2131 if (!VD->getType()->isDependentType() &&
2132 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
2134 SemaRef.DiagCompat(VD->getLocation(),
2135 diag_compat::constexpr_local_var_no_init)
2137 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2138 return false;
2139 }
2140 continue;
2141 }
2142 }
2144 SemaRef.DiagCompat(VD->getLocation(), diag_compat::constexpr_local_var)
2146 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
2147 return false;
2148 }
2149 continue;
2150 }
2151
2152 case Decl::NamespaceAlias:
2153 case Decl::Function:
2154 // These are disallowed in C++11 and permitted in C++1y. Allow them
2155 // everywhere as an extension.
2156 if (!Cxx1yLoc.isValid())
2157 Cxx1yLoc = DS->getBeginLoc();
2158 continue;
2159
2160 default:
2162 SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2163 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2164 }
2165 return false;
2166 }
2167 }
2168
2169 return true;
2170}
2171
2172/// Check that the given field is initialized within a constexpr constructor.
2173///
2174/// \param Dcl The constexpr constructor being checked.
2175/// \param Field The field being checked. This may be a member of an anonymous
2176/// struct or union nested within the class being checked.
2177/// \param Inits All declarations, including anonymous struct/union members and
2178/// indirect members, for which any initialization was provided.
2179/// \param Diagnosed Whether we've emitted the error message yet. Used to attach
2180/// multiple notes for different members to the same error.
2181/// \param Kind Whether we're diagnosing a constructor as written or determining
2182/// whether the formal requirements are satisfied.
2183/// \return \c false if we're checking for validity and the constructor does
2184/// not satisfy the requirements on a constexpr constructor.
2186 const FunctionDecl *Dcl,
2187 FieldDecl *Field,
2189 bool &Diagnosed,
2191 // In C++20 onwards, there's nothing to check for validity.
2193 SemaRef.getLangOpts().CPlusPlus20)
2194 return true;
2195
2196 if (Field->isInvalidDecl())
2197 return true;
2198
2199 if (Field->isUnnamedBitField())
2200 return true;
2201
2202 // Anonymous unions with no variant members and empty anonymous structs do not
2203 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
2204 // indirect fields don't need initializing.
2205 if (Field->isAnonymousStructOrUnion() &&
2206 (Field->getType()->isUnionType()
2207 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
2208 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
2209 return true;
2210
2211 if (!Inits.count(Field)) {
2213 if (!Diagnosed) {
2214 SemaRef.DiagCompat(Dcl->getLocation(),
2215 diag_compat::constexpr_ctor_missing_init);
2216 Diagnosed = true;
2217 }
2218 SemaRef.Diag(Field->getLocation(),
2219 diag::note_constexpr_ctor_missing_init);
2220 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2221 return false;
2222 }
2223 } else if (Field->isAnonymousStructOrUnion()) {
2224 const auto *RD = Field->getType()->castAsRecordDecl();
2225 for (auto *I : RD->fields())
2226 // If an anonymous union contains an anonymous struct of which any member
2227 // is initialized, all members must be initialized.
2228 if (!RD->isUnion() || Inits.count(I))
2229 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2230 Kind))
2231 return false;
2232 }
2233 return true;
2234}
2235
2236/// Check the provided statement is allowed in a constexpr function
2237/// definition.
2238static bool
2241 SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
2242 SourceLocation &Cxx2bLoc,
2244 // - its function-body shall be [...] a compound-statement that contains only
2245 switch (S->getStmtClass()) {
2246 case Stmt::NullStmtClass:
2247 // - null statements,
2248 return true;
2249
2250 case Stmt::DeclStmtClass:
2251 // - static_assert-declarations
2252 // - using-declarations,
2253 // - using-directives,
2254 // - typedef declarations and alias-declarations that do not define
2255 // classes or enumerations,
2256 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind))
2257 return false;
2258 return true;
2259
2260 case Stmt::ReturnStmtClass:
2261 // - and exactly one return statement;
2262 if (isa<CXXConstructorDecl>(Dcl)) {
2263 // C++1y allows return statements in constexpr constructors.
2264 if (!Cxx1yLoc.isValid())
2265 Cxx1yLoc = S->getBeginLoc();
2266 return true;
2267 }
2268
2269 ReturnStmts.push_back(S->getBeginLoc());
2270 return true;
2271
2272 case Stmt::AttributedStmtClass:
2273 // Attributes on a statement don't affect its formal kind and hence don't
2274 // affect its validity in a constexpr function.
2276 SemaRef, Dcl, cast<AttributedStmt>(S)->getSubStmt(), ReturnStmts,
2277 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind);
2278
2279 case Stmt::CompoundStmtClass: {
2280 // C++1y allows compound-statements.
2281 if (!Cxx1yLoc.isValid())
2282 Cxx1yLoc = S->getBeginLoc();
2283
2284 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
2285 for (auto *BodyIt : CompStmt->body()) {
2286 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
2287 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2288 return false;
2289 }
2290 return true;
2291 }
2292
2293 case Stmt::IfStmtClass: {
2294 // C++1y allows if-statements.
2295 if (!Cxx1yLoc.isValid())
2296 Cxx1yLoc = S->getBeginLoc();
2297
2298 IfStmt *If = cast<IfStmt>(S);
2299 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
2300 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2301 return false;
2302 if (If->getElse() &&
2303 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
2304 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2305 return false;
2306 return true;
2307 }
2308
2309 case Stmt::WhileStmtClass:
2310 case Stmt::DoStmtClass:
2311 case Stmt::ForStmtClass:
2312 case Stmt::CXXForRangeStmtClass:
2313 case Stmt::ContinueStmtClass:
2314 // C++1y allows all of these. We don't allow them as extensions in C++11,
2315 // because they don't make sense without variable mutation.
2316 if (!SemaRef.getLangOpts().CPlusPlus14)
2317 break;
2318 if (!Cxx1yLoc.isValid())
2319 Cxx1yLoc = S->getBeginLoc();
2320 for (Stmt *SubStmt : S->children()) {
2321 if (SubStmt &&
2322 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2323 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2324 return false;
2325 }
2326 return true;
2327
2328 case Stmt::SwitchStmtClass:
2329 case Stmt::CaseStmtClass:
2330 case Stmt::DefaultStmtClass:
2331 case Stmt::BreakStmtClass:
2332 // C++1y allows switch-statements, and since they don't need variable
2333 // mutation, we can reasonably allow them in C++11 as an extension.
2334 if (!Cxx1yLoc.isValid())
2335 Cxx1yLoc = S->getBeginLoc();
2336 for (Stmt *SubStmt : S->children()) {
2337 if (SubStmt &&
2338 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2339 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2340 return false;
2341 }
2342 return true;
2343
2344 case Stmt::LabelStmtClass:
2345 case Stmt::GotoStmtClass:
2346 if (Cxx2bLoc.isInvalid())
2347 Cxx2bLoc = S->getBeginLoc();
2348 for (Stmt *SubStmt : S->children()) {
2349 if (SubStmt &&
2350 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2351 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2352 return false;
2353 }
2354 return true;
2355
2356 case Stmt::GCCAsmStmtClass:
2357 case Stmt::MSAsmStmtClass:
2358 // C++2a allows inline assembly statements.
2359 case Stmt::CXXTryStmtClass:
2360 if (Cxx2aLoc.isInvalid())
2361 Cxx2aLoc = S->getBeginLoc();
2362 for (Stmt *SubStmt : S->children()) {
2363 if (SubStmt &&
2364 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2365 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2366 return false;
2367 }
2368 return true;
2369
2370 case Stmt::CXXCatchStmtClass:
2371 // Do not bother checking the language mode (already covered by the
2372 // try block check).
2374 SemaRef, Dcl, cast<CXXCatchStmt>(S)->getHandlerBlock(), ReturnStmts,
2375 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2376 return false;
2377 return true;
2378
2379 default:
2380 if (!isa<Expr>(S))
2381 break;
2382
2383 // C++1y allows expression-statements.
2384 if (!Cxx1yLoc.isValid())
2385 Cxx1yLoc = S->getBeginLoc();
2386 return true;
2387 }
2388
2390 SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2391 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2392 }
2393 return false;
2394}
2395
2396/// Check the body for the given constexpr function declaration only contains
2397/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
2398///
2399/// \return true if the body is OK, false if we have found or diagnosed a
2400/// problem.
2401static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
2402 Stmt *Body,
2405
2406 if (isa<CXXTryStmt>(Body)) {
2407 // C++11 [dcl.constexpr]p3:
2408 // The definition of a constexpr function shall satisfy the following
2409 // constraints: [...]
2410 // - its function-body shall be = delete, = default, or a
2411 // compound-statement
2412 //
2413 // C++11 [dcl.constexpr]p4:
2414 // In the definition of a constexpr constructor, [...]
2415 // - its function-body shall not be a function-try-block;
2416 //
2417 // This restriction is lifted in C++2a, as long as inner statements also
2418 // apply the general constexpr rules.
2419 switch (Kind) {
2421 if (!SemaRef.getLangOpts().CPlusPlus20)
2422 return false;
2423 break;
2424
2426 SemaRef.DiagCompat(Body->getBeginLoc(),
2427 diag_compat::constexpr_function_try_block)
2429 break;
2430 }
2431 }
2432
2433 // - its function-body shall be [...] a compound-statement that contains only
2434 // [... list of cases ...]
2435 //
2436 // Note that walking the children here is enough to properly check for
2437 // CompoundStmt and CXXTryStmt body.
2438 SourceLocation Cxx1yLoc, Cxx2aLoc, Cxx2bLoc;
2439 for (Stmt *SubStmt : Body->children()) {
2440 if (SubStmt &&
2441 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2442 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2443 return false;
2444 }
2445
2447 // If this is only valid as an extension, report that we don't satisfy the
2448 // constraints of the current language.
2449 if ((Cxx2bLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus23) ||
2450 (Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) ||
2451 (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
2452 return false;
2453 } else if (Cxx2bLoc.isValid()) {
2454 SemaRef.DiagCompat(Cxx2bLoc, diag_compat::cxx23_constexpr_body_invalid_stmt)
2456 } else if (Cxx2aLoc.isValid()) {
2457 SemaRef.DiagCompat(Cxx2aLoc, diag_compat::cxx20_constexpr_body_invalid_stmt)
2459 } else if (Cxx1yLoc.isValid()) {
2460 SemaRef.DiagCompat(Cxx1yLoc, diag_compat::cxx14_constexpr_body_invalid_stmt)
2462 }
2463
2465 = dyn_cast<CXXConstructorDecl>(Dcl)) {
2466 const CXXRecordDecl *RD = Constructor->getParent();
2467 // DR1359:
2468 // - every non-variant non-static data member and base class sub-object
2469 // shall be initialized;
2470 // DR1460:
2471 // - if the class is a union having variant members, exactly one of them
2472 // shall be initialized;
2473 if (RD->isUnion()) {
2474 if (Constructor->getNumCtorInitializers() == 0 &&
2475 RD->hasVariantMembers()) {
2477 SemaRef.DiagCompat(Dcl->getLocation(),
2478 diag_compat::constexpr_union_ctor_no_init);
2479 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2480 return false;
2481 }
2482 }
2483 } else if (!Constructor->isDependentContext() &&
2484 !Constructor->isDelegatingConstructor()) {
2485 // Skip detailed checking if we have enough initializers, and we would
2486 // allow at most one initializer per member.
2487 bool AnyAnonStructUnionMembers = false;
2488 unsigned Fields = 0;
2490 E = RD->field_end(); I != E; ++I, ++Fields) {
2491 if (I->isAnonymousStructOrUnion()) {
2492 AnyAnonStructUnionMembers = true;
2493 break;
2494 }
2495 }
2496 // DR1460:
2497 // - if the class is a union-like class, but is not a union, for each of
2498 // its anonymous union members having variant members, exactly one of
2499 // them shall be initialized;
2500 if (AnyAnonStructUnionMembers ||
2501 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2502 // Check initialization of non-static data members. Base classes are
2503 // always initialized so do not need to be checked. Dependent bases
2504 // might not have initializers in the member initializer list.
2506 for (const auto *I: Constructor->inits()) {
2507 if (FieldDecl *FD = I->getMember())
2508 Inits.insert(FD);
2509 else if (IndirectFieldDecl *ID = I->getIndirectMember())
2510 Inits.insert(ID->chain_begin(), ID->chain_end());
2511 }
2512
2513 bool Diagnosed = false;
2514 for (auto *I : RD->fields())
2515 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2516 Kind))
2517 return false;
2518 }
2519 }
2520 } else {
2521 if (ReturnStmts.empty()) {
2522 switch (Kind) {
2524 if (!CheckConstexprMissingReturn(SemaRef, Dcl))
2525 return false;
2526 break;
2527
2529 // The formal requirements don't include this rule in C++14, even
2530 // though the "must be able to produce a constant expression" rules
2531 // still imply it in some cases.
2532 if (!SemaRef.getLangOpts().CPlusPlus14)
2533 return false;
2534 break;
2535 }
2536 } else if (ReturnStmts.size() > 1) {
2537 switch (Kind) {
2539 SemaRef.DiagCompat(ReturnStmts.back(),
2540 diag_compat::constexpr_body_multiple_return);
2541 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2542 SemaRef.Diag(ReturnStmts[I],
2543 diag::note_constexpr_body_previous_return);
2544 break;
2545
2547 if (!SemaRef.getLangOpts().CPlusPlus14)
2548 return false;
2549 break;
2550 }
2551 }
2552 }
2553
2554 // C++11 [dcl.constexpr]p5:
2555 // if no function argument values exist such that the function invocation
2556 // substitution would produce a constant expression, the program is
2557 // ill-formed; no diagnostic required.
2558 // C++11 [dcl.constexpr]p3:
2559 // - every constructor call and implicit conversion used in initializing the
2560 // return value shall be one of those allowed in a constant expression.
2561 // C++11 [dcl.constexpr]p4:
2562 // - every constructor involved in initializing non-static data members and
2563 // base class sub-objects shall be a constexpr constructor.
2564 //
2565 // Note that this rule is distinct from the "requirements for a constexpr
2566 // function", so is not checked in CheckValid mode. Because the check for
2567 // constexpr potential is expensive, skip the check if the diagnostic is
2568 // disabled, the function is declared in a system header, or we're in C++23
2569 // or later mode (see https://wg21.link/P2448).
2570 bool SkipCheck =
2571 !SemaRef.getLangOpts().CheckConstexprFunctionBodies ||
2572 SemaRef.getSourceManager().isInSystemHeader(Dcl->getLocation()) ||
2573 SemaRef.getDiagnostics().isIgnored(
2574 diag::ext_constexpr_function_never_constant_expr, Dcl->getLocation());
2576 if (Kind == Sema::CheckConstexprKind::Diagnose && !SkipCheck &&
2577 !Expr::isPotentialConstantExpr(Dcl, Diags)) {
2578 SemaRef.Diag(Dcl->getLocation(),
2579 diag::ext_constexpr_function_never_constant_expr)
2580 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval()
2581 << Dcl->getNameInfo().getSourceRange();
2582 for (const auto &Diag : Diags)
2583 SemaRef.Diag(Diag.first, Diag.second);
2584 // Don't return false here: we allow this for compatibility in
2585 // system headers.
2586 }
2587
2588 return true;
2589}
2590
2592 const FunctionDecl *Dcl) {
2593 bool IsVoidOrDependentType = Dcl->getReturnType()->isVoidType() ||
2595 // Skip emitting a missing return error diagnostic for non-void functions
2596 // since C++23 no longer mandates constexpr functions to yield constant
2597 // expressions.
2598 if (SemaRef.getLangOpts().CPlusPlus23 && !IsVoidOrDependentType)
2599 return true;
2600
2601 // C++14 doesn't require constexpr functions to contain a 'return'
2602 // statement. We still do, unless the return type might be void, because
2603 // otherwise if there's no return statement, the function cannot
2604 // be used in a core constant expression.
2605 bool OK = SemaRef.getLangOpts().CPlusPlus14 && IsVoidOrDependentType;
2606 SemaRef.Diag(Dcl->getLocation(),
2607 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2608 : diag::err_constexpr_body_no_return)
2609 << Dcl->isConsteval();
2610 return OK;
2611}
2612
2614 FunctionDecl *FD, const sema::FunctionScopeInfo *FSI) {
2616 return true;
2620 auto it = UndefinedButUsed.find(FD->getCanonicalDecl());
2621 if (it != UndefinedButUsed.end()) {
2622 Diag(it->second, diag::err_immediate_function_used_before_definition)
2623 << it->first;
2624 Diag(FD->getLocation(), diag::note_defined_here) << FD;
2625 if (FD->isImmediateFunction() && !FD->isConsteval())
2627 return false;
2628 }
2629 }
2630 return true;
2631}
2632
2634 assert(FD->isImmediateEscalating() && !FD->isConsteval() &&
2635 "expected an immediate function");
2636 assert(FD->hasBody() && "expected the function to have a body");
2637 struct ImmediateEscalatingExpressionsVisitor : DynamicRecursiveASTVisitor {
2638 Sema &SemaRef;
2639
2640 const FunctionDecl *ImmediateFn;
2641 bool ImmediateFnIsConstructor;
2642 CXXConstructorDecl *CurrentConstructor = nullptr;
2643 CXXCtorInitializer *CurrentInit = nullptr;
2644
2645 ImmediateEscalatingExpressionsVisitor(Sema &SemaRef, FunctionDecl *FD)
2646 : SemaRef(SemaRef), ImmediateFn(FD),
2647 ImmediateFnIsConstructor(isa<CXXConstructorDecl>(FD)) {
2648 ShouldVisitImplicitCode = true;
2649 ShouldVisitLambdaBody = false;
2650 }
2651
2652 void Diag(const Expr *E, const FunctionDecl *Fn, bool IsCall) {
2653 SourceLocation Loc = E->getBeginLoc();
2654 SourceRange Range = E->getSourceRange();
2655 if (CurrentConstructor && CurrentInit) {
2656 Loc = CurrentConstructor->getLocation();
2657 Range = CurrentInit->isWritten() ? CurrentInit->getSourceRange()
2658 : SourceRange();
2659 }
2660
2661 FieldDecl* InitializedField = CurrentInit ? CurrentInit->getAnyMember() : nullptr;
2662
2663 SemaRef.Diag(Loc, diag::note_immediate_function_reason)
2664 << ImmediateFn << Fn << Fn->isConsteval() << IsCall
2665 << isa<CXXConstructorDecl>(Fn) << ImmediateFnIsConstructor
2666 << (InitializedField != nullptr)
2667 << (CurrentInit && !CurrentInit->isWritten())
2668 << InitializedField << Range;
2669 }
2670 bool TraverseCallExpr(CallExpr *E) override {
2671 if (const auto *DR =
2672 dyn_cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit());
2673 DR && DR->isImmediateEscalating()) {
2674 Diag(E, E->getDirectCallee(), /*IsCall=*/true);
2675 return false;
2676 }
2677
2678 for (Expr *A : E->arguments())
2679 if (!TraverseStmt(A))
2680 return false;
2681
2682 return true;
2683 }
2684
2685 bool VisitDeclRefExpr(DeclRefExpr *E) override {
2686 if (const auto *ReferencedFn = dyn_cast<FunctionDecl>(E->getDecl());
2687 ReferencedFn && E->isImmediateEscalating()) {
2688 Diag(E, ReferencedFn, /*IsCall=*/false);
2689 return false;
2690 }
2691
2692 return true;
2693 }
2694
2695 bool VisitCXXConstructExpr(CXXConstructExpr *E) override {
2697 if (E->isImmediateEscalating()) {
2698 Diag(E, D, /*IsCall=*/true);
2699 return false;
2700 }
2701 return true;
2702 }
2703
2704 bool TraverseConstructorInitializer(CXXCtorInitializer *Init) override {
2705 llvm::SaveAndRestore RAII(CurrentInit, Init);
2707 }
2708
2709 bool TraverseCXXConstructorDecl(CXXConstructorDecl *Ctr) override {
2710 llvm::SaveAndRestore RAII(CurrentConstructor, Ctr);
2711 return DynamicRecursiveASTVisitor::TraverseCXXConstructorDecl(Ctr);
2712 }
2713
2714 bool TraverseType(QualType T, bool TraverseQualifier) override {
2715 return true;
2716 }
2717 bool VisitBlockExpr(BlockExpr *T) override { return true; }
2718
2719 } Visitor(*this, FD);
2720 Visitor.TraverseDecl(FD);
2721}
2722
2724 assert(getLangOpts().CPlusPlus && "No class names in C!");
2725
2726 if (SS && SS->isInvalid())
2727 return nullptr;
2728
2729 if (SS && SS->isNotEmpty()) {
2730 DeclContext *DC = computeDeclContext(*SS, true);
2731 return dyn_cast_or_null<CXXRecordDecl>(DC);
2732 }
2733
2734 return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2735}
2736
2738 const CXXScopeSpec *SS) {
2739 CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2740 return CurDecl && &II == CurDecl->getIdentifier();
2741}
2742
2744 assert(getLangOpts().CPlusPlus && "No class names in C!");
2745
2746 if (!getLangOpts().SpellChecking)
2747 return false;
2748
2749 CXXRecordDecl *CurDecl;
2750 if (SS && SS->isSet() && !SS->isInvalid()) {
2751 DeclContext *DC = computeDeclContext(*SS, true);
2752 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2753 } else
2754 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2755
2756 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2757 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2758 < II->getLength()) {
2759 II = CurDecl->getIdentifier();
2760 return true;
2761 }
2762
2763 return false;
2764}
2765
2767 SourceRange SpecifierRange,
2768 bool Virtual, AccessSpecifier Access,
2769 TypeSourceInfo *TInfo,
2770 SourceLocation EllipsisLoc) {
2771 QualType BaseType = TInfo->getType();
2772 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2773 if (BaseType->containsErrors()) {
2774 // Already emitted a diagnostic when parsing the error type.
2775 return nullptr;
2776 }
2777
2778 if (EllipsisLoc.isValid() && !BaseType->containsUnexpandedParameterPack()) {
2779 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2780 << TInfo->getTypeLoc().getSourceRange();
2781 EllipsisLoc = SourceLocation();
2782 }
2783
2784 auto *BaseDecl =
2785 dyn_cast_if_present<CXXRecordDecl>(computeDeclContext(BaseType));
2786 // C++ [class.derived.general]p2:
2787 // A class-or-decltype shall denote a (possibly cv-qualified) class type
2788 // that is not an incompletely defined class; any cv-qualifiers are
2789 // ignored.
2790 if (BaseDecl) {
2791 // C++ [class.union.general]p4:
2792 // [...] A union shall not be used as a base class.
2793 if (BaseDecl->isUnion()) {
2794 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2795 return nullptr;
2796 }
2797
2798 if (BaseType.hasQualifiers()) {
2799 std::string Quals =
2800 BaseType.getQualifiers().getAsString(Context.getPrintingPolicy());
2801 Diag(BaseLoc, diag::warn_qual_base_type)
2802 << Quals << llvm::count(Quals, ' ') + 1 << BaseType;
2803 Diag(BaseLoc, diag::note_base_class_specified_here) << BaseType;
2804 }
2805
2806 // For the MS ABI, propagate DLL attributes to base class templates.
2807 if (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
2808 Context.getTargetInfo().getTriple().isPS()) {
2809 if (Attr *ClassAttr = getDLLAttr(Class)) {
2810 if (auto *BaseSpec =
2811 dyn_cast<ClassTemplateSpecializationDecl>(BaseDecl)) {
2812 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseSpec,
2813 BaseLoc);
2814 }
2815 }
2816 }
2817
2818 if (RequireCompleteType(BaseLoc, BaseType, diag::err_incomplete_base_class,
2819 SpecifierRange)) {
2820 Class->setInvalidDecl();
2821 return nullptr;
2822 }
2823
2824 BaseDecl = BaseDecl->getDefinition();
2825 assert(BaseDecl && "Base type is not incomplete, but has no definition");
2826
2827 // Microsoft docs say:
2828 // "If a base-class has a code_seg attribute, derived classes must have the
2829 // same attribute."
2830 const auto *BaseCSA = BaseDecl->getAttr<CodeSegAttr>();
2831 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2832 if ((DerivedCSA || BaseCSA) &&
2833 (!BaseCSA || !DerivedCSA ||
2834 BaseCSA->getName() != DerivedCSA->getName())) {
2835 Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2836 Diag(BaseDecl->getLocation(), diag::note_base_class_specified_here)
2837 << BaseDecl;
2838 return nullptr;
2839 }
2840
2841 // A class which contains a flexible array member is not suitable for use as
2842 // a base class:
2843 // - If the layout determines that a base comes before another base,
2844 // the flexible array member would index into the subsequent base.
2845 // - If the layout determines that base comes before the derived class,
2846 // the flexible array member would index into the derived class.
2847 if (BaseDecl->hasFlexibleArrayMember()) {
2848 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2849 << BaseDecl->getDeclName();
2850 return nullptr;
2851 }
2852
2853 // C++ [class]p3:
2854 // If a class is marked final and it appears as a base-type-specifier in
2855 // base-clause, the program is ill-formed.
2856 if (FinalAttr *FA = BaseDecl->getAttr<FinalAttr>()) {
2857 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2858 << BaseDecl->getDeclName() << FA->isSpelledAsSealed();
2859 Diag(BaseDecl->getLocation(), diag::note_entity_declared_at)
2860 << BaseDecl->getDeclName() << FA->getRange();
2861 return nullptr;
2862 }
2863
2864 // If the base class is invalid the derived class is as well.
2865 if (BaseDecl->isInvalidDecl())
2866 Class->setInvalidDecl();
2867 } else if (BaseType->isDependentType()) {
2868 // Make sure that we don't make an ill-formed AST where the type of the
2869 // Class is non-dependent and its attached base class specifier is an
2870 // dependent type, which violates invariants in many clang code paths (e.g.
2871 // constexpr evaluator). If this case happens (in errory-recovery mode), we
2872 // explicitly mark the Class decl invalid. The diagnostic was already
2873 // emitted.
2874 if (!Class->isDependentContext())
2875 Class->setInvalidDecl();
2876 } else {
2877 // The base class is some non-dependent non-class type.
2878 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2879 return nullptr;
2880 }
2881
2882 // In HLSL, unspecified class access is public rather than private.
2883 if (getLangOpts().HLSL && Class->getTagKind() == TagTypeKind::Class &&
2884 Access == AS_none)
2885 Access = AS_public;
2886
2887 // Create the base specifier.
2888 return new (Context) CXXBaseSpecifier(
2889 SpecifierRange, Virtual, Class->getTagKind() == TagTypeKind::Class,
2890 Access, TInfo, EllipsisLoc);
2891}
2892
2894 const ParsedAttributesView &Attributes,
2895 bool Virtual, AccessSpecifier Access,
2896 ParsedType basetype, SourceLocation BaseLoc,
2897 SourceLocation EllipsisLoc) {
2898 if (!classdecl)
2899 return true;
2900
2901 AdjustDeclIfTemplate(classdecl);
2902 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2903 if (!Class)
2904 return true;
2905
2906 // We haven't yet attached the base specifiers.
2907 Class->setIsParsingBaseSpecifiers();
2908
2909 // We do not support any C++11 attributes on base-specifiers yet.
2910 // Diagnose any attributes we see.
2911 for (const ParsedAttr &AL : Attributes) {
2912 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2913 continue;
2914 if (AL.getKind() == ParsedAttr::UnknownAttribute)
2916 else
2917 Diag(AL.getLoc(), diag::err_base_specifier_attribute)
2918 << AL << AL.isRegularKeywordAttribute() << AL.getRange();
2919 }
2920
2921 TypeSourceInfo *TInfo = nullptr;
2922 GetTypeFromParser(basetype, &TInfo);
2923
2924 if (EllipsisLoc.isInvalid() &&
2925 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2927 return true;
2928
2929 // C++ [class.union.general]p4:
2930 // [...] A union shall not have base classes.
2931 if (Class->isUnion()) {
2932 Diag(Class->getLocation(), diag::err_base_clause_on_union)
2933 << SpecifierRange;
2934 return true;
2935 }
2936
2937 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2938 Virtual, Access, TInfo,
2939 EllipsisLoc))
2940 return BaseSpec;
2941
2942 Class->setInvalidDecl();
2943 return true;
2944}
2945
2946/// Use small set to collect indirect bases. As this is only used
2947/// locally, there's no need to abstract the small size parameter.
2949
2950/// Recursively add the bases of Type. Don't add Type itself.
2951static void
2953 const QualType &Type)
2954{
2955 // Even though the incoming type is a base, it might not be
2956 // a class -- it could be a template parm, for instance.
2957 if (const auto *Decl = Type->getAsCXXRecordDecl()) {
2958 // Iterate over its bases.
2959 for (const auto &BaseSpec : Decl->bases()) {
2960 QualType Base = Context.getCanonicalType(BaseSpec.getType())
2961 .getUnqualifiedType();
2962 if (Set.insert(Base).second)
2963 // If we've not already seen it, recurse.
2964 NoteIndirectBases(Context, Set, Base);
2965 }
2966 }
2967}
2968
2971 if (Bases.empty())
2972 return false;
2973
2974 // Used to keep track of which base types we have already seen, so
2975 // that we can properly diagnose redundant direct base types. Note
2976 // that the key is always the unqualified canonical type of the base
2977 // class.
2978 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2979
2980 // Used to track indirect bases so we can see if a direct base is
2981 // ambiguous.
2982 IndirectBaseSet IndirectBaseTypes;
2983
2984 // Copy non-redundant base specifiers into permanent storage.
2985 unsigned NumGoodBases = 0;
2986 bool Invalid = false;
2987 for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2988 QualType NewBaseType
2989 = Context.getCanonicalType(Bases[idx]->getType());
2990 NewBaseType = NewBaseType.getLocalUnqualifiedType();
2991
2992 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2993 if (KnownBase) {
2994 // C++ [class.mi]p3:
2995 // A class shall not be specified as a direct base class of a
2996 // derived class more than once.
2997 Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2998 << KnownBase->getType() << Bases[idx]->getSourceRange();
2999
3000 // Delete the duplicate base class specifier; we're going to
3001 // overwrite its pointer later.
3002 Context.Deallocate(Bases[idx]);
3003
3004 Invalid = true;
3005 } else {
3006 // Okay, add this new base class.
3007 KnownBase = Bases[idx];
3008 Bases[NumGoodBases++] = Bases[idx];
3009
3010 if (NewBaseType->isDependentType())
3011 continue;
3012 // Note this base's direct & indirect bases, if there could be ambiguity.
3013 if (Bases.size() > 1)
3014 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
3015
3016 if (const auto *RD = NewBaseType->getAsCXXRecordDecl()) {
3017 if (Class->isInterface() &&
3018 (!RD->isInterfaceLike() ||
3019 KnownBase->getAccessSpecifier() != AS_public)) {
3020 // The Microsoft extension __interface does not permit bases that
3021 // are not themselves public interfaces.
3022 Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
3023 << getRecordDiagFromTagKind(RD->getTagKind()) << RD
3024 << RD->getSourceRange();
3025 Invalid = true;
3026 }
3027 if (RD->hasAttr<WeakAttr>())
3028 Class->addAttr(WeakAttr::CreateImplicit(Context));
3029 }
3030 }
3031 }
3032
3033 // Attach the remaining base class specifiers to the derived class.
3034 Class->setBases(Bases.data(), NumGoodBases);
3035
3036 // Check that the only base classes that are duplicate are virtual.
3037 for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
3038 // Check whether this direct base is inaccessible due to ambiguity.
3039 QualType BaseType = Bases[idx]->getType();
3040
3041 // Skip all dependent types in templates being used as base specifiers.
3042 // Checks below assume that the base specifier is a CXXRecord.
3043 if (BaseType->isDependentType())
3044 continue;
3045
3046 CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
3047 .getUnqualifiedType();
3048
3049 if (IndirectBaseTypes.count(CanonicalBase)) {
3050 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3051 /*DetectVirtual=*/true);
3052 bool found
3053 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
3054 assert(found);
3055 (void)found;
3056
3057 if (Paths.isAmbiguous(CanonicalBase))
3058 Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
3059 << BaseType << getAmbiguousPathsDisplayString(Paths)
3060 << Bases[idx]->getSourceRange();
3061 else
3062 assert(Bases[idx]->isVirtual());
3063 }
3064
3065 // Delete the base class specifier, since its data has been copied
3066 // into the CXXRecordDecl.
3067 Context.Deallocate(Bases[idx]);
3068 }
3069
3070 return Invalid;
3071}
3072
3075 if (!ClassDecl || Bases.empty())
3076 return;
3077
3078 AdjustDeclIfTemplate(ClassDecl);
3079 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
3080}
3081
3083 CXXRecordDecl *Base, CXXBasePaths &Paths) {
3084 if (!getLangOpts().CPlusPlus)
3085 return false;
3086
3087 if (!Base || !Derived)
3088 return false;
3089
3090 // If either the base or the derived type is invalid, don't try to
3091 // check whether one is derived from the other.
3092 if (Base->isInvalidDecl() || Derived->isInvalidDecl())
3093 return false;
3094
3095 // FIXME: In a modules build, do we need the entire path to be visible for us
3096 // to be able to use the inheritance relationship?
3097 if (!isCompleteType(Loc, Context.getCanonicalTagType(Derived)) &&
3098 !Derived->isBeingDefined())
3099 return false;
3100
3101 return Derived->isDerivedFrom(Base, Paths);
3102}
3103
3106 CXXBasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/false,
3107 /*DetectVirtual=*/false);
3108 return IsDerivedFrom(Loc, Derived, Base, Paths);
3109}
3110
3112 CXXBasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/false,
3113 /*DetectVirtual=*/false);
3114 return IsDerivedFrom(Loc, Derived->getAsCXXRecordDecl(),
3115 Base->getAsCXXRecordDecl(), Paths);
3116}
3117
3119 CXXBasePaths &Paths) {
3120 return IsDerivedFrom(Loc, Derived->getAsCXXRecordDecl(),
3121 Base->getAsCXXRecordDecl(), Paths);
3122}
3123
3124static void BuildBasePathArray(const CXXBasePath &Path,
3125 CXXCastPath &BasePathArray) {
3126 // We first go backward and check if we have a virtual base.
3127 // FIXME: It would be better if CXXBasePath had the base specifier for
3128 // the nearest virtual base.
3129 unsigned Start = 0;
3130 for (unsigned I = Path.size(); I != 0; --I) {
3131 if (Path[I - 1].Base->isVirtual()) {
3132 Start = I - 1;
3133 break;
3134 }
3135 }
3136
3137 // Now add all bases.
3138 for (unsigned I = Start, E = Path.size(); I != E; ++I)
3139 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
3140}
3141
3142
3144 CXXCastPath &BasePathArray) {
3145 assert(BasePathArray.empty() && "Base path array must be empty!");
3146 assert(Paths.isRecordingPaths() && "Must record paths!");
3147 return ::BuildBasePathArray(Paths.front(), BasePathArray);
3148}
3149
3150bool
3152 unsigned InaccessibleBaseID,
3153 unsigned AmbiguousBaseConvID,
3154 SourceLocation Loc, SourceRange Range,
3155 DeclarationName Name,
3156 CXXCastPath *BasePath,
3157 bool IgnoreAccess) {
3158 // First, determine whether the path from Derived to Base is
3159 // ambiguous. This is slightly more expensive than checking whether
3160 // the Derived to Base conversion exists, because here we need to
3161 // explore multiple paths to determine if there is an ambiguity.
3162 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3163 /*DetectVirtual=*/false);
3164 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
3165 if (!DerivationOkay)
3166 return true;
3167
3168 const CXXBasePath *Path = nullptr;
3169 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
3170 Path = &Paths.front();
3171
3172 // For MSVC compatibility, check if Derived directly inherits from Base. Clang
3173 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
3174 // user to access such bases.
3175 if (!Path && getLangOpts().MSVCCompat) {
3176 for (const CXXBasePath &PossiblePath : Paths) {
3177 if (PossiblePath.size() == 1) {
3178 Path = &PossiblePath;
3179 if (AmbiguousBaseConvID)
3180 Diag(Loc, diag::ext_ms_ambiguous_direct_base)
3181 << Base << Derived << Range;
3182 break;
3183 }
3184 }
3185 }
3186
3187 if (Path) {
3188 if (!IgnoreAccess) {
3189 // Check that the base class can be accessed.
3190 switch (
3191 CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
3192 case AR_inaccessible:
3193 return true;
3194 case AR_accessible:
3195 case AR_dependent:
3196 case AR_delayed:
3197 break;
3198 }
3199 }
3200
3201 // Build a base path if necessary.
3202 if (BasePath)
3203 ::BuildBasePathArray(*Path, *BasePath);
3204 return false;
3205 }
3206
3207 if (AmbiguousBaseConvID) {
3208 // We know that the derived-to-base conversion is ambiguous, and
3209 // we're going to produce a diagnostic. Perform the derived-to-base
3210 // search just one more time to compute all of the possible paths so
3211 // that we can print them out. This is more expensive than any of
3212 // the previous derived-to-base checks we've done, but at this point
3213 // performance isn't as much of an issue.
3214 Paths.clear();
3215 Paths.setRecordingPaths(true);
3216 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
3217 assert(StillOkay && "Can only be used with a derived-to-base conversion");
3218 (void)StillOkay;
3219
3220 // Build up a textual representation of the ambiguous paths, e.g.,
3221 // D -> B -> A, that will be used to illustrate the ambiguous
3222 // conversions in the diagnostic. We only print one of the paths
3223 // to each base class subobject.
3224 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3225
3226 Diag(Loc, AmbiguousBaseConvID)
3227 << Derived << Base << PathDisplayStr << Range << Name;
3228 }
3229 return true;
3230}
3231
3232bool
3234 SourceLocation Loc, SourceRange Range,
3235 CXXCastPath *BasePath,
3236 bool IgnoreAccess) {
3238 Derived, Base, diag::err_upcast_to_inaccessible_base,
3239 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
3240 BasePath, IgnoreAccess);
3241}
3242
3244 std::string PathDisplayStr;
3245 std::set<unsigned> DisplayedPaths;
3246 for (const CXXBasePath &Path : Paths) {
3247 if (DisplayedPaths.insert(Path.back().SubobjectNumber).second) {
3248 // We haven't displayed a path to this particular base
3249 // class subobject yet.
3250 PathDisplayStr += "\n ";
3251 PathDisplayStr += QualType(Context.getCanonicalTagType(Paths.getOrigin()))
3252 .getAsString();
3253 for (const CXXBasePathElement &Element : Path)
3254 PathDisplayStr += " -> " + Element.Base->getType().getAsString();
3255 }
3256 }
3257
3258 return PathDisplayStr;
3259}
3260
3261//===----------------------------------------------------------------------===//
3262// C++ class member Handling
3263//===----------------------------------------------------------------------===//
3264
3266 SourceLocation ColonLoc,
3267 const ParsedAttributesView &Attrs) {
3268 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
3270 ASLoc, ColonLoc);
3271 CurContext->addHiddenDecl(ASDecl);
3272 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
3273}
3274
3276 if (D->isInvalidDecl())
3277 return;
3278
3279 // We only care about "override" and "final" declarations.
3280 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
3281 return;
3282
3283 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3284
3285 // We can't check dependent instance methods.
3286 if (MD && MD->isInstance() &&
3287 (MD->getParent()->hasAnyDependentBases() ||
3288 MD->getType()->isDependentType()))
3289 return;
3290
3291 if (MD && !MD->isVirtual()) {
3292 // If we have a non-virtual method, check if it hides a virtual method.
3293 // (In that case, it's most likely the method has the wrong type.)
3294 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3295 FindHiddenVirtualMethods(MD, OverloadedMethods);
3296
3297 if (!OverloadedMethods.empty()) {
3298 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3299 Diag(OA->getLocation(),
3300 diag::override_keyword_hides_virtual_member_function)
3301 << "override" << (OverloadedMethods.size() > 1);
3302 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3303 Diag(FA->getLocation(),
3304 diag::override_keyword_hides_virtual_member_function)
3305 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3306 << (OverloadedMethods.size() > 1);
3307 }
3308 NoteHiddenVirtualMethods(MD, OverloadedMethods);
3309 MD->setInvalidDecl();
3310 return;
3311 }
3312 // Fall through into the general case diagnostic.
3313 // FIXME: We might want to attempt typo correction here.
3314 }
3315
3316 if (!MD || !MD->isVirtual()) {
3317 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3318 Diag(OA->getLocation(),
3319 diag::override_keyword_only_allowed_on_virtual_member_functions)
3320 << "override" << FixItHint::CreateRemoval(OA->getLocation());
3321 D->dropAttr<OverrideAttr>();
3322 }
3323 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3324 Diag(FA->getLocation(),
3325 diag::override_keyword_only_allowed_on_virtual_member_functions)
3326 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3327 << FixItHint::CreateRemoval(FA->getLocation());
3328 D->dropAttr<FinalAttr>();
3329 }
3330 return;
3331 }
3332
3333 // C++11 [class.virtual]p5:
3334 // If a function is marked with the virt-specifier override and
3335 // does not override a member function of a base class, the program is
3336 // ill-formed.
3337 bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
3338 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
3339 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
3340 << MD->getDeclName();
3341}
3342
3344 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
3345 return;
3346 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3347 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
3348 return;
3349
3350 SourceLocation Loc = MD->getLocation();
3351 SourceLocation SpellingLoc = Loc;
3352 if (getSourceManager().isMacroArgExpansion(Loc))
3353 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
3354 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
3355 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
3356 return;
3357
3358 if (MD->size_overridden_methods() > 0) {
3359 auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) {
3360 unsigned DiagID =
3361 Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation())
3362 ? DiagInconsistent
3363 : DiagSuggest;
3364 Diag(MD->getLocation(), DiagID) << MD->getDeclName();
3365 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
3366 Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
3367 };
3368 if (isa<CXXDestructorDecl>(MD))
3369 EmitDiag(
3370 diag::warn_inconsistent_destructor_marked_not_override_overriding,
3371 diag::warn_suggest_destructor_marked_not_override_overriding);
3372 else
3373 EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding,
3374 diag::warn_suggest_function_marked_not_override_overriding);
3375 }
3376}
3377
3379 const CXXMethodDecl *Old) {
3380 FinalAttr *FA = Old->getAttr<FinalAttr>();
3381 if (!FA)
3382 return false;
3383
3384 Diag(New->getLocation(), diag::err_final_function_overridden)
3385 << New->getDeclName()
3386 << FA->isSpelledAsSealed();
3387 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3388 return true;
3389}
3390
3392 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
3393 // FIXME: Destruction of ObjC lifetime types has side-effects.
3394 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3395 return !RD->isCompleteDefinition() ||
3396 !RD->hasTrivialDefaultConstructor() ||
3397 !RD->hasTrivialDestructor();
3398 return false;
3399}
3400
3401void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
3402 DeclarationName FieldName,
3403 const CXXRecordDecl *RD,
3404 bool DeclIsField) {
3405 if (Diags.isIgnored(diag::warn_shadow_field, Loc))
3406 return;
3407
3408 // To record a shadowed field in a base
3409 std::map<CXXRecordDecl*, NamedDecl*> Bases;
3410 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
3411 CXXBasePath &Path) {
3412 const auto Base = Specifier->getType()->getAsCXXRecordDecl();
3413 // Record an ambiguous path directly
3414 if (Bases.find(Base) != Bases.end())
3415 return true;
3416 for (const auto Field : Base->lookup(FieldName)) {
3417 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
3418 Field->getAccess() != AS_private) {
3419 assert(Field->getAccess() != AS_none);
3420 assert(Bases.find(Base) == Bases.end());
3421 Bases[Base] = Field;
3422 return true;
3423 }
3424 }
3425 return false;
3426 };
3427
3428 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3429 /*DetectVirtual=*/true);
3430 if (!RD->lookupInBases(FieldShadowed, Paths))
3431 return;
3432
3433 for (const auto &P : Paths) {
3434 auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
3435 auto It = Bases.find(Base);
3436 // Skip duplicated bases
3437 if (It == Bases.end())
3438 continue;
3439 auto BaseField = It->second;
3440 assert(BaseField->getAccess() != AS_private);
3441 if (AS_none !=
3442 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
3443 Diag(Loc, diag::warn_shadow_field)
3444 << FieldName << RD << Base << DeclIsField;
3445 Diag(BaseField->getLocation(), diag::note_shadow_field);
3446 Bases.erase(It);
3447 }
3448 }
3449}
3450
3451template <typename AttrType>
3452inline static bool HasAttribute(const QualType &T) {
3453 if (const TagDecl *TD = T->getAsTagDecl())
3454 return TD->hasAttr<AttrType>();
3455 if (const TypedefType *TDT = T->getAs<TypedefType>())
3456 return TDT->getDecl()->hasAttr<AttrType>();
3457 return false;
3458}
3459
3460static bool IsUnusedPrivateField(const FieldDecl *FD) {
3461 if (FD->getAccess() == AS_private && FD->getDeclName()) {
3462 QualType FieldType = FD->getType();
3463 if (HasAttribute<WarnUnusedAttr>(FieldType))
3464 return true;
3465
3466 return !FD->isImplicit() && !FD->hasAttr<UnusedAttr>() &&
3467 !FD->getParent()->isDependentContext() &&
3468 !HasAttribute<UnusedAttr>(FieldType) &&
3470 }
3471 return false;
3472}
3473
3474NamedDecl *
3476 MultiTemplateParamsArg TemplateParameterLists,
3477 Expr *BitWidth, const VirtSpecifiers &VS,
3478 InClassInitStyle InitStyle) {
3479 const DeclSpec &DS = D.getDeclSpec();
3481 DeclarationName Name = NameInfo.getName();
3482 SourceLocation Loc = NameInfo.getLoc();
3483
3484 // For anonymous bitfields, the location should point to the type.
3485 if (Loc.isInvalid())
3486 Loc = D.getBeginLoc();
3487
3489 assert(!DS.isFriendSpecified());
3490
3491 bool isFunc = D.isDeclarationOfFunction();
3492 const ParsedAttr *MSPropertyAttr =
3494
3495 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
3496 // The Microsoft extension __interface only permits public member functions
3497 // and prohibits constructors, destructors, operators, non-public member
3498 // functions, static methods and data members.
3499 unsigned InvalidDecl;
3500 bool ShowDeclName = true;
3501 if (!isFunc &&
3502 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
3503 InvalidDecl = 0;
3504 else if (!isFunc)
3505 InvalidDecl = 1;
3506 else if (AS != AS_public)
3507 InvalidDecl = 2;
3509 InvalidDecl = 3;
3510 else switch (Name.getNameKind()) {
3512 InvalidDecl = 4;
3513 ShowDeclName = false;
3514 break;
3515
3517 InvalidDecl = 5;
3518 ShowDeclName = false;
3519 break;
3520
3523 InvalidDecl = 6;
3524 break;
3525
3526 default:
3527 InvalidDecl = 0;
3528 break;
3529 }
3530
3531 if (InvalidDecl) {
3532 if (ShowDeclName)
3533 Diag(Loc, diag::err_invalid_member_in_interface)
3534 << (InvalidDecl-1) << Name;
3535 else
3536 Diag(Loc, diag::err_invalid_member_in_interface)
3537 << (InvalidDecl-1) << "";
3538 return nullptr;
3539 }
3540 }
3541
3542 // HLSL prohibits user defined constructors and destructors.
3543 if (getLangOpts().HLSL) {
3544 switch (Name.getNameKind()) {
3547 Diag(Loc, diag::err_hlsl_cstor_dstor);
3548 return nullptr;
3549 default:
3550 break;
3551 }
3552 }
3553
3554 // C++ 9.2p6: A member shall not be declared to have automatic storage
3555 // duration (auto, register) or with the extern storage-class-specifier.
3556 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3557 // data members and cannot be applied to names declared const or static,
3558 // and cannot be applied to reference members.
3559 switch (DS.getStorageClassSpec()) {
3563 break;
3565 if (isFunc) {
3566 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3567
3568 // FIXME: It would be nicer if the keyword was ignored only for this
3569 // declarator. Otherwise we could get follow-up errors.
3571 }
3572 break;
3573 default:
3575 diag::err_storageclass_invalid_for_member);
3577 break;
3578 }
3579
3580 bool isInstField = (DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3582 !isFunc && TemplateParameterLists.empty();
3583
3584 if (DS.hasConstexprSpecifier() && isInstField) {
3586 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3587 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3588 if (InitStyle == ICIS_NoInit) {
3589 B << 0 << 0;
3591 B << FixItHint::CreateRemoval(ConstexprLoc);
3592 else {
3593 B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3595 const char *PrevSpec;
3596 unsigned DiagID;
3597 bool Failed = D.getMutableDeclSpec().SetTypeQual(
3598 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3599 (void)Failed;
3600 assert(!Failed && "Making a constexpr member const shouldn't fail");
3601 }
3602 } else {
3603 B << 1;
3604 const char *PrevSpec;
3605 unsigned DiagID;
3607 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3608 Context.getPrintingPolicy())) {
3610 "This is the only DeclSpec that should fail to be applied");
3611 B << 1;
3612 } else {
3613 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3614 isInstField = false;
3615 }
3616 }
3617 }
3618
3620 if (isInstField) {
3621 CXXScopeSpec &SS = D.getCXXScopeSpec();
3622
3623 // Data members must have identifiers for names.
3624 if (!Name.isIdentifier()) {
3625 Diag(Loc, diag::err_bad_variable_name)
3626 << Name;
3627 return nullptr;
3628 }
3629
3632 Diag(D.getIdentifierLoc(), diag::err_member_with_template_arguments)
3633 << II
3637 D.SetIdentifier(II, Loc);
3638 }
3639
3640 if (SS.isSet() && !SS.isInvalid()) {
3641 // The user provided a superfluous scope specifier inside a class
3642 // definition:
3643 //
3644 // class X {
3645 // int X::member;
3646 // };
3647 if (DeclContext *DC = computeDeclContext(SS, false)) {
3648 TemplateIdAnnotation *TemplateId =
3650 ? D.getName().TemplateId
3651 : nullptr;
3653 TemplateId,
3654 /*IsMemberSpecialization=*/false);
3655 } else {
3656 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3657 << Name << SS.getRange();
3658 }
3659 SS.clear();
3660 }
3661
3662 if (MSPropertyAttr) {
3664 BitWidth, InitStyle, AS, *MSPropertyAttr);
3665 if (!Member)
3666 return nullptr;
3667 isInstField = false;
3668 } else {
3670 BitWidth, InitStyle, AS);
3671 if (!Member)
3672 return nullptr;
3673 }
3674
3675 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3676 } else {
3677 Member = HandleDeclarator(S, D, TemplateParameterLists);
3678 if (!Member)
3679 return nullptr;
3680
3681 // Non-instance-fields can't have a bitfield.
3682 if (BitWidth) {
3683 if (Member->isInvalidDecl()) {
3684 // don't emit another diagnostic.
3686 // C++ 9.6p3: A bit-field shall not be a static member.
3687 // "static member 'A' cannot be a bit-field"
3688 Diag(Loc, diag::err_static_not_bitfield)
3689 << Name << BitWidth->getSourceRange();
3690 } else if (isa<TypedefDecl>(Member)) {
3691 // "typedef member 'x' cannot be a bit-field"
3692 Diag(Loc, diag::err_typedef_not_bitfield)
3693 << Name << BitWidth->getSourceRange();
3694 } else {
3695 // A function typedef ("typedef int f(); f a;").
3696 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3697 Diag(Loc, diag::err_not_integral_type_bitfield)
3698 << Name << cast<ValueDecl>(Member)->getType()
3699 << BitWidth->getSourceRange();
3700 }
3701
3702 BitWidth = nullptr;
3703 Member->setInvalidDecl();
3704 }
3705
3706 NamedDecl *NonTemplateMember = Member;
3707 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3708 NonTemplateMember = FunTmpl->getTemplatedDecl();
3709 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3710 NonTemplateMember = VarTmpl->getTemplatedDecl();
3711
3712 Member->setAccess(AS);
3713
3714 // If we have declared a member function template or static data member
3715 // template, set the access of the templated declaration as well.
3716 if (NonTemplateMember != Member)
3717 NonTemplateMember->setAccess(AS);
3718
3719 // C++ [temp.deduct.guide]p3:
3720 // A deduction guide [...] for a member class template [shall be
3721 // declared] with the same access [as the template].
3722 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3723 auto *TD = DG->getDeducedTemplate();
3724 // Access specifiers are only meaningful if both the template and the
3725 // deduction guide are from the same scope.
3726 if (AS != TD->getAccess() &&
3727 TD->getDeclContext()->getRedeclContext()->Equals(
3728 DG->getDeclContext()->getRedeclContext())) {
3729 Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3730 Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3731 << TD->getAccess();
3732 const AccessSpecDecl *LastAccessSpec = nullptr;
3733 for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3734 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3735 LastAccessSpec = AccessSpec;
3736 }
3737 assert(LastAccessSpec && "differing access with no access specifier");
3738 Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3739 << AS;
3740 }
3741 }
3742 }
3743
3744 if (VS.isOverrideSpecified())
3745 Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc()));
3746 if (VS.isFinalSpecified())
3747 Member->addAttr(FinalAttr::Create(Context, VS.getFinalLoc(),
3749 ? FinalAttr::Keyword_sealed
3750 : FinalAttr::Keyword_final));
3751
3752 if (VS.getLastLocation().isValid()) {
3753 // Update the end location of a method that has a virt-specifiers.
3754 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3755 MD->setRangeEnd(VS.getLastLocation());
3756 }
3757
3759
3760 assert((Name || isInstField) && "No identifier for non-field ?");
3761
3762 if (isInstField) {
3764 FieldCollector->Add(FD);
3765
3766 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation()) &&
3768 // Remember all explicit private FieldDecls that have a name, no side
3769 // effects and are not part of a dependent type declaration.
3770 UnusedPrivateFields.insert(FD);
3771 }
3772 }
3773
3774 return Member;
3775}
3776
3777namespace {
3778 class UninitializedFieldVisitor
3779 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3780 Sema &S;
3781 // List of Decls to generate a warning on. Also remove Decls that become
3782 // initialized.
3783 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3784 // List of base classes of the record. Classes are removed after their
3785 // initializers.
3786 llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3787 // Vector of decls to be removed from the Decl set prior to visiting the
3788 // nodes. These Decls may have been initialized in the prior initializer.
3790 // If non-null, add a note to the warning pointing back to the constructor.
3792 // Variables to hold state when processing an initializer list. When
3793 // InitList is true, special case initialization of FieldDecls matching
3794 // InitListFieldDecl.
3795 bool InitList;
3796 FieldDecl *InitListFieldDecl;
3797 llvm::SmallVector<unsigned, 4> InitFieldIndex;
3798
3799 public:
3801 UninitializedFieldVisitor(Sema &S,
3802 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3803 llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3804 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3805 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3806
3807 // Returns true if the use of ME is not an uninitialized use.
3808 bool IsInitListMemberExprInitialized(MemberExpr *ME,
3809 bool CheckReferenceOnly) {
3811 bool ReferenceField = false;
3812 while (ME) {
3813 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3814 if (!FD)
3815 return false;
3816 Fields.push_back(FD);
3817 if (FD->getType()->isReferenceType())
3818 ReferenceField = true;
3819 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3820 }
3821
3822 // Binding a reference to an uninitialized field is not an
3823 // uninitialized use.
3824 if (CheckReferenceOnly && !ReferenceField)
3825 return true;
3826
3827 // Discard the first field since it is the field decl that is being
3828 // initialized.
3829 auto UsedFields = llvm::drop_begin(llvm::reverse(Fields));
3830 auto UsedIter = UsedFields.begin();
3831 const auto UsedEnd = UsedFields.end();
3832
3833 for (const unsigned Orig : InitFieldIndex) {
3834 if (UsedIter == UsedEnd)
3835 break;
3836 const unsigned UsedIndex = (*UsedIter)->getFieldIndex();
3837 if (UsedIndex < Orig)
3838 return true;
3839 if (UsedIndex > Orig)
3840 break;
3841 ++UsedIter;
3842 }
3843
3844 return false;
3845 }
3846
3847 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3848 bool AddressOf) {
3850 return;
3851
3852 // FieldME is the inner-most MemberExpr that is not an anonymous struct
3853 // or union.
3854 MemberExpr *FieldME = ME;
3855
3856 bool AllPODFields = FieldME->getType().isPODType(S.Context);
3857
3858 Expr *Base = ME;
3859 while (MemberExpr *SubME =
3860 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3861
3862 if (isa<VarDecl>(SubME->getMemberDecl()))
3863 return;
3864
3865 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3866 if (!FD->isAnonymousStructOrUnion())
3867 FieldME = SubME;
3868
3869 if (!FieldME->getType().isPODType(S.Context))
3870 AllPODFields = false;
3871
3872 Base = SubME->getBase();
3873 }
3874
3875 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) {
3876 Visit(Base);
3877 return;
3878 }
3879
3880 if (AddressOf && AllPODFields)
3881 return;
3882
3883 ValueDecl* FoundVD = FieldME->getMemberDecl();
3884
3885 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3886 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3887 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3888 }
3889
3890 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3891 QualType T = BaseCast->getType();
3892 if (T->isPointerType() &&
3893 BaseClasses.count(T->getPointeeType())) {
3894 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3895 << T->getPointeeType() << FoundVD;
3896 }
3897 }
3898 }
3899
3900 if (!Decls.count(FoundVD))
3901 return;
3902
3903 const bool IsReference = FoundVD->getType()->isReferenceType();
3904
3905 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3906 // Special checking for initializer lists.
3907 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3908 return;
3909 }
3910 } else {
3911 // Prevent double warnings on use of unbounded references.
3912 if (CheckReferenceOnly && !IsReference)
3913 return;
3914 }
3915
3916 unsigned diag = IsReference
3917 ? diag::warn_reference_field_is_uninit
3918 : diag::warn_field_is_uninit;
3919 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3920 if (Constructor)
3921 S.Diag(Constructor->getLocation(),
3922 diag::note_uninit_in_this_constructor)
3923 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3924
3925 }
3926
3927 void HandleValue(Expr *E, bool AddressOf) {
3928 E = E->IgnoreParens();
3929
3930 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3931 HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3932 AddressOf /*AddressOf*/);
3933 return;
3934 }
3935
3936 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3937 Visit(CO->getCond());
3938 HandleValue(CO->getTrueExpr(), AddressOf);
3939 HandleValue(CO->getFalseExpr(), AddressOf);
3940 return;
3941 }
3942
3943 if (BinaryConditionalOperator *BCO =
3944 dyn_cast<BinaryConditionalOperator>(E)) {
3945 Visit(BCO->getCond());
3946 HandleValue(BCO->getFalseExpr(), AddressOf);
3947 return;
3948 }
3949
3950 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3951 HandleValue(OVE->getSourceExpr(), AddressOf);
3952 return;
3953 }
3954
3955 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3956 switch (BO->getOpcode()) {
3957 default:
3958 break;
3959 case(BO_PtrMemD):
3960 case(BO_PtrMemI):
3961 HandleValue(BO->getLHS(), AddressOf);
3962 Visit(BO->getRHS());
3963 return;
3964 case(BO_Comma):
3965 Visit(BO->getLHS());
3966 HandleValue(BO->getRHS(), AddressOf);
3967 return;
3968 }
3969 }
3970
3971 Visit(E);
3972 }
3973
3974 void CheckInitListExpr(InitListExpr *ILE) {
3975 InitFieldIndex.push_back(0);
3976 for (auto *Child : ILE->children()) {
3977 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3978 CheckInitListExpr(SubList);
3979 } else {
3980 Visit(Child);
3981 }
3982 ++InitFieldIndex.back();
3983 }
3984 InitFieldIndex.pop_back();
3985 }
3986
3987 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3988 FieldDecl *Field, const Type *BaseClass) {
3989 // Remove Decls that may have been initialized in the previous
3990 // initializer.
3991 for (ValueDecl* VD : DeclsToRemove)
3992 Decls.erase(VD);
3993 DeclsToRemove.clear();
3994
3995 Constructor = FieldConstructor;
3996 InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3997
3998 if (ILE && Field) {
3999 InitList = true;
4000 InitListFieldDecl = Field;
4001 InitFieldIndex.clear();
4002 CheckInitListExpr(ILE);
4003 } else {
4004 InitList = false;
4005 Visit(E);
4006 }
4007
4008 if (Field)
4009 Decls.erase(Field);
4010 if (BaseClass)
4011 BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
4012 }
4013
4014 void VisitMemberExpr(MemberExpr *ME) {
4015 // All uses of unbounded reference fields will warn.
4016 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
4017 }
4018
4019 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
4020 if (E->getCastKind() == CK_LValueToRValue) {
4021 HandleValue(E->getSubExpr(), false /*AddressOf*/);
4022 return;
4023 }
4024
4025 Inherited::VisitImplicitCastExpr(E);
4026 }
4027
4028 void VisitCXXConstructExpr(CXXConstructExpr *E) {
4029 if (E->getConstructor()->isCopyConstructor()) {
4030 Expr *ArgExpr = E->getArg(0);
4031 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
4032 if (ILE->getNumInits() == 1)
4033 ArgExpr = ILE->getInit(0);
4034 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
4035 if (ICE->getCastKind() == CK_NoOp)
4036 ArgExpr = ICE->getSubExpr();
4037 HandleValue(ArgExpr, false /*AddressOf*/);
4038 return;
4039 }
4040 Inherited::VisitCXXConstructExpr(E);
4041 }
4042
4043 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
4044 Expr *Callee = E->getCallee();
4045 if (isa<MemberExpr>(Callee)) {
4046 HandleValue(Callee, false /*AddressOf*/);
4047 for (auto *Arg : E->arguments())
4048 Visit(Arg);
4049 return;
4050 }
4051
4052 Inherited::VisitCXXMemberCallExpr(E);
4053 }
4054
4055 void VisitCallExpr(CallExpr *E) {
4056 // Treat std::move as a use.
4057 if (E->isCallToStdMove()) {
4058 HandleValue(E->getArg(0), /*AddressOf=*/false);
4059 return;
4060 }
4061
4062 Inherited::VisitCallExpr(E);
4063 }
4064
4065 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
4066 Expr *Callee = E->getCallee();
4067
4068 if (isa<UnresolvedLookupExpr>(Callee))
4069 return Inherited::VisitCXXOperatorCallExpr(E);
4070
4071 Visit(Callee);
4072 for (auto *Arg : E->arguments())
4073 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
4074 }
4075
4076 void VisitBinaryOperator(BinaryOperator *E) {
4077 // If a field assignment is detected, remove the field from the
4078 // uninitiailized field set.
4079 if (E->getOpcode() == BO_Assign)
4080 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
4081 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
4082 if (!FD->getType()->isReferenceType())
4083 DeclsToRemove.push_back(FD);
4084
4085 if (E->isCompoundAssignmentOp()) {
4086 HandleValue(E->getLHS(), false /*AddressOf*/);
4087 Visit(E->getRHS());
4088 return;
4089 }
4090
4091 Inherited::VisitBinaryOperator(E);
4092 }
4093
4094 void VisitUnaryOperator(UnaryOperator *E) {
4095 if (E->isIncrementDecrementOp()) {
4096 HandleValue(E->getSubExpr(), false /*AddressOf*/);
4097 return;
4098 }
4099 if (E->getOpcode() == UO_AddrOf) {
4100 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
4101 HandleValue(ME->getBase(), true /*AddressOf*/);
4102 return;
4103 }
4104 }
4105
4106 Inherited::VisitUnaryOperator(E);
4107 }
4108 };
4109
4110 // Diagnose value-uses of fields to initialize themselves, e.g.
4111 // foo(foo)
4112 // where foo is not also a parameter to the constructor.
4113 // Also diagnose across field uninitialized use such as
4114 // x(y), y(x)
4115 // TODO: implement -Wuninitialized and fold this into that framework.
4116 static void DiagnoseUninitializedFields(
4117 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
4118
4119 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
4120 Constructor->getLocation())) {
4121 return;
4122 }
4123
4124 if (Constructor->isInvalidDecl())
4125 return;
4126
4127 const CXXRecordDecl *RD = Constructor->getParent();
4128
4129 if (RD->isDependentContext())
4130 return;
4131
4132 // Holds fields that are uninitialized.
4133 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
4134
4135 // At the beginning, all fields are uninitialized.
4136 for (auto *I : RD->decls()) {
4137 if (auto *FD = dyn_cast<FieldDecl>(I)) {
4138 UninitializedFields.insert(FD);
4139 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
4140 UninitializedFields.insert(IFD->getAnonField());
4141 }
4142 }
4143
4144 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
4145 for (const auto &I : RD->bases())
4146 UninitializedBaseClasses.insert(I.getType().getCanonicalType());
4147
4148 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
4149 return;
4150
4151 UninitializedFieldVisitor UninitializedChecker(SemaRef,
4152 UninitializedFields,
4153 UninitializedBaseClasses);
4154
4155 for (const auto *FieldInit : Constructor->inits()) {
4156 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
4157 break;
4158
4159 Expr *InitExpr = FieldInit->getInit();
4160 if (!InitExpr)
4161 continue;
4162
4163 if (CXXDefaultInitExpr *Default =
4164 dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
4165 InitExpr = Default->getExpr();
4166 if (!InitExpr)
4167 continue;
4168 // In class initializers will point to the constructor.
4169 UninitializedChecker.CheckInitializer(InitExpr, Constructor,
4170 FieldInit->getAnyMember(),
4171 FieldInit->getBaseClass());
4172 } else {
4173 UninitializedChecker.CheckInitializer(InitExpr, nullptr,
4174 FieldInit->getAnyMember(),
4175 FieldInit->getBaseClass());
4176 }
4177 }
4178 }
4179} // namespace
4180
4182 // Create a synthetic function scope to represent the call to the constructor
4183 // that notionally surrounds a use of this initializer.
4185}
4186
4188 if (!D.isFunctionDeclarator())
4189 return;
4190 auto &FTI = D.getFunctionTypeInfo();
4191 if (!FTI.Params)
4192 return;
4193 for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params,
4194 FTI.NumParams)) {
4195 auto *ParamDecl = cast<NamedDecl>(Param.Param);
4196 if (ParamDecl->getDeclName())
4197 PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false);
4198 }
4199}
4200
4202 return ActOnRequiresClause(ConstraintExpr);
4203}
4204
4206 if (ConstraintExpr.isInvalid())
4207 return ExprError();
4208
4209 if (DiagnoseUnexpandedParameterPack(ConstraintExpr.get(),
4211 return ExprError();
4212
4213 return ConstraintExpr;
4214}
4215
4217 Expr *InitExpr,
4218 SourceLocation InitLoc) {
4219 InitializedEntity Entity =
4221 InitializationKind Kind =
4224 InitExpr->getBeginLoc(),
4225 InitExpr->getEndLoc())
4226 : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
4227 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
4228 return Seq.Perform(*this, Entity, Kind, InitExpr);
4229}
4230
4232 SourceLocation InitLoc,
4233 ExprResult InitExpr) {
4234 // Pop the notional constructor scope we created earlier.
4235 PopFunctionScopeInfo(nullptr, D);
4236
4237 // Microsoft C++'s property declaration cannot have a default member
4238 // initializer.
4239 if (isa<MSPropertyDecl>(D)) {
4240 D->setInvalidDecl();
4241 return;
4242 }
4243
4244 FieldDecl *FD = dyn_cast<FieldDecl>(D);
4245 assert((FD && FD->getInClassInitStyle() != ICIS_NoInit) &&
4246 "must set init style when field is created");
4247
4248 if (!InitExpr.isUsable() ||
4250 FD->setInvalidDecl();
4251 ExprResult RecoveryInit =
4252 CreateRecoveryExpr(InitLoc, InitLoc, {}, FD->getType());
4253 if (RecoveryInit.isUsable())
4254 FD->setInClassInitializer(RecoveryInit.get());
4255 return;
4256 }
4257
4258 if (!FD->getType()->isDependentType() && !InitExpr.get()->isTypeDependent()) {
4259 InitExpr = ConvertMemberDefaultInitExpression(FD, InitExpr.get(), InitLoc);
4260 // C++11 [class.base.init]p7:
4261 // The initialization of each base and member constitutes a
4262 // full-expression.
4263 if (!InitExpr.isInvalid())
4264 InitExpr = ActOnFinishFullExpr(InitExpr.get(), /*DiscarededValue=*/false);
4265 if (InitExpr.isInvalid()) {
4266 FD->setInvalidDecl();
4267 return;
4268 }
4269 }
4270
4271 FD->setInClassInitializer(InitExpr.get());
4272}
4273
4274/// Find the direct and/or virtual base specifiers that
4275/// correspond to the given base type, for use in base initialization
4276/// within a constructor.
4277static bool FindBaseInitializer(Sema &SemaRef,
4278 CXXRecordDecl *ClassDecl,
4279 QualType BaseType,
4280 const CXXBaseSpecifier *&DirectBaseSpec,
4281 const CXXBaseSpecifier *&VirtualBaseSpec) {
4282 // First, check for a direct base class.
4283 DirectBaseSpec = nullptr;
4284 for (const auto &Base : ClassDecl->bases()) {
4285 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
4286 // We found a direct base of this type. That's what we're
4287 // initializing.
4288 DirectBaseSpec = &Base;
4289 break;
4290 }
4291 }
4292
4293 // Check for a virtual base class.
4294 // FIXME: We might be able to short-circuit this if we know in advance that
4295 // there are no virtual bases.
4296 VirtualBaseSpec = nullptr;
4297 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
4298 // We haven't found a base yet; search the class hierarchy for a
4299 // virtual base class.
4300 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
4301 /*DetectVirtual=*/false);
4302 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
4303 SemaRef.Context.getCanonicalTagType(ClassDecl),
4304 BaseType, Paths)) {
4305 for (const CXXBasePath &Path : Paths) {
4306 if (Path.back().Base->isVirtual()) {
4307 VirtualBaseSpec = Path.back().Base;
4308 break;
4309 }
4310 }
4311 }
4312 }
4313
4314 return DirectBaseSpec || VirtualBaseSpec;
4315}
4316
4319 Scope *S,
4320 CXXScopeSpec &SS,
4321 IdentifierInfo *MemberOrBase,
4322 ParsedType TemplateTypeTy,
4323 const DeclSpec &DS,
4324 SourceLocation IdLoc,
4325 Expr *InitList,
4326 SourceLocation EllipsisLoc) {
4327 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4328 DS, IdLoc, InitList,
4329 EllipsisLoc);
4330}
4331
4334 Scope *S,
4335 CXXScopeSpec &SS,
4336 IdentifierInfo *MemberOrBase,
4337 ParsedType TemplateTypeTy,
4338 const DeclSpec &DS,
4339 SourceLocation IdLoc,
4340 SourceLocation LParenLoc,
4341 ArrayRef<Expr *> Args,
4342 SourceLocation RParenLoc,
4343 SourceLocation EllipsisLoc) {
4344 Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
4345 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4346 DS, IdLoc, List, EllipsisLoc);
4347}
4348
4349namespace {
4350
4351// Callback to only accept typo corrections that can be a valid C++ member
4352// initializer: either a non-static field member or a base class.
4353class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
4354public:
4355 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
4356 : ClassDecl(ClassDecl) {}
4357
4358 bool ValidateCandidate(const TypoCorrection &candidate) override {
4359 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
4360 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
4361 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
4362 return isa<TypeDecl>(ND);
4363 }
4364 return false;
4365 }
4366
4367 std::unique_ptr<CorrectionCandidateCallback> clone() override {
4368 return std::make_unique<MemInitializerValidatorCCC>(*this);
4369 }
4370
4371private:
4372 CXXRecordDecl *ClassDecl;
4373};
4374
4375}
4376
4378 RecordDecl *ClassDecl,
4379 const IdentifierInfo *Name) {
4380 DeclContextLookupResult Result = ClassDecl->lookup(Name);
4382 llvm::find_if(Result, [this](const NamedDecl *Elem) {
4383 return isa<FieldDecl, IndirectFieldDecl>(Elem) &&
4385 });
4386 // We did not find a placeholder variable
4387 if (Found == Result.end())
4388 return false;
4389 Diag(Loc, diag::err_using_placeholder_variable) << Name;
4390 for (DeclContextLookupResult::iterator It = Found; It != Result.end(); It++) {
4391 const NamedDecl *ND = *It;
4392 if (ND->getDeclContext() != ND->getDeclContext())
4393 break;
4396 Diag(ND->getLocation(), diag::note_reference_placeholder) << ND;
4397 }
4398 return true;
4399}
4400
4401ValueDecl *
4403 const IdentifierInfo *MemberOrBase) {
4404 ValueDecl *ND = nullptr;
4405 for (auto *D : ClassDecl->lookup(MemberOrBase)) {
4407 bool IsPlaceholder = D->isPlaceholderVar(getLangOpts());
4408 if (ND) {
4409 if (IsPlaceholder && D->getDeclContext() == ND->getDeclContext())
4410 return nullptr;
4411 break;
4412 }
4413 if (!IsPlaceholder)
4414 return cast<ValueDecl>(D);
4415 ND = cast<ValueDecl>(D);
4416 }
4417 }
4418 return ND;
4419}
4420
4422 CXXScopeSpec &SS,
4423 ParsedType TemplateTypeTy,
4424 IdentifierInfo *MemberOrBase) {
4425 if (SS.getScopeRep() || TemplateTypeTy)
4426 return nullptr;
4427 return tryLookupUnambiguousFieldDecl(ClassDecl, MemberOrBase);
4428}
4429
4432 Scope *S,
4433 CXXScopeSpec &SS,
4434 IdentifierInfo *MemberOrBase,
4435 ParsedType TemplateTypeTy,
4436 const DeclSpec &DS,
4437 SourceLocation IdLoc,
4438 Expr *Init,
4439 SourceLocation EllipsisLoc) {
4440 if (!ConstructorD || !Init)
4441 return true;
4442
4443 AdjustDeclIfTemplate(ConstructorD);
4444
4446 = dyn_cast<CXXConstructorDecl>(ConstructorD);
4447 if (!Constructor) {
4448 // The user wrote a constructor initializer on a function that is
4449 // not a C++ constructor. Ignore the error for now, because we may
4450 // have more member initializers coming; we'll diagnose it just
4451 // once in ActOnMemInitializers.
4452 return true;
4453 }
4454
4455 CXXRecordDecl *ClassDecl = Constructor->getParent();
4456
4457 // C++ [class.base.init]p2:
4458 // Names in a mem-initializer-id are looked up in the scope of the
4459 // constructor's class and, if not found in that scope, are looked
4460 // up in the scope containing the constructor's definition.
4461 // [Note: if the constructor's class contains a member with the
4462 // same name as a direct or virtual base class of the class, a
4463 // mem-initializer-id naming the member or base class and composed
4464 // of a single identifier refers to the class member. A
4465 // mem-initializer-id for the hidden base class may be specified
4466 // using a qualified name. ]
4467
4468 // Look for a member, first.
4470 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
4471 if (EllipsisLoc.isValid())
4472 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
4473 << MemberOrBase
4474 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4475
4476 return BuildMemberInitializer(Member, Init, IdLoc);
4477 }
4478 // It didn't name a member, so see if it names a class.
4479 QualType BaseType;
4480 TypeSourceInfo *TInfo = nullptr;
4481
4482 if (TemplateTypeTy) {
4483 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
4484 if (BaseType.isNull())
4485 return true;
4486 } else if (DS.getTypeSpecType() == TST_decltype) {
4487 BaseType = BuildDecltypeType(DS.getRepAsExpr());
4488 } else if (DS.getTypeSpecType() == TST_decltype_auto) {
4489 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
4490 return true;
4491 } else if (DS.getTypeSpecType() == TST_typename_pack_indexing) {
4492 BaseType =
4494 DS.getBeginLoc(), DS.getEllipsisLoc());
4495 } else {
4496 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
4497 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
4498
4499 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
4500 if (!TyD) {
4501 if (R.isAmbiguous()) return true;
4502
4503 // We don't want access-control diagnostics here.
4504 R.suppressDiagnostics();
4505
4506 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
4507 bool NotUnknownSpecialization = false;
4508 DeclContext *DC = computeDeclContext(SS, false);
4509 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
4510 NotUnknownSpecialization = !Record->hasAnyDependentBases();
4511
4512 if (!NotUnknownSpecialization) {
4513 // When the scope specifier can refer to a member of an unknown
4514 // specialization, we take it as a type name.
4515 BaseType = CheckTypenameType(
4517 SS.getWithLocInContext(Context), *MemberOrBase, IdLoc);
4518 if (BaseType.isNull())
4519 return true;
4520
4521 TInfo = Context.CreateTypeSourceInfo(BaseType);
4524 if (!TL.isNull()) {
4525 TL.setNameLoc(IdLoc);
4528 }
4529
4530 R.clear();
4531 R.setLookupName(MemberOrBase);
4532 }
4533 }
4534
4535 if (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus20) {
4536 if (auto UnqualifiedBase = R.getAsSingle<ClassTemplateDecl>()) {
4537 auto *TempSpec = cast<TemplateSpecializationType>(
4538 UnqualifiedBase->getCanonicalInjectedSpecializationType(Context));
4539 TemplateName TN = TempSpec->getTemplateName();
4540 for (auto const &Base : ClassDecl->bases()) {
4541 auto BaseTemplate =
4542 Base.getType()->getAs<TemplateSpecializationType>();
4543 if (BaseTemplate &&
4544 Context.hasSameTemplateName(BaseTemplate->getTemplateName(), TN,
4545 /*IgnoreDeduced=*/true)) {
4546 Diag(IdLoc, diag::ext_unqualified_base_class)
4547 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4548 BaseType = Base.getType();
4549 break;
4550 }
4551 }
4552 }
4553 }
4554
4555 // If no results were found, try to correct typos.
4556 TypoCorrection Corr;
4557 MemInitializerValidatorCCC CCC(ClassDecl);
4558 if (R.empty() && BaseType.isNull() &&
4559 (Corr =
4560 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
4561 CCC, CorrectTypoKind::ErrorRecovery, ClassDecl))) {
4563 // We have found a non-static data member with a similar
4564 // name to what was typed; complain and initialize that
4565 // member.
4566 diagnoseTypo(Corr,
4567 PDiag(diag::err_mem_init_not_member_or_class_suggest)
4568 << MemberOrBase << true);
4569 return BuildMemberInitializer(Member, Init, IdLoc);
4570 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
4571 const CXXBaseSpecifier *DirectBaseSpec;
4572 const CXXBaseSpecifier *VirtualBaseSpec;
4573 if (FindBaseInitializer(*this, ClassDecl,
4574 Context.getTypeDeclType(Type),
4575 DirectBaseSpec, VirtualBaseSpec)) {
4576 // We have found a direct or virtual base class with a
4577 // similar name to what was typed; complain and initialize
4578 // that base class.
4579 diagnoseTypo(Corr,
4580 PDiag(diag::err_mem_init_not_member_or_class_suggest)
4581 << MemberOrBase << false,
4582 PDiag() /*Suppress note, we provide our own.*/);
4583
4584 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
4585 : VirtualBaseSpec;
4586 Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
4587 << BaseSpec->getType() << BaseSpec->getSourceRange();
4588
4589 TyD = Type;
4590 }
4591 }
4592 }
4593
4594 if (!TyD && BaseType.isNull()) {
4595 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
4596 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4597 return true;
4598 }
4599 }
4600
4601 if (BaseType.isNull()) {
4602 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
4603
4604 TypeLocBuilder TLB;
4605 // FIXME: This is missing building the UsingType for TyD, if any.
4606 if (const auto *TD = dyn_cast<TagDecl>(TyD)) {
4607 BaseType = Context.getTagType(ElaboratedTypeKeyword::None,
4608 SS.getScopeRep(), TD, /*OwnsTag=*/false);
4609 auto TL = TLB.push<TagTypeLoc>(BaseType);
4611 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4612 TL.setNameLoc(IdLoc);
4613 } else if (auto *TN = dyn_cast<TypedefNameDecl>(TyD)) {
4614 BaseType = Context.getTypedefType(ElaboratedTypeKeyword::None,
4615 SS.getScopeRep(), TN);
4616 TLB.push<TypedefTypeLoc>(BaseType).set(
4617 /*ElaboratedKeywordLoc=*/SourceLocation(),
4618 SS.getWithLocInContext(Context), IdLoc);
4619 } else if (auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(TyD)) {
4620 BaseType = Context.getUnresolvedUsingType(ElaboratedTypeKeyword::None,
4621 SS.getScopeRep(), UD);
4622 TLB.push<UnresolvedUsingTypeLoc>(BaseType).set(
4623 /*ElaboratedKeywordLoc=*/SourceLocation(),
4624 SS.getWithLocInContext(Context), IdLoc);
4625 } else {
4626 // FIXME: What else can appear here?
4627 assert(SS.isEmpty());
4628 BaseType = Context.getTypeDeclType(TyD);
4629 TLB.pushTypeSpec(BaseType).setNameLoc(IdLoc);
4630 }
4631 TInfo = TLB.getTypeSourceInfo(Context, BaseType);
4632 }
4633 }
4634
4635 if (!TInfo)
4636 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
4637
4638 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
4639}
4640
4643 SourceLocation IdLoc) {
4644 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
4645 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
4646 assert((DirectMember || IndirectMember) &&
4647 "Member must be a FieldDecl or IndirectFieldDecl");
4648
4650 return true;
4651
4652 if (Member->isInvalidDecl())
4653 return true;
4654
4655 MultiExprArg Args;
4656 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4657 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4658 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4659 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4660 } else {
4661 // Template instantiation doesn't reconstruct ParenListExprs for us.
4662 Args = Init;
4663 }
4664
4665 SourceRange InitRange = Init->getSourceRange();
4666
4667 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4668 // Can't check initialization for a member of dependent type or when
4669 // any of the arguments are type-dependent expressions.
4671 } else {
4672 bool InitList = false;
4673 if (isa<InitListExpr>(Init)) {
4674 InitList = true;
4675 Args = Init;
4676 }
4677
4678 // Initialize the member.
4679 InitializedEntity MemberEntity =
4680 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4681 : InitializedEntity::InitializeMember(IndirectMember,
4682 nullptr);
4683 InitializationKind Kind =
4685 IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4686 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4687 InitRange.getEnd());
4688
4689 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4690 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4691 nullptr);
4692 if (!MemberInit.isInvalid()) {
4693 // C++11 [class.base.init]p7:
4694 // The initialization of each base and member constitutes a
4695 // full-expression.
4696 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
4697 /*DiscardedValue*/ false);
4698 }
4699
4700 if (MemberInit.isInvalid()) {
4701 // Args were sensible expressions but we couldn't initialize the member
4702 // from them. Preserve them in a RecoveryExpr instead.
4703 Init = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,
4704 Member->getType())
4705 .get();
4706 if (!Init)
4707 return true;
4708 } else {
4709 Init = MemberInit.get();
4710 }
4711 }
4712
4713 if (DirectMember) {
4714 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4715 InitRange.getBegin(), Init,
4716 InitRange.getEnd());
4717 } else {
4718 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4719 InitRange.getBegin(), Init,
4720 InitRange.getEnd());
4721 }
4722}
4723
4726 CXXRecordDecl *ClassDecl) {
4727 SourceLocation NameLoc = TInfo->getTypeLoc().getSourceRange().getBegin();
4728 if (!LangOpts.CPlusPlus11)
4729 return Diag(NameLoc, diag::err_delegating_ctor)
4730 << TInfo->getTypeLoc().getSourceRange();
4731 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4732
4733 bool InitList = true;
4734 MultiExprArg Args = Init;
4735 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4736 InitList = false;
4737 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4738 }
4739
4740 CanQualType ClassType = Context.getCanonicalTagType(ClassDecl);
4741
4742 SourceRange InitRange = Init->getSourceRange();
4743 // Initialize the object.
4744 InitializedEntity DelegationEntity =
4746 InitializationKind Kind =
4748 NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4749 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4750 InitRange.getEnd());
4751 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4752 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4753 Args, nullptr);
4754 if (!DelegationInit.isInvalid()) {
4755 assert((DelegationInit.get()->containsErrors() ||
4756 cast<CXXConstructExpr>(DelegationInit.get())->getConstructor()) &&
4757 "Delegating constructor with no target?");
4758
4759 // C++11 [class.base.init]p7:
4760 // The initialization of each base and member constitutes a
4761 // full-expression.
4762 DelegationInit = ActOnFinishFullExpr(
4763 DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
4764 }
4765
4766 if (DelegationInit.isInvalid()) {
4767 DelegationInit = CreateRecoveryExpr(InitRange.getBegin(),
4768 InitRange.getEnd(), Args, ClassType);
4769 if (DelegationInit.isInvalid())
4770 return true;
4771 } else {
4772 // If we are in a dependent context, template instantiation will
4773 // perform this type-checking again. Just save the arguments that we
4774 // received in a ParenListExpr.
4775 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4776 // of the information that we have about the base
4777 // initializer. However, deconstructing the ASTs is a dicey process,
4778 // and this approach is far more likely to get the corner cases right.
4779 if (CurContext->isDependentContext())
4780 DelegationInit = Init;
4781 }
4782
4783 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4784 DelegationInit.getAs<Expr>(),
4785 InitRange.getEnd());
4786}
4787
4790 Expr *Init, CXXRecordDecl *ClassDecl,
4791 SourceLocation EllipsisLoc) {
4792 SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getBeginLoc();
4793
4794 if (!BaseType->isDependentType() && !BaseType->isRecordType())
4795 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4796 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
4797
4798 // C++ [class.base.init]p2:
4799 // [...] Unless the mem-initializer-id names a nonstatic data
4800 // member of the constructor's class or a direct or virtual base
4801 // of that class, the mem-initializer is ill-formed. A
4802 // mem-initializer-list can initialize a base class using any
4803 // name that denotes that base class type.
4804
4805 // We can store the initializers in "as-written" form and delay analysis until
4806 // instantiation if the constructor is dependent. But not for dependent
4807 // (broken) code in a non-template! SetCtorInitializers does not expect this.
4808 bool Dependent = CurContext->isDependentContext() &&
4809 (BaseType->isDependentType() || Init->isTypeDependent());
4810
4811 SourceRange InitRange = Init->getSourceRange();
4812 if (EllipsisLoc.isValid()) {
4813 // This is a pack expansion.
4814 if (!BaseType->containsUnexpandedParameterPack()) {
4815 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4816 << SourceRange(BaseLoc, InitRange.getEnd());
4817
4818 EllipsisLoc = SourceLocation();
4819 }
4820 } else {
4821 // Check for any unexpanded parameter packs.
4822 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4823 return true;
4824
4826 return true;
4827 }
4828
4829 // Check for direct and virtual base classes.
4830 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4831 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4832 if (!Dependent) {
4833 if (declaresSameEntity(ClassDecl, BaseType->getAsCXXRecordDecl()))
4834 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4835
4836 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4837 VirtualBaseSpec);
4838
4839 // C++ [base.class.init]p2:
4840 // Unless the mem-initializer-id names a nonstatic data member of the
4841 // constructor's class or a direct or virtual base of that class, the
4842 // mem-initializer is ill-formed.
4843 if (!DirectBaseSpec && !VirtualBaseSpec) {
4844 // If the class has any dependent bases, then it's possible that
4845 // one of those types will resolve to the same type as
4846 // BaseType. Therefore, just treat this as a dependent base
4847 // class initialization. FIXME: Should we try to check the
4848 // initialization anyway? It seems odd.
4849 if (ClassDecl->hasAnyDependentBases())
4850 Dependent = true;
4851 else
4852 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4853 << BaseType << Context.getCanonicalTagType(ClassDecl)
4854 << BaseTInfo->getTypeLoc().getSourceRange();
4855 }
4856 }
4857
4858 if (Dependent) {
4860
4861 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4862 /*IsVirtual=*/false,
4863 InitRange.getBegin(), Init,
4864 InitRange.getEnd(), EllipsisLoc);
4865 }
4866
4867 // C++ [base.class.init]p2:
4868 // If a mem-initializer-id is ambiguous because it designates both
4869 // a direct non-virtual base class and an inherited virtual base
4870 // class, the mem-initializer is ill-formed.
4871 if (DirectBaseSpec && VirtualBaseSpec)
4872 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4873 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4874
4875 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4876 if (!BaseSpec)
4877 BaseSpec = VirtualBaseSpec;
4878
4879 // Initialize the base.
4880 bool InitList = true;
4881 MultiExprArg Args = Init;
4882 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4883 InitList = false;
4884 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4885 }
4886
4887 InitializedEntity BaseEntity =
4888 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4889 InitializationKind Kind =
4890 InitList ? InitializationKind::CreateDirectList(BaseLoc)
4891 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4892 InitRange.getEnd());
4893 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4894 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4895 if (!BaseInit.isInvalid()) {
4896 // C++11 [class.base.init]p7:
4897 // The initialization of each base and member constitutes a
4898 // full-expression.
4899 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
4900 /*DiscardedValue*/ false);
4901 }
4902
4903 if (BaseInit.isInvalid()) {
4904 BaseInit = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(),
4905 Args, BaseType);
4906 if (BaseInit.isInvalid())
4907 return true;
4908 } else {
4909 // If we are in a dependent context, template instantiation will
4910 // perform this type-checking again. Just save the arguments that we
4911 // received in a ParenListExpr.
4912 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4913 // of the information that we have about the base
4914 // initializer. However, deconstructing the ASTs is a dicey process,
4915 // and this approach is far more likely to get the corner cases right.
4916 if (CurContext->isDependentContext())
4917 BaseInit = Init;
4918 }
4919
4920 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4921 BaseSpec->isVirtual(),
4922 InitRange.getBegin(),
4923 BaseInit.getAs<Expr>(),
4924 InitRange.getEnd(), EllipsisLoc);
4925}
4926
4927// Create a static_cast<T&&>(expr).
4928static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
4929 QualType TargetType =
4930 SemaRef.BuildReferenceType(E->getType(), /*SpelledAsLValue*/ false,
4932 SourceLocation ExprLoc = E->getBeginLoc();
4933 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4934 TargetType, ExprLoc);
4935
4936 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4937 SourceRange(ExprLoc, ExprLoc),
4938 E->getSourceRange()).get();
4939}
4940
4941/// ImplicitInitializerKind - How an implicit base or member initializer should
4942/// initialize its base or member.
4949
4950static bool
4952 ImplicitInitializerKind ImplicitInitKind,
4953 CXXBaseSpecifier *BaseSpec,
4954 bool IsInheritedVirtualBase,
4955 CXXCtorInitializer *&CXXBaseInit) {
4956 InitializedEntity InitEntity
4957 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4958 IsInheritedVirtualBase);
4959
4960 ExprResult BaseInit;
4961
4962 switch (ImplicitInitKind) {
4963 case IIK_Inherit:
4964 case IIK_Default: {
4965 InitializationKind InitKind
4967 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, {});
4968 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, {});
4969 break;
4970 }
4971
4972 case IIK_Move:
4973 case IIK_Copy: {
4974 bool Moving = ImplicitInitKind == IIK_Move;
4975 ParmVarDecl *Param = Constructor->getParamDecl(0);
4976 QualType ParamType = Param->getType().getNonReferenceType();
4977
4978 Expr *CopyCtorArg =
4980 SourceLocation(), Param, false,
4981 Constructor->getLocation(), ParamType,
4982 VK_LValue, nullptr);
4983
4984 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4985
4986 // Cast to the base class to avoid ambiguities.
4987 QualType ArgTy =
4988 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4989 ParamType.getQualifiers());
4990
4991 if (Moving) {
4992 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4993 }
4994
4995 CXXCastPath BasePath;
4996 BasePath.push_back(BaseSpec);
4997 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4998 CK_UncheckedDerivedToBase,
4999 Moving ? VK_XValue : VK_LValue,
5000 &BasePath).get();
5001
5002 InitializationKind InitKind
5005 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
5006 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
5007 break;
5008 }
5009 }
5010
5011 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
5012 if (BaseInit.isInvalid())
5013 return true;
5014
5015 CXXBaseInit =
5016 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5017 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
5018 SourceLocation()),
5019 BaseSpec->isVirtual(),
5021 BaseInit.getAs<Expr>(),
5023 SourceLocation());
5024
5025 return false;
5026}
5027
5028static bool RefersToRValueRef(Expr *MemRef) {
5029 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
5030 return Referenced->getType()->isRValueReferenceType();
5031}
5032
5033static bool
5035 ImplicitInitializerKind ImplicitInitKind,
5036 FieldDecl *Field, IndirectFieldDecl *Indirect,
5037 CXXCtorInitializer *&CXXMemberInit) {
5038 if (Field->isInvalidDecl())
5039 return true;
5040
5041 SourceLocation Loc = Constructor->getLocation();
5042
5043 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
5044 bool Moving = ImplicitInitKind == IIK_Move;
5045 ParmVarDecl *Param = Constructor->getParamDecl(0);
5046 QualType ParamType = Param->getType().getNonReferenceType();
5047
5048 // Suppress copying zero-width bitfields.
5049 if (Field->isZeroLengthBitField())
5050 return false;
5051
5052 Expr *MemberExprBase =
5054 SourceLocation(), Param, false,
5055 Loc, ParamType, VK_LValue, nullptr);
5056
5057 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
5058
5059 if (Moving) {
5060 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
5061 }
5062
5063 // Build a reference to this field within the parameter.
5064 CXXScopeSpec SS;
5065 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
5067 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
5068 : cast<ValueDecl>(Field), AS_public);
5069 MemberLookup.resolveKind();
5070 ExprResult CtorArg
5071 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
5072 ParamType, Loc,
5073 /*IsArrow=*/false,
5074 SS,
5075 /*TemplateKWLoc=*/SourceLocation(),
5076 /*FirstQualifierInScope=*/nullptr,
5077 MemberLookup,
5078 /*TemplateArgs=*/nullptr,
5079 /*S*/nullptr);
5080 if (CtorArg.isInvalid())
5081 return true;
5082
5083 // C++11 [class.copy]p15:
5084 // - if a member m has rvalue reference type T&&, it is direct-initialized
5085 // with static_cast<T&&>(x.m);
5086 if (RefersToRValueRef(CtorArg.get())) {
5087 CtorArg = CastForMoving(SemaRef, CtorArg.get());
5088 }
5089
5090 InitializedEntity Entity =
5093
5094 // Direct-initialize to use the copy constructor.
5095 InitializationKind InitKind =
5097
5098 Expr *CtorArgE = CtorArg.getAs<Expr>();
5099 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
5100 ExprResult MemberInit =
5101 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
5102 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
5103 if (MemberInit.isInvalid())
5104 return true;
5105
5106 if (Indirect)
5107 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
5108 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
5109 else
5110 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
5111 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
5112 return false;
5113 }
5114
5115 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
5116 "Unhandled implicit init kind!");
5117
5118 QualType FieldBaseElementType =
5119 SemaRef.Context.getBaseElementType(Field->getType());
5120
5121 if (FieldBaseElementType->isRecordType()) {
5122 InitializedEntity InitEntity =
5125 InitializationKind InitKind =
5127
5128 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, {});
5129 ExprResult MemberInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, {});
5130
5131 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
5132 if (MemberInit.isInvalid())
5133 return true;
5134
5135 if (Indirect)
5136 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5137 Indirect, Loc,
5138 Loc,
5139 MemberInit.get(),
5140 Loc);
5141 else
5142 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5143 Field, Loc, Loc,
5144 MemberInit.get(),
5145 Loc);
5146 return false;
5147 }
5148
5149 if (!Field->getParent()->isUnion()) {
5150 if (FieldBaseElementType->isReferenceType()) {
5151 SemaRef.Diag(Constructor->getLocation(),
5152 diag::err_uninitialized_member_in_ctor)
5153 << (int)Constructor->isImplicit()
5154 << SemaRef.Context.getCanonicalTagType(Constructor->getParent()) << 0
5155 << Field->getDeclName();
5156 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
5157 return true;
5158 }
5159
5160 if (FieldBaseElementType.isConstQualified()) {
5161 SemaRef.Diag(Constructor->getLocation(),
5162 diag::err_uninitialized_member_in_ctor)
5163 << (int)Constructor->isImplicit()
5164 << SemaRef.Context.getCanonicalTagType(Constructor->getParent()) << 1
5165 << Field->getDeclName();
5166 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
5167 return true;
5168 }
5169 }
5170
5171 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
5172 // ARC and Weak:
5173 // Default-initialize Objective-C pointers to NULL.
5174 CXXMemberInit
5175 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
5176 Loc, Loc,
5177 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
5178 Loc);
5179 return false;
5180 }
5181
5182 // Nothing to initialize.
5183 CXXMemberInit = nullptr;
5184 return false;
5185}
5186
5187namespace {
5188struct BaseAndFieldInfo {
5189 Sema &S;
5190 CXXConstructorDecl *Ctor;
5191 bool AnyErrorsInInits;
5193 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
5194 SmallVector<CXXCtorInitializer*, 8> AllToInit;
5195 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
5196
5197 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
5198 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
5199 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
5200 if (Ctor->getInheritedConstructor())
5201 IIK = IIK_Inherit;
5202 else if (Generated && Ctor->isCopyConstructor())
5203 IIK = IIK_Copy;
5204 else if (Generated && Ctor->isMoveConstructor())
5205 IIK = IIK_Move;
5206 else
5207 IIK = IIK_Default;
5208 }
5209
5210 bool isImplicitCopyOrMove() const {
5211 switch (IIK) {
5212 case IIK_Copy:
5213 case IIK_Move:
5214 return true;
5215
5216 case IIK_Default:
5217 case IIK_Inherit:
5218 return false;
5219 }
5220
5221 llvm_unreachable("Invalid ImplicitInitializerKind!");
5222 }
5223
5224 bool addFieldInitializer(CXXCtorInitializer *Init) {
5225 AllToInit.push_back(Init);
5226
5227 // Check whether this initializer makes the field "used".
5228 if (Init->getInit()->HasSideEffects(S.Context))
5229 S.UnusedPrivateFields.remove(Init->getAnyMember());
5230
5231 return false;
5232 }
5233
5234 bool isInactiveUnionMember(FieldDecl *Field) {
5235 RecordDecl *Record = Field->getParent();
5236 if (!Record->isUnion())
5237 return false;
5238
5239 if (FieldDecl *Active =
5240 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
5241 return Active != Field->getCanonicalDecl();
5242
5243 // In an implicit copy or move constructor, ignore any in-class initializer.
5244 if (isImplicitCopyOrMove())
5245 return true;
5246
5247 // If there's no explicit initialization, the field is active only if it
5248 // has an in-class initializer...
5249 if (Field->hasInClassInitializer())
5250 return false;
5251 // ... or it's an anonymous struct or union whose class has an in-class
5252 // initializer.
5253 if (!Field->isAnonymousStructOrUnion())
5254 return true;
5255 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
5256 return !FieldRD->hasInClassInitializer();
5257 }
5258
5259 /// Determine whether the given field is, or is within, a union member
5260 /// that is inactive (because there was an initializer given for a different
5261 /// member of the union, or because the union was not initialized at all).
5262 bool isWithinInactiveUnionMember(FieldDecl *Field,
5263 IndirectFieldDecl *Indirect) {
5264 if (!Indirect)
5265 return isInactiveUnionMember(Field);
5266
5267 for (auto *C : Indirect->chain()) {
5268 FieldDecl *Field = dyn_cast<FieldDecl>(C);
5269 if (Field && isInactiveUnionMember(Field))
5270 return true;
5271 }
5272 return false;
5273 }
5274};
5275}
5276
5277/// Determine whether the given type is an incomplete or zero-lenfgth
5278/// array type.
5280 if (T->isIncompleteArrayType())
5281 return true;
5282
5283 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
5284 if (ArrayT->isZeroSize())
5285 return true;
5286
5287 T = ArrayT->getElementType();
5288 }
5289
5290 return false;
5291}
5292
5293static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
5294 FieldDecl *Field,
5295 IndirectFieldDecl *Indirect = nullptr) {
5296 if (Field->isInvalidDecl())
5297 return false;
5298
5299 // Overwhelmingly common case: we have a direct initializer for this field.
5301 Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
5302 return Info.addFieldInitializer(Init);
5303
5304 // C++11 [class.base.init]p8:
5305 // if the entity is a non-static data member that has a
5306 // brace-or-equal-initializer and either
5307 // -- the constructor's class is a union and no other variant member of that
5308 // union is designated by a mem-initializer-id or
5309 // -- the constructor's class is not a union, and, if the entity is a member
5310 // of an anonymous union, no other member of that union is designated by
5311 // a mem-initializer-id,
5312 // the entity is initialized as specified in [dcl.init].
5313 //
5314 // We also apply the same rules to handle anonymous structs within anonymous
5315 // unions.
5316 if (Info.isWithinInactiveUnionMember(Field, Indirect))
5317 return false;
5318
5319 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
5320 ExprResult DIE =
5321 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
5322 if (DIE.isInvalid())
5323 return true;
5324
5326 SemaRef.checkInitializerLifetime(Entity, DIE.get());
5327
5329 if (Indirect)
5330 Init = new (SemaRef.Context)
5331 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
5332 SourceLocation(), DIE.get(), SourceLocation());
5333 else
5334 Init = new (SemaRef.Context)
5335 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
5336 SourceLocation(), DIE.get(), SourceLocation());
5337 return Info.addFieldInitializer(Init);
5338 }
5339
5340 // Don't initialize incomplete or zero-length arrays.
5341 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
5342 return false;
5343
5344 // Don't try to build an implicit initializer if there were semantic
5345 // errors in any of the initializers (and therefore we might be
5346 // missing some that the user actually wrote).
5347 if (Info.AnyErrorsInInits)
5348 return false;
5349
5350 CXXCtorInitializer *Init = nullptr;
5351 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
5352 Indirect, Init))
5353 return true;
5354
5355 if (!Init)
5356 return false;
5357
5358 return Info.addFieldInitializer(Init);
5359}
5360
5361bool
5364 assert(Initializer->isDelegatingInitializer());
5365 Constructor->setNumCtorInitializers(1);
5366 CXXCtorInitializer **initializer =
5367 new (Context) CXXCtorInitializer*[1];
5368 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
5369 Constructor->setCtorInitializers(initializer);
5370
5371 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
5372 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
5373 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
5374 }
5375
5377
5378 DiagnoseUninitializedFields(*this, Constructor);
5379
5380 return false;
5381}
5382
5384 CXXRecordDecl *Class) {
5385 if (Class->isInvalidDecl())
5386 return nullptr;
5387 if (Class->hasIrrelevantDestructor())
5388 return nullptr;
5389
5390 // Dtor might still be missing, e.g because it's invalid.
5391 return S.LookupDestructor(Class);
5392}
5393
5395 FieldDecl *Field) {
5396 if (Field->isInvalidDecl())
5397 return;
5398
5399 // Don't destroy incomplete or zero-length arrays.
5400 if (isIncompleteOrZeroLengthArrayType(S.Context, Field->getType()))
5401 return;
5402
5403 QualType FieldType = S.Context.getBaseElementType(Field->getType());
5404
5405 auto *FieldClassDecl = FieldType->getAsCXXRecordDecl();
5406 if (!FieldClassDecl)
5407 return;
5408
5409 // The destructor for an implicit anonymous union member is never invoked.
5410 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5411 return;
5412
5413 auto *Dtor = LookupDestructorIfRelevant(S, FieldClassDecl);
5414 if (!Dtor)
5415 return;
5416
5417 S.CheckDestructorAccess(Field->getLocation(), Dtor,
5418 S.PDiag(diag::err_access_dtor_field)
5419 << Field->getDeclName() << FieldType);
5420
5421 S.MarkFunctionReferenced(Location, Dtor);
5422 S.DiagnoseUseOfDecl(Dtor, Location);
5423}
5424
5426 CXXRecordDecl *ClassDecl) {
5427 if (ClassDecl->isDependentContext())
5428 return;
5429
5430 // We only potentially invoke the destructors of potentially constructed
5431 // subobjects.
5432 bool VisitVirtualBases = !ClassDecl->isAbstract();
5433
5434 // If the destructor exists and has already been marked used in the MS ABI,
5435 // then virtual base destructors have already been checked and marked used.
5436 // Skip checking them again to avoid duplicate diagnostics.
5438 CXXDestructorDecl *Dtor = ClassDecl->getDestructor();
5439 if (Dtor && Dtor->isUsed())
5440 VisitVirtualBases = false;
5441 }
5442
5444
5445 // Bases.
5446 for (const auto &Base : ClassDecl->bases()) {
5447 auto *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
5448 if (!BaseClassDecl)
5449 continue;
5450
5451 // Remember direct virtual bases.
5452 if (Base.isVirtual()) {
5453 if (!VisitVirtualBases)
5454 continue;
5455 DirectVirtualBases.insert(BaseClassDecl);
5456 }
5457
5458 auto *Dtor = LookupDestructorIfRelevant(S, BaseClassDecl);
5459 if (!Dtor)
5460 continue;
5461
5462 // FIXME: caret should be on the start of the class name
5463 S.CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5464 S.PDiag(diag::err_access_dtor_base)
5465 << Base.getType() << Base.getSourceRange(),
5466 S.Context.getCanonicalTagType(ClassDecl));
5467
5468 S.MarkFunctionReferenced(Location, Dtor);
5469 S.DiagnoseUseOfDecl(Dtor, Location);
5470 }
5471
5472 if (VisitVirtualBases)
5473 S.MarkVirtualBaseDestructorsReferenced(Location, ClassDecl,
5474 &DirectVirtualBases);
5475}
5476
5478 ArrayRef<CXXCtorInitializer *> Initializers) {
5479 if (Constructor->isDependentContext()) {
5480 // Just store the initializers as written, they will be checked during
5481 // instantiation.
5482 if (!Initializers.empty()) {
5483 Constructor->setNumCtorInitializers(Initializers.size());
5484 CXXCtorInitializer **baseOrMemberInitializers =
5485 new (Context) CXXCtorInitializer*[Initializers.size()];
5486 memcpy(baseOrMemberInitializers, Initializers.data(),
5487 Initializers.size() * sizeof(CXXCtorInitializer*));
5488 Constructor->setCtorInitializers(baseOrMemberInitializers);
5489 }
5490
5491 // Let template instantiation know whether we had errors.
5492 if (AnyErrors)
5493 Constructor->setInvalidDecl();
5494
5495 return false;
5496 }
5497
5498 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
5499
5500 // We need to build the initializer AST according to order of construction
5501 // and not what user specified in the Initializers list.
5502 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
5503 if (!ClassDecl)
5504 return true;
5505
5506 bool HadError = false;
5507
5508 for (CXXCtorInitializer *Member : Initializers) {
5509 if (Member->isBaseInitializer())
5510 Info.AllBaseFields[Member->getBaseClass()->getAsCanonical<RecordType>()] =
5511 Member;
5512 else {
5513 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
5514
5515 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
5516 for (auto *C : F->chain()) {
5517 FieldDecl *FD = dyn_cast<FieldDecl>(C);
5518 if (FD && FD->getParent()->isUnion())
5519 Info.ActiveUnionMember.insert(std::make_pair(
5521 }
5522 } else if (FieldDecl *FD = Member->getMember()) {
5523 if (FD->getParent()->isUnion())
5524 Info.ActiveUnionMember.insert(std::make_pair(
5526 }
5527 }
5528 }
5529
5530 // Keep track of the direct virtual bases.
5532 for (auto &I : ClassDecl->bases()) {
5533 if (I.isVirtual())
5534 DirectVBases.insert(&I);
5535 }
5536
5537 // Push virtual bases before others.
5538 for (auto &VBase : ClassDecl->vbases()) {
5539 if (CXXCtorInitializer *Value = Info.AllBaseFields.lookup(
5540 VBase.getType()->getAsCanonical<RecordType>())) {
5541 // [class.base.init]p7, per DR257:
5542 // A mem-initializer where the mem-initializer-id names a virtual base
5543 // class is ignored during execution of a constructor of any class that
5544 // is not the most derived class.
5545 if (ClassDecl->isAbstract()) {
5546 // FIXME: Provide a fixit to remove the base specifier. This requires
5547 // tracking the location of the associated comma for a base specifier.
5548 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
5549 << VBase.getType() << ClassDecl;
5550 DiagnoseAbstractType(ClassDecl);
5551 }
5552
5553 Info.AllToInit.push_back(Value);
5554 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
5555 // [class.base.init]p8, per DR257:
5556 // If a given [...] base class is not named by a mem-initializer-id
5557 // [...] and the entity is not a virtual base class of an abstract
5558 // class, then [...] the entity is default-initialized.
5559 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
5560 CXXCtorInitializer *CXXBaseInit;
5561 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5562 &VBase, IsInheritedVirtualBase,
5563 CXXBaseInit)) {
5564 HadError = true;
5565 continue;
5566 }
5567
5568 Info.AllToInit.push_back(CXXBaseInit);
5569 }
5570 }
5571
5572 // Non-virtual bases.
5573 for (auto &Base : ClassDecl->bases()) {
5574 // Virtuals are in the virtual base list and already constructed.
5575 if (Base.isVirtual())
5576 continue;
5577
5578 if (CXXCtorInitializer *Value = Info.AllBaseFields.lookup(
5579 Base.getType()->getAsCanonical<RecordType>())) {
5580 Info.AllToInit.push_back(Value);
5581 } else if (!AnyErrors) {
5582 CXXCtorInitializer *CXXBaseInit;
5583 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5584 &Base, /*IsInheritedVirtualBase=*/false,
5585 CXXBaseInit)) {
5586 HadError = true;
5587 continue;
5588 }
5589
5590 Info.AllToInit.push_back(CXXBaseInit);
5591 }
5592 }
5593
5594 // Fields.
5595 for (auto *Mem : ClassDecl->decls()) {
5596 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
5597 // C++ [class.bit]p2:
5598 // A declaration for a bit-field that omits the identifier declares an
5599 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
5600 // initialized.
5601 if (F->isUnnamedBitField())
5602 continue;
5603
5604 // If we're not generating the implicit copy/move constructor, then we'll
5605 // handle anonymous struct/union fields based on their individual
5606 // indirect fields.
5607 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
5608 continue;
5609
5610 if (CollectFieldInitializer(*this, Info, F))
5611 HadError = true;
5612 continue;
5613 }
5614
5615 // Beyond this point, we only consider default initialization.
5616 if (Info.isImplicitCopyOrMove())
5617 continue;
5618
5619 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
5620 if (F->getType()->isIncompleteArrayType()) {
5621 assert(ClassDecl->hasFlexibleArrayMember() &&
5622 "Incomplete array type is not valid");
5623 continue;
5624 }
5625
5626 // Initialize each field of an anonymous struct individually.
5627 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
5628 HadError = true;
5629
5630 continue;
5631 }
5632 }
5633
5634 unsigned NumInitializers = Info.AllToInit.size();
5635 if (NumInitializers > 0) {
5636 Constructor->setNumCtorInitializers(NumInitializers);
5637 CXXCtorInitializer **baseOrMemberInitializers =
5638 new (Context) CXXCtorInitializer*[NumInitializers];
5639 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
5640 NumInitializers * sizeof(CXXCtorInitializer*));
5641 Constructor->setCtorInitializers(baseOrMemberInitializers);
5642
5643 SourceLocation Location = Constructor->getLocation();
5644
5645 // Constructors implicitly reference the base and member
5646 // destructors.
5647
5648 for (CXXCtorInitializer *Initializer : Info.AllToInit) {
5649 FieldDecl *Field = Initializer->getAnyMember();
5650 if (!Field)
5651 continue;
5652
5653 // C++ [class.base.init]p12:
5654 // In a non-delegating constructor, the destructor for each
5655 // potentially constructed subobject of class type is potentially
5656 // invoked.
5657 MarkFieldDestructorReferenced(*this, Location, Field);
5658 }
5659
5660 MarkBaseDestructorsReferenced(*this, Location, Constructor->getParent());
5661 }
5662
5663 return HadError;
5664}
5665
5667 if (const RecordType *RT = Field->getType()->getAsCanonical<RecordType>()) {
5668 const RecordDecl *RD = RT->getDecl();
5669 if (RD->isAnonymousStructOrUnion()) {
5670 for (auto *Field : RD->getDefinitionOrSelf()->fields())
5671 PopulateKeysForFields(Field, IdealInits);
5672 return;
5673 }
5674 }
5675 IdealInits.push_back(Field->getCanonicalDecl());
5676}
5677
5678static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
5679 return Context.getCanonicalType(BaseType).getTypePtr();
5680}
5681
5682static const void *GetKeyForMember(ASTContext &Context,
5684 if (!Member->isAnyMemberInitializer())
5685 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
5686
5687 return Member->getAnyMember()->getCanonicalDecl();
5688}
5689
5692 const CXXCtorInitializer *Current) {
5693 if (Previous->isAnyMemberInitializer())
5694 Diag << 0 << Previous->getAnyMember();
5695 else
5696 Diag << 1 << Previous->getTypeSourceInfo()->getType();
5697
5698 if (Current->isAnyMemberInitializer())
5699 Diag << 0 << Current->getAnyMember();
5700 else
5701 Diag << 1 << Current->getTypeSourceInfo()->getType();
5702}
5703
5705 Sema &SemaRef, const CXXConstructorDecl *Constructor,
5707 if (Constructor->getDeclContext()->isDependentContext())
5708 return;
5709
5710 // Don't check initializers order unless the warning is enabled at the
5711 // location of at least one initializer.
5712 bool ShouldCheckOrder = false;
5713 for (const CXXCtorInitializer *Init : Inits) {
5714 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
5715 Init->getSourceLocation())) {
5716 ShouldCheckOrder = true;
5717 break;
5718 }
5719 }
5720 if (!ShouldCheckOrder)
5721 return;
5722
5723 // Build the list of bases and members in the order that they'll
5724 // actually be initialized. The explicit initializers should be in
5725 // this same order but may be missing things.
5726 SmallVector<const void*, 32> IdealInitKeys;
5727
5728 const CXXRecordDecl *ClassDecl = Constructor->getParent();
5729
5730 // 1. Virtual bases.
5731 for (const auto &VBase : ClassDecl->vbases())
5732 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
5733
5734 // 2. Non-virtual bases.
5735 for (const auto &Base : ClassDecl->bases()) {
5736 if (Base.isVirtual())
5737 continue;
5738 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
5739 }
5740
5741 // 3. Direct fields.
5742 for (auto *Field : ClassDecl->fields()) {
5743 if (Field->isUnnamedBitField())
5744 continue;
5745
5746 PopulateKeysForFields(Field, IdealInitKeys);
5747 }
5748
5749 unsigned NumIdealInits = IdealInitKeys.size();
5750 unsigned IdealIndex = 0;
5751
5752 // Track initializers that are in an incorrect order for either a warning or
5753 // note if multiple ones occur.
5754 SmallVector<unsigned> WarnIndexes;
5755 // Correlates the index of an initializer in the init-list to the index of
5756 // the field/base in the class.
5757 SmallVector<std::pair<unsigned, unsigned>, 32> CorrelatedInitOrder;
5758
5759 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5760 const void *InitKey = GetKeyForMember(SemaRef.Context, Inits[InitIndex]);
5761
5762 // Scan forward to try to find this initializer in the idealized
5763 // initializers list.
5764 for (; IdealIndex != NumIdealInits; ++IdealIndex)
5765 if (InitKey == IdealInitKeys[IdealIndex])
5766 break;
5767
5768 // If we didn't find this initializer, it must be because we
5769 // scanned past it on a previous iteration. That can only
5770 // happen if we're out of order; emit a warning.
5771 if (IdealIndex == NumIdealInits && InitIndex) {
5772 WarnIndexes.push_back(InitIndex);
5773
5774 // Move back to the initializer's location in the ideal list.
5775 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5776 if (InitKey == IdealInitKeys[IdealIndex])
5777 break;
5778
5779 assert(IdealIndex < NumIdealInits &&
5780 "initializer not found in initializer list");
5781 }
5782 CorrelatedInitOrder.emplace_back(IdealIndex, InitIndex);
5783 }
5784
5785 if (WarnIndexes.empty())
5786 return;
5787
5788 // Sort based on the ideal order, first in the pair.
5789 llvm::sort(CorrelatedInitOrder, llvm::less_first());
5790
5791 // Introduce a new scope as SemaDiagnosticBuilder needs to be destroyed to
5792 // emit the diagnostic before we can try adding notes.
5793 {
5795 Inits[WarnIndexes.front() - 1]->getSourceLocation(),
5796 WarnIndexes.size() == 1 ? diag::warn_initializer_out_of_order
5797 : diag::warn_some_initializers_out_of_order);
5798
5799 for (unsigned I = 0; I < CorrelatedInitOrder.size(); ++I) {
5800 if (CorrelatedInitOrder[I].second == I)
5801 continue;
5802 // Ideally we would be using InsertFromRange here, but clang doesn't
5803 // appear to handle InsertFromRange correctly when the source range is
5804 // modified by another fix-it.
5806 Inits[I]->getSourceRange(),
5809 Inits[CorrelatedInitOrder[I].second]->getSourceRange()),
5810 SemaRef.getSourceManager(), SemaRef.getLangOpts()));
5811 }
5812
5813 // If there is only 1 item out of order, the warning expects the name and
5814 // type of each being added to it.
5815 if (WarnIndexes.size() == 1) {
5816 AddInitializerToDiag(D, Inits[WarnIndexes.front() - 1],
5817 Inits[WarnIndexes.front()]);
5818 return;
5819 }
5820 }
5821 // More than 1 item to warn, create notes letting the user know which ones
5822 // are bad.
5823 for (unsigned WarnIndex : WarnIndexes) {
5824 const clang::CXXCtorInitializer *PrevInit = Inits[WarnIndex - 1];
5825 auto D = SemaRef.Diag(PrevInit->getSourceLocation(),
5826 diag::note_initializer_out_of_order);
5827 AddInitializerToDiag(D, PrevInit, Inits[WarnIndex]);
5828 D << PrevInit->getSourceRange();
5829 }
5830}
5831
5832namespace {
5833bool CheckRedundantInit(Sema &S,
5834 CXXCtorInitializer *Init,
5835 CXXCtorInitializer *&PrevInit) {
5836 if (!PrevInit) {
5837 PrevInit = Init;
5838 return false;
5839 }
5840
5841 if (FieldDecl *Field = Init->getAnyMember())
5842 S.Diag(Init->getSourceLocation(),
5843 diag::err_multiple_mem_initialization)
5844 << Field->getDeclName()
5845 << Init->getSourceRange();
5846 else {
5847 const Type *BaseClass = Init->getBaseClass();
5848 assert(BaseClass && "neither field nor base");
5849 S.Diag(Init->getSourceLocation(),
5850 diag::err_multiple_base_initialization)
5851 << QualType(BaseClass, 0)
5852 << Init->getSourceRange();
5853 }
5854 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5855 << 0 << PrevInit->getSourceRange();
5856
5857 return true;
5858}
5859
5860typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5861typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5862
5863bool CheckRedundantUnionInit(Sema &S,
5864 CXXCtorInitializer *Init,
5865 RedundantUnionMap &Unions) {
5866 FieldDecl *Field = Init->getAnyMember();
5867 RecordDecl *Parent = Field->getParent();
5868 NamedDecl *Child = Field;
5869
5870 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5871 if (Parent->isUnion()) {
5872 UnionEntry &En = Unions[Parent];
5873 if (En.first && En.first != Child) {
5874 S.Diag(Init->getSourceLocation(),
5875 diag::err_multiple_mem_union_initialization)
5876 << Field->getDeclName()
5877 << Init->getSourceRange();
5878 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5879 << 0 << En.second->getSourceRange();
5880 return true;
5881 }
5882 if (!En.first) {
5883 En.first = Child;
5884 En.second = Init;
5885 }
5886 if (!Parent->isAnonymousStructOrUnion())
5887 return false;
5888 }
5889
5890 Child = Parent;
5891 Parent = cast<RecordDecl>(Parent->getDeclContext());
5892 }
5893
5894 return false;
5895}
5896} // namespace
5897
5898void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5899 SourceLocation ColonLoc,
5901 bool AnyErrors) {
5902 if (!ConstructorDecl)
5903 return;
5904
5905 AdjustDeclIfTemplate(ConstructorDecl);
5906
5908 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5909
5910 if (!Constructor) {
5911 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5912 return;
5913 }
5914
5915 // Mapping for the duplicate initializers check.
5916 // For member initializers, this is keyed with a FieldDecl*.
5917 // For base initializers, this is keyed with a Type*.
5918 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5919
5920 // Mapping for the inconsistent anonymous-union initializers check.
5921 RedundantUnionMap MemberUnions;
5922
5923 bool HadError = false;
5924 for (unsigned i = 0; i < MemInits.size(); i++) {
5925 CXXCtorInitializer *Init = MemInits[i];
5926
5927 // Set the source order index.
5928 Init->setSourceOrder(i);
5929
5930 if (Init->isAnyMemberInitializer()) {
5931 const void *Key = GetKeyForMember(Context, Init);
5932 if (CheckRedundantInit(*this, Init, Members[Key]) ||
5933 CheckRedundantUnionInit(*this, Init, MemberUnions))
5934 HadError = true;
5935 } else if (Init->isBaseInitializer()) {
5936 const void *Key = GetKeyForMember(Context, Init);
5937 if (CheckRedundantInit(*this, Init, Members[Key]))
5938 HadError = true;
5939 } else {
5940 assert(Init->isDelegatingInitializer());
5941 // This must be the only initializer
5942 if (MemInits.size() != 1) {
5943 Diag(Init->getSourceLocation(),
5944 diag::err_delegating_initializer_alone)
5945 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5946 // We will treat this as being the only initializer.
5947 }
5949 // Return immediately as the initializer is set.
5950 return;
5951 }
5952 }
5953
5954 if (HadError)
5955 return;
5956
5958
5959 SetCtorInitializers(Constructor, AnyErrors, MemInits);
5960
5961 DiagnoseUninitializedFields(*this, Constructor);
5962}
5963
5965 CXXRecordDecl *ClassDecl) {
5966 // Ignore dependent contexts. Also ignore unions, since their members never
5967 // have destructors implicitly called.
5968 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5969 return;
5970
5971 // FIXME: all the access-control diagnostics are positioned on the
5972 // field/base declaration. That's probably good; that said, the
5973 // user might reasonably want to know why the destructor is being
5974 // emitted, and we currently don't say.
5975
5976 // Non-static data members.
5977 for (auto *Field : ClassDecl->fields()) {
5978 MarkFieldDestructorReferenced(*this, Location, Field);
5979 }
5980
5981 MarkBaseDestructorsReferenced(*this, Location, ClassDecl);
5982}
5983
5985 SourceLocation Location, CXXRecordDecl *ClassDecl,
5986 llvm::SmallPtrSetImpl<const CXXRecordDecl *> *DirectVirtualBases) {
5987 // Virtual bases.
5988 for (const auto &VBase : ClassDecl->vbases()) {
5989 auto *BaseClassDecl = VBase.getType()->getAsCXXRecordDecl();
5990 if (!BaseClassDecl)
5991 continue;
5992
5993 // Ignore already visited direct virtual bases.
5994 if (DirectVirtualBases && DirectVirtualBases->count(BaseClassDecl))
5995 continue;
5996
5997 auto *Dtor = LookupDestructorIfRelevant(*this, BaseClassDecl);
5998 if (!Dtor)
5999 continue;
6000
6001 CanQualType CT = Context.getCanonicalTagType(ClassDecl);
6002 if (CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
6003 PDiag(diag::err_access_dtor_vbase)
6004 << CT << VBase.getType(),
6005 CT) == AR_accessible) {
6007 CT, VBase.getType(), diag::err_access_dtor_vbase, 0,
6008 ClassDecl->getLocation(), SourceRange(), DeclarationName(), nullptr);
6009 }
6010
6011 MarkFunctionReferenced(Location, Dtor);
6012 DiagnoseUseOfDecl(Dtor, Location);
6013 }
6014}
6015
6017 if (!CDtorDecl)
6018 return;
6019
6021 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
6022 if (CXXRecordDecl *ClassDecl = Constructor->getParent();
6023 !ClassDecl || ClassDecl->isInvalidDecl()) {
6024 return;
6025 }
6026 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
6027 DiagnoseUninitializedFields(*this, Constructor);
6028 }
6029}
6030
6032 if (!getLangOpts().CPlusPlus)
6033 return false;
6034
6035 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
6036 if (!RD)
6037 return false;
6038
6039 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
6040 // class template specialization here, but doing so breaks a lot of code.
6041
6042 // We can't answer whether something is abstract until it has a
6043 // definition. If it's currently being defined, we'll walk back
6044 // over all the declarations when we have a full definition.
6045 const CXXRecordDecl *Def = RD->getDefinition();
6046 if (!Def || Def->isBeingDefined())
6047 return false;
6048
6049 return RD->isAbstract();
6050}
6051
6053 TypeDiagnoser &Diagnoser) {
6054 if (!isAbstractType(Loc, T))
6055 return false;
6056
6057 T = Context.getBaseElementType(T);
6058 Diagnoser.diagnose(*this, Loc, T);
6059 DiagnoseAbstractType(T->getAsCXXRecordDecl());
6060 return true;
6061}
6062
6064 // Check if we've already emitted the list of pure virtual functions
6065 // for this class.
6067 return;
6068
6069 // If the diagnostic is suppressed, don't emit the notes. We're only
6070 // going to emit them once, so try to attach them to a diagnostic we're
6071 // actually going to show.
6072 if (Diags.isLastDiagnosticIgnored())
6073 return;
6074
6075 CXXFinalOverriderMap FinalOverriders;
6076 RD->getFinalOverriders(FinalOverriders);
6077
6078 // Keep a set of seen pure methods so we won't diagnose the same method
6079 // more than once.
6081
6082 for (const auto &M : FinalOverriders) {
6083 for (const auto &SO : M.second) {
6084 // C++ [class.abstract]p4:
6085 // A class is abstract if it contains or inherits at least one
6086 // pure virtual function for which the final overrider is pure
6087 // virtual.
6088
6089 if (SO.second.size() != 1)
6090 continue;
6091 const CXXMethodDecl *Method = SO.second.front().Method;
6092
6093 if (!Method->isPureVirtual())
6094 continue;
6095
6096 if (!SeenPureMethods.insert(Method).second)
6097 continue;
6098
6099 Diag(Method->getLocation(), diag::note_pure_virtual_function)
6100 << Method->getDeclName() << RD->getDeclName();
6101 }
6102 }
6103
6106 PureVirtualClassDiagSet->insert(RD);
6107}
6108
6109namespace {
6110struct AbstractUsageInfo {
6111 Sema &S;
6113 CanQualType AbstractType;
6114 bool Invalid;
6115
6116 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
6117 : S(S), Record(Record),
6118 AbstractType(S.Context.getCanonicalTagType(Record)), Invalid(false) {}
6119
6120 void DiagnoseAbstractType() {
6121 if (Invalid) return;
6123 Invalid = true;
6124 }
6125
6126 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
6127};
6128
6129struct CheckAbstractUsage {
6130 AbstractUsageInfo &Info;
6131 const NamedDecl *Ctx;
6132
6133 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
6134 : Info(Info), Ctx(Ctx) {}
6135
6136 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
6137 switch (TL.getTypeLocClass()) {
6138#define ABSTRACT_TYPELOC(CLASS, PARENT)
6139#define TYPELOC(CLASS, PARENT) \
6140 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
6141#include "clang/AST/TypeLocNodes.def"
6142 }
6143 }
6144
6145 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6147 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
6148 if (!TL.getParam(I))
6149 continue;
6150
6151 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
6152 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
6153 }
6154 }
6155
6156 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6158 }
6159
6160 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6161 // Visit the type parameters from a permissive context.
6162 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
6163 TemplateArgumentLoc TAL = TL.getArgLoc(I);
6165 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
6166 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
6167 // TODO: other template argument types?
6168 }
6169 }
6170
6171 // Visit pointee types from a permissive context.
6172#define CheckPolymorphic(Type) \
6173 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
6174 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
6175 }
6181
6182 /// Handle all the types we haven't given a more specific
6183 /// implementation for above.
6184 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
6185 // Every other kind of type that we haven't called out already
6186 // that has an inner type is either (1) sugar or (2) contains that
6187 // inner type in some way as a subobject.
6188 if (TypeLoc Next = TL.getNextTypeLoc())
6189 return Visit(Next, Sel);
6190
6191 // If there's no inner type and we're in a permissive context,
6192 // don't diagnose.
6193 if (Sel == Sema::AbstractNone) return;
6194
6195 // Check whether the type matches the abstract type.
6196 QualType T = TL.getType();
6197 if (T->isArrayType()) {
6199 T = Info.S.Context.getBaseElementType(T);
6200 }
6201 CanQualType CT = T->getCanonicalTypeUnqualified();
6202 if (CT != Info.AbstractType) return;
6203
6204 // It matched; do some magic.
6205 // FIXME: These should be at most warnings. See P0929R2, CWG1640, CWG1646.
6206 if (Sel == Sema::AbstractArrayType) {
6207 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
6208 << T << TL.getSourceRange();
6209 } else {
6210 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
6211 << Sel << T << TL.getSourceRange();
6212 }
6213 Info.DiagnoseAbstractType();
6214 }
6215};
6216
6217void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
6219 CheckAbstractUsage(*this, D).Visit(TL, Sel);
6220}
6221
6222}
6223
6224/// Check for invalid uses of an abstract type in a function declaration.
6225static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6226 FunctionDecl *FD) {
6227 // Only definitions are required to refer to complete and
6228 // non-abstract types.
6230 return;
6231
6232 // For safety's sake, just ignore it if we don't have type source
6233 // information. This should never happen for non-implicit methods,
6234 // but...
6235 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6236 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractNone);
6237}
6238
6239/// Check for invalid uses of an abstract type in a variable0 declaration.
6240static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6241 VarDecl *VD) {
6242 // No need to do the check on definitions, which require that
6243 // the type is complete.
6245 return;
6246
6247 Info.CheckType(VD, VD->getTypeSourceInfo()->getTypeLoc(),
6249}
6250
6251/// Check for invalid uses of an abstract type within a class definition.
6252static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6253 CXXRecordDecl *RD) {
6254 for (auto *D : RD->decls()) {
6255 if (D->isImplicit()) continue;
6256
6257 // Step through friends to the befriended declaration.
6258 if (auto *FD = dyn_cast<FriendDecl>(D)) {
6259 D = FD->getFriendDecl();
6260 if (!D) continue;
6261 }
6262
6263 // Functions and function templates.
6264 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6265 CheckAbstractClassUsage(Info, FD);
6266 } else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) {
6267 CheckAbstractClassUsage(Info, FTD->getTemplatedDecl());
6268
6269 // Fields and static variables.
6270 } else if (auto *FD = dyn_cast<FieldDecl>(D)) {
6271 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6272 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
6273 } else if (auto *VD = dyn_cast<VarDecl>(D)) {
6274 CheckAbstractClassUsage(Info, VD);
6275 } else if (auto *VTD = dyn_cast<VarTemplateDecl>(D)) {
6276 CheckAbstractClassUsage(Info, VTD->getTemplatedDecl());
6277
6278 // Nested classes and class templates.
6279 } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
6280 CheckAbstractClassUsage(Info, RD);
6281 } else if (auto *CTD = dyn_cast<ClassTemplateDecl>(D)) {
6282 CheckAbstractClassUsage(Info, CTD->getTemplatedDecl());
6283 }
6284 }
6285}
6286
6288 Attr *ClassAttr = getDLLAttr(Class);
6289 if (!ClassAttr)
6290 return;
6291
6292 assert(ClassAttr->getKind() == attr::DLLExport);
6293
6294 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6295
6297 // Don't go any further if this is just an explicit instantiation
6298 // declaration.
6299 return;
6300
6301 // Add a context note to explain how we got to any diagnostics produced below.
6302 struct MarkingClassDllexported {
6303 Sema &S;
6304 MarkingClassDllexported(Sema &S, CXXRecordDecl *Class,
6305 SourceLocation AttrLoc)
6306 : S(S) {
6309 Ctx.PointOfInstantiation = AttrLoc;
6310 Ctx.Entity = Class;
6312 }
6313 ~MarkingClassDllexported() {
6315 }
6316 } MarkingDllexportedContext(S, Class, ClassAttr->getLocation());
6317
6318 if (S.Context.getTargetInfo().getTriple().isOSCygMing())
6319 S.MarkVTableUsed(Class->getLocation(), Class, true);
6320
6321 for (Decl *Member : Class->decls()) {
6322 // Skip members that were not marked exported.
6323 if (!Member->hasAttr<DLLExportAttr>())
6324 continue;
6325
6326 // Defined static variables that are members of an exported base
6327 // class must be marked export too.
6328 auto *VD = dyn_cast<VarDecl>(Member);
6329 if (VD && VD->getStorageClass() == SC_Static &&
6331 S.MarkVariableReferenced(VD->getLocation(), VD);
6332
6333 auto *MD = dyn_cast<CXXMethodDecl>(Member);
6334 if (!MD)
6335 continue;
6336
6337 if (MD->isUserProvided()) {
6338 // Instantiate non-default class member functions ...
6339
6340 // .. except for certain kinds of template specializations.
6341 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
6342 continue;
6343
6344 // If this is an MS ABI dllexport default constructor, instantiate any
6345 // default arguments.
6347 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6348 if (CD && CD->isDefaultConstructor() && TSK == TSK_Undeclared) {
6350 CD->getAttr<DLLExportAttr>()->getLocation(), CD);
6351 }
6352 }
6353
6354 S.MarkFunctionReferenced(Class->getLocation(), MD);
6355
6356 // The function will be passed to the consumer when its definition is
6357 // encountered.
6358 } else if (MD->isExplicitlyDefaulted()) {
6359 // Synthesize and instantiate explicitly defaulted methods.
6360 S.MarkFunctionReferenced(Class->getLocation(), MD);
6361
6363 // Except for explicit instantiation defs, we will not see the
6364 // definition again later, so pass it to the consumer now.
6366 }
6367 } else if (!MD->isTrivial() ||
6368 MD->isCopyAssignmentOperator() ||
6369 MD->isMoveAssignmentOperator()) {
6370 // Synthesize and instantiate non-trivial implicit methods, and the copy
6371 // and move assignment operators. The latter are exported even if they
6372 // are trivial, because the address of an operator can be taken and
6373 // should compare equal across libraries.
6374 S.MarkFunctionReferenced(Class->getLocation(), MD);
6375
6376 // There is no later point when we will see the definition of this
6377 // function, so pass it to the consumer now.
6379 }
6380 }
6381}
6382
6384 CXXRecordDecl *Class) {
6385 // Only the MS ABI has default constructor closures, so we don't need to do
6386 // this semantic checking anywhere else.
6388 return;
6389
6390 CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
6391 for (Decl *Member : Class->decls()) {
6392 // Look for exported default constructors.
6393 auto *CD = dyn_cast<CXXConstructorDecl>(Member);
6394 if (!CD || !CD->isDefaultConstructor())
6395 continue;
6396 auto *Attr = CD->getAttr<DLLExportAttr>();
6397 if (!Attr)
6398 continue;
6399
6400 // If the class is non-dependent, mark the default arguments as ODR-used so
6401 // that we can properly codegen the constructor closure.
6402 if (!Class->isDependentContext()) {
6405 }
6406
6407 if (LastExportedDefaultCtor) {
6408 S.Diag(LastExportedDefaultCtor->getLocation(),
6409 diag::err_attribute_dll_ambiguous_default_ctor)
6410 << Class;
6411 S.Diag(CD->getLocation(), diag::note_entity_declared_at)
6412 << CD->getDeclName();
6413 return;
6414 }
6415 LastExportedDefaultCtor = CD;
6416 }
6417}
6418
6420 CXXRecordDecl *Class) {
6421 bool ErrorReported = false;
6422 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6423 ClassTemplateDecl *TD) {
6424 if (ErrorReported)
6425 return;
6426 S.Diag(TD->getLocation(),
6427 diag::err_cuda_device_builtin_surftex_cls_template)
6428 << /*surface*/ 0 << TD;
6429 ErrorReported = true;
6430 };
6431
6432 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6433 if (!TD) {
6434 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6435 if (!SD) {
6436 S.Diag(Class->getLocation(),
6437 diag::err_cuda_device_builtin_surftex_ref_decl)
6438 << /*surface*/ 0 << Class;
6439 S.Diag(Class->getLocation(),
6440 diag::note_cuda_device_builtin_surftex_should_be_template_class)
6441 << Class;
6442 return;
6443 }
6444 TD = SD->getSpecializedTemplate();
6445 }
6446
6448 unsigned N = Params->size();
6449
6450 if (N != 2) {
6451 reportIllegalClassTemplate(S, TD);
6452 S.Diag(TD->getLocation(),
6453 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6454 << TD << 2;
6455 }
6456 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6457 reportIllegalClassTemplate(S, TD);
6458 S.Diag(TD->getLocation(),
6459 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6460 << TD << /*1st*/ 0 << /*type*/ 0;
6461 }
6462 if (N > 1) {
6463 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6464 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6465 reportIllegalClassTemplate(S, TD);
6466 S.Diag(TD->getLocation(),
6467 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6468 << TD << /*2nd*/ 1 << /*integer*/ 1;
6469 }
6470 }
6471}
6472
6474 CXXRecordDecl *Class) {
6475 bool ErrorReported = false;
6476 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6477 ClassTemplateDecl *TD) {
6478 if (ErrorReported)
6479 return;
6480 S.Diag(TD->getLocation(),
6481 diag::err_cuda_device_builtin_surftex_cls_template)
6482 << /*texture*/ 1 << TD;
6483 ErrorReported = true;
6484 };
6485
6486 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6487 if (!TD) {
6488 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6489 if (!SD) {
6490 S.Diag(Class->getLocation(),
6491 diag::err_cuda_device_builtin_surftex_ref_decl)
6492 << /*texture*/ 1 << Class;
6493 S.Diag(Class->getLocation(),
6494 diag::note_cuda_device_builtin_surftex_should_be_template_class)
6495 << Class;
6496 return;
6497 }
6498 TD = SD->getSpecializedTemplate();
6499 }
6500
6502 unsigned N = Params->size();
6503
6504 if (N != 3) {
6505 reportIllegalClassTemplate(S, TD);
6506 S.Diag(TD->getLocation(),
6507 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6508 << TD << 3;
6509 }
6510 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6511 reportIllegalClassTemplate(S, TD);
6512 S.Diag(TD->getLocation(),
6513 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6514 << TD << /*1st*/ 0 << /*type*/ 0;
6515 }
6516 if (N > 1) {
6517 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6518 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6519 reportIllegalClassTemplate(S, TD);
6520 S.Diag(TD->getLocation(),
6521 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6522 << TD << /*2nd*/ 1 << /*integer*/ 1;
6523 }
6524 }
6525 if (N > 2) {
6526 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2));
6527 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6528 reportIllegalClassTemplate(S, TD);
6529 S.Diag(TD->getLocation(),
6530 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6531 << TD << /*3rd*/ 2 << /*integer*/ 1;
6532 }
6533 }
6534}
6535
6537 // Mark any compiler-generated routines with the implicit code_seg attribute.
6538 for (auto *Method : Class->methods()) {
6539 if (Method->isUserProvided())
6540 continue;
6541 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
6542 Method->addAttr(A);
6543 }
6544}
6545
6547 Attr *ClassAttr = getDLLAttr(Class);
6548
6549 // MSVC inherits DLL attributes to partial class template specializations.
6550 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) {
6551 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
6552 if (Attr *TemplateAttr =
6553 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
6554 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
6555 A->setInherited(true);
6556 ClassAttr = A;
6557 }
6558 }
6559 }
6560
6561 if (!ClassAttr)
6562 return;
6563
6564 // MSVC allows imported or exported template classes that have UniqueExternal
6565 // linkage. This occurs when the template class has been instantiated with
6566 // a template parameter which itself has internal linkage.
6567 // We drop the attribute to avoid exporting or importing any members.
6568 if ((Context.getTargetInfo().getCXXABI().isMicrosoft() ||
6569 Context.getTargetInfo().getTriple().isPS()) &&
6570 (!Class->isExternallyVisible() && Class->hasExternalFormalLinkage())) {
6571 Class->dropAttrs<DLLExportAttr, DLLImportAttr>();
6572 return;
6573 }
6574
6575 if (!Class->isExternallyVisible()) {
6576 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
6577 << Class << ClassAttr;
6578 return;
6579 }
6580
6581 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6582 !ClassAttr->isInherited()) {
6583 // Diagnose dll attributes on members of class with dll attribute.
6584 for (Decl *Member : Class->decls()) {
6586 continue;
6587 InheritableAttr *MemberAttr = getDLLAttr(Member);
6588 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
6589 continue;
6590
6591 Diag(MemberAttr->getLocation(),
6592 diag::err_attribute_dll_member_of_dll_class)
6593 << MemberAttr << ClassAttr;
6594 Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
6595 Member->setInvalidDecl();
6596 }
6597 }
6598
6599 if (Class->getDescribedClassTemplate())
6600 // Don't inherit dll attribute until the template is instantiated.
6601 return;
6602
6603 // The class is either imported or exported.
6604 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
6605
6606 // Check if this was a dllimport attribute propagated from a derived class to
6607 // a base class template specialization. We don't apply these attributes to
6608 // static data members.
6609 const bool PropagatedImport =
6610 !ClassExported &&
6611 cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
6612
6613 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6614
6615 // Ignore explicit dllexport on explicit class template instantiation
6616 // declarations, except in MinGW mode.
6617 if (ClassExported && !ClassAttr->isInherited() &&
6619 !Context.getTargetInfo().getTriple().isOSCygMing()) {
6620 if (auto *DEA = Class->getAttr<DLLExportAttr>()) {
6621 Class->addAttr(DLLExportOnDeclAttr::Create(Context, DEA->getLoc()));
6622 Class->dropAttr<DLLExportAttr>();
6623 }
6624 return;
6625 }
6626
6627 // Force declaration of implicit members so they can inherit the attribute.
6629
6630 // Inherited constructors are created lazily; force their creation now so the
6631 // loop below can propagate the DLL attribute to them.
6632 if (ClassExported && getLangOpts().DllExportInlines) {
6634 for (Decl *D : Class->decls())
6635 if (auto *S = dyn_cast<ConstructorUsingShadowDecl>(D))
6636 Shadows.push_back(S);
6637 for (ConstructorUsingShadowDecl *S : Shadows) {
6638 CXXConstructorDecl *BC = dyn_cast<CXXConstructorDecl>(S->getTargetDecl());
6639 if (!BC || BC->isDeleted())
6640 continue;
6641 // Skip constructors whose requires clause is not satisfied.
6642 // Normally overload resolution filters these, but we are bypassing
6643 // it to eagerly create inherited constructors for dllexport.
6644 if (BC->getTrailingRequiresClause()) {
6645 ConstraintSatisfaction Satisfaction;
6646 if (CheckFunctionConstraints(BC, Satisfaction) ||
6647 !Satisfaction.IsSatisfied)
6648 continue;
6649 }
6650 findInheritingConstructor(Class->getLocation(), BC, S);
6651 }
6652 }
6653
6654 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
6655 // seem to be true in practice?
6656
6657 for (Decl *Member : Class->decls()) {
6658 if (Member->hasAttr<ExcludeFromExplicitInstantiationAttr>())
6659 continue;
6660
6661 VarDecl *VD = dyn_cast<VarDecl>(Member);
6662 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
6663
6664 // Only methods and static fields inherit the attributes.
6665 if (!VD && !MD)
6666 continue;
6667
6668 if (MD) {
6669 // Don't process deleted methods.
6670 if (MD->isDeleted())
6671 continue;
6672
6673 if (ClassExported && getLangOpts().DllExportInlines) {
6674 CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(MD);
6675 if (CD && CD->getInheritedConstructor()) {
6676 // Inherited constructors already had their base constructor's
6677 // constraints checked before creation via
6678 // findInheritingConstructor, so only ABI-compatibility checks
6679 // are needed here.
6680 //
6681 // Don't export inherited constructors whose parameters prevent
6682 // ABI-compatible forwarding. When canEmitDelegateCallArgs (in
6683 // CodeGen) returns false, Clang inlines the constructor body
6684 // instead of emitting a forwarding thunk, producing code that
6685 // is not ABI-compatible with MSVC. Suppress the export and warn
6686 // so the user gets a linker error rather than a silent runtime
6687 // mismatch.
6688 if (CD->isVariadic()) {
6689 Diag(CD->getLocation(),
6690 diag::warn_dllexport_inherited_ctor_unsupported)
6691 << /*variadic=*/0;
6692 continue;
6693 }
6694 if (Context.getTargetInfo()
6695 .getCXXABI()
6696 .areArgsDestroyedLeftToRightInCallee()) {
6697 bool HasCalleeCleanupParam = false;
6698 for (const ParmVarDecl *P : CD->parameters())
6699 if (P->needsDestruction(Context)) {
6700 HasCalleeCleanupParam = true;
6701 break;
6702 }
6703 if (HasCalleeCleanupParam) {
6704 Diag(CD->getLocation(),
6705 diag::warn_dllexport_inherited_ctor_unsupported)
6706 << /*callee-cleanup=*/1;
6707 continue;
6708 }
6709 }
6710 } else if (MD->getTrailingRequiresClause()) {
6711 // Don't export methods whose requires clause is not satisfied.
6712 // For class template specializations, member constraints may
6713 // depend on template arguments and an unsatisfied constraint
6714 // means the member should not be available in this
6715 // specialization.
6716 ConstraintSatisfaction Satisfaction;
6717 if (CheckFunctionConstraints(MD, Satisfaction) ||
6718 !Satisfaction.IsSatisfied)
6719 continue;
6720 }
6721 }
6722
6723 if (MD->isInlined()) {
6724 // MinGW does not import or export inline methods. But do it for
6725 // template instantiations and inherited constructors (which are
6726 // marked inline but must be exported to match MSVC behavior).
6727 if (!Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6730 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6731 !CD || !CD->getInheritedConstructor())
6732 continue;
6733 }
6734
6735 // MSVC versions before 2015 don't export the move assignment operators
6736 // and move constructor, so don't attempt to import/export them if
6737 // we have a definition.
6738 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
6739 if ((MD->isMoveAssignmentOperator() ||
6740 (Ctor && Ctor->isMoveConstructor())) &&
6741 getLangOpts().isCompatibleWithMSVC() &&
6742 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
6743 continue;
6744
6745 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
6746 // operator is exported anyway.
6747 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6748 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
6749 continue;
6750 }
6751 }
6752
6753 // Don't apply dllimport attributes to static data members of class template
6754 // instantiations when the attribute is propagated from a derived class.
6755 if (VD && PropagatedImport)
6756 continue;
6757
6759 continue;
6760
6761 if (!getDLLAttr(Member)) {
6762 InheritableAttr *NewAttr = nullptr;
6763
6764 // Do not export/import inline function when -fno-dllexport-inlines is
6765 // passed. But add attribute for later local static var check.
6766 if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
6769 if (ClassExported) {
6770 NewAttr = ::new (getASTContext())
6771 DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);
6772 } else {
6773 NewAttr = ::new (getASTContext())
6774 DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);
6775 }
6776 } else {
6777 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6778 }
6779
6780 NewAttr->setInherited(true);
6781 Member->addAttr(NewAttr);
6782
6783 if (MD) {
6784 // Propagate DLLAttr to friend re-declarations of MD that have already
6785 // been constructed.
6786 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
6787 FD = FD->getPreviousDecl()) {
6789 continue;
6790 assert(!getDLLAttr(FD) &&
6791 "friend re-decl should not already have a DLLAttr");
6792 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6793 NewAttr->setInherited(true);
6794 FD->addAttr(NewAttr);
6795 }
6796 }
6797 }
6798 }
6799
6800 if (ClassExported)
6801 DelayedDllExportClasses.push_back(Class);
6802}
6803
6805 CXXRecordDecl *Class, Attr *ClassAttr,
6806 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
6807 if (getDLLAttr(
6808 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
6809 // If the base class template has a DLL attribute, don't try to change it.
6810 return;
6811 }
6812
6813 auto TSK = BaseTemplateSpec->getSpecializationKind();
6814 if (!getDLLAttr(BaseTemplateSpec) &&
6816 TSK == TSK_ImplicitInstantiation)) {
6817 // The template hasn't been instantiated yet (or it has, but only as an
6818 // explicit instantiation declaration or implicit instantiation, which means
6819 // we haven't codegenned any members yet), so propagate the attribute.
6820 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6821 NewAttr->setInherited(true);
6822 BaseTemplateSpec->addAttr(NewAttr);
6823
6824 // If this was an import, mark that we propagated it from a derived class to
6825 // a base class template specialization.
6826 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
6827 ImportAttr->setPropagatedToBaseTemplate();
6828
6829 // If the template is already instantiated, checkDLLAttributeRedeclaration()
6830 // needs to be run again to work see the new attribute. Otherwise this will
6831 // get run whenever the template is instantiated.
6832 if (TSK != TSK_Undeclared)
6833 checkClassLevelDLLAttribute(BaseTemplateSpec);
6834
6835 return;
6836 }
6837
6838 if (getDLLAttr(BaseTemplateSpec)) {
6839 // The template has already been specialized or instantiated with an
6840 // attribute, explicitly or through propagation. We should not try to change
6841 // it.
6842 return;
6843 }
6844
6845 // The template was previously instantiated or explicitly specialized without
6846 // a dll attribute, It's too late for us to add an attribute, so warn that
6847 // this is unsupported.
6848 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
6849 << BaseTemplateSpec->isExplicitSpecialization();
6850 Diag(ClassAttr->getLocation(), diag::note_attribute);
6851 if (BaseTemplateSpec->isExplicitSpecialization()) {
6852 Diag(BaseTemplateSpec->getLocation(),
6853 diag::note_template_class_explicit_specialization_was_here)
6854 << BaseTemplateSpec;
6855 } else {
6856 Diag(BaseTemplateSpec->getPointOfInstantiation(),
6857 diag::note_template_class_instantiation_was_here)
6858 << BaseTemplateSpec;
6859 }
6860}
6861
6864 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
6865 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
6866 if (Ctor->isDefaultConstructor())
6868
6869 if (Ctor->isCopyConstructor())
6871
6872 if (Ctor->isMoveConstructor())
6874 }
6875
6876 if (MD->isCopyAssignmentOperator())
6878
6879 if (MD->isMoveAssignmentOperator())
6881
6882 if (isa<CXXDestructorDecl>(FD))
6884 }
6885
6886 switch (FD->getDeclName().getCXXOverloadedOperator()) {
6887 case OO_EqualEqual:
6889
6890 case OO_ExclaimEqual:
6892
6893 case OO_Spaceship:
6894 // No point allowing this if <=> doesn't exist in the current language mode.
6895 if (!getLangOpts().CPlusPlus20)
6896 break;
6898
6899 case OO_Less:
6900 case OO_LessEqual:
6901 case OO_Greater:
6902 case OO_GreaterEqual:
6903 // No point allowing this if <=> doesn't exist in the current language mode.
6904 if (!getLangOpts().CPlusPlus20)
6905 break;
6907
6908 default:
6909 break;
6910 }
6911
6912 // Not defaultable.
6913 return DefaultedFunctionKind();
6914}
6915
6916namespace {
6917/// RAII object to restore the floating-point (FP) features active at the time
6918/// a defaulted function was declared. This ensures that the synthesized body
6919/// of the function respects the FP pragmas (e.g., #pragma STDC FENV_ACCESS)
6920/// that were in effect when the function was explicitly defaulted.
6921struct DefaultedFunctionFPFeaturesRAII {
6922 Sema::FPFeaturesStateRAII SavedFPFeatures;
6923 DefaultedFunctionFPFeaturesRAII(Sema &S, FunctionDecl *FD)
6924 : SavedFPFeatures(S) {
6925 auto *Info = FD->getDefaultedOrDeletedInfo();
6926 FPOptionsOverride FPO = Info ? Info->getFPFeatures() : FPOptionsOverride();
6928 S.FpPragmaStack.CurrentValue = FPO;
6929 }
6930
6931 ~DefaultedFunctionFPFeaturesRAII() = default;
6932};
6933} // namespace
6934
6936 SourceLocation DefaultLoc) {
6938 if (DFK.isComparison())
6939 return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison());
6940
6941 switch (DFK.asSpecialMember()) {
6945 break;
6948 break;
6951 break;
6954 break;
6957 break;
6960 break;
6962 llvm_unreachable("Invalid special member.");
6963 }
6964}
6965
6966/// Determine whether a type is permitted to be passed or returned in
6967/// registers, per C++ [class.temporary]p3.
6970 if (D->isDependentType() || D->isInvalidDecl())
6971 return false;
6972
6973 // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
6974 // The PS4 platform ABI follows the behavior of Clang 3.2.
6976 return !D->hasNonTrivialDestructorForCall() &&
6978
6979 if (CCK == TargetInfo::CCK_MicrosoftWin64) {
6980 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
6981 bool DtorIsTrivialForCall = false;
6982
6983 // If a class has at least one eligible, trivial copy constructor, it
6984 // is passed according to the C ABI. Otherwise, it is passed indirectly.
6985 //
6986 // Note: This permits classes with non-trivial copy or move ctors to be
6987 // passed in registers, so long as they *also* have a trivial copy ctor,
6988 // which is non-conforming.
6992 CopyCtorIsTrivial = true;
6994 CopyCtorIsTrivialForCall = true;
6995 }
6996 } else {
6997 for (const CXXConstructorDecl *CD : D->ctors()) {
6998 if (CD->isCopyConstructor() && !CD->isDeleted() &&
6999 !CD->isIneligibleOrNotSelected()) {
7000 if (CD->isTrivial())
7001 CopyCtorIsTrivial = true;
7002 if (CD->isTrivialForCall())
7003 CopyCtorIsTrivialForCall = true;
7004 }
7005 }
7006 }
7007
7008 if (D->needsImplicitDestructor()) {
7009 if (!D->defaultedDestructorIsDeleted() &&
7011 DtorIsTrivialForCall = true;
7012 } else if (const auto *DD = D->getDestructor()) {
7013 if (!DD->isDeleted() && DD->isTrivialForCall())
7014 DtorIsTrivialForCall = true;
7015 }
7016
7017 // If the copy ctor and dtor are both trivial-for-calls, pass direct.
7018 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
7019 return true;
7020
7021 // If a class has a destructor, we'd really like to pass it indirectly
7022 // because it allows us to elide copies. Unfortunately, MSVC makes that
7023 // impossible for small types, which it will pass in a single register or
7024 // stack slot. Most objects with dtors are large-ish, so handle that early.
7025 // We can't call out all large objects as being indirect because there are
7026 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
7027 // how we pass large POD types.
7028
7029 // Note: This permits small classes with nontrivial destructors to be
7030 // passed in registers, which is non-conforming.
7031 bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
7032 uint64_t TypeSize = isAArch64 ? 128 : 64;
7033
7034 if (CopyCtorIsTrivial && S.getASTContext().getTypeSize(
7035 S.Context.getCanonicalTagType(D)) <= TypeSize)
7036 return true;
7037 return false;
7038 }
7039
7040 // Per C++ [class.temporary]p3, the relevant condition is:
7041 // each copy constructor, move constructor, and destructor of X is
7042 // either trivial or deleted, and X has at least one non-deleted copy
7043 // or move constructor
7044 bool HasNonDeletedCopyOrMove = false;
7045
7049 return false;
7050 HasNonDeletedCopyOrMove = true;
7051 }
7052
7053 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
7056 return false;
7057 HasNonDeletedCopyOrMove = true;
7058 }
7059
7062 return false;
7063
7064 for (const CXXMethodDecl *MD : D->methods()) {
7065 if (MD->isDeleted() || MD->isIneligibleOrNotSelected())
7066 continue;
7067
7068 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
7069 if (CD && CD->isCopyOrMoveConstructor())
7070 HasNonDeletedCopyOrMove = true;
7071 else if (!isa<CXXDestructorDecl>(MD))
7072 continue;
7073
7074 if (!MD->isTrivialForCall())
7075 return false;
7076 }
7077
7078 return HasNonDeletedCopyOrMove;
7079}
7080
7081/// Report an error regarding overriding, along with any relevant
7082/// overridden methods.
7083///
7084/// \param DiagID the primary error to report.
7085/// \param MD the overriding method.
7086static bool
7087ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD,
7088 llvm::function_ref<bool(const CXXMethodDecl *)> Report) {
7089 bool IssuedDiagnostic = false;
7090 for (const CXXMethodDecl *O : MD->overridden_methods()) {
7091 if (Report(O)) {
7092 if (!IssuedDiagnostic) {
7093 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7094 IssuedDiagnostic = true;
7095 }
7096 S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
7097 }
7098 }
7099 return IssuedDiagnostic;
7100}
7101
7103 if (!Record)
7104 return;
7105
7106 if (Record->isAbstract() && !Record->isInvalidDecl()) {
7107 AbstractUsageInfo Info(*this, Record);
7109 }
7110
7111 // If this is not an aggregate type and has no user-declared constructor,
7112 // complain about any non-static data members of reference or const scalar
7113 // type, since they will never get initializers.
7114 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
7115 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
7116 !Record->isLambda()) {
7117 bool Complained = false;
7118 for (const auto *F : Record->fields()) {
7119 if (F->hasInClassInitializer() || F->isUnnamedBitField())
7120 continue;
7121
7122 if (F->getType()->isReferenceType() ||
7123 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
7124 if (!Complained) {
7125 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
7126 << Record->getTagKind() << Record;
7127 Complained = true;
7128 }
7129
7130 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
7131 << F->getType()->isReferenceType()
7132 << F->getDeclName();
7133 }
7134 }
7135 }
7136
7137 if (Record->getIdentifier()) {
7138 // C++ [class.mem]p13:
7139 // If T is the name of a class, then each of the following shall have a
7140 // name different from T:
7141 // - every member of every anonymous union that is a member of class T.
7142 //
7143 // C++ [class.mem]p14:
7144 // In addition, if class T has a user-declared constructor (12.1), every
7145 // non-static data member of class T shall have a name different from T.
7146 for (const NamedDecl *Element : Record->lookup(Record->getDeclName())) {
7147 const NamedDecl *D = Element->getUnderlyingDecl();
7148 // Invalid IndirectFieldDecls have already been diagnosed with
7149 // err_anonymous_record_member_redecl in
7150 // SemaDecl.cpp:CheckAnonMemberRedeclaration.
7152 Record->hasUserDeclaredConstructor()) ||
7153 (isa<IndirectFieldDecl>(D) && !D->isInvalidDecl())) {
7154 Diag(Element->getLocation(), diag::err_member_name_of_class)
7155 << D->getDeclName();
7156 break;
7157 }
7158 }
7159 }
7160
7161 // Warn if the class has virtual methods but non-virtual public destructor.
7162 if (Record->isPolymorphic() && !Record->isDependentType()) {
7163 CXXDestructorDecl *dtor = Record->getDestructor();
7164 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
7165 !Record->hasAttr<FinalAttr>())
7166 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
7167 diag::warn_non_virtual_dtor)
7168 << Context.getCanonicalTagType(Record);
7169 }
7170
7171 if (Record->isAbstract()) {
7172 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
7173 Diag(Record->getLocation(), diag::warn_abstract_final_class)
7174 << FA->isSpelledAsSealed();
7176 }
7177 }
7178
7179 // Warn if the class has a final destructor but is not itself marked final.
7180 if (!Record->hasAttr<FinalAttr>()) {
7181 if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
7182 if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
7183 Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class)
7184 << FA->isSpelledAsSealed()
7186 getLocForEndOfToken(Record->getLocation()),
7187 (FA->isSpelledAsSealed() ? " sealed" : " final"));
7188 Diag(Record->getLocation(),
7189 diag::note_final_dtor_non_final_class_silence)
7190 << Context.getCanonicalTagType(Record) << FA->isSpelledAsSealed();
7191 }
7192 }
7193 }
7194
7195 // See if trivial_abi has to be dropped.
7196 if (Record->hasAttr<TrivialABIAttr>())
7198
7199 // Set HasTrivialSpecialMemberForCall if the record has attribute
7200 // "trivial_abi".
7201 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
7202
7203 if (HasTrivialABI)
7204 Record->setHasTrivialSpecialMemberForCall();
7205
7206 // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=).
7207 // We check these last because they can depend on the properties of the
7208 // primary comparison functions (==, <=>).
7209 llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons;
7210
7211 // Perform checks that can't be done until we know all the properties of a
7212 // member function (whether it's defaulted, deleted, virtual, overriding,
7213 // ...).
7214 auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) {
7215 // A static function cannot override anything.
7216 if (MD->getStorageClass() == SC_Static) {
7217 if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD,
7218 [](const CXXMethodDecl *) { return true; }))
7219 return;
7220 }
7221
7222 // A deleted function cannot override a non-deleted function and vice
7223 // versa.
7224 if (ReportOverrides(*this,
7225 MD->isDeleted() ? diag::err_deleted_override
7226 : diag::err_non_deleted_override,
7227 MD, [&](const CXXMethodDecl *V) {
7228 return MD->isDeleted() != V->isDeleted();
7229 })) {
7230 if (MD->isDefaulted() && MD->isDeleted())
7231 // Explain why this defaulted function was deleted.
7233 return;
7234 }
7235
7236 // A consteval function cannot override a non-consteval function and vice
7237 // versa.
7238 if (ReportOverrides(*this,
7239 MD->isConsteval() ? diag::err_consteval_override
7240 : diag::err_non_consteval_override,
7241 MD, [&](const CXXMethodDecl *V) {
7242 return MD->isConsteval() != V->isConsteval();
7243 })) {
7244 if (MD->isDefaulted() && MD->isDeleted())
7245 // Explain why this defaulted function was deleted.
7247 return;
7248 }
7249 };
7250
7251 auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool {
7252 if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted())
7253 return false;
7254
7258 DefaultedSecondaryComparisons.push_back(FD);
7259 return true;
7260 }
7261
7263 return false;
7264 };
7265
7266 if (!Record->isInvalidDecl() &&
7267 Record->hasAttr<VTablePointerAuthenticationAttr>())
7269
7270 auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
7271 // Check whether the explicitly-defaulted members are valid.
7272 bool Incomplete = CheckForDefaultedFunction(M);
7273
7274 // Skip the rest of the checks for a member of a dependent class.
7275 if (Record->isDependentType())
7276 return;
7277
7278 // For an explicitly defaulted or deleted special member, we defer
7279 // determining triviality until the class is complete. That time is now!
7281 if (!M->isImplicit() && !M->isUserProvided()) {
7282 if (CSM != CXXSpecialMemberKind::Invalid) {
7283 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
7284 // Inform the class that we've finished declaring this member.
7285 Record->finishedDefaultedOrDeletedMember(M);
7286 M->setTrivialForCall(
7287 HasTrivialABI ||
7290 Record->setTrivialForCallFlags(M);
7291 }
7292 }
7293
7294 // Set triviality for the purpose of calls if this is a user-provided
7295 // copy/move constructor or destructor.
7299 M->isUserProvided()) {
7300 M->setTrivialForCall(HasTrivialABI);
7301 Record->setTrivialForCallFlags(M);
7302 }
7303
7304 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
7305 M->hasAttr<DLLExportAttr>()) {
7306 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
7307 M->isTrivial() &&
7311 M->dropAttr<DLLExportAttr>();
7312
7313 if (M->hasAttr<DLLExportAttr>()) {
7314 // Define after any fields with in-class initializers have been parsed.
7316 }
7317 }
7318
7319 bool EffectivelyConstexprDestructor = true;
7320 // Avoid triggering vtable instantiation due to a dtor that is not
7321 // "effectively constexpr" for better compatibility.
7322 // See https://github.com/llvm/llvm-project/issues/102293 for more info.
7323 if (isa<CXXDestructorDecl>(M)) {
7324 llvm::SmallDenseSet<QualType> Visited;
7325 auto Check = [&Visited](QualType T, auto &&Check) -> bool {
7326 if (!Visited.insert(T->getCanonicalTypeUnqualified()).second)
7327 return false;
7328 const CXXRecordDecl *RD =
7329 T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
7330 if (!RD || !RD->isCompleteDefinition())
7331 return true;
7332
7333 if (!RD->hasConstexprDestructor())
7334 return false;
7335
7336 for (const CXXBaseSpecifier &B : RD->bases())
7337 if (!Check(B.getType(), Check))
7338 return false;
7339 for (const FieldDecl *FD : RD->fields())
7340 if (!Check(FD->getType(), Check))
7341 return false;
7342 return true;
7343 };
7344 EffectivelyConstexprDestructor =
7345 Check(Context.getCanonicalTagType(Record), Check);
7346 }
7347
7348 // Define defaulted constexpr virtual functions that override a base class
7349 // function right away.
7350 // FIXME: We can defer doing this until the vtable is marked as used.
7351 if (CSM != CXXSpecialMemberKind::Invalid && !M->isDeleted() &&
7352 M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods() &&
7353 EffectivelyConstexprDestructor)
7354 DefineDefaultedFunction(*this, M, M->getLocation());
7355
7356 if (!Incomplete)
7357 CheckCompletedMemberFunction(M);
7358 };
7359
7360 // Check the destructor before any other member function. We need to
7361 // determine whether it's trivial in order to determine whether the claas
7362 // type is a literal type, which is a prerequisite for determining whether
7363 // other special member functions are valid and whether they're implicitly
7364 // 'constexpr'.
7365 if (CXXDestructorDecl *Dtor = Record->getDestructor())
7366 CompleteMemberFunction(Dtor);
7367
7368 bool HasMethodWithOverrideControl = false,
7369 HasOverridingMethodWithoutOverrideControl = false;
7370 for (auto *D : Record->decls()) {
7371 if (auto *M = dyn_cast<CXXMethodDecl>(D)) {
7372 // FIXME: We could do this check for dependent types with non-dependent
7373 // bases.
7374 if (!Record->isDependentType()) {
7375 // See if a method overloads virtual methods in a base
7376 // class without overriding any.
7377 if (!M->isStatic())
7379
7380 if (M->hasAttr<OverrideAttr>()) {
7381 HasMethodWithOverrideControl = true;
7382 } else if (M->size_overridden_methods() > 0) {
7383 HasOverridingMethodWithoutOverrideControl = true;
7384 } else {
7385 // Warn on newly-declared virtual methods in `final` classes
7386 if (M->isVirtualAsWritten() && Record->isEffectivelyFinal()) {
7387 Diag(M->getLocation(), diag::warn_unnecessary_virtual_specifier)
7388 << M;
7389 }
7390 }
7391 }
7392
7393 if (!isa<CXXDestructorDecl>(M))
7394 CompleteMemberFunction(M);
7395 } else if (auto *F = dyn_cast<FriendDecl>(D)) {
7396 CheckForDefaultedFunction(
7397 dyn_cast_or_null<FunctionDecl>(F->getFriendDecl()));
7398 }
7399 }
7400
7401 if (HasOverridingMethodWithoutOverrideControl) {
7402 bool HasInconsistentOverrideControl = HasMethodWithOverrideControl;
7403 for (auto *M : Record->methods())
7404 DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl);
7405 }
7406
7407 // Check the defaulted secondary comparisons after any other member functions.
7408 for (FunctionDecl *FD : DefaultedSecondaryComparisons) {
7410
7411 // If this is a member function, we deferred checking it until now.
7412 if (auto *MD = dyn_cast<CXXMethodDecl>(FD))
7413 CheckCompletedMemberFunction(MD);
7414 }
7415
7416 // {ms,gcc}_struct is a request to change ABI rules to either follow
7417 // Microsoft or Itanium C++ ABI. However, even if these attributes are
7418 // present, we do not layout classes following foreign ABI rules, but
7419 // instead enter a special "compatibility mode", which only changes
7420 // alignments of fundamental types and layout of bit fields.
7421 // Check whether this class uses any C++ features that are implemented
7422 // completely differently in the requested ABI, and if so, emit a
7423 // diagnostic. That diagnostic defaults to an error, but we allow
7424 // projects to map it down to a warning (or ignore it). It's a fairly
7425 // common practice among users of the ms_struct pragma to
7426 // mass-annotate headers, sweeping up a bunch of types that the
7427 // project doesn't really rely on MSVC-compatible layout for. We must
7428 // therefore support "ms_struct except for C++ stuff" as a secondary
7429 // ABI.
7430 // Don't emit this diagnostic if the feature was enabled as a
7431 // language option (as opposed to via a pragma or attribute), as
7432 // the option -mms-bitfields otherwise essentially makes it impossible
7433 // to build C++ code, unless this diagnostic is turned off.
7434 if (Context.getLangOpts().getLayoutCompatibility() ==
7436 Record->isMsStruct(Context) != Context.defaultsToMsStruct() &&
7437 (Record->isPolymorphic() || Record->getNumBases())) {
7438 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
7439 }
7440
7443
7444 bool ClangABICompat4 =
7445 Context.getLangOpts().isCompatibleWith(LangOptions::ClangABI::Ver4);
7447 Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
7448 bool CanPass = canPassInRegisters(*this, Record, CCK);
7449
7450 // Do not change ArgPassingRestrictions if it has already been set to
7451 // RecordArgPassingKind::CanNeverPassInRegs.
7452 if (Record->getArgPassingRestrictions() !=
7454 Record->setArgPassingRestrictions(
7457
7458 // If canPassInRegisters returns true despite the record having a non-trivial
7459 // destructor, the record is destructed in the callee. This happens only when
7460 // the record or one of its subobjects has a field annotated with trivial_abi
7461 // or a field qualified with ObjC __strong/__weak.
7462 if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
7463 Record->setParamDestroyedInCallee(true);
7464 else if (Record->hasNonTrivialDestructor())
7465 Record->setParamDestroyedInCallee(CanPass);
7466
7467 if (getLangOpts().ForceEmitVTables) {
7468 // If we want to emit all the vtables, we need to mark it as used. This
7469 // is especially required for cases like vtable assumption loads.
7470 MarkVTableUsed(Record->getInnerLocStart(), Record);
7471 }
7472
7473 if (getLangOpts().CUDA) {
7474 if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>())
7476 else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>())
7478 }
7479
7480 llvm::SmallDenseMap<OverloadedOperatorKind,
7482 TypeAwareDecls{{OO_New, {}},
7483 {OO_Array_New, {}},
7484 {OO_Delete, {}},
7485 {OO_Array_New, {}}};
7486 for (auto *D : Record->decls()) {
7487 const FunctionDecl *FnDecl = D->getAsFunction();
7488 if (!FnDecl || !FnDecl->isTypeAwareOperatorNewOrDelete())
7489 continue;
7490 assert(FnDecl->getDeclName().isAnyOperatorNewOrDelete());
7491 TypeAwareDecls[FnDecl->getOverloadedOperator()].push_back(FnDecl);
7492 }
7493 auto CheckMismatchedTypeAwareAllocators =
7494 [this, &TypeAwareDecls, Record](OverloadedOperatorKind NewKind,
7495 OverloadedOperatorKind DeleteKind) {
7496 auto &NewDecls = TypeAwareDecls[NewKind];
7497 auto &DeleteDecls = TypeAwareDecls[DeleteKind];
7498 if (NewDecls.empty() == DeleteDecls.empty())
7499 return;
7500 DeclarationName FoundOperator =
7501 Context.DeclarationNames.getCXXOperatorName(
7502 NewDecls.empty() ? DeleteKind : NewKind);
7503 DeclarationName MissingOperator =
7504 Context.DeclarationNames.getCXXOperatorName(
7505 NewDecls.empty() ? NewKind : DeleteKind);
7506 Diag(Record->getLocation(),
7507 diag::err_type_aware_allocator_missing_matching_operator)
7508 << FoundOperator << Context.getCanonicalTagType(Record)
7509 << MissingOperator;
7510 for (auto MD : NewDecls)
7511 Diag(MD->getLocation(),
7512 diag::note_unmatched_type_aware_allocator_declared)
7513 << MD;
7514 for (auto MD : DeleteDecls)
7515 Diag(MD->getLocation(),
7516 diag::note_unmatched_type_aware_allocator_declared)
7517 << MD;
7518 };
7519 CheckMismatchedTypeAwareAllocators(OO_New, OO_Delete);
7520 CheckMismatchedTypeAwareAllocators(OO_Array_New, OO_Array_Delete);
7521}
7522
7523/// Look up the special member function that would be called by a special
7524/// member function for a subobject of class type.
7525///
7526/// \param Class The class type of the subobject.
7527/// \param CSM The kind of special member function.
7528/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
7529/// \param ConstRHS True if this is a copy operation with a const object
7530/// on its RHS, that is, if the argument to the outer special member
7531/// function is 'const' and this is not a field marked 'mutable'.
7534 CXXSpecialMemberKind CSM, unsigned FieldQuals,
7535 bool ConstRHS) {
7536 unsigned LHSQuals = 0;
7539 LHSQuals = FieldQuals;
7540
7541 unsigned RHSQuals = FieldQuals;
7544 RHSQuals = 0;
7545 else if (ConstRHS)
7546 RHSQuals |= Qualifiers::Const;
7547
7548 return S.LookupSpecialMember(Class, CSM,
7549 RHSQuals & Qualifiers::Const,
7550 RHSQuals & Qualifiers::Volatile,
7551 false,
7552 LHSQuals & Qualifiers::Const,
7553 LHSQuals & Qualifiers::Volatile);
7554}
7555
7557 Sema &S;
7558 SourceLocation UseLoc;
7559
7560 /// A mapping from the base classes through which the constructor was
7561 /// inherited to the using shadow declaration in that base class (or a null
7562 /// pointer if the constructor was declared in that base class).
7563 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
7564 InheritedFromBases;
7565
7566public:
7569 : S(S), UseLoc(UseLoc) {
7570 bool DiagnosedMultipleConstructedBases = false;
7571 CXXRecordDecl *ConstructedBase = nullptr;
7572 BaseUsingDecl *ConstructedBaseIntroducer = nullptr;
7573
7574 // Find the set of such base class subobjects and check that there's a
7575 // unique constructed subobject.
7576 for (auto *D : Shadow->redecls()) {
7577 auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
7578 auto *DNominatedBase = DShadow->getNominatedBaseClass();
7579 auto *DConstructedBase = DShadow->getConstructedBaseClass();
7580
7581 InheritedFromBases.insert(
7582 std::make_pair(DNominatedBase->getCanonicalDecl(),
7583 DShadow->getNominatedBaseClassShadowDecl()));
7584 if (DShadow->constructsVirtualBase())
7585 InheritedFromBases.insert(
7586 std::make_pair(DConstructedBase->getCanonicalDecl(),
7587 DShadow->getConstructedBaseClassShadowDecl()));
7588 else
7589 assert(DNominatedBase == DConstructedBase);
7590
7591 // [class.inhctor.init]p2:
7592 // If the constructor was inherited from multiple base class subobjects
7593 // of type B, the program is ill-formed.
7594 if (!ConstructedBase) {
7595 ConstructedBase = DConstructedBase;
7596 ConstructedBaseIntroducer = D->getIntroducer();
7597 } else if (ConstructedBase != DConstructedBase &&
7598 !Shadow->isInvalidDecl()) {
7599 if (!DiagnosedMultipleConstructedBases) {
7600 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
7601 << Shadow->getTargetDecl();
7602 S.Diag(ConstructedBaseIntroducer->getLocation(),
7603 diag::note_ambiguous_inherited_constructor_using)
7604 << ConstructedBase;
7605 DiagnosedMultipleConstructedBases = true;
7606 }
7607 S.Diag(D->getIntroducer()->getLocation(),
7608 diag::note_ambiguous_inherited_constructor_using)
7609 << DConstructedBase;
7610 }
7611 }
7612
7613 if (DiagnosedMultipleConstructedBases)
7614 Shadow->setInvalidDecl();
7615 }
7616
7617 /// Find the constructor to use for inherited construction of a base class,
7618 /// and whether that base class constructor inherits the constructor from a
7619 /// virtual base class (in which case it won't actually invoke it).
7620 std::pair<CXXConstructorDecl *, bool>
7622 auto It = InheritedFromBases.find(Base->getCanonicalDecl());
7623 if (It == InheritedFromBases.end())
7624 return std::make_pair(nullptr, false);
7625
7626 // This is an intermediary class.
7627 if (It->second)
7628 return std::make_pair(
7629 S.findInheritingConstructor(UseLoc, Ctor, It->second),
7630 It->second->constructsVirtualBase());
7631
7632 // This is the base class from which the constructor was inherited.
7633 return std::make_pair(Ctor, false);
7634 }
7635};
7636
7637/// Is the special member function which would be selected to perform the
7638/// specified operation on the specified class type a constexpr constructor?
7640 Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, unsigned Quals,
7641 bool ConstRHS, CXXConstructorDecl *InheritedCtor = nullptr,
7642 Sema::InheritedConstructorInfo *Inherited = nullptr) {
7643 // Suppress duplicate constraint checking here, in case a constraint check
7644 // caused us to decide to do this. Any truely recursive checks will get
7645 // caught during these checks anyway.
7647
7648 // If we're inheriting a constructor, see if we need to call it for this base
7649 // class.
7650 if (InheritedCtor) {
7652 auto BaseCtor =
7653 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
7654 if (BaseCtor)
7655 return BaseCtor->isConstexpr();
7656 }
7657
7659 return ClassDecl->hasConstexprDefaultConstructor();
7661 return ClassDecl->hasConstexprDestructor();
7662
7664 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
7665 if (!SMOR.getMethod())
7666 // A constructor we wouldn't select can't be "involved in initializing"
7667 // anything.
7668 return true;
7669 return SMOR.getMethod()->isConstexpr();
7670}
7671
7672/// Determine whether the specified special member function would be constexpr
7673/// if it were implicitly defined.
7675 Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, bool ConstArg,
7676 CXXConstructorDecl *InheritedCtor = nullptr,
7677 Sema::InheritedConstructorInfo *Inherited = nullptr) {
7678 if (!S.getLangOpts().CPlusPlus11)
7679 return false;
7680
7681 // C++11 [dcl.constexpr]p4:
7682 // In the definition of a constexpr constructor [...]
7683 bool Ctor = true;
7684 switch (CSM) {
7686 if (Inherited)
7687 break;
7688 // Since default constructor lookup is essentially trivial (and cannot
7689 // involve, for instance, template instantiation), we compute whether a
7690 // defaulted default constructor is constexpr directly within CXXRecordDecl.
7691 //
7692 // This is important for performance; we need to know whether the default
7693 // constructor is constexpr to determine whether the type is a literal type.
7694 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
7695
7698 // For copy or move constructors, we need to perform overload resolution.
7699 break;
7700
7703 if (!S.getLangOpts().CPlusPlus14)
7704 return false;
7705 // In C++1y, we need to perform overload resolution.
7706 Ctor = false;
7707 break;
7708
7710 return ClassDecl->defaultedDestructorIsConstexpr();
7711
7713 return false;
7714 }
7715
7716 // -- if the class is a non-empty union, or for each non-empty anonymous
7717 // union member of a non-union class, exactly one non-static data member
7718 // shall be initialized; [DR1359]
7719 //
7720 // If we squint, this is guaranteed, since exactly one non-static data member
7721 // will be initialized (if the constructor isn't deleted), we just don't know
7722 // which one.
7723 if (Ctor && ClassDecl->isUnion())
7725 ? ClassDecl->hasInClassInitializer() ||
7726 !ClassDecl->hasVariantMembers()
7727 : true;
7728
7729 // -- the class shall not have any virtual base classes;
7730 if (!S.getLangOpts().CPlusPlus26 && Ctor && ClassDecl->getNumVBases())
7731 return false;
7732
7733 // C++1y [class.copy]p26:
7734 // -- [the class] is a literal type, and
7735 if (!S.getLangOpts().CPlusPlus23 && !Ctor && !ClassDecl->isLiteral())
7736 return false;
7737
7738 // -- every constructor involved in initializing [...] base class
7739 // sub-objects shall be a constexpr constructor;
7740 // -- the assignment operator selected to copy/move each direct base
7741 // class is a constexpr function, and
7742 if (!S.getLangOpts().CPlusPlus23) {
7743 for (const auto &B : ClassDecl->bases()) {
7744 auto *BaseClassDecl = B.getType()->getAsCXXRecordDecl();
7745 if (!BaseClassDecl)
7746 continue;
7747 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
7748 InheritedCtor, Inherited))
7749 return false;
7750 }
7751 }
7752
7753 // -- every constructor involved in initializing non-static data members
7754 // [...] shall be a constexpr constructor;
7755 // -- every non-static data member and base class sub-object shall be
7756 // initialized
7757 // -- for each non-static data member of X that is of class type (or array
7758 // thereof), the assignment operator selected to copy/move that member is
7759 // a constexpr function
7760 if (!S.getLangOpts().CPlusPlus23) {
7761 for (const auto *F : ClassDecl->fields()) {
7762 if (F->isInvalidDecl())
7763 continue;
7765 F->hasInClassInitializer())
7766 continue;
7767 QualType BaseType = S.Context.getBaseElementType(F->getType());
7768 if (const RecordType *RecordTy = BaseType->getAsCanonical<RecordType>()) {
7769 auto *FieldRecDecl =
7770 cast<CXXRecordDecl>(RecordTy->getDecl())->getDefinitionOrSelf();
7771 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
7772 BaseType.getCVRQualifiers(),
7773 ConstArg && !F->isMutable()))
7774 return false;
7775 } else if (CSM == CXXSpecialMemberKind::DefaultConstructor) {
7776 return false;
7777 }
7778 }
7779 }
7780
7781 // All OK, it's constexpr!
7782 return true;
7783}
7784
7785namespace {
7786/// RAII object to register a defaulted function as having its exception
7787/// specification computed.
7788struct ComputingExceptionSpec {
7789 Sema &S;
7790
7791 ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc)
7792 : S(S) {
7793 Sema::CodeSynthesisContext Ctx;
7795 Ctx.PointOfInstantiation = Loc;
7796 Ctx.Entity = FD;
7798 }
7799 ~ComputingExceptionSpec() {
7801 }
7802};
7803}
7804
7805static Sema::ImplicitExceptionSpecification
7806ComputeDefaultedSpecialMemberExceptionSpec(Sema &S, SourceLocation Loc,
7807 CXXMethodDecl *MD,
7809 Sema::InheritedConstructorInfo *ICI);
7810
7811static Sema::ImplicitExceptionSpecification
7812ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
7813 FunctionDecl *FD,
7815
7816static Sema::ImplicitExceptionSpecification
7818 auto DFK = S.getDefaultedFunctionKind(FD);
7819 if (DFK.isSpecialMember())
7821 S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr);
7822 if (DFK.isComparison())
7824 DFK.asComparison());
7825
7826 auto *CD = cast<CXXConstructorDecl>(FD);
7827 assert(CD->getInheritedConstructor() &&
7828 "only defaulted functions and inherited constructors have implicit "
7829 "exception specs");
7831 S, Loc, CD->getInheritedConstructor().getShadowDecl());
7834}
7835
7837 CXXMethodDecl *MD) {
7839
7840 // Build an exception specification pointing back at this member.
7842 EPI.ExceptionSpec.SourceDecl = MD;
7843
7844 // Set the calling convention to the default for C++ instance methods.
7846 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
7847 /*IsCXXMethod=*/true));
7848 return EPI;
7849}
7850
7852 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
7854 return;
7855
7856 // Evaluate the exception specification.
7857 auto IES = computeImplicitExceptionSpec(*this, Loc, FD);
7858 auto ESI = IES.getExceptionSpec();
7859
7860 // Update the type of the special member to use it.
7861 UpdateExceptionSpec(FD, ESI);
7862}
7863
7865 assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted");
7866
7868 if (!DefKind) {
7869 assert(FD->getDeclContext()->isDependentContext());
7870 return;
7871 }
7872
7873 if (DefKind.isComparison()) {
7874 auto PT = FD->getParamDecl(0)->getType();
7875 if (const CXXRecordDecl *RD =
7876 PT.getNonReferenceType()->getAsCXXRecordDecl()) {
7877 for (FieldDecl *Field : RD->fields()) {
7878 UnusedPrivateFields.remove(Field);
7879 }
7880 }
7881 }
7882
7883 if (DefKind.isSpecialMember()
7885 DefKind.asSpecialMember(),
7886 FD->getDefaultLoc())
7888 FD->setInvalidDecl();
7889}
7890
7893 SourceLocation DefaultLoc) {
7894 CXXRecordDecl *RD = MD->getParent();
7895
7897 "not an explicitly-defaulted special member");
7898
7899 // Defer all checking for special members of a dependent type.
7900 if (RD->isDependentType())
7901 return false;
7902
7903 // Whether this was the first-declared instance of the constructor.
7904 // This affects whether we implicitly add an exception spec and constexpr.
7905 bool First = MD == MD->getCanonicalDecl();
7906
7907 bool HadError = false;
7908
7909 // C++11 [dcl.fct.def.default]p1:
7910 // A function that is explicitly defaulted shall
7911 // -- be a special member function [...] (checked elsewhere),
7912 // -- have the same type (except for ref-qualifiers, and except that a
7913 // copy operation can take a non-const reference) as an implicit
7914 // declaration, and
7915 // -- not have default arguments.
7916 // C++2a changes the second bullet to instead delete the function if it's
7917 // defaulted on its first declaration, unless it's "an assignment operator,
7918 // and its return type differs or its parameter type is not a reference".
7919 bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First;
7920 bool ShouldDeleteForTypeMismatch = false;
7921 unsigned ExpectedParams = 1;
7924 ExpectedParams = 0;
7925 if (MD->getNumExplicitParams() != ExpectedParams) {
7926 // This checks for default arguments: a copy or move constructor with a
7927 // default argument is classified as a default constructor, and assignment
7928 // operations and destructors can't have default arguments.
7929 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
7930 << CSM << MD->getSourceRange();
7931 HadError = true;
7932 } else if (MD->isVariadic()) {
7933 if (DeleteOnTypeMismatch)
7934 ShouldDeleteForTypeMismatch = true;
7935 else {
7936 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
7937 << CSM << MD->getSourceRange();
7938 HadError = true;
7939 }
7940 }
7941
7943
7944 bool CanHaveConstParam = false;
7946 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
7948 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
7949
7950 QualType ReturnType = Context.VoidTy;
7953 // Check for return type matching.
7954 ReturnType = Type->getReturnType();
7956
7957 QualType DeclType =
7959 /*Qualifier=*/std::nullopt, RD, /*OwnsTag=*/false);
7960 DeclType = Context.getAddrSpaceQualType(
7961 DeclType, ThisType.getQualifiers().getAddressSpace());
7962 QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
7963
7964 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
7965 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
7967 << ExpectedReturnType;
7968 HadError = true;
7969 }
7970
7971 // A defaulted special member cannot have cv-qualifiers.
7972 if (ThisType.isConstQualified() || ThisType.isVolatileQualified()) {
7973 if (DeleteOnTypeMismatch)
7974 ShouldDeleteForTypeMismatch = true;
7975 else {
7976 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
7978 << getLangOpts().CPlusPlus14;
7979 HadError = true;
7980 }
7981 }
7982 // [C++23][dcl.fct.def.default]/p2.2
7983 // if F2 has an implicit object parameter of type “reference to C”,
7984 // F1 may be an explicit object member function whose explicit object
7985 // parameter is of (possibly different) type “reference to C”,
7986 // in which case the type of F1 would differ from the type of F2
7987 // in that the type of F1 has an additional parameter;
7988 QualType ExplicitObjectParameter = MD->isExplicitObjectMemberFunction()
7989 ? MD->getParamDecl(0)->getType()
7990 : QualType();
7991 if (!ExplicitObjectParameter.isNull() &&
7992 (!ExplicitObjectParameter->isReferenceType() ||
7993 !Context.hasSameType(ExplicitObjectParameter.getNonReferenceType(),
7994 Context.getCanonicalTagType(RD)))) {
7995 if (DeleteOnTypeMismatch)
7996 ShouldDeleteForTypeMismatch = true;
7997 else {
7998 Diag(MD->getLocation(),
7999 diag::err_defaulted_special_member_explicit_object_mismatch)
8000 << (CSM == CXXSpecialMemberKind::MoveAssignment) << RD
8001 << MD->getSourceRange();
8002 HadError = true;
8003 }
8004 }
8005 }
8006
8007 // Check for parameter type matching.
8009 ExpectedParams
8010 ? Type->getParamType(MD->isExplicitObjectMemberFunction() ? 1 : 0)
8011 : QualType();
8012 bool HasConstParam = false;
8013 if (ExpectedParams && ArgType->isReferenceType()) {
8014 // Argument must be reference to possibly-const T.
8015 QualType ReferentType = ArgType->getPointeeType();
8016 HasConstParam = ReferentType.isConstQualified();
8017
8018 if (ReferentType.isVolatileQualified()) {
8019 if (DeleteOnTypeMismatch)
8020 ShouldDeleteForTypeMismatch = true;
8021 else {
8022 Diag(MD->getLocation(),
8023 diag::err_defaulted_special_member_volatile_param)
8024 << CSM;
8025 HadError = true;
8026 }
8027 }
8028
8029 if (HasConstParam && !CanHaveConstParam) {
8030 if (DeleteOnTypeMismatch)
8031 ShouldDeleteForTypeMismatch = true;
8032 else if (CSM == CXXSpecialMemberKind::CopyConstructor ||
8034 Diag(MD->getLocation(),
8035 diag::err_defaulted_special_member_copy_const_param)
8037 // FIXME: Explain why this special member can't be const.
8038 HadError = true;
8039 } else {
8040 Diag(MD->getLocation(),
8041 diag::err_defaulted_special_member_move_const_param)
8043 HadError = true;
8044 }
8045 }
8046 } else if (ExpectedParams) {
8047 // A copy assignment operator can take its argument by value, but a
8048 // defaulted one cannot.
8050 "unexpected non-ref argument");
8051 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
8052 HadError = true;
8053 }
8054
8055 // C++11 [dcl.fct.def.default]p2:
8056 // An explicitly-defaulted function may be declared constexpr only if it
8057 // would have been implicitly declared as constexpr,
8058 // Do not apply this rule to members of class templates, since core issue 1358
8059 // makes such functions always instantiate to constexpr functions. For
8060 // functions which cannot be constexpr (for non-constructors in C++11 and for
8061 // destructors in C++14 and C++17), this is checked elsewhere.
8062 //
8063 // FIXME: This should not apply if the member is deleted.
8064 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
8065 HasConstParam);
8066
8067 // C++14 [dcl.constexpr]p6 (CWG DR647/CWG DR1358):
8068 // If the instantiated template specialization of a constexpr function
8069 // template or member function of a class template would fail to satisfy
8070 // the requirements for a constexpr function or constexpr constructor, that
8071 // specialization is still a constexpr function or constexpr constructor,
8072 // even though a call to such a function cannot appear in a constant
8073 // expression.
8074 if (MD->isTemplateInstantiation() && MD->isConstexpr())
8075 Constexpr = true;
8076
8077 if ((getLangOpts().CPlusPlus20 ||
8079 : isa<CXXConstructorDecl>(MD))) &&
8080 MD->isConstexpr() && !Constexpr &&
8082 if (!MD->isConsteval() && RD->getNumVBases()) {
8083 Diag(MD->getBeginLoc(),
8084 diag::err_incorrect_defaulted_constexpr_with_vb)
8085 << CSM;
8086 for (const auto &I : RD->vbases())
8087 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here);
8088 } else {
8089 Diag(MD->getBeginLoc(), diag::err_incorrect_defaulted_constexpr)
8090 << CSM << MD->isConsteval();
8091 }
8092 HadError = true;
8093 // FIXME: Explain why the special member can't be constexpr.
8094 }
8095 if (First) {
8096 // C++2a [dcl.fct.def.default]p3:
8097 // If a function is explicitly defaulted on its first declaration, it is
8098 // implicitly considered to be constexpr if the implicit declaration
8099 // would be.
8104
8105 if (!Type->hasExceptionSpec()) {
8106 // C++2a [except.spec]p3:
8107 // If a declaration of a function does not have a noexcept-specifier
8108 // [and] is defaulted on its first declaration, [...] the exception
8109 // specification is as specified below
8110 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
8112 EPI.ExceptionSpec.SourceDecl = MD;
8113 MD->setType(
8114 Context.getFunctionType(ReturnType, Type->getParamTypes(), EPI));
8115 }
8116 }
8117
8118 if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
8119 if (First) {
8120 SetDeclDeleted(MD, MD->getLocation());
8121 if (!inTemplateInstantiation() && !HadError) {
8122 Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
8123 if (ShouldDeleteForTypeMismatch) {
8124 Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
8125 } else if (ShouldDeleteSpecialMember(MD, CSM, nullptr,
8126 /*Diagnose*/ true) &&
8127 DefaultLoc.isValid()) {
8128 Diag(DefaultLoc, diag::note_replace_equals_default_to_delete)
8129 << FixItHint::CreateReplacement(DefaultLoc, "delete");
8130 }
8131 }
8132 if (ShouldDeleteForTypeMismatch && !HadError) {
8133 Diag(MD->getLocation(),
8134 diag::warn_cxx17_compat_defaulted_method_type_mismatch)
8135 << CSM;
8136 }
8137 } else {
8138 // C++11 [dcl.fct.def.default]p4:
8139 // [For a] user-provided explicitly-defaulted function [...] if such a
8140 // function is implicitly defined as deleted, the program is ill-formed.
8141 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
8142 assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
8143 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
8144 HadError = true;
8145 }
8146 }
8147
8148 return HadError;
8149}
8150
8151namespace {
8152/// Helper class for building and checking a defaulted comparison.
8153///
8154/// Defaulted functions are built in two phases:
8155///
8156/// * First, the set of operations that the function will perform are
8157/// identified, and some of them are checked. If any of the checked
8158/// operations is invalid in certain ways, the comparison function is
8159/// defined as deleted and no body is built.
8160/// * Then, if the function is not defined as deleted, the body is built.
8161///
8162/// This is accomplished by performing two visitation steps over the eventual
8163/// body of the function.
8164template<typename Derived, typename ResultList, typename Result,
8165 typename Subobject>
8166class DefaultedComparisonVisitor {
8167public:
8168 using DefaultedComparisonKind = Sema::DefaultedComparisonKind;
8169
8170 DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8171 DefaultedComparisonKind DCK)
8172 : S(S), RD(RD), FD(FD), DCK(DCK) {
8173 if (auto *Info = FD->getDefaultedOrDeletedInfo()) {
8174 // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an
8175 // UnresolvedSet to avoid this copy.
8176 Fns.assign(Info->getUnqualifiedLookups().begin(),
8177 Info->getUnqualifiedLookups().end());
8178 }
8179 }
8180
8181 ResultList visit() {
8182 // The type of an lvalue naming a parameter of this function.
8183 QualType ParamLvalType =
8185
8186 ResultList Results;
8187
8188 switch (DCK) {
8189 case DefaultedComparisonKind::None:
8190 llvm_unreachable("not a defaulted comparison");
8191
8192 case DefaultedComparisonKind::Equal:
8193 case DefaultedComparisonKind::ThreeWay:
8194 getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers());
8195 return Results;
8196
8197 case DefaultedComparisonKind::NotEqual:
8198 case DefaultedComparisonKind::Relational:
8199 Results.add(getDerived().visitExpandedSubobject(
8200 ParamLvalType, getDerived().getCompleteObject()));
8201 return Results;
8202 }
8203 llvm_unreachable("");
8204 }
8205
8206protected:
8207 Derived &getDerived() { return static_cast<Derived&>(*this); }
8208
8209 /// Visit the expanded list of subobjects of the given type, as specified in
8210 /// C++2a [class.compare.default].
8211 ///
8212 /// \return \c true if the ResultList object said we're done, \c false if not.
8213 bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record,
8214 Qualifiers Quals) {
8215 // C++2a [class.compare.default]p4:
8216 // The direct base class subobjects of C
8217 for (CXXBaseSpecifier &Base : Record->bases())
8218 if (Results.add(getDerived().visitSubobject(
8219 S.Context.getQualifiedType(Base.getType(), Quals),
8220 getDerived().getBase(&Base))))
8221 return true;
8222
8223 // followed by the non-static data members of C
8224 for (FieldDecl *Field : Record->fields()) {
8225 // C++23 [class.bit]p2:
8226 // Unnamed bit-fields are not members ...
8227 if (Field->isUnnamedBitField())
8228 continue;
8229 // Recursively expand anonymous structs.
8230 if (Field->isAnonymousStructOrUnion()) {
8231 if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(),
8232 Quals))
8233 return true;
8234 continue;
8235 }
8236
8237 // Figure out the type of an lvalue denoting this field.
8238 Qualifiers FieldQuals = Quals;
8239 if (Field->isMutable())
8240 FieldQuals.removeConst();
8241 QualType FieldType =
8242 S.Context.getQualifiedType(Field->getType(), FieldQuals);
8243
8244 if (Results.add(getDerived().visitSubobject(
8245 FieldType, getDerived().getField(Field))))
8246 return true;
8247 }
8248
8249 // form a list of subobjects.
8250 return false;
8251 }
8252
8253 Result visitSubobject(QualType Type, Subobject Subobj) {
8254 // In that list, any subobject of array type is recursively expanded
8255 const ArrayType *AT = S.Context.getAsArrayType(Type);
8256 if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT))
8257 return getDerived().visitSubobjectArray(CAT->getElementType(),
8258 CAT->getSize(), Subobj);
8259 return getDerived().visitExpandedSubobject(Type, Subobj);
8260 }
8261
8262 Result visitSubobjectArray(QualType Type, const llvm::APInt &Size,
8263 Subobject Subobj) {
8264 return getDerived().visitSubobject(Type, Subobj);
8265 }
8266
8267protected:
8268 Sema &S;
8269 CXXRecordDecl *RD;
8270 FunctionDecl *FD;
8271 DefaultedComparisonKind DCK;
8272 UnresolvedSet<16> Fns;
8273};
8274
8275/// Information about a defaulted comparison, as determined by
8276/// DefaultedComparisonAnalyzer.
8277struct DefaultedComparisonInfo {
8278 bool Deleted = false;
8279 bool Constexpr = true;
8280 ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering;
8281
8282 static DefaultedComparisonInfo deleted() {
8283 DefaultedComparisonInfo Deleted;
8284 Deleted.Deleted = true;
8285 return Deleted;
8286 }
8287
8288 bool add(const DefaultedComparisonInfo &R) {
8289 Deleted |= R.Deleted;
8290 Constexpr &= R.Constexpr;
8291 Category = commonComparisonType(Category, R.Category);
8292 return Deleted;
8293 }
8294};
8295
8296/// An element in the expanded list of subobjects of a defaulted comparison, as
8297/// specified in C++2a [class.compare.default]p4.
8298struct DefaultedComparisonSubobject {
8299 enum { CompleteObject, Member, Base } Kind;
8300 NamedDecl *Decl;
8301 SourceLocation Loc;
8302};
8303
8304/// A visitor over the notional body of a defaulted comparison that determines
8305/// whether that body would be deleted or constexpr.
8306class DefaultedComparisonAnalyzer
8307 : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer,
8308 DefaultedComparisonInfo,
8309 DefaultedComparisonInfo,
8310 DefaultedComparisonSubobject> {
8311public:
8312 enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr };
8313
8314private:
8315 DiagnosticKind Diagnose;
8316
8317public:
8318 using Base = DefaultedComparisonVisitor;
8319 using Result = DefaultedComparisonInfo;
8320 using Subobject = DefaultedComparisonSubobject;
8321
8322 friend Base;
8323
8324 DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8325 DefaultedComparisonKind DCK,
8326 DiagnosticKind Diagnose = NoDiagnostics)
8327 : Base(S, RD, FD, DCK), Diagnose(Diagnose) {}
8328
8329 Result visit() {
8330 if ((DCK == DefaultedComparisonKind::Equal ||
8331 DCK == DefaultedComparisonKind::ThreeWay) &&
8332 RD->hasVariantMembers()) {
8333 // C++2a [class.compare.default]p2 [P2002R0]:
8334 // A defaulted comparison operator function for class C is defined as
8335 // deleted if [...] C has variant members.
8336 if (Diagnose == ExplainDeleted) {
8337 S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union)
8338 << FD << RD->isUnion() << RD;
8339 }
8340 return Result::deleted();
8341 }
8342
8343 return Base::visit();
8344 }
8345
8346private:
8347 Subobject getCompleteObject() {
8348 return Subobject{Subobject::CompleteObject, RD, FD->getLocation()};
8349 }
8350
8351 Subobject getBase(CXXBaseSpecifier *Base) {
8352 return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(),
8353 Base->getBaseTypeLoc()};
8354 }
8355
8356 Subobject getField(FieldDecl *Field) {
8357 return Subobject{Subobject::Member, Field, Field->getLocation()};
8358 }
8359
8360 Result visitExpandedSubobject(QualType Type, Subobject Subobj) {
8361 // C++2a [class.compare.default]p2 [P2002R0]:
8362 // A defaulted <=> or == operator function for class C is defined as
8363 // deleted if any non-static data member of C is of reference type
8364 if (Type->isReferenceType()) {
8365 if (Diagnose == ExplainDeleted) {
8366 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member)
8367 << FD << RD;
8368 }
8369 return Result::deleted();
8370 }
8371
8372 // [...] Let xi be an lvalue denoting the ith element [...]
8373 OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue);
8374 Expr *Args[] = {&Xi, &Xi};
8375
8376 // All operators start by trying to apply that same operator recursively.
8378 assert(OO != OO_None && "not an overloaded operator!");
8379 return visitBinaryOperator(OO, Args, Subobj);
8380 }
8381
8382 Result
8383 visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args,
8384 Subobject Subobj,
8385 OverloadCandidateSet *SpaceshipCandidates = nullptr) {
8386 // Note that there is no need to consider rewritten candidates here if
8387 // we've already found there is no viable 'operator<=>' candidate (and are
8388 // considering synthesizing a '<=>' from '==' and '<').
8389 OverloadCandidateSet CandidateSet(
8391 OverloadCandidateSet::OperatorRewriteInfo(
8392 OO, FD->getLocation(),
8393 /*AllowRewrittenCandidates=*/!SpaceshipCandidates));
8394
8395 /// C++2a [class.compare.default]p1 [P2002R0]:
8396 /// [...] the defaulted function itself is never a candidate for overload
8397 /// resolution [...]
8398 CandidateSet.exclude(FD);
8399
8400 if (Args[0]->getType()->isOverloadableType())
8401 S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args);
8402 else
8403 // FIXME: We determine whether this is a valid expression by checking to
8404 // see if there's a viable builtin operator candidate for it. That isn't
8405 // really what the rules ask us to do, but should give the right results.
8406 S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet);
8407
8408 Result R;
8409
8411 switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) {
8412 case OR_Success: {
8413 // C++2a [class.compare.secondary]p2 [P2002R0]:
8414 // The operator function [...] is defined as deleted if [...] the
8415 // candidate selected by overload resolution is not a rewritten
8416 // candidate.
8417 if ((DCK == DefaultedComparisonKind::NotEqual ||
8418 DCK == DefaultedComparisonKind::Relational) &&
8419 !Best->RewriteKind) {
8420 if (Diagnose == ExplainDeleted) {
8421 if (Best->Function) {
8422 S.Diag(Best->Function->getLocation(),
8423 diag::note_defaulted_comparison_not_rewritten_callee)
8424 << FD;
8425 } else {
8426 assert(Best->Conversions.size() == 2 &&
8427 Best->Conversions[0].isUserDefined() &&
8428 "non-user-defined conversion from class to built-in "
8429 "comparison");
8430 S.Diag(Best->Conversions[0]
8431 .UserDefined.FoundConversionFunction.getDecl()
8432 ->getLocation(),
8433 diag::note_defaulted_comparison_not_rewritten_conversion)
8434 << FD;
8435 }
8436 }
8437 return Result::deleted();
8438 }
8439
8440 // Throughout C++2a [class.compare]: if overload resolution does not
8441 // result in a usable function, the candidate function is defined as
8442 // deleted. This requires that we selected an accessible function.
8443 //
8444 // Note that this only considers the access of the function when named
8445 // within the type of the subobject, and not the access path for any
8446 // derived-to-base conversion.
8447 CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl();
8448 if (ArgClass && Best->FoundDecl.getDecl() &&
8449 Best->FoundDecl.getDecl()->isCXXClassMember()) {
8450 QualType ObjectType = Subobj.Kind == Subobject::Member
8451 ? Args[0]->getType()
8454 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc,
8455 Diagnose == ExplainDeleted
8456 ? S.PDiag(diag::note_defaulted_comparison_inaccessible)
8457 << FD << Subobj.Kind << Subobj.Decl
8458 : S.PDiag()))
8459 return Result::deleted();
8460 }
8461
8462 bool NeedsDeducing =
8463 OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType();
8464
8465 if (FunctionDecl *BestFD = Best->Function) {
8466 // C++2a [class.compare.default]p3 [P2002R0]:
8467 // A defaulted comparison function is constexpr-compatible if
8468 // [...] no overlod resolution performed [...] results in a
8469 // non-constexpr function.
8470 assert(!BestFD->isDeleted() && "wrong overload resolution result");
8471 // If it's not constexpr, explain why not.
8472 if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) {
8473 if (Subobj.Kind != Subobject::CompleteObject)
8474 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr)
8475 << Subobj.Kind << Subobj.Decl;
8476 S.Diag(BestFD->getLocation(),
8477 diag::note_defaulted_comparison_not_constexpr_here);
8478 // Bail out after explaining; we don't want any more notes.
8479 return Result::deleted();
8480 }
8481 R.Constexpr &= BestFD->isConstexpr();
8482
8483 if (NeedsDeducing) {
8484 // If any callee has an undeduced return type, deduce it now.
8485 // FIXME: It's not clear how a failure here should be handled. For
8486 // now, we produce an eager diagnostic, because that is forward
8487 // compatible with most (all?) other reasonable options.
8488 if (BestFD->getReturnType()->isUndeducedType() &&
8489 S.DeduceReturnType(BestFD, FD->getLocation(),
8490 /*Diagnose=*/false)) {
8491 // Don't produce a duplicate error when asked to explain why the
8492 // comparison is deleted: we diagnosed that when initially checking
8493 // the defaulted operator.
8494 if (Diagnose == NoDiagnostics) {
8495 S.Diag(
8496 FD->getLocation(),
8497 diag::err_defaulted_comparison_cannot_deduce_undeduced_auto)
8498 << Subobj.Kind << Subobj.Decl;
8499 S.Diag(
8500 Subobj.Loc,
8501 diag::note_defaulted_comparison_cannot_deduce_undeduced_auto)
8502 << Subobj.Kind << Subobj.Decl;
8503 S.Diag(BestFD->getLocation(),
8504 diag::note_defaulted_comparison_cannot_deduce_callee)
8505 << Subobj.Kind << Subobj.Decl;
8506 }
8507 return Result::deleted();
8508 }
8510 BestFD->getCallResultType());
8511 if (!Info) {
8512 if (Diagnose == ExplainDeleted) {
8513 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce)
8514 << Subobj.Kind << Subobj.Decl
8515 << BestFD->getCallResultType().withoutLocalFastQualifiers();
8516 S.Diag(BestFD->getLocation(),
8517 diag::note_defaulted_comparison_cannot_deduce_callee)
8518 << Subobj.Kind << Subobj.Decl;
8519 }
8520 return Result::deleted();
8521 }
8522 R.Category = Info->Kind;
8523 }
8524 } else {
8525 QualType T = Best->BuiltinParamTypes[0];
8526 assert(T == Best->BuiltinParamTypes[1] &&
8527 "builtin comparison for different types?");
8528 assert(Best->BuiltinParamTypes[2].isNull() &&
8529 "invalid builtin comparison");
8530
8531 // FIXME: If the type we deduced is a vector type, we mark the
8532 // comparison as deleted because we don't yet support this.
8533 if (isa<VectorType>(T)) {
8534 if (Diagnose == ExplainDeleted) {
8535 S.Diag(FD->getLocation(),
8536 diag::note_defaulted_comparison_vector_types)
8537 << FD;
8538 S.Diag(Subobj.Decl->getLocation(), diag::note_declared_at);
8539 }
8540 return Result::deleted();
8541 }
8542
8543 if (NeedsDeducing) {
8544 std::optional<ComparisonCategoryType> Cat =
8546 assert(Cat && "no category for builtin comparison?");
8547 R.Category = *Cat;
8548 }
8549 }
8550
8551 // Note that we might be rewriting to a different operator. That call is
8552 // not considered until we come to actually build the comparison function.
8553 break;
8554 }
8555
8556 case OR_Ambiguous:
8557 if (Diagnose == ExplainDeleted) {
8558 unsigned Kind = 0;
8559 if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship)
8560 Kind = OO == OO_EqualEqual ? 1 : 2;
8561 CandidateSet.NoteCandidates(
8563 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous)
8564 << FD << Kind << Subobj.Kind << Subobj.Decl),
8565 S, OCD_AmbiguousCandidates, Args);
8566 }
8567 R = Result::deleted();
8568 break;
8569
8570 case OR_Deleted:
8571 if (Diagnose == ExplainDeleted) {
8572 if ((DCK == DefaultedComparisonKind::NotEqual ||
8573 DCK == DefaultedComparisonKind::Relational) &&
8574 !Best->RewriteKind) {
8575 S.Diag(Best->Function->getLocation(),
8576 diag::note_defaulted_comparison_not_rewritten_callee)
8577 << FD;
8578 } else {
8579 S.Diag(Subobj.Loc,
8580 diag::note_defaulted_comparison_calls_deleted)
8581 << FD << Subobj.Kind << Subobj.Decl;
8582 S.NoteDeletedFunction(Best->Function);
8583 }
8584 }
8585 R = Result::deleted();
8586 break;
8587
8589 // If there's no usable candidate, we're done unless we can rewrite a
8590 // '<=>' in terms of '==' and '<'.
8591 if (OO == OO_Spaceship &&
8593 // For any kind of comparison category return type, we need a usable
8594 // '==' and a usable '<'.
8595 if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj,
8596 &CandidateSet)))
8597 R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet));
8598 break;
8599 }
8600
8601 if (Diagnose == ExplainDeleted) {
8602 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function)
8603 << FD << (OO == OO_EqualEqual || OO == OO_ExclaimEqual)
8604 << Subobj.Kind << Subobj.Decl;
8605
8606 // For a three-way comparison, list both the candidates for the
8607 // original operator and the candidates for the synthesized operator.
8608 if (SpaceshipCandidates) {
8609 SpaceshipCandidates->NoteCandidates(
8610 S, Args,
8611 SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates,
8612 Args, FD->getLocation()));
8613 S.Diag(Subobj.Loc,
8614 diag::note_defaulted_comparison_no_viable_function_synthesized)
8615 << (OO == OO_EqualEqual ? 0 : 1);
8616 }
8617
8618 CandidateSet.NoteCandidates(
8619 S, Args,
8620 CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args,
8621 FD->getLocation()));
8622 }
8623 R = Result::deleted();
8624 break;
8625 }
8626
8627 return R;
8628 }
8629};
8630
8631/// A list of statements.
8632struct StmtListResult {
8633 bool IsInvalid = false;
8634 llvm::SmallVector<Stmt*, 16> Stmts;
8635
8636 bool add(const StmtResult &S) {
8637 IsInvalid |= S.isInvalid();
8638 if (IsInvalid)
8639 return true;
8640 Stmts.push_back(S.get());
8641 return false;
8642 }
8643};
8644
8645/// A visitor over the notional body of a defaulted comparison that synthesizes
8646/// the actual body.
8647class DefaultedComparisonSynthesizer
8648 : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer,
8649 StmtListResult, StmtResult,
8650 std::pair<ExprResult, ExprResult>> {
8651 SourceLocation Loc;
8652 unsigned ArrayDepth = 0;
8653
8654public:
8655 using Base = DefaultedComparisonVisitor;
8656 using ExprPair = std::pair<ExprResult, ExprResult>;
8657
8658 friend Base;
8659
8660 DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8661 DefaultedComparisonKind DCK,
8662 SourceLocation BodyLoc)
8663 : Base(S, RD, FD, DCK), Loc(BodyLoc) {}
8664
8665 /// Build a suitable function body for this defaulted comparison operator.
8666 StmtResult build() {
8667 Sema::CompoundScopeRAII CompoundScope(S);
8668
8669 StmtListResult Stmts = visit();
8670 if (Stmts.IsInvalid)
8671 return StmtError();
8672
8673 ExprResult RetVal;
8674 switch (DCK) {
8675 case DefaultedComparisonKind::None:
8676 llvm_unreachable("not a defaulted comparison");
8677
8678 case DefaultedComparisonKind::Equal: {
8679 // C++2a [class.eq]p3:
8680 // [...] compar[e] the corresponding elements [...] until the first
8681 // index i where xi == yi yields [...] false. If no such index exists,
8682 // V is true. Otherwise, V is false.
8683 //
8684 // Join the comparisons with '&&'s and return the result. Use a right
8685 // fold (traversing the conditions right-to-left), because that
8686 // short-circuits more naturally.
8687 auto OldStmts = std::move(Stmts.Stmts);
8688 Stmts.Stmts.clear();
8689 ExprResult CmpSoFar;
8690 // Finish a particular comparison chain.
8691 auto FinishCmp = [&] {
8692 if (Expr *Prior = CmpSoFar.get()) {
8693 // Convert the last expression to 'return ...;'
8694 if (RetVal.isUnset() && Stmts.Stmts.empty())
8695 RetVal = CmpSoFar;
8696 // Convert any prior comparison to 'if (!(...)) return false;'
8697 else if (Stmts.add(buildIfNotCondReturnFalse(Prior)))
8698 return true;
8699 CmpSoFar = ExprResult();
8700 }
8701 return false;
8702 };
8703 for (Stmt *EAsStmt : llvm::reverse(OldStmts)) {
8704 Expr *E = dyn_cast<Expr>(EAsStmt);
8705 if (!E) {
8706 // Found an array comparison.
8707 if (FinishCmp() || Stmts.add(EAsStmt))
8708 return StmtError();
8709 continue;
8710 }
8711
8712 if (CmpSoFar.isUnset()) {
8713 CmpSoFar = E;
8714 continue;
8715 }
8716 CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get());
8717 if (CmpSoFar.isInvalid())
8718 return StmtError();
8719 }
8720 if (FinishCmp())
8721 return StmtError();
8722 std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end());
8723 // If no such index exists, V is true.
8724 if (RetVal.isUnset())
8725 RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true);
8726 break;
8727 }
8728
8729 case DefaultedComparisonKind::ThreeWay: {
8730 // Per C++2a [class.spaceship]p3, as a fallback add:
8731 // return static_cast<R>(std::strong_ordering::equal);
8732 QualType StrongOrdering = S.CheckComparisonCategoryType(
8733 ComparisonCategoryType::StrongOrdering, Loc,
8734 Sema::ComparisonCategoryUsage::DefaultedOperator);
8735 if (StrongOrdering.isNull())
8736 return StmtError();
8737 VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(StrongOrdering)
8738 .getValueInfo(ComparisonCategoryResult::Equal)
8739 ->VD;
8740 RetVal = getDecl(EqualVD);
8741 if (RetVal.isInvalid())
8742 return StmtError();
8743 RetVal = buildStaticCastToR(RetVal.get());
8744 break;
8745 }
8746
8747 case DefaultedComparisonKind::NotEqual:
8748 case DefaultedComparisonKind::Relational:
8749 RetVal = cast<Expr>(Stmts.Stmts.pop_back_val());
8750 break;
8751 }
8752
8753 // Build the final return statement.
8754 if (RetVal.isInvalid())
8755 return StmtError();
8756 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get());
8757 if (ReturnStmt.isInvalid())
8758 return StmtError();
8759 Stmts.Stmts.push_back(ReturnStmt.get());
8760
8761 return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false);
8762 }
8763
8764private:
8765 ExprResult getDecl(ValueDecl *VD) {
8766 return S.BuildDeclarationNameExpr(
8767 CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD);
8768 }
8769
8770 ExprResult getParam(unsigned I) {
8771 ParmVarDecl *PD = FD->getParamDecl(I);
8772 return getDecl(PD);
8773 }
8774
8775 ExprPair getCompleteObject() {
8776 unsigned Param = 0;
8777 ExprResult LHS;
8778 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD);
8779 MD && MD->isImplicitObjectMemberFunction()) {
8780 // LHS is '*this'.
8781 LHS = S.ActOnCXXThis(Loc);
8782 if (!LHS.isInvalid())
8783 LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get());
8784 } else {
8785 LHS = getParam(Param++);
8786 }
8787 ExprResult RHS = getParam(Param++);
8788 assert(Param == FD->getNumParams());
8789 return {LHS, RHS};
8790 }
8791
8792 ExprPair getBase(CXXBaseSpecifier *Base) {
8793 ExprPair Obj = getCompleteObject();
8794 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8795 return {ExprError(), ExprError()};
8796 CXXCastPath Path = {Base};
8797 const auto CastToBase = [&](Expr *E) {
8798 QualType ToType = S.Context.getQualifiedType(
8799 Base->getType(), E->getType().getQualifiers());
8800 return S.ImpCastExprToType(E, ToType, CK_DerivedToBase, VK_LValue, &Path);
8801 };
8802 return {CastToBase(Obj.first.get()), CastToBase(Obj.second.get())};
8803 }
8804
8805 ExprPair getField(FieldDecl *Field) {
8806 ExprPair Obj = getCompleteObject();
8807 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8808 return {ExprError(), ExprError()};
8809
8810 DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess());
8811 DeclarationNameInfo NameInfo(Field->getDeclName(), Loc);
8812 return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc,
8813 CXXScopeSpec(), Field, Found, NameInfo),
8814 S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc,
8815 CXXScopeSpec(), Field, Found, NameInfo)};
8816 }
8817
8818 // FIXME: When expanding a subobject, register a note in the code synthesis
8819 // stack to say which subobject we're comparing.
8820
8821 StmtResult buildIfNotCondReturnFalse(ExprResult Cond) {
8822 if (Cond.isInvalid())
8823 return StmtError();
8824
8825 ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get());
8826 if (NotCond.isInvalid())
8827 return StmtError();
8828
8829 ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false);
8830 assert(!False.isInvalid() && "should never fail");
8831 StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get());
8832 if (ReturnFalse.isInvalid())
8833 return StmtError();
8834
8835 return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, nullptr,
8836 S.ActOnCondition(nullptr, Loc, NotCond.get(),
8837 Sema::ConditionKind::Boolean),
8838 Loc, ReturnFalse.get(), SourceLocation(), nullptr);
8839 }
8840
8841 StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size,
8842 ExprPair Subobj) {
8843 QualType SizeType = S.Context.getSizeType();
8844 Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType));
8845
8846 // Build 'size_t i$n = 0'.
8847 IdentifierInfo *IterationVarName = nullptr;
8848 {
8849 SmallString<8> Str;
8850 llvm::raw_svector_ostream OS(Str);
8851 OS << "i" << ArrayDepth;
8852 IterationVarName = &S.Context.Idents.get(OS.str());
8853 }
8854 VarDecl *IterationVar = VarDecl::Create(
8855 S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType,
8856 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None);
8857 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
8858 IterationVar->setInit(
8859 IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
8860 Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc);
8861
8862 auto IterRef = [&] {
8863 ExprResult Ref = S.BuildDeclarationNameExpr(
8864 CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc),
8865 IterationVar);
8866 assert(!Ref.isInvalid() && "can't reference our own variable?");
8867 return Ref.get();
8868 };
8869
8870 // Build 'i$n != Size'.
8871 ExprResult Cond = S.CreateBuiltinBinOp(
8872 Loc, BO_NE, IterRef(),
8873 IntegerLiteral::Create(S.Context, Size, SizeType, Loc));
8874 assert(!Cond.isInvalid() && "should never fail");
8875
8876 // Build '++i$n'.
8877 ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef());
8878 assert(!Inc.isInvalid() && "should never fail");
8879
8880 // Build 'a[i$n]' and 'b[i$n]'.
8881 auto Index = [&](ExprResult E) {
8882 if (E.isInvalid())
8883 return ExprError();
8884 return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc);
8885 };
8886 Subobj.first = Index(Subobj.first);
8887 Subobj.second = Index(Subobj.second);
8888
8889 // Compare the array elements.
8890 ++ArrayDepth;
8891 StmtResult Substmt = visitSubobject(Type, Subobj);
8892 --ArrayDepth;
8893
8894 if (Substmt.isInvalid())
8895 return StmtError();
8896
8897 // For the inner level of an 'operator==', build 'if (!cmp) return false;'.
8898 // For outer levels or for an 'operator<=>' we already have a suitable
8899 // statement that returns as necessary.
8900 if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) {
8901 assert(DCK == DefaultedComparisonKind::Equal &&
8902 "should have non-expression statement");
8903 Substmt = buildIfNotCondReturnFalse(ElemCmp);
8904 if (Substmt.isInvalid())
8905 return StmtError();
8906 }
8907
8908 // Build 'for (...) ...'
8909 return S.ActOnForStmt(Loc, Loc, Init,
8910 S.ActOnCondition(nullptr, Loc, Cond.get(),
8911 Sema::ConditionKind::Boolean),
8912 S.MakeFullDiscardedValueExpr(Inc.get()), Loc,
8913 Substmt.get());
8914 }
8915
8916 StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) {
8917 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8918 return StmtError();
8919
8922 ExprResult Op;
8923 if (Type->isOverloadableType())
8924 Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(),
8925 Obj.second.get(), /*PerformADL=*/true,
8926 /*AllowRewrittenCandidates=*/true, FD);
8927 else
8928 Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get());
8929 if (Op.isInvalid())
8930 return StmtError();
8931
8932 switch (DCK) {
8933 case DefaultedComparisonKind::None:
8934 llvm_unreachable("not a defaulted comparison");
8935
8936 case DefaultedComparisonKind::Equal:
8937 // Per C++2a [class.eq]p2, each comparison is individually contextually
8938 // converted to bool.
8939 Op = S.PerformContextuallyConvertToBool(Op.get());
8940 if (Op.isInvalid())
8941 return StmtError();
8942 return Op.get();
8943
8944 case DefaultedComparisonKind::ThreeWay: {
8945 // Per C++2a [class.spaceship]p3, form:
8946 // if (R cmp = static_cast<R>(op); cmp != 0)
8947 // return cmp;
8948 QualType R = FD->getReturnType();
8949 Op = buildStaticCastToR(Op.get());
8950 if (Op.isInvalid())
8951 return StmtError();
8952
8953 // R cmp = ...;
8954 IdentifierInfo *Name = &S.Context.Idents.get("cmp");
8955 VarDecl *VD =
8956 VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R,
8957 S.Context.getTrivialTypeSourceInfo(R, Loc), SC_None);
8958 S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false);
8959 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc);
8960
8961 // cmp != 0
8962 ExprResult VDRef = getDecl(VD);
8963 if (VDRef.isInvalid())
8964 return StmtError();
8965 llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0);
8966 Expr *Zero =
8967 IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc);
8969 if (VDRef.get()->getType()->isOverloadableType())
8970 Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true,
8971 true, FD);
8972 else
8973 Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero);
8974 if (Comp.isInvalid())
8975 return StmtError();
8976 Sema::ConditionResult Cond = S.ActOnCondition(
8977 nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean);
8978 if (Cond.isInvalid())
8979 return StmtError();
8980
8981 // return cmp;
8982 VDRef = getDecl(VD);
8983 if (VDRef.isInvalid())
8984 return StmtError();
8985 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get());
8986 if (ReturnStmt.isInvalid())
8987 return StmtError();
8988
8989 // if (...)
8990 return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, InitStmt, Cond,
8991 Loc, ReturnStmt.get(),
8992 /*ElseLoc=*/SourceLocation(), /*Else=*/nullptr);
8993 }
8994
8995 case DefaultedComparisonKind::NotEqual:
8996 case DefaultedComparisonKind::Relational:
8997 // C++2a [class.compare.secondary]p2:
8998 // Otherwise, the operator function yields x @ y.
8999 return Op.get();
9000 }
9001 llvm_unreachable("");
9002 }
9003
9004 /// Build "static_cast<R>(E)".
9005 ExprResult buildStaticCastToR(Expr *E) {
9006 QualType R = FD->getReturnType();
9007 assert(!R->isUndeducedType() && "type should have been deduced already");
9008
9009 // Don't bother forming a no-op cast in the common case.
9010 if (E->isPRValue() && S.Context.hasSameType(E->getType(), R))
9011 return E;
9012 return S.BuildCXXNamedCast(Loc, tok::kw_static_cast,
9013 S.Context.getTrivialTypeSourceInfo(R, Loc), E,
9014 SourceRange(Loc, Loc), SourceRange(Loc, Loc));
9015 }
9016};
9017}
9018
9019/// Perform the unqualified lookups that might be needed to form a defaulted
9020/// comparison function for the given operator.
9022 UnresolvedSetImpl &Operators,
9024 auto Lookup = [&](OverloadedOperatorKind OO) {
9025 Self.LookupOverloadedOperatorName(OO, S, Operators);
9026 };
9027
9028 // Every defaulted operator looks up itself.
9029 Lookup(Op);
9030 // ... and the rewritten form of itself, if any.
9032 Lookup(ExtraOp);
9033
9034 // For 'operator<=>', we also form a 'cmp != 0' expression, and might
9035 // synthesize a three-way comparison from '<' and '=='. In a dependent
9036 // context, we also need to look up '==' in case we implicitly declare a
9037 // defaulted 'operator=='.
9038 if (Op == OO_Spaceship) {
9039 Lookup(OO_ExclaimEqual);
9040 Lookup(OO_Less);
9041 Lookup(OO_EqualEqual);
9042 }
9043}
9044
9047 assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison");
9048
9049 // Perform any unqualified lookups we're going to need to default this
9050 // function.
9051 if (S) {
9052 UnresolvedSet<32> Operators;
9053 lookupOperatorsForDefaultedComparison(*this, S, Operators,
9054 FD->getOverloadedOperator());
9057 Context, Operators.pairs(), CurFPFeatureOverrides()));
9058 }
9059
9060 // C++2a [class.compare.default]p1:
9061 // A defaulted comparison operator function for some class C shall be a
9062 // non-template function declared in the member-specification of C that is
9063 // -- a non-static const non-volatile member of C having one parameter of
9064 // type const C& and either no ref-qualifier or the ref-qualifier &, or
9065 // -- a friend of C having two parameters of type const C& or two
9066 // parameters of type C.
9067
9068 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext());
9069 bool IsMethod = isa<CXXMethodDecl>(FD);
9070 if (IsMethod) {
9071 auto *MD = cast<CXXMethodDecl>(FD);
9072 assert(!MD->isStatic() && "comparison function cannot be a static member");
9073
9074 if (MD->getRefQualifier() == RQ_RValue) {
9075 Diag(MD->getLocation(), diag::err_ref_qualifier_comparison_operator);
9076
9077 // Remove the ref qualifier to recover.
9078 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
9079 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9080 EPI.RefQualifier = RQ_None;
9081 MD->setType(Context.getFunctionType(FPT->getReturnType(),
9082 FPT->getParamTypes(), EPI));
9083 }
9084
9085 // If we're out-of-class, this is the class we're comparing.
9086 if (!RD)
9087 RD = MD->getParent();
9088 QualType T = MD->getFunctionObjectParameterReferenceType();
9089 if (!T.getNonReferenceType().isConstQualified() &&
9090 (MD->isImplicitObjectMemberFunction() || T->isLValueReferenceType())) {
9091 SourceLocation Loc, InsertLoc;
9092 if (MD->isExplicitObjectMemberFunction()) {
9093 Loc = MD->getParamDecl(0)->getBeginLoc();
9094 InsertLoc = getLocForEndOfToken(
9095 MD->getParamDecl(0)->getExplicitObjectParamThisLoc());
9096 } else {
9097 Loc = MD->getLocation();
9098 if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc())
9099 InsertLoc = getLocForEndOfToken(Loc.getRParenLoc());
9100 }
9101 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
9102 // corresponding defaulted 'operator<=>' already.
9103 if (!MD->isImplicit()) {
9104 Diag(Loc, diag::err_defaulted_comparison_non_const)
9105 << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const");
9106 }
9107
9108 // Add the 'const' to the type to recover.
9109 if (MD->isExplicitObjectMemberFunction()) {
9110 assert(T->isLValueReferenceType());
9111 MD->getParamDecl(0)->setType(Context.getLValueReferenceType(
9112 T.getNonReferenceType().withConst()));
9113 } else {
9114 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
9115 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9116 EPI.TypeQuals.addConst();
9117 MD->setType(Context.getFunctionType(FPT->getReturnType(),
9118 FPT->getParamTypes(), EPI));
9119 }
9120 }
9121
9122 if (MD->isVolatile()) {
9123 Diag(MD->getLocation(), diag::err_volatile_comparison_operator);
9124
9125 // Remove the 'volatile' from the type to recover.
9126 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
9127 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9129 MD->setType(Context.getFunctionType(FPT->getReturnType(),
9130 FPT->getParamTypes(), EPI));
9131 }
9132 }
9133
9134 if ((FD->getNumParams() -
9135 (unsigned)FD->hasCXXExplicitFunctionObjectParameter()) !=
9136 (IsMethod ? 1 : 2)) {
9137 // Let's not worry about using a variadic template pack here -- who would do
9138 // such a thing?
9139 Diag(FD->getLocation(), diag::err_defaulted_comparison_num_args)
9140 << int(IsMethod) << int(DCK);
9141 return true;
9142 }
9143
9144 const ParmVarDecl *KnownParm = nullptr;
9145 for (const ParmVarDecl *Param : FD->parameters()) {
9146 QualType ParmTy = Param->getType();
9147 if (!KnownParm) {
9148 auto CTy = ParmTy;
9149 // Is it `T const &`?
9150 bool Ok = !IsMethod || FD->hasCXXExplicitFunctionObjectParameter();
9151 QualType ExpectedTy;
9152 if (RD)
9153 ExpectedTy = Context.getCanonicalTagType(RD);
9154 if (auto *Ref = CTy->getAs<LValueReferenceType>()) {
9155 CTy = Ref->getPointeeType();
9156 if (RD)
9157 ExpectedTy.addConst();
9158 Ok = true;
9159 }
9160
9161 // Is T a class?
9162 if (RD) {
9163 Ok &= RD->isDependentType() || Context.hasSameType(CTy, ExpectedTy);
9164 } else {
9165 RD = CTy->getAsCXXRecordDecl();
9166 Ok &= RD != nullptr;
9167 }
9168
9169 if (Ok) {
9170 KnownParm = Param;
9171 } else {
9172 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
9173 // corresponding defaulted 'operator<=>' already.
9174 if (!FD->isImplicit()) {
9175 if (RD) {
9176 CanQualType PlainTy = Context.getCanonicalTagType(RD);
9177 QualType RefTy =
9178 Context.getLValueReferenceType(PlainTy.withConst());
9179 Diag(FD->getLocation(), diag::err_defaulted_comparison_param)
9180 << int(DCK) << ParmTy << RefTy << int(!IsMethod) << PlainTy
9181 << Param->getSourceRange();
9182 } else {
9183 assert(!IsMethod && "should know expected type for method");
9184 Diag(FD->getLocation(),
9185 diag::err_defaulted_comparison_param_unknown)
9186 << int(DCK) << ParmTy << Param->getSourceRange();
9187 }
9188 }
9189 return true;
9190 }
9191 } else if (!Context.hasSameType(KnownParm->getType(), ParmTy)) {
9192 Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch)
9193 << int(DCK) << KnownParm->getType() << KnownParm->getSourceRange()
9194 << ParmTy << Param->getSourceRange();
9195 return true;
9196 }
9197 }
9198
9199 assert(RD && "must have determined class");
9200 if (IsMethod) {
9201 } else if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
9202 // In-class, must be a friend decl.
9203 assert(FD->getFriendObjectKind() && "expected a friend declaration");
9204 } else {
9205 // Out of class, require the defaulted comparison to be a friend (of a
9206 // complete type, per CWG2547).
9207 if (RequireCompleteType(FD->getLocation(), Context.getCanonicalTagType(RD),
9208 diag::err_defaulted_comparison_not_friend, int(DCK),
9209 int(1)))
9210 return true;
9211
9212 if (llvm::none_of(RD->friends(), [&](const FriendDecl *F) {
9213 return declaresSameEntity(F->getFriendDecl(), FD);
9214 })) {
9215 Diag(FD->getLocation(), diag::err_defaulted_comparison_not_friend)
9216 << int(DCK) << int(0) << RD;
9217 Diag(RD->getCanonicalDecl()->getLocation(), diag::note_declared_at);
9218 return true;
9219 }
9220 }
9221
9222 // C++2a [class.eq]p1, [class.rel]p1:
9223 // A [defaulted comparison other than <=>] shall have a declared return
9224 // type bool.
9227 !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) {
9228 Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool)
9229 << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy
9230 << FD->getReturnTypeSourceRange();
9231 return true;
9232 }
9233 // C++2a [class.spaceship]p2 [P2002R0]:
9234 // Let R be the declared return type [...]. If R is auto, [...]. Otherwise,
9235 // R shall not contain a placeholder type.
9236 if (QualType RT = FD->getDeclaredReturnType();
9238 RT->getContainedDeducedType() &&
9239 (!Context.hasSameType(RT, Context.getAutoDeductType()) ||
9240 RT->getContainedAutoType()->isConstrained())) {
9241 Diag(FD->getLocation(),
9242 diag::err_defaulted_comparison_deduced_return_type_not_auto)
9243 << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy
9244 << FD->getReturnTypeSourceRange();
9245 return true;
9246 }
9247
9248 // For a defaulted function in a dependent class, defer all remaining checks
9249 // until instantiation.
9250 if (RD->isDependentType())
9251 return false;
9252
9253 // Determine whether the function should be defined as deleted.
9254 DefaultedComparisonInfo Info =
9255 DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit();
9256
9257 bool First = FD == FD->getCanonicalDecl();
9258
9259 if (!First) {
9260 if (Info.Deleted) {
9261 // C++11 [dcl.fct.def.default]p4:
9262 // [For a] user-provided explicitly-defaulted function [...] if such a
9263 // function is implicitly defined as deleted, the program is ill-formed.
9264 //
9265 // This is really just a consequence of the general rule that you can
9266 // only delete a function on its first declaration.
9267 Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes)
9268 << FD->isImplicit() << (int)DCK;
9269 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9270 DefaultedComparisonAnalyzer::ExplainDeleted)
9271 .visit();
9272 return true;
9273 }
9275 // C++20 [class.compare.default]p1:
9276 // [...] A definition of a comparison operator as defaulted that appears
9277 // in a class shall be the first declaration of that function.
9278 Diag(FD->getLocation(), diag::err_non_first_default_compare_in_class)
9279 << (int)DCK;
9281 diag::note_previous_declaration);
9282 return true;
9283 }
9284 }
9285
9286 // If we want to delete the function, then do so; there's nothing else to
9287 // check in that case.
9288 if (Info.Deleted) {
9289 SetDeclDeleted(FD, FD->getLocation());
9290 if (!inTemplateInstantiation() && !FD->isImplicit()) {
9291 Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted)
9292 << (int)DCK;
9293 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9294 DefaultedComparisonAnalyzer::ExplainDeleted)
9295 .visit();
9296 if (FD->getDefaultLoc().isValid())
9297 Diag(FD->getDefaultLoc(), diag::note_replace_equals_default_to_delete)
9298 << FixItHint::CreateReplacement(FD->getDefaultLoc(), "delete");
9299 }
9300 return false;
9301 }
9302
9303 // C++2a [class.spaceship]p2:
9304 // The return type is deduced as the common comparison type of R0, R1, ...
9308 if (RetLoc.isInvalid())
9309 RetLoc = FD->getBeginLoc();
9310 // FIXME: Should we really care whether we have the complete type and the
9311 // 'enumerator' constants here? A forward declaration seems sufficient.
9313 Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator);
9314 if (Cat.isNull())
9315 return true;
9316 Context.adjustDeducedFunctionResultType(
9317 FD, SubstAutoType(FD->getDeclaredReturnType(), Cat));
9318 }
9319
9320 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
9321 // An explicitly-defaulted function that is not defined as deleted may be
9322 // declared constexpr or consteval only if it is constexpr-compatible.
9323 // C++2a [class.compare.default]p3 [P2002R0]:
9324 // A defaulted comparison function is constexpr-compatible if it satisfies
9325 // the requirements for a constexpr function [...]
9326 // The only relevant requirements are that the parameter and return types are
9327 // literal types. The remaining conditions are checked by the analyzer.
9328 //
9329 // We support P2448R2 in language modes earlier than C++23 as an extension.
9330 // The concept of constexpr-compatible was removed.
9331 // C++23 [dcl.fct.def.default]p3 [P2448R2]
9332 // A function explicitly defaulted on its first declaration is implicitly
9333 // inline, and is implicitly constexpr if it is constexpr-suitable.
9334 // C++23 [dcl.constexpr]p3
9335 // A function is constexpr-suitable if
9336 // - it is not a coroutine, and
9337 // - if the function is a constructor or destructor, its class does not
9338 // have any virtual base classes.
9339 if (FD->isConstexpr()) {
9340 if (!getLangOpts().CPlusPlus23 &&
9343 !Info.Constexpr) {
9344 Diag(FD->getBeginLoc(), diag::err_defaulted_comparison_constexpr_mismatch)
9345 << FD->isImplicit() << (int)DCK << FD->isConsteval();
9346 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9347 DefaultedComparisonAnalyzer::ExplainConstexpr)
9348 .visit();
9349 }
9350 }
9351
9352 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
9353 // If a constexpr-compatible function is explicitly defaulted on its first
9354 // declaration, it is implicitly considered to be constexpr.
9355 // FIXME: Only applying this to the first declaration seems problematic, as
9356 // simple reorderings can affect the meaning of the program.
9357 if (First && !FD->isConstexpr() && Info.Constexpr)
9359
9360 // C++2a [except.spec]p3:
9361 // If a declaration of a function does not have a noexcept-specifier
9362 // [and] is defaulted on its first declaration, [...] the exception
9363 // specification is as specified below
9364 if (FD->getExceptionSpecType() == EST_None) {
9365 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9366 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9368 EPI.ExceptionSpec.SourceDecl = FD;
9369 FD->setType(Context.getFunctionType(FPT->getReturnType(),
9370 FPT->getParamTypes(), EPI));
9371 }
9372
9373 return false;
9374}
9375
9377 FunctionDecl *Spaceship) {
9380 Ctx.PointOfInstantiation = Spaceship->getEndLoc();
9381 Ctx.Entity = Spaceship;
9383
9384 if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship))
9385 EqualEqual->setImplicit();
9386
9388}
9389
9392 assert(FD->isDefaulted() && !FD->isDeleted() &&
9394 if (FD->willHaveBody() || FD->isInvalidDecl())
9395 return;
9396
9398
9399 // Add a context note for diagnostics produced after this point.
9400 Scope.addContextNote(UseLoc);
9401
9402 DefaultedFunctionFPFeaturesRAII RestoreFP(*this, FD);
9403
9404 {
9405 // Build and set up the function body.
9406 // The first parameter has type maybe-ref-to maybe-const T, use that to get
9407 // the type of the class being compared.
9408 auto PT = FD->getParamDecl(0)->getType();
9409 CXXRecordDecl *RD = PT.getNonReferenceType()->getAsCXXRecordDecl();
9410 SourceLocation BodyLoc =
9411 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
9412 StmtResult Body =
9413 DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build();
9414 if (Body.isInvalid()) {
9415 FD->setInvalidDecl();
9416 return;
9417 }
9418 FD->setBody(Body.get());
9419 FD->markUsed(Context);
9420 }
9421
9422 // The exception specification is needed because we are defining the
9423 // function. Note that this will reuse the body we just built.
9425
9427 L->CompletedImplicitDefinition(FD);
9428}
9429
9432 FunctionDecl *FD,
9434 ComputingExceptionSpec CES(S, FD, Loc);
9436
9437 if (FD->isInvalidDecl())
9438 return ExceptSpec;
9439
9440 // The common case is that we just defined the comparison function. In that
9441 // case, just look at whether the body can throw.
9442 if (FD->hasBody()) {
9443 ExceptSpec.CalledStmt(FD->getBody());
9444 } else {
9445 // Otherwise, build a body so we can check it. This should ideally only
9446 // happen when we're not actually marking the function referenced. (This is
9447 // only really important for efficiency: we don't want to build and throw
9448 // away bodies for comparison functions more than we strictly need to.)
9449
9450 // Pretend to synthesize the function body in an unevaluated context.
9451 // Note that we can't actually just go ahead and define the function here:
9452 // we are not permitted to mark its callees as referenced.
9456
9457 CXXRecordDecl *RD =
9459 ? FD->getDeclContext()
9460 : FD->getLexicalDeclContext());
9461 SourceLocation BodyLoc =
9462 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
9463 StmtResult Body =
9464 DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build();
9465 if (!Body.isInvalid())
9466 ExceptSpec.CalledStmt(Body.get());
9467
9468 // FIXME: Can we hold onto this body and just transform it to potentially
9469 // evaluated when we're asked to define the function rather than rebuilding
9470 // it? Either that, or we should only build the bits of the body that we
9471 // need (the expressions, not the statements).
9472 }
9473
9474 return ExceptSpec;
9475}
9476
9478 decltype(DelayedOverridingExceptionSpecChecks) Overriding;
9480
9481 std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
9483
9484 // Perform any deferred checking of exception specifications for virtual
9485 // destructors.
9486 for (auto &Check : Overriding)
9487 CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
9488
9489 // Perform any deferred checking of exception specifications for befriended
9490 // special members.
9491 for (auto &Check : Equivalent)
9492 CheckEquivalentExceptionSpec(Check.second, Check.first);
9493}
9494
9495namespace {
9496/// CRTP base class for visiting operations performed by a special member
9497/// function (or inherited constructor).
9498template<typename Derived>
9499struct SpecialMemberVisitor {
9500 Sema &S;
9501 CXXMethodDecl *MD;
9504
9505 // Properties of the special member, computed for convenience.
9506 bool IsConstructor = false, IsAssignment = false, ConstArg = false;
9507
9508 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, CXXSpecialMemberKind CSM,
9510 : S(S), MD(MD), CSM(CSM), ICI(ICI) {
9511 switch (CSM) {
9515 IsConstructor = true;
9516 break;
9519 IsAssignment = true;
9520 break;
9522 break;
9524 llvm_unreachable("invalid special member kind");
9525 }
9526
9527 if (MD->getNumExplicitParams()) {
9528 if (const ReferenceType *RT =
9529 MD->getNonObjectParameter(0)->getType()->getAs<ReferenceType>())
9530 ConstArg = RT->getPointeeType().isConstQualified();
9531 }
9532 }
9533
9534 Derived &getDerived() { return static_cast<Derived&>(*this); }
9535
9536 /// Is this a "move" special member?
9537 bool isMove() const {
9538 return CSM == CXXSpecialMemberKind::MoveConstructor ||
9539 CSM == CXXSpecialMemberKind::MoveAssignment;
9540 }
9541
9542 /// Look up the corresponding special member in the given class.
9543 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
9544 unsigned Quals, bool IsMutable) {
9545 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
9546 ConstArg && !IsMutable);
9547 }
9548
9549 /// Look up the constructor for the specified base class to see if it's
9550 /// overridden due to this being an inherited constructor.
9551 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
9552 if (!ICI)
9553 return {};
9554 assert(CSM == CXXSpecialMemberKind::DefaultConstructor);
9555 auto *BaseCtor =
9556 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
9557 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
9558 return MD;
9559 return {};
9560 }
9561
9562 /// A base or member subobject.
9563 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
9564
9565 /// Get the location to use for a subobject in diagnostics.
9566 static SourceLocation getSubobjectLoc(Subobject Subobj) {
9567 // FIXME: For an indirect virtual base, the direct base leading to
9568 // the indirect virtual base would be a more useful choice.
9569 if (auto *B = dyn_cast<CXXBaseSpecifier *>(Subobj))
9570 return B->getBaseTypeLoc();
9571 else
9572 return cast<FieldDecl *>(Subobj)->getLocation();
9573 }
9574
9575 enum BasesToVisit {
9576 /// Visit all non-virtual (direct) bases.
9577 VisitNonVirtualBases,
9578 /// Visit all direct bases, virtual or not.
9579 VisitDirectBases,
9580 /// Visit all non-virtual bases, and all virtual bases if the class
9581 /// is not abstract.
9582 VisitPotentiallyConstructedBases,
9583 /// Visit all direct or virtual bases.
9584 VisitAllBases
9585 };
9586
9587 // Visit the bases and members of the class.
9588 bool visit(BasesToVisit Bases) {
9589 CXXRecordDecl *RD = MD->getParent();
9590
9591 if (Bases == VisitPotentiallyConstructedBases)
9592 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
9593
9594 for (auto &B : RD->bases())
9595 if ((Bases == VisitDirectBases || !B.isVirtual()) &&
9596 getDerived().visitBase(&B))
9597 return true;
9598
9599 if (Bases == VisitAllBases)
9600 for (auto &B : RD->vbases())
9601 if (getDerived().visitBase(&B))
9602 return true;
9603
9604 for (auto *F : RD->fields())
9605 if (!F->isInvalidDecl() && !F->isUnnamedBitField() &&
9606 getDerived().visitField(F))
9607 return true;
9608
9609 return false;
9610 }
9611};
9612}
9613
9614namespace {
9615struct SpecialMemberDeletionInfo
9616 : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
9617 bool Diagnose;
9618
9619 SourceLocation Loc;
9620
9621 bool AllFieldsAreConst;
9622
9623 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
9625 Sema::InheritedConstructorInfo *ICI, bool Diagnose)
9626 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
9627 Loc(MD->getLocation()), AllFieldsAreConst(true) {}
9628
9629 bool inUnion() const { return MD->getParent()->isUnion(); }
9630
9631 CXXSpecialMemberKind getEffectiveCSM() {
9632 return ICI ? CXXSpecialMemberKind::Invalid : CSM;
9633 }
9634
9635 bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
9636
9637 bool shouldDeleteForVariantPtrAuthMember(const FieldDecl *FD);
9638
9639 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
9640 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
9641
9642 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
9643 bool shouldDeleteForField(FieldDecl *FD);
9644 bool shouldDeleteForAllConstMembers();
9645
9646 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
9647 unsigned Quals);
9648 bool shouldDeleteForSubobjectCall(Subobject Subobj,
9649 Sema::SpecialMemberOverloadResult SMOR,
9650 bool IsDtorCallInCtor);
9651
9652 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
9653};
9654}
9655
9656/// Is the given special member inaccessible when used on the given
9657/// sub-object.
9658bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
9659 CXXMethodDecl *target) {
9660 /// If we're operating on a base class, the object type is the
9661 /// type of this special member.
9662 CanQualType objectTy;
9663 AccessSpecifier access = target->getAccess();
9664 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
9665 objectTy = S.Context.getCanonicalTagType(MD->getParent());
9666 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
9667
9668 // If we're operating on a field, the object type is the type of the field.
9669 } else {
9670 objectTy = S.Context.getCanonicalTagType(target->getParent());
9671 }
9672
9674 target->getParent(), DeclAccessPair::make(target, access), objectTy);
9675}
9676
9677/// Check whether we should delete a special member due to the implicit
9678/// definition containing a call to a special member of a subobject.
9679bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
9680 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
9681 bool IsDtorCallInCtor) {
9682 CXXMethodDecl *Decl = SMOR.getMethod();
9683 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9684
9685 enum {
9686 NotSet = -1,
9687 NoDecl,
9688 DeletedDecl,
9689 MultipleDecl,
9690 InaccessibleDecl,
9691 NonTrivialDecl
9692 } DiagKind = NotSet;
9693
9695 if (CSM == CXXSpecialMemberKind::DefaultConstructor && Field &&
9696 Field->getParent()->isUnion()) {
9697 // [class.default.ctor]p2:
9698 // A defaulted default constructor for class X is defined as deleted if
9699 // - X is a union that has a variant member with a non-trivial default
9700 // constructor and no variant member of X has a default member
9701 // initializer
9702 const auto *RD = cast<CXXRecordDecl>(Field->getParent());
9703 if (RD->hasInClassInitializer())
9704 return false;
9705 }
9706 DiagKind = !Decl ? NoDecl : DeletedDecl;
9708 DiagKind = MultipleDecl;
9709 else if (!isAccessible(Subobj, Decl))
9710 DiagKind = InaccessibleDecl;
9711 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
9712 !Decl->isTrivial()) {
9713 // A member of a union must have a trivial corresponding special member.
9714 // As a weird special case, a destructor call from a union's constructor
9715 // must be accessible and non-deleted, but need not be trivial. Such a
9716 // destructor is never actually called, but is semantically checked as
9717 // if it were.
9718 if (CSM == CXXSpecialMemberKind::DefaultConstructor) {
9719 // [class.default.ctor]p2:
9720 // A defaulted default constructor for class X is defined as deleted if
9721 // - X is a union that has a variant member with a non-trivial default
9722 // constructor and no variant member of X has a default member
9723 // initializer
9724 const auto *RD = cast<CXXRecordDecl>(Field->getParent());
9725 if (!RD->hasInClassInitializer())
9726 DiagKind = NonTrivialDecl;
9727 } else {
9728 DiagKind = NonTrivialDecl;
9729 }
9730 }
9731
9732 if (DiagKind == NotSet)
9733 return false;
9734
9735 if (Diagnose) {
9736 if (Field) {
9737 S.Diag(Field->getLocation(),
9738 diag::note_deleted_special_member_class_subobject)
9739 << getEffectiveCSM() << MD->getParent() << /*IsField*/ true << Field
9740 << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/ false;
9741 } else {
9742 CXXBaseSpecifier *Base = cast<CXXBaseSpecifier *>(Subobj);
9743 S.Diag(Base->getBeginLoc(),
9744 diag::note_deleted_special_member_class_subobject)
9745 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9746 << Base->getType() << DiagKind << IsDtorCallInCtor
9747 << /*IsObjCPtr*/ false;
9748 }
9749
9750 if (DiagKind == DeletedDecl)
9751 S.NoteDeletedFunction(Decl);
9752 // FIXME: Explain inaccessibility if DiagKind == InaccessibleDecl.
9753 }
9754
9755 return true;
9756}
9757
9758/// Check whether we should delete a special member function due to having a
9759/// direct or virtual base class or non-static data member of class type M.
9760bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
9761 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
9762 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9763 bool IsMutable = Field && Field->isMutable();
9764
9765 // C++11 [class.ctor]p5:
9766 // -- any direct or virtual base class, or non-static data member with no
9767 // brace-or-equal-initializer, has class type M (or array thereof) and
9768 // either M has no default constructor or overload resolution as applied
9769 // to M's default constructor results in an ambiguity or in a function
9770 // that is deleted or inaccessible
9771 // C++11 [class.copy]p11, C++11 [class.copy]p23:
9772 // -- a direct or virtual base class B that cannot be copied/moved because
9773 // overload resolution, as applied to B's corresponding special member,
9774 // results in an ambiguity or a function that is deleted or inaccessible
9775 // from the defaulted special member
9776 // C++11 [class.dtor]p5:
9777 // -- any direct or virtual base class [...] has a type with a destructor
9778 // that is deleted or inaccessible
9779 if (!(CSM == CXXSpecialMemberKind::DefaultConstructor && Field &&
9780 Field->hasInClassInitializer()) &&
9781 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
9782 false))
9783 return true;
9784
9785 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
9786 // -- any direct or virtual base class or non-static data member has a
9787 // type with a destructor that is deleted or inaccessible
9788 if (IsConstructor) {
9789 Sema::SpecialMemberOverloadResult SMOR =
9790 S.LookupSpecialMember(Class, CXXSpecialMemberKind::Destructor, false,
9791 false, false, false, false);
9792 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
9793 return true;
9794 }
9795
9796 return false;
9797}
9798
9799bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
9800 FieldDecl *FD, QualType FieldType) {
9801 // The defaulted special functions are defined as deleted if this is a variant
9802 // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
9803 // type under ARC.
9804 if (!FieldType.hasNonTrivialObjCLifetime())
9805 return false;
9806
9807 // Don't make the defaulted default constructor defined as deleted if the
9808 // member has an in-class initializer.
9809 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
9811 return false;
9812
9813 if (Diagnose) {
9814 auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
9815 S.Diag(FD->getLocation(), diag::note_deleted_special_member_class_subobject)
9816 << getEffectiveCSM() << ParentClass << /*IsField*/ true << FD << 4
9817 << /*IsDtorCallInCtor*/ false << /*IsObjCPtr*/ true;
9818 }
9819
9820 return true;
9821}
9822
9823bool SpecialMemberDeletionInfo::shouldDeleteForVariantPtrAuthMember(
9824 const FieldDecl *FD) {
9825 QualType FieldType = S.Context.getBaseElementType(FD->getType());
9826 // Copy/move constructors/assignment operators are deleted if the field has an
9827 // address-discriminated ptrauth qualifier.
9828 PointerAuthQualifier Q = FieldType.getPointerAuth();
9829
9830 if (!Q || !Q.isAddressDiscriminated())
9831 return false;
9832
9833 if (CSM == CXXSpecialMemberKind::DefaultConstructor ||
9834 CSM == CXXSpecialMemberKind::Destructor)
9835 return false;
9836
9837 if (Diagnose) {
9838 auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
9839 S.Diag(FD->getLocation(), diag::note_deleted_special_member_class_subobject)
9840 << getEffectiveCSM() << ParentClass << /*IsField*/ true << FD << 4
9841 << /*IsDtorCallInCtor*/ false << 2;
9842 }
9843
9844 return true;
9845}
9846
9847/// Check whether we should delete a special member function due to the class
9848/// having a particular direct or virtual base class.
9849bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
9850 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
9851 // If program is correct, BaseClass cannot be null, but if it is, the error
9852 // must be reported elsewhere.
9853 if (!BaseClass)
9854 return false;
9855 // If we have an inheriting constructor, check whether we're calling an
9856 // inherited constructor instead of a default constructor.
9857 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
9858 if (auto *BaseCtor = SMOR.getMethod()) {
9859 // Note that we do not check access along this path; other than that,
9860 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
9861 // FIXME: Check that the base has a usable destructor! Sink this into
9862 // shouldDeleteForClassSubobject.
9863 if (BaseCtor->isDeleted() && Diagnose) {
9864 S.Diag(Base->getBeginLoc(),
9865 diag::note_deleted_special_member_class_subobject)
9866 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9867 << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
9868 << /*IsObjCPtr*/ false;
9869 S.NoteDeletedFunction(BaseCtor);
9870 }
9871 return BaseCtor->isDeleted();
9872 }
9873 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
9874}
9875
9876/// Check whether we should delete a special member function due to the class
9877/// having a particular non-static data member.
9878bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
9879 QualType FieldType = S.Context.getBaseElementType(FD->getType());
9880 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
9881
9882 if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
9883 return true;
9884
9885 if (inUnion() && shouldDeleteForVariantPtrAuthMember(FD))
9886 return true;
9887
9888 if (CSM == CXXSpecialMemberKind::DefaultConstructor) {
9889 // For a default constructor, all references must be initialized in-class
9890 // and, if a union, it must have a non-const member.
9891 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
9892 if (Diagnose)
9893 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9894 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
9895 return true;
9896 }
9897 // C++11 [class.ctor]p5 (modified by DR2394): any non-variant non-static
9898 // data member of const-qualified type (or array thereof) with no
9899 // brace-or-equal-initializer is not const-default-constructible.
9900 if (!inUnion() && FieldType.isConstQualified() &&
9901 !FD->hasInClassInitializer() &&
9902 (!FieldRecord || !FieldRecord->allowConstDefaultInit())) {
9903 if (Diagnose)
9904 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9905 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
9906 return true;
9907 }
9908
9909 if (inUnion() && !FieldType.isConstQualified())
9910 AllFieldsAreConst = false;
9911 } else if (CSM == CXXSpecialMemberKind::CopyConstructor) {
9912 // For a copy constructor, data members must not be of rvalue reference
9913 // type.
9914 if (FieldType->isRValueReferenceType()) {
9915 if (Diagnose)
9916 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
9917 << MD->getParent() << FD << FieldType;
9918 return true;
9919 }
9920 } else if (IsAssignment) {
9921 // For an assignment operator, data members must not be of reference type.
9922 if (FieldType->isReferenceType()) {
9923 if (Diagnose)
9924 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9925 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
9926 return true;
9927 }
9928 if (!FieldRecord && FieldType.isConstQualified()) {
9929 // C++11 [class.copy]p23:
9930 // -- a non-static data member of const non-class type (or array thereof)
9931 if (Diagnose)
9932 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9933 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
9934 return true;
9935 }
9936 }
9937
9938 if (FieldRecord) {
9939 // Some additional restrictions exist on the variant members.
9940 if (!inUnion() && FieldRecord->isUnion() &&
9941 FieldRecord->isAnonymousStructOrUnion()) {
9942 bool AllVariantFieldsAreConst = true;
9943
9944 // FIXME: Handle anonymous unions declared within anonymous unions.
9945 for (auto *UI : FieldRecord->fields()) {
9946 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
9947
9948 if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
9949 return true;
9950
9951 if (shouldDeleteForVariantPtrAuthMember(&*UI))
9952 return true;
9953
9954 if (!UnionFieldType.isConstQualified())
9955 AllVariantFieldsAreConst = false;
9956
9957 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
9958 if (UnionFieldRecord &&
9959 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
9960 UnionFieldType.getCVRQualifiers()))
9961 return true;
9962 }
9963
9964 // At least one member in each anonymous union must be non-const
9965 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
9966 AllVariantFieldsAreConst && !FieldRecord->field_empty()) {
9967 if (Diagnose)
9968 S.Diag(FieldRecord->getLocation(),
9969 diag::note_deleted_default_ctor_all_const)
9970 << !!ICI << MD->getParent() << /*anonymous union*/1;
9971 return true;
9972 }
9973
9974 // Don't check the implicit member of the anonymous union type.
9975 // This is technically non-conformant but supported, and we have a
9976 // diagnostic for this elsewhere.
9977 return false;
9978 }
9979
9980 if (shouldDeleteForClassSubobject(FieldRecord, FD,
9981 FieldType.getCVRQualifiers()))
9982 return true;
9983 }
9984
9985 return false;
9986}
9987
9988/// C++11 [class.ctor] p5:
9989/// A defaulted default constructor for a class X is defined as deleted if
9990/// X is a union and all of its variant members are of const-qualified type.
9991bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
9992 // This is a silly definition, because it gives an empty union a deleted
9993 // default constructor. Don't do that.
9994 if (CSM == CXXSpecialMemberKind::DefaultConstructor && inUnion() &&
9995 AllFieldsAreConst) {
9996 bool AnyFields = false;
9997 for (auto *F : MD->getParent()->fields())
9998 if ((AnyFields = !F->isUnnamedBitField()))
9999 break;
10000 if (!AnyFields)
10001 return false;
10002 if (Diagnose)
10003 S.Diag(MD->getParent()->getLocation(),
10004 diag::note_deleted_default_ctor_all_const)
10005 << !!ICI << MD->getParent() << /*not anonymous union*/0;
10006 return true;
10007 }
10008 return false;
10009}
10010
10011/// Determine whether a defaulted special member function should be defined as
10012/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
10013/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
10017 bool Diagnose) {
10018 if (MD->isInvalidDecl())
10019 return false;
10020 CXXRecordDecl *RD = MD->getParent();
10021 assert(!RD->isDependentType() && "do deletion after instantiation");
10022 if (!LangOpts.CPlusPlus || (!LangOpts.CPlusPlus11 && !RD->isLambda()) ||
10023 RD->isInvalidDecl())
10024 return false;
10025
10026 // C++11 [expr.lambda.prim]p19:
10027 // The closure type associated with a lambda-expression has a
10028 // deleted (8.4.3) default constructor and a deleted copy
10029 // assignment operator.
10030 // C++2a adds back these operators if the lambda has no lambda-capture.
10034 if (Diagnose)
10035 Diag(RD->getLocation(), diag::note_lambda_decl);
10036 return true;
10037 }
10038
10039 // C++11 [class.copy]p7, p18:
10040 // If the class definition declares a move constructor or move assignment
10041 // operator, an implicitly declared copy constructor or copy assignment
10042 // operator is defined as deleted.
10045 CXXMethodDecl *UserDeclaredMove = nullptr;
10046
10047 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
10048 // deletion of the corresponding copy operation, not both copy operations.
10049 // MSVC 2015 has adopted the standards conforming behavior.
10050 bool DeletesOnlyMatchingCopy =
10051 getLangOpts().MSVCCompat &&
10052 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
10053
10055 (!DeletesOnlyMatchingCopy ||
10057 if (!Diagnose) return true;
10058
10059 // Find any user-declared move constructor.
10060 for (auto *I : RD->ctors()) {
10061 if (I->isMoveConstructor()) {
10062 UserDeclaredMove = I;
10063 break;
10064 }
10065 }
10066 assert(UserDeclaredMove);
10067 } else if (RD->hasUserDeclaredMoveAssignment() &&
10068 (!DeletesOnlyMatchingCopy ||
10070 if (!Diagnose) return true;
10071
10072 // Find any user-declared move assignment operator.
10073 for (auto *I : RD->methods()) {
10074 if (I->isMoveAssignmentOperator()) {
10075 UserDeclaredMove = I;
10076 break;
10077 }
10078 }
10079 assert(UserDeclaredMove);
10080 }
10081
10082 if (UserDeclaredMove) {
10083 Diag(UserDeclaredMove->getLocation(),
10084 diag::note_deleted_copy_user_declared_move)
10085 << (CSM == CXXSpecialMemberKind::CopyAssignment) << RD
10086 << UserDeclaredMove->isMoveAssignmentOperator();
10087 return true;
10088 }
10089 }
10090
10091 // Do access control from the special member function
10092 ContextRAII MethodContext(*this, MD);
10093
10094 // C++11 [class.dtor]p5:
10095 // -- for a virtual destructor, lookup of the non-array deallocation function
10096 // results in an ambiguity or in a function that is deleted or inaccessible
10097 if (CSM == CXXSpecialMemberKind::Destructor && MD->isVirtual()) {
10098 FunctionDecl *OperatorDelete = nullptr;
10099 CanQualType DeallocType = Context.getCanonicalTagType(RD);
10100 DeclarationName Name =
10101 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
10105 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
10106 OperatorDelete, IDP,
10107 /*Diagnose=*/false)) {
10108 if (Diagnose)
10109 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
10110 return true;
10111 }
10112 }
10113
10114 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
10115
10116 // Per DR1611, do not consider virtual bases of constructors of abstract
10117 // classes, since we are not going to construct them.
10118 // Per DR1658, do not consider virtual bases of destructors of abstract
10119 // classes either.
10120 // Per DR2180, for assignment operators we only assign (and thus only
10121 // consider) direct bases.
10122 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
10123 : SMI.VisitPotentiallyConstructedBases))
10124 return true;
10125
10126 if (SMI.shouldDeleteForAllConstMembers())
10127 return true;
10128
10129 if (getLangOpts().CUDA) {
10130 // We should delete the special member in CUDA mode if target inference
10131 // failed.
10132 // For inherited constructors (non-null ICI), CSM may be passed so that MD
10133 // is treated as certain special member, which may not reflect what special
10134 // member MD really is. However inferTargetForImplicitSpecialMember
10135 // expects CSM to match MD, therefore recalculate CSM.
10136 assert(ICI || CSM == getSpecialMember(MD));
10137 auto RealCSM = CSM;
10138 if (ICI)
10139 RealCSM = getSpecialMember(MD);
10140
10141 return CUDA().inferTargetForImplicitSpecialMember(RD, RealCSM, MD,
10142 SMI.ConstArg, Diagnose);
10143 }
10144
10145 return false;
10146}
10147
10150 assert(DFK && "not a defaultable function");
10151 assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted");
10152
10153 if (DFK.isSpecialMember()) {
10155 nullptr, /*Diagnose=*/true);
10156 } else {
10157 DefaultedComparisonAnalyzer(
10159 DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted)
10160 .visit();
10161 }
10162}
10163
10164/// Perform lookup for a special member of the specified kind, and determine
10165/// whether it is trivial. If the triviality can be determined without the
10166/// lookup, skip it. This is intended for use when determining whether a
10167/// special member of a containing object is trivial, and thus does not ever
10168/// perform overload resolution for default constructors.
10169///
10170/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
10171/// member that was most likely to be intended to be trivial, if any.
10172///
10173/// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
10174/// determine whether the special member is trivial.
10176 CXXSpecialMemberKind CSM, unsigned Quals,
10177 bool ConstRHS, TrivialABIHandling TAH,
10178 CXXMethodDecl **Selected) {
10179 if (Selected)
10180 *Selected = nullptr;
10181
10182 switch (CSM) {
10184 llvm_unreachable("not a special member");
10185
10187 // C++11 [class.ctor]p5:
10188 // A default constructor is trivial if:
10189 // - all the [direct subobjects] have trivial default constructors
10190 //
10191 // Note, no overload resolution is performed in this case.
10193 return true;
10194
10195 if (Selected) {
10196 // If there's a default constructor which could have been trivial, dig it
10197 // out. Otherwise, if there's any user-provided default constructor, point
10198 // to that as an example of why there's not a trivial one.
10199 CXXConstructorDecl *DefCtor = nullptr;
10202 for (auto *CI : RD->ctors()) {
10203 if (!CI->isDefaultConstructor())
10204 continue;
10205 DefCtor = CI;
10206 if (!DefCtor->isUserProvided())
10207 break;
10208 }
10209
10210 *Selected = DefCtor;
10211 }
10212
10213 return false;
10214
10216 // C++11 [class.dtor]p5:
10217 // A destructor is trivial if:
10218 // - all the direct [subobjects] have trivial destructors
10219 if (RD->hasTrivialDestructor() ||
10222 return true;
10223
10224 if (Selected) {
10225 if (RD->needsImplicitDestructor())
10227 *Selected = RD->getDestructor();
10228 }
10229
10230 return false;
10231
10233 // C++11 [class.copy]p12:
10234 // A copy constructor is trivial if:
10235 // - the constructor selected to copy each direct [subobject] is trivial
10236 if (RD->hasTrivialCopyConstructor() ||
10239 if (Quals == Qualifiers::Const)
10240 // We must either select the trivial copy constructor or reach an
10241 // ambiguity; no need to actually perform overload resolution.
10242 return true;
10243 } else if (!Selected) {
10244 return false;
10245 }
10246 // In C++98, we are not supposed to perform overload resolution here, but we
10247 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
10248 // cases like B as having a non-trivial copy constructor:
10249 // struct A { template<typename T> A(T&); };
10250 // struct B { mutable A a; };
10251 goto NeedOverloadResolution;
10252
10254 // C++11 [class.copy]p25:
10255 // A copy assignment operator is trivial if:
10256 // - the assignment operator selected to copy each direct [subobject] is
10257 // trivial
10258 if (RD->hasTrivialCopyAssignment()) {
10259 if (Quals == Qualifiers::Const)
10260 return true;
10261 } else if (!Selected) {
10262 return false;
10263 }
10264 // In C++98, we are not supposed to perform overload resolution here, but we
10265 // treat that as a language defect.
10266 goto NeedOverloadResolution;
10267
10270 NeedOverloadResolution:
10272 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
10273
10274 // The standard doesn't describe how to behave if the lookup is ambiguous.
10275 // We treat it as not making the member non-trivial, just like the standard
10276 // mandates for the default constructor. This should rarely matter, because
10277 // the member will also be deleted.
10279 return true;
10280
10281 if (!SMOR.getMethod()) {
10282 assert(SMOR.getKind() ==
10284 return false;
10285 }
10286
10287 // We deliberately don't check if we found a deleted special member. We're
10288 // not supposed to!
10289 if (Selected)
10290 *Selected = SMOR.getMethod();
10291
10295 return SMOR.getMethod()->isTrivialForCall();
10296 return SMOR.getMethod()->isTrivial();
10297 }
10298
10299 llvm_unreachable("unknown special method kind");
10300}
10301
10303 for (auto *CI : RD->ctors())
10304 if (!CI->isImplicit())
10305 return CI;
10306
10307 // Look for constructor templates.
10309 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
10310 if (CXXConstructorDecl *CD =
10311 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
10312 return CD;
10313 }
10314
10315 return nullptr;
10316}
10317
10318/// The kind of subobject we are checking for triviality. The values of this
10319/// enumeration are used in diagnostics.
10321 /// The subobject is a base class.
10323 /// The subobject is a non-static data member.
10325 /// The object is actually the complete object.
10327};
10328
10329/// Check whether the special member selected for a given type would be trivial.
10331 QualType SubType, bool ConstRHS,
10334 TrivialABIHandling TAH, bool Diagnose) {
10335 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
10336 if (!SubRD)
10337 return true;
10338
10339 CXXMethodDecl *Selected;
10340 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
10341 ConstRHS, TAH, Diagnose ? &Selected : nullptr))
10342 return true;
10343
10344 if (Diagnose) {
10345 if (ConstRHS)
10346 SubType.addConst();
10347
10348 if (!Selected && CSM == CXXSpecialMemberKind::DefaultConstructor) {
10349 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
10350 << Kind << SubType.getUnqualifiedType();
10352 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
10353 } else if (!Selected)
10354 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
10355 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
10356 else if (Selected->isUserProvided()) {
10357 if (Kind == TSK_CompleteObject)
10358 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
10359 << Kind << SubType.getUnqualifiedType() << CSM;
10360 else {
10361 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
10362 << Kind << SubType.getUnqualifiedType() << CSM;
10363 S.Diag(Selected->getLocation(), diag::note_declared_at);
10364 }
10365 } else {
10366 if (Kind != TSK_CompleteObject)
10367 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
10368 << Kind << SubType.getUnqualifiedType() << CSM;
10369
10370 // Explain why the defaulted or deleted special member isn't trivial.
10371 S.SpecialMemberIsTrivial(Selected, CSM,
10373 }
10374 }
10375
10376 return false;
10377}
10378
10379/// Check whether the members of a class type allow a special member to be
10380/// trivial.
10382 CXXSpecialMemberKind CSM, bool ConstArg,
10383 TrivialABIHandling TAH, bool Diagnose) {
10384 for (const auto *FI : RD->fields()) {
10385 if (FI->isInvalidDecl() || FI->isUnnamedBitField())
10386 continue;
10387
10388 QualType FieldType = S.Context.getBaseElementType(FI->getType());
10389
10390 // Pretend anonymous struct or union members are members of this class.
10391 if (FI->isAnonymousStructOrUnion()) {
10392 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
10393 CSM, ConstArg, TAH, Diagnose))
10394 return false;
10395 continue;
10396 }
10397
10398 // C++11 [class.ctor]p5:
10399 // A default constructor is trivial if [...]
10400 // -- no non-static data member of its class has a
10401 // brace-or-equal-initializer
10403 FI->hasInClassInitializer()) {
10404 if (Diagnose)
10405 S.Diag(FI->getLocation(), diag::note_nontrivial_default_member_init)
10406 << FI;
10407 return false;
10408 }
10409
10410 // Objective C ARC 4.3.5:
10411 // [...] nontrivally ownership-qualified types are [...] not trivially
10412 // default constructible, copy constructible, move constructible, copy
10413 // assignable, move assignable, or destructible [...]
10414 if (FieldType.hasNonTrivialObjCLifetime()) {
10415 if (Diagnose)
10416 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
10417 << RD << FieldType.getObjCLifetime();
10418 return false;
10419 }
10420
10421 bool ConstRHS = ConstArg && !FI->isMutable();
10422 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
10423 CSM, TSK_Field, TAH, Diagnose))
10424 return false;
10425 }
10426
10427 return true;
10428}
10429
10432 CanQualType Ty = Context.getCanonicalTagType(RD);
10433
10434 bool ConstArg = (CSM == CXXSpecialMemberKind::CopyConstructor ||
10436 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
10439 /*Diagnose*/ true);
10440}
10441
10443 TrivialABIHandling TAH, bool Diagnose) {
10444 assert(!MD->isUserProvided() && CSM != CXXSpecialMemberKind::Invalid &&
10445 "not special enough");
10446
10447 CXXRecordDecl *RD = MD->getParent();
10448
10449 bool ConstArg = false;
10450
10451 // C++11 [class.copy]p12, p25: [DR1593]
10452 // A [special member] is trivial if [...] its parameter-type-list is
10453 // equivalent to the parameter-type-list of an implicit declaration [...]
10454 switch (CSM) {
10457 // Trivial default constructors and destructors cannot have parameters.
10458 break;
10459
10462 const ParmVarDecl *Param0 = MD->getNonObjectParameter(0);
10463 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
10464
10465 // When ClangABICompat14 is true, CXX copy constructors will only be trivial
10466 // if they are not user-provided and their parameter-type-list is equivalent
10467 // to the parameter-type-list of an implicit declaration. This maintains the
10468 // behavior before dr2171 was implemented.
10469 //
10470 // Otherwise, if ClangABICompat14 is false, All copy constructors can be
10471 // trivial, if they are not user-provided, regardless of the qualifiers on
10472 // the reference type.
10473 const bool ClangABICompat14 =
10474 Context.getLangOpts().isCompatibleWith(LangOptions::ClangABI::Ver14);
10475 if (!RT ||
10477 ClangABICompat14)) {
10478 if (Diagnose)
10479 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
10480 << Param0->getSourceRange() << Param0->getType()
10481 << Context.getLValueReferenceType(
10482 Context.getCanonicalTagType(RD).withConst());
10483 return false;
10484 }
10485
10486 ConstArg = RT->getPointeeType().isConstQualified();
10487 break;
10488 }
10489
10492 // Trivial move operations always have non-cv-qualified parameters.
10493 const ParmVarDecl *Param0 = MD->getNonObjectParameter(0);
10494 const RValueReferenceType *RT =
10495 Param0->getType()->getAs<RValueReferenceType>();
10496 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
10497 if (Diagnose)
10498 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
10499 << Param0->getSourceRange() << Param0->getType()
10500 << Context.getRValueReferenceType(Context.getCanonicalTagType(RD));
10501 return false;
10502 }
10503 break;
10504 }
10505
10507 llvm_unreachable("not a special member");
10508 }
10509
10510 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
10511 if (Diagnose)
10513 diag::note_nontrivial_default_arg)
10515 return false;
10516 }
10517 if (MD->isVariadic()) {
10518 if (Diagnose)
10519 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
10520 return false;
10521 }
10522
10523 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
10524 // A copy/move [constructor or assignment operator] is trivial if
10525 // -- the [member] selected to copy/move each direct base class subobject
10526 // is trivial
10527 //
10528 // C++11 [class.copy]p12, C++11 [class.copy]p25:
10529 // A [default constructor or destructor] is trivial if
10530 // -- all the direct base classes have trivial [default constructors or
10531 // destructors]
10532 for (const auto &BI : RD->bases())
10533 if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
10534 ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
10535 return false;
10536
10537 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
10538 // A copy/move [constructor or assignment operator] for a class X is
10539 // trivial if
10540 // -- for each non-static data member of X that is of class type (or array
10541 // thereof), the constructor selected to copy/move that member is
10542 // trivial
10543 //
10544 // C++11 [class.copy]p12, C++11 [class.copy]p25:
10545 // A [default constructor or destructor] is trivial if
10546 // -- for all of the non-static data members of its class that are of class
10547 // type (or array thereof), each such class has a trivial [default
10548 // constructor or destructor]
10549 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
10550 return false;
10551
10552 // C++11 [class.dtor]p5:
10553 // A destructor is trivial if [...]
10554 // -- the destructor is not virtual
10555 if (CSM == CXXSpecialMemberKind::Destructor && MD->isVirtual()) {
10556 if (Diagnose)
10557 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
10558 return false;
10559 }
10560
10561 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
10562 // A [special member] for class X is trivial if [...]
10563 // -- class X has no virtual functions and no virtual base classes
10565 MD->getParent()->isDynamicClass()) {
10566 if (!Diagnose)
10567 return false;
10568
10569 if (RD->getNumVBases()) {
10570 // Check for virtual bases. We already know that the corresponding
10571 // member in all bases is trivial, so vbases must all be direct.
10572 CXXBaseSpecifier &BS = *RD->vbases_begin();
10573 assert(BS.isVirtual());
10574 Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
10575 return false;
10576 }
10577
10578 // Must have a virtual method.
10579 for (const auto *MI : RD->methods()) {
10580 if (MI->isVirtual()) {
10581 SourceLocation MLoc = MI->getBeginLoc();
10582 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
10583 return false;
10584 }
10585 }
10586
10587 llvm_unreachable("dynamic class with no vbases and no virtual functions");
10588 }
10589
10590 // Looks like it's trivial!
10591 return true;
10592}
10593
10594namespace {
10595struct FindHiddenVirtualMethod {
10596 Sema *S;
10598 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
10599 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10600
10601private:
10602 /// Check whether any most overridden method from MD in Methods
10603 static bool CheckMostOverridenMethods(
10604 const CXXMethodDecl *MD,
10605 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
10606 if (MD->size_overridden_methods() == 0)
10607 return Methods.count(MD->getCanonicalDecl());
10608 for (const CXXMethodDecl *O : MD->overridden_methods())
10609 if (CheckMostOverridenMethods(O, Methods))
10610 return true;
10611 return false;
10612 }
10613
10614public:
10615 /// Member lookup function that determines whether a given C++
10616 /// method overloads virtual methods in a base class without overriding any,
10617 /// to be used with CXXRecordDecl::lookupInBases().
10618 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
10619 auto *BaseRecord = Specifier->getType()->castAsRecordDecl();
10620 DeclarationName Name = Method->getDeclName();
10621 assert(Name.getNameKind() == DeclarationName::Identifier);
10622
10623 bool foundSameNameMethod = false;
10624 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
10625 for (Path.Decls = BaseRecord->lookup(Name).begin();
10626 Path.Decls != DeclContext::lookup_iterator(); ++Path.Decls) {
10627 NamedDecl *D = *Path.Decls;
10628 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
10629 MD = MD->getCanonicalDecl();
10630 foundSameNameMethod = true;
10631 // Interested only in hidden virtual methods.
10632 if (!MD->isVirtual())
10633 continue;
10634 // If the method we are checking overrides a method from its base
10635 // don't warn about the other overloaded methods. Clang deviates from
10636 // GCC by only diagnosing overloads of inherited virtual functions that
10637 // do not override any other virtual functions in the base. GCC's
10638 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
10639 // function from a base class. These cases may be better served by a
10640 // warning (not specific to virtual functions) on call sites when the
10641 // call would select a different function from the base class, were it
10642 // visible.
10643 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
10644 if (!S->IsOverload(Method, MD, false))
10645 return true;
10646 // Collect the overload only if its hidden.
10647 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
10648 overloadedMethods.push_back(MD);
10649 }
10650 }
10651
10652 if (foundSameNameMethod)
10653 OverloadedMethods.append(overloadedMethods.begin(),
10654 overloadedMethods.end());
10655 return foundSameNameMethod;
10656 }
10657};
10658} // end anonymous namespace
10659
10660/// Add the most overridden methods from MD to Methods
10662 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
10663 if (MD->size_overridden_methods() == 0)
10664 Methods.insert(MD->getCanonicalDecl());
10665 else
10666 for (const CXXMethodDecl *O : MD->overridden_methods())
10667 AddMostOverridenMethods(O, Methods);
10668}
10669
10671 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10672 if (!MD->getDeclName().isIdentifier())
10673 return;
10674
10675 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
10676 /*bool RecordPaths=*/false,
10677 /*bool DetectVirtual=*/false);
10678 FindHiddenVirtualMethod FHVM;
10679 FHVM.Method = MD;
10680 FHVM.S = this;
10681
10682 // Keep the base methods that were overridden or introduced in the subclass
10683 // by 'using' in a set. A base method not in this set is hidden.
10684 CXXRecordDecl *DC = MD->getParent();
10685 for (NamedDecl *ND : DC->lookup(MD->getDeclName())) {
10686 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(ND))
10687 ND = shad->getTargetDecl();
10688 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
10689 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
10690 }
10691
10692 if (DC->lookupInBases(FHVM, Paths))
10693 OverloadedMethods = FHVM.OverloadedMethods;
10694}
10695
10697 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10698 for (const CXXMethodDecl *overloadedMD : OverloadedMethods) {
10700 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
10701 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
10702 Diag(overloadedMD->getLocation(), PD);
10703 }
10704}
10705
10707 if (MD->isInvalidDecl())
10708 return;
10709
10710 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
10711 return;
10712
10713 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10714 FindHiddenVirtualMethods(MD, OverloadedMethods);
10715 if (!OverloadedMethods.empty()) {
10716 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
10717 << MD << (OverloadedMethods.size() > 1);
10718
10719 NoteHiddenVirtualMethods(MD, OverloadedMethods);
10720 }
10721}
10722
10724 auto PrintDiagAndRemoveAttr = [&](unsigned N) {
10725 // No diagnostics if this is a template instantiation.
10727 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
10728 diag::ext_cannot_use_trivial_abi) << &RD;
10729 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
10730 diag::note_cannot_use_trivial_abi_reason) << &RD << N;
10731 }
10732 RD.dropAttr<TrivialABIAttr>();
10733 };
10734
10735 // Ill-formed if the struct has virtual functions.
10736 if (RD.isPolymorphic()) {
10737 PrintDiagAndRemoveAttr(1);
10738 return;
10739 }
10740
10741 for (const auto &B : RD.bases()) {
10742 // Ill-formed if the base class is non-trivial for the purpose of calls or a
10743 // virtual base.
10744 if (!B.getType()->isDependentType() &&
10745 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) {
10746 PrintDiagAndRemoveAttr(2);
10747 return;
10748 }
10749
10750 if (B.isVirtual()) {
10751 PrintDiagAndRemoveAttr(3);
10752 return;
10753 }
10754 }
10755
10756 for (const auto *FD : RD.fields()) {
10757 // Ill-formed if the field is an ObjectiveC pointer or of a type that is
10758 // non-trivial for the purpose of calls.
10759 QualType FT = FD->getType();
10761 PrintDiagAndRemoveAttr(4);
10762 return;
10763 }
10764
10765 // Ill-formed if the field is an address-discriminated value.
10767 PrintDiagAndRemoveAttr(6);
10768 return;
10769 }
10770
10771 if (const auto *RT =
10772 FT->getBaseElementTypeUnsafe()->getAsCanonical<RecordType>())
10773 if (!RT->isDependentType() &&
10774 !cast<CXXRecordDecl>(RT->getDecl()->getDefinitionOrSelf())
10775 ->canPassInRegisters()) {
10776 PrintDiagAndRemoveAttr(5);
10777 return;
10778 }
10779 }
10780
10782 return;
10783
10784 // Ill-formed if the copy and move constructors are deleted.
10785 auto HasNonDeletedCopyOrMoveConstructor = [&]() {
10786 // If the type is dependent, then assume it might have
10787 // implicit copy or move ctor because we won't know yet at this point.
10788 if (RD.isDependentType())
10789 return true;
10792 return true;
10795 return true;
10796 for (const CXXConstructorDecl *CD : RD.ctors())
10797 if (CD->isCopyOrMoveConstructor() && !CD->isDeleted())
10798 return true;
10799 return false;
10800 };
10801
10802 if (!HasNonDeletedCopyOrMoveConstructor()) {
10803 PrintDiagAndRemoveAttr(0);
10804 return;
10805 }
10806}
10807
10809 CXXRecordDecl &RD) {
10810 if (RequireCompleteType(RD.getLocation(), Context.getCanonicalTagType(&RD),
10811 diag::err_incomplete_type_vtable_pointer_auth))
10812 return;
10813
10814 const CXXRecordDecl *PrimaryBase = &RD;
10815 if (PrimaryBase->hasAnyDependentBases())
10816 return;
10817
10818 while (1) {
10819 assert(PrimaryBase);
10820 const CXXRecordDecl *Base = nullptr;
10821 for (const CXXBaseSpecifier &BasePtr : PrimaryBase->bases()) {
10822 if (!BasePtr.getType()->getAsCXXRecordDecl()->isDynamicClass())
10823 continue;
10824 Base = BasePtr.getType()->getAsCXXRecordDecl();
10825 break;
10826 }
10827 if (!Base || Base == PrimaryBase || !Base->isPolymorphic())
10828 break;
10829 Diag(RD.getAttr<VTablePointerAuthenticationAttr>()->getLocation(),
10830 diag::err_non_top_level_vtable_pointer_auth)
10831 << &RD << Base;
10832 PrimaryBase = Base;
10833 }
10834
10835 if (!RD.isPolymorphic())
10836 Diag(RD.getAttr<VTablePointerAuthenticationAttr>()->getLocation(),
10837 diag::err_non_polymorphic_vtable_pointer_auth)
10838 << &RD;
10839}
10840
10843 SourceLocation RBrac, const ParsedAttributesView &AttrList) {
10844 if (!TagDecl)
10845 return;
10846
10848
10849 for (const ParsedAttr &AL : AttrList) {
10850 if (AL.getKind() != ParsedAttr::AT_Visibility)
10851 continue;
10852 AL.setInvalid();
10853 Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL;
10854 }
10855
10856 ActOnFields(S, RLoc, TagDecl,
10858 // strict aliasing violation!
10859 reinterpret_cast<Decl **>(FieldCollector->getCurFields()),
10860 FieldCollector->getCurNumFields()),
10861 LBrac, RBrac, AttrList);
10862
10864}
10865
10866/// Find the equality comparison functions that should be implicitly declared
10867/// in a given class definition, per C++2a [class.compare.default]p3.
10869 ASTContext &Ctx, CXXRecordDecl *RD,
10871 DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual);
10872 if (!RD->lookup(EqEq).empty())
10873 // Member operator== explicitly declared: no implicit operator==s.
10874 return;
10875
10876 // Traverse friends looking for an '==' or a '<=>'.
10877 for (FriendDecl *Friend : RD->friends()) {
10878 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl());
10879 if (!FD) continue;
10880
10881 if (FD->getOverloadedOperator() == OO_EqualEqual) {
10882 // Friend operator== explicitly declared: no implicit operator==s.
10883 Spaceships.clear();
10884 return;
10885 }
10886
10887 if (FD->getOverloadedOperator() == OO_Spaceship &&
10889 Spaceships.push_back(FD);
10890 }
10891
10892 // Look for members named 'operator<=>'.
10894 for (NamedDecl *ND : RD->lookup(Cmp)) {
10895 // Note that we could find a non-function here (either a function template
10896 // or a using-declaration). Neither case results in an implicit
10897 // 'operator=='.
10898 if (auto *FD = dyn_cast<FunctionDecl>(ND))
10899 if (FD->isExplicitlyDefaulted())
10900 Spaceships.push_back(FD);
10901 }
10902}
10903
10905 // Don't add implicit special members to templated classes.
10906 // FIXME: This means unqualified lookups for 'operator=' within a class
10907 // template don't work properly.
10908 if (!ClassDecl->isDependentType()) {
10909 if (ClassDecl->needsImplicitDefaultConstructor()) {
10910 ++getASTContext().NumImplicitDefaultConstructors;
10911
10912 if (ClassDecl->hasInheritedConstructor())
10914 }
10915
10916 if (ClassDecl->needsImplicitCopyConstructor()) {
10917 ++getASTContext().NumImplicitCopyConstructors;
10918
10919 // If the properties or semantics of the copy constructor couldn't be
10920 // determined while the class was being declared, force a declaration
10921 // of it now.
10923 ClassDecl->hasInheritedConstructor())
10925 // For the MS ABI we need to know whether the copy ctor is deleted. A
10926 // prerequisite for deleting the implicit copy ctor is that the class has
10927 // a move ctor or move assignment that is either user-declared or whose
10928 // semantics are inherited from a subobject. FIXME: We should provide a
10929 // more direct way for CodeGen to ask whether the constructor was deleted.
10930 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
10931 (ClassDecl->hasUserDeclaredMoveConstructor() ||
10933 ClassDecl->hasUserDeclaredMoveAssignment() ||
10936 }
10937
10938 if (getLangOpts().CPlusPlus11 &&
10939 ClassDecl->needsImplicitMoveConstructor()) {
10940 ++getASTContext().NumImplicitMoveConstructors;
10941
10943 ClassDecl->hasInheritedConstructor())
10945 }
10946
10947 if (ClassDecl->needsImplicitCopyAssignment()) {
10948 ++getASTContext().NumImplicitCopyAssignmentOperators;
10949
10950 // If we have a dynamic class, then the copy assignment operator may be
10951 // virtual, so we have to declare it immediately. This ensures that, e.g.,
10952 // it shows up in the right place in the vtable and that we diagnose
10953 // problems with the implicit exception specification.
10954 if (ClassDecl->isDynamicClass() ||
10956 ClassDecl->hasInheritedAssignment())
10958 }
10959
10960 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
10961 ++getASTContext().NumImplicitMoveAssignmentOperators;
10962
10963 // Likewise for the move assignment operator.
10964 if (ClassDecl->isDynamicClass() ||
10966 ClassDecl->hasInheritedAssignment())
10968 }
10969
10970 if (ClassDecl->needsImplicitDestructor()) {
10971 ++getASTContext().NumImplicitDestructors;
10972
10973 // If we have a dynamic class, then the destructor may be virtual, so we
10974 // have to declare the destructor immediately. This ensures that, e.g., it
10975 // shows up in the right place in the vtable and that we diagnose problems
10976 // with the implicit exception specification.
10977 if (ClassDecl->isDynamicClass() ||
10979 DeclareImplicitDestructor(ClassDecl);
10980 }
10981 }
10982
10983 // C++2a [class.compare.default]p3:
10984 // If the member-specification does not explicitly declare any member or
10985 // friend named operator==, an == operator function is declared implicitly
10986 // for each defaulted three-way comparison operator function defined in
10987 // the member-specification
10988 // FIXME: Consider doing this lazily.
10989 // We do this during the initial parse for a class template, not during
10990 // instantiation, so that we can handle unqualified lookups for 'operator=='
10991 // when parsing the template.
10993 llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships;
10995 DefaultedSpaceships);
10996 for (auto *FD : DefaultedSpaceships)
10997 DeclareImplicitEqualityComparison(ClassDecl, FD);
10998 }
10999}
11000
11001unsigned
11003 llvm::function_ref<Scope *()> EnterScope) {
11004 if (!D)
11005 return 0;
11007
11008 // In order to get name lookup right, reenter template scopes in order from
11009 // outermost to innermost.
11011 DeclContext *LookupDC = dyn_cast<DeclContext>(D);
11012
11013 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
11014 for (TemplateParameterList *TPL : DD->getTemplateParameterLists())
11015 ParameterLists.push_back(TPL);
11016
11017 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
11018 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
11019 ParameterLists.push_back(FTD->getTemplateParameters());
11020 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
11021 LookupDC = VD->getDeclContext();
11022
11024 ParameterLists.push_back(VTD->getTemplateParameters());
11025 else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D))
11026 ParameterLists.push_back(PSD->getTemplateParameters());
11027 }
11028 } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
11029 for (TemplateParameterList *TPL : TD->getTemplateParameterLists())
11030 ParameterLists.push_back(TPL);
11031
11032 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
11034 ParameterLists.push_back(CTD->getTemplateParameters());
11035 else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
11036 ParameterLists.push_back(PSD->getTemplateParameters());
11037 }
11038 }
11039 // FIXME: Alias declarations and concepts.
11040
11041 unsigned Count = 0;
11042 Scope *InnermostTemplateScope = nullptr;
11043 for (TemplateParameterList *Params : ParameterLists) {
11044 // Ignore explicit specializations; they don't contribute to the template
11045 // depth.
11046 if (Params->size() == 0)
11047 continue;
11048
11049 InnermostTemplateScope = EnterScope();
11050 for (NamedDecl *Param : *Params) {
11051 if (Param->getDeclName()) {
11052 InnermostTemplateScope->AddDecl(Param);
11053 IdResolver.AddDecl(Param);
11054 }
11055 }
11056 ++Count;
11057 }
11058
11059 // Associate the new template scopes with the corresponding entities.
11060 if (InnermostTemplateScope) {
11061 assert(LookupDC && "no enclosing DeclContext for template lookup");
11062 EnterTemplatedContext(InnermostTemplateScope, LookupDC);
11063 }
11064
11065 return Count;
11066}
11067
11069 if (!RecordD) return;
11070 AdjustDeclIfTemplate(RecordD);
11073}
11074
11076 if (!RecordD) return;
11078}
11079
11081 if (!Param)
11082 return;
11083
11084 S->AddDecl(Param);
11085 if (Param->getDeclName())
11086 IdResolver.AddDecl(Param);
11087}
11088
11091
11092/// ActOnDelayedCXXMethodParameter - We've already started a delayed
11093/// C++ method declaration. We're (re-)introducing the given
11094/// function parameter into scope for use in parsing later parts of
11095/// the method declaration. For example, we could see an
11096/// ActOnParamDefaultArgument event for this parameter.
11098 if (!ParamD)
11099 return;
11100
11101 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
11102
11103 S->AddDecl(Param);
11104 if (Param->getDeclName())
11105 IdResolver.AddDecl(Param);
11106}
11107
11109 if (!MethodD)
11110 return;
11111
11112 AdjustDeclIfTemplate(MethodD);
11113
11115
11116 // Now that we have our default arguments, check the constructor
11117 // again. It could produce additional diagnostics or affect whether
11118 // the class has implicitly-declared destructors, among other
11119 // things.
11120 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
11122
11123 // Check the default arguments, which we may have added.
11124 if (!Method->isInvalidDecl())
11126}
11127
11128// Emit the given diagnostic for each non-address-space qualifier.
11129// Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
11130static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
11132 if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
11133 bool DiagOccurred = false;
11135 [DiagID, &S, &DiagOccurred](DeclSpec::TQ, StringRef QualName,
11136 SourceLocation SL) {
11137 // This diagnostic should be emitted on any qualifier except an addr
11138 // space qualifier. However, forEachQualifier currently doesn't visit
11139 // addr space qualifiers, so there's no way to write this condition
11140 // right now; we just diagnose on everything.
11141 S.Diag(SL, DiagID) << QualName << SourceRange(SL);
11142 DiagOccurred = true;
11143 });
11144 if (DiagOccurred)
11145 D.setInvalidType();
11146 }
11147}
11148
11150 unsigned Kind) {
11151 if (D.isInvalidType() || D.getNumTypeObjects() <= 1)
11152 return;
11153
11155 if (Chunk.Kind == DeclaratorChunk::Paren ||
11157 return;
11158
11159 SourceLocation PointerLoc = Chunk.getSourceRange().getBegin();
11160 S.Diag(PointerLoc, diag::err_invalid_ctor_dtor_decl)
11161 << Kind << Chunk.getSourceRange();
11162 D.setInvalidType();
11163}
11164
11166 StorageClass &SC) {
11167 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
11168
11169 // C++ [class.ctor]p3:
11170 // A constructor shall not be virtual (10.3) or static (9.4). A
11171 // constructor can be invoked for a const, volatile or const
11172 // volatile object. A constructor shall not be declared const,
11173 // volatile, or const volatile (9.3.2).
11174 if (isVirtual) {
11175 if (!D.isInvalidType())
11176 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
11177 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
11179 D.setInvalidType();
11180 }
11181 if (SC == SC_Static) {
11182 if (!D.isInvalidType())
11183 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
11184 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
11186 D.setInvalidType();
11187 SC = SC_None;
11188 }
11189
11190 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
11192 diag::err_constructor_return_type, TypeQuals, SourceLocation(),
11196 D.setInvalidType();
11197 }
11198
11199 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor);
11200 diagnoseInvalidDeclaratorChunks(*this, D, /*constructor*/ 0);
11201
11202 // C++0x [class.ctor]p4:
11203 // A constructor shall not be declared with a ref-qualifier.
11205 if (FTI.hasRefQualifier()) {
11206 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
11209 D.setInvalidType();
11210 }
11211
11212 // Rebuild the function type "R" without any type qualifiers (in
11213 // case any of the errors above fired) and with "void" as the
11214 // return type, since constructors don't have return types.
11215 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
11216 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
11217 return R;
11218
11220 EPI.TypeQuals = Qualifiers();
11221 EPI.RefQualifier = RQ_None;
11222
11223 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
11224}
11225
11227 CXXRecordDecl *ClassDecl
11228 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
11229 if (!ClassDecl)
11230 return Constructor->setInvalidDecl();
11231
11232 // C++ [class.copy]p3:
11233 // A declaration of a constructor for a class X is ill-formed if
11234 // its first parameter is of type (optionally cv-qualified) X and
11235 // either there are no other parameters or else all other
11236 // parameters have default arguments.
11237 if (!Constructor->isInvalidDecl() &&
11238 Constructor->hasOneParamOrDefaultArgs() &&
11239 !Constructor->isFunctionTemplateSpecialization()) {
11240 CanQualType ParamType =
11241 Constructor->getParamDecl(0)->getType()->getCanonicalTypeUnqualified();
11242 CanQualType ClassTy = Context.getCanonicalTagType(ClassDecl);
11243 if (ParamType == ClassTy) {
11244 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
11245 const char *ConstRef
11246 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
11247 : " const &";
11248 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
11249 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
11250
11251 // FIXME: Rather that making the constructor invalid, we should endeavor
11252 // to fix the type.
11253 Constructor->setInvalidDecl();
11254 }
11255 }
11256}
11257
11259 CXXRecordDecl *RD = Destructor->getParent();
11260
11261 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
11262 SourceLocation Loc;
11263
11264 if (!Destructor->isImplicit())
11265 Loc = Destructor->getLocation();
11266 else
11267 Loc = RD->getLocation();
11268
11269 DeclarationName Name =
11270 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
11271 // If we have a virtual destructor, look up the deallocation function
11273 Loc, RD, /*Diagnose=*/true, /*LookForGlobal=*/false, Name)) {
11274 Expr *ThisArg = nullptr;
11275
11276 // If the notional 'delete this' expression requires a non-trivial
11277 // conversion from 'this' to the type of a destroying operator delete's
11278 // first parameter, perform that conversion now.
11279 if (OperatorDelete->isDestroyingOperatorDelete()) {
11280 unsigned AddressParamIndex = 0;
11281 if (OperatorDelete->isTypeAwareOperatorNewOrDelete())
11282 ++AddressParamIndex;
11283 QualType ParamType =
11284 OperatorDelete->getParamDecl(AddressParamIndex)->getType();
11285 if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
11286 // C++ [class.dtor]p13:
11287 // ... as if for the expression 'delete this' appearing in a
11288 // non-virtual destructor of the destructor's class.
11289 ContextRAII SwitchContext(*this, Destructor);
11291 OperatorDelete->getParamDecl(AddressParamIndex)->getLocation());
11292 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
11293 This = PerformImplicitConversion(This.get(), ParamType,
11295 if (This.isInvalid()) {
11296 // FIXME: Register this as a context note so that it comes out
11297 // in the right order.
11298 Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
11299 return true;
11300 }
11301 ThisArg = This.get();
11302 }
11303 }
11304
11305 DiagnoseUseOfDecl(OperatorDelete, Loc);
11306 MarkFunctionReferenced(Loc, OperatorDelete);
11307 Destructor->setOperatorDelete(OperatorDelete, ThisArg);
11308
11309 if (isa<CXXMethodDecl>(OperatorDelete) &&
11310 Context.getTargetInfo().callGlobalDeleteInDeletingDtor(
11311 Context.getLangOpts())) {
11312 // In Microsoft ABI whenever a class has a defined operator delete,
11313 // scalar deleting destructors check the 3rd bit of the implicit
11314 // parameter and if it is set, then, global operator delete must be
11315 // called instead of the class-specific one. Find and save the global
11316 // operator delete for that case. Do not diagnose at this point because
11317 // the lack of a global operator delete is not an error if there are no
11318 // delete calls that require it.
11319 FunctionDecl *GlobalOperatorDelete =
11320 FindDeallocationFunctionForDestructor(Loc, RD, /*Diagnose*/ false,
11321 /*LookForGlobal*/ true, Name);
11322 if (GlobalOperatorDelete) {
11323 MarkFunctionReferenced(Loc, GlobalOperatorDelete);
11324 Destructor->setOperatorGlobalDelete(GlobalOperatorDelete);
11325 }
11326 }
11327
11328 if (Context.getTargetInfo().emitVectorDeletingDtors(
11329 Context.getLangOpts())) {
11330 bool DestructorIsExported = Destructor->hasAttr<DLLExportAttr>();
11331 // Lookup delete[] too in case we have to emit a vector deleting dtor.
11332 DeclarationName VDeleteName =
11333 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
11335 Loc, RD, /*Diagnose*/ false,
11336 /*LookForGlobal*/ false, VDeleteName);
11337 if (ArrOperatorDelete && isa<CXXMethodDecl>(ArrOperatorDelete)) {
11338 FunctionDecl *GlobalArrOperatorDelete =
11339 FindDeallocationFunctionForDestructor(Loc, RD, /*Diagnose*/ false,
11340 /*LookForGlobal*/ true,
11341 VDeleteName);
11342 Destructor->setGlobalOperatorArrayDelete(GlobalArrOperatorDelete);
11343 if (GlobalArrOperatorDelete &&
11344 (Context.classMaybeNeedsVectorDeletingDestructor(RD) ||
11345 DestructorIsExported))
11346 MarkFunctionReferenced(Loc, GlobalArrOperatorDelete);
11347 } else if (!ArrOperatorDelete) {
11348 ArrOperatorDelete = FindDeallocationFunctionForDestructor(
11349 Loc, RD, /*Diagnose*/ false,
11350 /*LookForGlobal*/ true, VDeleteName);
11351 }
11352 Destructor->setOperatorArrayDelete(ArrOperatorDelete);
11353 if (ArrOperatorDelete &&
11354 (Context.classMaybeNeedsVectorDeletingDestructor(RD) ||
11355 DestructorIsExported))
11356 MarkFunctionReferenced(Loc, ArrOperatorDelete);
11357 }
11358 }
11359 }
11360
11361 return false;
11362}
11363
11365 StorageClass& SC) {
11366 // C++ [class.dtor]p1:
11367 // [...] A typedef-name that names a class is a class-name
11368 // (7.1.3); however, a typedef-name that names a class shall not
11369 // be used as the identifier in the declarator for a destructor
11370 // declaration.
11371 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
11372 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
11373 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
11374 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
11375 else if (const TemplateSpecializationType *TST =
11376 DeclaratorType->getAs<TemplateSpecializationType>())
11377 if (TST->isTypeAlias())
11378 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
11379 << DeclaratorType << 1;
11380
11381 // C++ [class.dtor]p2:
11382 // A destructor is used to destroy objects of its class type. A
11383 // destructor takes no parameters, and no return type can be
11384 // specified for it (not even void). The address of a destructor
11385 // shall not be taken. A destructor shall not be static. A
11386 // destructor can be invoked for a const, volatile or const
11387 // volatile object. A destructor shall not be declared const,
11388 // volatile or const volatile (9.3.2).
11389 if (SC == SC_Static) {
11390 if (!D.isInvalidType())
11391 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
11392 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
11395
11396 SC = SC_None;
11397 }
11398 if (!D.isInvalidType()) {
11399 // Destructors don't have return types, but the parser will
11400 // happily parse something like:
11401 //
11402 // class X {
11403 // float ~X();
11404 // };
11405 //
11406 // The return type will be eliminated later.
11407 if (D.getDeclSpec().hasTypeSpecifier())
11408 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
11411 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
11412 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
11418 D.setInvalidType();
11419 }
11420 }
11421
11422 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor);
11423 diagnoseInvalidDeclaratorChunks(*this, D, /*destructor*/ 1);
11424
11425 // C++0x [class.dtor]p2:
11426 // A destructor shall not be declared with a ref-qualifier.
11428 if (FTI.hasRefQualifier()) {
11429 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
11432 D.setInvalidType();
11433 }
11434
11435 // Make sure we don't have any parameters.
11436 if (FTIHasNonVoidParameters(FTI)) {
11437 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
11438
11439 // Delete the parameters.
11440 FTI.freeParams();
11441 D.setInvalidType();
11442 }
11443
11444 // Make sure the destructor isn't variadic.
11445 if (FTI.isVariadic) {
11446 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
11447 D.setInvalidType();
11448 }
11449
11450 // Rebuild the function type "R" without any type qualifiers or
11451 // parameters (in case any of the errors above fired) and with
11452 // "void" as the return type, since destructors don't have return
11453 // types.
11454 if (!D.isInvalidType())
11455 return R;
11456
11457 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
11459 EPI.Variadic = false;
11460 EPI.TypeQuals = Qualifiers();
11461 EPI.RefQualifier = RQ_None;
11462 return Context.getFunctionType(Context.VoidTy, {}, EPI);
11463}
11464
11465static void extendLeft(SourceRange &R, SourceRange Before) {
11466 if (Before.isInvalid())
11467 return;
11468 R.setBegin(Before.getBegin());
11469 if (R.getEnd().isInvalid())
11470 R.setEnd(Before.getEnd());
11471}
11472
11473static void extendRight(SourceRange &R, SourceRange After) {
11474 if (After.isInvalid())
11475 return;
11476 if (R.getBegin().isInvalid())
11477 R.setBegin(After.getBegin());
11478 R.setEnd(After.getEnd());
11479}
11480
11482 StorageClass& SC) {
11483 // C++ [class.conv.fct]p1:
11484 // Neither parameter types nor return type can be specified. The
11485 // type of a conversion function (8.3.5) is "function taking no
11486 // parameter returning conversion-type-id."
11487 if (SC == SC_Static) {
11488 if (!D.isInvalidType())
11489 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
11491 << D.getName().getSourceRange();
11492 D.setInvalidType();
11493 SC = SC_None;
11494 }
11495
11496 TypeSourceInfo *ConvTSI = nullptr;
11497 QualType ConvType =
11499
11500 const DeclSpec &DS = D.getDeclSpec();
11501 if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
11502 // Conversion functions don't have return types, but the parser will
11503 // happily parse something like:
11504 //
11505 // class X {
11506 // float operator bool();
11507 // };
11508 //
11509 // The return type will be changed later anyway.
11510 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
11513 D.setInvalidType();
11514 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
11515 // It's also plausible that the user writes type qualifiers in the wrong
11516 // place, such as:
11517 // struct S { const operator int(); };
11518 // FIXME: we could provide a fixit to move the qualifiers onto the
11519 // conversion type.
11520 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
11521 << SourceRange(D.getIdentifierLoc()) << 0;
11522 D.setInvalidType();
11523 }
11524 const auto *Proto = R->castAs<FunctionProtoType>();
11525 // Make sure we don't have any parameters.
11527 unsigned NumParam = Proto->getNumParams();
11528
11529 // [C++2b]
11530 // A conversion function shall have no non-object parameters.
11531 if (NumParam == 1) {
11533 if (const auto *First =
11534 dyn_cast_if_present<ParmVarDecl>(FTI.Params[0].Param);
11535 First && First->isExplicitObjectParameter())
11536 NumParam--;
11537 }
11538
11539 if (NumParam != 0) {
11540 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
11541 // Delete the parameters.
11542 FTI.freeParams();
11543 D.setInvalidType();
11544 } else if (Proto->isVariadic()) {
11545 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
11546 D.setInvalidType();
11547 }
11548
11549 // Diagnose "&operator bool()" and other such nonsense. This
11550 // is actually a gcc extension which we don't support.
11551 if (Proto->getReturnType() != ConvType) {
11552 bool NeedsTypedef = false;
11553 SourceRange Before, After;
11554
11555 // Walk the chunks and extract information on them for our diagnostic.
11556 bool PastFunctionChunk = false;
11557 for (auto &Chunk : D.type_objects()) {
11558 switch (Chunk.Kind) {
11560 if (!PastFunctionChunk) {
11561 if (Chunk.Fun.HasTrailingReturnType) {
11562 TypeSourceInfo *TRT = nullptr;
11563 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
11564 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
11565 }
11566 PastFunctionChunk = true;
11567 break;
11568 }
11569 [[fallthrough]];
11571 NeedsTypedef = true;
11572 extendRight(After, Chunk.getSourceRange());
11573 break;
11574
11580 extendLeft(Before, Chunk.getSourceRange());
11581 break;
11582
11584 extendLeft(Before, Chunk.Loc);
11585 extendRight(After, Chunk.EndLoc);
11586 break;
11587 }
11588 }
11589
11590 SourceLocation Loc = Before.isValid() ? Before.getBegin() :
11591 After.isValid() ? After.getBegin() :
11592 D.getIdentifierLoc();
11593 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
11594 DB << Before << After;
11595
11596 if (!NeedsTypedef) {
11597 DB << /*don't need a typedef*/0;
11598
11599 // If we can provide a correct fix-it hint, do so.
11600 if (After.isInvalid() && ConvTSI) {
11601 SourceLocation InsertLoc =
11603 DB << FixItHint::CreateInsertion(InsertLoc, " ")
11605 InsertLoc, CharSourceRange::getTokenRange(Before))
11606 << FixItHint::CreateRemoval(Before);
11607 }
11608 } else if (!Proto->getReturnType()->isDependentType()) {
11609 DB << /*typedef*/1 << Proto->getReturnType();
11610 } else if (getLangOpts().CPlusPlus11) {
11611 DB << /*alias template*/2 << Proto->getReturnType();
11612 } else {
11613 DB << /*might not be fixable*/3;
11614 }
11615
11616 // Recover by incorporating the other type chunks into the result type.
11617 // Note, this does *not* change the name of the function. This is compatible
11618 // with the GCC extension:
11619 // struct S { &operator int(); } s;
11620 // int &r = s.operator int(); // ok in GCC
11621 // S::operator int&() {} // error in GCC, function name is 'operator int'.
11622 ConvType = Proto->getReturnType();
11623 }
11624
11625 // C++ [class.conv.fct]p4:
11626 // The conversion-type-id shall not represent a function type nor
11627 // an array type.
11628 if (ConvType->isArrayType()) {
11629 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
11630 ConvType = Context.getPointerType(ConvType);
11631 D.setInvalidType();
11632 } else if (ConvType->isFunctionType()) {
11633 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
11634 ConvType = Context.getPointerType(ConvType);
11635 D.setInvalidType();
11636 }
11637
11638 // Rebuild the function type "R" without any parameters (in case any
11639 // of the errors above fired) and with the conversion type as the
11640 // return type.
11641 if (D.isInvalidType())
11642 R = Context.getFunctionType(ConvType, {}, Proto->getExtProtoInfo());
11643
11644 // C++0x explicit conversion operators.
11648 ? diag::warn_cxx98_compat_explicit_conversion_functions
11649 : diag::ext_explicit_conversion_functions)
11651}
11652
11654 assert(Conversion && "Expected to receive a conversion function declaration");
11655
11656 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
11657
11658 // Make sure we aren't redeclaring the conversion function.
11659 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
11660 // C++ [class.conv.fct]p1:
11661 // [...] A conversion function is never used to convert a
11662 // (possibly cv-qualified) object to the (possibly cv-qualified)
11663 // same object type (or a reference to it), to a (possibly
11664 // cv-qualified) base class of that type (or a reference to it),
11665 // or to (possibly cv-qualified) void.
11666 CanQualType ClassType = Context.getCanonicalTagType(ClassDecl);
11667 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
11668 ConvType = ConvTypeRef->getPointeeType();
11669 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
11671 /* Suppress diagnostics for instantiations. */;
11672 else if (Conversion->size_overridden_methods() != 0)
11673 /* Suppress diagnostics for overriding virtual function in a base class. */;
11674 else if (ConvType->isRecordType()) {
11675 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
11676 if (ConvType == ClassType)
11677 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
11678 << ClassType;
11679 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
11680 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
11681 << ClassType << ConvType;
11682 } else if (ConvType->isVoidType()) {
11683 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
11684 << ClassType << ConvType;
11685 }
11686
11687 if (FunctionTemplateDecl *ConversionTemplate =
11688 Conversion->getDescribedFunctionTemplate()) {
11689 if (const auto *ConvTypePtr = ConvType->getAs<PointerType>()) {
11690 ConvType = ConvTypePtr->getPointeeType();
11691 }
11692 if (ConvType->isUndeducedAutoType()) {
11693 Diag(Conversion->getTypeSpecStartLoc(), diag::err_auto_not_allowed)
11694 << getReturnTypeLoc(Conversion).getSourceRange()
11695 << ConvType->castAs<AutoType>()->getKeyword()
11696 << /* in declaration of conversion function template= */ 24;
11697 }
11698
11699 return ConversionTemplate;
11700 }
11701
11702 return Conversion;
11703}
11704
11709
11713
11715 DeclarationName Name, QualType R,
11716 bool IsLambda, DeclContext *DC) {
11717 if (!D.isFunctionDeclarator())
11718 return;
11719
11721 if (FTI.NumParams == 0)
11722 return;
11723 ParmVarDecl *ExplicitObjectParam = nullptr;
11724 for (unsigned Idx = 0; Idx < FTI.NumParams; Idx++) {
11725 const auto &ParamInfo = FTI.Params[Idx];
11726 if (!ParamInfo.Param)
11727 continue;
11728 ParmVarDecl *Param = cast<ParmVarDecl>(ParamInfo.Param);
11729 if (!Param->isExplicitObjectParameter())
11730 continue;
11731 if (Idx == 0) {
11732 ExplicitObjectParam = Param;
11733 continue;
11734 } else {
11735 Diag(Param->getLocation(),
11736 diag::err_explicit_object_parameter_must_be_first)
11737 << IsLambda << Param->getSourceRange();
11738 }
11739 }
11740 if (!ExplicitObjectParam)
11741 return;
11742
11743 if (ExplicitObjectParam->hasDefaultArg()) {
11744 Diag(ExplicitObjectParam->getLocation(),
11745 diag::err_explicit_object_default_arg)
11746 << ExplicitObjectParam->getSourceRange();
11747 D.setInvalidType();
11748 }
11749
11752 D.isStaticMember())) {
11753 Diag(ExplicitObjectParam->getBeginLoc(),
11754 diag::err_explicit_object_parameter_nonmember)
11755 << D.getSourceRange() << /*static=*/0 << IsLambda;
11756 D.setInvalidType();
11757 }
11758
11759 if (D.getDeclSpec().isVirtualSpecified()) {
11760 Diag(ExplicitObjectParam->getBeginLoc(),
11761 diag::err_explicit_object_parameter_nonmember)
11762 << D.getSourceRange() << /*virtual=*/1 << IsLambda;
11763 D.setInvalidType();
11764 }
11765
11766 // Friend declarations require some care. Consider:
11767 //
11768 // namespace N {
11769 // struct A{};
11770 // int f(A);
11771 // }
11772 //
11773 // struct S {
11774 // struct T {
11775 // int f(this T);
11776 // };
11777 //
11778 // friend int T::f(this T); // Allow this.
11779 // friend int f(this S); // But disallow this.
11780 // friend int N::f(this A); // And disallow this.
11781 // };
11782 //
11783 // Here, it seems to suffice to check whether the scope
11784 // specifier designates a class type.
11785 if (D.getDeclSpec().isFriendSpecified() &&
11786 !isa_and_present<CXXRecordDecl>(
11788 Diag(ExplicitObjectParam->getBeginLoc(),
11789 diag::err_explicit_object_parameter_nonmember)
11790 << D.getSourceRange() << /*non-member=*/2 << IsLambda;
11791 D.setInvalidType();
11792 }
11793
11794 if (IsLambda && FTI.hasMutableQualifier()) {
11795 Diag(ExplicitObjectParam->getBeginLoc(),
11796 diag::err_explicit_object_parameter_mutable)
11797 << D.getSourceRange();
11798 }
11799
11800 if (IsLambda)
11801 return;
11802
11803 if (!DC || !DC->isRecord()) {
11804 assert(D.isInvalidType() && "Explicit object parameter in non-member "
11805 "should have been diagnosed already");
11806 return;
11807 }
11808
11809 // CWG2674: constructors and destructors cannot have explicit parameters.
11812 Diag(ExplicitObjectParam->getBeginLoc(),
11813 diag::err_explicit_object_parameter_constructor)
11815 << D.getSourceRange();
11816 D.setInvalidType();
11817 }
11818}
11819
11820namespace {
11821/// Utility class to accumulate and print a diagnostic listing the invalid
11822/// specifier(s) on a declaration.
11823struct BadSpecifierDiagnoser {
11824 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
11825 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
11826 ~BadSpecifierDiagnoser() {
11827 Diagnostic << Specifiers;
11828 }
11829
11830 template<typename T> void check(SourceLocation SpecLoc, T Spec) {
11831 return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
11832 }
11833 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
11834 return check(SpecLoc,
11836 }
11837 void check(SourceLocation SpecLoc, const char *Spec) {
11838 if (SpecLoc.isInvalid()) return;
11839 Diagnostic << SourceRange(SpecLoc, SpecLoc);
11840 if (!Specifiers.empty()) Specifiers += " ";
11841 Specifiers += Spec;
11842 }
11843
11844 Sema &S;
11845 Sema::SemaDiagnosticBuilder Diagnostic;
11846 std::string Specifiers;
11847};
11848}
11849
11851 StorageClass &SC) {
11852 TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
11853 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
11854 assert(GuidedTemplateDecl && "missing template decl for deduction guide");
11855
11856 // C++ [temp.deduct.guide]p3:
11857 // A deduction-gide shall be declared in the same scope as the
11858 // corresponding class template.
11859 if (!CurContext->getRedeclContext()->Equals(
11860 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
11861 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
11862 << GuidedTemplateDecl;
11863 NoteTemplateLocation(*GuidedTemplateDecl);
11864 }
11865
11866 auto &DS = D.getMutableDeclSpec();
11867 // We leave 'friend' and 'virtual' to be rejected in the normal way.
11868 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
11869 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
11870 DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
11871 BadSpecifierDiagnoser Diagnoser(
11872 *this, D.getIdentifierLoc(),
11873 diag::err_deduction_guide_invalid_specifier);
11874
11875 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
11876 DS.ClearStorageClassSpecs();
11877 SC = SC_None;
11878
11879 // 'explicit' is permitted.
11880 Diagnoser.check(DS.getInlineSpecLoc(), "inline");
11881 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
11882 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
11883 DS.ClearConstexprSpec();
11884
11885 Diagnoser.check(DS.getConstSpecLoc(), "const");
11886 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
11887 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
11888 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
11889 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
11890 DS.ClearTypeQualifiers();
11891
11892 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
11893 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
11894 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
11895 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
11896 DS.ClearTypeSpecType();
11897 }
11898
11899 if (D.isInvalidType())
11900 return true;
11901
11902 // Check the declarator is simple enough.
11903 bool FoundFunction = false;
11904 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
11905 if (Chunk.Kind == DeclaratorChunk::Paren)
11906 continue;
11907 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
11909 diag::err_deduction_guide_with_complex_decl)
11910 << D.getSourceRange();
11911 break;
11912 }
11913 if (!Chunk.Fun.hasTrailingReturnType())
11914 return Diag(D.getName().getBeginLoc(),
11915 diag::err_deduction_guide_no_trailing_return_type);
11916
11917 // Check that the return type is written as a specialization of
11918 // the template specified as the deduction-guide's name.
11919 // The template name may not be qualified. [temp.deduct.guide]
11920 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
11921 TypeSourceInfo *TSI = nullptr;
11922 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
11923 assert(TSI && "deduction guide has valid type but invalid return type?");
11924 bool AcceptableReturnType = false;
11925 bool MightInstantiateToSpecialization = false;
11926 if (auto RetTST =
11928 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
11929 bool TemplateMatches = Context.hasSameTemplateName(
11930 SpecifiedName, GuidedTemplate, /*IgnoreDeduced=*/true);
11931
11933 SpecifiedName.getAsQualifiedTemplateName();
11934 // A Template template parameter is never wrapped in a
11935 // QualifiedTemplateName, but it's always simply-written.
11936 bool SimplyWritten = !Qualifiers || (!Qualifiers->hasTemplateKeyword() &&
11937 !Qualifiers->getQualifier());
11938 if (SimplyWritten && TemplateMatches)
11939 AcceptableReturnType = true;
11940 else {
11941 // This could still instantiate to the right type, unless we know it
11942 // names the wrong class template.
11943 auto *TD = SpecifiedName.getAsTemplateDecl();
11944 MightInstantiateToSpecialization =
11945 !(TD && isa<ClassTemplateDecl>(TD) && !TemplateMatches);
11946 }
11947 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
11948 MightInstantiateToSpecialization = true;
11949 }
11950
11951 if (!AcceptableReturnType)
11952 return Diag(TSI->getTypeLoc().getBeginLoc(),
11953 diag::err_deduction_guide_bad_trailing_return_type)
11954 << GuidedTemplate << TSI->getType()
11955 << MightInstantiateToSpecialization
11956 << TSI->getTypeLoc().getSourceRange();
11957
11958 // Keep going to check that we don't have any inner declarator pieces (we
11959 // could still have a function returning a pointer to a function).
11960 FoundFunction = true;
11961 }
11962
11963 if (D.isFunctionDefinition())
11964 // we can still create a valid deduction guide here.
11965 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
11966 return false;
11967}
11968
11969//===----------------------------------------------------------------------===//
11970// Namespace Handling
11971//===----------------------------------------------------------------------===//
11972
11973/// Diagnose a mismatch in 'inline' qualifiers when a namespace is
11974/// reopened.
11976 SourceLocation Loc,
11977 IdentifierInfo *II, bool *IsInline,
11978 NamespaceDecl *PrevNS) {
11979 assert(*IsInline != PrevNS->isInline());
11980
11981 // 'inline' must appear on the original definition, but not necessarily
11982 // on all extension definitions, so the note should point to the first
11983 // definition to avoid confusion.
11984 PrevNS = PrevNS->getFirstDecl();
11985
11986 if (PrevNS->isInline())
11987 // The user probably just forgot the 'inline', so suggest that it
11988 // be added back.
11989 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
11990 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
11991 else
11992 S.Diag(Loc, diag::err_inline_namespace_mismatch);
11993
11994 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
11995 *IsInline = PrevNS->isInline();
11996}
11997
11998/// ActOnStartNamespaceDef - This is called at the start of a namespace
11999/// definition.
12001 SourceLocation InlineLoc,
12002 SourceLocation NamespaceLoc,
12003 SourceLocation IdentLoc, IdentifierInfo *II,
12004 SourceLocation LBrace,
12005 const ParsedAttributesView &AttrList,
12006 UsingDirectiveDecl *&UD, bool IsNested) {
12007 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
12008 // For anonymous namespace, take the location of the left brace.
12009 SourceLocation Loc = II ? IdentLoc : LBrace;
12010 bool IsInline = InlineLoc.isValid();
12011 bool IsInvalid = false;
12012 bool IsStd = false;
12013 bool AddToKnown = false;
12014 Scope *DeclRegionScope = NamespcScope->getParent();
12015
12016 NamespaceDecl *PrevNS = nullptr;
12017 if (II) {
12018 // C++ [namespace.std]p7:
12019 // A translation unit shall not declare namespace std to be an inline
12020 // namespace (9.8.2).
12021 //
12022 // Precondition: the std namespace is in the file scope and is declared to
12023 // be inline
12024 auto DiagnoseInlineStdNS = [&]() {
12025 assert(IsInline && II->isStr("std") &&
12026 CurContext->getRedeclContext()->isTranslationUnit() &&
12027 "Precondition of DiagnoseInlineStdNS not met");
12028 Diag(InlineLoc, diag::err_inline_namespace_std)
12029 << SourceRange(InlineLoc, InlineLoc.getLocWithOffset(6));
12030 IsInline = false;
12031 };
12032 // C++ [namespace.def]p2:
12033 // The identifier in an original-namespace-definition shall not
12034 // have been previously defined in the declarative region in
12035 // which the original-namespace-definition appears. The
12036 // identifier in an original-namespace-definition is the name of
12037 // the namespace. Subsequently in that declarative region, it is
12038 // treated as an original-namespace-name.
12039 //
12040 // Since namespace names are unique in their scope, and we don't
12041 // look through using directives, just look for any ordinary names
12042 // as if by qualified name lookup.
12043 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
12045 LookupQualifiedName(R, CurContext->getRedeclContext());
12046 NamedDecl *PrevDecl =
12047 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
12048 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
12049
12050 if (PrevNS) {
12051 // This is an extended namespace definition.
12052 if (IsInline && II->isStr("std") &&
12053 CurContext->getRedeclContext()->isTranslationUnit())
12054 DiagnoseInlineStdNS();
12055 else if (IsInline != PrevNS->isInline())
12056 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
12057 &IsInline, PrevNS);
12058 } else if (PrevDecl) {
12059 // This is an invalid name redefinition.
12060 Diag(Loc, diag::err_redefinition_different_kind)
12061 << II;
12062 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12063 IsInvalid = true;
12064 // Continue on to push Namespc as current DeclContext and return it.
12065 } else if (II->isStr("std") &&
12066 CurContext->getRedeclContext()->isTranslationUnit()) {
12067 if (IsInline)
12068 DiagnoseInlineStdNS();
12069 // This is the first "real" definition of the namespace "std", so update
12070 // our cache of the "std" namespace to point at this definition.
12071 PrevNS = getStdNamespace();
12072 IsStd = true;
12073 AddToKnown = !IsInline;
12074 } else {
12075 // We've seen this namespace for the first time.
12076 AddToKnown = !IsInline;
12077 }
12078 } else {
12079 // Anonymous namespaces.
12080
12081 // Determine whether the parent already has an anonymous namespace.
12082 DeclContext *Parent = CurContext->getRedeclContext();
12083 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
12084 PrevNS = TU->getAnonymousNamespace();
12085 } else {
12086 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
12087 PrevNS = ND->getAnonymousNamespace();
12088 }
12089
12090 if (PrevNS && IsInline != PrevNS->isInline())
12091 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
12092 &IsInline, PrevNS);
12093 }
12094
12096 Context, CurContext, IsInline, StartLoc, Loc, II, PrevNS, IsNested);
12097 if (IsInvalid)
12098 Namespc->setInvalidDecl();
12099
12100 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
12101 AddPragmaAttributes(DeclRegionScope, Namespc);
12102 ProcessAPINotes(Namespc);
12103
12104 // FIXME: Should we be merging attributes?
12105 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
12107
12108 if (IsStd)
12109 StdNamespace = Namespc;
12110 if (AddToKnown)
12111 KnownNamespaces[Namespc] = false;
12112
12113 if (II) {
12114 PushOnScopeChains(Namespc, DeclRegionScope);
12115 } else {
12116 // Link the anonymous namespace into its parent.
12117 DeclContext *Parent = CurContext->getRedeclContext();
12118 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
12119 TU->setAnonymousNamespace(Namespc);
12120 } else {
12121 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
12122 }
12123
12124 CurContext->addDecl(Namespc);
12125
12126 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
12127 // behaves as if it were replaced by
12128 // namespace unique { /* empty body */ }
12129 // using namespace unique;
12130 // namespace unique { namespace-body }
12131 // where all occurrences of 'unique' in a translation unit are
12132 // replaced by the same identifier and this identifier differs
12133 // from all other identifiers in the entire program.
12134
12135 // We just create the namespace with an empty name and then add an
12136 // implicit using declaration, just like the standard suggests.
12137 //
12138 // CodeGen enforces the "universally unique" aspect by giving all
12139 // declarations semantically contained within an anonymous
12140 // namespace internal linkage.
12141
12142 if (!PrevNS) {
12144 /* 'using' */ LBrace,
12145 /* 'namespace' */ SourceLocation(),
12146 /* qualifier */ NestedNameSpecifierLoc(),
12147 /* identifier */ SourceLocation(),
12148 Namespc,
12149 /* Ancestor */ Parent);
12150 UD->setImplicit();
12151 Parent->addDecl(UD);
12152 }
12153 }
12154
12155 ActOnDocumentableDecl(Namespc);
12156
12157 // Although we could have an invalid decl (i.e. the namespace name is a
12158 // redefinition), push it as current DeclContext and try to continue parsing.
12159 // FIXME: We should be able to push Namespc here, so that the each DeclContext
12160 // for the namespace has the declarations that showed up in that particular
12161 // namespace definition.
12162 PushDeclContext(NamespcScope, Namespc);
12163 return Namespc;
12164}
12165
12166/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
12167/// is a namespace alias, returns the namespace it points to.
12169 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
12170 return AD->getNamespace();
12171 return dyn_cast_or_null<NamespaceDecl>(D);
12172}
12173
12175 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
12176 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
12177 Namespc->setRBraceLoc(RBrace);
12179 if (Namespc->hasAttr<VisibilityAttr>())
12180 PopPragmaVisibility(true, RBrace);
12181 // If this namespace contains an export-declaration, export it now.
12182 if (DeferredExportedNamespaces.erase(Namespc))
12184}
12185
12187 return cast_or_null<CXXRecordDecl>(
12188 StdBadAlloc.get(Context.getExternalSource()));
12189}
12190
12192 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
12193}
12194
12196 return cast_or_null<NamespaceDecl>(
12197 StdNamespace.get(Context.getExternalSource()));
12198}
12199
12200namespace {
12201
12202enum UnsupportedSTLSelect {
12203 USS_InvalidMember,
12204 USS_MissingMember,
12205 USS_NonTrivial,
12206 USS_Other
12207};
12208
12209struct InvalidSTLDiagnoser {
12210 Sema &S;
12211 SourceLocation Loc;
12212 QualType TyForDiags;
12213
12214 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
12215 const VarDecl *VD = nullptr) {
12216 {
12217 auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
12218 << TyForDiags << ((int)Sel);
12219 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
12220 assert(!Name.empty());
12221 D << Name;
12222 }
12223 }
12224 if (Sel == USS_InvalidMember) {
12225 S.Diag(VD->getLocation(), diag::note_var_declared_here)
12226 << VD << VD->getSourceRange();
12227 }
12228 return QualType();
12229 }
12230};
12231} // namespace
12232
12234 SourceLocation Loc,
12236 assert(getLangOpts().CPlusPlus &&
12237 "Looking for comparison category type outside of C++.");
12238
12239 // Use an elaborated type for diagnostics which has a name containing the
12240 // prepended 'std' namespace but not any inline namespace names.
12241 auto TyForDiags = [&](ComparisonCategoryInfo *Info) {
12243 /*Prefix=*/std::nullopt);
12244 return Context.getTagType(ElaboratedTypeKeyword::None, Qualifier,
12245 Info->Record,
12246 /*OwnsTag=*/false);
12247 };
12248
12249 // Check if we've already successfully checked the comparison category type
12250 // before. If so, skip checking it again.
12251 ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
12252 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) {
12253 // The only thing we need to check is that the type has a reachable
12254 // definition in the current context.
12255 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
12256 return QualType();
12257
12258 return Info->getType();
12259 }
12260
12261 // If lookup failed
12262 if (!Info) {
12263 std::string NameForDiags = "std::";
12264 NameForDiags += ComparisonCategories::getCategoryString(Kind);
12265 Diag(Loc, diag::err_implied_comparison_category_type_not_found)
12266 << NameForDiags << (int)Usage;
12267 return QualType();
12268 }
12269
12270 assert(Info->Kind == Kind);
12271 assert(Info->Record);
12272
12273 // Update the Record decl in case we encountered a forward declaration on our
12274 // first pass. FIXME: This is a bit of a hack.
12275 if (Info->Record->hasDefinition())
12276 Info->Record = Info->Record->getDefinition();
12277
12278 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
12279 return QualType();
12280
12281 InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)};
12282
12283 if (!Info->Record->isTriviallyCopyable())
12284 return UnsupportedSTLError(USS_NonTrivial);
12285
12286 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
12287 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
12288 // Tolerate empty base classes.
12289 if (Base->isEmpty())
12290 continue;
12291 // Reject STL implementations which have at least one non-empty base.
12292 return UnsupportedSTLError();
12293 }
12294
12295 // Check that the STL has implemented the types using a single integer field.
12296 // This expectation allows better codegen for builtin operators. We require:
12297 // (1) The class has exactly one field.
12298 // (2) The field is an integral or enumeration type.
12299 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
12300 if (std::distance(FIt, FEnd) != 1 ||
12301 !FIt->getType()->isIntegralOrEnumerationType()) {
12302 return UnsupportedSTLError();
12303 }
12304
12305 // Build each of the require values and store them in Info.
12306 for (ComparisonCategoryResult CCR :
12308 StringRef MemName = ComparisonCategories::getResultString(CCR);
12309 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
12310
12311 if (!ValInfo)
12312 return UnsupportedSTLError(USS_MissingMember, MemName);
12313
12314 VarDecl *VD = ValInfo->VD;
12315 assert(VD && "should not be null!");
12316
12317 // Attempt to diagnose reasons why the STL definition of this type
12318 // might be foobar, including it failing to be a constant expression.
12319 // TODO Handle more ways the lookup or result can be invalid.
12320 if (!VD->isStaticDataMember() ||
12322 return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
12323
12324 // Attempt to evaluate the var decl as a constant expression and extract
12325 // the value of its first field as a ICE. If this fails, the STL
12326 // implementation is not supported.
12327 if (!ValInfo->hasValidIntValue())
12328 return UnsupportedSTLError();
12329
12330 MarkVariableReferenced(Loc, VD);
12331 }
12332
12333 // We've successfully built the required types and expressions. Update
12334 // the cache and return the newly cached value.
12335 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
12336 return Info->getType();
12337}
12338
12340 if (!StdNamespace) {
12341 // The "std" namespace has not yet been defined, so build one implicitly.
12343 Context, Context.getTranslationUnitDecl(),
12344 /*Inline=*/false, SourceLocation(), SourceLocation(),
12345 &PP.getIdentifierTable().get("std"),
12346 /*PrevDecl=*/nullptr, /*Nested=*/false);
12347 getStdNamespace()->setImplicit(true);
12348 // We want the created NamespaceDecl to be available for redeclaration
12349 // lookups, but not for regular name lookups.
12350 Context.getTranslationUnitDecl()->addDecl(getStdNamespace());
12351 getStdNamespace()->clearIdentifierNamespace();
12352 }
12353
12354 return getStdNamespace();
12355}
12356
12357static bool isStdClassTemplate(Sema &S, QualType SugaredType, QualType *TypeArg,
12358 const char *ClassName,
12359 ClassTemplateDecl **CachedDecl,
12360 const Decl **MalformedDecl) {
12361 // We're looking for implicit instantiations of
12362 // template <typename U> class std::{ClassName}.
12363
12364 if (!S.StdNamespace) // If we haven't seen namespace std yet, this can't be
12365 // it.
12366 return false;
12367
12368 auto ReportMatchingNameAsMalformed = [&](NamedDecl *D) {
12369 if (!MalformedDecl)
12370 return;
12371 if (!D)
12372 D = SugaredType->getAsTagDecl();
12373 if (!D || !D->isInStdNamespace())
12374 return;
12375 IdentifierInfo *II = D->getDeclName().getAsIdentifierInfo();
12376 if (II && II == &S.PP.getIdentifierTable().get(ClassName))
12377 *MalformedDecl = D;
12378 };
12379
12380 ClassTemplateDecl *Template = nullptr;
12382 if (const TemplateSpecializationType *TST =
12384 Template = dyn_cast_or_null<ClassTemplateDecl>(
12385 TST->getTemplateName().getAsTemplateDecl());
12386 Arguments = TST->template_arguments();
12387 } else if (const auto *TT = SugaredType->getAs<TagType>()) {
12388 Template = TT->getTemplateDecl();
12389 Arguments = TT->getTemplateArgs(S.Context);
12390 }
12391
12392 if (!Template) {
12393 ReportMatchingNameAsMalformed(SugaredType->getAsTagDecl());
12394 return false;
12395 }
12396
12397 if (!*CachedDecl) {
12398 // Haven't recognized std::{ClassName} yet, maybe this is it.
12399 // FIXME: It seems we should just reuse LookupStdClassTemplate but the
12400 // semantics of this are slightly different, most notably the existing
12401 // "lookup" semantics explicitly diagnose an invalid definition as an
12402 // error.
12403 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
12404 if (TemplateClass->getIdentifier() !=
12405 &S.PP.getIdentifierTable().get(ClassName) ||
12407 TemplateClass->getNonTransparentDeclContext()))
12408 return false;
12409 // This is a template called std::{ClassName}, but is it the right
12410 // template?
12411 TemplateParameterList *Params = Template->getTemplateParameters();
12412 if (Params->getMinRequiredArguments() != 1 ||
12413 !isa<TemplateTypeParmDecl>(Params->getParam(0)) ||
12414 Params->getParam(0)->isTemplateParameterPack()) {
12415 if (MalformedDecl)
12416 *MalformedDecl = TemplateClass;
12417 return false;
12418 }
12419
12420 // It's the right template.
12421 *CachedDecl = Template;
12422 }
12423
12424 if (Template->getCanonicalDecl() != (*CachedDecl)->getCanonicalDecl())
12425 return false;
12426
12427 // This is an instance of std::{ClassName}. Find the argument type.
12428 if (TypeArg) {
12429 QualType ArgType = Arguments[0].getAsType();
12430 // FIXME: Since TST only has as-written arguments, we have to perform the
12431 // only kind of conversion applicable to type arguments; in Objective-C ARC:
12432 // - If an explicitly-specified template argument type is a lifetime type
12433 // with no lifetime qualifier, the __strong lifetime qualifier is
12434 // inferred.
12435 if (S.getLangOpts().ObjCAutoRefCount && ArgType->isObjCLifetimeType() &&
12436 !ArgType.getObjCLifetime()) {
12437 Qualifiers Qs;
12439 ArgType = S.Context.getQualifiedType(ArgType, Qs);
12440 }
12441 *TypeArg = ArgType;
12442 }
12443
12444 return true;
12445}
12446
12448 assert(getLangOpts().CPlusPlus &&
12449 "Looking for std::initializer_list outside of C++.");
12450
12451 // We're looking for implicit instantiations of
12452 // template <typename E> class std::initializer_list.
12453
12454 return isStdClassTemplate(*this, Ty, Element, "initializer_list",
12455 &StdInitializerList, /*MalformedDecl=*/nullptr);
12456}
12457
12459 const Decl **MalformedDecl) {
12460 assert(getLangOpts().CPlusPlus &&
12461 "Looking for std::type_identity outside of C++.");
12462
12463 // We're looking for implicit instantiations of
12464 // template <typename T> struct std::type_identity.
12465
12466 return isStdClassTemplate(*this, Ty, Element, "type_identity",
12467 &StdTypeIdentity, MalformedDecl);
12468}
12469
12471 const char *ClassName,
12472 bool *WasMalformed) {
12473 if (!S.StdNamespace)
12474 return nullptr;
12475
12476 LookupResult Result(S, &S.PP.getIdentifierTable().get(ClassName), Loc,
12479 return nullptr;
12480
12482 if (!Template) {
12483 Result.suppressDiagnostics();
12484 // We found something weird. Complain about the first thing we found.
12485 NamedDecl *Found = *Result.begin();
12486 S.Diag(Found->getLocation(), diag::err_malformed_std_class_template)
12487 << ClassName;
12488 if (WasMalformed)
12489 *WasMalformed = true;
12490 return nullptr;
12491 }
12492
12493 // We found some template with the correct name. Now verify that it's
12494 // correct.
12495 TemplateParameterList *Params = Template->getTemplateParameters();
12496 if (Params->getMinRequiredArguments() != 1 ||
12497 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
12498 S.Diag(Template->getLocation(), diag::err_malformed_std_class_template)
12499 << ClassName;
12500 if (WasMalformed)
12501 *WasMalformed = true;
12502 return nullptr;
12503 }
12504
12505 return Template;
12506}
12507
12509 QualType TypeParam, SourceLocation Loc) {
12510 assert(S.getStdNamespace());
12511 TemplateArgumentListInfo Args(Loc, Loc);
12512 auto TSI = S.Context.getTrivialTypeSourceInfo(TypeParam, Loc);
12513 Args.addArgument(TemplateArgumentLoc(TemplateArgument(TypeParam), TSI));
12514
12516 Loc, Args, /*Scope=*/nullptr,
12517 /*ForNestedNameSpecifier=*/false);
12518}
12519
12521 if (!StdInitializerList) {
12522 bool WasMalformed = false;
12524 LookupStdClassTemplate(*this, Loc, "initializer_list", &WasMalformed);
12525 if (!StdInitializerList) {
12526 if (!WasMalformed)
12527 Diag(Loc, diag::err_implied_std_initializer_list_not_found);
12528 return QualType();
12529 }
12530 }
12531 return BuildStdClassTemplate(*this, StdInitializerList, Element, Loc);
12532}
12533
12535 if (!StdTypeIdentity) {
12536 StdTypeIdentity = LookupStdClassTemplate(*this, Loc, "type_identity",
12537 /*WasMalformed=*/nullptr);
12538 if (!StdTypeIdentity)
12539 return QualType();
12540 }
12541 return BuildStdClassTemplate(*this, StdTypeIdentity, Type, Loc);
12542}
12543
12545 // C++ [dcl.init.list]p2:
12546 // A constructor is an initializer-list constructor if its first parameter
12547 // is of type std::initializer_list<E> or reference to possibly cv-qualified
12548 // std::initializer_list<E> for some type E, and either there are no other
12549 // parameters or else all other parameters have default arguments.
12550 if (!Ctor->hasOneParamOrDefaultArgs())
12551 return false;
12552
12553 QualType ArgType = Ctor->getParamDecl(0)->getType();
12554 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
12555 ArgType = RT->getPointeeType().getUnqualifiedType();
12556
12557 return isStdInitializerList(ArgType, nullptr);
12558}
12559
12560/// Determine whether a using statement is in a context where it will be
12561/// apply in all contexts.
12563 switch (CurContext->getDeclKind()) {
12564 case Decl::TranslationUnit:
12565 return true;
12566 case Decl::LinkageSpec:
12567 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
12568 default:
12569 return false;
12570 }
12571}
12572
12573namespace {
12574
12575// Callback to only accept typo corrections that are namespaces.
12576class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
12577public:
12578 bool ValidateCandidate(const TypoCorrection &candidate) override {
12579 if (NamedDecl *ND = candidate.getCorrectionDecl())
12581 return false;
12582 }
12583
12584 std::unique_ptr<CorrectionCandidateCallback> clone() override {
12585 return std::make_unique<NamespaceValidatorCCC>(*this);
12586 }
12587};
12588
12589}
12590
12591static void DiagnoseInvisibleNamespace(const TypoCorrection &Corrected,
12592 Sema &S) {
12593 auto *ND = cast<NamespaceDecl>(Corrected.getFoundDecl());
12594 Module *M = ND->getOwningModule();
12595 assert(M && "hidden namespace definition not in a module?");
12596
12597 if (M->isExplicitGlobalModule())
12598 S.Diag(Corrected.getCorrectionRange().getBegin(),
12599 diag::err_module_unimported_use_header)
12601 << /*Header Name*/ false;
12602 else
12603 S.Diag(Corrected.getCorrectionRange().getBegin(),
12604 diag::err_module_unimported_use)
12606 << M->getTopLevelModuleName();
12607}
12608
12610 CXXScopeSpec &SS,
12611 SourceLocation IdentLoc,
12612 IdentifierInfo *Ident) {
12613 R.clear();
12614 NamespaceValidatorCCC CCC{};
12615 if (TypoCorrection Corrected =
12616 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
12618 // Generally we find it is confusing more than helpful to diagnose the
12619 // invisible namespace.
12620 // See https://github.com/llvm/llvm-project/issues/73893.
12621 //
12622 // However, we should diagnose when the users are trying to using an
12623 // invisible namespace. So we handle the case specially here.
12624 if (isa_and_nonnull<NamespaceDecl>(Corrected.getFoundDecl()) &&
12625 Corrected.requiresImport()) {
12626 DiagnoseInvisibleNamespace(Corrected, S);
12627 } else if (DeclContext *DC = S.computeDeclContext(SS, false)) {
12628 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
12629 bool DroppedSpecifier =
12630 Corrected.WillReplaceSpecifier() && Ident->getName() == CorrectedStr;
12631 S.diagnoseTypo(Corrected,
12632 S.PDiag(diag::err_using_directive_member_suggest)
12633 << Ident << DC << DroppedSpecifier << SS.getRange(),
12634 S.PDiag(diag::note_namespace_defined_here));
12635 } else {
12636 S.diagnoseTypo(Corrected,
12637 S.PDiag(diag::err_using_directive_suggest) << Ident,
12638 S.PDiag(diag::note_namespace_defined_here));
12639 }
12640 R.addDecl(Corrected.getFoundDecl());
12641 return true;
12642 }
12643 return false;
12644}
12645
12647 SourceLocation NamespcLoc, CXXScopeSpec &SS,
12648 SourceLocation IdentLoc,
12649 IdentifierInfo *NamespcName,
12650 const ParsedAttributesView &AttrList) {
12651 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
12652 assert(NamespcName && "Invalid NamespcName.");
12653 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
12654
12655 // Get the innermost enclosing declaration scope.
12656 S = S->getDeclParent();
12657
12658 UsingDirectiveDecl *UDir = nullptr;
12659 NestedNameSpecifier Qualifier = SS.getScopeRep();
12660
12661 // Lookup namespace name.
12662 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
12663 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
12664 if (R.isAmbiguous())
12665 return nullptr;
12666
12667 if (R.empty()) {
12668 R.clear();
12669 // Allow "using namespace std;" or "using namespace ::std;" even if
12670 // "std" hasn't been defined yet, for GCC compatibility.
12671 if ((!Qualifier ||
12672 Qualifier.getKind() == NestedNameSpecifier::Kind::Global) &&
12673 NamespcName->isStr("std")) {
12674 Diag(IdentLoc, diag::ext_using_undefined_std);
12675 R.addDecl(getOrCreateStdNamespace());
12676 R.resolveKind();
12677 }
12678 // Otherwise, attempt typo correction.
12679 else
12680 TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
12681 }
12682
12683 if (!R.empty()) {
12684 NamedDecl *Named = R.getRepresentativeDecl();
12685 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
12686 assert(NS && "expected namespace decl");
12687
12688 // The use of a nested name specifier may trigger deprecation warnings.
12689 DiagnoseUseOfDecl(Named, IdentLoc);
12690
12691 // C++ [namespace.udir]p1:
12692 // A using-directive specifies that the names in the nominated
12693 // namespace can be used in the scope in which the
12694 // using-directive appears after the using-directive. During
12695 // unqualified name lookup (3.4.1), the names appear as if they
12696 // were declared in the nearest enclosing namespace which
12697 // contains both the using-directive and the nominated
12698 // namespace. [Note: in this context, "contains" means "contains
12699 // directly or indirectly". ]
12700
12701 // Find enclosing context containing both using-directive and
12702 // nominated namespace.
12703 DeclContext *CommonAncestor = NS;
12704 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
12705 CommonAncestor = CommonAncestor->getParent();
12706
12707 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
12709 IdentLoc, Named, CommonAncestor);
12710
12712 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
12713 Diag(IdentLoc, diag::warn_using_directive_in_header);
12714 }
12715
12716 PushUsingDirective(S, UDir);
12717 } else {
12718 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
12719 }
12720
12721 if (UDir) {
12722 ProcessDeclAttributeList(S, UDir, AttrList);
12723 ProcessAPINotes(UDir);
12724 }
12725
12726 return UDir;
12727}
12728
12730 // If the scope has an associated entity and the using directive is at
12731 // namespace or translation unit scope, add the UsingDirectiveDecl into
12732 // its lookup structure so qualified name lookup can find it.
12733 DeclContext *Ctx = S->getEntity();
12734 if (Ctx && !Ctx->isFunctionOrMethod())
12735 Ctx->addDecl(UDir);
12736 else
12737 // Otherwise, it is at block scope. The using-directives will affect lookup
12738 // only to the end of the scope.
12739 S->PushUsingDirective(UDir);
12740}
12741
12743 SourceLocation UsingLoc,
12744 SourceLocation TypenameLoc, CXXScopeSpec &SS,
12745 UnqualifiedId &Name,
12746 SourceLocation EllipsisLoc,
12747 const ParsedAttributesView &AttrList) {
12748 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
12749
12750 if (SS.isEmpty()) {
12751 Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
12752 return nullptr;
12753 }
12754
12755 switch (Name.getKind()) {
12761 break;
12762
12765 // C++11 inheriting constructors.
12766 Diag(Name.getBeginLoc(),
12768 ? diag::warn_cxx98_compat_using_decl_constructor
12769 : diag::err_using_decl_constructor)
12770 << SS.getRange();
12771
12772 if (getLangOpts().CPlusPlus11) break;
12773
12774 return nullptr;
12775
12777 Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
12778 return nullptr;
12779
12781 Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
12783 return nullptr;
12784
12786 llvm_unreachable("cannot parse qualified deduction guide name");
12787 }
12788
12789 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
12790 DeclarationName TargetName = TargetNameInfo.getName();
12791 if (!TargetName)
12792 return nullptr;
12793
12794 // Warn about access declarations.
12795 if (UsingLoc.isInvalid()) {
12797 ? diag::err_access_decl
12798 : diag::warn_access_decl_deprecated)
12799 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
12800 }
12801
12802 if (EllipsisLoc.isInvalid()) {
12805 return nullptr;
12806 } else {
12808 !TargetNameInfo.containsUnexpandedParameterPack()) {
12809 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
12810 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
12811 EllipsisLoc = SourceLocation();
12812 }
12813 }
12814
12815 NamedDecl *UD =
12816 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
12817 SS, TargetNameInfo, EllipsisLoc, AttrList,
12818 /*IsInstantiation*/ false,
12819 AttrList.hasAttribute(ParsedAttr::AT_UsingIfExists));
12820 if (UD)
12821 PushOnScopeChains(UD, S, /*AddToContext*/ false);
12822
12823 return UD;
12824}
12825
12827 SourceLocation UsingLoc,
12828 SourceLocation EnumLoc, SourceRange TyLoc,
12829 const IdentifierInfo &II, ParsedType Ty,
12830 const CXXScopeSpec &SS) {
12831 TypeSourceInfo *TSI = nullptr;
12832 SourceLocation IdentLoc = TyLoc.getBegin();
12833 QualType EnumTy = GetTypeFromParser(Ty, &TSI);
12834 if (EnumTy.isNull()) {
12835 Diag(IdentLoc, isDependentScopeSpecifier(SS)
12836 ? diag::err_using_enum_is_dependent
12837 : diag::err_unknown_typename)
12838 << II.getName()
12839 << SourceRange(SS.isValid() ? SS.getBeginLoc() : IdentLoc,
12840 TyLoc.getEnd());
12841 return nullptr;
12842 }
12843
12844 if (EnumTy->isDependentType()) {
12845 Diag(IdentLoc, diag::err_using_enum_is_dependent);
12846 return nullptr;
12847 }
12848
12849 auto *Enum = EnumTy->getAsEnumDecl();
12850 if (!Enum) {
12851 Diag(IdentLoc, diag::err_using_enum_not_enum) << EnumTy;
12852 return nullptr;
12853 }
12854
12855 if (TSI == nullptr)
12856 TSI = Context.getTrivialTypeSourceInfo(EnumTy, IdentLoc);
12857
12858 auto *UD =
12859 BuildUsingEnumDeclaration(S, AS, UsingLoc, EnumLoc, IdentLoc, TSI, Enum);
12860
12861 if (UD)
12862 PushOnScopeChains(UD, S, /*AddToContext*/ false);
12863
12864 return UD;
12865}
12866
12867/// Determine whether a using declaration considers the given
12868/// declarations as "equivalent", e.g., if they are redeclarations of
12869/// the same entity or are both typedefs of the same type.
12870static bool
12872 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
12873 return true;
12874
12875 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
12876 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
12877 return Context.hasSameType(TD1->getUnderlyingType(),
12878 TD2->getUnderlyingType());
12879
12880 // Two using_if_exists using-declarations are equivalent if both are
12881 // unresolved.
12884 return true;
12885
12886 return false;
12887}
12888
12890 const LookupResult &Previous,
12891 UsingShadowDecl *&PrevShadow) {
12892 // Diagnose finding a decl which is not from a base class of the
12893 // current class. We do this now because there are cases where this
12894 // function will silently decide not to build a shadow decl, which
12895 // will pre-empt further diagnostics.
12896 //
12897 // We don't need to do this in C++11 because we do the check once on
12898 // the qualifier.
12899 //
12900 // FIXME: diagnose the following if we care enough:
12901 // struct A { int foo; };
12902 // struct B : A { using A::foo; };
12903 // template <class T> struct C : A {};
12904 // template <class T> struct D : C<T> { using B::foo; } // <---
12905 // This is invalid (during instantiation) in C++03 because B::foo
12906 // resolves to the using decl in B, which is not a base class of D<T>.
12907 // We can't diagnose it immediately because C<T> is an unknown
12908 // specialization. The UsingShadowDecl in D<T> then points directly
12909 // to A::foo, which will look well-formed when we instantiate.
12910 // The right solution is to not collapse the shadow-decl chain.
12911 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord())
12912 if (auto *Using = dyn_cast<UsingDecl>(BUD)) {
12913 DeclContext *OrigDC = Orig->getDeclContext();
12914
12915 // Handle enums and anonymous structs.
12916 if (isa<EnumDecl>(OrigDC))
12917 OrigDC = OrigDC->getParent();
12918 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
12919 while (OrigRec->isAnonymousStructOrUnion())
12920 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
12921
12923 if (OrigDC == CurContext) {
12924 Diag(Using->getLocation(),
12925 diag::err_using_decl_nested_name_specifier_is_current_class)
12926 << Using->getQualifierLoc().getSourceRange();
12927 Diag(Orig->getLocation(), diag::note_using_decl_target);
12928 Using->setInvalidDecl();
12929 return true;
12930 }
12931
12932 Diag(Using->getQualifierLoc().getBeginLoc(),
12933 diag::err_using_decl_nested_name_specifier_is_not_base_class)
12934 << Using->getQualifier() << cast<CXXRecordDecl>(CurContext)
12935 << Using->getQualifierLoc().getSourceRange();
12936 Diag(Orig->getLocation(), diag::note_using_decl_target);
12937 Using->setInvalidDecl();
12938 return true;
12939 }
12940 }
12941
12942 if (Previous.empty()) return false;
12943
12944 NamedDecl *Target = Orig;
12946 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
12947
12948 // If the target happens to be one of the previous declarations, we
12949 // don't have a conflict.
12950 //
12951 // FIXME: but we might be increasing its access, in which case we
12952 // should redeclare it.
12953 NamedDecl *NonTag = nullptr, *Tag = nullptr;
12954 bool FoundEquivalentDecl = false;
12955 for (NamedDecl *Element : Previous) {
12956 NamedDecl *D = Element->getUnderlyingDecl();
12957 // We can have UsingDecls in our Previous results because we use the same
12958 // LookupResult for checking whether the UsingDecl itself is a valid
12959 // redeclaration.
12961 continue;
12962
12963 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
12964 // C++ [class.mem]p19:
12965 // If T is the name of a class, then [every named member other than
12966 // a non-static data member] shall have a name different from T
12967 if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
12971 CurContext,
12973 return true;
12974 }
12975
12977 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Element))
12978 PrevShadow = Shadow;
12979 FoundEquivalentDecl = true;
12981 // We don't conflict with an existing using shadow decl of an equivalent
12982 // declaration, but we're not a redeclaration of it.
12983 FoundEquivalentDecl = true;
12984 }
12985
12986 if (isVisible(D))
12987 (isa<TagDecl>(D) ? Tag : NonTag) = D;
12988 }
12989
12990 if (FoundEquivalentDecl)
12991 return false;
12992
12993 // Always emit a diagnostic for a mismatch between an unresolved
12994 // using_if_exists and a resolved using declaration in either direction.
12996 (isa_and_nonnull<UnresolvedUsingIfExistsDecl>(NonTag))) {
12997 if (!NonTag && !Tag)
12998 return false;
12999 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
13000 Diag(Target->getLocation(), diag::note_using_decl_target);
13001 Diag((NonTag ? NonTag : Tag)->getLocation(),
13002 diag::note_using_decl_conflict);
13003 BUD->setInvalidDecl();
13004 return true;
13005 }
13006
13007 if (FunctionDecl *FD = Target->getAsFunction()) {
13008 NamedDecl *OldDecl = nullptr;
13009 switch (CheckOverload(nullptr, FD, Previous, OldDecl,
13010 /*IsForUsingDecl*/ true)) {
13012 return false;
13013
13015 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
13016 break;
13017
13018 // We found a decl with the exact signature.
13020 // If we're in a record, we want to hide the target, so we
13021 // return true (without a diagnostic) to tell the caller not to
13022 // build a shadow decl.
13023 if (CurContext->isRecord())
13024 return true;
13025
13026 // If we're not in a record, this is an error.
13027 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
13028 break;
13029 }
13030
13031 Diag(Target->getLocation(), diag::note_using_decl_target);
13032 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
13033 BUD->setInvalidDecl();
13034 return true;
13035 }
13036
13037 // Target is not a function.
13038
13039 if (isa<TagDecl>(Target)) {
13040 // No conflict between a tag and a non-tag.
13041 if (!Tag) return false;
13042
13043 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
13044 Diag(Target->getLocation(), diag::note_using_decl_target);
13045 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
13046 BUD->setInvalidDecl();
13047 return true;
13048 }
13049
13050 // No conflict between a tag and a non-tag.
13051 if (!NonTag) return false;
13052
13053 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
13054 Diag(Target->getLocation(), diag::note_using_decl_target);
13055 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
13056 BUD->setInvalidDecl();
13057 return true;
13058}
13059
13060/// Determine whether a direct base class is a virtual base class.
13062 if (!Derived->getNumVBases())
13063 return false;
13064 for (auto &B : Derived->bases())
13065 if (B.getType()->getAsCXXRecordDecl() == Base)
13066 return B.isVirtual();
13067 llvm_unreachable("not a direct base class");
13068}
13069
13071 NamedDecl *Orig,
13072 UsingShadowDecl *PrevDecl) {
13073 // If we resolved to another shadow declaration, just coalesce them.
13074 NamedDecl *Target = Orig;
13076 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
13077 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
13078 }
13079
13080 NamedDecl *NonTemplateTarget = Target;
13081 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
13082 NonTemplateTarget = TargetTD->getTemplatedDecl();
13083
13084 UsingShadowDecl *Shadow;
13085 if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) {
13086 UsingDecl *Using = cast<UsingDecl>(BUD);
13087 bool IsVirtualBase =
13089 Using->getQualifier().getAsRecordDecl());
13091 Context, CurContext, Using->getLocation(), Using, Orig, IsVirtualBase);
13092 } else {
13094 Target->getDeclName(), BUD, Target);
13095 }
13096 BUD->addShadowDecl(Shadow);
13097
13098 Shadow->setAccess(BUD->getAccess());
13099 if (Orig->isInvalidDecl() || BUD->isInvalidDecl())
13100 Shadow->setInvalidDecl();
13101
13102 Shadow->setPreviousDecl(PrevDecl);
13103
13104 if (S)
13105 PushOnScopeChains(Shadow, S);
13106 else
13107 CurContext->addDecl(Shadow);
13108
13109
13110 return Shadow;
13111}
13112
13114 if (Shadow->getDeclName().getNameKind() ==
13116 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
13117
13118 // Remove it from the DeclContext...
13119 Shadow->getDeclContext()->removeDecl(Shadow);
13120
13121 // ...and the scope, if applicable...
13122 if (S) {
13123 S->RemoveDecl(Shadow);
13124 IdResolver.RemoveDecl(Shadow);
13125 }
13126
13127 // ...and the using decl.
13128 Shadow->getIntroducer()->removeShadowDecl(Shadow);
13129
13130 // TODO: complain somehow if Shadow was used. It shouldn't
13131 // be possible for this to happen, because...?
13132}
13133
13134/// Find the base specifier for a base class with the given type.
13136 QualType DesiredBase,
13137 bool &AnyDependentBases) {
13138 // Check whether the named type is a direct base class.
13139 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
13140 for (auto &Base : Derived->bases()) {
13141 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
13142 if (CanonicalDesiredBase == BaseType)
13143 return &Base;
13144 if (BaseType->isDependentType())
13145 AnyDependentBases = true;
13146 }
13147 return nullptr;
13148}
13149
13150namespace {
13151class UsingValidatorCCC final : public CorrectionCandidateCallback {
13152public:
13153 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
13154 NestedNameSpecifier NNS, CXXRecordDecl *RequireMemberOf)
13155 : HasTypenameKeyword(HasTypenameKeyword),
13156 IsInstantiation(IsInstantiation), OldNNS(NNS),
13157 RequireMemberOf(RequireMemberOf) {}
13158
13159 bool ValidateCandidate(const TypoCorrection &Candidate) override {
13160 NamedDecl *ND = Candidate.getCorrectionDecl();
13161
13162 // Keywords are not valid here.
13163 if (!ND || isa<NamespaceDecl>(ND))
13164 return false;
13165
13166 // Completely unqualified names are invalid for a 'using' declaration.
13167 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
13168 return false;
13169
13170 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
13171 // reject.
13172
13173 if (RequireMemberOf) {
13174 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
13175 if (FoundRecord && FoundRecord->isInjectedClassName()) {
13176 // No-one ever wants a using-declaration to name an injected-class-name
13177 // of a base class, unless they're declaring an inheriting constructor.
13178 ASTContext &Ctx = ND->getASTContext();
13179 if (!Ctx.getLangOpts().CPlusPlus11)
13180 return false;
13181 CanQualType FoundType = Ctx.getCanonicalTagType(FoundRecord);
13182
13183 // Check that the injected-class-name is named as a member of its own
13184 // type; we don't want to suggest 'using Derived::Base;', since that
13185 // means something else.
13186 NestedNameSpecifier Specifier = Candidate.WillReplaceSpecifier()
13187 ? Candidate.getCorrectionSpecifier()
13188 : OldNNS;
13189 if (Specifier.getKind() != NestedNameSpecifier::Kind::Type ||
13190 !Ctx.hasSameType(QualType(Specifier.getAsType(), 0), FoundType))
13191 return false;
13192
13193 // Check that this inheriting constructor declaration actually names a
13194 // direct base class of the current class.
13195 bool AnyDependentBases = false;
13196 if (!findDirectBaseWithType(RequireMemberOf,
13197 Ctx.getCanonicalTagType(FoundRecord),
13198 AnyDependentBases) &&
13199 !AnyDependentBases)
13200 return false;
13201 } else {
13202 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
13203 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
13204 return false;
13205
13206 // FIXME: Check that the base class member is accessible?
13207 }
13208 } else {
13209 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
13210 if (FoundRecord && FoundRecord->isInjectedClassName())
13211 return false;
13212 }
13213
13214 if (isa<TypeDecl>(ND))
13215 return HasTypenameKeyword || !IsInstantiation;
13216
13217 return !HasTypenameKeyword;
13218 }
13219
13220 std::unique_ptr<CorrectionCandidateCallback> clone() override {
13221 return std::make_unique<UsingValidatorCCC>(*this);
13222 }
13223
13224private:
13225 bool HasTypenameKeyword;
13226 bool IsInstantiation;
13227 NestedNameSpecifier OldNNS;
13228 CXXRecordDecl *RequireMemberOf;
13229};
13230} // end anonymous namespace
13231
13233 // It is really dumb that we have to do this.
13234 LookupResult::Filter F = Previous.makeFilter();
13235 while (F.hasNext()) {
13236 NamedDecl *D = F.next();
13237 if (!isDeclInScope(D, CurContext, S))
13238 F.erase();
13239 // If we found a local extern declaration that's not ordinarily visible,
13240 // and this declaration is being added to a non-block scope, ignore it.
13241 // We're only checking for scope conflicts here, not also for violations
13242 // of the linkage rules.
13243 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
13245 F.erase();
13246 }
13247 F.done();
13248}
13249
13251 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
13252 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
13253 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
13254 const ParsedAttributesView &AttrList, bool IsInstantiation,
13255 bool IsUsingIfExists) {
13256 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
13257 SourceLocation IdentLoc = NameInfo.getLoc();
13258 assert(IdentLoc.isValid() && "Invalid TargetName location.");
13259
13260 // FIXME: We ignore attributes for now.
13261
13262 // For an inheriting constructor declaration, the name of the using
13263 // declaration is the name of a constructor in this class, not in the
13264 // base class.
13265 DeclarationNameInfo UsingName = NameInfo;
13267 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
13268 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
13269 Context.getCanonicalTagType(RD)));
13270
13271 // Do the redeclaration lookup in the current scope.
13272 LookupResult Previous(*this, UsingName, LookupUsingDeclName,
13274 Previous.setHideTags(false);
13275 if (S) {
13276 LookupName(Previous, S);
13277
13279 } else {
13280 assert(IsInstantiation && "no scope in non-instantiation");
13281 if (CurContext->isRecord())
13283 else {
13284 // No redeclaration check is needed here; in non-member contexts we
13285 // diagnosed all possible conflicts with other using-declarations when
13286 // building the template:
13287 //
13288 // For a dependent non-type using declaration, the only valid case is
13289 // if we instantiate to a single enumerator. We check for conflicts
13290 // between shadow declarations we introduce, and we check in the template
13291 // definition for conflicts between a non-type using declaration and any
13292 // other declaration, which together covers all cases.
13293 //
13294 // A dependent typename using declaration will never successfully
13295 // instantiate, since it will always name a class member, so we reject
13296 // that in the template definition.
13297 }
13298 }
13299
13300 // Check for invalid redeclarations.
13301 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
13302 SS, IdentLoc, Previous))
13303 return nullptr;
13304
13305 // 'using_if_exists' doesn't make sense on an inherited constructor.
13306 if (IsUsingIfExists && UsingName.getName().getNameKind() ==
13308 Diag(UsingLoc, diag::err_using_if_exists_on_ctor);
13309 return nullptr;
13310 }
13311
13312 DeclContext *LookupContext = computeDeclContext(SS);
13314 if (!LookupContext || EllipsisLoc.isValid()) {
13315 NamedDecl *D;
13316 // Dependent scope, or an unexpanded pack
13317 if (!LookupContext && CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword,
13318 SS, NameInfo, IdentLoc))
13319 return nullptr;
13320
13321 if (Previous.isSingleResult() &&
13322 Previous.getFoundDecl()->isTemplateParameter())
13323 DiagnoseTemplateParameterShadow(IdentLoc, Previous.getFoundDecl());
13324
13325 if (HasTypenameKeyword) {
13326 // FIXME: not all declaration name kinds are legal here
13328 UsingLoc, TypenameLoc,
13329 QualifierLoc,
13330 IdentLoc, NameInfo.getName(),
13331 EllipsisLoc);
13332 } else {
13334 QualifierLoc, NameInfo, EllipsisLoc);
13335 }
13336 D->setAccess(AS);
13337 CurContext->addDecl(D);
13338 ProcessDeclAttributeList(S, D, AttrList);
13339 return D;
13340 }
13341
13342 auto Build = [&](bool Invalid) {
13343 UsingDecl *UD =
13344 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
13345 UsingName, HasTypenameKeyword);
13346 UD->setAccess(AS);
13347 CurContext->addDecl(UD);
13348 ProcessDeclAttributeList(S, UD, AttrList);
13350 return UD;
13351 };
13352 auto BuildInvalid = [&]{ return Build(true); };
13353 auto BuildValid = [&]{ return Build(false); };
13354
13355 if (RequireCompleteDeclContext(SS, LookupContext))
13356 return BuildInvalid();
13357
13358 // Look up the target name.
13359 LookupResult R(*this, NameInfo, LookupOrdinaryName);
13360
13361 // Unlike most lookups, we don't always want to hide tag
13362 // declarations: tag names are visible through the using declaration
13363 // even if hidden by ordinary names, *except* in a dependent context
13364 // where they may be used by two-phase lookup.
13365 if (!IsInstantiation)
13366 R.setHideTags(false);
13367
13368 // For the purposes of this lookup, we have a base object type
13369 // equal to that of the current context.
13370 if (CurContext->isRecord()) {
13371 R.setBaseObjectType(
13372 Context.getCanonicalTagType(cast<CXXRecordDecl>(CurContext)));
13373 }
13374
13375 LookupQualifiedName(R, LookupContext);
13376
13377 // Validate the context, now we have a lookup
13378 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
13379 IdentLoc, &R))
13380 return nullptr;
13381
13382 if (R.empty() && IsUsingIfExists)
13384 UsingName.getName()),
13385 AS_public);
13386
13387 // Try to correct typos if possible. If constructor name lookup finds no
13388 // results, that means the named class has no explicit constructors, and we
13389 // suppressed declaring implicit ones (probably because it's dependent or
13390 // invalid).
13391 if (R.empty() &&
13393 // HACK 2017-01-08: Work around an issue with libstdc++'s detection of
13394 // ::gets. Sometimes it believes that glibc provides a ::gets in cases where
13395 // it does not. The issue was fixed in libstdc++ 6.3 (2016-12-21) and later.
13396 auto *II = NameInfo.getName().getAsIdentifierInfo();
13397 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
13398 CurContext->isStdNamespace() &&
13399 isa<TranslationUnitDecl>(LookupContext) &&
13400 PP.NeedsStdLibCxxWorkaroundBefore(2016'12'21) &&
13401 getSourceManager().isInSystemHeader(UsingLoc))
13402 return nullptr;
13403 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
13404 dyn_cast<CXXRecordDecl>(CurContext));
13405 if (TypoCorrection Corrected =
13406 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
13408 // We reject candidates where DroppedSpecifier == true, hence the
13409 // literal '0' below.
13410 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
13411 << NameInfo.getName() << LookupContext << 0
13412 << SS.getRange());
13413
13414 // If we picked a correction with no attached Decl we can't do anything
13415 // useful with it, bail out.
13416 NamedDecl *ND = Corrected.getCorrectionDecl();
13417 if (!ND)
13418 return BuildInvalid();
13419
13420 // If we corrected to an inheriting constructor, handle it as one.
13421 auto *RD = dyn_cast<CXXRecordDecl>(ND);
13422 if (RD && RD->isInjectedClassName()) {
13423 // The parent of the injected class name is the class itself.
13424 RD = cast<CXXRecordDecl>(RD->getParent());
13425
13426 // Fix up the information we'll use to build the using declaration.
13427 if (Corrected.WillReplaceSpecifier()) {
13429 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
13430 QualifierLoc.getSourceRange());
13431 QualifierLoc = Builder.getWithLocInContext(Context);
13432 }
13433
13434 // In this case, the name we introduce is the name of a derived class
13435 // constructor.
13436 auto *CurClass = cast<CXXRecordDecl>(CurContext);
13437 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
13438 Context.getCanonicalTagType(CurClass)));
13439 UsingName.setNamedTypeInfo(nullptr);
13440 for (auto *Ctor : LookupConstructors(RD))
13441 R.addDecl(Ctor);
13442 R.resolveKind();
13443 } else {
13444 // FIXME: Pick up all the declarations if we found an overloaded
13445 // function.
13446 UsingName.setName(ND->getDeclName());
13447 R.addDecl(ND);
13448 }
13449 } else {
13450 Diag(IdentLoc, diag::err_no_member)
13451 << NameInfo.getName() << LookupContext << SS.getRange();
13452 return BuildInvalid();
13453 }
13454 }
13455
13456 if (R.isAmbiguous())
13457 return BuildInvalid();
13458
13459 if (HasTypenameKeyword) {
13460 // If we asked for a typename and got a non-type decl, error out.
13461 if (!R.getAsSingle<TypeDecl>() &&
13462 !R.getAsSingle<UnresolvedUsingIfExistsDecl>()) {
13463 Diag(IdentLoc, diag::err_using_typename_non_type);
13464 for (const NamedDecl *D : R)
13465 Diag(D->getUnderlyingDecl()->getLocation(),
13466 diag::note_using_decl_target);
13467 return BuildInvalid();
13468 }
13469 } else {
13470 // If we asked for a non-typename and we got a type, error out,
13471 // but only if this is an instantiation of an unresolved using
13472 // decl. Otherwise just silently find the type name.
13473 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
13474 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
13475 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
13476 return BuildInvalid();
13477 }
13478 }
13479
13480 // C++14 [namespace.udecl]p6:
13481 // A using-declaration shall not name a namespace.
13482 if (R.getAsSingle<NamespaceDecl>()) {
13483 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
13484 << SS.getRange();
13485 // Suggest using 'using namespace ...' instead.
13486 Diag(SS.getBeginLoc(), diag::note_namespace_using_decl)
13487 << FixItHint::CreateInsertion(SS.getBeginLoc(), "namespace ");
13488 return BuildInvalid();
13489 }
13490
13491 UsingDecl *UD = BuildValid();
13492
13493 // Some additional rules apply to inheriting constructors.
13494 if (UsingName.getName().getNameKind() ==
13496 // Suppress access diagnostics; the access check is instead performed at the
13497 // point of use for an inheriting constructor.
13498 R.suppressDiagnostics();
13500 return UD;
13501 }
13502
13503 for (NamedDecl *D : R) {
13504 UsingShadowDecl *PrevDecl = nullptr;
13505 if (!CheckUsingShadowDecl(UD, D, Previous, PrevDecl))
13506 BuildUsingShadowDecl(S, UD, D, PrevDecl);
13507 }
13508
13509 return UD;
13510}
13511
13513 SourceLocation UsingLoc,
13514 SourceLocation EnumLoc,
13515 SourceLocation NameLoc,
13516 TypeSourceInfo *EnumType,
13517 EnumDecl *ED) {
13518 bool Invalid = false;
13519
13520 if (CurContext->getRedeclContext()->isRecord()) {
13521 /// In class scope, check if this is a duplicate, for better a diagnostic.
13522 DeclarationNameInfo UsingEnumName(ED->getDeclName(), NameLoc);
13523 LookupResult Previous(*this, UsingEnumName, LookupUsingDeclName,
13525
13527
13528 for (NamedDecl *D : Previous)
13529 if (UsingEnumDecl *UED = dyn_cast<UsingEnumDecl>(D))
13530 if (UED->getEnumDecl() == ED) {
13531 Diag(UsingLoc, diag::err_using_enum_decl_redeclaration)
13532 << SourceRange(EnumLoc, NameLoc);
13533 Diag(D->getLocation(), diag::note_using_enum_decl) << 1;
13534 Invalid = true;
13535 break;
13536 }
13537 }
13538
13539 if (RequireCompleteEnumDecl(ED, NameLoc))
13540 Invalid = true;
13541
13543 EnumLoc, NameLoc, EnumType);
13544 UD->setAccess(AS);
13545 CurContext->addDecl(UD);
13546
13547 if (Invalid) {
13548 UD->setInvalidDecl();
13549 return UD;
13550 }
13551
13552 // Create the shadow decls for each enumerator
13553 for (EnumConstantDecl *EC : ED->enumerators()) {
13554 UsingShadowDecl *PrevDecl = nullptr;
13555 DeclarationNameInfo DNI(EC->getDeclName(), EC->getLocation());
13558 LookupName(Previous, S);
13560
13561 if (!CheckUsingShadowDecl(UD, EC, Previous, PrevDecl))
13562 BuildUsingShadowDecl(S, UD, EC, PrevDecl);
13563 }
13564
13565 return UD;
13566}
13567
13569 ArrayRef<NamedDecl *> Expansions) {
13570 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
13571 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
13572 isa<UsingPackDecl>(InstantiatedFrom));
13573
13574 auto *UPD =
13575 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
13576 UPD->setAccess(InstantiatedFrom->getAccess());
13577 CurContext->addDecl(UPD);
13578 return UPD;
13579}
13580
13582 assert(!UD->hasTypename() && "expecting a constructor name");
13583
13584 QualType SourceType(UD->getQualifier().getAsType(), 0);
13586
13587 // Check whether the named type is a direct base class.
13588 bool AnyDependentBases = false;
13589 auto *Base =
13590 findDirectBaseWithType(TargetClass, SourceType, AnyDependentBases);
13591 if (!Base && !AnyDependentBases) {
13592 Diag(UD->getUsingLoc(), diag::err_using_decl_constructor_not_in_direct_base)
13593 << UD->getNameInfo().getSourceRange() << SourceType << TargetClass;
13594 UD->setInvalidDecl();
13595 return true;
13596 }
13597
13598 if (Base)
13599 Base->setInheritConstructors();
13600
13601 return false;
13602}
13603
13605 bool HasTypenameKeyword,
13606 const CXXScopeSpec &SS,
13607 SourceLocation NameLoc,
13608 const LookupResult &Prev) {
13609 NestedNameSpecifier Qual = SS.getScopeRep();
13610
13611 // C++03 [namespace.udecl]p8:
13612 // C++0x [namespace.udecl]p10:
13613 // A using-declaration is a declaration and can therefore be used
13614 // repeatedly where (and only where) multiple declarations are
13615 // allowed.
13616 //
13617 // That's in non-member contexts.
13618 if (!CurContext->getRedeclContext()->isRecord()) {
13619 // A dependent qualifier outside a class can only ever resolve to an
13620 // enumeration type. Therefore it conflicts with any other non-type
13621 // declaration in the same scope.
13622 // FIXME: How should we check for dependent type-type conflicts at block
13623 // scope?
13624 if (Qual.isDependent() && !HasTypenameKeyword) {
13625 for (auto *D : Prev) {
13626 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
13627 bool OldCouldBeEnumerator =
13629 Diag(NameLoc,
13630 OldCouldBeEnumerator ? diag::err_redefinition
13631 : diag::err_redefinition_different_kind)
13632 << Prev.getLookupName();
13633 Diag(D->getLocation(), diag::note_previous_definition);
13634 return true;
13635 }
13636 }
13637 }
13638 return false;
13639 }
13640
13641 NestedNameSpecifier CNNS = Qual.getCanonical();
13642 for (const NamedDecl *D : Prev) {
13643 bool DTypename;
13644 NestedNameSpecifier DQual = std::nullopt;
13645 if (const auto *UD = dyn_cast<UsingDecl>(D)) {
13646 DTypename = UD->hasTypename();
13647 DQual = UD->getQualifier();
13648 } else if (const auto *UD = dyn_cast<UnresolvedUsingValueDecl>(D)) {
13649 DTypename = false;
13650 DQual = UD->getQualifier();
13651 } else if (const auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
13652 DTypename = true;
13653 DQual = UD->getQualifier();
13654 } else
13655 continue;
13656
13657 // using decls differ if one says 'typename' and the other doesn't.
13658 // FIXME: non-dependent using decls?
13659 if (HasTypenameKeyword != DTypename) continue;
13660
13661 // using decls differ if they name different scopes (but note that
13662 // template instantiation can cause this check to trigger when it
13663 // didn't before instantiation).
13664 if (CNNS != DQual.getCanonical())
13665 continue;
13666
13667 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
13668 Diag(D->getLocation(), diag::note_using_decl) << 1;
13669 return true;
13670 }
13671
13672 return false;
13673}
13674
13675bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
13676 const CXXScopeSpec &SS,
13677 const DeclarationNameInfo &NameInfo,
13678 SourceLocation NameLoc,
13679 const LookupResult *R, const UsingDecl *UD) {
13680 DeclContext *NamedContext = computeDeclContext(SS);
13681 assert(bool(NamedContext) == (R || UD) && !(R && UD) &&
13682 "resolvable context must have exactly one set of decls");
13683
13684 // C++ 20 permits using an enumerator that does not have a class-hierarchy
13685 // relationship.
13686 bool Cxx20Enumerator = false;
13687 if (NamedContext) {
13688 EnumConstantDecl *EC = nullptr;
13689 if (R)
13690 EC = R->getAsSingle<EnumConstantDecl>();
13691 else if (UD && UD->shadow_size() == 1)
13692 EC = dyn_cast<EnumConstantDecl>(UD->shadow_begin()->getTargetDecl());
13693 if (EC)
13694 Cxx20Enumerator = getLangOpts().CPlusPlus20;
13695
13696 if (auto *ED = dyn_cast<EnumDecl>(NamedContext)) {
13697 // C++14 [namespace.udecl]p7:
13698 // A using-declaration shall not name a scoped enumerator.
13699 // C++20 p1099 permits enumerators.
13700 if (EC && R && ED->isScoped())
13701 Diag(SS.getBeginLoc(),
13703 ? diag::warn_cxx17_compat_using_decl_scoped_enumerator
13704 : diag::ext_using_decl_scoped_enumerator)
13705 << SS.getRange();
13706
13707 // We want to consider the scope of the enumerator
13708 NamedContext = ED->getDeclContext();
13709 }
13710 }
13711
13712 if (!CurContext->isRecord()) {
13713 // C++03 [namespace.udecl]p3:
13714 // C++0x [namespace.udecl]p8:
13715 // A using-declaration for a class member shall be a member-declaration.
13716 // C++20 [namespace.udecl]p7
13717 // ... other than an enumerator ...
13718
13719 // If we weren't able to compute a valid scope, it might validly be a
13720 // dependent class or enumeration scope. If we have a 'typename' keyword,
13721 // the scope must resolve to a class type.
13722 if (NamedContext ? !NamedContext->getRedeclContext()->isRecord()
13723 : !HasTypename)
13724 return false; // OK
13725
13726 Diag(NameLoc,
13727 Cxx20Enumerator
13728 ? diag::warn_cxx17_compat_using_decl_class_member_enumerator
13729 : diag::err_using_decl_can_not_refer_to_class_member)
13730 << SS.getRange();
13731
13732 if (Cxx20Enumerator)
13733 return false; // OK
13734
13735 auto *RD = NamedContext
13736 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
13737 : nullptr;
13738 if (RD && !RequireCompleteDeclContext(const_cast<CXXScopeSpec &>(SS), RD)) {
13739 // See if there's a helpful fixit
13740
13741 if (!R) {
13742 // We will have already diagnosed the problem on the template
13743 // definition, Maybe we should do so again?
13744 } else if (R->getAsSingle<TypeDecl>()) {
13745 if (getLangOpts().CPlusPlus11) {
13746 // Convert 'using X::Y;' to 'using Y = X::Y;'.
13747 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
13748 << diag::MemClassWorkaround::AliasDecl
13750 NameInfo.getName().getAsString() +
13751 " = ");
13752 } else {
13753 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
13754 SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
13755 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
13756 << diag::MemClassWorkaround::TypedefDecl
13757 << FixItHint::CreateReplacement(UsingLoc, "typedef")
13759 InsertLoc, " " + NameInfo.getName().getAsString());
13760 }
13761 } else if (R->getAsSingle<VarDecl>()) {
13762 // Don't provide a fixit outside C++11 mode; we don't want to suggest
13763 // repeating the type of the static data member here.
13764 FixItHint FixIt;
13765 if (getLangOpts().CPlusPlus11) {
13766 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
13768 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
13769 }
13770
13771 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
13772 << diag::MemClassWorkaround::ReferenceDecl << FixIt;
13773 } else if (R->getAsSingle<EnumConstantDecl>()) {
13774 // Don't provide a fixit outside C++11 mode; we don't want to suggest
13775 // repeating the type of the enumeration here, and we can't do so if
13776 // the type is anonymous.
13777 FixItHint FixIt;
13778 if (getLangOpts().CPlusPlus11) {
13779 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
13781 UsingLoc,
13782 "constexpr auto " + NameInfo.getName().getAsString() + " = ");
13783 }
13784
13785 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
13786 << (getLangOpts().CPlusPlus11
13787 ? diag::MemClassWorkaround::ConstexprVar
13788 : diag::MemClassWorkaround::ConstVar)
13789 << FixIt;
13790 }
13791 }
13792
13793 return true; // Fail
13794 }
13795
13796 // If the named context is dependent, we can't decide much.
13797 if (!NamedContext) {
13798 // FIXME: in C++0x, we can diagnose if we can prove that the
13799 // nested-name-specifier does not refer to a base class, which is
13800 // still possible in some cases.
13801
13802 // Otherwise we have to conservatively report that things might be
13803 // okay.
13804 return false;
13805 }
13806
13807 // The current scope is a record.
13808 if (!NamedContext->isRecord()) {
13809 // Ideally this would point at the last name in the specifier,
13810 // but we don't have that level of source info.
13811 Diag(SS.getBeginLoc(),
13812 Cxx20Enumerator
13813 ? diag::warn_cxx17_compat_using_decl_non_member_enumerator
13814 : diag::err_using_decl_nested_name_specifier_is_not_class)
13815 << SS.getScopeRep() << SS.getRange();
13816
13817 if (Cxx20Enumerator)
13818 return false; // OK
13819
13820 return true;
13821 }
13822
13823 if (!NamedContext->isDependentContext() &&
13824 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
13825 return true;
13826
13827 // C++26 [namespace.udecl]p3:
13828 // In a using-declaration used as a member-declaration, each
13829 // using-declarator shall either name an enumerator or have a
13830 // nested-name-specifier naming a base class of the current class
13831 // ([expr.prim.this]). ...
13832 // "have a nested-name-specifier naming a base class of the current class"
13833 // was introduced by CWG400.
13834
13837
13838 if (Cxx20Enumerator) {
13839 Diag(NameLoc, diag::warn_cxx17_compat_using_decl_non_member_enumerator)
13840 << SS.getScopeRep() << SS.getRange();
13841 return false;
13842 }
13843
13844 if (CurContext == NamedContext) {
13845 Diag(SS.getBeginLoc(),
13846 diag::err_using_decl_nested_name_specifier_is_current_class)
13847 << SS.getRange();
13848 return true;
13849 }
13850
13851 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
13852 Diag(SS.getBeginLoc(),
13853 diag::err_using_decl_nested_name_specifier_is_not_base_class)
13855 << SS.getRange();
13856 }
13857 return true;
13858 }
13859
13860 return false;
13861}
13862
13864 MultiTemplateParamsArg TemplateParamLists,
13865 SourceLocation UsingLoc, UnqualifiedId &Name,
13866 const ParsedAttributesView &AttrList,
13867 TypeResult Type, Decl *DeclFromDeclSpec) {
13868
13869 if (Type.isInvalid())
13870 return nullptr;
13871
13872 bool Invalid = false;
13874 TypeSourceInfo *TInfo = nullptr;
13875 GetTypeFromParser(Type.get(), &TInfo);
13876
13877 if (DiagnoseClassNameShadow(CurContext, NameInfo))
13878 return nullptr;
13879
13882 Invalid = true;
13883 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
13884 TInfo->getTypeLoc().getBeginLoc());
13885 }
13886
13887 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
13888 TemplateParamLists.size()
13891 LookupName(Previous, S);
13892
13893 // Warn about shadowing the name of a template parameter.
13894 if (Previous.isSingleResult() &&
13895 Previous.getFoundDecl()->isTemplateParameter()) {
13897 Previous.clear();
13898 }
13899
13900 assert(Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
13901 "name in alias declaration must be an identifier");
13903 Name.StartLocation,
13904 Name.Identifier, TInfo);
13905
13906 NewTD->setAccess(AS);
13907
13908 if (Invalid)
13909 NewTD->setInvalidDecl();
13910
13911 ProcessDeclAttributeList(S, NewTD, AttrList);
13912 AddPragmaAttributes(S, NewTD);
13913 ProcessAPINotes(NewTD);
13914
13916 Invalid |= NewTD->isInvalidDecl();
13917
13918 // Get the innermost enclosing declaration scope.
13919 S = S->getDeclParent();
13920
13921 bool Redeclaration = false;
13922
13923 NamedDecl *NewND;
13924 if (TemplateParamLists.size()) {
13925 TypeAliasTemplateDecl *OldDecl = nullptr;
13926 TemplateParameterList *OldTemplateParams = nullptr;
13927
13928 TemplateParameterList *TemplateParams = TemplateParamLists[0];
13929 if (TemplateParamLists.size() != 1) {
13930 Diag(UsingLoc, diag::err_alias_template_extra_headers)
13931 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
13932 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
13933 Invalid = true;
13934
13935 // Recover by picking the last non-empty template parameter list.
13936 auto It = llvm::find_if(
13937 llvm::reverse(TemplateParamLists),
13938 [](TemplateParameterList *TPL) { return !TPL->empty(); });
13939 assert(It != TemplateParamLists.rend() &&
13940 "if all template parameter lists were empty, this should have "
13941 "been rejected as an explicit specialization");
13942 TemplateParams = *It;
13943 }
13944
13945 // Check that we can declare a template here.
13946 if (CheckTemplateDeclScope(S, TemplateParams))
13947 return nullptr;
13948
13949 // Only consider previous declarations in the same scope.
13950 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
13951 /*ExplicitInstantiationOrSpecialization*/false);
13952 if (!Previous.empty()) {
13953 Redeclaration = true;
13954
13955 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
13956 if (!OldDecl && !Invalid) {
13957 Diag(UsingLoc, diag::err_redefinition_different_kind)
13958 << Name.Identifier;
13959
13960 NamedDecl *OldD = Previous.getRepresentativeDecl();
13961 if (OldD->getLocation().isValid())
13962 Diag(OldD->getLocation(), diag::note_previous_definition);
13963
13964 Invalid = true;
13965 }
13966
13967 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
13968 if (TemplateParameterListsAreEqual(TemplateParams,
13969 OldDecl->getTemplateParameters(),
13970 /*Complain=*/true,
13972 OldTemplateParams =
13974 else
13975 Invalid = true;
13976
13977 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
13978 if (!Invalid &&
13979 !Context.hasSameType(OldTD->getUnderlyingType(),
13980 NewTD->getUnderlyingType())) {
13981 // FIXME: The C++0x standard does not clearly say this is ill-formed,
13982 // but we can't reasonably accept it.
13983 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
13984 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
13985 if (OldTD->getLocation().isValid())
13986 Diag(OldTD->getLocation(), diag::note_previous_definition);
13987 Invalid = true;
13988 }
13989 }
13990 }
13991
13992 // Merge any previous default template arguments into our parameters,
13993 // and check the parameter list.
13994 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
13995 TPC_Other))
13996 return nullptr;
13997
13998 TypeAliasTemplateDecl *NewDecl =
14000 Name.Identifier, TemplateParams,
14001 NewTD);
14002 NewTD->setDescribedAliasTemplate(NewDecl);
14003
14004 NewDecl->setAccess(AS);
14005
14006 if (Invalid)
14007 NewDecl->setInvalidDecl();
14008 else if (OldDecl) {
14009 NewDecl->setPreviousDecl(OldDecl);
14010 CheckRedeclarationInModule(NewDecl, OldDecl);
14011 }
14012
14013 NewND = NewDecl;
14014 } else {
14015 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
14017 handleTagNumbering(TD, S);
14018 }
14020 NewND = NewTD;
14021 }
14022
14023 PushOnScopeChains(NewND, S);
14024 ActOnDocumentableDecl(NewND);
14025 return NewND;
14026}
14027
14029 SourceLocation AliasLoc,
14030 IdentifierInfo *Alias, CXXScopeSpec &SS,
14031 SourceLocation IdentLoc,
14032 IdentifierInfo *Ident) {
14033
14034 // Lookup the namespace name.
14035 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
14036 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
14037
14038 if (R.isAmbiguous())
14039 return nullptr;
14040
14041 if (R.empty()) {
14042 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
14043 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
14044 return nullptr;
14045 }
14046 }
14047 assert(!R.isAmbiguous() && !R.empty());
14048 auto *ND = cast<NamespaceBaseDecl>(R.getRepresentativeDecl());
14049
14050 // Check if we have a previous declaration with the same name.
14051 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
14053 LookupName(PrevR, S);
14054
14055 // Check we're not shadowing a template parameter.
14056 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
14058 PrevR.clear();
14059 }
14060
14061 // Filter out any other lookup result from an enclosing scope.
14062 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
14063 /*AllowInlineNamespace*/false);
14064
14065 // Find the previous declaration and check that we can redeclare it.
14066 NamespaceAliasDecl *Prev = nullptr;
14067 if (PrevR.isSingleResult()) {
14068 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
14069 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
14070 // We already have an alias with the same name that points to the same
14071 // namespace; check that it matches.
14072 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
14073 Prev = AD;
14074 } else if (isVisible(PrevDecl)) {
14075 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
14076 << Alias;
14077 Diag(AD->getLocation(), diag::note_previous_namespace_alias)
14078 << AD->getNamespace();
14079 return nullptr;
14080 }
14081 } else if (isVisible(PrevDecl)) {
14082 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
14083 ? diag::err_redefinition
14084 : diag::err_redefinition_different_kind;
14085 Diag(AliasLoc, DiagID) << Alias;
14086 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
14087 return nullptr;
14088 }
14089 }
14090
14091 // The use of a nested name specifier may trigger deprecation warnings.
14092 DiagnoseUseOfDecl(ND, IdentLoc);
14093
14095 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
14096 Alias, SS.getWithLocInContext(Context),
14097 IdentLoc, ND);
14098 if (Prev)
14099 AliasDecl->setPreviousDecl(Prev);
14100
14102 return AliasDecl;
14103}
14104
14105namespace {
14106struct SpecialMemberExceptionSpecInfo
14107 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
14108 SourceLocation Loc;
14110
14111 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
14114 SourceLocation Loc)
14115 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
14116
14117 bool visitBase(CXXBaseSpecifier *Base);
14118 bool visitField(FieldDecl *FD);
14119
14120 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
14121 unsigned Quals);
14122
14123 void visitSubobjectCall(Subobject Subobj,
14125};
14126}
14127
14128bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
14129 auto *BaseClass = Base->getType()->getAsCXXRecordDecl();
14130 if (!BaseClass)
14131 return false;
14132
14133 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
14134 if (auto *BaseCtor = SMOR.getMethod()) {
14135 visitSubobjectCall(Base, BaseCtor);
14136 return false;
14137 }
14138
14139 visitClassSubobject(BaseClass, Base, 0);
14140 return false;
14141}
14142
14143bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
14144 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
14145 FD->hasInClassInitializer()) {
14146 Expr *E = FD->getInClassInitializer();
14147 if (!E)
14148 // FIXME: It's a little wasteful to build and throw away a
14149 // CXXDefaultInitExpr here.
14150 // FIXME: We should have a single context note pointing at Loc, and
14151 // this location should be MD->getLocation() instead, since that's
14152 // the location where we actually use the default init expression.
14153 E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
14154 if (E)
14155 ExceptSpec.CalledExpr(E);
14156 } else if (auto *RD = S.Context.getBaseElementType(FD->getType())
14157 ->getAsCXXRecordDecl()) {
14158 visitClassSubobject(RD, FD, FD->getType().getCVRQualifiers());
14159 }
14160 return false;
14161}
14162
14163void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
14164 Subobject Subobj,
14165 unsigned Quals) {
14166 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
14167 bool IsMutable = Field && Field->isMutable();
14168 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
14169}
14170
14171void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
14172 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
14173 // Note, if lookup fails, it doesn't matter what exception specification we
14174 // choose because the special member will be deleted.
14175 if (CXXMethodDecl *MD = SMOR.getMethod())
14176 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
14177}
14178
14180 llvm::APSInt Result;
14182 ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEKind::ExplicitBool);
14183 ExplicitSpec.setExpr(Converted.get());
14184 if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
14185 ExplicitSpec.setKind(Result.getBoolValue()
14188 return true;
14189 }
14191 return false;
14192}
14193
14196 if (!ExplicitExpr->isTypeDependent())
14198 return ES;
14199}
14200
14205 ComputingExceptionSpec CES(S, MD, Loc);
14206
14207 CXXRecordDecl *ClassDecl = MD->getParent();
14208
14209 // C++ [except.spec]p14:
14210 // An implicitly declared special member function (Clause 12) shall have an
14211 // exception-specification. [...]
14212 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
14213 if (ClassDecl->isInvalidDecl())
14214 return Info.ExceptSpec;
14215
14216 // FIXME: If this diagnostic fires, we're probably missing a check for
14217 // attempting to resolve an exception specification before it's known
14218 // at a higher level.
14219 if (S.RequireCompleteType(MD->getLocation(),
14220 S.Context.getCanonicalTagType(ClassDecl),
14221 diag::err_exception_spec_incomplete_type))
14222 return Info.ExceptSpec;
14223
14224 // C++1z [except.spec]p7:
14225 // [Look for exceptions thrown by] a constructor selected [...] to
14226 // initialize a potentially constructed subobject,
14227 // C++1z [except.spec]p8:
14228 // The exception specification for an implicitly-declared destructor, or a
14229 // destructor without a noexcept-specifier, is potentially-throwing if and
14230 // only if any of the destructors for any of its potentially constructed
14231 // subojects is potentially throwing.
14232 // FIXME: We respect the first rule but ignore the "potentially constructed"
14233 // in the second rule to resolve a core issue (no number yet) that would have
14234 // us reject:
14235 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
14236 // struct B : A {};
14237 // struct C : B { void f(); };
14238 // ... due to giving B::~B() a non-throwing exception specification.
14239 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
14240 : Info.VisitAllBases);
14241
14242 return Info.ExceptSpec;
14243}
14244
14245namespace {
14246/// RAII object to register a special member as being currently declared.
14247struct DeclaringSpecialMember {
14248 Sema &S;
14250 Sema::ContextRAII SavedContext;
14251 bool WasAlreadyBeingDeclared;
14252
14253 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, CXXSpecialMemberKind CSM)
14254 : S(S), D(RD, CSM), SavedContext(S, RD) {
14255 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
14256 if (WasAlreadyBeingDeclared)
14257 // This almost never happens, but if it does, ensure that our cache
14258 // doesn't contain a stale result.
14259 S.SpecialMemberCache.clear();
14260 else {
14261 // Register a note to be produced if we encounter an error while
14262 // declaring the special member.
14263 Sema::CodeSynthesisContext Ctx;
14264 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
14265 // FIXME: We don't have a location to use here. Using the class's
14266 // location maintains the fiction that we declare all special members
14267 // with the class, but (1) it's not clear that lying about that helps our
14268 // users understand what's going on, and (2) there may be outer contexts
14269 // on the stack (some of which are relevant) and printing them exposes
14270 // our lies.
14271 Ctx.PointOfInstantiation = RD->getLocation();
14272 Ctx.Entity = RD;
14273 Ctx.SpecialMember = CSM;
14274 S.pushCodeSynthesisContext(Ctx);
14275 }
14276 }
14277 ~DeclaringSpecialMember() {
14278 if (!WasAlreadyBeingDeclared) {
14279 S.SpecialMembersBeingDeclared.erase(D);
14281 }
14282 }
14283
14284 /// Are we already trying to declare this special member?
14285 bool isAlreadyBeingDeclared() const {
14286 return WasAlreadyBeingDeclared;
14287 }
14288};
14289}
14290
14292 // Look up any existing declarations, but don't trigger declaration of all
14293 // implicit special members with this name.
14294 DeclarationName Name = FD->getDeclName();
14297 for (auto *D : FD->getParent()->lookup(Name))
14298 if (auto *Acceptable = R.getAcceptableDecl(D))
14299 R.addDecl(Acceptable);
14300 R.resolveKind();
14301 R.suppressDiagnostics();
14302
14303 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/ false,
14305}
14306
14307void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
14308 QualType ResultTy,
14309 ArrayRef<QualType> Args) {
14310 // Build an exception specification pointing back at this constructor.
14312
14313 LangAS AS = getDefaultCXXMethodAddrSpace();
14314 if (AS != LangAS::Default) {
14315 EPI.TypeQuals.addAddressSpace(AS);
14316 }
14317
14318 auto QT = Context.getFunctionType(ResultTy, Args, EPI);
14319 SpecialMem->setType(QT);
14320
14321 // During template instantiation of implicit special member functions we need
14322 // a reliable TypeSourceInfo for the function prototype in order to allow
14323 // functions to be substituted.
14324 if (inTemplateInstantiation() && isLambdaMethod(SpecialMem)) {
14325 TypeSourceInfo *TSI =
14326 Context.getTrivialTypeSourceInfo(SpecialMem->getType());
14327 SpecialMem->setTypeSourceInfo(TSI);
14328 }
14329}
14330
14332 CXXRecordDecl *ClassDecl) {
14333 // C++ [class.ctor]p5:
14334 // A default constructor for a class X is a constructor of class X
14335 // that can be called without an argument. If there is no
14336 // user-declared constructor for class X, a default constructor is
14337 // implicitly declared. An implicitly-declared default constructor
14338 // is an inline public member of its class.
14339 assert(ClassDecl->needsImplicitDefaultConstructor() &&
14340 "Should not build implicit default constructor!");
14341
14342 DeclaringSpecialMember DSM(*this, ClassDecl,
14344 if (DSM.isAlreadyBeingDeclared())
14345 return nullptr;
14346
14348 *this, ClassDecl, CXXSpecialMemberKind::DefaultConstructor, false);
14349
14350 // Create the actual constructor declaration.
14351 CanQualType ClassType = Context.getCanonicalTagType(ClassDecl);
14352 SourceLocation ClassLoc = ClassDecl->getLocation();
14353 DeclarationName Name
14354 = Context.DeclarationNames.getCXXConstructorName(ClassType);
14355 DeclarationNameInfo NameInfo(Name, ClassLoc);
14357 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),
14358 /*TInfo=*/nullptr, ExplicitSpecifier(),
14359 getCurFPFeatures().isFPConstrained(),
14360 /*isInline=*/true, /*isImplicitlyDeclared=*/true,
14363 DefaultCon->setAccess(AS_public);
14364 DefaultCon->setDefaulted();
14365
14366 setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, {});
14367
14368 if (getLangOpts().CUDA)
14369 CUDA().inferTargetForImplicitSpecialMember(
14370 ClassDecl, CXXSpecialMemberKind::DefaultConstructor, DefaultCon,
14371 /* ConstRHS */ false,
14372 /* Diagnose */ false);
14373
14374 // We don't need to use SpecialMemberIsTrivial here; triviality for default
14375 // constructors is easy to compute.
14376 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
14377
14378 // Note that we have declared this constructor.
14379 ++getASTContext().NumImplicitDefaultConstructorsDeclared;
14380
14381 Scope *S = getScopeForContext(ClassDecl);
14383
14384 if (ShouldDeleteSpecialMember(DefaultCon,
14386 SetDeclDeleted(DefaultCon, ClassLoc);
14387
14388 if (S)
14389 PushOnScopeChains(DefaultCon, S, false);
14390 ClassDecl->addDecl(DefaultCon);
14391
14392 return DefaultCon;
14393}
14394
14397 DefaultedFunctionFPFeaturesRAII RestoreFP(*this, Constructor);
14398 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
14399 !Constructor->doesThisDeclarationHaveABody() &&
14400 !Constructor->isDeleted()) &&
14401 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
14402 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
14403 return;
14404
14405 CXXRecordDecl *ClassDecl = Constructor->getParent();
14406 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
14407 if (ClassDecl->isInvalidDecl()) {
14408 return;
14409 }
14410
14412
14413 // The exception specification is needed because we are defining the
14414 // function.
14415 ResolveExceptionSpec(CurrentLocation,
14416 Constructor->getType()->castAs<FunctionProtoType>());
14417 MarkVTableUsed(CurrentLocation, ClassDecl);
14418
14419 // Add a context note for diagnostics produced after this point.
14420 Scope.addContextNote(CurrentLocation);
14421
14422 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
14423 Constructor->setInvalidDecl();
14424 return;
14425 }
14426
14427 SourceLocation Loc = Constructor->getEndLoc().isValid()
14428 ? Constructor->getEndLoc()
14429 : Constructor->getLocation();
14430 Constructor->setBody(new (Context) CompoundStmt(Loc));
14431 Constructor->markUsed(Context);
14432
14434 L->CompletedImplicitDefinition(Constructor);
14435 }
14436
14437 DiagnoseUninitializedFields(*this, Constructor);
14438
14439 // The synthesized body applies the class's NSDMIs and never reaches the
14440 // normal IssueWarnings path, so run lifetime safety on it here.
14441 AnalysisWarnings.IssueWarningsForImplicitFunction(Constructor);
14442}
14443
14445 // Perform any delayed checks on exception specifications.
14447}
14448
14449/// Find or create the fake constructor we synthesize to model constructing an
14450/// object of a derived class via a constructor of a base class.
14453 CXXConstructorDecl *BaseCtor,
14455 CXXRecordDecl *Derived = Shadow->getParent();
14456 SourceLocation UsingLoc = Shadow->getLocation();
14457
14458 // FIXME: Add a new kind of DeclarationName for an inherited constructor.
14459 // For now we use the name of the base class constructor as a member of the
14460 // derived class to indicate a (fake) inherited constructor name.
14461 DeclarationName Name = BaseCtor->getDeclName();
14462
14463 // Check to see if we already have a fake constructor for this inherited
14464 // constructor call.
14465 for (NamedDecl *Ctor : Derived->lookup(Name))
14467 ->getInheritedConstructor()
14468 .getConstructor(),
14469 BaseCtor))
14470 return cast<CXXConstructorDecl>(Ctor);
14471
14472 DeclarationNameInfo NameInfo(Name, UsingLoc);
14473 TypeSourceInfo *TInfo =
14474 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
14475 FunctionProtoTypeLoc ProtoLoc =
14477
14478 // Check the inherited constructor is valid and find the list of base classes
14479 // from which it was inherited.
14480 InheritedConstructorInfo ICI(*this, Loc, Shadow);
14481
14482 bool Constexpr = BaseCtor->isConstexpr() &&
14485 false, BaseCtor, &ICI);
14486
14488 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
14489 BaseCtor->getExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
14490 /*isInline=*/true,
14491 /*isImplicitlyDeclared=*/true,
14493 InheritedConstructor(Shadow, BaseCtor),
14494 BaseCtor->getTrailingRequiresClause());
14495 if (Shadow->isInvalidDecl())
14496 DerivedCtor->setInvalidDecl();
14497
14498 // Build an unevaluated exception specification for this fake constructor.
14499 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
14502 EPI.ExceptionSpec.SourceDecl = DerivedCtor;
14503 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
14504 FPT->getParamTypes(), EPI));
14505
14506 // Build the parameter declarations.
14508 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
14509 TypeSourceInfo *TInfo =
14510 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
14512 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
14513 FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr);
14514 PD->setScopeInfo(0, I);
14515 PD->setImplicit();
14516 // Ensure attributes are propagated onto parameters (this matters for
14517 // format, pass_object_size, ...).
14518 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
14519 ParamDecls.push_back(PD);
14520 ProtoLoc.setParam(I, PD);
14521 }
14522
14523 // Set up the new constructor.
14524 assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
14525 DerivedCtor->setAccess(BaseCtor->getAccess());
14526 DerivedCtor->setParams(ParamDecls);
14527 Derived->addDecl(DerivedCtor);
14528
14529 if (ShouldDeleteSpecialMember(DerivedCtor,
14531 SetDeclDeleted(DerivedCtor, UsingLoc);
14532
14533 return DerivedCtor;
14534}
14535
14543
14546 CXXRecordDecl *ClassDecl = Constructor->getParent();
14547 assert(Constructor->getInheritedConstructor() &&
14548 !Constructor->doesThisDeclarationHaveABody() &&
14549 !Constructor->isDeleted());
14550 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
14551 return;
14552
14553 // Initializations are performed "as if by a defaulted default constructor",
14554 // so enter the appropriate scope.
14556
14557 // The exception specification is needed because we are defining the
14558 // function.
14559 ResolveExceptionSpec(CurrentLocation,
14560 Constructor->getType()->castAs<FunctionProtoType>());
14561 MarkVTableUsed(CurrentLocation, ClassDecl);
14562
14563 // Add a context note for diagnostics produced after this point.
14564 Scope.addContextNote(CurrentLocation);
14565
14567 Constructor->getInheritedConstructor().getShadowDecl();
14568 CXXConstructorDecl *InheritedCtor =
14569 Constructor->getInheritedConstructor().getConstructor();
14570
14571 // [class.inhctor.init]p1:
14572 // initialization proceeds as if a defaulted default constructor is used to
14573 // initialize the D object and each base class subobject from which the
14574 // constructor was inherited
14575
14576 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
14577 CXXRecordDecl *RD = Shadow->getParent();
14578 SourceLocation InitLoc = Shadow->getLocation();
14579
14580 // Build explicit initializers for all base classes from which the
14581 // constructor was inherited.
14583 for (bool VBase : {false, true}) {
14584 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
14585 if (B.isVirtual() != VBase)
14586 continue;
14587
14588 auto *BaseRD = B.getType()->getAsCXXRecordDecl();
14589 if (!BaseRD)
14590 continue;
14591
14592 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
14593 if (!BaseCtor.first)
14594 continue;
14595
14596 MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
14598 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
14599
14600 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
14601 Inits.push_back(new (Context) CXXCtorInitializer(
14602 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
14603 SourceLocation()));
14604 }
14605 }
14606
14607 // We now proceed as if for a defaulted default constructor, with the relevant
14608 // initializers replaced.
14609
14610 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
14611 Constructor->setInvalidDecl();
14612 return;
14613 }
14614
14615 Constructor->setBody(new (Context) CompoundStmt(InitLoc));
14616 Constructor->markUsed(Context);
14617
14619 L->CompletedImplicitDefinition(Constructor);
14620 }
14621
14622 DiagnoseUninitializedFields(*this, Constructor);
14623
14624 // The synthesized body applies the class's NSDMIs and never reaches the
14625 // normal IssueWarnings path, so run lifetime safety on it here.
14626 AnalysisWarnings.IssueWarningsForImplicitFunction(Constructor);
14627}
14628
14630 // C++ [class.dtor]p2:
14631 // If a class has no user-declared destructor, a destructor is
14632 // declared implicitly. An implicitly-declared destructor is an
14633 // inline public member of its class.
14634 assert(ClassDecl->needsImplicitDestructor());
14635
14636 DeclaringSpecialMember DSM(*this, ClassDecl,
14638 if (DSM.isAlreadyBeingDeclared())
14639 return nullptr;
14640
14642 *this, ClassDecl, CXXSpecialMemberKind::Destructor, false);
14643
14644 // Create the actual destructor declaration.
14645 CanQualType ClassType = Context.getCanonicalTagType(ClassDecl);
14646 SourceLocation ClassLoc = ClassDecl->getLocation();
14647 DeclarationName Name
14648 = Context.DeclarationNames.getCXXDestructorName(ClassType);
14649 DeclarationNameInfo NameInfo(Name, ClassLoc);
14651 Context, ClassDecl, ClassLoc, NameInfo, QualType(), nullptr,
14652 getCurFPFeatures().isFPConstrained(),
14653 /*isInline=*/true,
14654 /*isImplicitlyDeclared=*/true,
14657 Destructor->setAccess(AS_public);
14658 Destructor->setDefaulted();
14659
14660 setupImplicitSpecialMemberType(Destructor, Context.VoidTy, {});
14661
14662 if (getLangOpts().CUDA)
14663 CUDA().inferTargetForImplicitSpecialMember(
14665 /* ConstRHS */ false,
14666 /* Diagnose */ false);
14667
14668 // We don't need to use SpecialMemberIsTrivial here; triviality for
14669 // destructors is easy to compute.
14670 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
14671 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
14672 ClassDecl->hasTrivialDestructorForCall());
14673
14674 // Note that we have declared this destructor.
14675 ++getASTContext().NumImplicitDestructorsDeclared;
14676
14677 Scope *S = getScopeForContext(ClassDecl);
14679
14680 // We can't check whether an implicit destructor is deleted before we complete
14681 // the definition of the class, because its validity depends on the alignment
14682 // of the class. We'll check this from ActOnFields once the class is complete.
14683 if (ClassDecl->isCompleteDefinition() &&
14685 SetDeclDeleted(Destructor, ClassLoc);
14686
14687 // Introduce this destructor into its scope.
14688 if (S)
14689 PushOnScopeChains(Destructor, S, false);
14690 ClassDecl->addDecl(Destructor);
14691
14692 return Destructor;
14693}
14694
14697 DefaultedFunctionFPFeaturesRAII RestoreFP(*this, Destructor);
14698 assert((Destructor->isDefaulted() &&
14699 !Destructor->doesThisDeclarationHaveABody() &&
14700 !Destructor->isDeleted()) &&
14701 "DefineImplicitDestructor - call it for implicit default dtor");
14702 if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
14703 return;
14704
14705 CXXRecordDecl *ClassDecl = Destructor->getParent();
14706 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
14707
14709
14710 // The exception specification is needed because we are defining the
14711 // function.
14712 ResolveExceptionSpec(CurrentLocation,
14713 Destructor->getType()->castAs<FunctionProtoType>());
14714 MarkVTableUsed(CurrentLocation, ClassDecl);
14715
14716 // Add a context note for diagnostics produced after this point.
14717 Scope.addContextNote(CurrentLocation);
14718
14720 Destructor->getParent());
14721
14723 Destructor->setInvalidDecl();
14724 return;
14725 }
14726
14727 SourceLocation Loc = Destructor->getEndLoc().isValid()
14728 ? Destructor->getEndLoc()
14729 : Destructor->getLocation();
14730 Destructor->setBody(new (Context) CompoundStmt(Loc));
14731 Destructor->markUsed(Context);
14732
14734 L->CompletedImplicitDefinition(Destructor);
14735 }
14736}
14737
14740 if (Destructor->isInvalidDecl())
14741 return;
14742
14743 CXXRecordDecl *ClassDecl = Destructor->getParent();
14744 assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&
14745 "implicit complete dtors unneeded outside MS ABI");
14746 assert(ClassDecl->getNumVBases() > 0 &&
14747 "complete dtor only exists for classes with vbases");
14748
14750
14751 // Add a context note for diagnostics produced after this point.
14752 Scope.addContextNote(CurrentLocation);
14753
14754 MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl);
14755}
14756
14758 // If the context is an invalid C++ class, just suppress these checks.
14759 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
14760 if (Record->isInvalidDecl()) {
14763 return;
14764 }
14766 }
14767}
14768
14771
14772 if (!DelayedDllExportMemberFunctions.empty()) {
14774 std::swap(DelayedDllExportMemberFunctions, WorkList);
14775 for (CXXMethodDecl *M : WorkList) {
14776 DefineDefaultedFunction(*this, M, M->getLocation());
14777
14778 // Pass the method to the consumer to get emitted. This is not necessary
14779 // for explicit instantiation definitions, as they will get emitted
14780 // anyway.
14781 if (M->getParent()->getTemplateSpecializationKind() !=
14784 }
14785 }
14786}
14787
14789 if (!DelayedDllExportClasses.empty()) {
14790 // Calling ReferenceDllExportedMembers might cause the current function to
14791 // be called again, so use a local copy of DelayedDllExportClasses.
14793 std::swap(DelayedDllExportClasses, WorkList);
14794 for (CXXRecordDecl *Class : WorkList)
14796 }
14797}
14798
14800 assert(getLangOpts().CPlusPlus11 &&
14801 "adjusting dtor exception specs was introduced in c++11");
14802
14803 if (Destructor->isDependentContext())
14804 return;
14805
14806 // C++11 [class.dtor]p3:
14807 // A declaration of a destructor that does not have an exception-
14808 // specification is implicitly considered to have the same exception-
14809 // specification as an implicit declaration.
14810 const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>();
14811 if (DtorType->hasExceptionSpec())
14812 return;
14813
14814 // Replace the destructor's type, building off the existing one. Fortunately,
14815 // the only thing of interest in the destructor type is its extended info.
14816 // The return and arguments are fixed.
14817 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
14820 Destructor->setType(Context.getFunctionType(Context.VoidTy, {}, EPI));
14821
14822 // FIXME: If the destructor has a body that could throw, and the newly created
14823 // spec doesn't allow exceptions, we should emit a warning, because this
14824 // change in behavior can break conforming C++03 programs at runtime.
14825 // However, we don't have a body or an exception specification yet, so it
14826 // needs to be done somewhere else.
14827}
14828
14829namespace {
14830/// An abstract base class for all helper classes used in building the
14831// copy/move operators. These classes serve as factory functions and help us
14832// avoid using the same Expr* in the AST twice.
14833class ExprBuilder {
14834 ExprBuilder(const ExprBuilder&) = delete;
14835 ExprBuilder &operator=(const ExprBuilder&) = delete;
14836
14837protected:
14838 static Expr *assertNotNull(Expr *E) {
14839 assert(E && "Expression construction must not fail.");
14840 return E;
14841 }
14842
14843public:
14844 ExprBuilder() {}
14845 virtual ~ExprBuilder() {}
14846
14847 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
14848};
14849
14850class RefBuilder: public ExprBuilder {
14851 VarDecl *Var;
14852 QualType VarType;
14853
14854public:
14855 Expr *build(Sema &S, SourceLocation Loc) const override {
14856 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));
14857 }
14858
14859 RefBuilder(VarDecl *Var, QualType VarType)
14860 : Var(Var), VarType(VarType) {}
14861};
14862
14863class ThisBuilder: public ExprBuilder {
14864public:
14865 Expr *build(Sema &S, SourceLocation Loc) const override {
14866 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
14867 }
14868};
14869
14870class CastBuilder: public ExprBuilder {
14871 const ExprBuilder &Builder;
14872 QualType Type;
14874 const CXXCastPath &Path;
14875
14876public:
14877 Expr *build(Sema &S, SourceLocation Loc) const override {
14878 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
14879 CK_UncheckedDerivedToBase, Kind,
14880 &Path).get());
14881 }
14882
14883 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
14884 const CXXCastPath &Path)
14885 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
14886};
14887
14888class DerefBuilder: public ExprBuilder {
14889 const ExprBuilder &Builder;
14890
14891public:
14892 Expr *build(Sema &S, SourceLocation Loc) const override {
14893 return assertNotNull(
14894 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
14895 }
14896
14897 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14898};
14899
14900class MemberBuilder: public ExprBuilder {
14901 const ExprBuilder &Builder;
14902 QualType Type;
14903 CXXScopeSpec SS;
14904 bool IsArrow;
14905 LookupResult &MemberLookup;
14906
14907public:
14908 Expr *build(Sema &S, SourceLocation Loc) const override {
14909 return assertNotNull(S.BuildMemberReferenceExpr(
14910 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
14911 nullptr, MemberLookup, nullptr, nullptr).get());
14912 }
14913
14914 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
14915 LookupResult &MemberLookup)
14916 : Builder(Builder), Type(Type), IsArrow(IsArrow),
14917 MemberLookup(MemberLookup) {}
14918};
14919
14920class MoveCastBuilder: public ExprBuilder {
14921 const ExprBuilder &Builder;
14922
14923public:
14924 Expr *build(Sema &S, SourceLocation Loc) const override {
14925 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
14926 }
14927
14928 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14929};
14930
14931class LvalueConvBuilder: public ExprBuilder {
14932 const ExprBuilder &Builder;
14933
14934public:
14935 Expr *build(Sema &S, SourceLocation Loc) const override {
14936 return assertNotNull(
14937 S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
14938 }
14939
14940 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14941};
14942
14943class SubscriptBuilder: public ExprBuilder {
14944 const ExprBuilder &Base;
14945 const ExprBuilder &Index;
14946
14947public:
14948 Expr *build(Sema &S, SourceLocation Loc) const override {
14949 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
14950 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
14951 }
14952
14953 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
14954 : Base(Base), Index(Index) {}
14955};
14956
14957} // end anonymous namespace
14958
14959/// When generating a defaulted copy or move assignment operator, if a field
14960/// should be copied with __builtin_memcpy rather than via explicit assignments,
14961/// do so. This optimization only applies for arrays of scalars, and for arrays
14962/// of class type where the selected copy/move-assignment operator is trivial.
14963static StmtResult
14965 const ExprBuilder &ToB, const ExprBuilder &FromB) {
14966 // Compute the size of the memory buffer to be copied.
14967 QualType SizeType = S.Context.getSizeType();
14968 llvm::APInt Size(S.Context.getTypeSize(SizeType),
14970
14971 // Take the address of the field references for "from" and "to". We
14972 // directly construct UnaryOperators here because semantic analysis
14973 // does not permit us to take the address of an xvalue.
14974 Expr *From = FromB.build(S, Loc);
14975 From = UnaryOperator::Create(
14976 S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()),
14977 VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
14978 Expr *To = ToB.build(S, Loc);
14980 S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()),
14981 VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
14982
14983 bool NeedsCollectableMemCpy = false;
14984 if (auto *RD = T->getBaseElementTypeUnsafe()->getAsRecordDecl())
14985 NeedsCollectableMemCpy = RD->hasObjectMember();
14986
14987 // Create a reference to the __builtin_objc_memmove_collectable function
14988 StringRef MemCpyName = NeedsCollectableMemCpy ?
14989 "__builtin_objc_memmove_collectable" :
14990 "__builtin_memcpy";
14991 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
14993 S.LookupName(R, S.TUScope, true);
14994
14995 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
14996 if (!MemCpy)
14997 // Something went horribly wrong earlier, and we will have complained
14998 // about it.
14999 return StmtError();
15000
15001 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
15002 VK_PRValue, Loc, nullptr);
15003 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
15004
15005 Expr *CallArgs[] = {
15006 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
15007 };
15008 ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
15009 Loc, CallArgs, Loc);
15010
15011 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
15012 return Call.getAs<Stmt>();
15013}
15014
15015/// Builds a statement that copies/moves the given entity from \p From to
15016/// \c To.
15017///
15018/// This routine is used to copy/move the members of a class with an
15019/// implicitly-declared copy/move assignment operator. When the entities being
15020/// copied are arrays, this routine builds for loops to copy them.
15021///
15022/// \param S The Sema object used for type-checking.
15023///
15024/// \param Loc The location where the implicit copy/move is being generated.
15025///
15026/// \param T The type of the expressions being copied/moved. Both expressions
15027/// must have this type.
15028///
15029/// \param To The expression we are copying/moving to.
15030///
15031/// \param From The expression we are copying/moving from.
15032///
15033/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
15034/// Otherwise, it's a non-static member subobject.
15035///
15036/// \param Copying Whether we're copying or moving.
15037///
15038/// \param Depth Internal parameter recording the depth of the recursion.
15039///
15040/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
15041/// if a memcpy should be used instead.
15042static StmtResult
15044 const ExprBuilder &To, const ExprBuilder &From,
15045 bool CopyingBaseSubobject, bool Copying,
15046 unsigned Depth = 0) {
15047 // C++11 [class.copy]p28:
15048 // Each subobject is assigned in the manner appropriate to its type:
15049 //
15050 // - if the subobject is of class type, as if by a call to operator= with
15051 // the subobject as the object expression and the corresponding
15052 // subobject of x as a single function argument (as if by explicit
15053 // qualification; that is, ignoring any possible virtual overriding
15054 // functions in more derived classes);
15055 //
15056 // C++03 [class.copy]p13:
15057 // - if the subobject is of class type, the copy assignment operator for
15058 // the class is used (as if by explicit qualification; that is,
15059 // ignoring any possible virtual overriding functions in more derived
15060 // classes);
15061 if (auto *ClassDecl = T->getAsCXXRecordDecl()) {
15062 // Look for operator=.
15063 DeclarationName Name
15065 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
15066 S.LookupQualifiedName(OpLookup, ClassDecl, false);
15067
15068 // Prior to C++11, filter out any result that isn't a copy/move-assignment
15069 // operator.
15070 if (!S.getLangOpts().CPlusPlus11) {
15071 LookupResult::Filter F = OpLookup.makeFilter();
15072 while (F.hasNext()) {
15073 NamedDecl *D = F.next();
15074 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
15075 if (Method->isCopyAssignmentOperator() ||
15076 (!Copying && Method->isMoveAssignmentOperator()))
15077 continue;
15078
15079 F.erase();
15080 }
15081 F.done();
15082 }
15083
15084 // Suppress the protected check (C++ [class.protected]) for each of the
15085 // assignment operators we found. This strange dance is required when
15086 // we're assigning via a base classes's copy-assignment operator. To
15087 // ensure that we're getting the right base class subobject (without
15088 // ambiguities), we need to cast "this" to that subobject type; to
15089 // ensure that we don't go through the virtual call mechanism, we need
15090 // to qualify the operator= name with the base class (see below). However,
15091 // this means that if the base class has a protected copy assignment
15092 // operator, the protected member access check will fail. So, we
15093 // rewrite "protected" access to "public" access in this case, since we
15094 // know by construction that we're calling from a derived class.
15095 if (CopyingBaseSubobject) {
15096 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
15097 L != LEnd; ++L) {
15098 if (L.getAccess() == AS_protected)
15099 L.setAccess(AS_public);
15100 }
15101 }
15102
15103 // Create the nested-name-specifier that will be used to qualify the
15104 // reference to operator=; this is required to suppress the virtual
15105 // call mechanism.
15106 CXXScopeSpec SS;
15107 // FIXME: Don't canonicalize this.
15108 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
15109 SS.MakeTrivial(S.Context, NestedNameSpecifier(CanonicalT), Loc);
15110
15111 // Create the reference to operator=.
15112 ExprResult OpEqualRef
15113 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false,
15114 SS, /*TemplateKWLoc=*/SourceLocation(),
15115 /*FirstQualifierInScope=*/nullptr,
15116 OpLookup,
15117 /*TemplateArgs=*/nullptr, /*S*/nullptr,
15118 /*SuppressQualifierCheck=*/true);
15119 if (OpEqualRef.isInvalid())
15120 return StmtError();
15121
15122 // Build the call to the assignment operator.
15123
15124 Expr *FromInst = From.build(S, Loc);
15125 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
15126 OpEqualRef.getAs<Expr>(),
15127 Loc, FromInst, Loc);
15128 if (Call.isInvalid())
15129 return StmtError();
15130
15131 // If we built a call to a trivial 'operator=' while copying an array,
15132 // bail out. We'll replace the whole shebang with a memcpy.
15133 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
15134 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
15135 return StmtResult((Stmt*)nullptr);
15136
15137 // Convert to an expression-statement, and clean up any produced
15138 // temporaries.
15139 return S.ActOnExprStmt(Call);
15140 }
15141
15142 // - if the subobject is of scalar type, the built-in assignment
15143 // operator is used.
15145 if (!ArrayTy) {
15147 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
15148 if (Assignment.isInvalid())
15149 return StmtError();
15150 return S.ActOnExprStmt(Assignment);
15151 }
15152
15153 // - if the subobject is an array, each element is assigned, in the
15154 // manner appropriate to the element type;
15155
15156 // Construct a loop over the array bounds, e.g.,
15157 //
15158 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
15159 //
15160 // that will copy each of the array elements.
15161 QualType SizeType = S.Context.getSizeType();
15162
15163 // Create the iteration variable.
15164 IdentifierInfo *IterationVarName = nullptr;
15165 {
15166 SmallString<8> Str;
15167 llvm::raw_svector_ostream OS(Str);
15168 OS << "__i" << Depth;
15169 IterationVarName = &S.Context.Idents.get(OS.str());
15170 }
15171 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
15172 IterationVarName, SizeType,
15173 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
15174 SC_None);
15175
15176 // Initialize the iteration variable to zero.
15177 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
15178 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
15179
15180 // Creates a reference to the iteration variable.
15181 RefBuilder IterationVarRef(IterationVar, SizeType);
15182 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
15183
15184 // Create the DeclStmt that holds the iteration variable.
15185 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
15186
15187 // Subscript the "from" and "to" expressions with the iteration variable.
15188 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
15189 MoveCastBuilder FromIndexMove(FromIndexCopy);
15190 const ExprBuilder *FromIndex;
15191 if (Copying)
15192 FromIndex = &FromIndexCopy;
15193 else
15194 FromIndex = &FromIndexMove;
15195
15196 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
15197
15198 // Build the copy/move for an individual element of the array.
15199 StmtResult Copy =
15201 ToIndex, *FromIndex, CopyingBaseSubobject,
15202 Copying, Depth + 1);
15203 // Bail out if copying fails or if we determined that we should use memcpy.
15204 if (Copy.isInvalid() || !Copy.get())
15205 return Copy;
15206
15207 // Create the comparison against the array bound.
15208 llvm::APInt Upper
15209 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
15211 S.Context, IterationVarRefRVal.build(S, Loc),
15212 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE,
15215
15216 // Create the pre-increment of the iteration variable. We can determine
15217 // whether the increment will overflow based on the value of the array
15218 // bound.
15219 Expr *Increment = UnaryOperator::Create(
15220 S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue,
15221 OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides());
15222
15223 // Construct the loop that copies all elements of this array.
15224 return S.ActOnForStmt(
15225 Loc, Loc, InitStmt,
15227 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
15228}
15229
15230static StmtResult
15232 const ExprBuilder &To, const ExprBuilder &From,
15233 bool CopyingBaseSubobject, bool Copying) {
15234 // Maybe we should use a memcpy?
15235 if (T->isArrayType() && !T.hasQualifiers() &&
15236 T.isTriviallyCopyableType(S.Context))
15237 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
15238
15239 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
15240 CopyingBaseSubobject,
15241 Copying, 0));
15242
15243 // If we ended up picking a trivial assignment operator for an array of a
15244 // non-trivially-copyable class type, just emit a memcpy.
15245 if (!Result.isInvalid() && !Result.get())
15246 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
15247
15248 return Result;
15249}
15250
15252 // Note: The following rules are largely analoguous to the copy
15253 // constructor rules. Note that virtual bases are not taken into account
15254 // for determining the argument type of the operator. Note also that
15255 // operators taking an object instead of a reference are allowed.
15256 assert(ClassDecl->needsImplicitCopyAssignment());
15257
15258 DeclaringSpecialMember DSM(*this, ClassDecl,
15260 if (DSM.isAlreadyBeingDeclared())
15261 return nullptr;
15262
15264 /*Qualifier=*/std::nullopt, ClassDecl,
15265 /*OwnsTag=*/false);
15267 if (AS != LangAS::Default)
15268 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
15269 QualType RetType = Context.getLValueReferenceType(ArgType);
15270 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
15271 if (Const)
15272 ArgType = ArgType.withConst();
15273
15274 ArgType = Context.getLValueReferenceType(ArgType);
15275
15277 *this, ClassDecl, CXXSpecialMemberKind::CopyAssignment, Const);
15278
15279 // An implicitly-declared copy assignment operator is an inline public
15280 // member of its class.
15281 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
15282 SourceLocation ClassLoc = ClassDecl->getLocation();
15283 DeclarationNameInfo NameInfo(Name, ClassLoc);
15285 Context, ClassDecl, ClassLoc, NameInfo, QualType(),
15286 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
15287 getCurFPFeatures().isFPConstrained(),
15288 /*isInline=*/true,
15290 SourceLocation());
15291 CopyAssignment->setAccess(AS_public);
15292 CopyAssignment->setDefaulted();
15293 CopyAssignment->setImplicit();
15294
15295 setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
15296
15297 if (getLangOpts().CUDA)
15298 CUDA().inferTargetForImplicitSpecialMember(
15300 /* ConstRHS */ Const,
15301 /* Diagnose */ false);
15302
15303 // Add the parameter to the operator.
15305 ClassLoc, ClassLoc,
15306 /*Id=*/nullptr, ArgType,
15307 /*TInfo=*/nullptr, SC_None,
15308 nullptr);
15309 CopyAssignment->setParams(FromParam);
15310
15311 CopyAssignment->setTrivial(
15315 : ClassDecl->hasTrivialCopyAssignment());
15316
15317 // Note that we have added this copy-assignment operator.
15318 ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
15319
15320 Scope *S = getScopeForContext(ClassDecl);
15322
15326 SetDeclDeleted(CopyAssignment, ClassLoc);
15327 }
15328
15329 if (S)
15331 ClassDecl->addDecl(CopyAssignment);
15332
15333 return CopyAssignment;
15334}
15335
15336/// Diagnose an implicit copy operation for a class which is odr-used, but
15337/// which is deprecated because the class has a user-declared copy constructor,
15338/// copy assignment operator, or destructor.
15340 assert(CopyOp->isImplicit());
15341
15342 CXXRecordDecl *RD = CopyOp->getParent();
15343 CXXMethodDecl *UserDeclaredOperation = nullptr;
15344
15345 if (RD->hasUserDeclaredDestructor()) {
15346 UserDeclaredOperation = RD->getDestructor();
15347 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
15349 // Find any user-declared copy constructor.
15350 for (auto *I : RD->ctors()) {
15351 if (I->isCopyConstructor()) {
15352 UserDeclaredOperation = I;
15353 break;
15354 }
15355 }
15356 assert(UserDeclaredOperation);
15357 } else if (isa<CXXConstructorDecl>(CopyOp) &&
15359 // Find any user-declared move assignment operator.
15360 for (auto *I : RD->methods()) {
15361 if (I->isCopyAssignmentOperator()) {
15362 UserDeclaredOperation = I;
15363 break;
15364 }
15365 }
15366 assert(UserDeclaredOperation);
15367 }
15368
15369 if (UserDeclaredOperation) {
15370 bool UDOIsUserProvided = UserDeclaredOperation->isUserProvided();
15371 bool UDOIsDestructor = isa<CXXDestructorDecl>(UserDeclaredOperation);
15372 bool IsCopyAssignment = !isa<CXXConstructorDecl>(CopyOp);
15373 unsigned DiagID =
15374 (UDOIsUserProvided && UDOIsDestructor)
15375 ? diag::warn_deprecated_copy_with_user_provided_dtor
15376 : (UDOIsUserProvided && !UDOIsDestructor)
15377 ? diag::warn_deprecated_copy_with_user_provided_copy
15378 : (!UDOIsUserProvided && UDOIsDestructor)
15379 ? diag::warn_deprecated_copy_with_dtor
15380 : diag::warn_deprecated_copy;
15381 S.Diag(UserDeclaredOperation->getLocation(), DiagID)
15382 << RD << IsCopyAssignment;
15383 }
15384}
15385
15387 CXXMethodDecl *CopyAssignOperator) {
15388 DefaultedFunctionFPFeaturesRAII RestoreFP(*this, CopyAssignOperator);
15389 assert((CopyAssignOperator->isDefaulted() &&
15390 CopyAssignOperator->isOverloadedOperator() &&
15391 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
15392 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
15393 !CopyAssignOperator->isDeleted()) &&
15394 "DefineImplicitCopyAssignment called for wrong function");
15395 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
15396 return;
15397
15398 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
15399 if (ClassDecl->isInvalidDecl()) {
15400 CopyAssignOperator->setInvalidDecl();
15401 return;
15402 }
15403
15404 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
15405
15406 // The exception specification is needed because we are defining the
15407 // function.
15408 ResolveExceptionSpec(CurrentLocation,
15409 CopyAssignOperator->getType()->castAs<FunctionProtoType>());
15410
15411 // Add a context note for diagnostics produced after this point.
15412 Scope.addContextNote(CurrentLocation);
15413
15414 // C++11 [class.copy]p18:
15415 // The [definition of an implicitly declared copy assignment operator] is
15416 // deprecated if the class has a user-declared copy constructor or a
15417 // user-declared destructor.
15418 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
15419 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
15420
15421 // C++0x [class.copy]p30:
15422 // The implicitly-defined or explicitly-defaulted copy assignment operator
15423 // for a non-union class X performs memberwise copy assignment of its
15424 // subobjects. The direct base classes of X are assigned first, in the
15425 // order of their declaration in the base-specifier-list, and then the
15426 // immediate non-static data members of X are assigned, in the order in
15427 // which they were declared in the class definition.
15428
15429 // The statements that form the synthesized function body.
15430 SmallVector<Stmt*, 8> Statements;
15431
15432 // The parameter for the "other" object, which we are copying from.
15433 ParmVarDecl *Other = CopyAssignOperator->getNonObjectParameter(0);
15434 Qualifiers OtherQuals = Other->getType().getQualifiers();
15435 QualType OtherRefType = Other->getType();
15436 if (OtherRefType->isLValueReferenceType()) {
15437 OtherRefType = OtherRefType->getPointeeType();
15438 OtherQuals = OtherRefType.getQualifiers();
15439 }
15440
15441 // Our location for everything implicitly-generated.
15442 SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
15443 ? CopyAssignOperator->getEndLoc()
15444 : CopyAssignOperator->getLocation();
15445
15446 // Builds a DeclRefExpr for the "other" object.
15447 RefBuilder OtherRef(Other, OtherRefType);
15448
15449 // Builds the function object parameter.
15450 std::optional<ThisBuilder> This;
15451 std::optional<DerefBuilder> DerefThis;
15452 std::optional<RefBuilder> ExplicitObject;
15453 bool IsArrow = false;
15454 QualType ObjectType;
15455 if (CopyAssignOperator->isExplicitObjectMemberFunction()) {
15456 ObjectType = CopyAssignOperator->getParamDecl(0)->getType();
15457 if (ObjectType->isReferenceType())
15458 ObjectType = ObjectType->getPointeeType();
15459 ExplicitObject.emplace(CopyAssignOperator->getParamDecl(0), ObjectType);
15460 } else {
15461 ObjectType = getCurrentThisType();
15462 This.emplace();
15463 DerefThis.emplace(*This);
15464 IsArrow = !LangOpts.HLSL;
15465 }
15466 ExprBuilder &ObjectParameter =
15467 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15468 : static_cast<ExprBuilder &>(*This);
15469
15470 // Assign base classes.
15471 bool Invalid = false;
15472 for (auto &Base : ClassDecl->bases()) {
15473 // Form the assignment:
15474 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
15475 QualType BaseType = Base.getType().getUnqualifiedType();
15476 if (!BaseType->isRecordType()) {
15477 Invalid = true;
15478 continue;
15479 }
15480
15481 CXXCastPath BasePath;
15482 BasePath.push_back(&Base);
15483
15484 // Construct the "from" expression, which is an implicit cast to the
15485 // appropriately-qualified base type.
15486 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
15487 VK_LValue, BasePath);
15488
15489 // Dereference "this".
15490 CastBuilder To(
15491 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15492 : static_cast<ExprBuilder &>(*DerefThis),
15493 Context.getQualifiedType(BaseType, ObjectType.getQualifiers()),
15494 VK_LValue, BasePath);
15495
15496 // Build the copy.
15497 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
15498 To, From,
15499 /*CopyingBaseSubobject=*/true,
15500 /*Copying=*/true);
15501 if (Copy.isInvalid()) {
15502 CopyAssignOperator->setInvalidDecl();
15503 return;
15504 }
15505
15506 // Success! Record the copy.
15507 Statements.push_back(Copy.getAs<Expr>());
15508 }
15509
15510 // Assign non-static members.
15511 for (auto *Field : ClassDecl->fields()) {
15512 // FIXME: We should form some kind of AST representation for the implied
15513 // memcpy in a union copy operation.
15514 if (Field->isUnnamedBitField() || Field->getParent()->isUnion())
15515 continue;
15516
15517 if (Field->isInvalidDecl()) {
15518 Invalid = true;
15519 continue;
15520 }
15521
15522 // Check for members of reference type; we can't copy those.
15523 if (Field->getType()->isReferenceType()) {
15524 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15525 << Context.getCanonicalTagType(ClassDecl) << 0
15526 << Field->getDeclName();
15527 Diag(Field->getLocation(), diag::note_declared_at);
15528 Invalid = true;
15529 continue;
15530 }
15531
15532 // Check for members of const-qualified, non-class type.
15533 QualType BaseType = Context.getBaseElementType(Field->getType());
15534 if (!BaseType->isRecordType() && BaseType.isConstQualified()) {
15535 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15536 << Context.getCanonicalTagType(ClassDecl) << 1
15537 << Field->getDeclName();
15538 Diag(Field->getLocation(), diag::note_declared_at);
15539 Invalid = true;
15540 continue;
15541 }
15542
15543 // Suppress assigning zero-width bitfields.
15544 if (Field->isZeroLengthBitField())
15545 continue;
15546
15547 QualType FieldType = Field->getType().getNonReferenceType();
15548 if (FieldType->isIncompleteArrayType()) {
15549 assert(ClassDecl->hasFlexibleArrayMember() &&
15550 "Incomplete array type is not valid");
15551 continue;
15552 }
15553
15554 // Build references to the field in the object we're copying from and to.
15555 CXXScopeSpec SS; // Intentionally empty
15556 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
15558 MemberLookup.addDecl(Field);
15559 MemberLookup.resolveKind();
15560
15561 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
15562 MemberBuilder To(ObjectParameter, ObjectType, IsArrow, MemberLookup);
15563 // Build the copy of this field.
15564 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
15565 To, From,
15566 /*CopyingBaseSubobject=*/false,
15567 /*Copying=*/true);
15568 if (Copy.isInvalid()) {
15569 CopyAssignOperator->setInvalidDecl();
15570 return;
15571 }
15572
15573 // Success! Record the copy.
15574 Statements.push_back(Copy.getAs<Stmt>());
15575 }
15576
15577 if (!Invalid) {
15578 // Add a "return *this;"
15579 Expr *ThisExpr =
15580 (ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15581 : LangOpts.HLSL ? static_cast<ExprBuilder &>(*This)
15582 : static_cast<ExprBuilder &>(*DerefThis))
15583 .build(*this, Loc);
15584 StmtResult Return = BuildReturnStmt(Loc, ThisExpr);
15585 if (Return.isInvalid())
15586 Invalid = true;
15587 else
15588 Statements.push_back(Return.getAs<Stmt>());
15589 }
15590
15591 if (Invalid) {
15592 CopyAssignOperator->setInvalidDecl();
15593 return;
15594 }
15595
15596 StmtResult Body;
15597 {
15598 CompoundScopeRAII CompoundScope(*this);
15599 Body = ActOnCompoundStmt(Loc, Loc, Statements,
15600 /*isStmtExpr=*/false);
15601 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
15602 }
15603 CopyAssignOperator->setBody(Body.getAs<Stmt>());
15604 CopyAssignOperator->markUsed(Context);
15605
15607 L->CompletedImplicitDefinition(CopyAssignOperator);
15608 }
15609}
15610
15612 assert(ClassDecl->needsImplicitMoveAssignment());
15613
15614 DeclaringSpecialMember DSM(*this, ClassDecl,
15616 if (DSM.isAlreadyBeingDeclared())
15617 return nullptr;
15618
15619 // Note: The following rules are largely analoguous to the move
15620 // constructor rules.
15621
15623 /*Qualifier=*/std::nullopt, ClassDecl,
15624 /*OwnsTag=*/false);
15626 if (AS != LangAS::Default)
15627 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
15628 QualType RetType = Context.getLValueReferenceType(ArgType);
15629 ArgType = Context.getRValueReferenceType(ArgType);
15630
15632 *this, ClassDecl, CXXSpecialMemberKind::MoveAssignment, false);
15633
15634 // An implicitly-declared move assignment operator is an inline public
15635 // member of its class.
15636 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
15637 SourceLocation ClassLoc = ClassDecl->getLocation();
15638 DeclarationNameInfo NameInfo(Name, ClassLoc);
15640 Context, ClassDecl, ClassLoc, NameInfo, QualType(),
15641 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
15642 getCurFPFeatures().isFPConstrained(),
15643 /*isInline=*/true,
15645 SourceLocation());
15646 MoveAssignment->setAccess(AS_public);
15647 MoveAssignment->setDefaulted();
15648 MoveAssignment->setImplicit();
15649
15650 setupImplicitSpecialMemberType(MoveAssignment, RetType, ArgType);
15651
15652 if (getLangOpts().CUDA)
15653 CUDA().inferTargetForImplicitSpecialMember(
15655 /* ConstRHS */ false,
15656 /* Diagnose */ false);
15657
15658 // Add the parameter to the operator.
15660 ClassLoc, ClassLoc,
15661 /*Id=*/nullptr, ArgType,
15662 /*TInfo=*/nullptr, SC_None,
15663 nullptr);
15664 MoveAssignment->setParams(FromParam);
15665
15666 MoveAssignment->setTrivial(
15670 : ClassDecl->hasTrivialMoveAssignment());
15671
15672 // Note that we have added this copy-assignment operator.
15673 ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
15674
15675 Scope *S = getScopeForContext(ClassDecl);
15677
15681 SetDeclDeleted(MoveAssignment, ClassLoc);
15682 }
15683
15684 if (S)
15686 ClassDecl->addDecl(MoveAssignment);
15687
15688 return MoveAssignment;
15689}
15690
15691/// Check if we're implicitly defining a move assignment operator for a class
15692/// with virtual bases. Such a move assignment might move-assign the virtual
15693/// base multiple times.
15695 SourceLocation CurrentLocation) {
15696 assert(!Class->isDependentContext() && "should not define dependent move");
15697
15698 // Only a virtual base could get implicitly move-assigned multiple times.
15699 // Only a non-trivial move assignment can observe this. We only want to
15700 // diagnose if we implicitly define an assignment operator that assigns
15701 // two base classes, both of which move-assign the same virtual base.
15702 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
15703 Class->getNumBases() < 2)
15704 return;
15705
15707 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
15708 VBaseMap VBases;
15709
15710 for (auto &BI : Class->bases()) {
15711 Worklist.push_back(&BI);
15712 while (!Worklist.empty()) {
15713 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
15714 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
15715
15716 // If the base has no non-trivial move assignment operators,
15717 // we don't care about moves from it.
15718 if (!Base->hasNonTrivialMoveAssignment())
15719 continue;
15720
15721 // If there's nothing virtual here, skip it.
15722 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
15723 continue;
15724
15725 // If we're not actually going to call a move assignment for this base,
15726 // or the selected move assignment is trivial, skip it.
15729 /*ConstArg*/ false, /*VolatileArg*/ false,
15730 /*RValueThis*/ true, /*ConstThis*/ false,
15731 /*VolatileThis*/ false);
15732 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
15734 continue;
15735
15736 if (BaseSpec->isVirtual()) {
15737 // We're going to move-assign this virtual base, and its move
15738 // assignment operator is not trivial. If this can happen for
15739 // multiple distinct direct bases of Class, diagnose it. (If it
15740 // only happens in one base, we'll diagnose it when synthesizing
15741 // that base class's move assignment operator.)
15742 CXXBaseSpecifier *&Existing =
15743 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
15744 .first->second;
15745 if (Existing && Existing != &BI) {
15746 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
15747 << Class << Base;
15748 S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
15749 << (Base->getCanonicalDecl() ==
15751 << Base << Existing->getType() << Existing->getSourceRange();
15752 S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
15753 << (Base->getCanonicalDecl() ==
15754 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
15755 << Base << BI.getType() << BaseSpec->getSourceRange();
15756
15757 // Only diagnose each vbase once.
15758 Existing = nullptr;
15759 }
15760 } else {
15761 // Only walk over bases that have defaulted move assignment operators.
15762 // We assume that any user-provided move assignment operator handles
15763 // the multiple-moves-of-vbase case itself somehow.
15764 if (!SMOR.getMethod()->isDefaulted())
15765 continue;
15766
15767 // We're going to move the base classes of Base. Add them to the list.
15768 llvm::append_range(Worklist, llvm::make_pointer_range(Base->bases()));
15769 }
15770 }
15771 }
15772}
15773
15775 CXXMethodDecl *MoveAssignOperator) {
15776 DefaultedFunctionFPFeaturesRAII RestoreFP(*this, MoveAssignOperator);
15777 assert((MoveAssignOperator->isDefaulted() &&
15778 MoveAssignOperator->isOverloadedOperator() &&
15779 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
15780 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
15781 !MoveAssignOperator->isDeleted()) &&
15782 "DefineImplicitMoveAssignment called for wrong function");
15783 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
15784 return;
15785
15786 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
15787 if (ClassDecl->isInvalidDecl()) {
15788 MoveAssignOperator->setInvalidDecl();
15789 return;
15790 }
15791
15792 // C++0x [class.copy]p28:
15793 // The implicitly-defined or move assignment operator for a non-union class
15794 // X performs memberwise move assignment of its subobjects. The direct base
15795 // classes of X are assigned first, in the order of their declaration in the
15796 // base-specifier-list, and then the immediate non-static data members of X
15797 // are assigned, in the order in which they were declared in the class
15798 // definition.
15799
15800 // Issue a warning if our implicit move assignment operator will move
15801 // from a virtual base more than once.
15802 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
15803
15804 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
15805
15806 // The exception specification is needed because we are defining the
15807 // function.
15808 ResolveExceptionSpec(CurrentLocation,
15809 MoveAssignOperator->getType()->castAs<FunctionProtoType>());
15810
15811 // Add a context note for diagnostics produced after this point.
15812 Scope.addContextNote(CurrentLocation);
15813
15814 // The statements that form the synthesized function body.
15815 SmallVector<Stmt*, 8> Statements;
15816
15817 // The parameter for the "other" object, which we are move from.
15818 ParmVarDecl *Other = MoveAssignOperator->getNonObjectParameter(0);
15819 QualType OtherRefType =
15820 Other->getType()->castAs<RValueReferenceType>()->getPointeeType();
15821
15822 // Our location for everything implicitly-generated.
15823 SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
15824 ? MoveAssignOperator->getEndLoc()
15825 : MoveAssignOperator->getLocation();
15826
15827 // Builds a reference to the "other" object.
15828 RefBuilder OtherRef(Other, OtherRefType);
15829 // Cast to rvalue.
15830 MoveCastBuilder MoveOther(OtherRef);
15831
15832 // Builds the function object parameter.
15833 std::optional<ThisBuilder> This;
15834 std::optional<DerefBuilder> DerefThis;
15835 std::optional<RefBuilder> ExplicitObject;
15836 QualType ObjectType;
15837 bool IsArrow = false;
15838 if (MoveAssignOperator->isExplicitObjectMemberFunction()) {
15839 ObjectType = MoveAssignOperator->getParamDecl(0)->getType();
15840 if (ObjectType->isReferenceType())
15841 ObjectType = ObjectType->getPointeeType();
15842 ExplicitObject.emplace(MoveAssignOperator->getParamDecl(0), ObjectType);
15843 } else {
15844 ObjectType = getCurrentThisType();
15845 This.emplace();
15846 DerefThis.emplace(*This);
15847 IsArrow = !getLangOpts().HLSL;
15848 }
15849 ExprBuilder &ObjectParameter =
15850 ExplicitObject ? *ExplicitObject : static_cast<ExprBuilder &>(*This);
15851
15852 // Assign base classes.
15853 bool Invalid = false;
15854 for (auto &Base : ClassDecl->bases()) {
15855 // C++11 [class.copy]p28:
15856 // It is unspecified whether subobjects representing virtual base classes
15857 // are assigned more than once by the implicitly-defined copy assignment
15858 // operator.
15859 // FIXME: Do not assign to a vbase that will be assigned by some other base
15860 // class. For a move-assignment, this can result in the vbase being moved
15861 // multiple times.
15862
15863 // Form the assignment:
15864 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
15865 QualType BaseType = Base.getType().getUnqualifiedType();
15866 if (!BaseType->isRecordType()) {
15867 Invalid = true;
15868 continue;
15869 }
15870
15871 CXXCastPath BasePath;
15872 BasePath.push_back(&Base);
15873
15874 // Construct the "from" expression, which is an implicit cast to the
15875 // appropriately-qualified base type.
15876 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
15877
15878 // Implicitly cast "this" to the appropriately-qualified base type.
15879 // Dereference "this".
15880 CastBuilder To(
15881 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15882 : static_cast<ExprBuilder &>(*DerefThis),
15883 Context.getQualifiedType(BaseType, ObjectType.getQualifiers()),
15884 VK_LValue, BasePath);
15885
15886 // Build the move.
15887 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
15888 To, From,
15889 /*CopyingBaseSubobject=*/true,
15890 /*Copying=*/false);
15891 if (Move.isInvalid()) {
15892 MoveAssignOperator->setInvalidDecl();
15893 return;
15894 }
15895
15896 // Success! Record the move.
15897 Statements.push_back(Move.getAs<Expr>());
15898 }
15899
15900 // Assign non-static members.
15901 for (auto *Field : ClassDecl->fields()) {
15902 // FIXME: We should form some kind of AST representation for the implied
15903 // memcpy in a union copy operation.
15904 if (Field->isUnnamedBitField() || Field->getParent()->isUnion())
15905 continue;
15906
15907 if (Field->isInvalidDecl()) {
15908 Invalid = true;
15909 continue;
15910 }
15911
15912 // Check for members of reference type; we can't move those.
15913 if (Field->getType()->isReferenceType()) {
15914 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15915 << Context.getCanonicalTagType(ClassDecl) << 0
15916 << Field->getDeclName();
15917 Diag(Field->getLocation(), diag::note_declared_at);
15918 Invalid = true;
15919 continue;
15920 }
15921
15922 // Check for members of const-qualified, non-class type.
15923 QualType BaseType = Context.getBaseElementType(Field->getType());
15924 if (!BaseType->isRecordType() && BaseType.isConstQualified()) {
15925 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15926 << Context.getCanonicalTagType(ClassDecl) << 1
15927 << Field->getDeclName();
15928 Diag(Field->getLocation(), diag::note_declared_at);
15929 Invalid = true;
15930 continue;
15931 }
15932
15933 // Suppress assigning zero-width bitfields.
15934 if (Field->isZeroLengthBitField())
15935 continue;
15936
15937 QualType FieldType = Field->getType().getNonReferenceType();
15938 if (FieldType->isIncompleteArrayType()) {
15939 assert(ClassDecl->hasFlexibleArrayMember() &&
15940 "Incomplete array type is not valid");
15941 continue;
15942 }
15943
15944 // Build references to the field in the object we're copying from and to.
15945 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
15947 MemberLookup.addDecl(Field);
15948 MemberLookup.resolveKind();
15949 MemberBuilder From(MoveOther, OtherRefType,
15950 /*IsArrow=*/false, MemberLookup);
15951 MemberBuilder To(ObjectParameter, ObjectType, IsArrow, MemberLookup);
15952
15953 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
15954 "Member reference with rvalue base must be rvalue except for reference "
15955 "members, which aren't allowed for move assignment.");
15956
15957 // Build the move of this field.
15958 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
15959 To, From,
15960 /*CopyingBaseSubobject=*/false,
15961 /*Copying=*/false);
15962 if (Move.isInvalid()) {
15963 MoveAssignOperator->setInvalidDecl();
15964 return;
15965 }
15966
15967 // Success! Record the copy.
15968 Statements.push_back(Move.getAs<Stmt>());
15969 }
15970
15971 if (!Invalid) {
15972 // Add a "return *this;"
15973 Expr *ThisExpr =
15974 (ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15975 : LangOpts.HLSL ? static_cast<ExprBuilder &>(*This)
15976 : static_cast<ExprBuilder &>(*DerefThis))
15977 .build(*this, Loc);
15978
15979 StmtResult Return = BuildReturnStmt(Loc, ThisExpr);
15980 if (Return.isInvalid())
15981 Invalid = true;
15982 else
15983 Statements.push_back(Return.getAs<Stmt>());
15984 }
15985
15986 if (Invalid) {
15987 MoveAssignOperator->setInvalidDecl();
15988 return;
15989 }
15990
15991 StmtResult Body;
15992 {
15993 CompoundScopeRAII CompoundScope(*this);
15994 Body = ActOnCompoundStmt(Loc, Loc, Statements,
15995 /*isStmtExpr=*/false);
15996 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
15997 }
15998 MoveAssignOperator->setBody(Body.getAs<Stmt>());
15999 MoveAssignOperator->markUsed(Context);
16000
16002 L->CompletedImplicitDefinition(MoveAssignOperator);
16003 }
16004}
16005
16007 CXXRecordDecl *ClassDecl) {
16008 // C++ [class.copy]p4:
16009 // If the class definition does not explicitly declare a copy
16010 // constructor, one is declared implicitly.
16011 assert(ClassDecl->needsImplicitCopyConstructor());
16012
16013 DeclaringSpecialMember DSM(*this, ClassDecl,
16015 if (DSM.isAlreadyBeingDeclared())
16016 return nullptr;
16017
16018 QualType ClassType = Context.getTagType(ElaboratedTypeKeyword::None,
16019 /*Qualifier=*/std::nullopt, ClassDecl,
16020 /*OwnsTag=*/false);
16021 QualType ArgType = ClassType;
16022 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
16023 if (Const)
16024 ArgType = ArgType.withConst();
16025
16027 if (AS != LangAS::Default)
16028 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
16029
16030 ArgType = Context.getLValueReferenceType(ArgType);
16031
16033 *this, ClassDecl, CXXSpecialMemberKind::CopyConstructor, Const);
16034
16035 DeclarationName Name
16036 = Context.DeclarationNames.getCXXConstructorName(
16037 Context.getCanonicalType(ClassType));
16038 SourceLocation ClassLoc = ClassDecl->getLocation();
16039 DeclarationNameInfo NameInfo(Name, ClassLoc);
16040
16041 // An implicitly-declared copy constructor is an inline public
16042 // member of its class.
16044 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
16045 ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
16046 /*isInline=*/true,
16047 /*isImplicitlyDeclared=*/true,
16050 CopyConstructor->setAccess(AS_public);
16051 CopyConstructor->setDefaulted();
16052
16053 setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
16054
16055 if (getLangOpts().CUDA)
16056 CUDA().inferTargetForImplicitSpecialMember(
16058 /* ConstRHS */ Const,
16059 /* Diagnose */ false);
16060
16061 // During template instantiation of special member functions we need a
16062 // reliable TypeSourceInfo for the parameter types in order to allow functions
16063 // to be substituted.
16064 TypeSourceInfo *TSI = nullptr;
16065 if (inTemplateInstantiation() && ClassDecl->isLambda())
16066 TSI = Context.getTrivialTypeSourceInfo(ArgType);
16067
16068 // Add the parameter to the constructor.
16069 ParmVarDecl *FromParam =
16070 ParmVarDecl::Create(Context, CopyConstructor, ClassLoc, ClassLoc,
16071 /*IdentifierInfo=*/nullptr, ArgType,
16072 /*TInfo=*/TSI, SC_None, nullptr);
16073 CopyConstructor->setParams(FromParam);
16074
16075 CopyConstructor->setTrivial(
16079 : ClassDecl->hasTrivialCopyConstructor());
16080
16081 CopyConstructor->setTrivialForCall(
16082 ClassDecl->hasAttr<TrivialABIAttr>() ||
16087 : ClassDecl->hasTrivialCopyConstructorForCall()));
16088
16089 // Note that we have declared this constructor.
16090 ++getASTContext().NumImplicitCopyConstructorsDeclared;
16091
16092 Scope *S = getScopeForContext(ClassDecl);
16094
16099 }
16100
16101 if (S)
16103 ClassDecl->addDecl(CopyConstructor);
16104
16105 return CopyConstructor;
16106}
16107
16110 DefaultedFunctionFPFeaturesRAII RestoreFP(*this, CopyConstructor);
16111 assert((CopyConstructor->isDefaulted() &&
16112 CopyConstructor->isCopyConstructor() &&
16113 !CopyConstructor->doesThisDeclarationHaveABody() &&
16114 !CopyConstructor->isDeleted()) &&
16115 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
16116 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
16117 return;
16118
16119 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
16120 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
16121
16123
16124 // The exception specification is needed because we are defining the
16125 // function.
16126 ResolveExceptionSpec(CurrentLocation,
16127 CopyConstructor->getType()->castAs<FunctionProtoType>());
16128 MarkVTableUsed(CurrentLocation, ClassDecl);
16129
16130 // Add a context note for diagnostics produced after this point.
16131 Scope.addContextNote(CurrentLocation);
16132
16133 // C++11 [class.copy]p7:
16134 // The [definition of an implicitly declared copy constructor] is
16135 // deprecated if the class has a user-declared copy assignment operator
16136 // or a user-declared destructor.
16137 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
16139
16140 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
16141 CopyConstructor->setInvalidDecl();
16142 } else {
16143 SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
16144 ? CopyConstructor->getEndLoc()
16145 : CopyConstructor->getLocation();
16146 Sema::CompoundScopeRAII CompoundScope(*this);
16147 CopyConstructor->setBody(
16148 ActOnCompoundStmt(Loc, Loc, {}, /*isStmtExpr=*/false).getAs<Stmt>());
16149 CopyConstructor->markUsed(Context);
16150 }
16151
16153 L->CompletedImplicitDefinition(CopyConstructor);
16154 }
16155}
16156
16158 CXXRecordDecl *ClassDecl) {
16159 assert(ClassDecl->needsImplicitMoveConstructor());
16160
16161 DeclaringSpecialMember DSM(*this, ClassDecl,
16163 if (DSM.isAlreadyBeingDeclared())
16164 return nullptr;
16165
16166 QualType ClassType = Context.getTagType(ElaboratedTypeKeyword::None,
16167 /*Qualifier=*/std::nullopt, ClassDecl,
16168 /*OwnsTag=*/false);
16169
16170 QualType ArgType = ClassType;
16172 if (AS != LangAS::Default)
16173 ArgType = Context.getAddrSpaceQualType(ClassType, AS);
16174 ArgType = Context.getRValueReferenceType(ArgType);
16175
16177 *this, ClassDecl, CXXSpecialMemberKind::MoveConstructor, false);
16178
16179 DeclarationName Name
16180 = Context.DeclarationNames.getCXXConstructorName(
16181 Context.getCanonicalType(ClassType));
16182 SourceLocation ClassLoc = ClassDecl->getLocation();
16183 DeclarationNameInfo NameInfo(Name, ClassLoc);
16184
16185 // C++11 [class.copy]p11:
16186 // An implicitly-declared copy/move constructor is an inline public
16187 // member of its class.
16189 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
16190 ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
16191 /*isInline=*/true,
16192 /*isImplicitlyDeclared=*/true,
16195 MoveConstructor->setAccess(AS_public);
16196 MoveConstructor->setDefaulted();
16197
16198 setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
16199
16200 if (getLangOpts().CUDA)
16201 CUDA().inferTargetForImplicitSpecialMember(
16203 /* ConstRHS */ false,
16204 /* Diagnose */ false);
16205
16206 // Add the parameter to the constructor.
16208 ClassLoc, ClassLoc,
16209 /*IdentifierInfo=*/nullptr,
16210 ArgType, /*TInfo=*/nullptr,
16211 SC_None, nullptr);
16212 MoveConstructor->setParams(FromParam);
16213
16214 MoveConstructor->setTrivial(
16218 : ClassDecl->hasTrivialMoveConstructor());
16219
16220 MoveConstructor->setTrivialForCall(
16221 ClassDecl->hasAttr<TrivialABIAttr>() ||
16226 : ClassDecl->hasTrivialMoveConstructorForCall()));
16227
16228 // Note that we have declared this constructor.
16229 ++getASTContext().NumImplicitMoveConstructorsDeclared;
16230
16231 Scope *S = getScopeForContext(ClassDecl);
16233
16238 }
16239
16240 if (S)
16242 ClassDecl->addDecl(MoveConstructor);
16243
16244 return MoveConstructor;
16245}
16246
16249 DefaultedFunctionFPFeaturesRAII RestoreFP(*this, MoveConstructor);
16250 assert((MoveConstructor->isDefaulted() &&
16251 MoveConstructor->isMoveConstructor() &&
16252 !MoveConstructor->doesThisDeclarationHaveABody() &&
16253 !MoveConstructor->isDeleted()) &&
16254 "DefineImplicitMoveConstructor - call it for implicit move ctor");
16255 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
16256 return;
16257
16258 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
16259 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
16260
16262
16263 // The exception specification is needed because we are defining the
16264 // function.
16265 ResolveExceptionSpec(CurrentLocation,
16266 MoveConstructor->getType()->castAs<FunctionProtoType>());
16267 MarkVTableUsed(CurrentLocation, ClassDecl);
16268
16269 // Add a context note for diagnostics produced after this point.
16270 Scope.addContextNote(CurrentLocation);
16271
16272 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
16273 MoveConstructor->setInvalidDecl();
16274 } else {
16275 SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
16276 ? MoveConstructor->getEndLoc()
16277 : MoveConstructor->getLocation();
16278 Sema::CompoundScopeRAII CompoundScope(*this);
16279 MoveConstructor->setBody(
16280 ActOnCompoundStmt(Loc, Loc, {}, /*isStmtExpr=*/false).getAs<Stmt>());
16281 MoveConstructor->markUsed(Context);
16282 }
16283
16285 L->CompletedImplicitDefinition(MoveConstructor);
16286 }
16287}
16288
16290 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
16291}
16292
16294 SourceLocation CurrentLocation,
16295 CXXConversionDecl *Conv) {
16296 SynthesizedFunctionScope Scope(*this, Conv);
16297 assert(!Conv->getReturnType()->isUndeducedType());
16298
16299 QualType ConvRT = Conv->getType()->castAs<FunctionType>()->getReturnType();
16300 CallingConv CC =
16301 ConvRT->getPointeeType()->castAs<FunctionType>()->getCallConv();
16302
16303 CXXRecordDecl *Lambda = Conv->getParent();
16304 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
16305 FunctionDecl *Invoker =
16306 CallOp->hasCXXExplicitFunctionObjectParameter() || CallOp->isStatic()
16307 ? CallOp
16308 : Lambda->getLambdaStaticInvoker(CC);
16309
16310 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
16312 CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
16313 if (!CallOp)
16314 return;
16315
16316 if (CallOp != Invoker) {
16318 Invoker->getDescribedFunctionTemplate(), TemplateArgs,
16319 CurrentLocation);
16320 if (!Invoker)
16321 return;
16322 }
16323 }
16324
16325 if (CallOp->isInvalidDecl())
16326 return;
16327
16328 // Mark the call operator referenced (and add to pending instantiations
16329 // if necessary).
16330 // For both the conversion and static-invoker template specializations
16331 // we construct their body's in this function, so no need to add them
16332 // to the PendingInstantiations.
16333 MarkFunctionReferenced(CurrentLocation, CallOp);
16334
16335 if (Invoker != CallOp) {
16336 // Fill in the __invoke function with a dummy implementation. IR generation
16337 // will fill in the actual details. Update its type in case it contained
16338 // an 'auto'.
16339 Invoker->markUsed(Context);
16340 Invoker->setReferenced();
16341 Invoker->setType(Conv->getReturnType()->getPointeeType());
16342 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
16343 }
16344
16345 // Construct the body of the conversion function { return __invoke; }.
16346 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), VK_LValue,
16347 Conv->getLocation());
16348 assert(FunctionRef && "Can't refer to __invoke function?");
16349 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
16351 Conv->getLocation(), Conv->getLocation()));
16352 Conv->markUsed(Context);
16353 Conv->setReferenced();
16354
16356 L->CompletedImplicitDefinition(Conv);
16357 if (Invoker != CallOp)
16358 L->CompletedImplicitDefinition(Invoker);
16359 }
16360}
16361
16363 SourceLocation CurrentLocation, CXXConversionDecl *Conv) {
16364 assert(!Conv->getParent()->isGenericLambda());
16365
16366 SynthesizedFunctionScope Scope(*this, Conv);
16367
16368 // Copy-initialize the lambda object as needed to capture it.
16369 Expr *This = ActOnCXXThis(CurrentLocation).get();
16370 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
16371
16372 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
16373 Conv->getLocation(),
16374 Conv, DerefThis);
16375
16376 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
16377 // behavior. Note that only the general conversion function does this
16378 // (since it's unusable otherwise); in the case where we inline the
16379 // block literal, it has block literal lifetime semantics.
16380 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
16381 BuildBlock = ImplicitCastExpr::Create(
16382 Context, BuildBlock.get()->getType(), CK_CopyAndAutoreleaseBlockObject,
16383 BuildBlock.get(), nullptr, VK_PRValue, FPOptionsOverride());
16384
16385 if (BuildBlock.isInvalid()) {
16386 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
16387 Conv->setInvalidDecl();
16388 return;
16389 }
16390
16391 // Create the return statement that returns the block from the conversion
16392 // function.
16393 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
16394 if (Return.isInvalid()) {
16395 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
16396 Conv->setInvalidDecl();
16397 return;
16398 }
16399
16400 // Set the body of the conversion function.
16401 Stmt *ReturnS = Return.get();
16403 Conv->getLocation(), Conv->getLocation()));
16404 Conv->markUsed(Context);
16405
16406 // We're done; notify the mutation listener, if any.
16408 L->CompletedImplicitDefinition(Conv);
16409 }
16410}
16411
16412/// Determine whether the given list arguments contains exactly one
16413/// "real" (non-default) argument.
16415 switch (Args.size()) {
16416 case 0:
16417 return false;
16418
16419 default:
16420 if (!Args[1]->isDefaultArgument())
16421 return false;
16422
16423 [[fallthrough]];
16424 case 1:
16425 return !Args[0]->isDefaultArgument();
16426 }
16427
16428 return false;
16429}
16430
16432 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
16434 bool HadMultipleCandidates, bool IsListInitialization,
16435 bool IsStdInitListInitialization, bool RequiresZeroInit,
16436 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16437 bool Elidable = false;
16438
16439 // C++0x [class.copy]p34:
16440 // When certain criteria are met, an implementation is allowed to
16441 // omit the copy/move construction of a class object, even if the
16442 // copy/move constructor and/or destructor for the object have
16443 // side effects. [...]
16444 // - when a temporary class object that has not been bound to a
16445 // reference (12.2) would be copied/moved to a class object
16446 // with the same cv-unqualified type, the copy/move operation
16447 // can be omitted by constructing the temporary object
16448 // directly into the target of the omitted copy/move
16449 if (ConstructKind == CXXConstructionKind::Complete && Constructor &&
16450 // FIXME: Converting constructors should also be accepted.
16451 // But to fix this, the logic that digs down into a CXXConstructExpr
16452 // to find the source object needs to handle it.
16453 // Right now it assumes the source object is passed directly as the
16454 // first argument.
16455 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
16456 Expr *SubExpr = ExprArgs[0];
16457 // FIXME: Per above, this is also incorrect if we want to accept
16458 // converting constructors, as isTemporaryObject will
16459 // reject temporaries with different type from the
16460 // CXXRecord itself.
16461 Elidable = SubExpr->isTemporaryObject(
16463 }
16464
16465 return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
16466 FoundDecl, Constructor,
16467 Elidable, ExprArgs, HadMultipleCandidates,
16468 IsListInitialization,
16469 IsStdInitListInitialization, RequiresZeroInit,
16470 ConstructKind, ParenRange);
16471}
16472
16474 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
16475 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg ExprArgs,
16476 bool HadMultipleCandidates, bool IsListInitialization,
16477 bool IsStdInitListInitialization, bool RequiresZeroInit,
16478 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16479 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
16480 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
16481 // The only way to get here is if we did overload resolution to find the
16482 // shadow decl, so we don't need to worry about re-checking the trailing
16483 // requires clause.
16484 if (DiagnoseUseOfOverloadedDecl(Constructor, ConstructLoc))
16485 return ExprError();
16486 }
16487
16488 return BuildCXXConstructExpr(
16489 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
16490 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
16491 RequiresZeroInit, ConstructKind, ParenRange);
16492}
16493
16494/// BuildCXXConstructExpr - Creates a complete call to a constructor,
16495/// including handling of its default argument expressions.
16497 SourceLocation ConstructLoc, QualType DeclInitType,
16498 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg ExprArgs,
16499 bool HadMultipleCandidates, bool IsListInitialization,
16500 bool IsStdInitListInitialization, bool RequiresZeroInit,
16501 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16502 assert(declaresSameEntity(
16503 Constructor->getParent(),
16504 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
16505 "given constructor for wrong type");
16506 MarkFunctionReferenced(ConstructLoc, Constructor);
16507 if (getLangOpts().CUDA && !CUDA().CheckCall(ConstructLoc, Constructor))
16508 return ExprError();
16509
16512 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
16513 HadMultipleCandidates, IsListInitialization,
16514 IsStdInitListInitialization, RequiresZeroInit,
16515 static_cast<CXXConstructionKind>(ConstructKind), ParenRange),
16516 Constructor);
16517}
16518
16520 if (VD->isInvalidDecl()) return;
16521 // If initializing the variable failed, don't also diagnose problems with
16522 // the destructor, they're likely related.
16523 if (VD->getInit() && VD->getInit()->containsErrors())
16524 return;
16525
16526 ClassDecl = ClassDecl->getDefinitionOrSelf();
16527 if (ClassDecl->isInvalidDecl()) return;
16528 if (ClassDecl->hasIrrelevantDestructor()) return;
16529 if (ClassDecl->isDependentContext()) return;
16530
16531 if (VD->isNoDestroy(getASTContext()))
16532 return;
16533
16535 // The result of `LookupDestructor` might be nullptr if the destructor is
16536 // invalid, in which case it is marked as `IneligibleOrNotSelected` and
16537 // will not be selected by `CXXRecordDecl::getDestructor()`.
16538 if (!Destructor)
16539 return;
16540 // If this is an array, we'll require the destructor during initialization, so
16541 // we can skip over this. We still want to emit exit-time destructor warnings
16542 // though.
16543 if (!VD->getType()->isArrayType()) {
16546 PDiag(diag::err_access_dtor_var)
16547 << VD->getDeclName() << VD->getType());
16549 }
16550
16551 if (Destructor->isTrivial()) return;
16552
16553 // If the destructor is constexpr, check whether the variable has constant
16554 // destruction now.
16555 if (Destructor->isConstexpr()) {
16556 bool HasConstantInit = false;
16557 if (VD->getInit() && !VD->getInit()->isValueDependent())
16558 HasConstantInit = VD->evaluateValue();
16560 if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() &&
16561 HasConstantInit) {
16562 Diag(VD->getLocation(),
16563 diag::err_constexpr_var_requires_const_destruction) << VD;
16564 for (const PartialDiagnosticAt &Note : Notes)
16565 Diag(Note.first, Note.second);
16566 }
16567 }
16568
16569 if (!VD->hasGlobalStorage() || !VD->needsDestruction(Context))
16570 return;
16571
16572 // Emit warning for non-trivial dtor in global scope (a real global,
16573 // class-static, function-static).
16574 if (!VD->hasAttr<AlwaysDestroyAttr>())
16575 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
16576
16577 // TODO: this should be re-enabled for static locals by !CXAAtExit
16578 if (!VD->isStaticLocal())
16579 Diag(VD->getLocation(), diag::warn_global_destructor);
16580}
16581
16583 QualType DeclInitType, MultiExprArg ArgsPtr,
16584 SourceLocation Loc,
16585 SmallVectorImpl<Expr *> &ConvertedArgs,
16586 bool AllowExplicit,
16587 bool IsListInitialization) {
16588 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
16589 unsigned NumArgs = ArgsPtr.size();
16590 Expr **Args = ArgsPtr.data();
16591
16592 const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>();
16593 unsigned NumParams = Proto->getNumParams();
16594
16595 // If too few arguments are available, we'll fill in the rest with defaults.
16596 if (NumArgs < NumParams)
16597 ConvertedArgs.reserve(NumParams);
16598 else
16599 ConvertedArgs.reserve(NumArgs);
16600
16601 VariadicCallType CallType = Proto->isVariadic()
16604 SmallVector<Expr *, 8> AllArgs;
16606 Loc, Constructor, Proto, 0, llvm::ArrayRef(Args, NumArgs), AllArgs,
16607 CallType, AllowExplicit, IsListInitialization);
16608 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
16609
16610 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
16611
16612 CheckConstructorCall(Constructor, DeclInitType, llvm::ArrayRef(AllArgs),
16613 Proto, Loc);
16614
16615 return Invalid;
16616}
16617
16619 bool SeenTypedOperators = Context.hasSeenTypeAwareOperatorNewOrDelete();
16620 return typeAwareAllocationModeFromBool(SeenTypedOperators);
16621}
16622
16625 QualType DeallocType, SourceLocation Loc) {
16626 if (DeallocType.isNull())
16627 return nullptr;
16628
16629 FunctionDecl *FnDecl = FnTemplateDecl->getTemplatedDecl();
16630 if (!FnDecl->isTypeAwareOperatorNewOrDelete())
16631 return nullptr;
16632
16633 if (FnDecl->isVariadic())
16634 return nullptr;
16635
16636 unsigned NumParams = FnDecl->getNumParams();
16637 constexpr unsigned RequiredParameterCount =
16639 // A usual deallocation function has no placement parameters
16640 if (NumParams != RequiredParameterCount)
16641 return nullptr;
16642
16643 // A type aware allocation is only usual if the only dependent parameter is
16644 // the first parameter.
16645 if (llvm::any_of(FnDecl->parameters().drop_front(),
16646 [](const ParmVarDecl *ParamDecl) {
16647 return ParamDecl->getType()->isDependentType();
16648 }))
16649 return nullptr;
16650
16651 QualType SpecializedTypeIdentity = tryBuildStdTypeIdentity(DeallocType, Loc);
16652 if (SpecializedTypeIdentity.isNull())
16653 return nullptr;
16654
16656 ArgTypes.reserve(NumParams);
16657
16658 // The first parameter to a type aware operator delete is by definition the
16659 // type-identity argument, so we explicitly set this to the target
16660 // type-identity type, the remaining usual parameters should then simply match
16661 // the type declared in the function template.
16662 ArgTypes.push_back(SpecializedTypeIdentity);
16663 for (unsigned ParamIdx = 1; ParamIdx < RequiredParameterCount; ++ParamIdx)
16664 ArgTypes.push_back(FnDecl->getParamDecl(ParamIdx)->getType());
16665
16667 QualType ExpectedFunctionType =
16668 Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
16671 if (DeduceTemplateArguments(FnTemplateDecl, nullptr, ExpectedFunctionType,
16673 return nullptr;
16674 return Result;
16675}
16676
16677static inline bool
16679 const FunctionDecl *FnDecl) {
16680 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
16681 if (isa<NamespaceDecl>(DC)) {
16682 return SemaRef.Diag(FnDecl->getLocation(),
16683 diag::err_operator_new_delete_declared_in_namespace)
16684 << FnDecl->getDeclName();
16685 }
16686
16687 if (isa<TranslationUnitDecl>(DC) &&
16688 FnDecl->getStorageClass() == SC_Static) {
16689 return SemaRef.Diag(FnDecl->getLocation(),
16690 diag::err_operator_new_delete_declared_static)
16691 << FnDecl->getDeclName();
16692 }
16693
16694 return false;
16695}
16696
16698 const PointerType *PtrTy) {
16699 auto &Ctx = SemaRef.Context;
16700 Qualifiers PtrQuals = PtrTy->getPointeeType().getQualifiers();
16701 PtrQuals.removeAddressSpace();
16703 PtrTy->getPointeeType().getUnqualifiedType(), PtrQuals)));
16704}
16705
16707
16709 const FunctionDecl *FD,
16710 bool *WasMalformed) {
16711 const Decl *MalformedDecl = nullptr;
16712 if (FD->getNumParams() > 0 &&
16713 SemaRef.isStdTypeIdentity(FD->getParamDecl(0)->getType(),
16714 /*TypeArgument=*/nullptr, &MalformedDecl))
16715 return true;
16716
16717 if (!MalformedDecl)
16718 return false;
16719
16720 if (WasMalformed)
16721 *WasMalformed = true;
16722
16723 return true;
16724}
16725
16727 auto *RD = Type->getAsCXXRecordDecl();
16728 return RD && RD->isInStdNamespace() && RD->getIdentifier() &&
16729 RD->getIdentifier()->isStr("destroying_delete_t");
16730}
16731
16733 const FunctionDecl *FD) {
16734 // C++ P0722:
16735 // Within a class C, a single object deallocation function with signature
16736 // (T, std::destroying_delete_t, <more params>)
16737 // is a destroying operator delete.
16738 bool IsPotentiallyTypeAware = IsPotentiallyTypeAwareOperatorNewOrDelete(
16739 SemaRef, FD, /*WasMalformed=*/nullptr);
16740 unsigned DestroyingDeleteIdx = IsPotentiallyTypeAware + /* address */ 1;
16741 return isa<CXXMethodDecl>(FD) && FD->getOverloadedOperator() == OO_Delete &&
16742 FD->getNumParams() > DestroyingDeleteIdx &&
16743 isDestroyingDeleteT(FD->getParamDecl(DestroyingDeleteIdx)->getType());
16744}
16745
16747 Sema &SemaRef, FunctionDecl *FnDecl, AllocationOperatorKind OperatorKind,
16748 CanQualType ExpectedResultType, CanQualType ExpectedSizeOrAddressParamType,
16749 unsigned DependentParamTypeDiag, unsigned InvalidParamTypeDiag) {
16750 auto NormalizeType = [&SemaRef](QualType T) {
16751 if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
16752 // The operator is valid on any address space for OpenCL.
16753 // Drop address space from actual and expected result types.
16754 if (const auto PtrTy = T->template getAs<PointerType>())
16755 T = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
16756 }
16757 return SemaRef.Context.getCanonicalType(T);
16758 };
16759
16760 const unsigned NumParams = FnDecl->getNumParams();
16761 unsigned FirstNonTypeParam = 0;
16762 bool MalformedTypeIdentity = false;
16763 bool IsPotentiallyTypeAware = IsPotentiallyTypeAwareOperatorNewOrDelete(
16764 SemaRef, FnDecl, &MalformedTypeIdentity);
16765 unsigned MinimumMandatoryArgumentCount = 1;
16766 unsigned SizeParameterIndex = 0;
16767 if (IsPotentiallyTypeAware) {
16768 // We don't emit this diagnosis for template instantiations as we will
16769 // have already emitted it for the original template declaration.
16770 if (!FnDecl->isTemplateInstantiation())
16771 SemaRef.Diag(FnDecl->getLocation(), diag::warn_ext_type_aware_allocators);
16772
16773 if (OperatorKind == AllocationOperatorKind::New) {
16774 SizeParameterIndex = 1;
16775 MinimumMandatoryArgumentCount =
16777 } else {
16778 SizeParameterIndex = 2;
16779 MinimumMandatoryArgumentCount =
16781 }
16782 FirstNonTypeParam = 1;
16783 }
16784
16785 bool IsPotentiallyDestroyingDelete =
16787
16788 if (IsPotentiallyDestroyingDelete) {
16789 ++MinimumMandatoryArgumentCount;
16790 ++SizeParameterIndex;
16791 }
16792
16793 if (NumParams < MinimumMandatoryArgumentCount)
16794 return SemaRef.Diag(FnDecl->getLocation(),
16795 diag::err_operator_new_delete_too_few_parameters)
16796 << IsPotentiallyTypeAware << IsPotentiallyDestroyingDelete
16797 << FnDecl->getDeclName() << MinimumMandatoryArgumentCount;
16798
16799 for (unsigned Idx = 0; Idx < MinimumMandatoryArgumentCount; ++Idx) {
16800 const ParmVarDecl *ParamDecl = FnDecl->getParamDecl(Idx);
16801 if (ParamDecl->hasDefaultArg())
16802 return SemaRef.Diag(FnDecl->getLocation(),
16803 diag::err_operator_new_default_arg)
16804 << FnDecl->getDeclName() << Idx << ParamDecl->getDefaultArgRange();
16805 }
16806
16807 auto *FnType = FnDecl->getType()->castAs<FunctionType>();
16808 QualType CanResultType = NormalizeType(FnType->getReturnType());
16809 QualType CanExpectedResultType = NormalizeType(ExpectedResultType);
16810 QualType CanExpectedSizeOrAddressParamType =
16811 NormalizeType(ExpectedSizeOrAddressParamType);
16812
16813 // Check that the result type is what we expect.
16814 if (CanResultType != CanExpectedResultType) {
16815 // Reject even if the type is dependent; an operator delete function is
16816 // required to have a non-dependent result type.
16817 return SemaRef.Diag(
16818 FnDecl->getLocation(),
16819 CanResultType->isDependentType()
16820 ? diag::err_operator_new_delete_dependent_result_type
16821 : diag::err_operator_new_delete_invalid_result_type)
16822 << FnDecl->getDeclName() << ExpectedResultType;
16823 }
16824
16825 // A function template must have at least 2 parameters.
16826 if (FnDecl->getDescribedFunctionTemplate() && NumParams < 2)
16827 return SemaRef.Diag(FnDecl->getLocation(),
16828 diag::err_operator_new_delete_template_too_few_parameters)
16829 << FnDecl->getDeclName();
16830
16831 auto CheckType = [&](unsigned ParamIdx, QualType ExpectedType,
16832 auto FallbackType) -> bool {
16833 const ParmVarDecl *ParamDecl = FnDecl->getParamDecl(ParamIdx);
16834 if (ExpectedType.isNull()) {
16835 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
16836 << IsPotentiallyTypeAware << IsPotentiallyDestroyingDelete
16837 << FnDecl->getDeclName() << (1 + ParamIdx) << FallbackType
16838 << ParamDecl->getSourceRange();
16839 }
16840 CanQualType CanExpectedTy =
16841 NormalizeType(SemaRef.Context.getCanonicalType(ExpectedType));
16842 auto ActualParamType =
16843 NormalizeType(ParamDecl->getType().getUnqualifiedType());
16844 if (ActualParamType == CanExpectedTy)
16845 return false;
16846 unsigned Diagnostic = ActualParamType->isDependentType()
16847 ? DependentParamTypeDiag
16848 : InvalidParamTypeDiag;
16849 return SemaRef.Diag(FnDecl->getLocation(), Diagnostic)
16850 << IsPotentiallyTypeAware << IsPotentiallyDestroyingDelete
16851 << FnDecl->getDeclName() << (1 + ParamIdx) << ExpectedType
16852 << FallbackType << ParamDecl->getSourceRange();
16853 };
16854
16855 // Check that the first parameter type is what we expect.
16856 if (CheckType(FirstNonTypeParam, CanExpectedSizeOrAddressParamType, "size_t"))
16857 return true;
16858
16859 FnDecl->setIsDestroyingOperatorDelete(IsPotentiallyDestroyingDelete);
16860
16861 // If the first parameter type is not a type-identity we're done, otherwise
16862 // we need to ensure the size and alignment parameters have the correct type
16863 if (!IsPotentiallyTypeAware)
16864 return false;
16865
16866 if (CheckType(SizeParameterIndex, SemaRef.Context.getSizeType(), "size_t"))
16867 return true;
16868 TagDecl *StdAlignValTDecl = SemaRef.getStdAlignValT();
16869 CanQualType StdAlignValT =
16870 StdAlignValTDecl ? SemaRef.Context.getCanonicalTagType(StdAlignValTDecl)
16871 : CanQualType();
16872 if (CheckType(SizeParameterIndex + 1, StdAlignValT, "std::align_val_t"))
16873 return true;
16874
16876 return MalformedTypeIdentity;
16877}
16878
16879static bool CheckOperatorNewDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
16880 // C++ [basic.stc.dynamic.allocation]p1:
16881 // A program is ill-formed if an allocation function is declared in a
16882 // namespace scope other than global scope or declared static in global
16883 // scope.
16884 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
16885 return true;
16886
16887 CanQualType SizeTy =
16888 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
16889
16890 // C++ [basic.stc.dynamic.allocation]p1:
16891 // The return type shall be void*. The first parameter shall have type
16892 // std::size_t.
16894 SemaRef, FnDecl, AllocationOperatorKind::New, SemaRef.Context.VoidPtrTy,
16895 SizeTy, diag::err_operator_new_dependent_param_type,
16896 diag::err_operator_new_param_type);
16897}
16898
16899static bool
16901 // C++ [basic.stc.dynamic.deallocation]p1:
16902 // A program is ill-formed if deallocation functions are declared in a
16903 // namespace scope other than global scope or declared static in global
16904 // scope.
16905 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
16906 return true;
16907
16908 auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
16909 auto ConstructDestroyingDeleteAddressType = [&]() {
16910 assert(MD);
16911 return SemaRef.Context.getPointerType(
16912 SemaRef.Context.getCanonicalTagType(MD->getParent()));
16913 };
16914
16915 // C++ P2719: A destroying operator delete cannot be type aware
16916 // so for QoL we actually check for this explicitly by considering
16917 // an destroying-delete appropriate address type and the presence of
16918 // any parameter of type destroying_delete_t as an erroneous attempt
16919 // to declare a type aware destroying delete, rather than emitting a
16920 // pile of incorrect parameter type errors.
16922 SemaRef, MD, /*WasMalformed=*/nullptr)) {
16923 QualType AddressParamType =
16924 SemaRef.Context.getCanonicalType(MD->getParamDecl(1)->getType());
16925 if (AddressParamType != SemaRef.Context.VoidPtrTy &&
16926 AddressParamType == ConstructDestroyingDeleteAddressType()) {
16927 // The address parameter type implies an author trying to construct a
16928 // type aware destroying delete, so we'll see if we can find a parameter
16929 // of type `std::destroying_delete_t`, and if we find it we'll report
16930 // this as being an attempt at a type aware destroying delete just stop
16931 // here. If we don't do this, the resulting incorrect parameter ordering
16932 // results in a pile mismatched argument type errors that don't explain
16933 // the core problem.
16934 for (auto Param : MD->parameters()) {
16935 if (isDestroyingDeleteT(Param->getType())) {
16936 SemaRef.Diag(MD->getLocation(),
16937 diag::err_type_aware_destroying_operator_delete)
16938 << Param->getSourceRange();
16939 return true;
16940 }
16941 }
16942 }
16943 }
16944
16945 // C++ P0722:
16946 // Within a class C, the first parameter of a destroying operator delete
16947 // shall be of type C *. The first parameter of any other deallocation
16948 // function shall be of type void *.
16949 CanQualType ExpectedAddressParamType =
16950 MD && IsPotentiallyDestroyingOperatorDelete(SemaRef, MD)
16951 ? SemaRef.Context.getPointerType(
16952 SemaRef.Context.getCanonicalTagType(MD->getParent()))
16953 : SemaRef.Context.VoidPtrTy;
16954
16955 // C++ [basic.stc.dynamic.deallocation]p2:
16956 // Each deallocation function shall return void
16958 SemaRef, FnDecl, AllocationOperatorKind::Delete,
16959 SemaRef.Context.VoidTy, ExpectedAddressParamType,
16960 diag::err_operator_delete_dependent_param_type,
16961 diag::err_operator_delete_param_type))
16962 return true;
16963
16964 // C++ P0722:
16965 // A destroying operator delete shall be a usual deallocation function.
16966 if (MD && !MD->getParent()->isDependentContext() &&
16968 if (!SemaRef.isUsualDeallocationFunction(MD)) {
16969 SemaRef.Diag(MD->getLocation(),
16970 diag::err_destroying_operator_delete_not_usual);
16971 return true;
16972 }
16973 }
16974
16975 return false;
16976}
16977
16979 assert(FnDecl && FnDecl->isOverloadedOperator() &&
16980 "Expected an overloaded operator declaration");
16981
16983
16984 // C++ [over.oper]p5:
16985 // The allocation and deallocation functions, operator new,
16986 // operator new[], operator delete and operator delete[], are
16987 // described completely in 3.7.3. The attributes and restrictions
16988 // found in the rest of this subclause do not apply to them unless
16989 // explicitly stated in 3.7.3.
16990 if (Op == OO_Delete || Op == OO_Array_Delete)
16991 return CheckOperatorDeleteDeclaration(*this, FnDecl);
16992
16993 if (Op == OO_New || Op == OO_Array_New)
16994 return CheckOperatorNewDeclaration(*this, FnDecl);
16995
16996 // C++ [over.oper]p7:
16997 // An operator function shall either be a member function or
16998 // be a non-member function and have at least one parameter
16999 // whose type is a class, a reference to a class, an enumeration,
17000 // or a reference to an enumeration.
17001 // Note: Before C++23, a member function could not be static. The only member
17002 // function allowed to be static is the call operator function.
17003 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
17004 if (MethodDecl->isStatic()) {
17005 if (Op == OO_Call || Op == OO_Subscript)
17006 Diag(FnDecl->getLocation(),
17007 (LangOpts.CPlusPlus23
17008 ? diag::warn_cxx20_compat_operator_overload_static
17009 : diag::ext_operator_overload_static))
17010 << FnDecl;
17011 else
17012 return Diag(FnDecl->getLocation(), diag::err_operator_overload_static)
17013 << FnDecl;
17014 }
17015 } else {
17016 bool ClassOrEnumParam = false;
17017 for (auto *Param : FnDecl->parameters()) {
17018 QualType ParamType = Param->getType().getNonReferenceType();
17019 if (ParamType->isDependentType() || ParamType->isRecordType() ||
17020 ParamType->isEnumeralType()) {
17021 ClassOrEnumParam = true;
17022 break;
17023 }
17024 }
17025
17026 if (!ClassOrEnumParam)
17027 return Diag(FnDecl->getLocation(),
17028 diag::err_operator_overload_needs_class_or_enum)
17029 << FnDecl->getDeclName();
17030 }
17031
17032 // C++ [over.oper]p8:
17033 // An operator function cannot have default arguments (8.3.6),
17034 // except where explicitly stated below.
17035 //
17036 // Only the function-call operator (C++ [over.call]p1) and the subscript
17037 // operator (CWG2507) allow default arguments.
17038 if (Op != OO_Call) {
17039 ParmVarDecl *FirstDefaultedParam = nullptr;
17040 for (auto *Param : FnDecl->parameters()) {
17041 if (Param->hasDefaultArg()) {
17042 FirstDefaultedParam = Param;
17043 break;
17044 }
17045 }
17046 if (FirstDefaultedParam) {
17047 if (Op == OO_Subscript) {
17048 Diag(FnDecl->getLocation(), LangOpts.CPlusPlus23
17049 ? diag::ext_subscript_overload
17050 : diag::error_subscript_overload)
17051 << FnDecl->getDeclName() << 1
17052 << FirstDefaultedParam->getDefaultArgRange();
17053 } else {
17054 return Diag(FirstDefaultedParam->getLocation(),
17055 diag::err_operator_overload_default_arg)
17056 << FnDecl->getDeclName()
17057 << FirstDefaultedParam->getDefaultArgRange();
17058 }
17059 }
17060 }
17061
17062 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
17063 { false, false, false }
17064#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
17065 , { Unary, Binary, MemberOnly }
17066#include "clang/Basic/OperatorKinds.def"
17067 };
17068
17069 bool CanBeUnaryOperator = OperatorUses[Op][0];
17070 bool CanBeBinaryOperator = OperatorUses[Op][1];
17071 bool MustBeMemberOperator = OperatorUses[Op][2];
17072
17073 // C++ [over.oper]p8:
17074 // [...] Operator functions cannot have more or fewer parameters
17075 // than the number required for the corresponding operator, as
17076 // described in the rest of this subclause.
17077 unsigned NumParams = FnDecl->getNumParams() +
17078 (isa<CXXMethodDecl>(FnDecl) &&
17080 ? 1
17081 : 0);
17082 if (Op != OO_Call && Op != OO_Subscript &&
17083 ((NumParams == 1 && !CanBeUnaryOperator) ||
17084 (NumParams == 2 && !CanBeBinaryOperator) || (NumParams < 1) ||
17085 (NumParams > 2))) {
17086 // We have the wrong number of parameters.
17087 unsigned ErrorKind;
17088 if (CanBeUnaryOperator && CanBeBinaryOperator) {
17089 ErrorKind = 2; // 2 -> unary or binary.
17090 } else if (CanBeUnaryOperator) {
17091 ErrorKind = 0; // 0 -> unary
17092 } else {
17093 assert(CanBeBinaryOperator &&
17094 "All non-call overloaded operators are unary or binary!");
17095 ErrorKind = 1; // 1 -> binary
17096 }
17097 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
17098 << FnDecl->getDeclName() << NumParams << ErrorKind;
17099 }
17100
17101 if (Op == OO_Subscript && NumParams != 2) {
17102 Diag(FnDecl->getLocation(), LangOpts.CPlusPlus23
17103 ? diag::ext_subscript_overload
17104 : diag::error_subscript_overload)
17105 << FnDecl->getDeclName() << (NumParams == 1 ? 0 : 2);
17106 }
17107
17108 // Overloaded operators other than operator() and operator[] cannot be
17109 // variadic.
17110 if (Op != OO_Call &&
17111 FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) {
17112 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
17113 << FnDecl->getDeclName();
17114 }
17115
17116 // Some operators must be member functions.
17117 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
17118 return Diag(FnDecl->getLocation(),
17119 diag::err_operator_overload_must_be_member)
17120 << FnDecl->getDeclName();
17121 }
17122
17123 // C++ [over.inc]p1:
17124 // The user-defined function called operator++ implements the
17125 // prefix and postfix ++ operator. If this function is a member
17126 // function with no parameters, or a non-member function with one
17127 // parameter of class or enumeration type, it defines the prefix
17128 // increment operator ++ for objects of that type. If the function
17129 // is a member function with one parameter (which shall be of type
17130 // int) or a non-member function with two parameters (the second
17131 // of which shall be of type int), it defines the postfix
17132 // increment operator ++ for objects of that type.
17133 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
17134 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
17135 QualType ParamType = LastParam->getType();
17136
17137 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
17138 !ParamType->isDependentType())
17139 return Diag(LastParam->getLocation(),
17140 diag::err_operator_overload_post_incdec_must_be_int)
17141 << LastParam->getType() << (Op == OO_MinusMinus);
17142 }
17143
17144 return false;
17145}
17146
17147static bool
17149 FunctionTemplateDecl *TpDecl) {
17150 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
17151
17152 // Must have one or two template parameters.
17153 if (TemplateParams->size() == 1) {
17154 NonTypeTemplateParmDecl *PmDecl =
17155 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
17156
17157 // The template parameter must be a char parameter pack.
17158 if (PmDecl && PmDecl->isTemplateParameterPack() &&
17159 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
17160 return false;
17161
17162 // C++20 [over.literal]p5:
17163 // A string literal operator template is a literal operator template
17164 // whose template-parameter-list comprises a single non-type
17165 // template-parameter of class type.
17166 //
17167 // As a DR resolution, we also allow placeholders for deduced class
17168 // template specializations.
17169 if (SemaRef.getLangOpts().CPlusPlus20 && PmDecl &&
17170 !PmDecl->isTemplateParameterPack() &&
17171 (PmDecl->getType()->isRecordType() ||
17172 PmDecl->getType()->getAs<DeducedTemplateSpecializationType>()))
17173 return false;
17174 } else if (TemplateParams->size() == 2) {
17175 TemplateTypeParmDecl *PmType =
17176 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
17177 NonTypeTemplateParmDecl *PmArgs =
17178 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
17179
17180 // The second template parameter must be a parameter pack with the
17181 // first template parameter as its type.
17182 if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
17183 PmArgs->isTemplateParameterPack()) {
17184 if (const auto *TArgs =
17185 PmArgs->getType()->getAsCanonical<TemplateTypeParmType>();
17186 TArgs && TArgs->getDepth() == PmType->getDepth() &&
17187 TArgs->getIndex() == PmType->getIndex()) {
17188 if (!SemaRef.inTemplateInstantiation())
17189 SemaRef.Diag(TpDecl->getLocation(),
17190 diag::ext_string_literal_operator_template);
17191 return false;
17192 }
17193 }
17194 }
17195
17196 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
17197 diag::err_literal_operator_template)
17198 << TpDecl->getTemplateParameters()->getSourceRange();
17199 return true;
17200}
17201
17203 if (isa<CXXMethodDecl>(FnDecl)) {
17204 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
17205 << FnDecl->getDeclName();
17206 return true;
17207 }
17208
17209 if (FnDecl->isExternC()) {
17210 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
17211 if (const LinkageSpecDecl *LSD =
17212 FnDecl->getDeclContext()->getExternCContext())
17213 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
17214 return true;
17215 }
17216
17217 // This might be the definition of a literal operator template.
17219
17220 // This might be a specialization of a literal operator template.
17221 if (!TpDecl)
17222 TpDecl = FnDecl->getPrimaryTemplate();
17223
17224 // template <char...> type operator "" name() and
17225 // template <class T, T...> type operator "" name() are the only valid
17226 // template signatures, and the only valid signatures with no parameters.
17227 //
17228 // C++20 also allows template <SomeClass T> type operator "" name().
17229 if (TpDecl) {
17230 if (FnDecl->param_size() != 0) {
17231 Diag(FnDecl->getLocation(),
17232 diag::err_literal_operator_template_with_params);
17233 return true;
17234 }
17235
17237 return true;
17238
17239 } else if (FnDecl->param_size() == 1) {
17240 const ParmVarDecl *Param = FnDecl->getParamDecl(0);
17241
17242 QualType ParamType = Param->getType().getUnqualifiedType();
17243
17244 // Only unsigned long long int, long double, any character type, and const
17245 // char * are allowed as the only parameters.
17246 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
17247 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
17248 Context.hasSameType(ParamType, Context.CharTy) ||
17249 Context.hasSameType(ParamType, Context.WideCharTy) ||
17250 Context.hasSameType(ParamType, Context.Char8Ty) ||
17251 Context.hasSameType(ParamType, Context.Char16Ty) ||
17252 Context.hasSameType(ParamType, Context.Char32Ty)) {
17253 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
17254 QualType InnerType = Ptr->getPointeeType();
17255
17256 // Pointer parameter must be a const char *.
17257 if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
17258 Context.CharTy) &&
17259 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
17260 Diag(Param->getSourceRange().getBegin(),
17261 diag::err_literal_operator_param)
17262 << ParamType << "'const char *'" << Param->getSourceRange();
17263 return true;
17264 }
17265
17266 } else if (ParamType->isRealFloatingType()) {
17267 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
17268 << ParamType << Context.LongDoubleTy << Param->getSourceRange();
17269 return true;
17270
17271 } else if (ParamType->isIntegerType()) {
17272 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
17273 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
17274 return true;
17275
17276 } else {
17277 Diag(Param->getSourceRange().getBegin(),
17278 diag::err_literal_operator_invalid_param)
17279 << ParamType << Param->getSourceRange();
17280 return true;
17281 }
17282
17283 } else if (FnDecl->param_size() == 2) {
17284 FunctionDecl::param_iterator Param = FnDecl->param_begin();
17285
17286 // First, verify that the first parameter is correct.
17287
17288 QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
17289
17290 // Two parameter function must have a pointer to const as a
17291 // first parameter; let's strip those qualifiers.
17292 const PointerType *PT = FirstParamType->getAs<PointerType>();
17293
17294 if (!PT) {
17295 Diag((*Param)->getSourceRange().getBegin(),
17296 diag::err_literal_operator_param)
17297 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
17298 return true;
17299 }
17300
17301 QualType PointeeType = PT->getPointeeType();
17302 // First parameter must be const
17303 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
17304 Diag((*Param)->getSourceRange().getBegin(),
17305 diag::err_literal_operator_param)
17306 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
17307 return true;
17308 }
17309
17310 QualType InnerType = PointeeType.getUnqualifiedType();
17311 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
17312 // const char32_t* are allowed as the first parameter to a two-parameter
17313 // function
17314 if (!(Context.hasSameType(InnerType, Context.CharTy) ||
17315 Context.hasSameType(InnerType, Context.WideCharTy) ||
17316 Context.hasSameType(InnerType, Context.Char8Ty) ||
17317 Context.hasSameType(InnerType, Context.Char16Ty) ||
17318 Context.hasSameType(InnerType, Context.Char32Ty))) {
17319 Diag((*Param)->getSourceRange().getBegin(),
17320 diag::err_literal_operator_param)
17321 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
17322 return true;
17323 }
17324
17325 // Move on to the second and final parameter.
17326 ++Param;
17327
17328 // The second parameter must be a std::size_t.
17329 QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
17330 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
17331 Diag((*Param)->getSourceRange().getBegin(),
17332 diag::err_literal_operator_param)
17333 << SecondParamType << Context.getSizeType()
17334 << (*Param)->getSourceRange();
17335 return true;
17336 }
17337 } else {
17338 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
17339 return true;
17340 }
17341
17342 // Parameters are good.
17343
17344 // A parameter-declaration-clause containing a default argument is not
17345 // equivalent to any of the permitted forms.
17346 for (auto *Param : FnDecl->parameters()) {
17347 if (Param->hasDefaultArg()) {
17348 Diag(Param->getDefaultArgRange().getBegin(),
17349 diag::err_literal_operator_default_argument)
17350 << Param->getDefaultArgRange();
17351 break;
17352 }
17353 }
17354
17355 const IdentifierInfo *II = FnDecl->getDeclName().getCXXLiteralIdentifier();
17358 !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
17359 // C++23 [usrlit.suffix]p1:
17360 // Literal suffix identifiers that do not start with an underscore are
17361 // reserved for future standardization. Literal suffix identifiers that
17362 // contain a double underscore __ are reserved for use by C++
17363 // implementations.
17364 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
17365 << static_cast<int>(Status)
17367 }
17368
17369 return false;
17370}
17371
17373 Expr *LangStr,
17374 SourceLocation LBraceLoc) {
17375 StringLiteral *Lit = cast<StringLiteral>(LangStr);
17376 assert(Lit->isUnevaluated() && "Unexpected string literal kind");
17377
17378 StringRef Lang = Lit->getString();
17380 if (Lang == "C")
17382 else if (Lang == "C++")
17384 else {
17385 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
17386 << LangStr->getSourceRange();
17387 return nullptr;
17388 }
17389
17390 // FIXME: Add all the various semantics of linkage specifications
17391
17393 LangStr->getExprLoc(), Language,
17394 LBraceLoc.isValid());
17395
17396 /// C++ [module.unit]p7.2.3
17397 /// - Otherwise, if the declaration
17398 /// - ...
17399 /// - ...
17400 /// - appears within a linkage-specification,
17401 /// it is attached to the global module.
17402 ///
17403 /// If the declaration is already in global module fragment, we don't
17404 /// need to attach it again.
17405 if (getLangOpts().CPlusPlusModules && isCurrentModulePurview()) {
17406 Module *GlobalModule = PushImplicitGlobalModuleFragment(ExternLoc);
17407 D->setLocalOwningModule(GlobalModule);
17408 }
17409
17410 CurContext->addDecl(D);
17411 PushDeclContext(S, D);
17412 return D;
17413}
17414
17416 Decl *LinkageSpec,
17417 SourceLocation RBraceLoc) {
17418 if (RBraceLoc.isValid()) {
17419 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
17420 LSDecl->setRBraceLoc(RBraceLoc);
17421 }
17422
17423 // If the current module doesn't has Parent, it implies that the
17424 // LinkageSpec isn't in the module created by itself. So we don't
17425 // need to pop it.
17426 if (getLangOpts().CPlusPlusModules && getCurrentModule() &&
17427 getCurrentModule()->isImplicitGlobalModule() &&
17428 getCurrentModule()->Parent)
17429 PopImplicitGlobalModuleFragment();
17430
17432 return LinkageSpec;
17433}
17434
17436 const ParsedAttributesView &AttrList,
17437 SourceLocation SemiLoc) {
17438 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
17439 // Attribute declarations appertain to empty declaration so we handle
17440 // them here.
17441 ProcessDeclAttributeList(S, ED, AttrList);
17442
17443 CurContext->addDecl(ED);
17444 return ED;
17445}
17446
17448 SourceLocation StartLoc,
17449 SourceLocation Loc,
17450 const IdentifierInfo *Name) {
17451 bool Invalid = false;
17452 QualType ExDeclType = TInfo->getType();
17453
17454 // Arrays and functions decay.
17455 if (ExDeclType->isArrayType())
17456 ExDeclType = Context.getArrayDecayedType(ExDeclType);
17457 else if (ExDeclType->isFunctionType())
17458 ExDeclType = Context.getPointerType(ExDeclType);
17459
17460 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
17461 // The exception-declaration shall not denote a pointer or reference to an
17462 // incomplete type, other than [cv] void*.
17463 // N2844 forbids rvalue references.
17464 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
17465 Diag(Loc, diag::err_catch_rvalue_ref);
17466 Invalid = true;
17467 }
17468
17469 if (ExDeclType->isVariablyModifiedType()) {
17470 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
17471 Invalid = true;
17472 }
17473
17474 QualType BaseType = ExDeclType;
17475 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
17476 unsigned DK = diag::err_catch_incomplete;
17477 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
17478 BaseType = Ptr->getPointeeType();
17479 Mode = 1;
17480 DK = diag::err_catch_incomplete_ptr;
17481 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
17482 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
17483 BaseType = Ref->getPointeeType();
17484 Mode = 2;
17485 DK = diag::err_catch_incomplete_ref;
17486 }
17487 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
17488 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
17489 Invalid = true;
17490
17491 if (!Invalid && BaseType.isWebAssemblyReferenceType()) {
17492 Diag(Loc, diag::err_wasm_reftype_tc) << 1;
17493 Invalid = true;
17494 }
17495
17496 if (!Invalid && Mode != 1 && BaseType->isSizelessType()) {
17497 Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType;
17498 Invalid = true;
17499 }
17500
17501 if (!Invalid && !ExDeclType->isDependentType() &&
17502 RequireNonAbstractType(Loc, ExDeclType,
17503 diag::err_abstract_type_in_decl,
17505 Invalid = true;
17506
17507 // Only the non-fragile NeXT runtime currently supports C++ catches
17508 // of ObjC types, and no runtime supports catching ObjC types by value.
17509 if (!Invalid && getLangOpts().ObjC) {
17510 QualType T = ExDeclType;
17511 if (const ReferenceType *RT = T->getAs<ReferenceType>())
17512 T = RT->getPointeeType();
17513
17514 if (T->isObjCObjectType()) {
17515 Diag(Loc, diag::err_objc_object_catch);
17516 Invalid = true;
17517 } else if (T->isObjCObjectPointerType()) {
17518 // FIXME: should this be a test for macosx-fragile specifically?
17520 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
17521 }
17522 }
17523
17524 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
17525 ExDeclType, TInfo, SC_None);
17526 ExDecl->setExceptionVariable(true);
17527
17528 // In ARC, infer 'retaining' for variables of retainable type.
17529 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(ExDecl))
17530 Invalid = true;
17531
17532 if (!Invalid && !ExDeclType->isDependentType()) {
17533 if (auto *ClassDecl = ExDeclType->getAsCXXRecordDecl()) {
17534 // Insulate this from anything else we might currently be parsing.
17537
17538 // C++ [except.handle]p16:
17539 // The object declared in an exception-declaration or, if the
17540 // exception-declaration does not specify a name, a temporary (12.2) is
17541 // copy-initialized (8.5) from the exception object. [...]
17542 // The object is destroyed when the handler exits, after the destruction
17543 // of any automatic objects initialized within the handler.
17544 //
17545 // We just pretend to initialize the object with itself, then make sure
17546 // it can be destroyed later.
17547 QualType initType = Context.getExceptionObjectType(ExDeclType);
17548
17549 InitializedEntity entity =
17551 InitializationKind initKind =
17553
17554 Expr *opaqueValue =
17555 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
17556 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
17557 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
17558 if (result.isInvalid())
17559 Invalid = true;
17560 else {
17561 // If the constructor used was non-trivial, set this as the
17562 // "initializer".
17563 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
17564 if (!construct->getConstructor()->isTrivial()) {
17565 Expr *init = MaybeCreateExprWithCleanups(construct);
17566 ExDecl->setInit(init);
17567 }
17568
17569 // And make sure it's destructable.
17570 FinalizeVarWithDestructor(ExDecl, ClassDecl);
17571 }
17572 }
17573 }
17574
17575 if (Invalid)
17576 ExDecl->setInvalidDecl();
17577
17578 return ExDecl;
17579}
17580
17583 bool Invalid = D.isInvalidType();
17584
17585 // Check for unexpanded parameter packs.
17588 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
17589 D.getIdentifierLoc());
17590 Invalid = true;
17591 }
17592
17593 const IdentifierInfo *II = D.getIdentifier();
17594 if (NamedDecl *PrevDecl =
17597 // The scope should be freshly made just for us. There is just no way
17598 // it contains any previous declaration, except for function parameters in
17599 // a function-try-block's catch statement.
17600 assert(!S->isDeclScope(PrevDecl));
17601 if (isDeclInScope(PrevDecl, CurContext, S)) {
17602 Diag(D.getIdentifierLoc(), diag::err_redefinition)
17603 << D.getIdentifier();
17604 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
17605 Invalid = true;
17606 } else if (PrevDecl->isTemplateParameter())
17607 // Maybe we will complain about the shadowed template parameter.
17609 }
17610
17611 if (D.getCXXScopeSpec().isSet() && !Invalid) {
17612 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
17613 << D.getCXXScopeSpec().getRange();
17614 Invalid = true;
17615 }
17616
17618 S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
17619 if (Invalid)
17620 ExDecl->setInvalidDecl();
17621
17622 // Add the exception declaration into this scope.
17623 if (II)
17624 PushOnScopeChains(ExDecl, S);
17625 else
17626 CurContext->addDecl(ExDecl);
17627
17628 ProcessDeclAttributes(S, ExDecl, D);
17629 return ExDecl;
17630}
17631
17633 Expr *AssertExpr,
17634 Expr *AssertMessageExpr,
17635 SourceLocation RParenLoc) {
17637 return nullptr;
17638
17639 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
17640 AssertMessageExpr, RParenLoc, false);
17641}
17642
17643static void WriteCharTypePrefix(BuiltinType::Kind BTK, llvm::raw_ostream &OS) {
17644 switch (BTK) {
17645 case BuiltinType::Char_S:
17646 case BuiltinType::Char_U:
17647 break;
17648 case BuiltinType::Char8:
17649 OS << "u8";
17650 break;
17651 case BuiltinType::Char16:
17652 OS << 'u';
17653 break;
17654 case BuiltinType::Char32:
17655 OS << 'U';
17656 break;
17657 case BuiltinType::WChar_S:
17658 case BuiltinType::WChar_U:
17659 OS << 'L';
17660 break;
17661 default:
17662 llvm_unreachable("Non-character type");
17663 }
17664}
17665
17666/// Convert character's value, interpreted as a code unit, to a string.
17667/// The value needs to be zero-extended to 32-bits.
17668/// FIXME: This assumes Unicode literal encodings
17670 unsigned TyWidth,
17671 SmallVectorImpl<char> &Str) {
17672 char Arr[UNI_MAX_UTF8_BYTES_PER_CODE_POINT];
17673 char *Ptr = Arr;
17674 BuiltinType::Kind K = BTy->getKind();
17675 llvm::raw_svector_ostream OS(Str);
17676
17677 // This should catch Char_S, Char_U, Char8, and use of escaped characters in
17678 // other types.
17679 if (K == BuiltinType::Char_S || K == BuiltinType::Char_U ||
17680 K == BuiltinType::Char8 || Value <= 0x7F) {
17681 StringRef Escaped = escapeCStyle<EscapeChar::Single>(Value);
17682 if (!Escaped.empty())
17683 EscapeStringForDiagnostic(Escaped, Str);
17684 else
17685 OS << static_cast<char>(Value);
17686 return;
17687 }
17688
17689 switch (K) {
17690 case BuiltinType::Char16:
17691 case BuiltinType::Char32:
17692 case BuiltinType::WChar_S:
17693 case BuiltinType::WChar_U: {
17694 if (llvm::ConvertCodePointToUTF8(Value, Ptr))
17695 EscapeStringForDiagnostic(StringRef(Arr, Ptr - Arr), Str);
17696 else
17697 OS << "\\x"
17698 << llvm::format_hex_no_prefix(Value, TyWidth / 4, /*Upper=*/true);
17699 break;
17700 }
17701 default:
17702 llvm_unreachable("Non-character type is passed");
17703 }
17704}
17705
17706/// Convert \V to a string we can present to the user in a diagnostic
17707/// \T is the type of the expression that has been evaluated into \V
17710 ASTContext &Context) {
17711 if (!V.hasValue())
17712 return false;
17713
17714 switch (V.getKind()) {
17716 if (T->isBooleanType()) {
17717 // Bools are reduced to ints during evaluation, but for
17718 // diagnostic purposes we want to print them as
17719 // true or false.
17720 int64_t BoolValue = V.getInt().getExtValue();
17721 assert((BoolValue == 0 || BoolValue == 1) &&
17722 "Bool type, but value is not 0 or 1");
17723 llvm::raw_svector_ostream OS(Str);
17724 OS << (BoolValue ? "true" : "false");
17725 } else {
17726 llvm::raw_svector_ostream OS(Str);
17727 // Same is true for chars.
17728 // We want to print the character representation for textual types
17729 const auto *BTy = T->getAs<BuiltinType>();
17730 if (BTy) {
17731 switch (BTy->getKind()) {
17732 case BuiltinType::Char_S:
17733 case BuiltinType::Char_U:
17734 case BuiltinType::Char8:
17735 case BuiltinType::Char16:
17736 case BuiltinType::Char32:
17737 case BuiltinType::WChar_S:
17738 case BuiltinType::WChar_U: {
17739 unsigned TyWidth = Context.getIntWidth(T);
17740 assert(8 <= TyWidth && TyWidth <= 32 && "Unexpected integer width");
17741 uint32_t CodeUnit = static_cast<uint32_t>(V.getInt().getZExtValue());
17742 WriteCharTypePrefix(BTy->getKind(), OS);
17743 OS << '\'';
17744 WriteCharValueForDiagnostic(CodeUnit, BTy, TyWidth, Str);
17745 OS << "' (0x"
17746 << llvm::format_hex_no_prefix(CodeUnit, /*Width=*/2,
17747 /*Upper=*/true)
17748 << ", " << V.getInt() << ')';
17749 return true;
17750 }
17751 default:
17752 break;
17753 }
17754 }
17755 V.getInt().toString(Str);
17756 }
17757
17758 break;
17759
17761 V.getFloat().toString(Str);
17762 break;
17763
17765 if (V.isNullPointer()) {
17766 llvm::raw_svector_ostream OS(Str);
17767 OS << "nullptr";
17768 } else
17769 return false;
17770 break;
17771
17773 llvm::raw_svector_ostream OS(Str);
17774 OS << '(';
17775 V.getComplexFloatReal().toString(Str);
17776 OS << " + ";
17777 V.getComplexFloatImag().toString(Str);
17778 OS << "i)";
17779 } break;
17780
17782 llvm::raw_svector_ostream OS(Str);
17783 OS << '(';
17784 V.getComplexIntReal().toString(Str);
17785 OS << " + ";
17786 V.getComplexIntImag().toString(Str);
17787 OS << "i)";
17788 } break;
17789
17790 default:
17791 return false;
17792 }
17793
17794 return true;
17795}
17796
17797/// Some Expression types are not useful to print notes about,
17798/// e.g. literals and values that have already been expanded
17799/// before such as int-valued template parameters.
17800static bool UsefulToPrintExpr(const Expr *E) {
17801 E = E->IgnoreParenImpCasts();
17802 // Literals are pretty easy for humans to understand.
17805 return false;
17806
17807 // These have been substituted from template parameters
17808 // and appear as literals in the static assert error.
17810 return false;
17811
17812 // -5 is also simple to understand.
17813 if (const auto *UnaryOp = dyn_cast<UnaryOperator>(E))
17814 return UsefulToPrintExpr(UnaryOp->getSubExpr());
17815
17816 // Only print nested arithmetic operators.
17817 if (const auto *BO = dyn_cast<BinaryOperator>(E))
17818 return (BO->isShiftOp() || BO->isAdditiveOp() || BO->isMultiplicativeOp() ||
17819 BO->isBitwiseOp());
17820
17821 return true;
17822}
17823
17825 if (const auto *Op = dyn_cast<BinaryOperator>(E);
17826 Op && Op->getOpcode() != BO_LOr) {
17827 const Expr *LHS = Op->getLHS()->IgnoreParenImpCasts();
17828 const Expr *RHS = Op->getRHS()->IgnoreParenImpCasts();
17829
17830 // Ignore comparisons of boolean expressions with a boolean literal.
17831 if ((isa<CXXBoolLiteralExpr>(LHS) && RHS->getType()->isBooleanType()) ||
17832 (isa<CXXBoolLiteralExpr>(RHS) && LHS->getType()->isBooleanType()))
17833 return;
17834
17835 // Don't print obvious expressions.
17836 if (!UsefulToPrintExpr(LHS) && !UsefulToPrintExpr(RHS))
17837 return;
17838
17839 struct {
17840 const clang::Expr *Cond;
17842 SmallString<12> ValueString;
17843 bool Print;
17844 } DiagSides[2] = {{LHS, Expr::EvalResult(), {}, false},
17845 {RHS, Expr::EvalResult(), {}, false}};
17846 for (auto &DiagSide : DiagSides) {
17847 const Expr *Side = DiagSide.Cond;
17848
17849 Side->EvaluateAsRValue(DiagSide.Result, Context, true);
17850
17851 DiagSide.Print = ConvertAPValueToString(
17852 DiagSide.Result.Val, Side->getType(), DiagSide.ValueString, Context);
17853 }
17854 if (DiagSides[0].Print && DiagSides[1].Print) {
17855 Diag(Op->getExprLoc(), diag::note_expr_evaluates_to)
17856 << DiagSides[0].ValueString << Op->getOpcodeStr()
17857 << DiagSides[1].ValueString << Op->getSourceRange();
17858 }
17859 } else {
17861 }
17862}
17863
17864template <typename ResultType>
17865static bool EvaluateAsStringImpl(Sema &SemaRef, Expr *Message,
17866 ResultType &Result, ASTContext &Ctx,
17868 bool ErrorOnInvalidMessage) {
17869
17870 assert(Message);
17871 assert(!Message->isTypeDependent() && !Message->isValueDependent() &&
17872 "can't evaluate a dependant static assert message");
17873
17874 if (const auto *SL = dyn_cast<StringLiteral>(Message)) {
17875 assert(SL->isUnevaluated() && "expected an unevaluated string");
17876 if constexpr (std::is_same_v<APValue, ResultType>) {
17877 Result =
17878 APValue(APValue::UninitArray{}, SL->getLength(), SL->getLength());
17879 const ConstantArrayType *CAT =
17880 SemaRef.getASTContext().getAsConstantArrayType(SL->getType());
17881 assert(CAT && "string literal isn't an array");
17882 QualType CharType = CAT->getElementType();
17883 llvm::APSInt Value(SemaRef.getASTContext().getTypeSize(CharType),
17884 CharType->isUnsignedIntegerType());
17885 for (unsigned I = 0; I < SL->getLength(); I++) {
17886 Value = SL->getCodeUnit(I);
17887 Result.getArrayInitializedElt(I) = APValue(Value);
17888 }
17889 } else {
17890 Result.assign(SL->getString().begin(), SL->getString().end());
17891 }
17892 return true;
17893 }
17894
17895 SourceLocation Loc = Message->getBeginLoc();
17896 QualType T = Message->getType().getNonReferenceType();
17897 auto *RD = T->getAsCXXRecordDecl();
17898 if (!RD) {
17899 SemaRef.Diag(Loc, diag::err_user_defined_msg_invalid) << EvalContext;
17900 return false;
17901 }
17902
17903 auto FindMember = [&](StringRef Member) -> std::optional<LookupResult> {
17905 LookupResult MemberLookup(SemaRef, DN, Loc, Sema::LookupMemberName);
17906 SemaRef.LookupQualifiedName(MemberLookup, RD);
17907 OverloadCandidateSet Candidates(MemberLookup.getNameLoc(),
17909 if (MemberLookup.empty())
17910 return std::nullopt;
17911 return std::move(MemberLookup);
17912 };
17913
17914 std::optional<LookupResult> SizeMember = FindMember("size");
17915 std::optional<LookupResult> DataMember = FindMember("data");
17916 if (!SizeMember || !DataMember) {
17917 SemaRef.Diag(Loc, diag::err_user_defined_msg_missing_member_function)
17918 << EvalContext
17919 << ((!SizeMember && !DataMember) ? 2
17920 : !SizeMember ? 0
17921 : 1);
17922 return false;
17923 }
17924
17925 auto BuildExpr = [&](LookupResult &LR) {
17927 Message, Message->getType(), Message->getBeginLoc(), false,
17928 CXXScopeSpec(), SourceLocation(), nullptr, LR, nullptr, nullptr);
17929 if (Res.isInvalid())
17930 return ExprError();
17931 Res = SemaRef.BuildCallExpr(nullptr, Res.get(), Loc, {}, Loc, nullptr,
17932 false, true);
17933 if (Res.isInvalid())
17934 return ExprError();
17935 if (Res.get()->isTypeDependent() || Res.get()->isValueDependent())
17936 return ExprError();
17937 return SemaRef.TemporaryMaterializationConversion(Res.get());
17938 };
17939
17940 ExprResult SizeE = BuildExpr(*SizeMember);
17941 ExprResult DataE = BuildExpr(*DataMember);
17942
17943 QualType SizeT = SemaRef.Context.getSizeType();
17944 QualType ConstCharPtr = SemaRef.Context.getPointerType(
17945 SemaRef.Context.getConstType(SemaRef.Context.CharTy));
17946
17947 ExprResult EvaluatedSize =
17948 SizeE.isInvalid()
17949 ? ExprError()
17952 if (EvaluatedSize.isInvalid()) {
17953 SemaRef.Diag(Loc, diag::err_user_defined_msg_invalid_mem_fn_ret_ty)
17954 << EvalContext << /*size*/ 0;
17955 return false;
17956 }
17957
17958 ExprResult EvaluatedData =
17959 DataE.isInvalid()
17960 ? ExprError()
17962 DataE.get(), ConstCharPtr, CCEKind::StaticAssertMessageData);
17963 if (EvaluatedData.isInvalid()) {
17964 SemaRef.Diag(Loc, diag::err_user_defined_msg_invalid_mem_fn_ret_ty)
17965 << EvalContext << /*data*/ 1;
17966 return false;
17967 }
17968
17969 if (!ErrorOnInvalidMessage &&
17970 SemaRef.Diags.isIgnored(diag::warn_user_defined_msg_constexpr, Loc))
17971 return true;
17972
17973 Expr::EvalResult Status;
17975 Status.Diag = &Notes;
17976 if (!Message->EvaluateCharRangeAsString(Result, EvaluatedSize.get(),
17977 EvaluatedData.get(), Ctx, Status) ||
17978 !Notes.empty()) {
17979 SemaRef.Diag(Message->getBeginLoc(),
17980 ErrorOnInvalidMessage ? diag::err_user_defined_msg_constexpr
17981 : diag::warn_user_defined_msg_constexpr)
17982 << EvalContext;
17983 for (const auto &Note : Notes)
17984 SemaRef.Diag(Note.first, Note.second);
17985 return !ErrorOnInvalidMessage;
17986 }
17987 return true;
17988}
17989
17991 StringEvaluationContext EvalContext,
17992 bool ErrorOnInvalidMessage) {
17993 return EvaluateAsStringImpl(*this, Message, Result, Ctx, EvalContext,
17994 ErrorOnInvalidMessage);
17995}
17996
17997bool Sema::EvaluateAsString(Expr *Message, std::string &Result, ASTContext &Ctx,
17998 StringEvaluationContext EvalContext,
17999 bool ErrorOnInvalidMessage) {
18000 return EvaluateAsStringImpl(*this, Message, Result, Ctx, EvalContext,
18001 ErrorOnInvalidMessage);
18002}
18003
18005 Expr *AssertExpr, Expr *AssertMessage,
18006 SourceLocation RParenLoc,
18007 bool Failed) {
18008 assert(AssertExpr != nullptr && "Expected non-null condition");
18009 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
18010 (!AssertMessage || (!AssertMessage->isTypeDependent() &&
18011 !AssertMessage->isValueDependent())) &&
18012 !Failed) {
18013 // In a static_assert-declaration, the constant-expression shall be a
18014 // constant expression that can be contextually converted to bool.
18015 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
18016 if (Converted.isInvalid())
18017 Failed = true;
18018
18019 ExprResult FullAssertExpr =
18020 ActOnFinishFullExpr(Converted.get(), StaticAssertLoc,
18021 /*DiscardedValue*/ false,
18022 /*IsConstexpr*/ true);
18023 if (FullAssertExpr.isInvalid())
18024 Failed = true;
18025 else
18026 AssertExpr = FullAssertExpr.get();
18027
18028 llvm::APSInt Cond;
18029 Expr *BaseExpr = AssertExpr;
18031
18032 if (!getLangOpts().CPlusPlus) {
18033 // In C mode, allow folding as an extension for better compatibility with
18034 // C++ in terms of expressions like static_assert("test") or
18035 // static_assert(nullptr).
18036 FoldKind = AllowFoldKind::Allow;
18037 }
18038
18039 if (!Failed && VerifyIntegerConstantExpression(
18040 BaseExpr, &Cond,
18041 diag::err_static_assert_expression_is_not_constant,
18042 FoldKind).isInvalid())
18043 Failed = true;
18044
18045 // If the static_assert passes, only verify that
18046 // the message is grammatically valid without evaluating it.
18047 if (!Failed && AssertMessage && Cond.getBoolValue()) {
18048 std::string Str;
18049 EvaluateAsString(AssertMessage, Str, Context,
18051 /*ErrorOnInvalidMessage=*/false);
18052 }
18053
18054 // CWG2518
18055 // [dcl.pre]/p10 If [...] the expression is evaluated in the context of a
18056 // template definition, the declaration has no effect.
18057 bool InTemplateDefinition =
18058 getLangOpts().CPlusPlus && CurContext->isDependentContext();
18059
18060 if (!Failed && !Cond && !InTemplateDefinition) {
18061 SmallString<256> MsgBuffer;
18062 llvm::raw_svector_ostream Msg(MsgBuffer);
18063 bool HasMessage = AssertMessage;
18064 if (AssertMessage) {
18065 std::string Str;
18066 HasMessage = EvaluateAsString(AssertMessage, Str, Context,
18068 /*ErrorOnInvalidMessage=*/true) ||
18069 !Str.empty();
18070 Msg << Str;
18071 }
18072 Expr *InnerCond = nullptr;
18073 std::string InnerCondDescription;
18074 std::tie(InnerCond, InnerCondDescription) =
18075 findFailedBooleanCondition(Converted.get());
18076 if (const auto *ConceptIDExpr =
18077 dyn_cast_or_null<ConceptSpecializationExpr>(InnerCond)) {
18078 const ASTConstraintSatisfaction &Satisfaction =
18079 ConceptIDExpr->getSatisfaction();
18080 if (!Satisfaction.ContainsErrors || Satisfaction.NumRecords) {
18081 Diag(AssertExpr->getBeginLoc(), diag::err_static_assert_failed)
18082 << !HasMessage << Msg.str() << AssertExpr->getSourceRange();
18083 // Drill down into concept specialization expressions to see why they
18084 // weren't satisfied.
18085 DiagnoseUnsatisfiedConstraint(ConceptIDExpr);
18086 }
18087 } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond) &&
18088 !isa<IntegerLiteral>(InnerCond)) {
18089 Diag(InnerCond->getBeginLoc(),
18090 diag::err_static_assert_requirement_failed)
18091 << InnerCondDescription << !HasMessage << Msg.str()
18092 << InnerCond->getSourceRange();
18093 DiagnoseStaticAssertDetails(InnerCond);
18094 } else {
18095 Diag(AssertExpr->getBeginLoc(), diag::err_static_assert_failed)
18096 << !HasMessage << Msg.str() << AssertExpr->getSourceRange();
18098 }
18099 Failed = true;
18100 }
18101 } else {
18102 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
18103 /*DiscardedValue*/false,
18104 /*IsConstexpr*/true);
18105 if (FullAssertExpr.isInvalid())
18106 Failed = true;
18107 else
18108 AssertExpr = FullAssertExpr.get();
18109 }
18110
18112 AssertExpr, AssertMessage, RParenLoc,
18113 Failed);
18114
18115 CurContext->addDecl(Decl);
18116 return Decl;
18117}
18118
18120 Scope *S, SourceLocation FriendLoc, unsigned TagSpec, SourceLocation TagLoc,
18121 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
18122 SourceLocation EllipsisLoc, const ParsedAttributesView &Attr,
18123 MultiTemplateParamsArg TempParamLists) {
18125
18126 bool IsMemberSpecialization = false;
18127 bool Invalid = false;
18128
18129 if (TemplateParameterList *TemplateParams =
18131 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
18132 IsMemberSpecialization, Invalid)) {
18133 if (TemplateParams->size() > 0) {
18134 // This is a declaration of a class template.
18135 if (Invalid)
18136 return true;
18137
18138 return CheckClassTemplate(S, TagSpec, TagUseKind::Friend, TagLoc, SS,
18139 Name, NameLoc, Attr, TemplateParams, AS_public,
18140 /*ModulePrivateLoc=*/SourceLocation(),
18141 FriendLoc, TempParamLists.size() - 1,
18142 TempParamLists.data(), IsMemberSpecialization)
18143 .get();
18144 } else {
18145 // The "template<>" header is extraneous.
18146 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
18147 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
18148 }
18149 }
18150
18151 if (Invalid) return true;
18152
18153 bool isAllExplicitSpecializations =
18154 llvm::all_of(TempParamLists, [](const TemplateParameterList *List) {
18155 return List->size() == 0;
18156 });
18157
18158 // FIXME: don't ignore attributes.
18159
18160 // If it's explicit specializations all the way down, just forget
18161 // about the template header and build an appropriate non-templated
18162 // friend. TODO: for source fidelity, remember the headers.
18164 if (isAllExplicitSpecializations) {
18165 if (SS.isEmpty()) {
18166 bool Owned = false;
18167 bool IsDependent = false;
18168 return ActOnTag(S, TagSpec, TagUseKind::Friend, TagLoc, SS, Name, NameLoc,
18169 Attr, AS_public,
18170 /*ModulePrivateLoc=*/SourceLocation(),
18171 MultiTemplateParamsArg(), Owned, IsDependent,
18172 /*ScopedEnumKWLoc=*/SourceLocation(),
18173 /*ScopedEnumUsesClassTag=*/false,
18174 /*UnderlyingType=*/TypeResult(),
18175 /*IsTypeSpecifier=*/false,
18176 /*IsTemplateParamOrArg=*/false,
18177 /*OOK=*/OffsetOfKind::Outside);
18178 }
18179
18180 TypeSourceInfo *TSI = nullptr;
18183 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, *Name,
18184 NameLoc, &TSI, /*DeducedTSTContext=*/true);
18185 if (T.isNull())
18186 return true;
18187
18189 FriendDecl::Create(Context, CurContext, NameLoc, TSI, FriendLoc,
18190 EllipsisLoc, TempParamLists);
18191 Friend->setAccess(AS_public);
18192 CurContext->addDecl(Friend);
18193 return Friend;
18194 }
18195
18196 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
18197
18198 // CWG 2917: if it (= the friend-type-specifier) is a pack expansion
18199 // (13.7.4 [temp.variadic]), any packs expanded by that pack expansion
18200 // shall not have been introduced by the template-declaration.
18202 collectUnexpandedParameterPacks(QualifierLoc, Unexpanded);
18203 unsigned FriendDeclDepth = TempParamLists.front()->getDepth();
18204 for (UnexpandedParameterPack &U : Unexpanded) {
18205 if (std::optional<std::pair<unsigned, unsigned>> DI = getDepthAndIndex(U);
18206 DI && DI->first >= FriendDeclDepth) {
18207 auto *ND = dyn_cast<NamedDecl *>(U.first);
18208 if (!ND)
18209 ND = cast<const TemplateTypeParmType *>(U.first)->getDecl();
18210 Diag(U.second, diag::friend_template_decl_malformed_pack_expansion)
18211 << ND->getDeclName() << SourceRange(SS.getBeginLoc(), EllipsisLoc);
18212 return true;
18213 }
18214 }
18215
18216 // Handle the case of a templated-scope friend class. e.g.
18217 // template <class T> class A<T>::B;
18218 // FIXME: we don't support these right now.
18219 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
18222 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
18223 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
18225 TL.setElaboratedKeywordLoc(TagLoc);
18227 TL.setNameLoc(NameLoc);
18228
18230 FriendDecl::Create(Context, CurContext, NameLoc, TSI, FriendLoc,
18231 EllipsisLoc, TempParamLists);
18232 Friend->setAccess(AS_public);
18233 Friend->setUnsupportedFriend(true);
18234 CurContext->addDecl(Friend);
18235 return Friend;
18236}
18237
18239 MultiTemplateParamsArg TempParams,
18240 SourceLocation EllipsisLoc) {
18241 SourceLocation Loc = DS.getBeginLoc();
18242 SourceLocation FriendLoc = DS.getFriendSpecLoc();
18243
18244 assert(DS.isFriendSpecified());
18246
18247 // C++ [class.friend]p3:
18248 // A friend declaration that does not declare a function shall have one of
18249 // the following forms:
18250 // friend elaborated-type-specifier ;
18251 // friend simple-type-specifier ;
18252 // friend typename-specifier ;
18253 //
18254 // If the friend keyword isn't first, or if the declarations has any type
18255 // qualifiers, then the declaration doesn't have that form.
18257 Diag(FriendLoc, diag::err_friend_not_first_in_declaration);
18258 if (DS.getTypeQualifiers()) {
18260 Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
18262 Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
18264 Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
18266 Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
18268 Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
18269 }
18270
18271 // Try to convert the decl specifier to a type. This works for
18272 // friend templates because ActOnTag never produces a ClassTemplateDecl
18273 // for a TagUseKind::Friend.
18274 Declarator TheDeclarator(DS, ParsedAttributesView::none(),
18276 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator);
18277 QualType T = TSI->getType();
18278 if (TheDeclarator.isInvalidType())
18279 return nullptr;
18280
18281 // If '...' is present, the type must contain an unexpanded parameter
18282 // pack, and vice versa.
18283 bool Invalid = false;
18284 if (EllipsisLoc.isInvalid() &&
18286 return nullptr;
18287 if (EllipsisLoc.isValid() &&
18289 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
18290 << TSI->getTypeLoc().getSourceRange();
18291 Invalid = true;
18292 }
18293
18294 if (!T->isElaboratedTypeSpecifier()) {
18295 if (TempParams.size()) {
18296 // C++23 [dcl.pre]p5:
18297 // In a simple-declaration, the optional init-declarator-list can be
18298 // omitted only when declaring a class or enumeration, that is, when
18299 // the decl-specifier-seq contains either a class-specifier, an
18300 // elaborated-type-specifier with a class-key, or an enum-specifier.
18301 //
18302 // The declaration of a template-declaration or explicit-specialization
18303 // is never a member-declaration, so this must be a simple-declaration
18304 // with no init-declarator-list. Therefore, this is ill-formed.
18305 Diag(Loc, diag::err_tagless_friend_type_template) << DS.getSourceRange();
18306 return nullptr;
18307 } else if (const RecordDecl *RD = T->getAsRecordDecl()) {
18308 SmallString<16> InsertionText(" ");
18309 InsertionText += RD->getKindName();
18310
18312 ? diag::warn_cxx98_compat_unelaborated_friend_type
18313 : diag::ext_unelaborated_friend_type)
18314 << (unsigned)RD->getTagKind() << T
18316 InsertionText);
18317 } else {
18318 DiagCompat(FriendLoc, diag_compat::nonclass_type_friend)
18319 << T << DS.getSourceRange();
18320 }
18321 }
18322
18323 // C++98 [class.friend]p1: A friend of a class is a function
18324 // or class that is not a member of the class . . .
18325 // This is fixed in DR77, which just barely didn't make the C++03
18326 // deadline. It's also a very silly restriction that seriously
18327 // affects inner classes and which nobody else seems to implement;
18328 // thus we never diagnose it, not even in -pedantic.
18329 //
18330 // But note that we could warn about it: it's always useless to
18331 // friend one of your own members (it's not, however, worthless to
18332 // friend a member of an arbitrary specialization of your template).
18333
18334 Decl *D;
18335 if (!TempParams.empty())
18336 // TODO: Support variadic friend template decls?
18337 D = FriendTemplateDecl::Create(Context, CurContext, Loc, TempParams, TSI,
18338 FriendLoc);
18339 else
18341 TSI, FriendLoc, EllipsisLoc);
18342
18343 if (!D)
18344 return nullptr;
18345
18346 D->setAccess(AS_public);
18347 CurContext->addDecl(D);
18348
18349 if (Invalid)
18350 D->setInvalidDecl();
18351
18352 return D;
18353}
18354
18356 MultiTemplateParamsArg TemplateParams) {
18357 const DeclSpec &DS = D.getDeclSpec();
18358
18359 assert(DS.isFriendSpecified());
18361
18364
18365 // C++ [class.friend]p1
18366 // A friend of a class is a function or class....
18367 // Note that this sees through typedefs, which is intended.
18368 // It *doesn't* see through dependent types, which is correct
18369 // according to [temp.arg.type]p3:
18370 // If a declaration acquires a function type through a
18371 // type dependent on a template-parameter and this causes
18372 // a declaration that does not use the syntactic form of a
18373 // function declarator to have a function type, the program
18374 // is ill-formed.
18375 if (!TInfo->getType()->isFunctionType()) {
18376 Diag(Loc, diag::err_unexpected_friend);
18377
18378 // It might be worthwhile to try to recover by creating an
18379 // appropriate declaration.
18380 return nullptr;
18381 }
18382
18383 // C++ [namespace.memdef]p3
18384 // - If a friend declaration in a non-local class first declares a
18385 // class or function, the friend class or function is a member
18386 // of the innermost enclosing namespace.
18387 // - The name of the friend is not found by simple name lookup
18388 // until a matching declaration is provided in that namespace
18389 // scope (either before or after the class declaration granting
18390 // friendship).
18391 // - If a friend function is called, its name may be found by the
18392 // name lookup that considers functions from namespaces and
18393 // classes associated with the types of the function arguments.
18394 // - When looking for a prior declaration of a class or a function
18395 // declared as a friend, scopes outside the innermost enclosing
18396 // namespace scope are not considered.
18397
18398 CXXScopeSpec &SS = D.getCXXScopeSpec();
18400 assert(NameInfo.getName());
18401
18402 // Check for unexpanded parameter packs.
18406 return nullptr;
18407
18408 bool isTemplateId = D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
18409
18410 if (D.isFunctionDefinition() && SS.isNotEmpty() && !isTemplateId) {
18411 auto Kind = SS.getScopeRep().getKind();
18412 bool IsNamespaceOrGlobal = Kind == NestedNameSpecifier::Kind::Global ||
18414 if (IsNamespaceOrGlobal) {
18415 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
18417 SS.clear();
18418 }
18419 }
18420
18421 // The context we found the declaration in, or in which we should
18422 // create the declaration.
18423 DeclContext *DC;
18424 Scope *DCScope = S;
18425 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
18427
18428 // There are five cases here.
18429 // - There's no scope specifier and we're in a local class. Only look
18430 // for functions declared in the immediately-enclosing block scope.
18431 // We recover from invalid scope qualifiers as if they just weren't there.
18432 FunctionDecl *FunctionContainingLocalClass = nullptr;
18433 if ((SS.isInvalid() || !SS.isSet()) &&
18434 (FunctionContainingLocalClass =
18435 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
18436 // C++11 [class.friend]p11:
18437 // If a friend declaration appears in a local class and the name
18438 // specified is an unqualified name, a prior declaration is
18439 // looked up without considering scopes that are outside the
18440 // innermost enclosing non-class scope. For a friend function
18441 // declaration, if there is no prior declaration, the program is
18442 // ill-formed.
18443
18444 // Find the innermost enclosing non-class scope. This is the block
18445 // scope containing the local class definition (or for a nested class,
18446 // the outer local class).
18447 DCScope = S->getFnParent();
18448
18449 // Look up the function name in the scope.
18451 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
18452
18453 if (!Previous.empty()) {
18454 // All possible previous declarations must have the same context:
18455 // either they were declared at block scope or they are members of
18456 // one of the enclosing local classes.
18457 DC = Previous.getRepresentativeDecl()->getDeclContext();
18458 } else {
18459 // This is ill-formed, but provide the context that we would have
18460 // declared the function in, if we were permitted to, for error recovery.
18461 DC = FunctionContainingLocalClass;
18462 }
18464
18465 // - There's no scope specifier, in which case we just go to the
18466 // appropriate scope and look for a function or function template
18467 // there as appropriate.
18468 } else if (SS.isInvalid() || !SS.isSet()) {
18469 // C++11 [namespace.memdef]p3:
18470 // If the name in a friend declaration is neither qualified nor
18471 // a template-id and the declaration is a function or an
18472 // elaborated-type-specifier, the lookup to determine whether
18473 // the entity has been previously declared shall not consider
18474 // any scopes outside the innermost enclosing namespace.
18475
18476 // Find the appropriate context according to the above.
18477 DC = CurContext;
18478
18479 // Skip class contexts. If someone can cite chapter and verse
18480 // for this behavior, that would be nice --- it's what GCC and
18481 // EDG do, and it seems like a reasonable intent, but the spec
18482 // really only says that checks for unqualified existing
18483 // declarations should stop at the nearest enclosing namespace,
18484 // not that they should only consider the nearest enclosing
18485 // namespace.
18486 while (DC->isRecord())
18487 DC = DC->getParent();
18488
18489 DeclContext *LookupDC = DC->getNonTransparentContext();
18490 while (true) {
18491 LookupQualifiedName(Previous, LookupDC);
18492
18493 if (!Previous.empty()) {
18494 DC = LookupDC;
18495 break;
18496 }
18497
18498 if (isTemplateId) {
18499 if (isa<TranslationUnitDecl>(LookupDC)) break;
18500 } else {
18501 if (LookupDC->isFileContext()) break;
18502 }
18503 LookupDC = LookupDC->getParent();
18504 }
18505
18506 DCScope = getScopeForDeclContext(S, DC);
18507
18508 // - There's a non-dependent scope specifier, in which case we
18509 // compute it and do a previous lookup there for a function
18510 // or function template.
18511 } else if (!SS.getScopeRep().isDependent()) {
18512 DC = computeDeclContext(SS);
18513 if (!DC) return nullptr;
18514
18515 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
18516
18518
18519 // C++ [class.friend]p1: A friend of a class is a function or
18520 // class that is not a member of the class . . .
18521 if (DC->Equals(CurContext))
18524 diag::warn_cxx98_compat_friend_is_member :
18525 diag::err_friend_is_member);
18526
18527 // - There's a scope specifier that does not match any template
18528 // parameter lists, in which case we use some arbitrary context,
18529 // create a method or method template, and wait for instantiation.
18530 // - There's a scope specifier that does match some template
18531 // parameter lists, which we don't handle right now.
18532 } else {
18533 DC = CurContext;
18534 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
18535 }
18536
18537 if (!DC->isRecord()) {
18538 int DiagArg = -1;
18539 switch (D.getName().getKind()) {
18542 DiagArg = 0;
18543 break;
18545 DiagArg = 1;
18546 break;
18548 DiagArg = 2;
18549 break;
18551 DiagArg = 3;
18552 break;
18558 break;
18559 }
18560 // This implies that it has to be an operator or function.
18561 if (DiagArg >= 0) {
18562 Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
18563 return nullptr;
18564 }
18565 } else {
18566 CXXRecordDecl *RC = dyn_cast<CXXRecordDecl>(DC);
18567 if (RC->isLambda()) {
18568 Diag(NameInfo.getBeginLoc(), diag::err_friend_lambda_decl);
18569 }
18570 }
18571
18572 // FIXME: This is an egregious hack to cope with cases where the scope stack
18573 // does not contain the declaration context, i.e., in an out-of-line
18574 // definition of a class.
18575 Scope FakeDCScope(S, Scope::DeclScope, Diags);
18576 if (!DCScope) {
18577 FakeDCScope.setEntity(DC);
18578 DCScope = &FakeDCScope;
18579 }
18580
18581 bool AddToScope = true;
18582 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
18583 TemplateParams, AddToScope);
18584 if (!ND) return nullptr;
18585
18586 assert(ND->getLexicalDeclContext() == CurContext);
18587
18588 // If we performed typo correction, we might have added a scope specifier
18589 // and changed the decl context.
18590 DC = ND->getDeclContext();
18591
18592 // Add the function declaration to the appropriate lookup tables,
18593 // adjusting the redeclarations list as necessary. We don't
18594 // want to do this yet if the friending class is dependent.
18595 //
18596 // Also update the scope-based lookup if the target context's
18597 // lookup context is in lexical scope.
18598 if (!CurContext->isDependentContext()) {
18599 DC = DC->getRedeclContext();
18601 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
18602 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
18603 }
18604
18606 D.getIdentifierLoc(), ND,
18607 DS.getFriendSpecLoc());
18608 FrD->setAccess(AS_public);
18609 CurContext->addDecl(FrD);
18610
18611 if (ND->isInvalidDecl()) {
18612 FrD->setInvalidDecl();
18613 } else {
18614 if (DC->isRecord()) CheckFriendAccess(ND);
18615
18616 FunctionDecl *FD;
18617 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
18618 FD = FTD->getTemplatedDecl();
18619 else
18620 FD = cast<FunctionDecl>(ND);
18621
18622 // C++ [class.friend]p6:
18623 // A function may be defined in a friend declaration of a class if and
18624 // only if the class is a non-local class, and the function name is
18625 // unqualified.
18626 if (D.isFunctionDefinition()) {
18627 // Qualified friend function definition.
18628 if (SS.isNotEmpty()) {
18629 // FIXME: We should only do this if the scope specifier names the
18630 // innermost enclosing namespace; otherwise the fixit changes the
18631 // meaning of the code.
18633 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
18634
18635 DB << SS.getScopeRep();
18636 if (DC->isFileContext())
18638
18639 // Friend function defined in a local class.
18640 } else if (FunctionContainingLocalClass) {
18641 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
18642
18643 // Per [basic.pre]p4, a template-id is not a name. Therefore, if we have
18644 // a template-id, the function name is not unqualified because these is
18645 // no name. While the wording requires some reading in-between the
18646 // lines, GCC, MSVC, and EDG all consider a friend function
18647 // specialization definitions to be de facto explicit specialization
18648 // and diagnose them as such.
18649 } else if (isTemplateId) {
18650 Diag(NameInfo.getBeginLoc(), diag::err_friend_specialization_def);
18651 }
18652 }
18653
18654 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
18655 // default argument expression, that declaration shall be a definition
18656 // and shall be the only declaration of the function or function
18657 // template in the translation unit.
18659 // We can't look at FD->getPreviousDecl() because it may not have been set
18660 // if we're in a dependent context. If the function is known to be a
18661 // redeclaration, we will have narrowed Previous down to the right decl.
18662 if (D.isRedeclaration()) {
18663 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
18664 Diag(Previous.getRepresentativeDecl()->getLocation(),
18665 diag::note_previous_declaration);
18666 } else if (!D.isFunctionDefinition())
18667 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
18668 }
18669
18670 // Mark templated-scope function declarations as unsupported.
18671 if (!FD->getTemplateParameterLists().empty() && SS.isValid()) {
18672 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
18673 << SS.getScopeRep() << SS.getRange()
18675 FrD->setUnsupportedFriend(true);
18676 }
18677 }
18678
18680
18681 return ND;
18682}
18683
18685 StringLiteral *Message) {
18687
18688 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
18689 if (!Fn) {
18690 Diag(DelLoc, diag::err_deleted_non_function);
18691 return;
18692 }
18693
18694 // Deleted function does not have a body.
18695 Fn->setWillHaveBody(false);
18696
18697 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
18698 // Don't consider the implicit declaration we generate for explicit
18699 // specializations. FIXME: Do not generate these implicit declarations.
18700 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
18701 Prev->getPreviousDecl()) &&
18702 !Prev->isDefined()) {
18703 Diag(DelLoc, diag::err_deleted_decl_not_first);
18704 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
18705 Prev->isImplicit() ? diag::note_previous_implicit_declaration
18706 : diag::note_previous_declaration);
18707 // We can't recover from this; the declaration might have already
18708 // been used.
18709 Fn->setInvalidDecl();
18710 return;
18711 }
18712
18713 // To maintain the invariant that functions are only deleted on their first
18714 // declaration, mark the implicitly-instantiated declaration of the
18715 // explicitly-specialized function as deleted instead of marking the
18716 // instantiated redeclaration.
18717 Fn = Fn->getCanonicalDecl();
18718 }
18719
18720 // dllimport/dllexport cannot be deleted.
18721 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
18722 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
18723 Fn->setInvalidDecl();
18724 }
18725
18726 // C++11 [basic.start.main]p3:
18727 // A program that defines main as deleted [...] is ill-formed.
18728 if (Fn->isMain())
18729 Diag(DelLoc, diag::err_deleted_main);
18730
18731 // C++11 [dcl.fct.def.delete]p4:
18732 // A deleted function is implicitly inline.
18733 Fn->setImplicitlyInline();
18734 Fn->setDeletedAsWritten(true, Message);
18735}
18736
18738 if (!Dcl || Dcl->isInvalidDecl())
18739 return;
18740
18741 auto *FD = dyn_cast<FunctionDecl>(Dcl);
18742 if (!FD) {
18743 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) {
18744 if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) {
18745 Diag(DefaultLoc, diag::err_defaulted_comparison_template);
18746 return;
18747 }
18748 }
18749
18750 Diag(DefaultLoc, diag::err_default_special_members)
18751 << getLangOpts().CPlusPlus20;
18752 return;
18753 }
18754
18755 // Reject if this can't possibly be a defaultable function.
18757 if (!DefKind &&
18758 // A dependent function that doesn't locally look defaultable can
18759 // still instantiate to a defaultable function if it's a constructor
18760 // or assignment operator.
18761 (!FD->isDependentContext() ||
18763 FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) {
18764 Diag(DefaultLoc, diag::err_default_special_members)
18765 << getLangOpts().CPlusPlus20;
18766 return;
18767 }
18768
18769 // Issue compatibility warning. We already warned if the operator is
18770 // 'operator<=>' when parsing the '<=>' token.
18771 if (DefKind.isComparison() &&
18773 Diag(DefaultLoc, getLangOpts().CPlusPlus20
18774 ? diag::warn_cxx17_compat_defaulted_comparison
18775 : diag::ext_defaulted_comparison);
18776 }
18777
18778 FD->setDefaulted();
18779 FD->setExplicitlyDefaulted();
18780 FD->setDefaultLoc(DefaultLoc);
18781
18782 // Defer checking functions that are defaulted in a dependent context.
18783 if (FD->isDependentContext())
18784 return;
18785
18786 // Unset that we will have a body for this function. We might not,
18787 // if it turns out to be trivial, and we don't need this marking now
18788 // that we've marked it as defaulted.
18789 FD->setWillHaveBody(false);
18790
18791 if (DefKind.isComparison()) {
18792 // If this comparison's defaulting occurs within the definition of its
18793 // lexical class context, we have to do the checking when complete.
18794 if (auto const *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext()))
18795 if (!RD->isCompleteDefinition())
18796 return;
18797 }
18798
18799 // If this member fn was defaulted on its first declaration, we will have
18800 // already performed the checking in CheckCompletedCXXClass. Such a
18801 // declaration doesn't trigger an implicit definition.
18802 if (isa<CXXMethodDecl>(FD)) {
18803 const FunctionDecl *Primary = FD;
18804 if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
18805 // Ask the template instantiation pattern that actually had the
18806 // '= default' on it.
18807 Primary = Pattern;
18808 if (Primary->getCanonicalDecl()->isDefaulted())
18809 return;
18810 }
18811
18812 // Only allocate DefaultedOrDeletedFunctionInfo if we actually have
18813 // non-default FP features to stash. This avoids memory overhead for
18814 // the vast majority of defaulted functions.
18815 if (!FD->getDefaultedOrDeletedInfo() &&
18816 CurFPFeatureOverrides().requiresTrailingStorage()) {
18817 FD->setDefaultedOrDeletedInfo(
18819 Context, /*Lookups=*/{}, CurFPFeatureOverrides()));
18820 }
18821
18822 if (DefKind.isComparison()) {
18823 if (CheckExplicitlyDefaultedComparison(nullptr, FD, DefKind.asComparison()))
18824 FD->setInvalidDecl();
18825 else
18826 DefineDefaultedComparison(DefaultLoc, FD, DefKind.asComparison());
18827 } else {
18828 auto *MD = cast<CXXMethodDecl>(FD);
18829
18831 DefaultLoc))
18832 MD->setInvalidDecl();
18833 else
18834 DefineDefaultedFunction(*this, MD, DefaultLoc);
18835 }
18836}
18837
18839 for (Stmt *SubStmt : S->children()) {
18840 if (!SubStmt)
18841 continue;
18842 if (isa<ReturnStmt>(SubStmt))
18843 Self.Diag(SubStmt->getBeginLoc(),
18844 diag::err_return_in_constructor_handler);
18845 if (!isa<Expr>(SubStmt))
18846 SearchForReturnInStmt(Self, SubStmt);
18847 }
18848}
18849
18851 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
18852 CXXCatchStmt *Handler = TryBlock->getHandler(I);
18853 SearchForReturnInStmt(*this, Handler);
18854 }
18855}
18856
18858 StringLiteral *DeletedMessage) {
18859 switch (BodyKind) {
18860 case FnBodyKind::Delete:
18861 SetDeclDeleted(D, Loc, DeletedMessage);
18862 break;
18864 SetDeclDefaulted(D, Loc);
18865 break;
18866 case FnBodyKind::Other:
18867 llvm_unreachable(
18868 "Parsed function body should be '= delete;' or '= default;'");
18869 }
18870}
18871
18873 const CXXMethodDecl *Old) {
18874 const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
18875 const auto *OldFT = Old->getType()->castAs<FunctionProtoType>();
18876
18877 if (OldFT->hasExtParameterInfos()) {
18878 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
18879 // A parameter of the overriding method should be annotated with noescape
18880 // if the corresponding parameter of the overridden method is annotated.
18881 if (OldFT->getExtParameterInfo(I).isNoEscape() &&
18882 !NewFT->getExtParameterInfo(I).isNoEscape()) {
18883 Diag(New->getParamDecl(I)->getLocation(),
18884 diag::warn_overriding_method_missing_noescape);
18885 Diag(Old->getParamDecl(I)->getLocation(),
18886 diag::note_overridden_marked_noescape);
18887 }
18888 }
18889
18890 // SME attributes must match when overriding a function declaration.
18891 if (IsInvalidSMECallConversion(Old->getType(), New->getType())) {
18892 Diag(New->getLocation(), diag::err_conflicting_overriding_attributes)
18893 << New << New->getType() << Old->getType();
18894 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
18895 return true;
18896 }
18897
18898 // Virtual overrides must have the same code_seg.
18899 const auto *OldCSA = Old->getAttr<CodeSegAttr>();
18900 const auto *NewCSA = New->getAttr<CodeSegAttr>();
18901 if ((NewCSA || OldCSA) &&
18902 (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
18903 Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
18904 Diag(Old->getLocation(), diag::note_previous_declaration);
18905 return true;
18906 }
18907
18908 // Virtual overrides: check for matching effects.
18909 if (Context.hasAnyFunctionEffects()) {
18910 const auto OldFX = Old->getFunctionEffects();
18911 const auto NewFXOrig = New->getFunctionEffects();
18912
18913 if (OldFX != NewFXOrig) {
18914 FunctionEffectSet NewFX(NewFXOrig);
18915 const auto Diffs = FunctionEffectDiffVector(OldFX, NewFX);
18917 for (const auto &Diff : Diffs) {
18918 switch (Diff.shouldDiagnoseMethodOverride(*Old, OldFX, *New, NewFX)) {
18920 break;
18922 Diag(New->getLocation(), diag::warn_conflicting_func_effect_override)
18923 << Diff.effectName();
18924 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18925 << Old->getReturnTypeSourceRange();
18926 break;
18928 NewFX.insert(Diff.Old.value(), Errs);
18929 const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
18930 FunctionProtoType::ExtProtoInfo EPI = NewFT->getExtProtoInfo();
18932 QualType ModQT = Context.getFunctionType(NewFT->getReturnType(),
18933 NewFT->getParamTypes(), EPI);
18934 New->setType(ModQT);
18935 if (Errs.empty()) {
18936 // A warning here is somewhat pedantic. Skip this if there was
18937 // already a merge conflict, which is more serious.
18938 Diag(New->getLocation(), diag::warn_mismatched_func_effect_override)
18939 << Diff.effectName();
18940 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18941 << Old->getReturnTypeSourceRange();
18942 }
18943 break;
18944 }
18945 }
18946 }
18947 if (!Errs.empty())
18948 diagnoseFunctionEffectMergeConflicts(Errs, New->getLocation(),
18949 Old->getLocation());
18950 }
18951 }
18952
18953 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
18954
18955 // If the calling conventions match, everything is fine
18956 if (NewCC == OldCC)
18957 return false;
18958
18959 // If the calling conventions mismatch because the new function is static,
18960 // suppress the calling convention mismatch error; the error about static
18961 // function override (err_static_overrides_virtual from
18962 // Sema::CheckFunctionDeclaration) is more clear.
18963 if (New->getStorageClass() == SC_Static)
18964 return false;
18965
18966 Diag(New->getLocation(),
18967 diag::err_conflicting_overriding_cc_attributes)
18968 << New->getDeclName() << New->getType() << Old->getType();
18969 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
18970 return true;
18971}
18972
18974 const CXXMethodDecl *Old) {
18975 // CWG2553
18976 // A virtual function shall not be an explicit object member function.
18977 if (!New->isExplicitObjectMemberFunction())
18978 return true;
18979 Diag(New->getParamDecl(0)->getBeginLoc(),
18980 diag::err_explicit_object_parameter_nonmember)
18981 << New->getSourceRange() << /*virtual*/ 1 << /*IsLambda*/ false;
18982 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
18983 New->setInvalidDecl();
18984 return false;
18985}
18986
18988 const CXXMethodDecl *Old) {
18989 QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType();
18990 QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType();
18991
18992 if (Context.hasSameType(NewTy, OldTy) ||
18993 NewTy->isDependentType() || OldTy->isDependentType())
18994 return false;
18995
18996 // Check if the return types are covariant
18997 QualType NewClassTy, OldClassTy;
18998
18999 /// Both types must be pointers or references to classes.
19000 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
19001 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
19002 NewClassTy = NewPT->getPointeeType();
19003 OldClassTy = OldPT->getPointeeType();
19004 }
19005 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
19006 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
19007 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
19008 NewClassTy = NewRT->getPointeeType();
19009 OldClassTy = OldRT->getPointeeType();
19010 }
19011 }
19012 }
19013
19014 // The return types aren't either both pointers or references to a class type.
19015 if (NewClassTy.isNull() || !NewClassTy->isStructureOrClassType()) {
19016 Diag(New->getLocation(),
19017 diag::err_different_return_type_for_overriding_virtual_function)
19018 << New->getDeclName() << NewTy << OldTy
19019 << New->getReturnTypeSourceRange();
19020 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
19021 << Old->getReturnTypeSourceRange();
19022
19023 return true;
19024 }
19025
19026 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
19027 // C++14 [class.virtual]p8:
19028 // If the class type in the covariant return type of D::f differs from
19029 // that of B::f, the class type in the return type of D::f shall be
19030 // complete at the point of declaration of D::f or shall be the class
19031 // type D.
19032 if (const auto *RD = NewClassTy->getAsCXXRecordDecl()) {
19033 if (!RD->isBeingDefined() &&
19034 RequireCompleteType(New->getLocation(), NewClassTy,
19035 diag::err_covariant_return_incomplete,
19036 New->getDeclName()))
19037 return true;
19038 }
19039
19040 // Check if the new class derives from the old class.
19041 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
19042 Diag(New->getLocation(), diag::err_covariant_return_not_derived)
19043 << New->getDeclName() << NewTy << OldTy
19044 << New->getReturnTypeSourceRange();
19045 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
19046 << Old->getReturnTypeSourceRange();
19047 return true;
19048 }
19049
19050 // Check if we the conversion from derived to base is valid.
19052 NewClassTy, OldClassTy,
19053 diag::err_covariant_return_inaccessible_base,
19054 diag::err_covariant_return_ambiguous_derived_to_base_conv,
19055 New->getLocation(), New->getReturnTypeSourceRange(),
19056 New->getDeclName(), nullptr)) {
19057 // FIXME: this note won't trigger for delayed access control
19058 // diagnostics, and it's impossible to get an undelayed error
19059 // here from access control during the original parse because
19060 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
19061 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
19062 << Old->getReturnTypeSourceRange();
19063 return true;
19064 }
19065 }
19066
19067 // The qualifiers of the return types must be the same.
19068 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
19069 Diag(New->getLocation(),
19070 diag::err_covariant_return_type_different_qualifications)
19071 << New->getDeclName() << NewTy << OldTy
19072 << New->getReturnTypeSourceRange();
19073 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
19074 << Old->getReturnTypeSourceRange();
19075 return true;
19076 }
19077
19078
19079 // The new class type must have the same or less qualifiers as the old type.
19080 if (!OldClassTy.isAtLeastAsQualifiedAs(NewClassTy, getASTContext())) {
19081 Diag(New->getLocation(),
19082 diag::err_covariant_return_type_class_type_not_same_or_less_qualified)
19083 << New->getDeclName() << NewTy << OldTy
19084 << New->getReturnTypeSourceRange();
19085 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
19086 << Old->getReturnTypeSourceRange();
19087 return true;
19088 }
19089
19090 return false;
19091}
19092
19094 SourceLocation EndLoc = InitRange.getEnd();
19095 if (EndLoc.isValid())
19096 Method->setRangeEnd(EndLoc);
19097
19098 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
19099 Method->setIsPureVirtual();
19100 return false;
19101 }
19102
19103 if (!Method->isInvalidDecl())
19104 Diag(Method->getLocation(), diag::err_non_virtual_pure)
19105 << Method->getDeclName() << InitRange;
19106 return true;
19107}
19108
19110 if (D->getFriendObjectKind())
19111 Diag(D->getLocation(), diag::err_pure_friend);
19112 else if (auto *M = dyn_cast<CXXMethodDecl>(D))
19113 CheckPureMethod(M, ZeroLoc);
19114 else
19115 Diag(D->getLocation(), diag::err_illegal_initializer);
19116}
19117
19118/// Invoked when we are about to parse an initializer for the declaration
19119/// 'Dcl'.
19120///
19121/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
19122/// static data member of class X, names should be looked up in the scope of
19123/// class X. If the declaration had a scope specifier, a scope will have
19124/// been created and passed in for this purpose. Otherwise, S will be null.
19126 assert(D && !D->isInvalidDecl());
19127
19128 // We will always have a nested name specifier here, but this declaration
19129 // might not be out of line if the specifier names the current namespace:
19130 // extern int n;
19131 // int ::n = 0;
19132 if (S && D->isOutOfLine())
19134
19138}
19139
19141 assert(D);
19142
19143 if (S && D->isOutOfLine())
19145
19147}
19148
19150 // C++ 6.4p2:
19151 // The declarator shall not specify a function or an array.
19152 // The type-specifier-seq shall not contain typedef and shall not declare a
19153 // new class or enumeration.
19155 "Parser allowed 'typedef' as storage class of condition decl.");
19156
19157 Decl *Dcl = ActOnDeclarator(S, D);
19158 if (!Dcl)
19159 return true;
19160
19161 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
19162 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
19163 << D.getSourceRange();
19164 return true;
19165 }
19166
19167 if (auto *VD = dyn_cast<VarDecl>(Dcl))
19168 VD->setCXXCondDecl();
19169
19170 return Dcl;
19171}
19172
19174 if (!ExternalSource)
19175 return;
19176
19178 ExternalSource->ReadUsedVTables(VTables);
19180 for (const ExternalVTableUse &VTable : VTables) {
19181 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos =
19182 VTablesUsed.find(VTable.Record);
19183 // Even if a definition wasn't required before, it may be required now.
19184 if (Pos != VTablesUsed.end()) {
19185 if (!Pos->second && VTable.DefinitionRequired)
19186 Pos->second = true;
19187 continue;
19188 }
19189
19190 VTablesUsed[VTable.Record] = VTable.DefinitionRequired;
19191 NewUses.push_back(VTableUse(VTable.Record, VTable.Location));
19192 }
19193
19194 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
19195}
19196
19198 bool DefinitionRequired) {
19199 // Ignore any vtable uses in unevaluated operands or for classes that do
19200 // not have a vtable.
19201 if (!Class->isDynamicClass() || Class->isDependentContext() ||
19202 CurContext->isDependentContext() || isUnevaluatedContext())
19203 return;
19204 // Do not mark as used if compiling for the device outside of the target
19205 // region.
19206 if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice &&
19207 !OpenMP().isInOpenMPDeclareTargetContext() &&
19208 !OpenMP().isInOpenMPTargetExecutionDirective()) {
19209 if (!DefinitionRequired)
19211 return;
19212 }
19213
19214 // Try to insert this class into the map.
19216 Class = Class->getCanonicalDecl();
19217 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
19218 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
19219 if (!Pos.second) {
19220 // If we already had an entry, check to see if we are promoting this vtable
19221 // to require a definition. If so, we need to reappend to the VTableUses
19222 // list, since we may have already processed the first entry.
19223 if (DefinitionRequired && !Pos.first->second) {
19224 Pos.first->second = true;
19225 } else {
19226 // Otherwise, we can early exit.
19227 return;
19228 }
19229 } else {
19230 // The Microsoft ABI requires that we perform the destructor body
19231 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
19232 // the deleting destructor is emitted with the vtable, not with the
19233 // destructor definition as in the Itanium ABI.
19234 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
19235 CXXDestructorDecl *DD = Class->getDestructor();
19236 if (DD && DD->isVirtual() && !DD->isDeleted()) {
19237 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
19238 // If this is an out-of-line declaration, marking it referenced will
19239 // not do anything. Manually call CheckDestructor to look up operator
19240 // delete().
19241 ContextRAII SavedContext(*this, DD);
19242 CheckDestructor(DD);
19243 if (!DD->getOperatorDelete())
19244 DD->setInvalidDecl();
19245 } else {
19246 MarkFunctionReferenced(Loc, Class->getDestructor());
19247 }
19248 }
19249 }
19250 }
19251
19252 // Local classes need to have their virtual members marked
19253 // immediately. For all other classes, we mark their virtual members
19254 // at the end of the translation unit.
19255 if (Class->isLocalClass())
19256 MarkVirtualMembersReferenced(Loc, Class->getDefinition());
19257 else
19258 VTableUses.push_back(std::make_pair(Class, Loc));
19259}
19260
19263 if (VTableUses.empty())
19264 return false;
19265
19266 // Note: The VTableUses vector could grow as a result of marking
19267 // the members of a class as "used", so we check the size each
19268 // time through the loop and prefer indices (which are stable) to
19269 // iterators (which are not).
19270 bool DefinedAnything = false;
19271 for (unsigned I = 0; I != VTableUses.size(); ++I) {
19272 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
19273 if (!Class)
19274 continue;
19276 Class->getTemplateSpecializationKind();
19277
19278 SourceLocation Loc = VTableUses[I].second;
19279
19280 bool DefineVTable = true;
19281
19282 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
19283 // V-tables for non-template classes with an owning module are always
19284 // uniquely emitted in that module.
19285 if (Class->isInCurrentModuleUnit()) {
19286 DefineVTable = true;
19287 } else if (KeyFunction && !KeyFunction->hasBody()) {
19288 // If this class has a key function, but that key function is
19289 // defined in another translation unit, we don't need to emit the
19290 // vtable even though we're using it.
19291 // The key function is in another translation unit.
19292 DefineVTable = false;
19294 KeyFunction->getTemplateSpecializationKind();
19297 "Instantiations don't have key functions");
19298 (void)TSK;
19299 } else if (!KeyFunction) {
19300 // If we have a class with no key function that is the subject
19301 // of an explicit instantiation declaration, suppress the
19302 // vtable; it will live with the explicit instantiation
19303 // definition.
19304 bool IsExplicitInstantiationDeclaration =
19306 for (auto *R : Class->redecls()) {
19308 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
19310 IsExplicitInstantiationDeclaration = true;
19311 else if (TSK == TSK_ExplicitInstantiationDefinition) {
19312 IsExplicitInstantiationDeclaration = false;
19313 break;
19314 }
19315 }
19316
19317 if (IsExplicitInstantiationDeclaration) {
19318 const bool HasExcludeFromExplicitInstantiation =
19319 llvm::any_of(Class->methods(), [](CXXMethodDecl *method) {
19320 // If the class has a member function declared with
19321 // `__attribute__((exclude_from_explicit_instantiation))`, the
19322 // explicit instantiation declaration should not suppress emitting
19323 // the vtable, since the corresponding explicit instantiation
19324 // definition might not emit the vtable if a triggering method is
19325 // excluded.
19326 return method->hasAttr<ExcludeFromExplicitInstantiationAttr>();
19327 });
19328 if (!HasExcludeFromExplicitInstantiation)
19329 DefineVTable = false;
19330 }
19331 }
19332
19333 // The exception specifications for all virtual members may be needed even
19334 // if we are not providing an authoritative form of the vtable in this TU.
19335 // We may choose to emit it available_externally anyway.
19336 if (!DefineVTable) {
19338 continue;
19339 }
19340
19341 // Mark all of the virtual members of this class as referenced, so
19342 // that we can build a vtable. Then, tell the AST consumer that a
19343 // vtable for this class is required.
19344 DefinedAnything = true;
19346 CXXRecordDecl *Canonical = Class->getCanonicalDecl();
19347 // The vtable is assumed to be emitted in an external source only for
19348 // classes attached to a named module, which is guaranteed to have an object
19349 // file. This isn't true for -fmodules-debuginfo, which still has
19350 // shouldEmitInExternalSource as true so that debug info gets supressed.
19351 if (VTablesUsed[Canonical] &&
19352 !(Class->isInNamedModule() && Class->shouldEmitInExternalSource()))
19353 Consumer.HandleVTable(Class);
19354
19355 // Warn if we're emitting a weak vtable. The vtable will be weak if there is
19356 // no key function or the key function is inlined. Don't warn in C++ ABIs
19357 // that lack key functions, since the user won't be able to make one.
19358 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
19359 Class->isExternallyVisible() &&
19360 !(Class->getOwningModule() &&
19361 Class->getOwningModule()->isInterfaceOrPartition()) &&
19362 ClassTSK != TSK_ImplicitInstantiation &&
19365 const FunctionDecl *KeyFunctionDef = nullptr;
19366 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
19367 KeyFunctionDef->isInlined()))
19368 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
19369 }
19370 }
19371 VTableUses.clear();
19372
19373 return DefinedAnything;
19374}
19375
19377 const CXXRecordDecl *RD) {
19378 for (const auto *I : RD->methods())
19379 if (I->isVirtual() && !I->isPureVirtual())
19380 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
19381}
19382
19384 const CXXRecordDecl *RD,
19385 bool ConstexprOnly) {
19386 // Mark all functions which will appear in RD's vtable as used.
19387 CXXFinalOverriderMap FinalOverriders;
19388 RD->getFinalOverriders(FinalOverriders);
19389 for (const auto &FinalOverrider : FinalOverriders) {
19390 for (const auto &OverridingMethod : FinalOverrider.second) {
19391 assert(OverridingMethod.second.size() > 0 && "no final overrider");
19392 CXXMethodDecl *Overrider = OverridingMethod.second.front().Method;
19393
19394 // C++ [basic.def.odr]p2:
19395 // [...] A virtual member function is used if it is not pure. [...]
19396 if (!Overrider->isPureVirtual() &&
19397 (!ConstexprOnly || Overrider->isConstexpr()))
19398 MarkFunctionReferenced(Loc, Overrider);
19399 }
19400 }
19401
19402 // Only classes that have virtual bases need a VTT.
19403 if (RD->getNumVBases() == 0)
19404 return;
19405
19406 for (const auto &I : RD->bases()) {
19407 const auto *Base = I.getType()->castAsCXXRecordDecl();
19408 if (Base->getNumVBases() == 0)
19409 continue;
19411 }
19412}
19413
19414static
19419 Sema &S) {
19420 if (Ctor->isInvalidDecl())
19421 return;
19422
19424
19425 // Target may not be determinable yet, for instance if this is a dependent
19426 // call in an uninstantiated template.
19427 if (Target) {
19428 const FunctionDecl *FNTarget = nullptr;
19429 (void)Target->hasBody(FNTarget);
19430 Target = const_cast<CXXConstructorDecl*>(
19431 cast_or_null<CXXConstructorDecl>(FNTarget));
19432 }
19433
19434 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
19435 // Avoid dereferencing a null pointer here.
19436 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
19437
19438 if (!Current.insert(Canonical).second)
19439 return;
19440
19441 // We know that beyond here, we aren't chaining into a cycle.
19442 if (!Target || !Target->isDelegatingConstructor() ||
19443 Target->isInvalidDecl() || Valid.count(TCanonical)) {
19444 Valid.insert_range(Current);
19445 Current.clear();
19446 // We've hit a cycle.
19447 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
19448 Current.count(TCanonical)) {
19449 // If we haven't diagnosed this cycle yet, do so now.
19450 if (!Invalid.count(TCanonical)) {
19451 S.Diag((*Ctor->init_begin())->getSourceLocation(),
19452 diag::warn_delegating_ctor_cycle)
19453 << Ctor;
19454
19455 // Don't add a note for a function delegating directly to itself.
19456 if (TCanonical != Canonical)
19457 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
19458
19460 while (C->getCanonicalDecl() != Canonical) {
19461 const FunctionDecl *FNTarget = nullptr;
19462 (void)C->getTargetConstructor()->hasBody(FNTarget);
19463 assert(FNTarget && "Ctor cycle through bodiless function");
19464
19465 C = const_cast<CXXConstructorDecl*>(
19466 cast<CXXConstructorDecl>(FNTarget));
19467 S.Diag(C->getLocation(), diag::note_which_delegates_to);
19468 }
19469 }
19470
19471 Invalid.insert_range(Current);
19472 Current.clear();
19473 } else {
19475 }
19476}
19477
19478
19481
19482 for (DelegatingCtorDeclsType::iterator
19483 I = DelegatingCtorDecls.begin(ExternalSource.get()),
19484 E = DelegatingCtorDecls.end();
19485 I != E; ++I)
19486 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
19487
19488 for (CXXConstructorDecl *CI : Invalid)
19489 CI->setInvalidDecl();
19490}
19491
19492namespace {
19493 /// AST visitor that finds references to the 'this' expression.
19494class FindCXXThisExpr : public DynamicRecursiveASTVisitor {
19495 Sema &S;
19496
19497public:
19498 explicit FindCXXThisExpr(Sema &S) : S(S) {}
19499
19500 bool VisitCXXThisExpr(CXXThisExpr *E) override {
19501 S.Diag(E->getLocation(), diag::err_this_static_member_func)
19502 << E->isImplicit();
19503 return false;
19504 }
19505};
19506}
19507
19509 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
19510 if (!TSInfo)
19511 return false;
19512
19513 TypeLoc TL = TSInfo->getTypeLoc();
19515 if (!ProtoTL)
19516 return false;
19517
19518 // C++11 [expr.prim.general]p3:
19519 // [The expression this] shall not appear before the optional
19520 // cv-qualifier-seq and it shall not appear within the declaration of a
19521 // static member function (although its type and value category are defined
19522 // within a static member function as they are within a non-static member
19523 // function). [ Note: this is because declaration matching does not occur
19524 // until the complete declarator is known. - end note ]
19525 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
19526 FindCXXThisExpr Finder(*this);
19527
19528 // If the return type came after the cv-qualifier-seq, check it now.
19529 if (Proto->hasTrailingReturn() &&
19530 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
19531 return true;
19532
19533 // Check the exception specification.
19535 return true;
19536
19537 // Check the trailing requires clause
19538 if (const AssociatedConstraint &TRC = Method->getTrailingRequiresClause())
19539 if (!Finder.TraverseStmt(const_cast<Expr *>(TRC.ConstraintExpr)))
19540 return true;
19541
19543}
19544
19546 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
19547 if (!TSInfo)
19548 return false;
19549
19550 TypeLoc TL = TSInfo->getTypeLoc();
19552 if (!ProtoTL)
19553 return false;
19554
19555 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
19556 FindCXXThisExpr Finder(*this);
19557
19558 switch (Proto->getExceptionSpecType()) {
19559 case EST_Unparsed:
19560 case EST_Uninstantiated:
19561 case EST_Unevaluated:
19562 case EST_BasicNoexcept:
19563 case EST_NoThrow:
19564 case EST_DynamicNone:
19565 case EST_MSAny:
19566 case EST_None:
19567 break;
19568
19570 case EST_NoexceptFalse:
19571 case EST_NoexceptTrue:
19572 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
19573 return true;
19574 [[fallthrough]];
19575
19576 case EST_Dynamic:
19577 for (const auto &E : Proto->exceptions()) {
19578 if (!Finder.TraverseType(E))
19579 return true;
19580 }
19581 break;
19582 }
19583
19584 return false;
19585}
19586
19588 FindCXXThisExpr Finder(*this);
19589
19590 // Check attributes.
19591 for (const auto *A : Method->attrs()) {
19592 // FIXME: This should be emitted by tblgen.
19593 Expr *Arg = nullptr;
19594 ArrayRef<Expr *> Args;
19595 if (const auto *G = dyn_cast<GuardedByAttr>(A))
19596 Args = llvm::ArrayRef(G->args_begin(), G->args_size());
19597 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
19598 Args = llvm::ArrayRef(G->args_begin(), G->args_size());
19599 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
19600 Args = llvm::ArrayRef(AA->args_begin(), AA->args_size());
19601 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
19602 Args = llvm::ArrayRef(AB->args_begin(), AB->args_size());
19603 else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
19604 Arg = LR->getArg();
19605 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
19606 Args = llvm::ArrayRef(LE->args_begin(), LE->args_size());
19607 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
19608 Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());
19609 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
19610 Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());
19611 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) {
19612 Arg = AC->getSuccessValue();
19613 Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());
19614 } else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
19615 Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());
19616
19617 if (Arg && !Finder.TraverseStmt(Arg))
19618 return true;
19619
19620 for (Expr *A : Args) {
19621 if (!Finder.TraverseStmt(A))
19622 return true;
19623 }
19624 }
19625
19626 return false;
19627}
19628
19630 bool IsTopLevel, ExceptionSpecificationType EST,
19631 ArrayRef<ParsedType> DynamicExceptions,
19632 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
19633 SmallVectorImpl<QualType> &Exceptions,
19635 Exceptions.clear();
19636 ESI.Type = EST;
19637 if (EST == EST_Dynamic) {
19638 Exceptions.reserve(DynamicExceptions.size());
19639 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
19640 // FIXME: Preserve type source info.
19641 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
19642
19643 if (IsTopLevel) {
19645 collectUnexpandedParameterPacks(ET, Unexpanded);
19646 if (!Unexpanded.empty()) {
19648 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
19649 Unexpanded);
19650 continue;
19651 }
19652 }
19653
19654 // Check that the type is valid for an exception spec, and
19655 // drop it if not.
19656 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
19657 Exceptions.push_back(ET);
19658 }
19659 ESI.Exceptions = Exceptions;
19660 return;
19661 }
19662
19663 if (isComputedNoexcept(EST)) {
19664 assert((NoexceptExpr->isTypeDependent() ||
19665 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
19666 Context.BoolTy) &&
19667 "Parser should have made sure that the expression is boolean");
19668 if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
19669 ESI.Type = EST_BasicNoexcept;
19670 return;
19671 }
19672
19673 ESI.NoexceptExpr = NoexceptExpr;
19674 return;
19675 }
19676}
19677
19679 Decl *D, ExceptionSpecificationType EST, SourceRange SpecificationRange,
19680 ArrayRef<ParsedType> DynamicExceptions,
19681 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr) {
19682 if (!D)
19683 return;
19684
19685 // Dig out the function we're referring to.
19686 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
19687 D = FTD->getTemplatedDecl();
19688
19689 FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
19690 if (!FD)
19691 return;
19692
19693 // Check the exception specification.
19696 checkExceptionSpecification(/*IsTopLevel=*/true, EST, DynamicExceptions,
19697 DynamicExceptionRanges, NoexceptExpr, Exceptions,
19698 ESI);
19699
19700 // Update the exception specification on the function type.
19701 Context.adjustExceptionSpec(FD, ESI, /*AsWritten=*/true);
19702
19703 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
19704 if (MD->isStatic())
19706
19707 if (MD->isVirtual()) {
19708 // Check overrides, which we previously had to delay.
19709 for (const CXXMethodDecl *O : MD->overridden_methods())
19711 }
19712 }
19713}
19714
19715/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
19716///
19718 SourceLocation DeclStart, Declarator &D,
19719 Expr *BitWidth,
19720 InClassInitStyle InitStyle,
19721 AccessSpecifier AS,
19722 const ParsedAttr &MSPropertyAttr) {
19723 const IdentifierInfo *II = D.getIdentifier();
19724 if (!II) {
19725 Diag(DeclStart, diag::err_anonymous_property);
19726 return nullptr;
19727 }
19729
19731 QualType T = TInfo->getType();
19732 if (getLangOpts().CPlusPlus) {
19734
19737 D.setInvalidType();
19738 T = Context.IntTy;
19739 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
19740 }
19741 }
19742
19744
19746 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
19747 << getLangOpts().CPlusPlus17;
19750 diag::err_invalid_thread)
19752
19753 // Check to see if this name was declared as a member previously
19754 NamedDecl *PrevDecl = nullptr;
19755 LookupResult Previous(*this, II, Loc, LookupMemberName,
19757 LookupName(Previous, S);
19758 switch (Previous.getResultKind()) {
19761 PrevDecl = Previous.getAsSingle<NamedDecl>();
19762 break;
19763
19765 PrevDecl = Previous.getRepresentativeDecl();
19766 break;
19767
19771 break;
19772 }
19773
19774 if (PrevDecl && PrevDecl->isTemplateParameter()) {
19775 // Maybe we will complain about the shadowed template parameter.
19777 // Just pretend that we didn't see the previous declaration.
19778 PrevDecl = nullptr;
19779 }
19780
19781 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
19782 PrevDecl = nullptr;
19783
19784 SourceLocation TSSL = D.getBeginLoc();
19785 MSPropertyDecl *NewPD =
19786 MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
19787 MSPropertyAttr.getPropertyDataGetter(),
19788 MSPropertyAttr.getPropertyDataSetter());
19789 ProcessDeclAttributes(TUScope, NewPD, D);
19790 NewPD->setAccess(AS);
19791
19792 if (NewPD->isInvalidDecl())
19793 Record->setInvalidDecl();
19794
19796 NewPD->setModulePrivate();
19797
19798 if (NewPD->isInvalidDecl() && PrevDecl) {
19799 // Don't introduce NewFD into scope; there's already something
19800 // with the same name in the same scope.
19801 } else if (II) {
19802 PushOnScopeChains(NewPD, S);
19803 } else
19804 Record->addDecl(NewPD);
19805
19806 return NewPD;
19807}
19808
19810 Declarator &Declarator, unsigned TemplateParameterDepth) {
19811 auto &Info = InventedParameterInfos.emplace_back();
19812 TemplateParameterList *ExplicitParams = nullptr;
19813 ArrayRef<TemplateParameterList *> ExplicitLists =
19815 if (!ExplicitLists.empty()) {
19816 bool IsMemberSpecialization, IsInvalid;
19819 Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr,
19820 ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid,
19821 /*SuppressDiagnostic=*/true);
19822 }
19823 // C++23 [dcl.fct]p23:
19824 // An abbreviated function template can have a template-head. The invented
19825 // template-parameters are appended to the template-parameter-list after
19826 // the explicitly declared template-parameters.
19827 //
19828 // A template-head must have one or more template-parameters (read:
19829 // 'template<>' is *not* a template-head). Only append the invented
19830 // template parameters if we matched the nested-name-specifier to a non-empty
19831 // TemplateParameterList.
19832 if (ExplicitParams && !ExplicitParams->empty()) {
19833 Info.AutoTemplateParameterDepth = ExplicitParams->getDepth();
19834 llvm::append_range(Info.TemplateParams, *ExplicitParams);
19835 Info.NumExplicitTemplateParams = ExplicitParams->size();
19836 } else {
19837 Info.AutoTemplateParameterDepth = TemplateParameterDepth;
19838 Info.NumExplicitTemplateParams = 0;
19839 }
19840}
19841
19843 auto &FSI = InventedParameterInfos.back();
19844 if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) {
19845 if (FSI.NumExplicitTemplateParams != 0) {
19846 TemplateParameterList *ExplicitParams =
19850 Context, ExplicitParams->getTemplateLoc(),
19851 ExplicitParams->getLAngleLoc(), FSI.TemplateParams,
19852 ExplicitParams->getRAngleLoc(),
19853 ExplicitParams->getRequiresClause()));
19854 } else {
19857 FSI.TemplateParams, Declarator.getEndLoc(),
19858 /*RequiresClause=*/nullptr));
19859 }
19860 }
19861 InventedParameterInfos.pop_back();
19862}
19863
19865 CXXConstructorDecl *Ctor, bool IsCopy) {
19866 assert(Context.getTargetInfo().getCXXABI().isMicrosoft());
19867
19868 if (!Ctor->getCtorClosureDefaultArgs().empty()) {
19869 // If we build args for default constructor closures, those will have
19870 // been generated *before* building args for any copy constructor closures.
19871 assert(IsCopy || Ctor->getCtorClosureDefaultArgs()[0] != nullptr);
19872 return false;
19873 }
19874
19875 unsigned NumParams = Ctor->getNumParams();
19876 if (NumParams == 0)
19877 return false;
19878
19879 CXXDefaultArgExpr **Args =
19880 new (getASTContext()) CXXDefaultArgExpr *[NumParams];
19881
19882 if (IsCopy)
19883 Args[0] = nullptr; // Copy ctor closure will provide the first argument.
19884
19885 for (unsigned I = IsCopy ? 1 : 0; I != NumParams; ++I) {
19886 ExprResult R = BuildCXXDefaultArgExpr(Loc, Ctor, Ctor->getParamDecl(I));
19888 if (R.isInvalid())
19889 return true;
19890 Args[I] = cast<CXXDefaultArgExpr>(R.get());
19891 }
19892
19893 Ctor->setCtorClosureDefaultArgs(ArrayRef(Args, NumParams));
19894 return false;
19895}
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)
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 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 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 Sema::ImplicitExceptionSpecification ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD, Sema::DefaultedComparisonKind DCK)
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 bool checkTupleLikeDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, VarDecl *Src, QualType DecompType, unsigned NumElems)
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)
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 bool isStdClassTemplate(Sema &S, QualType SugaredType, QualType *TypeArg, const char *ClassName, ClassTemplateDecl **CachedDecl, const Decl **MalformedDecl)
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 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 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 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 TemplateDeductionResult DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams, ArrayRef< TemplateArgument > Ps, ArrayRef< TemplateArgument > As, TemplateDeductionInfo &Info, SmallVectorImpl< DeducedTemplateArgument > &Deduced, bool NumberOfArgumentsMustMatch, bool PartialOrdering, PackFold PackFold, bool *HasDeducedAnyParam)
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:122
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:223
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:812
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:808
const LangOptions & getLangOpts() const
Definition ASTContext.h:965
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:861
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:927
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:3833
Attr - This represents one attribute.
Definition Attr.h:46
attr::Kind getKind() const
Definition Attr.h:92
bool isInherited() const
Definition Attr.h:101
Attr * clone(ASTContext &C) const
SourceLocation getLocation() const
Definition Attr.h:99
Represents a C++ declaration that introduces decls from somewhere else.
Definition DeclCXX.h:3517
unsigned shadow_size() const
Return the number of shadowed declarations associated with this using declaration.
Definition DeclCXX.h:3595
void addShadowDecl(UsingShadowDecl *S)
Definition DeclCXX.cpp:3516
shadow_iterator shadow_begin() const
Definition DeclCXX.h:3587
void removeShadowDecl(UsingShadowDecl *S)
Definition DeclCXX.cpp:3525
Expr * getLHS() const
Definition Expr.h:4094
Expr * getRHS() const
Definition Expr.h:4096
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:5107
static bool isCompoundAssignmentOp(Opcode Opc)
Definition Expr.h:4185
Opcode getOpcode() const
Definition Expr.h:4089
static Opcode getOverloadedOpcode(OverloadedOperatorKind OO)
Retrieve the binary opcode that corresponds to the given overloaded operator.
Definition Expr.cpp:2151
A binding in a decomposition declaration.
Definition DeclCXX.h:4206
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:4244
void setDecomposedDecl(ValueDecl *Decomposed)
Set the decomposed variable for this BindingDecl.
Definition DeclCXX.h:4250
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition Expr.h:6684
Wrapper for source info for block pointers.
Definition TypeLoc.h:1557
This class is used for builtin types like 'int'.
Definition TypeBase.h:3229
Kind getKind() const
Definition TypeBase.h:3277
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:726
CXXCatchStmt - This represents a C++ catch block.
Definition StmtCXX.h:29
Represents a call to a C++ constructor.
Definition ExprCXX.h:1551
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:1187
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition ExprCXX.h:1694
bool isImmediateEscalating() const
Definition ExprCXX.h:1709
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition ExprCXX.h:1614
Represents a C++ constructor within a class.
Definition DeclCXX.h:2633
CXXConstructorDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:2873
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:2727
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
bool isDefaultConstructor() const
Whether this constructor is a default constructor (C++ [class.ctor]p5), which can be used to default-...
Definition DeclCXX.cpp:3049
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:2868
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:2705
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2968
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition DeclCXX.h:3004
Represents a C++ base or member initializer.
Definition DeclCXX.h:2398
bool isWritten() const
Determine whether this initializer is explicitly written in the source code.
Definition DeclCXX.h:2570
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:2478
TypeSourceInfo * getTypeSourceInfo() const
Returns the declarator information for a base class or delegating initializer.
Definition DeclCXX.h:2532
FieldDecl * getAnyMember() const
Definition DeclCXX.h:2544
A default argument (C++ [dcl.fct.default]).
Definition ExprCXX.h:1273
Represents a C++ destructor within a class.
Definition DeclCXX.h:2898
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:1754
Represents a call to a member function that may be written either with member call syntax (e....
Definition ExprCXX.h:182
CXXMethodDecl * getMethodDecl() const
Retrieve the declaration of the called method.
Definition ExprCXX.cpp:748
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2145
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:2200
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:2312
CXXMethodDecl * getMostRecentDecl()
Definition DeclCXX.h:2261
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:2284
bool isInstance() const
Definition DeclCXX.h:2172
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition DeclCXX.cpp:2751
QualType getFunctionObjectParameterType() const
Definition DeclCXX.h:2308
bool isStatic() const
Definition DeclCXX.cpp:2417
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:2254
The null pointer literal (C++11 [lex.nullptr])
Definition ExprCXX.h:771
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:1281
friend_range friends() const
Definition DeclFriend.h:258
bool hasTrivialMoveAssignment() const
Determine whether this class has a trivial move assignment operator (C++11 [class....
Definition DeclCXX.h:1352
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:1251
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:1377
bool hasUserDeclaredDestructor() const
Determine whether this class has a user-declared destructor.
Definition DeclCXX.h:1006
bool implicitCopyConstructorHasConstParam() const
Determine whether an implicit copy constructor for this type would have a parameter with a const-qual...
Definition DeclCXX.h:822
bool defaultedDestructorIsDeleted() const
true if a defaulted destructor for this class would be deleted.
Definition DeclCXX.h:714
bool hasInheritedAssignment() const
Determine whether this class has a using-declaration that names a base class assignment operator.
Definition DeclCXX.h:1431
bool allowConstDefaultInit() const
Determine whether declaring a const variable with this type is ok per core issue 253.
Definition DeclCXX.h:1402
bool hasTrivialDestructorForCall() const
Definition DeclCXX.h:1381
bool defaultedMoveConstructorIsDeleted() const
true if a defaulted move constructor for this class would be deleted.
Definition DeclCXX.h:706
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:965
bool defaultedDestructorIsConstexpr() const
Determine whether a defaulted default constructor for this class would be constexpr.
Definition DeclCXX.h:1367
base_class_range bases()
Definition DeclCXX.h:608
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:1023
bool hasTrivialMoveConstructor() const
Determine whether this class has a trivial move constructor (C++11 [class.copy]p12)
Definition DeclCXX.h:1312
bool needsImplicitDefaultConstructor() const
Determine if we need to declare a default constructor for this class.
Definition DeclCXX.h:766
bool needsImplicitMoveConstructor() const
Determine whether this class should get an implicit move constructor or if any existing special membe...
Definition DeclCXX.h:894
bool hasUserDeclaredCopyAssignment() const
Determine whether this class has a user-declared copy assignment operator.
Definition DeclCXX.h:913
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:650
CXXRecordDecl * getDefinition() const
Definition DeclCXX.h:548
bool needsOverloadResolutionForCopyAssignment() const
Determine whether we need to eagerly declare a defaulted copy assignment operator for this class.
Definition DeclCXX.h:935
static AccessSpecifier MergeAccess(AccessSpecifier PathAccess, AccessSpecifier DeclAccess)
Calculates the access of a decl that is reached along a path.
Definition DeclCXX.h:1740
bool defaultedDefaultConstructorIsConstexpr() const
Determine whether a defaulted default constructor for this class would be constexpr.
Definition DeclCXX.h:1274
bool hasTrivialCopyConstructor() const
Determine whether this class has a trivial copy constructor (C++ [class.copy]p6, C++11 [class....
Definition DeclCXX.h:1289
void setImplicitMoveAssignmentIsDeleted()
Set that we attempted to declare an implicit move assignment operator, but overload resolution failed...
Definition DeclCXX.h:977
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:1219
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition DeclCXX.h:602
bool defaultedCopyConstructorIsDeleted() const
true if a defaulted copy constructor for this class would be deleted.
Definition DeclCXX.h:697
bool hasTrivialCopyConstructorForCall() const
Definition DeclCXX.h:1293
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:1339
base_class_range vbases()
Definition DeclCXX.h:625
base_class_iterator vbases_begin()
Definition DeclCXX.h:632
ctor_range ctors() const
Definition DeclCXX.h:670
void setImplicitMoveConstructorIsDeleted()
Set that we attempted to declare an implicit move constructor, but overload resolution failed so we d...
Definition DeclCXX.h:869
bool isAbstract() const
Determine whether this class has a pure virtual function.
Definition DeclCXX.h:1226
bool hasVariantMembers() const
Determine whether this class has any variant members.
Definition DeclCXX.h:1241
void setImplicitCopyConstructorIsDeleted()
Set that we attempted to declare an implicit copy constructor, but overload resolution failed so we d...
Definition DeclCXX.h:860
bool isDynamicClass() const
Definition DeclCXX.h:574
bool hasInClassInitializer() const
Whether this class has any in-class initializers for non-static data members (including those in anon...
Definition DeclCXX.h:1153
bool needsImplicitCopyConstructor() const
Determine whether this class needs an implicit copy constructor to be lazily declared.
Definition DeclCXX.h:800
bool hasIrrelevantDestructor() const
Determine whether this class has a destructor which has no semantic effect.
Definition DeclCXX.h:1413
bool hasNonTrivialCopyConstructorForCall() const
Definition DeclCXX.h:1304
bool hasDirectFields() const
Determine whether this class has direct non-static data members.
Definition DeclCXX.h:1205
bool hasUserDeclaredCopyConstructor() const
Determine whether this class has a user-declared copy constructor.
Definition DeclCXX.h:794
bool hasDefinition() const
Definition DeclCXX.h:561
void setImplicitCopyAssignmentIsDeleted()
Set that we attempted to declare an implicit copy assignment operator, but overload resolution failed...
Definition DeclCXX.h:919
bool needsImplicitDestructor() const
Determine whether this class needs an implicit destructor to be lazily declared.
Definition DeclCXX.h:1012
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:905
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:999
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
Definition DeclCXX.cpp:2129
bool hasNonTrivialDestructorForCall() const
Definition DeclCXX.h:1391
bool needsOverloadResolutionForDestructor() const
Determine whether we need to eagerly declare a destructor for this class.
Definition DeclCXX.h:1018
bool hasInheritedConstructor() const
Determine whether this class has a using-declaration that names a user-declared base class constructo...
Definition DeclCXX.h:1425
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:807
CXXRecordDecl * getDefinitionOrSelf() const
Definition DeclCXX.h:555
bool hasUserDeclaredMoveConstructor() const
Determine whether this class has had a move constructor declared by the user.
Definition DeclCXX.h:848
bool needsImplicitMoveAssignment() const
Determine whether this class should get an implicit move assignment operator or if any existing speci...
Definition DeclCXX.h:987
bool needsImplicitCopyAssignment() const
Determine whether this class needs an implicit copy assignment operator to be lazily declared.
Definition DeclCXX.h:928
bool hasTrivialMoveConstructorForCall() const
Definition DeclCXX.h:1317
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:522
unsigned getNumVBases() const
Retrieves the number of virtual base classes of this class.
Definition DeclCXX.h:623
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:950
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:76
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition DeclSpec.h:183
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition DeclSpec.h:188
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:82
SourceLocation getBeginLoc() const
Definition DeclSpec.h:86
bool isSet() const
Deprecated.
Definition DeclSpec.h:201
NestedNameSpecifier getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition DeclSpec.h:97
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:186
bool isEmpty() const
No scope specifier.
Definition DeclSpec.h:181
Represents the this expression in C++.
Definition ExprCXX.h:1157
SourceLocation getBeginLoc() const
Definition ExprCXX.h:1177
bool isImplicit() const
Definition ExprCXX.h:1180
SourceLocation getLocation() const
Definition ExprCXX.h:1174
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:2949
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3153
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3132
bool isCallToStdMove() const
Definition Expr.cpp:3653
Expr * getCallee()
Definition Expr.h:3096
arg_range arguments()
Definition Expr.h:3201
QualType withConst() const
Retrieves a version of this type with const applied.
CastKind getCastKind() const
Definition Expr.h:3726
Expr * getSubExpr()
Definition Expr.h:3732
static CharSourceRange getTokenRange(SourceRange R)
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition CharUnits.h:185
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:3340
QualType getElementType() const
Definition TypeBase.h:3350
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition Stmt.h:1749
body_range body()
Definition Stmt.h:1812
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:3859
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3915
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:3698
const CXXRecordDecl * getParent() const
Returns the parent of this using shadow declaration, which is the class in which this is declared.
Definition DeclCXX.h:3762
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:5347
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:1399
DeclListNode::iterator iterator
Definition DeclBase.h:1409
specific_decl_iterator - Iterates over a subrange of declarations stored in a DeclContext,...
Definition DeclBase.h:2423
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1466
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2126
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition DeclBase.h:2259
lookup_result::iterator lookup_iterator
Definition DeclBase.h:2608
bool isFileContext() const
Definition DeclBase.h:2197
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:2202
bool isRecord() const
Definition DeclBase.h:2206
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:2405
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition DeclBase.h:2403
bool isFunctionOrMethod() const
Definition DeclBase.h:2178
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:2119
DeclContext * getNonTransparentContext()
decl_iterator decls_begin() const
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1276
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:494
ValueDecl * getDecl()
Definition Expr.h:1344
NonOdrUseReason isNonOdrUse() const
Is this expression a non-odr-use reference, and if so, why?
Definition Expr.h:1474
SourceLocation getBeginLoc() const
Definition Expr.h:1355
bool isImmediateEscalating() const
Definition Expr.h:1484
Captures information about "declaration specifiers".
Definition DeclSpec.h:220
bool isVirtualSpecified() const
Definition DeclSpec.h:704
bool isModulePrivateSpecified() const
Definition DeclSpec.h:885
bool hasTypeSpecifier() const
Return true if any type-specifier has been found.
Definition DeclSpec.h:747
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:631
ThreadStorageClassSpecifier TSCS
Definition DeclSpec.h:237
Expr * getPackIndexingExpr() const
Definition DeclSpec.h:594
void ClearStorageClassSpecs()
Definition DeclSpec.h:546
TST getTypeSpecType() const
Definition DeclSpec.h:568
SourceLocation getStorageClassSpecLoc() const
Definition DeclSpec.h:541
SCS getStorageClassSpec() const
Definition DeclSpec.h:532
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:609
SourceRange getSourceRange() const LLVM_READONLY
Definition DeclSpec.h:608
unsigned getTypeQualifiers() const
getTypeQualifiers - Return a set of TQs.
Definition DeclSpec.h:651
SourceLocation getExplicitSpecLoc() const
Definition DeclSpec.h:710
SourceLocation getFriendSpecLoc() const
Definition DeclSpec.h:883
ParsedType getRepAsType() const
Definition DeclSpec.h:581
TSCS getThreadStorageClassSpec() const
Definition DeclSpec.h:533
bool isFriendSpecifiedFirst() const
Definition DeclSpec.h:881
ParsedAttributes & getAttributes()
Definition DeclSpec.h:929
SourceLocation getEllipsisLoc() const
Definition DeclSpec.h:658
SourceLocation getConstSpecLoc() const
Definition DeclSpec.h:652
SourceRange getExplicitSpecRange() const
Definition DeclSpec.h:711
Expr * getRepAsExpr() const
Definition DeclSpec.h:589
bool isInlineSpecified() const
Definition DeclSpec.h:693
SourceLocation getRestrictSpecLoc() const
Definition DeclSpec.h:653
TypeSpecifierType TST
Definition DeclSpec.h:250
bool SetTypeQual(TQ T, SourceLocation Loc)
void ClearConstexprSpec()
Definition DeclSpec.h:897
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:532
SourceLocation getThreadStorageClassSpecLoc() const
Definition DeclSpec.h:542
SourceLocation getAtomicSpecLoc() const
Definition DeclSpec.h:655
SourceLocation getVirtualSpecLoc() const
Definition DeclSpec.h:705
SourceLocation getConstexprSpecLoc() const
Definition DeclSpec.h:892
SourceLocation getTypeSpecTypeLoc() const
Definition DeclSpec.h:616
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:427
SourceLocation getInlineSpecLoc() const
Definition DeclSpec.h:696
SourceLocation getUnalignedSpecLoc() const
Definition DeclSpec.h:656
SourceLocation getVolatileSpecLoc() const
Definition DeclSpec.h:654
FriendSpecified isFriendSpecified() const
Definition DeclSpec.h:877
bool hasExplicitSpecifier() const
Definition DeclSpec.h:707
bool hasConstexprSpecifier() const
Definition DeclSpec.h:893
static const TST TST_auto
Definition DeclSpec.h:291
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Definition Stmt.h:1640
decl_range decls()
Definition Stmt.h:1688
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.h:1666
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:1078
bool isInStdNamespace() const
Definition DeclBase.cpp:453
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclBase.h:443
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition DeclBase.h:1243
T * getAttr() const
Definition DeclBase.h:581
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:601
virtual bool isOutOfLine() const
Determine whether this declaration is declared out of line (outside its semantic context).
Definition Decl.cpp:99
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:594
@ FOK_Undeclared
A friend of a previously-undeclared entity.
Definition DeclBase.h:1236
@ FOK_None
Not a friend object.
Definition DeclBase.h:1234
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:2823
DeclContext * getNonTransparentDeclContext()
Return the non transparent context.
bool isInvalidDecl() const
Definition DeclBase.h:596
unsigned getIdentifierNamespace() const
Definition DeclBase.h:906
bool isLocalExternDecl() const
Determine whether this is a block-scope declaration with linkage.
Definition DeclBase.h:1186
void setAccess(AccessSpecifier AS)
Definition DeclBase.h:510
SourceLocation getLocation() const
Definition DeclBase.h:447
@ 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:841
void setImplicit(bool I=true)
Definition DeclBase.h:602
void setReferenced(bool R=true)
Definition DeclBase.h:631
DeclContext * getDeclContext()
Definition DeclBase.h:456
AccessSpecifier getAccess() const
Definition DeclBase.h:515
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclBase.h:439
void dropAttr()
Definition DeclBase.h:564
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:935
bool hasAttr() const
Definition DeclBase.h:585
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:995
@ 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:898
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:780
SourceLocation getTypeSpecStartLoc() const
Definition Decl.cpp:2005
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:831
const AssociatedConstraint & getTrailingRequiresClause() const
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition Decl.h:855
void setTypeSourceInfo(TypeSourceInfo *TI)
Definition Decl.h:814
ArrayRef< TemplateParameterList * > getTemplateParameterLists() const
Definition Decl.h:862
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:809
Information about one declarator, including the parsed type information and the identifier.
Definition DeclSpec.h:2001
bool isFunctionDeclarator(unsigned &idx) const
isFunctionDeclarator - This method returns true if the declarator is a function declarator (looking t...
Definition DeclSpec.h:2557
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:2499
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition DeclSpec.h:2148
bool isFunctionDeclarationContext() const
Return true if this declaration appears in a context where a function declarator would be a function ...
Definition DeclSpec.h:2611
SourceLocation getIdentifierLoc() const
Definition DeclSpec.h:2437
void SetIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Set the name of this declarator to be the given identifier.
Definition DeclSpec.h:2440
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclSpec.h:2185
type_object_range type_objects() const
Returns the range of type objects, from the identifier outwards.
Definition DeclSpec.h:2512
bool hasGroupingParens() const
Definition DeclSpec.h:2820
void setInvalidType(bool Val=true)
Definition DeclSpec.h:2814
unsigned getNumTypeObjects() const
Return the number of types applied to this declarator.
Definition DeclSpec.h:2495
bool isRedeclaration() const
Definition DeclSpec.h:2866
DeclaratorContext getContext() const
Definition DeclSpec.h:2173
const DecompositionDeclarator & getDecompositionDeclarator() const
Definition DeclSpec.h:2169
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:2184
bool isFunctionDefinition() const
Definition DeclSpec.h:2838
UnqualifiedId & getName()
Retrieve the name specified by this declarator.
Definition DeclSpec.h:2167
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition DeclSpec.h:2163
ArrayRef< TemplateParameterList * > getTemplateParameterLists() const
The template parameter lists that preceded the declarator.
Definition DeclSpec.h:2750
void setInventedTemplateParameterList(TemplateParameterList *Invented)
Sets the template parameter list generated from the explicit template parameters along with any inven...
Definition DeclSpec.h:2757
bool mayHaveDecompositionDeclarator() const
Return true if the context permits a C++17 decomposition declarator.
Definition DeclSpec.h:2312
bool isInvalidType() const
Definition DeclSpec.h:2815
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition DeclSpec.h:2183
bool isDecompositionDeclarator() const
Return whether this declarator is a decomposition declarator.
Definition DeclSpec.h:2427
bool isStaticMember()
Returns true if this declares a static member.
Definition DeclSpec.cpp:389
DeclSpec & getMutableDeclSpec()
getMutableDeclSpec - Return a non-const version of the DeclSpec.
Definition DeclSpec.h:2155
DeclaratorChunk::FunctionTypeInfo & getFunctionTypeInfo()
getFunctionTypeInfo - Retrieves the function type info object (looking through parentheses).
Definition DeclSpec.h:2588
const IdentifierInfo * getIdentifier() const
Definition DeclSpec.h:2431
A decomposition declaration.
Definition DeclCXX.h:4270
ArrayRef< BindingDecl * > bindings() const
Definition DeclCXX.h:4310
A parsed C++17 decomposition declarator of the form '[' identifier-list ']'.
Definition DeclSpec.h:1889
ArrayRef< Binding > bindings() const
Definition DeclSpec.h:1929
SourceRange getSourceRange() const
Definition DeclSpec.h:1937
SourceLocation getLSquareLoc() const
Definition DeclSpec.h:1935
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2632
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:2612
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition TypeLoc.h:2621
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.
Definition Diagnostic.h:961
virtual bool TraverseConstructorInitializer(MaybeConst< CXXCtorInitializer > *Init)
static EmptyDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L)
Definition Decl.cpp:5895
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:3467
Represents an enum.
Definition Decl.h:4055
enumerator_range enumerators() const
Definition Decl.h:4201
EvaluatedExprVisitor - This class visits 'Expr *'s.
Store information needed for an explicit specifier.
Definition DeclCXX.h:1944
const Expr * getExpr() const
Definition DeclCXX.h:1953
void setExpr(Expr *E)
Definition DeclCXX.h:1978
void setKind(ExplicitSpecKind Kind)
Definition DeclCXX.h:1977
This represents one expression.
Definition Expr.h:112
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:177
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:194
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3101
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3089
bool containsErrors() const
Whether this expression contains subexpressions which had errors.
Definition Expr.h:246
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3097
bool isPRValue() const
Definition Expr.h:285
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition Expr.h:284
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:3264
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:144
Represents difference between two FPOptions values.
FPOptions applyOverrides(FPOptions Base)
Represents a member of a struct/union/class.
Definition Decl.h:3204
bool isMutable() const
Determines whether this field is mutable (C++ only).
Definition Decl.h:3304
Expr * getInClassInitializer() const
Get the C++11 default member initializer for this member, or null if one has not been set.
Definition Decl.cpp:4725
bool hasInClassInitializer() const
Determine whether this member has a C++11 default member initializer.
Definition Decl.h:3384
bool isAnonymousStructOrUnion() const
Determines whether this field is a representative for an anonymous struct or union.
Definition Decl.cpp:4715
InClassInitStyle getInClassInitStyle() const
Get the kind of (C++11) default member initializer that this field has.
Definition Decl.h:3378
void setInClassInitializer(Expr *NewInit)
Set the C++11 in-class initializer for this member.
Definition Decl.cpp:4735
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3440
FieldDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this field.
Definition Decl.h:3451
bool isUnnamedBitField() const
Determines whether this is an unnamed bitfield.
Definition Decl.h:3310
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:81
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:118
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:142
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:131
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:105
FriendDecl - Represents the declaration of a friend entity, which can be a function,...
Definition DeclFriend.h:54
static FriendDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, FriendUnion Friend_, SourceLocation FriendL, SourceLocation EllipsisLoc={}, ArrayRef< TemplateParameterList * > FriendTypeTPLists={})
void setUnsupportedFriend(bool Unsupported)
Definition DeclFriend.h:186
static FriendTemplateDecl * Create(ASTContext &Context, DeclContext *DC, SourceLocation Loc, MutableArrayRef< TemplateParameterList * > Params, FriendUnion Friend, SourceLocation FriendLoc)
static DefaultedOrDeletedFunctionInfo * Create(ASTContext &Context, ArrayRef< DeclAccessPair > Lookups, FPOptionsOverride FPFeatures, StringLiteral *DeletedMessage=nullptr)
Definition Decl.cpp:3119
Represents a function declaration or definition.
Definition Decl.h:2029
static constexpr unsigned RequiredTypeAwareDeleteParameterCount
Count of mandatory parameters for type aware operator delete.
Definition Decl.h:2682
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2837
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition Decl.cpp:3259
ExceptionSpecificationType getExceptionSpecType() const
Gets the ExceptionSpecificationType as declared.
Definition Decl.h:2909
bool isTrivialForCall() const
Definition Decl.h:2416
ConstexprSpecKind getConstexprKind() const
Definition Decl.h:2512
DefaultedOrDeletedFunctionInfo * getDefaultedOrDeletedInfo() const
Definition Decl.cpp:3174
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to call this function.
Definition Decl.cpp:3827
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4173
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
Definition Decl.h:2350
bool isImmediateFunction() const
Definition Decl.cpp:3320
void setDefaultedOrDeletedInfo(DefaultedOrDeletedFunctionInfo *Info)
Definition Decl.cpp:3140
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type.
Definition Decl.cpp:4004
bool isDestroyingOperatorDelete() const
Determine whether this is a destroying operator delete.
Definition Decl.cpp:3531
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3845
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition Decl.h:2961
SourceLocation getDefaultLoc() const
Definition Decl.h:2434
QualType getReturnType() const
Definition Decl.h:2885
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2814
bool isExplicitlyDefaulted() const
Whether this function is explicitly defaulted.
Definition Decl.h:2425
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition Decl.h:2413
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition Decl.cpp:4293
MutableArrayRef< ParmVarDecl * >::iterator param_iterator
Definition Decl.h:2822
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3727
param_iterator param_begin()
Definition Decl.h:2826
const ParmVarDecl * getNonObjectParameter(unsigned I) const
Definition Decl.h:2863
bool isVariadic() const
Whether this function is variadic.
Definition Decl.cpp:3112
bool doesThisDeclarationHaveABody() const
Returns whether this specific declaration of the function has a body.
Definition Decl.h:2362
bool isDeleted() const
Whether this function has been deleted.
Definition Decl.h:2576
void setBodyContainsImmediateEscalatingExpressions(bool Set)
Definition Decl.h:2522
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4309
FunctionEffectsRef getFunctionEffects() const
Definition Decl.h:3178
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition Decl.cpp:4237
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition Decl.h:2928
void setTrivial(bool IT)
Definition Decl.h:2414
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition Decl.cpp:4124
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition Decl.h:2506
static constexpr unsigned RequiredTypeAwareNewParameterCount
Count of mandatory parameters for type aware operator new.
Definition Decl.h:2678
bool isPureVirtual() const
Whether this virtual function is pure, i.e.
Definition Decl.h:2389
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition Decl.cpp:3598
FunctionDecl * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
bool isImmediateEscalating() const
Definition Decl.cpp:3291
void setIsDestroyingOperatorDelete(bool IsDestroyingDelete)
Definition Decl.cpp:3535
bool isTypeAwareOperatorNewOrDelete() const
Determine whether this is a type aware operator new or delete.
Definition Decl.cpp:3539
void setIsTypeAwareOperatorNewOrDelete(bool IsTypeAwareOperator=true)
Definition Decl.cpp:3543
bool isDefaulted() const
Whether this function is defaulted.
Definition Decl.h:2421
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:4549
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
Definition Decl.h:2973
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition Decl.cpp:4110
void setConstexprKind(ConstexprSpecKind CSK)
Definition Decl.h:2509
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition Decl.cpp:4397
void setDefaulted(bool D=true)
Definition Decl.h:2422
bool isConsteval() const
Definition Decl.h:2518
bool isUserProvided() const
True if this method is user-declared and was not deleted or defaulted on its first declaration.
Definition Decl.h:2446
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:2902
void setBody(Stmt *B)
Definition Decl.cpp:3271
bool isVirtualAsWritten() const
Whether this function is marked as virtual explicitly.
Definition Decl.h:2380
bool hasOneParamOrDefaultArgs() const
Determine whether this function has a single parameter, or multiple parameters where all but the firs...
Definition Decl.cpp:3859
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3806
size_t param_size() const
Definition Decl.h:2830
DeclarationNameInfo getNameInfo() const
Definition Decl.h:2247
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition Decl.cpp:3179
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:3226
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:2845
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition Decl.h:2725
A mutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5342
bool insert(const FunctionEffectWithCondition &NewEC, Conflicts &Errs)
Definition Type.cpp:5809
SmallVector< Conflict > Conflicts
Definition TypeBase.h:5374
An immutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5206
static FunctionParmPackExpr * Create(const ASTContext &Context, QualType T, ValueDecl *ParamPack, SourceLocation NameLoc, ArrayRef< ValueDecl * > Params)
Definition ExprCXX.cpp:1808
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5406
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition TypeBase.h:5910
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition TypeBase.h:5713
unsigned getNumParams() const
Definition TypeBase.h:5684
bool hasTrailingReturn() const
Whether this function prototype has a trailing return type.
Definition TypeBase.h:5826
const QualType * param_type_iterator
Definition TypeBase.h:5844
QualType getParamType(unsigned i) const
Definition TypeBase.h:5686
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5810
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5695
Expr * getNoexceptExpr() const
Return the expression inside noexcept(expression), or a null pointer if there is none (because the ex...
Definition TypeBase.h:5771
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5691
ArrayRef< QualType > exceptions() const
Definition TypeBase.h:5860
bool hasExtParameterInfos() const
Is there any interesting extra information for any of the parameters of this function type?
Definition TypeBase.h:5875
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:4825
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4602
CallingConv getCallConv() const
Definition TypeBase.h:4957
QualType getReturnType() const
Definition TypeBase.h:4942
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:2268
ImaginaryLiteral - We support imaginary integer and floating point literals, like "1....
Definition Expr.h:1737
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition Expr.cpp:2081
Represents an implicitly-generated value initialization of an object of a given type.
Definition Expr.h:6069
Represents a field injected from an anonymous union/struct into the parent scope.
Definition Decl.h:3511
ArrayRef< NamedDecl * > chain() const
Definition Decl.h:3532
void setInherited(bool I)
Definition Attr.h:163
Description of a constructor that was inherited from a base class.
Definition DeclCXX.h:2604
ConstructorUsingShadowDecl * getShadowDecl() const
Definition DeclCXX.h:2616
const TypeClass * getTypePtr() const
Definition TypeLoc.h:526
Describes an C or C++ initializer list.
Definition Expr.h:5314
unsigned getNumInits() const
Definition Expr.h:5347
const Expr * getInit(unsigned Init) const
Definition Expr.h:5369
child_range children()
Definition Expr.h:5510
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)
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.
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 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:981
An lvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3716
bool isInitCapture(const LambdaCapture *Capture) const
Determine whether one of this lambda's captures is an init-capture.
Definition ExprCXX.cpp:1365
capture_range captures() const
Retrieve this lambda's captures.
Definition ExprCXX.cpp:1378
@ 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:3036
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:3078
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.
SourceLocation getNameLoc() const
Gets the location of the identifier.
Definition Lookup.h:666
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:4370
static MSPropertyDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName N, QualType T, TypeSourceInfo *TInfo, SourceLocation StartL, IdentifierInfo *Getter, IdentifierInfo *Setter)
Definition DeclCXX.cpp:3780
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3370
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3453
Expr * getBase() const
Definition Expr.h:3447
SourceLocation getExprLoc() const LLVM_READONLY
Definition Expr.h:3565
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:3752
Describes a module or submodule.
Definition Module.h:340
StringRef getTopLevelModuleName() const
Retrieve the name of the top-level module.
Definition Module.h:950
bool isExplicitGlobalModule() const
Definition Module.h:441
This represents a decl that may have a name.
Definition Decl.h:274
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:487
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:295
bool isPlaceholderVar(const LangOptions &LangOpts) const
Definition Decl.cpp:1095
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:340
void setModulePrivate()
Specify that this declaration was marked as being private to the module in which it was defined.
Definition DeclBase.h:718
Represents a C++ namespace alias.
Definition DeclCXX.h:3222
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:573
NamespaceDecl * getNamespace()
Definition DeclCXX.cpp:3351
Represent a C++ namespace.
Definition Decl.h:592
bool isInline() const
Returns true if this is an inline namespace declaration.
Definition Decl.h:648
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:675
void setRBraceLoc(SourceLocation L)
Definition Decl.h:694
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.
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...
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:1184
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition Overload.h:1160
@ CSK_Normal
Normal lookup.
Definition Overload.h:1164
@ CSK_Operator
C++ [over.match.oper]: Lookup of operator function candidates in a call using operator syntax.
Definition Overload.h:1171
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition Overload.h:1376
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition Attr.h:279
static ParenListExpr * Create(const ASTContext &Ctx, SourceLocation LParenLoc, ArrayRef< Expr * > Exprs, SourceLocation RParenLoc)
Create a paren list.
Definition Expr.cpp:4979
Represents a parameter to a function.
Definition Decl.h:1819
void setDefaultArg(Expr *defarg)
Definition Decl.cpp:3001
void setUnparsedDefaultArg()
Specify that this parameter has an unparsed default argument.
Definition Decl.h:1960
bool hasUnparsedDefaultArg() const
Determines whether this parameter has a default argument that has not yet been parsed.
Definition Decl.h:1948
SourceRange getDefaultArgRange() const
Retrieve the source range that covers the entire default argument.
Definition Decl.cpp:3006
void setUninstantiatedDefaultArg(Expr *arg)
Definition Decl.cpp:3026
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition Decl.h:1852
bool hasUninstantiatedDefaultArg() const
Definition Decl.h:1952
bool hasInheritedDefaultArg() const
Definition Decl.h:1964
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:2936
Expr * getUninstantiatedDefaultArg()
Definition Decl.cpp:3031
bool hasDefaultArg() const
Determines whether this parameter has a default argument, either parsed or not.
Definition Decl.cpp:3037
void setHasInheritedDefaultArg(bool I=true)
Definition Decl.h:1968
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:2959
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:817
const ParsedAttr * getMSPropertyAttr() const
Definition ParsedAttr.h:903
bool hasAttribute(ParsedAttr::Kind K) const
Definition ParsedAttr.h:897
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:3393
QualType getPointeeType() const
Definition TypeBase.h:3403
IdentifierInfo * getIdentifierInfo(StringRef Name) const
Return information about the specified preprocessor identifier token.
IdentifierTable & getIdentifierTable()
ArrayRef< Expr * > semantics()
Definition Expr.h:6888
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:8573
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8578
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:8489
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8529
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:8674
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8583
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:8562
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition TypeBase.h:8535
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:2792
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:8654
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:3734
Represents a struct/union/class.
Definition Decl.h:4369
bool hasFlexibleArrayMember() const
Definition Decl.h:4402
bool hasObjectMember() const
Definition Decl.h:4429
field_iterator field_end() const
Definition Decl.h:4575
field_range fields() const
Definition Decl.h:4572
specific_decl_iterator< FieldDecl > field_iterator
Definition Decl.h:4569
RecordDecl * getDefinitionOrSelf() const
Definition Decl.h:4557
bool isAnonymousStructOrUnion() const
Whether this is an anonymous struct or union.
Definition Decl.h:4421
bool field_empty() const
Definition Decl.h:4580
field_iterator field_begin() const
Definition Decl.cpp:5275
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:5374
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3672
QualType getPointeeType() const
Definition TypeBase.h:3690
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:111
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition SemaBase.cpp:33
Sema & SemaRef
Definition SemaBase.h:40
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:1316
A RAII object to temporarily push a declaration context.
Definition Sema.h:3531
For a defaulted function, the kind of defaulted function that it is.
Definition Sema.h:6448
DefaultedComparisonKind asComparison() const
Definition Sema.h:6480
CXXSpecialMemberKind asSpecialMember() const
Definition Sema.h:6477
Records and restores the CurFPFeatures state on entry/exit of compound statements.
Definition Sema.h:14188
Helper class that collects exception specifications for implicitly-declared special member functions.
Definition Sema.h:5546
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:5588
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:9378
CXXMethodDecl * getMethod() const
Definition Sema.h:9390
RAII object to handle the state changes required to synthesize a function body.
Definition Sema.h:13678
Abstract base class used for diagnosing integer constant expression violations.
Definition Sema.h:7803
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:868
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:13196
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:6637
void ActOnParamUnparsedDefaultArgument(Decl *param, SourceLocation EqualLoc, SourceLocation ArgLoc)
ActOnParamUnparsedDefaultArgument - We've seen a default argument for a function parameter,...
DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD)
Determine the kind of defaulting that would be done for a given function.
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.
CXXSpecialMemberKind getSpecialMember(const CXXMethodDecl *MD)
Definition Sema.h:6399
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9420
@ LookupUsingDeclName
Look up all declarations in a scope with the given name, including resolved using declarations.
Definition Sema.h:9447
@ LookupLocalFriendName
Look up a friend of a local class.
Definition Sema.h:9455
@ LookupNamespaceName
Look up a namespace name within a C++ using directive or namespace alias definition,...
Definition Sema.h:9443
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9428
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:417
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:13815
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:1534
void CheckDelegatingCtorCycles()
SmallVector< CXXMethodDecl *, 4 > DelayedDllExportMemberFunctions
Definition Sema.h:6374
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:1263
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:6610
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:6591
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:1474
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:7924
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:1689
@ AR_accessible
Definition Sema.h:1687
@ AR_inaccessible
Definition Sema.h:1688
@ AR_delayed
Definition Sema.h:1690
DeclResult ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, unsigned TagSpec, SourceLocation TagLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, SourceLocation EllipsisLoc, const ParsedAttributesView &Attr, MultiTemplateParamsArg TempParamLists)
Handle a friend tag declaration where the scope specifier was templated.
Scope * getScopeForContext(DeclContext *Ctx)
Determines the active Scope associated with the given declaration context.
Definition Sema.cpp:2450
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:2077
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 SetFunctionBodyKind(Decl *D, SourceLocation Loc, FnBodyKind BodyKind, StringLiteral *DeletedMessage=nullptr)
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:4208
@ Default
= default ;
Definition Sema.h:4210
@ Delete
deleted-function-body
Definition Sema.h:4216
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:49
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:2078
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:1309
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:227
DeclarationNameInfo GetNameForDeclarator(Declarator &D)
GetNameForDeclarator - Determine the full declaration name for the given Declarator.
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:937
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:1519
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()
void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param)
This is used to implement the constant expression evaluation part of the attribute enable_if extensio...
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
void CleanupVarDeclMarking()
ASTContext & getASTContext() const
Definition Sema.h:940
ClassTemplateDecl * StdInitializerList
The C++ "std::initializer_list" template, which is defined in <initializer_list>.
Definition Sema.h:6617
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:6701
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:769
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.
std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths)
Builds a string representing ambiguous paths from a specific derived class to different subobjects of...
DefaultedComparisonKind
Kinds of defaulted comparison operator functions.
Definition Sema.h:6169
@ Relational
This is an <, <=, >, or >= that should be implemented as a rewrite in terms of a <=> comparison.
Definition Sema.h:6183
@ NotEqual
This is an operator!= that should be implemented as a rewrite in terms of a == comparison.
Definition Sema.h:6180
@ ThreeWay
This is an operator<=> that should be implemented as a series of subobject comparisons.
Definition Sema.h:6177
@ None
This is not a defaultable comparison operator.
Definition Sema.h:6171
@ Equal
This is an operator== that should be implemented as a series of subobject comparisons.
Definition Sema.h:6174
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:6632
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:1213
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:12298
EnumDecl * getStdAlignValT() const
void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record)
LangAS getDefaultCXXMethodAddrSpace() const
Returns default addr space for method qualifiers.
Definition Sema.cpp:1767
LazyDeclPtr StdBadAlloc
The C++ "std::bad_alloc" class, which is defined by the C++ standard library.
Definition Sema.h:8448
QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs, const DeclSpec *DS=nullptr)
void PushFunctionScope()
Enter a new function scope.
Definition Sema.cpp:2469
void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc)
void DefineImplicitCopyConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor)
DefineImplicitCopyConstructor - Checks for feasibility of defining this constructor as the copy const...
FPOptions & getCurFPFeatures()
Definition Sema.h:935
Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind=TU_Complete, CodeCompleteConsumer *CompletionConsumer=nullptr)
Definition Sema.cpp:272
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:83
@ UPPC_RequiresClause
Definition Sema.h:14608
@ UPPC_UsingDeclaration
A using declaration.
Definition Sema.h:14563
@ UPPC_ExceptionType
The type of an exception.
Definition Sema.h:14581
@ UPPC_Initializer
An initializer.
Definition Sema.h:14572
@ UPPC_BaseType
The base type of a class type.
Definition Sema.h:14542
@ UPPC_FriendDeclaration
A friend declaration.
Definition Sema.h:14566
@ UPPC_DefaultArgument
A default argument.
Definition Sema.h:14575
@ UPPC_DeclarationType
The type of an arbitrary declaration.
Definition Sema.h:14545
@ UPPC_DataMemberType
The type of a data member.
Definition Sema.h:14548
@ UPPC_StaticAssertExpression
The expression in a static assertion.
Definition Sema.h:14554
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:933
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:5948
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:2581
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:1308
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:1307
std::pair< Expr *, std::string > findFailedBooleanCondition(Expr *Cond)
Find the failed Boolean condition within a given Boolean constant expression, and describe it with a ...
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:6595
SemaHLSL & HLSL()
Definition Sema.h:1484
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:5954
void CheckCXXDefaultArguments(FunctionDecl *FD)
Helpers for dealing with blocks and functions.
ComparisonCategoryUsage
Definition Sema.h:5328
@ DefaultedOperator
A defaulted 'operator<=>' needed the comparison category.
Definition Sema.h:5335
SmallVector< InventedTemplateParameterInfo, 4 > InventedParameterInfos
Stack containing information needed when in C++2a an 'auto' is encountered in a function declaration ...
Definition Sema.h:6588
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:6693
llvm::DenseMap< ParmVarDecl *, SourceLocation > UnparsedDefaultArgLocs
Definition Sema.h:6625
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.
ExprResult ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr)
bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method)
Check whether 'this' shows up in the attributes of the given static member function.
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:13208
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:5944
ExprResult DefaultLvalueConversion(Expr *E)
Definition SemaExpr.cpp:647
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:15647
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:9948
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:7070
std::unique_ptr< RecordDeclSetTy > PureVirtualClassDiagSet
PureVirtualClassDiagSet - a set of class declarations which we have emitted a list of pure virtual fu...
Definition Sema.h:6602
void ActOnFinishInlineFunctionDef(FunctionDecl *D)
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition Sema.h:1447
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:6621
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:8263
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:14088
SourceManager & getSourceManager() const
Definition Sema.h:938
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,...
llvm::FoldingSet< SpecialMemberOverloadResultEntry > SpecialMemberCache
A cache of special member function overload resolution results for C++ records.
Definition Sema.h:9406
QualType BuildPackIndexingType(QualType Pattern, Expr *IndexExpr, SourceLocation Loc, SourceLocation EllipsisLoc, bool FullySubstituted=false, ArrayRef< QualType > Expansions={})
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.
Decl * ActOnExceptionDeclarator(Scope *S, Declarator &D)
ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch handler.
StringEvaluationContext
Definition Sema.h:6064
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:15602
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:6613
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:1585
ASTConsumer & Consumer
Definition Sema.h:1310
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:4708
void NoteDeletedFunction(FunctionDecl *FD)
Emit a note explaining that this function is deleted.
Definition SemaExpr.cpp:126
sema::AnalysisBasedWarnings AnalysisWarnings
Worker object for performing CFG-based warnings.
Definition Sema.h:1347
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:6823
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
Definition Sema.h:6833
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6802
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.
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:1268
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:1312
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)
void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method)
ActOnStartDelayedCXXMethodDeclaration - We have completed parsing a top-level (non-nested) C++ class,...
DiagnosticsEngine & Diags
Definition Sema.h:1311
FullExprArg MakeFullDiscardedValueExpr(Expr *Arg)
Definition Sema.h:7873
FPOptions CurFPFeatures
Definition Sema.h:1305
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:6597
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)
ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field)
Decl * ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList, SourceLocation SemiLoc)
Handle a C++11 empty-declaration and attribute-declaration.
friend class InitializationSequence
Definition Sema.h:1589
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:6629
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.
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:338
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:6373
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:6319
@ AbstractVariableType
Definition Sema.h:6323
@ AbstractReturnType
Definition Sema.h:6321
@ AbstractNone
Definition Sema.h:6320
@ AbstractFieldType
Definition Sema.h:6324
@ AbstractArrayType
Definition Sema.h:6327
@ AbstractParamType
Definition Sema.h:6322
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:8452
void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc)
CheckConstexprKind
Definition Sema.h:6508
@ CheckValid
Identify whether this function satisfies the formal rules for constexpr functions in the current lanu...
Definition Sema.h:6513
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
Definition Sema.h:6510
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:437
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:3524
DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class)
Look up the constructors for the given class.
void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record)
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:664
bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, ArrayRef< CXXCtorInitializer * > Initializers={})
void DiagnoseImmediateEscalatingReason(FunctionDecl *FD)
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition Sema.h:8748
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:1502
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:1805
bool isUnevaluated() const
Definition Expr.h:1927
StringRef getString() const
Definition Expr.h:1873
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3761
bool isBeingDefined() const
Return true if this decl is currently being defined.
Definition Decl.h:3882
StringRef getKindName() const
Definition Decl.h:3957
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3862
TagDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:4899
bool isUnion() const
Definition Decl.h:3972
TagKind getTagKind() const
Definition Decl.h:3961
bool isDependentType() const
Whether this declaration declares a type that is dependent, i.e., a type that somehow depends on temp...
Definition Decl.h:3907
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:105
Represents the declaration of a typedef-name via a C++11 alias-declaration.
Definition Decl.h:3732
static TypeAliasDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition Decl.cpp:5817
void setDescribedAliasTemplate(TypeAliasTemplateDecl *TAT)
Definition Decl.h:3751
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:3557
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
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:2766
SourceLocation getBeginLoc() const
Get the begin source location.
Definition TypeLoc.cpp:193
A container of type source information.
Definition TypeBase.h:8460
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:8471
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:551
The base class of the type hierarchy.
Definition TypeBase.h:1876
bool isVoidType() const
Definition TypeBase.h:9092
bool isBooleanType() const
Definition TypeBase.h:9229
const TemplateSpecializationType * getAsNonAliasTemplateSpecializationType() const
Look through sugar for an instance of TemplateSpecializationType which is not a type alias,...
Definition Type.cpp:1970
bool isIncompleteArrayType() const
Definition TypeBase.h:8833
bool isUndeducedAutoType() const
Definition TypeBase.h:8922
bool isRValueReferenceType() const
Definition TypeBase.h:8758
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:8825
bool isPointerType() const
Definition TypeBase.h:8726
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9136
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9386
bool isReferenceType() const
Definition TypeBase.h:8750
bool isEnumeralType() const
Definition TypeBase.h:8857
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:789
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:8754
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition TypeBase.h:9061
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2847
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition TypeBase.h:2466
QualType getCanonicalTypeInternal() const
Definition TypeBase.h:3184
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition TypeBase.h:9272
bool isFunctionProtoType() const
Definition TypeBase.h:2662
bool isOverloadableType() const
Determines whether this is a type for which one can define an overloaded operator.
Definition TypeBase.h:9242
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition TypeBase.h:2865
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9235
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition Type.h:53
bool isFunctionType() const
Definition TypeBase.h:8722
bool isStructureOrClassType() const
Definition Type.cpp:743
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2409
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:2986
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:2336
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9319
bool isRecordType() const
Definition TypeBase.h:8853
bool isUnionType() const
Definition Type.cpp:755
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3606
QualType getUnderlyingType() const
Definition Decl.h:3661
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:2291
Opcode getOpcode() const
Definition Expr.h:2286
static bool isIncrementDecrementOp(Opcode Op)
Definition Expr.h:2346
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:5164
Represents a C++ unqualified-id that has been parsed.
Definition DeclSpec.h:1088
UnionParsedType ConversionFunctionId
When Kind == IK_ConversionFunctionId, the type that the conversion function names.
Definition DeclSpec.h:1124
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:1300
SourceRange getSourceRange() const LLVM_READONLY
Return the source range that covers this unqualified-id.
Definition DeclSpec.h:1297
UnionParsedType DestructorName
When Kind == IK_DestructorName, the type referred to by the class-name.
Definition DeclSpec.h:1132
SourceLocation StartLocation
The location of the first token that describes this unqualified-id, which will be the location of the...
Definition DeclSpec.h:1146
UnionParsedTemplateTy TemplateName
When Kind == IK_DeductionGuideName, the parsed template-name.
Definition DeclSpec.h:1135
const IdentifierInfo * Identifier
When Kind == IK_Identifier, the parsed identifier, or when Kind == IK_UserLiteralId,...
Definition DeclSpec.h:1116
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition DeclSpec.h:1170
TemplateIdAnnotation * TemplateId
When Kind == IK_TemplateId or IK_ConstructorTemplateId, the template-id annotation that contains the ...
Definition DeclSpec.h:1140
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:437
A set of unresolved declarations.
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:4139
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:3612
bool hasTypename() const
Return true if the using declaration has 'typename'.
Definition DeclCXX.h:3661
NestedNameSpecifier getQualifier() const
Retrieve the nested-name-specifier that qualifies the name.
Definition DeclCXX.h:3649
DeclarationNameInfo getNameInfo() const
Definition DeclCXX.h:3653
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:3639
Represents C++ using-directive.
Definition DeclCXX.h:3117
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:3813
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:3420
static UsingShadowDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation Loc, DeclarationName Name, BaseUsingDecl *Introducer, NamedDecl *Target)
Definition DeclCXX.h:3456
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition DeclCXX.h:3484
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:712
void setType(QualType newType)
Definition Decl.h:724
QualType getType() const
Definition Decl.h:723
bool isParameterPack() const
Determine whether this value is actually a function parameter pack, init-capture pack,...
Definition Decl.cpp:5593
Represents a variable declaration or definition.
Definition Decl.h:932
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition Decl.cpp:2773
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition Decl.cpp:2132
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition Decl.h:1593
DefinitionKind isThisDeclarationADefinition(ASTContext &) const
Check whether this declaration is a definition.
Definition Decl.cpp:2241
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:2171
bool isNoDestroy(const ASTContext &) const
Is destruction of this variable entirely suppressed?
Definition Decl.cpp:2799
void setCXXCondDecl()
Definition Decl.h:1639
bool isInlineSpecified() const
Definition Decl.h:1578
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1306
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition Decl.h:1247
bool evaluateDestruction(SmallVectorImpl< PartialDiagnosticAt > &Notes) const
Evaluate the destruction of this variable to determine if it constitutes constant destruction.
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition Decl.h:1214
QualType::DestructionKind needsDestruction(const ASTContext &Ctx) const
Would the destruction of this variable have any effect, and if so, what kind?
Definition Decl.cpp:2814
ThreadStorageClassSpecifier getTSCSpec() const
Definition Decl.h:1183
const Expr * getInit() const
Definition Decl.h:1391
const APValue * evaluateValue() const
Attempt to evaluate the value of the initializer attached to this declaration, and produce notes expl...
Definition Decl.cpp:2556
@ TLS_Dynamic
TLS with a dynamic initializer.
Definition Decl.h:958
void setInit(Expr *I)
Definition Decl.cpp:2458
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition Decl.h:1174
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:2509
void setExceptionVariable(bool EV)
Definition Decl.h:1521
Declaration of a variable template.
Represents a GCC generic vector type.
Definition TypeBase.h:4274
unsigned getNumElements() const
Definition TypeBase.h:4289
QualType getElementType() const
Definition TypeBase.h:4288
Represents a C++11 virt-specifier-seq.
Definition DeclSpec.h:2881
SourceLocation getOverrideLoc() const
Definition DeclSpec.h:2901
SourceLocation getLastLocation() const
Definition DeclSpec.h:2913
bool isOverrideSpecified() const
Definition DeclSpec.h:2900
SourceLocation getFinalLoc() const
Definition DeclSpec.h:2905
bool isFinalSpecified() const
Definition DeclSpec.h:2903
bool isFinalSpelledSealed() const
Definition DeclSpec.h:2904
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:1191
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:975
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.
The JSON file list parser is used to communicate input to InstallAPI.
bool FTIHasNonVoidParameters(const DeclaratorChunk::FunctionTypeInfo &FTI)
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
@ 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:833
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:829
@ Overload
This is a legitimate overload: the existing declarations are functions or function templates with dif...
Definition Sema.h:825
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:213
@ CPlusPlus23
@ CPlusPlus20
@ CPlusPlus
@ CPlusPlus11
@ 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:512
ConstexprSpecKind
Define the kind of constexpr specifier.
Definition Specifiers.h:36
LinkageSpecLanguageIDs
Represents the language in a linkage specification.
Definition DeclCXX.h:3028
@ 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:666
InClassInitStyle
In-class initialization styles for non-static data members.
Definition Specifiers.h:272
@ ICIS_ListInit
Direct list-initialization.
Definition Specifiers.h:275
@ ICIS_NoInit
No in-class initializer.
Definition Specifiers.h:273
@ RQ_None
No ref-qualifier was provided.
Definition TypeBase.h:1798
@ RQ_RValue
An rvalue ref-qualifier was provided (&&).
Definition TypeBase.h:1804
@ 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:1543
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition Specifiers.h:152
@ Redeclaration
Merge availability attributes for a redeclaration, which requires an exact match.
Definition Sema.h:632
std::pair< llvm::PointerUnion< const TemplateTypeParmType *, NamedDecl *, const TemplateSpecializationType *, const SubstBuiltinTemplatePackType * >, SourceLocation > UnexpandedParameterPack
Definition Sema.h:237
@ 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:1084
@ IK_ImplicitSelfParam
An implicit 'self' parameter.
Definition DeclSpec.h:1082
@ IK_TemplateId
A template-id, e.g., f<int>.
Definition DeclSpec.h:1080
@ IK_ConstructorTemplateId
A constructor named via a template-id.
Definition DeclSpec.h:1076
@ IK_ConstructorName
A constructor name.
Definition DeclSpec.h:1074
@ IK_LiteralOperatorId
A user-defined literal name, e.g., operator "" _i.
Definition DeclSpec.h:1072
@ IK_Identifier
An identifier.
Definition DeclSpec.h:1066
@ IK_DestructorName
A destructor name.
Definition DeclSpec.h:1078
@ IK_OperatorFunctionId
An overloaded operator name, e.g., operator+.
Definition DeclSpec.h:1068
@ IK_ConversionFunctionId
A conversion function name, e.g., operator int.
Definition DeclSpec.h:1070
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition Specifiers.h:124
@ AS_public
Definition Specifiers.h:125
@ AS_protected
Definition Specifiers.h:126
@ AS_none
Definition Specifiers.h:128
@ AS_private
Definition Specifiers.h:127
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:249
@ SC_Static
Definition Specifiers.h:253
@ SC_None
Definition Specifiers.h:251
ComparisonCategoryType commonComparisonType(ComparisonCategoryType A, ComparisonCategoryType B)
Determine the common comparison type, as defined in C++2a [class.spaceship]p4.
Expr * Cond
};
@ 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:6030
@ Interface
The "__interface" keyword.
Definition TypeBase.h:6035
@ Struct
The "struct" keyword.
Definition TypeBase.h:6032
@ Class
The "class" keyword.
Definition TypeBase.h:6041
ExprResult ExprError()
Definition Ownership.h:265
@ Keyword
The name has been typo-corrected to a keyword.
Definition Sema.h:561
@ Type
The name was classified as a type.
Definition Sema.h:563
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:4348
@ CanNeverPassInRegs
The argument of this type cannot be passed directly in registers.
Definition Decl.h:4362
@ CannotPassInRegs
The argument of this type cannot be passed directly in registers.
Definition Decl.h:4357
AllowFoldKind
Definition Sema.h:654
@ 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.
CXXSpecialMemberKind
Kinds of C++ special members.
Definition Sema.h:426
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:133
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:136
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition Specifiers.h:145
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition Specifiers.h:140
SmallVector< CXXBaseSpecifier *, 4 > CXXCastPath
A simple array of base specifiers.
Definition ASTContext.h:147
TypeAwareAllocationMode
Definition ExprCXX.h:2254
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition DeclBase.h:1305
DynamicRecursiveASTVisitorBase< false > DynamicRecursiveASTVisitor
TrivialABIHandling
Definition Sema.h:644
@ ConsiderTrivialABI
The triviality of a method affected by "trivial_abi".
Definition Sema.h:649
@ IgnoreTrivialABI
The triviality of a method unaffected by "trivial_abi".
Definition Sema.h:646
@ Incomplete
Template argument deduction did not deduce a value for every template parameter.
Definition Sema.h:378
@ Success
Template argument deduction was successful.
Definition Sema.h:370
@ Inconsistent
Template argument deduction produced inconsistent deduced values for the given template parameter.
Definition Sema.h:384
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition Specifiers.h:189
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition Specifiers.h:207
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition Specifiers.h:203
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition Specifiers.h:199
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:195
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition Specifiers.h:192
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:279
TypeAwareAllocationMode typeAwareAllocationModeFromBool(bool IsTypeAwareAllocation)
Definition ExprCXX.h:2261
U cast(CodeGen::Address addr)
Definition Address.h:327
@ StaticAssertMessageData
Call to data() in a static assert message.
Definition Sema.h:848
@ StaticAssertMessageSize
Call to size() in a static assert message.
Definition Sema.h:846
@ ExplicitBool
Condition in an explicit(bool) specifier.
Definition Sema.h:844
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:6005
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:6026
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6016
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6019
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:178
__packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 __packed_splat2 __packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 uint32_t
#define false
Definition stdbool.h:26
#define true
Definition stdbool.h:25
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition ASTConcept.h:91
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:1461
ParamInfo * Params
Params - This is a pointer to a new[]'d array of ParamInfo objects that describe the parameters speci...
Definition DeclSpec.h:1521
unsigned RefQualifierIsLValueRef
Whether the ref-qualifier (if any) is an lvalue reference.
Definition DeclSpec.h:1470
DeclSpec * MethodQualifiers
DeclSpec for the function with the qualifier related info.
Definition DeclSpec.h:1524
SourceLocation getRefQualifierLoc() const
Retrieve the location of the ref-qualifier, if any.
Definition DeclSpec.h:1622
unsigned NumParams
NumParams - This is the number of formal parameters specified by the declarator.
Definition DeclSpec.h:1496
bool hasMutableQualifier() const
Determine whether this lambda-declarator contains a 'mutable' qualifier.
Definition DeclSpec.h:1651
bool hasMethodTypeQualifiers() const
Determine whether this method has qualifiers.
Definition DeclSpec.h:1654
void freeParams()
Reset the parameter list to having zero parameters.
Definition DeclSpec.h:1560
bool hasRefQualifier() const
Determine whether this function declaration contains a ref-qualifier.
Definition DeclSpec.h:1647
std::unique_ptr< CachedTokens > DefaultArgTokens
DefaultArgTokens - When the parameter's default argument cannot be parsed immediately (because it occ...
Definition DeclSpec.h:1436
One instance of this struct is used for each type in a declarator that is parsed.
Definition DeclSpec.h:1336
SourceRange getSourceRange() const
Definition DeclSpec.h:1348
FunctionTypeInfo Fun
Definition DeclSpec.h:1735
enum clang::DeclaratorChunk::@340323374315200305336204205154073066142310370142 Kind
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:652
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:5463
FunctionDecl * SourceDecl
The function whose exception specification this is, for EST_Unevaluated and EST_Uninstantiated.
Definition TypeBase.h:5475
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition TypeBase.h:5465
ArrayRef< QualType > Exceptions
Explicitly-specified list of exception types.
Definition TypeBase.h:5468
Expr * NoexceptExpr
Noexcept expression, if this is a computed noexcept specification.
Definition TypeBase.h:5471
Extra information about a function prototype.
Definition TypeBase.h:5491
static StringRef getTagTypeKindName(TagTypeKind Kind)
Definition TypeBase.h:6069
static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag)
Converts a TagTypeKind into an elaborated type keyword.
Definition Type.cpp:3389
static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into a tag type kind.
Definition Type.cpp:3371
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:13247
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
SourceLocation PointOfInstantiation
The point of instantiation or synthesis within the source code.
Definition Sema.h:13378
@ MarkingClassDllexported
We are marking a class as __dllexport.
Definition Sema.h:13338
@ InitializingStructuredBinding
We are initializing a structured binding.
Definition Sema.h:13335
@ ExceptionSpecEvaluation
We are computing the exception specification for a defaulted special member function.
Definition Sema.h:13291
@ DeclaringImplicitEqualityComparison
We are declaring an implicit 'operator==' for a defaulted 'operator<=>'.
Definition Sema.h:13309
Decl * Entity
The entity that is being synthesized.
Definition Sema.h:13381
Abstract class used to diagnose incomplete types.
Definition Sema.h:8344
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.
SourceLocation TemplateNameLoc
TemplateNameLoc - The location of the template name within the source.
SourceLocation RAngleLoc
The location of the '>' after the template argument list.
SourceLocation LAngleLoc
The location of the '<' before the template argument list.
OpaquePtr< T > get() const
Definition Ownership.h:105