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 if (PrevForDefaultArgs->getFriendObjectKind()) {
518 // Don't inherit default arguments from a friend declaration. It's invalid
519 // to redeclare such a function at all if it owns the default arguments;
520 // we check for that later. Otherwise, it's not the declaration that we're
521 // inheriting them from.
522 continue;
523 }
524
525 // We found the right previous declaration.
526 break;
527 }
528
529 // C++ [dcl.fct.default]p4:
530 // For non-template functions, default arguments can be added in
531 // later declarations of a function in the same
532 // scope. Declarations in different scopes have completely
533 // distinct sets of default arguments. That is, declarations in
534 // inner scopes do not acquire default arguments from
535 // declarations in outer scopes, and vice versa. In a given
536 // function declaration, all parameters subsequent to a
537 // parameter with a default argument shall have default
538 // arguments supplied in this or previous declarations. A
539 // default argument shall not be redefined by a later
540 // declaration (not even to the same value).
541 //
542 // C++ [dcl.fct.default]p6:
543 // Except for member functions of class templates, the default arguments
544 // in a member function definition that appears outside of the class
545 // definition are added to the set of default arguments provided by the
546 // member function declaration in the class definition.
547 for (unsigned p = 0, NumParams = PrevForDefaultArgs
548 ? PrevForDefaultArgs->getNumParams()
549 : 0;
550 p < NumParams; ++p) {
551 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
552 ParmVarDecl *NewParam = New->getParamDecl(p);
553
554 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
555 bool NewParamHasDfl = NewParam->hasDefaultArg();
556
557 if (OldParamHasDfl && NewParamHasDfl) {
558 unsigned DiagDefaultParamID =
559 diag::err_param_default_argument_redefinition;
560
561 // MSVC accepts that default parameters be redefined for member functions
562 // of template class. The new default parameter's value is ignored.
563 Invalid = true;
564 if (getLangOpts().MicrosoftExt) {
565 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
566 if (MD && MD->getParent()->getDescribedClassTemplate()) {
567 // Merge the old default argument into the new parameter.
568 NewParam->setHasInheritedDefaultArg();
569 if (OldParam->hasUninstantiatedDefaultArg())
571 OldParam->getUninstantiatedDefaultArg());
572 else
573 NewParam->setDefaultArg(OldParam->getInit());
574 DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
575 Invalid = false;
576 }
577 }
578
579 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
580 // hint here. Alternatively, we could walk the type-source information
581 // for NewParam to find the last source location in the type... but it
582 // isn't worth the effort right now. This is the kind of test case that
583 // is hard to get right:
584 // int f(int);
585 // void g(int (*fp)(int) = f);
586 // void g(int (*fp)(int) = &f);
587 Diag(NewParam->getLocation(), DiagDefaultParamID)
588 << NewParam->getDefaultArgRange();
589
590 // Look for the function declaration where the default argument was
591 // actually written, which may be a declaration prior to Old.
592 for (auto Older = PrevForDefaultArgs;
593 OldParam->hasInheritedDefaultArg(); /**/) {
594 Older = Older->getPreviousDecl();
595 OldParam = Older->getParamDecl(p);
596 }
597
598 Diag(OldParam->getLocation(), diag::note_previous_definition)
599 << OldParam->getDefaultArgRange();
600 } else if (OldParamHasDfl) {
601 // Merge the old default argument into the new parameter unless the new
602 // function is a friend declaration in a template class. In the latter
603 // case the default arguments will be inherited when the friend
604 // declaration will be instantiated.
605 if (New->getFriendObjectKind() == Decl::FOK_None ||
606 !New->getLexicalDeclContext()->isDependentContext()) {
607 // It's important to use getInit() here; getDefaultArg()
608 // strips off any top-level ExprWithCleanups.
609 NewParam->setHasInheritedDefaultArg();
610 if (OldParam->hasUnparsedDefaultArg())
611 NewParam->setUnparsedDefaultArg();
612 else if (OldParam->hasUninstantiatedDefaultArg())
614 OldParam->getUninstantiatedDefaultArg());
615 else
616 NewParam->setDefaultArg(OldParam->getInit());
617 }
618 } else if (NewParamHasDfl) {
619 if (New->getDescribedFunctionTemplate()) {
620 // Paragraph 4, quoted above, only applies to non-template functions.
621 Diag(NewParam->getLocation(),
622 diag::err_param_default_argument_template_redecl)
623 << NewParam->getDefaultArgRange();
624 Diag(PrevForDefaultArgs->getLocation(),
625 diag::note_template_prev_declaration)
626 << false;
627 } else if (New->getTemplateSpecializationKind()
629 New->getTemplateSpecializationKind() != TSK_Undeclared) {
630 // C++ [temp.expr.spec]p21:
631 // Default function arguments shall not be specified in a declaration
632 // or a definition for one of the following explicit specializations:
633 // - the explicit specialization of a function template;
634 // - the explicit specialization of a member function template;
635 // - the explicit specialization of a member function of a class
636 // template where the class template specialization to which the
637 // member function specialization belongs is implicitly
638 // instantiated.
639 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
640 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
641 << New->getDeclName()
642 << NewParam->getDefaultArgRange();
643 } else if (New->getDeclContext()->isDependentContext()) {
644 // C++ [dcl.fct.default]p6 (DR217):
645 // Default arguments for a member function of a class template shall
646 // be specified on the initial declaration of the member function
647 // within the class template.
648 //
649 // Reading the tea leaves a bit in DR217 and its reference to DR205
650 // leads me to the conclusion that one cannot add default function
651 // arguments for an out-of-line definition of a member function of a
652 // dependent type.
653 int WhichKind = 2;
655 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
656 if (Record->getDescribedClassTemplate())
657 WhichKind = 0;
659 WhichKind = 1;
660 else
661 WhichKind = 2;
662 }
663
664 Diag(NewParam->getLocation(),
665 diag::err_param_default_argument_member_template_redecl)
666 << WhichKind
667 << NewParam->getDefaultArgRange();
668 }
669 }
670 }
671
672 // DR1344: If a default argument is added outside a class definition and that
673 // default argument makes the function a special member function, the program
674 // is ill-formed. This can only happen for constructors.
676 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
678 cast<CXXMethodDecl>(New)->getSpecialMemberKind(),
679 OldSM =
680 cast<CXXMethodDecl>(Old)->getSpecialMemberKind();
681 if (NewSM != OldSM) {
682 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
683 assert(NewParam->hasDefaultArg());
684 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
685 << NewParam->getDefaultArgRange() << NewSM;
686 Diag(Old->getLocation(), diag::note_previous_declaration);
687 }
688 }
689
690 const FunctionDecl *Def;
691 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
692 // template has a constexpr specifier then all its declarations shall
693 // contain the constexpr specifier.
694 if (New->getConstexprKind() != Old->getConstexprKind()) {
695 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
696 << New << static_cast<int>(New->getConstexprKind())
697 << static_cast<int>(Old->getConstexprKind());
698 Diag(Old->getLocation(), diag::note_previous_declaration);
699 Invalid = true;
700 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
701 Old->isDefined(Def) &&
702 // If a friend function is inlined but does not have 'inline'
703 // specifier, it is a definition. Do not report attribute conflict
704 // in this case, redefinition will be diagnosed later.
705 (New->isInlineSpecified() ||
706 New->getFriendObjectKind() == Decl::FOK_None)) {
707 // C++11 [dcl.fcn.spec]p4:
708 // If the definition of a function appears in a translation unit before its
709 // first declaration as inline, the program is ill-formed.
710 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
711 Diag(Def->getLocation(), diag::note_previous_definition);
712 Invalid = true;
713 }
714
715 // C++17 [temp.deduct.guide]p3:
716 // Two deduction guide declarations in the same translation unit
717 // for the same class template shall not have equivalent
718 // parameter-declaration-clauses.
720 !New->isFunctionTemplateSpecialization() && isVisible(Old)) {
721 Diag(New->getLocation(), diag::err_deduction_guide_redeclared);
722 Diag(Old->getLocation(), diag::note_previous_declaration);
723 }
724
725 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
726 // argument expression, that declaration shall be a definition and shall be
727 // the only declaration of the function or function template in the
728 // translation unit.
731 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
732 Diag(Old->getLocation(), diag::note_previous_declaration);
733 Invalid = true;
734 }
735
736 // C++11 [temp.friend]p4 (DR329):
737 // When a function is defined in a friend function declaration in a class
738 // template, the function is instantiated when the function is odr-used.
739 // The same restrictions on multiple declarations and definitions that
740 // apply to non-template function declarations and definitions also apply
741 // to these implicit definitions.
742 const FunctionDecl *OldDefinition = nullptr;
743 if (New->isThisDeclarationInstantiatedFromAFriendDefinition() &&
744 Old->isDefined(OldDefinition, true))
745 CheckForFunctionRedefinition(New, OldDefinition);
746
747 return Invalid;
748}
749
752 ? diag::warn_cxx23_placeholder_var_definition
753 : diag::ext_placeholder_var_definition);
754}
755
756NamedDecl *
758 MultiTemplateParamsArg TemplateParamLists) {
759 assert(D.isDecompositionDeclarator());
761
762 // The syntax only allows a decomposition declarator as a simple-declaration,
763 // a for-range-declaration, or a condition in Clang, but we parse it in more
764 // cases than that.
766 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
767 << Decomp.getSourceRange();
768 return nullptr;
769 }
770
771 if (!TemplateParamLists.empty()) {
772 // C++17 [temp]/1:
773 // A template defines a family of class, functions, or variables, or an
774 // alias for a family of types.
775 //
776 // Structured bindings are not included.
777 Diag(TemplateParamLists.front()->getTemplateLoc(),
778 diag::err_decomp_decl_template);
779 return nullptr;
780 }
781
782 unsigned DiagID;
784 DiagID = diag::compat_pre_cxx17_decomp_decl;
786 DiagID = getLangOpts().CPlusPlus26
787 ? diag::compat_cxx26_decomp_decl_cond
788 : diag::compat_pre_cxx26_decomp_decl_cond;
789 else
790 DiagID = diag::compat_cxx17_decomp_decl;
791
792 Diag(Decomp.getLSquareLoc(), DiagID) << Decomp.getSourceRange();
793
794 // The semantic context is always just the current context.
795 DeclContext *const DC = CurContext;
796
797 // C++17 [dcl.dcl]/8:
798 // The decl-specifier-seq shall contain only the type-specifier auto
799 // and cv-qualifiers.
800 // C++20 [dcl.dcl]/8:
801 // If decl-specifier-seq contains any decl-specifier other than static,
802 // thread_local, auto, or cv-qualifiers, the program is ill-formed.
803 // C++23 [dcl.pre]/6:
804 // Each decl-specifier in the decl-specifier-seq shall be static,
805 // thread_local, auto (9.2.9.6 [dcl.spec.auto]), or a cv-qualifier.
806 // C++23 [dcl.pre]/7:
807 // Each decl-specifier in the decl-specifier-seq shall be constexpr,
808 // constinit, static, thread_local, auto, or a cv-qualifier
809 auto &DS = D.getDeclSpec();
810 auto DiagBadSpecifier = [&](StringRef Name, SourceLocation Loc) {
811 Diag(Loc, diag::err_decomp_decl_spec) << Name;
812 };
813
814 auto DiagCpp20Specifier = [&](StringRef Name, SourceLocation Loc) {
815 DiagCompat(Loc, diag_compat::decomp_decl_spec) << Name;
816 };
817
818 if (auto SCS = DS.getStorageClassSpec()) {
819 if (SCS == DeclSpec::SCS_static)
820 DiagCpp20Specifier(DeclSpec::getSpecifierName(SCS),
821 DS.getStorageClassSpecLoc());
822 else
823 DiagBadSpecifier(DeclSpec::getSpecifierName(SCS),
824 DS.getStorageClassSpecLoc());
825 }
826 if (auto TSCS = DS.getThreadStorageClassSpec())
827 DiagCpp20Specifier(DeclSpec::getSpecifierName(TSCS),
828 DS.getThreadStorageClassSpecLoc());
829
830 if (DS.isInlineSpecified())
831 DiagBadSpecifier("inline", DS.getInlineSpecLoc());
832
833 if (ConstexprSpecKind ConstexprSpec = DS.getConstexprSpecifier();
834 ConstexprSpec != ConstexprSpecKind::Unspecified) {
835 if (ConstexprSpec == ConstexprSpecKind::Consteval ||
837 DiagBadSpecifier(DeclSpec::getSpecifierName(ConstexprSpec),
838 DS.getConstexprSpecLoc());
839 }
840
841 // We can't recover from it being declared as a typedef.
842 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
843 return nullptr;
844
845 // C++2a [dcl.struct.bind]p1:
846 // A cv that includes volatile is deprecated
847 if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) &&
849 Diag(DS.getVolatileSpecLoc(),
850 diag::warn_deprecated_volatile_structured_binding);
851
853 QualType R = TInfo->getType();
854
857 D.setInvalidType();
858
859 // The syntax only allows a single ref-qualifier prior to the decomposition
860 // declarator. No other declarator chunks are permitted. Also check the type
861 // specifier here.
862 if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
863 D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
864 (D.getNumTypeObjects() == 1 &&
866 Diag(Decomp.getLSquareLoc(),
867 (D.hasGroupingParens() ||
868 (D.getNumTypeObjects() &&
870 ? diag::err_decomp_decl_parens
871 : diag::err_decomp_decl_type)
872 << R;
873
874 // In most cases, there's no actual problem with an explicitly-specified
875 // type, but a function type won't work here, and ActOnVariableDeclarator
876 // shouldn't be called for such a type.
877 if (R->isFunctionType())
878 D.setInvalidType();
879 }
880
881 // Constrained auto is prohibited by [decl.pre]p6, so check that here.
882 if (DS.isConstrainedAuto()) {
883 TemplateIdAnnotation *TemplRep = DS.getRepAsTemplateId();
884 assert(TemplRep->Kind == TNK_Concept_template &&
885 "No other template kind should be possible for a constrained auto");
886
887 SourceRange TemplRange{TemplRep->TemplateNameLoc,
888 TemplRep->RAngleLoc.isValid()
889 ? TemplRep->RAngleLoc
890 : TemplRep->TemplateNameLoc};
891 Diag(TemplRep->TemplateNameLoc, diag::err_decomp_decl_constraint)
892 << TemplRange << FixItHint::CreateRemoval(TemplRange);
893 }
894
895 // Build the BindingDecls.
897
898 // Build the BindingDecls.
899 for (auto &B : D.getDecompositionDeclarator().bindings()) {
900 // Check for name conflicts.
901 DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
902 IdentifierInfo *VarName = B.Name;
903 assert(VarName && "Cannot have an unnamed binding declaration");
904
908 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
909
910 // It's not permitted to shadow a template parameter name.
911 if (Previous.isSingleResult() &&
912 Previous.getFoundDecl()->isTemplateParameter()) {
913 DiagnoseTemplateParameterShadow(B.NameLoc, Previous.getFoundDecl());
914 Previous.clear();
915 }
916
917 QualType QT;
918 if (B.EllipsisLoc.isValid()) {
919 if (!cast<Decl>(DC)->isTemplated())
920 Diag(B.EllipsisLoc, diag::err_pack_outside_template);
921 QT = Context.getPackExpansionType(Context.DependentTy, std::nullopt,
922 /*ExpectsPackInType=*/false);
923 }
924
925 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name, QT);
926
927 if (BD->isParameterPack()) {
929 CSI->LocalPacks.push_back(BD);
930 }
931
932 ProcessDeclAttributeList(S, BD, *B.Attrs);
933
934 // Find the shadowed declaration before filtering for scope.
935 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
937 : nullptr;
938
939 bool ConsiderLinkage = DC->isFunctionOrMethod() &&
940 DS.getStorageClassSpec() == DeclSpec::SCS_extern;
941 FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
942 /*AllowInlineNamespace*/false);
943
944 bool IsPlaceholder = DS.getStorageClassSpec() != DeclSpec::SCS_static &&
945 DC->isFunctionOrMethod() && VarName->isPlaceholder();
946 if (!Previous.empty()) {
947 if (IsPlaceholder) {
948 bool sameDC = (Previous.end() - 1)
949 ->getDeclContext()
950 ->getRedeclContext()
951 ->Equals(DC->getRedeclContext());
952 if (sameDC &&
953 isDeclInScope(*(Previous.end() - 1), CurContext, S, false)) {
954 Previous.clear();
956 }
957 } else {
958 auto *Old = Previous.getRepresentativeDecl();
959 Diag(B.NameLoc, diag::err_redefinition) << B.Name;
960 Diag(Old->getLocation(), diag::note_previous_definition);
961 }
962 } else if (ShadowedDecl && !D.isRedeclaration()) {
963 CheckShadow(BD, ShadowedDecl, Previous);
964 }
965 PushOnScopeChains(BD, S, true);
966 Bindings.push_back(BD);
967 ParsingInitForAutoVars.insert(BD);
968 }
969
970 // There are no prior lookup results for the variable itself, because it
971 // is unnamed.
972 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
973 Decomp.getLSquareLoc());
976
977 // Build the variable that holds the non-decomposed object.
978 bool AddToScope = true;
979 NamedDecl *New =
980 ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
981 MultiTemplateParamsArg(), AddToScope, Bindings);
982 if (AddToScope) {
983 S->AddDecl(New);
984 CurContext->addHiddenDecl(New);
985 }
986
987 if (OpenMP().isInOpenMPDeclareTargetContext())
988 OpenMP().checkDeclIsAllowedInOpenMPTarget(nullptr, New);
989
990 return New;
991}
992
993// Check the arity of the structured bindings.
994// Create the resolved pack expr if needed.
996 QualType DecompType,
998 unsigned MemberCount) {
999 auto BindingWithPackItr = llvm::find_if(
1000 Bindings, [](BindingDecl *D) -> bool { return D->isParameterPack(); });
1001 bool HasPack = BindingWithPackItr != Bindings.end();
1002 bool IsValid;
1003 if (!HasPack) {
1004 IsValid = Bindings.size() == MemberCount;
1005 } else {
1006 // There may not be more members than non-pack bindings.
1007 IsValid = MemberCount >= Bindings.size() - 1;
1008 }
1009
1010 if (IsValid && HasPack) {
1011 // Create the pack expr and assign it to the binding.
1012 unsigned PackSize = MemberCount - Bindings.size() + 1;
1013
1014 BindingDecl *BPack = *BindingWithPackItr;
1015 BPack->setDecomposedDecl(DD);
1016 SmallVector<ValueDecl *, 8> NestedBDs(PackSize);
1017 // Create the nested BindingDecls.
1018 for (unsigned I = 0; I < PackSize; ++I) {
1019 BindingDecl *NestedBD = BindingDecl::Create(
1020 S.Context, BPack->getDeclContext(), BPack->getLocation(),
1021 BPack->getIdentifier(), QualType());
1022 NestedBD->setDecomposedDecl(DD);
1023 NestedBDs[I] = NestedBD;
1024 }
1025
1027 S.Context.DependentTy, PackSize, /*ExpectsPackInType=*/false);
1028 auto *PackExpr = FunctionParmPackExpr::Create(
1029 S.Context, PackType, BPack, BPack->getBeginLoc(), NestedBDs);
1030 BPack->setBinding(PackType, PackExpr);
1031 }
1032
1033 if (IsValid)
1034 return false;
1035
1036 S.Diag(DD->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1037 << DecompType << (unsigned)Bindings.size() << MemberCount << MemberCount
1038 << (MemberCount < Bindings.size());
1039 return true;
1040}
1041
1044 QualType DecompType, const llvm::APSInt &NumElemsAPS, QualType ElemType,
1045 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
1046 unsigned NumElems = (unsigned)NumElemsAPS.getLimitedValue(UINT_MAX);
1047 auto *DD = cast<DecompositionDecl>(Src);
1048
1049 if (CheckBindingsCount(S, DD, DecompType, Bindings, NumElems))
1050 return true;
1051
1052 unsigned I = 0;
1053 for (auto *B : DD->flat_bindings()) {
1054 SourceLocation Loc = B->getLocation();
1055 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1056 if (E.isInvalid())
1057 return true;
1058 E = GetInit(Loc, E.get(), I++);
1059 if (E.isInvalid())
1060 return true;
1061 B->setBinding(ElemType, E.get());
1062 }
1063
1064 return false;
1065}
1066
1069 ValueDecl *Src, QualType DecompType,
1070 const llvm::APSInt &NumElems,
1071 QualType ElemType) {
1073 S, Bindings, Src, DecompType, NumElems, ElemType,
1074 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
1075 ExprResult E = S.ActOnIntegerConstant(Loc, I);
1076 if (E.isInvalid())
1077 return ExprError();
1078 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
1079 });
1080}
1081
1083 ValueDecl *Src, QualType DecompType,
1084 const ConstantArrayType *CAT) {
1085 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
1086 llvm::APSInt(CAT->getSize()),
1087 CAT->getElementType());
1088}
1089
1091 ValueDecl *Src, QualType DecompType,
1092 const VectorType *VT) {
1094 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
1096 DecompType.getQualifiers()));
1097}
1098
1101 ValueDecl *Src, QualType DecompType,
1102 const ComplexType *CT) {
1104 S, Bindings, Src, DecompType, llvm::APSInt::get(2),
1106 DecompType.getQualifiers()),
1107 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
1108 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
1109 });
1110}
1111
1114 const TemplateParameterList *Params) {
1116 llvm::raw_svector_ostream OS(SS);
1117 bool First = true;
1118 unsigned I = 0;
1119 for (auto &Arg : Args.arguments()) {
1120 if (!First)
1121 OS << ", ";
1122 Arg.getArgument().print(PrintingPolicy, OS,
1124 PrintingPolicy, Params, I));
1125 First = false;
1126 I++;
1127 }
1128 return std::string(OS.str());
1129}
1130
1131static QualType getStdTrait(Sema &S, SourceLocation Loc, StringRef Trait,
1132 TemplateArgumentListInfo &Args, unsigned DiagID) {
1133 auto DiagnoseMissing = [&] {
1134 if (DiagID)
1135 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
1136 Args, /*Params*/ nullptr);
1137 return QualType();
1138 };
1139
1140 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
1141 NamespaceDecl *Std = S.getStdNamespace();
1142 if (!Std)
1143 return DiagnoseMissing();
1144
1145 // Look up the trait itself, within namespace std. We can diagnose various
1146 // problems with this lookup even if we've been asked to not diagnose a
1147 // missing specialization, because this can only fail if the user has been
1148 // declaring their own names in namespace std or we don't support the
1149 // standard library implementation in use.
1150 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait), Loc,
1152 if (!S.LookupQualifiedName(Result, Std))
1153 return DiagnoseMissing();
1154 if (Result.isAmbiguous())
1155 return QualType();
1156
1157 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
1158 if (!TraitTD) {
1159 Result.suppressDiagnostics();
1160 NamedDecl *Found = *Result.begin();
1161 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
1162 S.Diag(Found->getLocation(), diag::note_declared_at);
1163 return QualType();
1164 }
1165
1166 // Build the template-id.
1167 QualType TraitTy = S.CheckTemplateIdType(
1168 ElaboratedTypeKeyword::None, TemplateName(TraitTD), Loc, Args,
1169 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
1170 if (TraitTy.isNull())
1171 return QualType();
1172
1173 if (!S.isCompleteType(Loc, TraitTy)) {
1174 if (DiagID)
1176 Loc, TraitTy, DiagID,
1178 TraitTD->getTemplateParameters()));
1179 return QualType();
1180 }
1181 return TraitTy;
1182}
1183
1184static bool lookupMember(Sema &S, CXXRecordDecl *RD,
1185 LookupResult &MemberLookup) {
1186 assert(RD && "specialization of class template is not a class?");
1187 S.LookupQualifiedName(MemberLookup, RD);
1188 return MemberLookup.isAmbiguous();
1189}
1190
1191static TemplateArgumentLoc
1193 uint64_t I) {
1195 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
1196}
1197
1198static TemplateArgumentLoc
1202
1203namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1204
1205static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1206 unsigned &OutSize) {
1209
1210 // Form template argument list for tuple_size<T>.
1211 TemplateArgumentListInfo Args(Loc, Loc);
1213
1214 QualType TraitTy = getStdTrait(S, Loc, "tuple_size", Args, /*DiagID=*/0);
1215 if (TraitTy.isNull())
1216 return IsTupleLike::NotTupleLike;
1217
1220
1221 // If there's no tuple_size specialization or the lookup of 'value' is empty,
1222 // it's not tuple-like.
1223 if (lookupMember(S, TraitTy->getAsCXXRecordDecl(), R) || R.empty())
1224 return IsTupleLike::NotTupleLike;
1225
1226 // If we get this far, we've committed to the tuple interpretation, but
1227 // we can still fail if there actually isn't a usable ::value.
1228
1229 struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1230 LookupResult &R;
1232 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1233 : R(R), Args(Args) {}
1234 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
1235 SourceLocation Loc) override {
1236 return S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1238 /*Params*/ nullptr);
1239 }
1240 } Diagnoser(R, Args);
1241
1242 ExprResult E =
1243 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1244 if (E.isInvalid())
1245 return IsTupleLike::Error;
1246
1247 llvm::APSInt Size;
1248 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser);
1249 if (E.isInvalid())
1250 return IsTupleLike::Error;
1251
1252 // The implementation limit is UINT_MAX-1, to allow this to be passed down on
1253 // an UnsignedOrNone.
1254 if (Size < 0 || Size >= UINT_MAX) {
1256 Size.toString(Str);
1257 S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_invalid)
1259 /*Params=*/nullptr)
1260 << StringRef(Str.data(), Str.size());
1261 return IsTupleLike::Error;
1262 }
1263
1264 OutSize = Size.getExtValue();
1265 return IsTupleLike::TupleLike;
1266}
1267
1268/// \return std::tuple_element<I, T>::type.
1270 unsigned I, QualType T) {
1271 // Form template argument list for tuple_element<I, T>.
1272 TemplateArgumentListInfo Args(Loc, Loc);
1273 Args.addArgument(
1276
1277 QualType TraitTy =
1278 getStdTrait(S, Loc, "tuple_element", Args,
1279 diag::err_decomp_decl_std_tuple_element_not_specialized);
1280 if (TraitTy.isNull())
1281 return QualType();
1282
1283 DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1284 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1285 if (lookupMember(S, TraitTy->getAsCXXRecordDecl(), R))
1286 return QualType();
1287
1288 auto *TD = R.getAsSingle<TypeDecl>();
1289 if (!TD) {
1290 R.suppressDiagnostics();
1291 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1293 /*Params*/ nullptr);
1294 if (!R.empty())
1295 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1296 return QualType();
1297 }
1298
1299 NestedNameSpecifier Qualifier(TraitTy.getTypePtr());
1300 return S.Context.getTypeDeclType(ElaboratedTypeKeyword::None, Qualifier, TD);
1301}
1302
1303namespace {
1304struct InitializingBinding {
1305 Sema &S;
1306 InitializingBinding(Sema &S, BindingDecl *BD) : S(S) {
1307 Sema::CodeSynthesisContext Ctx;
1310 Ctx.Entity = BD;
1312 }
1313 ~InitializingBinding() {
1315 }
1316};
1317}
1318
1321 VarDecl *Src, QualType DecompType,
1322 unsigned NumElems) {
1323 auto *DD = cast<DecompositionDecl>(Src);
1324 if (CheckBindingsCount(S, DD, DecompType, Bindings, NumElems))
1325 return true;
1326
1327 if (Bindings.empty())
1328 return false;
1329
1330 DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1331
1332 // [dcl.decomp]p3:
1333 // The unqualified-id get is looked up in the scope of E by class member
1334 // access lookup ...
1335 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1336 bool UseMemberGet = false;
1337 if (S.isCompleteType(Src->getLocation(), DecompType)) {
1338 if (auto *RD = DecompType->getAsCXXRecordDecl())
1339 S.LookupQualifiedName(MemberGet, RD);
1340 if (MemberGet.isAmbiguous())
1341 return true;
1342 // ... and if that finds at least one declaration that is a function
1343 // template whose first template parameter is a non-type parameter ...
1344 for (NamedDecl *D : MemberGet) {
1345 if (FunctionTemplateDecl *FTD =
1346 dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
1347 TemplateParameterList *TPL = FTD->getTemplateParameters();
1348 if (TPL->size() != 0 &&
1350 // ... the initializer is e.get<i>().
1351 UseMemberGet = true;
1352 break;
1353 }
1354 }
1355 }
1356 }
1357
1358 unsigned I = 0;
1359 for (auto *B : DD->flat_bindings()) {
1360 InitializingBinding InitContext(S, B);
1361 SourceLocation Loc = B->getLocation();
1362
1363 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1364 if (E.isInvalid())
1365 return true;
1366
1367 // e is an lvalue if the type of the entity is an lvalue reference and
1368 // an xvalue otherwise
1369 if (!Src->getType()->isLValueReferenceType())
1370 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1371 E.get(), nullptr, VK_XValue,
1373
1374 TemplateArgumentListInfo Args(Loc, Loc);
1375 Args.addArgument(
1377
1378 if (UseMemberGet) {
1379 // if [lookup of member get] finds at least one declaration, the
1380 // initializer is e.get<i-1>().
1381 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1382 CXXScopeSpec(), SourceLocation(), nullptr,
1383 MemberGet, &Args, nullptr);
1384 if (E.isInvalid())
1385 return true;
1386
1387 E = S.BuildCallExpr(nullptr, E.get(), Loc, {}, Loc);
1388 } else {
1389 // Otherwise, the initializer is get<i-1>(e), where get is looked up
1390 // in the associated namespaces.
1393 DeclarationNameInfo(GetDN, Loc), /*RequiresADL=*/true, &Args,
1395 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
1396
1397 Expr *Arg = E.get();
1398 E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc);
1399 }
1400 if (E.isInvalid())
1401 return true;
1402 Expr *Init = E.get();
1403
1404 // Given the type T designated by std::tuple_element<i - 1, E>::type
1405 QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1406 if (T.isNull())
1407 return true;
1408
1409 // C++26 [dcl.struct.bind]p7:
1410 // and the type Ui, defined as Ti if the initializer is a prvalue,
1411 // as "lvalue reference to Ti" if the initializer is an lvalue,
1412 // or as "rvalue reference to Ti" otherwise
1413 // "defined as Ti if the initializer is a prvalue" was introduced by CWG3135
1414 QualType U = E.get()->isPRValue()
1415 ? T
1416 : S.BuildReferenceType(T, E.get()->isLValue(), Loc,
1417 B->getDeclName());
1418 if (U.isNull())
1419 return true;
1420
1421 // Don't give this VarDecl a TypeSourceInfo, since this is a synthesized
1422 // entity and this type was never written in source code.
1423 auto *BindingVD =
1424 VarDecl::Create(S.Context, Src->getDeclContext(), Loc, Loc,
1425 B->getDeclName().getAsIdentifierInfo(), U,
1426 /*TInfo=*/nullptr, Src->getStorageClass());
1427 BindingVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1428 BindingVD->setTSCSpec(Src->getTSCSpec());
1429 BindingVD->setConstexpr(Src->isConstexpr());
1430 if (const auto *CIAttr = Src->getAttr<ConstInitAttr>())
1431 BindingVD->addAttr(CIAttr->clone(S.Context));
1432 BindingVD->setImplicit();
1433 if (Src->isInlineSpecified())
1434 BindingVD->setInlineSpecified();
1435 BindingVD->getLexicalDeclContext()->addHiddenDecl(BindingVD);
1436
1439 InitializationSequence Seq(S, Entity, Kind, Init);
1440 E = Seq.Perform(S, Entity, Kind, Init);
1441 if (E.isInvalid())
1442 return true;
1443 E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
1444 if (E.isInvalid())
1445 return true;
1446 BindingVD->setInit(E.get());
1448
1450 CXXScopeSpec(), DeclarationNameInfo(B->getDeclName(), Loc), BindingVD);
1451 if (E.isInvalid())
1452 return true;
1453
1454 B->setBinding(T, E.get());
1455 I++;
1456 }
1457
1458 return false;
1459}
1460
1461/// Find the base class to decompose in a built-in decomposition of a class type.
1462/// This base class search is, unfortunately, not quite like any other that we
1463/// perform anywhere else in C++.
1465 const CXXRecordDecl *RD,
1466 CXXCastPath &BasePath) {
1467 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1468 CXXBasePath &Path) {
1469 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1470 };
1471
1472 const CXXRecordDecl *ClassWithFields = nullptr;
1474 if (RD->hasDirectFields())
1475 // [dcl.decomp]p4:
1476 // Otherwise, all of E's non-static data members shall be public direct
1477 // members of E ...
1478 ClassWithFields = RD;
1479 else {
1480 // ... or of ...
1481 CXXBasePaths Paths;
1482 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1483 if (!RD->lookupInBases(BaseHasFields, Paths)) {
1484 // If no classes have fields, just decompose RD itself. (This will work
1485 // if and only if zero bindings were provided.)
1486 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
1487 }
1488
1489 CXXBasePath *BestPath = nullptr;
1490 for (auto &P : Paths) {
1491 if (!BestPath)
1492 BestPath = &P;
1493 else if (!S.Context.hasSameType(P.back().Base->getType(),
1494 BestPath->back().Base->getType())) {
1495 // ... the same ...
1496 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1497 << false << RD << BestPath->back().Base->getType()
1498 << P.back().Base->getType();
1499 return DeclAccessPair();
1500 } else if (P.Access < BestPath->Access) {
1501 BestPath = &P;
1502 }
1503 }
1504
1505 // ... unambiguous ...
1506 QualType BaseType = BestPath->back().Base->getType();
1507 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1508 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1509 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1510 return DeclAccessPair();
1511 }
1512
1513 // ... [accessible, implied by other rules] base class of E.
1514 S.CheckBaseClassAccess(Loc, BaseType, S.Context.getCanonicalTagType(RD),
1515 *BestPath, diag::err_decomp_decl_inaccessible_base);
1516 AS = BestPath->Access;
1517
1518 ClassWithFields = BaseType->getAsCXXRecordDecl();
1519 S.BuildBasePathArray(Paths, BasePath);
1520 }
1521
1522 // The above search did not check whether the selected class itself has base
1523 // classes with fields, so check that now.
1524 CXXBasePaths Paths;
1525 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1526 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1527 << (ClassWithFields == RD) << RD << ClassWithFields
1528 << Paths.front().back().Base->getType();
1529 return DeclAccessPair();
1530 }
1531
1532 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1533}
1534
1536 const CXXRecordDecl *OrigRD,
1537 QualType DecompType,
1538 DeclAccessPair BasePair) {
1539 const auto *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1540 if (!RD)
1541 return true;
1542
1543 for (auto *FD : RD->fields()) {
1544 if (FD->isUnnamedBitField())
1545 continue;
1546
1547 // All the non-static data members are required to be nameable, so they
1548 // must all have names.
1549 if (!FD->getDeclName()) {
1550 if (RD->isLambda()) {
1551 S.Diag(Loc, diag::err_decomp_decl_lambda);
1552 S.Diag(RD->getLocation(), diag::note_lambda_decl);
1553 return true;
1554 }
1555
1556 if (FD->isAnonymousStructOrUnion()) {
1557 S.Diag(Loc, diag::err_decomp_decl_anon_union_member)
1558 << DecompType << FD->getType()->isUnionType();
1559 S.Diag(FD->getLocation(), diag::note_declared_at);
1560 return true;
1561 }
1562
1563 // FIXME: Are there any other ways we could have an anonymous member?
1564 }
1565 // The field must be accessible in the context of the structured binding.
1566 // We already checked that the base class is accessible.
1567 // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1568 // const_cast here.
1570 Loc, const_cast<CXXRecordDecl *>(OrigRD),
1572 BasePair.getAccess(), FD->getAccess())));
1573 }
1574 return false;
1575}
1576
1578 ValueDecl *Src, QualType DecompType,
1579 const CXXRecordDecl *OrigRD) {
1580 if (S.RequireCompleteType(Src->getLocation(), DecompType,
1581 diag::err_incomplete_type))
1582 return true;
1583
1584 CXXCastPath BasePath;
1585 DeclAccessPair BasePair =
1586 findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1587 const auto *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1588 if (!RD)
1589 return true;
1590 QualType BaseType = S.Context.getQualifiedType(
1591 S.Context.getCanonicalTagType(RD), DecompType.getQualifiers());
1592
1593 auto *DD = cast<DecompositionDecl>(Src);
1594 unsigned NumFields = llvm::count_if(
1595 RD->fields(), [](FieldDecl *FD) { return !FD->isUnnamedBitField(); });
1596 if (CheckBindingsCount(S, DD, DecompType, Bindings, NumFields))
1597 return true;
1598
1599 // all of E's non-static data members shall be [...] well-formed
1600 // when named as e.name in the context of the structured binding,
1601 // E shall not have an anonymous union member, ...
1602 auto FlatBindings = DD->flat_bindings();
1603 assert(llvm::range_size(FlatBindings) == NumFields);
1604 auto FlatBindingsItr = FlatBindings.begin();
1605
1606 if (CheckMemberDecompositionFields(S, Src->getLocation(), OrigRD, DecompType,
1607 BasePair))
1608 return true;
1609
1610 for (auto *FD : RD->fields()) {
1611 if (FD->isUnnamedBitField())
1612 continue;
1613
1614 // We have a real field to bind.
1615 assert(FlatBindingsItr != FlatBindings.end());
1616 BindingDecl *B = *(FlatBindingsItr++);
1617 SourceLocation Loc = B->getLocation();
1618
1619 // Initialize the binding to Src.FD.
1620 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1621 if (E.isInvalid())
1622 return true;
1623 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1624 VK_LValue, &BasePath);
1625 if (E.isInvalid())
1626 return true;
1627 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1628 CXXScopeSpec(), FD,
1630 DeclarationNameInfo(FD->getDeclName(), Loc));
1631 if (E.isInvalid())
1632 return true;
1633
1634 // If the type of the member is T, the referenced type is cv T, where cv is
1635 // the cv-qualification of the decomposition expression.
1636 //
1637 // FIXME: We resolve a defect here: if the field is mutable, we do not add
1638 // 'const' to the type of the field.
1639 Qualifiers Q = DecompType.getQualifiers();
1640 if (FD->isMutable())
1641 Q.removeConst();
1642 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1643 }
1644
1645 return false;
1646}
1647
1649 QualType DecompType = DD->getType();
1650
1651 // If the type of the decomposition is dependent, then so is the type of
1652 // each binding.
1653 if (DecompType->isDependentType()) {
1654 // Note that all of the types are still Null or PackExpansionType.
1655 for (auto *B : DD->bindings()) {
1656 // Do not overwrite any pack type.
1657 if (B->getType().isNull())
1658 B->setType(Context.DependentTy);
1659 }
1660 return;
1661 }
1662
1663 DecompType = DecompType.getNonReferenceType();
1665
1666 // C++1z [dcl.decomp]/2:
1667 // If E is an array type [...]
1668 // As an extension, we also support decomposition of built-in complex and
1669 // vector types.
1670 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1671 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1672 DD->setInvalidDecl();
1673 return;
1674 }
1675 if (auto *VT = DecompType->getAs<VectorType>()) {
1676 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1677 DD->setInvalidDecl();
1678 return;
1679 }
1680 if (auto *CT = DecompType->getAs<ComplexType>()) {
1681 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1682 DD->setInvalidDecl();
1683 return;
1684 }
1685
1686 // C++1z [dcl.decomp]/3:
1687 // if the expression std::tuple_size<E>::value is a well-formed integral
1688 // constant expression, [...]
1689 unsigned TupleSize;
1690 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1691 case IsTupleLike::Error:
1692 DD->setInvalidDecl();
1693 return;
1694
1695 case IsTupleLike::TupleLike:
1696 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1697 DD->setInvalidDecl();
1698 return;
1699
1700 case IsTupleLike::NotTupleLike:
1701 break;
1702 }
1703
1704 // C++1z [dcl.dcl]/8:
1705 // [E shall be of array or non-union class type]
1706 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1707 if (!RD || RD->isUnion()) {
1708 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1709 << DD << !RD << DecompType;
1710 DD->setInvalidDecl();
1711 return;
1712 }
1713
1714 // C++1z [dcl.decomp]/4:
1715 // all of E's non-static data members shall be [...] direct members of
1716 // E or of the same unambiguous public base class of E, ...
1717 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1718 DD->setInvalidDecl();
1719}
1720
1722 SourceLocation Loc) {
1723 const ASTContext &Ctx = getASTContext();
1724 assert(!T->isDependentType());
1725
1726 Qualifiers Quals;
1727 QualType Unqual = Context.getUnqualifiedArrayType(T, Quals);
1728 Quals.removeCVRQualifiers();
1729 T = Context.getQualifiedType(Unqual, Quals);
1730
1731 if (auto *CAT = Ctx.getAsConstantArrayType(T))
1732 return static_cast<unsigned>(CAT->getSize().getZExtValue());
1733 if (auto *VT = T->getAs<VectorType>())
1734 return VT->getNumElements();
1735 if (T->getAs<ComplexType>())
1736 return 2u;
1737
1738 unsigned TupleSize;
1739 switch (isTupleLike(*this, Loc, T, TupleSize)) {
1740 case IsTupleLike::Error:
1741 return std::nullopt;
1742 case IsTupleLike::TupleLike:
1743 return TupleSize;
1744 case IsTupleLike::NotTupleLike:
1745 break;
1746 }
1747
1748 const CXXRecordDecl *OrigRD = T->getAsCXXRecordDecl();
1749 if (!OrigRD || OrigRD->isUnion())
1750 return std::nullopt;
1751
1752 if (RequireCompleteType(Loc, T, diag::err_incomplete_type))
1753 return std::nullopt;
1754
1755 CXXCastPath BasePath;
1756 DeclAccessPair BasePair =
1757 findDecomposableBaseClass(*this, Loc, OrigRD, BasePath);
1758 const auto *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1759 if (!RD)
1760 return std::nullopt;
1761
1762 unsigned NumFields = llvm::count_if(
1763 RD->fields(), [](FieldDecl *FD) { return !FD->isUnnamedBitField(); });
1764
1765 if (CheckMemberDecompositionFields(*this, Loc, OrigRD, T, BasePair))
1766 return std::nullopt;
1767
1768 return NumFields;
1769}
1770
1772 // Shortcut if exceptions are disabled.
1773 if (!getLangOpts().CXXExceptions)
1774 return;
1775
1776 assert(Context.hasSameType(New->getType(), Old->getType()) &&
1777 "Should only be called if types are otherwise the same.");
1778
1779 QualType NewType = New->getType();
1780 QualType OldType = Old->getType();
1781
1782 // We're only interested in pointers and references to functions, as well
1783 // as pointers to member functions.
1784 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1785 NewType = R->getPointeeType();
1786 OldType = OldType->castAs<ReferenceType>()->getPointeeType();
1787 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1788 NewType = P->getPointeeType();
1789 OldType = OldType->castAs<PointerType>()->getPointeeType();
1790 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1791 NewType = M->getPointeeType();
1792 OldType = OldType->castAs<MemberPointerType>()->getPointeeType();
1793 }
1794
1795 if (!NewType->isFunctionProtoType())
1796 return;
1797
1798 // There's lots of special cases for functions. For function pointers, system
1799 // libraries are hopefully not as broken so that we don't need these
1800 // workarounds.
1802 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1803 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1804 New->setInvalidDecl();
1805 }
1806}
1807
1808/// CheckCXXDefaultArguments - Verify that the default arguments for a
1809/// function declaration are well-formed according to C++
1810/// [dcl.fct.default].
1812 // This checking doesn't make sense for explicit specializations; their
1813 // default arguments are determined by the declaration we're specializing,
1814 // not by FD.
1816 return;
1817 if (auto *FTD = FD->getDescribedFunctionTemplate())
1818 if (FTD->isMemberSpecialization())
1819 return;
1820
1821 unsigned NumParams = FD->getNumParams();
1822 unsigned ParamIdx = 0;
1823
1824 // Find first parameter with a default argument
1825 for (; ParamIdx < NumParams; ++ParamIdx) {
1826 ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1827 if (Param->hasDefaultArg())
1828 break;
1829 }
1830
1831 // C++20 [dcl.fct.default]p4:
1832 // In a given function declaration, each parameter subsequent to a parameter
1833 // with a default argument shall have a default argument supplied in this or
1834 // a previous declaration, unless the parameter was expanded from a
1835 // parameter pack, or shall be a function parameter pack.
1836 for (++ParamIdx; ParamIdx < NumParams; ++ParamIdx) {
1837 ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1838 if (Param->hasDefaultArg() || Param->isParameterPack() ||
1840 CurrentInstantiationScope->isLocalPackExpansion(Param)))
1841 continue;
1842 if (Param->isInvalidDecl())
1843 /* We already complained about this parameter. */;
1844 else if (Param->getIdentifier())
1845 Diag(Param->getLocation(), diag::err_param_default_argument_missing_name)
1846 << Param->getIdentifier();
1847 else
1848 Diag(Param->getLocation(), diag::err_param_default_argument_missing);
1849 }
1850}
1851
1852/// Check that the given type is a literal type. Issue a diagnostic if not,
1853/// if Kind is Diagnose.
1854/// \return \c true if a problem has been found (and optionally diagnosed).
1855template <typename... Ts>
1857 SourceLocation Loc, QualType T, unsigned DiagID,
1858 Ts &&...DiagArgs) {
1859 if (T->isDependentType())
1860 return false;
1861
1862 switch (Kind) {
1864 return SemaRef.RequireLiteralType(Loc, T, DiagID,
1865 std::forward<Ts>(DiagArgs)...);
1866
1868 return !T->isLiteralType(SemaRef.Context);
1869 }
1870
1871 llvm_unreachable("unknown CheckConstexprKind");
1872}
1873
1874/// Determine whether a destructor cannot be constexpr due to
1876 const CXXDestructorDecl *DD,
1878 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1879 "this check is obsolete for C++23");
1880 auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) {
1881 const CXXRecordDecl *RD =
1882 T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1883 if (!RD || RD->hasConstexprDestructor())
1884 return true;
1885
1887 SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject)
1888 << static_cast<int>(DD->getConstexprKind()) << !FD
1889 << (FD ? FD->getDeclName() : DeclarationName()) << T;
1890 SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject)
1891 << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T;
1892 }
1893 return false;
1894 };
1895
1896 const CXXRecordDecl *RD = DD->getParent();
1897 for (const CXXBaseSpecifier &B : RD->bases())
1898 if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr))
1899 return false;
1900 for (const FieldDecl *FD : RD->fields())
1901 if (!Check(FD->getLocation(), FD->getType(), FD))
1902 return false;
1903 return true;
1904}
1905
1906/// Check whether a function's parameter types are all literal types. If so,
1907/// return true. If not, produce a suitable diagnostic and return false.
1909 const FunctionDecl *FD,
1911 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1912 "this check is obsolete for C++23");
1913 unsigned ArgIndex = 0;
1914 const auto *FT = FD->getType()->castAs<FunctionProtoType>();
1915 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1916 e = FT->param_type_end();
1917 i != e; ++i, ++ArgIndex) {
1918 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1919 assert(PD && "null in a parameter list");
1920 SourceLocation ParamLoc = PD->getLocation();
1921 if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i,
1922 diag::err_constexpr_non_literal_param, ArgIndex + 1,
1924 FD->isConsteval()))
1925 return false;
1926 }
1927 return true;
1928}
1929
1930/// Check whether a function's return type is a literal type. If so, return
1931/// true. If not, produce a suitable diagnostic and return false.
1932static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD,
1934 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1935 "this check is obsolete for C++23");
1936 if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(),
1937 diag::err_constexpr_non_literal_return,
1938 FD->isConsteval()))
1939 return false;
1940 return true;
1941}
1942
1943/// Get diagnostic %select index for tag kind for
1944/// record diagnostic message.
1945/// WARNING: Indexes apply to particular diagnostics only!
1946///
1947/// \returns diagnostic %select index.
1949 switch (Tag) {
1951 return 0;
1953 return 1;
1954 case TagTypeKind::Class:
1955 return 2;
1956 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1957 }
1958}
1959
1960static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
1961 Stmt *Body,
1963static bool CheckConstexprMissingReturn(Sema &SemaRef, const FunctionDecl *Dcl);
1964
1966 CheckConstexprKind Kind) {
1967 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1968 if (!getLangOpts().CPlusPlus26 && MD && MD->isInstance()) {
1969 // C++11 [dcl.constexpr]p4:
1970 // The definition of a constexpr constructor shall satisfy the following
1971 // constraints:
1972 // - the class shall not have any virtual base classes;
1973 //
1974 // FIXME: This only applies to constructors and destructors, not arbitrary
1975 // member functions.
1976 const CXXRecordDecl *RD = MD->getParent();
1977 if (RD->getNumVBases()) {
1979 return false;
1980
1981 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1982 << isa<CXXConstructorDecl>(NewFD)
1984 for (const auto &I : RD->vbases())
1985 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1986 << I.getSourceRange();
1987 return false;
1988 }
1989 }
1990
1991 if (!isa<CXXConstructorDecl>(NewFD)) {
1992 // C++11 [dcl.constexpr]p3:
1993 // The definition of a constexpr function shall satisfy the following
1994 // constraints:
1995 // - it shall not be virtual; (removed in C++20)
1996 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1997 if (Method && Method->isVirtual()) {
1998 if (getLangOpts().CPlusPlus20) {
1999 if (Kind == CheckConstexprKind::Diagnose)
2000 Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
2001 } else {
2003 return false;
2004
2005 Method = Method->getCanonicalDecl();
2006 Diag(Method->getLocation(), diag::err_constexpr_virtual);
2007
2008 // If it's not obvious why this function is virtual, find an overridden
2009 // function which uses the 'virtual' keyword.
2010 const CXXMethodDecl *WrittenVirtual = Method;
2011 while (!WrittenVirtual->isVirtualAsWritten())
2012 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
2013 if (WrittenVirtual != Method)
2014 Diag(WrittenVirtual->getLocation(),
2015 diag::note_overridden_virtual_function);
2016 return false;
2017 }
2018 }
2019
2020 // - its return type shall be a literal type; (removed in C++23)
2021 if (!getLangOpts().CPlusPlus23 &&
2022 !CheckConstexprReturnType(*this, NewFD, Kind))
2023 return false;
2024 }
2025
2026 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) {
2027 // A destructor can be constexpr only if the defaulted destructor could be;
2028 // we don't need to check the members and bases if we already know they all
2029 // have constexpr destructors. (removed in C++23)
2030 if (!getLangOpts().CPlusPlus23 &&
2031 !Dtor->getParent()->defaultedDestructorIsConstexpr()) {
2033 return false;
2034 if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind))
2035 return false;
2036 }
2037 }
2038
2039 // - each of its parameter types shall be a literal type; (removed in C++23)
2040 if (!getLangOpts().CPlusPlus23 &&
2041 !CheckConstexprParameterTypes(*this, NewFD, Kind))
2042 return false;
2043
2044 Stmt *Body = NewFD->getBody();
2045 assert(Body &&
2046 "CheckConstexprFunctionDefinition called on function with no body");
2047 return CheckConstexprFunctionBody(*this, NewFD, Body, Kind);
2048}
2049
2050/// Check the given declaration statement is legal within a constexpr function
2051/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
2052///
2053/// \return true if the body is OK (maybe only as an extension), false if we
2054/// have diagnosed a problem.
2055static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
2056 DeclStmt *DS, SourceLocation &Cxx1yLoc,
2058 // C++11 [dcl.constexpr]p3 and p4:
2059 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
2060 // contain only
2061 for (const auto *DclIt : DS->decls()) {
2062 switch (DclIt->getKind()) {
2063 case Decl::StaticAssert:
2064 case Decl::Using:
2065 case Decl::UsingShadow:
2066 case Decl::UsingDirective:
2067 case Decl::UnresolvedUsingTypename:
2068 case Decl::UnresolvedUsingValue:
2069 case Decl::UsingEnum:
2070 // - static_assert-declarations
2071 // - using-declarations,
2072 // - using-directives,
2073 // - using-enum-declaration
2074 continue;
2075
2076 case Decl::CXXExpansionStmt:
2077 continue;
2078
2079 case Decl::Typedef:
2080 case Decl::TypeAlias: {
2081 // - typedef declarations and alias-declarations that do not define
2082 // classes or enumerations,
2083 const auto *TN = cast<TypedefNameDecl>(DclIt);
2084 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
2085 // Don't allow variably-modified types in constexpr functions.
2087 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
2088 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
2089 << TL.getSourceRange() << TL.getType()
2091 }
2092 return false;
2093 }
2094 continue;
2095 }
2096
2097 case Decl::Enum:
2098 case Decl::CXXRecord:
2099 // C++1y allows types to be defined, not just declared.
2100 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) {
2102 SemaRef.DiagCompat(DS->getBeginLoc(),
2103 diag_compat::constexpr_type_definition)
2105 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
2106 return false;
2107 }
2108 }
2109 continue;
2110
2111 case Decl::EnumConstant:
2112 case Decl::IndirectField:
2113 case Decl::ParmVar:
2114 // These can only appear with other declarations which are banned in
2115 // C++11 and permitted in C++1y, so ignore them.
2116 continue;
2117
2118 case Decl::Var:
2119 case Decl::Decomposition: {
2120 // C++1y [dcl.constexpr]p3 allows anything except:
2121 // a definition of a variable of non-literal type or of static or
2122 // thread storage duration or [before C++2a] for which no
2123 // initialization is performed.
2124 const auto *VD = cast<VarDecl>(DclIt);
2125 if (VD->isThisDeclarationADefinition()) {
2126 if (VD->isStaticLocal()) {
2128 SemaRef.DiagCompat(VD->getLocation(),
2129 diag_compat::constexpr_static_var)
2131 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
2132 } else if (!SemaRef.getLangOpts().CPlusPlus23) {
2133 return false;
2134 }
2135 }
2136 if (SemaRef.LangOpts.CPlusPlus23) {
2137 CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(),
2138 diag::warn_cxx20_compat_constexpr_var,
2140 } else if (CheckLiteralType(
2141 SemaRef, Kind, VD->getLocation(), VD->getType(),
2142 diag::err_constexpr_local_var_non_literal_type,
2144 return false;
2145 }
2146 if (!VD->getType()->isDependentType() &&
2147 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
2149 SemaRef.DiagCompat(VD->getLocation(),
2150 diag_compat::constexpr_local_var_no_init)
2152 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2153 return false;
2154 }
2155 continue;
2156 }
2157 }
2159 SemaRef.DiagCompat(VD->getLocation(), diag_compat::constexpr_local_var)
2161 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
2162 return false;
2163 }
2164 continue;
2165 }
2166
2167 case Decl::NamespaceAlias:
2168 case Decl::Function:
2169 // These are disallowed in C++11 and permitted in C++1y. Allow them
2170 // everywhere as an extension.
2171 if (!Cxx1yLoc.isValid())
2172 Cxx1yLoc = DS->getBeginLoc();
2173 continue;
2174
2175 default:
2177 SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2178 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2179 }
2180 return false;
2181 }
2182 }
2183
2184 return true;
2185}
2186
2187/// Check that the given field is initialized within a constexpr constructor.
2188///
2189/// \param Dcl The constexpr constructor being checked.
2190/// \param Field The field being checked. This may be a member of an anonymous
2191/// struct or union nested within the class being checked.
2192/// \param Inits All declarations, including anonymous struct/union members and
2193/// indirect members, for which any initialization was provided.
2194/// \param Diagnosed Whether we've emitted the error message yet. Used to attach
2195/// multiple notes for different members to the same error.
2196/// \param Kind Whether we're diagnosing a constructor as written or determining
2197/// whether the formal requirements are satisfied.
2198/// \return \c false if we're checking for validity and the constructor does
2199/// not satisfy the requirements on a constexpr constructor.
2201 const FunctionDecl *Dcl,
2202 FieldDecl *Field,
2204 bool &Diagnosed,
2206 // In C++20 onwards, there's nothing to check for validity.
2208 SemaRef.getLangOpts().CPlusPlus20)
2209 return true;
2210
2211 if (Field->isInvalidDecl())
2212 return true;
2213
2214 if (Field->isUnnamedBitField())
2215 return true;
2216
2217 // Anonymous unions with no variant members and empty anonymous structs do not
2218 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
2219 // indirect fields don't need initializing.
2220 if (Field->isAnonymousStructOrUnion() &&
2221 (Field->getType()->isUnionType()
2222 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
2223 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
2224 return true;
2225
2226 if (!Inits.count(Field)) {
2228 if (!Diagnosed) {
2229 SemaRef.DiagCompat(Dcl->getLocation(),
2230 diag_compat::constexpr_ctor_missing_init);
2231 Diagnosed = true;
2232 }
2233 SemaRef.Diag(Field->getLocation(),
2234 diag::note_constexpr_ctor_missing_init);
2235 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2236 return false;
2237 }
2238 } else if (Field->isAnonymousStructOrUnion()) {
2239 const auto *RD = Field->getType()->castAsRecordDecl();
2240 for (auto *I : RD->fields())
2241 // If an anonymous union contains an anonymous struct of which any member
2242 // is initialized, all members must be initialized.
2243 if (!RD->isUnion() || Inits.count(I))
2244 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2245 Kind))
2246 return false;
2247 }
2248 return true;
2249}
2250
2251/// Check the provided statement is allowed in a constexpr function
2252/// definition.
2253static bool
2256 SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
2257 SourceLocation &Cxx2bLoc,
2259 // - its function-body shall be [...] a compound-statement that contains only
2260 switch (S->getStmtClass()) {
2261 case Stmt::NullStmtClass:
2262 // - null statements,
2263 return true;
2264
2265 case Stmt::DeclStmtClass:
2266 // - static_assert-declarations
2267 // - using-declarations,
2268 // - using-directives,
2269 // - typedef declarations and alias-declarations that do not define
2270 // classes or enumerations,
2271 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind))
2272 return false;
2273 return true;
2274
2275 case Stmt::ReturnStmtClass:
2276 // - and exactly one return statement;
2277 if (isa<CXXConstructorDecl>(Dcl)) {
2278 // C++1y allows return statements in constexpr constructors.
2279 if (!Cxx1yLoc.isValid())
2280 Cxx1yLoc = S->getBeginLoc();
2281 return true;
2282 }
2283
2284 ReturnStmts.push_back(S->getBeginLoc());
2285 return true;
2286
2287 case Stmt::AttributedStmtClass:
2288 // Attributes on a statement don't affect its formal kind and hence don't
2289 // affect its validity in a constexpr function.
2291 SemaRef, Dcl, cast<AttributedStmt>(S)->getSubStmt(), ReturnStmts,
2292 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind);
2293
2294 case Stmt::CompoundStmtClass: {
2295 // C++1y allows compound-statements.
2296 if (!Cxx1yLoc.isValid())
2297 Cxx1yLoc = S->getBeginLoc();
2298
2299 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
2300 for (auto *BodyIt : CompStmt->body()) {
2301 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
2302 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2303 return false;
2304 }
2305 return true;
2306 }
2307
2308 case Stmt::IfStmtClass: {
2309 // C++1y allows if-statements.
2310 if (!Cxx1yLoc.isValid())
2311 Cxx1yLoc = S->getBeginLoc();
2312
2313 IfStmt *If = cast<IfStmt>(S);
2314 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
2315 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2316 return false;
2317 if (If->getElse() &&
2318 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
2319 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2320 return false;
2321 return true;
2322 }
2323
2324 case Stmt::WhileStmtClass:
2325 case Stmt::DoStmtClass:
2326 case Stmt::ForStmtClass:
2327 case Stmt::CXXForRangeStmtClass:
2328 case Stmt::ContinueStmtClass:
2329 // C++1y allows all of these. We don't allow them as extensions in C++11,
2330 // because they don't make sense without variable mutation.
2331 if (!SemaRef.getLangOpts().CPlusPlus14)
2332 break;
2333 if (!Cxx1yLoc.isValid())
2334 Cxx1yLoc = S->getBeginLoc();
2335 for (Stmt *SubStmt : S->children()) {
2336 if (SubStmt &&
2337 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2338 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2339 return false;
2340 }
2341 return true;
2342
2343 case Stmt::SwitchStmtClass:
2344 case Stmt::CaseStmtClass:
2345 case Stmt::DefaultStmtClass:
2346 case Stmt::BreakStmtClass:
2347 // C++1y allows switch-statements, and since they don't need variable
2348 // mutation, we can reasonably allow them in C++11 as an extension.
2349 if (!Cxx1yLoc.isValid())
2350 Cxx1yLoc = S->getBeginLoc();
2351 for (Stmt *SubStmt : S->children()) {
2352 if (SubStmt &&
2353 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2354 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2355 return false;
2356 }
2357 return true;
2358
2359 case Stmt::LabelStmtClass:
2360 case Stmt::GotoStmtClass:
2361 case Stmt::IndirectGotoStmtClass:
2362 if (Cxx2bLoc.isInvalid())
2363 Cxx2bLoc = S->getBeginLoc();
2364 for (Stmt *SubStmt : S->children()) {
2365 if (SubStmt &&
2366 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2367 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2368 return false;
2369 }
2370 return true;
2371
2372 case Stmt::GCCAsmStmtClass:
2373 case Stmt::MSAsmStmtClass:
2374 // C++2a allows inline assembly statements.
2375 case Stmt::CXXTryStmtClass:
2376 if (Cxx2aLoc.isInvalid())
2377 Cxx2aLoc = S->getBeginLoc();
2378 for (Stmt *SubStmt : S->children()) {
2379 if (SubStmt &&
2380 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2381 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2382 return false;
2383 }
2384 return true;
2385
2386 case Stmt::CXXCatchStmtClass:
2387 // Do not bother checking the language mode (already covered by the
2388 // try block check).
2390 SemaRef, Dcl, cast<CXXCatchStmt>(S)->getHandlerBlock(), ReturnStmts,
2391 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2392 return false;
2393 return true;
2394
2395 default:
2396 if (!isa<Expr>(S))
2397 break;
2398
2399 // C++1y allows expression-statements.
2400 if (!Cxx1yLoc.isValid())
2401 Cxx1yLoc = S->getBeginLoc();
2402 return true;
2403 }
2404
2406 SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2407 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2408 }
2409 return false;
2410}
2411
2412/// Check the body for the given constexpr function declaration only contains
2413/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
2414///
2415/// \return true if the body is OK, false if we have found or diagnosed a
2416/// problem.
2417static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
2418 Stmt *Body,
2421
2422 if (isa<CXXTryStmt>(Body)) {
2423 // C++11 [dcl.constexpr]p3:
2424 // The definition of a constexpr function shall satisfy the following
2425 // constraints: [...]
2426 // - its function-body shall be = delete, = default, or a
2427 // compound-statement
2428 //
2429 // C++11 [dcl.constexpr]p4:
2430 // In the definition of a constexpr constructor, [...]
2431 // - its function-body shall not be a function-try-block;
2432 //
2433 // This restriction is lifted in C++2a, as long as inner statements also
2434 // apply the general constexpr rules.
2435 switch (Kind) {
2437 if (!SemaRef.getLangOpts().CPlusPlus20)
2438 return false;
2439 break;
2440
2442 SemaRef.DiagCompat(Body->getBeginLoc(),
2443 diag_compat::constexpr_function_try_block)
2445 break;
2446 }
2447 }
2448
2449 // - its function-body shall be [...] a compound-statement that contains only
2450 // [... list of cases ...]
2451 //
2452 // Note that walking the children here is enough to properly check for
2453 // CompoundStmt and CXXTryStmt body.
2454 SourceLocation Cxx1yLoc, Cxx2aLoc, Cxx2bLoc;
2455 for (Stmt *SubStmt : Body->children()) {
2456 if (SubStmt &&
2457 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2458 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2459 return false;
2460 }
2461
2463 // If this is only valid as an extension, report that we don't satisfy the
2464 // constraints of the current language.
2465 if ((Cxx2bLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus23) ||
2466 (Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) ||
2467 (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
2468 return false;
2469 } else if (Cxx2bLoc.isValid()) {
2470 SemaRef.DiagCompat(Cxx2bLoc, diag_compat::cxx23_constexpr_body_invalid_stmt)
2472 } else if (Cxx2aLoc.isValid()) {
2473 SemaRef.DiagCompat(Cxx2aLoc, diag_compat::cxx20_constexpr_body_invalid_stmt)
2475 } else if (Cxx1yLoc.isValid()) {
2476 SemaRef.DiagCompat(Cxx1yLoc, diag_compat::cxx14_constexpr_body_invalid_stmt)
2478 }
2479
2481 = dyn_cast<CXXConstructorDecl>(Dcl)) {
2482 const CXXRecordDecl *RD = Constructor->getParent();
2483 // DR1359:
2484 // - every non-variant non-static data member and base class sub-object
2485 // shall be initialized;
2486 // DR1460:
2487 // - if the class is a union having variant members, exactly one of them
2488 // shall be initialized;
2489 if (RD->isUnion()) {
2490 if (Constructor->getNumCtorInitializers() == 0 &&
2491 RD->hasVariantMembers()) {
2493 SemaRef.DiagCompat(Dcl->getLocation(),
2494 diag_compat::constexpr_union_ctor_no_init);
2495 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2496 return false;
2497 }
2498 }
2499 } else if (!Constructor->isDependentContext() &&
2500 !Constructor->isDelegatingConstructor()) {
2501 // Skip detailed checking if we have enough initializers, and we would
2502 // allow at most one initializer per member.
2503 bool AnyAnonStructUnionMembers = false;
2504 unsigned Fields = 0;
2506 E = RD->field_end(); I != E; ++I, ++Fields) {
2507 if (I->isAnonymousStructOrUnion()) {
2508 AnyAnonStructUnionMembers = true;
2509 break;
2510 }
2511 }
2512 // DR1460:
2513 // - if the class is a union-like class, but is not a union, for each of
2514 // its anonymous union members having variant members, exactly one of
2515 // them shall be initialized;
2516 if (AnyAnonStructUnionMembers ||
2517 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2518 // Check initialization of non-static data members. Base classes are
2519 // always initialized so do not need to be checked. Dependent bases
2520 // might not have initializers in the member initializer list.
2522 for (const auto *I: Constructor->inits()) {
2523 if (FieldDecl *FD = I->getMember())
2524 Inits.insert(FD);
2525 else if (IndirectFieldDecl *ID = I->getIndirectMember())
2526 Inits.insert(ID->chain_begin(), ID->chain_end());
2527 }
2528
2529 bool Diagnosed = false;
2530 for (auto *I : RD->fields())
2531 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2532 Kind))
2533 return false;
2534 }
2535 }
2536 } else {
2537 if (ReturnStmts.empty()) {
2538 switch (Kind) {
2540 if (!CheckConstexprMissingReturn(SemaRef, Dcl))
2541 return false;
2542 break;
2543
2545 // The formal requirements don't include this rule in C++14, even
2546 // though the "must be able to produce a constant expression" rules
2547 // still imply it in some cases.
2548 if (!SemaRef.getLangOpts().CPlusPlus14)
2549 return false;
2550 break;
2551 }
2552 } else if (ReturnStmts.size() > 1) {
2553 switch (Kind) {
2555 SemaRef.DiagCompat(ReturnStmts.back(),
2556 diag_compat::constexpr_body_multiple_return);
2557 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2558 SemaRef.Diag(ReturnStmts[I],
2559 diag::note_constexpr_body_previous_return);
2560 break;
2561
2563 if (!SemaRef.getLangOpts().CPlusPlus14)
2564 return false;
2565 break;
2566 }
2567 }
2568 }
2569
2570 // C++11 [dcl.constexpr]p5:
2571 // if no function argument values exist such that the function invocation
2572 // substitution would produce a constant expression, the program is
2573 // ill-formed; no diagnostic required.
2574 // C++11 [dcl.constexpr]p3:
2575 // - every constructor call and implicit conversion used in initializing the
2576 // return value shall be one of those allowed in a constant expression.
2577 // C++11 [dcl.constexpr]p4:
2578 // - every constructor involved in initializing non-static data members and
2579 // base class sub-objects shall be a constexpr constructor.
2580 //
2581 // Note that this rule is distinct from the "requirements for a constexpr
2582 // function", so is not checked in CheckValid mode. Because the check for
2583 // constexpr potential is expensive, skip the check if the diagnostic is
2584 // disabled, the function is declared in a system header, or we're in C++23
2585 // or later mode (see https://wg21.link/P2448).
2586 bool SkipCheck =
2587 !SemaRef.getLangOpts().CheckConstexprFunctionBodies ||
2588 SemaRef.getSourceManager().isInSystemHeader(Dcl->getLocation()) ||
2589 SemaRef.getDiagnostics().isIgnored(
2590 diag::ext_constexpr_function_never_constant_expr, Dcl->getLocation());
2592 if (Kind == Sema::CheckConstexprKind::Diagnose && !SkipCheck &&
2593 !Expr::isPotentialConstantExpr(Dcl, Diags)) {
2594 SemaRef.Diag(Dcl->getLocation(),
2595 diag::ext_constexpr_function_never_constant_expr)
2596 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval()
2597 << Dcl->getNameInfo().getSourceRange();
2598 for (const auto &Diag : Diags)
2599 SemaRef.Diag(Diag.first, Diag.second);
2600 // Don't return false here: we allow this for compatibility in
2601 // system headers.
2602 }
2603
2604 return true;
2605}
2606
2608 const FunctionDecl *Dcl) {
2609 bool IsVoidOrDependentType = Dcl->getReturnType()->isVoidType() ||
2611 // Skip emitting a missing return error diagnostic for non-void functions
2612 // since C++23 no longer mandates constexpr functions to yield constant
2613 // expressions.
2614 if (SemaRef.getLangOpts().CPlusPlus23 && !IsVoidOrDependentType)
2615 return true;
2616
2617 // C++14 doesn't require constexpr functions to contain a 'return'
2618 // statement. We still do, unless the return type might be void, because
2619 // otherwise if there's no return statement, the function cannot
2620 // be used in a core constant expression.
2621 bool OK = SemaRef.getLangOpts().CPlusPlus14 && IsVoidOrDependentType;
2622 SemaRef.Diag(Dcl->getLocation(),
2623 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2624 : diag::err_constexpr_body_no_return)
2625 << Dcl->isConsteval();
2626 return OK;
2627}
2628
2630 FunctionDecl *FD, const sema::FunctionScopeInfo *FSI) {
2632 return true;
2636 auto it = UndefinedButUsed.find(FD->getCanonicalDecl());
2637 if (it != UndefinedButUsed.end()) {
2638 Diag(it->second, diag::err_immediate_function_used_before_definition)
2639 << it->first;
2640 Diag(FD->getLocation(), diag::note_defined_here) << FD;
2641 if (FD->isImmediateFunction() && !FD->isConsteval())
2643 return false;
2644 }
2645 }
2646 return true;
2647}
2648
2650 assert(FD->isImmediateEscalating() && !FD->isConsteval() &&
2651 "expected an immediate function");
2652 assert(FD->hasBody() && "expected the function to have a body");
2653 struct ImmediateEscalatingExpressionsVisitor : DynamicRecursiveASTVisitor {
2654 Sema &SemaRef;
2655
2656 const FunctionDecl *ImmediateFn;
2657 bool ImmediateFnIsConstructor;
2658 CXXConstructorDecl *CurrentConstructor = nullptr;
2659 CXXCtorInitializer *CurrentInit = nullptr;
2660
2661 ImmediateEscalatingExpressionsVisitor(Sema &SemaRef, FunctionDecl *FD)
2662 : SemaRef(SemaRef), ImmediateFn(FD),
2663 ImmediateFnIsConstructor(isa<CXXConstructorDecl>(FD)) {
2664 ShouldVisitImplicitCode = true;
2665 ShouldVisitLambdaBody = false;
2666 }
2667
2668 void Diag(const Expr *E, const FunctionDecl *Fn, bool IsCall) {
2669 SourceLocation Loc = E->getBeginLoc();
2670 SourceRange Range = E->getSourceRange();
2671 if (CurrentConstructor && CurrentInit) {
2672 Loc = CurrentConstructor->getLocation();
2673 Range = CurrentInit->isWritten() ? CurrentInit->getSourceRange()
2674 : SourceRange();
2675 }
2676
2677 FieldDecl* InitializedField = CurrentInit ? CurrentInit->getAnyMember() : nullptr;
2678
2679 SemaRef.Diag(Loc, diag::note_immediate_function_reason)
2680 << ImmediateFn << Fn << Fn->isConsteval() << IsCall
2681 << isa<CXXConstructorDecl>(Fn) << ImmediateFnIsConstructor
2682 << (InitializedField != nullptr)
2683 << (CurrentInit && !CurrentInit->isWritten())
2684 << InitializedField << Range;
2685 }
2686 bool TraverseCallExpr(CallExpr *E) override {
2687 if (const auto *DR =
2688 dyn_cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit());
2689 DR && DR->isImmediateEscalating()) {
2690 Diag(E, E->getDirectCallee(), /*IsCall=*/true);
2691 return false;
2692 }
2693
2694 for (Expr *A : E->arguments())
2695 if (!TraverseStmt(A))
2696 return false;
2697
2698 return true;
2699 }
2700
2701 bool VisitDeclRefExpr(DeclRefExpr *E) override {
2702 if (const auto *ReferencedFn = dyn_cast<FunctionDecl>(E->getDecl());
2703 ReferencedFn && E->isImmediateEscalating()) {
2704 Diag(E, ReferencedFn, /*IsCall=*/false);
2705 return false;
2706 }
2707
2708 return true;
2709 }
2710
2711 bool VisitCXXConstructExpr(CXXConstructExpr *E) override {
2713 if (E->isImmediateEscalating()) {
2714 Diag(E, D, /*IsCall=*/true);
2715 return false;
2716 }
2717 return true;
2718 }
2719
2720 bool TraverseConstructorInitializer(CXXCtorInitializer *Init) override {
2721 llvm::SaveAndRestore RAII(CurrentInit, Init);
2723 }
2724
2725 bool TraverseCXXConstructorDecl(CXXConstructorDecl *Ctr) override {
2726 llvm::SaveAndRestore RAII(CurrentConstructor, Ctr);
2727 return DynamicRecursiveASTVisitor::TraverseCXXConstructorDecl(Ctr);
2728 }
2729
2730 bool TraverseType(QualType T, bool TraverseQualifier) override {
2731 return true;
2732 }
2733 bool VisitBlockExpr(BlockExpr *T) override { return true; }
2734
2735 } Visitor(*this, FD);
2736 Visitor.TraverseDecl(FD);
2737}
2738
2740 assert(getLangOpts().CPlusPlus && "No class names in C!");
2741
2742 if (SS && SS->isInvalid())
2743 return nullptr;
2744
2745 if (SS && SS->isNotEmpty()) {
2746 DeclContext *DC = computeDeclContext(*SS, true);
2747 return dyn_cast_or_null<CXXRecordDecl>(DC);
2748 }
2749
2750 return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2751}
2752
2754 const CXXScopeSpec *SS) {
2755 CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2756 return CurDecl && &II == CurDecl->getIdentifier();
2757}
2758
2760 assert(getLangOpts().CPlusPlus && "No class names in C!");
2761
2762 if (!getLangOpts().SpellChecking)
2763 return false;
2764
2765 CXXRecordDecl *CurDecl;
2766 if (SS && SS->isSet() && !SS->isInvalid()) {
2767 DeclContext *DC = computeDeclContext(*SS, true);
2768 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2769 } else
2770 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2771
2772 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2773 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2774 < II->getLength()) {
2775 II = CurDecl->getIdentifier();
2776 return true;
2777 }
2778
2779 return false;
2780}
2781
2783 SourceRange SpecifierRange,
2784 bool Virtual, AccessSpecifier Access,
2785 TypeSourceInfo *TInfo,
2786 SourceLocation EllipsisLoc) {
2787 QualType BaseType = TInfo->getType();
2788 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2789 if (BaseType->containsErrors()) {
2790 // Already emitted a diagnostic when parsing the error type.
2791 return nullptr;
2792 }
2793
2794 if (EllipsisLoc.isValid() && !BaseType->containsUnexpandedParameterPack()) {
2795 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2796 << TInfo->getTypeLoc().getSourceRange();
2797 EllipsisLoc = SourceLocation();
2798 }
2799
2800 auto *BaseDecl =
2801 dyn_cast_if_present<CXXRecordDecl>(computeDeclContext(BaseType));
2802 // C++ [class.derived.general]p2:
2803 // A class-or-decltype shall denote a (possibly cv-qualified) class type
2804 // that is not an incompletely defined class; any cv-qualifiers are
2805 // ignored.
2806 if (BaseDecl) {
2807 // C++ [class.union.general]p4:
2808 // [...] A union shall not be used as a base class.
2809 if (BaseDecl->isUnion()) {
2810 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2811 return nullptr;
2812 }
2813
2814 if (BaseType.hasQualifiers()) {
2815 std::string Quals =
2816 BaseType.getQualifiers().getAsString(Context.getPrintingPolicy());
2817 Diag(BaseLoc, diag::warn_qual_base_type)
2818 << Quals << llvm::count(Quals, ' ') + 1 << BaseType;
2819 Diag(BaseLoc, diag::note_base_class_specified_here) << BaseType;
2820 }
2821
2822 // For the MS ABI, propagate DLL attributes to base class templates.
2823 if (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
2824 Context.getTargetInfo().getTriple().isPS()) {
2825 if (Attr *ClassAttr = getDLLAttr(Class)) {
2826 if (auto *BaseSpec =
2827 dyn_cast<ClassTemplateSpecializationDecl>(BaseDecl)) {
2828 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseSpec,
2829 BaseLoc);
2830 }
2831 }
2832 }
2833
2834 if (RequireCompleteType(BaseLoc, BaseType, diag::err_incomplete_base_class,
2835 SpecifierRange)) {
2836 Class->setInvalidDecl();
2837 return nullptr;
2838 }
2839
2840 BaseDecl = BaseDecl->getDefinition();
2841 assert(BaseDecl && "Base type is not incomplete, but has no definition");
2842
2843 // Microsoft docs say:
2844 // "If a base-class has a code_seg attribute, derived classes must have the
2845 // same attribute."
2846 const auto *BaseCSA = BaseDecl->getAttr<CodeSegAttr>();
2847 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2848 if ((DerivedCSA || BaseCSA) &&
2849 (!BaseCSA || !DerivedCSA ||
2850 BaseCSA->getName() != DerivedCSA->getName())) {
2851 Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2852 Diag(BaseDecl->getLocation(), diag::note_base_class_specified_here)
2853 << BaseDecl;
2854 return nullptr;
2855 }
2856
2857 // A class which contains a flexible array member is not suitable for use as
2858 // a base class:
2859 // - If the layout determines that a base comes before another base,
2860 // the flexible array member would index into the subsequent base.
2861 // - If the layout determines that base comes before the derived class,
2862 // the flexible array member would index into the derived class.
2863 if (BaseDecl->hasFlexibleArrayMember()) {
2864 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2865 << BaseDecl->getDeclName();
2866 return nullptr;
2867 }
2868
2869 // C++ [class]p3:
2870 // If a class is marked final and it appears as a base-type-specifier in
2871 // base-clause, the program is ill-formed.
2872 if (FinalAttr *FA = BaseDecl->getAttr<FinalAttr>()) {
2873 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2874 << BaseDecl->getDeclName() << FA->isSpelledAsSealed();
2875 Diag(BaseDecl->getLocation(), diag::note_entity_declared_at)
2876 << BaseDecl->getDeclName() << FA->getRange();
2877 return nullptr;
2878 }
2879
2880 // If the base class is invalid the derived class is as well.
2881 if (BaseDecl->isInvalidDecl())
2882 Class->setInvalidDecl();
2883 } else if (BaseType->isDependentType()) {
2884 // Make sure that we don't make an ill-formed AST where the type of the
2885 // Class is non-dependent and its attached base class specifier is an
2886 // dependent type, which violates invariants in many clang code paths (e.g.
2887 // constexpr evaluator). If this case happens (in errory-recovery mode), we
2888 // explicitly mark the Class decl invalid. The diagnostic was already
2889 // emitted.
2890 if (!Class->isDependentContext())
2891 Class->setInvalidDecl();
2892 } else {
2893 // The base class is some non-dependent non-class type.
2894 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2895 return nullptr;
2896 }
2897
2898 // In HLSL, unspecified class access is public rather than private.
2899 if (getLangOpts().HLSL && Class->getTagKind() == TagTypeKind::Class &&
2900 Access == AS_none)
2901 Access = AS_public;
2902
2903 // Create the base specifier.
2904 return new (Context) CXXBaseSpecifier(
2905 SpecifierRange, Virtual, Class->getTagKind() == TagTypeKind::Class,
2906 Access, TInfo, EllipsisLoc);
2907}
2908
2910 const ParsedAttributesView &Attributes,
2911 bool Virtual, AccessSpecifier Access,
2912 ParsedType basetype, SourceLocation BaseLoc,
2913 SourceLocation EllipsisLoc) {
2914 if (!classdecl)
2915 return true;
2916
2917 AdjustDeclIfTemplate(classdecl);
2918 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2919 if (!Class)
2920 return true;
2921
2922 // We haven't yet attached the base specifiers.
2923 Class->setIsParsingBaseSpecifiers();
2924
2925 // We do not support any C++11 attributes on base-specifiers yet.
2926 // Diagnose any attributes we see.
2927 for (const ParsedAttr &AL : Attributes) {
2928 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2929 continue;
2930 if (AL.getKind() == ParsedAttr::UnknownAttribute)
2932 else
2933 Diag(AL.getLoc(), diag::err_base_specifier_attribute)
2934 << AL << AL.isRegularKeywordAttribute() << AL.getRange();
2935 }
2936
2937 TypeSourceInfo *TInfo = nullptr;
2938 GetTypeFromParser(basetype, &TInfo);
2939
2940 if (EllipsisLoc.isInvalid() &&
2941 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2943 return true;
2944
2945 // C++ [class.union.general]p4:
2946 // [...] A union shall not have base classes.
2947 if (Class->isUnion()) {
2948 Diag(Class->getLocation(), diag::err_base_clause_on_union)
2949 << SpecifierRange;
2950 return true;
2951 }
2952
2953 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2954 Virtual, Access, TInfo,
2955 EllipsisLoc))
2956 return BaseSpec;
2957
2958 Class->setInvalidDecl();
2959 return true;
2960}
2961
2962/// Use small set to collect indirect bases. As this is only used
2963/// locally, there's no need to abstract the small size parameter.
2965
2966/// Recursively add the bases of Type. Don't add Type itself.
2967static void
2969 const QualType &Type)
2970{
2971 // Even though the incoming type is a base, it might not be
2972 // a class -- it could be a template parm, for instance.
2973 if (const auto *Decl = Type->getAsCXXRecordDecl()) {
2974 // Iterate over its bases.
2975 for (const auto &BaseSpec : Decl->bases()) {
2976 QualType Base = Context.getCanonicalType(BaseSpec.getType())
2977 .getUnqualifiedType();
2978 if (Set.insert(Base).second)
2979 // If we've not already seen it, recurse.
2980 NoteIndirectBases(Context, Set, Base);
2981 }
2982 }
2983}
2984
2987 if (Bases.empty())
2988 return false;
2989
2990 // Used to keep track of which base types we have already seen, so
2991 // that we can properly diagnose redundant direct base types. Note
2992 // that the key is always the unqualified canonical type of the base
2993 // class.
2994 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2995
2996 // Used to track indirect bases so we can see if a direct base is
2997 // ambiguous.
2998 IndirectBaseSet IndirectBaseTypes;
2999
3000 // Copy non-redundant base specifiers into permanent storage.
3001 unsigned NumGoodBases = 0;
3002 bool Invalid = false;
3003 for (unsigned idx = 0; idx < Bases.size(); ++idx) {
3004 QualType NewBaseType
3005 = Context.getCanonicalType(Bases[idx]->getType());
3006 NewBaseType = NewBaseType.getLocalUnqualifiedType();
3007
3008 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
3009 if (KnownBase) {
3010 // C++ [class.mi]p3:
3011 // A class shall not be specified as a direct base class of a
3012 // derived class more than once.
3013 Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
3014 << KnownBase->getType() << Bases[idx]->getSourceRange();
3015
3016 // Delete the duplicate base class specifier; we're going to
3017 // overwrite its pointer later.
3018 Context.Deallocate(Bases[idx]);
3019
3020 Invalid = true;
3021 } else {
3022 // Okay, add this new base class.
3023 KnownBase = Bases[idx];
3024 Bases[NumGoodBases++] = Bases[idx];
3025
3026 if (NewBaseType->isDependentType())
3027 continue;
3028 // Note this base's direct & indirect bases, if there could be ambiguity.
3029 if (Bases.size() > 1)
3030 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
3031
3032 if (const auto *RD = NewBaseType->getAsCXXRecordDecl()) {
3033 if (Class->isInterface() &&
3034 (!RD->isInterfaceLike() ||
3035 KnownBase->getAccessSpecifier() != AS_public)) {
3036 // The Microsoft extension __interface does not permit bases that
3037 // are not themselves public interfaces.
3038 Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
3039 << getRecordDiagFromTagKind(RD->getTagKind()) << RD
3040 << RD->getSourceRange();
3041 Invalid = true;
3042 }
3043 if (RD->hasAttr<WeakAttr>())
3044 Class->addAttr(WeakAttr::CreateImplicit(Context));
3045 }
3046 }
3047 }
3048
3049 // Attach the remaining base class specifiers to the derived class.
3050 Class->setBases(Bases.data(), NumGoodBases);
3051
3052 // Check that the only base classes that are duplicate are virtual.
3053 for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
3054 // Check whether this direct base is inaccessible due to ambiguity.
3055 QualType BaseType = Bases[idx]->getType();
3056
3057 // Skip all dependent types in templates being used as base specifiers.
3058 // Checks below assume that the base specifier is a CXXRecord.
3059 if (BaseType->isDependentType())
3060 continue;
3061
3062 CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
3063 .getUnqualifiedType();
3064
3065 if (IndirectBaseTypes.count(CanonicalBase)) {
3066 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3067 /*DetectVirtual=*/true);
3068 bool found
3069 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
3070 assert(found);
3071 (void)found;
3072
3073 if (Paths.isAmbiguous(CanonicalBase))
3074 Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
3075 << BaseType << getAmbiguousPathsDisplayString(Paths)
3076 << Bases[idx]->getSourceRange();
3077 else
3078 assert(Bases[idx]->isVirtual());
3079 }
3080
3081 // Delete the base class specifier, since its data has been copied
3082 // into the CXXRecordDecl.
3083 Context.Deallocate(Bases[idx]);
3084 }
3085
3086 return Invalid;
3087}
3088
3091 if (!ClassDecl || Bases.empty())
3092 return;
3093
3094 AdjustDeclIfTemplate(ClassDecl);
3095 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
3096}
3097
3099 CXXRecordDecl *Base, CXXBasePaths &Paths) {
3100 if (!getLangOpts().CPlusPlus)
3101 return false;
3102
3103 if (!Base || !Derived)
3104 return false;
3105
3106 // If either the base or the derived type is invalid, don't try to
3107 // check whether one is derived from the other.
3108 if (Base->isInvalidDecl() || Derived->isInvalidDecl())
3109 return false;
3110
3111 // FIXME: In a modules build, do we need the entire path to be visible for us
3112 // to be able to use the inheritance relationship?
3113 if (!isCompleteType(Loc, Context.getCanonicalTagType(Derived)) &&
3114 !Derived->isBeingDefined())
3115 return false;
3116
3117 return Derived->isDerivedFrom(Base, Paths);
3118}
3119
3122 CXXBasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/false,
3123 /*DetectVirtual=*/false);
3124 return IsDerivedFrom(Loc, Derived, Base, Paths);
3125}
3126
3128 CXXBasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/false,
3129 /*DetectVirtual=*/false);
3130 return IsDerivedFrom(Loc, Derived->getAsCXXRecordDecl(),
3131 Base->getAsCXXRecordDecl(), Paths);
3132}
3133
3135 CXXBasePaths &Paths) {
3136 return IsDerivedFrom(Loc, Derived->getAsCXXRecordDecl(),
3137 Base->getAsCXXRecordDecl(), Paths);
3138}
3139
3140static void BuildBasePathArray(const CXXBasePath &Path,
3141 CXXCastPath &BasePathArray) {
3142 // We first go backward and check if we have a virtual base.
3143 // FIXME: It would be better if CXXBasePath had the base specifier for
3144 // the nearest virtual base.
3145 unsigned Start = 0;
3146 for (unsigned I = Path.size(); I != 0; --I) {
3147 if (Path[I - 1].Base->isVirtual()) {
3148 Start = I - 1;
3149 break;
3150 }
3151 }
3152
3153 // Now add all bases.
3154 for (unsigned I = Start, E = Path.size(); I != E; ++I)
3155 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
3156}
3157
3158
3160 CXXCastPath &BasePathArray) {
3161 assert(BasePathArray.empty() && "Base path array must be empty!");
3162 assert(Paths.isRecordingPaths() && "Must record paths!");
3163 return ::BuildBasePathArray(Paths.front(), BasePathArray);
3164}
3165
3166bool
3168 unsigned InaccessibleBaseID,
3169 unsigned AmbiguousBaseConvID,
3170 SourceLocation Loc, SourceRange Range,
3171 DeclarationName Name,
3172 CXXCastPath *BasePath,
3173 bool IgnoreAccess) {
3174 // First, determine whether the path from Derived to Base is
3175 // ambiguous. This is slightly more expensive than checking whether
3176 // the Derived to Base conversion exists, because here we need to
3177 // explore multiple paths to determine if there is an ambiguity.
3178 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3179 /*DetectVirtual=*/false);
3180 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
3181 if (!DerivationOkay)
3182 return true;
3183
3184 const CXXBasePath *Path = nullptr;
3185 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
3186 Path = &Paths.front();
3187
3188 // For MSVC compatibility, check if Derived directly inherits from Base. Clang
3189 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
3190 // user to access such bases.
3191 if (!Path && getLangOpts().MSVCCompat) {
3192 for (const CXXBasePath &PossiblePath : Paths) {
3193 if (PossiblePath.size() == 1) {
3194 Path = &PossiblePath;
3195 if (AmbiguousBaseConvID)
3196 Diag(Loc, diag::ext_ms_ambiguous_direct_base)
3197 << Base << Derived << Range;
3198 break;
3199 }
3200 }
3201 }
3202
3203 if (Path) {
3204 if (!IgnoreAccess) {
3205 // Check that the base class can be accessed.
3206 switch (
3207 CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
3208 case AR_inaccessible:
3209 return true;
3210 case AR_accessible:
3211 case AR_dependent:
3212 case AR_delayed:
3213 break;
3214 }
3215 }
3216
3217 // Build a base path if necessary.
3218 if (BasePath)
3219 ::BuildBasePathArray(*Path, *BasePath);
3220 return false;
3221 }
3222
3223 if (AmbiguousBaseConvID) {
3224 // We know that the derived-to-base conversion is ambiguous, and
3225 // we're going to produce a diagnostic. Perform the derived-to-base
3226 // search just one more time to compute all of the possible paths so
3227 // that we can print them out. This is more expensive than any of
3228 // the previous derived-to-base checks we've done, but at this point
3229 // performance isn't as much of an issue.
3230 Paths.clear();
3231 Paths.setRecordingPaths(true);
3232 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
3233 assert(StillOkay && "Can only be used with a derived-to-base conversion");
3234 (void)StillOkay;
3235
3236 // Build up a textual representation of the ambiguous paths, e.g.,
3237 // D -> B -> A, that will be used to illustrate the ambiguous
3238 // conversions in the diagnostic. We only print one of the paths
3239 // to each base class subobject.
3240 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3241
3242 Diag(Loc, AmbiguousBaseConvID)
3243 << Derived << Base << PathDisplayStr << Range << Name;
3244 }
3245 return true;
3246}
3247
3248bool
3250 SourceLocation Loc, SourceRange Range,
3251 CXXCastPath *BasePath,
3252 bool IgnoreAccess) {
3254 Derived, Base, diag::err_upcast_to_inaccessible_base,
3255 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
3256 BasePath, IgnoreAccess);
3257}
3258
3260 std::string PathDisplayStr;
3261 std::set<unsigned> DisplayedPaths;
3262 for (const CXXBasePath &Path : Paths) {
3263 if (DisplayedPaths.insert(Path.back().SubobjectNumber).second) {
3264 // We haven't displayed a path to this particular base
3265 // class subobject yet.
3266 PathDisplayStr += "\n ";
3267 PathDisplayStr += QualType(Context.getCanonicalTagType(Paths.getOrigin()))
3268 .getAsString();
3269 for (const CXXBasePathElement &Element : Path)
3270 PathDisplayStr += " -> " + Element.Base->getType().getAsString();
3271 }
3272 }
3273
3274 return PathDisplayStr;
3275}
3276
3277//===----------------------------------------------------------------------===//
3278// C++ class member Handling
3279//===----------------------------------------------------------------------===//
3280
3282 SourceLocation ColonLoc,
3283 const ParsedAttributesView &Attrs) {
3284 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
3286 ASLoc, ColonLoc);
3287 CurContext->addHiddenDecl(ASDecl);
3288 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
3289}
3290
3292 if (D->isInvalidDecl())
3293 return;
3294
3295 // We only care about "override" and "final" declarations.
3296 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
3297 return;
3298
3299 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3300
3301 // We can't check dependent instance methods.
3302 if (MD && MD->isInstance() &&
3303 (MD->getParent()->hasAnyDependentBases() ||
3304 MD->getType()->isDependentType()))
3305 return;
3306
3307 if (MD && !MD->isVirtual()) {
3308 // If we have a non-virtual method, check if it hides a virtual method.
3309 // (In that case, it's most likely the method has the wrong type.)
3310 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3311 FindHiddenVirtualMethods(MD, OverloadedMethods);
3312
3313 if (!OverloadedMethods.empty()) {
3314 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3315 Diag(OA->getLocation(),
3316 diag::override_keyword_hides_virtual_member_function)
3317 << "override" << (OverloadedMethods.size() > 1);
3318 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3319 Diag(FA->getLocation(),
3320 diag::override_keyword_hides_virtual_member_function)
3321 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3322 << (OverloadedMethods.size() > 1);
3323 }
3324 NoteHiddenVirtualMethods(MD, OverloadedMethods);
3325 MD->setInvalidDecl();
3326 return;
3327 }
3328 // Fall through into the general case diagnostic.
3329 // FIXME: We might want to attempt typo correction here.
3330 }
3331
3332 if (!MD || !MD->isVirtual()) {
3333 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3334 Diag(OA->getLocation(),
3335 diag::override_keyword_only_allowed_on_virtual_member_functions)
3336 << "override" << FixItHint::CreateRemoval(OA->getLocation());
3337 D->dropAttr<OverrideAttr>();
3338 }
3339 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3340 Diag(FA->getLocation(),
3341 diag::override_keyword_only_allowed_on_virtual_member_functions)
3342 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3343 << FixItHint::CreateRemoval(FA->getLocation());
3344 D->dropAttr<FinalAttr>();
3345 }
3346 return;
3347 }
3348
3349 // C++11 [class.virtual]p5:
3350 // If a function is marked with the virt-specifier override and
3351 // does not override a member function of a base class, the program is
3352 // ill-formed.
3353 bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
3354 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
3355 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
3356 << MD->getDeclName();
3357}
3358
3360 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
3361 return;
3362 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3363 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
3364 return;
3365
3366 SourceLocation Loc = MD->getLocation();
3367 SourceLocation SpellingLoc = Loc;
3368 if (getSourceManager().isMacroArgExpansion(Loc))
3369 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
3370 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
3371 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
3372 return;
3373
3374 if (MD->size_overridden_methods() > 0) {
3375 auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) {
3376 unsigned DiagID =
3377 Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation())
3378 ? DiagInconsistent
3379 : DiagSuggest;
3380 Diag(MD->getLocation(), DiagID) << MD->getDeclName();
3381 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
3382 Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
3383 };
3384 if (isa<CXXDestructorDecl>(MD))
3385 EmitDiag(
3386 diag::warn_inconsistent_destructor_marked_not_override_overriding,
3387 diag::warn_suggest_destructor_marked_not_override_overriding);
3388 else
3389 EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding,
3390 diag::warn_suggest_function_marked_not_override_overriding);
3391 }
3392}
3393
3395 const CXXMethodDecl *Old) {
3396 FinalAttr *FA = Old->getAttr<FinalAttr>();
3397 if (!FA)
3398 return false;
3399
3400 Diag(New->getLocation(), diag::err_final_function_overridden)
3401 << New->getDeclName()
3402 << FA->isSpelledAsSealed();
3403 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3404 return true;
3405}
3406
3408 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
3409 // FIXME: Destruction of ObjC lifetime types has side-effects.
3410 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3411 return !RD->isCompleteDefinition() ||
3412 !RD->hasTrivialDefaultConstructor() ||
3413 !RD->hasTrivialDestructor();
3414 return false;
3415}
3416
3417void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
3418 DeclarationName FieldName,
3419 const CXXRecordDecl *RD,
3420 bool DeclIsField) {
3421 if (Diags.isIgnored(diag::warn_shadow_field, Loc))
3422 return;
3423
3424 // To record a shadowed field in a base
3425 std::map<CXXRecordDecl*, NamedDecl*> Bases;
3426 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
3427 CXXBasePath &Path) {
3428 const auto Base = Specifier->getType()->getAsCXXRecordDecl();
3429 // Record an ambiguous path directly
3430 if (Bases.find(Base) != Bases.end())
3431 return true;
3432 for (const auto Field : Base->lookup(FieldName)) {
3433 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
3434 Field->getAccess() != AS_private) {
3435 assert(Field->getAccess() != AS_none);
3436 assert(Bases.find(Base) == Bases.end());
3437 Bases[Base] = Field;
3438 return true;
3439 }
3440 }
3441 return false;
3442 };
3443
3444 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3445 /*DetectVirtual=*/true);
3446 if (!RD->lookupInBases(FieldShadowed, Paths))
3447 return;
3448
3449 for (const auto &P : Paths) {
3450 auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
3451 auto It = Bases.find(Base);
3452 // Skip duplicated bases
3453 if (It == Bases.end())
3454 continue;
3455 auto BaseField = It->second;
3456 assert(BaseField->getAccess() != AS_private);
3457 if (AS_none !=
3458 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
3459 Diag(Loc, diag::warn_shadow_field)
3460 << FieldName << RD << Base << DeclIsField;
3461 Diag(BaseField->getLocation(), diag::note_shadow_field);
3462 Bases.erase(It);
3463 }
3464 }
3465}
3466
3467template <typename AttrType>
3468inline static bool HasAttribute(const QualType &T) {
3469 if (const TagDecl *TD = T->getAsTagDecl())
3470 return TD->hasAttr<AttrType>();
3471 if (const TypedefType *TDT = T->getAs<TypedefType>())
3472 return TDT->getDecl()->hasAttr<AttrType>();
3473 return false;
3474}
3475
3476static bool IsUnusedPrivateField(const FieldDecl *FD) {
3477 if (FD->getAccess() == AS_private && FD->getDeclName()) {
3478 QualType FieldType = FD->getType();
3479 if (HasAttribute<WarnUnusedAttr>(FieldType))
3480 return true;
3481
3482 return !FD->isImplicit() && !FD->hasAttr<UnusedAttr>() &&
3483 !FD->getParent()->isDependentContext() &&
3484 !HasAttribute<UnusedAttr>(FieldType) &&
3486 }
3487 return false;
3488}
3489
3490NamedDecl *
3492 MultiTemplateParamsArg TemplateParameterLists,
3493 Expr *BitWidth, const VirtSpecifiers &VS,
3494 InClassInitStyle InitStyle) {
3495 const DeclSpec &DS = D.getDeclSpec();
3497 DeclarationName Name = NameInfo.getName();
3498 SourceLocation Loc = NameInfo.getLoc();
3499
3500 // For anonymous bitfields, the location should point to the type.
3501 if (Loc.isInvalid())
3502 Loc = D.getBeginLoc();
3503
3505 assert(!DS.isFriendSpecified());
3506
3507 bool isFunc = D.isDeclarationOfFunction();
3508 const ParsedAttr *MSPropertyAttr =
3510
3511 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
3512 // The Microsoft extension __interface only permits public member functions
3513 // and prohibits constructors, destructors, operators, non-public member
3514 // functions, static methods and data members.
3515 unsigned InvalidDecl;
3516 bool ShowDeclName = true;
3517 if (!isFunc &&
3518 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
3519 InvalidDecl = 0;
3520 else if (!isFunc)
3521 InvalidDecl = 1;
3522 else if (AS != AS_public)
3523 InvalidDecl = 2;
3525 InvalidDecl = 3;
3526 else switch (Name.getNameKind()) {
3528 InvalidDecl = 4;
3529 ShowDeclName = false;
3530 break;
3531
3533 InvalidDecl = 5;
3534 ShowDeclName = false;
3535 break;
3536
3539 InvalidDecl = 6;
3540 break;
3541
3542 default:
3543 InvalidDecl = 0;
3544 break;
3545 }
3546
3547 if (InvalidDecl) {
3548 if (ShowDeclName)
3549 Diag(Loc, diag::err_invalid_member_in_interface)
3550 << (InvalidDecl-1) << Name;
3551 else
3552 Diag(Loc, diag::err_invalid_member_in_interface)
3553 << (InvalidDecl-1) << "";
3554 return nullptr;
3555 }
3556 }
3557
3558 // HLSL prohibits user defined constructors and destructors.
3559 if (getLangOpts().HLSL) {
3560 switch (Name.getNameKind()) {
3563 Diag(Loc, diag::err_hlsl_cstor_dstor);
3564 return nullptr;
3565 default:
3566 break;
3567 }
3568 }
3569
3570 // C++ 9.2p6: A member shall not be declared to have automatic storage
3571 // duration (auto, register) or with the extern storage-class-specifier.
3572 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3573 // data members and cannot be applied to names declared const or static,
3574 // and cannot be applied to reference members.
3575 switch (DS.getStorageClassSpec()) {
3579 break;
3581 if (isFunc) {
3582 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3583
3584 // FIXME: It would be nicer if the keyword was ignored only for this
3585 // declarator. Otherwise we could get follow-up errors.
3587 }
3588 break;
3589 default:
3591 diag::err_storageclass_invalid_for_member);
3593 break;
3594 }
3595
3596 bool isInstField = (DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3598 !isFunc && TemplateParameterLists.empty();
3599
3600 if (DS.hasConstexprSpecifier() && isInstField) {
3602 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3603 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3604 if (InitStyle == ICIS_NoInit) {
3605 B << 0 << 0;
3607 B << FixItHint::CreateRemoval(ConstexprLoc);
3608 else {
3609 B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3611 const char *PrevSpec;
3612 unsigned DiagID;
3613 bool Failed = D.getMutableDeclSpec().SetTypeQual(
3614 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3615 (void)Failed;
3616 assert(!Failed && "Making a constexpr member const shouldn't fail");
3617 }
3618 } else {
3619 B << 1;
3620 const char *PrevSpec;
3621 unsigned DiagID;
3623 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3624 Context.getPrintingPolicy())) {
3626 "This is the only DeclSpec that should fail to be applied");
3627 B << 1;
3628 } else {
3629 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3630 isInstField = false;
3631 }
3632 }
3633 }
3634
3636 if (isInstField) {
3637 CXXScopeSpec &SS = D.getCXXScopeSpec();
3638
3639 // Data members must have identifiers for names.
3640 if (!Name.isIdentifier()) {
3641 Diag(Loc, diag::err_bad_variable_name)
3642 << Name;
3643 return nullptr;
3644 }
3645
3648 Diag(D.getIdentifierLoc(), diag::err_member_with_template_arguments)
3649 << II
3653 D.SetIdentifier(II, Loc);
3654 }
3655
3656 if (SS.isSet() && !SS.isInvalid()) {
3657 // The user provided a superfluous scope specifier inside a class
3658 // definition:
3659 //
3660 // class X {
3661 // int X::member;
3662 // };
3663 if (DeclContext *DC = computeDeclContext(SS, false)) {
3664 TemplateIdAnnotation *TemplateId =
3666 ? D.getName().TemplateId
3667 : nullptr;
3669 TemplateId,
3670 /*IsMemberSpecialization=*/false);
3671 } else {
3672 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3673 << Name << SS.getRange();
3674 }
3675 SS.clear();
3676 }
3677
3678 if (MSPropertyAttr) {
3680 BitWidth, InitStyle, AS, *MSPropertyAttr);
3681 if (!Member)
3682 return nullptr;
3683 isInstField = false;
3684 } else {
3686 BitWidth, InitStyle, AS);
3687 if (!Member)
3688 return nullptr;
3689 }
3690
3691 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3692 } else {
3693 Member = HandleDeclarator(S, D, TemplateParameterLists);
3694 if (!Member)
3695 return nullptr;
3696
3697 // Non-instance-fields can't have a bitfield.
3698 if (BitWidth) {
3699 if (Member->isInvalidDecl()) {
3700 // don't emit another diagnostic.
3702 // C++ 9.6p3: A bit-field shall not be a static member.
3703 // "static member 'A' cannot be a bit-field"
3704 Diag(Loc, diag::err_static_not_bitfield)
3705 << Name << BitWidth->getSourceRange();
3706 } else if (isa<TypedefDecl>(Member)) {
3707 // "typedef member 'x' cannot be a bit-field"
3708 Diag(Loc, diag::err_typedef_not_bitfield)
3709 << Name << BitWidth->getSourceRange();
3710 } else {
3711 // A function typedef ("typedef int f(); f a;").
3712 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3713 Diag(Loc, diag::err_not_integral_type_bitfield)
3714 << Name << cast<ValueDecl>(Member)->getType()
3715 << BitWidth->getSourceRange();
3716 }
3717
3718 BitWidth = nullptr;
3719 Member->setInvalidDecl();
3720 }
3721
3722 NamedDecl *NonTemplateMember = Member;
3723 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3724 NonTemplateMember = FunTmpl->getTemplatedDecl();
3725 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3726 NonTemplateMember = VarTmpl->getTemplatedDecl();
3727
3728 Member->setAccess(AS);
3729
3730 // If we have declared a member function template or static data member
3731 // template, set the access of the templated declaration as well.
3732 if (NonTemplateMember != Member)
3733 NonTemplateMember->setAccess(AS);
3734
3735 // C++ [temp.deduct.guide]p3:
3736 // A deduction guide [...] for a member class template [shall be
3737 // declared] with the same access [as the template].
3738 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3739 auto *TD = DG->getDeducedTemplate();
3740 // Access specifiers are only meaningful if both the template and the
3741 // deduction guide are from the same scope.
3742 if (AS != TD->getAccess() &&
3743 TD->getDeclContext()->getRedeclContext()->Equals(
3744 DG->getDeclContext()->getRedeclContext())) {
3745 Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3746 Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3747 << TD->getAccess();
3748 const AccessSpecDecl *LastAccessSpec = nullptr;
3749 for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3750 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3751 LastAccessSpec = AccessSpec;
3752 }
3753 assert(LastAccessSpec && "differing access with no access specifier");
3754 Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3755 << AS;
3756 }
3757 }
3758 }
3759
3760 if (VS.isOverrideSpecified())
3761 Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc()));
3762 if (VS.isFinalSpecified())
3763 Member->addAttr(FinalAttr::Create(Context, VS.getFinalLoc(),
3765 ? FinalAttr::Keyword_sealed
3766 : FinalAttr::Keyword_final));
3767
3768 if (VS.getLastLocation().isValid()) {
3769 // Update the end location of a method that has a virt-specifiers.
3770 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3771 MD->setRangeEnd(VS.getLastLocation());
3772 }
3773
3775
3776 assert((Name || isInstField) && "No identifier for non-field ?");
3777
3778 if (isInstField) {
3780 FieldCollector->Add(FD);
3781
3782 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation()) &&
3784 // Remember all explicit private FieldDecls that have a name, no side
3785 // effects and are not part of a dependent type declaration.
3786 UnusedPrivateFields.insert(FD);
3787 }
3788 }
3789
3790 return Member;
3791}
3792
3793namespace {
3794 class UninitializedFieldVisitor
3795 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3796 Sema &S;
3797 // List of Decls to generate a warning on. Also remove Decls that become
3798 // initialized.
3799 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3800 // List of base classes of the record. Classes are removed after their
3801 // initializers.
3802 llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3803 // Vector of decls to be removed from the Decl set prior to visiting the
3804 // nodes. These Decls may have been initialized in the prior initializer.
3806 // If non-null, add a note to the warning pointing back to the constructor.
3808 // Variables to hold state when processing an initializer list. When
3809 // InitList is true, special case initialization of FieldDecls matching
3810 // InitListFieldDecl.
3811 bool InitList;
3812 FieldDecl *InitListFieldDecl;
3813 llvm::SmallVector<unsigned, 4> InitFieldIndex;
3814
3815 public:
3817 UninitializedFieldVisitor(Sema &S,
3818 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3819 llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3820 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3821 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3822
3823 // Returns true if the use of ME is not an uninitialized use.
3824 bool IsInitListMemberExprInitialized(MemberExpr *ME,
3825 bool CheckReferenceOnly) {
3827 bool ReferenceField = false;
3828 while (ME) {
3829 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3830 if (!FD)
3831 return false;
3832 Fields.push_back(FD);
3833 if (FD->getType()->isReferenceType())
3834 ReferenceField = true;
3835 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3836 }
3837
3838 // Binding a reference to an uninitialized field is not an
3839 // uninitialized use.
3840 if (CheckReferenceOnly && !ReferenceField)
3841 return true;
3842
3843 // Discard the first field since it is the field decl that is being
3844 // initialized.
3845 auto UsedFields = llvm::drop_begin(llvm::reverse(Fields));
3846 auto UsedIter = UsedFields.begin();
3847 const auto UsedEnd = UsedFields.end();
3848
3849 for (const unsigned Orig : InitFieldIndex) {
3850 if (UsedIter == UsedEnd)
3851 break;
3852 const unsigned UsedIndex = (*UsedIter)->getFieldIndex();
3853 if (UsedIndex < Orig)
3854 return true;
3855 if (UsedIndex > Orig)
3856 break;
3857 ++UsedIter;
3858 }
3859
3860 return false;
3861 }
3862
3863 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3864 bool AddressOf) {
3866 return;
3867
3868 // FieldME is the inner-most MemberExpr that is not an anonymous struct
3869 // or union.
3870 MemberExpr *FieldME = ME;
3871
3872 bool AllPODFields = FieldME->getType().isPODType(S.Context);
3873
3874 Expr *Base = ME;
3875 while (MemberExpr *SubME =
3876 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3877
3878 if (isa<VarDecl>(SubME->getMemberDecl()))
3879 return;
3880
3881 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3882 if (!FD->isAnonymousStructOrUnion())
3883 FieldME = SubME;
3884
3885 if (!FieldME->getType().isPODType(S.Context))
3886 AllPODFields = false;
3887
3888 Base = SubME->getBase();
3889 }
3890
3891 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) {
3892 Visit(Base);
3893 return;
3894 }
3895
3896 if (AddressOf && AllPODFields)
3897 return;
3898
3899 ValueDecl* FoundVD = FieldME->getMemberDecl();
3900
3901 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3902 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3903 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3904 }
3905
3906 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3907 QualType T = BaseCast->getType();
3908 if (T->isPointerType() &&
3909 BaseClasses.count(T->getPointeeType())) {
3910 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3911 << T->getPointeeType() << FoundVD;
3912 }
3913 }
3914 }
3915
3916 if (!Decls.count(FoundVD))
3917 return;
3918
3919 const bool IsReference = FoundVD->getType()->isReferenceType();
3920
3921 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3922 // Special checking for initializer lists.
3923 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3924 return;
3925 }
3926 } else {
3927 // Prevent double warnings on use of unbounded references.
3928 if (CheckReferenceOnly && !IsReference)
3929 return;
3930 }
3931
3932 unsigned diag = IsReference
3933 ? diag::warn_reference_field_is_uninit
3934 : diag::warn_field_is_uninit;
3935 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3936 if (Constructor)
3937 S.Diag(Constructor->getLocation(),
3938 diag::note_uninit_in_this_constructor)
3939 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3940
3941 }
3942
3943 void HandleValue(Expr *E, bool AddressOf) {
3944 E = E->IgnoreParens();
3945
3946 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3947 HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3948 AddressOf /*AddressOf*/);
3949 return;
3950 }
3951
3952 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3953 Visit(CO->getCond());
3954 HandleValue(CO->getTrueExpr(), AddressOf);
3955 HandleValue(CO->getFalseExpr(), AddressOf);
3956 return;
3957 }
3958
3959 if (BinaryConditionalOperator *BCO =
3960 dyn_cast<BinaryConditionalOperator>(E)) {
3961 Visit(BCO->getCond());
3962 HandleValue(BCO->getFalseExpr(), AddressOf);
3963 return;
3964 }
3965
3966 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3967 HandleValue(OVE->getSourceExpr(), AddressOf);
3968 return;
3969 }
3970
3971 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3972 switch (BO->getOpcode()) {
3973 default:
3974 break;
3975 case(BO_PtrMemD):
3976 case(BO_PtrMemI):
3977 HandleValue(BO->getLHS(), AddressOf);
3978 Visit(BO->getRHS());
3979 return;
3980 case(BO_Comma):
3981 Visit(BO->getLHS());
3982 HandleValue(BO->getRHS(), AddressOf);
3983 return;
3984 }
3985 }
3986
3987 Visit(E);
3988 }
3989
3990 void CheckInitListExpr(InitListExpr *ILE) {
3991 InitFieldIndex.push_back(0);
3992 for (auto *Child : ILE->children()) {
3993 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3994 CheckInitListExpr(SubList);
3995 } else {
3996 Visit(Child);
3997 }
3998 ++InitFieldIndex.back();
3999 }
4000 InitFieldIndex.pop_back();
4001 }
4002
4003 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
4004 FieldDecl *Field, const Type *BaseClass) {
4005 // Remove Decls that may have been initialized in the previous
4006 // initializer.
4007 for (ValueDecl* VD : DeclsToRemove)
4008 Decls.erase(VD);
4009 DeclsToRemove.clear();
4010
4011 Constructor = FieldConstructor;
4012 InitListExpr *ILE = dyn_cast<InitListExpr>(E);
4013
4014 if (ILE && Field) {
4015 InitList = true;
4016 InitListFieldDecl = Field;
4017 InitFieldIndex.clear();
4018 CheckInitListExpr(ILE);
4019 } else {
4020 InitList = false;
4021 Visit(E);
4022 }
4023
4024 if (Field)
4025 Decls.erase(Field);
4026 if (BaseClass)
4027 BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
4028 }
4029
4030 void VisitMemberExpr(MemberExpr *ME) {
4031 // All uses of unbounded reference fields will warn.
4032 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
4033 }
4034
4035 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
4036 if (E->getCastKind() == CK_LValueToRValue) {
4037 HandleValue(E->getSubExpr(), false /*AddressOf*/);
4038 return;
4039 }
4040
4041 Inherited::VisitImplicitCastExpr(E);
4042 }
4043
4044 void VisitCXXConstructExpr(CXXConstructExpr *E) {
4045 if (E->getConstructor()->isCopyConstructor()) {
4046 Expr *ArgExpr = E->getArg(0);
4047 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
4048 if (ILE->getNumInits() == 1)
4049 ArgExpr = ILE->getInit(0);
4050 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
4051 if (ICE->getCastKind() == CK_NoOp)
4052 ArgExpr = ICE->getSubExpr();
4053 HandleValue(ArgExpr, false /*AddressOf*/);
4054 return;
4055 }
4056 Inherited::VisitCXXConstructExpr(E);
4057 }
4058
4059 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
4060 Expr *Callee = E->getCallee();
4061 if (isa<MemberExpr>(Callee)) {
4062 HandleValue(Callee, false /*AddressOf*/);
4063 for (auto *Arg : E->arguments())
4064 Visit(Arg);
4065 return;
4066 }
4067
4068 Inherited::VisitCXXMemberCallExpr(E);
4069 }
4070
4071 void VisitCallExpr(CallExpr *E) {
4072 // Treat std::move as a use.
4073 if (E->isCallToStdMove()) {
4074 HandleValue(E->getArg(0), /*AddressOf=*/false);
4075 return;
4076 }
4077
4078 Inherited::VisitCallExpr(E);
4079 }
4080
4081 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
4082 Expr *Callee = E->getCallee();
4083
4084 if (isa<UnresolvedLookupExpr>(Callee))
4085 return Inherited::VisitCXXOperatorCallExpr(E);
4086
4087 Visit(Callee);
4088 for (auto *Arg : E->arguments())
4089 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
4090 }
4091
4092 void VisitBinaryOperator(BinaryOperator *E) {
4093 // If a field assignment is detected, remove the field from the
4094 // uninitiailized field set.
4095 if (E->getOpcode() == BO_Assign)
4096 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
4097 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
4098 if (!FD->getType()->isReferenceType())
4099 DeclsToRemove.push_back(FD);
4100
4101 if (E->isCompoundAssignmentOp()) {
4102 HandleValue(E->getLHS(), false /*AddressOf*/);
4103 Visit(E->getRHS());
4104 return;
4105 }
4106
4107 Inherited::VisitBinaryOperator(E);
4108 }
4109
4110 void VisitUnaryOperator(UnaryOperator *E) {
4111 if (E->isIncrementDecrementOp()) {
4112 HandleValue(E->getSubExpr(), false /*AddressOf*/);
4113 return;
4114 }
4115 if (E->getOpcode() == UO_AddrOf) {
4116 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
4117 HandleValue(ME->getBase(), true /*AddressOf*/);
4118 return;
4119 }
4120 }
4121
4122 Inherited::VisitUnaryOperator(E);
4123 }
4124 };
4125
4126 // Diagnose value-uses of fields to initialize themselves, e.g.
4127 // foo(foo)
4128 // where foo is not also a parameter to the constructor.
4129 // Also diagnose across field uninitialized use such as
4130 // x(y), y(x)
4131 // TODO: implement -Wuninitialized and fold this into that framework.
4132 static void DiagnoseUninitializedFields(
4133 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
4134
4135 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
4136 Constructor->getLocation())) {
4137 return;
4138 }
4139
4140 if (Constructor->isInvalidDecl())
4141 return;
4142
4143 const CXXRecordDecl *RD = Constructor->getParent();
4144
4145 if (RD->isDependentContext())
4146 return;
4147
4148 // Holds fields that are uninitialized.
4149 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
4150
4151 // At the beginning, all fields are uninitialized.
4152 for (auto *I : RD->decls()) {
4153 if (auto *FD = dyn_cast<FieldDecl>(I)) {
4154 UninitializedFields.insert(FD);
4155 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
4156 UninitializedFields.insert(IFD->getAnonField());
4157 }
4158 }
4159
4160 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
4161 for (const auto &I : RD->bases())
4162 UninitializedBaseClasses.insert(I.getType().getCanonicalType());
4163
4164 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
4165 return;
4166
4167 UninitializedFieldVisitor UninitializedChecker(SemaRef,
4168 UninitializedFields,
4169 UninitializedBaseClasses);
4170
4171 for (const auto *FieldInit : Constructor->inits()) {
4172 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
4173 break;
4174
4175 Expr *InitExpr = FieldInit->getInit();
4176 if (!InitExpr)
4177 continue;
4178
4179 if (CXXDefaultInitExpr *Default =
4180 dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
4181 InitExpr = Default->getExpr();
4182 if (!InitExpr)
4183 continue;
4184 // In class initializers will point to the constructor.
4185 UninitializedChecker.CheckInitializer(InitExpr, Constructor,
4186 FieldInit->getAnyMember(),
4187 FieldInit->getBaseClass());
4188 } else {
4189 UninitializedChecker.CheckInitializer(InitExpr, nullptr,
4190 FieldInit->getAnyMember(),
4191 FieldInit->getBaseClass());
4192 }
4193 }
4194 }
4195} // namespace
4196
4198 // Create a synthetic function scope to represent the call to the constructor
4199 // that notionally surrounds a use of this initializer.
4201}
4202
4204 if (!D.isFunctionDeclarator())
4205 return;
4206 auto &FTI = D.getFunctionTypeInfo();
4207 if (!FTI.Params)
4208 return;
4209 for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params,
4210 FTI.NumParams)) {
4211 auto *ParamDecl = cast<NamedDecl>(Param.Param);
4212 if (ParamDecl->getDeclName())
4213 PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false);
4214 }
4215}
4216
4218 return ActOnRequiresClause(ConstraintExpr);
4219}
4220
4222 if (ConstraintExpr.isInvalid())
4223 return ExprError();
4224
4225 if (DiagnoseUnexpandedParameterPack(ConstraintExpr.get(),
4227 return ExprError();
4228
4229 return ConstraintExpr;
4230}
4231
4233 Expr *InitExpr,
4234 SourceLocation InitLoc) {
4235 InitializedEntity Entity =
4237 InitializationKind Kind =
4240 InitExpr->getBeginLoc(),
4241 InitExpr->getEndLoc())
4242 : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
4243 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
4244 return Seq.Perform(*this, Entity, Kind, InitExpr);
4245}
4246
4248 SourceLocation InitLoc,
4249 ExprResult InitExpr) {
4250 // Pop the notional constructor scope we created earlier.
4251 PopFunctionScopeInfo(nullptr, D);
4252
4253 // Microsoft C++'s property declaration cannot have a default member
4254 // initializer.
4255 if (isa<MSPropertyDecl>(D)) {
4256 D->setInvalidDecl();
4257 return;
4258 }
4259
4260 FieldDecl *FD = dyn_cast<FieldDecl>(D);
4261 assert((FD && FD->getInClassInitStyle() != ICIS_NoInit) &&
4262 "must set init style when field is created");
4263
4264 if (!InitExpr.isUsable() ||
4266 FD->setInvalidDecl();
4267 ExprResult RecoveryInit =
4268 CreateRecoveryExpr(InitLoc, InitLoc, {}, FD->getType());
4269 if (RecoveryInit.isUsable())
4270 FD->setInClassInitializer(RecoveryInit.get());
4271 return;
4272 }
4273
4274 if (!FD->getType()->isDependentType() && !InitExpr.get()->isTypeDependent()) {
4275 InitExpr = ConvertMemberDefaultInitExpression(FD, InitExpr.get(), InitLoc);
4276 // C++11 [class.base.init]p7:
4277 // The initialization of each base and member constitutes a
4278 // full-expression.
4279 if (!InitExpr.isInvalid())
4280 InitExpr = ActOnFinishFullExpr(InitExpr.get(), /*DiscarededValue=*/false);
4281 if (InitExpr.isInvalid()) {
4282 FD->setInvalidDecl();
4283 return;
4284 }
4285 }
4286
4287 FD->setInClassInitializer(InitExpr.get());
4288}
4289
4290/// Find the direct and/or virtual base specifiers that
4291/// correspond to the given base type, for use in base initialization
4292/// within a constructor.
4293static bool FindBaseInitializer(Sema &SemaRef,
4294 CXXRecordDecl *ClassDecl,
4295 QualType BaseType,
4296 const CXXBaseSpecifier *&DirectBaseSpec,
4297 const CXXBaseSpecifier *&VirtualBaseSpec) {
4298 // First, check for a direct base class.
4299 DirectBaseSpec = nullptr;
4300 for (const auto &Base : ClassDecl->bases()) {
4301 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
4302 // We found a direct base of this type. That's what we're
4303 // initializing.
4304 DirectBaseSpec = &Base;
4305 break;
4306 }
4307 }
4308
4309 // Check for a virtual base class.
4310 // FIXME: We might be able to short-circuit this if we know in advance that
4311 // there are no virtual bases.
4312 VirtualBaseSpec = nullptr;
4313 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
4314 // We haven't found a base yet; search the class hierarchy for a
4315 // virtual base class.
4316 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
4317 /*DetectVirtual=*/false);
4318 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
4319 SemaRef.Context.getCanonicalTagType(ClassDecl),
4320 BaseType, Paths)) {
4321 for (const CXXBasePath &Path : Paths) {
4322 if (Path.back().Base->isVirtual()) {
4323 VirtualBaseSpec = Path.back().Base;
4324 break;
4325 }
4326 }
4327 }
4328 }
4329
4330 return DirectBaseSpec || VirtualBaseSpec;
4331}
4332
4335 Scope *S,
4336 CXXScopeSpec &SS,
4337 IdentifierInfo *MemberOrBase,
4338 ParsedType TemplateTypeTy,
4339 const DeclSpec &DS,
4340 SourceLocation IdLoc,
4341 Expr *InitList,
4342 SourceLocation EllipsisLoc) {
4343 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4344 DS, IdLoc, InitList,
4345 EllipsisLoc);
4346}
4347
4350 Scope *S,
4351 CXXScopeSpec &SS,
4352 IdentifierInfo *MemberOrBase,
4353 ParsedType TemplateTypeTy,
4354 const DeclSpec &DS,
4355 SourceLocation IdLoc,
4356 SourceLocation LParenLoc,
4357 ArrayRef<Expr *> Args,
4358 SourceLocation RParenLoc,
4359 SourceLocation EllipsisLoc) {
4360 Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
4361 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4362 DS, IdLoc, List, EllipsisLoc);
4363}
4364
4365namespace {
4366
4367// Callback to only accept typo corrections that can be a valid C++ member
4368// initializer: either a non-static field member or a base class.
4369class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
4370public:
4371 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
4372 : ClassDecl(ClassDecl) {}
4373
4374 bool ValidateCandidate(const TypoCorrection &candidate) override {
4375 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
4376 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
4377 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
4378 return isa<TypeDecl>(ND);
4379 }
4380 return false;
4381 }
4382
4383 std::unique_ptr<CorrectionCandidateCallback> clone() override {
4384 return std::make_unique<MemInitializerValidatorCCC>(*this);
4385 }
4386
4387private:
4388 CXXRecordDecl *ClassDecl;
4389};
4390
4391}
4392
4394 RecordDecl *ClassDecl,
4395 const IdentifierInfo *Name) {
4396 DeclContextLookupResult Result = ClassDecl->lookup(Name);
4398 llvm::find_if(Result, [this](const NamedDecl *Elem) {
4399 return isa<FieldDecl, IndirectFieldDecl>(Elem) &&
4401 });
4402 // We did not find a placeholder variable
4403 if (Found == Result.end())
4404 return false;
4405 Diag(Loc, diag::err_using_placeholder_variable) << Name;
4406 for (DeclContextLookupResult::iterator It = Found; It != Result.end(); It++) {
4407 const NamedDecl *ND = *It;
4408 if (ND->getDeclContext() != ND->getDeclContext())
4409 break;
4412 Diag(ND->getLocation(), diag::note_reference_placeholder) << ND;
4413 }
4414 return true;
4415}
4416
4417ValueDecl *
4419 const IdentifierInfo *MemberOrBase) {
4420 ValueDecl *ND = nullptr;
4421 for (auto *D : ClassDecl->lookup(MemberOrBase)) {
4423 bool IsPlaceholder = D->isPlaceholderVar(getLangOpts());
4424 if (ND) {
4425 if (IsPlaceholder && D->getDeclContext() == ND->getDeclContext())
4426 return nullptr;
4427 break;
4428 }
4429 if (!IsPlaceholder)
4430 return cast<ValueDecl>(D);
4431 ND = cast<ValueDecl>(D);
4432 }
4433 }
4434 return ND;
4435}
4436
4438 CXXScopeSpec &SS,
4439 ParsedType TemplateTypeTy,
4440 IdentifierInfo *MemberOrBase) {
4441 if (SS.getScopeRep() || TemplateTypeTy)
4442 return nullptr;
4443 return tryLookupUnambiguousFieldDecl(ClassDecl, MemberOrBase);
4444}
4445
4448 Scope *S,
4449 CXXScopeSpec &SS,
4450 IdentifierInfo *MemberOrBase,
4451 ParsedType TemplateTypeTy,
4452 const DeclSpec &DS,
4453 SourceLocation IdLoc,
4454 Expr *Init,
4455 SourceLocation EllipsisLoc) {
4456 if (!ConstructorD || !Init)
4457 return true;
4458
4459 AdjustDeclIfTemplate(ConstructorD);
4460
4462 = dyn_cast<CXXConstructorDecl>(ConstructorD);
4463 if (!Constructor) {
4464 // The user wrote a constructor initializer on a function that is
4465 // not a C++ constructor. Ignore the error for now, because we may
4466 // have more member initializers coming; we'll diagnose it just
4467 // once in ActOnMemInitializers.
4468 return true;
4469 }
4470
4471 CXXRecordDecl *ClassDecl = Constructor->getParent();
4472
4473 // C++ [class.base.init]p2:
4474 // Names in a mem-initializer-id are looked up in the scope of the
4475 // constructor's class and, if not found in that scope, are looked
4476 // up in the scope containing the constructor's definition.
4477 // [Note: if the constructor's class contains a member with the
4478 // same name as a direct or virtual base class of the class, a
4479 // mem-initializer-id naming the member or base class and composed
4480 // of a single identifier refers to the class member. A
4481 // mem-initializer-id for the hidden base class may be specified
4482 // using a qualified name. ]
4483
4484 // Look for a member, first.
4486 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
4487 if (EllipsisLoc.isValid())
4488 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
4489 << MemberOrBase
4490 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4491
4492 return BuildMemberInitializer(Member, Init, IdLoc);
4493 }
4494 // It didn't name a member, so see if it names a class.
4495 QualType BaseType;
4496 TypeSourceInfo *TInfo = nullptr;
4497
4498 if (TemplateTypeTy) {
4499 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
4500 if (BaseType.isNull())
4501 return true;
4502 } else if (DS.getTypeSpecType() == TST_decltype) {
4503 BaseType = BuildDecltypeType(DS.getRepAsExpr());
4504 } else if (DS.getTypeSpecType() == TST_decltype_auto) {
4505 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
4506 return true;
4507 } else if (DS.getTypeSpecType() == TST_typename_pack_indexing) {
4508 BaseType =
4510 DS.getBeginLoc(), DS.getEllipsisLoc());
4511 } else {
4512 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
4513 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
4514
4515 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
4516 if (!TyD) {
4517 if (R.isAmbiguous()) return true;
4518
4519 // We don't want access-control diagnostics here.
4520 R.suppressDiagnostics();
4521
4522 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
4523 bool NotUnknownSpecialization = false;
4524 DeclContext *DC = computeDeclContext(SS, false);
4525 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
4526 NotUnknownSpecialization = !Record->hasAnyDependentBases();
4527
4528 if (!NotUnknownSpecialization) {
4529 // When the scope specifier can refer to a member of an unknown
4530 // specialization, we take it as a type name.
4531 BaseType = CheckTypenameType(
4533 SS.getWithLocInContext(Context), *MemberOrBase, IdLoc);
4534 if (BaseType.isNull())
4535 return true;
4536
4537 TInfo = Context.CreateTypeSourceInfo(BaseType);
4540 if (!TL.isNull()) {
4541 TL.setNameLoc(IdLoc);
4544 }
4545
4546 R.clear();
4547 R.setLookupName(MemberOrBase);
4548 }
4549 }
4550
4551 if (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus20) {
4552 if (auto UnqualifiedBase = R.getAsSingle<ClassTemplateDecl>()) {
4553 auto *TempSpec = cast<TemplateSpecializationType>(
4554 UnqualifiedBase->getCanonicalInjectedSpecializationType(Context));
4555 TemplateName TN = TempSpec->getTemplateName();
4556 for (auto const &Base : ClassDecl->bases()) {
4557 auto BaseTemplate =
4558 Base.getType()->getAs<TemplateSpecializationType>();
4559 if (BaseTemplate &&
4560 Context.hasSameTemplateName(BaseTemplate->getTemplateName(), TN,
4561 /*IgnoreDeduced=*/true)) {
4562 Diag(IdLoc, diag::ext_unqualified_base_class)
4563 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4564 BaseType = Base.getType();
4565 break;
4566 }
4567 }
4568 }
4569 }
4570
4571 // If no results were found, try to correct typos.
4572 TypoCorrection Corr;
4573 MemInitializerValidatorCCC CCC(ClassDecl);
4574 if (R.empty() && BaseType.isNull() &&
4575 (Corr =
4576 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
4577 CCC, CorrectTypoKind::ErrorRecovery, ClassDecl))) {
4579 // We have found a non-static data member with a similar
4580 // name to what was typed; complain and initialize that
4581 // member.
4582 diagnoseTypo(Corr,
4583 PDiag(diag::err_mem_init_not_member_or_class_suggest)
4584 << MemberOrBase << true);
4585 return BuildMemberInitializer(Member, Init, IdLoc);
4586 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
4587 const CXXBaseSpecifier *DirectBaseSpec;
4588 const CXXBaseSpecifier *VirtualBaseSpec;
4589 if (FindBaseInitializer(*this, ClassDecl,
4590 Context.getTypeDeclType(Type),
4591 DirectBaseSpec, VirtualBaseSpec)) {
4592 // We have found a direct or virtual base class with a
4593 // similar name to what was typed; complain and initialize
4594 // that base class.
4595 diagnoseTypo(Corr,
4596 PDiag(diag::err_mem_init_not_member_or_class_suggest)
4597 << MemberOrBase << false,
4598 PDiag() /*Suppress note, we provide our own.*/);
4599
4600 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
4601 : VirtualBaseSpec;
4602 Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
4603 << BaseSpec->getType() << BaseSpec->getSourceRange();
4604
4605 TyD = Type;
4606 }
4607 }
4608 }
4609
4610 if (!TyD && BaseType.isNull()) {
4611 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
4612 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4613 return true;
4614 }
4615 }
4616
4617 if (BaseType.isNull()) {
4618 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
4619
4620 TypeLocBuilder TLB;
4621 // FIXME: This is missing building the UsingType for TyD, if any.
4622 if (const auto *TD = dyn_cast<TagDecl>(TyD)) {
4623 BaseType = Context.getTagType(ElaboratedTypeKeyword::None,
4624 SS.getScopeRep(), TD, /*OwnsTag=*/false);
4625 auto TL = TLB.push<TagTypeLoc>(BaseType);
4627 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4628 TL.setNameLoc(IdLoc);
4629 } else if (auto *TN = dyn_cast<TypedefNameDecl>(TyD)) {
4630 BaseType = Context.getTypedefType(ElaboratedTypeKeyword::None,
4631 SS.getScopeRep(), TN);
4632 TLB.push<TypedefTypeLoc>(BaseType).set(
4633 /*ElaboratedKeywordLoc=*/SourceLocation(),
4634 SS.getWithLocInContext(Context), IdLoc);
4635 } else if (auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(TyD)) {
4636 BaseType = Context.getUnresolvedUsingType(ElaboratedTypeKeyword::None,
4637 SS.getScopeRep(), UD);
4638 TLB.push<UnresolvedUsingTypeLoc>(BaseType).set(
4639 /*ElaboratedKeywordLoc=*/SourceLocation(),
4640 SS.getWithLocInContext(Context), IdLoc);
4641 } else {
4642 // FIXME: What else can appear here?
4643 assert(SS.isEmpty());
4644 BaseType = Context.getTypeDeclType(TyD);
4645 TLB.pushTypeSpec(BaseType).setNameLoc(IdLoc);
4646 }
4647 TInfo = TLB.getTypeSourceInfo(Context, BaseType);
4648 }
4649 }
4650
4651 if (!TInfo)
4652 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
4653
4654 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
4655}
4656
4659 SourceLocation IdLoc) {
4660 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
4661 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
4662 assert((DirectMember || IndirectMember) &&
4663 "Member must be a FieldDecl or IndirectFieldDecl");
4664
4666 return true;
4667
4668 if (Member->isInvalidDecl())
4669 return true;
4670
4671 MultiExprArg Args;
4672 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4673 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4674 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4675 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4676 } else {
4677 // Template instantiation doesn't reconstruct ParenListExprs for us.
4678 Args = Init;
4679 }
4680
4681 SourceRange InitRange = Init->getSourceRange();
4682
4683 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4684 // Can't check initialization for a member of dependent type or when
4685 // any of the arguments are type-dependent expressions.
4687 } else {
4688 bool InitList = false;
4689 if (isa<InitListExpr>(Init)) {
4690 InitList = true;
4691 Args = Init;
4692 }
4693
4694 // Initialize the member.
4695 InitializedEntity MemberEntity =
4696 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4697 : InitializedEntity::InitializeMember(IndirectMember,
4698 nullptr);
4699 InitializationKind Kind =
4701 IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4702 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4703 InitRange.getEnd());
4704
4705 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4706 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4707 nullptr);
4708 if (!MemberInit.isInvalid()) {
4709 // C++11 [class.base.init]p7:
4710 // The initialization of each base and member constitutes a
4711 // full-expression.
4712 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
4713 /*DiscardedValue*/ false);
4714 }
4715
4716 if (MemberInit.isInvalid()) {
4717 // Args were sensible expressions but we couldn't initialize the member
4718 // from them. Preserve them in a RecoveryExpr instead.
4719 Init = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,
4720 Member->getType())
4721 .get();
4722 if (!Init)
4723 return true;
4724 } else {
4725 Init = MemberInit.get();
4726 }
4727 }
4728
4729 if (DirectMember) {
4730 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4731 InitRange.getBegin(), Init,
4732 InitRange.getEnd());
4733 } else {
4734 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4735 InitRange.getBegin(), Init,
4736 InitRange.getEnd());
4737 }
4738}
4739
4742 CXXRecordDecl *ClassDecl) {
4743 SourceLocation NameLoc = TInfo->getTypeLoc().getSourceRange().getBegin();
4744 if (!LangOpts.CPlusPlus11)
4745 return Diag(NameLoc, diag::err_delegating_ctor)
4746 << TInfo->getTypeLoc().getSourceRange();
4747 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4748
4749 bool InitList = true;
4750 MultiExprArg Args = Init;
4751 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4752 InitList = false;
4753 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4754 }
4755
4756 CanQualType ClassType = Context.getCanonicalTagType(ClassDecl);
4757
4758 SourceRange InitRange = Init->getSourceRange();
4759 // Initialize the object.
4760 InitializedEntity DelegationEntity =
4762 InitializationKind Kind =
4764 NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4765 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4766 InitRange.getEnd());
4767 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4768 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4769 Args, nullptr);
4770 if (!DelegationInit.isInvalid()) {
4771 assert((DelegationInit.get()->containsErrors() ||
4772 cast<CXXConstructExpr>(DelegationInit.get())->getConstructor()) &&
4773 "Delegating constructor with no target?");
4774
4775 // C++11 [class.base.init]p7:
4776 // The initialization of each base and member constitutes a
4777 // full-expression.
4778 DelegationInit = ActOnFinishFullExpr(
4779 DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
4780 }
4781
4782 if (DelegationInit.isInvalid()) {
4783 DelegationInit = CreateRecoveryExpr(InitRange.getBegin(),
4784 InitRange.getEnd(), Args, ClassType);
4785 if (DelegationInit.isInvalid())
4786 return true;
4787 } else {
4788 // If we are in a dependent context, template instantiation will
4789 // perform this type-checking again. Just save the arguments that we
4790 // received in a ParenListExpr.
4791 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4792 // of the information that we have about the base
4793 // initializer. However, deconstructing the ASTs is a dicey process,
4794 // and this approach is far more likely to get the corner cases right.
4795 if (CurContext->isDependentContext())
4796 DelegationInit = Init;
4797 }
4798
4799 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4800 DelegationInit.getAs<Expr>(),
4801 InitRange.getEnd());
4802}
4803
4806 Expr *Init, CXXRecordDecl *ClassDecl,
4807 SourceLocation EllipsisLoc) {
4808 SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getBeginLoc();
4809
4810 if (!BaseType->isDependentType() && !BaseType->isRecordType())
4811 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4812 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
4813
4814 // C++ [class.base.init]p2:
4815 // [...] Unless the mem-initializer-id names a nonstatic data
4816 // member of the constructor's class or a direct or virtual base
4817 // of that class, the mem-initializer is ill-formed. A
4818 // mem-initializer-list can initialize a base class using any
4819 // name that denotes that base class type.
4820
4821 // We can store the initializers in "as-written" form and delay analysis until
4822 // instantiation if the constructor is dependent. But not for dependent
4823 // (broken) code in a non-template! SetCtorInitializers does not expect this.
4824 bool Dependent = CurContext->isDependentContext() &&
4825 (BaseType->isDependentType() || Init->isTypeDependent());
4826
4827 SourceRange InitRange = Init->getSourceRange();
4828 if (EllipsisLoc.isValid()) {
4829 // This is a pack expansion.
4830 if (!BaseType->containsUnexpandedParameterPack()) {
4831 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4832 << SourceRange(BaseLoc, InitRange.getEnd());
4833
4834 EllipsisLoc = SourceLocation();
4835 }
4836 } else {
4837 // Check for any unexpanded parameter packs.
4838 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4839 return true;
4840
4842 return true;
4843 }
4844
4845 // Check for direct and virtual base classes.
4846 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4847 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4848 if (!Dependent) {
4849 if (declaresSameEntity(ClassDecl, BaseType->getAsCXXRecordDecl()))
4850 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4851
4852 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4853 VirtualBaseSpec);
4854
4855 // C++ [base.class.init]p2:
4856 // Unless the mem-initializer-id names a nonstatic data member of the
4857 // constructor's class or a direct or virtual base of that class, the
4858 // mem-initializer is ill-formed.
4859 if (!DirectBaseSpec && !VirtualBaseSpec) {
4860 // If the class has any dependent bases, then it's possible that
4861 // one of those types will resolve to the same type as
4862 // BaseType. Therefore, just treat this as a dependent base
4863 // class initialization. FIXME: Should we try to check the
4864 // initialization anyway? It seems odd.
4865 if (ClassDecl->hasAnyDependentBases())
4866 Dependent = true;
4867 else
4868 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4869 << BaseType << Context.getCanonicalTagType(ClassDecl)
4870 << BaseTInfo->getTypeLoc().getSourceRange();
4871 }
4872 }
4873
4874 if (Dependent) {
4876
4877 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4878 /*IsVirtual=*/false,
4879 InitRange.getBegin(), Init,
4880 InitRange.getEnd(), EllipsisLoc);
4881 }
4882
4883 // C++ [base.class.init]p2:
4884 // If a mem-initializer-id is ambiguous because it designates both
4885 // a direct non-virtual base class and an inherited virtual base
4886 // class, the mem-initializer is ill-formed.
4887 if (DirectBaseSpec && VirtualBaseSpec)
4888 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4889 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4890
4891 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4892 if (!BaseSpec)
4893 BaseSpec = VirtualBaseSpec;
4894
4895 // Initialize the base.
4896 bool InitList = true;
4897 MultiExprArg Args = Init;
4898 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4899 InitList = false;
4900 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4901 }
4902
4903 InitializedEntity BaseEntity =
4904 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4905 InitializationKind Kind =
4906 InitList ? InitializationKind::CreateDirectList(BaseLoc)
4907 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4908 InitRange.getEnd());
4909 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4910 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4911 if (!BaseInit.isInvalid()) {
4912 // C++11 [class.base.init]p7:
4913 // The initialization of each base and member constitutes a
4914 // full-expression.
4915 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
4916 /*DiscardedValue*/ false);
4917 }
4918
4919 if (BaseInit.isInvalid()) {
4920 BaseInit = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(),
4921 Args, BaseType);
4922 if (BaseInit.isInvalid())
4923 return true;
4924 } else {
4925 // If we are in a dependent context, template instantiation will
4926 // perform this type-checking again. Just save the arguments that we
4927 // received in a ParenListExpr.
4928 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4929 // of the information that we have about the base
4930 // initializer. However, deconstructing the ASTs is a dicey process,
4931 // and this approach is far more likely to get the corner cases right.
4932 if (CurContext->isDependentContext())
4933 BaseInit = Init;
4934 }
4935
4936 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4937 BaseSpec->isVirtual(),
4938 InitRange.getBegin(),
4939 BaseInit.getAs<Expr>(),
4940 InitRange.getEnd(), EllipsisLoc);
4941}
4942
4943// Create a static_cast<T&&>(expr).
4944static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
4945 QualType TargetType =
4946 SemaRef.BuildReferenceType(E->getType(), /*SpelledAsLValue*/ false,
4948 SourceLocation ExprLoc = E->getBeginLoc();
4949 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4950 TargetType, ExprLoc);
4951
4952 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4953 SourceRange(ExprLoc, ExprLoc),
4954 E->getSourceRange()).get();
4955}
4956
4957/// ImplicitInitializerKind - How an implicit base or member initializer should
4958/// initialize its base or member.
4965
4966static bool
4968 ImplicitInitializerKind ImplicitInitKind,
4969 CXXBaseSpecifier *BaseSpec,
4970 bool IsInheritedVirtualBase,
4971 CXXCtorInitializer *&CXXBaseInit) {
4972 InitializedEntity InitEntity
4973 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4974 IsInheritedVirtualBase);
4975
4976 ExprResult BaseInit;
4977
4978 switch (ImplicitInitKind) {
4979 case IIK_Inherit:
4980 case IIK_Default: {
4981 InitializationKind InitKind
4983 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, {});
4984 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, {});
4985 break;
4986 }
4987
4988 case IIK_Move:
4989 case IIK_Copy: {
4990 bool Moving = ImplicitInitKind == IIK_Move;
4991 ParmVarDecl *Param = Constructor->getParamDecl(0);
4992 QualType ParamType = Param->getType().getNonReferenceType();
4993
4994 Expr *CopyCtorArg =
4996 SourceLocation(), Param, false,
4997 Constructor->getLocation(), ParamType,
4998 VK_LValue, nullptr);
4999
5000 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
5001
5002 // Cast to the base class to avoid ambiguities.
5003 QualType ArgTy =
5004 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
5005 ParamType.getQualifiers());
5006
5007 if (Moving) {
5008 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
5009 }
5010
5011 CXXCastPath BasePath;
5012 BasePath.push_back(BaseSpec);
5013 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
5014 CK_UncheckedDerivedToBase,
5015 Moving ? VK_XValue : VK_LValue,
5016 &BasePath).get();
5017
5018 InitializationKind InitKind
5021 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
5022 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
5023 break;
5024 }
5025 }
5026
5027 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
5028 if (BaseInit.isInvalid())
5029 return true;
5030
5031 CXXBaseInit =
5032 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5033 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
5034 SourceLocation()),
5035 BaseSpec->isVirtual(),
5037 BaseInit.getAs<Expr>(),
5039 SourceLocation());
5040
5041 return false;
5042}
5043
5044static bool RefersToRValueRef(Expr *MemRef) {
5045 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
5046 return Referenced->getType()->isRValueReferenceType();
5047}
5048
5049static bool
5051 ImplicitInitializerKind ImplicitInitKind,
5052 FieldDecl *Field, IndirectFieldDecl *Indirect,
5053 CXXCtorInitializer *&CXXMemberInit) {
5054 if (Field->isInvalidDecl())
5055 return true;
5056
5057 SourceLocation Loc = Constructor->getLocation();
5058
5059 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
5060 bool Moving = ImplicitInitKind == IIK_Move;
5061 ParmVarDecl *Param = Constructor->getParamDecl(0);
5062 QualType ParamType = Param->getType().getNonReferenceType();
5063
5064 // Suppress copying zero-width bitfields.
5065 if (Field->isZeroLengthBitField())
5066 return false;
5067
5068 Expr *MemberExprBase =
5070 SourceLocation(), Param, false,
5071 Loc, ParamType, VK_LValue, nullptr);
5072
5073 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
5074
5075 if (Moving) {
5076 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
5077 }
5078
5079 // Build a reference to this field within the parameter.
5080 CXXScopeSpec SS;
5081 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
5083 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
5084 : cast<ValueDecl>(Field), AS_public);
5085 MemberLookup.resolveKind();
5086 ExprResult CtorArg
5087 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
5088 ParamType, Loc,
5089 /*IsArrow=*/false,
5090 SS,
5091 /*TemplateKWLoc=*/SourceLocation(),
5092 /*FirstQualifierInScope=*/nullptr,
5093 MemberLookup,
5094 /*TemplateArgs=*/nullptr,
5095 /*S*/nullptr);
5096 if (CtorArg.isInvalid())
5097 return true;
5098
5099 // C++11 [class.copy]p15:
5100 // - if a member m has rvalue reference type T&&, it is direct-initialized
5101 // with static_cast<T&&>(x.m);
5102 if (RefersToRValueRef(CtorArg.get())) {
5103 CtorArg = CastForMoving(SemaRef, CtorArg.get());
5104 }
5105
5106 InitializedEntity Entity =
5109
5110 // Direct-initialize to use the copy constructor.
5111 InitializationKind InitKind =
5113
5114 Expr *CtorArgE = CtorArg.getAs<Expr>();
5115 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
5116 ExprResult MemberInit =
5117 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
5118 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
5119 if (MemberInit.isInvalid())
5120 return true;
5121
5122 if (Indirect)
5123 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
5124 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
5125 else
5126 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
5127 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
5128 return false;
5129 }
5130
5131 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
5132 "Unhandled implicit init kind!");
5133
5134 QualType FieldBaseElementType =
5135 SemaRef.Context.getBaseElementType(Field->getType());
5136
5137 if (FieldBaseElementType->isRecordType()) {
5138 InitializedEntity InitEntity =
5141 InitializationKind InitKind =
5143
5144 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, {});
5145 ExprResult MemberInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, {});
5146
5147 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
5148 if (MemberInit.isInvalid())
5149 return true;
5150
5151 if (Indirect)
5152 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5153 Indirect, Loc,
5154 Loc,
5155 MemberInit.get(),
5156 Loc);
5157 else
5158 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5159 Field, Loc, Loc,
5160 MemberInit.get(),
5161 Loc);
5162 return false;
5163 }
5164
5165 if (!Field->getParent()->isUnion()) {
5166 if (FieldBaseElementType->isReferenceType()) {
5167 SemaRef.Diag(Constructor->getLocation(),
5168 diag::err_uninitialized_member_in_ctor)
5169 << (int)Constructor->isImplicit()
5170 << SemaRef.Context.getCanonicalTagType(Constructor->getParent()) << 0
5171 << Field->getDeclName();
5172 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
5173 return true;
5174 }
5175
5176 if (FieldBaseElementType.isConstQualified()) {
5177 SemaRef.Diag(Constructor->getLocation(),
5178 diag::err_uninitialized_member_in_ctor)
5179 << (int)Constructor->isImplicit()
5180 << SemaRef.Context.getCanonicalTagType(Constructor->getParent()) << 1
5181 << Field->getDeclName();
5182 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
5183 return true;
5184 }
5185 }
5186
5187 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
5188 // ARC and Weak:
5189 // Default-initialize Objective-C pointers to NULL.
5190 CXXMemberInit
5191 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
5192 Loc, Loc,
5193 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
5194 Loc);
5195 return false;
5196 }
5197
5198 // Nothing to initialize.
5199 CXXMemberInit = nullptr;
5200 return false;
5201}
5202
5203namespace {
5204struct BaseAndFieldInfo {
5205 Sema &S;
5206 CXXConstructorDecl *Ctor;
5207 bool AnyErrorsInInits;
5209 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
5210 SmallVector<CXXCtorInitializer*, 8> AllToInit;
5211 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
5212
5213 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
5214 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
5215 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
5216 if (Ctor->getInheritedConstructor())
5217 IIK = IIK_Inherit;
5218 else if (Generated && Ctor->isCopyConstructor())
5219 IIK = IIK_Copy;
5220 else if (Generated && Ctor->isMoveConstructor())
5221 IIK = IIK_Move;
5222 else
5223 IIK = IIK_Default;
5224 }
5225
5226 bool isImplicitCopyOrMove() const {
5227 switch (IIK) {
5228 case IIK_Copy:
5229 case IIK_Move:
5230 return true;
5231
5232 case IIK_Default:
5233 case IIK_Inherit:
5234 return false;
5235 }
5236
5237 llvm_unreachable("Invalid ImplicitInitializerKind!");
5238 }
5239
5240 bool addFieldInitializer(CXXCtorInitializer *Init) {
5241 AllToInit.push_back(Init);
5242
5243 // Check whether this initializer makes the field "used".
5244 if (Init->getInit()->HasSideEffects(S.Context))
5245 S.UnusedPrivateFields.remove(Init->getAnyMember());
5246
5247 return false;
5248 }
5249
5250 bool isInactiveUnionMember(FieldDecl *Field) {
5251 RecordDecl *Record = Field->getParent();
5252 if (!Record->isUnion())
5253 return false;
5254
5255 if (FieldDecl *Active =
5256 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
5257 return Active != Field->getCanonicalDecl();
5258
5259 // In an implicit copy or move constructor, ignore any in-class initializer.
5260 if (isImplicitCopyOrMove())
5261 return true;
5262
5263 // If there's no explicit initialization, the field is active only if it
5264 // has an in-class initializer...
5265 if (Field->hasInClassInitializer())
5266 return false;
5267 // ... or it's an anonymous struct or union whose class has an in-class
5268 // initializer.
5269 if (!Field->isAnonymousStructOrUnion())
5270 return true;
5271 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
5272 return !FieldRD->hasInClassInitializer();
5273 }
5274
5275 /// Determine whether the given field is, or is within, a union member
5276 /// that is inactive (because there was an initializer given for a different
5277 /// member of the union, or because the union was not initialized at all).
5278 bool isWithinInactiveUnionMember(FieldDecl *Field,
5279 IndirectFieldDecl *Indirect) {
5280 if (!Indirect)
5281 return isInactiveUnionMember(Field);
5282
5283 for (auto *C : Indirect->chain()) {
5284 FieldDecl *Field = dyn_cast<FieldDecl>(C);
5285 if (Field && isInactiveUnionMember(Field))
5286 return true;
5287 }
5288 return false;
5289 }
5290};
5291}
5292
5293/// Determine whether the given type is an incomplete or zero-lenfgth
5294/// array type.
5296 if (T->isIncompleteArrayType())
5297 return true;
5298
5299 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
5300 if (ArrayT->isZeroSize())
5301 return true;
5302
5303 T = ArrayT->getElementType();
5304 }
5305
5306 return false;
5307}
5308
5309static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
5310 FieldDecl *Field,
5311 IndirectFieldDecl *Indirect = nullptr) {
5312 if (Field->isInvalidDecl())
5313 return false;
5314
5315 // Overwhelmingly common case: we have a direct initializer for this field.
5317 Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
5318 return Info.addFieldInitializer(Init);
5319
5320 // C++11 [class.base.init]p8:
5321 // if the entity is a non-static data member that has a
5322 // brace-or-equal-initializer and either
5323 // -- the constructor's class is a union and no other variant member of that
5324 // union is designated by a mem-initializer-id or
5325 // -- the constructor's class is not a union, and, if the entity is a member
5326 // of an anonymous union, no other member of that union is designated by
5327 // a mem-initializer-id,
5328 // the entity is initialized as specified in [dcl.init].
5329 //
5330 // We also apply the same rules to handle anonymous structs within anonymous
5331 // unions.
5332 if (Info.isWithinInactiveUnionMember(Field, Indirect))
5333 return false;
5334
5335 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
5336 ExprResult DIE =
5337 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
5338 if (DIE.isInvalid())
5339 return true;
5340
5342 SemaRef.checkInitializerLifetime(Entity, DIE.get());
5343
5345 if (Indirect)
5346 Init = new (SemaRef.Context)
5347 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
5348 SourceLocation(), DIE.get(), SourceLocation());
5349 else
5350 Init = new (SemaRef.Context)
5351 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
5352 SourceLocation(), DIE.get(), SourceLocation());
5353 return Info.addFieldInitializer(Init);
5354 }
5355
5356 // Don't initialize incomplete or zero-length arrays.
5357 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
5358 return false;
5359
5360 // Don't try to build an implicit initializer if there were semantic
5361 // errors in any of the initializers (and therefore we might be
5362 // missing some that the user actually wrote).
5363 if (Info.AnyErrorsInInits)
5364 return false;
5365
5366 CXXCtorInitializer *Init = nullptr;
5367 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
5368 Indirect, Init))
5369 return true;
5370
5371 if (!Init)
5372 return false;
5373
5374 return Info.addFieldInitializer(Init);
5375}
5376
5377bool
5380 assert(Initializer->isDelegatingInitializer());
5381 Constructor->setNumCtorInitializers(1);
5382 CXXCtorInitializer **initializer =
5383 new (Context) CXXCtorInitializer*[1];
5384 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
5385 Constructor->setCtorInitializers(initializer);
5386
5387 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
5388 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
5389 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
5390 }
5391
5393
5394 DiagnoseUninitializedFields(*this, Constructor);
5395
5396 return false;
5397}
5398
5400 CXXRecordDecl *Class) {
5401 if (Class->isInvalidDecl())
5402 return nullptr;
5403 if (Class->hasIrrelevantDestructor())
5404 return nullptr;
5405
5406 // Dtor might still be missing, e.g because it's invalid.
5407 return S.LookupDestructor(Class);
5408}
5409
5411 FieldDecl *Field) {
5412 if (Field->isInvalidDecl())
5413 return;
5414
5415 // Don't destroy incomplete or zero-length arrays.
5416 if (isIncompleteOrZeroLengthArrayType(S.Context, Field->getType()))
5417 return;
5418
5419 QualType FieldType = S.Context.getBaseElementType(Field->getType());
5420
5421 auto *FieldClassDecl = FieldType->getAsCXXRecordDecl();
5422 if (!FieldClassDecl)
5423 return;
5424
5425 // The destructor for an implicit anonymous union member is never invoked.
5426 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5427 return;
5428
5429 auto *Dtor = LookupDestructorIfRelevant(S, FieldClassDecl);
5430 if (!Dtor)
5431 return;
5432
5433 S.CheckDestructorAccess(Field->getLocation(), Dtor,
5434 S.PDiag(diag::err_access_dtor_field)
5435 << Field->getDeclName() << FieldType);
5436
5437 S.MarkFunctionReferenced(Location, Dtor);
5438 S.DiagnoseUseOfDecl(Dtor, Location);
5439}
5440
5442 CXXRecordDecl *ClassDecl) {
5443 if (ClassDecl->isDependentContext())
5444 return;
5445
5446 // We only potentially invoke the destructors of potentially constructed
5447 // subobjects.
5448 bool VisitVirtualBases = !ClassDecl->isAbstract();
5449
5450 // If the destructor exists and has already been marked used in the MS ABI,
5451 // then virtual base destructors have already been checked and marked used.
5452 // Skip checking them again to avoid duplicate diagnostics.
5454 CXXDestructorDecl *Dtor = ClassDecl->getDestructor();
5455 if (Dtor && Dtor->isUsed())
5456 VisitVirtualBases = false;
5457 }
5458
5460
5461 // Bases.
5462 for (const auto &Base : ClassDecl->bases()) {
5463 auto *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
5464 if (!BaseClassDecl)
5465 continue;
5466
5467 // Remember direct virtual bases.
5468 if (Base.isVirtual()) {
5469 if (!VisitVirtualBases)
5470 continue;
5471 DirectVirtualBases.insert(BaseClassDecl);
5472 }
5473
5474 auto *Dtor = LookupDestructorIfRelevant(S, BaseClassDecl);
5475 if (!Dtor)
5476 continue;
5477
5478 // FIXME: caret should be on the start of the class name
5479 S.CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5480 S.PDiag(diag::err_access_dtor_base)
5481 << Base.getType() << Base.getSourceRange(),
5482 S.Context.getCanonicalTagType(ClassDecl));
5483
5484 S.MarkFunctionReferenced(Location, Dtor);
5485 S.DiagnoseUseOfDecl(Dtor, Location);
5486 }
5487
5488 if (VisitVirtualBases)
5489 S.MarkVirtualBaseDestructorsReferenced(Location, ClassDecl,
5490 &DirectVirtualBases);
5491}
5492
5494 ArrayRef<CXXCtorInitializer *> Initializers) {
5495 if (Constructor->isDependentContext()) {
5496 // Just store the initializers as written, they will be checked during
5497 // instantiation.
5498 if (!Initializers.empty()) {
5499 Constructor->setNumCtorInitializers(Initializers.size());
5500 CXXCtorInitializer **baseOrMemberInitializers =
5501 new (Context) CXXCtorInitializer*[Initializers.size()];
5502 memcpy(baseOrMemberInitializers, Initializers.data(),
5503 Initializers.size() * sizeof(CXXCtorInitializer*));
5504 Constructor->setCtorInitializers(baseOrMemberInitializers);
5505 }
5506
5507 // Let template instantiation know whether we had errors.
5508 if (AnyErrors)
5509 Constructor->setInvalidDecl();
5510
5511 return false;
5512 }
5513
5514 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
5515
5516 // We need to build the initializer AST according to order of construction
5517 // and not what user specified in the Initializers list.
5518 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
5519 if (!ClassDecl)
5520 return true;
5521
5522 bool HadError = false;
5523
5524 for (CXXCtorInitializer *Member : Initializers) {
5525 if (Member->isBaseInitializer())
5526 Info.AllBaseFields[Member->getBaseClass()->getAsCanonical<RecordType>()] =
5527 Member;
5528 else {
5529 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
5530
5531 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
5532 for (auto *C : F->chain()) {
5533 FieldDecl *FD = dyn_cast<FieldDecl>(C);
5534 if (FD && FD->getParent()->isUnion())
5535 Info.ActiveUnionMember.insert(std::make_pair(
5537 }
5538 } else if (FieldDecl *FD = Member->getMember()) {
5539 if (FD->getParent()->isUnion())
5540 Info.ActiveUnionMember.insert(std::make_pair(
5542 }
5543 }
5544 }
5545
5546 // Keep track of the direct virtual bases.
5548 for (auto &I : ClassDecl->bases()) {
5549 if (I.isVirtual())
5550 DirectVBases.insert(&I);
5551 }
5552
5553 // Push virtual bases before others.
5554 for (auto &VBase : ClassDecl->vbases()) {
5555 if (CXXCtorInitializer *Value = Info.AllBaseFields.lookup(
5556 VBase.getType()->getAsCanonical<RecordType>())) {
5557 // [class.base.init]p7, per DR257:
5558 // A mem-initializer where the mem-initializer-id names a virtual base
5559 // class is ignored during execution of a constructor of any class that
5560 // is not the most derived class.
5561 if (ClassDecl->isAbstract()) {
5562 // FIXME: Provide a fixit to remove the base specifier. This requires
5563 // tracking the location of the associated comma for a base specifier.
5564 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
5565 << VBase.getType() << ClassDecl;
5566 DiagnoseAbstractType(ClassDecl);
5567 }
5568
5569 Info.AllToInit.push_back(Value);
5570 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
5571 // [class.base.init]p8, per DR257:
5572 // If a given [...] base class is not named by a mem-initializer-id
5573 // [...] and the entity is not a virtual base class of an abstract
5574 // class, then [...] the entity is default-initialized.
5575 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
5576 CXXCtorInitializer *CXXBaseInit;
5577 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5578 &VBase, IsInheritedVirtualBase,
5579 CXXBaseInit)) {
5580 HadError = true;
5581 continue;
5582 }
5583
5584 Info.AllToInit.push_back(CXXBaseInit);
5585 }
5586 }
5587
5588 // Non-virtual bases.
5589 for (auto &Base : ClassDecl->bases()) {
5590 // Virtuals are in the virtual base list and already constructed.
5591 if (Base.isVirtual())
5592 continue;
5593
5594 if (CXXCtorInitializer *Value = Info.AllBaseFields.lookup(
5595 Base.getType()->getAsCanonical<RecordType>())) {
5596 Info.AllToInit.push_back(Value);
5597 } else if (!AnyErrors) {
5598 CXXCtorInitializer *CXXBaseInit;
5599 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5600 &Base, /*IsInheritedVirtualBase=*/false,
5601 CXXBaseInit)) {
5602 HadError = true;
5603 continue;
5604 }
5605
5606 Info.AllToInit.push_back(CXXBaseInit);
5607 }
5608 }
5609
5610 // Fields.
5611 for (auto *Mem : ClassDecl->decls()) {
5612 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
5613 // C++ [class.bit]p2:
5614 // A declaration for a bit-field that omits the identifier declares an
5615 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
5616 // initialized.
5617 if (F->isUnnamedBitField())
5618 continue;
5619
5620 // If we're not generating the implicit copy/move constructor, then we'll
5621 // handle anonymous struct/union fields based on their individual
5622 // indirect fields.
5623 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
5624 continue;
5625
5626 if (CollectFieldInitializer(*this, Info, F))
5627 HadError = true;
5628 continue;
5629 }
5630
5631 // Beyond this point, we only consider default initialization.
5632 if (Info.isImplicitCopyOrMove())
5633 continue;
5634
5635 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
5636 if (F->getType()->isIncompleteArrayType()) {
5637 assert(ClassDecl->hasFlexibleArrayMember() &&
5638 "Incomplete array type is not valid");
5639 continue;
5640 }
5641
5642 // Initialize each field of an anonymous struct individually.
5643 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
5644 HadError = true;
5645
5646 continue;
5647 }
5648 }
5649
5650 unsigned NumInitializers = Info.AllToInit.size();
5651 if (NumInitializers > 0) {
5652 Constructor->setNumCtorInitializers(NumInitializers);
5653 CXXCtorInitializer **baseOrMemberInitializers =
5654 new (Context) CXXCtorInitializer*[NumInitializers];
5655 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
5656 NumInitializers * sizeof(CXXCtorInitializer*));
5657 Constructor->setCtorInitializers(baseOrMemberInitializers);
5658
5659 SourceLocation Location = Constructor->getLocation();
5660
5661 // Constructors implicitly reference the base and member
5662 // destructors.
5663
5664 for (CXXCtorInitializer *Initializer : Info.AllToInit) {
5665 FieldDecl *Field = Initializer->getAnyMember();
5666 if (!Field)
5667 continue;
5668
5669 // C++ [class.base.init]p12:
5670 // In a non-delegating constructor, the destructor for each
5671 // potentially constructed subobject of class type is potentially
5672 // invoked.
5673 MarkFieldDestructorReferenced(*this, Location, Field);
5674 }
5675
5676 MarkBaseDestructorsReferenced(*this, Location, Constructor->getParent());
5677 }
5678
5679 return HadError;
5680}
5681
5683 if (const RecordType *RT = Field->getType()->getAsCanonical<RecordType>()) {
5684 const RecordDecl *RD = RT->getDecl();
5685 if (RD->isAnonymousStructOrUnion()) {
5686 for (auto *Field : RD->getDefinitionOrSelf()->fields())
5687 PopulateKeysForFields(Field, IdealInits);
5688 return;
5689 }
5690 }
5691 IdealInits.push_back(Field->getCanonicalDecl());
5692}
5693
5694static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
5695 return Context.getCanonicalType(BaseType).getTypePtr();
5696}
5697
5698static const void *GetKeyForMember(ASTContext &Context,
5700 if (!Member->isAnyMemberInitializer())
5701 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
5702
5703 return Member->getAnyMember()->getCanonicalDecl();
5704}
5705
5708 const CXXCtorInitializer *Current) {
5709 if (Previous->isAnyMemberInitializer())
5710 Diag << 0 << Previous->getAnyMember();
5711 else
5712 Diag << 1 << Previous->getTypeSourceInfo()->getType();
5713
5714 if (Current->isAnyMemberInitializer())
5715 Diag << 0 << Current->getAnyMember();
5716 else
5717 Diag << 1 << Current->getTypeSourceInfo()->getType();
5718}
5719
5721 Sema &SemaRef, const CXXConstructorDecl *Constructor,
5723 if (Constructor->getDeclContext()->isDependentContext())
5724 return;
5725
5726 // Don't check initializers order unless the warning is enabled at the
5727 // location of at least one initializer.
5728 bool ShouldCheckOrder = false;
5729 for (const CXXCtorInitializer *Init : Inits) {
5730 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
5731 Init->getSourceLocation())) {
5732 ShouldCheckOrder = true;
5733 break;
5734 }
5735 }
5736 if (!ShouldCheckOrder)
5737 return;
5738
5739 // Build the list of bases and members in the order that they'll
5740 // actually be initialized. The explicit initializers should be in
5741 // this same order but may be missing things.
5742 SmallVector<const void*, 32> IdealInitKeys;
5743
5744 const CXXRecordDecl *ClassDecl = Constructor->getParent();
5745
5746 // 1. Virtual bases.
5747 for (const auto &VBase : ClassDecl->vbases())
5748 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
5749
5750 // 2. Non-virtual bases.
5751 for (const auto &Base : ClassDecl->bases()) {
5752 if (Base.isVirtual())
5753 continue;
5754 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
5755 }
5756
5757 // 3. Direct fields.
5758 for (auto *Field : ClassDecl->fields()) {
5759 if (Field->isUnnamedBitField())
5760 continue;
5761
5762 PopulateKeysForFields(Field, IdealInitKeys);
5763 }
5764
5765 unsigned NumIdealInits = IdealInitKeys.size();
5766 unsigned IdealIndex = 0;
5767
5768 // Track initializers that are in an incorrect order for either a warning or
5769 // note if multiple ones occur.
5770 SmallVector<unsigned> WarnIndexes;
5771 // Correlates the index of an initializer in the init-list to the index of
5772 // the field/base in the class.
5773 SmallVector<std::pair<unsigned, unsigned>, 32> CorrelatedInitOrder;
5774
5775 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5776 const void *InitKey = GetKeyForMember(SemaRef.Context, Inits[InitIndex]);
5777
5778 // Scan forward to try to find this initializer in the idealized
5779 // initializers list.
5780 for (; IdealIndex != NumIdealInits; ++IdealIndex)
5781 if (InitKey == IdealInitKeys[IdealIndex])
5782 break;
5783
5784 // If we didn't find this initializer, it must be because we
5785 // scanned past it on a previous iteration. That can only
5786 // happen if we're out of order; emit a warning.
5787 if (IdealIndex == NumIdealInits && InitIndex) {
5788 WarnIndexes.push_back(InitIndex);
5789
5790 // Move back to the initializer's location in the ideal list.
5791 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5792 if (InitKey == IdealInitKeys[IdealIndex])
5793 break;
5794
5795 assert(IdealIndex < NumIdealInits &&
5796 "initializer not found in initializer list");
5797 }
5798 CorrelatedInitOrder.emplace_back(IdealIndex, InitIndex);
5799 }
5800
5801 if (WarnIndexes.empty())
5802 return;
5803
5804 // Sort based on the ideal order, first in the pair.
5805 llvm::sort(CorrelatedInitOrder, llvm::less_first());
5806
5807 // Introduce a new scope as SemaDiagnosticBuilder needs to be destroyed to
5808 // emit the diagnostic before we can try adding notes.
5809 {
5811 Inits[WarnIndexes.front() - 1]->getSourceLocation(),
5812 WarnIndexes.size() == 1 ? diag::warn_initializer_out_of_order
5813 : diag::warn_some_initializers_out_of_order);
5814
5815 for (unsigned I = 0; I < CorrelatedInitOrder.size(); ++I) {
5816 if (CorrelatedInitOrder[I].second == I)
5817 continue;
5818 // Ideally we would be using InsertFromRange here, but clang doesn't
5819 // appear to handle InsertFromRange correctly when the source range is
5820 // modified by another fix-it.
5822 Inits[I]->getSourceRange(),
5825 Inits[CorrelatedInitOrder[I].second]->getSourceRange()),
5826 SemaRef.getSourceManager(), SemaRef.getLangOpts()));
5827 }
5828
5829 // If there is only 1 item out of order, the warning expects the name and
5830 // type of each being added to it.
5831 if (WarnIndexes.size() == 1) {
5832 AddInitializerToDiag(D, Inits[WarnIndexes.front() - 1],
5833 Inits[WarnIndexes.front()]);
5834 return;
5835 }
5836 }
5837 // More than 1 item to warn, create notes letting the user know which ones
5838 // are bad.
5839 for (unsigned WarnIndex : WarnIndexes) {
5840 const clang::CXXCtorInitializer *PrevInit = Inits[WarnIndex - 1];
5841 auto D = SemaRef.Diag(PrevInit->getSourceLocation(),
5842 diag::note_initializer_out_of_order);
5843 AddInitializerToDiag(D, PrevInit, Inits[WarnIndex]);
5844 D << PrevInit->getSourceRange();
5845 }
5846}
5847
5848namespace {
5849bool CheckRedundantInit(Sema &S,
5850 CXXCtorInitializer *Init,
5851 CXXCtorInitializer *&PrevInit) {
5852 if (!PrevInit) {
5853 PrevInit = Init;
5854 return false;
5855 }
5856
5857 if (FieldDecl *Field = Init->getAnyMember())
5858 S.Diag(Init->getSourceLocation(),
5859 diag::err_multiple_mem_initialization)
5860 << Field->getDeclName()
5861 << Init->getSourceRange();
5862 else {
5863 const Type *BaseClass = Init->getBaseClass();
5864 assert(BaseClass && "neither field nor base");
5865 S.Diag(Init->getSourceLocation(),
5866 diag::err_multiple_base_initialization)
5867 << QualType(BaseClass, 0)
5868 << Init->getSourceRange();
5869 }
5870 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5871 << 0 << PrevInit->getSourceRange();
5872
5873 return true;
5874}
5875
5876typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5877typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5878
5879bool CheckRedundantUnionInit(Sema &S,
5880 CXXCtorInitializer *Init,
5881 RedundantUnionMap &Unions) {
5882 FieldDecl *Field = Init->getAnyMember();
5883 RecordDecl *Parent = Field->getParent();
5884 NamedDecl *Child = Field;
5885
5886 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5887 if (Parent->isUnion()) {
5888 UnionEntry &En = Unions[Parent];
5889 if (En.first && En.first != Child) {
5890 S.Diag(Init->getSourceLocation(),
5891 diag::err_multiple_mem_union_initialization)
5892 << Field->getDeclName()
5893 << Init->getSourceRange();
5894 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5895 << 0 << En.second->getSourceRange();
5896 return true;
5897 }
5898 if (!En.first) {
5899 En.first = Child;
5900 En.second = Init;
5901 }
5902 if (!Parent->isAnonymousStructOrUnion())
5903 return false;
5904 }
5905
5906 Child = Parent;
5907 Parent = cast<RecordDecl>(Parent->getDeclContext());
5908 }
5909
5910 return false;
5911}
5912} // namespace
5913
5914void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5915 SourceLocation ColonLoc,
5917 bool AnyErrors) {
5918 if (!ConstructorDecl)
5919 return;
5920
5921 AdjustDeclIfTemplate(ConstructorDecl);
5922
5924 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5925
5926 if (!Constructor) {
5927 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5928 return;
5929 }
5930
5931 // Mapping for the duplicate initializers check.
5932 // For member initializers, this is keyed with a FieldDecl*.
5933 // For base initializers, this is keyed with a Type*.
5934 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5935
5936 // Mapping for the inconsistent anonymous-union initializers check.
5937 RedundantUnionMap MemberUnions;
5938
5939 bool HadError = false;
5940 for (unsigned i = 0; i < MemInits.size(); i++) {
5941 CXXCtorInitializer *Init = MemInits[i];
5942
5943 // Set the source order index.
5944 Init->setSourceOrder(i);
5945
5946 if (Init->isAnyMemberInitializer()) {
5947 const void *Key = GetKeyForMember(Context, Init);
5948 if (CheckRedundantInit(*this, Init, Members[Key]) ||
5949 CheckRedundantUnionInit(*this, Init, MemberUnions))
5950 HadError = true;
5951 } else if (Init->isBaseInitializer()) {
5952 const void *Key = GetKeyForMember(Context, Init);
5953 if (CheckRedundantInit(*this, Init, Members[Key]))
5954 HadError = true;
5955 } else {
5956 assert(Init->isDelegatingInitializer());
5957 // This must be the only initializer
5958 if (MemInits.size() != 1) {
5959 Diag(Init->getSourceLocation(),
5960 diag::err_delegating_initializer_alone)
5961 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5962 // We will treat this as being the only initializer.
5963 }
5965 // Return immediately as the initializer is set.
5966 return;
5967 }
5968 }
5969
5970 if (HadError)
5971 return;
5972
5974
5975 SetCtorInitializers(Constructor, AnyErrors, MemInits);
5976
5977 DiagnoseUninitializedFields(*this, Constructor);
5978}
5979
5981 CXXRecordDecl *ClassDecl) {
5982 // Ignore dependent contexts. Also ignore unions, since their members never
5983 // have destructors implicitly called.
5984 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5985 return;
5986
5987 // FIXME: all the access-control diagnostics are positioned on the
5988 // field/base declaration. That's probably good; that said, the
5989 // user might reasonably want to know why the destructor is being
5990 // emitted, and we currently don't say.
5991
5992 // Non-static data members.
5993 for (auto *Field : ClassDecl->fields()) {
5994 MarkFieldDestructorReferenced(*this, Location, Field);
5995 }
5996
5997 MarkBaseDestructorsReferenced(*this, Location, ClassDecl);
5998}
5999
6001 SourceLocation Location, CXXRecordDecl *ClassDecl,
6002 llvm::SmallPtrSetImpl<const CXXRecordDecl *> *DirectVirtualBases) {
6003 // Virtual bases.
6004 for (const auto &VBase : ClassDecl->vbases()) {
6005 auto *BaseClassDecl = VBase.getType()->getAsCXXRecordDecl();
6006 if (!BaseClassDecl)
6007 continue;
6008
6009 // Ignore already visited direct virtual bases.
6010 if (DirectVirtualBases && DirectVirtualBases->count(BaseClassDecl))
6011 continue;
6012
6013 auto *Dtor = LookupDestructorIfRelevant(*this, BaseClassDecl);
6014 if (!Dtor)
6015 continue;
6016
6017 CanQualType CT = Context.getCanonicalTagType(ClassDecl);
6018 if (CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
6019 PDiag(diag::err_access_dtor_vbase)
6020 << CT << VBase.getType(),
6021 CT) == AR_accessible) {
6023 CT, VBase.getType(), diag::err_access_dtor_vbase, 0,
6024 ClassDecl->getLocation(), SourceRange(), DeclarationName(), nullptr);
6025 }
6026
6027 MarkFunctionReferenced(Location, Dtor);
6028 DiagnoseUseOfDecl(Dtor, Location);
6029 }
6030}
6031
6033 if (!CDtorDecl)
6034 return;
6035
6037 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
6038 if (CXXRecordDecl *ClassDecl = Constructor->getParent();
6039 !ClassDecl || ClassDecl->isInvalidDecl()) {
6040 return;
6041 }
6042 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
6043 DiagnoseUninitializedFields(*this, Constructor);
6044 }
6045}
6046
6048 if (!getLangOpts().CPlusPlus)
6049 return false;
6050
6051 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
6052 if (!RD)
6053 return false;
6054
6055 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
6056 // class template specialization here, but doing so breaks a lot of code.
6057
6058 // We can't answer whether something is abstract until it has a
6059 // definition. If it's currently being defined, we'll walk back
6060 // over all the declarations when we have a full definition.
6061 const CXXRecordDecl *Def = RD->getDefinition();
6062 if (!Def || Def->isBeingDefined())
6063 return false;
6064
6065 return RD->isAbstract();
6066}
6067
6069 TypeDiagnoser &Diagnoser) {
6070 if (!isAbstractType(Loc, T))
6071 return false;
6072
6073 T = Context.getBaseElementType(T);
6074 Diagnoser.diagnose(*this, Loc, T);
6075 DiagnoseAbstractType(T->getAsCXXRecordDecl());
6076 return true;
6077}
6078
6080 // Check if we've already emitted the list of pure virtual functions
6081 // for this class.
6083 return;
6084
6085 // If the diagnostic is suppressed, don't emit the notes. We're only
6086 // going to emit them once, so try to attach them to a diagnostic we're
6087 // actually going to show.
6088 if (Diags.isLastDiagnosticIgnored())
6089 return;
6090
6091 CXXFinalOverriderMap FinalOverriders;
6092 RD->getFinalOverriders(FinalOverriders);
6093
6094 // Keep a set of seen pure methods so we won't diagnose the same method
6095 // more than once.
6097
6098 for (const auto &M : FinalOverriders) {
6099 for (const auto &SO : M.second) {
6100 // C++ [class.abstract]p4:
6101 // A class is abstract if it contains or inherits at least one
6102 // pure virtual function for which the final overrider is pure
6103 // virtual.
6104
6105 if (SO.second.size() != 1)
6106 continue;
6107 const CXXMethodDecl *Method = SO.second.front().Method;
6108
6109 if (!Method->isPureVirtual())
6110 continue;
6111
6112 if (!SeenPureMethods.insert(Method).second)
6113 continue;
6114
6115 Diag(Method->getLocation(), diag::note_pure_virtual_function)
6116 << Method->getDeclName() << RD->getDeclName();
6117 }
6118 }
6119
6122 PureVirtualClassDiagSet->insert(RD);
6123}
6124
6125namespace {
6126struct AbstractUsageInfo {
6127 Sema &S;
6129 CanQualType AbstractType;
6130 bool Invalid;
6131
6132 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
6133 : S(S), Record(Record),
6134 AbstractType(S.Context.getCanonicalTagType(Record)), Invalid(false) {}
6135
6136 void DiagnoseAbstractType() {
6137 if (Invalid) return;
6139 Invalid = true;
6140 }
6141
6142 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
6143};
6144
6145struct CheckAbstractUsage {
6146 AbstractUsageInfo &Info;
6147 const NamedDecl *Ctx;
6148
6149 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
6150 : Info(Info), Ctx(Ctx) {}
6151
6152 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
6153 switch (TL.getTypeLocClass()) {
6154#define ABSTRACT_TYPELOC(CLASS, PARENT)
6155#define TYPELOC(CLASS, PARENT) \
6156 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
6157#include "clang/AST/TypeLocNodes.def"
6158 }
6159 }
6160
6161 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6163 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
6164 if (!TL.getParam(I))
6165 continue;
6166
6167 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
6168 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
6169 }
6170 }
6171
6172 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6174 }
6175
6176 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6177 // Visit the type parameters from a permissive context.
6178 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
6179 TemplateArgumentLoc TAL = TL.getArgLoc(I);
6181 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
6182 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
6183 // TODO: other template argument types?
6184 }
6185 }
6186
6187 // Visit pointee types from a permissive context.
6188#define CheckPolymorphic(Type) \
6189 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
6190 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
6191 }
6197
6198 /// Handle all the types we haven't given a more specific
6199 /// implementation for above.
6200 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
6201 // Every other kind of type that we haven't called out already
6202 // that has an inner type is either (1) sugar or (2) contains that
6203 // inner type in some way as a subobject.
6204 if (TypeLoc Next = TL.getNextTypeLoc())
6205 return Visit(Next, Sel);
6206
6207 // If there's no inner type and we're in a permissive context,
6208 // don't diagnose.
6209 if (Sel == Sema::AbstractNone) return;
6210
6211 // Check whether the type matches the abstract type.
6212 QualType T = TL.getType();
6213 if (T->isArrayType()) {
6215 T = Info.S.Context.getBaseElementType(T);
6216 }
6217 CanQualType CT = T->getCanonicalTypeUnqualified();
6218 if (CT != Info.AbstractType) return;
6219
6220 // It matched; do some magic.
6221 // FIXME: These should be at most warnings. See P0929R2, CWG1640, CWG1646.
6222 if (Sel == Sema::AbstractArrayType) {
6223 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
6224 << T << TL.getSourceRange();
6225 } else {
6226 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
6227 << Sel << T << TL.getSourceRange();
6228 }
6229 Info.DiagnoseAbstractType();
6230 }
6231};
6232
6233void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
6235 CheckAbstractUsage(*this, D).Visit(TL, Sel);
6236}
6237
6238}
6239
6240/// Check for invalid uses of an abstract type in a function declaration.
6241static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6242 FunctionDecl *FD) {
6243 // Only definitions are required to refer to complete and
6244 // non-abstract types.
6246 return;
6247
6248 // For safety's sake, just ignore it if we don't have type source
6249 // information. This should never happen for non-implicit methods,
6250 // but...
6251 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6252 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractNone);
6253}
6254
6255/// Check for invalid uses of an abstract type in a variable0 declaration.
6256static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6257 VarDecl *VD) {
6258 // No need to do the check on definitions, which require that
6259 // the type is complete.
6261 return;
6262
6263 Info.CheckType(VD, VD->getTypeSourceInfo()->getTypeLoc(),
6265}
6266
6267/// Check for invalid uses of an abstract type within a class definition.
6268static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6269 CXXRecordDecl *RD) {
6270 for (auto *D : RD->decls()) {
6271 if (D->isImplicit()) continue;
6272
6273 // Step through friends to the befriended declaration.
6274 if (auto *FD = dyn_cast<FriendDecl>(D)) {
6275 D = FD->getFriendDecl();
6276 if (!D) continue;
6277 }
6278
6279 // Functions and function templates.
6280 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6281 CheckAbstractClassUsage(Info, FD);
6282 } else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) {
6283 CheckAbstractClassUsage(Info, FTD->getTemplatedDecl());
6284
6285 // Fields and static variables.
6286 } else if (auto *FD = dyn_cast<FieldDecl>(D)) {
6287 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6288 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
6289 } else if (auto *VD = dyn_cast<VarDecl>(D)) {
6290 CheckAbstractClassUsage(Info, VD);
6291 } else if (auto *VTD = dyn_cast<VarTemplateDecl>(D)) {
6292 CheckAbstractClassUsage(Info, VTD->getTemplatedDecl());
6293
6294 // Nested classes and class templates.
6295 } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
6296 CheckAbstractClassUsage(Info, RD);
6297 } else if (auto *CTD = dyn_cast<ClassTemplateDecl>(D)) {
6298 CheckAbstractClassUsage(Info, CTD->getTemplatedDecl());
6299 }
6300 }
6301}
6302
6304 Attr *ClassAttr = getDLLAttr(Class);
6305 if (!ClassAttr)
6306 return;
6307
6308 assert(ClassAttr->getKind() == attr::DLLExport);
6309
6310 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6311
6313 // Don't go any further if this is just an explicit instantiation
6314 // declaration.
6315 return;
6316
6317 // Add a context note to explain how we got to any diagnostics produced below.
6318 struct MarkingClassDllexported {
6319 Sema &S;
6320 MarkingClassDllexported(Sema &S, CXXRecordDecl *Class,
6321 SourceLocation AttrLoc)
6322 : S(S) {
6325 Ctx.PointOfInstantiation = AttrLoc;
6326 Ctx.Entity = Class;
6328 }
6329 ~MarkingClassDllexported() {
6331 }
6332 } MarkingDllexportedContext(S, Class, ClassAttr->getLocation());
6333
6334 if (S.Context.getTargetInfo().getTriple().isOSCygMing())
6335 S.MarkVTableUsed(Class->getLocation(), Class, true);
6336
6337 for (Decl *Member : Class->decls()) {
6338 // Skip members that were not marked exported.
6339 if (!Member->hasAttr<DLLExportAttr>())
6340 continue;
6341
6342 // Defined static variables that are members of an exported base
6343 // class must be marked export too.
6344 auto *VD = dyn_cast<VarDecl>(Member);
6345 if (VD && VD->getStorageClass() == SC_Static &&
6347 S.MarkVariableReferenced(VD->getLocation(), VD);
6348
6349 auto *MD = dyn_cast<CXXMethodDecl>(Member);
6350 if (!MD)
6351 continue;
6352
6353 if (MD->isUserProvided()) {
6354 // Instantiate non-default class member functions ...
6355
6356 // .. except for certain kinds of template specializations.
6357 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
6358 continue;
6359
6360 // If this is an MS ABI dllexport default constructor, instantiate any
6361 // default arguments.
6363 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6364 if (CD && CD->isDefaultConstructor() && TSK == TSK_Undeclared) {
6366 CD->getAttr<DLLExportAttr>()->getLocation(), CD);
6367 }
6368 }
6369
6370 S.MarkFunctionReferenced(Class->getLocation(), MD);
6371
6372 // The function will be passed to the consumer when its definition is
6373 // encountered.
6374 } else if (MD->isExplicitlyDefaulted()) {
6375 // Synthesize and instantiate explicitly defaulted methods.
6376 S.MarkFunctionReferenced(Class->getLocation(), MD);
6377
6379 // Except for explicit instantiation defs, we will not see the
6380 // definition again later, so pass it to the consumer now.
6382 }
6383 } else if (!MD->isTrivial() ||
6384 MD->isCopyAssignmentOperator() ||
6385 MD->isMoveAssignmentOperator()) {
6386 // Synthesize and instantiate non-trivial implicit methods, and the copy
6387 // and move assignment operators. The latter are exported even if they
6388 // are trivial, because the address of an operator can be taken and
6389 // should compare equal across libraries.
6390 S.MarkFunctionReferenced(Class->getLocation(), MD);
6391
6392 // There is no later point when we will see the definition of this
6393 // function, so pass it to the consumer now.
6395 }
6396 }
6397}
6398
6400 CXXRecordDecl *Class) {
6401 // Only the MS ABI has default constructor closures, so we don't need to do
6402 // this semantic checking anywhere else.
6404 return;
6405
6406 if (Class->isInvalidDecl())
6407 return;
6408
6409 CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
6410 for (Decl *Member : Class->decls()) {
6411 // Nested classes finish delayed default argument parsing with the outermost
6412 // class, so check each nested definition here.
6413 if (auto *NestedClass = dyn_cast<CXXRecordDecl>(Member)) {
6414 if (NestedClass->isThisDeclarationADefinition())
6416 continue;
6417 }
6418
6419 // Look for exported default constructors.
6420 auto *CD = dyn_cast<CXXConstructorDecl>(Member);
6421 if (!CD || !CD->isDefaultConstructor())
6422 continue;
6423 auto *Attr = CD->getAttr<DLLExportAttr>();
6424 if (!Attr)
6425 continue;
6426
6427 // If the class is non-dependent, mark the default arguments as ODR-used so
6428 // that we can properly codegen the constructor closure.
6429 if (!Class->isDependentContext()) {
6432 }
6433
6434 if (LastExportedDefaultCtor) {
6435 S.Diag(LastExportedDefaultCtor->getLocation(),
6436 diag::err_attribute_dll_ambiguous_default_ctor)
6437 << Class;
6438 S.Diag(CD->getLocation(), diag::note_entity_declared_at)
6439 << CD->getDeclName();
6440 return;
6441 }
6442 LastExportedDefaultCtor = CD;
6443 }
6444}
6445
6447 CXXRecordDecl *Class) {
6448 bool ErrorReported = false;
6449 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6450 ClassTemplateDecl *TD) {
6451 if (ErrorReported)
6452 return;
6453 S.Diag(TD->getLocation(),
6454 diag::err_cuda_device_builtin_surftex_cls_template)
6455 << /*surface*/ 0 << TD;
6456 ErrorReported = true;
6457 };
6458
6459 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6460 if (!TD) {
6461 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6462 if (!SD) {
6463 S.Diag(Class->getLocation(),
6464 diag::err_cuda_device_builtin_surftex_ref_decl)
6465 << /*surface*/ 0 << Class;
6466 S.Diag(Class->getLocation(),
6467 diag::note_cuda_device_builtin_surftex_should_be_template_class)
6468 << Class;
6469 return;
6470 }
6471 TD = SD->getSpecializedTemplate();
6472 }
6473
6475 unsigned N = Params->size();
6476
6477 if (N != 2) {
6478 reportIllegalClassTemplate(S, TD);
6479 S.Diag(TD->getLocation(),
6480 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6481 << TD << 2;
6482 }
6483 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6484 reportIllegalClassTemplate(S, TD);
6485 S.Diag(TD->getLocation(),
6486 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6487 << TD << /*1st*/ 0 << /*type*/ 0;
6488 }
6489 if (N > 1) {
6490 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6491 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6492 reportIllegalClassTemplate(S, TD);
6493 S.Diag(TD->getLocation(),
6494 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6495 << TD << /*2nd*/ 1 << /*integer*/ 1;
6496 }
6497 }
6498}
6499
6501 CXXRecordDecl *Class) {
6502 bool ErrorReported = false;
6503 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6504 ClassTemplateDecl *TD) {
6505 if (ErrorReported)
6506 return;
6507 S.Diag(TD->getLocation(),
6508 diag::err_cuda_device_builtin_surftex_cls_template)
6509 << /*texture*/ 1 << TD;
6510 ErrorReported = true;
6511 };
6512
6513 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6514 if (!TD) {
6515 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6516 if (!SD) {
6517 S.Diag(Class->getLocation(),
6518 diag::err_cuda_device_builtin_surftex_ref_decl)
6519 << /*texture*/ 1 << Class;
6520 S.Diag(Class->getLocation(),
6521 diag::note_cuda_device_builtin_surftex_should_be_template_class)
6522 << Class;
6523 return;
6524 }
6525 TD = SD->getSpecializedTemplate();
6526 }
6527
6529 unsigned N = Params->size();
6530
6531 if (N != 3) {
6532 reportIllegalClassTemplate(S, TD);
6533 S.Diag(TD->getLocation(),
6534 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6535 << TD << 3;
6536 }
6537 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6538 reportIllegalClassTemplate(S, TD);
6539 S.Diag(TD->getLocation(),
6540 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6541 << TD << /*1st*/ 0 << /*type*/ 0;
6542 }
6543 if (N > 1) {
6544 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6545 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6546 reportIllegalClassTemplate(S, TD);
6547 S.Diag(TD->getLocation(),
6548 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6549 << TD << /*2nd*/ 1 << /*integer*/ 1;
6550 }
6551 }
6552 if (N > 2) {
6553 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2));
6554 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6555 reportIllegalClassTemplate(S, TD);
6556 S.Diag(TD->getLocation(),
6557 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6558 << TD << /*3rd*/ 2 << /*integer*/ 1;
6559 }
6560 }
6561}
6562
6564 // Mark any compiler-generated routines with the implicit code_seg attribute.
6565 for (auto *Method : Class->methods()) {
6566 if (Method->isUserProvided())
6567 continue;
6568 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
6569 Method->addAttr(A);
6570 }
6571}
6572
6574 Attr *ClassAttr = getDLLAttr(Class);
6575
6576 // MSVC inherits DLL attributes to partial class template specializations.
6577 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) {
6578 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
6579 if (Attr *TemplateAttr =
6580 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
6581 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
6582 A->setInherited(true);
6583 ClassAttr = A;
6584 }
6585 }
6586 }
6587
6588 if (!ClassAttr)
6589 return;
6590
6591 // MSVC allows imported or exported template classes that have UniqueExternal
6592 // linkage. This occurs when the template class has been instantiated with
6593 // a template parameter which itself has internal linkage.
6594 // We drop the attribute to avoid exporting or importing any members.
6595 if ((Context.getTargetInfo().getCXXABI().isMicrosoft() ||
6596 Context.getTargetInfo().getTriple().isPS()) &&
6597 (!Class->isExternallyVisible() && Class->hasExternalFormalLinkage())) {
6598 Class->dropAttrs<DLLExportAttr, DLLImportAttr>();
6599 return;
6600 }
6601
6602 if (!Class->isExternallyVisible()) {
6603 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
6604 << Class << ClassAttr;
6605 return;
6606 }
6607
6608 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6609 !ClassAttr->isInherited()) {
6610 // Diagnose dll attributes on members of class with dll attribute.
6611 for (Decl *Member : Class->decls()) {
6613 continue;
6614 InheritableAttr *MemberAttr = getDLLAttr(Member);
6615 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
6616 continue;
6617
6618 Diag(MemberAttr->getLocation(),
6619 diag::err_attribute_dll_member_of_dll_class)
6620 << MemberAttr << ClassAttr;
6621 Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
6622 Member->setInvalidDecl();
6623 }
6624 }
6625
6626 if (Class->getDescribedClassTemplate())
6627 // Don't inherit dll attribute until the template is instantiated.
6628 return;
6629
6630 // The class is either imported or exported.
6631 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
6632
6633 // Check if this was a dllimport attribute propagated from a derived class to
6634 // a base class template specialization. We don't apply these attributes to
6635 // static data members.
6636 const bool PropagatedImport =
6637 !ClassExported &&
6638 cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
6639
6640 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6641
6642 // Ignore explicit dllexport on explicit class template instantiation
6643 // declarations, except in MinGW mode.
6644 if (ClassExported && !ClassAttr->isInherited() &&
6646 !Context.getTargetInfo().getTriple().isOSCygMing()) {
6647 if (auto *DEA = Class->getAttr<DLLExportAttr>()) {
6648 Class->addAttr(DLLExportOnDeclAttr::Create(Context, DEA->getLoc()));
6649 Class->dropAttr<DLLExportAttr>();
6650 }
6651 return;
6652 }
6653
6654 // Force declaration of implicit members so they can inherit the attribute.
6656
6657 // Inherited constructors are created lazily; force their creation now so the
6658 // loop below can propagate the DLL attribute to them.
6659 if (ClassExported && getLangOpts().DllExportInlines) {
6661 for (Decl *D : Class->decls())
6662 if (auto *S = dyn_cast<ConstructorUsingShadowDecl>(D))
6663 Shadows.push_back(S);
6664 for (ConstructorUsingShadowDecl *S : Shadows) {
6665 CXXConstructorDecl *BC = dyn_cast<CXXConstructorDecl>(S->getTargetDecl());
6666 if (!BC || BC->isDeleted())
6667 continue;
6668 // Skip constructors whose requires clause is not satisfied.
6669 // Normally overload resolution filters these, but we are bypassing
6670 // it to eagerly create inherited constructors for dllexport.
6671 if (BC->getTrailingRequiresClause()) {
6672 ConstraintSatisfaction Satisfaction;
6673 if (CheckFunctionConstraints(BC, Satisfaction) ||
6674 !Satisfaction.IsSatisfied)
6675 continue;
6676 }
6677 findInheritingConstructor(Class->getLocation(), BC, S);
6678 }
6679 }
6680
6681 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
6682 // seem to be true in practice?
6683
6684 for (Decl *Member : Class->decls()) {
6685 if (Member->hasAttr<ExcludeFromExplicitInstantiationAttr>())
6686 continue;
6687
6688 VarDecl *VD = dyn_cast<VarDecl>(Member);
6689 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
6690
6691 // Only methods and static fields inherit the attributes.
6692 if (!VD && !MD)
6693 continue;
6694
6695 if (MD) {
6696 // Don't process deleted methods.
6697 if (MD->isDeleted())
6698 continue;
6699
6700 if (ClassExported && getLangOpts().DllExportInlines) {
6701 CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(MD);
6702 if (CD && CD->getInheritedConstructor()) {
6703 // Inherited constructors already had their base constructor's
6704 // constraints checked before creation via
6705 // findInheritingConstructor, so only ABI-compatibility checks
6706 // are needed here.
6707 //
6708 // Don't export inherited constructors whose parameters prevent
6709 // ABI-compatible forwarding. When canEmitDelegateCallArgs (in
6710 // CodeGen) returns false, Clang inlines the constructor body
6711 // instead of emitting a forwarding thunk, producing code that
6712 // is not ABI-compatible with MSVC. Suppress the export and warn
6713 // so the user gets a linker error rather than a silent runtime
6714 // mismatch.
6715 if (CD->isVariadic()) {
6716 Diag(CD->getLocation(),
6717 diag::warn_dllexport_inherited_ctor_unsupported)
6718 << /*variadic=*/0;
6719 continue;
6720 }
6721 if (Context.getTargetInfo()
6722 .getCXXABI()
6723 .areArgsDestroyedLeftToRightInCallee()) {
6724 bool HasCalleeCleanupParam = false;
6725 for (const ParmVarDecl *P : CD->parameters())
6726 if (P->needsDestruction(Context)) {
6727 HasCalleeCleanupParam = true;
6728 break;
6729 }
6730 if (HasCalleeCleanupParam) {
6731 Diag(CD->getLocation(),
6732 diag::warn_dllexport_inherited_ctor_unsupported)
6733 << /*callee-cleanup=*/1;
6734 continue;
6735 }
6736 }
6737 } else if (MD->getTrailingRequiresClause()) {
6738 // Don't export methods whose requires clause is not satisfied.
6739 // For class template specializations, member constraints may
6740 // depend on template arguments and an unsatisfied constraint
6741 // means the member should not be available in this
6742 // specialization.
6743 ConstraintSatisfaction Satisfaction;
6744 if (CheckFunctionConstraints(MD, Satisfaction) ||
6745 !Satisfaction.IsSatisfied)
6746 continue;
6747 }
6748 }
6749
6750 if (MD->isInlined()) {
6751 // MinGW does not import or export inline methods. But do it for
6752 // template instantiations and inherited constructors (which are
6753 // marked inline but must be exported to match MSVC behavior).
6754 if (!Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6757 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6758 !CD || !CD->getInheritedConstructor())
6759 continue;
6760 }
6761
6762 // MSVC versions before 2015 don't export the move assignment operators
6763 // and move constructor, so don't attempt to import/export them if
6764 // we have a definition.
6765 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
6766 if ((MD->isMoveAssignmentOperator() ||
6767 (Ctor && Ctor->isMoveConstructor())) &&
6768 getLangOpts().isCompatibleWithMSVC() &&
6769 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
6770 continue;
6771
6772 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
6773 // operator is exported anyway.
6774 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6775 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
6776 continue;
6777 }
6778 }
6779
6780 // Don't apply dllimport attributes to static data members of class template
6781 // instantiations when the attribute is propagated from a derived class.
6782 if (VD && PropagatedImport)
6783 continue;
6784
6786 continue;
6787
6788 if (!getDLLAttr(Member)) {
6789 InheritableAttr *NewAttr = nullptr;
6790
6791 // Do not export/import inline function when -fno-dllexport-inlines is
6792 // passed. But add attribute for later local static var check.
6793 if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
6796 if (ClassExported) {
6797 NewAttr = ::new (getASTContext())
6798 DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);
6799 } else {
6800 NewAttr = ::new (getASTContext())
6801 DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);
6802 }
6803 } else {
6804 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6805 }
6806
6807 NewAttr->setInherited(true);
6808 Member->addAttr(NewAttr);
6809
6810 if (MD) {
6811 // Propagate DLLAttr to friend re-declarations of MD that have already
6812 // been constructed.
6813 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
6814 FD = FD->getPreviousDecl()) {
6816 continue;
6817 assert(!getDLLAttr(FD) &&
6818 "friend re-decl should not already have a DLLAttr");
6819 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6820 NewAttr->setInherited(true);
6821 FD->addAttr(NewAttr);
6822 }
6823 }
6824 }
6825 }
6826
6827 if (ClassExported)
6828 DelayedDllExportClasses.push_back(Class);
6829}
6830
6832 CXXRecordDecl *Class, Attr *ClassAttr,
6833 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
6834 if (getDLLAttr(
6835 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
6836 // If the base class template has a DLL attribute, don't try to change it.
6837 return;
6838 }
6839
6840 auto TSK = BaseTemplateSpec->getSpecializationKind();
6841 if (!getDLLAttr(BaseTemplateSpec) &&
6843 TSK == TSK_ImplicitInstantiation)) {
6844 // The template hasn't been instantiated yet (or it has, but only as an
6845 // explicit instantiation declaration or implicit instantiation, which means
6846 // we haven't codegenned any members yet), so propagate the attribute.
6847 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6848 NewAttr->setInherited(true);
6849 BaseTemplateSpec->addAttr(NewAttr);
6850
6851 // If this was an import, mark that we propagated it from a derived class to
6852 // a base class template specialization.
6853 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
6854 ImportAttr->setPropagatedToBaseTemplate();
6855
6856 // If the template is already instantiated, checkDLLAttributeRedeclaration()
6857 // needs to be run again to work see the new attribute. Otherwise this will
6858 // get run whenever the template is instantiated.
6859 if (TSK != TSK_Undeclared)
6860 checkClassLevelDLLAttribute(BaseTemplateSpec);
6861
6862 return;
6863 }
6864
6865 if (getDLLAttr(BaseTemplateSpec)) {
6866 // The template has already been specialized or instantiated with an
6867 // attribute, explicitly or through propagation. We should not try to change
6868 // it.
6869 return;
6870 }
6871
6872 // The template was previously instantiated or explicitly specialized without
6873 // a dll attribute, It's too late for us to add an attribute, so warn that
6874 // this is unsupported.
6875 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
6876 << BaseTemplateSpec->isExplicitSpecialization();
6877 Diag(ClassAttr->getLocation(), diag::note_attribute);
6878 if (BaseTemplateSpec->isExplicitSpecialization()) {
6879 Diag(BaseTemplateSpec->getLocation(),
6880 diag::note_template_class_explicit_specialization_was_here)
6881 << BaseTemplateSpec;
6882 } else {
6883 Diag(BaseTemplateSpec->getPointOfInstantiation(),
6884 diag::note_template_class_instantiation_was_here)
6885 << BaseTemplateSpec;
6886 }
6887}
6888
6889namespace {
6890/// RAII object to restore the floating-point (FP) features active at the time
6891/// a defaulted function was declared. This ensures that the synthesized body
6892/// of the function respects the FP pragmas (e.g., #pragma STDC FENV_ACCESS)
6893/// that were in effect when the function was explicitly defaulted.
6894struct DefaultedFunctionFPFeaturesRAII {
6895 Sema::FPFeaturesStateRAII SavedFPFeatures;
6896 DefaultedFunctionFPFeaturesRAII(Sema &S, FunctionDecl *FD)
6897 : SavedFPFeatures(S) {
6898 auto *Info = FD->getDefaultedOrDeletedInfo();
6899 FPOptionsOverride FPO = Info ? Info->getFPFeatures() : FPOptionsOverride();
6901 S.FpPragmaStack.CurrentValue = FPO;
6902 }
6903
6904 ~DefaultedFunctionFPFeaturesRAII() = default;
6905};
6906} // namespace
6907
6909 SourceLocation DefaultLoc) {
6911 if (DFK.isComparison())
6912 return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison());
6913
6914 switch (DFK.asSpecialMember()) {
6918 break;
6921 break;
6924 break;
6927 break;
6930 break;
6933 break;
6935 llvm_unreachable("Invalid special member.");
6936 }
6937}
6938
6939/// Determine whether a type is permitted to be passed or returned in
6940/// registers, per C++ [class.temporary]p3.
6943 if (D->isDependentType() || D->isInvalidDecl())
6944 return false;
6945
6946 // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
6947 // The PS4 platform ABI follows the behavior of Clang 3.2.
6949 return !D->hasNonTrivialDestructorForCall() &&
6951
6952 if (CCK == TargetInfo::CCK_MicrosoftWin64) {
6953 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
6954 bool DtorIsTrivialForCall = false;
6955
6956 // If a class has at least one eligible, trivial copy constructor, it
6957 // is passed according to the C ABI. Otherwise, it is passed indirectly.
6958 //
6959 // Note: This permits classes with non-trivial copy or move ctors to be
6960 // passed in registers, so long as they *also* have a trivial copy ctor,
6961 // which is non-conforming.
6965 CopyCtorIsTrivial = true;
6967 CopyCtorIsTrivialForCall = true;
6968 }
6969 } else {
6970 for (const CXXConstructorDecl *CD : D->ctors()) {
6971 if (CD->isCopyConstructor() && !CD->isDeleted() &&
6972 !CD->isIneligibleOrNotSelected()) {
6973 if (CD->isTrivial())
6974 CopyCtorIsTrivial = true;
6975 if (CD->isTrivialForCall())
6976 CopyCtorIsTrivialForCall = true;
6977 }
6978 }
6979 }
6980
6981 if (D->needsImplicitDestructor()) {
6982 if (!D->defaultedDestructorIsDeleted() &&
6984 DtorIsTrivialForCall = true;
6985 } else if (const auto *DD = D->getDestructor()) {
6986 if (!DD->isDeleted() && DD->isTrivialForCall())
6987 DtorIsTrivialForCall = true;
6988 }
6989
6990 // If the copy ctor and dtor are both trivial-for-calls, pass direct.
6991 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
6992 return true;
6993
6994 // If a class has a destructor, we'd really like to pass it indirectly
6995 // because it allows us to elide copies. Unfortunately, MSVC makes that
6996 // impossible for small types, which it will pass in a single register or
6997 // stack slot. Most objects with dtors are large-ish, so handle that early.
6998 // We can't call out all large objects as being indirect because there are
6999 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
7000 // how we pass large POD types.
7001
7002 // Note: This permits small classes with nontrivial destructors to be
7003 // passed in registers, which is non-conforming.
7004 bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
7005 uint64_t TypeSize = isAArch64 ? 128 : 64;
7006
7007 if (CopyCtorIsTrivial && S.getASTContext().getTypeSize(
7008 S.Context.getCanonicalTagType(D)) <= TypeSize)
7009 return true;
7010 return false;
7011 }
7012
7013 // Per C++ [class.temporary]p3, the relevant condition is:
7014 // each copy constructor, move constructor, and destructor of X is
7015 // either trivial or deleted, and X has at least one non-deleted copy
7016 // or move constructor
7017 bool HasNonDeletedCopyOrMove = false;
7018
7022 return false;
7023 HasNonDeletedCopyOrMove = true;
7024 }
7025
7026 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
7029 return false;
7030 HasNonDeletedCopyOrMove = true;
7031 }
7032
7035 return false;
7036
7037 for (const CXXMethodDecl *MD : D->methods()) {
7038 if (MD->isDeleted() || MD->isIneligibleOrNotSelected())
7039 continue;
7040
7041 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
7042 if (CD && CD->isCopyOrMoveConstructor())
7043 HasNonDeletedCopyOrMove = true;
7044 else if (!isa<CXXDestructorDecl>(MD))
7045 continue;
7046
7047 if (!MD->isTrivialForCall())
7048 return false;
7049 }
7050
7051 return HasNonDeletedCopyOrMove;
7052}
7053
7054/// Report an error regarding overriding, along with any relevant
7055/// overridden methods.
7056///
7057/// \param DiagID the primary error to report.
7058/// \param MD the overriding method.
7059static bool
7060ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD,
7061 llvm::function_ref<bool(const CXXMethodDecl *)> Report) {
7062 bool IssuedDiagnostic = false;
7063 for (const CXXMethodDecl *O : MD->overridden_methods()) {
7064 if (Report(O)) {
7065 if (!IssuedDiagnostic) {
7066 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7067 IssuedDiagnostic = true;
7068 }
7069 S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
7070 }
7071 }
7072 return IssuedDiagnostic;
7073}
7074
7076 if (!Record)
7077 return;
7078
7079 if (Record->isAbstract() && !Record->isInvalidDecl()) {
7080 AbstractUsageInfo Info(*this, Record);
7082 }
7083
7084 // If this is not an aggregate type and has no user-declared constructor,
7085 // complain about any non-static data members of reference or const scalar
7086 // type, since they will never get initializers.
7087 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
7088 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
7089 !Record->isLambda()) {
7090 bool Complained = false;
7091 for (const auto *F : Record->fields()) {
7092 if (F->hasInClassInitializer() || F->isUnnamedBitField())
7093 continue;
7094
7095 if (F->getType()->isReferenceType() ||
7096 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
7097 if (!Complained) {
7098 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
7099 << Record->getTagKind() << Record;
7100 Complained = true;
7101 }
7102
7103 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
7104 << F->getType()->isReferenceType()
7105 << F->getDeclName();
7106 }
7107 }
7108 }
7109
7110 if (Record->getIdentifier()) {
7111 // C++ [class.mem]p13:
7112 // If T is the name of a class, then each of the following shall have a
7113 // name different from T:
7114 // - every member of every anonymous union that is a member of class T.
7115 //
7116 // C++ [class.mem]p14:
7117 // In addition, if class T has a user-declared constructor (12.1), every
7118 // non-static data member of class T shall have a name different from T.
7119 for (const NamedDecl *Element : Record->lookup(Record->getDeclName())) {
7120 const NamedDecl *D = Element->getUnderlyingDecl();
7121 // Invalid IndirectFieldDecls have already been diagnosed with
7122 // err_anonymous_record_member_redecl in
7123 // SemaDecl.cpp:CheckAnonMemberRedeclaration.
7125 Record->hasUserDeclaredConstructor()) ||
7126 (isa<IndirectFieldDecl>(D) && !D->isInvalidDecl())) {
7127 Diag(Element->getLocation(), diag::err_member_name_of_class)
7128 << D->getDeclName();
7129 break;
7130 }
7131 }
7132 }
7133
7134 // Warn if the class has virtual methods but non-virtual public destructor.
7135 if (Record->isPolymorphic() && !Record->isDependentType()) {
7136 CXXDestructorDecl *dtor = Record->getDestructor();
7137 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
7138 !Record->hasAttr<FinalAttr>())
7139 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
7140 diag::warn_non_virtual_dtor)
7141 << Context.getCanonicalTagType(Record);
7142 }
7143
7144 if (Record->isAbstract()) {
7145 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
7146 Diag(Record->getLocation(), diag::warn_abstract_final_class)
7147 << FA->isSpelledAsSealed();
7149 }
7150 }
7151
7152 // Warn if the class has a final destructor but is not itself marked final.
7153 if (!Record->hasAttr<FinalAttr>()) {
7154 if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
7155 if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
7156 Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class)
7157 << FA->isSpelledAsSealed()
7159 getLocForEndOfToken(Record->getLocation()),
7160 (FA->isSpelledAsSealed() ? " sealed" : " final"));
7161 Diag(Record->getLocation(),
7162 diag::note_final_dtor_non_final_class_silence)
7163 << Context.getCanonicalTagType(Record) << FA->isSpelledAsSealed();
7164 }
7165 }
7166 }
7167
7168 // See if trivial_abi has to be dropped.
7169 if (Record->hasAttr<TrivialABIAttr>())
7171
7172 // Set HasTrivialSpecialMemberForCall if the record has attribute
7173 // "trivial_abi".
7174 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
7175
7176 if (HasTrivialABI)
7177 Record->setHasTrivialSpecialMemberForCall();
7178
7179 // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=).
7180 // We check these last because they can depend on the properties of the
7181 // primary comparison functions (==, <=>).
7182 llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons;
7183
7184 // Perform checks that can't be done until we know all the properties of a
7185 // member function (whether it's defaulted, deleted, virtual, overriding,
7186 // ...).
7187 auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) {
7188 // A static function cannot override anything.
7189 if (MD->getStorageClass() == SC_Static) {
7190 if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD,
7191 [](const CXXMethodDecl *) { return true; }))
7192 return;
7193 }
7194
7195 // A deleted function cannot override a non-deleted function and vice
7196 // versa.
7197 if (ReportOverrides(*this,
7198 MD->isDeleted() ? diag::err_deleted_override
7199 : diag::err_non_deleted_override,
7200 MD, [&](const CXXMethodDecl *V) {
7201 return MD->isDeleted() != V->isDeleted();
7202 })) {
7203 if (MD->isDefaulted() && MD->isDeleted())
7204 // Explain why this defaulted function was deleted.
7206 return;
7207 }
7208
7209 // A consteval function cannot override a non-consteval function and vice
7210 // versa.
7211 if (ReportOverrides(*this,
7212 MD->isConsteval() ? diag::err_consteval_override
7213 : diag::err_non_consteval_override,
7214 MD, [&](const CXXMethodDecl *V) {
7215 return MD->isConsteval() != V->isConsteval();
7216 })) {
7217 if (MD->isDefaulted() && MD->isDeleted())
7218 // Explain why this defaulted function was deleted.
7220 return;
7221 }
7222 };
7223
7224 auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool {
7225 if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted())
7226 return false;
7227
7231 DefaultedSecondaryComparisons.push_back(FD);
7232 return true;
7233 }
7234
7236 return false;
7237 };
7238
7239 if (!Record->isInvalidDecl() &&
7240 Record->hasAttr<VTablePointerAuthenticationAttr>())
7242
7243 auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
7244 // Check whether the explicitly-defaulted members are valid.
7245 bool Incomplete = CheckForDefaultedFunction(M);
7246
7247 // Skip the rest of the checks for a member of a dependent class.
7248 if (Record->isDependentType())
7249 return;
7250
7251 // For an explicitly defaulted or deleted special member, we defer
7252 // determining triviality until the class is complete. That time is now!
7253 CXXSpecialMemberKind CSM = M->getSpecialMemberKind();
7254 if (!M->isImplicit() && !M->isUserProvided()) {
7255 if (CSM != CXXSpecialMemberKind::Invalid) {
7256 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
7257 // Inform the class that we've finished declaring this member.
7258 Record->finishedDefaultedOrDeletedMember(M);
7259 M->setTrivialForCall(
7260 HasTrivialABI ||
7263 Record->setTrivialForCallFlags(M);
7264 }
7265 }
7266
7267 // Set triviality for the purpose of calls if this is a user-provided
7268 // copy/move constructor or destructor.
7272 M->isUserProvided()) {
7273 M->setTrivialForCall(HasTrivialABI);
7274 Record->setTrivialForCallFlags(M);
7275 }
7276
7277 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
7278 M->hasAttr<DLLExportAttr>()) {
7279 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
7280 M->isTrivial() &&
7284 M->dropAttr<DLLExportAttr>();
7285
7286 if (M->hasAttr<DLLExportAttr>()) {
7287 // Define after any fields with in-class initializers have been parsed.
7289 }
7290 }
7291
7292 bool EffectivelyConstexprDestructor = true;
7293 // Avoid triggering vtable instantiation due to a dtor that is not
7294 // "effectively constexpr" for better compatibility.
7295 // See https://github.com/llvm/llvm-project/issues/102293 for more info.
7296 if (isa<CXXDestructorDecl>(M)) {
7297 llvm::SmallDenseSet<QualType> Visited;
7298 auto Check = [&Visited](QualType T, auto &&Check) -> bool {
7299 if (!Visited.insert(T->getCanonicalTypeUnqualified()).second)
7300 return false;
7301 const CXXRecordDecl *RD =
7302 T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
7303 if (!RD || !RD->isCompleteDefinition())
7304 return true;
7305
7306 if (!RD->hasConstexprDestructor())
7307 return false;
7308
7309 for (const CXXBaseSpecifier &B : RD->bases())
7310 if (!Check(B.getType(), Check))
7311 return false;
7312 for (const FieldDecl *FD : RD->fields())
7313 if (!Check(FD->getType(), Check))
7314 return false;
7315 return true;
7316 };
7317 EffectivelyConstexprDestructor =
7318 Check(Context.getCanonicalTagType(Record), Check);
7319 }
7320
7321 // Define defaulted constexpr virtual functions that override a base class
7322 // function right away.
7323 // FIXME: We can defer doing this until the vtable is marked as used.
7324 if (CSM != CXXSpecialMemberKind::Invalid && !M->isDeleted() &&
7325 M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods() &&
7326 EffectivelyConstexprDestructor)
7327 DefineDefaultedFunction(*this, M, M->getLocation());
7328
7329 if (!Incomplete)
7330 CheckCompletedMemberFunction(M);
7331 };
7332
7333 // Check the destructor before any other member function. We need to
7334 // determine whether it's trivial in order to determine whether the claas
7335 // type is a literal type, which is a prerequisite for determining whether
7336 // other special member functions are valid and whether they're implicitly
7337 // 'constexpr'.
7338 if (CXXDestructorDecl *Dtor = Record->getDestructor())
7339 CompleteMemberFunction(Dtor);
7340
7341 bool HasMethodWithOverrideControl = false,
7342 HasOverridingMethodWithoutOverrideControl = false;
7343 for (auto *D : Record->decls()) {
7344 if (auto *M = dyn_cast<CXXMethodDecl>(D)) {
7345 // FIXME: We could do this check for dependent types with non-dependent
7346 // bases.
7347 if (!Record->isDependentType()) {
7348 // See if a method overloads virtual methods in a base
7349 // class without overriding any.
7350 if (!M->isStatic())
7352
7353 if (M->hasAttr<OverrideAttr>()) {
7354 HasMethodWithOverrideControl = true;
7355 } else if (M->size_overridden_methods() > 0) {
7356 HasOverridingMethodWithoutOverrideControl = true;
7357 } else {
7358 // Warn on newly-declared virtual methods in `final` classes
7359 if (M->isVirtualAsWritten() && Record->isEffectivelyFinal()) {
7360 Diag(M->getLocation(), diag::warn_unnecessary_virtual_specifier)
7361 << M;
7362 }
7363 }
7364 }
7365
7366 if (!isa<CXXDestructorDecl>(M))
7367 CompleteMemberFunction(M);
7368 } else if (auto *F = dyn_cast<FriendDecl>(D)) {
7369 CheckForDefaultedFunction(
7370 dyn_cast_or_null<FunctionDecl>(F->getFriendDecl()));
7371 }
7372 }
7373
7374 if (HasOverridingMethodWithoutOverrideControl) {
7375 bool HasInconsistentOverrideControl = HasMethodWithOverrideControl;
7376 for (auto *M : Record->methods())
7377 DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl);
7378 }
7379
7380 // Check the defaulted secondary comparisons after any other member functions.
7381 for (FunctionDecl *FD : DefaultedSecondaryComparisons) {
7383
7384 // If this is a member function, we deferred checking it until now.
7385 if (auto *MD = dyn_cast<CXXMethodDecl>(FD))
7386 CheckCompletedMemberFunction(MD);
7387 }
7388
7389 // {ms,gcc}_struct is a request to change ABI rules to either follow
7390 // Microsoft or Itanium C++ ABI. However, even if these attributes are
7391 // present, we do not layout classes following foreign ABI rules, but
7392 // instead enter a special "compatibility mode", which only changes
7393 // alignments of fundamental types and layout of bit fields.
7394 // Check whether this class uses any C++ features that are implemented
7395 // completely differently in the requested ABI, and if so, emit a
7396 // diagnostic. That diagnostic defaults to an error, but we allow
7397 // projects to map it down to a warning (or ignore it). It's a fairly
7398 // common practice among users of the ms_struct pragma to
7399 // mass-annotate headers, sweeping up a bunch of types that the
7400 // project doesn't really rely on MSVC-compatible layout for. We must
7401 // therefore support "ms_struct except for C++ stuff" as a secondary
7402 // ABI.
7403 // Don't emit this diagnostic if the feature was enabled as a
7404 // language option (as opposed to via a pragma or attribute), as
7405 // the option -mms-bitfields otherwise essentially makes it impossible
7406 // to build C++ code, unless this diagnostic is turned off.
7407 if (Context.getLangOpts().getLayoutCompatibility() ==
7409 Record->isMsStruct(Context) != Context.defaultsToMsStruct() &&
7410 (Record->isPolymorphic() || Record->getNumBases())) {
7411 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
7412 }
7413
7416
7417 bool ClangABICompat4 =
7418 Context.getLangOpts().isCompatibleWith(LangOptions::ClangABI::Ver4);
7420 Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
7421 bool CanPass = canPassInRegisters(*this, Record, CCK);
7422
7423 // Do not change ArgPassingRestrictions if it has already been set to
7424 // RecordArgPassingKind::CanNeverPassInRegs.
7425 if (Record->getArgPassingRestrictions() !=
7427 Record->setArgPassingRestrictions(
7430
7431 // If canPassInRegisters returns true despite the record having a non-trivial
7432 // destructor, the record is destructed in the callee. This happens only when
7433 // the record or one of its subobjects has a field annotated with trivial_abi
7434 // or a field qualified with ObjC __strong/__weak.
7435 if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
7436 Record->setParamDestroyedInCallee(true);
7437 else if (Record->hasNonTrivialDestructor())
7438 Record->setParamDestroyedInCallee(CanPass);
7439
7440 if (getLangOpts().ForceEmitVTables) {
7441 // If we want to emit all the vtables, we need to mark it as used. This
7442 // is especially required for cases like vtable assumption loads.
7443 MarkVTableUsed(Record->getInnerLocStart(), Record);
7444 }
7445
7446 if (getLangOpts().CUDA) {
7447 if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>())
7449 else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>())
7451 }
7452
7453 llvm::SmallDenseMap<OverloadedOperatorKind,
7455 TypeAwareDecls{{OO_New, {}},
7456 {OO_Array_New, {}},
7457 {OO_Delete, {}},
7458 {OO_Array_New, {}}};
7459 for (auto *D : Record->decls()) {
7460 const FunctionDecl *FnDecl = D->getAsFunction();
7461 if (!FnDecl || !FnDecl->isTypeAwareOperatorNewOrDelete())
7462 continue;
7463 assert(FnDecl->getDeclName().isAnyOperatorNewOrDelete());
7464 TypeAwareDecls[FnDecl->getOverloadedOperator()].push_back(FnDecl);
7465 }
7466 auto CheckMismatchedTypeAwareAllocators =
7467 [this, &TypeAwareDecls, Record](OverloadedOperatorKind NewKind,
7468 OverloadedOperatorKind DeleteKind) {
7469 auto &NewDecls = TypeAwareDecls[NewKind];
7470 auto &DeleteDecls = TypeAwareDecls[DeleteKind];
7471 if (NewDecls.empty() == DeleteDecls.empty())
7472 return;
7473 DeclarationName FoundOperator =
7474 Context.DeclarationNames.getCXXOperatorName(
7475 NewDecls.empty() ? DeleteKind : NewKind);
7476 DeclarationName MissingOperator =
7477 Context.DeclarationNames.getCXXOperatorName(
7478 NewDecls.empty() ? NewKind : DeleteKind);
7479 Diag(Record->getLocation(),
7480 diag::err_type_aware_allocator_missing_matching_operator)
7481 << FoundOperator << Context.getCanonicalTagType(Record)
7482 << MissingOperator;
7483 for (auto MD : NewDecls)
7484 Diag(MD->getLocation(),
7485 diag::note_unmatched_type_aware_allocator_declared)
7486 << MD;
7487 for (auto MD : DeleteDecls)
7488 Diag(MD->getLocation(),
7489 diag::note_unmatched_type_aware_allocator_declared)
7490 << MD;
7491 };
7492 CheckMismatchedTypeAwareAllocators(OO_New, OO_Delete);
7493 CheckMismatchedTypeAwareAllocators(OO_Array_New, OO_Array_Delete);
7494}
7495
7496/// Look up the special member function that would be called by a special
7497/// member function for a subobject of class type.
7498///
7499/// \param Class The class type of the subobject.
7500/// \param CSM The kind of special member function.
7501/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
7502/// \param ConstRHS True if this is a copy operation with a const object
7503/// on its RHS, that is, if the argument to the outer special member
7504/// function is 'const' and this is not a field marked 'mutable'.
7507 CXXSpecialMemberKind CSM, unsigned FieldQuals,
7508 bool ConstRHS) {
7509 unsigned LHSQuals = 0;
7512 LHSQuals = FieldQuals;
7513
7514 unsigned RHSQuals = FieldQuals;
7517 RHSQuals = 0;
7518 else if (ConstRHS)
7519 RHSQuals |= Qualifiers::Const;
7520
7521 return S.LookupSpecialMember(Class, CSM,
7522 RHSQuals & Qualifiers::Const,
7523 RHSQuals & Qualifiers::Volatile,
7524 false,
7525 LHSQuals & Qualifiers::Const,
7526 LHSQuals & Qualifiers::Volatile);
7527}
7528
7530 Sema &S;
7531 SourceLocation UseLoc;
7532
7533 /// A mapping from the base classes through which the constructor was
7534 /// inherited to the using shadow declaration in that base class (or a null
7535 /// pointer if the constructor was declared in that base class).
7536 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
7537 InheritedFromBases;
7538
7539public:
7542 : S(S), UseLoc(UseLoc) {
7543 bool DiagnosedMultipleConstructedBases = false;
7544 CXXRecordDecl *ConstructedBase = nullptr;
7545 BaseUsingDecl *ConstructedBaseIntroducer = nullptr;
7546
7547 // Find the set of such base class subobjects and check that there's a
7548 // unique constructed subobject.
7549 for (auto *D : Shadow->redecls()) {
7550 auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
7551 auto *DNominatedBase = DShadow->getNominatedBaseClass();
7552 auto *DConstructedBase = DShadow->getConstructedBaseClass();
7553
7554 InheritedFromBases.insert(
7555 std::make_pair(DNominatedBase->getCanonicalDecl(),
7556 DShadow->getNominatedBaseClassShadowDecl()));
7557 if (DShadow->constructsVirtualBase())
7558 InheritedFromBases.insert(
7559 std::make_pair(DConstructedBase->getCanonicalDecl(),
7560 DShadow->getConstructedBaseClassShadowDecl()));
7561 else
7562 assert(DNominatedBase == DConstructedBase);
7563
7564 // [class.inhctor.init]p2:
7565 // If the constructor was inherited from multiple base class subobjects
7566 // of type B, the program is ill-formed.
7567 if (!ConstructedBase) {
7568 ConstructedBase = DConstructedBase;
7569 ConstructedBaseIntroducer = D->getIntroducer();
7570 } else if (ConstructedBase != DConstructedBase &&
7571 !Shadow->isInvalidDecl()) {
7572 if (!DiagnosedMultipleConstructedBases) {
7573 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
7574 << Shadow->getTargetDecl();
7575 S.Diag(ConstructedBaseIntroducer->getLocation(),
7576 diag::note_ambiguous_inherited_constructor_using)
7577 << ConstructedBase;
7578 DiagnosedMultipleConstructedBases = true;
7579 }
7580 S.Diag(D->getIntroducer()->getLocation(),
7581 diag::note_ambiguous_inherited_constructor_using)
7582 << DConstructedBase;
7583 }
7584 }
7585
7586 if (DiagnosedMultipleConstructedBases)
7587 Shadow->setInvalidDecl();
7588 }
7589
7590 /// Find the constructor to use for inherited construction of a base class,
7591 /// and whether that base class constructor inherits the constructor from a
7592 /// virtual base class (in which case it won't actually invoke it).
7593 std::pair<CXXConstructorDecl *, bool>
7595 auto It = InheritedFromBases.find(Base->getCanonicalDecl());
7596 if (It == InheritedFromBases.end())
7597 return std::make_pair(nullptr, false);
7598
7599 // This is an intermediary class.
7600 if (It->second)
7601 return std::make_pair(
7602 S.findInheritingConstructor(UseLoc, Ctor, It->second),
7603 It->second->constructsVirtualBase());
7604
7605 // This is the base class from which the constructor was inherited.
7606 return std::make_pair(Ctor, false);
7607 }
7608};
7609
7610/// Is the special member function which would be selected to perform the
7611/// specified operation on the specified class type a constexpr constructor?
7613 Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, unsigned Quals,
7614 bool ConstRHS, CXXConstructorDecl *InheritedCtor = nullptr,
7615 Sema::InheritedConstructorInfo *Inherited = nullptr) {
7616 // Suppress duplicate constraint checking here, in case a constraint check
7617 // caused us to decide to do this. Any truely recursive checks will get
7618 // caught during these checks anyway.
7620
7621 // If we're inheriting a constructor, see if we need to call it for this base
7622 // class.
7623 if (InheritedCtor) {
7625 auto BaseCtor =
7626 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
7627 if (BaseCtor)
7628 return BaseCtor->isConstexpr();
7629 }
7630
7632 return ClassDecl->hasConstexprDefaultConstructor();
7634 return ClassDecl->hasConstexprDestructor();
7635
7637 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
7638 if (!SMOR.getMethod())
7639 // A constructor we wouldn't select can't be "involved in initializing"
7640 // anything.
7641 return true;
7642 return SMOR.getMethod()->isConstexpr();
7643}
7644
7645/// Determine whether the specified special member function would be constexpr
7646/// if it were implicitly defined.
7648 Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, bool ConstArg,
7649 CXXConstructorDecl *InheritedCtor = nullptr,
7650 Sema::InheritedConstructorInfo *Inherited = nullptr) {
7651 if (!S.getLangOpts().CPlusPlus11)
7652 return false;
7653
7654 // C++11 [dcl.constexpr]p4:
7655 // In the definition of a constexpr constructor [...]
7656 bool Ctor = true;
7657 switch (CSM) {
7659 if (Inherited)
7660 break;
7661 // Since default constructor lookup is essentially trivial (and cannot
7662 // involve, for instance, template instantiation), we compute whether a
7663 // defaulted default constructor is constexpr directly within CXXRecordDecl.
7664 //
7665 // This is important for performance; we need to know whether the default
7666 // constructor is constexpr to determine whether the type is a literal type.
7667 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
7668
7671 // For copy or move constructors, we need to perform overload resolution.
7672 break;
7673
7676 if (!S.getLangOpts().CPlusPlus14)
7677 return false;
7678 // In C++1y, we need to perform overload resolution.
7679 Ctor = false;
7680 break;
7681
7683 return ClassDecl->defaultedDestructorIsConstexpr();
7684
7686 return false;
7687 }
7688
7689 // -- if the class is a non-empty union, or for each non-empty anonymous
7690 // union member of a non-union class, exactly one non-static data member
7691 // shall be initialized; [DR1359]
7692 //
7693 // If we squint, this is guaranteed, since exactly one non-static data member
7694 // will be initialized (if the constructor isn't deleted), we just don't know
7695 // which one.
7696 if (Ctor && ClassDecl->isUnion())
7698 ? ClassDecl->hasInClassInitializer() ||
7699 !ClassDecl->hasVariantMembers()
7700 : true;
7701
7702 // -- the class shall not have any virtual base classes;
7703 if (!S.getLangOpts().CPlusPlus26 && Ctor && ClassDecl->getNumVBases())
7704 return false;
7705
7706 // C++1y [class.copy]p26:
7707 // -- [the class] is a literal type, and
7708 if (!S.getLangOpts().CPlusPlus23 && !Ctor && !ClassDecl->isLiteral())
7709 return false;
7710
7711 // -- every constructor involved in initializing [...] base class
7712 // sub-objects shall be a constexpr constructor;
7713 // -- the assignment operator selected to copy/move each direct base
7714 // class is a constexpr function, and
7715 if (!S.getLangOpts().CPlusPlus23) {
7716 for (const auto &B : ClassDecl->bases()) {
7717 auto *BaseClassDecl = B.getType()->getAsCXXRecordDecl();
7718 if (!BaseClassDecl)
7719 continue;
7720 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
7721 InheritedCtor, Inherited))
7722 return false;
7723 }
7724 }
7725
7726 // -- every constructor involved in initializing non-static data members
7727 // [...] shall be a constexpr constructor;
7728 // -- every non-static data member and base class sub-object shall be
7729 // initialized
7730 // -- for each non-static data member of X that is of class type (or array
7731 // thereof), the assignment operator selected to copy/move that member is
7732 // a constexpr function
7733 if (!S.getLangOpts().CPlusPlus23) {
7734 for (const auto *F : ClassDecl->fields()) {
7735 if (F->isInvalidDecl())
7736 continue;
7738 F->hasInClassInitializer())
7739 continue;
7740 QualType BaseType = S.Context.getBaseElementType(F->getType());
7741 if (const RecordType *RecordTy = BaseType->getAsCanonical<RecordType>()) {
7742 auto *FieldRecDecl =
7743 cast<CXXRecordDecl>(RecordTy->getDecl())->getDefinitionOrSelf();
7744 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
7745 BaseType.getCVRQualifiers(),
7746 ConstArg && !F->isMutable()))
7747 return false;
7748 } else if (CSM == CXXSpecialMemberKind::DefaultConstructor) {
7749 return false;
7750 }
7751 }
7752 }
7753
7754 // All OK, it's constexpr!
7755 return true;
7756}
7757
7758namespace {
7759/// RAII object to register a defaulted function as having its exception
7760/// specification computed.
7761struct ComputingExceptionSpec {
7762 Sema &S;
7763
7764 ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc)
7765 : S(S) {
7766 Sema::CodeSynthesisContext Ctx;
7768 Ctx.PointOfInstantiation = Loc;
7769 Ctx.Entity = FD;
7771 }
7772 ~ComputingExceptionSpec() {
7774 }
7775};
7776}
7777
7778static Sema::ImplicitExceptionSpecification
7779ComputeDefaultedSpecialMemberExceptionSpec(Sema &S, SourceLocation Loc,
7780 CXXMethodDecl *MD,
7782 Sema::InheritedConstructorInfo *ICI);
7783
7784static Sema::ImplicitExceptionSpecification
7785ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
7786 FunctionDecl *FD,
7788
7789static Sema::ImplicitExceptionSpecification
7791 auto DFK = FD->getDefaultedFunctionKind();
7792 if (DFK.isSpecialMember())
7794 S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr);
7795 if (DFK.isComparison())
7797 DFK.asComparison());
7798
7799 auto *CD = cast<CXXConstructorDecl>(FD);
7800 assert(CD->getInheritedConstructor() &&
7801 "only defaulted functions and inherited constructors have implicit "
7802 "exception specs");
7804 S, Loc, CD->getInheritedConstructor().getShadowDecl());
7807}
7808
7810 CXXMethodDecl *MD) {
7812
7813 // Build an exception specification pointing back at this member.
7815 EPI.ExceptionSpec.SourceDecl = MD;
7816
7817 // Set the calling convention to the default for C++ instance methods.
7819 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
7820 /*IsCXXMethod=*/true));
7821 return EPI;
7822}
7823
7825 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
7827 return;
7828
7829 // Evaluate the exception specification.
7830 auto IES = computeImplicitExceptionSpec(*this, Loc, FD);
7831 auto ESI = IES.getExceptionSpec();
7832
7833 // Update the type of the special member to use it.
7834 UpdateExceptionSpec(FD, ESI);
7835}
7836
7838 assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted");
7839
7841 if (!DefKind) {
7842 assert(FD->getDeclContext()->isDependentContext());
7843 return;
7844 }
7845
7846 if (DefKind.isComparison()) {
7847 auto PT = FD->getParamDecl(0)->getType();
7848 if (const CXXRecordDecl *RD =
7849 PT.getNonReferenceType()->getAsCXXRecordDecl()) {
7850 for (FieldDecl *Field : RD->fields()) {
7851 UnusedPrivateFields.remove(Field);
7852 }
7853 }
7854 }
7855
7856 if (DefKind.isSpecialMember()
7858 DefKind.asSpecialMember(),
7859 FD->getDefaultLoc())
7861 FD->setInvalidDecl();
7862}
7863
7866 SourceLocation DefaultLoc) {
7867 CXXRecordDecl *RD = MD->getParent();
7868
7870 "not an explicitly-defaulted special member");
7871
7872 // Defer all checking for special members of a dependent type.
7873 if (RD->isDependentType())
7874 return false;
7875
7876 // Whether this was the first-declared instance of the constructor.
7877 // This affects whether we implicitly add an exception spec and constexpr.
7878 bool First = MD == MD->getCanonicalDecl();
7879
7880 bool HadError = false;
7881
7882 // C++11 [dcl.fct.def.default]p1:
7883 // A function that is explicitly defaulted shall
7884 // -- be a special member function [...] (checked elsewhere),
7885 // -- have the same type (except for ref-qualifiers, and except that a
7886 // copy operation can take a non-const reference) as an implicit
7887 // declaration, and
7888 // -- not have default arguments.
7889 // C++2a changes the second bullet to instead delete the function if it's
7890 // defaulted on its first declaration, unless it's "an assignment operator,
7891 // and its return type differs or its parameter type is not a reference".
7892 bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First;
7893 bool ShouldDeleteForTypeMismatch = false;
7894 unsigned ExpectedParams = 1;
7897 ExpectedParams = 0;
7898 if (MD->getNumExplicitParams() != ExpectedParams) {
7899 // This checks for default arguments: a copy or move constructor with a
7900 // default argument is classified as a default constructor, and assignment
7901 // operations and destructors can't have default arguments.
7902 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
7903 << CSM << MD->getSourceRange();
7904 HadError = true;
7905 } else if (MD->isVariadic()) {
7906 if (DeleteOnTypeMismatch)
7907 ShouldDeleteForTypeMismatch = true;
7908 else {
7909 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
7910 << CSM << MD->getSourceRange();
7911 HadError = true;
7912 }
7913 }
7914
7916
7917 bool CanHaveConstParam = false;
7919 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
7921 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
7922
7923 QualType ReturnType = Context.VoidTy;
7926 // Check for return type matching.
7927 ReturnType = Type->getReturnType();
7929
7930 QualType DeclType =
7932 /*Qualifier=*/std::nullopt, RD, /*OwnsTag=*/false);
7933 DeclType = Context.getAddrSpaceQualType(
7934 DeclType, ThisType.getQualifiers().getAddressSpace());
7935 QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
7936
7937 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
7938 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
7940 << ExpectedReturnType;
7941 HadError = true;
7942 }
7943
7944 // A defaulted special member cannot have cv-qualifiers.
7945 if (ThisType.isConstQualified() || ThisType.isVolatileQualified()) {
7946 if (DeleteOnTypeMismatch)
7947 ShouldDeleteForTypeMismatch = true;
7948 else {
7949 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
7951 << getLangOpts().CPlusPlus14;
7952 HadError = true;
7953 }
7954 }
7955 // [C++23][dcl.fct.def.default]/p2.2
7956 // if F2 has an implicit object parameter of type “reference to C”,
7957 // F1 may be an explicit object member function whose explicit object
7958 // parameter is of (possibly different) type “reference to C”,
7959 // in which case the type of F1 would differ from the type of F2
7960 // in that the type of F1 has an additional parameter;
7961 QualType ExplicitObjectParameter = MD->isExplicitObjectMemberFunction()
7962 ? MD->getParamDecl(0)->getType()
7963 : QualType();
7964 if (!ExplicitObjectParameter.isNull() &&
7965 (!ExplicitObjectParameter->isReferenceType() ||
7966 !Context.hasSameType(ExplicitObjectParameter.getNonReferenceType(),
7967 Context.getCanonicalTagType(RD)))) {
7968 if (DeleteOnTypeMismatch)
7969 ShouldDeleteForTypeMismatch = true;
7970 else {
7971 Diag(MD->getLocation(),
7972 diag::err_defaulted_special_member_explicit_object_mismatch)
7973 << (CSM == CXXSpecialMemberKind::MoveAssignment) << RD
7974 << MD->getSourceRange();
7975 HadError = true;
7976 }
7977 }
7978 }
7979
7980 // Check for parameter type matching.
7982 ExpectedParams
7983 ? Type->getParamType(MD->isExplicitObjectMemberFunction() ? 1 : 0)
7984 : QualType();
7985 bool HasConstParam = false;
7986 if (ExpectedParams && ArgType->isReferenceType()) {
7987 // Argument must be reference to possibly-const T.
7988 QualType ReferentType = ArgType->getPointeeType();
7989 HasConstParam = ReferentType.isConstQualified();
7990
7991 if (ReferentType.isVolatileQualified()) {
7992 if (DeleteOnTypeMismatch)
7993 ShouldDeleteForTypeMismatch = true;
7994 else {
7995 Diag(MD->getLocation(),
7996 diag::err_defaulted_special_member_volatile_param)
7997 << CSM;
7998 HadError = true;
7999 }
8000 }
8001
8002 if (HasConstParam && !CanHaveConstParam) {
8003 if (DeleteOnTypeMismatch)
8004 ShouldDeleteForTypeMismatch = true;
8005 else if (CSM == CXXSpecialMemberKind::CopyConstructor ||
8007 Diag(MD->getLocation(),
8008 diag::err_defaulted_special_member_copy_const_param)
8010 // FIXME: Explain why this special member can't be const.
8011 HadError = true;
8012 } else {
8013 Diag(MD->getLocation(),
8014 diag::err_defaulted_special_member_move_const_param)
8016 HadError = true;
8017 }
8018 }
8019 } else if (ExpectedParams) {
8020 // A copy assignment operator can take its argument by value, but a
8021 // defaulted one cannot.
8023 "unexpected non-ref argument");
8024 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
8025 HadError = true;
8026 }
8027
8028 // C++11 [dcl.fct.def.default]p2:
8029 // An explicitly-defaulted function may be declared constexpr only if it
8030 // would have been implicitly declared as constexpr,
8031 // Do not apply this rule to members of class templates, since core issue 1358
8032 // makes such functions always instantiate to constexpr functions. For
8033 // functions which cannot be constexpr (for non-constructors in C++11 and for
8034 // destructors in C++14 and C++17), this is checked elsewhere.
8035 //
8036 // FIXME: This should not apply if the member is deleted.
8037 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
8038 HasConstParam);
8039
8040 // C++14 [dcl.constexpr]p6 (CWG DR647/CWG DR1358):
8041 // If the instantiated template specialization of a constexpr function
8042 // template or member function of a class template would fail to satisfy
8043 // the requirements for a constexpr function or constexpr constructor, that
8044 // specialization is still a constexpr function or constexpr constructor,
8045 // even though a call to such a function cannot appear in a constant
8046 // expression.
8047 if (MD->isTemplateInstantiation() && MD->isConstexpr())
8048 Constexpr = true;
8049
8050 if ((getLangOpts().CPlusPlus20 ||
8052 : isa<CXXConstructorDecl>(MD))) &&
8053 MD->isConstexpr() && !Constexpr &&
8055 if (!MD->isConsteval() && RD->getNumVBases()) {
8056 Diag(MD->getBeginLoc(),
8057 diag::err_incorrect_defaulted_constexpr_with_vb)
8058 << CSM;
8059 for (const auto &I : RD->vbases())
8060 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here);
8061 } else {
8062 Diag(MD->getBeginLoc(), diag::err_incorrect_defaulted_constexpr)
8063 << CSM << MD->isConsteval();
8064 }
8065 HadError = true;
8066 // FIXME: Explain why the special member can't be constexpr.
8067 }
8068 if (First) {
8069 // C++2a [dcl.fct.def.default]p3:
8070 // If a function is explicitly defaulted on its first declaration, it is
8071 // implicitly considered to be constexpr if the implicit declaration
8072 // would be.
8077
8078 if (!Type->hasExceptionSpec()) {
8079 // C++2a [except.spec]p3:
8080 // If a declaration of a function does not have a noexcept-specifier
8081 // [and] is defaulted on its first declaration, [...] the exception
8082 // specification is as specified below
8083 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
8085 EPI.ExceptionSpec.SourceDecl = MD;
8086 MD->setType(
8087 Context.getFunctionType(ReturnType, Type->getParamTypes(), EPI));
8088 }
8089 }
8090
8091 if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
8092 if (First) {
8093 SetDeclDeleted(MD, MD->getLocation());
8094 if (!inTemplateInstantiation() && !HadError) {
8095 Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
8096 if (ShouldDeleteForTypeMismatch) {
8097 Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
8098 } else if (ShouldDeleteSpecialMember(MD, CSM, nullptr,
8099 /*Diagnose*/ true) &&
8100 DefaultLoc.isValid()) {
8101 Diag(DefaultLoc, diag::note_replace_equals_default_to_delete)
8102 << FixItHint::CreateReplacement(DefaultLoc, "delete");
8103 }
8104 }
8105 if (ShouldDeleteForTypeMismatch && !HadError) {
8106 Diag(MD->getLocation(),
8107 diag::warn_cxx17_compat_defaulted_method_type_mismatch)
8108 << CSM;
8109 }
8110 } else {
8111 // C++11 [dcl.fct.def.default]p4:
8112 // [For a] user-provided explicitly-defaulted function [...] if such a
8113 // function is implicitly defined as deleted, the program is ill-formed.
8114 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
8115 assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
8116 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
8117 HadError = true;
8118 }
8119 }
8120
8121 return HadError;
8122}
8123
8124namespace {
8125/// Helper class for building and checking a defaulted comparison.
8126///
8127/// Defaulted functions are built in two phases:
8128///
8129/// * First, the set of operations that the function will perform are
8130/// identified, and some of them are checked. If any of the checked
8131/// operations is invalid in certain ways, the comparison function is
8132/// defined as deleted and no body is built.
8133/// * Then, if the function is not defined as deleted, the body is built.
8134///
8135/// This is accomplished by performing two visitation steps over the eventual
8136/// body of the function.
8137template<typename Derived, typename ResultList, typename Result,
8138 typename Subobject>
8139class DefaultedComparisonVisitor {
8140public:
8141 DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8143 : S(S), RD(RD), FD(FD), DCK(DCK) {
8144 if (auto *Info = FD->getDefaultedOrDeletedInfo()) {
8145 // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an
8146 // UnresolvedSet to avoid this copy.
8147 Fns.assign(Info->getUnqualifiedLookups().begin(),
8148 Info->getUnqualifiedLookups().end());
8149 }
8150 }
8151
8152 ResultList visit() {
8153 // The type of an lvalue naming a parameter of this function.
8154 QualType ParamLvalType =
8156
8157 ResultList Results;
8158
8159 switch (DCK) {
8161 llvm_unreachable("not a defaulted comparison");
8162
8165 getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers());
8166 return Results;
8167
8170 Results.add(getDerived().visitExpandedSubobject(
8171 ParamLvalType, getDerived().getCompleteObject()));
8172 return Results;
8173 }
8174 llvm_unreachable("");
8175 }
8176
8177protected:
8178 Derived &getDerived() { return static_cast<Derived&>(*this); }
8179
8180 /// Visit the expanded list of subobjects of the given type, as specified in
8181 /// C++2a [class.compare.default].
8182 ///
8183 /// \return \c true if the ResultList object said we're done, \c false if not.
8184 bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record,
8185 Qualifiers Quals) {
8186 // C++2a [class.compare.default]p4:
8187 // The direct base class subobjects of C
8188 for (CXXBaseSpecifier &Base : Record->bases())
8189 if (Results.add(getDerived().visitSubobject(
8190 S.Context.getQualifiedType(Base.getType(), Quals),
8191 getDerived().getBase(&Base))))
8192 return true;
8193
8194 // followed by the non-static data members of C
8195 for (FieldDecl *Field : Record->fields()) {
8196 // C++23 [class.bit]p2:
8197 // Unnamed bit-fields are not members ...
8198 if (Field->isUnnamedBitField())
8199 continue;
8200 // Recursively expand anonymous structs.
8201 if (Field->isAnonymousStructOrUnion()) {
8202 if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(),
8203 Quals))
8204 return true;
8205 continue;
8206 }
8207
8208 // Figure out the type of an lvalue denoting this field.
8209 Qualifiers FieldQuals = Quals;
8210 if (Field->isMutable())
8211 FieldQuals.removeConst();
8212 QualType FieldType =
8213 S.Context.getQualifiedType(Field->getType(), FieldQuals);
8214
8215 if (Results.add(getDerived().visitSubobject(
8216 FieldType, getDerived().getField(Field))))
8217 return true;
8218 }
8219
8220 // form a list of subobjects.
8221 return false;
8222 }
8223
8224 Result visitSubobject(QualType Type, Subobject Subobj) {
8225 // In that list, any subobject of array type is recursively expanded
8226 const ArrayType *AT = S.Context.getAsArrayType(Type);
8227 if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT))
8228 return getDerived().visitSubobjectArray(CAT->getElementType(),
8229 CAT->getSize(), Subobj);
8230 return getDerived().visitExpandedSubobject(Type, Subobj);
8231 }
8232
8233 Result visitSubobjectArray(QualType Type, const llvm::APInt &Size,
8234 Subobject Subobj) {
8235 return getDerived().visitSubobject(Type, Subobj);
8236 }
8237
8238protected:
8239 Sema &S;
8240 CXXRecordDecl *RD;
8241 FunctionDecl *FD;
8243 UnresolvedSet<16> Fns;
8244};
8245
8246/// Information about a defaulted comparison, as determined by
8247/// DefaultedComparisonAnalyzer.
8248struct DefaultedComparisonInfo {
8249 bool Deleted = false;
8250 bool Constexpr = true;
8251 ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering;
8252
8253 static DefaultedComparisonInfo deleted() {
8254 DefaultedComparisonInfo Deleted;
8255 Deleted.Deleted = true;
8256 return Deleted;
8257 }
8258
8259 bool add(const DefaultedComparisonInfo &R) {
8260 Deleted |= R.Deleted;
8261 Constexpr &= R.Constexpr;
8262 Category = commonComparisonType(Category, R.Category);
8263 return Deleted;
8264 }
8265};
8266
8267/// An element in the expanded list of subobjects of a defaulted comparison, as
8268/// specified in C++2a [class.compare.default]p4.
8269struct DefaultedComparisonSubobject {
8270 enum { CompleteObject, Member, Base } Kind;
8271 NamedDecl *Decl;
8272 SourceLocation Loc;
8273};
8274
8275/// A visitor over the notional body of a defaulted comparison that determines
8276/// whether that body would be deleted or constexpr.
8277class DefaultedComparisonAnalyzer
8278 : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer,
8279 DefaultedComparisonInfo,
8280 DefaultedComparisonInfo,
8281 DefaultedComparisonSubobject> {
8282public:
8283 enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr };
8284
8285private:
8286 DiagnosticKind Diagnose;
8287
8288public:
8289 using Base = DefaultedComparisonVisitor;
8290 using Result = DefaultedComparisonInfo;
8291 using Subobject = DefaultedComparisonSubobject;
8292
8293 friend Base;
8294
8295 DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8297 DiagnosticKind Diagnose = NoDiagnostics)
8298 : Base(S, RD, FD, DCK), Diagnose(Diagnose) {}
8299
8300 Result visit() {
8301 if ((DCK == DefaultedComparisonKind::Equal ||
8302 DCK == DefaultedComparisonKind::ThreeWay) &&
8303 RD->hasVariantMembers()) {
8304 // C++2a [class.compare.default]p2 [P2002R0]:
8305 // A defaulted comparison operator function for class C is defined as
8306 // deleted if [...] C has variant members.
8307 if (Diagnose == ExplainDeleted) {
8308 S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union)
8309 << FD << RD->isUnion() << RD;
8310 }
8311 return Result::deleted();
8312 }
8313
8314 return Base::visit();
8315 }
8316
8317private:
8318 Subobject getCompleteObject() {
8319 return Subobject{Subobject::CompleteObject, RD, FD->getLocation()};
8320 }
8321
8322 Subobject getBase(CXXBaseSpecifier *Base) {
8323 return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(),
8324 Base->getBaseTypeLoc()};
8325 }
8326
8327 Subobject getField(FieldDecl *Field) {
8328 return Subobject{Subobject::Member, Field, Field->getLocation()};
8329 }
8330
8331 Result visitExpandedSubobject(QualType Type, Subobject Subobj) {
8332 // C++2a [class.compare.default]p2 [P2002R0]:
8333 // A defaulted <=> or == operator function for class C is defined as
8334 // deleted if any non-static data member of C is of reference type
8335 if (Type->isReferenceType()) {
8336 if (Diagnose == ExplainDeleted) {
8337 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member)
8338 << FD << RD;
8339 }
8340 return Result::deleted();
8341 }
8342
8343 // [...] Let xi be an lvalue denoting the ith element [...]
8344 OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue);
8345 Expr *Args[] = {&Xi, &Xi};
8346
8347 // All operators start by trying to apply that same operator recursively.
8349 assert(OO != OO_None && "not an overloaded operator!");
8350 return visitBinaryOperator(OO, Args, Subobj);
8351 }
8352
8353 Result
8354 visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args,
8355 Subobject Subobj,
8356 OverloadCandidateSet *SpaceshipCandidates = nullptr) {
8357 // Note that there is no need to consider rewritten candidates here if
8358 // we've already found there is no viable 'operator<=>' candidate (and are
8359 // considering synthesizing a '<=>' from '==' and '<').
8360 OverloadCandidateSet CandidateSet(
8362 OverloadCandidateSet::OperatorRewriteInfo(
8363 OO, FD->getLocation(),
8364 /*AllowRewrittenCandidates=*/!SpaceshipCandidates));
8365
8366 /// C++2a [class.compare.default]p1 [P2002R0]:
8367 /// [...] the defaulted function itself is never a candidate for overload
8368 /// resolution [...]
8369 CandidateSet.exclude(FD);
8370
8371 if (Args[0]->getType()->isOverloadableType())
8372 S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args);
8373 else
8374 // FIXME: We determine whether this is a valid expression by checking to
8375 // see if there's a viable builtin operator candidate for it. That isn't
8376 // really what the rules ask us to do, but should give the right results.
8377 S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet);
8378
8379 Result R;
8380
8382 switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) {
8383 case OR_Success: {
8384 // C++2a [class.compare.secondary]p2 [P2002R0]:
8385 // The operator function [...] is defined as deleted if [...] the
8386 // candidate selected by overload resolution is not a rewritten
8387 // candidate.
8388 if ((DCK == DefaultedComparisonKind::NotEqual ||
8389 DCK == DefaultedComparisonKind::Relational) &&
8390 !Best->RewriteKind) {
8391 if (Diagnose == ExplainDeleted) {
8392 if (Best->Function) {
8393 S.Diag(Best->Function->getLocation(),
8394 diag::note_defaulted_comparison_not_rewritten_callee)
8395 << FD;
8396 } else {
8397 assert(Best->Conversions.size() == 2 &&
8398 Best->Conversions[0].isUserDefined() &&
8399 "non-user-defined conversion from class to built-in "
8400 "comparison");
8401 S.Diag(Best->Conversions[0]
8402 .UserDefined.FoundConversionFunction.getDecl()
8403 ->getLocation(),
8404 diag::note_defaulted_comparison_not_rewritten_conversion)
8405 << FD;
8406 }
8407 }
8408 return Result::deleted();
8409 }
8410
8411 // Throughout C++2a [class.compare]: if overload resolution does not
8412 // result in a usable function, the candidate function is defined as
8413 // deleted. This requires that we selected an accessible function.
8414 //
8415 // Note that this only considers the access of the function when named
8416 // within the type of the subobject, and not the access path for any
8417 // derived-to-base conversion.
8418 CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl();
8419 if (ArgClass && Best->FoundDecl.getDecl() &&
8420 Best->FoundDecl.getDecl()->isCXXClassMember()) {
8421 QualType ObjectType = Subobj.Kind == Subobject::Member
8422 ? Args[0]->getType()
8425 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc,
8426 Diagnose == ExplainDeleted
8427 ? S.PDiag(diag::note_defaulted_comparison_inaccessible)
8428 << FD << Subobj.Kind << Subobj.Decl
8429 : S.PDiag()))
8430 return Result::deleted();
8431 }
8432
8433 bool NeedsDeducing =
8434 OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType();
8435
8436 if (FunctionDecl *BestFD = Best->Function) {
8437 // C++2a [class.compare.default]p3 [P2002R0]:
8438 // A defaulted comparison function is constexpr-compatible if
8439 // [...] no overlod resolution performed [...] results in a
8440 // non-constexpr function.
8441 assert(!BestFD->isDeleted() && "wrong overload resolution result");
8442 // If it's not constexpr, explain why not.
8443 if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) {
8444 if (Subobj.Kind != Subobject::CompleteObject)
8445 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr)
8446 << Subobj.Kind << Subobj.Decl;
8447 S.Diag(BestFD->getLocation(),
8448 diag::note_defaulted_comparison_not_constexpr_here);
8449 // Bail out after explaining; we don't want any more notes.
8450 return Result::deleted();
8451 }
8452 R.Constexpr &= BestFD->isConstexpr();
8453
8454 if (NeedsDeducing) {
8455 // If any callee has an undeduced return type, deduce it now.
8456 // FIXME: It's not clear how a failure here should be handled. For
8457 // now, we produce an eager diagnostic, because that is forward
8458 // compatible with most (all?) other reasonable options.
8459 if (BestFD->getReturnType()->isUndeducedType() &&
8460 S.DeduceReturnType(BestFD, FD->getLocation(),
8461 /*Diagnose=*/false)) {
8462 // Don't produce a duplicate error when asked to explain why the
8463 // comparison is deleted: we diagnosed that when initially checking
8464 // the defaulted operator.
8465 if (Diagnose == NoDiagnostics) {
8466 S.Diag(
8467 FD->getLocation(),
8468 diag::err_defaulted_comparison_cannot_deduce_undeduced_auto)
8469 << Subobj.Kind << Subobj.Decl;
8470 S.Diag(
8471 Subobj.Loc,
8472 diag::note_defaulted_comparison_cannot_deduce_undeduced_auto)
8473 << Subobj.Kind << Subobj.Decl;
8474 S.Diag(BestFD->getLocation(),
8475 diag::note_defaulted_comparison_cannot_deduce_callee)
8476 << Subobj.Kind << Subobj.Decl;
8477 }
8478 return Result::deleted();
8479 }
8481 BestFD->getCallResultType());
8482 if (!Info) {
8483 if (Diagnose == ExplainDeleted) {
8484 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce)
8485 << Subobj.Kind << Subobj.Decl
8486 << BestFD->getCallResultType().withoutLocalFastQualifiers();
8487 S.Diag(BestFD->getLocation(),
8488 diag::note_defaulted_comparison_cannot_deduce_callee)
8489 << Subobj.Kind << Subobj.Decl;
8490 }
8491 return Result::deleted();
8492 }
8493 R.Category = Info->Kind;
8494 }
8495 } else {
8496 QualType T = Best->BuiltinParamTypes[0];
8497 assert(T == Best->BuiltinParamTypes[1] &&
8498 "builtin comparison for different types?");
8499 assert(Best->BuiltinParamTypes[2].isNull() &&
8500 "invalid builtin comparison");
8501
8502 // FIXME: If the type we deduced is a vector type, we mark the
8503 // comparison as deleted because we don't yet support this.
8504 if (isa<VectorType>(T)) {
8505 if (Diagnose == ExplainDeleted) {
8506 S.Diag(FD->getLocation(),
8507 diag::note_defaulted_comparison_vector_types)
8508 << FD;
8509 S.Diag(Subobj.Decl->getLocation(), diag::note_declared_at);
8510 }
8511 return Result::deleted();
8512 }
8513
8514 if (NeedsDeducing) {
8515 std::optional<ComparisonCategoryType> Cat =
8517 assert(Cat && "no category for builtin comparison?");
8518 R.Category = *Cat;
8519 }
8520 }
8521
8522 // Note that we might be rewriting to a different operator. That call is
8523 // not considered until we come to actually build the comparison function.
8524 break;
8525 }
8526
8527 case OR_Ambiguous:
8528 if (Diagnose == ExplainDeleted) {
8529 unsigned Kind = 0;
8530 if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship)
8531 Kind = OO == OO_EqualEqual ? 1 : 2;
8532 CandidateSet.NoteCandidates(
8534 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous)
8535 << FD << Kind << Subobj.Kind << Subobj.Decl),
8536 S, OCD_AmbiguousCandidates, Args);
8537 }
8538 R = Result::deleted();
8539 break;
8540
8541 case OR_Deleted:
8542 if (Diagnose == ExplainDeleted) {
8543 if ((DCK == DefaultedComparisonKind::NotEqual ||
8544 DCK == DefaultedComparisonKind::Relational) &&
8545 !Best->RewriteKind) {
8546 S.Diag(Best->Function->getLocation(),
8547 diag::note_defaulted_comparison_not_rewritten_callee)
8548 << FD;
8549 } else {
8550 S.Diag(Subobj.Loc,
8551 diag::note_defaulted_comparison_calls_deleted)
8552 << FD << Subobj.Kind << Subobj.Decl;
8553 S.NoteDeletedFunction(Best->Function);
8554 }
8555 }
8556 R = Result::deleted();
8557 break;
8558
8560 // If there's no usable candidate, we're done unless we can rewrite a
8561 // '<=>' in terms of '==' and '<'.
8562 if (OO == OO_Spaceship &&
8564 // For any kind of comparison category return type, we need a usable
8565 // '==' and a usable '<'.
8566 if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj,
8567 &CandidateSet)))
8568 R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet));
8569 break;
8570 }
8571
8572 if (Diagnose == ExplainDeleted) {
8573 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function)
8574 << FD << (OO == OO_EqualEqual || OO == OO_ExclaimEqual)
8575 << Subobj.Kind << Subobj.Decl;
8576
8577 // For a three-way comparison, list both the candidates for the
8578 // original operator and the candidates for the synthesized operator.
8579 if (SpaceshipCandidates) {
8580 SpaceshipCandidates->NoteCandidates(
8581 S, Args,
8582 SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates,
8583 Args, FD->getLocation()));
8584 S.Diag(Subobj.Loc,
8585 diag::note_defaulted_comparison_no_viable_function_synthesized)
8586 << (OO == OO_EqualEqual ? 0 : 1);
8587 }
8588
8589 CandidateSet.NoteCandidates(
8590 S, Args,
8591 CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args,
8592 FD->getLocation()));
8593 }
8594 R = Result::deleted();
8595 break;
8596 }
8597
8598 return R;
8599 }
8600};
8601
8602/// A list of statements.
8603struct StmtListResult {
8604 bool IsInvalid = false;
8605 llvm::SmallVector<Stmt*, 16> Stmts;
8606
8607 bool add(const StmtResult &S) {
8608 IsInvalid |= S.isInvalid();
8609 if (IsInvalid)
8610 return true;
8611 Stmts.push_back(S.get());
8612 return false;
8613 }
8614};
8615
8616/// A visitor over the notional body of a defaulted comparison that synthesizes
8617/// the actual body.
8618class DefaultedComparisonSynthesizer
8619 : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer,
8620 StmtListResult, StmtResult,
8621 std::pair<ExprResult, ExprResult>> {
8622 SourceLocation Loc;
8623 unsigned ArrayDepth = 0;
8624
8625public:
8626 using Base = DefaultedComparisonVisitor;
8627 using ExprPair = std::pair<ExprResult, ExprResult>;
8628
8629 friend Base;
8630
8631 DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8633 SourceLocation BodyLoc)
8634 : Base(S, RD, FD, DCK), Loc(BodyLoc) {}
8635
8636 /// Build a suitable function body for this defaulted comparison operator.
8637 StmtResult build() {
8638 Sema::CompoundScopeRAII CompoundScope(S);
8639
8640 StmtListResult Stmts = visit();
8641 if (Stmts.IsInvalid)
8642 return StmtError();
8643
8644 ExprResult RetVal;
8645 switch (DCK) {
8646 case DefaultedComparisonKind::None:
8647 llvm_unreachable("not a defaulted comparison");
8648
8649 case DefaultedComparisonKind::Equal: {
8650 // C++2a [class.eq]p3:
8651 // [...] compar[e] the corresponding elements [...] until the first
8652 // index i where xi == yi yields [...] false. If no such index exists,
8653 // V is true. Otherwise, V is false.
8654 //
8655 // Join the comparisons with '&&'s and return the result. Use a right
8656 // fold (traversing the conditions right-to-left), because that
8657 // short-circuits more naturally.
8658 auto OldStmts = std::move(Stmts.Stmts);
8659 Stmts.Stmts.clear();
8660 ExprResult CmpSoFar;
8661 // Finish a particular comparison chain.
8662 auto FinishCmp = [&] {
8663 if (Expr *Prior = CmpSoFar.get()) {
8664 // Convert the last expression to 'return ...;'
8665 if (RetVal.isUnset() && Stmts.Stmts.empty())
8666 RetVal = CmpSoFar;
8667 // Convert any prior comparison to 'if (!(...)) return false;'
8668 else if (Stmts.add(buildIfNotCondReturnFalse(Prior)))
8669 return true;
8670 CmpSoFar = ExprResult();
8671 }
8672 return false;
8673 };
8674 for (Stmt *EAsStmt : llvm::reverse(OldStmts)) {
8675 Expr *E = dyn_cast<Expr>(EAsStmt);
8676 if (!E) {
8677 // Found an array comparison.
8678 if (FinishCmp() || Stmts.add(EAsStmt))
8679 return StmtError();
8680 continue;
8681 }
8682
8683 if (CmpSoFar.isUnset()) {
8684 CmpSoFar = E;
8685 continue;
8686 }
8687 CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get());
8688 if (CmpSoFar.isInvalid())
8689 return StmtError();
8690 }
8691 if (FinishCmp())
8692 return StmtError();
8693 std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end());
8694 // If no such index exists, V is true.
8695 if (RetVal.isUnset())
8696 RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true);
8697 break;
8698 }
8699
8700 case DefaultedComparisonKind::ThreeWay: {
8701 // Per C++2a [class.spaceship]p3, as a fallback add:
8702 // return static_cast<R>(std::strong_ordering::equal);
8703 QualType StrongOrdering = S.CheckComparisonCategoryType(
8704 ComparisonCategoryType::StrongOrdering, Loc,
8705 Sema::ComparisonCategoryUsage::DefaultedOperator);
8706 if (StrongOrdering.isNull())
8707 return StmtError();
8708 VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(StrongOrdering)
8709 .getValueInfo(ComparisonCategoryResult::Equal)
8710 ->VD;
8711 RetVal = getDecl(EqualVD);
8712 if (RetVal.isInvalid())
8713 return StmtError();
8714 RetVal = buildStaticCastToR(RetVal.get());
8715 break;
8716 }
8717
8718 case DefaultedComparisonKind::NotEqual:
8719 case DefaultedComparisonKind::Relational:
8720 RetVal = cast<Expr>(Stmts.Stmts.pop_back_val());
8721 break;
8722 }
8723
8724 // Build the final return statement.
8725 if (RetVal.isInvalid())
8726 return StmtError();
8727 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get());
8728 if (ReturnStmt.isInvalid())
8729 return StmtError();
8730 Stmts.Stmts.push_back(ReturnStmt.get());
8731
8732 return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false);
8733 }
8734
8735private:
8736 ExprResult getDecl(ValueDecl *VD) {
8737 return S.BuildDeclarationNameExpr(
8738 CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD);
8739 }
8740
8741 ExprResult getParam(unsigned I) {
8742 ParmVarDecl *PD = FD->getParamDecl(I);
8743 return getDecl(PD);
8744 }
8745
8746 ExprPair getCompleteObject() {
8747 unsigned Param = 0;
8748 ExprResult LHS;
8749 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD);
8750 MD && MD->isImplicitObjectMemberFunction()) {
8751 // LHS is '*this'.
8752 LHS = S.ActOnCXXThis(Loc);
8753 if (!LHS.isInvalid())
8754 LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get());
8755 } else {
8756 LHS = getParam(Param++);
8757 }
8758 ExprResult RHS = getParam(Param++);
8759 assert(Param == FD->getNumParams());
8760 return {LHS, RHS};
8761 }
8762
8763 ExprPair getBase(CXXBaseSpecifier *Base) {
8764 ExprPair Obj = getCompleteObject();
8765 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8766 return {ExprError(), ExprError()};
8767 CXXCastPath Path = {Base};
8768 const auto CastToBase = [&](Expr *E) {
8769 QualType ToType = S.Context.getQualifiedType(
8770 Base->getType(), E->getType().getQualifiers());
8771 return S.ImpCastExprToType(E, ToType, CK_DerivedToBase, VK_LValue, &Path);
8772 };
8773 return {CastToBase(Obj.first.get()), CastToBase(Obj.second.get())};
8774 }
8775
8776 ExprPair getField(FieldDecl *Field) {
8777 ExprPair Obj = getCompleteObject();
8778 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8779 return {ExprError(), ExprError()};
8780
8781 DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess());
8782 DeclarationNameInfo NameInfo(Field->getDeclName(), Loc);
8783 return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc,
8784 CXXScopeSpec(), Field, Found, NameInfo),
8785 S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc,
8786 CXXScopeSpec(), Field, Found, NameInfo)};
8787 }
8788
8789 // FIXME: When expanding a subobject, register a note in the code synthesis
8790 // stack to say which subobject we're comparing.
8791
8792 StmtResult buildIfNotCondReturnFalse(ExprResult Cond) {
8793 if (Cond.isInvalid())
8794 return StmtError();
8795
8796 ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get());
8797 if (NotCond.isInvalid())
8798 return StmtError();
8799
8800 ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false);
8801 assert(!False.isInvalid() && "should never fail");
8802 StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get());
8803 if (ReturnFalse.isInvalid())
8804 return StmtError();
8805
8806 return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, nullptr,
8807 S.ActOnCondition(nullptr, Loc, NotCond.get(),
8808 Sema::ConditionKind::Boolean),
8809 Loc, ReturnFalse.get(), SourceLocation(), nullptr);
8810 }
8811
8812 StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size,
8813 ExprPair Subobj) {
8814 QualType SizeType = S.Context.getSizeType();
8815 Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType));
8816
8817 // Build 'size_t i$n = 0'.
8818 IdentifierInfo *IterationVarName = nullptr;
8819 {
8820 SmallString<8> Str;
8821 llvm::raw_svector_ostream OS(Str);
8822 OS << "i" << ArrayDepth;
8823 IterationVarName = &S.Context.Idents.get(OS.str());
8824 }
8825 VarDecl *IterationVar = VarDecl::Create(
8826 S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType,
8827 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None);
8828 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
8829 IterationVar->setInit(
8830 IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
8831 Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc);
8832
8833 auto IterRef = [&] {
8834 ExprResult Ref = S.BuildDeclarationNameExpr(
8835 CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc),
8836 IterationVar);
8837 assert(!Ref.isInvalid() && "can't reference our own variable?");
8838 return Ref.get();
8839 };
8840
8841 // Build 'i$n != Size'.
8842 ExprResult Cond = S.CreateBuiltinBinOp(
8843 Loc, BO_NE, IterRef(),
8844 IntegerLiteral::Create(S.Context, Size, SizeType, Loc));
8845 assert(!Cond.isInvalid() && "should never fail");
8846
8847 // Build '++i$n'.
8848 ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef());
8849 assert(!Inc.isInvalid() && "should never fail");
8850
8851 // Build 'a[i$n]' and 'b[i$n]'.
8852 auto Index = [&](ExprResult E) {
8853 if (E.isInvalid())
8854 return ExprError();
8855 return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc);
8856 };
8857 Subobj.first = Index(Subobj.first);
8858 Subobj.second = Index(Subobj.second);
8859
8860 // Compare the array elements.
8861 ++ArrayDepth;
8862 StmtResult Substmt = visitSubobject(Type, Subobj);
8863 --ArrayDepth;
8864
8865 if (Substmt.isInvalid())
8866 return StmtError();
8867
8868 // For the inner level of an 'operator==', build 'if (!cmp) return false;'.
8869 // For outer levels or for an 'operator<=>' we already have a suitable
8870 // statement that returns as necessary.
8871 if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) {
8872 assert(DCK == DefaultedComparisonKind::Equal &&
8873 "should have non-expression statement");
8874 Substmt = buildIfNotCondReturnFalse(ElemCmp);
8875 if (Substmt.isInvalid())
8876 return StmtError();
8877 }
8878
8879 // Build 'for (...) ...'
8880 return S.ActOnForStmt(Loc, Loc, Init,
8881 S.ActOnCondition(nullptr, Loc, Cond.get(),
8882 Sema::ConditionKind::Boolean),
8883 S.MakeFullDiscardedValueExpr(Inc.get()), Loc,
8884 Substmt.get());
8885 }
8886
8887 StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) {
8888 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8889 return StmtError();
8890
8893 ExprResult Op;
8894 if (Type->isOverloadableType())
8895 Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(),
8896 Obj.second.get(), /*PerformADL=*/true,
8897 /*AllowRewrittenCandidates=*/true, FD);
8898 else
8899 Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get());
8900 if (Op.isInvalid())
8901 return StmtError();
8902
8903 switch (DCK) {
8904 case DefaultedComparisonKind::None:
8905 llvm_unreachable("not a defaulted comparison");
8906
8907 case DefaultedComparisonKind::Equal:
8908 // Per C++2a [class.eq]p2, each comparison is individually contextually
8909 // converted to bool.
8910 Op = S.PerformContextuallyConvertToBool(Op.get());
8911 if (Op.isInvalid())
8912 return StmtError();
8913 return Op.get();
8914
8915 case DefaultedComparisonKind::ThreeWay: {
8916 // Per C++2a [class.spaceship]p3, form:
8917 // if (R cmp = static_cast<R>(op); cmp != 0)
8918 // return cmp;
8919 QualType R = FD->getReturnType();
8920 Op = buildStaticCastToR(Op.get());
8921 if (Op.isInvalid())
8922 return StmtError();
8923
8924 // R cmp = ...;
8925 IdentifierInfo *Name = &S.Context.Idents.get("cmp");
8926 VarDecl *VD =
8927 VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R,
8928 S.Context.getTrivialTypeSourceInfo(R, Loc), SC_None);
8929 S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false);
8930 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc);
8931
8932 // cmp != 0
8933 ExprResult VDRef = getDecl(VD);
8934 if (VDRef.isInvalid())
8935 return StmtError();
8936 llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0);
8937 Expr *Zero =
8938 IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc);
8940 if (VDRef.get()->getType()->isOverloadableType())
8941 Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true,
8942 true, FD);
8943 else
8944 Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero);
8945 if (Comp.isInvalid())
8946 return StmtError();
8947 Sema::ConditionResult Cond = S.ActOnCondition(
8948 nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean);
8949 if (Cond.isInvalid())
8950 return StmtError();
8951
8952 // return cmp;
8953 VDRef = getDecl(VD);
8954 if (VDRef.isInvalid())
8955 return StmtError();
8956 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get());
8957 if (ReturnStmt.isInvalid())
8958 return StmtError();
8959
8960 // if (...)
8961 return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, InitStmt, Cond,
8962 Loc, ReturnStmt.get(),
8963 /*ElseLoc=*/SourceLocation(), /*Else=*/nullptr);
8964 }
8965
8966 case DefaultedComparisonKind::NotEqual:
8967 case DefaultedComparisonKind::Relational:
8968 // C++2a [class.compare.secondary]p2:
8969 // Otherwise, the operator function yields x @ y.
8970 return Op.get();
8971 }
8972 llvm_unreachable("");
8973 }
8974
8975 /// Build "static_cast<R>(E)".
8976 ExprResult buildStaticCastToR(Expr *E) {
8977 QualType R = FD->getReturnType();
8978 assert(!R->isUndeducedType() && "type should have been deduced already");
8979
8980 // Don't bother forming a no-op cast in the common case.
8981 if (E->isPRValue() && S.Context.hasSameType(E->getType(), R))
8982 return E;
8983 return S.BuildCXXNamedCast(Loc, tok::kw_static_cast,
8984 S.Context.getTrivialTypeSourceInfo(R, Loc), E,
8985 SourceRange(Loc, Loc), SourceRange(Loc, Loc));
8986 }
8987};
8988}
8989
8990/// Perform the unqualified lookups that might be needed to form a defaulted
8991/// comparison function for the given operator.
8993 UnresolvedSetImpl &Operators,
8995 auto Lookup = [&](OverloadedOperatorKind OO) {
8996 Self.LookupOverloadedOperatorName(OO, S, Operators);
8997 };
8998
8999 // Every defaulted operator looks up itself.
9000 Lookup(Op);
9001 // ... and the rewritten form of itself, if any.
9003 Lookup(ExtraOp);
9004
9005 // For 'operator<=>', we also form a 'cmp != 0' expression, and might
9006 // synthesize a three-way comparison from '<' and '=='. In a dependent
9007 // context, we also need to look up '==' in case we implicitly declare a
9008 // defaulted 'operator=='.
9009 if (Op == OO_Spaceship) {
9010 Lookup(OO_ExclaimEqual);
9011 Lookup(OO_Less);
9012 Lookup(OO_EqualEqual);
9013 }
9014}
9015
9018 assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison");
9019
9020 // Perform any unqualified lookups we're going to need to default this
9021 // function.
9022 if (S) {
9023 UnresolvedSet<32> Operators;
9024 lookupOperatorsForDefaultedComparison(*this, S, Operators,
9025 FD->getOverloadedOperator());
9028 Context, Operators.pairs(), CurFPFeatureOverrides()));
9029 }
9030
9031 // C++2a [class.compare.default]p1:
9032 // A defaulted comparison operator function for some class C shall be a
9033 // non-template function declared in the member-specification of C that is
9034 // -- a non-static const non-volatile member of C having one parameter of
9035 // type const C& and either no ref-qualifier or the ref-qualifier &, or
9036 // -- a friend of C having two parameters of type const C& or two
9037 // parameters of type C.
9038
9039 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext());
9040 bool IsMethod = isa<CXXMethodDecl>(FD);
9041 if (IsMethod) {
9042 auto *MD = cast<CXXMethodDecl>(FD);
9043 assert(!MD->isStatic() && "comparison function cannot be a static member");
9044
9045 if (MD->getRefQualifier() == RQ_RValue) {
9046 Diag(MD->getLocation(), diag::err_ref_qualifier_comparison_operator);
9047
9048 // Remove the ref qualifier to recover.
9049 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
9050 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9051 EPI.RefQualifier = RQ_None;
9052 MD->setType(Context.getFunctionType(FPT->getReturnType(),
9053 FPT->getParamTypes(), EPI));
9054 }
9055
9056 // If we're out-of-class, this is the class we're comparing.
9057 if (!RD)
9058 RD = MD->getParent();
9059 QualType T = MD->getFunctionObjectParameterReferenceType();
9060 if (!T.getNonReferenceType().isConstQualified() &&
9061 (MD->isImplicitObjectMemberFunction() || T->isLValueReferenceType())) {
9062 SourceLocation Loc, InsertLoc;
9063 if (MD->isExplicitObjectMemberFunction()) {
9064 Loc = MD->getParamDecl(0)->getBeginLoc();
9065 InsertLoc = getLocForEndOfToken(
9066 MD->getParamDecl(0)->getExplicitObjectParamThisLoc());
9067 } else {
9068 Loc = MD->getLocation();
9069 if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc())
9070 InsertLoc = getLocForEndOfToken(Loc.getRParenLoc());
9071 }
9072 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
9073 // corresponding defaulted 'operator<=>' already.
9074 if (!MD->isImplicit()) {
9075 Diag(Loc, diag::err_defaulted_comparison_non_const)
9076 << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const");
9077 }
9078
9079 // Add the 'const' to the type to recover.
9080 if (MD->isExplicitObjectMemberFunction()) {
9081 assert(T->isLValueReferenceType());
9082 MD->getParamDecl(0)->setType(Context.getLValueReferenceType(
9083 T.getNonReferenceType().withConst()));
9084 } else {
9085 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
9086 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9087 EPI.TypeQuals.addConst();
9088 MD->setType(Context.getFunctionType(FPT->getReturnType(),
9089 FPT->getParamTypes(), EPI));
9090 }
9091 }
9092
9093 if (MD->isVolatile()) {
9094 Diag(MD->getLocation(), diag::err_volatile_comparison_operator);
9095
9096 // Remove the 'volatile' from the type to recover.
9097 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
9098 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9100 MD->setType(Context.getFunctionType(FPT->getReturnType(),
9101 FPT->getParamTypes(), EPI));
9102 }
9103 }
9104
9105 if ((FD->getNumParams() -
9106 (unsigned)FD->hasCXXExplicitFunctionObjectParameter()) !=
9107 (IsMethod ? 1 : 2)) {
9108 // Let's not worry about using a variadic template pack here -- who would do
9109 // such a thing?
9110 Diag(FD->getLocation(), diag::err_defaulted_comparison_num_args)
9111 << int(IsMethod) << int(DCK);
9112 return true;
9113 }
9114
9115 const ParmVarDecl *KnownParm = nullptr;
9116 for (const ParmVarDecl *Param : FD->parameters()) {
9117 QualType ParmTy = Param->getType();
9118 if (!KnownParm) {
9119 auto CTy = ParmTy;
9120 // Is it `T const &`?
9121 bool Ok = !IsMethod || FD->hasCXXExplicitFunctionObjectParameter();
9122 QualType ExpectedTy;
9123 if (RD)
9124 ExpectedTy = Context.getCanonicalTagType(RD);
9125 if (auto *Ref = CTy->getAs<LValueReferenceType>()) {
9126 CTy = Ref->getPointeeType();
9127 if (RD)
9128 ExpectedTy.addConst();
9129 Ok = true;
9130 }
9131
9132 // Is T a class?
9133 if (RD) {
9134 Ok &= RD->isDependentType() || Context.hasSameType(CTy, ExpectedTy);
9135 } else {
9136 RD = CTy->getAsCXXRecordDecl();
9137 Ok &= RD != nullptr;
9138 }
9139
9140 if (Ok) {
9141 KnownParm = Param;
9142 } else {
9143 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
9144 // corresponding defaulted 'operator<=>' already.
9145 if (!FD->isImplicit()) {
9146 if (RD) {
9147 CanQualType PlainTy = Context.getCanonicalTagType(RD);
9148 QualType RefTy =
9149 Context.getLValueReferenceType(PlainTy.withConst());
9150 Diag(FD->getLocation(), diag::err_defaulted_comparison_param)
9151 << int(DCK) << ParmTy << RefTy << int(!IsMethod) << PlainTy
9152 << Param->getSourceRange();
9153 } else {
9154 assert(!IsMethod && "should know expected type for method");
9155 Diag(FD->getLocation(),
9156 diag::err_defaulted_comparison_param_unknown)
9157 << int(DCK) << ParmTy << Param->getSourceRange();
9158 }
9159 }
9160 return true;
9161 }
9162 } else if (!Context.hasSameType(KnownParm->getType(), ParmTy)) {
9163 Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch)
9164 << int(DCK) << KnownParm->getType() << KnownParm->getSourceRange()
9165 << ParmTy << Param->getSourceRange();
9166 return true;
9167 }
9168 }
9169
9170 assert(RD && "must have determined class");
9171 if (IsMethod) {
9172 } else if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
9173 // In-class, must be a friend decl.
9174 assert(FD->getFriendObjectKind() && "expected a friend declaration");
9175 } else {
9176 // Out of class, require the defaulted comparison to be a friend (of a
9177 // complete type, per CWG2547).
9178 if (RequireCompleteType(FD->getLocation(), Context.getCanonicalTagType(RD),
9179 diag::err_defaulted_comparison_not_friend, int(DCK),
9180 int(1)))
9181 return true;
9182
9183 if (llvm::none_of(RD->friends(), [&](const FriendDecl *F) {
9184 return declaresSameEntity(F->getFriendDecl(), FD);
9185 })) {
9186 Diag(FD->getLocation(), diag::err_defaulted_comparison_not_friend)
9187 << int(DCK) << int(0) << RD;
9188 Diag(RD->getCanonicalDecl()->getLocation(), diag::note_declared_at);
9189 return true;
9190 }
9191 }
9192
9193 // C++2a [class.eq]p1, [class.rel]p1:
9194 // A [defaulted comparison other than <=>] shall have a declared return
9195 // type bool.
9198 !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) {
9199 Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool)
9200 << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy
9201 << FD->getReturnTypeSourceRange();
9202 return true;
9203 }
9204 // C++2a [class.spaceship]p2 [P2002R0]:
9205 // Let R be the declared return type [...]. If R is auto, [...]. Otherwise,
9206 // R shall not contain a placeholder type.
9207 if (QualType RT = FD->getDeclaredReturnType();
9209 RT->getContainedDeducedType() &&
9210 (!Context.hasSameType(RT, Context.getAutoDeductType()) ||
9211 RT->getContainedAutoType()->isConstrained())) {
9212 Diag(FD->getLocation(),
9213 diag::err_defaulted_comparison_deduced_return_type_not_auto)
9214 << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy
9215 << FD->getReturnTypeSourceRange();
9216 return true;
9217 }
9218
9219 // For a defaulted function in a dependent class, defer all remaining checks
9220 // until instantiation.
9221 if (RD->isDependentType())
9222 return false;
9223
9224 // Determine whether the function should be defined as deleted.
9225 DefaultedComparisonInfo Info =
9226 DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit();
9227
9228 bool First = FD == FD->getCanonicalDecl();
9229
9230 if (!First) {
9231 if (Info.Deleted) {
9232 // C++11 [dcl.fct.def.default]p4:
9233 // [For a] user-provided explicitly-defaulted function [...] if such a
9234 // function is implicitly defined as deleted, the program is ill-formed.
9235 //
9236 // This is really just a consequence of the general rule that you can
9237 // only delete a function on its first declaration.
9238 Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes)
9239 << FD->isImplicit() << (int)DCK;
9240 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9241 DefaultedComparisonAnalyzer::ExplainDeleted)
9242 .visit();
9243 return true;
9244 }
9246 // C++20 [class.compare.default]p1:
9247 // [...] A definition of a comparison operator as defaulted that appears
9248 // in a class shall be the first declaration of that function.
9249 Diag(FD->getLocation(), diag::err_non_first_default_compare_in_class)
9250 << (int)DCK;
9252 diag::note_previous_declaration);
9253 return true;
9254 }
9255 }
9256
9257 // If we want to delete the function, then do so; there's nothing else to
9258 // check in that case.
9259 if (Info.Deleted) {
9260 SetDeclDeleted(FD, FD->getLocation());
9261 if (!inTemplateInstantiation() && !FD->isImplicit()) {
9262 Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted)
9263 << (int)DCK;
9264 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9265 DefaultedComparisonAnalyzer::ExplainDeleted)
9266 .visit();
9267 if (FD->getDefaultLoc().isValid())
9268 Diag(FD->getDefaultLoc(), diag::note_replace_equals_default_to_delete)
9269 << FixItHint::CreateReplacement(FD->getDefaultLoc(), "delete");
9270 }
9271 return false;
9272 }
9273
9274 // C++2a [class.spaceship]p2:
9275 // The return type is deduced as the common comparison type of R0, R1, ...
9279 if (RetLoc.isInvalid())
9280 RetLoc = FD->getBeginLoc();
9281 // FIXME: Should we really care whether we have the complete type and the
9282 // 'enumerator' constants here? A forward declaration seems sufficient.
9284 Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator);
9285 if (Cat.isNull())
9286 return true;
9287 Context.adjustDeducedFunctionResultType(
9288 FD, SubstAutoType(FD->getDeclaredReturnType(), Cat));
9289 }
9290
9291 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
9292 // An explicitly-defaulted function that is not defined as deleted may be
9293 // declared constexpr or consteval only if it is constexpr-compatible.
9294 // C++2a [class.compare.default]p3 [P2002R0]:
9295 // A defaulted comparison function is constexpr-compatible if it satisfies
9296 // the requirements for a constexpr function [...]
9297 // The only relevant requirements are that the parameter and return types are
9298 // literal types. The remaining conditions are checked by the analyzer.
9299 //
9300 // We support P2448R2 in language modes earlier than C++23 as an extension.
9301 // The concept of constexpr-compatible was removed.
9302 // C++23 [dcl.fct.def.default]p3 [P2448R2]
9303 // A function explicitly defaulted on its first declaration is implicitly
9304 // inline, and is implicitly constexpr if it is constexpr-suitable.
9305 // C++23 [dcl.constexpr]p3
9306 // A function is constexpr-suitable if
9307 // - it is not a coroutine, and
9308 // - if the function is a constructor or destructor, its class does not
9309 // have any virtual base classes.
9310 if (FD->isConstexpr()) {
9311 if (!getLangOpts().CPlusPlus23 &&
9314 !Info.Constexpr) {
9315 Diag(FD->getBeginLoc(), diag::err_defaulted_comparison_constexpr_mismatch)
9316 << FD->isImplicit() << (int)DCK << FD->isConsteval();
9317 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9318 DefaultedComparisonAnalyzer::ExplainConstexpr)
9319 .visit();
9320 }
9321 }
9322
9323 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
9324 // If a constexpr-compatible function is explicitly defaulted on its first
9325 // declaration, it is implicitly considered to be constexpr.
9326 // FIXME: Only applying this to the first declaration seems problematic, as
9327 // simple reorderings can affect the meaning of the program.
9328 if (First && !FD->isConstexpr() && Info.Constexpr)
9330
9331 // C++2a [except.spec]p3:
9332 // If a declaration of a function does not have a noexcept-specifier
9333 // [and] is defaulted on its first declaration, [...] the exception
9334 // specification is as specified below
9335 if (FD->getExceptionSpecType() == EST_None) {
9336 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9337 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9339 EPI.ExceptionSpec.SourceDecl = FD;
9340 FD->setType(Context.getFunctionType(FPT->getReturnType(),
9341 FPT->getParamTypes(), EPI));
9342 }
9343
9344 return false;
9345}
9346
9348 FunctionDecl *Spaceship) {
9351 Ctx.PointOfInstantiation = Spaceship->getEndLoc();
9352 Ctx.Entity = Spaceship;
9354
9355 if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship))
9356 EqualEqual->setImplicit();
9357
9359}
9360
9363 assert(FD->isDefaulted() && !FD->isDeleted() &&
9365 if (FD->willHaveBody() || FD->isInvalidDecl())
9366 return;
9367
9369
9370 // Add a context note for diagnostics produced after this point.
9371 Scope.addContextNote(UseLoc);
9372
9373 DefaultedFunctionFPFeaturesRAII RestoreFP(*this, FD);
9374
9375 {
9376 // Build and set up the function body.
9377 // The first parameter has type maybe-ref-to maybe-const T, use that to get
9378 // the type of the class being compared.
9379 auto PT = FD->getParamDecl(0)->getType();
9380 CXXRecordDecl *RD = PT.getNonReferenceType()->getAsCXXRecordDecl();
9381 SourceLocation BodyLoc =
9382 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
9383 StmtResult Body =
9384 DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build();
9385 if (Body.isInvalid()) {
9386 FD->setInvalidDecl();
9387 return;
9388 }
9389 FD->setBody(Body.get());
9390 FD->markUsed(Context);
9391 }
9392
9393 // The exception specification is needed because we are defining the
9394 // function. Note that this will reuse the body we just built.
9396
9398 L->CompletedImplicitDefinition(FD);
9399}
9400
9403 FunctionDecl *FD,
9405 ComputingExceptionSpec CES(S, FD, Loc);
9407
9408 if (FD->isInvalidDecl())
9409 return ExceptSpec;
9410
9411 // The common case is that we just defined the comparison function. In that
9412 // case, just look at whether the body can throw.
9413 if (FD->hasBody()) {
9414 ExceptSpec.CalledStmt(FD->getBody());
9415 } else {
9416 // Otherwise, build a body so we can check it. This should ideally only
9417 // happen when we're not actually marking the function referenced. (This is
9418 // only really important for efficiency: we don't want to build and throw
9419 // away bodies for comparison functions more than we strictly need to.)
9420
9421 // Pretend to synthesize the function body in an unevaluated context.
9422 // Note that we can't actually just go ahead and define the function here:
9423 // we are not permitted to mark its callees as referenced.
9427
9428 CXXRecordDecl *RD =
9430 ? FD->getDeclContext()
9431 : FD->getLexicalDeclContext());
9432 SourceLocation BodyLoc =
9433 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
9434 StmtResult Body =
9435 DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build();
9436 if (!Body.isInvalid())
9437 ExceptSpec.CalledStmt(Body.get());
9438
9439 // FIXME: Can we hold onto this body and just transform it to potentially
9440 // evaluated when we're asked to define the function rather than rebuilding
9441 // it? Either that, or we should only build the bits of the body that we
9442 // need (the expressions, not the statements).
9443 }
9444
9445 return ExceptSpec;
9446}
9447
9449 decltype(DelayedOverridingExceptionSpecChecks) Overriding;
9451
9452 std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
9454
9455 // Perform any deferred checking of exception specifications for virtual
9456 // destructors.
9457 for (auto &Check : Overriding)
9458 CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
9459
9460 // Perform any deferred checking of exception specifications for befriended
9461 // special members.
9462 for (auto &Check : Equivalent)
9463 CheckEquivalentExceptionSpec(Check.second, Check.first);
9464}
9465
9466namespace {
9467/// CRTP base class for visiting operations performed by a special member
9468/// function (or inherited constructor).
9469template<typename Derived>
9470struct SpecialMemberVisitor {
9471 Sema &S;
9472 CXXMethodDecl *MD;
9475
9476 // Properties of the special member, computed for convenience.
9477 bool IsConstructor = false, IsAssignment = false, ConstArg = false;
9478
9479 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, CXXSpecialMemberKind CSM,
9481 : S(S), MD(MD), CSM(CSM), ICI(ICI) {
9482 switch (CSM) {
9486 IsConstructor = true;
9487 break;
9490 IsAssignment = true;
9491 break;
9493 break;
9495 llvm_unreachable("invalid special member kind");
9496 }
9497
9498 if (MD->getNumExplicitParams()) {
9499 if (const ReferenceType *RT =
9500 MD->getNonObjectParameter(0)->getType()->getAs<ReferenceType>())
9501 ConstArg = RT->getPointeeType().isConstQualified();
9502 }
9503 }
9504
9505 Derived &getDerived() { return static_cast<Derived&>(*this); }
9506
9507 /// Is this a "move" special member?
9508 bool isMove() const {
9509 return CSM == CXXSpecialMemberKind::MoveConstructor ||
9510 CSM == CXXSpecialMemberKind::MoveAssignment;
9511 }
9512
9513 /// Look up the corresponding special member in the given class.
9514 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
9515 unsigned Quals, bool IsMutable) {
9516 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
9517 ConstArg && !IsMutable);
9518 }
9519
9520 /// Look up the constructor for the specified base class to see if it's
9521 /// overridden due to this being an inherited constructor.
9522 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
9523 if (!ICI)
9524 return {};
9525 assert(CSM == CXXSpecialMemberKind::DefaultConstructor);
9526 auto *BaseCtor =
9527 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
9528 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
9529 return MD;
9530 return {};
9531 }
9532
9533 /// A base or member subobject.
9534 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
9535
9536 /// Get the location to use for a subobject in diagnostics.
9537 static SourceLocation getSubobjectLoc(Subobject Subobj) {
9538 // FIXME: For an indirect virtual base, the direct base leading to
9539 // the indirect virtual base would be a more useful choice.
9540 if (auto *B = dyn_cast<CXXBaseSpecifier *>(Subobj))
9541 return B->getBaseTypeLoc();
9542 else
9543 return cast<FieldDecl *>(Subobj)->getLocation();
9544 }
9545
9546 enum BasesToVisit {
9547 /// Visit all non-virtual (direct) bases.
9548 VisitNonVirtualBases,
9549 /// Visit all direct bases, virtual or not.
9550 VisitDirectBases,
9551 /// Visit all non-virtual bases, and all virtual bases if the class
9552 /// is not abstract.
9553 VisitPotentiallyConstructedBases,
9554 /// Visit all direct or virtual bases.
9555 VisitAllBases
9556 };
9557
9558 // Visit the bases and members of the class.
9559 bool visit(BasesToVisit Bases) {
9560 CXXRecordDecl *RD = MD->getParent();
9561
9562 if (Bases == VisitPotentiallyConstructedBases)
9563 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
9564
9565 for (auto &B : RD->bases())
9566 if ((Bases == VisitDirectBases || !B.isVirtual()) &&
9567 getDerived().visitBase(&B))
9568 return true;
9569
9570 if (Bases == VisitAllBases)
9571 for (auto &B : RD->vbases())
9572 if (getDerived().visitBase(&B))
9573 return true;
9574
9575 for (auto *F : RD->fields())
9576 if (!F->isInvalidDecl() && !F->isUnnamedBitField() &&
9577 getDerived().visitField(F))
9578 return true;
9579
9580 return false;
9581 }
9582};
9583}
9584
9585namespace {
9586struct SpecialMemberDeletionInfo
9587 : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
9588 bool Diagnose;
9589
9590 SourceLocation Loc;
9591
9592 bool AllFieldsAreConst;
9593
9594 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
9596 Sema::InheritedConstructorInfo *ICI, bool Diagnose)
9597 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
9598 Loc(MD->getLocation()), AllFieldsAreConst(true) {}
9599
9600 bool inUnion() const { return MD->getParent()->isUnion(); }
9601
9602 CXXSpecialMemberKind getEffectiveCSM() {
9603 return ICI ? CXXSpecialMemberKind::Invalid : CSM;
9604 }
9605
9606 bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
9607
9608 bool shouldDeleteForVariantPtrAuthMember(const FieldDecl *FD);
9609
9610 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
9611 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
9612
9613 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
9614 bool shouldDeleteForField(FieldDecl *FD);
9615 bool shouldDeleteForAllConstMembers();
9616
9617 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
9618 unsigned Quals);
9619 bool shouldDeleteForSubobjectCall(Subobject Subobj,
9620 Sema::SpecialMemberOverloadResult SMOR,
9621 bool IsDtorCallInCtor);
9622
9623 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
9624};
9625}
9626
9627/// Is the given special member inaccessible when used on the given
9628/// sub-object.
9629bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
9630 CXXMethodDecl *target) {
9631 /// If we're operating on a base class, the object type is the
9632 /// type of this special member.
9633 CanQualType objectTy;
9634 AccessSpecifier access = target->getAccess();
9635 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
9636 objectTy = S.Context.getCanonicalTagType(MD->getParent());
9637 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
9638
9639 // If we're operating on a field, the object type is the type of the field.
9640 } else {
9641 objectTy = S.Context.getCanonicalTagType(target->getParent());
9642 }
9643
9645 target->getParent(), DeclAccessPair::make(target, access), objectTy);
9646}
9647
9648/// Check whether we should delete a special member due to the implicit
9649/// definition containing a call to a special member of a subobject.
9650bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
9651 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
9652 bool IsDtorCallInCtor) {
9653 CXXMethodDecl *Decl = SMOR.getMethod();
9654 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9655
9656 enum {
9657 NotSet = -1,
9658 NoDecl,
9659 DeletedDecl,
9660 MultipleDecl,
9661 InaccessibleDecl,
9662 NonTrivialDecl
9663 } DiagKind = NotSet;
9664
9666 if (CSM == CXXSpecialMemberKind::DefaultConstructor && Field &&
9667 Field->getParent()->isUnion()) {
9668 // [class.default.ctor]p2:
9669 // A defaulted default constructor for class X is defined as deleted if
9670 // - X is a union that has a variant member with a non-trivial default
9671 // constructor and no variant member of X has a default member
9672 // initializer
9673 const auto *RD = cast<CXXRecordDecl>(Field->getParent());
9674 if (RD->hasInClassInitializer())
9675 return false;
9676 }
9677 DiagKind = !Decl ? NoDecl : DeletedDecl;
9679 DiagKind = MultipleDecl;
9680 else if (!isAccessible(Subobj, Decl))
9681 DiagKind = InaccessibleDecl;
9682 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
9683 !Decl->isTrivial()) {
9684 // A member of a union must have a trivial corresponding special member.
9685 // As a weird special case, a destructor call from a union's constructor
9686 // must be accessible and non-deleted, but need not be trivial. Such a
9687 // destructor is never actually called, but is semantically checked as
9688 // if it were.
9689 if (CSM == CXXSpecialMemberKind::DefaultConstructor) {
9690 // [class.default.ctor]p2:
9691 // A defaulted default constructor for class X is defined as deleted if
9692 // - X is a union that has a variant member with a non-trivial default
9693 // constructor and no variant member of X has a default member
9694 // initializer
9695 const auto *RD = cast<CXXRecordDecl>(Field->getParent());
9696 if (!RD->hasInClassInitializer())
9697 DiagKind = NonTrivialDecl;
9698 } else {
9699 DiagKind = NonTrivialDecl;
9700 }
9701 }
9702
9703 if (DiagKind == NotSet)
9704 return false;
9705
9706 if (Diagnose) {
9707 if (Field) {
9708 S.Diag(Field->getLocation(),
9709 diag::note_deleted_special_member_class_subobject)
9710 << getEffectiveCSM() << MD->getParent() << /*IsField*/ true << Field
9711 << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/ false;
9712 } else {
9713 CXXBaseSpecifier *Base = cast<CXXBaseSpecifier *>(Subobj);
9714 S.Diag(Base->getBeginLoc(),
9715 diag::note_deleted_special_member_class_subobject)
9716 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9717 << Base->getType() << DiagKind << IsDtorCallInCtor
9718 << /*IsObjCPtr*/ false;
9719 }
9720
9721 if (DiagKind == DeletedDecl)
9722 S.NoteDeletedFunction(Decl);
9723 // FIXME: Explain inaccessibility if DiagKind == InaccessibleDecl.
9724 }
9725
9726 return true;
9727}
9728
9729/// Check whether we should delete a special member function due to having a
9730/// direct or virtual base class or non-static data member of class type M.
9731bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
9732 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
9733 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9734 bool IsMutable = Field && Field->isMutable();
9735
9736 // C++11 [class.ctor]p5:
9737 // -- any direct or virtual base class, or non-static data member with no
9738 // brace-or-equal-initializer, has class type M (or array thereof) and
9739 // either M has no default constructor or overload resolution as applied
9740 // to M's default constructor results in an ambiguity or in a function
9741 // that is deleted or inaccessible
9742 // C++11 [class.copy]p11, C++11 [class.copy]p23:
9743 // -- a direct or virtual base class B that cannot be copied/moved because
9744 // overload resolution, as applied to B's corresponding special member,
9745 // results in an ambiguity or a function that is deleted or inaccessible
9746 // from the defaulted special member
9747 // C++11 [class.dtor]p5:
9748 // -- any direct or virtual base class [...] has a type with a destructor
9749 // that is deleted or inaccessible
9750 if (!(CSM == CXXSpecialMemberKind::DefaultConstructor && Field &&
9751 Field->hasInClassInitializer()) &&
9752 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
9753 false))
9754 return true;
9755
9756 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
9757 // -- any direct or virtual base class or non-static data member has a
9758 // type with a destructor that is deleted or inaccessible
9759 if (IsConstructor) {
9760 Sema::SpecialMemberOverloadResult SMOR =
9761 S.LookupSpecialMember(Class, CXXSpecialMemberKind::Destructor, false,
9762 false, false, false, false);
9763 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
9764 return true;
9765 }
9766
9767 return false;
9768}
9769
9770bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
9771 FieldDecl *FD, QualType FieldType) {
9772 // The defaulted special functions are defined as deleted if this is a variant
9773 // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
9774 // type under ARC.
9775 if (!FieldType.hasNonTrivialObjCLifetime())
9776 return false;
9777
9778 // Don't make the defaulted default constructor defined as deleted if the
9779 // member has an in-class initializer.
9780 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
9782 return false;
9783
9784 if (Diagnose) {
9785 auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
9786 S.Diag(FD->getLocation(), diag::note_deleted_special_member_class_subobject)
9787 << getEffectiveCSM() << ParentClass << /*IsField*/ true << FD << 4
9788 << /*IsDtorCallInCtor*/ false << /*IsObjCPtr*/ true;
9789 }
9790
9791 return true;
9792}
9793
9794bool SpecialMemberDeletionInfo::shouldDeleteForVariantPtrAuthMember(
9795 const FieldDecl *FD) {
9796 QualType FieldType = S.Context.getBaseElementType(FD->getType());
9797 // Copy/move constructors/assignment operators are deleted if the field has an
9798 // address-discriminated ptrauth qualifier.
9799 PointerAuthQualifier Q = FieldType.getPointerAuth();
9800
9801 if (!Q || !Q.isAddressDiscriminated())
9802 return false;
9803
9804 if (CSM == CXXSpecialMemberKind::DefaultConstructor ||
9805 CSM == CXXSpecialMemberKind::Destructor)
9806 return false;
9807
9808 if (Diagnose) {
9809 auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
9810 S.Diag(FD->getLocation(), diag::note_deleted_special_member_class_subobject)
9811 << getEffectiveCSM() << ParentClass << /*IsField*/ true << FD << 4
9812 << /*IsDtorCallInCtor*/ false << 2;
9813 }
9814
9815 return true;
9816}
9817
9818/// Check whether we should delete a special member function due to the class
9819/// having a particular direct or virtual base class.
9820bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
9821 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
9822 // If program is correct, BaseClass cannot be null, but if it is, the error
9823 // must be reported elsewhere.
9824 if (!BaseClass)
9825 return false;
9826 // If we have an inheriting constructor, check whether we're calling an
9827 // inherited constructor instead of a default constructor.
9828 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
9829 if (auto *BaseCtor = SMOR.getMethod()) {
9830 // Note that we do not check access along this path; other than that,
9831 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
9832 // FIXME: Check that the base has a usable destructor! Sink this into
9833 // shouldDeleteForClassSubobject.
9834 if (BaseCtor->isDeleted() && Diagnose) {
9835 S.Diag(Base->getBeginLoc(),
9836 diag::note_deleted_special_member_class_subobject)
9837 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9838 << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
9839 << /*IsObjCPtr*/ false;
9840 S.NoteDeletedFunction(BaseCtor);
9841 }
9842 return BaseCtor->isDeleted();
9843 }
9844 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
9845}
9846
9847/// Check whether we should delete a special member function due to the class
9848/// having a particular non-static data member.
9849bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
9850 QualType FieldType = S.Context.getBaseElementType(FD->getType());
9851 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
9852
9853 if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
9854 return true;
9855
9856 if (inUnion() && shouldDeleteForVariantPtrAuthMember(FD))
9857 return true;
9858
9859 if (CSM == CXXSpecialMemberKind::DefaultConstructor) {
9860 // For a default constructor, all references must be initialized in-class
9861 // and, if a union, it must have a non-const member.
9862 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
9863 if (Diagnose)
9864 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9865 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
9866 return true;
9867 }
9868 // C++11 [class.ctor]p5 (modified by DR2394): any non-variant non-static
9869 // data member of const-qualified type (or array thereof) with no
9870 // brace-or-equal-initializer is not const-default-constructible.
9871 if (!inUnion() && FieldType.isConstQualified() &&
9872 !FD->hasInClassInitializer() &&
9873 (!FieldRecord || !FieldRecord->allowConstDefaultInit())) {
9874 if (Diagnose)
9875 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9876 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
9877 return true;
9878 }
9879
9880 if (inUnion() && !FieldType.isConstQualified())
9881 AllFieldsAreConst = false;
9882 } else if (CSM == CXXSpecialMemberKind::CopyConstructor) {
9883 // For a copy constructor, data members must not be of rvalue reference
9884 // type.
9885 if (FieldType->isRValueReferenceType()) {
9886 if (Diagnose)
9887 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
9888 << MD->getParent() << FD << FieldType;
9889 return true;
9890 }
9891 } else if (IsAssignment) {
9892 // For an assignment operator, data members must not be of reference type.
9893 if (FieldType->isReferenceType()) {
9894 if (Diagnose)
9895 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9896 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
9897 return true;
9898 }
9899 if (!FieldRecord && FieldType.isConstQualified()) {
9900 // C++11 [class.copy]p23:
9901 // -- a non-static data member of const non-class type (or array thereof)
9902 if (Diagnose)
9903 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9904 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
9905 return true;
9906 }
9907 }
9908
9909 if (FieldRecord) {
9910 // Some additional restrictions exist on the variant members.
9911 if (!inUnion() && FieldRecord->isUnion() &&
9912 FieldRecord->isAnonymousStructOrUnion()) {
9913 bool AllVariantFieldsAreConst = true;
9914
9915 // FIXME: Handle anonymous unions declared within anonymous unions.
9916 for (auto *UI : FieldRecord->fields()) {
9917 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
9918
9919 if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
9920 return true;
9921
9922 if (shouldDeleteForVariantPtrAuthMember(&*UI))
9923 return true;
9924
9925 if (!UnionFieldType.isConstQualified())
9926 AllVariantFieldsAreConst = false;
9927
9928 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
9929 if (UnionFieldRecord &&
9930 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
9931 UnionFieldType.getCVRQualifiers()))
9932 return true;
9933 }
9934
9935 // At least one member in each anonymous union must be non-const
9936 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
9937 AllVariantFieldsAreConst && !FieldRecord->field_empty()) {
9938 if (Diagnose)
9939 S.Diag(FieldRecord->getLocation(),
9940 diag::note_deleted_default_ctor_all_const)
9941 << !!ICI << MD->getParent() << /*anonymous union*/1;
9942 return true;
9943 }
9944
9945 // Don't check the implicit member of the anonymous union type.
9946 // This is technically non-conformant but supported, and we have a
9947 // diagnostic for this elsewhere.
9948 return false;
9949 }
9950
9951 if (shouldDeleteForClassSubobject(FieldRecord, FD,
9952 FieldType.getCVRQualifiers()))
9953 return true;
9954 }
9955
9956 return false;
9957}
9958
9959/// C++11 [class.ctor] p5:
9960/// A defaulted default constructor for a class X is defined as deleted if
9961/// X is a union and all of its variant members are of const-qualified type.
9962bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
9963 // This is a silly definition, because it gives an empty union a deleted
9964 // default constructor. Don't do that.
9965 if (CSM == CXXSpecialMemberKind::DefaultConstructor && inUnion() &&
9966 AllFieldsAreConst) {
9967 bool AnyFields = false;
9968 for (auto *F : MD->getParent()->fields())
9969 if ((AnyFields = !F->isUnnamedBitField()))
9970 break;
9971 if (!AnyFields)
9972 return false;
9973 if (Diagnose)
9974 S.Diag(MD->getParent()->getLocation(),
9975 diag::note_deleted_default_ctor_all_const)
9976 << !!ICI << MD->getParent() << /*not anonymous union*/0;
9977 return true;
9978 }
9979 return false;
9980}
9981
9982/// Determine whether a defaulted special member function should be defined as
9983/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
9984/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
9988 bool Diagnose) {
9989 if (MD->isInvalidDecl())
9990 return false;
9991 CXXRecordDecl *RD = MD->getParent();
9992 assert(!RD->isDependentType() && "do deletion after instantiation");
9993 if (!LangOpts.CPlusPlus || (!LangOpts.CPlusPlus11 && !RD->isLambda()) ||
9994 RD->isInvalidDecl())
9995 return false;
9996
9997 // C++11 [expr.lambda.prim]p19:
9998 // The closure type associated with a lambda-expression has a
9999 // deleted (8.4.3) default constructor and a deleted copy
10000 // assignment operator.
10001 // C++2a adds back these operators if the lambda has no lambda-capture.
10005 if (Diagnose)
10006 Diag(RD->getLocation(), diag::note_lambda_decl);
10007 return true;
10008 }
10009
10010 // C++11 [class.copy]p7, p18:
10011 // If the class definition declares a move constructor or move assignment
10012 // operator, an implicitly declared copy constructor or copy assignment
10013 // operator is defined as deleted.
10016 CXXMethodDecl *UserDeclaredMove = nullptr;
10017
10018 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
10019 // deletion of the corresponding copy operation, not both copy operations.
10020 // MSVC 2015 has adopted the standards conforming behavior.
10021 bool DeletesOnlyMatchingCopy =
10022 getLangOpts().MSVCCompat &&
10023 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
10024
10026 (!DeletesOnlyMatchingCopy ||
10028 if (!Diagnose) return true;
10029
10030 // Find any user-declared move constructor.
10031 for (auto *I : RD->ctors()) {
10032 if (I->isMoveConstructor()) {
10033 UserDeclaredMove = I;
10034 break;
10035 }
10036 }
10037 assert(UserDeclaredMove);
10038 } else if (RD->hasUserDeclaredMoveAssignment() &&
10039 (!DeletesOnlyMatchingCopy ||
10041 if (!Diagnose) return true;
10042
10043 // Find any user-declared move assignment operator.
10044 for (auto *I : RD->methods()) {
10045 if (I->isMoveAssignmentOperator()) {
10046 UserDeclaredMove = I;
10047 break;
10048 }
10049 }
10050 assert(UserDeclaredMove);
10051 }
10052
10053 if (UserDeclaredMove) {
10054 Diag(UserDeclaredMove->getLocation(),
10055 diag::note_deleted_copy_user_declared_move)
10056 << (CSM == CXXSpecialMemberKind::CopyAssignment) << RD
10057 << UserDeclaredMove->isMoveAssignmentOperator();
10058 return true;
10059 }
10060 }
10061
10062 // Do access control from the special member function
10063 ContextRAII MethodContext(*this, MD);
10064
10065 // C++11 [class.dtor]p5:
10066 // -- for a virtual destructor, lookup of the non-array deallocation function
10067 // results in an ambiguity or in a function that is deleted or inaccessible
10068 if (CSM == CXXSpecialMemberKind::Destructor && MD->isVirtual()) {
10069 FunctionDecl *OperatorDelete = nullptr;
10070 CanQualType DeallocType = Context.getCanonicalTagType(RD);
10071 DeclarationName Name =
10072 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
10076 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
10077 OperatorDelete, IDP,
10078 /*Diagnose=*/false)) {
10079 if (Diagnose)
10080 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
10081 return true;
10082 }
10083 }
10084
10085 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
10086
10087 // Per DR1611, do not consider virtual bases of constructors of abstract
10088 // classes, since we are not going to construct them.
10089 // Per DR1658, do not consider virtual bases of destructors of abstract
10090 // classes either.
10091 // Per DR2180, for assignment operators we only assign (and thus only
10092 // consider) direct bases.
10093 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
10094 : SMI.VisitPotentiallyConstructedBases))
10095 return true;
10096
10097 if (SMI.shouldDeleteForAllConstMembers())
10098 return true;
10099
10100 if (getLangOpts().CUDA) {
10101 // We should delete the special member in CUDA mode if target inference
10102 // failed.
10103 // For inherited constructors (non-null ICI), CSM may be passed so that MD
10104 // is treated as certain special member, which may not reflect what special
10105 // member MD really is. However inferTargetForImplicitSpecialMember
10106 // expects CSM to match MD, therefore recalculate CSM.
10107 assert(ICI || CSM == MD->getSpecialMemberKind());
10108 auto RealCSM = CSM;
10109 if (ICI)
10110 RealCSM = MD->getSpecialMemberKind();
10111
10112 return CUDA().inferTargetForImplicitSpecialMember(RD, RealCSM, MD,
10113 SMI.ConstArg, Diagnose);
10114 }
10115
10116 return false;
10117}
10118
10121 assert(DFK && "not a defaultable function");
10122 assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted");
10123
10124 if (DFK.isSpecialMember()) {
10126 nullptr, /*Diagnose=*/true);
10127 } else {
10128 DefaultedComparisonAnalyzer(
10130 DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted)
10131 .visit();
10132 }
10133}
10134
10135/// Perform lookup for a special member of the specified kind, and determine
10136/// whether it is trivial. If the triviality can be determined without the
10137/// lookup, skip it. This is intended for use when determining whether a
10138/// special member of a containing object is trivial, and thus does not ever
10139/// perform overload resolution for default constructors.
10140///
10141/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
10142/// member that was most likely to be intended to be trivial, if any.
10143///
10144/// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
10145/// determine whether the special member is trivial.
10147 CXXSpecialMemberKind CSM, unsigned Quals,
10148 bool ConstRHS, TrivialABIHandling TAH,
10149 CXXMethodDecl **Selected) {
10150 if (Selected)
10151 *Selected = nullptr;
10152
10153 switch (CSM) {
10155 llvm_unreachable("not a special member");
10156
10158 // C++11 [class.ctor]p5:
10159 // A default constructor is trivial if:
10160 // - all the [direct subobjects] have trivial default constructors
10161 //
10162 // Note, no overload resolution is performed in this case.
10164 return true;
10165
10166 if (Selected) {
10167 // If there's a default constructor which could have been trivial, dig it
10168 // out. Otherwise, if there's any user-provided default constructor, point
10169 // to that as an example of why there's not a trivial one.
10170 CXXConstructorDecl *DefCtor = nullptr;
10173 for (auto *CI : RD->ctors()) {
10174 if (!CI->isDefaultConstructor())
10175 continue;
10176 DefCtor = CI;
10177 if (!DefCtor->isUserProvided())
10178 break;
10179 }
10180
10181 *Selected = DefCtor;
10182 }
10183
10184 return false;
10185
10187 // C++11 [class.dtor]p5:
10188 // A destructor is trivial if:
10189 // - all the direct [subobjects] have trivial destructors
10190 if (RD->hasTrivialDestructor() ||
10193 return true;
10194
10195 if (Selected) {
10196 if (RD->needsImplicitDestructor())
10198 *Selected = RD->getDestructor();
10199 }
10200
10201 return false;
10202
10204 // C++11 [class.copy]p12:
10205 // A copy constructor is trivial if:
10206 // - the constructor selected to copy each direct [subobject] is trivial
10207 if (RD->hasTrivialCopyConstructor() ||
10210 if (Quals == Qualifiers::Const)
10211 // We must either select the trivial copy constructor or reach an
10212 // ambiguity; no need to actually perform overload resolution.
10213 return true;
10214 } else if (!Selected) {
10215 return false;
10216 }
10217 // In C++98, we are not supposed to perform overload resolution here, but we
10218 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
10219 // cases like B as having a non-trivial copy constructor:
10220 // struct A { template<typename T> A(T&); };
10221 // struct B { mutable A a; };
10222 goto NeedOverloadResolution;
10223
10225 // C++11 [class.copy]p25:
10226 // A copy assignment operator is trivial if:
10227 // - the assignment operator selected to copy each direct [subobject] is
10228 // trivial
10229 if (RD->hasTrivialCopyAssignment()) {
10230 if (Quals == Qualifiers::Const)
10231 return true;
10232 } else if (!Selected) {
10233 return false;
10234 }
10235 // In C++98, we are not supposed to perform overload resolution here, but we
10236 // treat that as a language defect.
10237 goto NeedOverloadResolution;
10238
10241 NeedOverloadResolution:
10243 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
10244
10245 // The standard doesn't describe how to behave if the lookup is ambiguous.
10246 // We treat it as not making the member non-trivial, just like the standard
10247 // mandates for the default constructor. This should rarely matter, because
10248 // the member will also be deleted.
10250 return true;
10251
10252 if (!SMOR.getMethod()) {
10253 assert(SMOR.getKind() ==
10255 return false;
10256 }
10257
10258 // We deliberately don't check if we found a deleted special member. We're
10259 // not supposed to!
10260 if (Selected)
10261 *Selected = SMOR.getMethod();
10262
10266 return SMOR.getMethod()->isTrivialForCall();
10267 return SMOR.getMethod()->isTrivial();
10268 }
10269
10270 llvm_unreachable("unknown special method kind");
10271}
10272
10274 for (auto *CI : RD->ctors())
10275 if (!CI->isImplicit())
10276 return CI;
10277
10278 // Look for constructor templates.
10280 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
10281 if (CXXConstructorDecl *CD =
10282 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
10283 return CD;
10284 }
10285
10286 return nullptr;
10287}
10288
10289/// The kind of subobject we are checking for triviality. The values of this
10290/// enumeration are used in diagnostics.
10292 /// The subobject is a base class.
10294 /// The subobject is a non-static data member.
10296 /// The object is actually the complete object.
10298};
10299
10300/// Check whether the special member selected for a given type would be trivial.
10302 QualType SubType, bool ConstRHS,
10305 TrivialABIHandling TAH, bool Diagnose) {
10306 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
10307 if (!SubRD)
10308 return true;
10309
10310 CXXMethodDecl *Selected;
10311 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
10312 ConstRHS, TAH, Diagnose ? &Selected : nullptr))
10313 return true;
10314
10315 if (Diagnose) {
10316 if (ConstRHS)
10317 SubType.addConst();
10318
10319 if (!Selected && CSM == CXXSpecialMemberKind::DefaultConstructor) {
10320 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
10321 << Kind << SubType.getUnqualifiedType();
10323 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
10324 } else if (!Selected)
10325 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
10326 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
10327 else if (Selected->isUserProvided()) {
10328 if (Kind == TSK_CompleteObject)
10329 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
10330 << Kind << SubType.getUnqualifiedType() << CSM;
10331 else {
10332 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
10333 << Kind << SubType.getUnqualifiedType() << CSM;
10334 S.Diag(Selected->getLocation(), diag::note_declared_at);
10335 }
10336 } else {
10337 if (Kind != TSK_CompleteObject)
10338 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
10339 << Kind << SubType.getUnqualifiedType() << CSM;
10340
10341 // Explain why the defaulted or deleted special member isn't trivial.
10342 S.SpecialMemberIsTrivial(Selected, CSM,
10344 }
10345 }
10346
10347 return false;
10348}
10349
10350/// Check whether the members of a class type allow a special member to be
10351/// trivial.
10353 CXXSpecialMemberKind CSM, bool ConstArg,
10354 TrivialABIHandling TAH, bool Diagnose) {
10355 for (const auto *FI : RD->fields()) {
10356 if (FI->isInvalidDecl() || FI->isUnnamedBitField())
10357 continue;
10358
10359 QualType FieldType = S.Context.getBaseElementType(FI->getType());
10360
10361 // Pretend anonymous struct or union members are members of this class.
10362 if (FI->isAnonymousStructOrUnion()) {
10363 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
10364 CSM, ConstArg, TAH, Diagnose))
10365 return false;
10366 continue;
10367 }
10368
10369 // C++11 [class.ctor]p5:
10370 // A default constructor is trivial if [...]
10371 // -- no non-static data member of its class has a
10372 // brace-or-equal-initializer
10374 FI->hasInClassInitializer()) {
10375 if (Diagnose)
10376 S.Diag(FI->getLocation(), diag::note_nontrivial_default_member_init)
10377 << FI;
10378 return false;
10379 }
10380
10381 // Objective C ARC 4.3.5:
10382 // [...] nontrivally ownership-qualified types are [...] not trivially
10383 // default constructible, copy constructible, move constructible, copy
10384 // assignable, move assignable, or destructible [...]
10385 if (FieldType.hasNonTrivialObjCLifetime()) {
10386 if (Diagnose)
10387 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
10388 << RD << FieldType.getObjCLifetime();
10389 return false;
10390 }
10391
10392 bool ConstRHS = ConstArg && !FI->isMutable();
10393 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
10394 CSM, TSK_Field, TAH, Diagnose))
10395 return false;
10396 }
10397
10398 return true;
10399}
10400
10403 CanQualType Ty = Context.getCanonicalTagType(RD);
10404
10405 bool ConstArg = (CSM == CXXSpecialMemberKind::CopyConstructor ||
10407 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
10410 /*Diagnose*/ true);
10411}
10412
10414 TrivialABIHandling TAH, bool Diagnose) {
10415 assert(!MD->isUserProvided() && CSM != CXXSpecialMemberKind::Invalid &&
10416 "not special enough");
10417
10418 CXXRecordDecl *RD = MD->getParent();
10419
10420 bool ConstArg = false;
10421
10422 // C++11 [class.copy]p12, p25: [DR1593]
10423 // A [special member] is trivial if [...] its parameter-type-list is
10424 // equivalent to the parameter-type-list of an implicit declaration [...]
10425 switch (CSM) {
10428 // Trivial default constructors and destructors cannot have parameters.
10429 break;
10430
10433 const ParmVarDecl *Param0 = MD->getNonObjectParameter(0);
10434 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
10435
10436 // When ClangABICompat14 is true, CXX copy constructors will only be trivial
10437 // if they are not user-provided and their parameter-type-list is equivalent
10438 // to the parameter-type-list of an implicit declaration. This maintains the
10439 // behavior before dr2171 was implemented.
10440 //
10441 // Otherwise, if ClangABICompat14 is false, All copy constructors can be
10442 // trivial, if they are not user-provided, regardless of the qualifiers on
10443 // the reference type.
10444 const bool ClangABICompat14 =
10445 Context.getLangOpts().isCompatibleWith(LangOptions::ClangABI::Ver14);
10446 if (!RT ||
10448 ClangABICompat14)) {
10449 if (Diagnose)
10450 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
10451 << Param0->getSourceRange() << Param0->getType()
10452 << Context.getLValueReferenceType(
10453 Context.getCanonicalTagType(RD).withConst());
10454 return false;
10455 }
10456
10457 ConstArg = RT->getPointeeType().isConstQualified();
10458 break;
10459 }
10460
10463 // Trivial move operations always have non-cv-qualified parameters.
10464 const ParmVarDecl *Param0 = MD->getNonObjectParameter(0);
10465 const RValueReferenceType *RT =
10466 Param0->getType()->getAs<RValueReferenceType>();
10467 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
10468 if (Diagnose)
10469 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
10470 << Param0->getSourceRange() << Param0->getType()
10471 << Context.getRValueReferenceType(Context.getCanonicalTagType(RD));
10472 return false;
10473 }
10474 break;
10475 }
10476
10478 llvm_unreachable("not a special member");
10479 }
10480
10481 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
10482 if (Diagnose)
10484 diag::note_nontrivial_default_arg)
10486 return false;
10487 }
10488 if (MD->isVariadic()) {
10489 if (Diagnose)
10490 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
10491 return false;
10492 }
10493
10494 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
10495 // A copy/move [constructor or assignment operator] is trivial if
10496 // -- the [member] selected to copy/move each direct base class subobject
10497 // is trivial
10498 //
10499 // C++11 [class.copy]p12, C++11 [class.copy]p25:
10500 // A [default constructor or destructor] is trivial if
10501 // -- all the direct base classes have trivial [default constructors or
10502 // destructors]
10503 for (const auto &BI : RD->bases())
10504 if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
10505 ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
10506 return false;
10507
10508 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
10509 // A copy/move [constructor or assignment operator] for a class X is
10510 // trivial if
10511 // -- for each non-static data member of X that is of class type (or array
10512 // thereof), the constructor selected to copy/move that member is
10513 // trivial
10514 //
10515 // C++11 [class.copy]p12, C++11 [class.copy]p25:
10516 // A [default constructor or destructor] is trivial if
10517 // -- for all of the non-static data members of its class that are of class
10518 // type (or array thereof), each such class has a trivial [default
10519 // constructor or destructor]
10520 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
10521 return false;
10522
10523 // C++11 [class.dtor]p5:
10524 // A destructor is trivial if [...]
10525 // -- the destructor is not virtual
10526 if (CSM == CXXSpecialMemberKind::Destructor && MD->isVirtual()) {
10527 if (Diagnose)
10528 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
10529 return false;
10530 }
10531
10532 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
10533 // A [special member] for class X is trivial if [...]
10534 // -- class X has no virtual functions and no virtual base classes
10536 MD->getParent()->isDynamicClass()) {
10537 if (!Diagnose)
10538 return false;
10539
10540 if (RD->getNumVBases()) {
10541 // Check for virtual bases. We already know that the corresponding
10542 // member in all bases is trivial, so vbases must all be direct.
10543 CXXBaseSpecifier &BS = *RD->vbases_begin();
10544 assert(BS.isVirtual());
10545 Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
10546 return false;
10547 }
10548
10549 // Must have a virtual method.
10550 for (const auto *MI : RD->methods()) {
10551 if (MI->isVirtual()) {
10552 SourceLocation MLoc = MI->getBeginLoc();
10553 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
10554 return false;
10555 }
10556 }
10557
10558 llvm_unreachable("dynamic class with no vbases and no virtual functions");
10559 }
10560
10561 // Looks like it's trivial!
10562 return true;
10563}
10564
10565namespace {
10566struct FindHiddenVirtualMethod {
10567 Sema *S;
10569 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
10570 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10571
10572private:
10573 /// Check whether any most overridden method from MD in Methods
10574 static bool CheckMostOverridenMethods(
10575 const CXXMethodDecl *MD,
10576 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
10577 if (MD->size_overridden_methods() == 0)
10578 return Methods.count(MD->getCanonicalDecl());
10579 for (const CXXMethodDecl *O : MD->overridden_methods())
10580 if (CheckMostOverridenMethods(O, Methods))
10581 return true;
10582 return false;
10583 }
10584
10585public:
10586 /// Member lookup function that determines whether a given C++
10587 /// method overloads virtual methods in a base class without overriding any,
10588 /// to be used with CXXRecordDecl::lookupInBases().
10589 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
10590 auto *BaseRecord = Specifier->getType()->castAsRecordDecl();
10591 DeclarationName Name = Method->getDeclName();
10592 assert(Name.getNameKind() == DeclarationName::Identifier);
10593
10594 bool foundSameNameMethod = false;
10595 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
10596 for (Path.Decls = BaseRecord->lookup(Name).begin();
10597 Path.Decls != DeclContext::lookup_iterator(); ++Path.Decls) {
10598 NamedDecl *D = *Path.Decls;
10599 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
10600 MD = MD->getCanonicalDecl();
10601 foundSameNameMethod = true;
10602 // Interested only in hidden virtual methods.
10603 if (!MD->isVirtual())
10604 continue;
10605 // If the method we are checking overrides a method from its base
10606 // don't warn about the other overloaded methods. Clang deviates from
10607 // GCC by only diagnosing overloads of inherited virtual functions that
10608 // do not override any other virtual functions in the base. GCC's
10609 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
10610 // function from a base class. These cases may be better served by a
10611 // warning (not specific to virtual functions) on call sites when the
10612 // call would select a different function from the base class, were it
10613 // visible.
10614 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
10615 if (!S->IsOverload(Method, MD, false))
10616 return true;
10617 // Collect the overload only if its hidden.
10618 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
10619 overloadedMethods.push_back(MD);
10620 }
10621 }
10622
10623 if (foundSameNameMethod)
10624 OverloadedMethods.append(overloadedMethods.begin(),
10625 overloadedMethods.end());
10626 return foundSameNameMethod;
10627 }
10628};
10629} // end anonymous namespace
10630
10631/// Add the most overridden methods from MD to Methods
10633 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
10634 if (MD->size_overridden_methods() == 0)
10635 Methods.insert(MD->getCanonicalDecl());
10636 else
10637 for (const CXXMethodDecl *O : MD->overridden_methods())
10638 AddMostOverridenMethods(O, Methods);
10639}
10640
10642 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10643 if (!MD->getDeclName().isIdentifier())
10644 return;
10645
10646 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
10647 /*bool RecordPaths=*/false,
10648 /*bool DetectVirtual=*/false);
10649 FindHiddenVirtualMethod FHVM;
10650 FHVM.Method = MD;
10651 FHVM.S = this;
10652
10653 // Keep the base methods that were overridden or introduced in the subclass
10654 // by 'using' in a set. A base method not in this set is hidden.
10655 CXXRecordDecl *DC = MD->getParent();
10656 for (NamedDecl *ND : DC->lookup(MD->getDeclName())) {
10657 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(ND))
10658 ND = shad->getTargetDecl();
10659 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
10660 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
10661 }
10662
10663 if (DC->lookupInBases(FHVM, Paths))
10664 OverloadedMethods = FHVM.OverloadedMethods;
10665}
10666
10668 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10669 for (const CXXMethodDecl *overloadedMD : OverloadedMethods) {
10671 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
10672 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
10673 Diag(overloadedMD->getLocation(), PD);
10674 }
10675}
10676
10678 if (MD->isInvalidDecl())
10679 return;
10680
10681 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
10682 return;
10683
10684 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10685 FindHiddenVirtualMethods(MD, OverloadedMethods);
10686 if (!OverloadedMethods.empty()) {
10687 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
10688 << MD << (OverloadedMethods.size() > 1);
10689
10690 NoteHiddenVirtualMethods(MD, OverloadedMethods);
10691 }
10692}
10693
10695 auto PrintDiagAndRemoveAttr = [&](unsigned N) {
10696 // No diagnostics if this is a template instantiation.
10698 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
10699 diag::ext_cannot_use_trivial_abi) << &RD;
10700 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
10701 diag::note_cannot_use_trivial_abi_reason) << &RD << N;
10702 }
10703 RD.dropAttr<TrivialABIAttr>();
10704 };
10705
10706 // Ill-formed if the struct has virtual functions.
10707 if (RD.isPolymorphic()) {
10708 PrintDiagAndRemoveAttr(1);
10709 return;
10710 }
10711
10712 for (const auto &B : RD.bases()) {
10713 // Ill-formed if the base class is non-trivial for the purpose of calls or a
10714 // virtual base.
10715 if (!B.getType()->isDependentType() &&
10716 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) {
10717 PrintDiagAndRemoveAttr(2);
10718 return;
10719 }
10720
10721 if (B.isVirtual()) {
10722 PrintDiagAndRemoveAttr(3);
10723 return;
10724 }
10725 }
10726
10727 for (const auto *FD : RD.fields()) {
10728 // Ill-formed if the field is an ObjectiveC pointer or of a type that is
10729 // non-trivial for the purpose of calls.
10730 QualType FT = FD->getType();
10732 PrintDiagAndRemoveAttr(4);
10733 return;
10734 }
10735
10736 // Ill-formed if the field is an address-discriminated value.
10738 PrintDiagAndRemoveAttr(6);
10739 return;
10740 }
10741
10742 if (const auto *RT =
10743 FT->getBaseElementTypeUnsafe()->getAsCanonical<RecordType>())
10744 if (!RT->isDependentType() &&
10745 !cast<CXXRecordDecl>(RT->getDecl()->getDefinitionOrSelf())
10746 ->canPassInRegisters()) {
10747 PrintDiagAndRemoveAttr(5);
10748 return;
10749 }
10750 }
10751
10753 return;
10754
10755 // Ill-formed if the copy and move constructors are deleted.
10756 auto HasNonDeletedCopyOrMoveConstructor = [&]() {
10757 // If the type is dependent, then assume it might have
10758 // implicit copy or move ctor because we won't know yet at this point.
10759 if (RD.isDependentType())
10760 return true;
10763 return true;
10766 return true;
10767 for (const CXXConstructorDecl *CD : RD.ctors())
10768 if (CD->isCopyOrMoveConstructor() && !CD->isDeleted())
10769 return true;
10770 return false;
10771 };
10772
10773 if (!HasNonDeletedCopyOrMoveConstructor()) {
10774 PrintDiagAndRemoveAttr(0);
10775 return;
10776 }
10777}
10778
10780 CXXRecordDecl &RD) {
10781 if (RequireCompleteType(RD.getLocation(), Context.getCanonicalTagType(&RD),
10782 diag::err_incomplete_type_vtable_pointer_auth))
10783 return;
10784
10785 const CXXRecordDecl *PrimaryBase = &RD;
10786 if (PrimaryBase->hasAnyDependentBases())
10787 return;
10788
10789 while (1) {
10790 assert(PrimaryBase);
10791 const CXXRecordDecl *Base = nullptr;
10792 for (const CXXBaseSpecifier &BasePtr : PrimaryBase->bases()) {
10793 if (!BasePtr.getType()->getAsCXXRecordDecl()->isDynamicClass())
10794 continue;
10795 Base = BasePtr.getType()->getAsCXXRecordDecl();
10796 break;
10797 }
10798 if (!Base || Base == PrimaryBase || !Base->isPolymorphic())
10799 break;
10800 Diag(RD.getAttr<VTablePointerAuthenticationAttr>()->getLocation(),
10801 diag::err_non_top_level_vtable_pointer_auth)
10802 << &RD << Base;
10803 PrimaryBase = Base;
10804 }
10805
10806 if (!RD.isPolymorphic())
10807 Diag(RD.getAttr<VTablePointerAuthenticationAttr>()->getLocation(),
10808 diag::err_non_polymorphic_vtable_pointer_auth)
10809 << &RD;
10810}
10811
10814 SourceLocation RBrac, const ParsedAttributesView &AttrList) {
10815 if (!TagDecl)
10816 return;
10817
10819
10820 for (const ParsedAttr &AL : AttrList) {
10821 if (AL.getKind() != ParsedAttr::AT_Visibility)
10822 continue;
10823 AL.setInvalid();
10824 Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL;
10825 }
10826
10827 ActOnFields(S, RLoc, TagDecl,
10829 // strict aliasing violation!
10830 reinterpret_cast<Decl **>(FieldCollector->getCurFields()),
10831 FieldCollector->getCurNumFields()),
10832 LBrac, RBrac, AttrList);
10833
10835}
10836
10837/// Find the equality comparison functions that should be implicitly declared
10838/// in a given class definition, per C++2a [class.compare.default]p3.
10840 ASTContext &Ctx, CXXRecordDecl *RD,
10842 DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual);
10843 if (!RD->lookup(EqEq).empty())
10844 // Member operator== explicitly declared: no implicit operator==s.
10845 return;
10846
10847 // Traverse friends looking for an '==' or a '<=>'.
10848 for (FriendDecl *Friend : RD->friends()) {
10849 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl());
10850 if (!FD) continue;
10851
10852 if (FD->getOverloadedOperator() == OO_EqualEqual) {
10853 // Friend operator== explicitly declared: no implicit operator==s.
10854 Spaceships.clear();
10855 return;
10856 }
10857
10858 if (FD->getOverloadedOperator() == OO_Spaceship &&
10860 Spaceships.push_back(FD);
10861 }
10862
10863 // Look for members named 'operator<=>'.
10865 for (NamedDecl *ND : RD->lookup(Cmp)) {
10866 // Note that we could find a non-function here (either a function template
10867 // or a using-declaration). Neither case results in an implicit
10868 // 'operator=='.
10869 if (auto *FD = dyn_cast<FunctionDecl>(ND))
10870 if (FD->isExplicitlyDefaulted())
10871 Spaceships.push_back(FD);
10872 }
10873}
10874
10876 // Don't add implicit special members to templated classes.
10877 // FIXME: This means unqualified lookups for 'operator=' within a class
10878 // template don't work properly.
10879 if (!ClassDecl->isDependentType()) {
10880 if (ClassDecl->needsImplicitDefaultConstructor()) {
10881 ++getASTContext().NumImplicitDefaultConstructors;
10882
10883 if (ClassDecl->hasInheritedConstructor())
10885 }
10886
10887 if (ClassDecl->needsImplicitCopyConstructor()) {
10888 ++getASTContext().NumImplicitCopyConstructors;
10889
10890 // If the properties or semantics of the copy constructor couldn't be
10891 // determined while the class was being declared, force a declaration
10892 // of it now.
10894 ClassDecl->hasInheritedConstructor())
10896 // For the MS ABI we need to know whether the copy ctor is deleted. A
10897 // prerequisite for deleting the implicit copy ctor is that the class has
10898 // a move ctor or move assignment that is either user-declared or whose
10899 // semantics are inherited from a subobject. FIXME: We should provide a
10900 // more direct way for CodeGen to ask whether the constructor was deleted.
10901 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
10902 (ClassDecl->hasUserDeclaredMoveConstructor() ||
10904 ClassDecl->hasUserDeclaredMoveAssignment() ||
10907 }
10908
10909 if (getLangOpts().CPlusPlus11 &&
10910 ClassDecl->needsImplicitMoveConstructor()) {
10911 ++getASTContext().NumImplicitMoveConstructors;
10912
10914 ClassDecl->hasInheritedConstructor())
10916 }
10917
10918 if (ClassDecl->needsImplicitCopyAssignment()) {
10919 ++getASTContext().NumImplicitCopyAssignmentOperators;
10920
10921 // If we have a dynamic class, then the copy assignment operator may be
10922 // virtual, so we have to declare it immediately. This ensures that, e.g.,
10923 // it shows up in the right place in the vtable and that we diagnose
10924 // problems with the implicit exception specification.
10925 if (ClassDecl->isDynamicClass() ||
10927 ClassDecl->hasInheritedAssignment())
10929 }
10930
10931 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
10932 ++getASTContext().NumImplicitMoveAssignmentOperators;
10933
10934 // Likewise for the move assignment operator.
10935 if (ClassDecl->isDynamicClass() ||
10937 ClassDecl->hasInheritedAssignment())
10939 }
10940
10941 if (ClassDecl->needsImplicitDestructor()) {
10942 ++getASTContext().NumImplicitDestructors;
10943
10944 // If we have a dynamic class, then the destructor may be virtual, so we
10945 // have to declare the destructor immediately. This ensures that, e.g., it
10946 // shows up in the right place in the vtable and that we diagnose problems
10947 // with the implicit exception specification.
10948 if (ClassDecl->isDynamicClass() ||
10950 DeclareImplicitDestructor(ClassDecl);
10951 }
10952 }
10953
10954 // C++2a [class.compare.default]p3:
10955 // If the member-specification does not explicitly declare any member or
10956 // friend named operator==, an == operator function is declared implicitly
10957 // for each defaulted three-way comparison operator function defined in
10958 // the member-specification
10959 // FIXME: Consider doing this lazily.
10960 // We do this during the initial parse for a class template, not during
10961 // instantiation, so that we can handle unqualified lookups for 'operator=='
10962 // when parsing the template.
10964 llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships;
10966 DefaultedSpaceships);
10967 for (auto *FD : DefaultedSpaceships)
10968 DeclareImplicitEqualityComparison(ClassDecl, FD);
10969 }
10970}
10971
10972unsigned
10974 llvm::function_ref<Scope *()> EnterScope) {
10975 if (!D)
10976 return 0;
10978
10979 // In order to get name lookup right, reenter template scopes in order from
10980 // outermost to innermost.
10982 DeclContext *LookupDC = dyn_cast<DeclContext>(D);
10983
10984 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
10985 for (TemplateParameterList *TPL : DD->getTemplateParameterLists())
10986 ParameterLists.push_back(TPL);
10987
10988 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
10989 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
10990 ParameterLists.push_back(FTD->getTemplateParameters());
10991 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
10992 LookupDC = VD->getDeclContext();
10993
10995 ParameterLists.push_back(VTD->getTemplateParameters());
10996 else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D))
10997 ParameterLists.push_back(PSD->getTemplateParameters());
10998 }
10999 } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
11000 for (TemplateParameterList *TPL : TD->getTemplateParameterLists())
11001 ParameterLists.push_back(TPL);
11002
11003 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
11005 ParameterLists.push_back(CTD->getTemplateParameters());
11006 else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
11007 ParameterLists.push_back(PSD->getTemplateParameters());
11008 }
11009 }
11010 // FIXME: Alias declarations and concepts.
11011
11012 unsigned Count = 0;
11013 Scope *InnermostTemplateScope = nullptr;
11014 for (TemplateParameterList *Params : ParameterLists) {
11015 // Ignore explicit specializations; they don't contribute to the template
11016 // depth.
11017 if (Params->size() == 0)
11018 continue;
11019
11020 InnermostTemplateScope = EnterScope();
11021 for (NamedDecl *Param : *Params) {
11022 if (Param->getDeclName()) {
11023 InnermostTemplateScope->AddDecl(Param);
11024 IdResolver.AddDecl(Param);
11025 }
11026 }
11027 ++Count;
11028 }
11029
11030 // Associate the new template scopes with the corresponding entities.
11031 if (InnermostTemplateScope) {
11032 assert(LookupDC && "no enclosing DeclContext for template lookup");
11033 EnterTemplatedContext(InnermostTemplateScope, LookupDC);
11034 }
11035
11036 return Count;
11037}
11038
11040 if (!RecordD) return;
11041 AdjustDeclIfTemplate(RecordD);
11044}
11045
11047 if (!RecordD) return;
11049}
11050
11052 if (!Param)
11053 return;
11054
11055 S->AddDecl(Param);
11056 if (Param->getDeclName())
11057 IdResolver.AddDecl(Param);
11058}
11059
11062
11063/// ActOnDelayedCXXMethodParameter - We've already started a delayed
11064/// C++ method declaration. We're (re-)introducing the given
11065/// function parameter into scope for use in parsing later parts of
11066/// the method declaration. For example, we could see an
11067/// ActOnParamDefaultArgument event for this parameter.
11069 if (!ParamD)
11070 return;
11071
11072 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
11073
11074 S->AddDecl(Param);
11075 if (Param->getDeclName())
11076 IdResolver.AddDecl(Param);
11077}
11078
11080 if (!MethodD)
11081 return;
11082
11083 AdjustDeclIfTemplate(MethodD);
11084
11086
11087 // Now that we have our default arguments, check the constructor
11088 // again. It could produce additional diagnostics or affect whether
11089 // the class has implicitly-declared destructors, among other
11090 // things.
11091 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
11093
11094 // Check the default arguments, which we may have added.
11095 if (!Method->isInvalidDecl())
11097}
11098
11099// Emit the given diagnostic for each non-address-space qualifier.
11100// Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
11101static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
11103 if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
11104 bool DiagOccurred = false;
11106 [DiagID, &S, &DiagOccurred](DeclSpec::TQ, StringRef QualName,
11107 SourceLocation SL) {
11108 // This diagnostic should be emitted on any qualifier except an addr
11109 // space qualifier. However, forEachQualifier currently doesn't visit
11110 // addr space qualifiers, so there's no way to write this condition
11111 // right now; we just diagnose on everything.
11112 S.Diag(SL, DiagID) << QualName << SourceRange(SL);
11113 DiagOccurred = true;
11114 });
11115 if (DiagOccurred)
11116 D.setInvalidType();
11117 }
11118}
11119
11121 unsigned Kind) {
11122 if (D.isInvalidType() || D.getNumTypeObjects() <= 1)
11123 return;
11124
11126 if (Chunk.Kind == DeclaratorChunk::Paren ||
11128 return;
11129
11130 SourceLocation PointerLoc = Chunk.getSourceRange().getBegin();
11131 S.Diag(PointerLoc, diag::err_invalid_ctor_dtor_decl)
11132 << Kind << Chunk.getSourceRange();
11133 D.setInvalidType();
11134}
11135
11137 StorageClass &SC) {
11138 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
11139
11140 // C++ [class.ctor]p3:
11141 // A constructor shall not be virtual (10.3) or static (9.4). A
11142 // constructor can be invoked for a const, volatile or const
11143 // volatile object. A constructor shall not be declared const,
11144 // volatile, or const volatile (9.3.2).
11145 if (isVirtual) {
11146 if (!D.isInvalidType())
11147 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
11148 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
11150 D.setInvalidType();
11151 }
11152 if (SC == SC_Static) {
11153 if (!D.isInvalidType())
11154 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
11155 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
11157 D.setInvalidType();
11158 SC = SC_None;
11159 }
11160
11161 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
11163 diag::err_constructor_return_type, TypeQuals, SourceLocation(),
11167 D.setInvalidType();
11168 }
11169
11170 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor);
11171 diagnoseInvalidDeclaratorChunks(*this, D, /*constructor*/ 0);
11172
11173 // C++0x [class.ctor]p4:
11174 // A constructor shall not be declared with a ref-qualifier.
11176 if (FTI.hasRefQualifier()) {
11177 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
11180 D.setInvalidType();
11181 }
11182
11183 // Rebuild the function type "R" without any type qualifiers (in
11184 // case any of the errors above fired) and with "void" as the
11185 // return type, since constructors don't have return types.
11186 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
11187 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
11188 return R;
11189
11191 EPI.TypeQuals = Qualifiers();
11192 EPI.RefQualifier = RQ_None;
11193
11194 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
11195}
11196
11198 CXXRecordDecl *ClassDecl
11199 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
11200 if (!ClassDecl)
11201 return Constructor->setInvalidDecl();
11202
11203 // C++ [class.copy]p3:
11204 // A declaration of a constructor for a class X is ill-formed if
11205 // its first parameter is of type (optionally cv-qualified) X and
11206 // either there are no other parameters or else all other
11207 // parameters have default arguments.
11208 if (!Constructor->isInvalidDecl() &&
11209 Constructor->hasOneParamOrDefaultArgs() &&
11210 !Constructor->isFunctionTemplateSpecialization()) {
11211 CanQualType ParamType =
11212 Constructor->getParamDecl(0)->getType()->getCanonicalTypeUnqualified();
11213 CanQualType ClassTy = Context.getCanonicalTagType(ClassDecl);
11214 if (ParamType == ClassTy) {
11215 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
11216 const char *ConstRef
11217 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
11218 : " const &";
11219 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
11220 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
11221
11222 // FIXME: Rather that making the constructor invalid, we should endeavor
11223 // to fix the type.
11224 Constructor->setInvalidDecl();
11225 }
11226 }
11227}
11228
11230 CXXRecordDecl *RD = Destructor->getParent();
11231
11232 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
11233 SourceLocation Loc;
11234
11235 if (!Destructor->isImplicit())
11236 Loc = Destructor->getLocation();
11237 else
11238 Loc = RD->getLocation();
11239
11240 DeclarationName Name =
11241 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
11242 // If we have a virtual destructor, look up the deallocation function
11244 Loc, RD, /*Diagnose=*/true, /*LookForGlobal=*/false, Name)) {
11245 Expr *ThisArg = nullptr;
11246
11247 // If the notional 'delete this' expression requires a non-trivial
11248 // conversion from 'this' to the type of a destroying operator delete's
11249 // first parameter, perform that conversion now.
11250 if (OperatorDelete->isDestroyingOperatorDelete()) {
11251 unsigned AddressParamIndex = 0;
11252 if (OperatorDelete->isTypeAwareOperatorNewOrDelete())
11253 ++AddressParamIndex;
11254 QualType ParamType =
11255 OperatorDelete->getParamDecl(AddressParamIndex)->getType();
11256 if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
11257 // C++ [class.dtor]p13:
11258 // ... as if for the expression 'delete this' appearing in a
11259 // non-virtual destructor of the destructor's class.
11260 ContextRAII SwitchContext(*this, Destructor);
11262 OperatorDelete->getParamDecl(AddressParamIndex)->getLocation());
11263 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
11264 This = PerformImplicitConversion(This.get(), ParamType,
11266 if (This.isInvalid()) {
11267 // FIXME: Register this as a context note so that it comes out
11268 // in the right order.
11269 Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
11270 return true;
11271 }
11272 ThisArg = This.get();
11273 }
11274 }
11275
11276 DiagnoseUseOfDecl(OperatorDelete, Loc);
11277 MarkFunctionReferenced(Loc, OperatorDelete);
11278 Destructor->setOperatorDelete(OperatorDelete, ThisArg);
11279
11280 if (isa<CXXMethodDecl>(OperatorDelete) &&
11281 Context.getTargetInfo().callGlobalDeleteInDeletingDtor(
11282 Context.getLangOpts())) {
11283 // In Microsoft ABI whenever a class has a defined operator delete,
11284 // scalar deleting destructors check the 3rd bit of the implicit
11285 // parameter and if it is set, then, global operator delete must be
11286 // called instead of the class-specific one. Find and save the global
11287 // operator delete for that case. Do not diagnose at this point because
11288 // the lack of a global operator delete is not an error if there are no
11289 // delete calls that require it.
11290 FunctionDecl *GlobalOperatorDelete =
11291 FindDeallocationFunctionForDestructor(Loc, RD, /*Diagnose*/ false,
11292 /*LookForGlobal*/ true, Name);
11293 if (GlobalOperatorDelete) {
11294 MarkFunctionReferenced(Loc, GlobalOperatorDelete);
11295 Destructor->setOperatorGlobalDelete(GlobalOperatorDelete);
11296 }
11297 }
11298
11299 if (Context.getTargetInfo().emitVectorDeletingDtors(
11300 Context.getLangOpts())) {
11301 bool DestructorIsExported = Destructor->hasAttr<DLLExportAttr>();
11302 // Lookup delete[] too in case we have to emit a vector deleting dtor.
11303 DeclarationName VDeleteName =
11304 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
11306 Loc, RD, /*Diagnose*/ false,
11307 /*LookForGlobal*/ false, VDeleteName);
11308 if (ArrOperatorDelete && isa<CXXMethodDecl>(ArrOperatorDelete)) {
11309 FunctionDecl *GlobalArrOperatorDelete =
11310 FindDeallocationFunctionForDestructor(Loc, RD, /*Diagnose*/ false,
11311 /*LookForGlobal*/ true,
11312 VDeleteName);
11313 Destructor->setGlobalOperatorArrayDelete(GlobalArrOperatorDelete);
11314 if (GlobalArrOperatorDelete &&
11315 (Context.classMaybeNeedsVectorDeletingDestructor(RD) ||
11316 DestructorIsExported))
11317 MarkFunctionReferenced(Loc, GlobalArrOperatorDelete);
11318 } else if (!ArrOperatorDelete) {
11319 ArrOperatorDelete = FindDeallocationFunctionForDestructor(
11320 Loc, RD, /*Diagnose*/ false,
11321 /*LookForGlobal*/ true, VDeleteName);
11322 }
11323 Destructor->setOperatorArrayDelete(ArrOperatorDelete);
11324 if (ArrOperatorDelete &&
11325 (Context.classMaybeNeedsVectorDeletingDestructor(RD) ||
11326 DestructorIsExported))
11327 MarkFunctionReferenced(Loc, ArrOperatorDelete);
11328 }
11329 }
11330 }
11331
11332 return false;
11333}
11334
11336 StorageClass& SC) {
11337 // C++ [class.dtor]p1:
11338 // [...] A typedef-name that names a class is a class-name
11339 // (7.1.3); however, a typedef-name that names a class shall not
11340 // be used as the identifier in the declarator for a destructor
11341 // declaration.
11342 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
11343 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
11344 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
11345 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
11346 else if (const TemplateSpecializationType *TST =
11347 DeclaratorType->getAs<TemplateSpecializationType>())
11348 if (TST->isTypeAlias())
11349 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
11350 << DeclaratorType << 1;
11351
11352 // C++ [class.dtor]p2:
11353 // A destructor is used to destroy objects of its class type. A
11354 // destructor takes no parameters, and no return type can be
11355 // specified for it (not even void). The address of a destructor
11356 // shall not be taken. A destructor shall not be static. A
11357 // destructor can be invoked for a const, volatile or const
11358 // volatile object. A destructor shall not be declared const,
11359 // volatile or const volatile (9.3.2).
11360 if (SC == SC_Static) {
11361 if (!D.isInvalidType())
11362 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
11363 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
11366
11367 SC = SC_None;
11368 }
11369 if (!D.isInvalidType()) {
11370 // Destructors don't have return types, but the parser will
11371 // happily parse something like:
11372 //
11373 // class X {
11374 // float ~X();
11375 // };
11376 //
11377 // The return type will be eliminated later.
11378 if (D.getDeclSpec().hasTypeSpecifier())
11379 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
11382 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
11383 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
11389 D.setInvalidType();
11390 }
11391 }
11392
11393 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor);
11394 diagnoseInvalidDeclaratorChunks(*this, D, /*destructor*/ 1);
11395
11396 // C++0x [class.dtor]p2:
11397 // A destructor shall not be declared with a ref-qualifier.
11399 if (FTI.hasRefQualifier()) {
11400 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
11403 D.setInvalidType();
11404 }
11405
11406 // Make sure we don't have any parameters.
11407 if (FTIHasNonVoidParameters(FTI)) {
11408 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
11409
11410 // Delete the parameters.
11411 FTI.freeParams();
11412 D.setInvalidType();
11413 }
11414
11415 // Make sure the destructor isn't variadic.
11416 if (FTI.isVariadic) {
11417 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
11418 D.setInvalidType();
11419 }
11420
11421 // Rebuild the function type "R" without any type qualifiers or
11422 // parameters (in case any of the errors above fired) and with
11423 // "void" as the return type, since destructors don't have return
11424 // types.
11425 if (!D.isInvalidType())
11426 return R;
11427
11428 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
11430 EPI.Variadic = false;
11431 EPI.TypeQuals = Qualifiers();
11432 EPI.RefQualifier = RQ_None;
11433 return Context.getFunctionType(Context.VoidTy, {}, EPI);
11434}
11435
11436static void extendLeft(SourceRange &R, SourceRange Before) {
11437 if (Before.isInvalid())
11438 return;
11439 R.setBegin(Before.getBegin());
11440 if (R.getEnd().isInvalid())
11441 R.setEnd(Before.getEnd());
11442}
11443
11444static void extendRight(SourceRange &R, SourceRange After) {
11445 if (After.isInvalid())
11446 return;
11447 if (R.getBegin().isInvalid())
11448 R.setBegin(After.getBegin());
11449 R.setEnd(After.getEnd());
11450}
11451
11453 StorageClass& SC) {
11454 // C++ [class.conv.fct]p1:
11455 // Neither parameter types nor return type can be specified. The
11456 // type of a conversion function (8.3.5) is "function taking no
11457 // parameter returning conversion-type-id."
11458 if (SC == SC_Static) {
11459 if (!D.isInvalidType())
11460 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
11462 << D.getName().getSourceRange();
11463 D.setInvalidType();
11464 SC = SC_None;
11465 }
11466
11467 TypeSourceInfo *ConvTSI = nullptr;
11468 QualType ConvType =
11470
11471 const DeclSpec &DS = D.getDeclSpec();
11472 if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
11473 // Conversion functions don't have return types, but the parser will
11474 // happily parse something like:
11475 //
11476 // class X {
11477 // float operator bool();
11478 // };
11479 //
11480 // The return type will be changed later anyway.
11481 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
11484 D.setInvalidType();
11485 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
11486 // It's also plausible that the user writes type qualifiers in the wrong
11487 // place, such as:
11488 // struct S { const operator int(); };
11489 // FIXME: we could provide a fixit to move the qualifiers onto the
11490 // conversion type.
11491 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
11492 << SourceRange(D.getIdentifierLoc()) << 0;
11493 D.setInvalidType();
11494 }
11495 const auto *Proto = R->castAs<FunctionProtoType>();
11496 // Make sure we don't have any parameters.
11498 unsigned NumParam = Proto->getNumParams();
11499
11500 // [C++2b]
11501 // A conversion function shall have no non-object parameters.
11502 if (NumParam == 1) {
11504 if (const auto *First =
11505 dyn_cast_if_present<ParmVarDecl>(FTI.Params[0].Param);
11506 First && First->isExplicitObjectParameter())
11507 NumParam--;
11508 }
11509
11510 if (NumParam != 0) {
11511 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
11512 // Delete the parameters.
11513 FTI.freeParams();
11514 D.setInvalidType();
11515 } else if (Proto->isVariadic()) {
11516 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
11517 D.setInvalidType();
11518 }
11519
11520 // Diagnose "&operator bool()" and other such nonsense. This
11521 // is actually a gcc extension which we don't support.
11522 if (Proto->getReturnType() != ConvType) {
11523 bool NeedsTypedef = false;
11524 SourceRange Before, After;
11525
11526 // Walk the chunks and extract information on them for our diagnostic.
11527 bool PastFunctionChunk = false;
11528 for (auto &Chunk : D.type_objects()) {
11529 switch (Chunk.Kind) {
11531 if (!PastFunctionChunk) {
11532 if (Chunk.Fun.HasTrailingReturnType) {
11533 TypeSourceInfo *TRT = nullptr;
11534 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
11535 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
11536 }
11537 PastFunctionChunk = true;
11538 break;
11539 }
11540 [[fallthrough]];
11542 NeedsTypedef = true;
11543 extendRight(After, Chunk.getSourceRange());
11544 break;
11545
11551 extendLeft(Before, Chunk.getSourceRange());
11552 break;
11553
11555 extendLeft(Before, Chunk.Loc);
11556 extendRight(After, Chunk.EndLoc);
11557 break;
11558 }
11559 }
11560
11561 SourceLocation Loc = Before.isValid() ? Before.getBegin() :
11562 After.isValid() ? After.getBegin() :
11563 D.getIdentifierLoc();
11564 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
11565 DB << Before << After;
11566
11567 if (!NeedsTypedef) {
11568 DB << /*don't need a typedef*/0;
11569
11570 // If we can provide a correct fix-it hint, do so.
11571 if (After.isInvalid() && ConvTSI) {
11572 SourceLocation InsertLoc =
11574 DB << FixItHint::CreateInsertion(InsertLoc, " ")
11576 InsertLoc, CharSourceRange::getTokenRange(Before))
11577 << FixItHint::CreateRemoval(Before);
11578 }
11579 } else if (!Proto->getReturnType()->isDependentType()) {
11580 DB << /*typedef*/1 << Proto->getReturnType();
11581 } else if (getLangOpts().CPlusPlus11) {
11582 DB << /*alias template*/2 << Proto->getReturnType();
11583 } else {
11584 DB << /*might not be fixable*/3;
11585 }
11586
11587 // Recover by incorporating the other type chunks into the result type.
11588 // Note, this does *not* change the name of the function. This is compatible
11589 // with the GCC extension:
11590 // struct S { &operator int(); } s;
11591 // int &r = s.operator int(); // ok in GCC
11592 // S::operator int&() {} // error in GCC, function name is 'operator int'.
11593 ConvType = Proto->getReturnType();
11594 }
11595
11596 // C++ [class.conv.fct]p4:
11597 // The conversion-type-id shall not represent a function type nor
11598 // an array type.
11599 if (ConvType->isArrayType()) {
11600 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
11601 ConvType = Context.getPointerType(ConvType);
11602 D.setInvalidType();
11603 } else if (ConvType->isFunctionType()) {
11604 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
11605 ConvType = Context.getPointerType(ConvType);
11606 D.setInvalidType();
11607 }
11608
11609 // Rebuild the function type "R" without any parameters (in case any
11610 // of the errors above fired) and with the conversion type as the
11611 // return type.
11612 if (D.isInvalidType())
11613 R = Context.getFunctionType(ConvType, {}, Proto->getExtProtoInfo());
11614
11615 // C++0x explicit conversion operators.
11619 ? diag::warn_cxx98_compat_explicit_conversion_functions
11620 : diag::ext_explicit_conversion_functions)
11622}
11623
11625 assert(Conversion && "Expected to receive a conversion function declaration");
11626
11627 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
11628
11629 // Make sure we aren't redeclaring the conversion function.
11630 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
11631 // C++ [class.conv.fct]p1:
11632 // [...] A conversion function is never used to convert a
11633 // (possibly cv-qualified) object to the (possibly cv-qualified)
11634 // same object type (or a reference to it), to a (possibly
11635 // cv-qualified) base class of that type (or a reference to it),
11636 // or to (possibly cv-qualified) void.
11637 CanQualType ClassType = Context.getCanonicalTagType(ClassDecl);
11638 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
11639 ConvType = ConvTypeRef->getPointeeType();
11640 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
11642 /* Suppress diagnostics for instantiations. */;
11643 else if (Conversion->size_overridden_methods() != 0)
11644 /* Suppress diagnostics for overriding virtual function in a base class. */;
11645 else if (ConvType->isRecordType()) {
11646 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
11647 if (ConvType == ClassType)
11648 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
11649 << ClassType;
11650 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
11651 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
11652 << ClassType << ConvType;
11653 } else if (ConvType->isVoidType()) {
11654 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
11655 << ClassType << ConvType;
11656 }
11657
11658 if (FunctionTemplateDecl *ConversionTemplate =
11659 Conversion->getDescribedFunctionTemplate()) {
11660 if (const auto *ConvTypePtr = ConvType->getAs<PointerType>()) {
11661 ConvType = ConvTypePtr->getPointeeType();
11662 }
11663 if (ConvType->isUndeducedAutoType()) {
11664 Diag(Conversion->getTypeSpecStartLoc(), diag::err_auto_not_allowed)
11665 << getReturnTypeLoc(Conversion).getSourceRange()
11666 << ConvType->castAs<AutoType>()->getKeyword()
11667 << /* in declaration of conversion function template= */ 24;
11668 }
11669
11670 return ConversionTemplate;
11671 }
11672
11673 return Conversion;
11674}
11675
11680
11684
11686 DeclarationName Name, QualType R,
11687 bool IsLambda, DeclContext *DC) {
11688 if (!D.isFunctionDeclarator())
11689 return;
11690
11692 if (FTI.NumParams == 0)
11693 return;
11694 ParmVarDecl *ExplicitObjectParam = nullptr;
11695 for (unsigned Idx = 0; Idx < FTI.NumParams; Idx++) {
11696 const auto &ParamInfo = FTI.Params[Idx];
11697 if (!ParamInfo.Param)
11698 continue;
11699 ParmVarDecl *Param = cast<ParmVarDecl>(ParamInfo.Param);
11700 if (!Param->isExplicitObjectParameter())
11701 continue;
11702 if (Idx == 0) {
11703 ExplicitObjectParam = Param;
11704 continue;
11705 } else {
11706 Diag(Param->getLocation(),
11707 diag::err_explicit_object_parameter_must_be_first)
11708 << IsLambda << Param->getSourceRange();
11709 }
11710 }
11711 if (!ExplicitObjectParam)
11712 return;
11713
11714 if (ExplicitObjectParam->hasDefaultArg()) {
11715 Diag(ExplicitObjectParam->getLocation(),
11716 diag::err_explicit_object_default_arg)
11717 << ExplicitObjectParam->getSourceRange();
11718 D.setInvalidType();
11719 }
11720
11723 D.isStaticMember())) {
11724 Diag(ExplicitObjectParam->getBeginLoc(),
11725 diag::err_explicit_object_parameter_nonmember)
11726 << D.getSourceRange() << /*static=*/0 << IsLambda;
11727 D.setInvalidType();
11728 }
11729
11730 if (D.getDeclSpec().isVirtualSpecified()) {
11731 Diag(ExplicitObjectParam->getBeginLoc(),
11732 diag::err_explicit_object_parameter_nonmember)
11733 << D.getSourceRange() << /*virtual=*/1 << IsLambda;
11734 D.setInvalidType();
11735 }
11736
11737 // Friend declarations require some care. Consider:
11738 //
11739 // namespace N {
11740 // struct A{};
11741 // int f(A);
11742 // }
11743 //
11744 // struct S {
11745 // struct T {
11746 // int f(this T);
11747 // };
11748 //
11749 // friend int T::f(this T); // Allow this.
11750 // friend int f(this S); // But disallow this.
11751 // friend int N::f(this A); // And disallow this.
11752 // };
11753 //
11754 // Here, it seems to suffice to check whether the scope
11755 // specifier designates a class type.
11756 if (D.getDeclSpec().isFriendSpecified() &&
11757 !isa_and_present<CXXRecordDecl>(
11759 Diag(ExplicitObjectParam->getBeginLoc(),
11760 diag::err_explicit_object_parameter_nonmember)
11761 << D.getSourceRange() << /*non-member=*/2 << IsLambda;
11762 D.setInvalidType();
11763 }
11764
11765 if (IsLambda && FTI.hasMutableQualifier()) {
11766 Diag(ExplicitObjectParam->getBeginLoc(),
11767 diag::err_explicit_object_parameter_mutable)
11768 << D.getSourceRange();
11769 }
11770
11771 if (IsLambda)
11772 return;
11773
11774 if (!DC || !DC->isRecord()) {
11775 assert(D.isInvalidType() && "Explicit object parameter in non-member "
11776 "should have been diagnosed already");
11777 return;
11778 }
11779
11780 // CWG2674: constructors and destructors cannot have explicit parameters.
11783 Diag(ExplicitObjectParam->getBeginLoc(),
11784 diag::err_explicit_object_parameter_constructor)
11786 << D.getSourceRange();
11787 D.setInvalidType();
11788 }
11789}
11790
11791namespace {
11792/// Utility class to accumulate and print a diagnostic listing the invalid
11793/// specifier(s) on a declaration.
11794struct BadSpecifierDiagnoser {
11795 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
11796 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
11797 ~BadSpecifierDiagnoser() {
11798 Diagnostic << Specifiers;
11799 }
11800
11801 template<typename T> void check(SourceLocation SpecLoc, T Spec) {
11802 return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
11803 }
11804 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
11805 return check(SpecLoc,
11807 }
11808 void check(SourceLocation SpecLoc, const char *Spec) {
11809 if (SpecLoc.isInvalid()) return;
11810 Diagnostic << SourceRange(SpecLoc, SpecLoc);
11811 if (!Specifiers.empty()) Specifiers += " ";
11812 Specifiers += Spec;
11813 }
11814
11815 Sema &S;
11816 Sema::SemaDiagnosticBuilder Diagnostic;
11817 std::string Specifiers;
11818};
11819}
11820
11822 StorageClass &SC) {
11823 TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
11824 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
11825 assert(GuidedTemplateDecl && "missing template decl for deduction guide");
11826
11827 // C++ [temp.deduct.guide]p3:
11828 // A deduction-gide shall be declared in the same scope as the
11829 // corresponding class template.
11830 if (!CurContext->getRedeclContext()->Equals(
11831 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
11832 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
11833 << GuidedTemplateDecl;
11834 NoteTemplateLocation(*GuidedTemplateDecl);
11835 }
11836
11837 auto &DS = D.getMutableDeclSpec();
11838 // We leave 'friend' and 'virtual' to be rejected in the normal way.
11839 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
11840 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
11841 DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
11842 BadSpecifierDiagnoser Diagnoser(
11843 *this, D.getIdentifierLoc(),
11844 diag::err_deduction_guide_invalid_specifier);
11845
11846 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
11847 DS.ClearStorageClassSpecs();
11848 SC = SC_None;
11849
11850 // 'explicit' is permitted.
11851 Diagnoser.check(DS.getInlineSpecLoc(), "inline");
11852 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
11853 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
11854 DS.ClearConstexprSpec();
11855
11856 Diagnoser.check(DS.getConstSpecLoc(), "const");
11857 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
11858 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
11859 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
11860 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
11861 DS.ClearTypeQualifiers();
11862
11863 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
11864 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
11865 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
11866 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
11867 DS.ClearTypeSpecType();
11868 }
11869
11870 if (D.isInvalidType())
11871 return true;
11872
11873 // Check the declarator is simple enough.
11874 bool FoundFunction = false;
11875 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
11876 if (Chunk.Kind == DeclaratorChunk::Paren)
11877 continue;
11878 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
11880 diag::err_deduction_guide_with_complex_decl)
11881 << D.getSourceRange();
11882 break;
11883 }
11884 if (!Chunk.Fun.hasTrailingReturnType())
11885 return Diag(D.getName().getBeginLoc(),
11886 diag::err_deduction_guide_no_trailing_return_type);
11887
11888 // Check that the return type is written as a specialization of
11889 // the template specified as the deduction-guide's name.
11890 // The template name may not be qualified. [temp.deduct.guide]
11891 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
11892 TypeSourceInfo *TSI = nullptr;
11893 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
11894 assert(TSI && "deduction guide has valid type but invalid return type?");
11895 bool AcceptableReturnType = false;
11896 bool MightInstantiateToSpecialization = false;
11897 if (auto RetTST =
11899 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
11900 bool TemplateMatches = Context.hasSameTemplateName(
11901 SpecifiedName, GuidedTemplate, /*IgnoreDeduced=*/true);
11902
11904 SpecifiedName.getAsQualifiedTemplateName();
11905 // A Template template parameter is never wrapped in a
11906 // QualifiedTemplateName, but it's always simply-written.
11907 bool SimplyWritten = !Qualifiers || (!Qualifiers->hasTemplateKeyword() &&
11908 !Qualifiers->getQualifier());
11909 if (SimplyWritten && TemplateMatches)
11910 AcceptableReturnType = true;
11911 else {
11912 // This could still instantiate to the right type, unless we know it
11913 // names the wrong class template.
11914 auto *TD = SpecifiedName.getAsTemplateDecl();
11915 MightInstantiateToSpecialization =
11916 !(TD && isa<ClassTemplateDecl>(TD) && !TemplateMatches);
11917 }
11918 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
11919 MightInstantiateToSpecialization = true;
11920 }
11921
11922 if (!AcceptableReturnType)
11923 return Diag(TSI->getTypeLoc().getBeginLoc(),
11924 diag::err_deduction_guide_bad_trailing_return_type)
11925 << GuidedTemplate << TSI->getType()
11926 << MightInstantiateToSpecialization
11927 << TSI->getTypeLoc().getSourceRange();
11928
11929 // Keep going to check that we don't have any inner declarator pieces (we
11930 // could still have a function returning a pointer to a function).
11931 FoundFunction = true;
11932 }
11933
11934 if (D.isFunctionDefinition())
11935 // we can still create a valid deduction guide here.
11936 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
11937 return false;
11938}
11939
11940//===----------------------------------------------------------------------===//
11941// Namespace Handling
11942//===----------------------------------------------------------------------===//
11943
11944/// Diagnose a mismatch in 'inline' qualifiers when a namespace is
11945/// reopened.
11947 SourceLocation Loc,
11948 IdentifierInfo *II, bool *IsInline,
11949 NamespaceDecl *PrevNS) {
11950 assert(*IsInline != PrevNS->isInline());
11951
11952 // 'inline' must appear on the original definition, but not necessarily
11953 // on all extension definitions, so the note should point to the first
11954 // definition to avoid confusion.
11955 PrevNS = PrevNS->getFirstDecl();
11956
11957 if (PrevNS->isInline())
11958 // The user probably just forgot the 'inline', so suggest that it
11959 // be added back.
11960 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
11961 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
11962 else
11963 S.Diag(Loc, diag::err_inline_namespace_mismatch);
11964
11965 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
11966 *IsInline = PrevNS->isInline();
11967}
11968
11969/// ActOnStartNamespaceDef - This is called at the start of a namespace
11970/// definition.
11972 SourceLocation InlineLoc,
11973 SourceLocation NamespaceLoc,
11974 SourceLocation IdentLoc, IdentifierInfo *II,
11975 SourceLocation LBrace,
11976 const ParsedAttributesView &AttrList,
11977 UsingDirectiveDecl *&UD, bool IsNested) {
11978 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
11979 // For anonymous namespace, take the location of the left brace.
11980 SourceLocation Loc = II ? IdentLoc : LBrace;
11981 bool IsInline = InlineLoc.isValid();
11982 bool IsInvalid = false;
11983 bool IsStd = false;
11984 bool AddToKnown = false;
11985 Scope *DeclRegionScope = NamespcScope->getParent();
11986
11987 NamespaceDecl *PrevNS = nullptr;
11988 if (II) {
11989 // C++ [namespace.std]p7:
11990 // A translation unit shall not declare namespace std to be an inline
11991 // namespace (9.8.2).
11992 //
11993 // Precondition: the std namespace is in the file scope and is declared to
11994 // be inline
11995 auto DiagnoseInlineStdNS = [&]() {
11996 assert(IsInline && II->isStr("std") &&
11997 CurContext->getRedeclContext()->isTranslationUnit() &&
11998 "Precondition of DiagnoseInlineStdNS not met");
11999 Diag(InlineLoc, diag::err_inline_namespace_std)
12000 << SourceRange(InlineLoc, InlineLoc.getLocWithOffset(6));
12001 IsInline = false;
12002 };
12003 // C++ [namespace.def]p2:
12004 // The identifier in an original-namespace-definition shall not
12005 // have been previously defined in the declarative region in
12006 // which the original-namespace-definition appears. The
12007 // identifier in an original-namespace-definition is the name of
12008 // the namespace. Subsequently in that declarative region, it is
12009 // treated as an original-namespace-name.
12010 //
12011 // Since namespace names are unique in their scope, and we don't
12012 // look through using directives, just look for any ordinary names
12013 // as if by qualified name lookup.
12014 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
12016 LookupQualifiedName(R, CurContext->getRedeclContext());
12017 NamedDecl *PrevDecl =
12018 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
12019 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
12020
12021 if (PrevNS) {
12022 // This is an extended namespace definition.
12023 if (IsInline && II->isStr("std") &&
12024 CurContext->getRedeclContext()->isTranslationUnit())
12025 DiagnoseInlineStdNS();
12026 else if (IsInline != PrevNS->isInline())
12027 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
12028 &IsInline, PrevNS);
12029 } else if (PrevDecl) {
12030 // This is an invalid name redefinition.
12031 Diag(Loc, diag::err_redefinition_different_kind)
12032 << II;
12033 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12034 IsInvalid = true;
12035 // Continue on to push Namespc as current DeclContext and return it.
12036 } else if (II->isStr("std") &&
12037 CurContext->getRedeclContext()->isTranslationUnit()) {
12038 if (IsInline)
12039 DiagnoseInlineStdNS();
12040 // This is the first "real" definition of the namespace "std", so update
12041 // our cache of the "std" namespace to point at this definition.
12042 PrevNS = getStdNamespace();
12043 IsStd = true;
12044 AddToKnown = !IsInline;
12045 } else {
12046 // We've seen this namespace for the first time.
12047 AddToKnown = !IsInline;
12048 }
12049 } else {
12050 // Anonymous namespaces.
12051
12052 // Determine whether the parent already has an anonymous namespace.
12053 DeclContext *Parent = CurContext->getRedeclContext();
12054 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
12055 PrevNS = TU->getAnonymousNamespace();
12056 } else {
12057 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
12058 PrevNS = ND->getAnonymousNamespace();
12059 }
12060
12061 if (PrevNS && IsInline != PrevNS->isInline())
12062 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
12063 &IsInline, PrevNS);
12064 }
12065
12067 Context, CurContext, IsInline, StartLoc, Loc, II, PrevNS, IsNested);
12068 if (IsInvalid)
12069 Namespc->setInvalidDecl();
12070
12071 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
12072 AddPragmaAttributes(DeclRegionScope, Namespc);
12073 ProcessAPINotes(Namespc);
12074
12075 // FIXME: Should we be merging attributes?
12076 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
12078
12079 if (IsStd)
12080 StdNamespace = Namespc;
12081 if (AddToKnown)
12082 KnownNamespaces[Namespc] = false;
12083
12084 if (II) {
12085 PushOnScopeChains(Namespc, DeclRegionScope);
12086 } else {
12087 // Link the anonymous namespace into its parent.
12088 DeclContext *Parent = CurContext->getRedeclContext();
12089 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
12090 TU->setAnonymousNamespace(Namespc);
12091 } else {
12092 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
12093 }
12094
12095 CurContext->addDecl(Namespc);
12096
12097 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
12098 // behaves as if it were replaced by
12099 // namespace unique { /* empty body */ }
12100 // using namespace unique;
12101 // namespace unique { namespace-body }
12102 // where all occurrences of 'unique' in a translation unit are
12103 // replaced by the same identifier and this identifier differs
12104 // from all other identifiers in the entire program.
12105
12106 // We just create the namespace with an empty name and then add an
12107 // implicit using declaration, just like the standard suggests.
12108 //
12109 // CodeGen enforces the "universally unique" aspect by giving all
12110 // declarations semantically contained within an anonymous
12111 // namespace internal linkage.
12112
12113 if (!PrevNS) {
12115 /* 'using' */ LBrace,
12116 /* 'namespace' */ SourceLocation(),
12117 /* qualifier */ NestedNameSpecifierLoc(),
12118 /* identifier */ SourceLocation(),
12119 Namespc,
12120 /* Ancestor */ Parent);
12121 UD->setImplicit();
12122 Parent->addDecl(UD);
12123 }
12124 }
12125
12126 ActOnDocumentableDecl(Namespc);
12127
12128 // Although we could have an invalid decl (i.e. the namespace name is a
12129 // redefinition), push it as current DeclContext and try to continue parsing.
12130 // FIXME: We should be able to push Namespc here, so that the each DeclContext
12131 // for the namespace has the declarations that showed up in that particular
12132 // namespace definition.
12133 PushDeclContext(NamespcScope, Namespc);
12134 return Namespc;
12135}
12136
12137/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
12138/// is a namespace alias, returns the namespace it points to.
12140 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
12141 return AD->getNamespace();
12142 return dyn_cast_or_null<NamespaceDecl>(D);
12143}
12144
12146 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
12147 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
12148 Namespc->setRBraceLoc(RBrace);
12150 if (Namespc->hasAttr<VisibilityAttr>())
12151 PopPragmaVisibility(true, RBrace);
12152 // If this namespace contains an export-declaration, export it now.
12153 if (DeferredExportedNamespaces.erase(Namespc))
12155}
12156
12158 return cast_or_null<CXXRecordDecl>(
12159 StdBadAlloc.get(Context.getExternalSource()));
12160}
12161
12163 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
12164}
12165
12167 return cast_or_null<NamespaceDecl>(
12168 StdNamespace.get(Context.getExternalSource()));
12169}
12170
12171namespace {
12172
12173enum UnsupportedSTLSelect {
12174 USS_InvalidMember,
12175 USS_MissingMember,
12176 USS_NonTrivial,
12177 USS_Other
12178};
12179
12180struct InvalidSTLDiagnoser {
12181 Sema &S;
12182 SourceLocation Loc;
12183 QualType TyForDiags;
12184
12185 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
12186 const VarDecl *VD = nullptr) {
12187 {
12188 auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
12189 << TyForDiags << ((int)Sel);
12190 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
12191 assert(!Name.empty());
12192 D << Name;
12193 }
12194 }
12195 if (Sel == USS_InvalidMember) {
12196 S.Diag(VD->getLocation(), diag::note_var_declared_here)
12197 << VD << VD->getSourceRange();
12198 }
12199 return QualType();
12200 }
12201};
12202} // namespace
12203
12205 SourceLocation Loc,
12207 assert(getLangOpts().CPlusPlus &&
12208 "Looking for comparison category type outside of C++.");
12209
12210 // Use an elaborated type for diagnostics which has a name containing the
12211 // prepended 'std' namespace but not any inline namespace names.
12212 auto TyForDiags = [&](ComparisonCategoryInfo *Info) {
12214 /*Prefix=*/std::nullopt);
12215 return Context.getTagType(ElaboratedTypeKeyword::None, Qualifier,
12216 Info->Record,
12217 /*OwnsTag=*/false);
12218 };
12219
12220 // Check if we've already successfully checked the comparison category type
12221 // before. If so, skip checking it again.
12222 ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
12223 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) {
12224 // The only thing we need to check is that the type has a reachable
12225 // definition in the current context.
12226 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
12227 return QualType();
12228
12229 return Info->getType();
12230 }
12231
12232 // If lookup failed
12233 if (!Info) {
12234 std::string NameForDiags = "std::";
12235 NameForDiags += ComparisonCategories::getCategoryString(Kind);
12236 Diag(Loc, diag::err_implied_comparison_category_type_not_found)
12237 << NameForDiags << (int)Usage;
12238 return QualType();
12239 }
12240
12241 assert(Info->Kind == Kind);
12242 assert(Info->Record);
12243
12244 // Update the Record decl in case we encountered a forward declaration on our
12245 // first pass. FIXME: This is a bit of a hack.
12246 if (Info->Record->hasDefinition())
12247 Info->Record = Info->Record->getDefinition();
12248
12249 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
12250 return QualType();
12251
12252 InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)};
12253
12254 if (!Info->Record->isTriviallyCopyable())
12255 return UnsupportedSTLError(USS_NonTrivial);
12256
12257 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
12258 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
12259 // Tolerate empty base classes.
12260 if (Base->isEmpty())
12261 continue;
12262 // Reject STL implementations which have at least one non-empty base.
12263 return UnsupportedSTLError();
12264 }
12265
12266 // Check that the STL has implemented the types using a single integer field.
12267 // This expectation allows better codegen for builtin operators. We require:
12268 // (1) The class has exactly one field.
12269 // (2) The field is an integral or enumeration type.
12270 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
12271 if (std::distance(FIt, FEnd) != 1 ||
12272 !FIt->getType()->isIntegralOrEnumerationType()) {
12273 return UnsupportedSTLError();
12274 }
12275
12276 // Build each of the require values and store them in Info.
12277 for (ComparisonCategoryResult CCR :
12279 StringRef MemName = ComparisonCategories::getResultString(CCR);
12280 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
12281
12282 if (!ValInfo)
12283 return UnsupportedSTLError(USS_MissingMember, MemName);
12284
12285 VarDecl *VD = ValInfo->VD;
12286 assert(VD && "should not be null!");
12287
12288 // Attempt to diagnose reasons why the STL definition of this type
12289 // might be foobar, including it failing to be a constant expression.
12290 // TODO Handle more ways the lookup or result can be invalid.
12291 if (!VD->isStaticDataMember() ||
12293 return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
12294
12295 // Attempt to evaluate the var decl as a constant expression and extract
12296 // the value of its first field as a ICE. If this fails, the STL
12297 // implementation is not supported.
12298 if (!ValInfo->hasValidIntValue())
12299 return UnsupportedSTLError();
12300
12301 MarkVariableReferenced(Loc, VD);
12302 }
12303
12304 // We've successfully built the required types and expressions. Update
12305 // the cache and return the newly cached value.
12306 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
12307 return Info->getType();
12308}
12309
12311 if (!StdNamespace) {
12312 // The "std" namespace has not yet been defined, so build one implicitly.
12314 Context, Context.getTranslationUnitDecl(),
12315 /*Inline=*/false, SourceLocation(), SourceLocation(),
12316 &PP.getIdentifierTable().get("std"),
12317 /*PrevDecl=*/nullptr, /*Nested=*/false);
12318 getStdNamespace()->setImplicit(true);
12319 // We want the created NamespaceDecl to be available for redeclaration
12320 // lookups, but not for regular name lookups.
12321 Context.getTranslationUnitDecl()->addDecl(getStdNamespace());
12322 getStdNamespace()->clearIdentifierNamespace();
12323 }
12324
12325 return getStdNamespace();
12326}
12327
12328static bool isStdClassTemplate(Sema &S, QualType SugaredType, QualType *TypeArg,
12329 const char *ClassName,
12330 ClassTemplateDecl **CachedDecl,
12331 const Decl **MalformedDecl) {
12332 // We're looking for implicit instantiations of
12333 // template <typename U> class std::{ClassName}.
12334
12335 if (!S.StdNamespace) // If we haven't seen namespace std yet, this can't be
12336 // it.
12337 return false;
12338
12339 auto ReportMatchingNameAsMalformed = [&](NamedDecl *D) {
12340 if (!MalformedDecl)
12341 return;
12342 if (!D)
12343 D = SugaredType->getAsTagDecl();
12344 if (!D || !D->isInStdNamespace())
12345 return;
12346 IdentifierInfo *II = D->getDeclName().getAsIdentifierInfo();
12347 if (II && II == &S.PP.getIdentifierTable().get(ClassName))
12348 *MalformedDecl = D;
12349 };
12350
12351 ClassTemplateDecl *Template = nullptr;
12353 if (const TemplateSpecializationType *TST =
12355 Template = dyn_cast_or_null<ClassTemplateDecl>(
12356 TST->getTemplateName().getAsTemplateDecl());
12357 Arguments = TST->template_arguments();
12358 } else if (const auto *TT = SugaredType->getAs<TagType>()) {
12359 Template = TT->getTemplateDecl();
12360 Arguments = TT->getTemplateArgs(S.Context);
12361 }
12362
12363 if (!Template) {
12364 ReportMatchingNameAsMalformed(SugaredType->getAsTagDecl());
12365 return false;
12366 }
12367
12368 if (!*CachedDecl) {
12369 // Haven't recognized std::{ClassName} yet, maybe this is it.
12370 // FIXME: It seems we should just reuse LookupStdClassTemplate but the
12371 // semantics of this are slightly different, most notably the existing
12372 // "lookup" semantics explicitly diagnose an invalid definition as an
12373 // error.
12374 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
12375 if (TemplateClass->getIdentifier() !=
12376 &S.PP.getIdentifierTable().get(ClassName) ||
12378 TemplateClass->getNonTransparentDeclContext()))
12379 return false;
12380 // This is a template called std::{ClassName}, but is it the right
12381 // template?
12382 TemplateParameterList *Params = Template->getTemplateParameters();
12383 if (Params->getMinRequiredArguments() != 1 ||
12384 !isa<TemplateTypeParmDecl>(Params->getParam(0)) ||
12385 Params->getParam(0)->isTemplateParameterPack()) {
12386 if (MalformedDecl)
12387 *MalformedDecl = TemplateClass;
12388 return false;
12389 }
12390
12391 // It's the right template.
12392 *CachedDecl = Template;
12393 }
12394
12395 if (Template->getCanonicalDecl() != (*CachedDecl)->getCanonicalDecl())
12396 return false;
12397
12398 // This is an instance of std::{ClassName}. Find the argument type.
12399 if (TypeArg) {
12400 QualType ArgType = Arguments[0].getAsType();
12401 // FIXME: Since TST only has as-written arguments, we have to perform the
12402 // only kind of conversion applicable to type arguments; in Objective-C ARC:
12403 // - If an explicitly-specified template argument type is a lifetime type
12404 // with no lifetime qualifier, the __strong lifetime qualifier is
12405 // inferred.
12406 if (S.getLangOpts().ObjCAutoRefCount && ArgType->isObjCLifetimeType() &&
12407 !ArgType.getObjCLifetime()) {
12408 Qualifiers Qs;
12410 ArgType = S.Context.getQualifiedType(ArgType, Qs);
12411 }
12412 *TypeArg = ArgType;
12413 }
12414
12415 return true;
12416}
12417
12419 assert(getLangOpts().CPlusPlus &&
12420 "Looking for std::initializer_list outside of C++.");
12421
12422 // We're looking for implicit instantiations of
12423 // template <typename E> class std::initializer_list.
12424
12425 return isStdClassTemplate(*this, Ty, Element, "initializer_list",
12426 &StdInitializerList, /*MalformedDecl=*/nullptr);
12427}
12428
12430 const Decl **MalformedDecl) {
12431 assert(getLangOpts().CPlusPlus &&
12432 "Looking for std::type_identity outside of C++.");
12433
12434 // We're looking for implicit instantiations of
12435 // template <typename T> struct std::type_identity.
12436
12437 return isStdClassTemplate(*this, Ty, Element, "type_identity",
12438 &StdTypeIdentity, MalformedDecl);
12439}
12440
12442 const char *ClassName,
12443 bool *WasMalformed) {
12444 if (!S.StdNamespace)
12445 return nullptr;
12446
12447 LookupResult Result(S, &S.PP.getIdentifierTable().get(ClassName), Loc,
12450 return nullptr;
12451
12453 if (!Template) {
12454 Result.suppressDiagnostics();
12455 // We found something weird. Complain about the first thing we found.
12456 NamedDecl *Found = *Result.begin();
12457 S.Diag(Found->getLocation(), diag::err_malformed_std_class_template)
12458 << ClassName;
12459 if (WasMalformed)
12460 *WasMalformed = true;
12461 return nullptr;
12462 }
12463
12464 // We found some template with the correct name. Now verify that it's
12465 // correct.
12466 TemplateParameterList *Params = Template->getTemplateParameters();
12467 if (Params->getMinRequiredArguments() != 1 ||
12468 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
12469 S.Diag(Template->getLocation(), diag::err_malformed_std_class_template)
12470 << ClassName;
12471 if (WasMalformed)
12472 *WasMalformed = true;
12473 return nullptr;
12474 }
12475
12476 return Template;
12477}
12478
12480 QualType TypeParam, SourceLocation Loc) {
12481 assert(S.getStdNamespace());
12482 TemplateArgumentListInfo Args(Loc, Loc);
12483 auto TSI = S.Context.getTrivialTypeSourceInfo(TypeParam, Loc);
12484 Args.addArgument(TemplateArgumentLoc(TemplateArgument(TypeParam), TSI));
12485
12487 Loc, Args, /*Scope=*/nullptr,
12488 /*ForNestedNameSpecifier=*/false);
12489}
12490
12492 if (!StdInitializerList) {
12493 bool WasMalformed = false;
12495 LookupStdClassTemplate(*this, Loc, "initializer_list", &WasMalformed);
12496 if (!StdInitializerList) {
12497 if (!WasMalformed)
12498 Diag(Loc, diag::err_implied_std_initializer_list_not_found);
12499 return QualType();
12500 }
12501 }
12502 return BuildStdClassTemplate(*this, StdInitializerList, Element, Loc);
12503}
12504
12506 if (!StdTypeIdentity) {
12507 StdTypeIdentity = LookupStdClassTemplate(*this, Loc, "type_identity",
12508 /*WasMalformed=*/nullptr);
12509 if (!StdTypeIdentity)
12510 return QualType();
12511 }
12512 return BuildStdClassTemplate(*this, StdTypeIdentity, Type, Loc);
12513}
12514
12516 // C++ [dcl.init.list]p2:
12517 // A constructor is an initializer-list constructor if its first parameter
12518 // is of type std::initializer_list<E> or reference to possibly cv-qualified
12519 // std::initializer_list<E> for some type E, and either there are no other
12520 // parameters or else all other parameters have default arguments.
12521 if (!Ctor->hasOneParamOrDefaultArgs())
12522 return false;
12523
12524 QualType ArgType = Ctor->getParamDecl(0)->getType();
12525 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
12526 ArgType = RT->getPointeeType().getUnqualifiedType();
12527
12528 return isStdInitializerList(ArgType, nullptr);
12529}
12530
12531/// Determine whether a using statement is in a context where it will be
12532/// apply in all contexts.
12534 switch (CurContext->getDeclKind()) {
12535 case Decl::TranslationUnit:
12536 return true;
12537 case Decl::LinkageSpec:
12538 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
12539 default:
12540 return false;
12541 }
12542}
12543
12544namespace {
12545
12546// Callback to only accept typo corrections that are namespaces.
12547class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
12548public:
12549 bool ValidateCandidate(const TypoCorrection &candidate) override {
12550 if (NamedDecl *ND = candidate.getCorrectionDecl())
12552 return false;
12553 }
12554
12555 std::unique_ptr<CorrectionCandidateCallback> clone() override {
12556 return std::make_unique<NamespaceValidatorCCC>(*this);
12557 }
12558};
12559
12560}
12561
12562static void DiagnoseInvisibleNamespace(const TypoCorrection &Corrected,
12563 Sema &S) {
12564 auto *ND = cast<NamespaceDecl>(Corrected.getFoundDecl());
12565 Module *M = ND->getOwningModule();
12566 assert(M && "hidden namespace definition not in a module?");
12567
12568 if (M->isExplicitGlobalModule())
12569 S.Diag(Corrected.getCorrectionRange().getBegin(),
12570 diag::err_module_unimported_use_header)
12572 << /*Header Name*/ false;
12573 else
12574 S.Diag(Corrected.getCorrectionRange().getBegin(),
12575 diag::err_module_unimported_use)
12577 << M->getTopLevelModuleName();
12578}
12579
12581 CXXScopeSpec &SS,
12582 SourceLocation IdentLoc,
12583 IdentifierInfo *Ident) {
12584 R.clear();
12585 NamespaceValidatorCCC CCC{};
12586 if (TypoCorrection Corrected =
12587 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
12589 // Generally we find it is confusing more than helpful to diagnose the
12590 // invisible namespace.
12591 // See https://github.com/llvm/llvm-project/issues/73893.
12592 //
12593 // However, we should diagnose when the users are trying to using an
12594 // invisible namespace. So we handle the case specially here.
12595 if (isa_and_nonnull<NamespaceDecl>(Corrected.getFoundDecl()) &&
12596 Corrected.requiresImport()) {
12597 DiagnoseInvisibleNamespace(Corrected, S);
12598 } else if (DeclContext *DC = S.computeDeclContext(SS, false)) {
12599 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
12600 bool DroppedSpecifier =
12601 Corrected.WillReplaceSpecifier() && Ident->getName() == CorrectedStr;
12602 S.diagnoseTypo(Corrected,
12603 S.PDiag(diag::err_using_directive_member_suggest)
12604 << Ident << DC << DroppedSpecifier << SS.getRange(),
12605 S.PDiag(diag::note_namespace_defined_here));
12606 } else {
12607 S.diagnoseTypo(Corrected,
12608 S.PDiag(diag::err_using_directive_suggest) << Ident,
12609 S.PDiag(diag::note_namespace_defined_here));
12610 }
12611 R.addDecl(Corrected.getFoundDecl());
12612 return true;
12613 }
12614 return false;
12615}
12616
12618 SourceLocation NamespcLoc, CXXScopeSpec &SS,
12619 SourceLocation IdentLoc,
12620 IdentifierInfo *NamespcName,
12621 const ParsedAttributesView &AttrList) {
12622 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
12623 assert(NamespcName && "Invalid NamespcName.");
12624 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
12625
12626 // Get the innermost enclosing declaration scope.
12627 S = S->getDeclParent();
12628
12629 UsingDirectiveDecl *UDir = nullptr;
12630 NestedNameSpecifier Qualifier = SS.getScopeRep();
12631
12632 // Lookup namespace name.
12633 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
12634 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
12635 if (R.isAmbiguous())
12636 return nullptr;
12637
12638 if (R.empty()) {
12639 R.clear();
12640 // Allow "using namespace std;" or "using namespace ::std;" even if
12641 // "std" hasn't been defined yet, for GCC compatibility.
12642 if ((!Qualifier ||
12643 Qualifier.getKind() == NestedNameSpecifier::Kind::Global) &&
12644 NamespcName->isStr("std")) {
12645 Diag(IdentLoc, diag::ext_using_undefined_std);
12646 R.addDecl(getOrCreateStdNamespace());
12647 R.resolveKind();
12648 }
12649 // Otherwise, attempt typo correction.
12650 else
12651 TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
12652 }
12653
12654 if (!R.empty()) {
12655 NamedDecl *Named = R.getRepresentativeDecl();
12656 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
12657 assert(NS && "expected namespace decl");
12658
12659 // The use of a nested name specifier may trigger deprecation warnings.
12660 DiagnoseUseOfDecl(Named, IdentLoc);
12661
12662 // C++ [namespace.udir]p1:
12663 // A using-directive specifies that the names in the nominated
12664 // namespace can be used in the scope in which the
12665 // using-directive appears after the using-directive. During
12666 // unqualified name lookup (3.4.1), the names appear as if they
12667 // were declared in the nearest enclosing namespace which
12668 // contains both the using-directive and the nominated
12669 // namespace. [Note: in this context, "contains" means "contains
12670 // directly or indirectly". ]
12671
12672 // Find enclosing context containing both using-directive and
12673 // nominated namespace.
12674 DeclContext *CommonAncestor = NS;
12675 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
12676 CommonAncestor = CommonAncestor->getParent();
12677
12678 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
12680 IdentLoc, Named, CommonAncestor);
12681
12683 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
12684 Diag(IdentLoc, diag::warn_using_directive_in_header);
12685 }
12686
12687 PushUsingDirective(S, UDir);
12688 } else {
12689 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
12690 }
12691
12692 if (UDir) {
12693 ProcessDeclAttributeList(S, UDir, AttrList);
12694 ProcessAPINotes(UDir);
12695 }
12696
12697 return UDir;
12698}
12699
12701 // If the scope has an associated entity and the using directive is at
12702 // namespace or translation unit scope, add the UsingDirectiveDecl into
12703 // its lookup structure so qualified name lookup can find it.
12704 DeclContext *Ctx = S->getEntity();
12705 if (Ctx && !Ctx->isFunctionOrMethod())
12706 Ctx->addDecl(UDir);
12707 else
12708 // Otherwise, it is at block scope. The using-directives will affect lookup
12709 // only to the end of the scope.
12710 S->PushUsingDirective(UDir);
12711}
12712
12714 SourceLocation UsingLoc,
12715 SourceLocation TypenameLoc, CXXScopeSpec &SS,
12716 UnqualifiedId &Name,
12717 SourceLocation EllipsisLoc,
12718 const ParsedAttributesView &AttrList) {
12719 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
12720
12721 if (SS.isEmpty()) {
12722 Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
12723 return nullptr;
12724 }
12725
12726 switch (Name.getKind()) {
12732 break;
12733
12736 // C++11 inheriting constructors.
12737 Diag(Name.getBeginLoc(),
12739 ? diag::warn_cxx98_compat_using_decl_constructor
12740 : diag::err_using_decl_constructor)
12741 << SS.getRange();
12742
12743 if (getLangOpts().CPlusPlus11) break;
12744
12745 return nullptr;
12746
12748 Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
12749 return nullptr;
12750
12752 Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
12754 return nullptr;
12755
12757 llvm_unreachable("cannot parse qualified deduction guide name");
12758 }
12759
12760 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
12761 DeclarationName TargetName = TargetNameInfo.getName();
12762 if (!TargetName)
12763 return nullptr;
12764
12765 // Warn about access declarations.
12766 if (UsingLoc.isInvalid()) {
12768 ? diag::err_access_decl
12769 : diag::warn_access_decl_deprecated)
12770 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
12771 }
12772
12773 if (EllipsisLoc.isInvalid()) {
12776 return nullptr;
12777 } else {
12779 !TargetNameInfo.containsUnexpandedParameterPack()) {
12780 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
12781 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
12782 EllipsisLoc = SourceLocation();
12783 }
12784 }
12785
12786 NamedDecl *UD =
12787 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
12788 SS, TargetNameInfo, EllipsisLoc, AttrList,
12789 /*IsInstantiation*/ false,
12790 AttrList.hasAttribute(ParsedAttr::AT_UsingIfExists));
12791 if (UD)
12792 PushOnScopeChains(UD, S, /*AddToContext*/ false);
12793
12794 return UD;
12795}
12796
12798 SourceLocation UsingLoc,
12799 SourceLocation EnumLoc, SourceRange TyLoc,
12800 const IdentifierInfo &II, ParsedType Ty,
12801 const CXXScopeSpec &SS) {
12802 TypeSourceInfo *TSI = nullptr;
12803 SourceLocation IdentLoc = TyLoc.getBegin();
12804 QualType EnumTy = GetTypeFromParser(Ty, &TSI);
12805 if (EnumTy.isNull()) {
12806 Diag(IdentLoc, isDependentScopeSpecifier(SS)
12807 ? diag::err_using_enum_is_dependent
12808 : diag::err_unknown_typename)
12809 << II.getName()
12810 << SourceRange(SS.isValid() ? SS.getBeginLoc() : IdentLoc,
12811 TyLoc.getEnd());
12812 return nullptr;
12813 }
12814
12815 if (EnumTy->isDependentType()) {
12816 Diag(IdentLoc, diag::err_using_enum_is_dependent);
12817 return nullptr;
12818 }
12819
12820 auto *Enum = EnumTy->getAsEnumDecl();
12821 if (!Enum) {
12822 Diag(IdentLoc, diag::err_using_enum_not_enum) << EnumTy;
12823 return nullptr;
12824 }
12825
12826 if (TSI == nullptr)
12827 TSI = Context.getTrivialTypeSourceInfo(EnumTy, IdentLoc);
12828
12829 auto *UD =
12830 BuildUsingEnumDeclaration(S, AS, UsingLoc, EnumLoc, IdentLoc, TSI, Enum);
12831
12832 if (UD)
12833 PushOnScopeChains(UD, S, /*AddToContext*/ false);
12834
12835 return UD;
12836}
12837
12838/// Determine whether a using declaration considers the given
12839/// declarations as "equivalent", e.g., if they are redeclarations of
12840/// the same entity or are both typedefs of the same type.
12841static bool
12843 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
12844 return true;
12845
12846 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
12847 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
12848 return Context.hasSameType(TD1->getUnderlyingType(),
12849 TD2->getUnderlyingType());
12850
12851 // Two using_if_exists using-declarations are equivalent if both are
12852 // unresolved.
12855 return true;
12856
12857 return false;
12858}
12859
12861 const LookupResult &Previous,
12862 UsingShadowDecl *&PrevShadow) {
12863 // Diagnose finding a decl which is not from a base class of the
12864 // current class. We do this now because there are cases where this
12865 // function will silently decide not to build a shadow decl, which
12866 // will pre-empt further diagnostics.
12867 //
12868 // We don't need to do this in C++11 because we do the check once on
12869 // the qualifier.
12870 //
12871 // FIXME: diagnose the following if we care enough:
12872 // struct A { int foo; };
12873 // struct B : A { using A::foo; };
12874 // template <class T> struct C : A {};
12875 // template <class T> struct D : C<T> { using B::foo; } // <---
12876 // This is invalid (during instantiation) in C++03 because B::foo
12877 // resolves to the using decl in B, which is not a base class of D<T>.
12878 // We can't diagnose it immediately because C<T> is an unknown
12879 // specialization. The UsingShadowDecl in D<T> then points directly
12880 // to A::foo, which will look well-formed when we instantiate.
12881 // The right solution is to not collapse the shadow-decl chain.
12882 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord())
12883 if (auto *Using = dyn_cast<UsingDecl>(BUD)) {
12884 DeclContext *OrigDC = Orig->getDeclContext();
12885
12886 // Handle enums and anonymous structs.
12887 if (isa<EnumDecl>(OrigDC))
12888 OrigDC = OrigDC->getParent();
12889 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
12890 while (OrigRec->isAnonymousStructOrUnion())
12891 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
12892
12894 if (OrigDC == CurContext) {
12895 Diag(Using->getLocation(),
12896 diag::err_using_decl_nested_name_specifier_is_current_class)
12897 << Using->getQualifierLoc().getSourceRange();
12898 Diag(Orig->getLocation(), diag::note_using_decl_target);
12899 Using->setInvalidDecl();
12900 return true;
12901 }
12902
12903 Diag(Using->getQualifierLoc().getBeginLoc(),
12904 diag::err_using_decl_nested_name_specifier_is_not_base_class)
12905 << Using->getQualifier() << cast<CXXRecordDecl>(CurContext)
12906 << Using->getQualifierLoc().getSourceRange();
12907 Diag(Orig->getLocation(), diag::note_using_decl_target);
12908 Using->setInvalidDecl();
12909 return true;
12910 }
12911 }
12912
12913 if (Previous.empty()) return false;
12914
12915 NamedDecl *Target = Orig;
12917 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
12918
12919 // If the target happens to be one of the previous declarations, we
12920 // don't have a conflict.
12921 //
12922 // FIXME: but we might be increasing its access, in which case we
12923 // should redeclare it.
12924 NamedDecl *NonTag = nullptr, *Tag = nullptr;
12925 bool FoundEquivalentDecl = false;
12926 for (NamedDecl *Element : Previous) {
12927 NamedDecl *D = Element->getUnderlyingDecl();
12928 // We can have UsingDecls in our Previous results because we use the same
12929 // LookupResult for checking whether the UsingDecl itself is a valid
12930 // redeclaration.
12932 continue;
12933
12934 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
12935 // C++ [class.mem]p19:
12936 // If T is the name of a class, then [every named member other than
12937 // a non-static data member] shall have a name different from T
12938 if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
12942 CurContext,
12944 return true;
12945 }
12946
12948 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Element))
12949 PrevShadow = Shadow;
12950 FoundEquivalentDecl = true;
12952 // We don't conflict with an existing using shadow decl of an equivalent
12953 // declaration, but we're not a redeclaration of it.
12954 FoundEquivalentDecl = true;
12955 }
12956
12957 if (isVisible(D))
12958 (isa<TagDecl>(D) ? Tag : NonTag) = D;
12959 }
12960
12961 if (FoundEquivalentDecl)
12962 return false;
12963
12964 // Always emit a diagnostic for a mismatch between an unresolved
12965 // using_if_exists and a resolved using declaration in either direction.
12967 (isa_and_nonnull<UnresolvedUsingIfExistsDecl>(NonTag))) {
12968 if (!NonTag && !Tag)
12969 return false;
12970 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12971 Diag(Target->getLocation(), diag::note_using_decl_target);
12972 Diag((NonTag ? NonTag : Tag)->getLocation(),
12973 diag::note_using_decl_conflict);
12974 BUD->setInvalidDecl();
12975 return true;
12976 }
12977
12978 if (FunctionDecl *FD = Target->getAsFunction()) {
12979 NamedDecl *OldDecl = nullptr;
12980 switch (CheckOverload(nullptr, FD, Previous, OldDecl,
12981 /*IsForUsingDecl*/ true)) {
12983 return false;
12984
12986 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12987 break;
12988
12989 // We found a decl with the exact signature.
12991 // If we're in a record, we want to hide the target, so we
12992 // return true (without a diagnostic) to tell the caller not to
12993 // build a shadow decl.
12994 if (CurContext->isRecord())
12995 return true;
12996
12997 // If we're not in a record, this is an error.
12998 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12999 break;
13000 }
13001
13002 Diag(Target->getLocation(), diag::note_using_decl_target);
13003 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
13004 BUD->setInvalidDecl();
13005 return true;
13006 }
13007
13008 // Target is not a function.
13009
13010 if (isa<TagDecl>(Target)) {
13011 // No conflict between a tag and a non-tag.
13012 if (!Tag) return false;
13013
13014 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
13015 Diag(Target->getLocation(), diag::note_using_decl_target);
13016 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
13017 BUD->setInvalidDecl();
13018 return true;
13019 }
13020
13021 // No conflict between a tag and a non-tag.
13022 if (!NonTag) return false;
13023
13024 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
13025 Diag(Target->getLocation(), diag::note_using_decl_target);
13026 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
13027 BUD->setInvalidDecl();
13028 return true;
13029}
13030
13031/// Determine whether a direct base class is a virtual base class.
13033 if (!Derived->getNumVBases())
13034 return false;
13035 for (auto &B : Derived->bases())
13036 if (B.getType()->getAsCXXRecordDecl() == Base)
13037 return B.isVirtual();
13038 llvm_unreachable("not a direct base class");
13039}
13040
13042 NamedDecl *Orig,
13043 UsingShadowDecl *PrevDecl) {
13044 // If we resolved to another shadow declaration, just coalesce them.
13045 NamedDecl *Target = Orig;
13047 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
13048 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
13049 }
13050
13051 NamedDecl *NonTemplateTarget = Target;
13052 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
13053 NonTemplateTarget = TargetTD->getTemplatedDecl();
13054
13055 UsingShadowDecl *Shadow;
13056 if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) {
13057 UsingDecl *Using = cast<UsingDecl>(BUD);
13058 bool IsVirtualBase =
13060 Using->getQualifier().getAsRecordDecl());
13062 Context, CurContext, Using->getLocation(), Using, Orig, IsVirtualBase);
13063 } else {
13065 Target->getDeclName(), BUD, Target);
13066 }
13067 BUD->addShadowDecl(Shadow);
13068
13069 Shadow->setAccess(BUD->getAccess());
13070 if (Orig->isInvalidDecl() || BUD->isInvalidDecl())
13071 Shadow->setInvalidDecl();
13072
13073 Shadow->setPreviousDecl(PrevDecl);
13074
13075 if (S)
13076 PushOnScopeChains(Shadow, S);
13077 else
13078 CurContext->addDecl(Shadow);
13079
13080
13081 return Shadow;
13082}
13083
13085 if (Shadow->getDeclName().getNameKind() ==
13087 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
13088
13089 // Remove it from the DeclContext...
13090 Shadow->getDeclContext()->removeDecl(Shadow);
13091
13092 // ...and the scope, if applicable...
13093 if (S) {
13094 S->RemoveDecl(Shadow);
13095 IdResolver.RemoveDecl(Shadow);
13096 }
13097
13098 // ...and the using decl.
13099 Shadow->getIntroducer()->removeShadowDecl(Shadow);
13100
13101 // TODO: complain somehow if Shadow was used. It shouldn't
13102 // be possible for this to happen, because...?
13103}
13104
13105/// Find the base specifier for a base class with the given type.
13107 QualType DesiredBase,
13108 bool &AnyDependentBases) {
13109 // Check whether the named type is a direct base class.
13110 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
13111 for (auto &Base : Derived->bases()) {
13112 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
13113 if (CanonicalDesiredBase == BaseType)
13114 return &Base;
13115 if (BaseType->isDependentType())
13116 AnyDependentBases = true;
13117 }
13118 return nullptr;
13119}
13120
13121namespace {
13122class UsingValidatorCCC final : public CorrectionCandidateCallback {
13123public:
13124 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
13125 NestedNameSpecifier NNS, CXXRecordDecl *RequireMemberOf)
13126 : HasTypenameKeyword(HasTypenameKeyword),
13127 IsInstantiation(IsInstantiation), OldNNS(NNS),
13128 RequireMemberOf(RequireMemberOf) {}
13129
13130 bool ValidateCandidate(const TypoCorrection &Candidate) override {
13131 NamedDecl *ND = Candidate.getCorrectionDecl();
13132
13133 // Keywords are not valid here.
13134 if (!ND || isa<NamespaceDecl>(ND))
13135 return false;
13136
13137 // Completely unqualified names are invalid for a 'using' declaration.
13138 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
13139 return false;
13140
13141 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
13142 // reject.
13143
13144 if (RequireMemberOf) {
13145 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
13146 if (FoundRecord && FoundRecord->isInjectedClassName()) {
13147 // No-one ever wants a using-declaration to name an injected-class-name
13148 // of a base class, unless they're declaring an inheriting constructor.
13149 ASTContext &Ctx = ND->getASTContext();
13150 if (!Ctx.getLangOpts().CPlusPlus11)
13151 return false;
13152 CanQualType FoundType = Ctx.getCanonicalTagType(FoundRecord);
13153
13154 // Check that the injected-class-name is named as a member of its own
13155 // type; we don't want to suggest 'using Derived::Base;', since that
13156 // means something else.
13157 NestedNameSpecifier Specifier = Candidate.WillReplaceSpecifier()
13158 ? Candidate.getCorrectionSpecifier()
13159 : OldNNS;
13160 if (Specifier.getKind() != NestedNameSpecifier::Kind::Type ||
13161 !Ctx.hasSameType(QualType(Specifier.getAsType(), 0), FoundType))
13162 return false;
13163
13164 // Check that this inheriting constructor declaration actually names a
13165 // direct base class of the current class.
13166 bool AnyDependentBases = false;
13167 if (!findDirectBaseWithType(RequireMemberOf,
13168 Ctx.getCanonicalTagType(FoundRecord),
13169 AnyDependentBases) &&
13170 !AnyDependentBases)
13171 return false;
13172 } else {
13173 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
13174 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
13175 return false;
13176
13177 // FIXME: Check that the base class member is accessible?
13178 }
13179 } else {
13180 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
13181 if (FoundRecord && FoundRecord->isInjectedClassName())
13182 return false;
13183 }
13184
13185 if (isa<TypeDecl>(ND))
13186 return HasTypenameKeyword || !IsInstantiation;
13187
13188 return !HasTypenameKeyword;
13189 }
13190
13191 std::unique_ptr<CorrectionCandidateCallback> clone() override {
13192 return std::make_unique<UsingValidatorCCC>(*this);
13193 }
13194
13195private:
13196 bool HasTypenameKeyword;
13197 bool IsInstantiation;
13198 NestedNameSpecifier OldNNS;
13199 CXXRecordDecl *RequireMemberOf;
13200};
13201} // end anonymous namespace
13202
13204 // It is really dumb that we have to do this.
13205 LookupResult::Filter F = Previous.makeFilter();
13206 while (F.hasNext()) {
13207 NamedDecl *D = F.next();
13208 if (!isDeclInScope(D, CurContext, S))
13209 F.erase();
13210 // If we found a local extern declaration that's not ordinarily visible,
13211 // and this declaration is being added to a non-block scope, ignore it.
13212 // We're only checking for scope conflicts here, not also for violations
13213 // of the linkage rules.
13214 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
13216 F.erase();
13217 }
13218 F.done();
13219}
13220
13222 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
13223 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
13224 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
13225 const ParsedAttributesView &AttrList, bool IsInstantiation,
13226 bool IsUsingIfExists) {
13227 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
13228 SourceLocation IdentLoc = NameInfo.getLoc();
13229 assert(IdentLoc.isValid() && "Invalid TargetName location.");
13230
13231 // FIXME: We ignore attributes for now.
13232
13233 // For an inheriting constructor declaration, the name of the using
13234 // declaration is the name of a constructor in this class, not in the
13235 // base class.
13236 DeclarationNameInfo UsingName = NameInfo;
13238 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
13239 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
13240 Context.getCanonicalTagType(RD)));
13241
13242 // Do the redeclaration lookup in the current scope.
13243 LookupResult Previous(*this, UsingName, LookupUsingDeclName,
13245 Previous.setHideTags(false);
13246 if (S) {
13247 LookupName(Previous, S);
13248
13250 } else {
13251 assert(IsInstantiation && "no scope in non-instantiation");
13252 if (CurContext->isRecord())
13254 else {
13255 // No redeclaration check is needed here; in non-member contexts we
13256 // diagnosed all possible conflicts with other using-declarations when
13257 // building the template:
13258 //
13259 // For a dependent non-type using declaration, the only valid case is
13260 // if we instantiate to a single enumerator. We check for conflicts
13261 // between shadow declarations we introduce, and we check in the template
13262 // definition for conflicts between a non-type using declaration and any
13263 // other declaration, which together covers all cases.
13264 //
13265 // A dependent typename using declaration will never successfully
13266 // instantiate, since it will always name a class member, so we reject
13267 // that in the template definition.
13268 }
13269 }
13270
13271 // Check for invalid redeclarations.
13272 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
13273 SS, IdentLoc, Previous))
13274 return nullptr;
13275
13276 // 'using_if_exists' doesn't make sense on an inherited constructor.
13277 if (IsUsingIfExists && UsingName.getName().getNameKind() ==
13279 Diag(UsingLoc, diag::err_using_if_exists_on_ctor);
13280 return nullptr;
13281 }
13282
13283 DeclContext *LookupContext = computeDeclContext(SS);
13285 if (!LookupContext || EllipsisLoc.isValid()) {
13286 NamedDecl *D;
13287 // Dependent scope, or an unexpanded pack
13288 if (!LookupContext && CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword,
13289 SS, NameInfo, IdentLoc))
13290 return nullptr;
13291
13292 if (Previous.isSingleResult() &&
13293 Previous.getFoundDecl()->isTemplateParameter())
13294 DiagnoseTemplateParameterShadow(IdentLoc, Previous.getFoundDecl());
13295
13296 if (HasTypenameKeyword) {
13297 // FIXME: not all declaration name kinds are legal here
13299 UsingLoc, TypenameLoc,
13300 QualifierLoc,
13301 IdentLoc, NameInfo.getName(),
13302 EllipsisLoc);
13303 } else {
13305 QualifierLoc, NameInfo, EllipsisLoc);
13306 }
13307 D->setAccess(AS);
13308 CurContext->addDecl(D);
13309 ProcessDeclAttributeList(S, D, AttrList);
13310 return D;
13311 }
13312
13313 auto Build = [&](bool Invalid) {
13314 UsingDecl *UD =
13315 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
13316 UsingName, HasTypenameKeyword);
13317 UD->setAccess(AS);
13318 CurContext->addDecl(UD);
13319 ProcessDeclAttributeList(S, UD, AttrList);
13321 return UD;
13322 };
13323 auto BuildInvalid = [&]{ return Build(true); };
13324 auto BuildValid = [&]{ return Build(false); };
13325
13326 if (RequireCompleteDeclContext(SS, LookupContext))
13327 return BuildInvalid();
13328
13329 // Look up the target name.
13330 LookupResult R(*this, NameInfo, LookupOrdinaryName);
13331
13332 // Unlike most lookups, we don't always want to hide tag
13333 // declarations: tag names are visible through the using declaration
13334 // even if hidden by ordinary names, *except* in a dependent context
13335 // where they may be used by two-phase lookup.
13336 if (!IsInstantiation)
13337 R.setHideTags(false);
13338
13339 // For the purposes of this lookup, we have a base object type
13340 // equal to that of the current context.
13341 if (CurContext->isRecord()) {
13342 R.setBaseObjectType(
13343 Context.getCanonicalTagType(cast<CXXRecordDecl>(CurContext)));
13344 }
13345
13346 LookupQualifiedName(R, LookupContext);
13347
13348 // Validate the context, now we have a lookup
13349 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
13350 IdentLoc, &R))
13351 return nullptr;
13352
13353 if (R.empty() && IsUsingIfExists)
13355 UsingName.getName()),
13356 AS_public);
13357
13358 // Try to correct typos if possible. If constructor name lookup finds no
13359 // results, that means the named class has no explicit constructors, and we
13360 // suppressed declaring implicit ones (probably because it's dependent or
13361 // invalid).
13362 if (R.empty() &&
13364 // HACK 2017-01-08: Work around an issue with libstdc++'s detection of
13365 // ::gets. Sometimes it believes that glibc provides a ::gets in cases where
13366 // it does not. The issue was fixed in libstdc++ 6.3 (2016-12-21) and later.
13367 auto *II = NameInfo.getName().getAsIdentifierInfo();
13368 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
13369 CurContext->isStdNamespace() &&
13370 isa<TranslationUnitDecl>(LookupContext) &&
13371 PP.NeedsStdLibCxxWorkaroundBefore(2016'12'21) &&
13372 getSourceManager().isInSystemHeader(UsingLoc))
13373 return nullptr;
13374 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
13375 dyn_cast<CXXRecordDecl>(CurContext));
13376 if (TypoCorrection Corrected =
13377 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
13379 // We reject candidates where DroppedSpecifier == true, hence the
13380 // literal '0' below.
13381 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
13382 << NameInfo.getName() << LookupContext << 0
13383 << SS.getRange());
13384
13385 // If we picked a correction with no attached Decl we can't do anything
13386 // useful with it, bail out.
13387 NamedDecl *ND = Corrected.getCorrectionDecl();
13388 if (!ND)
13389 return BuildInvalid();
13390
13391 // If we corrected to an inheriting constructor, handle it as one.
13392 auto *RD = dyn_cast<CXXRecordDecl>(ND);
13393 if (RD && RD->isInjectedClassName()) {
13394 // The parent of the injected class name is the class itself.
13395 RD = cast<CXXRecordDecl>(RD->getParent());
13396
13397 // Fix up the information we'll use to build the using declaration.
13398 if (Corrected.WillReplaceSpecifier()) {
13400 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
13401 QualifierLoc.getSourceRange());
13402 QualifierLoc = Builder.getWithLocInContext(Context);
13403 }
13404
13405 // In this case, the name we introduce is the name of a derived class
13406 // constructor.
13407 auto *CurClass = cast<CXXRecordDecl>(CurContext);
13408 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
13409 Context.getCanonicalTagType(CurClass)));
13410 UsingName.setNamedTypeInfo(nullptr);
13411 for (auto *Ctor : LookupConstructors(RD))
13412 R.addDecl(Ctor);
13413 R.resolveKind();
13414 } else {
13415 // FIXME: Pick up all the declarations if we found an overloaded
13416 // function.
13417 UsingName.setName(ND->getDeclName());
13418 R.addDecl(ND);
13419 }
13420 } else {
13421 Diag(IdentLoc, diag::err_no_member)
13422 << NameInfo.getName() << LookupContext << SS.getRange();
13423 return BuildInvalid();
13424 }
13425 }
13426
13427 if (R.isAmbiguous())
13428 return BuildInvalid();
13429
13430 if (HasTypenameKeyword) {
13431 // If we asked for a typename and got a non-type decl, error out.
13432 if (!R.getAsSingle<TypeDecl>() &&
13433 !R.getAsSingle<UnresolvedUsingIfExistsDecl>()) {
13434 Diag(IdentLoc, diag::err_using_typename_non_type);
13435 for (const NamedDecl *D : R)
13436 Diag(D->getUnderlyingDecl()->getLocation(),
13437 diag::note_using_decl_target);
13438 return BuildInvalid();
13439 }
13440 } else {
13441 // If we asked for a non-typename and we got a type, error out,
13442 // but only if this is an instantiation of an unresolved using
13443 // decl. Otherwise just silently find the type name.
13444 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
13445 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
13446 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
13447 return BuildInvalid();
13448 }
13449 }
13450
13451 // C++14 [namespace.udecl]p6:
13452 // A using-declaration shall not name a namespace.
13453 if (R.getAsSingle<NamespaceDecl>()) {
13454 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
13455 << SS.getRange();
13456 // Suggest using 'using namespace ...' instead.
13457 Diag(SS.getBeginLoc(), diag::note_namespace_using_decl)
13458 << FixItHint::CreateInsertion(SS.getBeginLoc(), "namespace ");
13459 return BuildInvalid();
13460 }
13461
13462 UsingDecl *UD = BuildValid();
13463
13464 // Some additional rules apply to inheriting constructors.
13465 if (UsingName.getName().getNameKind() ==
13467 // Suppress access diagnostics; the access check is instead performed at the
13468 // point of use for an inheriting constructor.
13469 R.suppressDiagnostics();
13471 return UD;
13472 }
13473
13474 for (NamedDecl *D : R) {
13475 UsingShadowDecl *PrevDecl = nullptr;
13476 if (!CheckUsingShadowDecl(UD, D, Previous, PrevDecl))
13477 BuildUsingShadowDecl(S, UD, D, PrevDecl);
13478 }
13479
13480 return UD;
13481}
13482
13484 SourceLocation UsingLoc,
13485 SourceLocation EnumLoc,
13486 SourceLocation NameLoc,
13487 TypeSourceInfo *EnumType,
13488 EnumDecl *ED) {
13489 bool Invalid = false;
13490
13491 if (CurContext->getRedeclContext()->isRecord()) {
13492 /// In class scope, check if this is a duplicate, for better a diagnostic.
13493 DeclarationNameInfo UsingEnumName(ED->getDeclName(), NameLoc);
13494 LookupResult Previous(*this, UsingEnumName, LookupUsingDeclName,
13496
13498
13499 for (NamedDecl *D : Previous)
13500 if (UsingEnumDecl *UED = dyn_cast<UsingEnumDecl>(D))
13501 if (UED->getEnumDecl() == ED) {
13502 Diag(UsingLoc, diag::err_using_enum_decl_redeclaration)
13503 << SourceRange(EnumLoc, NameLoc);
13504 Diag(D->getLocation(), diag::note_using_enum_decl) << 1;
13505 Invalid = true;
13506 break;
13507 }
13508 }
13509
13510 if (RequireCompleteEnumDecl(ED, NameLoc))
13511 Invalid = true;
13512
13514 EnumLoc, NameLoc, EnumType);
13515 UD->setAccess(AS);
13516 CurContext->addDecl(UD);
13517
13518 if (Invalid) {
13519 UD->setInvalidDecl();
13520 return UD;
13521 }
13522
13523 // Create the shadow decls for each enumerator
13524 for (EnumConstantDecl *EC : ED->enumerators()) {
13525 UsingShadowDecl *PrevDecl = nullptr;
13526 DeclarationNameInfo DNI(EC->getDeclName(), EC->getLocation());
13529 LookupName(Previous, S);
13531
13532 if (!CheckUsingShadowDecl(UD, EC, Previous, PrevDecl))
13533 BuildUsingShadowDecl(S, UD, EC, PrevDecl);
13534 }
13535
13536 return UD;
13537}
13538
13540 ArrayRef<NamedDecl *> Expansions) {
13541 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
13542 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
13543 isa<UsingPackDecl>(InstantiatedFrom));
13544
13545 auto *UPD =
13546 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
13547 UPD->setAccess(InstantiatedFrom->getAccess());
13548 CurContext->addDecl(UPD);
13549 return UPD;
13550}
13551
13553 assert(!UD->hasTypename() && "expecting a constructor name");
13554
13555 QualType SourceType(UD->getQualifier().getAsType(), 0);
13557
13558 // Check whether the named type is a direct base class.
13559 bool AnyDependentBases = false;
13560 auto *Base =
13561 findDirectBaseWithType(TargetClass, SourceType, AnyDependentBases);
13562 if (!Base && !AnyDependentBases) {
13563 Diag(UD->getUsingLoc(), diag::err_using_decl_constructor_not_in_direct_base)
13564 << UD->getNameInfo().getSourceRange() << SourceType << TargetClass;
13565 UD->setInvalidDecl();
13566 return true;
13567 }
13568
13569 if (Base)
13570 Base->setInheritConstructors();
13571
13572 return false;
13573}
13574
13576 bool HasTypenameKeyword,
13577 const CXXScopeSpec &SS,
13578 SourceLocation NameLoc,
13579 const LookupResult &Prev) {
13580 NestedNameSpecifier Qual = SS.getScopeRep();
13581
13582 // C++03 [namespace.udecl]p8:
13583 // C++0x [namespace.udecl]p10:
13584 // A using-declaration is a declaration and can therefore be used
13585 // repeatedly where (and only where) multiple declarations are
13586 // allowed.
13587 //
13588 // That's in non-member contexts.
13589 if (!CurContext->getRedeclContext()->isRecord()) {
13590 // A dependent qualifier outside a class can only ever resolve to an
13591 // enumeration type. Therefore it conflicts with any other non-type
13592 // declaration in the same scope.
13593 // FIXME: How should we check for dependent type-type conflicts at block
13594 // scope?
13595 if (Qual.isDependent() && !HasTypenameKeyword) {
13596 for (auto *D : Prev) {
13597 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
13598 bool OldCouldBeEnumerator =
13600 Diag(NameLoc,
13601 OldCouldBeEnumerator ? diag::err_redefinition
13602 : diag::err_redefinition_different_kind)
13603 << Prev.getLookupName();
13604 Diag(D->getLocation(), diag::note_previous_definition);
13605 return true;
13606 }
13607 }
13608 }
13609 return false;
13610 }
13611
13612 NestedNameSpecifier CNNS = Qual.getCanonical();
13613 for (const NamedDecl *D : Prev) {
13614 bool DTypename;
13615 NestedNameSpecifier DQual = std::nullopt;
13616 if (const auto *UD = dyn_cast<UsingDecl>(D)) {
13617 DTypename = UD->hasTypename();
13618 DQual = UD->getQualifier();
13619 } else if (const auto *UD = dyn_cast<UnresolvedUsingValueDecl>(D)) {
13620 DTypename = false;
13621 DQual = UD->getQualifier();
13622 } else if (const auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
13623 DTypename = true;
13624 DQual = UD->getQualifier();
13625 } else
13626 continue;
13627
13628 // using decls differ if one says 'typename' and the other doesn't.
13629 // FIXME: non-dependent using decls?
13630 if (HasTypenameKeyword != DTypename) continue;
13631
13632 // using decls differ if they name different scopes (but note that
13633 // template instantiation can cause this check to trigger when it
13634 // didn't before instantiation).
13635 if (CNNS != DQual.getCanonical())
13636 continue;
13637
13638 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
13639 Diag(D->getLocation(), diag::note_using_decl) << 1;
13640 return true;
13641 }
13642
13643 return false;
13644}
13645
13646bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
13647 const CXXScopeSpec &SS,
13648 const DeclarationNameInfo &NameInfo,
13649 SourceLocation NameLoc,
13650 const LookupResult *R, const UsingDecl *UD) {
13651 DeclContext *NamedContext = computeDeclContext(SS);
13652 assert(bool(NamedContext) == (R || UD) && !(R && UD) &&
13653 "resolvable context must have exactly one set of decls");
13654
13655 // C++ 20 permits using an enumerator that does not have a class-hierarchy
13656 // relationship.
13657 bool Cxx20Enumerator = false;
13658 if (NamedContext) {
13659 EnumConstantDecl *EC = nullptr;
13660 if (R)
13661 EC = R->getAsSingle<EnumConstantDecl>();
13662 else if (UD && UD->shadow_size() == 1)
13663 EC = dyn_cast<EnumConstantDecl>(UD->shadow_begin()->getTargetDecl());
13664 if (EC)
13665 Cxx20Enumerator = getLangOpts().CPlusPlus20;
13666
13667 if (auto *ED = dyn_cast<EnumDecl>(NamedContext)) {
13668 // C++14 [namespace.udecl]p7:
13669 // A using-declaration shall not name a scoped enumerator.
13670 // C++20 p1099 permits enumerators.
13671 if (EC && R && ED->isScoped())
13672 Diag(SS.getBeginLoc(),
13674 ? diag::warn_cxx17_compat_using_decl_scoped_enumerator
13675 : diag::ext_using_decl_scoped_enumerator)
13676 << SS.getRange();
13677
13678 // We want to consider the scope of the enumerator
13679 NamedContext = ED->getDeclContext();
13680 }
13681 }
13682
13683 if (!CurContext->isRecord()) {
13684 // C++03 [namespace.udecl]p3:
13685 // C++0x [namespace.udecl]p8:
13686 // A using-declaration for a class member shall be a member-declaration.
13687 // C++20 [namespace.udecl]p7
13688 // ... other than an enumerator ...
13689
13690 // If we weren't able to compute a valid scope, it might validly be a
13691 // dependent class or enumeration scope. If we have a 'typename' keyword,
13692 // the scope must resolve to a class type.
13693 if (NamedContext ? !NamedContext->getRedeclContext()->isRecord()
13694 : !HasTypename)
13695 return false; // OK
13696
13697 Diag(NameLoc,
13698 Cxx20Enumerator
13699 ? diag::warn_cxx17_compat_using_decl_class_member_enumerator
13700 : diag::err_using_decl_can_not_refer_to_class_member)
13701 << SS.getRange();
13702
13703 if (Cxx20Enumerator)
13704 return false; // OK
13705
13706 auto *RD = NamedContext
13707 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
13708 : nullptr;
13709 if (RD && !RequireCompleteDeclContext(const_cast<CXXScopeSpec &>(SS), RD)) {
13710 // See if there's a helpful fixit
13711
13712 if (!R) {
13713 // We will have already diagnosed the problem on the template
13714 // definition, Maybe we should do so again?
13715 } else if (R->getAsSingle<TypeDecl>()) {
13716 if (getLangOpts().CPlusPlus11) {
13717 // Convert 'using X::Y;' to 'using Y = X::Y;'.
13718 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
13719 << diag::MemClassWorkaround::AliasDecl
13721 NameInfo.getName().getAsString() +
13722 " = ");
13723 } else {
13724 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
13725 SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
13726 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
13727 << diag::MemClassWorkaround::TypedefDecl
13728 << FixItHint::CreateReplacement(UsingLoc, "typedef")
13730 InsertLoc, " " + NameInfo.getName().getAsString());
13731 }
13732 } else if (R->getAsSingle<VarDecl>()) {
13733 // Don't provide a fixit outside C++11 mode; we don't want to suggest
13734 // repeating the type of the static data member here.
13735 FixItHint FixIt;
13736 if (getLangOpts().CPlusPlus11) {
13737 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
13739 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
13740 }
13741
13742 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
13743 << diag::MemClassWorkaround::ReferenceDecl << FixIt;
13744 } else if (R->getAsSingle<EnumConstantDecl>()) {
13745 // Don't provide a fixit outside C++11 mode; we don't want to suggest
13746 // repeating the type of the enumeration here, and we can't do so if
13747 // the type is anonymous.
13748 FixItHint FixIt;
13749 if (getLangOpts().CPlusPlus11) {
13750 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
13752 UsingLoc,
13753 "constexpr auto " + NameInfo.getName().getAsString() + " = ");
13754 }
13755
13756 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
13757 << (getLangOpts().CPlusPlus11
13758 ? diag::MemClassWorkaround::ConstexprVar
13759 : diag::MemClassWorkaround::ConstVar)
13760 << FixIt;
13761 }
13762 }
13763
13764 return true; // Fail
13765 }
13766
13767 // If the named context is dependent, we can't decide much.
13768 if (!NamedContext) {
13769 // FIXME: in C++0x, we can diagnose if we can prove that the
13770 // nested-name-specifier does not refer to a base class, which is
13771 // still possible in some cases.
13772
13773 // Otherwise we have to conservatively report that things might be
13774 // okay.
13775 return false;
13776 }
13777
13778 // The current scope is a record.
13779 if (!NamedContext->isRecord()) {
13780 // Ideally this would point at the last name in the specifier,
13781 // but we don't have that level of source info.
13782 Diag(SS.getBeginLoc(),
13783 Cxx20Enumerator
13784 ? diag::warn_cxx17_compat_using_decl_non_member_enumerator
13785 : diag::err_using_decl_nested_name_specifier_is_not_class)
13786 << SS.getScopeRep() << SS.getRange();
13787
13788 if (Cxx20Enumerator)
13789 return false; // OK
13790
13791 return true;
13792 }
13793
13794 if (!NamedContext->isDependentContext() &&
13795 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
13796 return true;
13797
13798 // C++26 [namespace.udecl]p3:
13799 // In a using-declaration used as a member-declaration, each
13800 // using-declarator shall either name an enumerator or have a
13801 // nested-name-specifier naming a base class of the current class
13802 // ([expr.prim.this]). ...
13803 // "have a nested-name-specifier naming a base class of the current class"
13804 // was introduced by CWG400.
13805
13808
13809 if (Cxx20Enumerator) {
13810 Diag(NameLoc, diag::warn_cxx17_compat_using_decl_non_member_enumerator)
13811 << SS.getScopeRep() << SS.getRange();
13812 return false;
13813 }
13814
13815 if (CurContext == NamedContext) {
13816 Diag(SS.getBeginLoc(),
13817 diag::err_using_decl_nested_name_specifier_is_current_class)
13818 << SS.getRange();
13819 return true;
13820 }
13821
13822 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
13823 Diag(SS.getBeginLoc(),
13824 diag::err_using_decl_nested_name_specifier_is_not_base_class)
13826 << SS.getRange();
13827 }
13828 return true;
13829 }
13830
13831 return false;
13832}
13833
13835 MultiTemplateParamsArg TemplateParamLists,
13836 SourceLocation UsingLoc, UnqualifiedId &Name,
13837 const ParsedAttributesView &AttrList,
13838 TypeResult Type, Decl *DeclFromDeclSpec) {
13839
13840 if (Type.isInvalid())
13841 return nullptr;
13842
13843 bool Invalid = false;
13845 TypeSourceInfo *TInfo = nullptr;
13846 GetTypeFromParser(Type.get(), &TInfo);
13847
13848 if (DiagnoseClassNameShadow(CurContext, NameInfo))
13849 return nullptr;
13850
13853 Invalid = true;
13854 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
13855 TInfo->getTypeLoc().getBeginLoc());
13856 }
13857
13858 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
13859 TemplateParamLists.size()
13862 LookupName(Previous, S);
13863
13864 // Warn about shadowing the name of a template parameter.
13865 if (Previous.isSingleResult() &&
13866 Previous.getFoundDecl()->isTemplateParameter()) {
13868 Previous.clear();
13869 }
13870
13871 assert(Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
13872 "name in alias declaration must be an identifier");
13874 Name.StartLocation,
13875 Name.Identifier, TInfo);
13876
13877 NewTD->setAccess(AS);
13878
13879 if (Invalid)
13880 NewTD->setInvalidDecl();
13881
13882 ProcessDeclAttributeList(S, NewTD, AttrList);
13883 AddPragmaAttributes(S, NewTD);
13884 ProcessAPINotes(NewTD);
13885
13887 Invalid |= NewTD->isInvalidDecl();
13888
13889 // Get the innermost enclosing declaration scope.
13890 S = S->getDeclParent();
13891
13892 bool Redeclaration = false;
13893
13894 NamedDecl *NewND;
13895 if (TemplateParamLists.size()) {
13896 TypeAliasTemplateDecl *OldDecl = nullptr;
13897 TemplateParameterList *OldTemplateParams = nullptr;
13898
13899 TemplateParameterList *TemplateParams = TemplateParamLists[0];
13900 if (TemplateParamLists.size() != 1) {
13901 Diag(UsingLoc, diag::err_alias_template_extra_headers)
13902 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
13903 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
13904 Invalid = true;
13905
13906 // Recover by picking the last non-empty template parameter list.
13907 auto It = llvm::find_if(
13908 llvm::reverse(TemplateParamLists),
13909 [](TemplateParameterList *TPL) { return !TPL->empty(); });
13910 assert(It != TemplateParamLists.rend() &&
13911 "if all template parameter lists were empty, this should have "
13912 "been rejected as an explicit specialization");
13913 TemplateParams = *It;
13914 }
13915
13916 // Check that we can declare a template here.
13917 if (CheckTemplateDeclScope(S, TemplateParams))
13918 return nullptr;
13919
13920 // Only consider previous declarations in the same scope.
13921 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
13922 /*ExplicitInstantiationOrSpecialization*/false);
13923 if (!Previous.empty()) {
13924 Redeclaration = true;
13925
13926 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
13927 if (!OldDecl && !Invalid) {
13928 Diag(UsingLoc, diag::err_redefinition_different_kind)
13929 << Name.Identifier;
13930
13931 NamedDecl *OldD = Previous.getRepresentativeDecl();
13932 if (OldD->getLocation().isValid())
13933 Diag(OldD->getLocation(), diag::note_previous_definition);
13934
13935 Invalid = true;
13936 }
13937
13938 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
13939 if (TemplateParameterListsAreEqual(TemplateParams,
13940 OldDecl->getTemplateParameters(),
13941 /*Complain=*/true,
13943 OldTemplateParams =
13945 else
13946 Invalid = true;
13947
13948 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
13949 if (!Invalid &&
13950 !Context.hasSameType(OldTD->getUnderlyingType(),
13951 NewTD->getUnderlyingType())) {
13952 // FIXME: The C++0x standard does not clearly say this is ill-formed,
13953 // but we can't reasonably accept it.
13954 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
13955 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
13956 if (OldTD->getLocation().isValid())
13957 Diag(OldTD->getLocation(), diag::note_previous_definition);
13958 Invalid = true;
13959 }
13960 }
13961 }
13962
13963 // Merge any previous default template arguments into our parameters,
13964 // and check the parameter list.
13965 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
13966 TPC_Other))
13967 return nullptr;
13968
13969 TypeAliasTemplateDecl *NewDecl =
13971 Name.Identifier, TemplateParams,
13972 NewTD);
13973 NewTD->setDescribedAliasTemplate(NewDecl);
13974
13975 NewDecl->setAccess(AS);
13976
13977 if (Invalid)
13978 NewDecl->setInvalidDecl();
13979 else if (OldDecl) {
13980 NewDecl->setPreviousDecl(OldDecl);
13981 CheckRedeclarationInModule(NewDecl, OldDecl);
13982 }
13983
13984 NewND = NewDecl;
13985 } else {
13986 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
13988 handleTagNumbering(TD, S);
13989 }
13991 NewND = NewTD;
13992 }
13993
13994 PushOnScopeChains(NewND, S);
13995 ActOnDocumentableDecl(NewND);
13996 return NewND;
13997}
13998
14000 SourceLocation AliasLoc,
14001 IdentifierInfo *Alias, CXXScopeSpec &SS,
14002 SourceLocation IdentLoc,
14003 IdentifierInfo *Ident) {
14004
14005 // Lookup the namespace name.
14006 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
14007 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
14008
14009 if (R.isAmbiguous())
14010 return nullptr;
14011
14012 if (R.empty()) {
14013 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
14014 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
14015 return nullptr;
14016 }
14017 }
14018 assert(!R.isAmbiguous() && !R.empty());
14019 auto *ND = cast<NamespaceBaseDecl>(R.getRepresentativeDecl());
14020
14021 // Check if we have a previous declaration with the same name.
14022 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
14024 LookupName(PrevR, S);
14025
14026 // Check we're not shadowing a template parameter.
14027 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
14029 PrevR.clear();
14030 }
14031
14032 // Filter out any other lookup result from an enclosing scope.
14033 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
14034 /*AllowInlineNamespace*/false);
14035
14036 // Find the previous declaration and check that we can redeclare it.
14037 NamespaceAliasDecl *Prev = nullptr;
14038 if (PrevR.isSingleResult()) {
14039 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
14040 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
14041 // We already have an alias with the same name that points to the same
14042 // namespace; check that it matches.
14043 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
14044 Prev = AD;
14045 } else if (isVisible(PrevDecl)) {
14046 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
14047 << Alias;
14048 Diag(AD->getLocation(), diag::note_previous_namespace_alias)
14049 << AD->getNamespace();
14050 return nullptr;
14051 }
14052 } else if (isVisible(PrevDecl)) {
14053 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
14054 ? diag::err_redefinition
14055 : diag::err_redefinition_different_kind;
14056 Diag(AliasLoc, DiagID) << Alias;
14057 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
14058 return nullptr;
14059 }
14060 }
14061
14062 // The use of a nested name specifier may trigger deprecation warnings.
14063 DiagnoseUseOfDecl(ND, IdentLoc);
14064
14066 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
14067 Alias, SS.getWithLocInContext(Context),
14068 IdentLoc, ND);
14069 if (Prev)
14070 AliasDecl->setPreviousDecl(Prev);
14071
14073 return AliasDecl;
14074}
14075
14076namespace {
14077struct SpecialMemberExceptionSpecInfo
14078 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
14079 SourceLocation Loc;
14081
14082 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
14085 SourceLocation Loc)
14086 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
14087
14088 bool visitBase(CXXBaseSpecifier *Base);
14089 bool visitField(FieldDecl *FD);
14090
14091 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
14092 unsigned Quals);
14093
14094 void visitSubobjectCall(Subobject Subobj,
14096};
14097}
14098
14099bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
14100 auto *BaseClass = Base->getType()->getAsCXXRecordDecl();
14101 if (!BaseClass)
14102 return false;
14103
14104 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
14105 if (auto *BaseCtor = SMOR.getMethod()) {
14106 visitSubobjectCall(Base, BaseCtor);
14107 return false;
14108 }
14109
14110 visitClassSubobject(BaseClass, Base, 0);
14111 return false;
14112}
14113
14114bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
14115 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
14116 FD->hasInClassInitializer()) {
14117 Expr *E = FD->getInClassInitializer();
14118 if (!E)
14119 // FIXME: It's a little wasteful to build and throw away a
14120 // CXXDefaultInitExpr here.
14121 // FIXME: We should have a single context note pointing at Loc, and
14122 // this location should be MD->getLocation() instead, since that's
14123 // the location where we actually use the default init expression.
14124 E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
14125 if (E)
14126 ExceptSpec.CalledExpr(E);
14127 } else if (auto *RD = S.Context.getBaseElementType(FD->getType())
14128 ->getAsCXXRecordDecl()) {
14129 visitClassSubobject(RD, FD, FD->getType().getCVRQualifiers());
14130 }
14131 return false;
14132}
14133
14134void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
14135 Subobject Subobj,
14136 unsigned Quals) {
14137 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
14138 bool IsMutable = Field && Field->isMutable();
14139 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
14140}
14141
14142void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
14143 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
14144 // Note, if lookup fails, it doesn't matter what exception specification we
14145 // choose because the special member will be deleted.
14146 if (CXXMethodDecl *MD = SMOR.getMethod())
14147 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
14148}
14149
14151 llvm::APSInt Result;
14153 ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEKind::ExplicitBool);
14154 ExplicitSpec.setExpr(Converted.get());
14155 if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
14156 ExplicitSpec.setKind(Result.getBoolValue()
14159 return true;
14160 }
14162 return false;
14163}
14164
14167 if (!ExplicitExpr->isTypeDependent())
14169 return ES;
14170}
14171
14176 ComputingExceptionSpec CES(S, MD, Loc);
14177
14178 CXXRecordDecl *ClassDecl = MD->getParent();
14179
14180 // C++ [except.spec]p14:
14181 // An implicitly declared special member function (Clause 12) shall have an
14182 // exception-specification. [...]
14183 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
14184 if (ClassDecl->isInvalidDecl())
14185 return Info.ExceptSpec;
14186
14187 // FIXME: If this diagnostic fires, we're probably missing a check for
14188 // attempting to resolve an exception specification before it's known
14189 // at a higher level.
14190 if (S.RequireCompleteType(MD->getLocation(),
14191 S.Context.getCanonicalTagType(ClassDecl),
14192 diag::err_exception_spec_incomplete_type))
14193 return Info.ExceptSpec;
14194
14195 // C++1z [except.spec]p7:
14196 // [Look for exceptions thrown by] a constructor selected [...] to
14197 // initialize a potentially constructed subobject,
14198 // C++1z [except.spec]p8:
14199 // The exception specification for an implicitly-declared destructor, or a
14200 // destructor without a noexcept-specifier, is potentially-throwing if and
14201 // only if any of the destructors for any of its potentially constructed
14202 // subojects is potentially throwing.
14203 // FIXME: We respect the first rule but ignore the "potentially constructed"
14204 // in the second rule to resolve a core issue (no number yet) that would have
14205 // us reject:
14206 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
14207 // struct B : A {};
14208 // struct C : B { void f(); };
14209 // ... due to giving B::~B() a non-throwing exception specification.
14210 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
14211 : Info.VisitAllBases);
14212
14213 return Info.ExceptSpec;
14214}
14215
14216namespace {
14217/// RAII object to register a special member as being currently declared.
14218struct DeclaringSpecialMember {
14219 Sema &S;
14221 Sema::ContextRAII SavedContext;
14222 bool WasAlreadyBeingDeclared;
14223
14224 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, CXXSpecialMemberKind CSM)
14225 : S(S), D(RD, CSM), SavedContext(S, RD) {
14226 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
14227 if (WasAlreadyBeingDeclared)
14228 // This almost never happens, but if it does, ensure that our cache
14229 // doesn't contain a stale result.
14230 S.SpecialMemberCache.clear();
14231 else {
14232 // Register a note to be produced if we encounter an error while
14233 // declaring the special member.
14234 Sema::CodeSynthesisContext Ctx;
14235 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
14236 // FIXME: We don't have a location to use here. Using the class's
14237 // location maintains the fiction that we declare all special members
14238 // with the class, but (1) it's not clear that lying about that helps our
14239 // users understand what's going on, and (2) there may be outer contexts
14240 // on the stack (some of which are relevant) and printing them exposes
14241 // our lies.
14242 Ctx.PointOfInstantiation = RD->getLocation();
14243 Ctx.Entity = RD;
14244 Ctx.SpecialMember = CSM;
14245 S.pushCodeSynthesisContext(Ctx);
14246 }
14247 }
14248 ~DeclaringSpecialMember() {
14249 if (!WasAlreadyBeingDeclared) {
14250 S.SpecialMembersBeingDeclared.erase(D);
14252 }
14253 }
14254
14255 /// Are we already trying to declare this special member?
14256 bool isAlreadyBeingDeclared() const {
14257 return WasAlreadyBeingDeclared;
14258 }
14259};
14260}
14261
14263 // Look up any existing declarations, but don't trigger declaration of all
14264 // implicit special members with this name.
14265 DeclarationName Name = FD->getDeclName();
14268 for (auto *D : FD->getParent()->lookup(Name))
14269 if (auto *Acceptable = R.getAcceptableDecl(D))
14270 R.addDecl(Acceptable);
14271 R.resolveKind();
14272 R.suppressDiagnostics();
14273
14274 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/ false,
14276}
14277
14278void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
14279 QualType ResultTy,
14280 ArrayRef<QualType> Args) {
14281 // Build an exception specification pointing back at this constructor.
14283
14284 LangAS AS = getDefaultCXXMethodAddrSpace();
14285 if (AS != LangAS::Default) {
14286 EPI.TypeQuals.addAddressSpace(AS);
14287 }
14288
14289 auto QT = Context.getFunctionType(ResultTy, Args, EPI);
14290 SpecialMem->setType(QT);
14291
14292 // During template instantiation of implicit special member functions we need
14293 // a reliable TypeSourceInfo for the function prototype in order to allow
14294 // functions to be substituted.
14295 if (inTemplateInstantiation() && isLambdaMethod(SpecialMem)) {
14296 TypeSourceInfo *TSI =
14297 Context.getTrivialTypeSourceInfo(SpecialMem->getType());
14298 SpecialMem->setTypeSourceInfo(TSI);
14299 }
14300}
14301
14303 CXXRecordDecl *ClassDecl) {
14304 // C++ [class.ctor]p5:
14305 // A default constructor for a class X is a constructor of class X
14306 // that can be called without an argument. If there is no
14307 // user-declared constructor for class X, a default constructor is
14308 // implicitly declared. An implicitly-declared default constructor
14309 // is an inline public member of its class.
14310 assert(ClassDecl->needsImplicitDefaultConstructor() &&
14311 "Should not build implicit default constructor!");
14312
14313 DeclaringSpecialMember DSM(*this, ClassDecl,
14315 if (DSM.isAlreadyBeingDeclared())
14316 return nullptr;
14317
14319 *this, ClassDecl, CXXSpecialMemberKind::DefaultConstructor, false);
14320
14321 // Create the actual constructor declaration.
14322 CanQualType ClassType = Context.getCanonicalTagType(ClassDecl);
14323 SourceLocation ClassLoc = ClassDecl->getLocation();
14324 DeclarationName Name
14325 = Context.DeclarationNames.getCXXConstructorName(ClassType);
14326 DeclarationNameInfo NameInfo(Name, ClassLoc);
14328 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),
14329 /*TInfo=*/nullptr, ExplicitSpecifier(),
14330 getCurFPFeatures().isFPConstrained(),
14331 /*isInline=*/true, /*isImplicitlyDeclared=*/true,
14334 DefaultCon->setAccess(AS_public);
14335 DefaultCon->setDefaulted();
14336
14337 setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, {});
14338
14339 if (getLangOpts().CUDA)
14340 CUDA().inferTargetForImplicitSpecialMember(
14341 ClassDecl, CXXSpecialMemberKind::DefaultConstructor, DefaultCon,
14342 /* ConstRHS */ false,
14343 /* Diagnose */ false);
14344
14345 // We don't need to use SpecialMemberIsTrivial here; triviality for default
14346 // constructors is easy to compute.
14347 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
14348
14349 // Note that we have declared this constructor.
14350 ++getASTContext().NumImplicitDefaultConstructorsDeclared;
14351
14352 Scope *S = getScopeForContext(ClassDecl);
14354
14355 if (ShouldDeleteSpecialMember(DefaultCon,
14357 SetDeclDeleted(DefaultCon, ClassLoc);
14358
14359 if (S)
14360 PushOnScopeChains(DefaultCon, S, false);
14361 ClassDecl->addDecl(DefaultCon);
14362
14363 return DefaultCon;
14364}
14365
14368 DefaultedFunctionFPFeaturesRAII RestoreFP(*this, Constructor);
14369 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
14370 !Constructor->doesThisDeclarationHaveABody() &&
14371 !Constructor->isDeleted()) &&
14372 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
14373 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
14374 return;
14375
14376 CXXRecordDecl *ClassDecl = Constructor->getParent();
14377 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
14378 if (ClassDecl->isInvalidDecl()) {
14379 return;
14380 }
14381
14383
14384 // The exception specification is needed because we are defining the
14385 // function.
14386 ResolveExceptionSpec(CurrentLocation,
14387 Constructor->getType()->castAs<FunctionProtoType>());
14388 MarkVTableUsed(CurrentLocation, ClassDecl);
14389
14390 // Add a context note for diagnostics produced after this point.
14391 Scope.addContextNote(CurrentLocation);
14392
14393 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
14394 Constructor->setInvalidDecl();
14395 return;
14396 }
14397
14398 SourceLocation Loc = Constructor->getEndLoc().isValid()
14399 ? Constructor->getEndLoc()
14400 : Constructor->getLocation();
14401 Constructor->setBody(new (Context) CompoundStmt(Loc));
14402 Constructor->markUsed(Context);
14403
14405 L->CompletedImplicitDefinition(Constructor);
14406 }
14407
14408 DiagnoseUninitializedFields(*this, Constructor);
14409
14410 // The synthesized body applies the class's NSDMIs and never reaches the
14411 // normal IssueWarnings path, so run lifetime safety on it here.
14412 AnalysisWarnings.IssueWarningsForImplicitFunction(Constructor);
14413}
14414
14416 // Perform any delayed checks on exception specifications.
14418}
14419
14420/// Find or create the fake constructor we synthesize to model constructing an
14421/// object of a derived class via a constructor of a base class.
14424 CXXConstructorDecl *BaseCtor,
14426 CXXRecordDecl *Derived = Shadow->getParent();
14427 SourceLocation UsingLoc = Shadow->getLocation();
14428
14429 // FIXME: Add a new kind of DeclarationName for an inherited constructor.
14430 // For now we use the name of the base class constructor as a member of the
14431 // derived class to indicate a (fake) inherited constructor name.
14432 DeclarationName Name = BaseCtor->getDeclName();
14433
14434 // Check to see if we already have a fake constructor for this inherited
14435 // constructor call.
14436 for (NamedDecl *Ctor : Derived->lookup(Name))
14438 ->getInheritedConstructor()
14439 .getConstructor(),
14440 BaseCtor))
14441 return cast<CXXConstructorDecl>(Ctor);
14442
14443 DeclarationNameInfo NameInfo(Name, UsingLoc);
14444 TypeSourceInfo *TInfo =
14445 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
14446 FunctionProtoTypeLoc ProtoLoc =
14448
14449 // Check the inherited constructor is valid and find the list of base classes
14450 // from which it was inherited.
14451 InheritedConstructorInfo ICI(*this, Loc, Shadow);
14452
14453 bool Constexpr = BaseCtor->isConstexpr() &&
14456 false, BaseCtor, &ICI);
14457
14459 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
14460 BaseCtor->getExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
14461 /*isInline=*/true,
14462 /*isImplicitlyDeclared=*/true,
14464 InheritedConstructor(Shadow, BaseCtor),
14465 BaseCtor->getTrailingRequiresClause());
14466 if (Shadow->isInvalidDecl())
14467 DerivedCtor->setInvalidDecl();
14468
14469 // Build an unevaluated exception specification for this fake constructor.
14470 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
14473 EPI.ExceptionSpec.SourceDecl = DerivedCtor;
14474 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
14475 FPT->getParamTypes(), EPI));
14476
14477 // Build the parameter declarations.
14479 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
14480 TypeSourceInfo *TInfo =
14481 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
14483 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
14484 FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr);
14485 PD->setScopeInfo(0, I);
14486 PD->setImplicit();
14487 // Ensure attributes are propagated onto parameters (this matters for
14488 // format, pass_object_size, ...).
14489 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
14490 ParamDecls.push_back(PD);
14491 ProtoLoc.setParam(I, PD);
14492 }
14493
14494 // Set up the new constructor.
14495 assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
14496 DerivedCtor->setAccess(BaseCtor->getAccess());
14497 DerivedCtor->setParams(ParamDecls);
14498 Derived->addDecl(DerivedCtor);
14499
14500 if (ShouldDeleteSpecialMember(DerivedCtor,
14502 SetDeclDeleted(DerivedCtor, UsingLoc);
14503
14504 return DerivedCtor;
14505}
14506
14514
14517 CXXRecordDecl *ClassDecl = Constructor->getParent();
14518 assert(Constructor->getInheritedConstructor() &&
14519 !Constructor->doesThisDeclarationHaveABody() &&
14520 !Constructor->isDeleted());
14521 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
14522 return;
14523
14524 // Initializations are performed "as if by a defaulted default constructor",
14525 // so enter the appropriate scope.
14527
14528 // The exception specification is needed because we are defining the
14529 // function.
14530 ResolveExceptionSpec(CurrentLocation,
14531 Constructor->getType()->castAs<FunctionProtoType>());
14532 MarkVTableUsed(CurrentLocation, ClassDecl);
14533
14534 // Add a context note for diagnostics produced after this point.
14535 Scope.addContextNote(CurrentLocation);
14536
14538 Constructor->getInheritedConstructor().getShadowDecl();
14539 CXXConstructorDecl *InheritedCtor =
14540 Constructor->getInheritedConstructor().getConstructor();
14541
14542 // [class.inhctor.init]p1:
14543 // initialization proceeds as if a defaulted default constructor is used to
14544 // initialize the D object and each base class subobject from which the
14545 // constructor was inherited
14546
14547 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
14548 CXXRecordDecl *RD = Shadow->getParent();
14549 SourceLocation InitLoc = Shadow->getLocation();
14550
14551 // Build explicit initializers for all base classes from which the
14552 // constructor was inherited.
14554 for (bool VBase : {false, true}) {
14555 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
14556 if (B.isVirtual() != VBase)
14557 continue;
14558
14559 auto *BaseRD = B.getType()->getAsCXXRecordDecl();
14560 if (!BaseRD)
14561 continue;
14562
14563 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
14564 if (!BaseCtor.first)
14565 continue;
14566
14567 MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
14569 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
14570
14571 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
14572 Inits.push_back(new (Context) CXXCtorInitializer(
14573 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
14574 SourceLocation()));
14575 }
14576 }
14577
14578 // We now proceed as if for a defaulted default constructor, with the relevant
14579 // initializers replaced.
14580
14581 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
14582 Constructor->setInvalidDecl();
14583 return;
14584 }
14585
14586 Constructor->setBody(new (Context) CompoundStmt(InitLoc));
14587 Constructor->markUsed(Context);
14588
14590 L->CompletedImplicitDefinition(Constructor);
14591 }
14592
14593 DiagnoseUninitializedFields(*this, Constructor);
14594
14595 // The synthesized body applies the class's NSDMIs and never reaches the
14596 // normal IssueWarnings path, so run lifetime safety on it here.
14597 AnalysisWarnings.IssueWarningsForImplicitFunction(Constructor);
14598}
14599
14601 // C++ [class.dtor]p2:
14602 // If a class has no user-declared destructor, a destructor is
14603 // declared implicitly. An implicitly-declared destructor is an
14604 // inline public member of its class.
14605 assert(ClassDecl->needsImplicitDestructor());
14606
14607 DeclaringSpecialMember DSM(*this, ClassDecl,
14609 if (DSM.isAlreadyBeingDeclared())
14610 return nullptr;
14611
14613 *this, ClassDecl, CXXSpecialMemberKind::Destructor, false);
14614
14615 // Create the actual destructor declaration.
14616 CanQualType ClassType = Context.getCanonicalTagType(ClassDecl);
14617 SourceLocation ClassLoc = ClassDecl->getLocation();
14618 DeclarationName Name
14619 = Context.DeclarationNames.getCXXDestructorName(ClassType);
14620 DeclarationNameInfo NameInfo(Name, ClassLoc);
14622 Context, ClassDecl, ClassLoc, NameInfo, QualType(), nullptr,
14623 getCurFPFeatures().isFPConstrained(),
14624 /*isInline=*/true,
14625 /*isImplicitlyDeclared=*/true,
14628 Destructor->setAccess(AS_public);
14629 Destructor->setDefaulted();
14630
14631 setupImplicitSpecialMemberType(Destructor, Context.VoidTy, {});
14632
14633 if (getLangOpts().CUDA)
14634 CUDA().inferTargetForImplicitSpecialMember(
14636 /* ConstRHS */ false,
14637 /* Diagnose */ false);
14638
14639 // We don't need to use SpecialMemberIsTrivial here; triviality for
14640 // destructors is easy to compute.
14641 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
14642 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
14643 ClassDecl->hasTrivialDestructorForCall());
14644
14645 // Note that we have declared this destructor.
14646 ++getASTContext().NumImplicitDestructorsDeclared;
14647
14648 Scope *S = getScopeForContext(ClassDecl);
14650
14651 // We can't check whether an implicit destructor is deleted before we complete
14652 // the definition of the class, because its validity depends on the alignment
14653 // of the class. We'll check this from ActOnFields once the class is complete.
14654 if (ClassDecl->isCompleteDefinition() &&
14656 SetDeclDeleted(Destructor, ClassLoc);
14657
14658 // Introduce this destructor into its scope.
14659 if (S)
14660 PushOnScopeChains(Destructor, S, false);
14661 ClassDecl->addDecl(Destructor);
14662
14663 return Destructor;
14664}
14665
14668 DefaultedFunctionFPFeaturesRAII RestoreFP(*this, Destructor);
14669 assert((Destructor->isDefaulted() &&
14670 !Destructor->doesThisDeclarationHaveABody() &&
14671 !Destructor->isDeleted()) &&
14672 "DefineImplicitDestructor - call it for implicit default dtor");
14673 if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
14674 return;
14675
14676 CXXRecordDecl *ClassDecl = Destructor->getParent();
14677 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
14678
14680
14681 // The exception specification is needed because we are defining the
14682 // function.
14683 ResolveExceptionSpec(CurrentLocation,
14684 Destructor->getType()->castAs<FunctionProtoType>());
14685 MarkVTableUsed(CurrentLocation, ClassDecl);
14686
14687 // Add a context note for diagnostics produced after this point.
14688 Scope.addContextNote(CurrentLocation);
14689
14691 Destructor->getParent());
14692
14694 Destructor->setInvalidDecl();
14695 return;
14696 }
14697
14698 SourceLocation Loc = Destructor->getEndLoc().isValid()
14699 ? Destructor->getEndLoc()
14700 : Destructor->getLocation();
14701 Destructor->setBody(new (Context) CompoundStmt(Loc));
14702 Destructor->markUsed(Context);
14703
14705 L->CompletedImplicitDefinition(Destructor);
14706 }
14707}
14708
14711 if (Destructor->isInvalidDecl())
14712 return;
14713
14714 CXXRecordDecl *ClassDecl = Destructor->getParent();
14715 assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&
14716 "implicit complete dtors unneeded outside MS ABI");
14717 assert(ClassDecl->getNumVBases() > 0 &&
14718 "complete dtor only exists for classes with vbases");
14719
14721
14722 // Add a context note for diagnostics produced after this point.
14723 Scope.addContextNote(CurrentLocation);
14724
14725 MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl);
14726}
14727
14729 // If the context is an invalid C++ class, just suppress these checks.
14730 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
14731 if (Record->isInvalidDecl()) {
14734 return;
14735 }
14737 }
14738}
14739
14742
14743 if (!DelayedDllExportMemberFunctions.empty()) {
14745 std::swap(DelayedDllExportMemberFunctions, WorkList);
14746 for (CXXMethodDecl *M : WorkList) {
14747 DefineDefaultedFunction(*this, M, M->getLocation());
14748
14749 // Pass the method to the consumer to get emitted. This is not necessary
14750 // for explicit instantiation definitions, as they will get emitted
14751 // anyway.
14752 if (M->getParent()->getTemplateSpecializationKind() !=
14755 }
14756 }
14757}
14758
14760 if (!DelayedDllExportClasses.empty()) {
14761 // Calling ReferenceDllExportedMembers might cause the current function to
14762 // be called again, so use a local copy of DelayedDllExportClasses.
14764 std::swap(DelayedDllExportClasses, WorkList);
14765 for (CXXRecordDecl *Class : WorkList)
14767 }
14768}
14769
14771 assert(getLangOpts().CPlusPlus11 &&
14772 "adjusting dtor exception specs was introduced in c++11");
14773
14774 if (Destructor->isDependentContext())
14775 return;
14776
14777 // C++11 [class.dtor]p3:
14778 // A declaration of a destructor that does not have an exception-
14779 // specification is implicitly considered to have the same exception-
14780 // specification as an implicit declaration.
14781 const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>();
14782 if (DtorType->hasExceptionSpec())
14783 return;
14784
14785 // Replace the destructor's type, building off the existing one. Fortunately,
14786 // the only thing of interest in the destructor type is its extended info.
14787 // The return and arguments are fixed.
14788 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
14791 Destructor->setType(Context.getFunctionType(Context.VoidTy, {}, EPI));
14792
14793 // FIXME: If the destructor has a body that could throw, and the newly created
14794 // spec doesn't allow exceptions, we should emit a warning, because this
14795 // change in behavior can break conforming C++03 programs at runtime.
14796 // However, we don't have a body or an exception specification yet, so it
14797 // needs to be done somewhere else.
14798}
14799
14800namespace {
14801/// An abstract base class for all helper classes used in building the
14802// copy/move operators. These classes serve as factory functions and help us
14803// avoid using the same Expr* in the AST twice.
14804class ExprBuilder {
14805 ExprBuilder(const ExprBuilder&) = delete;
14806 ExprBuilder &operator=(const ExprBuilder&) = delete;
14807
14808protected:
14809 static Expr *assertNotNull(Expr *E) {
14810 assert(E && "Expression construction must not fail.");
14811 return E;
14812 }
14813
14814public:
14815 ExprBuilder() {}
14816 virtual ~ExprBuilder() {}
14817
14818 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
14819};
14820
14821class RefBuilder: public ExprBuilder {
14822 VarDecl *Var;
14823 QualType VarType;
14824
14825public:
14826 Expr *build(Sema &S, SourceLocation Loc) const override {
14827 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));
14828 }
14829
14830 RefBuilder(VarDecl *Var, QualType VarType)
14831 : Var(Var), VarType(VarType) {}
14832};
14833
14834class ThisBuilder: public ExprBuilder {
14835public:
14836 Expr *build(Sema &S, SourceLocation Loc) const override {
14837 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
14838 }
14839};
14840
14841class CastBuilder: public ExprBuilder {
14842 const ExprBuilder &Builder;
14843 QualType Type;
14845 const CXXCastPath &Path;
14846
14847public:
14848 Expr *build(Sema &S, SourceLocation Loc) const override {
14849 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
14850 CK_UncheckedDerivedToBase, Kind,
14851 &Path).get());
14852 }
14853
14854 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
14855 const CXXCastPath &Path)
14856 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
14857};
14858
14859class DerefBuilder: public ExprBuilder {
14860 const ExprBuilder &Builder;
14861
14862public:
14863 Expr *build(Sema &S, SourceLocation Loc) const override {
14864 return assertNotNull(
14865 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
14866 }
14867
14868 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14869};
14870
14871class MemberBuilder: public ExprBuilder {
14872 const ExprBuilder &Builder;
14873 QualType Type;
14874 CXXScopeSpec SS;
14875 bool IsArrow;
14876 LookupResult &MemberLookup;
14877
14878public:
14879 Expr *build(Sema &S, SourceLocation Loc) const override {
14880 return assertNotNull(S.BuildMemberReferenceExpr(
14881 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
14882 nullptr, MemberLookup, nullptr, nullptr).get());
14883 }
14884
14885 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
14886 LookupResult &MemberLookup)
14887 : Builder(Builder), Type(Type), IsArrow(IsArrow),
14888 MemberLookup(MemberLookup) {}
14889};
14890
14891class MoveCastBuilder: public ExprBuilder {
14892 const ExprBuilder &Builder;
14893
14894public:
14895 Expr *build(Sema &S, SourceLocation Loc) const override {
14896 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
14897 }
14898
14899 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14900};
14901
14902class LvalueConvBuilder: public ExprBuilder {
14903 const ExprBuilder &Builder;
14904
14905public:
14906 Expr *build(Sema &S, SourceLocation Loc) const override {
14907 return assertNotNull(
14908 S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
14909 }
14910
14911 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14912};
14913
14914class SubscriptBuilder: public ExprBuilder {
14915 const ExprBuilder &Base;
14916 const ExprBuilder &Index;
14917
14918public:
14919 Expr *build(Sema &S, SourceLocation Loc) const override {
14920 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
14921 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
14922 }
14923
14924 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
14925 : Base(Base), Index(Index) {}
14926};
14927
14928} // end anonymous namespace
14929
14930/// When generating a defaulted copy or move assignment operator, if a field
14931/// should be copied with __builtin_memcpy rather than via explicit assignments,
14932/// do so. This optimization only applies for arrays of scalars, and for arrays
14933/// of class type where the selected copy/move-assignment operator is trivial.
14934static StmtResult
14936 const ExprBuilder &ToB, const ExprBuilder &FromB) {
14937 // Compute the size of the memory buffer to be copied.
14938 QualType SizeType = S.Context.getSizeType();
14939 llvm::APInt Size(S.Context.getTypeSize(SizeType),
14941
14942 // Take the address of the field references for "from" and "to". We
14943 // directly construct UnaryOperators here because semantic analysis
14944 // does not permit us to take the address of an xvalue.
14945 Expr *From = FromB.build(S, Loc);
14946 From = UnaryOperator::Create(
14947 S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()),
14948 VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
14949 Expr *To = ToB.build(S, Loc);
14951 S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()),
14952 VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
14953
14954 bool NeedsCollectableMemCpy = false;
14955 if (auto *RD = T->getBaseElementTypeUnsafe()->getAsRecordDecl())
14956 NeedsCollectableMemCpy = RD->hasObjectMember();
14957
14958 // Create a reference to the __builtin_objc_memmove_collectable function
14959 StringRef MemCpyName = NeedsCollectableMemCpy ?
14960 "__builtin_objc_memmove_collectable" :
14961 "__builtin_memcpy";
14962 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
14964 S.LookupName(R, S.TUScope, true);
14965
14966 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
14967 if (!MemCpy)
14968 // Something went horribly wrong earlier, and we will have complained
14969 // about it.
14970 return StmtError();
14971
14972 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
14973 VK_PRValue, Loc, nullptr);
14974 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
14975
14976 Expr *CallArgs[] = {
14977 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
14978 };
14979 ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
14980 Loc, CallArgs, Loc);
14981
14982 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
14983 return Call.getAs<Stmt>();
14984}
14985
14986/// Builds a statement that copies/moves the given entity from \p From to
14987/// \c To.
14988///
14989/// This routine is used to copy/move the members of a class with an
14990/// implicitly-declared copy/move assignment operator. When the entities being
14991/// copied are arrays, this routine builds for loops to copy them.
14992///
14993/// \param S The Sema object used for type-checking.
14994///
14995/// \param Loc The location where the implicit copy/move is being generated.
14996///
14997/// \param T The type of the expressions being copied/moved. Both expressions
14998/// must have this type.
14999///
15000/// \param To The expression we are copying/moving to.
15001///
15002/// \param From The expression we are copying/moving from.
15003///
15004/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
15005/// Otherwise, it's a non-static member subobject.
15006///
15007/// \param Copying Whether we're copying or moving.
15008///
15009/// \param Depth Internal parameter recording the depth of the recursion.
15010///
15011/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
15012/// if a memcpy should be used instead.
15013static StmtResult
15015 const ExprBuilder &To, const ExprBuilder &From,
15016 bool CopyingBaseSubobject, bool Copying,
15017 unsigned Depth = 0) {
15018 // C++11 [class.copy]p28:
15019 // Each subobject is assigned in the manner appropriate to its type:
15020 //
15021 // - if the subobject is of class type, as if by a call to operator= with
15022 // the subobject as the object expression and the corresponding
15023 // subobject of x as a single function argument (as if by explicit
15024 // qualification; that is, ignoring any possible virtual overriding
15025 // functions in more derived classes);
15026 //
15027 // C++03 [class.copy]p13:
15028 // - if the subobject is of class type, the copy assignment operator for
15029 // the class is used (as if by explicit qualification; that is,
15030 // ignoring any possible virtual overriding functions in more derived
15031 // classes);
15032 if (auto *ClassDecl = T->getAsCXXRecordDecl()) {
15033 // Look for operator=.
15034 DeclarationName Name
15036 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
15037 S.LookupQualifiedName(OpLookup, ClassDecl, false);
15038
15039 // Prior to C++11, filter out any result that isn't a copy/move-assignment
15040 // operator.
15041 if (!S.getLangOpts().CPlusPlus11) {
15042 LookupResult::Filter F = OpLookup.makeFilter();
15043 while (F.hasNext()) {
15044 NamedDecl *D = F.next();
15045 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
15046 if (Method->isCopyAssignmentOperator() ||
15047 (!Copying && Method->isMoveAssignmentOperator()))
15048 continue;
15049
15050 F.erase();
15051 }
15052 F.done();
15053 }
15054
15055 // Suppress the protected check (C++ [class.protected]) for each of the
15056 // assignment operators we found. This strange dance is required when
15057 // we're assigning via a base classes's copy-assignment operator. To
15058 // ensure that we're getting the right base class subobject (without
15059 // ambiguities), we need to cast "this" to that subobject type; to
15060 // ensure that we don't go through the virtual call mechanism, we need
15061 // to qualify the operator= name with the base class (see below). However,
15062 // this means that if the base class has a protected copy assignment
15063 // operator, the protected member access check will fail. So, we
15064 // rewrite "protected" access to "public" access in this case, since we
15065 // know by construction that we're calling from a derived class.
15066 if (CopyingBaseSubobject) {
15067 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
15068 L != LEnd; ++L) {
15069 if (L.getAccess() == AS_protected)
15070 L.setAccess(AS_public);
15071 }
15072 }
15073
15074 // Create the nested-name-specifier that will be used to qualify the
15075 // reference to operator=; this is required to suppress the virtual
15076 // call mechanism.
15077 CXXScopeSpec SS;
15078 // FIXME: Don't canonicalize this.
15079 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
15080 SS.MakeTrivial(S.Context, NestedNameSpecifier(CanonicalT), Loc);
15081
15082 // Create the reference to operator=.
15083 ExprResult OpEqualRef
15084 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false,
15085 SS, /*TemplateKWLoc=*/SourceLocation(),
15086 /*FirstQualifierInScope=*/nullptr,
15087 OpLookup,
15088 /*TemplateArgs=*/nullptr, /*S*/nullptr,
15089 /*SuppressQualifierCheck=*/true);
15090 if (OpEqualRef.isInvalid())
15091 return StmtError();
15092
15093 // Build the call to the assignment operator.
15094
15095 Expr *FromInst = From.build(S, Loc);
15096 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
15097 OpEqualRef.getAs<Expr>(),
15098 Loc, FromInst, Loc);
15099 if (Call.isInvalid())
15100 return StmtError();
15101
15102 // If we built a call to a trivial 'operator=' while copying an array,
15103 // bail out. We'll replace the whole shebang with a memcpy.
15104 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
15105 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
15106 return StmtResult((Stmt*)nullptr);
15107
15108 // Convert to an expression-statement, and clean up any produced
15109 // temporaries.
15110 return S.ActOnExprStmt(Call);
15111 }
15112
15113 // - if the subobject is of scalar type, the built-in assignment
15114 // operator is used.
15116 if (!ArrayTy) {
15118 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
15119 if (Assignment.isInvalid())
15120 return StmtError();
15121 return S.ActOnExprStmt(Assignment);
15122 }
15123
15124 // - if the subobject is an array, each element is assigned, in the
15125 // manner appropriate to the element type;
15126
15127 // Construct a loop over the array bounds, e.g.,
15128 //
15129 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
15130 //
15131 // that will copy each of the array elements.
15132 QualType SizeType = S.Context.getSizeType();
15133
15134 // Create the iteration variable.
15135 IdentifierInfo *IterationVarName = nullptr;
15136 {
15137 SmallString<8> Str;
15138 llvm::raw_svector_ostream OS(Str);
15139 OS << "__i" << Depth;
15140 IterationVarName = &S.Context.Idents.get(OS.str());
15141 }
15142 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
15143 IterationVarName, SizeType,
15144 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
15145 SC_None);
15146
15147 // Initialize the iteration variable to zero.
15148 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
15149 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
15150
15151 // Creates a reference to the iteration variable.
15152 RefBuilder IterationVarRef(IterationVar, SizeType);
15153 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
15154
15155 // Create the DeclStmt that holds the iteration variable.
15156 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
15157
15158 // Subscript the "from" and "to" expressions with the iteration variable.
15159 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
15160 MoveCastBuilder FromIndexMove(FromIndexCopy);
15161 const ExprBuilder *FromIndex;
15162 if (Copying)
15163 FromIndex = &FromIndexCopy;
15164 else
15165 FromIndex = &FromIndexMove;
15166
15167 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
15168
15169 // Build the copy/move for an individual element of the array.
15170 StmtResult Copy =
15172 ToIndex, *FromIndex, CopyingBaseSubobject,
15173 Copying, Depth + 1);
15174 // Bail out if copying fails or if we determined that we should use memcpy.
15175 if (Copy.isInvalid() || !Copy.get())
15176 return Copy;
15177
15178 // Create the comparison against the array bound.
15179 llvm::APInt Upper
15180 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
15182 S.Context, IterationVarRefRVal.build(S, Loc),
15183 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE,
15186
15187 // Create the pre-increment of the iteration variable. We can determine
15188 // whether the increment will overflow based on the value of the array
15189 // bound.
15190 Expr *Increment = UnaryOperator::Create(
15191 S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue,
15192 OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides());
15193
15194 // Construct the loop that copies all elements of this array.
15195 return S.ActOnForStmt(
15196 Loc, Loc, InitStmt,
15198 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
15199}
15200
15201static StmtResult
15203 const ExprBuilder &To, const ExprBuilder &From,
15204 bool CopyingBaseSubobject, bool Copying) {
15205 // Maybe we should use a memcpy?
15206 if (T->isArrayType() && !T.hasQualifiers() &&
15207 T.isTriviallyCopyableType(S.Context))
15208 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
15209
15210 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
15211 CopyingBaseSubobject,
15212 Copying, 0));
15213
15214 // If we ended up picking a trivial assignment operator for an array of a
15215 // non-trivially-copyable class type, just emit a memcpy.
15216 if (!Result.isInvalid() && !Result.get())
15217 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
15218
15219 return Result;
15220}
15221
15223 // Note: The following rules are largely analoguous to the copy
15224 // constructor rules. Note that virtual bases are not taken into account
15225 // for determining the argument type of the operator. Note also that
15226 // operators taking an object instead of a reference are allowed.
15227 assert(ClassDecl->needsImplicitCopyAssignment());
15228
15229 DeclaringSpecialMember DSM(*this, ClassDecl,
15231 if (DSM.isAlreadyBeingDeclared())
15232 return nullptr;
15233
15235 /*Qualifier=*/std::nullopt, ClassDecl,
15236 /*OwnsTag=*/false);
15238 if (AS != LangAS::Default)
15239 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
15240 QualType RetType = Context.getLValueReferenceType(ArgType);
15241 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
15242 if (Const)
15243 ArgType = ArgType.withConst();
15244
15245 ArgType = Context.getLValueReferenceType(ArgType);
15246
15248 *this, ClassDecl, CXXSpecialMemberKind::CopyAssignment, Const);
15249
15250 // An implicitly-declared copy assignment operator is an inline public
15251 // member of its class.
15252 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
15253 SourceLocation ClassLoc = ClassDecl->getLocation();
15254 DeclarationNameInfo NameInfo(Name, ClassLoc);
15256 Context, ClassDecl, ClassLoc, NameInfo, QualType(),
15257 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
15258 getCurFPFeatures().isFPConstrained(),
15259 /*isInline=*/true,
15261 SourceLocation());
15262 CopyAssignment->setAccess(AS_public);
15263 CopyAssignment->setDefaulted();
15264 CopyAssignment->setImplicit();
15265
15266 setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
15267
15268 if (getLangOpts().CUDA)
15269 CUDA().inferTargetForImplicitSpecialMember(
15271 /* ConstRHS */ Const,
15272 /* Diagnose */ false);
15273
15274 // Add the parameter to the operator.
15276 ClassLoc, ClassLoc,
15277 /*Id=*/nullptr, ArgType,
15278 /*TInfo=*/nullptr, SC_None,
15279 nullptr);
15280 CopyAssignment->setParams(FromParam);
15281
15282 CopyAssignment->setTrivial(
15286 : ClassDecl->hasTrivialCopyAssignment());
15287
15288 // Note that we have added this copy-assignment operator.
15289 ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
15290
15291 Scope *S = getScopeForContext(ClassDecl);
15293
15297 SetDeclDeleted(CopyAssignment, ClassLoc);
15298 }
15299
15300 if (S)
15302 ClassDecl->addDecl(CopyAssignment);
15303
15304 return CopyAssignment;
15305}
15306
15307/// Diagnose an implicit copy operation for a class which is odr-used, but
15308/// which is deprecated because the class has a user-declared copy constructor,
15309/// copy assignment operator, or destructor.
15311 assert(CopyOp->isImplicit());
15312
15313 CXXRecordDecl *RD = CopyOp->getParent();
15314 CXXMethodDecl *UserDeclaredOperation = nullptr;
15315
15316 if (RD->hasUserDeclaredDestructor()) {
15317 UserDeclaredOperation = RD->getDestructor();
15318 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
15320 // Find any user-declared copy constructor.
15321 for (auto *I : RD->ctors()) {
15322 if (I->isCopyConstructor()) {
15323 UserDeclaredOperation = I;
15324 break;
15325 }
15326 }
15327 assert(UserDeclaredOperation);
15328 } else if (isa<CXXConstructorDecl>(CopyOp) &&
15330 // Find any user-declared move assignment operator.
15331 for (auto *I : RD->methods()) {
15332 if (I->isCopyAssignmentOperator()) {
15333 UserDeclaredOperation = I;
15334 break;
15335 }
15336 }
15337 assert(UserDeclaredOperation);
15338 }
15339
15340 if (UserDeclaredOperation) {
15341 bool UDOIsUserProvided = UserDeclaredOperation->isUserProvided();
15342 bool UDOIsDestructor = isa<CXXDestructorDecl>(UserDeclaredOperation);
15343 bool IsCopyAssignment = !isa<CXXConstructorDecl>(CopyOp);
15344 unsigned DiagID =
15345 (UDOIsUserProvided && UDOIsDestructor)
15346 ? diag::warn_deprecated_copy_with_user_provided_dtor
15347 : (UDOIsUserProvided && !UDOIsDestructor)
15348 ? diag::warn_deprecated_copy_with_user_provided_copy
15349 : (!UDOIsUserProvided && UDOIsDestructor)
15350 ? diag::warn_deprecated_copy_with_dtor
15351 : diag::warn_deprecated_copy;
15352 S.Diag(UserDeclaredOperation->getLocation(), DiagID)
15353 << RD << IsCopyAssignment;
15354 }
15355}
15356
15358 CXXMethodDecl *CopyAssignOperator) {
15359 DefaultedFunctionFPFeaturesRAII RestoreFP(*this, CopyAssignOperator);
15360 assert((CopyAssignOperator->isDefaulted() &&
15361 CopyAssignOperator->isOverloadedOperator() &&
15362 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
15363 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
15364 !CopyAssignOperator->isDeleted()) &&
15365 "DefineImplicitCopyAssignment called for wrong function");
15366 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
15367 return;
15368
15369 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
15370 if (ClassDecl->isInvalidDecl()) {
15371 CopyAssignOperator->setInvalidDecl();
15372 return;
15373 }
15374
15375 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
15376
15377 // The exception specification is needed because we are defining the
15378 // function.
15379 ResolveExceptionSpec(CurrentLocation,
15380 CopyAssignOperator->getType()->castAs<FunctionProtoType>());
15381
15382 // Add a context note for diagnostics produced after this point.
15383 Scope.addContextNote(CurrentLocation);
15384
15385 // C++11 [class.copy]p18:
15386 // The [definition of an implicitly declared copy assignment operator] is
15387 // deprecated if the class has a user-declared copy constructor or a
15388 // user-declared destructor.
15389 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
15390 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
15391
15392 // C++0x [class.copy]p30:
15393 // The implicitly-defined or explicitly-defaulted copy assignment operator
15394 // for a non-union class X performs memberwise copy assignment of its
15395 // subobjects. The direct base classes of X are assigned first, in the
15396 // order of their declaration in the base-specifier-list, and then the
15397 // immediate non-static data members of X are assigned, in the order in
15398 // which they were declared in the class definition.
15399
15400 // The statements that form the synthesized function body.
15401 SmallVector<Stmt*, 8> Statements;
15402
15403 // The parameter for the "other" object, which we are copying from.
15404 ParmVarDecl *Other = CopyAssignOperator->getNonObjectParameter(0);
15405 Qualifiers OtherQuals = Other->getType().getQualifiers();
15406 QualType OtherRefType = Other->getType();
15407 if (OtherRefType->isLValueReferenceType()) {
15408 OtherRefType = OtherRefType->getPointeeType();
15409 OtherQuals = OtherRefType.getQualifiers();
15410 }
15411
15412 // Our location for everything implicitly-generated.
15413 SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
15414 ? CopyAssignOperator->getEndLoc()
15415 : CopyAssignOperator->getLocation();
15416
15417 // Builds a DeclRefExpr for the "other" object.
15418 RefBuilder OtherRef(Other, OtherRefType);
15419
15420 // Builds the function object parameter.
15421 std::optional<ThisBuilder> This;
15422 std::optional<DerefBuilder> DerefThis;
15423 std::optional<RefBuilder> ExplicitObject;
15424 bool IsArrow = false;
15425 QualType ObjectType;
15426 if (CopyAssignOperator->isExplicitObjectMemberFunction()) {
15427 ObjectType = CopyAssignOperator->getParamDecl(0)->getType();
15428 if (ObjectType->isReferenceType())
15429 ObjectType = ObjectType->getPointeeType();
15430 ExplicitObject.emplace(CopyAssignOperator->getParamDecl(0), ObjectType);
15431 } else {
15432 ObjectType = getCurrentThisType();
15433 This.emplace();
15434 DerefThis.emplace(*This);
15435 IsArrow = !LangOpts.HLSL;
15436 }
15437 ExprBuilder &ObjectParameter =
15438 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15439 : static_cast<ExprBuilder &>(*This);
15440
15441 // Assign base classes.
15442 bool Invalid = false;
15443 for (auto &Base : ClassDecl->bases()) {
15444 // Form the assignment:
15445 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
15446 QualType BaseType = Base.getType().getUnqualifiedType();
15447 if (!BaseType->isRecordType()) {
15448 Invalid = true;
15449 continue;
15450 }
15451
15452 CXXCastPath BasePath;
15453 BasePath.push_back(&Base);
15454
15455 // Construct the "from" expression, which is an implicit cast to the
15456 // appropriately-qualified base type.
15457 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
15458 VK_LValue, BasePath);
15459
15460 // Dereference "this".
15461 CastBuilder To(
15462 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15463 : static_cast<ExprBuilder &>(*DerefThis),
15464 Context.getQualifiedType(BaseType, ObjectType.getQualifiers()),
15465 VK_LValue, BasePath);
15466
15467 // Build the copy.
15468 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
15469 To, From,
15470 /*CopyingBaseSubobject=*/true,
15471 /*Copying=*/true);
15472 if (Copy.isInvalid()) {
15473 CopyAssignOperator->setInvalidDecl();
15474 return;
15475 }
15476
15477 // Success! Record the copy.
15478 Statements.push_back(Copy.getAs<Expr>());
15479 }
15480
15481 // A defaulted copy assignment operator for a union copies the object
15482 // representation as if by a memcpy, the same way the defaulted union copy
15483 // constructor does. The memberwise loop below skips union members.
15484 if (ClassDecl->isUnion()) {
15485 ExprBuilder &To = ExplicitObject
15486 ? static_cast<ExprBuilder &>(*ExplicitObject)
15487 : static_cast<ExprBuilder &>(*DerefThis);
15488 // Copying the object representation is correct even for a union that is
15489 // not trivially copyable, so -Wnontrivial-memcall is a false positive
15490 // here. Ignoring warnings rather than casting the arguments to void*
15491 // keeps them typed, which preserves their address space.
15492 IgnoreAllWarningDiagRAII IgnoreWarnings(Diags);
15494 *this, Loc, Context.getCanonicalTagType(ClassDecl), To, OtherRef);
15495 if (Copy.isInvalid()) {
15496 CopyAssignOperator->setInvalidDecl();
15497 return;
15498 }
15499 Statements.push_back(Copy.getAs<Stmt>());
15500 }
15501
15502 // Assign non-static members.
15503 for (auto *Field : ClassDecl->fields()) {
15504 // Union members are copied by the whole-object memcpy emitted above.
15505 if (Field->isUnnamedBitField() || Field->getParent()->isUnion())
15506 continue;
15507
15508 if (Field->isInvalidDecl()) {
15509 Invalid = true;
15510 continue;
15511 }
15512
15513 // Check for members of reference type; we can't copy those.
15514 if (Field->getType()->isReferenceType()) {
15515 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15516 << Context.getCanonicalTagType(ClassDecl) << 0
15517 << Field->getDeclName();
15518 Diag(Field->getLocation(), diag::note_declared_at);
15519 Invalid = true;
15520 continue;
15521 }
15522
15523 // Check for members of const-qualified, non-class type.
15524 QualType BaseType = Context.getBaseElementType(Field->getType());
15525 if (!BaseType->isRecordType() && BaseType.isConstQualified()) {
15526 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15527 << Context.getCanonicalTagType(ClassDecl) << 1
15528 << Field->getDeclName();
15529 Diag(Field->getLocation(), diag::note_declared_at);
15530 Invalid = true;
15531 continue;
15532 }
15533
15534 // Suppress assigning zero-width bitfields.
15535 if (Field->isZeroLengthBitField())
15536 continue;
15537
15538 QualType FieldType = Field->getType().getNonReferenceType();
15539 if (FieldType->isIncompleteArrayType()) {
15540 assert(ClassDecl->hasFlexibleArrayMember() &&
15541 "Incomplete array type is not valid");
15542 continue;
15543 }
15544
15545 // Build references to the field in the object we're copying from and to.
15546 CXXScopeSpec SS; // Intentionally empty
15547 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
15549 MemberLookup.addDecl(Field);
15550 MemberLookup.resolveKind();
15551
15552 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
15553 MemberBuilder To(ObjectParameter, ObjectType, IsArrow, MemberLookup);
15554 // Build the copy of this field.
15555 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
15556 To, From,
15557 /*CopyingBaseSubobject=*/false,
15558 /*Copying=*/true);
15559 if (Copy.isInvalid()) {
15560 CopyAssignOperator->setInvalidDecl();
15561 return;
15562 }
15563
15564 // Success! Record the copy.
15565 Statements.push_back(Copy.getAs<Stmt>());
15566 }
15567
15568 if (!Invalid) {
15569 // Add a "return *this;"
15570 Expr *ThisExpr =
15571 (ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15572 : LangOpts.HLSL ? static_cast<ExprBuilder &>(*This)
15573 : static_cast<ExprBuilder &>(*DerefThis))
15574 .build(*this, Loc);
15575 StmtResult Return = BuildReturnStmt(Loc, ThisExpr);
15576 if (Return.isInvalid())
15577 Invalid = true;
15578 else
15579 Statements.push_back(Return.getAs<Stmt>());
15580 }
15581
15582 if (Invalid) {
15583 CopyAssignOperator->setInvalidDecl();
15584 return;
15585 }
15586
15587 StmtResult Body;
15588 {
15589 CompoundScopeRAII CompoundScope(*this);
15590 Body = ActOnCompoundStmt(Loc, Loc, Statements,
15591 /*isStmtExpr=*/false);
15592 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
15593 }
15594 CopyAssignOperator->setBody(Body.getAs<Stmt>());
15595 CopyAssignOperator->markUsed(Context);
15596
15598 L->CompletedImplicitDefinition(CopyAssignOperator);
15599 }
15600}
15601
15603 assert(ClassDecl->needsImplicitMoveAssignment());
15604
15605 DeclaringSpecialMember DSM(*this, ClassDecl,
15607 if (DSM.isAlreadyBeingDeclared())
15608 return nullptr;
15609
15610 // Note: The following rules are largely analoguous to the move
15611 // constructor rules.
15612
15614 /*Qualifier=*/std::nullopt, ClassDecl,
15615 /*OwnsTag=*/false);
15617 if (AS != LangAS::Default)
15618 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
15619 QualType RetType = Context.getLValueReferenceType(ArgType);
15620 ArgType = Context.getRValueReferenceType(ArgType);
15621
15623 *this, ClassDecl, CXXSpecialMemberKind::MoveAssignment, false);
15624
15625 // An implicitly-declared move assignment operator is an inline public
15626 // member of its class.
15627 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
15628 SourceLocation ClassLoc = ClassDecl->getLocation();
15629 DeclarationNameInfo NameInfo(Name, ClassLoc);
15631 Context, ClassDecl, ClassLoc, NameInfo, QualType(),
15632 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
15633 getCurFPFeatures().isFPConstrained(),
15634 /*isInline=*/true,
15636 SourceLocation());
15637 MoveAssignment->setAccess(AS_public);
15638 MoveAssignment->setDefaulted();
15639 MoveAssignment->setImplicit();
15640
15641 setupImplicitSpecialMemberType(MoveAssignment, RetType, ArgType);
15642
15643 if (getLangOpts().CUDA)
15644 CUDA().inferTargetForImplicitSpecialMember(
15646 /* ConstRHS */ false,
15647 /* Diagnose */ false);
15648
15649 // Add the parameter to the operator.
15651 ClassLoc, ClassLoc,
15652 /*Id=*/nullptr, ArgType,
15653 /*TInfo=*/nullptr, SC_None,
15654 nullptr);
15655 MoveAssignment->setParams(FromParam);
15656
15657 MoveAssignment->setTrivial(
15661 : ClassDecl->hasTrivialMoveAssignment());
15662
15663 // Note that we have added this copy-assignment operator.
15664 ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
15665
15666 Scope *S = getScopeForContext(ClassDecl);
15668
15672 SetDeclDeleted(MoveAssignment, ClassLoc);
15673 }
15674
15675 if (S)
15677 ClassDecl->addDecl(MoveAssignment);
15678
15679 return MoveAssignment;
15680}
15681
15682/// Check if we're implicitly defining a move assignment operator for a class
15683/// with virtual bases. Such a move assignment might move-assign the virtual
15684/// base multiple times.
15686 SourceLocation CurrentLocation) {
15687 assert(!Class->isDependentContext() && "should not define dependent move");
15688
15689 // Only a virtual base could get implicitly move-assigned multiple times.
15690 // Only a non-trivial move assignment can observe this. We only want to
15691 // diagnose if we implicitly define an assignment operator that assigns
15692 // two base classes, both of which move-assign the same virtual base.
15693 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
15694 Class->getNumBases() < 2)
15695 return;
15696
15698 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
15699 VBaseMap VBases;
15700
15701 for (auto &BI : Class->bases()) {
15702 Worklist.push_back(&BI);
15703 while (!Worklist.empty()) {
15704 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
15705 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
15706
15707 // If the base has no non-trivial move assignment operators,
15708 // we don't care about moves from it.
15709 if (!Base->hasNonTrivialMoveAssignment())
15710 continue;
15711
15712 // If there's nothing virtual here, skip it.
15713 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
15714 continue;
15715
15716 // If we're not actually going to call a move assignment for this base,
15717 // or the selected move assignment is trivial, skip it.
15720 /*ConstArg*/ false, /*VolatileArg*/ false,
15721 /*RValueThis*/ true, /*ConstThis*/ false,
15722 /*VolatileThis*/ false);
15723 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
15725 continue;
15726
15727 if (BaseSpec->isVirtual()) {
15728 // We're going to move-assign this virtual base, and its move
15729 // assignment operator is not trivial. If this can happen for
15730 // multiple distinct direct bases of Class, diagnose it. (If it
15731 // only happens in one base, we'll diagnose it when synthesizing
15732 // that base class's move assignment operator.)
15733 CXXBaseSpecifier *&Existing =
15734 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
15735 .first->second;
15736 if (Existing && Existing != &BI) {
15737 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
15738 << Class << Base;
15739 S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
15740 << (Base->getCanonicalDecl() ==
15742 << Base << Existing->getType() << Existing->getSourceRange();
15743 S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
15744 << (Base->getCanonicalDecl() ==
15745 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
15746 << Base << BI.getType() << BaseSpec->getSourceRange();
15747
15748 // Only diagnose each vbase once.
15749 Existing = nullptr;
15750 }
15751 } else {
15752 // Only walk over bases that have defaulted move assignment operators.
15753 // We assume that any user-provided move assignment operator handles
15754 // the multiple-moves-of-vbase case itself somehow.
15755 if (!SMOR.getMethod()->isDefaulted())
15756 continue;
15757
15758 // We're going to move the base classes of Base. Add them to the list.
15759 llvm::append_range(Worklist, llvm::make_pointer_range(Base->bases()));
15760 }
15761 }
15762 }
15763}
15764
15766 CXXMethodDecl *MoveAssignOperator) {
15767 DefaultedFunctionFPFeaturesRAII RestoreFP(*this, MoveAssignOperator);
15768 assert((MoveAssignOperator->isDefaulted() &&
15769 MoveAssignOperator->isOverloadedOperator() &&
15770 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
15771 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
15772 !MoveAssignOperator->isDeleted()) &&
15773 "DefineImplicitMoveAssignment called for wrong function");
15774 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
15775 return;
15776
15777 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
15778 if (ClassDecl->isInvalidDecl()) {
15779 MoveAssignOperator->setInvalidDecl();
15780 return;
15781 }
15782
15783 // C++0x [class.copy]p28:
15784 // The implicitly-defined or move assignment operator for a non-union class
15785 // X performs memberwise move assignment of its subobjects. The direct base
15786 // classes of X are assigned first, in the order of their declaration in the
15787 // base-specifier-list, and then the immediate non-static data members of X
15788 // are assigned, in the order in which they were declared in the class
15789 // definition.
15790
15791 // Issue a warning if our implicit move assignment operator will move
15792 // from a virtual base more than once.
15793 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
15794
15795 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
15796
15797 // The exception specification is needed because we are defining the
15798 // function.
15799 ResolveExceptionSpec(CurrentLocation,
15800 MoveAssignOperator->getType()->castAs<FunctionProtoType>());
15801
15802 // Add a context note for diagnostics produced after this point.
15803 Scope.addContextNote(CurrentLocation);
15804
15805 // The statements that form the synthesized function body.
15806 SmallVector<Stmt*, 8> Statements;
15807
15808 // The parameter for the "other" object, which we are move from.
15809 ParmVarDecl *Other = MoveAssignOperator->getNonObjectParameter(0);
15810 QualType OtherRefType =
15811 Other->getType()->castAs<RValueReferenceType>()->getPointeeType();
15812
15813 // Our location for everything implicitly-generated.
15814 SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
15815 ? MoveAssignOperator->getEndLoc()
15816 : MoveAssignOperator->getLocation();
15817
15818 // Builds a reference to the "other" object.
15819 RefBuilder OtherRef(Other, OtherRefType);
15820 // Cast to rvalue.
15821 MoveCastBuilder MoveOther(OtherRef);
15822
15823 // Builds the function object parameter.
15824 std::optional<ThisBuilder> This;
15825 std::optional<DerefBuilder> DerefThis;
15826 std::optional<RefBuilder> ExplicitObject;
15827 QualType ObjectType;
15828 bool IsArrow = false;
15829 if (MoveAssignOperator->isExplicitObjectMemberFunction()) {
15830 ObjectType = MoveAssignOperator->getParamDecl(0)->getType();
15831 if (ObjectType->isReferenceType())
15832 ObjectType = ObjectType->getPointeeType();
15833 ExplicitObject.emplace(MoveAssignOperator->getParamDecl(0), ObjectType);
15834 } else {
15835 ObjectType = getCurrentThisType();
15836 This.emplace();
15837 DerefThis.emplace(*This);
15838 IsArrow = !getLangOpts().HLSL;
15839 }
15840 ExprBuilder &ObjectParameter =
15841 ExplicitObject ? *ExplicitObject : static_cast<ExprBuilder &>(*This);
15842
15843 // Assign base classes.
15844 bool Invalid = false;
15845 for (auto &Base : ClassDecl->bases()) {
15846 // C++11 [class.copy]p28:
15847 // It is unspecified whether subobjects representing virtual base classes
15848 // are assigned more than once by the implicitly-defined copy assignment
15849 // operator.
15850 // FIXME: Do not assign to a vbase that will be assigned by some other base
15851 // class. For a move-assignment, this can result in the vbase being moved
15852 // multiple times.
15853
15854 // Form the assignment:
15855 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
15856 QualType BaseType = Base.getType().getUnqualifiedType();
15857 if (!BaseType->isRecordType()) {
15858 Invalid = true;
15859 continue;
15860 }
15861
15862 CXXCastPath BasePath;
15863 BasePath.push_back(&Base);
15864
15865 // Construct the "from" expression, which is an implicit cast to the
15866 // appropriately-qualified base type.
15867 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
15868
15869 // Implicitly cast "this" to the appropriately-qualified base type.
15870 // Dereference "this".
15871 CastBuilder To(
15872 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15873 : static_cast<ExprBuilder &>(*DerefThis),
15874 Context.getQualifiedType(BaseType, ObjectType.getQualifiers()),
15875 VK_LValue, BasePath);
15876
15877 // Build the move.
15878 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
15879 To, From,
15880 /*CopyingBaseSubobject=*/true,
15881 /*Copying=*/false);
15882 if (Move.isInvalid()) {
15883 MoveAssignOperator->setInvalidDecl();
15884 return;
15885 }
15886
15887 // Success! Record the move.
15888 Statements.push_back(Move.getAs<Expr>());
15889 }
15890
15891 // A defaulted move assignment operator for a union copies the object
15892 // representation as if by a memcpy, the same way the defaulted union copy
15893 // constructor does. The memberwise loop below skips union members.
15894 if (ClassDecl->isUnion()) {
15895 ExprBuilder &To = ExplicitObject
15896 ? static_cast<ExprBuilder &>(*ExplicitObject)
15897 : static_cast<ExprBuilder &>(*DerefThis);
15898 // Copying the object representation is correct even for a union that is
15899 // not trivially copyable, so -Wnontrivial-memcall is a false positive
15900 // here. Ignoring warnings rather than casting the arguments to void*
15901 // keeps them typed, which preserves their address space.
15902 IgnoreAllWarningDiagRAII IgnoreWarnings(Diags);
15904 *this, Loc, Context.getCanonicalTagType(ClassDecl), To, OtherRef);
15905 if (Copy.isInvalid()) {
15906 MoveAssignOperator->setInvalidDecl();
15907 return;
15908 }
15909 Statements.push_back(Copy.getAs<Stmt>());
15910 }
15911
15912 // Assign non-static members.
15913 for (auto *Field : ClassDecl->fields()) {
15914 // Union members are copied by the whole-object memcpy emitted above.
15915 if (Field->isUnnamedBitField() || Field->getParent()->isUnion())
15916 continue;
15917
15918 if (Field->isInvalidDecl()) {
15919 Invalid = true;
15920 continue;
15921 }
15922
15923 // Check for members of reference type; we can't move those.
15924 if (Field->getType()->isReferenceType()) {
15925 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15926 << Context.getCanonicalTagType(ClassDecl) << 0
15927 << Field->getDeclName();
15928 Diag(Field->getLocation(), diag::note_declared_at);
15929 Invalid = true;
15930 continue;
15931 }
15932
15933 // Check for members of const-qualified, non-class type.
15934 QualType BaseType = Context.getBaseElementType(Field->getType());
15935 if (!BaseType->isRecordType() && BaseType.isConstQualified()) {
15936 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15937 << Context.getCanonicalTagType(ClassDecl) << 1
15938 << Field->getDeclName();
15939 Diag(Field->getLocation(), diag::note_declared_at);
15940 Invalid = true;
15941 continue;
15942 }
15943
15944 // Suppress assigning zero-width bitfields.
15945 if (Field->isZeroLengthBitField())
15946 continue;
15947
15948 QualType FieldType = Field->getType().getNonReferenceType();
15949 if (FieldType->isIncompleteArrayType()) {
15950 assert(ClassDecl->hasFlexibleArrayMember() &&
15951 "Incomplete array type is not valid");
15952 continue;
15953 }
15954
15955 // Build references to the field in the object we're copying from and to.
15956 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
15958 MemberLookup.addDecl(Field);
15959 MemberLookup.resolveKind();
15960 MemberBuilder From(MoveOther, OtherRefType,
15961 /*IsArrow=*/false, MemberLookup);
15962 MemberBuilder To(ObjectParameter, ObjectType, IsArrow, MemberLookup);
15963
15964 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
15965 "Member reference with rvalue base must be rvalue except for reference "
15966 "members, which aren't allowed for move assignment.");
15967
15968 // Build the move of this field.
15969 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
15970 To, From,
15971 /*CopyingBaseSubobject=*/false,
15972 /*Copying=*/false);
15973 if (Move.isInvalid()) {
15974 MoveAssignOperator->setInvalidDecl();
15975 return;
15976 }
15977
15978 // Success! Record the copy.
15979 Statements.push_back(Move.getAs<Stmt>());
15980 }
15981
15982 if (!Invalid) {
15983 // Add a "return *this;"
15984 Expr *ThisExpr =
15985 (ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15986 : LangOpts.HLSL ? static_cast<ExprBuilder &>(*This)
15987 : static_cast<ExprBuilder &>(*DerefThis))
15988 .build(*this, Loc);
15989
15990 StmtResult Return = BuildReturnStmt(Loc, ThisExpr);
15991 if (Return.isInvalid())
15992 Invalid = true;
15993 else
15994 Statements.push_back(Return.getAs<Stmt>());
15995 }
15996
15997 if (Invalid) {
15998 MoveAssignOperator->setInvalidDecl();
15999 return;
16000 }
16001
16002 StmtResult Body;
16003 {
16004 CompoundScopeRAII CompoundScope(*this);
16005 Body = ActOnCompoundStmt(Loc, Loc, Statements,
16006 /*isStmtExpr=*/false);
16007 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
16008 }
16009 MoveAssignOperator->setBody(Body.getAs<Stmt>());
16010 MoveAssignOperator->markUsed(Context);
16011
16013 L->CompletedImplicitDefinition(MoveAssignOperator);
16014 }
16015}
16016
16018 CXXRecordDecl *ClassDecl) {
16019 // C++ [class.copy]p4:
16020 // If the class definition does not explicitly declare a copy
16021 // constructor, one is declared implicitly.
16022 assert(ClassDecl->needsImplicitCopyConstructor());
16023
16024 DeclaringSpecialMember DSM(*this, ClassDecl,
16026 if (DSM.isAlreadyBeingDeclared())
16027 return nullptr;
16028
16029 QualType ClassType = Context.getTagType(ElaboratedTypeKeyword::None,
16030 /*Qualifier=*/std::nullopt, ClassDecl,
16031 /*OwnsTag=*/false);
16032 QualType ArgType = ClassType;
16033 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
16034 if (Const)
16035 ArgType = ArgType.withConst();
16036
16038 if (AS != LangAS::Default)
16039 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
16040
16041 ArgType = Context.getLValueReferenceType(ArgType);
16042
16044 *this, ClassDecl, CXXSpecialMemberKind::CopyConstructor, Const);
16045
16046 DeclarationName Name
16047 = Context.DeclarationNames.getCXXConstructorName(
16048 Context.getCanonicalType(ClassType));
16049 SourceLocation ClassLoc = ClassDecl->getLocation();
16050 DeclarationNameInfo NameInfo(Name, ClassLoc);
16051
16052 // An implicitly-declared copy constructor is an inline public
16053 // member of its class.
16055 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
16056 ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
16057 /*isInline=*/true,
16058 /*isImplicitlyDeclared=*/true,
16061 CopyConstructor->setAccess(AS_public);
16062 CopyConstructor->setDefaulted();
16063
16064 setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
16065
16066 if (getLangOpts().CUDA)
16067 CUDA().inferTargetForImplicitSpecialMember(
16069 /* ConstRHS */ Const,
16070 /* Diagnose */ false);
16071
16072 // During template instantiation of special member functions we need a
16073 // reliable TypeSourceInfo for the parameter types in order to allow functions
16074 // to be substituted.
16075 TypeSourceInfo *TSI = nullptr;
16076 if (inTemplateInstantiation() && ClassDecl->isLambda())
16077 TSI = Context.getTrivialTypeSourceInfo(ArgType);
16078
16079 // Add the parameter to the constructor.
16080 ParmVarDecl *FromParam =
16081 ParmVarDecl::Create(Context, CopyConstructor, ClassLoc, ClassLoc,
16082 /*IdentifierInfo=*/nullptr, ArgType,
16083 /*TInfo=*/TSI, SC_None, nullptr);
16084 CopyConstructor->setParams(FromParam);
16085
16086 CopyConstructor->setTrivial(
16090 : ClassDecl->hasTrivialCopyConstructor());
16091
16092 CopyConstructor->setTrivialForCall(
16093 ClassDecl->hasAttr<TrivialABIAttr>() ||
16098 : ClassDecl->hasTrivialCopyConstructorForCall()));
16099
16100 // Note that we have declared this constructor.
16101 ++getASTContext().NumImplicitCopyConstructorsDeclared;
16102
16103 Scope *S = getScopeForContext(ClassDecl);
16105
16110 }
16111
16112 if (S)
16114 ClassDecl->addDecl(CopyConstructor);
16115
16116 return CopyConstructor;
16117}
16118
16121 DefaultedFunctionFPFeaturesRAII RestoreFP(*this, CopyConstructor);
16122 assert((CopyConstructor->isDefaulted() &&
16123 CopyConstructor->isCopyConstructor() &&
16124 !CopyConstructor->doesThisDeclarationHaveABody() &&
16125 !CopyConstructor->isDeleted()) &&
16126 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
16127 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
16128 return;
16129
16130 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
16131 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
16132
16134
16135 // The exception specification is needed because we are defining the
16136 // function.
16137 ResolveExceptionSpec(CurrentLocation,
16138 CopyConstructor->getType()->castAs<FunctionProtoType>());
16139 MarkVTableUsed(CurrentLocation, ClassDecl);
16140
16141 // Add a context note for diagnostics produced after this point.
16142 Scope.addContextNote(CurrentLocation);
16143
16144 // C++11 [class.copy]p7:
16145 // The [definition of an implicitly declared copy constructor] is
16146 // deprecated if the class has a user-declared copy assignment operator
16147 // or a user-declared destructor.
16148 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
16150
16151 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
16152 CopyConstructor->setInvalidDecl();
16153 } else {
16154 SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
16155 ? CopyConstructor->getEndLoc()
16156 : CopyConstructor->getLocation();
16157 Sema::CompoundScopeRAII CompoundScope(*this);
16158 CopyConstructor->setBody(
16159 ActOnCompoundStmt(Loc, Loc, {}, /*isStmtExpr=*/false).getAs<Stmt>());
16160 CopyConstructor->markUsed(Context);
16161 }
16162
16164 L->CompletedImplicitDefinition(CopyConstructor);
16165 }
16166}
16167
16169 CXXRecordDecl *ClassDecl) {
16170 assert(ClassDecl->needsImplicitMoveConstructor());
16171
16172 DeclaringSpecialMember DSM(*this, ClassDecl,
16174 if (DSM.isAlreadyBeingDeclared())
16175 return nullptr;
16176
16177 QualType ClassType = Context.getTagType(ElaboratedTypeKeyword::None,
16178 /*Qualifier=*/std::nullopt, ClassDecl,
16179 /*OwnsTag=*/false);
16180
16181 QualType ArgType = ClassType;
16183 if (AS != LangAS::Default)
16184 ArgType = Context.getAddrSpaceQualType(ClassType, AS);
16185 ArgType = Context.getRValueReferenceType(ArgType);
16186
16188 *this, ClassDecl, CXXSpecialMemberKind::MoveConstructor, false);
16189
16190 DeclarationName Name
16191 = Context.DeclarationNames.getCXXConstructorName(
16192 Context.getCanonicalType(ClassType));
16193 SourceLocation ClassLoc = ClassDecl->getLocation();
16194 DeclarationNameInfo NameInfo(Name, ClassLoc);
16195
16196 // C++11 [class.copy]p11:
16197 // An implicitly-declared copy/move constructor is an inline public
16198 // member of its class.
16200 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
16201 ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
16202 /*isInline=*/true,
16203 /*isImplicitlyDeclared=*/true,
16206 MoveConstructor->setAccess(AS_public);
16207 MoveConstructor->setDefaulted();
16208
16209 setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
16210
16211 if (getLangOpts().CUDA)
16212 CUDA().inferTargetForImplicitSpecialMember(
16214 /* ConstRHS */ false,
16215 /* Diagnose */ false);
16216
16217 // Add the parameter to the constructor.
16219 ClassLoc, ClassLoc,
16220 /*IdentifierInfo=*/nullptr,
16221 ArgType, /*TInfo=*/nullptr,
16222 SC_None, nullptr);
16223 MoveConstructor->setParams(FromParam);
16224
16225 MoveConstructor->setTrivial(
16229 : ClassDecl->hasTrivialMoveConstructor());
16230
16231 MoveConstructor->setTrivialForCall(
16232 ClassDecl->hasAttr<TrivialABIAttr>() ||
16237 : ClassDecl->hasTrivialMoveConstructorForCall()));
16238
16239 // Note that we have declared this constructor.
16240 ++getASTContext().NumImplicitMoveConstructorsDeclared;
16241
16242 Scope *S = getScopeForContext(ClassDecl);
16244
16249 }
16250
16251 if (S)
16253 ClassDecl->addDecl(MoveConstructor);
16254
16255 return MoveConstructor;
16256}
16257
16260 DefaultedFunctionFPFeaturesRAII RestoreFP(*this, MoveConstructor);
16261 assert((MoveConstructor->isDefaulted() &&
16262 MoveConstructor->isMoveConstructor() &&
16263 !MoveConstructor->doesThisDeclarationHaveABody() &&
16264 !MoveConstructor->isDeleted()) &&
16265 "DefineImplicitMoveConstructor - call it for implicit move ctor");
16266 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
16267 return;
16268
16269 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
16270 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
16271
16273
16274 // The exception specification is needed because we are defining the
16275 // function.
16276 ResolveExceptionSpec(CurrentLocation,
16277 MoveConstructor->getType()->castAs<FunctionProtoType>());
16278 MarkVTableUsed(CurrentLocation, ClassDecl);
16279
16280 // Add a context note for diagnostics produced after this point.
16281 Scope.addContextNote(CurrentLocation);
16282
16283 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
16284 MoveConstructor->setInvalidDecl();
16285 } else {
16286 SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
16287 ? MoveConstructor->getEndLoc()
16288 : MoveConstructor->getLocation();
16289 Sema::CompoundScopeRAII CompoundScope(*this);
16290 MoveConstructor->setBody(
16291 ActOnCompoundStmt(Loc, Loc, {}, /*isStmtExpr=*/false).getAs<Stmt>());
16292 MoveConstructor->markUsed(Context);
16293 }
16294
16296 L->CompletedImplicitDefinition(MoveConstructor);
16297 }
16298}
16299
16301 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
16302}
16303
16305 SourceLocation CurrentLocation,
16306 CXXConversionDecl *Conv) {
16307 SynthesizedFunctionScope Scope(*this, Conv);
16308 assert(!Conv->getReturnType()->isUndeducedType());
16309
16310 QualType ConvRT = Conv->getType()->castAs<FunctionType>()->getReturnType();
16311 CallingConv CC =
16312 ConvRT->getPointeeType()->castAs<FunctionType>()->getCallConv();
16313
16314 CXXRecordDecl *Lambda = Conv->getParent();
16315 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
16316 FunctionDecl *Invoker =
16317 CallOp->hasCXXExplicitFunctionObjectParameter() || CallOp->isStatic()
16318 ? CallOp
16319 : Lambda->getLambdaStaticInvoker(CC);
16320
16321 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
16323 CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
16324 if (!CallOp)
16325 return;
16326
16327 if (CallOp != Invoker) {
16329 Invoker->getDescribedFunctionTemplate(), TemplateArgs,
16330 CurrentLocation);
16331 if (!Invoker)
16332 return;
16333 }
16334 }
16335
16336 if (CallOp->isInvalidDecl())
16337 return;
16338
16339 // Mark the call operator referenced (and add to pending instantiations
16340 // if necessary).
16341 // For both the conversion and static-invoker template specializations
16342 // we construct their body's in this function, so no need to add them
16343 // to the PendingInstantiations.
16344 MarkFunctionReferenced(CurrentLocation, CallOp);
16345
16346 if (Invoker != CallOp) {
16347 // Fill in the __invoke function with a dummy implementation. IR generation
16348 // will fill in the actual details. Update its type in case it contained
16349 // an 'auto'.
16350 Invoker->markUsed(Context);
16351 Invoker->setReferenced();
16352 Invoker->setType(Conv->getReturnType()->getPointeeType());
16353 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
16354 }
16355
16356 // Construct the body of the conversion function { return __invoke; }.
16357 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), VK_LValue,
16358 Conv->getLocation());
16359 assert(FunctionRef && "Can't refer to __invoke function?");
16360 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
16362 Conv->getLocation(), Conv->getLocation()));
16363 Conv->markUsed(Context);
16364 Conv->setReferenced();
16365
16367 L->CompletedImplicitDefinition(Conv);
16368 if (Invoker != CallOp)
16369 L->CompletedImplicitDefinition(Invoker);
16370 }
16371}
16372
16374 SourceLocation CurrentLocation, CXXConversionDecl *Conv) {
16375 assert(!Conv->getParent()->isGenericLambda());
16376
16377 SynthesizedFunctionScope Scope(*this, Conv);
16378
16379 // Copy-initialize the lambda object as needed to capture it.
16380 Expr *This = ActOnCXXThis(CurrentLocation).get();
16381 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
16382
16383 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
16384 Conv->getLocation(),
16385 Conv, DerefThis);
16386
16387 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
16388 // behavior. Note that only the general conversion function does this
16389 // (since it's unusable otherwise); in the case where we inline the
16390 // block literal, it has block literal lifetime semantics.
16391 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
16392 BuildBlock = ImplicitCastExpr::Create(
16393 Context, BuildBlock.get()->getType(), CK_CopyAndAutoreleaseBlockObject,
16394 BuildBlock.get(), nullptr, VK_PRValue, FPOptionsOverride());
16395
16396 if (BuildBlock.isInvalid()) {
16397 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
16398 Conv->setInvalidDecl();
16399 return;
16400 }
16401
16402 // Create the return statement that returns the block from the conversion
16403 // function.
16404 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
16405 if (Return.isInvalid()) {
16406 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
16407 Conv->setInvalidDecl();
16408 return;
16409 }
16410
16411 // Set the body of the conversion function.
16412 Stmt *ReturnS = Return.get();
16414 Conv->getLocation(), Conv->getLocation()));
16415 Conv->markUsed(Context);
16416
16417 // We're done; notify the mutation listener, if any.
16419 L->CompletedImplicitDefinition(Conv);
16420 }
16421}
16422
16423/// Determine whether the given list arguments contains exactly one
16424/// "real" (non-default) argument.
16426 switch (Args.size()) {
16427 case 0:
16428 return false;
16429
16430 default:
16431 if (!Args[1]->isDefaultArgument())
16432 return false;
16433
16434 [[fallthrough]];
16435 case 1:
16436 return !Args[0]->isDefaultArgument();
16437 }
16438
16439 return false;
16440}
16441
16443 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
16445 bool HadMultipleCandidates, bool IsListInitialization,
16446 bool IsStdInitListInitialization, bool RequiresZeroInit,
16447 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16448 bool Elidable = false;
16449
16450 // C++0x [class.copy]p34:
16451 // When certain criteria are met, an implementation is allowed to
16452 // omit the copy/move construction of a class object, even if the
16453 // copy/move constructor and/or destructor for the object have
16454 // side effects. [...]
16455 // - when a temporary class object that has not been bound to a
16456 // reference (12.2) would be copied/moved to a class object
16457 // with the same cv-unqualified type, the copy/move operation
16458 // can be omitted by constructing the temporary object
16459 // directly into the target of the omitted copy/move
16460 if (ConstructKind == CXXConstructionKind::Complete && Constructor &&
16461 // FIXME: Converting constructors should also be accepted.
16462 // But to fix this, the logic that digs down into a CXXConstructExpr
16463 // to find the source object needs to handle it.
16464 // Right now it assumes the source object is passed directly as the
16465 // first argument.
16466 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
16467 Expr *SubExpr = ExprArgs[0];
16468 // FIXME: Per above, this is also incorrect if we want to accept
16469 // converting constructors, as isTemporaryObject will
16470 // reject temporaries with different type from the
16471 // CXXRecord itself.
16472 Elidable = SubExpr->isTemporaryObject(
16474 }
16475
16476 return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
16477 FoundDecl, Constructor,
16478 Elidable, ExprArgs, HadMultipleCandidates,
16479 IsListInitialization,
16480 IsStdInitListInitialization, RequiresZeroInit,
16481 ConstructKind, ParenRange);
16482}
16483
16485 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
16486 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg ExprArgs,
16487 bool HadMultipleCandidates, bool IsListInitialization,
16488 bool IsStdInitListInitialization, bool RequiresZeroInit,
16489 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16490 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
16491 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
16492 // The only way to get here is if we did overload resolution to find the
16493 // shadow decl, so we don't need to worry about re-checking the trailing
16494 // requires clause.
16495 if (DiagnoseUseOfOverloadedDecl(Constructor, ConstructLoc))
16496 return ExprError();
16497 }
16498
16499 return BuildCXXConstructExpr(
16500 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
16501 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
16502 RequiresZeroInit, ConstructKind, ParenRange);
16503}
16504
16505/// BuildCXXConstructExpr - Creates a complete call to a constructor,
16506/// including handling of its default argument expressions.
16508 SourceLocation ConstructLoc, QualType DeclInitType,
16509 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg ExprArgs,
16510 bool HadMultipleCandidates, bool IsListInitialization,
16511 bool IsStdInitListInitialization, bool RequiresZeroInit,
16512 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16513 assert(declaresSameEntity(
16514 Constructor->getParent(),
16515 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
16516 "given constructor for wrong type");
16517 MarkFunctionReferenced(ConstructLoc, Constructor);
16518 if (getLangOpts().CUDA && !CUDA().CheckCall(ConstructLoc, Constructor))
16519 return ExprError();
16520
16523 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
16524 HadMultipleCandidates, IsListInitialization,
16525 IsStdInitListInitialization, RequiresZeroInit,
16526 static_cast<CXXConstructionKind>(ConstructKind), ParenRange),
16527 Constructor);
16528}
16529
16531 if (VD->isInvalidDecl()) return;
16532 // If initializing the variable failed, don't also diagnose problems with
16533 // the destructor, they're likely related.
16534 if (VD->getInit() && VD->getInit()->containsErrors())
16535 return;
16536
16537 ClassDecl = ClassDecl->getDefinitionOrSelf();
16538 if (ClassDecl->isInvalidDecl()) return;
16539 if (ClassDecl->hasIrrelevantDestructor()) return;
16540 if (ClassDecl->isDependentContext()) return;
16541
16542 if (VD->isNoDestroy(getASTContext()))
16543 return;
16544
16546 // The result of `LookupDestructor` might be nullptr if the destructor is
16547 // invalid, in which case it is marked as `IneligibleOrNotSelected` and
16548 // will not be selected by `CXXRecordDecl::getDestructor()`.
16549 if (!Destructor)
16550 return;
16551 // If this is an array, we'll require the destructor during initialization, so
16552 // we can skip over this. We still want to emit exit-time destructor warnings
16553 // though.
16554 if (!VD->getType()->isArrayType()) {
16557 PDiag(diag::err_access_dtor_var)
16558 << VD->getDeclName() << VD->getType());
16560 }
16561
16562 if (Destructor->isTrivial()) return;
16563
16564 // If the destructor is constexpr, check whether the variable has constant
16565 // destruction now.
16566 if (Destructor->isConstexpr()) {
16567 bool HasConstantInit = false;
16568 if (VD->getInit() && !VD->getInit()->isValueDependent())
16569 HasConstantInit = VD->evaluateValue();
16571 if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() &&
16572 HasConstantInit) {
16573 Diag(VD->getLocation(),
16574 diag::err_constexpr_var_requires_const_destruction) << VD;
16575 for (const PartialDiagnosticAt &Note : Notes)
16576 Diag(Note.first, Note.second);
16577 }
16578 }
16579
16580 if (!VD->hasGlobalStorage() || !VD->needsDestruction(Context))
16581 return;
16582
16583 // Emit warning for non-trivial dtor in global scope (a real global,
16584 // class-static, function-static).
16585 if (!VD->hasAttr<AlwaysDestroyAttr>())
16586 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
16587
16588 // TODO: this should be re-enabled for static locals by !CXAAtExit
16589 if (!VD->isStaticLocal())
16590 Diag(VD->getLocation(), diag::warn_global_destructor);
16591}
16592
16594 QualType DeclInitType, MultiExprArg ArgsPtr,
16595 SourceLocation Loc,
16596 SmallVectorImpl<Expr *> &ConvertedArgs,
16597 bool AllowExplicit,
16598 bool IsListInitialization) {
16599 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
16600 unsigned NumArgs = ArgsPtr.size();
16601 Expr **Args = ArgsPtr.data();
16602
16603 const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>();
16604 unsigned NumParams = Proto->getNumParams();
16605
16606 // If too few arguments are available, we'll fill in the rest with defaults.
16607 if (NumArgs < NumParams)
16608 ConvertedArgs.reserve(NumParams);
16609 else
16610 ConvertedArgs.reserve(NumArgs);
16611
16612 VariadicCallType CallType = Proto->isVariadic()
16615 SmallVector<Expr *, 8> AllArgs;
16617 Loc, Constructor, Proto, 0, llvm::ArrayRef(Args, NumArgs), AllArgs,
16618 CallType, AllowExplicit, IsListInitialization);
16619 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
16620
16621 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
16622
16623 CheckConstructorCall(Constructor, DeclInitType, llvm::ArrayRef(AllArgs),
16624 Proto, Loc);
16625
16626 return Invalid;
16627}
16628
16630 bool SeenTypedOperators = Context.hasSeenTypeAwareOperatorNewOrDelete();
16631 return typeAwareAllocationModeFromBool(SeenTypedOperators);
16632}
16633
16636 QualType DeallocType, SourceLocation Loc) {
16637 if (DeallocType.isNull())
16638 return nullptr;
16639
16640 FunctionDecl *FnDecl = FnTemplateDecl->getTemplatedDecl();
16641 if (!FnDecl->isTypeAwareOperatorNewOrDelete())
16642 return nullptr;
16643
16644 if (FnDecl->isVariadic())
16645 return nullptr;
16646
16647 unsigned NumParams = FnDecl->getNumParams();
16648 constexpr unsigned RequiredParameterCount =
16650 // A usual deallocation function has no placement parameters
16651 if (NumParams != RequiredParameterCount)
16652 return nullptr;
16653
16654 // A type aware allocation is only usual if the only dependent parameter is
16655 // the first parameter.
16656 if (llvm::any_of(FnDecl->parameters().drop_front(),
16657 [](const ParmVarDecl *ParamDecl) {
16658 return ParamDecl->getType()->isDependentType();
16659 }))
16660 return nullptr;
16661
16662 QualType SpecializedTypeIdentity = tryBuildStdTypeIdentity(DeallocType, Loc);
16663 if (SpecializedTypeIdentity.isNull())
16664 return nullptr;
16665
16667 ArgTypes.reserve(NumParams);
16668
16669 // The first parameter to a type aware operator delete is by definition the
16670 // type-identity argument, so we explicitly set this to the target
16671 // type-identity type, the remaining usual parameters should then simply match
16672 // the type declared in the function template.
16673 ArgTypes.push_back(SpecializedTypeIdentity);
16674 for (unsigned ParamIdx = 1; ParamIdx < RequiredParameterCount; ++ParamIdx)
16675 ArgTypes.push_back(FnDecl->getParamDecl(ParamIdx)->getType());
16676
16678 QualType ExpectedFunctionType =
16679 Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
16682 if (DeduceTemplateArguments(FnTemplateDecl, nullptr, ExpectedFunctionType,
16684 return nullptr;
16685 return Result;
16686}
16687
16688static inline bool
16690 const FunctionDecl *FnDecl) {
16691 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
16692 if (isa<NamespaceDecl>(DC)) {
16693 return SemaRef.Diag(FnDecl->getLocation(),
16694 diag::err_operator_new_delete_declared_in_namespace)
16695 << FnDecl->getDeclName();
16696 }
16697
16698 if (isa<TranslationUnitDecl>(DC) &&
16699 FnDecl->getStorageClass() == SC_Static) {
16700 return SemaRef.Diag(FnDecl->getLocation(),
16701 diag::err_operator_new_delete_declared_static)
16702 << FnDecl->getDeclName();
16703 }
16704
16705 return false;
16706}
16707
16709 const PointerType *PtrTy) {
16710 auto &Ctx = SemaRef.Context;
16711 Qualifiers PtrQuals = PtrTy->getPointeeType().getQualifiers();
16712 PtrQuals.removeAddressSpace();
16714 PtrTy->getPointeeType().getUnqualifiedType(), PtrQuals)));
16715}
16716
16718
16720 const FunctionDecl *FD,
16721 bool *WasMalformed) {
16722 const Decl *MalformedDecl = nullptr;
16723 if (FD->getNumParams() > 0 &&
16724 SemaRef.isStdTypeIdentity(FD->getParamDecl(0)->getType(),
16725 /*TypeArgument=*/nullptr, &MalformedDecl))
16726 return true;
16727
16728 if (!MalformedDecl)
16729 return false;
16730
16731 if (WasMalformed)
16732 *WasMalformed = true;
16733
16734 return true;
16735}
16736
16738 auto *RD = Type->getAsCXXRecordDecl();
16739 return RD && RD->isInStdNamespace() && RD->getIdentifier() &&
16740 RD->getIdentifier()->isStr("destroying_delete_t");
16741}
16742
16744 const FunctionDecl *FD) {
16745 // C++ P0722:
16746 // Within a class C, a single object deallocation function with signature
16747 // (T, std::destroying_delete_t, <more params>)
16748 // is a destroying operator delete.
16749 bool IsPotentiallyTypeAware = IsPotentiallyTypeAwareOperatorNewOrDelete(
16750 SemaRef, FD, /*WasMalformed=*/nullptr);
16751 unsigned DestroyingDeleteIdx = IsPotentiallyTypeAware + /* address */ 1;
16752 return isa<CXXMethodDecl>(FD) && FD->getOverloadedOperator() == OO_Delete &&
16753 FD->getNumParams() > DestroyingDeleteIdx &&
16754 isDestroyingDeleteT(FD->getParamDecl(DestroyingDeleteIdx)->getType());
16755}
16756
16758 Sema &SemaRef, FunctionDecl *FnDecl, AllocationOperatorKind OperatorKind,
16759 CanQualType ExpectedResultType, CanQualType ExpectedSizeOrAddressParamType,
16760 unsigned DependentParamTypeDiag, unsigned InvalidParamTypeDiag) {
16761 auto NormalizeType = [&SemaRef](QualType T) {
16762 if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
16763 // The operator is valid on any address space for OpenCL.
16764 // Drop address space from actual and expected result types.
16765 if (const auto PtrTy = T->template getAs<PointerType>())
16766 T = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
16767 }
16768 return SemaRef.Context.getCanonicalType(T);
16769 };
16770
16771 const unsigned NumParams = FnDecl->getNumParams();
16772 unsigned FirstNonTypeParam = 0;
16773 bool MalformedTypeIdentity = false;
16774 bool IsPotentiallyTypeAware = IsPotentiallyTypeAwareOperatorNewOrDelete(
16775 SemaRef, FnDecl, &MalformedTypeIdentity);
16776 unsigned MinimumMandatoryArgumentCount = 1;
16777 unsigned SizeParameterIndex = 0;
16778 if (IsPotentiallyTypeAware) {
16779 // We don't emit this diagnosis for template instantiations as we will
16780 // have already emitted it for the original template declaration.
16781 if (!FnDecl->isTemplateInstantiation())
16782 SemaRef.Diag(FnDecl->getLocation(), diag::warn_ext_type_aware_allocators);
16783
16784 if (OperatorKind == AllocationOperatorKind::New) {
16785 SizeParameterIndex = 1;
16786 MinimumMandatoryArgumentCount =
16788 } else {
16789 SizeParameterIndex = 2;
16790 MinimumMandatoryArgumentCount =
16792 }
16793 FirstNonTypeParam = 1;
16794 }
16795
16796 bool IsPotentiallyDestroyingDelete =
16798
16799 if (IsPotentiallyDestroyingDelete) {
16800 ++MinimumMandatoryArgumentCount;
16801 ++SizeParameterIndex;
16802 }
16803
16804 if (NumParams < MinimumMandatoryArgumentCount)
16805 return SemaRef.Diag(FnDecl->getLocation(),
16806 diag::err_operator_new_delete_too_few_parameters)
16807 << IsPotentiallyTypeAware << IsPotentiallyDestroyingDelete
16808 << FnDecl->getDeclName() << MinimumMandatoryArgumentCount;
16809
16810 for (unsigned Idx = 0; Idx < MinimumMandatoryArgumentCount; ++Idx) {
16811 const ParmVarDecl *ParamDecl = FnDecl->getParamDecl(Idx);
16812 if (ParamDecl->hasDefaultArg())
16813 return SemaRef.Diag(FnDecl->getLocation(),
16814 diag::err_operator_new_default_arg)
16815 << FnDecl->getDeclName() << Idx << ParamDecl->getDefaultArgRange();
16816 }
16817
16818 auto *FnType = FnDecl->getType()->castAs<FunctionType>();
16819 QualType CanResultType = NormalizeType(FnType->getReturnType());
16820 QualType CanExpectedResultType = NormalizeType(ExpectedResultType);
16821 QualType CanExpectedSizeOrAddressParamType =
16822 NormalizeType(ExpectedSizeOrAddressParamType);
16823
16824 // Check that the result type is what we expect.
16825 if (CanResultType != CanExpectedResultType) {
16826 // Reject even if the type is dependent; an operator delete function is
16827 // required to have a non-dependent result type.
16828 return SemaRef.Diag(
16829 FnDecl->getLocation(),
16830 CanResultType->isDependentType()
16831 ? diag::err_operator_new_delete_dependent_result_type
16832 : diag::err_operator_new_delete_invalid_result_type)
16833 << FnDecl->getDeclName() << ExpectedResultType;
16834 }
16835
16836 // A function template must have at least 2 parameters.
16837 if (FnDecl->getDescribedFunctionTemplate() && NumParams < 2)
16838 return SemaRef.Diag(FnDecl->getLocation(),
16839 diag::err_operator_new_delete_template_too_few_parameters)
16840 << FnDecl->getDeclName();
16841
16842 auto CheckType = [&](unsigned ParamIdx, QualType ExpectedType,
16843 auto FallbackType) -> bool {
16844 const ParmVarDecl *ParamDecl = FnDecl->getParamDecl(ParamIdx);
16845 if (ExpectedType.isNull()) {
16846 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
16847 << IsPotentiallyTypeAware << IsPotentiallyDestroyingDelete
16848 << FnDecl->getDeclName() << (1 + ParamIdx) << FallbackType
16849 << ParamDecl->getSourceRange();
16850 }
16851 CanQualType CanExpectedTy =
16852 NormalizeType(SemaRef.Context.getCanonicalType(ExpectedType));
16853 auto ActualParamType =
16854 NormalizeType(ParamDecl->getType().getUnqualifiedType());
16855 if (ActualParamType == CanExpectedTy)
16856 return false;
16857 unsigned Diagnostic = ActualParamType->isDependentType()
16858 ? DependentParamTypeDiag
16859 : InvalidParamTypeDiag;
16860 return SemaRef.Diag(FnDecl->getLocation(), Diagnostic)
16861 << IsPotentiallyTypeAware << IsPotentiallyDestroyingDelete
16862 << FnDecl->getDeclName() << (1 + ParamIdx) << ExpectedType
16863 << FallbackType << ParamDecl->getSourceRange();
16864 };
16865
16866 // Check that the first parameter type is what we expect.
16867 if (CheckType(FirstNonTypeParam, CanExpectedSizeOrAddressParamType, "size_t"))
16868 return true;
16869
16870 FnDecl->setIsDestroyingOperatorDelete(IsPotentiallyDestroyingDelete);
16871
16872 // If the first parameter type is not a type-identity we're done, otherwise
16873 // we need to ensure the size and alignment parameters have the correct type
16874 if (!IsPotentiallyTypeAware)
16875 return false;
16876
16877 if (CheckType(SizeParameterIndex, SemaRef.Context.getSizeType(), "size_t"))
16878 return true;
16879 TagDecl *StdAlignValTDecl = SemaRef.getStdAlignValT();
16880 CanQualType StdAlignValT =
16881 StdAlignValTDecl ? SemaRef.Context.getCanonicalTagType(StdAlignValTDecl)
16882 : CanQualType();
16883 if (CheckType(SizeParameterIndex + 1, StdAlignValT, "std::align_val_t"))
16884 return true;
16885
16887 return MalformedTypeIdentity;
16888}
16889
16890static bool CheckOperatorNewDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
16891 // C++ [basic.stc.dynamic.allocation]p1:
16892 // A program is ill-formed if an allocation function is declared in a
16893 // namespace scope other than global scope or declared static in global
16894 // scope.
16895 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
16896 return true;
16897
16898 CanQualType SizeTy =
16899 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
16900
16901 // C++ [basic.stc.dynamic.allocation]p1:
16902 // The return type shall be void*. The first parameter shall have type
16903 // std::size_t.
16905 SemaRef, FnDecl, AllocationOperatorKind::New, SemaRef.Context.VoidPtrTy,
16906 SizeTy, diag::err_operator_new_dependent_param_type,
16907 diag::err_operator_new_param_type);
16908}
16909
16910static bool
16912 // C++ [basic.stc.dynamic.deallocation]p1:
16913 // A program is ill-formed if deallocation functions are declared in a
16914 // namespace scope other than global scope or declared static in global
16915 // scope.
16916 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
16917 return true;
16918
16919 auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
16920 auto ConstructDestroyingDeleteAddressType = [&]() {
16921 assert(MD);
16922 return SemaRef.Context.getPointerType(
16923 SemaRef.Context.getCanonicalTagType(MD->getParent()));
16924 };
16925
16926 // C++ P2719: A destroying operator delete cannot be type aware
16927 // so for QoL we actually check for this explicitly by considering
16928 // an destroying-delete appropriate address type and the presence of
16929 // any parameter of type destroying_delete_t as an erroneous attempt
16930 // to declare a type aware destroying delete, rather than emitting a
16931 // pile of incorrect parameter type errors.
16933 SemaRef, MD, /*WasMalformed=*/nullptr)) {
16934 QualType AddressParamType =
16935 SemaRef.Context.getCanonicalType(MD->getParamDecl(1)->getType());
16936 if (AddressParamType != SemaRef.Context.VoidPtrTy &&
16937 AddressParamType == ConstructDestroyingDeleteAddressType()) {
16938 // The address parameter type implies an author trying to construct a
16939 // type aware destroying delete, so we'll see if we can find a parameter
16940 // of type `std::destroying_delete_t`, and if we find it we'll report
16941 // this as being an attempt at a type aware destroying delete just stop
16942 // here. If we don't do this, the resulting incorrect parameter ordering
16943 // results in a pile mismatched argument type errors that don't explain
16944 // the core problem.
16945 for (auto Param : MD->parameters()) {
16946 if (isDestroyingDeleteT(Param->getType())) {
16947 SemaRef.Diag(MD->getLocation(),
16948 diag::err_type_aware_destroying_operator_delete)
16949 << Param->getSourceRange();
16950 return true;
16951 }
16952 }
16953 }
16954 }
16955
16956 // C++ P0722:
16957 // Within a class C, the first parameter of a destroying operator delete
16958 // shall be of type C *. The first parameter of any other deallocation
16959 // function shall be of type void *.
16960 CanQualType ExpectedAddressParamType =
16961 MD && IsPotentiallyDestroyingOperatorDelete(SemaRef, MD)
16962 ? SemaRef.Context.getPointerType(
16963 SemaRef.Context.getCanonicalTagType(MD->getParent()))
16964 : SemaRef.Context.VoidPtrTy;
16965
16966 // C++ [basic.stc.dynamic.deallocation]p2:
16967 // Each deallocation function shall return void
16969 SemaRef, FnDecl, AllocationOperatorKind::Delete,
16970 SemaRef.Context.VoidTy, ExpectedAddressParamType,
16971 diag::err_operator_delete_dependent_param_type,
16972 diag::err_operator_delete_param_type))
16973 return true;
16974
16975 // C++ P0722:
16976 // A destroying operator delete shall be a usual deallocation function.
16977 if (MD && !MD->getParent()->isDependentContext() &&
16979 if (!SemaRef.isUsualDeallocationFunction(MD)) {
16980 SemaRef.Diag(MD->getLocation(),
16981 diag::err_destroying_operator_delete_not_usual);
16982 return true;
16983 }
16984 }
16985
16986 return false;
16987}
16988
16990 assert(FnDecl && FnDecl->isOverloadedOperator() &&
16991 "Expected an overloaded operator declaration");
16992
16994
16995 // C++ [over.oper]p5:
16996 // The allocation and deallocation functions, operator new,
16997 // operator new[], operator delete and operator delete[], are
16998 // described completely in 3.7.3. The attributes and restrictions
16999 // found in the rest of this subclause do not apply to them unless
17000 // explicitly stated in 3.7.3.
17001 if (Op == OO_Delete || Op == OO_Array_Delete)
17002 return CheckOperatorDeleteDeclaration(*this, FnDecl);
17003
17004 if (Op == OO_New || Op == OO_Array_New)
17005 return CheckOperatorNewDeclaration(*this, FnDecl);
17006
17007 // C++ [over.oper]p7:
17008 // An operator function shall either be a member function or
17009 // be a non-member function and have at least one parameter
17010 // whose type is a class, a reference to a class, an enumeration,
17011 // or a reference to an enumeration.
17012 // Note: Before C++23, a member function could not be static. The only member
17013 // function allowed to be static is the call operator function.
17014 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
17015 if (MethodDecl->isStatic()) {
17016 if (Op == OO_Call || Op == OO_Subscript)
17017 Diag(FnDecl->getLocation(),
17018 (LangOpts.CPlusPlus23
17019 ? diag::warn_cxx20_compat_operator_overload_static
17020 : diag::ext_operator_overload_static))
17021 << FnDecl;
17022 else
17023 return Diag(FnDecl->getLocation(), diag::err_operator_overload_static)
17024 << FnDecl;
17025 }
17026 } else {
17027 bool ClassOrEnumParam = false;
17028 for (auto *Param : FnDecl->parameters()) {
17029 QualType ParamType = Param->getType().getNonReferenceType();
17030 if (ParamType->isDependentType() || ParamType->isRecordType() ||
17031 ParamType->isEnumeralType()) {
17032 ClassOrEnumParam = true;
17033 break;
17034 }
17035 }
17036
17037 if (!ClassOrEnumParam)
17038 return Diag(FnDecl->getLocation(),
17039 diag::err_operator_overload_needs_class_or_enum)
17040 << FnDecl->getDeclName();
17041 }
17042
17043 // C++ [over.oper]p8:
17044 // An operator function cannot have default arguments (8.3.6),
17045 // except where explicitly stated below.
17046 //
17047 // Only the function-call operator (C++ [over.call]p1) and the subscript
17048 // operator (CWG2507) allow default arguments.
17049 if (Op != OO_Call) {
17050 ParmVarDecl *FirstDefaultedParam = nullptr;
17051 for (auto *Param : FnDecl->parameters()) {
17052 if (Param->hasDefaultArg()) {
17053 FirstDefaultedParam = Param;
17054 break;
17055 }
17056 }
17057 if (FirstDefaultedParam) {
17058 if (Op == OO_Subscript) {
17059 Diag(FnDecl->getLocation(), LangOpts.CPlusPlus23
17060 ? diag::ext_subscript_overload
17061 : diag::error_subscript_overload)
17062 << FnDecl->getDeclName() << 1
17063 << FirstDefaultedParam->getDefaultArgRange();
17064 } else {
17065 return Diag(FirstDefaultedParam->getLocation(),
17066 diag::err_operator_overload_default_arg)
17067 << FnDecl->getDeclName()
17068 << FirstDefaultedParam->getDefaultArgRange();
17069 }
17070 }
17071 }
17072
17073 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
17074 { false, false, false }
17075#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
17076 , { Unary, Binary, MemberOnly }
17077#include "clang/Basic/OperatorKinds.def"
17078 };
17079
17080 bool CanBeUnaryOperator = OperatorUses[Op][0];
17081 bool CanBeBinaryOperator = OperatorUses[Op][1];
17082 bool MustBeMemberOperator = OperatorUses[Op][2];
17083
17084 // C++ [over.oper]p8:
17085 // [...] Operator functions cannot have more or fewer parameters
17086 // than the number required for the corresponding operator, as
17087 // described in the rest of this subclause.
17088 unsigned NumParams = FnDecl->getNumParams() +
17089 (isa<CXXMethodDecl>(FnDecl) &&
17091 ? 1
17092 : 0);
17093 if (Op != OO_Call && Op != OO_Subscript &&
17094 ((NumParams == 1 && !CanBeUnaryOperator) ||
17095 (NumParams == 2 && !CanBeBinaryOperator) || (NumParams < 1) ||
17096 (NumParams > 2))) {
17097 // We have the wrong number of parameters.
17098 unsigned ErrorKind;
17099 if (CanBeUnaryOperator && CanBeBinaryOperator) {
17100 ErrorKind = 2; // 2 -> unary or binary.
17101 } else if (CanBeUnaryOperator) {
17102 ErrorKind = 0; // 0 -> unary
17103 } else {
17104 assert(CanBeBinaryOperator &&
17105 "All non-call overloaded operators are unary or binary!");
17106 ErrorKind = 1; // 1 -> binary
17107 }
17108 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
17109 << FnDecl->getDeclName() << NumParams << ErrorKind;
17110 }
17111
17112 if (Op == OO_Subscript && NumParams != 2) {
17113 Diag(FnDecl->getLocation(), LangOpts.CPlusPlus23
17114 ? diag::ext_subscript_overload
17115 : diag::error_subscript_overload)
17116 << FnDecl->getDeclName() << (NumParams == 1 ? 0 : 2);
17117 }
17118
17119 // Overloaded operators other than operator() and operator[] cannot be
17120 // variadic.
17121 if (Op != OO_Call &&
17122 FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) {
17123 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
17124 << FnDecl->getDeclName();
17125 }
17126
17127 // Some operators must be member functions.
17128 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
17129 return Diag(FnDecl->getLocation(),
17130 diag::err_operator_overload_must_be_member)
17131 << FnDecl->getDeclName();
17132 }
17133
17134 // C++ [over.inc]p1:
17135 // The user-defined function called operator++ implements the
17136 // prefix and postfix ++ operator. If this function is a member
17137 // function with no parameters, or a non-member function with one
17138 // parameter of class or enumeration type, it defines the prefix
17139 // increment operator ++ for objects of that type. If the function
17140 // is a member function with one parameter (which shall be of type
17141 // int) or a non-member function with two parameters (the second
17142 // of which shall be of type int), it defines the postfix
17143 // increment operator ++ for objects of that type.
17144 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
17145 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
17146 QualType ParamType = LastParam->getType();
17147
17148 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
17149 !ParamType->isDependentType())
17150 return Diag(LastParam->getLocation(),
17151 diag::err_operator_overload_post_incdec_must_be_int)
17152 << LastParam->getType() << (Op == OO_MinusMinus);
17153 }
17154
17155 return false;
17156}
17157
17158static bool
17160 FunctionTemplateDecl *TpDecl) {
17161 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
17162
17163 // Must have one or two template parameters.
17164 if (TemplateParams->size() == 1) {
17165 NonTypeTemplateParmDecl *PmDecl =
17166 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
17167
17168 // The template parameter must be a char parameter pack.
17169 if (PmDecl && PmDecl->isTemplateParameterPack() &&
17170 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
17171 return false;
17172
17173 // C++20 [over.literal]p5:
17174 // A string literal operator template is a literal operator template
17175 // whose template-parameter-list comprises a single non-type
17176 // template-parameter of class type.
17177 //
17178 // As a DR resolution, we also allow placeholders for deduced class
17179 // template specializations.
17180 if (SemaRef.getLangOpts().CPlusPlus20 && PmDecl &&
17181 !PmDecl->isTemplateParameterPack() &&
17182 (PmDecl->getType()->isRecordType() ||
17183 PmDecl->getType()->getAs<DeducedTemplateSpecializationType>()))
17184 return false;
17185 } else if (TemplateParams->size() == 2) {
17186 TemplateTypeParmDecl *PmType =
17187 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
17188 NonTypeTemplateParmDecl *PmArgs =
17189 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
17190
17191 // The second template parameter must be a parameter pack with the
17192 // first template parameter as its type.
17193 if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
17194 PmArgs->isTemplateParameterPack()) {
17195 if (const auto *TArgs =
17196 PmArgs->getType()->getAsCanonical<TemplateTypeParmType>();
17197 TArgs && TArgs->getDepth() == PmType->getDepth() &&
17198 TArgs->getIndex() == PmType->getIndex()) {
17199 if (!SemaRef.inTemplateInstantiation())
17200 SemaRef.Diag(TpDecl->getLocation(),
17201 diag::ext_string_literal_operator_template);
17202 return false;
17203 }
17204 }
17205 }
17206
17207 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
17208 diag::err_literal_operator_template)
17209 << TpDecl->getTemplateParameters()->getSourceRange();
17210 return true;
17211}
17212
17214 if (isa<CXXMethodDecl>(FnDecl)) {
17215 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
17216 << FnDecl->getDeclName();
17217 return true;
17218 }
17219
17220 if (FnDecl->isExternC()) {
17221 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
17222 if (const LinkageSpecDecl *LSD =
17223 FnDecl->getDeclContext()->getExternCContext())
17224 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
17225 return true;
17226 }
17227
17228 // This might be the definition of a literal operator template.
17230
17231 // This might be a specialization of a literal operator template.
17232 if (!TpDecl)
17233 TpDecl = FnDecl->getPrimaryTemplate();
17234
17235 // template <char...> type operator "" name() and
17236 // template <class T, T...> type operator "" name() are the only valid
17237 // template signatures, and the only valid signatures with no parameters.
17238 //
17239 // C++20 also allows template <SomeClass T> type operator "" name().
17240 if (TpDecl) {
17241 if (FnDecl->param_size() != 0) {
17242 Diag(FnDecl->getLocation(),
17243 diag::err_literal_operator_template_with_params);
17244 return true;
17245 }
17246
17248 return true;
17249
17250 } else if (FnDecl->param_size() == 1) {
17251 const ParmVarDecl *Param = FnDecl->getParamDecl(0);
17252
17253 QualType ParamType = Param->getType().getUnqualifiedType();
17254
17255 // Only unsigned long long int, long double, any character type, and const
17256 // char * are allowed as the only parameters.
17257 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
17258 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
17259 Context.hasSameType(ParamType, Context.CharTy) ||
17260 Context.hasSameType(ParamType, Context.WideCharTy) ||
17261 Context.hasSameType(ParamType, Context.Char8Ty) ||
17262 Context.hasSameType(ParamType, Context.Char16Ty) ||
17263 Context.hasSameType(ParamType, Context.Char32Ty)) {
17264 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
17265 QualType InnerType = Ptr->getPointeeType();
17266
17267 // Pointer parameter must be a const char *.
17268 if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
17269 Context.CharTy) &&
17270 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
17271 Diag(Param->getSourceRange().getBegin(),
17272 diag::err_literal_operator_param)
17273 << ParamType << "'const char *'" << Param->getSourceRange();
17274 return true;
17275 }
17276
17277 } else if (ParamType->isRealFloatingType()) {
17278 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
17279 << ParamType << Context.LongDoubleTy << Param->getSourceRange();
17280 return true;
17281
17282 } else if (ParamType->isIntegerType()) {
17283 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
17284 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
17285 return true;
17286
17287 } else {
17288 Diag(Param->getSourceRange().getBegin(),
17289 diag::err_literal_operator_invalid_param)
17290 << ParamType << Param->getSourceRange();
17291 return true;
17292 }
17293
17294 } else if (FnDecl->param_size() == 2) {
17295 FunctionDecl::param_iterator Param = FnDecl->param_begin();
17296
17297 // First, verify that the first parameter is correct.
17298
17299 QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
17300
17301 // Two parameter function must have a pointer to const as a
17302 // first parameter; let's strip those qualifiers.
17303 const PointerType *PT = FirstParamType->getAs<PointerType>();
17304
17305 if (!PT) {
17306 Diag((*Param)->getSourceRange().getBegin(),
17307 diag::err_literal_operator_param)
17308 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
17309 return true;
17310 }
17311
17312 QualType PointeeType = PT->getPointeeType();
17313 // First parameter must be const
17314 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
17315 Diag((*Param)->getSourceRange().getBegin(),
17316 diag::err_literal_operator_param)
17317 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
17318 return true;
17319 }
17320
17321 QualType InnerType = PointeeType.getUnqualifiedType();
17322 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
17323 // const char32_t* are allowed as the first parameter to a two-parameter
17324 // function
17325 if (!(Context.hasSameType(InnerType, Context.CharTy) ||
17326 Context.hasSameType(InnerType, Context.WideCharTy) ||
17327 Context.hasSameType(InnerType, Context.Char8Ty) ||
17328 Context.hasSameType(InnerType, Context.Char16Ty) ||
17329 Context.hasSameType(InnerType, Context.Char32Ty))) {
17330 Diag((*Param)->getSourceRange().getBegin(),
17331 diag::err_literal_operator_param)
17332 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
17333 return true;
17334 }
17335
17336 // Move on to the second and final parameter.
17337 ++Param;
17338
17339 // The second parameter must be a std::size_t.
17340 QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
17341 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
17342 Diag((*Param)->getSourceRange().getBegin(),
17343 diag::err_literal_operator_param)
17344 << SecondParamType << Context.getSizeType()
17345 << (*Param)->getSourceRange();
17346 return true;
17347 }
17348 } else {
17349 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
17350 return true;
17351 }
17352
17353 // Parameters are good.
17354
17355 // A parameter-declaration-clause containing a default argument is not
17356 // equivalent to any of the permitted forms.
17357 for (auto *Param : FnDecl->parameters()) {
17358 if (Param->hasDefaultArg()) {
17359 Diag(Param->getDefaultArgRange().getBegin(),
17360 diag::err_literal_operator_default_argument)
17361 << Param->getDefaultArgRange();
17362 break;
17363 }
17364 }
17365
17366 const IdentifierInfo *II = FnDecl->getDeclName().getCXXLiteralIdentifier();
17369 !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
17370 // C++23 [usrlit.suffix]p1:
17371 // Literal suffix identifiers that do not start with an underscore are
17372 // reserved for future standardization. Literal suffix identifiers that
17373 // contain a double underscore __ are reserved for use by C++
17374 // implementations.
17375 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
17376 << static_cast<int>(Status)
17378 }
17379
17380 return false;
17381}
17382
17384 Expr *LangStr,
17385 SourceLocation LBraceLoc) {
17386 StringLiteral *Lit = cast<StringLiteral>(LangStr);
17387 assert(Lit->isUnevaluated() && "Unexpected string literal kind");
17388
17389 StringRef Lang = Lit->getString();
17391 if (Lang == "C")
17393 else if (Lang == "C++")
17395 else {
17396 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
17397 << LangStr->getSourceRange();
17398 return nullptr;
17399 }
17400
17401 // FIXME: Add all the various semantics of linkage specifications
17402
17404 LangStr->getExprLoc(), Language,
17405 LBraceLoc.isValid());
17406
17407 /// C++ [module.unit]p7.2.3
17408 /// - Otherwise, if the declaration
17409 /// - ...
17410 /// - ...
17411 /// - appears within a linkage-specification,
17412 /// it is attached to the global module.
17413 ///
17414 /// If the declaration is already in global module fragment, we don't
17415 /// need to attach it again.
17416 if (getLangOpts().CPlusPlusModules && isCurrentModulePurview()) {
17417 Module *GlobalModule = PushImplicitGlobalModuleFragment(ExternLoc);
17418 D->setLocalOwningModule(GlobalModule);
17419 }
17420
17421 CurContext->addDecl(D);
17422 PushDeclContext(S, D);
17423 return D;
17424}
17425
17427 Decl *LinkageSpec,
17428 SourceLocation RBraceLoc) {
17429 if (RBraceLoc.isValid()) {
17430 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
17431 LSDecl->setRBraceLoc(RBraceLoc);
17432 }
17433
17434 // If the current module doesn't has Parent, it implies that the
17435 // LinkageSpec isn't in the module created by itself. So we don't
17436 // need to pop it.
17437 if (getLangOpts().CPlusPlusModules && getCurrentModule() &&
17438 getCurrentModule()->isImplicitGlobalModule() &&
17439 getCurrentModule()->Parent)
17440 PopImplicitGlobalModuleFragment();
17441
17443 return LinkageSpec;
17444}
17445
17447 const ParsedAttributesView &AttrList,
17448 SourceLocation SemiLoc) {
17449 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
17450 // Attribute declarations appertain to empty declaration so we handle
17451 // them here.
17452 ProcessDeclAttributeList(S, ED, AttrList);
17453
17454 CurContext->addDecl(ED);
17455 return ED;
17456}
17457
17459 SourceLocation StartLoc,
17460 SourceLocation Loc,
17461 const IdentifierInfo *Name) {
17462 bool Invalid = false;
17463 QualType ExDeclType = TInfo->getType();
17464
17465 // Arrays and functions decay.
17466 if (ExDeclType->isArrayType())
17467 ExDeclType = Context.getArrayDecayedType(ExDeclType);
17468 else if (ExDeclType->isFunctionType())
17469 ExDeclType = Context.getPointerType(ExDeclType);
17470
17471 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
17472 // The exception-declaration shall not denote a pointer or reference to an
17473 // incomplete type, other than [cv] void*.
17474 // N2844 forbids rvalue references.
17475 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
17476 Diag(Loc, diag::err_catch_rvalue_ref);
17477 Invalid = true;
17478 }
17479
17480 if (ExDeclType->isVariablyModifiedType()) {
17481 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
17482 Invalid = true;
17483 }
17484
17485 QualType BaseType = ExDeclType;
17486 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
17487 unsigned DK = diag::err_catch_incomplete;
17488 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
17489 BaseType = Ptr->getPointeeType();
17490 Mode = 1;
17491 DK = diag::err_catch_incomplete_ptr;
17492 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
17493 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
17494 BaseType = Ref->getPointeeType();
17495 Mode = 2;
17496 DK = diag::err_catch_incomplete_ref;
17497 }
17498 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
17499 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
17500 Invalid = true;
17501
17502 if (!Invalid && BaseType.isWebAssemblyReferenceType()) {
17503 Diag(Loc, diag::err_wasm_reftype_tc) << 1;
17504 Invalid = true;
17505 }
17506
17507 if (!Invalid && Mode != 1 && BaseType->isSizelessType()) {
17508 Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType;
17509 Invalid = true;
17510 }
17511
17512 if (!Invalid && !ExDeclType->isDependentType() &&
17513 RequireNonAbstractType(Loc, ExDeclType,
17514 diag::err_abstract_type_in_decl,
17516 Invalid = true;
17517
17518 // Only the non-fragile NeXT runtime currently supports C++ catches
17519 // of ObjC types, and no runtime supports catching ObjC types by value.
17520 if (!Invalid && getLangOpts().ObjC) {
17521 QualType T = ExDeclType;
17522 if (const ReferenceType *RT = T->getAs<ReferenceType>())
17523 T = RT->getPointeeType();
17524
17525 if (T->isObjCObjectType()) {
17526 Diag(Loc, diag::err_objc_object_catch);
17527 Invalid = true;
17528 } else if (T->isObjCObjectPointerType()) {
17529 // FIXME: should this be a test for macosx-fragile specifically?
17531 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
17532 }
17533 }
17534
17535 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
17536 ExDeclType, TInfo, SC_None);
17537 ExDecl->setExceptionVariable(true);
17538
17539 // In ARC, infer 'retaining' for variables of retainable type.
17540 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(ExDecl))
17541 Invalid = true;
17542
17543 if (!Invalid && !ExDeclType->isDependentType()) {
17544 if (auto *ClassDecl = ExDeclType->getAsCXXRecordDecl()) {
17545 // Insulate this from anything else we might currently be parsing.
17548
17549 // C++ [except.handle]p16:
17550 // The object declared in an exception-declaration or, if the
17551 // exception-declaration does not specify a name, a temporary (12.2) is
17552 // copy-initialized (8.5) from the exception object. [...]
17553 // The object is destroyed when the handler exits, after the destruction
17554 // of any automatic objects initialized within the handler.
17555 //
17556 // We just pretend to initialize the object with itself, then make sure
17557 // it can be destroyed later.
17558 QualType initType = Context.getExceptionObjectType(ExDeclType);
17559
17560 InitializedEntity entity =
17562 InitializationKind initKind =
17564
17565 Expr *opaqueValue =
17566 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
17567 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
17568 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
17569 if (result.isInvalid())
17570 Invalid = true;
17571 else {
17572 // If the constructor used was non-trivial, set this as the
17573 // "initializer".
17574 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
17575 if (!construct->getConstructor()->isTrivial()) {
17576 Expr *init = MaybeCreateExprWithCleanups(construct);
17577 ExDecl->setInit(init);
17578 }
17579
17580 // And make sure it's destructable.
17581 FinalizeVarWithDestructor(ExDecl, ClassDecl);
17582 }
17583 }
17584 }
17585
17586 if (Invalid)
17587 ExDecl->setInvalidDecl();
17588
17589 return ExDecl;
17590}
17591
17594 bool Invalid = D.isInvalidType();
17595
17596 // Check for unexpanded parameter packs.
17599 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
17600 D.getIdentifierLoc());
17601 Invalid = true;
17602 }
17603
17604 const IdentifierInfo *II = D.getIdentifier();
17605 if (NamedDecl *PrevDecl =
17608 // The scope should be freshly made just for us. There is just no way
17609 // it contains any previous declaration, except for function parameters in
17610 // a function-try-block's catch statement.
17611 assert(!S->isDeclScope(PrevDecl));
17612 if (isDeclInScope(PrevDecl, CurContext, S)) {
17613 Diag(D.getIdentifierLoc(), diag::err_redefinition)
17614 << D.getIdentifier();
17615 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
17616 Invalid = true;
17617 } else if (PrevDecl->isTemplateParameter())
17618 // Maybe we will complain about the shadowed template parameter.
17620 }
17621
17622 if (D.getCXXScopeSpec().isSet() && !Invalid) {
17623 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
17624 << D.getCXXScopeSpec().getRange();
17625 Invalid = true;
17626 }
17627
17629 S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
17630 if (Invalid)
17631 ExDecl->setInvalidDecl();
17632
17633 // Add the exception declaration into this scope.
17634 if (II)
17635 PushOnScopeChains(ExDecl, S);
17636 else
17637 CurContext->addDecl(ExDecl);
17638
17639 ProcessDeclAttributes(S, ExDecl, D);
17640 return ExDecl;
17641}
17642
17644 Expr *AssertExpr,
17645 Expr *AssertMessageExpr,
17646 SourceLocation RParenLoc) {
17648 return nullptr;
17649
17650 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
17651 AssertMessageExpr, RParenLoc, false);
17652}
17653
17654static void WriteCharTypePrefix(BuiltinType::Kind BTK, llvm::raw_ostream &OS) {
17655 switch (BTK) {
17656 case BuiltinType::Char_S:
17657 case BuiltinType::Char_U:
17658 break;
17659 case BuiltinType::Char8:
17660 OS << "u8";
17661 break;
17662 case BuiltinType::Char16:
17663 OS << 'u';
17664 break;
17665 case BuiltinType::Char32:
17666 OS << 'U';
17667 break;
17668 case BuiltinType::WChar_S:
17669 case BuiltinType::WChar_U:
17670 OS << 'L';
17671 break;
17672 default:
17673 llvm_unreachable("Non-character type");
17674 }
17675}
17676
17677/// Convert character's value, interpreted as a code unit, to a string.
17678/// The value needs to be zero-extended to 32-bits.
17679/// FIXME: This assumes Unicode literal encodings
17681 unsigned TyWidth,
17682 SmallVectorImpl<char> &Str) {
17683 char Arr[UNI_MAX_UTF8_BYTES_PER_CODE_POINT];
17684 char *Ptr = Arr;
17685 BuiltinType::Kind K = BTy->getKind();
17686 llvm::raw_svector_ostream OS(Str);
17687
17688 // This should catch Char_S, Char_U, Char8, and use of escaped characters in
17689 // other types.
17690 if (K == BuiltinType::Char_S || K == BuiltinType::Char_U ||
17691 K == BuiltinType::Char8 || Value <= 0x7F) {
17692 StringRef Escaped = escapeCStyle<EscapeChar::Single>(Value);
17693 if (!Escaped.empty())
17694 EscapeStringForDiagnostic(Escaped, Str);
17695 else
17696 OS << static_cast<char>(Value);
17697 return;
17698 }
17699
17700 switch (K) {
17701 case BuiltinType::Char16:
17702 case BuiltinType::Char32:
17703 case BuiltinType::WChar_S:
17704 case BuiltinType::WChar_U: {
17705 if (llvm::ConvertCodePointToUTF8(Value, Ptr))
17706 EscapeStringForDiagnostic(StringRef(Arr, Ptr - Arr), Str);
17707 else
17708 OS << "\\x"
17709 << llvm::format_hex_no_prefix(Value, TyWidth / 4, /*Upper=*/true);
17710 break;
17711 }
17712 default:
17713 llvm_unreachable("Non-character type is passed");
17714 }
17715}
17716
17717/// Convert \V to a string we can present to the user in a diagnostic
17718/// \T is the type of the expression that has been evaluated into \V
17721 ASTContext &Context) {
17722 if (!V.hasValue())
17723 return false;
17724
17725 switch (V.getKind()) {
17727 if (T->isBooleanType()) {
17728 // Bools are reduced to ints during evaluation, but for
17729 // diagnostic purposes we want to print them as
17730 // true or false.
17731 int64_t BoolValue = V.getInt().getExtValue();
17732 assert((BoolValue == 0 || BoolValue == 1) &&
17733 "Bool type, but value is not 0 or 1");
17734 llvm::raw_svector_ostream OS(Str);
17735 OS << (BoolValue ? "true" : "false");
17736 } else {
17737 llvm::raw_svector_ostream OS(Str);
17738 // Same is true for chars.
17739 // We want to print the character representation for textual types
17740 const auto *BTy = T->getAs<BuiltinType>();
17741 if (BTy) {
17742 switch (BTy->getKind()) {
17743 case BuiltinType::Char_S:
17744 case BuiltinType::Char_U:
17745 case BuiltinType::Char8:
17746 case BuiltinType::Char16:
17747 case BuiltinType::Char32:
17748 case BuiltinType::WChar_S:
17749 case BuiltinType::WChar_U: {
17750 unsigned TyWidth = Context.getIntWidth(T);
17751 assert(8 <= TyWidth && TyWidth <= 32 && "Unexpected integer width");
17752 uint32_t CodeUnit = static_cast<uint32_t>(V.getInt().getZExtValue());
17753 WriteCharTypePrefix(BTy->getKind(), OS);
17754 OS << '\'';
17755 WriteCharValueForDiagnostic(CodeUnit, BTy, TyWidth, Str);
17756 OS << "' (0x"
17757 << llvm::format_hex_no_prefix(CodeUnit, /*Width=*/2,
17758 /*Upper=*/true)
17759 << ", " << V.getInt() << ')';
17760 return true;
17761 }
17762 default:
17763 break;
17764 }
17765 }
17766 V.getInt().toString(Str);
17767 }
17768
17769 break;
17770
17772 V.getFloat().toString(Str);
17773 break;
17774
17776 if (V.isNullPointer()) {
17777 llvm::raw_svector_ostream OS(Str);
17778 OS << "nullptr";
17779 } else
17780 return false;
17781 break;
17782
17784 llvm::raw_svector_ostream OS(Str);
17785 OS << '(';
17786 V.getComplexFloatReal().toString(Str);
17787 OS << " + ";
17788 V.getComplexFloatImag().toString(Str);
17789 OS << "i)";
17790 } break;
17791
17793 llvm::raw_svector_ostream OS(Str);
17794 OS << '(';
17795 V.getComplexIntReal().toString(Str);
17796 OS << " + ";
17797 V.getComplexIntImag().toString(Str);
17798 OS << "i)";
17799 } break;
17800
17801 default:
17802 return false;
17803 }
17804
17805 return true;
17806}
17807
17808/// Some Expression types are not useful to print notes about,
17809/// e.g. literals and values that have already been expanded
17810/// before such as int-valued template parameters.
17811static bool UsefulToPrintExpr(const Expr *E) {
17812 E = E->IgnoreParenImpCasts();
17813 // Literals are pretty easy for humans to understand.
17816 return false;
17817
17818 // These have been substituted from template parameters
17819 // and appear as literals in the static assert error.
17821 return false;
17822
17823 // -5 is also simple to understand.
17824 if (const auto *UnaryOp = dyn_cast<UnaryOperator>(E))
17825 return UsefulToPrintExpr(UnaryOp->getSubExpr());
17826
17827 // Only print nested arithmetic operators.
17828 if (const auto *BO = dyn_cast<BinaryOperator>(E))
17829 return (BO->isShiftOp() || BO->isAdditiveOp() || BO->isMultiplicativeOp() ||
17830 BO->isBitwiseOp());
17831
17832 return true;
17833}
17834
17836 if (const auto *Op = dyn_cast<BinaryOperator>(E);
17837 Op && Op->getOpcode() != BO_LOr) {
17838 const Expr *LHS = Op->getLHS()->IgnoreParenImpCasts();
17839 const Expr *RHS = Op->getRHS()->IgnoreParenImpCasts();
17840
17841 // Ignore comparisons of boolean expressions with a boolean literal.
17842 if ((isa<CXXBoolLiteralExpr>(LHS) && RHS->getType()->isBooleanType()) ||
17843 (isa<CXXBoolLiteralExpr>(RHS) && LHS->getType()->isBooleanType()))
17844 return;
17845
17846 // Don't print obvious expressions.
17847 if (!UsefulToPrintExpr(LHS) && !UsefulToPrintExpr(RHS))
17848 return;
17849
17850 struct {
17851 const clang::Expr *Cond;
17853 SmallString<12> ValueString;
17854 bool Print;
17855 } DiagSides[2] = {{LHS, Expr::EvalResult(), {}, false},
17856 {RHS, Expr::EvalResult(), {}, false}};
17857 for (auto &DiagSide : DiagSides) {
17858 const Expr *Side = DiagSide.Cond;
17859
17860 Side->EvaluateAsRValue(DiagSide.Result, Context, true);
17861
17862 DiagSide.Print = ConvertAPValueToString(
17863 DiagSide.Result.Val, Side->getType(), DiagSide.ValueString, Context);
17864 }
17865 if (DiagSides[0].Print && DiagSides[1].Print) {
17866 Diag(Op->getExprLoc(), diag::note_expr_evaluates_to)
17867 << DiagSides[0].ValueString << Op->getOpcodeStr()
17868 << DiagSides[1].ValueString << Op->getSourceRange();
17869 }
17870 } else {
17872 }
17873}
17874
17875template <typename ResultType>
17876static bool EvaluateAsStringImpl(Sema &SemaRef, Expr *Message,
17877 ResultType &Result, ASTContext &Ctx,
17879 bool ErrorOnInvalidMessage) {
17880
17881 assert(Message);
17882 assert(!Message->isTypeDependent() && !Message->isValueDependent() &&
17883 "can't evaluate a dependant static assert message");
17884
17885 if (const auto *SL = dyn_cast<StringLiteral>(Message)) {
17886 assert(SL->isUnevaluated() && "expected an unevaluated string");
17887 if constexpr (std::is_same_v<APValue, ResultType>) {
17888 Result =
17889 APValue(APValue::UninitArray{}, SL->getLength(), SL->getLength());
17890 const ConstantArrayType *CAT =
17891 SemaRef.getASTContext().getAsConstantArrayType(SL->getType());
17892 assert(CAT && "string literal isn't an array");
17893 QualType CharType = CAT->getElementType();
17894 llvm::APSInt Value(SemaRef.getASTContext().getTypeSize(CharType),
17895 CharType->isUnsignedIntegerType());
17896 for (unsigned I = 0; I < SL->getLength(); I++) {
17897 Value = SL->getCodeUnit(I);
17898 Result.getArrayInitializedElt(I) = APValue(Value);
17899 }
17900 } else {
17901 Result.assign(SL->getString().begin(), SL->getString().end());
17902 }
17903 return true;
17904 }
17905
17906 SourceLocation Loc = Message->getBeginLoc();
17907 QualType T = Message->getType().getNonReferenceType();
17908 auto *RD = T->getAsCXXRecordDecl();
17909 if (!RD) {
17910 SemaRef.Diag(Loc, diag::err_user_defined_msg_invalid) << EvalContext;
17911 return false;
17912 }
17913
17914 auto FindMember = [&](StringRef Member) -> std::optional<LookupResult> {
17916 LookupResult MemberLookup(SemaRef, DN, Loc, Sema::LookupMemberName);
17917 SemaRef.LookupQualifiedName(MemberLookup, RD);
17918 OverloadCandidateSet Candidates(MemberLookup.getNameLoc(),
17920 if (MemberLookup.empty())
17921 return std::nullopt;
17922 return std::move(MemberLookup);
17923 };
17924
17925 std::optional<LookupResult> SizeMember = FindMember("size");
17926 std::optional<LookupResult> DataMember = FindMember("data");
17927 if (!SizeMember || !DataMember) {
17928 SemaRef.Diag(Loc, diag::err_user_defined_msg_missing_member_function)
17929 << EvalContext
17930 << ((!SizeMember && !DataMember) ? 2
17931 : !SizeMember ? 0
17932 : 1);
17933 return false;
17934 }
17935
17936 auto BuildExpr = [&](LookupResult &LR) {
17938 Message, Message->getType(), Message->getBeginLoc(), false,
17939 CXXScopeSpec(), SourceLocation(), nullptr, LR, nullptr, nullptr);
17940 if (Res.isInvalid())
17941 return ExprError();
17942 Res = SemaRef.BuildCallExpr(nullptr, Res.get(), Loc, {}, Loc, nullptr,
17943 false, true);
17944 if (Res.isInvalid())
17945 return ExprError();
17946 if (Res.get()->isTypeDependent() || Res.get()->isValueDependent())
17947 return ExprError();
17948 return SemaRef.TemporaryMaterializationConversion(Res.get());
17949 };
17950
17951 ExprResult SizeE = BuildExpr(*SizeMember);
17952 ExprResult DataE = BuildExpr(*DataMember);
17953
17954 QualType SizeT = SemaRef.Context.getSizeType();
17955 QualType ConstCharPtr = SemaRef.Context.getPointerType(
17956 SemaRef.Context.getConstType(SemaRef.Context.CharTy));
17957
17958 ExprResult EvaluatedSize =
17959 SizeE.isInvalid()
17960 ? ExprError()
17963 if (EvaluatedSize.isInvalid()) {
17964 SemaRef.Diag(Loc, diag::err_user_defined_msg_invalid_mem_fn_ret_ty)
17965 << EvalContext << /*size*/ 0;
17966 return false;
17967 }
17968
17969 ExprResult EvaluatedData =
17970 DataE.isInvalid()
17971 ? ExprError()
17973 DataE.get(), ConstCharPtr, CCEKind::StaticAssertMessageData);
17974 if (EvaluatedData.isInvalid()) {
17975 SemaRef.Diag(Loc, diag::err_user_defined_msg_invalid_mem_fn_ret_ty)
17976 << EvalContext << /*data*/ 1;
17977 return false;
17978 }
17979
17980 if (!ErrorOnInvalidMessage &&
17981 SemaRef.Diags.isIgnored(diag::warn_user_defined_msg_constexpr, Loc))
17982 return true;
17983
17984 Expr::EvalResult Status;
17986 Status.Diag = &Notes;
17987 if (!Message->EvaluateCharRangeAsString(Result, EvaluatedSize.get(),
17988 EvaluatedData.get(), Ctx, Status) ||
17989 !Notes.empty()) {
17990 SemaRef.Diag(Message->getBeginLoc(),
17991 ErrorOnInvalidMessage ? diag::err_user_defined_msg_constexpr
17992 : diag::warn_user_defined_msg_constexpr)
17993 << EvalContext;
17994 for (const auto &Note : Notes)
17995 SemaRef.Diag(Note.first, Note.second);
17996 return !ErrorOnInvalidMessage;
17997 }
17998 return true;
17999}
18000
18002 StringEvaluationContext EvalContext,
18003 bool ErrorOnInvalidMessage) {
18004 return EvaluateAsStringImpl(*this, Message, Result, Ctx, EvalContext,
18005 ErrorOnInvalidMessage);
18006}
18007
18008bool Sema::EvaluateAsString(Expr *Message, std::string &Result, ASTContext &Ctx,
18009 StringEvaluationContext EvalContext,
18010 bool ErrorOnInvalidMessage) {
18011 return EvaluateAsStringImpl(*this, Message, Result, Ctx, EvalContext,
18012 ErrorOnInvalidMessage);
18013}
18014
18016 Expr *AssertExpr, Expr *AssertMessage,
18017 SourceLocation RParenLoc,
18018 bool Failed) {
18019 assert(AssertExpr != nullptr && "Expected non-null condition");
18020 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
18021 (!AssertMessage || (!AssertMessage->isTypeDependent() &&
18022 !AssertMessage->isValueDependent())) &&
18023 !Failed) {
18024 // In a static_assert-declaration, the constant-expression shall be a
18025 // constant expression that can be contextually converted to bool.
18026 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
18027 if (Converted.isInvalid())
18028 Failed = true;
18029
18030 ExprResult FullAssertExpr =
18031 ActOnFinishFullExpr(Converted.get(), StaticAssertLoc,
18032 /*DiscardedValue*/ false,
18033 /*IsConstexpr*/ true);
18034 if (FullAssertExpr.isInvalid())
18035 Failed = true;
18036 else
18037 AssertExpr = FullAssertExpr.get();
18038
18039 llvm::APSInt Cond;
18040 Expr *BaseExpr = AssertExpr;
18042
18043 if (!getLangOpts().CPlusPlus) {
18044 // In C mode, allow folding as an extension for better compatibility with
18045 // C++ in terms of expressions like static_assert("test") or
18046 // static_assert(nullptr).
18047 FoldKind = AllowFoldKind::Allow;
18048 }
18049
18050 if (!Failed && VerifyIntegerConstantExpression(
18051 BaseExpr, &Cond,
18052 diag::err_static_assert_expression_is_not_constant,
18053 FoldKind).isInvalid())
18054 Failed = true;
18055
18056 // If the static_assert passes, only verify that
18057 // the message is grammatically valid without evaluating it.
18058 if (!Failed && AssertMessage && Cond.getBoolValue()) {
18059 std::string Str;
18060 EvaluateAsString(AssertMessage, Str, Context,
18062 /*ErrorOnInvalidMessage=*/false);
18063 }
18064
18065 // CWG2518
18066 // [dcl.pre]/p10 If [...] the expression is evaluated in the context of a
18067 // template definition, the declaration has no effect.
18068 bool InTemplateDefinition =
18069 getLangOpts().CPlusPlus && CurContext->isDependentContext();
18070
18071 if (!Failed && !Cond && !InTemplateDefinition) {
18072 SmallString<256> MsgBuffer;
18073 llvm::raw_svector_ostream Msg(MsgBuffer);
18074 bool HasMessage = AssertMessage;
18075 if (AssertMessage) {
18076 std::string Str;
18077 HasMessage = EvaluateAsString(AssertMessage, Str, Context,
18079 /*ErrorOnInvalidMessage=*/true) ||
18080 !Str.empty();
18081 Msg << Str;
18082 }
18083 Expr *InnerCond = nullptr;
18084 std::string InnerCondDescription;
18085 std::tie(InnerCond, InnerCondDescription) =
18086 findFailedBooleanCondition(Converted.get());
18087 if (const auto *ConceptIDExpr =
18088 dyn_cast_or_null<ConceptSpecializationExpr>(InnerCond)) {
18089 const ASTConstraintSatisfaction &Satisfaction =
18090 ConceptIDExpr->getSatisfaction();
18091 if (!Satisfaction.ContainsErrors || Satisfaction.NumRecords) {
18092 Diag(AssertExpr->getBeginLoc(), diag::err_static_assert_failed)
18093 << !HasMessage << Msg.str() << AssertExpr->getSourceRange();
18094 // Drill down into concept specialization expressions to see why they
18095 // weren't satisfied.
18096 DiagnoseUnsatisfiedConstraint(ConceptIDExpr);
18097 }
18098 } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond) &&
18099 !isa<IntegerLiteral>(InnerCond)) {
18100 Diag(InnerCond->getBeginLoc(),
18101 diag::err_static_assert_requirement_failed)
18102 << InnerCondDescription << !HasMessage << Msg.str()
18103 << InnerCond->getSourceRange();
18104 DiagnoseStaticAssertDetails(InnerCond);
18105 } else {
18106 Diag(AssertExpr->getBeginLoc(), diag::err_static_assert_failed)
18107 << !HasMessage << Msg.str() << AssertExpr->getSourceRange();
18109 }
18110 Failed = true;
18111 }
18112 } else {
18113 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
18114 /*DiscardedValue*/false,
18115 /*IsConstexpr*/true);
18116 if (FullAssertExpr.isInvalid())
18117 Failed = true;
18118 else
18119 AssertExpr = FullAssertExpr.get();
18120 }
18121
18123 AssertExpr, AssertMessage, RParenLoc,
18124 Failed);
18125
18126 CurContext->addDecl(Decl);
18127 return Decl;
18128}
18129
18131 if (const auto *PIT = dyn_cast<PackIndexingType>(T))
18132 return PIT->getPattern();
18133 return T;
18134}
18135
18136static const TemplateSpecializationType *
18139 if (const auto *ICNT = dyn_cast<InjectedClassNameType>(T))
18140 T = ICNT->getDecl()->getCanonicalTemplateSpecializationType(Context);
18141
18142 const auto *TST = dyn_cast<TemplateSpecializationType>(T);
18143 if (!TST)
18144 return nullptr;
18145
18146 TemplateDecl *TD = TST->getTemplateName().getAsTemplateDecl();
18147 if (!TD || isa<ClassTemplateDecl>(TD))
18148 return TST;
18149 return nullptr;
18150}
18151
18153 NestedNameSpecifierLoc NNSLoc) {
18154 for (TypeLoc TL = NNSLoc.getAsTypeLoc(); TL;
18155 TL = TL.getPrefix().getAsTypeLoc()) {
18156 if (TL.getTypeLocClass() != TypeLoc::PackIndexing)
18157 continue;
18158
18159 Diag(Loc, diag::err_pack_indexing_in_friend) << TL.getSourceRange();
18160 return true;
18161 }
18162 return false;
18163}
18164
18166 NestedNameSpecifier NNS) {
18167 QualType T(NNS.getAsType(), 0);
18168 if (const auto *TST =
18169 dyn_cast<TemplateSpecializationType>(IgnorePackIndexing(T))) {
18170 if (isa_and_nonnull<TypeAliasTemplateDecl>(
18171 TST->getTemplateName().getAsTemplateDecl())) {
18172 S.Diag(Loc, diag::err_dependent_friend_not_member_of_template_spec)
18173 << NNS;
18174 return;
18175 }
18176 }
18177
18178 if (NNS.getAsRecordDecl()) {
18179 S.Diag(Loc, diag::err_dependent_friend_not_member_of_template_spec) << NNS;
18180 } else {
18181 S.Diag(Loc, diag::err_dependent_friend_not_member);
18182 }
18183}
18184
18188 bool IsInstantiation) {
18190 if (!NNS.isDependent() && !IsInstantiation)
18191 return false;
18192
18193 assert(NNS.getKind() == NestedNameSpecifier::Kind::Type &&
18194 "nested-name-specifier of dependent friend must be a type");
18195
18196 QualType T(NNS.getAsType(), 0);
18197 if (DiagnosePackIndexingInFriendNNS(Loc, NNSLoc))
18198 return true;
18199
18200 const TemplateSpecializationType *TST =
18202 if (!TST) {
18203 DiagnoseDependentFriendNotMember(*this, Loc, NNS);
18204 return true;
18205 }
18206
18207 if (TPLs.empty())
18208 return false;
18209
18210 SmallVector<NamedDecl *, 4> UndeducedParameters;
18211 for (TemplateParameterList *Params : TPLs) {
18212 llvm::SmallBitVector UsedParameters(Params->size());
18213 MarkUsedTemplateParameters(TST->template_arguments(),
18214 /*OnlyDeduced=*/true, Params->getDepth(),
18215 UsedParameters);
18216
18217 for (unsigned I = 0, N = UsedParameters.size(); I != N; ++I)
18218 if (!UsedParameters[I])
18219 UndeducedParameters.push_back(Params->getParam(I));
18220 }
18221
18222 if (UndeducedParameters.empty())
18223 return false;
18224
18225 Diag(Loc, diag::err_dependent_friend_undeduced_params)
18226 << (UndeducedParameters.size() > 1) << QualType(TST, 0);
18227
18228 for (NamedDecl *Param : UndeducedParameters) {
18229 if (Param->getDeclName())
18230 Diag(Param->getLocation(), diag::note_non_deducible_parameter)
18231 << Param->getDeclName();
18232 else
18233 Diag(Param->getLocation(), diag::note_non_deducible_parameter)
18234 << "(anonymous)";
18235 }
18236
18237 return true;
18238}
18239
18241 Scope *S, SourceLocation FriendLoc, unsigned TagSpec, SourceLocation TagLoc,
18242 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
18243 SourceLocation EllipsisLoc, const ParsedAttributesView &Attr,
18244 MultiTemplateParamsArg TempParamLists, TemplateIdAnnotation *TemplateId) {
18246
18247 bool IsMemberSpecialization = false;
18248 bool Invalid = false;
18249
18250 TemplateParameterList *TemplateParams =
18251 MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS, TemplateId,
18252 TempParamLists, /*friend*/ true,
18253 IsMemberSpecialization, Invalid);
18254 if (TemplateId) {
18255 if (Invalid)
18256 return true;
18257
18258 if (TemplateParams) {
18259 Diag(NameLoc, diag::err_not_class_template_specialization) << 0;
18260 return true;
18261 }
18262 }
18263
18264 if (TemplateParams) {
18265 if (TemplateParams->size() > 0) {
18266 if (Invalid)
18267 return true;
18268
18269 if (SS.isEmpty() || !SS.getScopeRep().isDependent()) {
18271 S, TagSpec, TagUseKind::Friend, TagLoc, SS, Name, NameLoc, Attr,
18272 TemplateParams, AS_public, /*ModulePrivateLoc=*/SourceLocation(),
18273 FriendLoc, TempParamLists.size() - 1, TempParamLists.data(),
18274 IsMemberSpecialization);
18275 return Result.get();
18276 }
18277 } else {
18278 // The "template<>" header is extraneous.
18279 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
18280 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
18281 }
18282 }
18283
18284 if (Invalid)
18285 return true;
18286
18287 bool IsAllExplicitSpecializations =
18288 llvm::all_of(TempParamLists, [](const TemplateParameterList *List) {
18289 return List->size() == 0;
18290 });
18291
18292 // FIXME: don't ignore attributes.
18293
18294 // If it's explicit specializations all the way down, just forget
18295 // about the template header and build an appropriate non-templated
18296 // friend. TODO: for source fidelity, remember the headers.
18298 if (!TemplateId && IsAllExplicitSpecializations) {
18299 if (SS.isEmpty()) {
18300 bool Owned = false;
18301 bool IsDependent = false;
18302 return ActOnTag(S, TagSpec, TagUseKind::Friend, TagLoc, SS, Name, NameLoc,
18303 Attr, AS_public,
18304 /*ModulePrivateLoc=*/SourceLocation(),
18305 MultiTemplateParamsArg(), Owned, IsDependent,
18306 /*ScopedEnumKWLoc=*/SourceLocation(),
18307 /*ScopedEnumUsesClassTag=*/false,
18308 /*UnderlyingType=*/TypeResult(),
18309 /*IsTypeSpecifier=*/false,
18310 /*IsTemplateParamOrArg=*/false,
18311 /*OOK=*/OffsetOfKind::Outside);
18312 }
18313
18314 TypeSourceInfo *TSI = nullptr;
18317 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, *Name,
18318 NameLoc, &TSI, /*DeducedTSTContext=*/true);
18319 if (T.isNull())
18320 return true;
18321
18323 FriendLoc, EllipsisLoc);
18324 Friend->setAccess(AS_public);
18325 CurContext->addDecl(Friend);
18326 return Friend;
18327 }
18328
18329 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
18330
18331 ArrayRef<TemplateParameterList *> TPLs = TempParamLists;
18332 if (TemplateParams)
18333 TPLs = TPLs.drop_back();
18334 if (CheckDependentFriend(TagLoc, QualifierLoc, TPLs,
18335 /*IsInstantiation=*/false))
18336 return true;
18337
18338 TypeSourceInfo *TSI = nullptr;
18339 if (TemplateId) {
18340 ASTTemplateArgsPtr ParsedArgs(TemplateId->getTemplateArgs(),
18341 TemplateId->NumArgs);
18343 TagUseKind::Friend, static_cast<TypeSpecifierType>(TagSpec), TagLoc, SS,
18344 TemplateId->TemplateKWLoc, TemplateId->Template, NameLoc,
18345 TemplateId->LAngleLoc, ParsedArgs, TemplateId->RAngleLoc);
18346 if (ParsedType.isInvalid())
18347 return true;
18348
18349 GetTypeFromParser(ParsedType.get(), &TSI);
18350 } else {
18352 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
18353 TSI = Context.CreateTypeSourceInfo(T);
18354
18356 TL.setElaboratedKeywordLoc(TagLoc);
18357 TL.setQualifierLoc(QualifierLoc);
18358 TL.setNameLoc(NameLoc);
18359 }
18360
18362 collectUnexpandedParameterPacks(TSI->getTypeLoc(), Unexpanded);
18363 if (EllipsisLoc.isInvalid()) {
18365 return true;
18366 } else if (Unexpanded.empty()) {
18367 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
18368 << TSI->getTypeLoc().getSourceRange();
18369 return true;
18370 } else {
18371 // CWG 2917: a pack expanded by a friend-type-specifier cannot have been
18372 // introduced by the template-declaration containing that specifier.
18373 if (!TempParamLists.empty()) {
18374 unsigned FriendDeclDepth = TempParamLists.front()->getDepth();
18375 for (UnexpandedParameterPack &U : Unexpanded) {
18376 if (std::optional<std::pair<unsigned, unsigned>> DI =
18378 DI && DI->first >= FriendDeclDepth) {
18379 auto *ND = dyn_cast<NamedDecl *>(U.first);
18380 if (!ND)
18381 ND = cast<const TemplateTypeParmType *>(U.first)->getDecl();
18382 Diag(U.second, diag::friend_template_decl_malformed_pack_expansion)
18383 << ND->getDeclName()
18384 << SourceRange(TSI->getTypeLoc().getBeginLoc(), EllipsisLoc);
18385 return true;
18386 }
18387 }
18388 }
18389 }
18390
18392 if (TempParamLists.empty())
18393 Friend = FriendDecl::Create(Context, CurContext, NameLoc, TSI, FriendLoc,
18394 EllipsisLoc);
18395 else {
18396 if (CheckTemplateDeclScope(S, TempParamLists.back()))
18397 return true;
18398
18400 if (TemplateParams)
18401 FriendTemplate = Context.getDependentTemplateName(
18402 {SS.getScopeRep(), Name, /*HasTemplateKeyword=*/false});
18403 Friend =
18404 FriendTemplateDecl::Create(Context, CurContext, NameLoc, TSI, FriendLoc,
18405 TempParamLists, EllipsisLoc, FriendTemplate);
18406 }
18407
18408 Friend->setAccess(AS_public);
18409 CurContext->addDecl(Friend);
18410
18411 return Friend;
18412}
18413
18415 MultiTemplateParamsArg TempParams,
18416 SourceLocation EllipsisLoc) {
18417 SourceLocation Loc = DS.getBeginLoc();
18418 SourceLocation FriendLoc = DS.getFriendSpecLoc();
18419
18420 assert(DS.isFriendSpecified());
18422
18423 // C++ [class.friend]p3:
18424 // A friend declaration that does not declare a function shall have one of
18425 // the following forms:
18426 // friend elaborated-type-specifier ;
18427 // friend simple-type-specifier ;
18428 // friend typename-specifier ;
18429 //
18430 // If the friend keyword isn't first, or if the declarations has any type
18431 // qualifiers, then the declaration doesn't have that form.
18433 Diag(FriendLoc, diag::err_friend_not_first_in_declaration);
18434 if (DS.getTypeQualifiers()) {
18436 Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
18438 Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
18440 Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
18442 Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
18444 Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
18445 }
18446
18447 // Try to convert the decl specifier to a type. This works for
18448 // friend templates because ActOnTag never produces a ClassTemplateDecl
18449 // for a TagUseKind::Friend.
18450 Declarator TheDeclarator(DS, ParsedAttributesView::none(),
18452 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator);
18453 QualType T = TSI->getType();
18454 if (TheDeclarator.isInvalidType())
18455 return nullptr;
18456
18457 // If '...' is present, the type must contain an unexpanded parameter
18458 // pack, and vice versa.
18459 bool Invalid = false;
18460 if (EllipsisLoc.isInvalid() &&
18462 return nullptr;
18463 if (EllipsisLoc.isValid() &&
18465 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
18466 << TSI->getTypeLoc().getSourceRange();
18467 Invalid = true;
18468 }
18469
18470 if (!T->isElaboratedTypeSpecifier()) {
18471 if (TempParams.size()) {
18472 // C++23 [dcl.pre]p5:
18473 // In a simple-declaration, the optional init-declarator-list can be
18474 // omitted only when declaring a class or enumeration, that is, when
18475 // the decl-specifier-seq contains either a class-specifier, an
18476 // elaborated-type-specifier with a class-key, or an enum-specifier.
18477 //
18478 // The declaration of a template-declaration or explicit-specialization
18479 // is never a member-declaration, so this must be a simple-declaration
18480 // with no init-declarator-list. Therefore, this is ill-formed.
18481 Diag(Loc, diag::err_tagless_friend_type_template) << DS.getSourceRange();
18482 return nullptr;
18483 } else if (const RecordDecl *RD = T->getAsRecordDecl()) {
18484 SmallString<16> InsertionText(" ");
18485 InsertionText += RD->getKindName();
18486
18488 ? diag::warn_cxx98_compat_unelaborated_friend_type
18489 : diag::ext_unelaborated_friend_type)
18490 << (unsigned)RD->getTagKind() << T
18492 InsertionText);
18493 } else {
18494 DiagCompat(FriendLoc, diag_compat::nonclass_type_friend)
18495 << T << DS.getSourceRange();
18496 }
18497 }
18498
18499 // C++98 [class.friend]p1: A friend of a class is a function
18500 // or class that is not a member of the class . . .
18501 // This is fixed in DR77, which just barely didn't make the C++03
18502 // deadline. It's also a very silly restriction that seriously
18503 // affects inner classes and which nobody else seems to implement;
18504 // thus we never diagnose it, not even in -pedantic.
18505 //
18506 // But note that we could warn about it: it's always useless to
18507 // friend one of your own members (it's not, however, worthless to
18508 // friend a member of an arbitrary specialization of your template).
18509
18510 Decl *D;
18511 if (!TempParams.empty()) {
18512 if (CheckTemplateDeclScope(S, TempParams.back()))
18513 return nullptr;
18514
18515 // TODO: Support variadic friend template decls?
18516 D = FriendTemplateDecl::Create(Context, CurContext, Loc, TSI, FriendLoc,
18517 TempParams, EllipsisLoc);
18518 } else
18520 TSI, FriendLoc, EllipsisLoc);
18521
18522 if (!D)
18523 return nullptr;
18524
18525 D->setAccess(AS_public);
18526 CurContext->addDecl(D);
18527
18528 if (Invalid)
18529 D->setInvalidDecl();
18530
18531 return D;
18532}
18533
18535 MultiTemplateParamsArg TemplateParams) {
18536 const DeclSpec &DS = D.getDeclSpec();
18537
18538 assert(DS.isFriendSpecified());
18540
18543
18544 // C++ [class.friend]p1
18545 // A friend of a class is a function or class....
18546 // Note that this sees through typedefs, which is intended.
18547 // It *doesn't* see through dependent types, which is correct
18548 // according to [temp.arg.type]p3:
18549 // If a declaration acquires a function type through a
18550 // type dependent on a template-parameter and this causes
18551 // a declaration that does not use the syntactic form of a
18552 // function declarator to have a function type, the program
18553 // is ill-formed.
18554 if (!TInfo->getType()->isFunctionType()) {
18555 Diag(Loc, diag::err_unexpected_friend);
18556
18557 // It might be worthwhile to try to recover by creating an
18558 // appropriate declaration.
18559 return nullptr;
18560 }
18561
18562 // C++ [namespace.memdef]p3
18563 // - If a friend declaration in a non-local class first declares a
18564 // class or function, the friend class or function is a member
18565 // of the innermost enclosing namespace.
18566 // - The name of the friend is not found by simple name lookup
18567 // until a matching declaration is provided in that namespace
18568 // scope (either before or after the class declaration granting
18569 // friendship).
18570 // - If a friend function is called, its name may be found by the
18571 // name lookup that considers functions from namespaces and
18572 // classes associated with the types of the function arguments.
18573 // - When looking for a prior declaration of a class or a function
18574 // declared as a friend, scopes outside the innermost enclosing
18575 // namespace scope are not considered.
18576
18577 CXXScopeSpec &SS = D.getCXXScopeSpec();
18579 assert(NameInfo.getName());
18580
18582 NameInfo.getLoc(), SS.getWithLocInContext(Context)))
18583 return nullptr;
18584
18585 // Check for unexpanded parameter packs.
18589 return nullptr;
18590
18591 bool isTemplateId = D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
18592
18593 if (D.isFunctionDefinition() && SS.isNotEmpty() && !isTemplateId) {
18594 auto Kind = SS.getScopeRep().getKind();
18595 bool IsNamespaceOrGlobal = Kind == NestedNameSpecifier::Kind::Global ||
18597 if (IsNamespaceOrGlobal) {
18598 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
18599 << SS.getScopeRep();
18600 SS.clear();
18601 }
18602 }
18603
18604 // The context we found the declaration in, or in which we should
18605 // create the declaration.
18606 DeclContext *DC;
18607 Scope *DCScope = S;
18608 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
18610
18611 // There are five cases here.
18612 // - There's no scope specifier and we're in a local class. Only look
18613 // for functions declared in the immediately-enclosing block scope.
18614 // We recover from invalid scope qualifiers as if they just weren't there.
18615 FunctionDecl *FunctionContainingLocalClass = nullptr;
18616 if ((SS.isInvalid() || !SS.isSet()) &&
18617 (FunctionContainingLocalClass =
18618 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
18619 // C++11 [class.friend]p11:
18620 // If a friend declaration appears in a local class and the name
18621 // specified is an unqualified name, a prior declaration is
18622 // looked up without considering scopes that are outside the
18623 // innermost enclosing non-class scope. For a friend function
18624 // declaration, if there is no prior declaration, the program is
18625 // ill-formed.
18626
18627 // Find the innermost enclosing non-class scope. This is the block
18628 // scope containing the local class definition (or for a nested class,
18629 // the outer local class).
18630 DCScope = S->getFnParent();
18631
18632 // Look up the function name in the scope.
18634 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
18635
18636 if (!Previous.empty()) {
18637 // All possible previous declarations must have the same context:
18638 // either they were declared at block scope or they are members of
18639 // one of the enclosing local classes.
18640 DC = Previous.getRepresentativeDecl()->getDeclContext();
18641 } else {
18642 // This is ill-formed, but provide the context that we would have
18643 // declared the function in, if we were permitted to, for error recovery.
18644 DC = FunctionContainingLocalClass;
18645 }
18647
18648 // - There's no scope specifier, in which case we just go to the
18649 // appropriate scope and look for a function or function template
18650 // there as appropriate.
18651 } else if (SS.isInvalid() || !SS.isSet()) {
18652 // C++11 [namespace.memdef]p3:
18653 // If the name in a friend declaration is neither qualified nor
18654 // a template-id and the declaration is a function or an
18655 // elaborated-type-specifier, the lookup to determine whether
18656 // the entity has been previously declared shall not consider
18657 // any scopes outside the innermost enclosing namespace.
18658
18659 // Find the appropriate context according to the above.
18660 DC = CurContext;
18661
18662 // Skip class contexts. If someone can cite chapter and verse
18663 // for this behavior, that would be nice --- it's what GCC and
18664 // EDG do, and it seems like a reasonable intent, but the spec
18665 // really only says that checks for unqualified existing
18666 // declarations should stop at the nearest enclosing namespace,
18667 // not that they should only consider the nearest enclosing
18668 // namespace.
18669 while (DC->isRecord())
18670 DC = DC->getParent();
18671
18672 DeclContext *LookupDC = DC->getNonTransparentContext();
18673 while (true) {
18674 LookupQualifiedName(Previous, LookupDC);
18675
18676 if (!Previous.empty()) {
18677 DC = LookupDC;
18678 break;
18679 }
18680
18681 if (isTemplateId) {
18682 if (isa<TranslationUnitDecl>(LookupDC)) break;
18683 } else {
18684 if (LookupDC->isFileContext()) break;
18685 }
18686 LookupDC = LookupDC->getParent();
18687 }
18688
18689 DCScope = getScopeForDeclContext(S, DC);
18690
18691 // - There's a non-dependent scope specifier, in which case we
18692 // compute it and do a previous lookup there for a function
18693 // or function template.
18694 } else if (!SS.getScopeRep().isDependent()) {
18695 DC = computeDeclContext(SS);
18696 if (!DC) return nullptr;
18697
18698 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
18699
18701
18702 // C++ [class.friend]p1: A friend of a class is a function or
18703 // class that is not a member of the class . . .
18704 if (DC->Equals(CurContext))
18707 diag::warn_cxx98_compat_friend_is_member :
18708 diag::err_friend_is_member);
18709
18710 // - There's a dependent scope specifier, in which case we use an
18711 // arbitrary context and wait for instantiation.
18712 } else {
18713 DC = CurContext;
18714 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
18715 }
18716
18717 if (!DC->isRecord()) {
18718 int DiagArg = -1;
18719 switch (D.getName().getKind()) {
18722 DiagArg = 0;
18723 break;
18725 DiagArg = 1;
18726 break;
18728 DiagArg = 2;
18729 break;
18731 DiagArg = 3;
18732 break;
18738 break;
18739 }
18740 // This implies that it has to be an operator or function.
18741 if (DiagArg >= 0) {
18742 Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
18743 return nullptr;
18744 }
18745 } else {
18746 CXXRecordDecl *RC = dyn_cast<CXXRecordDecl>(DC);
18747 if (RC->isLambda()) {
18748 Diag(NameInfo.getBeginLoc(), diag::err_friend_lambda_decl);
18749 }
18750 }
18751
18752 // FIXME: This is an egregious hack to cope with cases where the scope stack
18753 // does not contain the declaration context, i.e., in an out-of-line
18754 // definition of a class.
18755 Scope FakeDCScope(S, Scope::DeclScope, Diags);
18756 if (!DCScope) {
18757 FakeDCScope.setEntity(DC);
18758 DCScope = &FakeDCScope;
18759 }
18760
18761 bool AddToScope = true;
18762 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
18763 TemplateParams, AddToScope);
18764 if (!ND) return nullptr;
18765
18766 assert(ND->getLexicalDeclContext() == CurContext);
18767
18768 // If we performed typo correction, we might have added a scope specifier
18769 // and changed the decl context.
18770 DC = ND->getDeclContext();
18771
18772 // Add the function declaration to the appropriate lookup tables,
18773 // adjusting the redeclarations list as necessary. We don't
18774 // want to do this yet if the friending class is dependent.
18775 //
18776 // Also update the scope-based lookup if the target context's
18777 // lookup context is in lexical scope.
18778 if (!CurContext->isDependentContext()) {
18779 DC = DC->getRedeclContext();
18781 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
18782 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
18783 }
18784
18786
18787 if (ND->isInvalidDecl()) {
18790 Friend->setAccess(AS_public);
18792 Friend->setInvalidDecl();
18793 CurContext->addDecl(Friend);
18794 return ND;
18795 }
18796
18797 FunctionDecl *FD = ND->getAsFunction();
18798 assert(FD && "Expected a function declaration!");
18799
18801 if (!TPLs.empty() && SS.isValid() && CheckTemplateDeclScope(S, TPLs.back()))
18802 return nullptr;
18803
18805 if (!TPLs.empty() && SS.isValid())
18806 Friend =
18808 ND, DS.getFriendSpecLoc(), TPLs);
18809 else
18811 DS.getFriendSpecLoc());
18812
18813 Friend->setAccess(AS_public);
18814 CurContext->addDecl(Friend);
18815
18816 if (DC->isRecord())
18818
18819 if (!TemplateParams.empty() && SS.isValid() &&
18822 /*IsInstantiation=*/false))
18823 return ND;
18824
18825 // C++ [class.friend]p6:
18826 // A function may be defined in a friend declaration of a class if and
18827 // only if the class is a non-local class, and the function name is
18828 // unqualified.
18829 if (D.isFunctionDefinition()) {
18830 // Qualified friend function definition.
18831 if (SS.isNotEmpty()) {
18833 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
18834
18835 DB << SS.getScopeRep();
18836
18837 // Friend function defined in a local class.
18838 } else if (FunctionContainingLocalClass) {
18839 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
18840
18841 // Per [basic.pre]p4, a template-id is not a name. Therefore, if we have
18842 // a template-id, the function name is not unqualified because these is
18843 // no name. While the wording requires some reading in-between the
18844 // lines, GCC, MSVC, and EDG all consider a friend function
18845 // specialization definitions to be de facto explicit specialization
18846 // and diagnose them as such.
18847 } else if (isTemplateId) {
18848 Diag(NameInfo.getBeginLoc(), diag::err_friend_specialization_def);
18849 }
18850 }
18851
18852 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
18853 // default argument expression, that declaration shall be a definition
18854 // and shall be the only declaration of the function or function
18855 // template in the translation unit.
18857 // We can't look at FD->getPreviousDecl() because it may not have been set
18858 // if we're in a dependent context. If the function is known to be a
18859 // redeclaration, we will have narrowed Previous down to the right decl.
18860 if (D.isRedeclaration()) {
18861 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
18862 Diag(Previous.getRepresentativeDecl()->getLocation(),
18863 diag::note_previous_declaration);
18864 } else if (!D.isFunctionDefinition())
18865 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
18866 }
18867
18868 return ND;
18869}
18870
18872 StringLiteral *Message) {
18874
18875 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
18876 if (!Fn) {
18877 Diag(DelLoc, diag::err_deleted_non_function);
18878 return;
18879 }
18880
18881 // Deleted function does not have a body.
18882 Fn->setWillHaveBody(false);
18883
18884 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
18885 // Don't consider the implicit declaration we generate for explicit
18886 // specializations. FIXME: Do not generate these implicit declarations.
18887 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
18888 Prev->getPreviousDecl()) &&
18889 !Prev->isDefined()) {
18890 Diag(DelLoc, diag::err_deleted_decl_not_first);
18891 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
18892 Prev->isImplicit() ? diag::note_previous_implicit_declaration
18893 : diag::note_previous_declaration);
18894 // We can't recover from this; the declaration might have already
18895 // been used.
18896 Fn->setInvalidDecl();
18897 return;
18898 }
18899
18900 // To maintain the invariant that functions are only deleted on their first
18901 // declaration, mark the implicitly-instantiated declaration of the
18902 // explicitly-specialized function as deleted instead of marking the
18903 // instantiated redeclaration.
18904 Fn = Fn->getCanonicalDecl();
18905 }
18906
18907 // dllimport/dllexport cannot be deleted.
18908 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
18909 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
18910 Fn->setInvalidDecl();
18911 }
18912
18913 // C++11 [basic.start.main]p3:
18914 // A program that defines main as deleted [...] is ill-formed.
18915 if (Fn->isMain())
18916 Diag(DelLoc, diag::err_deleted_main);
18917
18918 // C++11 [dcl.fct.def.delete]p4:
18919 // A deleted function is implicitly inline.
18920 Fn->setImplicitlyInline();
18921 Fn->setDeletedAsWritten(true, Message);
18922}
18923
18925 if (!Dcl || Dcl->isInvalidDecl())
18926 return;
18927
18928 auto *FD = dyn_cast<FunctionDecl>(Dcl);
18929 if (!FD) {
18930 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) {
18931 if (FTD->getTemplatedDecl()->getDefaultedFunctionKind().isComparison()) {
18932 Diag(DefaultLoc, diag::err_defaulted_comparison_template);
18933 return;
18934 }
18935 }
18936
18937 Diag(DefaultLoc, diag::err_default_special_members)
18938 << getLangOpts().CPlusPlus20;
18939 return;
18940 }
18941
18942 // Reject if this can't possibly be a defaultable function.
18943 FunctionDecl::DefaultedFunctionKind DefKind = FD->getDefaultedFunctionKind();
18944 if (!DefKind &&
18945 // A dependent function that doesn't locally look defaultable can
18946 // still instantiate to a defaultable function if it's a constructor
18947 // or assignment operator.
18948 (!FD->isDependentContext() ||
18950 FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) {
18951 Diag(DefaultLoc, diag::err_default_special_members)
18952 << getLangOpts().CPlusPlus20;
18953 return;
18954 }
18955
18956 // Issue compatibility warning. We already warned if the operator is
18957 // 'operator<=>' when parsing the '<=>' token.
18958 if (DefKind.isComparison() &&
18960 Diag(DefaultLoc, getLangOpts().CPlusPlus20
18961 ? diag::warn_cxx17_compat_defaulted_comparison
18962 : diag::ext_defaulted_comparison);
18963 }
18964
18965 FD->setDefaulted();
18966 FD->setExplicitlyDefaulted();
18967 FD->setDefaultLoc(DefaultLoc);
18968
18969 // Defer checking functions that are defaulted in a dependent context.
18970 if (FD->isDependentContext())
18971 return;
18972
18973 // Unset that we will have a body for this function. We might not,
18974 // if it turns out to be trivial, and we don't need this marking now
18975 // that we've marked it as defaulted.
18976 FD->setWillHaveBody(false);
18977
18978 if (DefKind.isComparison()) {
18979 // If this comparison's defaulting occurs within the definition of its
18980 // lexical class context, we have to do the checking when complete.
18981 if (auto const *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext()))
18982 if (!RD->isCompleteDefinition())
18983 return;
18984 }
18985
18986 // If this member fn was defaulted on its first declaration, we will have
18987 // already performed the checking in CheckCompletedCXXClass. Such a
18988 // declaration doesn't trigger an implicit definition.
18989 if (isa<CXXMethodDecl>(FD)) {
18990 const FunctionDecl *Primary = FD;
18991 if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
18992 // Ask the template instantiation pattern that actually had the
18993 // '= default' on it.
18994 Primary = Pattern;
18995 if (Primary->getCanonicalDecl()->isDefaulted())
18996 return;
18997 }
18998
18999 // Only allocate DefaultedOrDeletedFunctionInfo if we actually have
19000 // non-default FP features to stash. This avoids memory overhead for
19001 // the vast majority of defaulted functions.
19002 if (!FD->getDefaultedOrDeletedInfo() &&
19003 CurFPFeatureOverrides().requiresTrailingStorage()) {
19004 FD->setDefaultedOrDeletedInfo(
19006 Context, /*Lookups=*/{}, CurFPFeatureOverrides()));
19007 }
19008
19009 if (DefKind.isComparison()) {
19010 if (CheckExplicitlyDefaultedComparison(nullptr, FD, DefKind.asComparison()))
19011 FD->setInvalidDecl();
19012 else
19013 DefineDefaultedComparison(DefaultLoc, FD, DefKind.asComparison());
19014 } else {
19015 auto *MD = cast<CXXMethodDecl>(FD);
19016
19018 DefaultLoc))
19019 MD->setInvalidDecl();
19020 else
19021 DefineDefaultedFunction(*this, MD, DefaultLoc);
19022 }
19023}
19024
19026 for (Stmt *SubStmt : S->children()) {
19027 if (!SubStmt)
19028 continue;
19029 if (isa<ReturnStmt>(SubStmt))
19030 Self.Diag(SubStmt->getBeginLoc(),
19031 diag::err_return_in_constructor_handler);
19032 if (!isa<Expr>(SubStmt))
19033 SearchForReturnInStmt(Self, SubStmt);
19034 }
19035}
19036
19038 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
19039 CXXCatchStmt *Handler = TryBlock->getHandler(I);
19040 SearchForReturnInStmt(*this, Handler);
19041 }
19042}
19043
19045 StringLiteral *DeletedMessage) {
19046 switch (BodyKind) {
19047 case FnBodyKind::Delete:
19048 SetDeclDeleted(D, Loc, DeletedMessage);
19049 break;
19051 SetDeclDefaulted(D, Loc);
19052 break;
19053 case FnBodyKind::Other:
19054 llvm_unreachable(
19055 "Parsed function body should be '= delete;' or '= default;'");
19056 }
19057}
19058
19060 const CXXMethodDecl *Old) {
19061 const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
19062 const auto *OldFT = Old->getType()->castAs<FunctionProtoType>();
19063
19064 if (OldFT->hasExtParameterInfos()) {
19065 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
19066 // A parameter of the overriding method should be annotated with noescape
19067 // if the corresponding parameter of the overridden method is annotated.
19068 if (OldFT->getExtParameterInfo(I).isNoEscape() &&
19069 !NewFT->getExtParameterInfo(I).isNoEscape()) {
19070 Diag(New->getParamDecl(I)->getLocation(),
19071 diag::warn_overriding_method_missing_noescape);
19072 Diag(Old->getParamDecl(I)->getLocation(),
19073 diag::note_overridden_marked_noescape);
19074 }
19075 }
19076
19077 // SME attributes must match when overriding a function declaration.
19078 if (IsInvalidSMECallConversion(Old->getType(), New->getType())) {
19079 Diag(New->getLocation(), diag::err_conflicting_overriding_attributes)
19080 << New << New->getType() << Old->getType();
19081 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
19082 return true;
19083 }
19084
19085 // Virtual overrides must have the same code_seg.
19086 const auto *OldCSA = Old->getAttr<CodeSegAttr>();
19087 const auto *NewCSA = New->getAttr<CodeSegAttr>();
19088 if ((NewCSA || OldCSA) &&
19089 (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
19090 Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
19091 Diag(Old->getLocation(), diag::note_previous_declaration);
19092 return true;
19093 }
19094
19095 // Virtual overrides: check for matching effects.
19096 if (Context.hasAnyFunctionEffects()) {
19097 const auto OldFX = Old->getFunctionEffects();
19098 const auto NewFXOrig = New->getFunctionEffects();
19099
19100 if (OldFX != NewFXOrig) {
19101 FunctionEffectSet NewFX(NewFXOrig);
19102 const auto Diffs = FunctionEffectDiffVector(OldFX, NewFX);
19104 for (const auto &Diff : Diffs) {
19105 switch (Diff.shouldDiagnoseMethodOverride(*Old, OldFX, *New, NewFX)) {
19107 break;
19109 Diag(New->getLocation(), diag::warn_conflicting_func_effect_override)
19110 << Diff.effectName();
19111 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
19112 << Old->getReturnTypeSourceRange();
19113 break;
19115 NewFX.insert(Diff.Old.value(), Errs);
19116 const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
19117 FunctionProtoType::ExtProtoInfo EPI = NewFT->getExtProtoInfo();
19119 QualType ModQT = Context.getFunctionType(NewFT->getReturnType(),
19120 NewFT->getParamTypes(), EPI);
19121 New->setType(ModQT);
19122 if (Errs.empty()) {
19123 // A warning here is somewhat pedantic. Skip this if there was
19124 // already a merge conflict, which is more serious.
19125 Diag(New->getLocation(), diag::warn_mismatched_func_effect_override)
19126 << Diff.effectName();
19127 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
19128 << Old->getReturnTypeSourceRange();
19129 }
19130 break;
19131 }
19132 }
19133 }
19134 if (!Errs.empty())
19135 diagnoseFunctionEffectMergeConflicts(Errs, New->getLocation(),
19136 Old->getLocation());
19137 }
19138 }
19139
19140 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
19141
19142 // If the calling conventions match, everything is fine
19143 if (NewCC == OldCC)
19144 return false;
19145
19146 // If the calling conventions mismatch because the new function is static,
19147 // suppress the calling convention mismatch error; the error about static
19148 // function override (err_static_overrides_virtual from
19149 // Sema::CheckFunctionDeclaration) is more clear.
19150 if (New->getStorageClass() == SC_Static)
19151 return false;
19152
19153 Diag(New->getLocation(),
19154 diag::err_conflicting_overriding_cc_attributes)
19155 << New->getDeclName() << New->getType() << Old->getType();
19156 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
19157 return true;
19158}
19159
19161 const CXXMethodDecl *Old) {
19162 // CWG2553
19163 // A virtual function shall not be an explicit object member function.
19164 if (!New->isExplicitObjectMemberFunction())
19165 return true;
19166 Diag(New->getParamDecl(0)->getBeginLoc(),
19167 diag::err_explicit_object_parameter_nonmember)
19168 << New->getSourceRange() << /*virtual*/ 1 << /*IsLambda*/ false;
19169 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
19170 New->setInvalidDecl();
19171 return false;
19172}
19173
19175 const CXXMethodDecl *Old) {
19176 QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType();
19177 QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType();
19178
19179 if (Context.hasSameType(NewTy, OldTy) ||
19180 NewTy->isDependentType() || OldTy->isDependentType())
19181 return false;
19182
19183 // Check if the return types are covariant
19184 QualType NewClassTy, OldClassTy;
19185
19186 /// Both types must be pointers or references to classes.
19187 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
19188 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
19189 NewClassTy = NewPT->getPointeeType();
19190 OldClassTy = OldPT->getPointeeType();
19191 }
19192 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
19193 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
19194 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
19195 NewClassTy = NewRT->getPointeeType();
19196 OldClassTy = OldRT->getPointeeType();
19197 }
19198 }
19199 }
19200
19201 // The return types aren't either both pointers or references to a class type.
19202 if (NewClassTy.isNull() || !NewClassTy->isStructureOrClassType()) {
19203 Diag(New->getLocation(),
19204 diag::err_different_return_type_for_overriding_virtual_function)
19205 << New->getDeclName() << NewTy << OldTy
19206 << New->getReturnTypeSourceRange();
19207 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
19208 << Old->getReturnTypeSourceRange();
19209
19210 return true;
19211 }
19212
19213 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
19214 // C++14 [class.virtual]p8:
19215 // If the class type in the covariant return type of D::f differs from
19216 // that of B::f, the class type in the return type of D::f shall be
19217 // complete at the point of declaration of D::f or shall be the class
19218 // type D.
19219 if (const auto *RD = NewClassTy->getAsCXXRecordDecl()) {
19220 if (!RD->isBeingDefined() &&
19221 RequireCompleteType(New->getLocation(), NewClassTy,
19222 diag::err_covariant_return_incomplete,
19223 New->getDeclName()))
19224 return true;
19225 }
19226
19227 // Check if the new class derives from the old class.
19228 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
19229 Diag(New->getLocation(), diag::err_covariant_return_not_derived)
19230 << New->getDeclName() << NewTy << OldTy
19231 << New->getReturnTypeSourceRange();
19232 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
19233 << Old->getReturnTypeSourceRange();
19234 return true;
19235 }
19236
19237 // Check if we the conversion from derived to base is valid.
19239 NewClassTy, OldClassTy,
19240 diag::err_covariant_return_inaccessible_base,
19241 diag::err_covariant_return_ambiguous_derived_to_base_conv,
19242 New->getLocation(), New->getReturnTypeSourceRange(),
19243 New->getDeclName(), nullptr)) {
19244 // FIXME: this note won't trigger for delayed access control
19245 // diagnostics, and it's impossible to get an undelayed error
19246 // here from access control during the original parse because
19247 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
19248 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
19249 << Old->getReturnTypeSourceRange();
19250 return true;
19251 }
19252 }
19253
19254 // The qualifiers of the return types must be the same.
19255 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
19256 Diag(New->getLocation(),
19257 diag::err_covariant_return_type_different_qualifications)
19258 << New->getDeclName() << NewTy << OldTy
19259 << New->getReturnTypeSourceRange();
19260 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
19261 << Old->getReturnTypeSourceRange();
19262 return true;
19263 }
19264
19265
19266 // The new class type must have the same or less qualifiers as the old type.
19267 if (!OldClassTy.isAtLeastAsQualifiedAs(NewClassTy, getASTContext())) {
19268 Diag(New->getLocation(),
19269 diag::err_covariant_return_type_class_type_not_same_or_less_qualified)
19270 << New->getDeclName() << NewTy << OldTy
19271 << New->getReturnTypeSourceRange();
19272 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
19273 << Old->getReturnTypeSourceRange();
19274 return true;
19275 }
19276
19277 return false;
19278}
19279
19281 SourceLocation EndLoc = InitRange.getEnd();
19282 if (EndLoc.isValid())
19283 Method->setRangeEnd(EndLoc);
19284
19285 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
19286 Method->setIsPureVirtual();
19287 return false;
19288 }
19289
19290 if (!Method->isInvalidDecl())
19291 Diag(Method->getLocation(), diag::err_non_virtual_pure)
19292 << Method->getDeclName() << InitRange;
19293 return true;
19294}
19295
19297 if (D->getFriendObjectKind())
19298 Diag(D->getLocation(), diag::err_pure_friend);
19299 else if (auto *M = dyn_cast<CXXMethodDecl>(D))
19300 CheckPureMethod(M, ZeroLoc);
19301 else
19302 Diag(D->getLocation(), diag::err_illegal_initializer);
19303}
19304
19305/// Invoked when we are about to parse an initializer for the declaration
19306/// 'Dcl'.
19307///
19308/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
19309/// static data member of class X, names should be looked up in the scope of
19310/// class X. If the declaration had a scope specifier, a scope will have
19311/// been created and passed in for this purpose. Otherwise, S will be null.
19313 assert(D && !D->isInvalidDecl());
19314
19315 // We will always have a nested name specifier here, but this declaration
19316 // might not be out of line if the specifier names the current namespace:
19317 // extern int n;
19318 // int ::n = 0;
19319 if (S && D->isOutOfLine())
19321
19325}
19326
19328 assert(D);
19329
19330 if (S && D->isOutOfLine())
19332
19334}
19335
19337 // C++ 6.4p2:
19338 // The declarator shall not specify a function or an array.
19339 // The type-specifier-seq shall not contain typedef and shall not declare a
19340 // new class or enumeration.
19342 "Parser allowed 'typedef' as storage class of condition decl.");
19343
19344 Decl *Dcl = ActOnDeclarator(S, D);
19345 if (!Dcl)
19346 return true;
19347
19348 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
19349 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
19350 << D.getSourceRange();
19351 return true;
19352 }
19353
19354 if (auto *VD = dyn_cast<VarDecl>(Dcl))
19355 VD->setCXXCondDecl();
19356
19357 return Dcl;
19358}
19359
19361 if (!ExternalSource)
19362 return;
19363
19365 ExternalSource->ReadUsedVTables(VTables);
19367 for (const ExternalVTableUse &VTable : VTables) {
19368 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos =
19369 VTablesUsed.find(VTable.Record);
19370 // Even if a definition wasn't required before, it may be required now.
19371 if (Pos != VTablesUsed.end()) {
19372 if (!Pos->second && VTable.DefinitionRequired)
19373 Pos->second = true;
19374 continue;
19375 }
19376
19377 VTablesUsed[VTable.Record] = VTable.DefinitionRequired;
19378 NewUses.push_back(VTableUse(VTable.Record, VTable.Location));
19379 }
19380
19381 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
19382}
19383
19385 bool DefinitionRequired) {
19386 // Ignore any vtable uses in unevaluated operands or for classes that do
19387 // not have a vtable.
19388 if (!Class->isDynamicClass() || Class->isDependentContext() ||
19389 CurContext->isDependentContext() || isUnevaluatedContext())
19390 return;
19391 // Do not mark as used if compiling for the device outside of the target
19392 // region.
19393 if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice &&
19394 !OpenMP().isInOpenMPDeclareTargetContext() &&
19395 !OpenMP().isInOpenMPTargetExecutionDirective()) {
19396 if (!DefinitionRequired)
19398 return;
19399 }
19400
19401 // Try to insert this class into the map.
19403 Class = Class->getCanonicalDecl();
19404 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
19405 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
19406 if (!Pos.second) {
19407 // If we already had an entry, check to see if we are promoting this vtable
19408 // to require a definition. If so, we need to reappend to the VTableUses
19409 // list, since we may have already processed the first entry.
19410 if (DefinitionRequired && !Pos.first->second) {
19411 Pos.first->second = true;
19412 } else {
19413 // Otherwise, we can early exit.
19414 return;
19415 }
19416 } else {
19417 // The Microsoft ABI requires that we perform the destructor body
19418 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
19419 // the deleting destructor is emitted with the vtable, not with the
19420 // destructor definition as in the Itanium ABI.
19421 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
19422 CXXDestructorDecl *DD = Class->getDestructor();
19423 if (DD && DD->isVirtual() && !DD->isDeleted()) {
19424 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
19425 // If this is an out-of-line declaration, marking it referenced will
19426 // not do anything. Manually call CheckDestructor to look up operator
19427 // delete().
19428 ContextRAII SavedContext(*this, DD);
19429 CheckDestructor(DD);
19430 if (!DD->getOperatorDelete())
19431 DD->setInvalidDecl();
19432 } else {
19433 MarkFunctionReferenced(Loc, Class->getDestructor());
19434 }
19435 }
19436 }
19437 }
19438
19439 // Local classes need to have their virtual members marked
19440 // immediately. For all other classes, we mark their virtual members
19441 // at the end of the translation unit.
19442 if (Class->isLocalClass())
19443 MarkVirtualMembersReferenced(Loc, Class->getDefinition());
19444 else
19445 VTableUses.push_back(std::make_pair(Class, Loc));
19446}
19447
19450 if (VTableUses.empty())
19451 return false;
19452
19453 // Note: The VTableUses vector could grow as a result of marking
19454 // the members of a class as "used", so we check the size each
19455 // time through the loop and prefer indices (which are stable) to
19456 // iterators (which are not).
19457 bool DefinedAnything = false;
19458 for (unsigned I = 0; I != VTableUses.size(); ++I) {
19459 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
19460 if (!Class)
19461 continue;
19463 Class->getTemplateSpecializationKind();
19464
19465 SourceLocation Loc = VTableUses[I].second;
19466
19467 bool DefineVTable = true;
19468
19469 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
19470 // V-tables for non-template classes with an owning module are always
19471 // uniquely emitted in that module.
19472 if (Class->isInCurrentModuleUnit()) {
19473 DefineVTable = true;
19474 } else if (KeyFunction && !KeyFunction->hasBody()) {
19475 // If this class has a key function, but that key function is
19476 // defined in another translation unit, we don't need to emit the
19477 // vtable even though we're using it.
19478 // The key function is in another translation unit.
19479 DefineVTable = false;
19481 KeyFunction->getTemplateSpecializationKind();
19484 "Instantiations don't have key functions");
19485 (void)TSK;
19486 } else if (!KeyFunction) {
19487 // If we have a class with no key function that is the subject
19488 // of an explicit instantiation declaration, suppress the
19489 // vtable; it will live with the explicit instantiation
19490 // definition.
19491 bool IsExplicitInstantiationDeclaration =
19493 for (auto *R : Class->redecls()) {
19495 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
19497 IsExplicitInstantiationDeclaration = true;
19498 else if (TSK == TSK_ExplicitInstantiationDefinition) {
19499 IsExplicitInstantiationDeclaration = false;
19500 break;
19501 }
19502 }
19503
19504 if (IsExplicitInstantiationDeclaration) {
19505 const bool HasExcludeFromExplicitInstantiation =
19506 llvm::any_of(Class->methods(), [](CXXMethodDecl *method) {
19507 // If the class has a member function declared with
19508 // `__attribute__((exclude_from_explicit_instantiation))`, the
19509 // explicit instantiation declaration should not suppress emitting
19510 // the vtable, since the corresponding explicit instantiation
19511 // definition might not emit the vtable if a triggering method is
19512 // excluded.
19513 return method->hasAttr<ExcludeFromExplicitInstantiationAttr>();
19514 });
19515 if (!HasExcludeFromExplicitInstantiation)
19516 DefineVTable = false;
19517 }
19518 }
19519
19520 // The exception specifications for all virtual members may be needed even
19521 // if we are not providing an authoritative form of the vtable in this TU.
19522 // We may choose to emit it available_externally anyway.
19523 if (!DefineVTable) {
19525 continue;
19526 }
19527
19528 // Mark all of the virtual members of this class as referenced, so
19529 // that we can build a vtable. Then, tell the AST consumer that a
19530 // vtable for this class is required.
19531 DefinedAnything = true;
19533 CXXRecordDecl *Canonical = Class->getCanonicalDecl();
19534 // The vtable is assumed to be emitted in an external source only for
19535 // classes attached to a named module, which is guaranteed to have an object
19536 // file. This isn't true for -fmodules-debuginfo, which still has
19537 // shouldEmitInExternalSource as true so that debug info gets supressed.
19538 if (VTablesUsed[Canonical] &&
19539 !(Class->isInNamedModule() && Class->shouldEmitInExternalSource()))
19540 Consumer.HandleVTable(Class);
19541
19542 // Warn if we're emitting a weak vtable. The vtable will be weak if there is
19543 // no key function or the key function is inlined. Don't warn in C++ ABIs
19544 // that lack key functions, since the user won't be able to make one.
19545 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
19546 Class->isExternallyVisible() &&
19547 !(Class->getOwningModule() &&
19548 Class->getOwningModule()->isInterfaceOrPartition()) &&
19549 ClassTSK != TSK_ImplicitInstantiation &&
19552 const FunctionDecl *KeyFunctionDef = nullptr;
19553 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
19554 KeyFunctionDef->isInlined()))
19555 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
19556 }
19557 }
19558 VTableUses.clear();
19559
19560 return DefinedAnything;
19561}
19562
19564 const CXXRecordDecl *RD) {
19565 for (const auto *I : RD->methods())
19566 if (I->isVirtual() && !I->isPureVirtual())
19567 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
19568}
19569
19571 const CXXRecordDecl *RD,
19572 bool ConstexprOnly) {
19573 // Mark all functions which will appear in RD's vtable as used.
19574 CXXFinalOverriderMap FinalOverriders;
19575 RD->getFinalOverriders(FinalOverriders);
19576 for (const auto &FinalOverrider : FinalOverriders) {
19577 for (const auto &OverridingMethod : FinalOverrider.second) {
19578 assert(OverridingMethod.second.size() > 0 && "no final overrider");
19579 CXXMethodDecl *Overrider = OverridingMethod.second.front().Method;
19580
19581 // C++ [basic.def.odr]p2:
19582 // [...] A virtual member function is used if it is not pure. [...]
19583 if (!Overrider->isPureVirtual() &&
19584 (!ConstexprOnly || Overrider->isConstexpr()))
19585 MarkFunctionReferenced(Loc, Overrider);
19586 }
19587 }
19588
19589 // Only classes that have virtual bases need a VTT.
19590 if (RD->getNumVBases() == 0)
19591 return;
19592
19593 for (const auto &I : RD->bases()) {
19594 const auto *Base = I.getType()->castAsCXXRecordDecl();
19595 if (Base->getNumVBases() == 0)
19596 continue;
19598 }
19599}
19600
19601static
19606 Sema &S) {
19607 if (Ctor->isInvalidDecl())
19608 return;
19609
19611
19612 // Target may not be determinable yet, for instance if this is a dependent
19613 // call in an uninstantiated template.
19614 if (Target) {
19615 const FunctionDecl *FNTarget = nullptr;
19616 (void)Target->hasBody(FNTarget);
19617 Target = const_cast<CXXConstructorDecl*>(
19618 cast_or_null<CXXConstructorDecl>(FNTarget));
19619 }
19620
19621 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
19622 // Avoid dereferencing a null pointer here.
19623 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
19624
19625 if (!Current.insert(Canonical).second)
19626 return;
19627
19628 // We know that beyond here, we aren't chaining into a cycle.
19629 if (!Target || !Target->isDelegatingConstructor() ||
19630 Target->isInvalidDecl() || Valid.count(TCanonical)) {
19631 Valid.insert_range(Current);
19632 Current.clear();
19633 // We've hit a cycle.
19634 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
19635 Current.count(TCanonical)) {
19636 // If we haven't diagnosed this cycle yet, do so now.
19637 if (!Invalid.count(TCanonical)) {
19638 S.Diag((*Ctor->init_begin())->getSourceLocation(),
19639 diag::warn_delegating_ctor_cycle)
19640 << Ctor;
19641
19642 // Don't add a note for a function delegating directly to itself.
19643 if (TCanonical != Canonical)
19644 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
19645
19647 while (C->getCanonicalDecl() != Canonical) {
19648 const FunctionDecl *FNTarget = nullptr;
19649 (void)C->getTargetConstructor()->hasBody(FNTarget);
19650 assert(FNTarget && "Ctor cycle through bodiless function");
19651
19652 C = const_cast<CXXConstructorDecl*>(
19653 cast<CXXConstructorDecl>(FNTarget));
19654 S.Diag(C->getLocation(), diag::note_which_delegates_to);
19655 }
19656 }
19657
19658 Invalid.insert_range(Current);
19659 Current.clear();
19660 } else {
19662 }
19663}
19664
19665
19668
19669 for (DelegatingCtorDeclsType::iterator
19670 I = DelegatingCtorDecls.begin(ExternalSource.get()),
19671 E = DelegatingCtorDecls.end();
19672 I != E; ++I)
19673 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
19674
19675 for (CXXConstructorDecl *CI : Invalid)
19676 CI->setInvalidDecl();
19677}
19678
19679namespace {
19680 /// AST visitor that finds references to the 'this' expression.
19681class FindCXXThisExpr : public DynamicRecursiveASTVisitor {
19682 Sema &S;
19683
19684public:
19685 explicit FindCXXThisExpr(Sema &S) : S(S) {}
19686
19687 bool VisitCXXThisExpr(CXXThisExpr *E) override {
19688 S.Diag(E->getLocation(), diag::err_this_static_member_func)
19689 << E->isImplicit();
19690 return false;
19691 }
19692};
19693}
19694
19696 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
19697 if (!TSInfo)
19698 return false;
19699
19700 TypeLoc TL = TSInfo->getTypeLoc();
19702 if (!ProtoTL)
19703 return false;
19704
19705 // C++11 [expr.prim.general]p3:
19706 // [The expression this] shall not appear before the optional
19707 // cv-qualifier-seq and it shall not appear within the declaration of a
19708 // static member function (although its type and value category are defined
19709 // within a static member function as they are within a non-static member
19710 // function). [ Note: this is because declaration matching does not occur
19711 // until the complete declarator is known. - end note ]
19712 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
19713 FindCXXThisExpr Finder(*this);
19714
19715 // If the return type came after the cv-qualifier-seq, check it now.
19716 if (Proto->hasTrailingReturn() &&
19717 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
19718 return true;
19719
19720 // Check the exception specification.
19722 return true;
19723
19724 // Check the trailing requires clause
19725 if (const AssociatedConstraint &TRC = Method->getTrailingRequiresClause())
19726 if (!Finder.TraverseStmt(const_cast<Expr *>(TRC.ConstraintExpr)))
19727 return true;
19728
19730}
19731
19733 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
19734 if (!TSInfo)
19735 return false;
19736
19737 TypeLoc TL = TSInfo->getTypeLoc();
19739 if (!ProtoTL)
19740 return false;
19741
19742 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
19743 FindCXXThisExpr Finder(*this);
19744
19745 switch (Proto->getExceptionSpecType()) {
19746 case EST_Unparsed:
19747 case EST_Uninstantiated:
19748 case EST_Unevaluated:
19749 case EST_BasicNoexcept:
19750 case EST_NoThrow:
19751 case EST_DynamicNone:
19752 case EST_MSAny:
19753 case EST_None:
19754 break;
19755
19757 case EST_NoexceptFalse:
19758 case EST_NoexceptTrue:
19759 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
19760 return true;
19761 [[fallthrough]];
19762
19763 case EST_Dynamic:
19764 for (const auto &E : Proto->exceptions()) {
19765 if (!Finder.TraverseType(E))
19766 return true;
19767 }
19768 break;
19769 }
19770
19771 return false;
19772}
19773
19775 FindCXXThisExpr Finder(*this);
19776
19777 // Check attributes.
19778 for (const auto *A : Method->attrs()) {
19779 // FIXME: This should be emitted by tblgen.
19780 Expr *Arg = nullptr;
19781 ArrayRef<Expr *> Args;
19782 if (const auto *G = dyn_cast<GuardedByAttr>(A))
19783 Args = llvm::ArrayRef(G->args_begin(), G->args_size());
19784 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
19785 Args = llvm::ArrayRef(G->args_begin(), G->args_size());
19786 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
19787 Args = llvm::ArrayRef(AA->args_begin(), AA->args_size());
19788 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
19789 Args = llvm::ArrayRef(AB->args_begin(), AB->args_size());
19790 else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
19791 Arg = LR->getArg();
19792 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
19793 Args = llvm::ArrayRef(LE->args_begin(), LE->args_size());
19794 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
19795 Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());
19796 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
19797 Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());
19798 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) {
19799 Arg = AC->getSuccessValue();
19800 Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());
19801 } else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
19802 Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());
19803
19804 if (Arg && !Finder.TraverseStmt(Arg))
19805 return true;
19806
19807 for (Expr *A : Args) {
19808 if (!Finder.TraverseStmt(A))
19809 return true;
19810 }
19811 }
19812
19813 return false;
19814}
19815
19817 bool IsTopLevel, ExceptionSpecificationType EST,
19818 ArrayRef<ParsedType> DynamicExceptions,
19819 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
19820 SmallVectorImpl<QualType> &Exceptions,
19822 Exceptions.clear();
19823 ESI.Type = EST;
19824 if (EST == EST_Dynamic) {
19825 Exceptions.reserve(DynamicExceptions.size());
19826 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
19827 // FIXME: Preserve type source info.
19828 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
19829
19830 if (IsTopLevel) {
19832 collectUnexpandedParameterPacks(ET, Unexpanded);
19833 if (!Unexpanded.empty()) {
19835 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
19836 Unexpanded);
19837 continue;
19838 }
19839 }
19840
19841 // Check that the type is valid for an exception spec, and
19842 // drop it if not.
19843 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
19844 Exceptions.push_back(ET);
19845 }
19846 ESI.Exceptions = Exceptions;
19847 return;
19848 }
19849
19850 if (isComputedNoexcept(EST)) {
19851 assert((NoexceptExpr->isTypeDependent() ||
19852 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
19853 Context.BoolTy) &&
19854 "Parser should have made sure that the expression is boolean");
19855 if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
19856 ESI.Type = EST_BasicNoexcept;
19857 return;
19858 }
19859
19860 ESI.NoexceptExpr = NoexceptExpr;
19861 return;
19862 }
19863}
19864
19866 Decl *D, ExceptionSpecificationType EST, SourceRange SpecificationRange,
19867 ArrayRef<ParsedType> DynamicExceptions,
19868 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr) {
19869 if (!D)
19870 return;
19871
19872 // Dig out the function we're referring to.
19873 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
19874 D = FTD->getTemplatedDecl();
19875
19876 FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
19877 if (!FD)
19878 return;
19879
19880 // Check the exception specification.
19883 checkExceptionSpecification(/*IsTopLevel=*/true, EST, DynamicExceptions,
19884 DynamicExceptionRanges, NoexceptExpr, Exceptions,
19885 ESI);
19886
19887 // Update the exception specification on the function type.
19888 Context.adjustExceptionSpec(FD, ESI, /*AsWritten=*/true);
19889
19890 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
19891 if (MD->isStatic())
19893
19894 if (MD->isVirtual()) {
19895 // Check overrides, which we previously had to delay.
19896 for (const CXXMethodDecl *O : MD->overridden_methods())
19898 }
19899 }
19900}
19901
19902/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
19903///
19905 SourceLocation DeclStart, Declarator &D,
19906 Expr *BitWidth,
19907 InClassInitStyle InitStyle,
19908 AccessSpecifier AS,
19909 const ParsedAttr &MSPropertyAttr) {
19910 const IdentifierInfo *II = D.getIdentifier();
19911 if (!II) {
19912 Diag(DeclStart, diag::err_anonymous_property);
19913 return nullptr;
19914 }
19916
19918 QualType T = TInfo->getType();
19919 if (getLangOpts().CPlusPlus) {
19921
19924 D.setInvalidType();
19925 T = Context.IntTy;
19926 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
19927 }
19928 }
19929
19931
19933 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
19934 << getLangOpts().CPlusPlus17;
19937 diag::err_invalid_thread)
19939
19940 // Check to see if this name was declared as a member previously
19941 NamedDecl *PrevDecl = nullptr;
19942 LookupResult Previous(*this, II, Loc, LookupMemberName,
19944 LookupName(Previous, S);
19945 switch (Previous.getResultKind()) {
19948 PrevDecl = Previous.getAsSingle<NamedDecl>();
19949 break;
19950
19952 PrevDecl = Previous.getRepresentativeDecl();
19953 break;
19954
19958 break;
19959 }
19960
19961 if (PrevDecl && PrevDecl->isTemplateParameter()) {
19962 // Maybe we will complain about the shadowed template parameter.
19964 // Just pretend that we didn't see the previous declaration.
19965 PrevDecl = nullptr;
19966 }
19967
19968 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
19969 PrevDecl = nullptr;
19970
19971 SourceLocation TSSL = D.getBeginLoc();
19972 MSPropertyDecl *NewPD =
19973 MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
19974 MSPropertyAttr.getPropertyDataGetter(),
19975 MSPropertyAttr.getPropertyDataSetter());
19976 ProcessDeclAttributes(TUScope, NewPD, D);
19977 NewPD->setAccess(AS);
19978
19979 if (NewPD->isInvalidDecl())
19980 Record->setInvalidDecl();
19981
19983 NewPD->setModulePrivate();
19984
19985 if (NewPD->isInvalidDecl() && PrevDecl) {
19986 // Don't introduce NewFD into scope; there's already something
19987 // with the same name in the same scope.
19988 } else if (II) {
19989 PushOnScopeChains(NewPD, S);
19990 } else
19991 Record->addDecl(NewPD);
19992
19993 return NewPD;
19994}
19995
19997 Declarator &Declarator, unsigned TemplateParameterDepth) {
19998 auto &Info = InventedParameterInfos.emplace_back();
19999 TemplateParameterList *ExplicitParams = nullptr;
20000 ArrayRef<TemplateParameterList *> ExplicitLists =
20002 if (!ExplicitLists.empty()) {
20003 bool IsMemberSpecialization, IsInvalid;
20006 Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr,
20007 ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid,
20008 /*SuppressDiagnostic=*/true);
20009 }
20010 // C++23 [dcl.fct]p23:
20011 // An abbreviated function template can have a template-head. The invented
20012 // template-parameters are appended to the template-parameter-list after
20013 // the explicitly declared template-parameters.
20014 //
20015 // A template-head must have one or more template-parameters (read:
20016 // 'template<>' is *not* a template-head). Only append the invented
20017 // template parameters if we matched the nested-name-specifier to a non-empty
20018 // TemplateParameterList.
20019 if (ExplicitParams && !ExplicitParams->empty()) {
20020 Info.AutoTemplateParameterDepth = ExplicitParams->getDepth();
20021 llvm::append_range(Info.TemplateParams, *ExplicitParams);
20022 Info.NumExplicitTemplateParams = ExplicitParams->size();
20023 } else {
20024 Info.AutoTemplateParameterDepth = TemplateParameterDepth;
20025 Info.NumExplicitTemplateParams = 0;
20026 }
20027}
20028
20030 auto &FSI = InventedParameterInfos.back();
20031 if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) {
20032 if (FSI.NumExplicitTemplateParams != 0) {
20033 TemplateParameterList *ExplicitParams =
20037 Context, ExplicitParams->getTemplateLoc(),
20038 ExplicitParams->getLAngleLoc(), FSI.TemplateParams,
20039 ExplicitParams->getRAngleLoc(),
20040 ExplicitParams->getRequiresClause()));
20041 } else {
20044 FSI.TemplateParams, Declarator.getEndLoc(),
20045 /*RequiresClause=*/nullptr));
20046 }
20047 }
20048 InventedParameterInfos.pop_back();
20049}
20050
20052 CXXConstructorDecl *Ctor, bool IsCopy) {
20053 assert(Context.getTargetInfo().getCXXABI().isMicrosoft());
20054
20055 if (!Ctor->getCtorClosureDefaultArgs().empty()) {
20056 // If we build args for default constructor closures, those will have
20057 // been generated *before* building args for any copy constructor closures.
20058 assert(IsCopy || Ctor->getCtorClosureDefaultArgs()[0] != nullptr);
20059 return false;
20060 }
20061
20062 unsigned NumParams = Ctor->getNumParams();
20063 if (NumParams == 0)
20064 return false;
20065
20066 CXXDefaultArgExpr **Args =
20067 new (getASTContext()) CXXDefaultArgExpr *[NumParams];
20068
20069 if (IsCopy)
20070 Args[0] = nullptr; // Copy ctor closure will provide the first argument.
20071
20072 for (unsigned I = IsCopy ? 1 : 0; I != NumParams; ++I) {
20073 ExprResult R = BuildCXXDefaultArgExpr(Loc, Ctor, Ctor->getParamDecl(I));
20075 if (R.isInvalid())
20076 return true;
20077 Args[I] = cast<CXXDefaultArgExpr>(R.get());
20078 }
20079
20080 Ctor->setCtorClosureDefaultArgs(ArrayRef(Args, NumParams));
20081 return false;
20082}
Defines the clang::ASTContext interface.
#define V(N, I)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
This file defines the classes used to store parsed information about declaration-specifiers and decla...
Defines the C++ template declaration subclasses.
Defines the clang::Expr interface and subclasses for C++ expressions.
static bool CheckLiteralType(EvalInfo &Info, const Expr *E, const LValue *This=nullptr)
Check that this core constant expression is of literal type, and if not, produce an appropriate diagn...
TokenType getType() const
Returns the token's type, e.g.
FormatToken * Previous
The previous token in the unwrapped line.
FormatToken * Next
The next token in the unwrapped line.
Result
Implement __builtin_bit_cast and related operations.
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Target Target
Definition MachO.h:51
llvm::MachO::Record Record
Definition MachO.h:31
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
Defines the clang::Preprocessor interface.
@ ForExternalRedeclaration
The lookup results will be used for redeclaration of a name with external linkage; non-visible lookup...
@ ForVisibleRedeclaration
The lookup results will be used for redeclaration of a name, if an entity by that name already exists...
llvm::SmallVector< std::pair< const MemRegion *, SVal >, 4 > Bindings
static void ProcessAPINotes(Sema &S, Decl *D, const api_notes::CommonEntityInfo &Info, VersionedInfoMetadata Metadata)
static AccessResult DeduceTemplateArguments(Sema &S, FriendTemplateDecl *FTD, DeclContext *DC, const TemplateSpecializationType *TST, ArrayRef< TemplateParameterList * > TPLs, TemplateSpecCandidateSet *FailedTSC, MultiLevelTemplateArgumentList &DeducedArgs)
This file declares semantic analysis for CUDA constructs.
static void DiagnoseUnsatisfiedConstraint(Sema &S, ArrayRef< UnsatisfiedConstraintRecord > Records, SourceLocation Loc, bool First=true, concepts::NestedRequirement *Req=nullptr)
static LookupResult lookupMember(Sema &S, const char *Name, CXXRecordDecl *RD, SourceLocation Loc, bool &Res)
static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, CXXSpecialMemberKind CSM, unsigned Quals, bool ConstRHS, TrivialABIHandling TAH, CXXMethodDecl **Selected)
Perform lookup for a special member of the specified kind, and determine whether it is trivial.
static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, SourceLocation CurrentLocation)
Check if we're implicitly defining a move assignment operator for a class with virtual bases.
static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID)
static void DelegatingCycleHelper(CXXConstructorDecl *Ctor, llvm::SmallPtrSet< CXXConstructorDecl *, 4 > &Valid, llvm::SmallPtrSet< CXXConstructorDecl *, 4 > &Invalid, llvm::SmallPtrSet< CXXConstructorDecl *, 4 > &Current, Sema &S)
static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *Body, Sema::CheckConstexprKind Kind)
Check the body for the given constexpr function declaration only contains the permitted types of stat...
llvm::SmallPtrSet< QualType, 4 > IndirectBaseSet
Use small set to collect indirect bases.
static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S, CXXRecordDecl *Class)
static bool checkVectorDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, ValueDecl *Src, QualType DecompType, const VectorType *VT)
static void SearchForReturnInStmt(Sema &Self, Stmt *S)
static bool checkSimpleDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, ValueDecl *Src, QualType DecompType, const llvm::APSInt &NumElemsAPS, QualType ElemType, llvm::function_ref< ExprResult(SourceLocation, Expr *, unsigned)> GetInit)
static CXXDestructorDecl * LookupDestructorIfRelevant(Sema &S, CXXRecordDecl *Class)
static Sema::ImplicitExceptionSpecification ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD, DefaultedComparisonKind DCK)
static void extendRight(SourceRange &R, SourceRange After)
static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, SourceLocation Loc, IdentifierInfo *II, bool *IsInline, NamespaceDecl *PrevNS)
Diagnose a mismatch in 'inline' qualifiers when a namespace is reopened.
static bool IsPotentiallyTypeAwareOperatorNewOrDelete(Sema &SemaRef, const FunctionDecl *FD, bool *WasMalformed)
static bool RefersToRValueRef(Expr *MemRef)
static bool CheckConstexprCtorInitializer(Sema &SemaRef, const FunctionDecl *Dcl, FieldDecl *Field, llvm::SmallPtrSet< Decl *, 16 > &Inits, bool &Diagnosed, Sema::CheckConstexprKind Kind)
Check that the given field is initialized within a constexpr constructor.
static CanQualType RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy)
static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base)
Determine whether a direct base class is a virtual base class.
#define CheckPolymorphic(Type)
static void BuildBasePathArray(const CXXBasePath &Path, CXXCastPath &BasePathArray)
static void WriteCharValueForDiagnostic(uint32_t Value, const BuiltinType *BTy, unsigned TyWidth, SmallVectorImpl< char > &Str)
Convert character's value, interpreted as a code unit, to a string.
static void CheckAbstractClassUsage(AbstractUsageInfo &Info, FunctionDecl *FD)
Check for invalid uses of an abstract type in a function declaration.
static unsigned getRecordDiagFromTagKind(TagTypeKind Tag)
Get diagnostic select index for tag kind for record diagnostic message.
static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T, unsigned &OutSize)
static Expr * CastForMoving(Sema &SemaRef, Expr *E)
static bool IsPotentiallyDestroyingOperatorDelete(Sema &SemaRef, const FunctionDecl *FD)
static void extendLeft(SourceRange &R, SourceRange Before)
static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, unsigned Quals, bool ConstRHS, CXXConstructorDecl *InheritedCtor=nullptr, Sema::InheritedConstructorInfo *Inherited=nullptr)
Is the special member function which would be selected to perform the specified operation on the spec...
static void diagnoseInvalidDeclaratorChunks(Sema &S, Declarator &D, unsigned Kind)
static bool canPassInRegisters(Sema &S, CXXRecordDecl *D, TargetInfo::CallingConvKind CCK)
Determine whether a type is permitted to be passed or returned in registers, per C++ [class....
static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S, UnresolvedSetImpl &Operators, OverloadedOperatorKind Op)
Perform the unqualified lookups that might be needed to form a defaulted comparison function for the ...
static void WriteCharTypePrefix(BuiltinType::Kind BTK, llvm::raw_ostream &OS)
static bool EvaluateAsStringImpl(Sema &SemaRef, Expr *Message, ResultType &Result, ASTContext &Ctx, Sema::StringEvaluationContext EvalContext, bool ErrorOnInvalidMessage)
static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp)
Diagnose an implicit copy operation for a class which is odr-used, but which is deprecated because th...
static void AddMostOverridenMethods(const CXXMethodDecl *MD, llvm::SmallPtrSetImpl< const CXXMethodDecl * > &Methods)
Add the most overridden methods from MD to Methods.
static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc, const CXXRecordDecl *RD, CXXCastPath &BasePath)
Find the base class to decompose in a built-in decomposition of a class type.
static const void * GetKeyForBase(ASTContext &Context, QualType BaseType)
static QualType BuildStdClassTemplate(Sema &S, ClassTemplateDecl *CTD, QualType TypeParam, SourceLocation Loc)
AllocationOperatorKind
static NamespaceDecl * getNamespaceDecl(NamespaceBaseDecl *D)
getNamespaceDecl - Returns the namespace a decl represents.
static bool isDestroyingDeleteT(QualType Type)
static StmtResult buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, const ExprBuilder &To, const ExprBuilder &From, bool CopyingBaseSubobject, bool Copying, unsigned Depth=0)
Builds a statement that copies/moves the given entity from From to To.
static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S, CXXRecordDecl *Class)
static void AddInitializerToDiag(const Sema::SemaDiagnosticBuilder &Diag, const CXXCtorInitializer *Previous, const CXXCtorInitializer *Current)
static bool BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, ImplicitInitializerKind ImplicitInitKind, CXXBaseSpecifier *BaseSpec, bool IsInheritedVirtualBase, CXXCtorInitializer *&CXXBaseInit)
static bool IsUnusedPrivateField(const FieldDecl *FD)
static void NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set, const QualType &Type)
Recursively add the bases of Type. Don't add Type itself.
static bool CheckConstexprMissingReturn(Sema &SemaRef, const FunctionDecl *Dcl)
static bool CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, SmallVectorImpl< SourceLocation > &ReturnStmts, SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc, SourceLocation &Cxx2bLoc, Sema::CheckConstexprKind Kind)
Check the provided statement is allowed in a constexpr function definition.
static bool functionDeclHasDefaultArgument(const FunctionDecl *FD)
static bool CheckConstexprParameterTypes(Sema &SemaRef, const FunctionDecl *FD, Sema::CheckConstexprKind Kind)
Check whether a function's parameter types are all literal types.
static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext)
Determine whether a using statement is in a context where it will be apply in all contexts.
static const TemplateSpecializationType * GetClassTemplateSpecializationType(ASTContext &Context, QualType T)
static bool checkTupleLikeDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, VarDecl *Src, QualType DecompType, unsigned NumElems)
static 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 QualType IgnorePackIndexing(QualType T)
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 void DiagnoseDependentFriendNotMember(Sema &S, SourceLocation Loc, NestedNameSpecifier NNS)
static bool CheckConstexprDestructorSubobjects(Sema &SemaRef, const CXXDestructorDecl *DD, Sema::CheckConstexprKind Kind)
Determine whether a destructor cannot be constexpr due to.
static bool isProvablyNotDerivedFrom(Sema &SemaRef, CXXRecordDecl *Record, const BaseSet &Bases)
Determines if the given class is provably not derived from all of the prospective base classes.
This file declares semantic analysis for Objective-C.
This file declares semantic analysis for OpenMP constructs and clauses.
static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, QualType T, APValue &Value, CCEKind CCE, bool RequireInt, NamedDecl *Dest)
CheckConvertedConstantExpression - Check that the expression From is a converted constant expression ...
static void MarkUsedTemplateParameters(ASTContext &Ctx, const TemplateArgument &TemplateArg, bool OnlyDeduced, unsigned Depth, llvm::SmallBitVector &Used)
Mark the template parameters that are used by this template argument.
static void collectUnexpandedParameterPacks(Sema &S, TemplateParameterList *Params, SmallVectorImpl< UnexpandedParameterPack > &Unexpanded)
static bool DiagnoseUnexpandedParameterPacks(Sema &S, TemplateTemplateParmDecl *TTP)
Check for unexpanded parameter packs within the template parameters of a template template parameter,...
static bool isInvalid(LocType Loc, bool *Invalid)
Defines various enumerations that describe declaration and type specifiers.
static QualType getPointeeType(const MemRegion *R)
Defines the clang::TypeLoc interface and its subclasses.
Allows QualTypes to be sorted and hence used in maps and sets.
__DEVICE__ void * memcpy(void *__a, const void *__b, size_t __c)
std::pair< CXXConstructorDecl *, bool > findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const
Find the constructor to use for inherited construction of a base class, and whether that base class c...
InheritedConstructorInfo(Sema &S, SourceLocation UseLoc, ConstructorUsingShadowDecl *Shadow)
a trap message and trap category.
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h: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:827
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:823
const LangOptions & getLangOpts() const
Definition ASTContext.h:980
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:876
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:942
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:3848
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:3521
unsigned shadow_size() const
Return the number of shadowed declarations associated with this using declaration.
Definition DeclCXX.h:3599
void addShadowDecl(UsingShadowDecl *S)
Definition DeclCXX.cpp:3516
shadow_iterator shadow_begin() const
Definition DeclCXX.h:3591
void removeShadowDecl(UsingShadowDecl *S)
Definition DeclCXX.cpp:3525
Expr * getLHS() const
Definition Expr.h:4099
Expr * getRHS() const
Definition Expr.h:4101
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:5108
static bool isCompoundAssignmentOp(Opcode Opc)
Definition Expr.h:4190
Opcode getOpcode() const
Definition Expr.h:4094
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:4210
void setDecomposedDecl(DecompositionDecl *Decomposed)
Set the decomposed variable for this BindingDecl.
Definition DeclCXX.h:4254
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:4248
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition Expr.h:6689
Wrapper for source info for block pointers.
Definition TypeLoc.h:1557
This class is used for builtin types like 'int'.
Definition TypeBase.h:3241
Kind getKind() const
Definition TypeBase.h:3292
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:2637
CXXConstructorDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:2877
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:2731
CXXConstructorDecl * getTargetConstructor() const
When this constructor delegates to another, retrieve the target.
Definition DeclCXX.cpp:3040
bool isCopyConstructor(unsigned &TypeQuals) const
Whether this constructor is a copy constructor (C++ [class.copy]p2, which can be used to copy the cla...
Definition DeclCXX.cpp:3058
void setCtorClosureDefaultArgs(ArrayRef< CXXDefaultArgExpr * > Args)
Definition DeclCXX.cpp:3143
InheritedConstructor getInheritedConstructor() const
Get the constructor that this inheriting constructor is based on.
Definition DeclCXX.h:2872
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:2709
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2972
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition DeclCXX.h:3008
Represents a C++ base or member initializer.
Definition DeclCXX.h:2402
bool isWritten() const
Determine whether this initializer is explicitly written in the source code.
Definition DeclCXX.h:2574
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:2482
TypeSourceInfo * getTypeSourceInfo() const
Returns the declarator information for a base class or delegating initializer.
Definition DeclCXX.h:2536
FieldDecl * getAnyMember() const
Definition DeclCXX.h:2548
A default argument (C++ [dcl.fct.default]).
Definition ExprCXX.h:1273
Represents a C++ destructor within a class.
Definition DeclCXX.h:2902
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
CXXSpecialMemberKind getSpecialMemberKind() const
Definition DeclCXX.h:2224
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:2316
CXXMethodDecl * getMostRecentDecl()
Definition DeclCXX.h:2265
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:2288
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:2312
bool isStatic() const
Definition DeclCXX.cpp:2417
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:2258
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:183
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:2954
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3158
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3137
bool isCallToStdMove() const
Definition Expr.cpp:3654
Expr * getCallee()
Definition Expr.h:3101
arg_range arguments()
Definition Expr.h:3206
QualType withConst() const
Retrieves a version of this type with const applied.
CastKind getCastKind() const
Definition Expr.h:3731
Expr * getSubExpr()
Definition Expr.h:3737
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:3355
QualType getElementType() const
Definition TypeBase.h:3365
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:3874
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3930
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:3702
const CXXRecordDecl * getParent() const
Returns the parent of this using shadow declaration, which is the class in which this is declared.
Definition DeclCXX.h:3766
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:1281
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:1349
NonOdrUseReason isNonOdrUse() const
Is this expression a non-odr-use reference, and if so, why?
Definition Expr.h:1479
SourceLocation getBeginLoc() const
Definition Expr.h:1360
bool isImmediateEscalating() const
Definition Expr.h:1489
Captures information about "declaration specifiers".
Definition DeclSpec.h:220
bool isVirtualSpecified() const
Definition DeclSpec.h:655
bool isModulePrivateSpecified() const
Definition DeclSpec.h:836
bool hasTypeSpecifier() const
Return true if any type-specifier has been found.
Definition DeclSpec.h:698
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:545
void ClearStorageClassSpecs()
Definition DeclSpec.h:500
TST getTypeSpecType() const
Definition DeclSpec.h:522
SourceLocation getStorageClassSpecLoc() const
Definition DeclSpec.h:495
SCS getStorageClassSpec() const
Definition DeclSpec.h:486
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:560
SourceRange getSourceRange() const LLVM_READONLY
Definition DeclSpec.h:559
unsigned getTypeQualifiers() const
getTypeQualifiers - Return a set of TQs.
Definition DeclSpec.h:602
SourceLocation getExplicitSpecLoc() const
Definition DeclSpec.h:661
SourceLocation getFriendSpecLoc() const
Definition DeclSpec.h:834
ParsedType getRepAsType() const
Definition DeclSpec.h:532
TSCS getThreadStorageClassSpec() const
Definition DeclSpec.h:487
bool isFriendSpecifiedFirst() const
Definition DeclSpec.h:832
ParsedAttributes & getAttributes()
Definition DeclSpec.h:880
SourceLocation getEllipsisLoc() const
Definition DeclSpec.h:609
SourceLocation getConstSpecLoc() const
Definition DeclSpec.h:603
SourceRange getExplicitSpecRange() const
Definition DeclSpec.h:662
Expr * getRepAsExpr() const
Definition DeclSpec.h:540
bool isInlineSpecified() const
Definition DeclSpec.h:644
SourceLocation getRestrictSpecLoc() const
Definition DeclSpec.h:604
TypeSpecifierType TST
Definition DeclSpec.h:250
bool SetTypeQual(TQ T, SourceLocation Loc)
void ClearConstexprSpec()
Definition DeclSpec.h:848
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:496
SourceLocation getAtomicSpecLoc() const
Definition DeclSpec.h:606
SourceLocation getVirtualSpecLoc() const
Definition DeclSpec.h:656
SourceLocation getConstexprSpecLoc() const
Definition DeclSpec.h:843
SourceLocation getTypeSpecTypeLoc() const
Definition DeclSpec.h:567
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:647
SourceLocation getUnalignedSpecLoc() const
Definition DeclSpec.h:607
SourceLocation getVolatileSpecLoc() const
Definition DeclSpec.h:605
FriendSpecified isFriendSpecified() const
Definition DeclSpec.h:828
bool hasExplicitSpecifier() const
Definition DeclSpec.h:658
bool hasConstexprSpecifier() const
Definition DeclSpec.h:844
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:1952
bool isFunctionDeclarator(unsigned &idx) const
isFunctionDeclarator - This method returns true if the declarator is a function declarator (looking t...
Definition DeclSpec.h:2508
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:2450
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition DeclSpec.h:2099
bool isFunctionDeclarationContext() const
Return true if this declaration appears in a context where a function declarator would be a function ...
Definition DeclSpec.h:2562
SourceLocation getIdentifierLoc() const
Definition DeclSpec.h:2388
void SetIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Set the name of this declarator to be the given identifier.
Definition DeclSpec.h:2391
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclSpec.h:2136
type_object_range type_objects() const
Returns the range of type objects, from the identifier outwards.
Definition DeclSpec.h:2463
bool hasGroupingParens() const
Definition DeclSpec.h:2771
void setInvalidType(bool Val=true)
Definition DeclSpec.h:2765
unsigned getNumTypeObjects() const
Return the number of types applied to this declarator.
Definition DeclSpec.h:2446
bool isRedeclaration() const
Definition DeclSpec.h:2817
DeclaratorContext getContext() const
Definition DeclSpec.h:2124
const DecompositionDeclarator & getDecompositionDeclarator() const
Definition DeclSpec.h:2120
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:2135
bool isFunctionDefinition() const
Definition DeclSpec.h:2789
UnqualifiedId & getName()
Retrieve the name specified by this declarator.
Definition DeclSpec.h:2118
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition DeclSpec.h:2114
ArrayRef< TemplateParameterList * > getTemplateParameterLists() const
The template parameter lists that preceded the declarator.
Definition DeclSpec.h:2701
void setInventedTemplateParameterList(TemplateParameterList *Invented)
Sets the template parameter list generated from the explicit template parameters along with any inven...
Definition DeclSpec.h:2708
bool mayHaveDecompositionDeclarator() const
Return true if the context permits a C++17 decomposition declarator.
Definition DeclSpec.h:2263
bool isInvalidType() const
Definition DeclSpec.h:2766
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition DeclSpec.h:2134
bool isDecompositionDeclarator() const
Return whether this declarator is a decomposition declarator.
Definition DeclSpec.h:2378
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:2106
DeclaratorChunk::FunctionTypeInfo & getFunctionTypeInfo()
getFunctionTypeInfo - Retrieves the function type info object (looking through parentheses).
Definition DeclSpec.h:2539
const IdentifierInfo * getIdentifier() const
Definition DeclSpec.h:2382
A decomposition declaration.
Definition DeclCXX.h:4274
ArrayRef< BindingDecl * > bindings() const
Definition DeclCXX.h:4314
A parsed C++17 decomposition declarator of the form '[' identifier-list ']'.
Definition DeclSpec.h:1840
ArrayRef< Binding > bindings() const
Definition DeclSpec.h:1880
SourceRange getSourceRange() const
Definition DeclSpec.h:1888
SourceLocation getLSquareLoc() const
Definition DeclSpec.h:1886
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:972
virtual bool TraverseConstructorInitializer(MaybeConst< CXXCtorInitializer > *Init)
static EmptyDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L)
Definition Decl.cpp:5958
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:3557
Represents an enum.
Definition Decl.h:4145
enumerator_range enumerators() const
Definition Decl.h:4291
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:3294
bool isMutable() const
Determines whether this field is mutable (C++ only).
Definition Decl.h:3394
Expr * getInClassInitializer() const
Get the C++11 default member initializer for this member, or null if one has not been set.
Definition Decl.cpp:4788
bool hasInClassInitializer() const
Determine whether this member has a C++11 default member initializer.
Definition Decl.h:3474
bool isAnonymousStructOrUnion() const
Determines whether this field is a representative for an anonymous struct or union.
Definition Decl.cpp:4778
InClassInitStyle getInClassInitStyle() const
Get the kind of (C++11) default member initializer that this field has.
Definition Decl.h:3468
void setInClassInitializer(Expr *NewInit)
Set the C++11 in-class initializer for this member.
Definition Decl.cpp:4798
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3530
FieldDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this field.
Definition Decl.h:3541
bool isUnnamedBitField() const
Determines whether this is an unnamed bitfield.
Definition Decl.h:3400
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:46
static FriendDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, FriendUnion Friend, SourceLocation FriendL, SourceLocation EllipsisLoc={})
static FriendTemplateDecl * Create(ASTContext &Context, DeclContext *DC, SourceLocation Loc, FriendUnion Friend, SourceLocation FriendLoc, ArrayRef< TemplateParameterList * > FriendTPLists, SourceLocation EllipsisLoc={}, TemplateName Template={})
For a defaulted function, the kind of defaulted function that it is.
Definition Decl.h:2122
CXXSpecialMemberKind asSpecialMember() const
Definition Decl.h:2151
DefaultedComparisonKind asComparison() const
Definition Decl.h:2154
static DefaultedOrDeletedFunctionInfo * Create(ASTContext &Context, ArrayRef< DeclAccessPair > Lookups, FPOptionsOverride FPFeatures, StringLiteral *DeletedMessage=nullptr)
Definition Decl.cpp:3127
Represents a function declaration or definition.
Definition Decl.h:2058
static constexpr unsigned RequiredTypeAwareDeleteParameterCount
Count of mandatory parameters for type aware operator delete.
Definition Decl.h:2772
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2927
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition Decl.cpp:3267
ExceptionSpecificationType getExceptionSpecType() const
Gets the ExceptionSpecificationType as declared.
Definition Decl.h:2999
bool isTrivialForCall() const
Definition Decl.h:2506
ConstexprSpecKind getConstexprKind() const
Definition Decl.h:2602
DefaultedOrDeletedFunctionInfo * getDefaultedOrDeletedInfo() const
Definition Decl.cpp:3182
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to call this function.
Definition Decl.cpp:3890
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4236
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
Definition Decl.h:2427
bool isImmediateFunction() const
Definition Decl.cpp:3383
void setDefaultedOrDeletedInfo(DefaultedOrDeletedFunctionInfo *Info)
Definition Decl.cpp:3148
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type.
Definition Decl.cpp:4067
bool isDestroyingOperatorDelete() const
Determine whether this is a destroying operator delete.
Definition Decl.cpp:3594
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3908
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition Decl.h:3051
SourceLocation getDefaultLoc() const
Definition Decl.h:2524
QualType getReturnType() const
Definition Decl.h:2975
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2904
bool isExplicitlyDefaulted() const
Whether this function is explicitly defaulted.
Definition Decl.h:2515
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition Decl.h:2503
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition Decl.cpp:4356
MutableArrayRef< ParmVarDecl * >::iterator param_iterator
Definition Decl.h:2912
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3790
param_iterator param_begin()
Definition Decl.h:2916
const ParmVarDecl * getNonObjectParameter(unsigned I) const
Definition Decl.h:2953
bool isVariadic() const
Whether this function is variadic.
Definition Decl.cpp:3120
bool doesThisDeclarationHaveABody() const
Returns whether this specific declaration of the function has a body.
Definition Decl.h:2439
bool isDeleted() const
Whether this function has been deleted.
Definition Decl.h:2666
void setBodyContainsImmediateEscalatingExpressions(bool Set)
Definition Decl.h:2612
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4372
FunctionEffectsRef getFunctionEffects() const
Definition Decl.h:3268
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition Decl.cpp:4300
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition Decl.h:3018
bool isStatic() const
Definition Decl.h:3059
void setTrivial(bool IT)
Definition Decl.h:2504
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition Decl.cpp:4187
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition Decl.h:2596
static constexpr unsigned RequiredTypeAwareNewParameterCount
Count of mandatory parameters for type aware operator new.
Definition Decl.h:2768
bool isPureVirtual() const
Whether this virtual function is pure, i.e.
Definition Decl.h:2479
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition Decl.cpp:3661
FunctionDecl * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
bool isImmediateEscalating() const
Definition Decl.cpp:3354
void setIsDestroyingOperatorDelete(bool IsDestroyingDelete)
Definition Decl.cpp:3598
bool isTypeAwareOperatorNewOrDelete() const
Determine whether this is a type aware operator new or delete.
Definition Decl.cpp:3602
void setIsTypeAwareOperatorNewOrDelete(bool IsTypeAwareOperator=true)
Definition Decl.cpp:3606
bool isDefaulted() const
Whether this function is defaulted.
Definition Decl.h:2511
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:4612
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
Definition Decl.h:3063
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition Decl.cpp:4173
void setConstexprKind(ConstexprSpecKind CSK)
Definition Decl.h:2599
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition Decl.cpp:4460
void setDefaulted(bool D=true)
Definition Decl.h:2512
bool isConsteval() const
Definition Decl.h:2608
bool isUserProvided() const
True if this method is user-declared and was not deleted or defaulted on its first declaration.
Definition Decl.h:2536
DefaultedFunctionKind getDefaultedFunctionKind() const
Determine the kind of defaulting that would be done for a given function.
Definition Decl.cpp:3287
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:2992
void setBody(Stmt *B)
Definition Decl.cpp:3279
bool isVirtualAsWritten() const
Whether this function is marked as virtual explicitly.
Definition Decl.h:2470
bool hasOneParamOrDefaultArgs() const
Determine whether this function has a single parameter, or multiple parameters where all but the firs...
Definition Decl.cpp:3922
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3869
size_t param_size() const
Definition Decl.h:2920
DeclarationNameInfo getNameInfo() const
Definition Decl.h:2324
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition Decl.cpp:3187
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:3234
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:2935
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition Decl.h:2815
A mutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5357
bool insert(const FunctionEffectWithCondition &NewEC, Conflicts &Errs)
Definition Type.cpp:5866
SmallVector< Conflict > Conflicts
Definition TypeBase.h:5389
An immutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5221
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:5421
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition TypeBase.h:5925
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition TypeBase.h:5728
unsigned getNumParams() const
Definition TypeBase.h:5699
bool hasTrailingReturn() const
Whether this function prototype has a trailing return type.
Definition TypeBase.h:5841
const QualType * param_type_iterator
Definition TypeBase.h:5859
QualType getParamType(unsigned i) const
Definition TypeBase.h:5701
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5825
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5710
Expr * getNoexceptExpr() const
Return the expression inside noexcept(expression), or a null pointer if there is none (because the ex...
Definition TypeBase.h:5786
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5706
ArrayRef< QualType > exceptions() const
Definition TypeBase.h:5875
bool hasExtParameterInfos() const
Is there any interesting extra information for any of the parameters of this function type?
Definition TypeBase.h:5890
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:4840
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4617
CallingConv getCallConv() const
Definition TypeBase.h:4972
QualType getReturnType() const
Definition TypeBase.h:4957
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
RAII class that temporarily sets the "ignore all warnings" state on a DiagnosticsEngine and restores ...
ImaginaryLiteral - We support imaginary integer and floating point literals, like "1....
Definition Expr.h:1742
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:6074
Represents a field injected from an anonymous union/struct into the parent scope.
Definition Decl.h:3601
ArrayRef< NamedDecl * > chain() const
Definition Decl.h:3622
void setInherited(bool I)
Definition Attr.h:163
Description of a constructor that was inherited from a base class.
Definition DeclCXX.h:2608
ConstructorUsingShadowDecl * getShadowDecl() const
Definition DeclCXX.h:2620
const TypeClass * getTypePtr() const
Definition TypeLoc.h:526
Describes an C or C++ initializer list.
Definition Expr.h:5319
unsigned getNumInits() const
Definition Expr.h:5352
const Expr * getInit(unsigned Init) const
Definition Expr.h:5374
child_range children()
Definition Expr.h:5515
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:3731
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:3040
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:3082
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:4374
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:3375
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3458
Expr * getBase() const
Definition Expr.h:3452
SourceLocation getExprLoc() const LLVM_READONLY
Definition Expr.h:3570
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:3767
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:3226
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.
NestedNameSpecifier getNestedNameSpecifier() const
Retrieve the nested-name-specifier to which this instance refers.
SourceRange getSourceRange() const LLVM_READONLY
Retrieve the source range covering the entirety of this nested-name-specifier.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
NestedNameSpecifier getCanonical() const
Retrieves the "canonical" nested name specifier for a given nested name specifier.
bool containsUnexpandedParameterPack() const
Whether this nested-name-specifier contains an unexpanded parameter pack (for C++11 variadic template...
CXXRecordDecl * getAsRecordDecl() const
Retrieve the record declaration stored in this nested name specifier, or null.
bool isDependent() const
Whether this nested name specifier refers to a dependent type or not.
@ Global
The global specifier '::'. There is no stored value.
@ Namespace
A namespace-like entity, stored as a NamespaceBaseDecl*.
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
The basic abstraction for the target Objective-C runtime.
Definition ObjCRuntime.h:28
bool isFragile() const
The inverse of isNonFragile(): does this runtime follow the set of implied behaviors for a "fragile" ...
Definition ObjCRuntime.h:97
PtrTy get() const
Definition Ownership.h:81
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition Expr.h:1189
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition Overload.h:1161
@ CSK_Normal
Normal lookup.
Definition Overload.h:1165
@ CSK_Operator
C++ [over.match.oper]: Lookup of operator function candidates in a call using operator syntax.
Definition Overload.h:1172
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition Overload.h:1377
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:4980
Represents a parameter to a function.
Definition Decl.h:1819
void setDefaultArg(Expr *defarg)
Definition Decl.cpp:3009
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:3014
void setUninstantiatedDefaultArg(Expr *arg)
Definition Decl.cpp:3034
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:2944
Expr * getUninstantiatedDefaultArg()
Definition Decl.cpp:3039
bool hasDefaultArg() const
Determines whether this parameter has a default argument, either parsed or not.
Definition Decl.cpp:3045
void setHasInheritedDefaultArg(bool I=true)
Definition Decl.h:1968
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:2967
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:3408
QualType getPointeeType() const
Definition TypeBase.h:3418
IdentifierInfo * getIdentifierInfo(StringRef Name) const
Return information about the specified preprocessor identifier token.
IdentifierTable & getIdentifierTable()
ArrayRef< Expr * > semantics()
Definition Expr.h:6893
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:8588
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8593
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:8504
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8544
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:8689
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8598
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:8577
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition TypeBase.h:8550
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:2818
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:8669
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:3749
Represents a struct/union/class.
Definition Decl.h:4459
bool hasFlexibleArrayMember() const
Definition Decl.h:4492
bool hasObjectMember() const
Definition Decl.h:4519
field_iterator field_end() const
Definition Decl.h:4665
field_range fields() const
Definition Decl.h:4662
specific_decl_iterator< FieldDecl > field_iterator
Definition Decl.h:4659
RecordDecl * getDefinitionOrSelf() const
Definition Decl.h:4647
bool isAnonymousStructOrUnion() const
Whether this is an anonymous struct or union.
Definition Decl.h:4511
bool field_empty() const
Definition Decl.h:4670
field_iterator field_begin() const
Definition Decl.cpp:5338
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:5464
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3687
QualType getPointeeType() const
Definition TypeBase.h:3705
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:1314
A RAII object to temporarily push a declaration context.
Definition Sema.h:3533
Records and restores the CurFPFeatures state on entry/exit of compound statements.
Definition Sema.h:14145
Helper class that collects exception specifications for implicitly-declared special member functions.
Definition Sema.h:5548
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:5590
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:9317
CXXMethodDecl * getMethod() const
Definition Sema.h:9329
RAII object to handle the state changes required to synthesize a function body.
Definition Sema.h:13630
Abstract base class used for diagnosing integer constant expression violations.
Definition Sema.h:7734
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:864
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:13148
sema::CapturingScopeInfo * getEnclosingLambdaOrBlock() const
Get the innermost lambda or block enclosing the current location, if any.
Definition Sema.cpp:2691
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:6568
void ActOnParamUnparsedDefaultArgument(Decl *param, SourceLocation EqualLoc, SourceLocation ArgLoc)
ActOnParamUnparsedDefaultArgument - We've seen a default argument for a function parameter,...
ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs, const Scope *S, ActOnMemberAccessExtraArgs *ExtraArgs=nullptr)
bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S=nullptr, bool AllowInlineNamespace=false) const
isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true if 'D' is in Scope 'S',...
bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs=true)
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr, bool IsAfterAmp=false)
void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath)
void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old)
Merge the exception specifications of two variable declarations.
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9359
@ LookupUsingDeclName
Look up all declarations in a scope with the given name, including resolved using declarations.
Definition Sema.h:9386
@ LookupLocalFriendName
Look up a friend of a local class.
Definition Sema.h:9394
@ LookupNamespaceName
Look up a namespace name within a C++ using directive or namespace alias definition,...
Definition Sema.h:9382
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9367
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:13767
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:1532
void CheckDelegatingCtorCycles()
SmallVector< CXXMethodDecl *, 4 > DelayedDllExportMemberFunctions
Definition Sema.h:6358
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:1259
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:6541
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:6522
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:1472
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:7855
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:1691
@ AR_accessible
Definition Sema.h:1689
@ AR_inaccessible
Definition Sema.h:1690
@ AR_delayed
Definition Sema.h:1692
Scope * getScopeForContext(DeclContext *Ctx)
Determines the active Scope associated with the given declaration context.
Definition Sema.cpp:2463
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:2079
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:4210
@ Default
= default ;
Definition Sema.h:4212
@ Delete
deleted-function-body
Definition Sema.h:4218
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:2080
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:1305
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:933
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:1517
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:936
ClassTemplateDecl * StdInitializerList
The C++ "std::initializer_list" template, which is defined in <initializer_list>.
Definition Sema.h:6548
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:6632
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:777
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...
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:6563
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:1209
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:12237
EnumDecl * getStdAlignValT() const
void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record)
LangAS getDefaultCXXMethodAddrSpace() const
Returns default addr space for method qualifiers.
Definition Sema.cpp:1777
LazyDeclPtr StdBadAlloc
The C++ "std::bad_alloc" class, which is defined by the C++ standard library.
Definition Sema.h:8375
QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs, const DeclSpec *DS=nullptr)
void PushFunctionScope()
Enter a new function scope.
Definition Sema.cpp:2482
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:931
Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind=TU_Complete, CodeCompleteConsumer *CompletionConsumer=nullptr)
Definition Sema.cpp:277
ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr, ConditionKind CK, bool MissingOK=false)
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:84
@ UPPC_RequiresClause
Definition Sema.h:14565
@ UPPC_UsingDeclaration
A using declaration.
Definition Sema.h:14520
@ UPPC_ExceptionType
The type of an exception.
Definition Sema.h:14538
@ UPPC_Initializer
An initializer.
Definition Sema.h:14529
@ UPPC_BaseType
The base type of a class type.
Definition Sema.h:14499
@ UPPC_FriendDeclaration
A friend declaration.
Definition Sema.h:14523
@ UPPC_DefaultArgument
A default argument.
Definition Sema.h:14532
@ UPPC_DeclarationType
The type of an arbitrary declaration.
Definition Sema.h:14502
@ UPPC_DataMemberType
The type of a data member.
Definition Sema.h:14505
@ UPPC_StaticAssertExpression
The expression in a static assertion.
Definition Sema.h:14511
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:929
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:5950
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:2594
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:1304
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:1303
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:6526
SemaHLSL & HLSL()
Definition Sema.h:1482
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:5956
void CheckCXXDefaultArguments(FunctionDecl *FD)
Helpers for dealing with blocks and functions.
ComparisonCategoryUsage
Definition Sema.h:5330
@ DefaultedOperator
A defaulted 'operator<=>' needed the comparison category.
Definition Sema.h:5337
SmallVector< InventedTemplateParameterInfo, 4 > InventedParameterInfos
Stack containing information needed when in C++2a an 'auto' is encountered in a function declaration ...
Definition Sema.h:6519
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:6624
llvm::DenseMap< ParmVarDecl *, SourceLocation > UnparsedDefaultArgLocs
Definition Sema.h:6556
void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, const CXXRecordDecl *RD)
Mark the exception specifications of all virtual member functions in the given class as needed.
ExprResult BuildConvertedConstantExpression(Expr *From, QualType T, CCEKind CCE, NamedDecl *Dest=nullptr)
bool RequireCompleteEnumDecl(EnumDecl *D, SourceLocation L, CXXScopeSpec *SS=nullptr)
Require that the EnumDecl is completed with its enumerators defined or instantiated.
bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl)
CheckOverloadedOperatorDeclaration - Check whether the declaration of this overloaded operator is wel...
void MarkVirtualBaseDestructorsReferenced(SourceLocation Location, CXXRecordDecl *ClassDecl, llvm::SmallPtrSetImpl< const CXXRecordDecl * > *DirectVirtualBases=nullptr)
Mark destructors of virtual bases of this class referenced.
void ExitDeclaratorContext(Scope *S)
void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir)
void CheckConstructor(CXXConstructorDecl *Constructor)
CheckConstructor - Checks a fully-formed constructor for well-formedness, issuing any diagnostics req...
void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc, CXXConversionDecl *Conv)
Define the "body" of the conversion from a lambda object to a block pointer.
void DefineImplicitDestructor(SourceLocation CurrentLocation, CXXDestructorDecl *Destructor)
DefineImplicitDestructor - Checks for feasibility of defining this destructor as the default destruct...
void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMemberKind CSM)
Diagnose why the specified class does not have a trivial special member of the given kind.
Decl * ActOnUsingEnumDeclaration(Scope *CurScope, AccessSpecifier AS, SourceLocation UsingLoc, SourceLocation EnumLoc, SourceRange TyLoc, const IdentifierInfo &II, ParsedType Ty, const CXXScopeSpec &SS)
CXXRecordDecl * getCurrentClass(Scope *S, const CXXScopeSpec *SS)
Get the class that is directly named by the current context.
bool EvaluateAsString(Expr *Message, APValue &Result, ASTContext &Ctx, StringEvaluationContext EvalContext, bool ErrorOnInvalidMessage)
QualType BuildReferenceType(QualType T, bool LValueRef, SourceLocation Loc, DeclarationName Entity)
Build a reference type.
TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, QualType NTTPType, SourceLocation Loc)
Allocate a TemplateArgumentLoc where all locations have been initialized to the given location.
bool DiagnosePackIndexingInFriendNNS(SourceLocation Loc, NestedNameSpecifierLoc NNSLoc)
ExprResult ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr)
bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method)
Check whether 'this' shows up in the attributes of the given static member function.
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:13160
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:5946
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:15604
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:9887
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:7001
std::unique_ptr< RecordDeclSetTy > PureVirtualClassDiagSet
PureVirtualClassDiagSet - a set of class declarations which we have emitted a list of pure virtual fu...
Definition Sema.h:6533
void ActOnFinishInlineFunctionDef(FunctionDecl *D)
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition Sema.h:1445
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:6552
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:8194
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:14045
SourceManager & getSourceManager() const
Definition Sema.h:934
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:9345
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:6066
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:15559
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:6544
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:1583
ASTConsumer & Consumer
Definition Sema.h:1306
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:4710
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:1345
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:6754
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
Definition Sema.h:6764
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6733
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:1264
bool CheckDependentFriend(SourceLocation Loc, NestedNameSpecifierLoc NNSLoc, ArrayRef< TemplateParameterList * > TPLs, bool IsInstantiation)
void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, ArrayRef< Decl * > Fields, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList)
void CheckExplicitObjectLambda(Declarator &D)
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD)
void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc)
PopPragmaVisibility - Pop the top element of the visibility stack; used for '#pragma GCC visibility' ...
Expr * MaybeCreateExprWithCleanups(Expr *SubExpr)
MaybeCreateExprWithCleanups - If the current full-expression requires any cleanups,...
void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init)
Check that the lifetime of the initializer (and its subobjects) is sufficient for initializing the en...
void CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record)
Perform semantic checks on a class definition that has been completing, introducing implicitly-declar...
void DiscardCleanupsInEvaluationContext()
void PushDeclContext(Scope *S, DeclContext *DC)
Set the current declaration context until it gets popped.
bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New)
void mergeDeclAttributes(NamedDecl *New, Decl *Old, AvailabilityMergeKind AMK=AvailabilityMergeKind::Redeclaration)
mergeDeclAttributes - Copy attributes from the Old decl to the New one.
bool isDependentScopeSpecifier(const CXXScopeSpec &SS)
SourceManager & SourceMgr
Definition Sema.h:1308
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:1307
FullExprArg MakeFullDiscardedValueExpr(Expr *Arg)
Definition Sema.h:7804
FPOptions CurFPFeatures
Definition Sema.h:1301
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:6528
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:1587
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:6560
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:6357
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:6303
@ AbstractVariableType
Definition Sema.h:6307
@ AbstractReturnType
Definition Sema.h:6305
@ AbstractNone
Definition Sema.h:6304
@ AbstractFieldType
Definition Sema.h:6308
@ AbstractArrayType
Definition Sema.h:6311
@ AbstractParamType
Definition Sema.h:6306
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:8379
DeclResult ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, unsigned TagSpec, SourceLocation TagLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, SourceLocation EllipsisLoc, const ParsedAttributesView &Attr, MultiTemplateParamsArg TempParamLists, TemplateIdAnnotation *TemplateId)
Handle a friend tag declaration where the scope specifier was templated.
void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc)
CheckConstexprKind
Definition Sema.h:6439
@ CheckValid
Identify whether this function satisfies the formal rules for constexpr functions in the current lanu...
Definition Sema.h:6444
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
Definition Sema.h:6441
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:3526
DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class)
Look up the constructors for the given class.
void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record)
TypeResult ActOnTagTemplateIdType(TagUseKind TUK, TypeSpecifierType TagSpec, SourceLocation TagLoc, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy TemplateD, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc)
Parsed an elaborated-type-specifier that refers to a template-id, such as class T::template apply.
ExprResult ActOnCXXThis(SourceLocation Loc)
CXXConstructorDecl * findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor, ConstructorUsingShadowDecl *DerivedShadow)
Given a derived-class using shadow declaration for a constructor and the correspnding base class cons...
void warnOnReservedIdentifier(const NamedDecl *D)
bool CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD, CXXSpecialMemberKind CSM, SourceLocation DefaultLoc)
bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS)
Determine whether the identifier II is a typo for the name of the class type currently being defined.
Decl * ActOnUsingDeclaration(Scope *CurScope, AccessSpecifier AS, SourceLocation UsingLoc, SourceLocation TypenameLoc, CXXScopeSpec &SS, UnqualifiedId &Name, SourceLocation EllipsisLoc, const ParsedAttributesView &AttrList)
void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param)
ActOnDelayedCXXMethodParameter - We've already started a delayed C++ method declaration.
bool isAbstractType(SourceLocation Loc, QualType T)
ValueDecl * tryLookupUnambiguousFieldDecl(RecordDecl *ClassDecl, const IdentifierInfo *MemberOrBase)
ASTMutationListener * getASTMutationListener() const
Definition Sema.cpp:672
bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, ArrayRef< CXXCtorInitializer * > Initializers={})
void DiagnoseImmediateEscalatingReason(FunctionDecl *FD)
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition Sema.h:8674
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:1810
bool isUnevaluated() const
Definition Expr.h:1932
StringRef getString() const
Definition Expr.h:1878
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3851
bool isBeingDefined() const
Return true if this decl is currently being defined.
Definition Decl.h:3972
StringRef getKindName() const
Definition Decl.h:4047
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3952
TagDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:4962
bool isUnion() const
Definition Decl.h:4062
TagKind getTagKind() const
Definition Decl.h:4051
bool isDependentType() const
Whether this declaration declares a type that is dependent, i.e., a type that somehow depends on temp...
Definition Decl.h:3997
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:3822
static TypeAliasDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition Decl.cpp:5880
void setDescribedAliasTemplate(TypeAliasTemplateDecl *TAT)
Definition Decl.h:3841
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:3647
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
TypeSpecTypeLoc pushTypeSpec(QualType T)
Pushes space for a typespec TypeLoc.
TypeSourceInfo * getTypeSourceInfo(ASTContext &Context, QualType T)
Creates a TypeSourceInfo for the given type.
Base wrapper for a particular "section" of type source info.
Definition TypeLoc.h:59
QualType getType() const
Get the type for which this source info wrapper provides information.
Definition TypeLoc.h:133
TypeLoc getNextTypeLoc() const
Get the next TypeLoc pointed by this TypeLoc, e.g for "int*" the TypeLoc is a PointerLoc and next Typ...
Definition TypeLoc.h:171
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition TypeLoc.h:89
NestedNameSpecifierLoc getPrefix() const
If this type represents a qualified-id, this returns it's nested name specifier.
Definition TypeLoc.cpp:475
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:8475
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:8486
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:551
The base class of the type hierarchy.
Definition TypeBase.h:1879
bool isVoidType() const
Definition TypeBase.h:9113
bool isBooleanType() const
Definition TypeBase.h:9250
const TemplateSpecializationType * getAsNonAliasTemplateSpecializationType() const
Look through sugar for an instance of TemplateSpecializationType which is not a type alias,...
Definition Type.cpp:1996
bool isIncompleteArrayType() const
Definition TypeBase.h:8848
bool isUndeducedAutoType() const
Definition TypeBase.h:8937
bool isRValueReferenceType() const
Definition TypeBase.h:8773
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:8840
bool isPointerType() const
Definition TypeBase.h:8741
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9157
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9407
bool isReferenceType() const
Definition TypeBase.h:8765
bool isEnumeralType() const
Definition TypeBase.h:8872
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:8769
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition TypeBase.h:9082
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2859
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition TypeBase.h:2469
QualType getCanonicalTypeInternal() const
Definition TypeBase.h:3196
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition TypeBase.h:9293
bool isFunctionProtoType() const
Definition TypeBase.h:2665
bool isOverloadableType() const
Determines whether this is a type for which one can define an overloaded operator.
Definition TypeBase.h:9263
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition TypeBase.h:2877
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9256
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition Type.h:53
bool isFunctionType() const
Definition TypeBase.h:8737
bool isStructureOrClassType() const
Definition Type.cpp:743
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2435
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:2998
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:2362
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9340
bool isRecordType() const
Definition TypeBase.h:8868
bool isUnionType() const
Definition Type.cpp:755
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3696
QualType getUnderlyingType() const
Definition Decl.h:3751
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:2296
Opcode getOpcode() const
Definition Expr.h:2291
static bool isIncrementDecrementOp(Opcode Op)
Definition Expr.h:2351
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:5165
TypeLocClass getTypeLocClass() const
Definition TypeLoc.h:283
Represents a C++ unqualified-id that has been parsed.
Definition DeclSpec.h:1039
UnionParsedType ConversionFunctionId
When Kind == IK_ConversionFunctionId, the type that the conversion function names.
Definition DeclSpec.h:1075
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:1251
SourceRange getSourceRange() const LLVM_READONLY
Return the source range that covers this unqualified-id.
Definition DeclSpec.h:1248
UnionParsedType DestructorName
When Kind == IK_DestructorName, the type referred to by the class-name.
Definition DeclSpec.h:1083
SourceLocation StartLocation
The location of the first token that describes this unqualified-id, which will be the location of the...
Definition DeclSpec.h:1097
UnionParsedTemplateTy TemplateName
When Kind == IK_DeductionGuideName, the parsed template-name.
Definition DeclSpec.h:1086
const IdentifierInfo * Identifier
When Kind == IK_Identifier, the parsed identifier, or when Kind == IK_UserLiteralId,...
Definition DeclSpec.h:1067
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition DeclSpec.h:1121
TemplateIdAnnotation * TemplateId
When Kind == IK_TemplateId or IK_ConstructorTemplateId, the template-id annotation that contains the ...
Definition DeclSpec.h:1091
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:4143
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:3616
bool hasTypename() const
Return true if the using declaration has 'typename'.
Definition DeclCXX.h:3665
NestedNameSpecifier getQualifier() const
Retrieve the nested-name-specifier that qualifies the name.
Definition DeclCXX.h:3653
DeclarationNameInfo getNameInfo() const
Definition DeclCXX.h:3657
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:3643
Represents C++ using-directive.
Definition DeclCXX.h:3121
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:3817
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:3424
static UsingShadowDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation Loc, DeclarationName Name, BaseUsingDecl *Introducer, NamedDecl *Target)
Definition DeclCXX.h:3460
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition DeclCXX.h:3488
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:5656
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:2781
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:2807
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:2822
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:4289
unsigned getNumElements() const
Definition TypeBase.h:4304
QualType getElementType() const
Definition TypeBase.h:4303
Represents a C++11 virt-specifier-seq.
Definition DeclSpec.h:2832
SourceLocation getOverrideLoc() const
Definition DeclSpec.h:2852
SourceLocation getLastLocation() const
Definition DeclSpec.h:2864
bool isOverrideSpecified() const
Definition DeclSpec.h:2851
SourceLocation getFinalLoc() const
Definition DeclSpec.h:2856
bool isFinalSpecified() const
Definition DeclSpec.h:2854
bool isFinalSpelledSealed() const
Definition DeclSpec.h:2855
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:1203
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:987
std::variant< struct RequiresDecl, struct HeaderDecl, struct UmbrellaDirDecl, struct ModuleDecl, struct ExcludeDecl, struct ExportDecl, struct ExportAsDecl, struct ExternModuleDecl, struct UseDecl, struct LinkDecl, struct ConfigMacrosDecl, struct ConflictDecl > Decl
All declarations that can appear in a module declaration.
Stencil access(llvm::StringRef BaseId, Stencil Member)
Constructs a MemberExpr that accesses the named member (Member) of the object bound to BaseId.
Top level wrappers for InstallAPI frontend operations.
bool FTIHasNonVoidParameters(const DeclaratorChunk::FunctionTypeInfo &FTI)
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
TypeSpecifierType
Specifies the kind of type.
Definition Specifiers.h:56
@ TST_decltype
Definition Specifiers.h:90
@ TST_typename_pack_indexing
Definition Specifiers.h:98
@ TST_decltype_auto
Definition Specifiers.h:94
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
@ OO_None
Not an overloaded operator.
@ NUM_OVERLOADED_OPERATORS
@ NonFunction
This is not an overload because the lookup results contain a non-function.
Definition Sema.h:829
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:825
@ Overload
This is a legitimate overload: the existing declarations are functions or function templates with dif...
Definition Sema.h:821
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:508
ConstexprSpecKind
Define the kind of constexpr specifier.
Definition Specifiers.h:36
LinkageSpecLanguageIDs
Represents the language in a linkage specification.
Definition DeclCXX.h:3032
@ 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:662
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:1801
@ RQ_RValue
An rvalue ref-qualifier was provided (&&).
Definition TypeBase.h:1807
@ TemplateName
The identifier is a template name. FIXME: Add an annotation for that.
Definition Parser.h:61
@ OCD_AmbiguousCandidates
Requests that only tied-for-best candidates be shown.
Definition Overload.h:73
@ OCD_AllCandidates
Requests that all candidates be shown.
Definition Overload.h:67
CXXConstructionKind
Definition ExprCXX.h: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:628
std::pair< llvm::PointerUnion< const TemplateTypeParmType *, NamedDecl *, const TemplateSpecializationType *, const SubstBuiltinTemplatePackType * >, SourceLocation > UnexpandedParameterPack
Definition Sema.h:244
@ 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:1035
@ IK_ImplicitSelfParam
An implicit 'self' parameter.
Definition DeclSpec.h:1033
@ IK_TemplateId
A template-id, e.g., f<int>.
Definition DeclSpec.h:1031
@ IK_ConstructorTemplateId
A constructor named via a template-id.
Definition DeclSpec.h:1027
@ IK_ConstructorName
A constructor name.
Definition DeclSpec.h:1025
@ IK_LiteralOperatorId
A user-defined literal name, e.g., operator "" _i.
Definition DeclSpec.h:1023
@ IK_Identifier
An identifier.
Definition DeclSpec.h:1017
@ IK_DestructorName
A destructor name.
Definition DeclSpec.h:1029
@ IK_OperatorFunctionId
An overloaded operator name, e.g., operator+.
Definition DeclSpec.h:1019
@ IK_ConversionFunctionId
A conversion function name, e.g., operator int.
Definition DeclSpec.h:1021
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:6045
@ Interface
The "__interface" keyword.
Definition TypeBase.h:6050
@ Struct
The "struct" keyword.
Definition TypeBase.h:6047
@ Class
The "class" keyword.
Definition TypeBase.h:6056
ExprResult ExprError()
Definition Ownership.h:265
@ Keyword
The name has been typo-corrected to a keyword.
Definition Sema.h:557
@ Type
The name was classified as a type.
Definition Sema.h:559
DefaultedComparisonKind
Kinds of defaulted comparison operator functions.
Definition Decl.h:2029
@ Relational
This is an <, <=, >, or >= that should be implemented as a rewrite in terms of a <=> comparison.
Definition Decl.h:2043
@ NotEqual
This is an operator!= that should be implemented as a rewrite in terms of a == comparison.
Definition Decl.h:2040
@ ThreeWay
This is an operator<=> that should be implemented as a series of subobject comparisons.
Definition Decl.h:2037
@ None
This is not a defaultable comparison operator.
Definition Decl.h:2031
@ Equal
This is an operator== that should be implemented as a series of subobject comparisons.
Definition Decl.h:2034
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:4438
@ CanNeverPassInRegs
The argument of this type cannot be passed directly in registers.
Definition Decl.h:4452
@ CannotPassInRegs
The argument of this type cannot be passed directly in registers.
Definition Decl.h:4447
AllowFoldKind
Definition Sema.h:650
@ TU_Prefix
The translation unit is a prefix to a translation unit, and is not complete.
ComparisonCategoryType
An enumeration representing the different comparison categories types.
MutableArrayRef< ParsedTemplateArgument > ASTTemplateArgsPtr
Definition Ownership.h:261
CXXSpecialMemberKind
Kinds of C++ special members.
Definition Decl.h:2018
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:640
@ ConsiderTrivialABI
The triviality of a method affected by "trivial_abi".
Definition Sema.h:645
@ IgnoreTrivialABI
The triviality of a method unaffected by "trivial_abi".
Definition Sema.h:642
@ Incomplete
Template argument deduction did not deduce a value for every template parameter.
Definition Sema.h:385
@ Success
Template argument deduction was successful.
Definition Sema.h:377
@ Inconsistent
Template argument deduction produced inconsistent deduced values for the given template parameter.
Definition Sema.h:391
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:844
@ StaticAssertMessageSize
Call to size() in a static assert message.
Definition Sema.h:842
@ ExplicitBool
Condition in an explicit(bool) specifier.
Definition Sema.h:840
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:6020
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:6041
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6031
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6034
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:1412
ParamInfo * Params
Params - This is a pointer to a new[]'d array of ParamInfo objects that describe the parameters speci...
Definition DeclSpec.h:1472
unsigned RefQualifierIsLValueRef
Whether the ref-qualifier (if any) is an lvalue reference.
Definition DeclSpec.h:1421
DeclSpec * MethodQualifiers
DeclSpec for the function with the qualifier related info.
Definition DeclSpec.h:1475
SourceLocation getRefQualifierLoc() const
Retrieve the location of the ref-qualifier, if any.
Definition DeclSpec.h:1573
unsigned NumParams
NumParams - This is the number of formal parameters specified by the declarator.
Definition DeclSpec.h:1447
bool hasMutableQualifier() const
Determine whether this lambda-declarator contains a 'mutable' qualifier.
Definition DeclSpec.h:1602
bool hasMethodTypeQualifiers() const
Determine whether this method has qualifiers.
Definition DeclSpec.h:1605
void freeParams()
Reset the parameter list to having zero parameters.
Definition DeclSpec.h:1511
bool hasRefQualifier() const
Determine whether this function declaration contains a ref-qualifier.
Definition DeclSpec.h:1598
std::unique_ptr< CachedTokens > DefaultArgTokens
DefaultArgTokens - When the parameter's default argument cannot be parsed immediately (because it occ...
Definition DeclSpec.h:1387
One instance of this struct is used for each type in a declarator that is parsed.
Definition DeclSpec.h:1287
SourceRange getSourceRange() const
Definition DeclSpec.h:1299
FunctionTypeInfo Fun
Definition DeclSpec.h:1686
enum clang::DeclaratorChunk::@340323374315200305336204205154073066142310370142 Kind
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:657
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:5478
FunctionDecl * SourceDecl
The function whose exception specification this is, for EST_Unevaluated and EST_Uninstantiated.
Definition TypeBase.h:5490
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition TypeBase.h:5480
ArrayRef< QualType > Exceptions
Explicitly-specified list of exception types.
Definition TypeBase.h:5483
Expr * NoexceptExpr
Noexcept expression, if this is a computed noexcept specification.
Definition TypeBase.h:5486
Extra information about a function prototype.
Definition TypeBase.h:5506
static StringRef getTagTypeKindName(TagTypeKind Kind)
Definition TypeBase.h:6084
static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag)
Converts a TagTypeKind into an elaborated type keyword.
Definition Type.cpp:3415
static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into a tag type kind.
Definition Type.cpp:3397
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:13199
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
SourceLocation PointOfInstantiation
The point of instantiation or synthesis within the source code.
Definition Sema.h:13330
@ MarkingClassDllexported
We are marking a class as __dllexport.
Definition Sema.h:13290
@ InitializingStructuredBinding
We are initializing a structured binding.
Definition Sema.h:13287
@ ExceptionSpecEvaluation
We are computing the exception specification for a defaulted special member function.
Definition Sema.h:13243
@ DeclaringImplicitEqualityComparison
We are declaring an implicit 'operator==' for a defaulted 'operator<=>'.
Definition Sema.h:13261
Decl * Entity
The entity that is being synthesized.
Definition Sema.h:13333
Abstract class used to diagnose incomplete types.
Definition Sema.h:8271
virtual void diagnose(Sema &S, SourceLocation Loc, QualType T)=0
Information about a template-id annotation token.
TemplateNameKind Kind
The kind of template that Template refers to.
unsigned NumArgs
NumArgs - The number of template arguments.
SourceLocation TemplateNameLoc
TemplateNameLoc - The location of the template name within the source.
ParsedTemplateArgument * getTemplateArgs()
Retrieves a pointer to the template arguments.
SourceLocation RAngleLoc
The location of the '>' after the template argument list.
SourceLocation LAngleLoc
The location of the '<' before the template argument list.
SourceLocation TemplateKWLoc
TemplateKWLoc - The location of the template keyword.
ParsedTemplateTy Template
The declaration of the template corresponding to the template-name.
OpaquePtr< T > get() const
Definition Ownership.h:105