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 auto It = llvm::find_if(New->parameters(), [](const ParmVarDecl *P) {
683 return P->hasDefaultArg();
684 });
685 assert(It != New->param_end());
686 ParmVarDecl *NewParam = *It;
687 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
688 << NewParam->getDefaultArgRange() << NewSM;
689 Diag(Old->getLocation(), diag::note_previous_declaration);
690 }
691 }
692
693 const FunctionDecl *Def;
694 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
695 // template has a constexpr specifier then all its declarations shall
696 // contain the constexpr specifier.
697 if (New->getConstexprKind() != Old->getConstexprKind()) {
698 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
699 << New << static_cast<int>(New->getConstexprKind())
700 << static_cast<int>(Old->getConstexprKind());
701 Diag(Old->getLocation(), diag::note_previous_declaration);
702 Invalid = true;
703 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
704 Old->isDefined(Def) &&
705 // If a friend function is inlined but does not have 'inline'
706 // specifier, it is a definition. Do not report attribute conflict
707 // in this case, redefinition will be diagnosed later.
708 (New->isInlineSpecified() ||
709 New->getFriendObjectKind() == Decl::FOK_None)) {
710 // C++11 [dcl.fcn.spec]p4:
711 // If the definition of a function appears in a translation unit before its
712 // first declaration as inline, the program is ill-formed.
713 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
714 Diag(Def->getLocation(), diag::note_previous_definition);
715 Invalid = true;
716 }
717
718 // C++17 [temp.deduct.guide]p3:
719 // Two deduction guide declarations in the same translation unit
720 // for the same class template shall not have equivalent
721 // parameter-declaration-clauses.
723 !New->isFunctionTemplateSpecialization() && isVisible(Old)) {
724 Diag(New->getLocation(), diag::err_deduction_guide_redeclared);
725 Diag(Old->getLocation(), diag::note_previous_declaration);
726 }
727
728 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
729 // argument expression, that declaration shall be a definition and shall be
730 // the only declaration of the function or function template in the
731 // translation unit.
734 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
735 Diag(Old->getLocation(), diag::note_previous_declaration);
736 Invalid = true;
737 }
738
739 // C++11 [temp.friend]p4 (DR329):
740 // When a function is defined in a friend function declaration in a class
741 // template, the function is instantiated when the function is odr-used.
742 // The same restrictions on multiple declarations and definitions that
743 // apply to non-template function declarations and definitions also apply
744 // to these implicit definitions.
745 const FunctionDecl *OldDefinition = nullptr;
746 if (New->isThisDeclarationInstantiatedFromAFriendDefinition() &&
747 Old->isDefined(OldDefinition, true))
748 CheckForFunctionRedefinition(New, OldDefinition);
749
750 return Invalid;
751}
752
754 DiagCompat(Loc, diag_compat::placeholder_var_definition);
755}
756
757NamedDecl *
759 MultiTemplateParamsArg TemplateParamLists) {
760 assert(D.isDecompositionDeclarator());
762
763 // The syntax only allows a decomposition declarator as a simple-declaration,
764 // a for-range-declaration, or a condition in Clang, but we parse it in more
765 // cases than that.
767 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
768 << Decomp.getSourceRange();
769 return nullptr;
770 }
771
772 if (!TemplateParamLists.empty()) {
773 // C++17 [temp]/1:
774 // A template defines a family of class, functions, or variables, or an
775 // alias for a family of types.
776 //
777 // Structured bindings are not included.
778 Diag(TemplateParamLists.front()->getTemplateLoc(),
779 diag::err_decomp_decl_template);
780 return nullptr;
781 }
782
783 unsigned DiagID;
785 DiagID = diag::compat_pre_cxx17_decomp_decl;
787 DiagID = getLangOpts().CPlusPlus26
788 ? diag::compat_cxx26_decomp_decl_cond
789 : diag::compat_pre_cxx26_decomp_decl_cond;
790 else
791 DiagID = diag::compat_cxx17_decomp_decl;
792
793 Diag(Decomp.getLSquareLoc(), DiagID) << Decomp.getSourceRange();
794
795 // The semantic context is always just the current context.
796 DeclContext *const DC = CurContext;
797
798 // C++17 [dcl.dcl]/8:
799 // The decl-specifier-seq shall contain only the type-specifier auto
800 // and cv-qualifiers.
801 // C++20 [dcl.dcl]/8:
802 // If decl-specifier-seq contains any decl-specifier other than static,
803 // thread_local, auto, or cv-qualifiers, the program is ill-formed.
804 // C++23 [dcl.pre]/6:
805 // Each decl-specifier in the decl-specifier-seq shall be static,
806 // thread_local, auto (9.2.9.6 [dcl.spec.auto]), or a cv-qualifier.
807 // C++23 [dcl.pre]/7:
808 // Each decl-specifier in the decl-specifier-seq shall be constexpr,
809 // constinit, static, thread_local, auto, or a cv-qualifier
810 auto &DS = D.getDeclSpec();
811 auto DiagBadSpecifier = [&](StringRef Name, SourceLocation Loc) {
812 Diag(Loc, diag::err_decomp_decl_spec) << Name;
813 };
814
815 auto DiagCpp20Specifier = [&](StringRef Name, SourceLocation Loc) {
816 DiagCompat(Loc, diag_compat::decomp_decl_spec) << Name;
817 };
818
819 if (auto SCS = DS.getStorageClassSpec()) {
820 if (SCS == DeclSpec::SCS_static)
821 DiagCpp20Specifier(DeclSpec::getSpecifierName(SCS),
822 DS.getStorageClassSpecLoc());
823 else
824 DiagBadSpecifier(DeclSpec::getSpecifierName(SCS),
825 DS.getStorageClassSpecLoc());
826 }
827 if (auto TSCS = DS.getThreadStorageClassSpec())
828 DiagCpp20Specifier(DeclSpec::getSpecifierName(TSCS),
829 DS.getThreadStorageClassSpecLoc());
830
831 if (DS.isInlineSpecified())
832 DiagBadSpecifier("inline", DS.getInlineSpecLoc());
833
834 if (ConstexprSpecKind ConstexprSpec = DS.getConstexprSpecifier();
835 ConstexprSpec != ConstexprSpecKind::Unspecified) {
836 if (ConstexprSpec == ConstexprSpecKind::Consteval ||
838 DiagBadSpecifier(DeclSpec::getSpecifierName(ConstexprSpec),
839 DS.getConstexprSpecLoc());
840 }
841
842 // We can't recover from it being declared as a typedef.
843 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
844 return nullptr;
845
846 // C++2a [dcl.struct.bind]p1:
847 // A cv that includes volatile is deprecated
848 if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) &&
850 Diag(DS.getVolatileSpecLoc(),
851 diag::warn_deprecated_volatile_structured_binding);
852
854 QualType R = TInfo->getType();
855
858 D.setInvalidType();
859
860 // The syntax only allows a single ref-qualifier prior to the decomposition
861 // declarator. No other declarator chunks are permitted. Also check the type
862 // specifier here.
863 if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
864 D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
865 (D.getNumTypeObjects() == 1 &&
867 Diag(Decomp.getLSquareLoc(),
868 (D.hasGroupingParens() ||
869 (D.getNumTypeObjects() &&
871 ? diag::err_decomp_decl_parens
872 : diag::err_decomp_decl_type)
873 << R;
874
875 // In most cases, there's no actual problem with an explicitly-specified
876 // type, but a function type won't work here, and ActOnVariableDeclarator
877 // shouldn't be called for such a type.
878 if (R->isFunctionType())
879 D.setInvalidType();
880 }
881
882 // Constrained auto is prohibited by [decl.pre]p6, so check that here.
883 if (DS.isConstrainedAuto()) {
884 TemplateIdAnnotation *TemplRep = DS.getRepAsTemplateId();
885 assert(TemplRep->Kind == TNK_Concept_template &&
886 "No other template kind should be possible for a constrained auto");
887
888 SourceRange TemplRange{TemplRep->TemplateNameLoc,
889 TemplRep->RAngleLoc.isValid()
890 ? TemplRep->RAngleLoc
891 : TemplRep->TemplateNameLoc};
892 Diag(TemplRep->TemplateNameLoc, diag::err_decomp_decl_constraint)
893 << TemplRange << FixItHint::CreateRemoval(TemplRange);
894 }
895
896 // Build the BindingDecls.
898
899 // Build the BindingDecls.
900 for (auto &B : D.getDecompositionDeclarator().bindings()) {
901 // Check for name conflicts.
902 DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
903 IdentifierInfo *VarName = B.Name;
904 assert(VarName && "Cannot have an unnamed binding declaration");
905
909 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
910
911 // It's not permitted to shadow a template parameter name.
912 if (Previous.isSingleResult() &&
913 Previous.getFoundDecl()->isTemplateParameter()) {
914 DiagnoseTemplateParameterShadow(B.NameLoc, Previous.getFoundDecl());
915 Previous.clear();
916 }
917
918 QualType QT;
919 if (B.EllipsisLoc.isValid()) {
920 if (!cast<Decl>(DC)->isTemplated())
921 Diag(B.EllipsisLoc, diag::err_pack_outside_template);
922 QT = Context.getPackExpansionType(Context.DependentTy, std::nullopt,
923 /*ExpectsPackInType=*/false);
924 }
925
926 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name, QT);
927
928 if (BD->isParameterPack()) {
930 CSI->LocalPacks.push_back(BD);
931 }
932
933 ProcessDeclAttributeList(S, BD, *B.Attrs);
934
935 // Find the shadowed declaration before filtering for scope.
936 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
938 : nullptr;
939
940 bool ConsiderLinkage = DC->isFunctionOrMethod() &&
941 DS.getStorageClassSpec() == DeclSpec::SCS_extern;
942 FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
943 /*AllowInlineNamespace*/false);
944
945 bool IsPlaceholder = DS.getStorageClassSpec() != DeclSpec::SCS_static &&
946 DC->isFunctionOrMethod() && VarName->isPlaceholder();
947 if (!Previous.empty()) {
948 if (IsPlaceholder) {
949 bool sameDC = (Previous.end() - 1)
950 ->getDeclContext()
951 ->getRedeclContext()
952 ->Equals(DC->getRedeclContext());
953 if (sameDC &&
954 isDeclInScope(*(Previous.end() - 1), CurContext, S, false)) {
955 Previous.clear();
957 }
958 } else {
959 auto *Old = Previous.getRepresentativeDecl();
960 Diag(B.NameLoc, diag::err_redefinition) << B.Name;
961 Diag(Old->getLocation(), diag::note_previous_definition);
962 }
963 } else if (ShadowedDecl && !D.isRedeclaration()) {
964 CheckShadow(BD, ShadowedDecl, Previous);
965 }
966 PushOnScopeChains(BD, S, true);
967 Bindings.push_back(BD);
968 ParsingInitForAutoVars.insert(BD);
969 }
970
971 // There are no prior lookup results for the variable itself, because it
972 // is unnamed.
973 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
974 Decomp.getLSquareLoc());
977
978 // Build the variable that holds the non-decomposed object.
979 bool AddToScope = true;
980 NamedDecl *New =
981 ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
982 MultiTemplateParamsArg(), AddToScope, Bindings);
983 if (AddToScope) {
984 S->AddDecl(New);
985 CurContext->addHiddenDecl(New);
986 }
987
988 if (OpenMP().isInOpenMPDeclareTargetContext())
989 OpenMP().checkDeclIsAllowedInOpenMPTarget(nullptr, New);
990
991 return New;
992}
993
994// Check the arity of the structured bindings.
995// Create the resolved pack expr if needed.
997 QualType DecompType,
999 unsigned MemberCount) {
1000 auto BindingWithPackItr = llvm::find_if(
1001 Bindings, [](BindingDecl *D) -> bool { return D->isParameterPack(); });
1002 bool HasPack = BindingWithPackItr != Bindings.end();
1003 bool IsValid;
1004 if (!HasPack) {
1005 IsValid = Bindings.size() == MemberCount;
1006 } else {
1007 // There may not be more members than non-pack bindings.
1008 IsValid = MemberCount >= Bindings.size() - 1;
1009 }
1010
1011 if (IsValid && HasPack) {
1012 // Create the pack expr and assign it to the binding.
1013 unsigned PackSize = MemberCount - Bindings.size() + 1;
1014
1015 BindingDecl *BPack = *BindingWithPackItr;
1016 BPack->setDecomposedDecl(DD);
1017 SmallVector<ValueDecl *, 8> NestedBDs(PackSize);
1018 // Create the nested BindingDecls.
1019 for (unsigned I = 0; I < PackSize; ++I) {
1020 BindingDecl *NestedBD = BindingDecl::Create(
1021 S.Context, BPack->getDeclContext(), BPack->getLocation(),
1022 BPack->getIdentifier(), QualType());
1023 NestedBD->setDecomposedDecl(DD);
1024 NestedBDs[I] = NestedBD;
1025 }
1026
1028 S.Context.DependentTy, PackSize, /*ExpectsPackInType=*/false);
1029 auto *PackExpr = FunctionParmPackExpr::Create(
1030 S.Context, PackType, BPack, BPack->getBeginLoc(), NestedBDs);
1031 BPack->setBinding(PackType, PackExpr);
1032 }
1033
1034 if (IsValid)
1035 return false;
1036
1037 S.Diag(DD->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1038 << DecompType << (unsigned)Bindings.size() << MemberCount << MemberCount
1039 << (MemberCount < Bindings.size());
1040 return true;
1041}
1042
1045 QualType DecompType, const llvm::APSInt &NumElemsAPS, QualType ElemType,
1046 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
1047 unsigned NumElems = (unsigned)NumElemsAPS.getLimitedValue(UINT_MAX);
1048 auto *DD = cast<DecompositionDecl>(Src);
1049
1050 if (CheckBindingsCount(S, DD, DecompType, Bindings, NumElems))
1051 return true;
1052
1053 unsigned I = 0;
1054 for (auto *B : DD->flat_bindings()) {
1055 SourceLocation Loc = B->getLocation();
1056 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1057 if (E.isInvalid())
1058 return true;
1059 E = GetInit(Loc, E.get(), I++);
1060 if (E.isInvalid())
1061 return true;
1062 B->setBinding(ElemType, E.get());
1063 }
1064
1065 return false;
1066}
1067
1070 ValueDecl *Src, QualType DecompType,
1071 const llvm::APSInt &NumElems,
1072 QualType ElemType) {
1074 S, Bindings, Src, DecompType, NumElems, ElemType,
1075 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
1076 ExprResult E = S.ActOnIntegerConstant(Loc, I);
1077 if (E.isInvalid())
1078 return ExprError();
1079 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
1080 });
1081}
1082
1084 ValueDecl *Src, QualType DecompType,
1085 const ConstantArrayType *CAT) {
1086 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
1087 llvm::APSInt(CAT->getSize()),
1088 CAT->getElementType());
1089}
1090
1092 ValueDecl *Src, QualType DecompType,
1093 const VectorType *VT) {
1095 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
1097 DecompType.getQualifiers()));
1098}
1099
1102 ValueDecl *Src, QualType DecompType,
1103 const ComplexType *CT) {
1105 S, Bindings, Src, DecompType, llvm::APSInt::get(2),
1107 DecompType.getQualifiers()),
1108 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
1109 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
1110 });
1111}
1112
1115 const TemplateParameterList *Params) {
1117 llvm::raw_svector_ostream OS(SS);
1118 bool First = true;
1119 unsigned I = 0;
1120 for (auto &Arg : Args.arguments()) {
1121 if (!First)
1122 OS << ", ";
1123 Arg.getArgument().print(PrintingPolicy, OS,
1125 PrintingPolicy, Params, I));
1126 First = false;
1127 I++;
1128 }
1129 return std::string(OS.str());
1130}
1131
1132static QualType getStdTrait(Sema &S, SourceLocation Loc, StringRef Trait,
1133 TemplateArgumentListInfo &Args, unsigned DiagID) {
1134 auto DiagnoseMissing = [&] {
1135 if (DiagID)
1136 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
1137 Args, /*Params*/ nullptr);
1138 return QualType();
1139 };
1140
1141 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
1142 NamespaceDecl *Std = S.getStdNamespace();
1143 if (!Std)
1144 return DiagnoseMissing();
1145
1146 // Look up the trait itself, within namespace std. We can diagnose various
1147 // problems with this lookup even if we've been asked to not diagnose a
1148 // missing specialization, because this can only fail if the user has been
1149 // declaring their own names in namespace std or we don't support the
1150 // standard library implementation in use.
1151 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait), Loc,
1153 if (!S.LookupQualifiedName(Result, Std))
1154 return DiagnoseMissing();
1155 if (Result.isAmbiguous())
1156 return QualType();
1157
1158 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
1159 if (!TraitTD) {
1160 Result.suppressDiagnostics();
1161 NamedDecl *Found = *Result.begin();
1162 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
1163 S.Diag(Found->getLocation(), diag::note_declared_at);
1164 return QualType();
1165 }
1166
1167 // Build the template-id.
1168 QualType TraitTy = S.CheckTemplateIdType(
1169 ElaboratedTypeKeyword::None, TemplateName(TraitTD), Loc, Args,
1170 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
1171 if (TraitTy.isNull())
1172 return QualType();
1173
1174 if (!S.isCompleteType(Loc, TraitTy)) {
1175 if (DiagID)
1177 Loc, TraitTy, DiagID,
1179 TraitTD->getTemplateParameters()));
1180 return QualType();
1181 }
1182 return TraitTy;
1183}
1184
1185static bool lookupMember(Sema &S, CXXRecordDecl *RD,
1186 LookupResult &MemberLookup) {
1187 assert(RD && "specialization of class template is not a class?");
1188 S.LookupQualifiedName(MemberLookup, RD);
1189 return MemberLookup.isAmbiguous();
1190}
1191
1192static TemplateArgumentLoc
1194 uint64_t I) {
1196 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
1197}
1198
1199static TemplateArgumentLoc
1203
1204namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1205
1206static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1207 unsigned &OutSize) {
1210
1211 // Form template argument list for tuple_size<T>.
1212 TemplateArgumentListInfo Args(Loc, Loc);
1214
1215 QualType TraitTy = getStdTrait(S, Loc, "tuple_size", Args, /*DiagID=*/0);
1216 if (TraitTy.isNull())
1217 return IsTupleLike::NotTupleLike;
1218
1221
1222 // If there's no tuple_size specialization or the lookup of 'value' is empty,
1223 // it's not tuple-like.
1224 if (lookupMember(S, TraitTy->getAsCXXRecordDecl(), R) || R.empty())
1225 return IsTupleLike::NotTupleLike;
1226
1227 // If we get this far, we've committed to the tuple interpretation, but
1228 // we can still fail if there actually isn't a usable ::value.
1229
1230 struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1231 LookupResult &R;
1233 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1234 : R(R), Args(Args) {}
1235 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
1236 SourceLocation Loc) override {
1237 return S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1239 /*Params*/ nullptr);
1240 }
1241 } Diagnoser(R, Args);
1242
1243 ExprResult E =
1244 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1245 if (E.isInvalid())
1246 return IsTupleLike::Error;
1247
1248 llvm::APSInt Size;
1249 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser);
1250 if (E.isInvalid())
1251 return IsTupleLike::Error;
1252
1253 // The implementation limit is UINT_MAX-1, to allow this to be passed down on
1254 // an UnsignedOrNone.
1255 if (Size < 0 || Size >= UINT_MAX) {
1257 Size.toString(Str);
1258 S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_invalid)
1260 /*Params=*/nullptr)
1261 << StringRef(Str.data(), Str.size());
1262 return IsTupleLike::Error;
1263 }
1264
1265 OutSize = Size.getExtValue();
1266 return IsTupleLike::TupleLike;
1267}
1268
1269/// \return std::tuple_element<I, T>::type.
1271 unsigned I, QualType T) {
1272 // Form template argument list for tuple_element<I, T>.
1273 TemplateArgumentListInfo Args(Loc, Loc);
1274 Args.addArgument(
1277
1278 QualType TraitTy =
1279 getStdTrait(S, Loc, "tuple_element", Args,
1280 diag::err_decomp_decl_std_tuple_element_not_specialized);
1281 if (TraitTy.isNull())
1282 return QualType();
1283
1284 DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1285 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1286 if (lookupMember(S, TraitTy->getAsCXXRecordDecl(), R))
1287 return QualType();
1288
1289 auto *TD = R.getAsSingle<TypeDecl>();
1290 if (!TD) {
1291 R.suppressDiagnostics();
1292 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1294 /*Params*/ nullptr);
1295 if (!R.empty())
1296 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1297 return QualType();
1298 }
1299
1300 NestedNameSpecifier Qualifier(TraitTy.getTypePtr());
1301 return S.Context.getTypeDeclType(ElaboratedTypeKeyword::None, Qualifier, TD);
1302}
1303
1304namespace {
1305struct InitializingBinding {
1306 Sema &S;
1307 InitializingBinding(Sema &S, BindingDecl *BD) : S(S) {
1308 Sema::CodeSynthesisContext Ctx;
1311 Ctx.Entity = BD;
1313 }
1314 ~InitializingBinding() {
1316 }
1317};
1318}
1319
1322 VarDecl *Src, QualType DecompType,
1323 unsigned NumElems) {
1324 auto *DD = cast<DecompositionDecl>(Src);
1325 if (CheckBindingsCount(S, DD, DecompType, Bindings, NumElems))
1326 return true;
1327
1328 if (Bindings.empty())
1329 return false;
1330
1331 DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1332
1333 // [dcl.decomp]p3:
1334 // The unqualified-id get is looked up in the scope of E by class member
1335 // access lookup ...
1336 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1337 bool UseMemberGet = false;
1338 if (S.isCompleteType(Src->getLocation(), DecompType)) {
1339 if (auto *RD = DecompType->getAsCXXRecordDecl())
1340 S.LookupQualifiedName(MemberGet, RD);
1341 if (MemberGet.isAmbiguous())
1342 return true;
1343 // ... and if that finds at least one declaration that is a function
1344 // template whose first template parameter is a non-type parameter ...
1345 for (NamedDecl *D : MemberGet) {
1346 if (FunctionTemplateDecl *FTD =
1347 dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
1348 TemplateParameterList *TPL = FTD->getTemplateParameters();
1349 if (TPL->size() != 0 &&
1351 // ... the initializer is e.get<i>().
1352 UseMemberGet = true;
1353 break;
1354 }
1355 }
1356 }
1357 }
1358
1359 unsigned I = 0;
1360 for (auto *B : DD->flat_bindings()) {
1361 InitializingBinding InitContext(S, B);
1362 SourceLocation Loc = B->getLocation();
1363
1364 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1365 if (E.isInvalid())
1366 return true;
1367
1368 // e is an lvalue if the type of the entity is an lvalue reference and
1369 // an xvalue otherwise
1370 if (!Src->getType()->isLValueReferenceType())
1371 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1372 E.get(), nullptr, VK_XValue,
1374
1375 TemplateArgumentListInfo Args(Loc, Loc);
1376 Args.addArgument(
1378
1379 if (UseMemberGet) {
1380 // if [lookup of member get] finds at least one declaration, the
1381 // initializer is e.get<i-1>().
1382 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1383 CXXScopeSpec(), SourceLocation(), nullptr,
1384 MemberGet, &Args, nullptr);
1385 if (E.isInvalid())
1386 return true;
1387
1388 E = S.BuildCallExpr(nullptr, E.get(), Loc, {}, Loc);
1389 } else {
1390 // Otherwise, the initializer is get<i-1>(e), where get is looked up
1391 // in the associated namespaces.
1394 DeclarationNameInfo(GetDN, Loc), /*RequiresADL=*/true, &Args,
1396 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
1397
1398 Expr *Arg = E.get();
1399 E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc);
1400 }
1401 if (E.isInvalid())
1402 return true;
1403 Expr *Init = E.get();
1404
1405 // Given the type T designated by std::tuple_element<i - 1, E>::type
1406 QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1407 if (T.isNull())
1408 return true;
1409
1410 // C++26 [dcl.struct.bind]p7:
1411 // and the type Ui, defined as Ti if the initializer is a prvalue,
1412 // as "lvalue reference to Ti" if the initializer is an lvalue,
1413 // or as "rvalue reference to Ti" otherwise
1414 // "defined as Ti if the initializer is a prvalue" was introduced by CWG3135
1415 QualType U = E.get()->isPRValue()
1416 ? T
1417 : S.BuildReferenceType(T, E.get()->isLValue(), Loc,
1418 B->getDeclName());
1419 if (U.isNull())
1420 return true;
1421
1422 // Don't give this VarDecl a TypeSourceInfo, since this is a synthesized
1423 // entity and this type was never written in source code.
1424 auto *BindingVD =
1425 VarDecl::Create(S.Context, Src->getDeclContext(), Loc, Loc,
1426 B->getDeclName().getAsIdentifierInfo(), U,
1427 /*TInfo=*/nullptr, Src->getStorageClass());
1428 BindingVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1429 BindingVD->setTSCSpec(Src->getTSCSpec());
1430 BindingVD->setConstexpr(Src->isConstexpr());
1431 if (const auto *CIAttr = Src->getAttr<ConstInitAttr>())
1432 BindingVD->addAttr(CIAttr->clone(S.Context));
1433 BindingVD->setImplicit();
1434 if (Src->isInlineSpecified())
1435 BindingVD->setInlineSpecified();
1436 BindingVD->getLexicalDeclContext()->addHiddenDecl(BindingVD);
1437
1440 InitializationSequence Seq(S, Entity, Kind, Init);
1441 E = Seq.Perform(S, Entity, Kind, Init);
1442 if (E.isInvalid())
1443 return true;
1444 E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
1445 if (E.isInvalid())
1446 return true;
1447 BindingVD->setInit(E.get());
1449
1451 CXXScopeSpec(), DeclarationNameInfo(B->getDeclName(), Loc), BindingVD);
1452 if (E.isInvalid())
1453 return true;
1454
1455 B->setBinding(T, E.get());
1456 I++;
1457 }
1458
1459 return false;
1460}
1461
1462/// Find the base class to decompose in a built-in decomposition of a class type.
1463/// This base class search is, unfortunately, not quite like any other that we
1464/// perform anywhere else in C++.
1466 const CXXRecordDecl *RD,
1467 CXXCastPath &BasePath) {
1468 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1469 CXXBasePath &Path) {
1470 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1471 };
1472
1473 const CXXRecordDecl *ClassWithFields = nullptr;
1475 if (RD->hasDirectFields())
1476 // [dcl.decomp]p4:
1477 // Otherwise, all of E's non-static data members shall be public direct
1478 // members of E ...
1479 ClassWithFields = RD;
1480 else {
1481 // ... or of ...
1482 CXXBasePaths Paths;
1483 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1484 if (!RD->lookupInBases(BaseHasFields, Paths)) {
1485 // If no classes have fields, just decompose RD itself. (This will work
1486 // if and only if zero bindings were provided.)
1487 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
1488 }
1489
1490 CXXBasePath *BestPath = nullptr;
1491 for (auto &P : Paths) {
1492 if (!BestPath)
1493 BestPath = &P;
1494 else if (!S.Context.hasSameType(P.back().Base->getType(),
1495 BestPath->back().Base->getType())) {
1496 // ... the same ...
1497 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1498 << false << RD << BestPath->back().Base->getType()
1499 << P.back().Base->getType();
1500 return DeclAccessPair();
1501 } else if (P.Access < BestPath->Access) {
1502 BestPath = &P;
1503 }
1504 }
1505
1506 // ... unambiguous ...
1507 QualType BaseType = BestPath->back().Base->getType();
1508 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1509 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1510 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1511 return DeclAccessPair();
1512 }
1513
1514 // ... [accessible, implied by other rules] base class of E.
1515 S.CheckBaseClassAccess(Loc, BaseType, S.Context.getCanonicalTagType(RD),
1516 *BestPath, diag::err_decomp_decl_inaccessible_base);
1517 AS = BestPath->Access;
1518
1519 ClassWithFields = BaseType->getAsCXXRecordDecl();
1520 S.BuildBasePathArray(Paths, BasePath);
1521 }
1522
1523 // The above search did not check whether the selected class itself has base
1524 // classes with fields, so check that now.
1525 CXXBasePaths Paths;
1526 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1527 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1528 << (ClassWithFields == RD) << RD << ClassWithFields
1529 << Paths.front().back().Base->getType();
1530 return DeclAccessPair();
1531 }
1532
1533 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1534}
1535
1537 const CXXRecordDecl *OrigRD,
1538 QualType DecompType,
1539 DeclAccessPair BasePair) {
1540 const auto *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1541 if (!RD)
1542 return true;
1543
1544 for (auto *FD : RD->fields()) {
1545 if (FD->isUnnamedBitField())
1546 continue;
1547
1548 // All the non-static data members are required to be nameable, so they
1549 // must all have names.
1550 if (!FD->getDeclName()) {
1551 if (RD->isLambda()) {
1552 S.Diag(Loc, diag::err_decomp_decl_lambda);
1553 S.Diag(RD->getLocation(), diag::note_lambda_decl);
1554 return true;
1555 }
1556
1557 if (FD->isAnonymousStructOrUnion()) {
1558 S.Diag(Loc, diag::err_decomp_decl_anon_union_member)
1559 << DecompType << FD->getType()->isUnionType();
1560 S.Diag(FD->getLocation(), diag::note_declared_at);
1561 return true;
1562 }
1563
1564 // FIXME: Are there any other ways we could have an anonymous member?
1565 }
1566 // The field must be accessible in the context of the structured binding.
1567 // We already checked that the base class is accessible.
1568 // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1569 // const_cast here.
1571 Loc, const_cast<CXXRecordDecl *>(OrigRD),
1573 BasePair.getAccess(), FD->getAccess())));
1574 }
1575 return false;
1576}
1577
1579 ValueDecl *Src, QualType DecompType,
1580 const CXXRecordDecl *OrigRD) {
1581 if (S.RequireCompleteType(Src->getLocation(), DecompType,
1582 diag::err_incomplete_type))
1583 return true;
1584
1585 CXXCastPath BasePath;
1586 DeclAccessPair BasePair =
1587 findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1588 const auto *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1589 if (!RD)
1590 return true;
1591 QualType BaseType = S.Context.getQualifiedType(
1592 S.Context.getCanonicalTagType(RD), DecompType.getQualifiers());
1593
1594 auto *DD = cast<DecompositionDecl>(Src);
1595 unsigned NumFields = llvm::count_if(
1596 RD->fields(), [](FieldDecl *FD) { return !FD->isUnnamedBitField(); });
1597 if (CheckBindingsCount(S, DD, DecompType, Bindings, NumFields))
1598 return true;
1599
1600 // all of E's non-static data members shall be [...] well-formed
1601 // when named as e.name in the context of the structured binding,
1602 // E shall not have an anonymous union member, ...
1603 auto FlatBindings = DD->flat_bindings();
1604 assert(llvm::range_size(FlatBindings) == NumFields);
1605 auto FlatBindingsItr = FlatBindings.begin();
1606
1607 if (CheckMemberDecompositionFields(S, Src->getLocation(), OrigRD, DecompType,
1608 BasePair))
1609 return true;
1610
1611 for (auto *FD : RD->fields()) {
1612 if (FD->isUnnamedBitField())
1613 continue;
1614
1615 // We have a real field to bind.
1616 assert(FlatBindingsItr != FlatBindings.end());
1617 BindingDecl *B = *(FlatBindingsItr++);
1618 SourceLocation Loc = B->getLocation();
1619
1620 // Initialize the binding to Src.FD.
1621 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1622 if (E.isInvalid())
1623 return true;
1624 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1625 VK_LValue, &BasePath);
1626 if (E.isInvalid())
1627 return true;
1628 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1629 CXXScopeSpec(), FD,
1631 DeclarationNameInfo(FD->getDeclName(), Loc));
1632 if (E.isInvalid())
1633 return true;
1634
1635 // If the type of the member is T, the referenced type is cv T, where cv is
1636 // the cv-qualification of the decomposition expression.
1637 //
1638 // FIXME: We resolve a defect here: if the field is mutable, we do not add
1639 // 'const' to the type of the field.
1640 Qualifiers Q = DecompType.getQualifiers();
1641 if (FD->isMutable())
1642 Q.removeConst();
1643 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1644 }
1645
1646 return false;
1647}
1648
1650 QualType DecompType = DD->getType();
1651
1652 // If the type of the decomposition is dependent, then so is the type of
1653 // each binding.
1654 if (DecompType->isDependentType()) {
1655 // Note that all of the types are still Null or PackExpansionType.
1656 for (auto *B : DD->bindings()) {
1657 // Do not overwrite any pack type.
1658 if (B->getType().isNull())
1659 B->setType(Context.DependentTy);
1660 }
1661 return;
1662 }
1663
1664 DecompType = DecompType.getNonReferenceType();
1666
1667 // C++1z [dcl.decomp]/2:
1668 // If E is an array type [...]
1669 // As an extension, we also support decomposition of built-in complex and
1670 // vector types.
1671 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1672 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1673 DD->setInvalidDecl();
1674 return;
1675 }
1676 if (auto *VT = DecompType->getAs<VectorType>()) {
1677 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1678 DD->setInvalidDecl();
1679 return;
1680 }
1681 if (auto *CT = DecompType->getAs<ComplexType>()) {
1682 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1683 DD->setInvalidDecl();
1684 return;
1685 }
1686
1687 // C++1z [dcl.decomp]/3:
1688 // if the expression std::tuple_size<E>::value is a well-formed integral
1689 // constant expression, [...]
1690 unsigned TupleSize;
1691 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1692 case IsTupleLike::Error:
1693 DD->setInvalidDecl();
1694 return;
1695
1696 case IsTupleLike::TupleLike:
1697 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1698 DD->setInvalidDecl();
1699 return;
1700
1701 case IsTupleLike::NotTupleLike:
1702 break;
1703 }
1704
1705 // C++1z [dcl.dcl]/8:
1706 // [E shall be of array or non-union class type]
1707 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1708 if (!RD || RD->isUnion()) {
1709 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1710 << DD << !RD << DecompType;
1711 DD->setInvalidDecl();
1712 return;
1713 }
1714
1715 // C++1z [dcl.decomp]/4:
1716 // all of E's non-static data members shall be [...] direct members of
1717 // E or of the same unambiguous public base class of E, ...
1718 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1719 DD->setInvalidDecl();
1720}
1721
1723 SourceLocation Loc) {
1724 const ASTContext &Ctx = getASTContext();
1725 assert(!T->isDependentType());
1726
1727 Qualifiers Quals;
1728 QualType Unqual = Context.getUnqualifiedArrayType(T, Quals);
1729 Quals.removeCVRQualifiers();
1730 T = Context.getQualifiedType(Unqual, Quals);
1731
1732 if (auto *CAT = Ctx.getAsConstantArrayType(T))
1733 return static_cast<unsigned>(CAT->getSize().getZExtValue());
1734 if (auto *VT = T->getAs<VectorType>())
1735 return VT->getNumElements();
1736 if (T->getAs<ComplexType>())
1737 return 2u;
1738
1739 unsigned TupleSize;
1740 switch (isTupleLike(*this, Loc, T, TupleSize)) {
1741 case IsTupleLike::Error:
1742 return std::nullopt;
1743 case IsTupleLike::TupleLike:
1744 return TupleSize;
1745 case IsTupleLike::NotTupleLike:
1746 break;
1747 }
1748
1749 const CXXRecordDecl *OrigRD = T->getAsCXXRecordDecl();
1750 if (!OrigRD || OrigRD->isUnion())
1751 return std::nullopt;
1752
1753 if (RequireCompleteType(Loc, T, diag::err_incomplete_type))
1754 return std::nullopt;
1755
1756 CXXCastPath BasePath;
1757 DeclAccessPair BasePair =
1758 findDecomposableBaseClass(*this, Loc, OrigRD, BasePath);
1759 const auto *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1760 if (!RD)
1761 return std::nullopt;
1762
1763 unsigned NumFields = llvm::count_if(
1764 RD->fields(), [](FieldDecl *FD) { return !FD->isUnnamedBitField(); });
1765
1766 if (CheckMemberDecompositionFields(*this, Loc, OrigRD, T, BasePair))
1767 return std::nullopt;
1768
1769 return NumFields;
1770}
1771
1773 // Shortcut if exceptions are disabled.
1774 if (!getLangOpts().CXXExceptions)
1775 return;
1776
1777 assert(Context.hasSameType(New->getType(), Old->getType()) &&
1778 "Should only be called if types are otherwise the same.");
1779
1780 QualType NewType = New->getType();
1781 QualType OldType = Old->getType();
1782
1783 // We're only interested in pointers and references to functions, as well
1784 // as pointers to member functions.
1785 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1786 NewType = R->getPointeeType();
1787 OldType = OldType->castAs<ReferenceType>()->getPointeeType();
1788 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1789 NewType = P->getPointeeType();
1790 OldType = OldType->castAs<PointerType>()->getPointeeType();
1791 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1792 NewType = M->getPointeeType();
1793 OldType = OldType->castAs<MemberPointerType>()->getPointeeType();
1794 }
1795
1796 if (!NewType->isFunctionProtoType())
1797 return;
1798
1799 // There's lots of special cases for functions. For function pointers, system
1800 // libraries are hopefully not as broken so that we don't need these
1801 // workarounds.
1803 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1804 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1805 New->setInvalidDecl();
1806 }
1807}
1808
1809/// CheckCXXDefaultArguments - Verify that the default arguments for a
1810/// function declaration are well-formed according to C++
1811/// [dcl.fct.default].
1813 // This checking doesn't make sense for explicit specializations; their
1814 // default arguments are determined by the declaration we're specializing,
1815 // not by FD.
1817 return;
1818 if (auto *FTD = FD->getDescribedFunctionTemplate())
1819 if (FTD->isMemberSpecialization())
1820 return;
1821
1822 unsigned NumParams = FD->getNumParams();
1823 unsigned ParamIdx = 0;
1824
1825 // Find first parameter with a default argument
1826 for (; ParamIdx < NumParams; ++ParamIdx) {
1827 ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1828 if (Param->hasDefaultArg())
1829 break;
1830 }
1831
1832 // C++20 [dcl.fct.default]p4:
1833 // In a given function declaration, each parameter subsequent to a parameter
1834 // with a default argument shall have a default argument supplied in this or
1835 // a previous declaration, unless the parameter was expanded from a
1836 // parameter pack, or shall be a function parameter pack.
1837 for (++ParamIdx; ParamIdx < NumParams; ++ParamIdx) {
1838 ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1839 if (Param->hasDefaultArg() || Param->isParameterPack() ||
1841 CurrentInstantiationScope->isLocalPackExpansion(Param)))
1842 continue;
1843 if (Param->isInvalidDecl())
1844 /* We already complained about this parameter. */;
1845 else if (Param->getIdentifier())
1846 Diag(Param->getLocation(), diag::err_param_default_argument_missing_name)
1847 << Param->getIdentifier();
1848 else
1849 Diag(Param->getLocation(), diag::err_param_default_argument_missing);
1850 }
1851}
1852
1853/// Check that the given type is a literal type. Issue a diagnostic if not,
1854/// if Kind is Diagnose.
1855/// \return \c true if a problem has been found (and optionally diagnosed).
1856template <typename... Ts>
1858 SourceLocation Loc, QualType T, unsigned DiagID,
1859 Ts &&...DiagArgs) {
1860 if (T->isDependentType())
1861 return false;
1862
1863 switch (Kind) {
1865 return SemaRef.RequireLiteralType(Loc, T, DiagID,
1866 std::forward<Ts>(DiagArgs)...);
1867
1869 return !T->isLiteralType(SemaRef.Context);
1870 }
1871
1872 llvm_unreachable("unknown CheckConstexprKind");
1873}
1874
1875/// Determine whether a destructor cannot be constexpr due to
1877 const CXXDestructorDecl *DD,
1879 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1880 "this check is obsolete for C++23");
1881 auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) {
1882 const CXXRecordDecl *RD =
1883 T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1884 if (!RD || RD->hasConstexprDestructor())
1885 return true;
1886
1888 SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject)
1889 << static_cast<int>(DD->getConstexprKind()) << !FD
1890 << (FD ? FD->getDeclName() : DeclarationName()) << T;
1891 SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject)
1892 << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T;
1893 }
1894 return false;
1895 };
1896
1897 const CXXRecordDecl *RD = DD->getParent();
1898 for (const CXXBaseSpecifier &B : RD->bases())
1899 if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr))
1900 return false;
1901 for (const FieldDecl *FD : RD->fields())
1902 if (!Check(FD->getLocation(), FD->getType(), FD))
1903 return false;
1904 return true;
1905}
1906
1907/// Check whether a function's parameter types are all literal types. If so,
1908/// return true. If not, produce a suitable diagnostic and return false.
1910 const FunctionDecl *FD,
1912 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1913 "this check is obsolete for C++23");
1914 unsigned ArgIndex = 0;
1915 const auto *FT = FD->getType()->castAs<FunctionProtoType>();
1916 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1917 e = FT->param_type_end();
1918 i != e; ++i, ++ArgIndex) {
1919 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1920 assert(PD && "null in a parameter list");
1921 SourceLocation ParamLoc = PD->getLocation();
1922 if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i,
1923 diag::err_constexpr_non_literal_param, ArgIndex + 1,
1925 FD->isConsteval()))
1926 return false;
1927 }
1928 return true;
1929}
1930
1931/// Check whether a function's return type is a literal type. If so, return
1932/// true. If not, produce a suitable diagnostic and return false.
1933static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD,
1935 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1936 "this check is obsolete for C++23");
1937 if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(),
1938 diag::err_constexpr_non_literal_return,
1939 FD->isConsteval()))
1940 return false;
1941 return true;
1942}
1943
1944/// Get diagnostic %select index for tag kind for
1945/// record diagnostic message.
1946/// WARNING: Indexes apply to particular diagnostics only!
1947///
1948/// \returns diagnostic %select index.
1950 switch (Tag) {
1952 return 0;
1954 return 1;
1955 case TagTypeKind::Class:
1956 return 2;
1957 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1958 }
1959}
1960
1961static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
1962 Stmt *Body,
1964static bool CheckConstexprMissingReturn(Sema &SemaRef, const FunctionDecl *Dcl);
1965
1967 CheckConstexprKind Kind) {
1968 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1969 if (!getLangOpts().CPlusPlus26 && MD && MD->isInstance()) {
1970 // C++11 [dcl.constexpr]p4:
1971 // The definition of a constexpr constructor shall satisfy the following
1972 // constraints:
1973 // - the class shall not have any virtual base classes;
1974 //
1975 // FIXME: This only applies to constructors and destructors, not arbitrary
1976 // member functions.
1977 const CXXRecordDecl *RD = MD->getParent();
1978 if (RD->getNumVBases()) {
1980 return false;
1981
1982 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1983 << isa<CXXConstructorDecl>(NewFD)
1985 for (const auto &I : RD->vbases())
1986 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1987 << I.getSourceRange();
1988 return false;
1989 }
1990 }
1991
1992 if (!isa<CXXConstructorDecl>(NewFD)) {
1993 // C++11 [dcl.constexpr]p3:
1994 // The definition of a constexpr function shall satisfy the following
1995 // constraints:
1996 // - it shall not be virtual; (removed in C++20)
1997 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1998 if (Method && Method->isVirtual()) {
1999 if (getLangOpts().CPlusPlus20) {
2000 if (Kind == CheckConstexprKind::Diagnose)
2001 Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
2002 } else {
2004 return false;
2005
2006 Method = Method->getCanonicalDecl();
2007 Diag(Method->getLocation(), diag::err_constexpr_virtual);
2008
2009 // If it's not obvious why this function is virtual, find an overridden
2010 // function which uses the 'virtual' keyword.
2011 const CXXMethodDecl *WrittenVirtual = Method;
2012 while (!WrittenVirtual->isVirtualAsWritten())
2013 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
2014 if (WrittenVirtual != Method)
2015 Diag(WrittenVirtual->getLocation(),
2016 diag::note_overridden_virtual_function);
2017 return false;
2018 }
2019 }
2020
2021 // - its return type shall be a literal type; (removed in C++23)
2022 if (!getLangOpts().CPlusPlus23 &&
2023 !CheckConstexprReturnType(*this, NewFD, Kind))
2024 return false;
2025 }
2026
2027 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) {
2028 // A destructor can be constexpr only if the defaulted destructor could be;
2029 // we don't need to check the members and bases if we already know they all
2030 // have constexpr destructors. (removed in C++23)
2031 if (!getLangOpts().CPlusPlus23 &&
2032 !Dtor->getParent()->defaultedDestructorIsConstexpr()) {
2034 return false;
2035 if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind))
2036 return false;
2037 }
2038 }
2039
2040 // - each of its parameter types shall be a literal type; (removed in C++23)
2041 if (!getLangOpts().CPlusPlus23 &&
2042 !CheckConstexprParameterTypes(*this, NewFD, Kind))
2043 return false;
2044
2045 Stmt *Body = NewFD->getBody();
2046 assert(Body &&
2047 "CheckConstexprFunctionDefinition called on function with no body");
2048 return CheckConstexprFunctionBody(*this, NewFD, Body, Kind);
2049}
2050
2051/// Check the given declaration statement is legal within a constexpr function
2052/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
2053///
2054/// \return true if the body is OK (maybe only as an extension), false if we
2055/// have diagnosed a problem.
2056static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
2057 DeclStmt *DS, SourceLocation &Cxx1yLoc,
2059 // C++11 [dcl.constexpr]p3 and p4:
2060 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
2061 // contain only
2062 for (const auto *DclIt : DS->decls()) {
2063 switch (DclIt->getKind()) {
2064 case Decl::StaticAssert:
2065 case Decl::Using:
2066 case Decl::UsingShadow:
2067 case Decl::UsingDirective:
2068 case Decl::UnresolvedUsingTypename:
2069 case Decl::UnresolvedUsingValue:
2070 case Decl::UsingEnum:
2071 // - static_assert-declarations
2072 // - using-declarations,
2073 // - using-directives,
2074 // - using-enum-declaration
2075 continue;
2076
2077 case Decl::CXXExpansionStmt:
2078 continue;
2079
2080 case Decl::Typedef:
2081 case Decl::TypeAlias: {
2082 // - typedef declarations and alias-declarations that do not define
2083 // classes or enumerations,
2084 const auto *TN = cast<TypedefNameDecl>(DclIt);
2085 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
2086 // Don't allow variably-modified types in constexpr functions.
2088 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
2089 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
2090 << TL.getSourceRange() << TL.getType()
2092 }
2093 return false;
2094 }
2095 continue;
2096 }
2097
2098 case Decl::Enum:
2099 case Decl::CXXRecord:
2100 // C++1y allows types to be defined, not just declared.
2101 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) {
2103 SemaRef.DiagCompat(DS->getBeginLoc(),
2104 diag_compat::constexpr_type_definition)
2106 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
2107 return false;
2108 }
2109 }
2110 continue;
2111
2112 case Decl::EnumConstant:
2113 case Decl::IndirectField:
2114 case Decl::ParmVar:
2115 // These can only appear with other declarations which are banned in
2116 // C++11 and permitted in C++1y, so ignore them.
2117 continue;
2118
2119 case Decl::Var:
2120 case Decl::Decomposition: {
2121 // C++1y [dcl.constexpr]p3 allows anything except:
2122 // a definition of a variable of non-literal type or of static or
2123 // thread storage duration or [before C++2a] for which no
2124 // initialization is performed.
2125 const auto *VD = cast<VarDecl>(DclIt);
2126 if (VD->isThisDeclarationADefinition()) {
2127 if (VD->isStaticLocal()) {
2129 SemaRef.DiagCompat(VD->getLocation(),
2130 diag_compat::constexpr_static_var)
2132 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
2133 } else if (!SemaRef.getLangOpts().CPlusPlus23) {
2134 return false;
2135 }
2136 }
2137 if (SemaRef.LangOpts.CPlusPlus23) {
2138 CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(),
2139 diag::warn_cxx20_compat_constexpr_var,
2141 } else if (CheckLiteralType(
2142 SemaRef, Kind, VD->getLocation(), VD->getType(),
2143 diag::err_constexpr_local_var_non_literal_type,
2145 return false;
2146 }
2147 if (!VD->getType()->isDependentType() &&
2148 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
2150 SemaRef.DiagCompat(VD->getLocation(),
2151 diag_compat::constexpr_local_var_no_init)
2153 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2154 return false;
2155 }
2156 continue;
2157 }
2158 }
2160 SemaRef.DiagCompat(VD->getLocation(), diag_compat::constexpr_local_var)
2162 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
2163 return false;
2164 }
2165 continue;
2166 }
2167
2168 case Decl::NamespaceAlias:
2169 case Decl::Function:
2170 // These are disallowed in C++11 and permitted in C++1y. Allow them
2171 // everywhere as an extension.
2172 if (!Cxx1yLoc.isValid())
2173 Cxx1yLoc = DS->getBeginLoc();
2174 continue;
2175
2176 default:
2178 SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2179 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2180 }
2181 return false;
2182 }
2183 }
2184
2185 return true;
2186}
2187
2188/// Check that the given field is initialized within a constexpr constructor.
2189///
2190/// \param Dcl The constexpr constructor being checked.
2191/// \param Field The field being checked. This may be a member of an anonymous
2192/// struct or union nested within the class being checked.
2193/// \param Inits All declarations, including anonymous struct/union members and
2194/// indirect members, for which any initialization was provided.
2195/// \param Diagnosed Whether we've emitted the error message yet. Used to attach
2196/// multiple notes for different members to the same error.
2197/// \param Kind Whether we're diagnosing a constructor as written or determining
2198/// whether the formal requirements are satisfied.
2199/// \return \c false if we're checking for validity and the constructor does
2200/// not satisfy the requirements on a constexpr constructor.
2202 const FunctionDecl *Dcl,
2203 FieldDecl *Field,
2205 bool &Diagnosed,
2207 // In C++20 onwards, there's nothing to check for validity.
2209 SemaRef.getLangOpts().CPlusPlus20)
2210 return true;
2211
2212 if (Field->isInvalidDecl())
2213 return true;
2214
2215 if (Field->isUnnamedBitField())
2216 return true;
2217
2218 // Anonymous unions with no variant members and empty anonymous structs do not
2219 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
2220 // indirect fields don't need initializing.
2221 if (Field->isAnonymousStructOrUnion() &&
2222 (Field->getType()->isUnionType()
2223 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
2224 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
2225 return true;
2226
2227 if (!Inits.count(Field)) {
2229 if (!Diagnosed) {
2230 SemaRef.DiagCompat(Dcl->getLocation(),
2231 diag_compat::constexpr_ctor_missing_init);
2232 Diagnosed = true;
2233 }
2234 SemaRef.Diag(Field->getLocation(),
2235 diag::note_constexpr_ctor_missing_init);
2236 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2237 return false;
2238 }
2239 } else if (Field->isAnonymousStructOrUnion()) {
2240 const auto *RD = Field->getType()->castAsRecordDecl();
2241 for (auto *I : RD->fields())
2242 // If an anonymous union contains an anonymous struct of which any member
2243 // is initialized, all members must be initialized.
2244 if (!RD->isUnion() || Inits.count(I))
2245 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2246 Kind))
2247 return false;
2248 }
2249 return true;
2250}
2251
2252/// Check the provided statement is allowed in a constexpr function
2253/// definition.
2254static bool
2257 SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
2258 SourceLocation &Cxx2bLoc,
2260 // - its function-body shall be [...] a compound-statement that contains only
2261 switch (S->getStmtClass()) {
2262 case Stmt::NullStmtClass:
2263 // - null statements,
2264 return true;
2265
2266 case Stmt::DeclStmtClass:
2267 // - static_assert-declarations
2268 // - using-declarations,
2269 // - using-directives,
2270 // - typedef declarations and alias-declarations that do not define
2271 // classes or enumerations,
2272 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind))
2273 return false;
2274 return true;
2275
2276 case Stmt::ReturnStmtClass:
2277 // - and exactly one return statement;
2278 if (isa<CXXConstructorDecl>(Dcl)) {
2279 // C++1y allows return statements in constexpr constructors.
2280 if (!Cxx1yLoc.isValid())
2281 Cxx1yLoc = S->getBeginLoc();
2282 return true;
2283 }
2284
2285 ReturnStmts.push_back(S->getBeginLoc());
2286 return true;
2287
2288 case Stmt::AttributedStmtClass:
2289 // Attributes on a statement don't affect its formal kind and hence don't
2290 // affect its validity in a constexpr function.
2292 SemaRef, Dcl, cast<AttributedStmt>(S)->getSubStmt(), ReturnStmts,
2293 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind);
2294
2295 case Stmt::CompoundStmtClass: {
2296 // C++1y allows compound-statements.
2297 if (!Cxx1yLoc.isValid())
2298 Cxx1yLoc = S->getBeginLoc();
2299
2300 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
2301 for (auto *BodyIt : CompStmt->body()) {
2302 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
2303 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2304 return false;
2305 }
2306 return true;
2307 }
2308
2309 case Stmt::IfStmtClass: {
2310 // C++1y allows if-statements.
2311 if (!Cxx1yLoc.isValid())
2312 Cxx1yLoc = S->getBeginLoc();
2313
2314 IfStmt *If = cast<IfStmt>(S);
2315 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
2316 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2317 return false;
2318 if (If->getElse() &&
2319 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
2320 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2321 return false;
2322 return true;
2323 }
2324
2325 case Stmt::WhileStmtClass:
2326 case Stmt::DoStmtClass:
2327 case Stmt::ForStmtClass:
2328 case Stmt::CXXForRangeStmtClass:
2329 case Stmt::ContinueStmtClass:
2330 // C++1y allows all of these. We don't allow them as extensions in C++11,
2331 // because they don't make sense without variable mutation.
2332 if (!SemaRef.getLangOpts().CPlusPlus14)
2333 break;
2334 if (!Cxx1yLoc.isValid())
2335 Cxx1yLoc = S->getBeginLoc();
2336 for (Stmt *SubStmt : S->children()) {
2337 if (SubStmt &&
2338 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2339 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2340 return false;
2341 }
2342 return true;
2343
2344 case Stmt::SwitchStmtClass:
2345 case Stmt::CaseStmtClass:
2346 case Stmt::DefaultStmtClass:
2347 case Stmt::BreakStmtClass:
2348 // C++1y allows switch-statements, and since they don't need variable
2349 // mutation, we can reasonably allow them in C++11 as an extension.
2350 if (!Cxx1yLoc.isValid())
2351 Cxx1yLoc = S->getBeginLoc();
2352 for (Stmt *SubStmt : S->children()) {
2353 if (SubStmt &&
2354 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2355 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2356 return false;
2357 }
2358 return true;
2359
2360 case Stmt::LabelStmtClass:
2361 case Stmt::GotoStmtClass:
2362 case Stmt::IndirectGotoStmtClass:
2363 if (Cxx2bLoc.isInvalid())
2364 Cxx2bLoc = S->getBeginLoc();
2365 for (Stmt *SubStmt : S->children()) {
2366 if (SubStmt &&
2367 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2368 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2369 return false;
2370 }
2371 return true;
2372
2373 case Stmt::GCCAsmStmtClass:
2374 case Stmt::MSAsmStmtClass:
2375 // C++2a allows inline assembly statements.
2376 case Stmt::CXXTryStmtClass:
2377 if (Cxx2aLoc.isInvalid())
2378 Cxx2aLoc = S->getBeginLoc();
2379 for (Stmt *SubStmt : S->children()) {
2380 if (SubStmt &&
2381 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2382 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2383 return false;
2384 }
2385 return true;
2386
2387 case Stmt::CXXCatchStmtClass:
2388 // Do not bother checking the language mode (already covered by the
2389 // try block check).
2391 SemaRef, Dcl, cast<CXXCatchStmt>(S)->getHandlerBlock(), ReturnStmts,
2392 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2393 return false;
2394 return true;
2395
2396 default:
2397 if (!isa<Expr>(S))
2398 break;
2399
2400 // C++1y allows expression-statements.
2401 if (!Cxx1yLoc.isValid())
2402 Cxx1yLoc = S->getBeginLoc();
2403 return true;
2404 }
2405
2407 SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2408 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2409 }
2410 return false;
2411}
2412
2413/// Check the body for the given constexpr function declaration only contains
2414/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
2415///
2416/// \return true if the body is OK, false if we have found or diagnosed a
2417/// problem.
2418static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
2419 Stmt *Body,
2422
2423 if (isa<CXXTryStmt>(Body)) {
2424 // C++11 [dcl.constexpr]p3:
2425 // The definition of a constexpr function shall satisfy the following
2426 // constraints: [...]
2427 // - its function-body shall be = delete, = default, or a
2428 // compound-statement
2429 //
2430 // C++11 [dcl.constexpr]p4:
2431 // In the definition of a constexpr constructor, [...]
2432 // - its function-body shall not be a function-try-block;
2433 //
2434 // This restriction is lifted in C++2a, as long as inner statements also
2435 // apply the general constexpr rules.
2436 switch (Kind) {
2438 if (!SemaRef.getLangOpts().CPlusPlus20)
2439 return false;
2440 break;
2441
2443 SemaRef.DiagCompat(Body->getBeginLoc(),
2444 diag_compat::constexpr_function_try_block)
2446 break;
2447 }
2448 }
2449
2450 // - its function-body shall be [...] a compound-statement that contains only
2451 // [... list of cases ...]
2452 //
2453 // Note that walking the children here is enough to properly check for
2454 // CompoundStmt and CXXTryStmt body.
2455 SourceLocation Cxx1yLoc, Cxx2aLoc, Cxx2bLoc;
2456 for (Stmt *SubStmt : Body->children()) {
2457 if (SubStmt &&
2458 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2459 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2460 return false;
2461 }
2462
2464 // If this is only valid as an extension, report that we don't satisfy the
2465 // constraints of the current language.
2466 if ((Cxx2bLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus23) ||
2467 (Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) ||
2468 (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
2469 return false;
2470 } else if (Cxx2bLoc.isValid()) {
2471 SemaRef.DiagCompat(Cxx2bLoc, diag_compat::cxx23_constexpr_body_invalid_stmt)
2473 } else if (Cxx2aLoc.isValid()) {
2474 SemaRef.DiagCompat(Cxx2aLoc, diag_compat::cxx20_constexpr_body_invalid_stmt)
2476 } else if (Cxx1yLoc.isValid()) {
2477 SemaRef.DiagCompat(Cxx1yLoc, diag_compat::cxx14_constexpr_body_invalid_stmt)
2479 }
2480
2482 = dyn_cast<CXXConstructorDecl>(Dcl)) {
2483 const CXXRecordDecl *RD = Constructor->getParent();
2484 // DR1359:
2485 // - every non-variant non-static data member and base class sub-object
2486 // shall be initialized;
2487 // DR1460:
2488 // - if the class is a union having variant members, exactly one of them
2489 // shall be initialized;
2490 if (RD->isUnion()) {
2491 if (Constructor->getNumCtorInitializers() == 0 &&
2492 RD->hasVariantMembers()) {
2494 SemaRef.DiagCompat(Dcl->getLocation(),
2495 diag_compat::constexpr_union_ctor_no_init);
2496 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2497 return false;
2498 }
2499 }
2500 } else if (!Constructor->isDependentContext() &&
2501 !Constructor->isDelegatingConstructor()) {
2502 // Skip detailed checking if we have enough initializers, and we would
2503 // allow at most one initializer per member.
2504 bool AnyAnonStructUnionMembers = false;
2505 unsigned Fields = 0;
2507 E = RD->field_end(); I != E; ++I, ++Fields) {
2508 if (I->isAnonymousStructOrUnion()) {
2509 AnyAnonStructUnionMembers = true;
2510 break;
2511 }
2512 }
2513 // DR1460:
2514 // - if the class is a union-like class, but is not a union, for each of
2515 // its anonymous union members having variant members, exactly one of
2516 // them shall be initialized;
2517 if (AnyAnonStructUnionMembers ||
2518 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2519 // Check initialization of non-static data members. Base classes are
2520 // always initialized so do not need to be checked. Dependent bases
2521 // might not have initializers in the member initializer list.
2523 for (const auto *I: Constructor->inits()) {
2524 if (FieldDecl *FD = I->getMember())
2525 Inits.insert(FD);
2526 else if (IndirectFieldDecl *ID = I->getIndirectMember())
2527 Inits.insert(ID->chain_begin(), ID->chain_end());
2528 }
2529
2530 bool Diagnosed = false;
2531 for (auto *I : RD->fields())
2532 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2533 Kind))
2534 return false;
2535 }
2536 }
2537 } else {
2538 if (ReturnStmts.empty()) {
2539 switch (Kind) {
2541 if (!CheckConstexprMissingReturn(SemaRef, Dcl))
2542 return false;
2543 break;
2544
2546 // The formal requirements don't include this rule in C++14, even
2547 // though the "must be able to produce a constant expression" rules
2548 // still imply it in some cases.
2549 if (!SemaRef.getLangOpts().CPlusPlus14)
2550 return false;
2551 break;
2552 }
2553 } else if (ReturnStmts.size() > 1) {
2554 switch (Kind) {
2556 SemaRef.DiagCompat(ReturnStmts.back(),
2557 diag_compat::constexpr_body_multiple_return);
2558 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2559 SemaRef.Diag(ReturnStmts[I],
2560 diag::note_constexpr_body_previous_return);
2561 break;
2562
2564 if (!SemaRef.getLangOpts().CPlusPlus14)
2565 return false;
2566 break;
2567 }
2568 }
2569 }
2570
2571 // C++11 [dcl.constexpr]p5:
2572 // if no function argument values exist such that the function invocation
2573 // substitution would produce a constant expression, the program is
2574 // ill-formed; no diagnostic required.
2575 // C++11 [dcl.constexpr]p3:
2576 // - every constructor call and implicit conversion used in initializing the
2577 // return value shall be one of those allowed in a constant expression.
2578 // C++11 [dcl.constexpr]p4:
2579 // - every constructor involved in initializing non-static data members and
2580 // base class sub-objects shall be a constexpr constructor.
2581 //
2582 // Note that this rule is distinct from the "requirements for a constexpr
2583 // function", so is not checked in CheckValid mode. Because the check for
2584 // constexpr potential is expensive, skip the check if the diagnostic is
2585 // disabled, the function is declared in a system header, or we're in C++23
2586 // or later mode (see https://wg21.link/P2448).
2587 bool SkipCheck =
2588 !SemaRef.getLangOpts().CheckConstexprFunctionBodies ||
2589 SemaRef.getSourceManager().isInSystemHeader(Dcl->getLocation()) ||
2590 SemaRef.getDiagnostics().isIgnored(
2591 diag::ext_constexpr_function_never_constant_expr, Dcl->getLocation());
2593 if (Kind == Sema::CheckConstexprKind::Diagnose && !SkipCheck &&
2594 !Expr::isPotentialConstantExpr(Dcl, Diags)) {
2595 SemaRef.Diag(Dcl->getLocation(),
2596 diag::ext_constexpr_function_never_constant_expr)
2597 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval()
2598 << Dcl->getNameInfo().getSourceRange();
2599 for (const auto &Diag : Diags)
2600 SemaRef.Diag(Diag.first, Diag.second);
2601 // Don't return false here: we allow this for compatibility in
2602 // system headers.
2603 }
2604
2605 return true;
2606}
2607
2609 const FunctionDecl *Dcl) {
2610 bool IsVoidOrDependentType = Dcl->getReturnType()->isVoidType() ||
2612 // Skip emitting a missing return error diagnostic for non-void functions
2613 // since C++23 no longer mandates constexpr functions to yield constant
2614 // expressions.
2615 if (SemaRef.getLangOpts().CPlusPlus23 && !IsVoidOrDependentType)
2616 return true;
2617
2618 // C++14 doesn't require constexpr functions to contain a 'return'
2619 // statement. We still do, unless the return type might be void, because
2620 // otherwise if there's no return statement, the function cannot
2621 // be used in a core constant expression.
2622 bool OK = SemaRef.getLangOpts().CPlusPlus14 && IsVoidOrDependentType;
2623 SemaRef.Diag(Dcl->getLocation(),
2624 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2625 : diag::err_constexpr_body_no_return)
2626 << Dcl->isConsteval();
2627 return OK;
2628}
2629
2631 FunctionDecl *FD, const sema::FunctionScopeInfo *FSI) {
2633 return true;
2637 auto it = UndefinedButUsed.find(FD->getCanonicalDecl());
2638 if (it != UndefinedButUsed.end()) {
2639 Diag(it->second, diag::err_immediate_function_used_before_definition)
2640 << it->first;
2641 Diag(FD->getLocation(), diag::note_defined_here) << FD;
2642 if (FD->isImmediateFunction() && !FD->isConsteval())
2644 return false;
2645 }
2646 }
2647 return true;
2648}
2649
2651 assert(FD->isImmediateEscalating() && !FD->isConsteval() &&
2652 "expected an immediate function");
2653 assert(FD->hasBody() && "expected the function to have a body");
2654 struct ImmediateEscalatingExpressionsVisitor : DynamicRecursiveASTVisitor {
2655 Sema &SemaRef;
2656
2657 const FunctionDecl *ImmediateFn;
2658 bool ImmediateFnIsConstructor;
2659 CXXConstructorDecl *CurrentConstructor = nullptr;
2660 CXXCtorInitializer *CurrentInit = nullptr;
2661
2662 ImmediateEscalatingExpressionsVisitor(Sema &SemaRef, FunctionDecl *FD)
2663 : SemaRef(SemaRef), ImmediateFn(FD),
2664 ImmediateFnIsConstructor(isa<CXXConstructorDecl>(FD)) {
2665 ShouldVisitImplicitCode = true;
2666 ShouldVisitLambdaBody = false;
2667 }
2668
2669 void Diag(const Expr *E, const FunctionDecl *Fn, bool IsCall) {
2670 SourceLocation Loc = E->getBeginLoc();
2671 SourceRange Range = E->getSourceRange();
2672 if (CurrentConstructor && CurrentInit) {
2673 Loc = CurrentConstructor->getLocation();
2674 Range = CurrentInit->isWritten() ? CurrentInit->getSourceRange()
2675 : SourceRange();
2676 }
2677
2678 FieldDecl* InitializedField = CurrentInit ? CurrentInit->getAnyMember() : nullptr;
2679
2680 SemaRef.Diag(Loc, diag::note_immediate_function_reason)
2681 << ImmediateFn << Fn << Fn->isConsteval() << IsCall
2682 << isa<CXXConstructorDecl>(Fn) << ImmediateFnIsConstructor
2683 << (InitializedField != nullptr)
2684 << (CurrentInit && !CurrentInit->isWritten())
2685 << InitializedField << Range;
2686 }
2687 bool TraverseCallExpr(CallExpr *E) override {
2688 if (const auto *DR =
2689 dyn_cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit());
2690 DR && DR->isImmediateEscalating()) {
2691 Diag(E, E->getDirectCallee(), /*IsCall=*/true);
2692 return false;
2693 }
2694
2695 for (Expr *A : E->arguments())
2696 if (!TraverseStmt(A))
2697 return false;
2698
2699 return true;
2700 }
2701
2702 bool VisitDeclRefExpr(DeclRefExpr *E) override {
2703 if (const auto *ReferencedFn = dyn_cast<FunctionDecl>(E->getDecl());
2704 ReferencedFn && E->isImmediateEscalating()) {
2705 Diag(E, ReferencedFn, /*IsCall=*/false);
2706 return false;
2707 }
2708
2709 return true;
2710 }
2711
2712 bool VisitCXXConstructExpr(CXXConstructExpr *E) override {
2714 if (E->isImmediateEscalating()) {
2715 Diag(E, D, /*IsCall=*/true);
2716 return false;
2717 }
2718 return true;
2719 }
2720
2721 bool TraverseConstructorInitializer(CXXCtorInitializer *Init) override {
2722 llvm::SaveAndRestore RAII(CurrentInit, Init);
2724 }
2725
2726 bool TraverseCXXConstructorDecl(CXXConstructorDecl *Ctr) override {
2727 llvm::SaveAndRestore RAII(CurrentConstructor, Ctr);
2728 return DynamicRecursiveASTVisitor::TraverseCXXConstructorDecl(Ctr);
2729 }
2730
2731 bool TraverseType(QualType T, bool TraverseQualifier) override {
2732 return true;
2733 }
2734 bool VisitBlockExpr(BlockExpr *T) override { return true; }
2735
2736 } Visitor(*this, FD);
2737 Visitor.TraverseDecl(FD);
2738}
2739
2741 assert(getLangOpts().CPlusPlus && "No class names in C!");
2742
2743 if (SS && SS->isInvalid())
2744 return nullptr;
2745
2746 if (SS && SS->isNotEmpty()) {
2747 DeclContext *DC = computeDeclContext(*SS, true);
2748 return dyn_cast_or_null<CXXRecordDecl>(DC);
2749 }
2750
2751 return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2752}
2753
2755 const CXXScopeSpec *SS) {
2756 CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2757 return CurDecl && &II == CurDecl->getIdentifier();
2758}
2759
2761 assert(getLangOpts().CPlusPlus && "No class names in C!");
2762
2763 if (!getLangOpts().SpellChecking)
2764 return false;
2765
2766 CXXRecordDecl *CurDecl;
2767 if (SS && SS->isSet() && !SS->isInvalid()) {
2768 DeclContext *DC = computeDeclContext(*SS, true);
2769 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2770 } else
2771 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2772
2773 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2774 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2775 < II->getLength()) {
2776 II = CurDecl->getIdentifier();
2777 return true;
2778 }
2779
2780 return false;
2781}
2782
2784 SourceRange SpecifierRange,
2785 bool Virtual, AccessSpecifier Access,
2786 TypeSourceInfo *TInfo,
2787 SourceLocation EllipsisLoc) {
2788 QualType BaseType = TInfo->getType();
2789 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2790 if (BaseType->containsErrors()) {
2791 // Already emitted a diagnostic when parsing the error type.
2792 return nullptr;
2793 }
2794
2795 if (EllipsisLoc.isValid() && !BaseType->containsUnexpandedParameterPack()) {
2796 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2797 << TInfo->getTypeLoc().getSourceRange();
2798 EllipsisLoc = SourceLocation();
2799 }
2800
2801 auto *BaseDecl =
2802 dyn_cast_if_present<CXXRecordDecl>(computeDeclContext(BaseType));
2803 // C++ [class.derived.general]p2:
2804 // A class-or-decltype shall denote a (possibly cv-qualified) class type
2805 // that is not an incompletely defined class; any cv-qualifiers are
2806 // ignored.
2807 if (BaseDecl) {
2808 // C++ [class.union.general]p4:
2809 // [...] A union shall not be used as a base class.
2810 if (BaseDecl->isUnion()) {
2811 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2812 return nullptr;
2813 }
2814
2815 if (BaseType.hasQualifiers()) {
2816 std::string Quals =
2817 BaseType.getQualifiers().getAsString(Context.getPrintingPolicy());
2818 Diag(BaseLoc, diag::warn_qual_base_type)
2819 << Quals << llvm::count(Quals, ' ') + 1 << BaseType;
2820 Diag(BaseLoc, diag::note_base_class_specified_here) << BaseType;
2821 }
2822
2823 // For the MS ABI, propagate DLL attributes to base class templates.
2824 if (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
2825 Context.getTargetInfo().getTriple().isPS()) {
2826 if (Attr *ClassAttr = getDLLAttr(Class)) {
2827 if (auto *BaseSpec =
2828 dyn_cast<ClassTemplateSpecializationDecl>(BaseDecl)) {
2829 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseSpec,
2830 BaseLoc);
2831 }
2832 }
2833 }
2834
2835 if (RequireCompleteType(BaseLoc, BaseType, diag::err_incomplete_base_class,
2836 SpecifierRange)) {
2837 Class->setInvalidDecl();
2838 return nullptr;
2839 }
2840
2841 BaseDecl = BaseDecl->getDefinition();
2842 assert(BaseDecl && "Base type is not incomplete, but has no definition");
2843
2844 // Microsoft docs say:
2845 // "If a base-class has a code_seg attribute, derived classes must have the
2846 // same attribute."
2847 const auto *BaseCSA = BaseDecl->getAttr<CodeSegAttr>();
2848 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2849 if ((DerivedCSA || BaseCSA) &&
2850 (!BaseCSA || !DerivedCSA ||
2851 BaseCSA->getName() != DerivedCSA->getName())) {
2852 Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2853 Diag(BaseDecl->getLocation(), diag::note_base_class_specified_here)
2854 << BaseDecl;
2855 return nullptr;
2856 }
2857
2858 // A class which contains a flexible array member is not suitable for use as
2859 // a base class:
2860 // - If the layout determines that a base comes before another base,
2861 // the flexible array member would index into the subsequent base.
2862 // - If the layout determines that base comes before the derived class,
2863 // the flexible array member would index into the derived class.
2864 if (BaseDecl->hasFlexibleArrayMember()) {
2865 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2866 << BaseDecl->getDeclName();
2867 return nullptr;
2868 }
2869
2870 // C++ [class]p3:
2871 // If a class is marked final and it appears as a base-type-specifier in
2872 // base-clause, the program is ill-formed.
2873 if (FinalAttr *FA = BaseDecl->getAttr<FinalAttr>()) {
2874 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2875 << BaseDecl->getDeclName() << FA->isSpelledAsSealed();
2876 Diag(BaseDecl->getLocation(), diag::note_entity_declared_at)
2877 << BaseDecl->getDeclName() << FA->getRange();
2878 return nullptr;
2879 }
2880
2881 // If the base class is invalid the derived class is as well.
2882 if (BaseDecl->isInvalidDecl())
2883 Class->setInvalidDecl();
2884 } else if (BaseType->isDependentType()) {
2885 // Make sure that we don't make an ill-formed AST where the type of the
2886 // Class is non-dependent and its attached base class specifier is an
2887 // dependent type, which violates invariants in many clang code paths (e.g.
2888 // constexpr evaluator). If this case happens (in errory-recovery mode), we
2889 // explicitly mark the Class decl invalid. The diagnostic was already
2890 // emitted.
2891 if (!Class->isDependentContext())
2892 Class->setInvalidDecl();
2893 } else {
2894 // The base class is some non-dependent non-class type.
2895 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2896 return nullptr;
2897 }
2898
2899 // In HLSL, unspecified class access is public rather than private.
2900 if (getLangOpts().HLSL && Class->getTagKind() == TagTypeKind::Class &&
2901 Access == AS_none)
2902 Access = AS_public;
2903
2904 // Create the base specifier.
2905 return new (Context) CXXBaseSpecifier(
2906 SpecifierRange, Virtual, Class->getTagKind() == TagTypeKind::Class,
2907 Access, TInfo, EllipsisLoc);
2908}
2909
2911 const ParsedAttributesView &Attributes,
2912 bool Virtual, AccessSpecifier Access,
2913 ParsedType basetype, SourceLocation BaseLoc,
2914 SourceLocation EllipsisLoc) {
2915 if (!classdecl)
2916 return true;
2917
2918 AdjustDeclIfTemplate(classdecl);
2919 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2920 if (!Class)
2921 return true;
2922
2923 // We haven't yet attached the base specifiers.
2924 Class->setIsParsingBaseSpecifiers();
2925
2926 // We do not support any C++11 attributes on base-specifiers yet.
2927 // Diagnose any attributes we see.
2928 for (const ParsedAttr &AL : Attributes) {
2929 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2930 continue;
2931 if (AL.getKind() == ParsedAttr::UnknownAttribute)
2933 else
2934 Diag(AL.getLoc(), diag::err_base_specifier_attribute)
2935 << AL << AL.isRegularKeywordAttribute() << AL.getRange();
2936 }
2937
2938 TypeSourceInfo *TInfo = nullptr;
2939 GetTypeFromParser(basetype, &TInfo);
2940
2941 if (EllipsisLoc.isInvalid() &&
2942 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2944 return true;
2945
2946 // C++ [class.union.general]p4:
2947 // [...] A union shall not have base classes.
2948 if (Class->isUnion()) {
2949 Diag(Class->getLocation(), diag::err_base_clause_on_union)
2950 << SpecifierRange;
2951 return true;
2952 }
2953
2954 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2955 Virtual, Access, TInfo,
2956 EllipsisLoc))
2957 return BaseSpec;
2958
2959 Class->setInvalidDecl();
2960 return true;
2961}
2962
2963/// Use small set to collect indirect bases. As this is only used
2964/// locally, there's no need to abstract the small size parameter.
2966
2967/// Recursively add the bases of Type. Don't add Type itself.
2968static void
2970 const QualType &Type)
2971{
2972 // Even though the incoming type is a base, it might not be
2973 // a class -- it could be a template parm, for instance.
2974 if (const auto *Decl = Type->getAsCXXRecordDecl()) {
2975 // Iterate over its bases.
2976 for (const auto &BaseSpec : Decl->bases()) {
2977 QualType Base = Context.getCanonicalType(BaseSpec.getType())
2978 .getUnqualifiedType();
2979 if (Set.insert(Base).second)
2980 // If we've not already seen it, recurse.
2981 NoteIndirectBases(Context, Set, Base);
2982 }
2983 }
2984}
2985
2988 if (Bases.empty())
2989 return false;
2990
2991 // Used to keep track of which base types we have already seen, so
2992 // that we can properly diagnose redundant direct base types. Note
2993 // that the key is always the unqualified canonical type of the base
2994 // class.
2995 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2996
2997 // Used to track indirect bases so we can see if a direct base is
2998 // ambiguous.
2999 IndirectBaseSet IndirectBaseTypes;
3000
3001 // Copy non-redundant base specifiers into permanent storage.
3002 unsigned NumGoodBases = 0;
3003 bool Invalid = false;
3004 for (unsigned idx = 0; idx < Bases.size(); ++idx) {
3005 QualType NewBaseType
3006 = Context.getCanonicalType(Bases[idx]->getType());
3007 NewBaseType = NewBaseType.getLocalUnqualifiedType();
3008
3009 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
3010 if (KnownBase) {
3011 // C++ [class.mi]p3:
3012 // A class shall not be specified as a direct base class of a
3013 // derived class more than once.
3014 Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
3015 << KnownBase->getType() << Bases[idx]->getSourceRange();
3016
3017 // Delete the duplicate base class specifier; we're going to
3018 // overwrite its pointer later.
3019 Context.Deallocate(Bases[idx]);
3020
3021 Invalid = true;
3022 } else {
3023 // Okay, add this new base class.
3024 KnownBase = Bases[idx];
3025 Bases[NumGoodBases++] = Bases[idx];
3026
3027 if (NewBaseType->isDependentType())
3028 continue;
3029 // Note this base's direct & indirect bases, if there could be ambiguity.
3030 if (Bases.size() > 1)
3031 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
3032
3033 if (const auto *RD = NewBaseType->getAsCXXRecordDecl()) {
3034 if (Class->isInterface() &&
3035 (!RD->isInterfaceLike() ||
3036 KnownBase->getAccessSpecifier() != AS_public)) {
3037 // The Microsoft extension __interface does not permit bases that
3038 // are not themselves public interfaces.
3039 Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
3040 << getRecordDiagFromTagKind(RD->getTagKind()) << RD
3041 << RD->getSourceRange();
3042 Invalid = true;
3043 }
3044 if (RD->hasAttr<WeakAttr>())
3045 Class->addAttr(WeakAttr::CreateImplicit(Context));
3046 }
3047 }
3048 }
3049
3050 // Attach the remaining base class specifiers to the derived class.
3051 Class->setBases(Bases.data(), NumGoodBases);
3052
3053 // Check that the only base classes that are duplicate are virtual.
3054 for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
3055 // Check whether this direct base is inaccessible due to ambiguity.
3056 QualType BaseType = Bases[idx]->getType();
3057
3058 // Skip all dependent types in templates being used as base specifiers.
3059 // Checks below assume that the base specifier is a CXXRecord.
3060 if (BaseType->isDependentType())
3061 continue;
3062
3063 CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
3064 .getUnqualifiedType();
3065
3066 if (IndirectBaseTypes.count(CanonicalBase)) {
3067 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3068 /*DetectVirtual=*/true);
3069 bool found
3070 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
3071 assert(found);
3072 (void)found;
3073
3074 if (Paths.isAmbiguous(CanonicalBase))
3075 Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
3076 << BaseType << getAmbiguousPathsDisplayString(Paths)
3077 << Bases[idx]->getSourceRange();
3078 else
3079 assert(Bases[idx]->isVirtual());
3080 }
3081
3082 // Delete the base class specifier, since its data has been copied
3083 // into the CXXRecordDecl.
3084 Context.Deallocate(Bases[idx]);
3085 }
3086
3087 return Invalid;
3088}
3089
3092 if (!ClassDecl || Bases.empty())
3093 return;
3094
3095 AdjustDeclIfTemplate(ClassDecl);
3096 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
3097}
3098
3100 CXXRecordDecl *Base, CXXBasePaths &Paths) {
3101 if (!getLangOpts().CPlusPlus)
3102 return false;
3103
3104 if (!Base || !Derived)
3105 return false;
3106
3107 // If either the base or the derived type is invalid, don't try to
3108 // check whether one is derived from the other.
3109 if (Base->isInvalidDecl() || Derived->isInvalidDecl())
3110 return false;
3111
3112 // FIXME: In a modules build, do we need the entire path to be visible for us
3113 // to be able to use the inheritance relationship?
3114 if (!isCompleteType(Loc, Context.getCanonicalTagType(Derived)) &&
3115 !Derived->isBeingDefined())
3116 return false;
3117
3118 return Derived->isDerivedFrom(Base, Paths);
3119}
3120
3123 CXXBasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/false,
3124 /*DetectVirtual=*/false);
3125 return IsDerivedFrom(Loc, Derived, Base, Paths);
3126}
3127
3129 CXXBasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/false,
3130 /*DetectVirtual=*/false);
3131 return IsDerivedFrom(Loc, Derived->getAsCXXRecordDecl(),
3132 Base->getAsCXXRecordDecl(), Paths);
3133}
3134
3136 CXXBasePaths &Paths) {
3137 return IsDerivedFrom(Loc, Derived->getAsCXXRecordDecl(),
3138 Base->getAsCXXRecordDecl(), Paths);
3139}
3140
3141static void BuildBasePathArray(const CXXBasePath &Path,
3142 CXXCastPath &BasePathArray) {
3143 // We first go backward and check if we have a virtual base.
3144 // FIXME: It would be better if CXXBasePath had the base specifier for
3145 // the nearest virtual base.
3146 unsigned Start = 0;
3147 for (unsigned I = Path.size(); I != 0; --I) {
3148 if (Path[I - 1].Base->isVirtual()) {
3149 Start = I - 1;
3150 break;
3151 }
3152 }
3153
3154 // Now add all bases.
3155 for (unsigned I = Start, E = Path.size(); I != E; ++I)
3156 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
3157}
3158
3159
3161 CXXCastPath &BasePathArray) {
3162 assert(BasePathArray.empty() && "Base path array must be empty!");
3163 assert(Paths.isRecordingPaths() && "Must record paths!");
3164 return ::BuildBasePathArray(Paths.front(), BasePathArray);
3165}
3166
3167bool
3169 unsigned InaccessibleBaseID,
3170 unsigned AmbiguousBaseConvID,
3171 SourceLocation Loc, SourceRange Range,
3172 DeclarationName Name,
3173 CXXCastPath *BasePath,
3174 bool IgnoreAccess) {
3175 // First, determine whether the path from Derived to Base is
3176 // ambiguous. This is slightly more expensive than checking whether
3177 // the Derived to Base conversion exists, because here we need to
3178 // explore multiple paths to determine if there is an ambiguity.
3179 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3180 /*DetectVirtual=*/false);
3181 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
3182 if (!DerivationOkay)
3183 return true;
3184
3185 const CXXBasePath *Path = nullptr;
3186 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
3187 Path = &Paths.front();
3188
3189 // For MSVC compatibility, check if Derived directly inherits from Base. Clang
3190 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
3191 // user to access such bases.
3192 if (!Path && getLangOpts().MSVCCompat) {
3193 for (const CXXBasePath &PossiblePath : Paths) {
3194 if (PossiblePath.size() == 1) {
3195 Path = &PossiblePath;
3196 if (AmbiguousBaseConvID)
3197 Diag(Loc, diag::ext_ms_ambiguous_direct_base)
3198 << Base << Derived << Range;
3199 break;
3200 }
3201 }
3202 }
3203
3204 if (Path) {
3205 if (!IgnoreAccess) {
3206 // Check that the base class can be accessed.
3207 switch (
3208 CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
3209 case AR_inaccessible:
3210 return true;
3211 case AR_accessible:
3212 case AR_dependent:
3213 case AR_delayed:
3214 break;
3215 }
3216 }
3217
3218 // Build a base path if necessary.
3219 if (BasePath)
3220 ::BuildBasePathArray(*Path, *BasePath);
3221 return false;
3222 }
3223
3224 if (AmbiguousBaseConvID) {
3225 // We know that the derived-to-base conversion is ambiguous, and
3226 // we're going to produce a diagnostic. Perform the derived-to-base
3227 // search just one more time to compute all of the possible paths so
3228 // that we can print them out. This is more expensive than any of
3229 // the previous derived-to-base checks we've done, but at this point
3230 // performance isn't as much of an issue.
3231 Paths.clear();
3232 Paths.setRecordingPaths(true);
3233 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
3234 assert(StillOkay && "Can only be used with a derived-to-base conversion");
3235 (void)StillOkay;
3236
3237 // Build up a textual representation of the ambiguous paths, e.g.,
3238 // D -> B -> A, that will be used to illustrate the ambiguous
3239 // conversions in the diagnostic. We only print one of the paths
3240 // to each base class subobject.
3241 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3242
3243 Diag(Loc, AmbiguousBaseConvID)
3244 << Derived << Base << PathDisplayStr << Range << Name;
3245 }
3246 return true;
3247}
3248
3249bool
3251 SourceLocation Loc, SourceRange Range,
3252 CXXCastPath *BasePath,
3253 bool IgnoreAccess) {
3255 Derived, Base, diag::err_upcast_to_inaccessible_base,
3256 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
3257 BasePath, IgnoreAccess);
3258}
3259
3261 std::string PathDisplayStr;
3262 std::set<unsigned> DisplayedPaths;
3263 for (const CXXBasePath &Path : Paths) {
3264 if (DisplayedPaths.insert(Path.back().SubobjectNumber).second) {
3265 // We haven't displayed a path to this particular base
3266 // class subobject yet.
3267 PathDisplayStr += "\n ";
3268 PathDisplayStr += QualType(Context.getCanonicalTagType(Paths.getOrigin()))
3269 .getAsString();
3270 for (const CXXBasePathElement &Element : Path)
3271 PathDisplayStr += " -> " + Element.Base->getType().getAsString();
3272 }
3273 }
3274
3275 return PathDisplayStr;
3276}
3277
3278//===----------------------------------------------------------------------===//
3279// C++ class member Handling
3280//===----------------------------------------------------------------------===//
3281
3283 SourceLocation ColonLoc,
3284 const ParsedAttributesView &Attrs) {
3285 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
3287 ASLoc, ColonLoc);
3288 CurContext->addHiddenDecl(ASDecl);
3289 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
3290}
3291
3293 if (D->isInvalidDecl())
3294 return;
3295
3296 // We only care about "override" and "final" declarations.
3297 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
3298 return;
3299
3300 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3301
3302 // We can't check dependent instance methods.
3303 if (MD && MD->isInstance() &&
3304 (MD->getParent()->hasAnyDependentBases() ||
3305 MD->getType()->isDependentType()))
3306 return;
3307
3308 if (MD && !MD->isVirtual()) {
3309 // If we have a non-virtual method, check if it hides a virtual method.
3310 // (In that case, it's most likely the method has the wrong type.)
3311 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3312 FindHiddenVirtualMethods(MD, OverloadedMethods);
3313
3314 if (!OverloadedMethods.empty()) {
3315 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3316 Diag(OA->getLocation(),
3317 diag::override_keyword_hides_virtual_member_function)
3318 << "override" << (OverloadedMethods.size() > 1);
3319 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3320 Diag(FA->getLocation(),
3321 diag::override_keyword_hides_virtual_member_function)
3322 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3323 << (OverloadedMethods.size() > 1);
3324 }
3325 NoteHiddenVirtualMethods(MD, OverloadedMethods);
3326 MD->setInvalidDecl();
3327 return;
3328 }
3329 // Fall through into the general case diagnostic.
3330 // FIXME: We might want to attempt typo correction here.
3331 }
3332
3333 if (!MD || !MD->isVirtual()) {
3334 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3335 Diag(OA->getLocation(),
3336 diag::override_keyword_only_allowed_on_virtual_member_functions)
3337 << "override" << FixItHint::CreateRemoval(OA->getLocation());
3338 D->dropAttr<OverrideAttr>();
3339 }
3340 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3341 Diag(FA->getLocation(),
3342 diag::override_keyword_only_allowed_on_virtual_member_functions)
3343 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3344 << FixItHint::CreateRemoval(FA->getLocation());
3345 D->dropAttr<FinalAttr>();
3346 }
3347 return;
3348 }
3349
3350 // C++11 [class.virtual]p5:
3351 // If a function is marked with the virt-specifier override and
3352 // does not override a member function of a base class, the program is
3353 // ill-formed.
3354 bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
3355 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
3356 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
3357 << MD->getDeclName();
3358}
3359
3361 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
3362 return;
3363 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3364 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
3365 return;
3366
3367 SourceLocation Loc = MD->getLocation();
3368 SourceLocation SpellingLoc = Loc;
3369 if (getSourceManager().isMacroArgExpansion(Loc))
3370 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
3371 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
3372 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
3373 return;
3374
3375 if (MD->size_overridden_methods() > 0) {
3376 auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) {
3377 unsigned DiagID =
3378 Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation())
3379 ? DiagInconsistent
3380 : DiagSuggest;
3381 Diag(MD->getLocation(), DiagID) << MD->getDeclName();
3382 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
3383 Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
3384 };
3385 if (isa<CXXDestructorDecl>(MD))
3386 EmitDiag(
3387 diag::warn_inconsistent_destructor_marked_not_override_overriding,
3388 diag::warn_suggest_destructor_marked_not_override_overriding);
3389 else
3390 EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding,
3391 diag::warn_suggest_function_marked_not_override_overriding);
3392 }
3393}
3394
3396 const CXXMethodDecl *Old) {
3397 FinalAttr *FA = Old->getAttr<FinalAttr>();
3398 if (!FA)
3399 return false;
3400
3401 Diag(New->getLocation(), diag::err_final_function_overridden)
3402 << New->getDeclName()
3403 << FA->isSpelledAsSealed();
3404 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3405 return true;
3406}
3407
3409 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
3410 // FIXME: Destruction of ObjC lifetime types has side-effects.
3411 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3412 return !RD->isCompleteDefinition() ||
3413 !RD->hasTrivialDefaultConstructor() ||
3414 !RD->hasTrivialDestructor();
3415 return false;
3416}
3417
3418void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
3419 DeclarationName FieldName,
3420 const CXXRecordDecl *RD,
3421 bool DeclIsField) {
3422 if (Diags.isIgnored(diag::warn_shadow_field, Loc))
3423 return;
3424
3425 // To record a shadowed field in a base
3426 std::map<CXXRecordDecl*, NamedDecl*> Bases;
3427 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
3428 CXXBasePath &Path) {
3429 const auto Base = Specifier->getType()->getAsCXXRecordDecl();
3430 // Record an ambiguous path directly
3431 if (Bases.find(Base) != Bases.end())
3432 return true;
3433 for (const auto Field : Base->lookup(FieldName)) {
3434 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
3435 Field->getAccess() != AS_private) {
3436 assert(Field->getAccess() != AS_none);
3437 assert(Bases.find(Base) == Bases.end());
3438 Bases[Base] = Field;
3439 return true;
3440 }
3441 }
3442 return false;
3443 };
3444
3445 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3446 /*DetectVirtual=*/true);
3447 if (!RD->lookupInBases(FieldShadowed, Paths))
3448 return;
3449
3450 for (const auto &P : Paths) {
3451 auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
3452 auto It = Bases.find(Base);
3453 // Skip duplicated bases
3454 if (It == Bases.end())
3455 continue;
3456 auto BaseField = It->second;
3457 assert(BaseField->getAccess() != AS_private);
3458 if (AS_none !=
3459 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
3460 Diag(Loc, diag::warn_shadow_field)
3461 << FieldName << RD << Base << DeclIsField;
3462 Diag(BaseField->getLocation(), diag::note_shadow_field);
3463 Bases.erase(It);
3464 }
3465 }
3466}
3467
3468template <typename AttrType>
3469inline static bool HasAttribute(const QualType &T) {
3470 if (const TagDecl *TD = T->getAsTagDecl())
3471 return TD->hasAttr<AttrType>();
3472 if (const TypedefType *TDT = T->getAs<TypedefType>())
3473 return TDT->getDecl()->hasAttr<AttrType>();
3474 return false;
3475}
3476
3477static bool IsUnusedPrivateField(const FieldDecl *FD) {
3478 if (FD->getAccess() == AS_private && FD->getDeclName()) {
3479 QualType FieldType = FD->getType();
3480 if (HasAttribute<WarnUnusedAttr>(FieldType))
3481 return true;
3482
3483 return !FD->isImplicit() && !FD->hasAttr<UnusedAttr>() &&
3484 !FD->getParent()->isDependentContext() &&
3485 !HasAttribute<UnusedAttr>(FieldType) &&
3487 }
3488 return false;
3489}
3490
3491NamedDecl *
3493 MultiTemplateParamsArg TemplateParameterLists,
3494 Expr *BitWidth, const VirtSpecifiers &VS,
3495 InClassInitStyle InitStyle) {
3496 const DeclSpec &DS = D.getDeclSpec();
3498 DeclarationName Name = NameInfo.getName();
3499 SourceLocation Loc = NameInfo.getLoc();
3500
3501 // For anonymous bitfields, the location should point to the type.
3502 if (Loc.isInvalid())
3503 Loc = D.getBeginLoc();
3504
3506 assert(!DS.isFriendSpecified());
3507
3508 bool isFunc = D.isDeclarationOfFunction();
3509 const ParsedAttr *MSPropertyAttr =
3511
3512 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
3513 // The Microsoft extension __interface only permits public member functions
3514 // and prohibits constructors, destructors, operators, non-public member
3515 // functions, static methods and data members.
3516 unsigned InvalidDecl;
3517 bool ShowDeclName = true;
3518 if (!isFunc &&
3519 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
3520 InvalidDecl = 0;
3521 else if (!isFunc)
3522 InvalidDecl = 1;
3523 else if (AS != AS_public)
3524 InvalidDecl = 2;
3526 InvalidDecl = 3;
3527 else switch (Name.getNameKind()) {
3529 InvalidDecl = 4;
3530 ShowDeclName = false;
3531 break;
3532
3534 InvalidDecl = 5;
3535 ShowDeclName = false;
3536 break;
3537
3540 InvalidDecl = 6;
3541 break;
3542
3543 default:
3544 InvalidDecl = 0;
3545 break;
3546 }
3547
3548 if (InvalidDecl) {
3549 if (ShowDeclName)
3550 Diag(Loc, diag::err_invalid_member_in_interface)
3551 << (InvalidDecl-1) << Name;
3552 else
3553 Diag(Loc, diag::err_invalid_member_in_interface)
3554 << (InvalidDecl-1) << "";
3555 return nullptr;
3556 }
3557 }
3558
3559 // HLSL prohibits user defined constructors and destructors.
3560 if (getLangOpts().HLSL) {
3561 switch (Name.getNameKind()) {
3564 Diag(Loc, diag::err_hlsl_cstor_dstor);
3565 return nullptr;
3566 default:
3567 break;
3568 }
3569 }
3570
3571 // C++ 9.2p6: A member shall not be declared to have automatic storage
3572 // duration (auto, register) or with the extern storage-class-specifier.
3573 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3574 // data members and cannot be applied to names declared const or static,
3575 // and cannot be applied to reference members.
3576 switch (DS.getStorageClassSpec()) {
3580 break;
3582 if (isFunc) {
3583 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3584
3585 // FIXME: It would be nicer if the keyword was ignored only for this
3586 // declarator. Otherwise we could get follow-up errors.
3588 }
3589 break;
3590 default:
3592 diag::err_storageclass_invalid_for_member);
3594 break;
3595 }
3596
3597 bool isInstField = (DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3599 !isFunc && TemplateParameterLists.empty();
3600
3601 if (DS.hasConstexprSpecifier() && isInstField) {
3603 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3604 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3605 if (InitStyle == ICIS_NoInit) {
3606 B << 0 << 0;
3608 B << FixItHint::CreateRemoval(ConstexprLoc);
3609 else {
3610 B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3612 const char *PrevSpec;
3613 unsigned DiagID;
3614 bool Failed = D.getMutableDeclSpec().SetTypeQual(
3615 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3616 (void)Failed;
3617 assert(!Failed && "Making a constexpr member const shouldn't fail");
3618 }
3619 } else {
3620 B << 1;
3621 const char *PrevSpec;
3622 unsigned DiagID;
3624 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3625 Context.getPrintingPolicy())) {
3627 "This is the only DeclSpec that should fail to be applied");
3628 B << 1;
3629 } else {
3630 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3631 isInstField = false;
3632 }
3633 }
3634 }
3635
3637 if (isInstField) {
3638 CXXScopeSpec &SS = D.getCXXScopeSpec();
3639
3640 // Data members must have identifiers for names.
3641 if (!Name.isIdentifier()) {
3642 Diag(Loc, diag::err_bad_variable_name)
3643 << Name;
3644 return nullptr;
3645 }
3646
3649 Diag(D.getIdentifierLoc(), diag::err_member_with_template_arguments)
3650 << II
3654 D.SetIdentifier(II, Loc);
3655 }
3656
3657 if (SS.isSet() && !SS.isInvalid()) {
3658 // The user provided a superfluous scope specifier inside a class
3659 // definition:
3660 //
3661 // class X {
3662 // int X::member;
3663 // };
3664 if (DeclContext *DC = computeDeclContext(SS, false)) {
3665 TemplateIdAnnotation *TemplateId =
3667 ? D.getName().TemplateId
3668 : nullptr;
3670 TemplateId,
3671 /*IsMemberSpecialization=*/false);
3672 } else {
3673 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3674 << Name << SS.getRange();
3675 }
3676 SS.clear();
3677 }
3678
3679 if (MSPropertyAttr) {
3681 BitWidth, InitStyle, AS, *MSPropertyAttr);
3682 if (!Member)
3683 return nullptr;
3684 isInstField = false;
3685 } else {
3687 BitWidth, InitStyle, AS);
3688 if (!Member)
3689 return nullptr;
3690 }
3691
3692 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3693 } else {
3694 Member = HandleDeclarator(S, D, TemplateParameterLists);
3695 if (!Member)
3696 return nullptr;
3697
3698 // Non-instance-fields can't have a bitfield.
3699 if (BitWidth) {
3700 if (Member->isInvalidDecl()) {
3701 // don't emit another diagnostic.
3703 // C++ 9.6p3: A bit-field shall not be a static member.
3704 // "static member 'A' cannot be a bit-field"
3705 Diag(Loc, diag::err_static_not_bitfield)
3706 << Name << BitWidth->getSourceRange();
3707 } else if (isa<TypedefDecl>(Member)) {
3708 // "typedef member 'x' cannot be a bit-field"
3709 Diag(Loc, diag::err_typedef_not_bitfield)
3710 << Name << BitWidth->getSourceRange();
3711 } else {
3712 // A function typedef ("typedef int f(); f a;").
3713 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3714 Diag(Loc, diag::err_not_integral_type_bitfield)
3715 << Name << cast<ValueDecl>(Member)->getType()
3716 << BitWidth->getSourceRange();
3717 }
3718
3719 BitWidth = nullptr;
3720 Member->setInvalidDecl();
3721 }
3722
3723 NamedDecl *NonTemplateMember = Member;
3724 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3725 NonTemplateMember = FunTmpl->getTemplatedDecl();
3726 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3727 NonTemplateMember = VarTmpl->getTemplatedDecl();
3728
3729 Member->setAccess(AS);
3730
3731 // If we have declared a member function template or static data member
3732 // template, set the access of the templated declaration as well.
3733 if (NonTemplateMember != Member)
3734 NonTemplateMember->setAccess(AS);
3735
3736 // C++ [temp.deduct.guide]p3:
3737 // A deduction guide [...] for a member class template [shall be
3738 // declared] with the same access [as the template].
3739 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3740 auto *TD = DG->getDeducedTemplate();
3741 // Access specifiers are only meaningful if both the template and the
3742 // deduction guide are from the same scope.
3743 if (AS != TD->getAccess() &&
3744 TD->getDeclContext()->getRedeclContext()->Equals(
3745 DG->getDeclContext()->getRedeclContext())) {
3746 Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3747 Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3748 << TD->getAccess();
3749 const AccessSpecDecl *LastAccessSpec = nullptr;
3750 for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3751 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3752 LastAccessSpec = AccessSpec;
3753 }
3754 assert(LastAccessSpec && "differing access with no access specifier");
3755 Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3756 << AS;
3757 }
3758 }
3759 }
3760
3761 if (VS.isOverrideSpecified())
3762 Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc()));
3763 if (VS.isFinalSpecified())
3764 Member->addAttr(FinalAttr::Create(Context, VS.getFinalLoc(),
3766 ? FinalAttr::Keyword_sealed
3767 : FinalAttr::Keyword_final));
3768
3769 if (VS.getLastLocation().isValid()) {
3770 // Update the end location of a method that has a virt-specifiers.
3771 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3772 MD->setRangeEnd(VS.getLastLocation());
3773 }
3774
3776
3777 assert((Name || isInstField) && "No identifier for non-field ?");
3778
3779 if (isInstField) {
3781 FieldCollector->Add(FD);
3782
3783 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation()) &&
3785 // Remember all explicit private FieldDecls that have a name, no side
3786 // effects and are not part of a dependent type declaration.
3787 UnusedPrivateFields.insert(FD);
3788 }
3789 }
3790
3791 return Member;
3792}
3793
3794namespace {
3795 class UninitializedFieldVisitor
3796 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3797 Sema &S;
3798 // List of Decls to generate a warning on. Also remove Decls that become
3799 // initialized.
3800 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3801 // List of base classes of the record. Classes are removed after their
3802 // initializers.
3803 llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3804 // Vector of decls to be removed from the Decl set prior to visiting the
3805 // nodes. These Decls may have been initialized in the prior initializer.
3807 // If non-null, add a note to the warning pointing back to the constructor.
3809 // Variables to hold state when processing an initializer list. When
3810 // InitList is true, special case initialization of FieldDecls matching
3811 // InitListFieldDecl.
3812 bool InitList;
3813 FieldDecl *InitListFieldDecl;
3814 llvm::SmallVector<unsigned, 4> InitFieldIndex;
3815
3816 public:
3818 UninitializedFieldVisitor(Sema &S,
3819 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3820 llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3821 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3822 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3823
3824 // Returns true if the use of ME is not an uninitialized use.
3825 bool IsInitListMemberExprInitialized(MemberExpr *ME,
3826 bool CheckReferenceOnly) {
3828 bool ReferenceField = false;
3829 while (ME) {
3830 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3831 if (!FD)
3832 return false;
3833 Fields.push_back(FD);
3834 if (FD->getType()->isReferenceType())
3835 ReferenceField = true;
3836 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3837 }
3838
3839 // Binding a reference to an uninitialized field is not an
3840 // uninitialized use.
3841 if (CheckReferenceOnly && !ReferenceField)
3842 return true;
3843
3844 // Discard the first field since it is the field decl that is being
3845 // initialized.
3846 auto UsedFields = llvm::drop_begin(llvm::reverse(Fields));
3847 auto UsedIter = UsedFields.begin();
3848 const auto UsedEnd = UsedFields.end();
3849
3850 for (const unsigned Orig : InitFieldIndex) {
3851 if (UsedIter == UsedEnd)
3852 break;
3853 const unsigned UsedIndex = (*UsedIter)->getFieldIndex();
3854 if (UsedIndex < Orig)
3855 return true;
3856 if (UsedIndex > Orig)
3857 break;
3858 ++UsedIter;
3859 }
3860
3861 return false;
3862 }
3863
3864 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3865 bool AddressOf) {
3867 return;
3868
3869 // FieldME is the inner-most MemberExpr that is not an anonymous struct
3870 // or union.
3871 MemberExpr *FieldME = ME;
3872
3873 bool AllPODFields = FieldME->getType().isPODType(S.Context);
3874
3875 Expr *Base = ME;
3876 while (MemberExpr *SubME =
3877 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3878
3879 if (isa<VarDecl>(SubME->getMemberDecl()))
3880 return;
3881
3882 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3883 if (!FD->isAnonymousStructOrUnion())
3884 FieldME = SubME;
3885
3886 if (!FieldME->getType().isPODType(S.Context))
3887 AllPODFields = false;
3888
3889 Base = SubME->getBase();
3890 }
3891
3892 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) {
3893 Visit(Base);
3894 return;
3895 }
3896
3897 if (AddressOf && AllPODFields)
3898 return;
3899
3900 ValueDecl* FoundVD = FieldME->getMemberDecl();
3901
3902 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3903 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3904 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3905 }
3906
3907 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3908 QualType T = BaseCast->getType();
3909 if (T->isPointerType() &&
3910 BaseClasses.count(T->getPointeeType())) {
3911 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3912 << T->getPointeeType() << FoundVD;
3913 }
3914 }
3915 }
3916
3917 if (!Decls.count(FoundVD))
3918 return;
3919
3920 const bool IsReference = FoundVD->getType()->isReferenceType();
3921
3922 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3923 // Special checking for initializer lists.
3924 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3925 return;
3926 }
3927 } else {
3928 // Prevent double warnings on use of unbounded references.
3929 if (CheckReferenceOnly && !IsReference)
3930 return;
3931 }
3932
3933 unsigned diag = IsReference
3934 ? diag::warn_reference_field_is_uninit
3935 : diag::warn_field_is_uninit;
3936 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3937 if (Constructor)
3938 S.Diag(Constructor->getLocation(),
3939 diag::note_uninit_in_this_constructor)
3940 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3941
3942 }
3943
3944 void HandleValue(Expr *E, bool AddressOf) {
3945 E = E->IgnoreParens();
3946
3947 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3948 HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3949 AddressOf /*AddressOf*/);
3950 return;
3951 }
3952
3953 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3954 Visit(CO->getCond());
3955 HandleValue(CO->getTrueExpr(), AddressOf);
3956 HandleValue(CO->getFalseExpr(), AddressOf);
3957 return;
3958 }
3959
3960 if (BinaryConditionalOperator *BCO =
3961 dyn_cast<BinaryConditionalOperator>(E)) {
3962 Visit(BCO->getCond());
3963 HandleValue(BCO->getFalseExpr(), AddressOf);
3964 return;
3965 }
3966
3967 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3968 HandleValue(OVE->getSourceExpr(), AddressOf);
3969 return;
3970 }
3971
3972 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3973 switch (BO->getOpcode()) {
3974 default:
3975 break;
3976 case(BO_PtrMemD):
3977 case(BO_PtrMemI):
3978 HandleValue(BO->getLHS(), AddressOf);
3979 Visit(BO->getRHS());
3980 return;
3981 case(BO_Comma):
3982 Visit(BO->getLHS());
3983 HandleValue(BO->getRHS(), AddressOf);
3984 return;
3985 }
3986 }
3987
3988 Visit(E);
3989 }
3990
3991 void CheckInitListExpr(InitListExpr *ILE) {
3992 InitFieldIndex.push_back(0);
3993 for (auto *Child : ILE->children()) {
3994 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3995 CheckInitListExpr(SubList);
3996 } else {
3997 Visit(Child);
3998 }
3999 ++InitFieldIndex.back();
4000 }
4001 InitFieldIndex.pop_back();
4002 }
4003
4004 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
4005 FieldDecl *Field, const Type *BaseClass) {
4006 // Remove Decls that may have been initialized in the previous
4007 // initializer.
4008 for (ValueDecl* VD : DeclsToRemove)
4009 Decls.erase(VD);
4010 DeclsToRemove.clear();
4011
4012 Constructor = FieldConstructor;
4013 InitListExpr *ILE = dyn_cast<InitListExpr>(E);
4014
4015 if (ILE && Field) {
4016 InitList = true;
4017 InitListFieldDecl = Field;
4018 InitFieldIndex.clear();
4019 CheckInitListExpr(ILE);
4020 } else {
4021 InitList = false;
4022 Visit(E);
4023 }
4024
4025 if (Field)
4026 Decls.erase(Field);
4027 if (BaseClass)
4028 BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
4029 }
4030
4031 void VisitMemberExpr(MemberExpr *ME) {
4032 // All uses of unbounded reference fields will warn.
4033 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
4034 }
4035
4036 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
4037 if (E->getCastKind() == CK_LValueToRValue) {
4038 HandleValue(E->getSubExpr(), false /*AddressOf*/);
4039 return;
4040 }
4041
4042 Inherited::VisitImplicitCastExpr(E);
4043 }
4044
4045 void VisitCXXConstructExpr(CXXConstructExpr *E) {
4046 if (E->getConstructor()->isCopyConstructor()) {
4047 Expr *ArgExpr = E->getArg(0);
4048 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
4049 if (ILE->getNumInits() == 1)
4050 ArgExpr = ILE->getInit(0);
4051 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
4052 if (ICE->getCastKind() == CK_NoOp)
4053 ArgExpr = ICE->getSubExpr();
4054 HandleValue(ArgExpr, false /*AddressOf*/);
4055 return;
4056 }
4057 Inherited::VisitCXXConstructExpr(E);
4058 }
4059
4060 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
4061 Expr *Callee = E->getCallee();
4062 if (isa<MemberExpr>(Callee)) {
4063 HandleValue(Callee, false /*AddressOf*/);
4064 for (auto *Arg : E->arguments())
4065 Visit(Arg);
4066 return;
4067 }
4068
4069 Inherited::VisitCXXMemberCallExpr(E);
4070 }
4071
4072 void VisitCallExpr(CallExpr *E) {
4073 // Treat std::move as a use.
4074 if (E->isCallToStdMove()) {
4075 HandleValue(E->getArg(0), /*AddressOf=*/false);
4076 return;
4077 }
4078
4079 Inherited::VisitCallExpr(E);
4080 }
4081
4082 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
4083 Expr *Callee = E->getCallee();
4084
4085 if (isa<UnresolvedLookupExpr>(Callee))
4086 return Inherited::VisitCXXOperatorCallExpr(E);
4087
4088 Visit(Callee);
4089 for (auto *Arg : E->arguments())
4090 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
4091 }
4092
4093 void VisitBinaryOperator(BinaryOperator *E) {
4094 // If a field assignment is detected, remove the field from the
4095 // uninitiailized field set.
4096 if (E->getOpcode() == BO_Assign)
4097 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
4098 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
4099 if (!FD->getType()->isReferenceType())
4100 DeclsToRemove.push_back(FD);
4101
4102 if (E->isCompoundAssignmentOp()) {
4103 HandleValue(E->getLHS(), false /*AddressOf*/);
4104 Visit(E->getRHS());
4105 return;
4106 }
4107
4108 Inherited::VisitBinaryOperator(E);
4109 }
4110
4111 void VisitUnaryOperator(UnaryOperator *E) {
4112 if (E->isIncrementDecrementOp()) {
4113 HandleValue(E->getSubExpr(), false /*AddressOf*/);
4114 return;
4115 }
4116 if (E->getOpcode() == UO_AddrOf) {
4117 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
4118 HandleValue(ME->getBase(), true /*AddressOf*/);
4119 return;
4120 }
4121 }
4122
4123 Inherited::VisitUnaryOperator(E);
4124 }
4125 };
4126
4127 // Diagnose value-uses of fields to initialize themselves, e.g.
4128 // foo(foo)
4129 // where foo is not also a parameter to the constructor.
4130 // Also diagnose across field uninitialized use such as
4131 // x(y), y(x)
4132 // TODO: implement -Wuninitialized and fold this into that framework.
4133 static void DiagnoseUninitializedFields(
4134 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
4135
4136 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
4137 Constructor->getLocation())) {
4138 return;
4139 }
4140
4141 if (Constructor->isInvalidDecl())
4142 return;
4143
4144 const CXXRecordDecl *RD = Constructor->getParent();
4145
4146 if (RD->isDependentContext())
4147 return;
4148
4149 // Holds fields that are uninitialized.
4150 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
4151
4152 // At the beginning, all fields are uninitialized.
4153 for (auto *I : RD->decls()) {
4154 if (auto *FD = dyn_cast<FieldDecl>(I)) {
4155 UninitializedFields.insert(FD);
4156 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
4157 UninitializedFields.insert(IFD->getAnonField());
4158 }
4159 }
4160
4161 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
4162 for (const auto &I : RD->bases()) {
4163 // Virtual bases are initialized from the most derived class, so an
4164 // abstract base class constructor can assume it to be initialized.
4165 if (I.isVirtual() && RD->isAbstract())
4166 continue;
4167 UninitializedBaseClasses.insert(I.getType().getCanonicalType());
4168 }
4169
4170 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
4171 return;
4172
4173 UninitializedFieldVisitor UninitializedChecker(SemaRef,
4174 UninitializedFields,
4175 UninitializedBaseClasses);
4176
4177 for (const auto *FieldInit : Constructor->inits()) {
4178 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
4179 break;
4180
4181 Expr *InitExpr = FieldInit->getInit();
4182 if (!InitExpr)
4183 continue;
4184
4185 if (CXXDefaultInitExpr *Default =
4186 dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
4187 InitExpr = Default->getExpr();
4188 if (!InitExpr)
4189 continue;
4190 // In class initializers will point to the constructor.
4191 UninitializedChecker.CheckInitializer(InitExpr, Constructor,
4192 FieldInit->getAnyMember(),
4193 FieldInit->getBaseClass());
4194 } else {
4195 UninitializedChecker.CheckInitializer(InitExpr, nullptr,
4196 FieldInit->getAnyMember(),
4197 FieldInit->getBaseClass());
4198 }
4199 }
4200 }
4201} // namespace
4202
4204 // Create a synthetic function scope to represent the call to the constructor
4205 // that notionally surrounds a use of this initializer.
4207}
4208
4210 if (!D.isFunctionDeclarator())
4211 return;
4212 auto &FTI = D.getFunctionTypeInfo();
4213 if (!FTI.Params)
4214 return;
4215 for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params,
4216 FTI.NumParams)) {
4217 auto *ParamDecl = cast<NamedDecl>(Param.Param);
4218 if (ParamDecl->getDeclName())
4219 PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false);
4220 }
4221}
4222
4224 return ActOnRequiresClause(ConstraintExpr);
4225}
4226
4228 if (ConstraintExpr.isInvalid())
4229 return ExprError();
4230
4231 if (DiagnoseUnexpandedParameterPack(ConstraintExpr.get(),
4233 return ExprError();
4234
4235 return ConstraintExpr;
4236}
4237
4239 Expr *InitExpr,
4240 SourceLocation InitLoc) {
4241 InitializedEntity Entity =
4243 InitializationKind Kind =
4246 InitExpr->getBeginLoc(),
4247 InitExpr->getEndLoc())
4248 : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
4249 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
4250 return Seq.Perform(*this, Entity, Kind, InitExpr);
4251}
4252
4254 SourceLocation InitLoc,
4255 ExprResult InitExpr) {
4256 // Pop the notional constructor scope we created earlier.
4257 PopFunctionScopeInfo(nullptr, D);
4258
4259 // Microsoft C++'s property declaration cannot have a default member
4260 // initializer.
4261 if (isa<MSPropertyDecl>(D)) {
4262 D->setInvalidDecl();
4263 return;
4264 }
4265
4266 FieldDecl *FD = dyn_cast<FieldDecl>(D);
4267 assert((FD && FD->getInClassInitStyle() != ICIS_NoInit) &&
4268 "must set init style when field is created");
4269
4270 if (!InitExpr.isUsable() ||
4272 FD->setInvalidDecl();
4273 ExprResult RecoveryInit =
4274 CreateRecoveryExpr(InitLoc, InitLoc, {}, FD->getType());
4275 if (RecoveryInit.isUsable())
4276 FD->setInClassInitializer(RecoveryInit.get());
4277 return;
4278 }
4279
4280 if (!FD->getType()->isDependentType() && !InitExpr.get()->isTypeDependent()) {
4281 InitExpr = ConvertMemberDefaultInitExpression(FD, InitExpr.get(), InitLoc);
4282 // C++11 [class.base.init]p7:
4283 // The initialization of each base and member constitutes a
4284 // full-expression.
4285 if (!InitExpr.isInvalid())
4286 InitExpr = ActOnFinishFullExpr(InitExpr.get(), /*DiscarededValue=*/false);
4287 if (InitExpr.isInvalid()) {
4288 FD->setInvalidDecl();
4289 return;
4290 }
4291 }
4292
4293 FD->setInClassInitializer(InitExpr.get());
4294}
4295
4296/// Find the direct and/or virtual base specifiers that
4297/// correspond to the given base type, for use in base initialization
4298/// within a constructor.
4299static bool FindBaseInitializer(Sema &SemaRef,
4300 CXXRecordDecl *ClassDecl,
4301 QualType BaseType,
4302 const CXXBaseSpecifier *&DirectBaseSpec,
4303 const CXXBaseSpecifier *&VirtualBaseSpec) {
4304 // First, check for a direct base class.
4305 DirectBaseSpec = nullptr;
4306 for (const auto &Base : ClassDecl->bases()) {
4307 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
4308 // We found a direct base of this type. That's what we're
4309 // initializing.
4310 DirectBaseSpec = &Base;
4311 break;
4312 }
4313 }
4314
4315 // Check for a virtual base class.
4316 // FIXME: We might be able to short-circuit this if we know in advance that
4317 // there are no virtual bases.
4318 VirtualBaseSpec = nullptr;
4319 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
4320 // We haven't found a base yet; search the class hierarchy for a
4321 // virtual base class.
4322 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
4323 /*DetectVirtual=*/false);
4324 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
4325 SemaRef.Context.getCanonicalTagType(ClassDecl),
4326 BaseType, Paths)) {
4327 for (const CXXBasePath &Path : Paths) {
4328 if (Path.back().Base->isVirtual()) {
4329 VirtualBaseSpec = Path.back().Base;
4330 break;
4331 }
4332 }
4333 }
4334 }
4335
4336 return DirectBaseSpec || VirtualBaseSpec;
4337}
4338
4341 Scope *S,
4342 CXXScopeSpec &SS,
4343 IdentifierInfo *MemberOrBase,
4344 ParsedType TemplateTypeTy,
4345 const DeclSpec &DS,
4346 SourceLocation IdLoc,
4347 Expr *InitList,
4348 SourceLocation EllipsisLoc) {
4349 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4350 DS, IdLoc, InitList,
4351 EllipsisLoc);
4352}
4353
4356 Scope *S,
4357 CXXScopeSpec &SS,
4358 IdentifierInfo *MemberOrBase,
4359 ParsedType TemplateTypeTy,
4360 const DeclSpec &DS,
4361 SourceLocation IdLoc,
4362 SourceLocation LParenLoc,
4363 ArrayRef<Expr *> Args,
4364 SourceLocation RParenLoc,
4365 SourceLocation EllipsisLoc) {
4366 Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
4367 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4368 DS, IdLoc, List, EllipsisLoc);
4369}
4370
4371namespace {
4372
4373// Callback to only accept typo corrections that can be a valid C++ member
4374// initializer: either a non-static field member or a base class.
4375class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
4376public:
4377 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
4378 : ClassDecl(ClassDecl) {}
4379
4380 bool ValidateCandidate(const TypoCorrection &candidate) override {
4381 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
4382 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
4383 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
4384 return isa<TypeDecl>(ND);
4385 }
4386 return false;
4387 }
4388
4389 std::unique_ptr<CorrectionCandidateCallback> clone() override {
4390 return std::make_unique<MemInitializerValidatorCCC>(*this);
4391 }
4392
4393private:
4394 CXXRecordDecl *ClassDecl;
4395};
4396
4397}
4398
4400 RecordDecl *ClassDecl,
4401 const IdentifierInfo *Name) {
4402 DeclContextLookupResult Result = ClassDecl->lookup(Name);
4404 llvm::find_if(Result, [this](const NamedDecl *Elem) {
4405 return isa<FieldDecl, IndirectFieldDecl>(Elem) &&
4407 });
4408 // We did not find a placeholder variable
4409 if (Found == Result.end())
4410 return false;
4411 Diag(Loc, diag::err_using_placeholder_variable) << Name;
4412 for (DeclContextLookupResult::iterator It = Found; It != Result.end(); It++) {
4413 const NamedDecl *ND = *It;
4414 if (ND->getDeclContext() != ND->getDeclContext())
4415 break;
4418 Diag(ND->getLocation(), diag::note_reference_placeholder) << ND;
4419 }
4420 return true;
4421}
4422
4423ValueDecl *
4425 const IdentifierInfo *MemberOrBase) {
4426 ValueDecl *ND = nullptr;
4427 for (auto *D : ClassDecl->lookup(MemberOrBase)) {
4429 bool IsPlaceholder = D->isPlaceholderVar(getLangOpts());
4430 if (ND) {
4431 if (IsPlaceholder && D->getDeclContext() == ND->getDeclContext())
4432 return nullptr;
4433 break;
4434 }
4435 if (!IsPlaceholder)
4436 return cast<ValueDecl>(D);
4437 ND = cast<ValueDecl>(D);
4438 }
4439 }
4440 return ND;
4441}
4442
4444 CXXScopeSpec &SS,
4445 ParsedType TemplateTypeTy,
4446 IdentifierInfo *MemberOrBase) {
4447 if (SS.getScopeRep() || TemplateTypeTy)
4448 return nullptr;
4449 return tryLookupUnambiguousFieldDecl(ClassDecl, MemberOrBase);
4450}
4451
4454 Scope *S,
4455 CXXScopeSpec &SS,
4456 IdentifierInfo *MemberOrBase,
4457 ParsedType TemplateTypeTy,
4458 const DeclSpec &DS,
4459 SourceLocation IdLoc,
4460 Expr *Init,
4461 SourceLocation EllipsisLoc) {
4462 if (!ConstructorD || !Init)
4463 return true;
4464
4465 AdjustDeclIfTemplate(ConstructorD);
4466
4468 = dyn_cast<CXXConstructorDecl>(ConstructorD);
4469 if (!Constructor) {
4470 // The user wrote a constructor initializer on a function that is
4471 // not a C++ constructor. Ignore the error for now, because we may
4472 // have more member initializers coming; we'll diagnose it just
4473 // once in ActOnMemInitializers.
4474 return true;
4475 }
4476
4477 CXXRecordDecl *ClassDecl = Constructor->getParent();
4478
4479 // C++ [class.base.init]p2:
4480 // Names in a mem-initializer-id are looked up in the scope of the
4481 // constructor's class and, if not found in that scope, are looked
4482 // up in the scope containing the constructor's definition.
4483 // [Note: if the constructor's class contains a member with the
4484 // same name as a direct or virtual base class of the class, a
4485 // mem-initializer-id naming the member or base class and composed
4486 // of a single identifier refers to the class member. A
4487 // mem-initializer-id for the hidden base class may be specified
4488 // using a qualified name. ]
4489
4490 // Look for a member, first.
4492 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
4493 if (EllipsisLoc.isValid())
4494 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
4495 << MemberOrBase
4496 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4497
4498 return BuildMemberInitializer(Member, Init, IdLoc);
4499 }
4500 // It didn't name a member, so see if it names a class.
4501 QualType BaseType;
4502 TypeSourceInfo *TInfo = nullptr;
4503
4504 if (TemplateTypeTy) {
4505 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
4506 if (BaseType.isNull())
4507 return true;
4508 } else if (DS.getTypeSpecType() == TST_decltype) {
4509 BaseType = BuildDecltypeType(DS.getRepAsExpr());
4510 } else if (DS.getTypeSpecType() == TST_decltype_auto) {
4511 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
4512 return true;
4513 } else if (DS.getTypeSpecType() == TST_typename_pack_indexing) {
4514 BaseType =
4516 DS.getBeginLoc(), DS.getEllipsisLoc());
4517 } else {
4518 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
4519 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
4520
4521 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
4522 if (!TyD) {
4523 if (R.isAmbiguous()) return true;
4524
4525 // We don't want access-control diagnostics here.
4526 R.suppressDiagnostics();
4527
4528 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
4529 bool NotUnknownSpecialization = false;
4530 DeclContext *DC = computeDeclContext(SS, false);
4531 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
4532 NotUnknownSpecialization = !Record->hasAnyDependentBases();
4533
4534 if (!NotUnknownSpecialization) {
4535 // When the scope specifier can refer to a member of an unknown
4536 // specialization, we take it as a type name.
4537 BaseType = CheckTypenameType(
4539 SS.getWithLocInContext(Context), *MemberOrBase, IdLoc);
4540 if (BaseType.isNull())
4541 return true;
4542
4543 TInfo = Context.CreateTypeSourceInfo(BaseType);
4546 if (!TL.isNull()) {
4547 TL.setNameLoc(IdLoc);
4550 }
4551
4552 R.clear();
4553 R.setLookupName(MemberOrBase);
4554 }
4555 }
4556
4557 if (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus20) {
4558 if (auto UnqualifiedBase = R.getAsSingle<ClassTemplateDecl>()) {
4559 auto *TempSpec = cast<TemplateSpecializationType>(
4560 UnqualifiedBase->getCanonicalInjectedSpecializationType(Context));
4561 TemplateName TN = TempSpec->getTemplateName();
4562 for (auto const &Base : ClassDecl->bases()) {
4563 auto BaseTemplate =
4564 Base.getType()->getAs<TemplateSpecializationType>();
4565 if (BaseTemplate &&
4566 Context.hasSameTemplateName(BaseTemplate->getTemplateName(), TN,
4567 /*IgnoreDeduced=*/true)) {
4568 Diag(IdLoc, diag::ext_unqualified_base_class)
4569 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4570 BaseType = Base.getType();
4571 break;
4572 }
4573 }
4574 }
4575 }
4576
4577 // If no results were found, try to correct typos.
4578 TypoCorrection Corr;
4579 MemInitializerValidatorCCC CCC(ClassDecl);
4580 if (R.empty() && BaseType.isNull() &&
4581 (Corr =
4582 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
4583 CCC, CorrectTypoKind::ErrorRecovery, ClassDecl))) {
4585 // We have found a non-static data member with a similar
4586 // name to what was typed; complain and initialize that
4587 // member.
4588 diagnoseTypo(Corr,
4589 PDiag(diag::err_mem_init_not_member_or_class_suggest)
4590 << MemberOrBase << true);
4591 return BuildMemberInitializer(Member, Init, IdLoc);
4592 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
4593 const CXXBaseSpecifier *DirectBaseSpec;
4594 const CXXBaseSpecifier *VirtualBaseSpec;
4595 if (FindBaseInitializer(*this, ClassDecl,
4596 Context.getTypeDeclType(Type),
4597 DirectBaseSpec, VirtualBaseSpec)) {
4598 // We have found a direct or virtual base class with a
4599 // similar name to what was typed; complain and initialize
4600 // that base class.
4601 diagnoseTypo(Corr,
4602 PDiag(diag::err_mem_init_not_member_or_class_suggest)
4603 << MemberOrBase << false,
4604 PDiag() /*Suppress note, we provide our own.*/);
4605
4606 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
4607 : VirtualBaseSpec;
4608 Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
4609 << BaseSpec->getType() << BaseSpec->getSourceRange();
4610
4611 TyD = Type;
4612 }
4613 }
4614 }
4615
4616 if (!TyD && BaseType.isNull()) {
4617 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
4618 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4619 return true;
4620 }
4621 }
4622
4623 if (BaseType.isNull()) {
4624 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
4625
4626 TypeLocBuilder TLB;
4627 // FIXME: This is missing building the UsingType for TyD, if any.
4628 if (const auto *TD = dyn_cast<TagDecl>(TyD)) {
4629 BaseType = Context.getTagType(ElaboratedTypeKeyword::None,
4630 SS.getScopeRep(), TD, /*OwnsTag=*/false);
4631 auto TL = TLB.push<TagTypeLoc>(BaseType);
4633 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4634 TL.setNameLoc(IdLoc);
4635 } else if (auto *TN = dyn_cast<TypedefNameDecl>(TyD)) {
4636 BaseType = Context.getTypedefType(ElaboratedTypeKeyword::None,
4637 SS.getScopeRep(), TN);
4638 TLB.push<TypedefTypeLoc>(BaseType).set(
4639 /*ElaboratedKeywordLoc=*/SourceLocation(),
4640 SS.getWithLocInContext(Context), IdLoc);
4641 } else if (auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(TyD)) {
4642 BaseType = Context.getUnresolvedUsingType(ElaboratedTypeKeyword::None,
4643 SS.getScopeRep(), UD);
4644 TLB.push<UnresolvedUsingTypeLoc>(BaseType).set(
4645 /*ElaboratedKeywordLoc=*/SourceLocation(),
4646 SS.getWithLocInContext(Context), IdLoc);
4647 } else {
4648 // FIXME: What else can appear here?
4649 assert(SS.isEmpty());
4650 BaseType = Context.getTypeDeclType(TyD);
4651 TLB.pushTypeSpec(BaseType).setNameLoc(IdLoc);
4652 }
4653 TInfo = TLB.getTypeSourceInfo(Context, BaseType);
4654 }
4655 }
4656
4657 if (!TInfo)
4658 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
4659
4660 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
4661}
4662
4665 SourceLocation IdLoc) {
4666 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
4667 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
4668 assert((DirectMember || IndirectMember) &&
4669 "Member must be a FieldDecl or IndirectFieldDecl");
4670
4672 return true;
4673
4674 if (Member->isInvalidDecl())
4675 return true;
4676
4677 MultiExprArg Args;
4678 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4679 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4680 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4681 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4682 } else {
4683 // Template instantiation doesn't reconstruct ParenListExprs for us.
4684 Args = Init;
4685 }
4686
4687 SourceRange InitRange = Init->getSourceRange();
4688
4689 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4690 // Can't check initialization for a member of dependent type or when
4691 // any of the arguments are type-dependent expressions.
4693 } else {
4694 bool InitList = false;
4695 if (isa<InitListExpr>(Init)) {
4696 InitList = true;
4697 Args = Init;
4698 }
4699
4700 // Initialize the member.
4701 InitializedEntity MemberEntity =
4702 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4703 : InitializedEntity::InitializeMember(IndirectMember,
4704 nullptr);
4705 InitializationKind Kind =
4707 IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4708 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4709 InitRange.getEnd());
4710
4711 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4712 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4713 nullptr);
4714 if (!MemberInit.isInvalid()) {
4715 // C++11 [class.base.init]p7:
4716 // The initialization of each base and member constitutes a
4717 // full-expression.
4718 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
4719 /*DiscardedValue*/ false);
4720 }
4721
4722 if (MemberInit.isInvalid()) {
4723 // Args were sensible expressions but we couldn't initialize the member
4724 // from them. Preserve them in a RecoveryExpr instead.
4725 Init = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,
4726 Member->getType())
4727 .get();
4728 if (!Init)
4729 return true;
4730 } else {
4731 Init = MemberInit.get();
4732 }
4733 }
4734
4735 if (DirectMember) {
4736 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4737 InitRange.getBegin(), Init,
4738 InitRange.getEnd());
4739 } else {
4740 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4741 InitRange.getBegin(), Init,
4742 InitRange.getEnd());
4743 }
4744}
4745
4748 CXXRecordDecl *ClassDecl) {
4749 SourceLocation NameLoc = TInfo->getTypeLoc().getSourceRange().getBegin();
4750 if (!LangOpts.CPlusPlus11)
4751 return Diag(NameLoc, diag::err_delegating_ctor)
4752 << TInfo->getTypeLoc().getSourceRange();
4753 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4754
4755 bool InitList = true;
4756 MultiExprArg Args = Init;
4757 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4758 InitList = false;
4759 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4760 }
4761
4762 CanQualType ClassType = Context.getCanonicalTagType(ClassDecl);
4763
4764 SourceRange InitRange = Init->getSourceRange();
4765 // Initialize the object.
4766 InitializedEntity DelegationEntity =
4768 InitializationKind Kind =
4770 NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4771 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4772 InitRange.getEnd());
4773 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4774 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4775 Args, nullptr);
4776 if (!DelegationInit.isInvalid()) {
4777 assert((DelegationInit.get()->containsErrors() ||
4778 cast<CXXConstructExpr>(DelegationInit.get())->getConstructor()) &&
4779 "Delegating constructor with no target?");
4780
4781 // C++11 [class.base.init]p7:
4782 // The initialization of each base and member constitutes a
4783 // full-expression.
4784 DelegationInit = ActOnFinishFullExpr(
4785 DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
4786 }
4787
4788 if (DelegationInit.isInvalid()) {
4789 DelegationInit = CreateRecoveryExpr(InitRange.getBegin(),
4790 InitRange.getEnd(), Args, ClassType);
4791 if (DelegationInit.isInvalid())
4792 return true;
4793 } else {
4794 // If we are in a dependent context, template instantiation will
4795 // perform this type-checking again. Just save the arguments that we
4796 // received in a ParenListExpr.
4797 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4798 // of the information that we have about the base
4799 // initializer. However, deconstructing the ASTs is a dicey process,
4800 // and this approach is far more likely to get the corner cases right.
4801 if (CurContext->isDependentContext())
4802 DelegationInit = Init;
4803 }
4804
4805 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4806 DelegationInit.getAs<Expr>(),
4807 InitRange.getEnd());
4808}
4809
4812 Expr *Init, CXXRecordDecl *ClassDecl,
4813 SourceLocation EllipsisLoc) {
4814 SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getBeginLoc();
4815
4816 if (!BaseType->isDependentType() && !BaseType->isRecordType())
4817 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4818 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
4819
4820 // C++ [class.base.init]p2:
4821 // [...] Unless the mem-initializer-id names a nonstatic data
4822 // member of the constructor's class or a direct or virtual base
4823 // of that class, the mem-initializer is ill-formed. A
4824 // mem-initializer-list can initialize a base class using any
4825 // name that denotes that base class type.
4826
4827 // We can store the initializers in "as-written" form and delay analysis until
4828 // instantiation if the constructor is dependent. But not for dependent
4829 // (broken) code in a non-template! SetCtorInitializers does not expect this.
4830 bool Dependent = CurContext->isDependentContext() &&
4831 (BaseType->isDependentType() || Init->isTypeDependent());
4832
4833 SourceRange InitRange = Init->getSourceRange();
4834 if (EllipsisLoc.isValid()) {
4835 // This is a pack expansion.
4836 if (!BaseType->containsUnexpandedParameterPack()) {
4837 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4838 << SourceRange(BaseLoc, InitRange.getEnd());
4839
4840 EllipsisLoc = SourceLocation();
4841 }
4842 } else {
4843 // Check for any unexpanded parameter packs.
4844 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4845 return true;
4846
4848 return true;
4849 }
4850
4851 // Check for direct and virtual base classes.
4852 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4853 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4854 if (!Dependent) {
4855 if (declaresSameEntity(ClassDecl, BaseType->getAsCXXRecordDecl()))
4856 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4857
4858 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4859 VirtualBaseSpec);
4860
4861 // C++ [base.class.init]p2:
4862 // Unless the mem-initializer-id names a nonstatic data member of the
4863 // constructor's class or a direct or virtual base of that class, the
4864 // mem-initializer is ill-formed.
4865 if (!DirectBaseSpec && !VirtualBaseSpec) {
4866 // If the class has any dependent bases, then it's possible that
4867 // one of those types will resolve to the same type as
4868 // BaseType. Therefore, just treat this as a dependent base
4869 // class initialization. FIXME: Should we try to check the
4870 // initialization anyway? It seems odd.
4871 if (ClassDecl->hasAnyDependentBases())
4872 Dependent = true;
4873 else
4874 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4875 << BaseType << Context.getCanonicalTagType(ClassDecl)
4876 << BaseTInfo->getTypeLoc().getSourceRange();
4877 }
4878 }
4879
4880 if (Dependent) {
4882
4883 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4884 /*IsVirtual=*/false,
4885 InitRange.getBegin(), Init,
4886 InitRange.getEnd(), EllipsisLoc);
4887 }
4888
4889 // C++ [base.class.init]p2:
4890 // If a mem-initializer-id is ambiguous because it designates both
4891 // a direct non-virtual base class and an inherited virtual base
4892 // class, the mem-initializer is ill-formed.
4893 if (DirectBaseSpec && VirtualBaseSpec)
4894 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4895 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4896
4897 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4898 if (!BaseSpec)
4899 BaseSpec = VirtualBaseSpec;
4900
4901 // Initialize the base.
4902 bool InitList = true;
4903 MultiExprArg Args = Init;
4904 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4905 InitList = false;
4906 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4907 }
4908
4909 InitializedEntity BaseEntity =
4910 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4911 InitializationKind Kind =
4912 InitList ? InitializationKind::CreateDirectList(BaseLoc)
4913 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4914 InitRange.getEnd());
4915 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4916 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4917 if (!BaseInit.isInvalid()) {
4918 // C++11 [class.base.init]p7:
4919 // The initialization of each base and member constitutes a
4920 // full-expression.
4921 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
4922 /*DiscardedValue*/ false);
4923 }
4924
4925 if (BaseInit.isInvalid()) {
4926 BaseInit = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(),
4927 Args, BaseType);
4928 if (BaseInit.isInvalid())
4929 return true;
4930 } else {
4931 // If we are in a dependent context, template instantiation will
4932 // perform this type-checking again. Just save the arguments that we
4933 // received in a ParenListExpr.
4934 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4935 // of the information that we have about the base
4936 // initializer. However, deconstructing the ASTs is a dicey process,
4937 // and this approach is far more likely to get the corner cases right.
4938 if (CurContext->isDependentContext())
4939 BaseInit = Init;
4940 }
4941
4942 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4943 BaseSpec->isVirtual(),
4944 InitRange.getBegin(),
4945 BaseInit.getAs<Expr>(),
4946 InitRange.getEnd(), EllipsisLoc);
4947}
4948
4949// Create a static_cast<T&&>(expr).
4950static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
4951 QualType TargetType =
4952 SemaRef.BuildReferenceType(E->getType(), /*SpelledAsLValue*/ false,
4954 SourceLocation ExprLoc = E->getBeginLoc();
4955 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4956 TargetType, ExprLoc);
4957
4958 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4959 SourceRange(ExprLoc, ExprLoc),
4960 E->getSourceRange()).get();
4961}
4962
4963/// ImplicitInitializerKind - How an implicit base or member initializer should
4964/// initialize its base or member.
4971
4972static bool
4974 ImplicitInitializerKind ImplicitInitKind,
4975 CXXBaseSpecifier *BaseSpec,
4976 bool IsInheritedVirtualBase,
4977 CXXCtorInitializer *&CXXBaseInit) {
4978 InitializedEntity InitEntity
4979 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4980 IsInheritedVirtualBase);
4981
4982 ExprResult BaseInit;
4983
4984 switch (ImplicitInitKind) {
4985 case IIK_Inherit:
4986 case IIK_Default: {
4987 InitializationKind InitKind
4989 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, {});
4990 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, {});
4991 break;
4992 }
4993
4994 case IIK_Move:
4995 case IIK_Copy: {
4996 bool Moving = ImplicitInitKind == IIK_Move;
4997 ParmVarDecl *Param = Constructor->getParamDecl(0);
4998 QualType ParamType = Param->getType().getNonReferenceType();
4999
5000 Expr *CopyCtorArg =
5002 SourceLocation(), Param, false,
5003 Constructor->getLocation(), ParamType,
5004 VK_LValue, nullptr);
5005
5006 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
5007
5008 // Cast to the base class to avoid ambiguities.
5009 QualType ArgTy =
5010 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
5011 ParamType.getQualifiers());
5012
5013 if (Moving) {
5014 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
5015 }
5016
5017 CXXCastPath BasePath;
5018 BasePath.push_back(BaseSpec);
5019 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
5020 CK_UncheckedDerivedToBase,
5021 Moving ? VK_XValue : VK_LValue,
5022 &BasePath).get();
5023
5024 InitializationKind InitKind
5027 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
5028 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
5029 break;
5030 }
5031 }
5032
5033 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
5034 if (BaseInit.isInvalid())
5035 return true;
5036
5037 CXXBaseInit =
5038 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5039 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
5040 SourceLocation()),
5041 BaseSpec->isVirtual(),
5043 BaseInit.getAs<Expr>(),
5045 SourceLocation());
5046
5047 return false;
5048}
5049
5050static bool RefersToRValueRef(Expr *MemRef) {
5051 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
5052 return Referenced->getType()->isRValueReferenceType();
5053}
5054
5055static bool
5057 ImplicitInitializerKind ImplicitInitKind,
5058 FieldDecl *Field, IndirectFieldDecl *Indirect,
5059 CXXCtorInitializer *&CXXMemberInit) {
5060 if (Field->isInvalidDecl())
5061 return true;
5062
5063 SourceLocation Loc = Constructor->getLocation();
5064
5065 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
5066 bool Moving = ImplicitInitKind == IIK_Move;
5067 ParmVarDecl *Param = Constructor->getParamDecl(0);
5068 QualType ParamType = Param->getType().getNonReferenceType();
5069
5070 // Suppress copying zero-width bitfields.
5071 if (Field->isZeroLengthBitField())
5072 return false;
5073
5074 Expr *MemberExprBase =
5076 SourceLocation(), Param, false,
5077 Loc, ParamType, VK_LValue, nullptr);
5078
5079 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
5080
5081 if (Moving) {
5082 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
5083 }
5084
5085 // Build a reference to this field within the parameter.
5086 CXXScopeSpec SS;
5087 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
5089 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
5090 : cast<ValueDecl>(Field), AS_public);
5091 MemberLookup.resolveKind();
5092 ExprResult CtorArg
5093 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
5094 ParamType, Loc,
5095 /*IsArrow=*/false,
5096 SS,
5097 /*TemplateKWLoc=*/SourceLocation(),
5098 /*FirstQualifierInScope=*/nullptr,
5099 MemberLookup,
5100 /*TemplateArgs=*/nullptr,
5101 /*S*/nullptr);
5102 if (CtorArg.isInvalid())
5103 return true;
5104
5105 // C++11 [class.copy]p15:
5106 // - if a member m has rvalue reference type T&&, it is direct-initialized
5107 // with static_cast<T&&>(x.m);
5108 if (RefersToRValueRef(CtorArg.get())) {
5109 CtorArg = CastForMoving(SemaRef, CtorArg.get());
5110 }
5111
5112 InitializedEntity Entity =
5115
5116 // Direct-initialize to use the copy constructor.
5117 InitializationKind InitKind =
5119
5120 Expr *CtorArgE = CtorArg.getAs<Expr>();
5121 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
5122 ExprResult MemberInit =
5123 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
5124 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
5125 if (MemberInit.isInvalid())
5126 return true;
5127
5128 if (Indirect)
5129 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
5130 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
5131 else
5132 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
5133 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
5134 return false;
5135 }
5136
5137 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
5138 "Unhandled implicit init kind!");
5139
5140 QualType FieldBaseElementType =
5141 SemaRef.Context.getBaseElementType(Field->getType());
5142
5143 if (FieldBaseElementType->isRecordType()) {
5144 InitializedEntity InitEntity =
5147 InitializationKind InitKind =
5149
5150 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, {});
5151 ExprResult MemberInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, {});
5152
5153 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
5154 if (MemberInit.isInvalid())
5155 return true;
5156
5157 if (Indirect)
5158 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5159 Indirect, Loc,
5160 Loc,
5161 MemberInit.get(),
5162 Loc);
5163 else
5164 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5165 Field, Loc, Loc,
5166 MemberInit.get(),
5167 Loc);
5168 return false;
5169 }
5170
5171 if (!Field->getParent()->isUnion()) {
5172 if (FieldBaseElementType->isReferenceType()) {
5173 SemaRef.Diag(Constructor->getLocation(),
5174 diag::err_uninitialized_member_in_ctor)
5175 << (int)Constructor->isImplicit()
5176 << SemaRef.Context.getCanonicalTagType(Constructor->getParent()) << 0
5177 << Field->getDeclName();
5178 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
5179 return true;
5180 }
5181
5182 if (FieldBaseElementType.isConstQualified()) {
5183 SemaRef.Diag(Constructor->getLocation(),
5184 diag::err_uninitialized_member_in_ctor)
5185 << (int)Constructor->isImplicit()
5186 << SemaRef.Context.getCanonicalTagType(Constructor->getParent()) << 1
5187 << Field->getDeclName();
5188 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
5189 return true;
5190 }
5191 }
5192
5193 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
5194 // ARC and Weak:
5195 // Default-initialize Objective-C pointers to NULL.
5196 CXXMemberInit
5197 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
5198 Loc, Loc,
5199 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
5200 Loc);
5201 return false;
5202 }
5203
5204 // Nothing to initialize.
5205 CXXMemberInit = nullptr;
5206 return false;
5207}
5208
5209namespace {
5210struct BaseAndFieldInfo {
5211 Sema &S;
5212 CXXConstructorDecl *Ctor;
5213 bool AnyErrorsInInits;
5215 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
5216 SmallVector<CXXCtorInitializer*, 8> AllToInit;
5217 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
5218
5219 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
5220 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
5221 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
5222 if (Ctor->getInheritedConstructor())
5223 IIK = IIK_Inherit;
5224 else if (Generated && Ctor->isCopyConstructor())
5225 IIK = IIK_Copy;
5226 else if (Generated && Ctor->isMoveConstructor())
5227 IIK = IIK_Move;
5228 else
5229 IIK = IIK_Default;
5230 }
5231
5232 bool isImplicitCopyOrMove() const {
5233 switch (IIK) {
5234 case IIK_Copy:
5235 case IIK_Move:
5236 return true;
5237
5238 case IIK_Default:
5239 case IIK_Inherit:
5240 return false;
5241 }
5242
5243 llvm_unreachable("Invalid ImplicitInitializerKind!");
5244 }
5245
5246 bool addFieldInitializer(CXXCtorInitializer *Init) {
5247 AllToInit.push_back(Init);
5248
5249 // Check whether this initializer makes the field "used".
5250 if (Init->getInit()->HasSideEffects(S.Context))
5251 S.UnusedPrivateFields.remove(Init->getAnyMember());
5252
5253 return false;
5254 }
5255
5256 bool isInactiveUnionMember(FieldDecl *Field) {
5257 RecordDecl *Record = Field->getParent();
5258 if (!Record->isUnion())
5259 return false;
5260
5261 if (FieldDecl *Active =
5262 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
5263 return Active != Field->getCanonicalDecl();
5264
5265 // In an implicit copy or move constructor, ignore any in-class initializer.
5266 if (isImplicitCopyOrMove())
5267 return true;
5268
5269 // If there's no explicit initialization, the field is active only if it
5270 // has an in-class initializer...
5271 if (Field->hasInClassInitializer())
5272 return false;
5273 // ... or it's an anonymous struct or union whose class has an in-class
5274 // initializer.
5275 if (!Field->isAnonymousStructOrUnion())
5276 return true;
5277 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
5278 return !FieldRD->hasInClassInitializer();
5279 }
5280
5281 /// Determine whether the given field is, or is within, a union member
5282 /// that is inactive (because there was an initializer given for a different
5283 /// member of the union, or because the union was not initialized at all).
5284 bool isWithinInactiveUnionMember(FieldDecl *Field,
5285 IndirectFieldDecl *Indirect) {
5286 if (!Indirect)
5287 return isInactiveUnionMember(Field);
5288
5289 for (auto *C : Indirect->chain()) {
5290 FieldDecl *Field = dyn_cast<FieldDecl>(C);
5291 if (Field && isInactiveUnionMember(Field))
5292 return true;
5293 }
5294 return false;
5295 }
5296};
5297}
5298
5299/// Determine whether the given type is an incomplete or zero-lenfgth
5300/// array type.
5302 if (T->isIncompleteArrayType())
5303 return true;
5304
5305 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
5306 if (ArrayT->isZeroSize())
5307 return true;
5308
5309 T = ArrayT->getElementType();
5310 }
5311
5312 return false;
5313}
5314
5315static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
5316 FieldDecl *Field,
5317 IndirectFieldDecl *Indirect = nullptr) {
5318 if (Field->isInvalidDecl())
5319 return false;
5320
5321 // Overwhelmingly common case: we have a direct initializer for this field.
5323 Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
5324 return Info.addFieldInitializer(Init);
5325
5326 // C++11 [class.base.init]p8:
5327 // if the entity is a non-static data member that has a
5328 // brace-or-equal-initializer and either
5329 // -- the constructor's class is a union and no other variant member of that
5330 // union is designated by a mem-initializer-id or
5331 // -- the constructor's class is not a union, and, if the entity is a member
5332 // of an anonymous union, no other member of that union is designated by
5333 // a mem-initializer-id,
5334 // the entity is initialized as specified in [dcl.init].
5335 //
5336 // We also apply the same rules to handle anonymous structs within anonymous
5337 // unions.
5338 if (Info.isWithinInactiveUnionMember(Field, Indirect))
5339 return false;
5340
5341 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
5342 ExprResult DIE =
5343 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
5344 if (DIE.isInvalid())
5345 return true;
5346
5348 SemaRef.checkInitializerLifetime(Entity, DIE.get());
5349
5351 if (Indirect)
5352 Init = new (SemaRef.Context)
5353 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
5354 SourceLocation(), DIE.get(), SourceLocation());
5355 else
5356 Init = new (SemaRef.Context)
5357 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
5358 SourceLocation(), DIE.get(), SourceLocation());
5359 return Info.addFieldInitializer(Init);
5360 }
5361
5362 // Don't initialize incomplete or zero-length arrays.
5363 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
5364 return false;
5365
5366 // Don't try to build an implicit initializer if there were semantic
5367 // errors in any of the initializers (and therefore we might be
5368 // missing some that the user actually wrote).
5369 if (Info.AnyErrorsInInits)
5370 return false;
5371
5372 CXXCtorInitializer *Init = nullptr;
5373 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
5374 Indirect, Init))
5375 return true;
5376
5377 if (!Init)
5378 return false;
5379
5380 return Info.addFieldInitializer(Init);
5381}
5382
5383bool
5386 assert(Initializer->isDelegatingInitializer());
5387 Constructor->setNumCtorInitializers(1);
5388 CXXCtorInitializer **initializer =
5389 new (Context) CXXCtorInitializer*[1];
5390 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
5391 Constructor->setCtorInitializers(initializer);
5392
5393 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
5394 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
5395 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
5396 }
5397
5399
5400 DiagnoseUninitializedFields(*this, Constructor);
5401
5402 return false;
5403}
5404
5406 CXXRecordDecl *Class) {
5407 if (Class->isInvalidDecl())
5408 return nullptr;
5409 if (Class->hasIrrelevantDestructor())
5410 return nullptr;
5411
5412 // Dtor might still be missing, e.g because it's invalid.
5413 return S.LookupDestructor(Class);
5414}
5415
5417 FieldDecl *Field) {
5418 if (Field->isInvalidDecl())
5419 return;
5420
5421 // Don't destroy incomplete or zero-length arrays.
5422 if (isIncompleteOrZeroLengthArrayType(S.Context, Field->getType()))
5423 return;
5424
5425 QualType FieldType = S.Context.getBaseElementType(Field->getType());
5426
5427 auto *FieldClassDecl = FieldType->getAsCXXRecordDecl();
5428 if (!FieldClassDecl)
5429 return;
5430
5431 // The destructor for an implicit anonymous union member is never invoked.
5432 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5433 return;
5434
5435 auto *Dtor = LookupDestructorIfRelevant(S, FieldClassDecl);
5436 if (!Dtor)
5437 return;
5438
5439 S.CheckDestructorAccess(Field->getLocation(), Dtor,
5440 S.PDiag(diag::err_access_dtor_field)
5441 << Field->getDeclName() << FieldType);
5442
5443 S.MarkFunctionReferenced(Location, Dtor);
5444 S.DiagnoseUseOfDecl(Dtor, Location);
5445}
5446
5448 CXXRecordDecl *ClassDecl) {
5449 if (ClassDecl->isDependentContext())
5450 return;
5451
5452 // We only potentially invoke the destructors of potentially constructed
5453 // subobjects.
5454 bool VisitVirtualBases = !ClassDecl->isAbstract();
5455
5456 // If the destructor exists and has already been marked used in the MS ABI,
5457 // then virtual base destructors have already been checked and marked used.
5458 // Skip checking them again to avoid duplicate diagnostics.
5460 CXXDestructorDecl *Dtor = ClassDecl->getDestructor();
5461 if (Dtor && Dtor->isUsed())
5462 VisitVirtualBases = false;
5463 }
5464
5466
5467 // Bases.
5468 for (const auto &Base : ClassDecl->bases()) {
5469 auto *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
5470 if (!BaseClassDecl)
5471 continue;
5472
5473 // Remember direct virtual bases.
5474 if (Base.isVirtual()) {
5475 if (!VisitVirtualBases)
5476 continue;
5477 DirectVirtualBases.insert(BaseClassDecl);
5478 }
5479
5480 auto *Dtor = LookupDestructorIfRelevant(S, BaseClassDecl);
5481 if (!Dtor)
5482 continue;
5483
5484 // FIXME: caret should be on the start of the class name
5485 S.CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5486 S.PDiag(diag::err_access_dtor_base)
5487 << Base.getType() << Base.getSourceRange(),
5488 S.Context.getCanonicalTagType(ClassDecl));
5489
5490 S.MarkFunctionReferenced(Location, Dtor);
5491 S.DiagnoseUseOfDecl(Dtor, Location);
5492 }
5493
5494 if (VisitVirtualBases)
5495 S.MarkVirtualBaseDestructorsReferenced(Location, ClassDecl,
5496 &DirectVirtualBases);
5497}
5498
5500 ArrayRef<CXXCtorInitializer *> Initializers) {
5501 if (Constructor->isDependentContext()) {
5502 // Just store the initializers as written, they will be checked during
5503 // instantiation.
5504 if (!Initializers.empty()) {
5505 Constructor->setNumCtorInitializers(Initializers.size());
5506 CXXCtorInitializer **baseOrMemberInitializers =
5507 new (Context) CXXCtorInitializer*[Initializers.size()];
5508 memcpy(baseOrMemberInitializers, Initializers.data(),
5509 Initializers.size() * sizeof(CXXCtorInitializer*));
5510 Constructor->setCtorInitializers(baseOrMemberInitializers);
5511 }
5512
5513 // Let template instantiation know whether we had errors.
5514 if (AnyErrors)
5515 Constructor->setInvalidDecl();
5516
5517 return false;
5518 }
5519
5520 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
5521
5522 // We need to build the initializer AST according to order of construction
5523 // and not what user specified in the Initializers list.
5524 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
5525 if (!ClassDecl)
5526 return true;
5527
5528 bool HadError = false;
5529
5530 for (CXXCtorInitializer *Member : Initializers) {
5531 if (Member->isBaseInitializer())
5532 Info.AllBaseFields[Member->getBaseClass()->getAsCanonical<RecordType>()] =
5533 Member;
5534 else {
5535 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
5536
5537 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
5538 for (auto *C : F->chain()) {
5539 FieldDecl *FD = dyn_cast<FieldDecl>(C);
5540 if (FD && FD->getParent()->isUnion())
5541 Info.ActiveUnionMember.insert(std::make_pair(
5543 }
5544 } else if (FieldDecl *FD = Member->getMember()) {
5545 if (FD->getParent()->isUnion())
5546 Info.ActiveUnionMember.insert(std::make_pair(
5548 }
5549 }
5550 }
5551
5552 // Keep track of the direct virtual bases.
5554 for (auto &I : ClassDecl->bases()) {
5555 if (I.isVirtual())
5556 DirectVBases.insert(&I);
5557 }
5558
5559 // Push virtual bases before others.
5560 for (auto &VBase : ClassDecl->vbases()) {
5561 if (CXXCtorInitializer *Value = Info.AllBaseFields.lookup(
5562 VBase.getType()->getAsCanonical<RecordType>())) {
5563 // [class.base.init]p7, per DR257:
5564 // A mem-initializer where the mem-initializer-id names a virtual base
5565 // class is ignored during execution of a constructor of any class that
5566 // is not the most derived class.
5567 if (ClassDecl->isAbstract()) {
5568 // FIXME: Provide a fixit to remove the base specifier. This requires
5569 // tracking the location of the associated comma for a base specifier.
5570 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
5571 << VBase.getType() << ClassDecl;
5572 DiagnoseAbstractType(ClassDecl);
5573 }
5574
5575 Info.AllToInit.push_back(Value);
5576 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
5577 // [class.base.init]p8, per DR257:
5578 // If a given [...] base class is not named by a mem-initializer-id
5579 // [...] and the entity is not a virtual base class of an abstract
5580 // class, then [...] the entity is default-initialized.
5581 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
5582 CXXCtorInitializer *CXXBaseInit;
5583 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5584 &VBase, IsInheritedVirtualBase,
5585 CXXBaseInit)) {
5586 HadError = true;
5587 continue;
5588 }
5589
5590 Info.AllToInit.push_back(CXXBaseInit);
5591 }
5592 }
5593
5594 // Non-virtual bases.
5595 for (auto &Base : ClassDecl->bases()) {
5596 // Virtuals are in the virtual base list and already constructed.
5597 if (Base.isVirtual())
5598 continue;
5599
5600 if (CXXCtorInitializer *Value = Info.AllBaseFields.lookup(
5601 Base.getType()->getAsCanonical<RecordType>())) {
5602 Info.AllToInit.push_back(Value);
5603 } else if (!AnyErrors) {
5604 CXXCtorInitializer *CXXBaseInit;
5605 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5606 &Base, /*IsInheritedVirtualBase=*/false,
5607 CXXBaseInit)) {
5608 HadError = true;
5609 continue;
5610 }
5611
5612 Info.AllToInit.push_back(CXXBaseInit);
5613 }
5614 }
5615
5616 // Fields.
5617 for (auto *Mem : ClassDecl->decls()) {
5618 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
5619 // C++ [class.bit]p2:
5620 // A declaration for a bit-field that omits the identifier declares an
5621 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
5622 // initialized.
5623 if (F->isUnnamedBitField())
5624 continue;
5625
5626 // If we're not generating the implicit copy/move constructor, then we'll
5627 // handle anonymous struct/union fields based on their individual
5628 // indirect fields.
5629 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
5630 continue;
5631
5632 if (CollectFieldInitializer(*this, Info, F))
5633 HadError = true;
5634 continue;
5635 }
5636
5637 // Beyond this point, we only consider default initialization.
5638 if (Info.isImplicitCopyOrMove())
5639 continue;
5640
5641 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
5642 if (F->getType()->isIncompleteArrayType()) {
5643 assert(ClassDecl->hasFlexibleArrayMember() &&
5644 "Incomplete array type is not valid");
5645 continue;
5646 }
5647
5648 // Initialize each field of an anonymous struct individually.
5649 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
5650 HadError = true;
5651
5652 continue;
5653 }
5654 }
5655
5656 unsigned NumInitializers = Info.AllToInit.size();
5657 if (NumInitializers > 0) {
5658 Constructor->setNumCtorInitializers(NumInitializers);
5659 CXXCtorInitializer **baseOrMemberInitializers =
5660 new (Context) CXXCtorInitializer*[NumInitializers];
5661 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
5662 NumInitializers * sizeof(CXXCtorInitializer*));
5663 Constructor->setCtorInitializers(baseOrMemberInitializers);
5664
5665 SourceLocation Location = Constructor->getLocation();
5666
5667 // Constructors implicitly reference the base and member
5668 // destructors.
5669
5670 for (CXXCtorInitializer *Initializer : Info.AllToInit) {
5671 FieldDecl *Field = Initializer->getAnyMember();
5672 if (!Field)
5673 continue;
5674
5675 // C++ [class.base.init]p12:
5676 // In a non-delegating constructor, the destructor for each
5677 // potentially constructed subobject of class type is potentially
5678 // invoked.
5679 MarkFieldDestructorReferenced(*this, Location, Field);
5680 }
5681
5682 MarkBaseDestructorsReferenced(*this, Location, Constructor->getParent());
5683 }
5684
5685 return HadError;
5686}
5687
5689 if (const RecordType *RT = Field->getType()->getAsCanonical<RecordType>()) {
5690 const RecordDecl *RD = RT->getDecl();
5691 if (RD->isAnonymousStructOrUnion()) {
5692 for (auto *Field : RD->getDefinitionOrSelf()->fields())
5693 PopulateKeysForFields(Field, IdealInits);
5694 return;
5695 }
5696 }
5697 IdealInits.push_back(Field->getCanonicalDecl());
5698}
5699
5700static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
5701 return Context.getCanonicalType(BaseType).getTypePtr();
5702}
5703
5704static const void *GetKeyForMember(ASTContext &Context,
5706 if (!Member->isAnyMemberInitializer())
5707 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
5708
5709 return Member->getAnyMember()->getCanonicalDecl();
5710}
5711
5714 const CXXCtorInitializer *Current) {
5715 if (Previous->isAnyMemberInitializer())
5716 Diag << 0 << Previous->getAnyMember();
5717 else
5718 Diag << 1 << Previous->getTypeSourceInfo()->getType();
5719
5720 if (Current->isAnyMemberInitializer())
5721 Diag << 0 << Current->getAnyMember();
5722 else
5723 Diag << 1 << Current->getTypeSourceInfo()->getType();
5724}
5725
5727 Sema &SemaRef, const CXXConstructorDecl *Constructor,
5729 if (Constructor->getDeclContext()->isDependentContext())
5730 return;
5731
5732 // Don't check initializers order unless the warning is enabled at the
5733 // location of at least one initializer.
5734 bool ShouldCheckOrder = false;
5735 for (const CXXCtorInitializer *Init : Inits) {
5736 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
5737 Init->getSourceLocation())) {
5738 ShouldCheckOrder = true;
5739 break;
5740 }
5741 }
5742 if (!ShouldCheckOrder)
5743 return;
5744
5745 // Build the list of bases and members in the order that they'll
5746 // actually be initialized. The explicit initializers should be in
5747 // this same order but may be missing things.
5748 SmallVector<const void*, 32> IdealInitKeys;
5749
5750 const CXXRecordDecl *ClassDecl = Constructor->getParent();
5751
5752 // 1. Virtual bases.
5753 for (const auto &VBase : ClassDecl->vbases())
5754 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
5755
5756 // 2. Non-virtual bases.
5757 for (const auto &Base : ClassDecl->bases()) {
5758 if (Base.isVirtual())
5759 continue;
5760 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
5761 }
5762
5763 // 3. Direct fields.
5764 for (auto *Field : ClassDecl->fields()) {
5765 if (Field->isUnnamedBitField())
5766 continue;
5767
5768 PopulateKeysForFields(Field, IdealInitKeys);
5769 }
5770
5771 unsigned NumIdealInits = IdealInitKeys.size();
5772 unsigned IdealIndex = 0;
5773
5774 // Track initializers that are in an incorrect order for either a warning or
5775 // note if multiple ones occur.
5776 SmallVector<unsigned> WarnIndexes;
5777 // Correlates the index of an initializer in the init-list to the index of
5778 // the field/base in the class.
5779 SmallVector<std::pair<unsigned, unsigned>, 32> CorrelatedInitOrder;
5780
5781 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5782 const void *InitKey = GetKeyForMember(SemaRef.Context, Inits[InitIndex]);
5783
5784 // Scan forward to try to find this initializer in the idealized
5785 // initializers list.
5786 for (; IdealIndex != NumIdealInits; ++IdealIndex)
5787 if (InitKey == IdealInitKeys[IdealIndex])
5788 break;
5789
5790 // If we didn't find this initializer, it must be because we
5791 // scanned past it on a previous iteration. That can only
5792 // happen if we're out of order; emit a warning.
5793 if (IdealIndex == NumIdealInits && InitIndex) {
5794 WarnIndexes.push_back(InitIndex);
5795
5796 // Move back to the initializer's location in the ideal list.
5797 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5798 if (InitKey == IdealInitKeys[IdealIndex])
5799 break;
5800
5801 assert(IdealIndex < NumIdealInits &&
5802 "initializer not found in initializer list");
5803 }
5804 CorrelatedInitOrder.emplace_back(IdealIndex, InitIndex);
5805 }
5806
5807 if (WarnIndexes.empty())
5808 return;
5809
5810 // Sort based on the ideal order, first in the pair.
5811 llvm::sort(CorrelatedInitOrder, llvm::less_first());
5812
5813 // Introduce a new scope as SemaDiagnosticBuilder needs to be destroyed to
5814 // emit the diagnostic before we can try adding notes.
5815 {
5817 Inits[WarnIndexes.front() - 1]->getSourceLocation(),
5818 WarnIndexes.size() == 1 ? diag::warn_initializer_out_of_order
5819 : diag::warn_some_initializers_out_of_order);
5820
5821 for (unsigned I = 0; I < CorrelatedInitOrder.size(); ++I) {
5822 if (CorrelatedInitOrder[I].second == I)
5823 continue;
5824 // Ideally we would be using InsertFromRange here, but clang doesn't
5825 // appear to handle InsertFromRange correctly when the source range is
5826 // modified by another fix-it.
5828 Inits[I]->getSourceRange(),
5831 Inits[CorrelatedInitOrder[I].second]->getSourceRange()),
5832 SemaRef.getSourceManager(), SemaRef.getLangOpts()));
5833 }
5834
5835 // If there is only 1 item out of order, the warning expects the name and
5836 // type of each being added to it.
5837 if (WarnIndexes.size() == 1) {
5838 AddInitializerToDiag(D, Inits[WarnIndexes.front() - 1],
5839 Inits[WarnIndexes.front()]);
5840 return;
5841 }
5842 }
5843 // More than 1 item to warn, create notes letting the user know which ones
5844 // are bad.
5845 for (unsigned WarnIndex : WarnIndexes) {
5846 const clang::CXXCtorInitializer *PrevInit = Inits[WarnIndex - 1];
5847 auto D = SemaRef.Diag(PrevInit->getSourceLocation(),
5848 diag::note_initializer_out_of_order);
5849 AddInitializerToDiag(D, PrevInit, Inits[WarnIndex]);
5850 D << PrevInit->getSourceRange();
5851 }
5852}
5853
5854namespace {
5855bool CheckRedundantInit(Sema &S,
5856 CXXCtorInitializer *Init,
5857 CXXCtorInitializer *&PrevInit) {
5858 if (!PrevInit) {
5859 PrevInit = Init;
5860 return false;
5861 }
5862
5863 if (FieldDecl *Field = Init->getAnyMember())
5864 S.Diag(Init->getSourceLocation(),
5865 diag::err_multiple_mem_initialization)
5866 << Field->getDeclName()
5867 << Init->getSourceRange();
5868 else {
5869 const Type *BaseClass = Init->getBaseClass();
5870 assert(BaseClass && "neither field nor base");
5871 S.Diag(Init->getSourceLocation(),
5872 diag::err_multiple_base_initialization)
5873 << QualType(BaseClass, 0)
5874 << Init->getSourceRange();
5875 }
5876 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5877 << 0 << PrevInit->getSourceRange();
5878
5879 return true;
5880}
5881
5882typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5883typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5884
5885bool CheckRedundantUnionInit(Sema &S,
5886 CXXCtorInitializer *Init,
5887 RedundantUnionMap &Unions) {
5888 FieldDecl *Field = Init->getAnyMember();
5889 RecordDecl *Parent = Field->getParent();
5890 NamedDecl *Child = Field;
5891
5892 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5893 if (Parent->isUnion()) {
5894 UnionEntry &En = Unions[Parent];
5895 if (En.first && En.first != Child) {
5896 S.Diag(Init->getSourceLocation(),
5897 diag::err_multiple_mem_union_initialization)
5898 << Field->getDeclName()
5899 << Init->getSourceRange();
5900 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5901 << 0 << En.second->getSourceRange();
5902 return true;
5903 }
5904 if (!En.first) {
5905 En.first = Child;
5906 En.second = Init;
5907 }
5908 if (!Parent->isAnonymousStructOrUnion())
5909 return false;
5910 }
5911
5912 Child = Parent;
5913 Parent = cast<RecordDecl>(Parent->getDeclContext());
5914 }
5915
5916 return false;
5917}
5918} // namespace
5919
5920void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5921 SourceLocation ColonLoc,
5923 bool AnyErrors) {
5924 if (!ConstructorDecl)
5925 return;
5926
5927 AdjustDeclIfTemplate(ConstructorDecl);
5928
5930 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5931
5932 if (!Constructor) {
5933 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5934 return;
5935 }
5936
5937 // Mapping for the duplicate initializers check.
5938 // For member initializers, this is keyed with a FieldDecl*.
5939 // For base initializers, this is keyed with a Type*.
5940 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5941
5942 // Mapping for the inconsistent anonymous-union initializers check.
5943 RedundantUnionMap MemberUnions;
5944
5945 bool HadError = false;
5946 for (unsigned i = 0; i < MemInits.size(); i++) {
5947 CXXCtorInitializer *Init = MemInits[i];
5948
5949 // Set the source order index.
5950 Init->setSourceOrder(i);
5951
5952 if (Init->isAnyMemberInitializer()) {
5953 const void *Key = GetKeyForMember(Context, Init);
5954 if (CheckRedundantInit(*this, Init, Members[Key]) ||
5955 CheckRedundantUnionInit(*this, Init, MemberUnions))
5956 HadError = true;
5957 } else if (Init->isBaseInitializer()) {
5958 const void *Key = GetKeyForMember(Context, Init);
5959 if (CheckRedundantInit(*this, Init, Members[Key]))
5960 HadError = true;
5961 } else {
5962 assert(Init->isDelegatingInitializer());
5963 // This must be the only initializer
5964 if (MemInits.size() != 1) {
5965 Diag(Init->getSourceLocation(),
5966 diag::err_delegating_initializer_alone)
5967 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5968 // We will treat this as being the only initializer.
5969 }
5971 // Return immediately as the initializer is set.
5972 return;
5973 }
5974 }
5975
5976 if (HadError)
5977 return;
5978
5980
5981 SetCtorInitializers(Constructor, AnyErrors, MemInits);
5982
5983 DiagnoseUninitializedFields(*this, Constructor);
5984}
5985
5987 CXXRecordDecl *ClassDecl) {
5988 // Ignore dependent contexts. Also ignore unions, since their members never
5989 // have destructors implicitly called.
5990 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5991 return;
5992
5993 // FIXME: all the access-control diagnostics are positioned on the
5994 // field/base declaration. That's probably good; that said, the
5995 // user might reasonably want to know why the destructor is being
5996 // emitted, and we currently don't say.
5997
5998 // Non-static data members.
5999 for (auto *Field : ClassDecl->fields()) {
6000 MarkFieldDestructorReferenced(*this, Location, Field);
6001 }
6002
6003 MarkBaseDestructorsReferenced(*this, Location, ClassDecl);
6004}
6005
6007 SourceLocation Location, CXXRecordDecl *ClassDecl,
6008 llvm::SmallPtrSetImpl<const CXXRecordDecl *> *DirectVirtualBases) {
6009 // Virtual bases.
6010 for (const auto &VBase : ClassDecl->vbases()) {
6011 auto *BaseClassDecl = VBase.getType()->getAsCXXRecordDecl();
6012 if (!BaseClassDecl)
6013 continue;
6014
6015 // Ignore already visited direct virtual bases.
6016 if (DirectVirtualBases && DirectVirtualBases->count(BaseClassDecl))
6017 continue;
6018
6019 auto *Dtor = LookupDestructorIfRelevant(*this, BaseClassDecl);
6020 if (!Dtor)
6021 continue;
6022
6023 CanQualType CT = Context.getCanonicalTagType(ClassDecl);
6024 if (CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
6025 PDiag(diag::err_access_dtor_vbase)
6026 << CT << VBase.getType(),
6027 CT) == AR_accessible) {
6029 CT, VBase.getType(), diag::err_access_dtor_vbase, 0,
6030 ClassDecl->getLocation(), SourceRange(), DeclarationName(), nullptr);
6031 }
6032
6033 MarkFunctionReferenced(Location, Dtor);
6034 DiagnoseUseOfDecl(Dtor, Location);
6035 }
6036}
6037
6039 if (!CDtorDecl)
6040 return;
6041
6043 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
6044 if (CXXRecordDecl *ClassDecl = Constructor->getParent();
6045 !ClassDecl || ClassDecl->isInvalidDecl()) {
6046 return;
6047 }
6048 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
6049 DiagnoseUninitializedFields(*this, Constructor);
6050 }
6051}
6052
6054 if (!getLangOpts().CPlusPlus)
6055 return false;
6056
6057 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
6058 if (!RD)
6059 return false;
6060
6061 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
6062 // class template specialization here, but doing so breaks a lot of code.
6063
6064 // We can't answer whether something is abstract until it has a
6065 // definition. If it's currently being defined, we'll walk back
6066 // over all the declarations when we have a full definition.
6067 const CXXRecordDecl *Def = RD->getDefinition();
6068 if (!Def || Def->isBeingDefined())
6069 return false;
6070
6071 return RD->isAbstract();
6072}
6073
6075 TypeDiagnoser &Diagnoser) {
6076 if (!isAbstractType(Loc, T))
6077 return false;
6078
6079 T = Context.getBaseElementType(T);
6080 Diagnoser.diagnose(*this, Loc, T);
6081 DiagnoseAbstractType(T->getAsCXXRecordDecl());
6082 return true;
6083}
6084
6086 // Check if we've already emitted the list of pure virtual functions
6087 // for this class.
6089 return;
6090
6091 // If the diagnostic is suppressed, don't emit the notes. We're only
6092 // going to emit them once, so try to attach them to a diagnostic we're
6093 // actually going to show.
6094 if (Diags.isLastDiagnosticIgnored())
6095 return;
6096
6097 CXXFinalOverriderMap FinalOverriders;
6098 RD->getFinalOverriders(FinalOverriders);
6099
6100 // Keep a set of seen pure methods so we won't diagnose the same method
6101 // more than once.
6103
6104 for (const auto &M : FinalOverriders) {
6105 for (const auto &SO : M.second) {
6106 // C++ [class.abstract]p4:
6107 // A class is abstract if it contains or inherits at least one
6108 // pure virtual function for which the final overrider is pure
6109 // virtual.
6110
6111 if (SO.second.size() != 1)
6112 continue;
6113 const CXXMethodDecl *Method = SO.second.front().Method;
6114
6115 if (!Method->isPureVirtual())
6116 continue;
6117
6118 if (!SeenPureMethods.insert(Method).second)
6119 continue;
6120
6121 Diag(Method->getLocation(), diag::note_pure_virtual_function)
6122 << Method->getDeclName() << RD->getDeclName();
6123 }
6124 }
6125
6128 PureVirtualClassDiagSet->insert(RD);
6129}
6130
6131namespace {
6132struct AbstractUsageInfo {
6133 Sema &S;
6135 CanQualType AbstractType;
6136 bool Invalid;
6137
6138 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
6139 : S(S), Record(Record),
6140 AbstractType(S.Context.getCanonicalTagType(Record)), Invalid(false) {}
6141
6142 void DiagnoseAbstractType() {
6143 if (Invalid) return;
6145 Invalid = true;
6146 }
6147
6148 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
6149};
6150
6151struct CheckAbstractUsage {
6152 AbstractUsageInfo &Info;
6153 const NamedDecl *Ctx;
6154
6155 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
6156 : Info(Info), Ctx(Ctx) {}
6157
6158 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
6159 switch (TL.getTypeLocClass()) {
6160#define ABSTRACT_TYPELOC(CLASS, PARENT)
6161#define TYPELOC(CLASS, PARENT) \
6162 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
6163#include "clang/AST/TypeLocNodes.def"
6164 }
6165 }
6166
6167 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6169 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
6170 if (!TL.getParam(I))
6171 continue;
6172
6173 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
6174 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
6175 }
6176 }
6177
6178 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6180 }
6181
6182 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6183 // Visit the type parameters from a permissive context.
6184 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
6185 TemplateArgumentLoc TAL = TL.getArgLoc(I);
6187 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
6188 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
6189 // TODO: other template argument types?
6190 }
6191 }
6192
6193 // Visit pointee types from a permissive context.
6194#define CheckPolymorphic(Type) \
6195 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
6196 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
6197 }
6203
6204 /// Handle all the types we haven't given a more specific
6205 /// implementation for above.
6206 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
6207 // Every other kind of type that we haven't called out already
6208 // that has an inner type is either (1) sugar or (2) contains that
6209 // inner type in some way as a subobject.
6210 if (TypeLoc Next = TL.getNextTypeLoc())
6211 return Visit(Next, Sel);
6212
6213 // If there's no inner type and we're in a permissive context,
6214 // don't diagnose.
6215 if (Sel == Sema::AbstractNone) return;
6216
6217 // Check whether the type matches the abstract type.
6218 QualType T = TL.getType();
6219 if (T->isArrayType()) {
6221 T = Info.S.Context.getBaseElementType(T);
6222 }
6223 CanQualType CT = T->getCanonicalTypeUnqualified();
6224 if (CT != Info.AbstractType) return;
6225
6226 // It matched; do some magic.
6227 // FIXME: These should be at most warnings. See P0929R2, CWG1640, CWG1646.
6228 if (Sel == Sema::AbstractArrayType) {
6229 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
6230 << T << TL.getSourceRange();
6231 } else {
6232 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
6233 << Sel << T << TL.getSourceRange();
6234 }
6235 Info.DiagnoseAbstractType();
6236 }
6237};
6238
6239void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
6241 CheckAbstractUsage(*this, D).Visit(TL, Sel);
6242}
6243
6244}
6245
6246/// Check for invalid uses of an abstract type in a function declaration.
6247static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6248 FunctionDecl *FD) {
6249 // Only definitions are required to refer to complete and
6250 // non-abstract types.
6252 return;
6253
6254 // For safety's sake, just ignore it if we don't have type source
6255 // information. This should never happen for non-implicit methods,
6256 // but...
6257 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6258 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractNone);
6259}
6260
6261/// Check for invalid uses of an abstract type in a variable0 declaration.
6262static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6263 VarDecl *VD) {
6264 // No need to do the check on definitions, which require that
6265 // the type is complete.
6267 return;
6268
6269 Info.CheckType(VD, VD->getTypeSourceInfo()->getTypeLoc(),
6271}
6272
6273/// Check for invalid uses of an abstract type within a class definition.
6274static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6275 CXXRecordDecl *RD) {
6276 for (auto *D : RD->decls()) {
6277 if (D->isImplicit()) continue;
6278
6279 // Step through friends to the befriended declaration.
6280 if (auto *FD = dyn_cast<FriendDecl>(D)) {
6281 D = FD->getFriendDecl();
6282 if (!D) continue;
6283 }
6284
6285 // Functions and function templates.
6286 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6287 CheckAbstractClassUsage(Info, FD);
6288 } else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) {
6289 CheckAbstractClassUsage(Info, FTD->getTemplatedDecl());
6290
6291 // Fields and static variables.
6292 } else if (auto *FD = dyn_cast<FieldDecl>(D)) {
6293 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6294 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
6295 } else if (auto *VD = dyn_cast<VarDecl>(D)) {
6296 CheckAbstractClassUsage(Info, VD);
6297 } else if (auto *VTD = dyn_cast<VarTemplateDecl>(D)) {
6298 CheckAbstractClassUsage(Info, VTD->getTemplatedDecl());
6299
6300 // Nested classes and class templates.
6301 } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
6302 CheckAbstractClassUsage(Info, RD);
6303 } else if (auto *CTD = dyn_cast<ClassTemplateDecl>(D)) {
6304 CheckAbstractClassUsage(Info, CTD->getTemplatedDecl());
6305 }
6306 }
6307}
6308
6310 Attr *ClassAttr = getDLLAttr(Class);
6311 if (!ClassAttr)
6312 return;
6313
6314 assert(ClassAttr->getKind() == attr::DLLExport);
6315
6316 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6317
6319 // Don't go any further if this is just an explicit instantiation
6320 // declaration.
6321 return;
6322
6323 // Add a context note to explain how we got to any diagnostics produced below.
6324 struct MarkingClassDllexported {
6325 Sema &S;
6326 MarkingClassDllexported(Sema &S, CXXRecordDecl *Class,
6327 SourceLocation AttrLoc)
6328 : S(S) {
6331 Ctx.PointOfInstantiation = AttrLoc;
6332 Ctx.Entity = Class;
6334 }
6335 ~MarkingClassDllexported() {
6337 }
6338 } MarkingDllexportedContext(S, Class, ClassAttr->getLocation());
6339
6340 if (S.Context.getTargetInfo().getTriple().isOSCygMing())
6341 S.MarkVTableUsed(Class->getLocation(), Class, true);
6342
6343 for (Decl *Member : Class->decls()) {
6344 // Skip members that were not marked exported.
6345 if (!Member->hasAttr<DLLExportAttr>())
6346 continue;
6347
6348 // Defined static variables that are members of an exported base
6349 // class must be marked export too.
6350 auto *VD = dyn_cast<VarDecl>(Member);
6351 if (VD && VD->getStorageClass() == SC_Static &&
6353 S.MarkVariableReferenced(VD->getLocation(), VD);
6354
6355 auto *MD = dyn_cast<CXXMethodDecl>(Member);
6356 if (!MD)
6357 continue;
6358
6359 if (MD->isUserProvided()) {
6360 // Instantiate non-default class member functions ...
6361
6362 // .. except for certain kinds of template specializations.
6363 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
6364 continue;
6365
6366 // If this is an MS ABI dllexport default constructor, instantiate any
6367 // default arguments.
6369 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6370 if (CD && CD->isDefaultConstructor() && TSK == TSK_Undeclared) {
6372 CD->getAttr<DLLExportAttr>()->getLocation(), CD);
6373 }
6374 }
6375
6376 S.MarkFunctionReferenced(Class->getLocation(), MD);
6377
6378 // The function will be passed to the consumer when its definition is
6379 // encountered.
6380 } else if (MD->isExplicitlyDefaulted()) {
6381 // Synthesize and instantiate explicitly defaulted methods.
6382 S.MarkFunctionReferenced(Class->getLocation(), MD);
6383
6385 // Except for explicit instantiation defs, we will not see the
6386 // definition again later, so pass it to the consumer now.
6388 }
6389 } else if (!MD->isTrivial() ||
6390 MD->isCopyAssignmentOperator() ||
6391 MD->isMoveAssignmentOperator()) {
6392 // Synthesize and instantiate non-trivial implicit methods, and the copy
6393 // and move assignment operators. The latter are exported even if they
6394 // are trivial, because the address of an operator can be taken and
6395 // should compare equal across libraries.
6396 S.MarkFunctionReferenced(Class->getLocation(), MD);
6397
6398 // There is no later point when we will see the definition of this
6399 // function, so pass it to the consumer now.
6401 }
6402 }
6403}
6404
6406 CXXRecordDecl *Class) {
6407 // Only the MS ABI has default constructor closures, so we don't need to do
6408 // this semantic checking anywhere else.
6410 return;
6411
6412 if (Class->isInvalidDecl())
6413 return;
6414
6415 CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
6416 for (Decl *Member : Class->decls()) {
6417 // Nested classes finish delayed default argument parsing with the outermost
6418 // class, so check each nested definition here.
6419 if (auto *NestedClass = dyn_cast<CXXRecordDecl>(Member)) {
6420 if (NestedClass->isThisDeclarationADefinition())
6422 continue;
6423 }
6424
6425 // Look for exported default constructors.
6426 auto *CD = dyn_cast<CXXConstructorDecl>(Member);
6427 if (!CD || !CD->isDefaultConstructor())
6428 continue;
6429 auto *Attr = CD->getAttr<DLLExportAttr>();
6430 if (!Attr)
6431 continue;
6432
6433 // If the class is non-dependent, mark the default arguments as ODR-used so
6434 // that we can properly codegen the constructor closure.
6435 if (!Class->isDependentContext()) {
6438 }
6439
6440 if (LastExportedDefaultCtor) {
6441 S.Diag(LastExportedDefaultCtor->getLocation(),
6442 diag::err_attribute_dll_ambiguous_default_ctor)
6443 << Class;
6444 S.Diag(CD->getLocation(), diag::note_entity_declared_at)
6445 << CD->getDeclName();
6446 return;
6447 }
6448 LastExportedDefaultCtor = CD;
6449 }
6450}
6451
6453 CXXRecordDecl *Class) {
6454 bool ErrorReported = false;
6455 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6456 ClassTemplateDecl *TD) {
6457 if (ErrorReported)
6458 return;
6459 S.Diag(TD->getLocation(),
6460 diag::err_cuda_device_builtin_surftex_cls_template)
6461 << /*surface*/ 0 << TD;
6462 ErrorReported = true;
6463 };
6464
6465 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6466 if (!TD) {
6467 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6468 if (!SD) {
6469 S.Diag(Class->getLocation(),
6470 diag::err_cuda_device_builtin_surftex_ref_decl)
6471 << /*surface*/ 0 << Class;
6472 S.Diag(Class->getLocation(),
6473 diag::note_cuda_device_builtin_surftex_should_be_template_class)
6474 << Class;
6475 return;
6476 }
6477 TD = SD->getSpecializedTemplate();
6478 }
6479
6481 unsigned N = Params->size();
6482
6483 if (N != 2) {
6484 reportIllegalClassTemplate(S, TD);
6485 S.Diag(TD->getLocation(),
6486 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6487 << TD << 2;
6488 }
6489 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6490 reportIllegalClassTemplate(S, TD);
6491 S.Diag(TD->getLocation(),
6492 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6493 << TD << /*1st*/ 0 << /*type*/ 0;
6494 }
6495 if (N > 1) {
6496 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6497 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6498 reportIllegalClassTemplate(S, TD);
6499 S.Diag(TD->getLocation(),
6500 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6501 << TD << /*2nd*/ 1 << /*integer*/ 1;
6502 }
6503 }
6504}
6505
6507 CXXRecordDecl *Class) {
6508 bool ErrorReported = false;
6509 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6510 ClassTemplateDecl *TD) {
6511 if (ErrorReported)
6512 return;
6513 S.Diag(TD->getLocation(),
6514 diag::err_cuda_device_builtin_surftex_cls_template)
6515 << /*texture*/ 1 << TD;
6516 ErrorReported = true;
6517 };
6518
6519 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6520 if (!TD) {
6521 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6522 if (!SD) {
6523 S.Diag(Class->getLocation(),
6524 diag::err_cuda_device_builtin_surftex_ref_decl)
6525 << /*texture*/ 1 << Class;
6526 S.Diag(Class->getLocation(),
6527 diag::note_cuda_device_builtin_surftex_should_be_template_class)
6528 << Class;
6529 return;
6530 }
6531 TD = SD->getSpecializedTemplate();
6532 }
6533
6535 unsigned N = Params->size();
6536
6537 if (N != 3) {
6538 reportIllegalClassTemplate(S, TD);
6539 S.Diag(TD->getLocation(),
6540 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6541 << TD << 3;
6542 }
6543 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6544 reportIllegalClassTemplate(S, TD);
6545 S.Diag(TD->getLocation(),
6546 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6547 << TD << /*1st*/ 0 << /*type*/ 0;
6548 }
6549 if (N > 1) {
6550 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6551 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6552 reportIllegalClassTemplate(S, TD);
6553 S.Diag(TD->getLocation(),
6554 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6555 << TD << /*2nd*/ 1 << /*integer*/ 1;
6556 }
6557 }
6558 if (N > 2) {
6559 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2));
6560 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6561 reportIllegalClassTemplate(S, TD);
6562 S.Diag(TD->getLocation(),
6563 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6564 << TD << /*3rd*/ 2 << /*integer*/ 1;
6565 }
6566 }
6567}
6568
6570 // Mark any compiler-generated routines with the implicit code_seg attribute.
6571 for (auto *Method : Class->methods()) {
6572 if (Method->isUserProvided())
6573 continue;
6574 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
6575 Method->addAttr(A);
6576 }
6577}
6578
6580 Attr *ClassAttr = getDLLAttr(Class);
6581
6582 // MSVC inherits DLL attributes to partial class template specializations.
6583 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) {
6584 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
6585 if (Attr *TemplateAttr =
6586 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
6587 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
6588 A->setInherited(true);
6589 ClassAttr = A;
6590 }
6591 }
6592 }
6593
6594 if (!ClassAttr)
6595 return;
6596
6597 // MSVC allows imported or exported template classes that have UniqueExternal
6598 // linkage. This occurs when the template class has been instantiated with
6599 // a template parameter which itself has internal linkage.
6600 // We drop the attribute to avoid exporting or importing any members.
6601 if ((Context.getTargetInfo().getCXXABI().isMicrosoft() ||
6602 Context.getTargetInfo().getTriple().isPS()) &&
6603 (!Class->isExternallyVisible() && Class->hasExternalFormalLinkage())) {
6604 Class->dropAttrs<DLLExportAttr, DLLImportAttr>();
6605 return;
6606 }
6607
6608 if (!Class->isExternallyVisible()) {
6609 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
6610 << Class << ClassAttr;
6611 return;
6612 }
6613
6614 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6615 !ClassAttr->isInherited()) {
6616 // Diagnose dll attributes on members of class with dll attribute.
6617 for (Decl *Member : Class->decls()) {
6619 continue;
6620 InheritableAttr *MemberAttr = getDLLAttr(Member);
6621 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
6622 continue;
6623
6624 Diag(MemberAttr->getLocation(),
6625 diag::err_attribute_dll_member_of_dll_class)
6626 << MemberAttr << ClassAttr;
6627 Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
6628 Member->setInvalidDecl();
6629 }
6630 }
6631
6632 if (Class->getDescribedClassTemplate())
6633 // Don't inherit dll attribute until the template is instantiated.
6634 return;
6635
6636 // The class is either imported or exported.
6637 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
6638
6639 // Check if this was a dllimport attribute propagated from a derived class to
6640 // a base class template specialization. We don't apply these attributes to
6641 // static data members.
6642 const bool PropagatedImport =
6643 !ClassExported &&
6644 cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
6645
6646 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6647
6648 // Ignore explicit dllexport on explicit class template instantiation
6649 // declarations, except in MinGW mode.
6650 if (ClassExported && !ClassAttr->isInherited() &&
6652 !Context.getTargetInfo().getTriple().isOSCygMing()) {
6653 if (auto *DEA = Class->getAttr<DLLExportAttr>()) {
6654 Class->addAttr(DLLExportOnDeclAttr::Create(Context, DEA->getLoc()));
6655 Class->dropAttr<DLLExportAttr>();
6656 }
6657 return;
6658 }
6659
6660 // Force declaration of implicit members so they can inherit the attribute.
6662
6663 // Inherited constructors are created lazily; force their creation now so the
6664 // loop below can propagate the DLL attribute to them.
6665 if (ClassExported && getLangOpts().DllExportInlines) {
6667 for (Decl *D : Class->decls())
6668 if (auto *S = dyn_cast<ConstructorUsingShadowDecl>(D))
6669 Shadows.push_back(S);
6670 for (ConstructorUsingShadowDecl *S : Shadows) {
6671 CXXConstructorDecl *BC = dyn_cast<CXXConstructorDecl>(S->getTargetDecl());
6672 if (!BC || BC->isDeleted())
6673 continue;
6674 // Skip constructors whose requires clause is not satisfied.
6675 // Normally overload resolution filters these, but we are bypassing
6676 // it to eagerly create inherited constructors for dllexport.
6677 if (BC->getTrailingRequiresClause()) {
6678 ConstraintSatisfaction Satisfaction;
6679 if (CheckFunctionConstraints(BC, Satisfaction) ||
6680 !Satisfaction.IsSatisfied)
6681 continue;
6682 }
6683 findInheritingConstructor(Class->getLocation(), BC, S);
6684 }
6685 }
6686
6687 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
6688 // seem to be true in practice?
6689
6690 for (Decl *Member : Class->decls()) {
6691 if (Member->hasAttr<ExcludeFromExplicitInstantiationAttr>())
6692 continue;
6693
6694 VarDecl *VD = dyn_cast<VarDecl>(Member);
6695 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
6696
6697 // Only methods and static fields inherit the attributes.
6698 if (!VD && !MD)
6699 continue;
6700
6701 if (MD) {
6702 // Don't process deleted methods.
6703 if (MD->isDeleted())
6704 continue;
6705
6706 if (ClassExported && getLangOpts().DllExportInlines) {
6707 CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(MD);
6708 if (CD && CD->getInheritedConstructor()) {
6709 // Inherited constructors already had their base constructor's
6710 // constraints checked before creation via
6711 // findInheritingConstructor, so only ABI-compatibility checks
6712 // are needed here.
6713 //
6714 // Don't export inherited constructors whose parameters prevent
6715 // ABI-compatible forwarding. When canEmitDelegateCallArgs (in
6716 // CodeGen) returns false, Clang inlines the constructor body
6717 // instead of emitting a forwarding thunk, producing code that
6718 // is not ABI-compatible with MSVC. Suppress the export and warn
6719 // so the user gets a linker error rather than a silent runtime
6720 // mismatch.
6721 if (CD->isVariadic()) {
6722 Diag(CD->getLocation(),
6723 diag::warn_dllexport_inherited_ctor_unsupported)
6724 << /*variadic=*/0;
6725 continue;
6726 }
6727 if (Context.getTargetInfo()
6728 .getCXXABI()
6729 .areArgsDestroyedLeftToRightInCallee()) {
6730 bool HasCalleeCleanupParam = false;
6731 for (const ParmVarDecl *P : CD->parameters())
6732 if (P->needsDestruction(Context)) {
6733 HasCalleeCleanupParam = true;
6734 break;
6735 }
6736 if (HasCalleeCleanupParam) {
6737 Diag(CD->getLocation(),
6738 diag::warn_dllexport_inherited_ctor_unsupported)
6739 << /*callee-cleanup=*/1;
6740 continue;
6741 }
6742 }
6743 } else if (MD->getTrailingRequiresClause()) {
6744 // Don't export methods whose requires clause is not satisfied.
6745 // For class template specializations, member constraints may
6746 // depend on template arguments and an unsatisfied constraint
6747 // means the member should not be available in this
6748 // specialization.
6749 ConstraintSatisfaction Satisfaction;
6750 if (CheckFunctionConstraints(MD, Satisfaction) ||
6751 !Satisfaction.IsSatisfied)
6752 continue;
6753 }
6754 }
6755
6756 if (MD->isInlined()) {
6757 // MinGW does not import or export inline methods. But do it for
6758 // template instantiations and inherited constructors (which are
6759 // marked inline but must be exported to match MSVC behavior).
6760 if (!Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6763 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6764 !CD || !CD->getInheritedConstructor())
6765 continue;
6766 }
6767
6768 // MSVC versions before 2015 don't export the move assignment operators
6769 // and move constructor, so don't attempt to import/export them if
6770 // we have a definition.
6771 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
6772 if ((MD->isMoveAssignmentOperator() ||
6773 (Ctor && Ctor->isMoveConstructor())) &&
6774 getLangOpts().isCompatibleWithMSVC() &&
6775 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
6776 continue;
6777
6778 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
6779 // operator is exported anyway.
6780 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6781 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
6782 continue;
6783 }
6784 }
6785
6786 // Don't apply dllimport attributes to static data members of class template
6787 // instantiations when the attribute is propagated from a derived class.
6788 if (VD && PropagatedImport)
6789 continue;
6790
6792 continue;
6793
6794 if (!getDLLAttr(Member)) {
6795 InheritableAttr *NewAttr = nullptr;
6796
6797 // Do not export/import inline function when -fno-dllexport-inlines is
6798 // passed. But add attribute for later local static var check.
6799 if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
6802 if (ClassExported) {
6803 NewAttr = ::new (getASTContext())
6804 DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);
6805 } else {
6806 NewAttr = ::new (getASTContext())
6807 DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);
6808 }
6809 } else {
6810 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6811 }
6812
6813 NewAttr->setInherited(true);
6814 Member->addAttr(NewAttr);
6815
6816 if (MD) {
6817 // Propagate DLLAttr to friend re-declarations of MD that have already
6818 // been constructed.
6819 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
6820 FD = FD->getPreviousDecl()) {
6822 continue;
6823 assert(!getDLLAttr(FD) &&
6824 "friend re-decl should not already have a DLLAttr");
6825 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6826 NewAttr->setInherited(true);
6827 FD->addAttr(NewAttr);
6828 }
6829 }
6830 }
6831 }
6832
6833 if (ClassExported)
6834 DelayedDllExportClasses.push_back(Class);
6835}
6836
6838 CXXRecordDecl *Class, Attr *ClassAttr,
6839 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
6840 if (getDLLAttr(
6841 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
6842 // If the base class template has a DLL attribute, don't try to change it.
6843 return;
6844 }
6845
6846 auto TSK = BaseTemplateSpec->getSpecializationKind();
6847 if (!getDLLAttr(BaseTemplateSpec) &&
6849 TSK == TSK_ImplicitInstantiation)) {
6850 // The template hasn't been instantiated yet (or it has, but only as an
6851 // explicit instantiation declaration or implicit instantiation, which means
6852 // we haven't codegenned any members yet), so propagate the attribute.
6853 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6854 NewAttr->setInherited(true);
6855 BaseTemplateSpec->addAttr(NewAttr);
6856
6857 // If this was an import, mark that we propagated it from a derived class to
6858 // a base class template specialization.
6859 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
6860 ImportAttr->setPropagatedToBaseTemplate();
6861
6862 // If the template is already instantiated, checkDLLAttributeRedeclaration()
6863 // needs to be run again to work see the new attribute. Otherwise this will
6864 // get run whenever the template is instantiated.
6865 if (TSK != TSK_Undeclared)
6866 checkClassLevelDLLAttribute(BaseTemplateSpec);
6867
6868 return;
6869 }
6870
6871 if (getDLLAttr(BaseTemplateSpec)) {
6872 // The template has already been specialized or instantiated with an
6873 // attribute, explicitly or through propagation. We should not try to change
6874 // it.
6875 return;
6876 }
6877
6878 // The template was previously instantiated or explicitly specialized without
6879 // a dll attribute, It's too late for us to add an attribute, so warn that
6880 // this is unsupported.
6881 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
6882 << BaseTemplateSpec->isExplicitSpecialization();
6883 Diag(ClassAttr->getLocation(), diag::note_attribute);
6884 if (BaseTemplateSpec->isExplicitSpecialization()) {
6885 Diag(BaseTemplateSpec->getLocation(),
6886 diag::note_template_class_explicit_specialization_was_here)
6887 << BaseTemplateSpec;
6888 } else {
6889 Diag(BaseTemplateSpec->getPointOfInstantiation(),
6890 diag::note_template_class_instantiation_was_here)
6891 << BaseTemplateSpec;
6892 }
6893}
6894
6895namespace {
6896/// RAII object to restore the floating-point (FP) features active at the time
6897/// a defaulted function was declared. This ensures that the synthesized body
6898/// of the function respects the FP pragmas (e.g., #pragma STDC FENV_ACCESS)
6899/// that were in effect when the function was explicitly defaulted.
6900struct DefaultedFunctionFPFeaturesRAII {
6901 Sema::FPFeaturesStateRAII SavedFPFeatures;
6902 DefaultedFunctionFPFeaturesRAII(Sema &S, FunctionDecl *FD)
6903 : SavedFPFeatures(S) {
6904 auto *Info = FD->getDefaultedOrDeletedInfo();
6905 FPOptionsOverride FPO = Info ? Info->getFPFeatures() : FPOptionsOverride();
6907 S.FpPragmaStack.CurrentValue = FPO;
6908 }
6909
6910 ~DefaultedFunctionFPFeaturesRAII() = default;
6911};
6912} // namespace
6913
6915 SourceLocation DefaultLoc) {
6917 if (DFK.isComparison())
6918 return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison());
6919
6920 switch (DFK.asSpecialMember()) {
6924 break;
6927 break;
6930 break;
6933 break;
6936 break;
6939 break;
6941 llvm_unreachable("Invalid special member.");
6942 }
6943}
6944
6945/// Determine whether a type is permitted to be passed or returned in
6946/// registers, per C++ [class.temporary]p3.
6949 if (D->isDependentType() || D->isInvalidDecl())
6950 return false;
6951
6952 // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
6953 // The PS4 platform ABI follows the behavior of Clang 3.2.
6955 return !D->hasNonTrivialDestructorForCall() &&
6957
6958 if (CCK == TargetInfo::CCK_MicrosoftWin64) {
6959 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
6960 bool DtorIsTrivialForCall = false;
6961
6962 // If a class has at least one eligible, trivial copy constructor, it
6963 // is passed according to the C ABI. Otherwise, it is passed indirectly.
6964 //
6965 // Note: This permits classes with non-trivial copy or move ctors to be
6966 // passed in registers, so long as they *also* have a trivial copy ctor,
6967 // which is non-conforming.
6971 CopyCtorIsTrivial = true;
6973 CopyCtorIsTrivialForCall = true;
6974 }
6975 } else {
6976 for (const CXXConstructorDecl *CD : D->ctors()) {
6977 if (CD->isCopyConstructor() && !CD->isDeleted() &&
6978 !CD->isIneligibleOrNotSelected()) {
6979 if (CD->isTrivial())
6980 CopyCtorIsTrivial = true;
6981 if (CD->isTrivialForCall())
6982 CopyCtorIsTrivialForCall = true;
6983 }
6984 }
6985 }
6986
6987 if (D->needsImplicitDestructor()) {
6988 if (!D->defaultedDestructorIsDeleted() &&
6990 DtorIsTrivialForCall = true;
6991 } else if (const auto *DD = D->getDestructor()) {
6992 if (!DD->isDeleted() && DD->isTrivialForCall())
6993 DtorIsTrivialForCall = true;
6994 }
6995
6996 // If the copy ctor and dtor are both trivial-for-calls, pass direct.
6997 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
6998 return true;
6999
7000 // If a class has a destructor, we'd really like to pass it indirectly
7001 // because it allows us to elide copies. Unfortunately, MSVC makes that
7002 // impossible for small types, which it will pass in a single register or
7003 // stack slot. Most objects with dtors are large-ish, so handle that early.
7004 // We can't call out all large objects as being indirect because there are
7005 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
7006 // how we pass large POD types.
7007
7008 // Note: This permits small classes with nontrivial destructors to be
7009 // passed in registers, which is non-conforming.
7010 bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
7011 uint64_t TypeSize = isAArch64 ? 128 : 64;
7012
7013 if (CopyCtorIsTrivial && S.getASTContext().getTypeSize(
7014 S.Context.getCanonicalTagType(D)) <= TypeSize)
7015 return true;
7016 return false;
7017 }
7018
7019 // Per C++ [class.temporary]p3, the relevant condition is:
7020 // each copy constructor, move constructor, and destructor of X is
7021 // either trivial or deleted, and X has at least one non-deleted copy
7022 // or move constructor
7023 bool HasNonDeletedCopyOrMove = false;
7024
7028 return false;
7029 HasNonDeletedCopyOrMove = true;
7030 }
7031
7032 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
7035 return false;
7036 HasNonDeletedCopyOrMove = true;
7037 }
7038
7041 return false;
7042
7043 for (const CXXMethodDecl *MD : D->methods()) {
7044 if (MD->isDeleted() || MD->isIneligibleOrNotSelected())
7045 continue;
7046
7047 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
7048 if (CD && CD->isCopyOrMoveConstructor())
7049 HasNonDeletedCopyOrMove = true;
7050 else if (!isa<CXXDestructorDecl>(MD))
7051 continue;
7052
7053 if (!MD->isTrivialForCall())
7054 return false;
7055 }
7056
7057 return HasNonDeletedCopyOrMove;
7058}
7059
7060/// Report an error regarding overriding, along with any relevant
7061/// overridden methods.
7062///
7063/// \param DiagID the primary error to report.
7064/// \param MD the overriding method.
7065static bool
7066ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD,
7067 llvm::function_ref<bool(const CXXMethodDecl *)> Report) {
7068 bool IssuedDiagnostic = false;
7069 for (const CXXMethodDecl *O : MD->overridden_methods()) {
7070 if (Report(O)) {
7071 if (!IssuedDiagnostic) {
7072 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7073 IssuedDiagnostic = true;
7074 }
7075 S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
7076 }
7077 }
7078 return IssuedDiagnostic;
7079}
7080
7082 if (!Record)
7083 return;
7084
7085 if (Record->isAbstract() && !Record->isInvalidDecl()) {
7086 AbstractUsageInfo Info(*this, Record);
7088 }
7089
7090 // If this is not an aggregate type and has no user-declared constructor,
7091 // complain about any non-static data members of reference or const scalar
7092 // type, since they will never get initializers.
7093 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
7094 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
7095 !Record->isLambda()) {
7096 bool Complained = false;
7097 for (const auto *F : Record->fields()) {
7098 if (F->hasInClassInitializer() || F->isUnnamedBitField())
7099 continue;
7100
7101 if (F->getType()->isReferenceType() ||
7102 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
7103 if (!Complained) {
7104 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
7105 << Record->getTagKind() << Record;
7106 Complained = true;
7107 }
7108
7109 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
7110 << F->getType()->isReferenceType()
7111 << F->getDeclName();
7112 }
7113 }
7114 }
7115
7116 if (Record->getIdentifier()) {
7117 // C++ [class.mem]p13:
7118 // If T is the name of a class, then each of the following shall have a
7119 // name different from T:
7120 // - every member of every anonymous union that is a member of class T.
7121 //
7122 // C++ [class.mem]p14:
7123 // In addition, if class T has a user-declared constructor (12.1), every
7124 // non-static data member of class T shall have a name different from T.
7125 for (const NamedDecl *Element : Record->lookup(Record->getDeclName())) {
7126 const NamedDecl *D = Element->getUnderlyingDecl();
7127 // Invalid IndirectFieldDecls have already been diagnosed with
7128 // err_anonymous_record_member_redecl in
7129 // SemaDecl.cpp:CheckAnonMemberRedeclaration.
7131 Record->hasUserDeclaredConstructor()) ||
7132 (isa<IndirectFieldDecl>(D) && !D->isInvalidDecl())) {
7133 Diag(Element->getLocation(), diag::err_member_name_of_class)
7134 << D->getDeclName();
7135 break;
7136 }
7137 }
7138 }
7139
7140 // Warn if the class has virtual methods but non-virtual public destructor.
7141 if (Record->isPolymorphic() && !Record->isDependentType()) {
7142 CXXDestructorDecl *dtor = Record->getDestructor();
7143 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
7144 !Record->hasAttr<FinalAttr>())
7145 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
7146 diag::warn_non_virtual_dtor)
7147 << Context.getCanonicalTagType(Record);
7148 }
7149
7150 if (Record->isAbstract()) {
7151 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
7152 Diag(Record->getLocation(), diag::warn_abstract_final_class)
7153 << FA->isSpelledAsSealed();
7155 }
7156 }
7157
7158 // Warn if the class has a final destructor but is not itself marked final.
7159 if (!Record->hasAttr<FinalAttr>()) {
7160 if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
7161 if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
7162 Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class)
7163 << FA->isSpelledAsSealed()
7165 getLocForEndOfToken(Record->getLocation()),
7166 (FA->isSpelledAsSealed() ? " sealed" : " final"));
7167 Diag(Record->getLocation(),
7168 diag::note_final_dtor_non_final_class_silence)
7169 << Context.getCanonicalTagType(Record) << FA->isSpelledAsSealed();
7170 }
7171 }
7172 }
7173
7174 // See if trivial_abi has to be dropped.
7175 if (Record->hasAttr<TrivialABIAttr>())
7177
7178 // Set HasTrivialSpecialMemberForCall if the record has attribute
7179 // "trivial_abi".
7180 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
7181
7182 if (HasTrivialABI)
7183 Record->setHasTrivialSpecialMemberForCall();
7184
7185 // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=).
7186 // We check these last because they can depend on the properties of the
7187 // primary comparison functions (==, <=>).
7188 llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons;
7189
7190 // Perform checks that can't be done until we know all the properties of a
7191 // member function (whether it's defaulted, deleted, virtual, overriding,
7192 // ...).
7193 auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) {
7194 // A static function cannot override anything.
7195 if (MD->getStorageClass() == SC_Static) {
7196 if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD,
7197 [](const CXXMethodDecl *) { return true; }))
7198 return;
7199 }
7200
7201 // A deleted function cannot override a non-deleted function and vice
7202 // versa.
7203 if (ReportOverrides(*this,
7204 MD->isDeleted() ? diag::err_deleted_override
7205 : diag::err_non_deleted_override,
7206 MD, [&](const CXXMethodDecl *V) {
7207 return MD->isDeleted() != V->isDeleted();
7208 })) {
7209 if (MD->isDefaulted() && MD->isDeleted())
7210 // Explain why this defaulted function was deleted.
7212 return;
7213 }
7214
7215 // A consteval function cannot override a non-consteval function and vice
7216 // versa.
7217 if (ReportOverrides(*this,
7218 MD->isConsteval() ? diag::err_consteval_override
7219 : diag::err_non_consteval_override,
7220 MD, [&](const CXXMethodDecl *V) {
7221 return MD->isConsteval() != V->isConsteval();
7222 })) {
7223 if (MD->isDefaulted() && MD->isDeleted())
7224 // Explain why this defaulted function was deleted.
7226 return;
7227 }
7228 };
7229
7230 auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool {
7231 if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted())
7232 return false;
7233
7237 DefaultedSecondaryComparisons.push_back(FD);
7238 return true;
7239 }
7240
7242 return false;
7243 };
7244
7245 if (!Record->isInvalidDecl() &&
7246 Record->hasAttr<VTablePointerAuthenticationAttr>())
7248
7249 auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
7250 // Check whether the explicitly-defaulted members are valid.
7251 bool Incomplete = CheckForDefaultedFunction(M);
7252
7253 // Skip the rest of the checks for a member of a dependent class.
7254 if (Record->isDependentType())
7255 return;
7256
7257 // For an explicitly defaulted or deleted special member, we defer
7258 // determining triviality until the class is complete. That time is now!
7259 CXXSpecialMemberKind CSM = M->getSpecialMemberKind();
7260 if (!M->isImplicit() && !M->isUserProvided()) {
7261 if (CSM != CXXSpecialMemberKind::Invalid) {
7262 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
7263 // Inform the class that we've finished declaring this member.
7264 Record->finishedDefaultedOrDeletedMember(M);
7265 M->setTrivialForCall(
7266 HasTrivialABI ||
7269 Record->setTrivialForCallFlags(M);
7270 }
7271 }
7272
7273 // Set triviality for the purpose of calls if this is a user-provided
7274 // copy/move constructor or destructor.
7278 M->isUserProvided()) {
7279 M->setTrivialForCall(HasTrivialABI);
7280 Record->setTrivialForCallFlags(M);
7281 }
7282
7283 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
7284 M->hasAttr<DLLExportAttr>()) {
7285 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
7286 M->isTrivial() &&
7290 M->dropAttr<DLLExportAttr>();
7291
7292 if (M->hasAttr<DLLExportAttr>()) {
7293 // Define after any fields with in-class initializers have been parsed.
7295 }
7296 }
7297
7298 bool EffectivelyConstexprDestructor = true;
7299 // Avoid triggering vtable instantiation due to a dtor that is not
7300 // "effectively constexpr" for better compatibility.
7301 // See https://github.com/llvm/llvm-project/issues/102293 for more info.
7302 if (isa<CXXDestructorDecl>(M)) {
7303 llvm::SmallDenseSet<QualType> Visited;
7304 auto Check = [&Visited](QualType T, auto &&Check) -> bool {
7305 if (!Visited.insert(T->getCanonicalTypeUnqualified()).second)
7306 return false;
7307 const CXXRecordDecl *RD =
7308 T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
7309 if (!RD || !RD->isCompleteDefinition())
7310 return true;
7311
7312 if (!RD->hasConstexprDestructor())
7313 return false;
7314
7315 for (const CXXBaseSpecifier &B : RD->bases())
7316 if (!Check(B.getType(), Check))
7317 return false;
7318 for (const FieldDecl *FD : RD->fields())
7319 if (!Check(FD->getType(), Check))
7320 return false;
7321 return true;
7322 };
7323 EffectivelyConstexprDestructor =
7324 Check(Context.getCanonicalTagType(Record), Check);
7325 }
7326
7327 // Define defaulted constexpr virtual functions that override a base class
7328 // function right away.
7329 // FIXME: We can defer doing this until the vtable is marked as used.
7330 if (CSM != CXXSpecialMemberKind::Invalid && !M->isDeleted() &&
7331 M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods() &&
7332 EffectivelyConstexprDestructor)
7333 DefineDefaultedFunction(*this, M, M->getLocation());
7334
7335 if (!Incomplete)
7336 CheckCompletedMemberFunction(M);
7337 };
7338
7339 // Check the destructor before any other member function. We need to
7340 // determine whether it's trivial in order to determine whether the claas
7341 // type is a literal type, which is a prerequisite for determining whether
7342 // other special member functions are valid and whether they're implicitly
7343 // 'constexpr'.
7344 if (CXXDestructorDecl *Dtor = Record->getDestructor())
7345 CompleteMemberFunction(Dtor);
7346
7347 bool HasMethodWithOverrideControl = false,
7348 HasOverridingMethodWithoutOverrideControl = false;
7349 for (auto *D : Record->decls()) {
7350 if (auto *M = dyn_cast<CXXMethodDecl>(D)) {
7351 // FIXME: We could do this check for dependent types with non-dependent
7352 // bases.
7353 if (!Record->isDependentType()) {
7354 // See if a method overloads virtual methods in a base
7355 // class without overriding any.
7356 if (!M->isStatic())
7358
7359 if (M->hasAttr<OverrideAttr>()) {
7360 HasMethodWithOverrideControl = true;
7361 } else if (M->size_overridden_methods() > 0) {
7362 HasOverridingMethodWithoutOverrideControl = true;
7363 } else {
7364 // Warn on newly-declared virtual methods in `final` classes
7365 if (M->isVirtualAsWritten() && Record->isEffectivelyFinal()) {
7366 Diag(M->getLocation(), diag::warn_unnecessary_virtual_specifier)
7367 << M;
7368 }
7369 }
7370 }
7371
7372 if (!isa<CXXDestructorDecl>(M))
7373 CompleteMemberFunction(M);
7374 } else if (auto *F = dyn_cast<FriendDecl>(D)) {
7375 CheckForDefaultedFunction(
7376 dyn_cast_or_null<FunctionDecl>(F->getFriendDecl()));
7377 }
7378 }
7379
7380 if (HasOverridingMethodWithoutOverrideControl) {
7381 bool HasInconsistentOverrideControl = HasMethodWithOverrideControl;
7382 for (auto *M : Record->methods())
7383 DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl);
7384 }
7385
7386 // Check the defaulted secondary comparisons after any other member functions.
7387 for (FunctionDecl *FD : DefaultedSecondaryComparisons) {
7389
7390 // If this is a member function, we deferred checking it until now.
7391 if (auto *MD = dyn_cast<CXXMethodDecl>(FD))
7392 CheckCompletedMemberFunction(MD);
7393 }
7394
7395 // {ms,gcc}_struct is a request to change ABI rules to either follow
7396 // Microsoft or Itanium C++ ABI. However, even if these attributes are
7397 // present, we do not layout classes following foreign ABI rules, but
7398 // instead enter a special "compatibility mode", which only changes
7399 // alignments of fundamental types and layout of bit fields.
7400 // Check whether this class uses any C++ features that are implemented
7401 // completely differently in the requested ABI, and if so, emit a
7402 // diagnostic. That diagnostic defaults to an error, but we allow
7403 // projects to map it down to a warning (or ignore it). It's a fairly
7404 // common practice among users of the ms_struct pragma to
7405 // mass-annotate headers, sweeping up a bunch of types that the
7406 // project doesn't really rely on MSVC-compatible layout for. We must
7407 // therefore support "ms_struct except for C++ stuff" as a secondary
7408 // ABI.
7409 // Don't emit this diagnostic if the feature was enabled as a
7410 // language option (as opposed to via a pragma or attribute), as
7411 // the option -mms-bitfields otherwise essentially makes it impossible
7412 // to build C++ code, unless this diagnostic is turned off.
7413 if (Context.getLangOpts().getLayoutCompatibility() ==
7415 Record->isMsStruct(Context) != Context.defaultsToMsStruct() &&
7416 (Record->isPolymorphic() || Record->getNumBases())) {
7417 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
7418 }
7419
7422
7423 bool ClangABICompat4 =
7424 Context.getLangOpts().isCompatibleWith(LangOptions::ClangABI::Ver4);
7426 Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
7427 bool CanPass = canPassInRegisters(*this, Record, CCK);
7428
7429 // Do not change ArgPassingRestrictions if it has already been set to
7430 // RecordArgPassingKind::CanNeverPassInRegs.
7431 if (Record->getArgPassingRestrictions() !=
7433 Record->setArgPassingRestrictions(
7436
7437 // If canPassInRegisters returns true despite the record having a non-trivial
7438 // destructor, the record is destructed in the callee. This happens only when
7439 // the record or one of its subobjects has a field annotated with trivial_abi
7440 // or a field qualified with ObjC __strong/__weak.
7441 if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
7442 Record->setParamDestroyedInCallee(true);
7443 else if (Record->hasNonTrivialDestructor())
7444 Record->setParamDestroyedInCallee(CanPass);
7445
7446 if (getLangOpts().ForceEmitVTables) {
7447 // If we want to emit all the vtables, we need to mark it as used. This
7448 // is especially required for cases like vtable assumption loads.
7449 MarkVTableUsed(Record->getInnerLocStart(), Record);
7450 }
7451
7452 if (getLangOpts().CUDA) {
7453 if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>())
7455 else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>())
7457 }
7458
7459 llvm::SmallDenseMap<OverloadedOperatorKind,
7461 TypeAwareDecls{{OO_New, {}},
7462 {OO_Array_New, {}},
7463 {OO_Delete, {}},
7464 {OO_Array_New, {}}};
7465 for (auto *D : Record->decls()) {
7466 const FunctionDecl *FnDecl = D->getAsFunction();
7467 if (!FnDecl || !FnDecl->isTypeAwareOperatorNewOrDelete())
7468 continue;
7469 assert(FnDecl->getDeclName().isAnyOperatorNewOrDelete());
7470 TypeAwareDecls[FnDecl->getOverloadedOperator()].push_back(FnDecl);
7471 }
7472 auto CheckMismatchedTypeAwareAllocators =
7473 [this, &TypeAwareDecls, Record](OverloadedOperatorKind NewKind,
7474 OverloadedOperatorKind DeleteKind) {
7475 auto &NewDecls = TypeAwareDecls[NewKind];
7476 auto &DeleteDecls = TypeAwareDecls[DeleteKind];
7477 if (NewDecls.empty() == DeleteDecls.empty())
7478 return;
7479 DeclarationName FoundOperator =
7480 Context.DeclarationNames.getCXXOperatorName(
7481 NewDecls.empty() ? DeleteKind : NewKind);
7482 DeclarationName MissingOperator =
7483 Context.DeclarationNames.getCXXOperatorName(
7484 NewDecls.empty() ? NewKind : DeleteKind);
7485 Diag(Record->getLocation(),
7486 diag::err_type_aware_allocator_missing_matching_operator)
7487 << FoundOperator << Context.getCanonicalTagType(Record)
7488 << MissingOperator;
7489 for (auto MD : NewDecls)
7490 Diag(MD->getLocation(),
7491 diag::note_unmatched_type_aware_allocator_declared)
7492 << MD;
7493 for (auto MD : DeleteDecls)
7494 Diag(MD->getLocation(),
7495 diag::note_unmatched_type_aware_allocator_declared)
7496 << MD;
7497 };
7498 CheckMismatchedTypeAwareAllocators(OO_New, OO_Delete);
7499 CheckMismatchedTypeAwareAllocators(OO_Array_New, OO_Array_Delete);
7500}
7501
7502/// Look up the special member function that would be called by a special
7503/// member function for a subobject of class type.
7504///
7505/// \param Class The class type of the subobject.
7506/// \param CSM The kind of special member function.
7507/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
7508/// \param ConstRHS True if this is a copy operation with a const object
7509/// on its RHS, that is, if the argument to the outer special member
7510/// function is 'const' and this is not a field marked 'mutable'.
7513 CXXSpecialMemberKind CSM, unsigned FieldQuals,
7514 bool ConstRHS) {
7515 unsigned LHSQuals = 0;
7518 LHSQuals = FieldQuals;
7519
7520 unsigned RHSQuals = FieldQuals;
7523 RHSQuals = 0;
7524 else if (ConstRHS)
7525 RHSQuals |= Qualifiers::Const;
7526
7527 return S.LookupSpecialMember(Class, CSM,
7528 RHSQuals & Qualifiers::Const,
7529 RHSQuals & Qualifiers::Volatile,
7530 false,
7531 LHSQuals & Qualifiers::Const,
7532 LHSQuals & Qualifiers::Volatile);
7533}
7534
7536 Sema &S;
7537 SourceLocation UseLoc;
7538
7539 /// A mapping from the base classes through which the constructor was
7540 /// inherited to the using shadow declaration in that base class (or a null
7541 /// pointer if the constructor was declared in that base class).
7542 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
7543 InheritedFromBases;
7544
7545public:
7548 : S(S), UseLoc(UseLoc) {
7549 bool DiagnosedMultipleConstructedBases = false;
7550 CXXRecordDecl *ConstructedBase = nullptr;
7551 BaseUsingDecl *ConstructedBaseIntroducer = nullptr;
7552
7553 // Find the set of such base class subobjects and check that there's a
7554 // unique constructed subobject.
7555 for (auto *D : Shadow->redecls()) {
7556 auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
7557 auto *DNominatedBase = DShadow->getNominatedBaseClass();
7558 auto *DConstructedBase = DShadow->getConstructedBaseClass();
7559
7560 InheritedFromBases.insert(
7561 std::make_pair(DNominatedBase->getCanonicalDecl(),
7562 DShadow->getNominatedBaseClassShadowDecl()));
7563 if (DShadow->constructsVirtualBase())
7564 InheritedFromBases.insert(
7565 std::make_pair(DConstructedBase->getCanonicalDecl(),
7566 DShadow->getConstructedBaseClassShadowDecl()));
7567 else
7568 assert(DNominatedBase == DConstructedBase);
7569
7570 // [class.inhctor.init]p2:
7571 // If the constructor was inherited from multiple base class subobjects
7572 // of type B, the program is ill-formed.
7573 if (!ConstructedBase) {
7574 ConstructedBase = DConstructedBase;
7575 ConstructedBaseIntroducer = D->getIntroducer();
7576 } else if (ConstructedBase != DConstructedBase &&
7577 !Shadow->isInvalidDecl()) {
7578 if (!DiagnosedMultipleConstructedBases) {
7579 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
7580 << Shadow->getTargetDecl();
7581 S.Diag(ConstructedBaseIntroducer->getLocation(),
7582 diag::note_ambiguous_inherited_constructor_using)
7583 << ConstructedBase;
7584 DiagnosedMultipleConstructedBases = true;
7585 }
7586 S.Diag(D->getIntroducer()->getLocation(),
7587 diag::note_ambiguous_inherited_constructor_using)
7588 << DConstructedBase;
7589 }
7590 }
7591
7592 if (DiagnosedMultipleConstructedBases)
7593 Shadow->setInvalidDecl();
7594 }
7595
7596 /// Find the constructor to use for inherited construction of a base class,
7597 /// and whether that base class constructor inherits the constructor from a
7598 /// virtual base class (in which case it won't actually invoke it).
7599 std::pair<CXXConstructorDecl *, bool>
7601 auto It = InheritedFromBases.find(Base->getCanonicalDecl());
7602 if (It == InheritedFromBases.end())
7603 return std::make_pair(nullptr, false);
7604
7605 // This is an intermediary class.
7606 if (It->second)
7607 return std::make_pair(
7608 S.findInheritingConstructor(UseLoc, Ctor, It->second),
7609 It->second->constructsVirtualBase());
7610
7611 // This is the base class from which the constructor was inherited.
7612 return std::make_pair(Ctor, false);
7613 }
7614};
7615
7616/// Is the special member function which would be selected to perform the
7617/// specified operation on the specified class type a constexpr constructor?
7619 Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, unsigned Quals,
7620 bool ConstRHS, CXXConstructorDecl *InheritedCtor = nullptr,
7621 Sema::InheritedConstructorInfo *Inherited = nullptr) {
7622 // Suppress duplicate constraint checking here, in case a constraint check
7623 // caused us to decide to do this. Any truely recursive checks will get
7624 // caught during these checks anyway.
7626
7627 // If we're inheriting a constructor, see if we need to call it for this base
7628 // class.
7629 if (InheritedCtor) {
7631 auto BaseCtor =
7632 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
7633 if (BaseCtor)
7634 return BaseCtor->isConstexpr();
7635 }
7636
7638 return ClassDecl->hasConstexprDefaultConstructor();
7640 return ClassDecl->hasConstexprDestructor();
7641
7643 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
7644 if (!SMOR.getMethod())
7645 // A constructor we wouldn't select can't be "involved in initializing"
7646 // anything.
7647 return true;
7648 return SMOR.getMethod()->isConstexpr();
7649}
7650
7651/// Determine whether the specified special member function would be constexpr
7652/// if it were implicitly defined.
7654 Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, bool ConstArg,
7655 CXXConstructorDecl *InheritedCtor = nullptr,
7656 Sema::InheritedConstructorInfo *Inherited = nullptr) {
7657 if (!S.getLangOpts().CPlusPlus11)
7658 return false;
7659
7660 // C++11 [dcl.constexpr]p4:
7661 // In the definition of a constexpr constructor [...]
7662 bool Ctor = true;
7663 switch (CSM) {
7665 if (Inherited)
7666 break;
7667 // Since default constructor lookup is essentially trivial (and cannot
7668 // involve, for instance, template instantiation), we compute whether a
7669 // defaulted default constructor is constexpr directly within CXXRecordDecl.
7670 //
7671 // This is important for performance; we need to know whether the default
7672 // constructor is constexpr to determine whether the type is a literal type.
7673 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
7674
7677 // For copy or move constructors, we need to perform overload resolution.
7678 break;
7679
7682 if (!S.getLangOpts().CPlusPlus14)
7683 return false;
7684 // In C++1y, we need to perform overload resolution.
7685 Ctor = false;
7686 break;
7687
7689 return ClassDecl->defaultedDestructorIsConstexpr();
7690
7692 return false;
7693 }
7694
7695 // -- if the class is a non-empty union, or for each non-empty anonymous
7696 // union member of a non-union class, exactly one non-static data member
7697 // shall be initialized; [DR1359]
7698 //
7699 // If we squint, this is guaranteed, since exactly one non-static data member
7700 // will be initialized (if the constructor isn't deleted), we just don't know
7701 // which one.
7702 if (Ctor && ClassDecl->isUnion())
7704 ? ClassDecl->hasInClassInitializer() ||
7705 !ClassDecl->hasVariantMembers()
7706 : true;
7707
7708 // -- the class shall not have any virtual base classes;
7709 if (!S.getLangOpts().CPlusPlus26 && Ctor && ClassDecl->getNumVBases())
7710 return false;
7711
7712 // C++1y [class.copy]p26:
7713 // -- [the class] is a literal type, and
7714 if (!S.getLangOpts().CPlusPlus23 && !Ctor && !ClassDecl->isLiteral())
7715 return false;
7716
7717 // -- every constructor involved in initializing [...] base class
7718 // sub-objects shall be a constexpr constructor;
7719 // -- the assignment operator selected to copy/move each direct base
7720 // class is a constexpr function, and
7721 if (!S.getLangOpts().CPlusPlus23) {
7722 for (const auto &B : ClassDecl->bases()) {
7723 auto *BaseClassDecl = B.getType()->getAsCXXRecordDecl();
7724 if (!BaseClassDecl)
7725 continue;
7726 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
7727 InheritedCtor, Inherited))
7728 return false;
7729 }
7730 }
7731
7732 // -- every constructor involved in initializing non-static data members
7733 // [...] shall be a constexpr constructor;
7734 // -- every non-static data member and base class sub-object shall be
7735 // initialized
7736 // -- for each non-static data member of X that is of class type (or array
7737 // thereof), the assignment operator selected to copy/move that member is
7738 // a constexpr function
7739 if (!S.getLangOpts().CPlusPlus23) {
7740 for (const auto *F : ClassDecl->fields()) {
7741 if (F->isInvalidDecl())
7742 continue;
7744 F->hasInClassInitializer())
7745 continue;
7746 QualType BaseType = S.Context.getBaseElementType(F->getType());
7747 if (const RecordType *RecordTy = BaseType->getAsCanonical<RecordType>()) {
7748 auto *FieldRecDecl =
7749 cast<CXXRecordDecl>(RecordTy->getDecl())->getDefinitionOrSelf();
7750 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
7751 BaseType.getCVRQualifiers(),
7752 ConstArg && !F->isMutable()))
7753 return false;
7754 } else if (CSM == CXXSpecialMemberKind::DefaultConstructor) {
7755 return false;
7756 }
7757 }
7758 }
7759
7760 // All OK, it's constexpr!
7761 return true;
7762}
7763
7764namespace {
7765/// RAII object to register a defaulted function as having its exception
7766/// specification computed.
7767struct ComputingExceptionSpec {
7768 Sema &S;
7769
7770 ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc)
7771 : S(S) {
7772 Sema::CodeSynthesisContext Ctx;
7774 Ctx.PointOfInstantiation = Loc;
7775 Ctx.Entity = FD;
7777 }
7778 ~ComputingExceptionSpec() {
7780 }
7781};
7782}
7783
7784static Sema::ImplicitExceptionSpecification
7785ComputeDefaultedSpecialMemberExceptionSpec(Sema &S, SourceLocation Loc,
7786 CXXMethodDecl *MD,
7788 Sema::InheritedConstructorInfo *ICI);
7789
7790static Sema::ImplicitExceptionSpecification
7791ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
7792 FunctionDecl *FD,
7794
7795static Sema::ImplicitExceptionSpecification
7797 auto DFK = FD->getDefaultedFunctionKind();
7798 if (DFK.isSpecialMember())
7800 S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr);
7801 if (DFK.isComparison())
7803 DFK.asComparison());
7804
7805 auto *CD = cast<CXXConstructorDecl>(FD);
7806 assert(CD->getInheritedConstructor() &&
7807 "only defaulted functions and inherited constructors have implicit "
7808 "exception specs");
7810 S, Loc, CD->getInheritedConstructor().getShadowDecl());
7813}
7814
7816 CXXMethodDecl *MD) {
7818
7819 // Build an exception specification pointing back at this member.
7821 EPI.ExceptionSpec.SourceDecl = MD;
7822
7823 // Set the calling convention to the default for C++ instance methods.
7825 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
7826 /*IsCXXMethod=*/true));
7827 return EPI;
7828}
7829
7831 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
7833 return;
7834
7835 // Evaluate the exception specification.
7836 auto IES = computeImplicitExceptionSpec(*this, Loc, FD);
7837 auto ESI = IES.getExceptionSpec();
7838
7839 // Update the type of the special member to use it.
7840 UpdateExceptionSpec(FD, ESI);
7841}
7842
7844 assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted");
7845
7847 if (!DefKind) {
7848 assert(FD->getDeclContext()->isDependentContext());
7849 return;
7850 }
7851
7852 if (DefKind.isComparison()) {
7853 auto PT = FD->getParamDecl(0)->getType();
7854 if (const CXXRecordDecl *RD =
7855 PT.getNonReferenceType()->getAsCXXRecordDecl()) {
7856 for (FieldDecl *Field : RD->fields()) {
7857 UnusedPrivateFields.remove(Field);
7858 }
7859 }
7860 }
7861
7862 if (DefKind.isSpecialMember()
7864 DefKind.asSpecialMember(),
7865 FD->getDefaultLoc())
7867 FD->setInvalidDecl();
7868}
7869
7872 SourceLocation DefaultLoc) {
7873 CXXRecordDecl *RD = MD->getParent();
7874
7876 "not an explicitly-defaulted special member");
7877
7878 // Defer all checking for special members of a dependent type.
7879 if (RD->isDependentType())
7880 return false;
7881
7882 // Whether this was the first-declared instance of the constructor.
7883 // This affects whether we implicitly add an exception spec and constexpr.
7884 bool First = MD == MD->getCanonicalDecl();
7885
7886 bool HadError = false;
7887
7888 // C++11 [dcl.fct.def.default]p1:
7889 // A function that is explicitly defaulted shall
7890 // -- be a special member function [...] (checked elsewhere),
7891 // -- have the same type (except for ref-qualifiers, and except that a
7892 // copy operation can take a non-const reference) as an implicit
7893 // declaration, and
7894 // -- not have default arguments.
7895 // C++2a changes the second bullet to instead delete the function if it's
7896 // defaulted on its first declaration, unless it's "an assignment operator,
7897 // and its return type differs or its parameter type is not a reference".
7898 bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First;
7899 bool ShouldDeleteForTypeMismatch = false;
7900 unsigned ExpectedParams = 1;
7903 ExpectedParams = 0;
7904 if (MD->getNumExplicitParams() != ExpectedParams) {
7905 // This checks for default arguments: a copy or move constructor with a
7906 // default argument is classified as a default constructor, and assignment
7907 // operations and destructors can't have default arguments.
7908 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
7909 << CSM << MD->getSourceRange();
7910 HadError = true;
7911 } else if (MD->isVariadic()) {
7912 if (DeleteOnTypeMismatch)
7913 ShouldDeleteForTypeMismatch = true;
7914 else {
7915 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
7916 << CSM << MD->getSourceRange();
7917 HadError = true;
7918 }
7919 }
7920
7922
7923 bool CanHaveConstParam = false;
7925 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
7927 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
7928
7929 QualType ReturnType = Context.VoidTy;
7932 // Check for return type matching.
7933 ReturnType = Type->getReturnType();
7935
7936 QualType DeclType =
7938 /*Qualifier=*/std::nullopt, RD, /*OwnsTag=*/false);
7939 DeclType = Context.getAddrSpaceQualType(
7940 DeclType, ThisType.getQualifiers().getAddressSpace());
7941 QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
7942
7943 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
7944 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
7946 << ExpectedReturnType;
7947 HadError = true;
7948 }
7949
7950 // A defaulted special member cannot have cv-qualifiers.
7951 if (ThisType.isConstQualified() || ThisType.isVolatileQualified()) {
7952 if (DeleteOnTypeMismatch)
7953 ShouldDeleteForTypeMismatch = true;
7954 else {
7955 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
7957 << getLangOpts().CPlusPlus14;
7958 HadError = true;
7959 }
7960 }
7961 // [C++23][dcl.fct.def.default]/p2.2
7962 // if F2 has an implicit object parameter of type “reference to C”,
7963 // F1 may be an explicit object member function whose explicit object
7964 // parameter is of (possibly different) type “reference to C”,
7965 // in which case the type of F1 would differ from the type of F2
7966 // in that the type of F1 has an additional parameter;
7967 QualType ExplicitObjectParameter = MD->isExplicitObjectMemberFunction()
7968 ? MD->getParamDecl(0)->getType()
7969 : QualType();
7970 if (!ExplicitObjectParameter.isNull() &&
7971 (!ExplicitObjectParameter->isReferenceType() ||
7972 !Context.hasSameType(ExplicitObjectParameter.getNonReferenceType(),
7973 Context.getCanonicalTagType(RD)))) {
7974 if (DeleteOnTypeMismatch)
7975 ShouldDeleteForTypeMismatch = true;
7976 else {
7977 Diag(MD->getLocation(),
7978 diag::err_defaulted_special_member_explicit_object_mismatch)
7979 << (CSM == CXXSpecialMemberKind::MoveAssignment) << RD
7980 << MD->getSourceRange();
7981 HadError = true;
7982 }
7983 }
7984 }
7985
7986 // Check for parameter type matching.
7988 ExpectedParams
7989 ? Type->getParamType(MD->isExplicitObjectMemberFunction() ? 1 : 0)
7990 : QualType();
7991 bool HasConstParam = false;
7992 if (ExpectedParams && ArgType->isReferenceType()) {
7993 // Argument must be reference to possibly-const T.
7994 QualType ReferentType = ArgType->getPointeeType();
7995 HasConstParam = ReferentType.isConstQualified();
7996
7997 if (ReferentType.isVolatileQualified()) {
7998 if (DeleteOnTypeMismatch)
7999 ShouldDeleteForTypeMismatch = true;
8000 else {
8001 Diag(MD->getLocation(),
8002 diag::err_defaulted_special_member_volatile_param)
8003 << CSM;
8004 HadError = true;
8005 }
8006 }
8007
8008 if (HasConstParam && !CanHaveConstParam) {
8009 if (DeleteOnTypeMismatch)
8010 ShouldDeleteForTypeMismatch = true;
8011 else if (CSM == CXXSpecialMemberKind::CopyConstructor ||
8013 Diag(MD->getLocation(),
8014 diag::err_defaulted_special_member_copy_const_param)
8016 // FIXME: Explain why this special member can't be const.
8017 HadError = true;
8018 } else {
8019 Diag(MD->getLocation(),
8020 diag::err_defaulted_special_member_move_const_param)
8022 HadError = true;
8023 }
8024 }
8025 } else if (ExpectedParams) {
8026 // A copy assignment operator can take its argument by value, but a
8027 // defaulted one cannot.
8029 "unexpected non-ref argument");
8030 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
8031 HadError = true;
8032 }
8033
8034 // C++11 [dcl.fct.def.default]p2:
8035 // An explicitly-defaulted function may be declared constexpr only if it
8036 // would have been implicitly declared as constexpr,
8037 // Do not apply this rule to members of class templates, since core issue 1358
8038 // makes such functions always instantiate to constexpr functions. For
8039 // functions which cannot be constexpr (for non-constructors in C++11 and for
8040 // destructors in C++14 and C++17), this is checked elsewhere.
8041 //
8042 // FIXME: This should not apply if the member is deleted.
8043 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
8044 HasConstParam);
8045
8046 // C++14 [dcl.constexpr]p6 (CWG DR647/CWG DR1358):
8047 // If the instantiated template specialization of a constexpr function
8048 // template or member function of a class template would fail to satisfy
8049 // the requirements for a constexpr function or constexpr constructor, that
8050 // specialization is still a constexpr function or constexpr constructor,
8051 // even though a call to such a function cannot appear in a constant
8052 // expression.
8053 if (MD->isTemplateInstantiation() && MD->isConstexpr())
8054 Constexpr = true;
8055
8056 if ((getLangOpts().CPlusPlus20 ||
8058 : isa<CXXConstructorDecl>(MD))) &&
8059 MD->isConstexpr() && !Constexpr &&
8061 if (!MD->isConsteval() && RD->getNumVBases()) {
8062 Diag(MD->getBeginLoc(),
8063 diag::err_incorrect_defaulted_constexpr_with_vb)
8064 << CSM;
8065 for (const auto &I : RD->vbases())
8066 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here);
8067 } else {
8068 Diag(MD->getBeginLoc(), diag::err_incorrect_defaulted_constexpr)
8069 << CSM << MD->isConsteval();
8070 }
8071 HadError = true;
8072 // FIXME: Explain why the special member can't be constexpr.
8073 }
8074 if (First) {
8075 // C++2a [dcl.fct.def.default]p3:
8076 // If a function is explicitly defaulted on its first declaration, it is
8077 // implicitly considered to be constexpr if the implicit declaration
8078 // would be.
8083
8084 if (!Type->hasExceptionSpec()) {
8085 // C++2a [except.spec]p3:
8086 // If a declaration of a function does not have a noexcept-specifier
8087 // [and] is defaulted on its first declaration, [...] the exception
8088 // specification is as specified below
8089 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
8091 EPI.ExceptionSpec.SourceDecl = MD;
8092 MD->setType(
8093 Context.getFunctionType(ReturnType, Type->getParamTypes(), EPI));
8094 }
8095 }
8096
8097 if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
8098 if (First) {
8099 SetDeclDeleted(MD, MD->getLocation());
8100 if (!inTemplateInstantiation() && !HadError) {
8101 Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
8102 if (ShouldDeleteForTypeMismatch) {
8103 Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
8104 } else if (ShouldDeleteSpecialMember(MD, CSM, nullptr,
8105 /*Diagnose*/ true) &&
8106 DefaultLoc.isValid()) {
8107 Diag(DefaultLoc, diag::note_replace_equals_default_to_delete)
8108 << FixItHint::CreateReplacement(DefaultLoc, "delete");
8109 }
8110 }
8111 if (ShouldDeleteForTypeMismatch && !HadError) {
8112 Diag(MD->getLocation(),
8113 diag::warn_cxx17_compat_defaulted_method_type_mismatch)
8114 << CSM;
8115 }
8116 } else {
8117 // C++11 [dcl.fct.def.default]p4:
8118 // [For a] user-provided explicitly-defaulted function [...] if such a
8119 // function is implicitly defined as deleted, the program is ill-formed.
8120 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
8121 assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
8122 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
8123 HadError = true;
8124 }
8125 }
8126
8127 return HadError;
8128}
8129
8130namespace {
8131/// Helper class for building and checking a defaulted comparison.
8132///
8133/// Defaulted functions are built in two phases:
8134///
8135/// * First, the set of operations that the function will perform are
8136/// identified, and some of them are checked. If any of the checked
8137/// operations is invalid in certain ways, the comparison function is
8138/// defined as deleted and no body is built.
8139/// * Then, if the function is not defined as deleted, the body is built.
8140///
8141/// This is accomplished by performing two visitation steps over the eventual
8142/// body of the function.
8143template<typename Derived, typename ResultList, typename Result,
8144 typename Subobject>
8145class DefaultedComparisonVisitor {
8146public:
8147 DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8149 : S(S), RD(RD), FD(FD), DCK(DCK) {
8150 if (auto *Info = FD->getDefaultedOrDeletedInfo()) {
8151 // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an
8152 // UnresolvedSet to avoid this copy.
8153 Fns.assign(Info->getUnqualifiedLookups().begin(),
8154 Info->getUnqualifiedLookups().end());
8155 }
8156 }
8157
8158 ResultList visit() {
8159 // The type of an lvalue naming a parameter of this function.
8160 QualType ParamLvalType =
8162
8163 ResultList Results;
8164
8165 switch (DCK) {
8167 llvm_unreachable("not a defaulted comparison");
8168
8171 getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers());
8172 return Results;
8173
8176 Results.add(getDerived().visitExpandedSubobject(
8177 ParamLvalType, getDerived().getCompleteObject()));
8178 return Results;
8179 }
8180 llvm_unreachable("");
8181 }
8182
8183protected:
8184 Derived &getDerived() { return static_cast<Derived&>(*this); }
8185
8186 /// Visit the expanded list of subobjects of the given type, as specified in
8187 /// C++2a [class.compare.default].
8188 ///
8189 /// \return \c true if the ResultList object said we're done, \c false if not.
8190 bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record,
8191 Qualifiers Quals) {
8192 // C++2a [class.compare.default]p4:
8193 // The direct base class subobjects of C
8194 for (CXXBaseSpecifier &Base : Record->bases())
8195 if (Results.add(getDerived().visitSubobject(
8196 S.Context.getQualifiedType(Base.getType(), Quals),
8197 getDerived().getBase(&Base))))
8198 return true;
8199
8200 // followed by the non-static data members of C
8201 for (FieldDecl *Field : Record->fields()) {
8202 // C++23 [class.bit]p2:
8203 // Unnamed bit-fields are not members ...
8204 if (Field->isUnnamedBitField())
8205 continue;
8206 // Recursively expand anonymous structs.
8207 if (Field->isAnonymousStructOrUnion()) {
8208 if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(),
8209 Quals))
8210 return true;
8211 continue;
8212 }
8213
8214 // Figure out the type of an lvalue denoting this field.
8215 Qualifiers FieldQuals = Quals;
8216 if (Field->isMutable())
8217 FieldQuals.removeConst();
8218 QualType FieldType =
8219 S.Context.getQualifiedType(Field->getType(), FieldQuals);
8220
8221 if (Results.add(getDerived().visitSubobject(
8222 FieldType, getDerived().getField(Field))))
8223 return true;
8224 }
8225
8226 // form a list of subobjects.
8227 return false;
8228 }
8229
8230 Result visitSubobject(QualType Type, Subobject Subobj) {
8231 // In that list, any subobject of array type is recursively expanded
8232 const ArrayType *AT = S.Context.getAsArrayType(Type);
8233 if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT))
8234 return getDerived().visitSubobjectArray(CAT->getElementType(),
8235 CAT->getSize(), Subobj);
8236 return getDerived().visitExpandedSubobject(Type, Subobj);
8237 }
8238
8239 Result visitSubobjectArray(QualType Type, const llvm::APInt &Size,
8240 Subobject Subobj) {
8241 return getDerived().visitSubobject(Type, Subobj);
8242 }
8243
8244protected:
8245 Sema &S;
8246 CXXRecordDecl *RD;
8247 FunctionDecl *FD;
8249 UnresolvedSet<16> Fns;
8250};
8251
8252/// Information about a defaulted comparison, as determined by
8253/// DefaultedComparisonAnalyzer.
8254struct DefaultedComparisonInfo {
8255 bool Deleted = false;
8256 bool Constexpr = true;
8257 ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering;
8258
8259 static DefaultedComparisonInfo deleted() {
8260 DefaultedComparisonInfo Deleted;
8261 Deleted.Deleted = true;
8262 return Deleted;
8263 }
8264
8265 bool add(const DefaultedComparisonInfo &R) {
8266 Deleted |= R.Deleted;
8267 Constexpr &= R.Constexpr;
8268 Category = commonComparisonType(Category, R.Category);
8269 return Deleted;
8270 }
8271};
8272
8273/// An element in the expanded list of subobjects of a defaulted comparison, as
8274/// specified in C++2a [class.compare.default]p4.
8275struct DefaultedComparisonSubobject {
8276 enum { CompleteObject, Member, Base } Kind;
8277 NamedDecl *Decl;
8278 SourceLocation Loc;
8279};
8280
8281/// A visitor over the notional body of a defaulted comparison that determines
8282/// whether that body would be deleted or constexpr.
8283class DefaultedComparisonAnalyzer
8284 : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer,
8285 DefaultedComparisonInfo,
8286 DefaultedComparisonInfo,
8287 DefaultedComparisonSubobject> {
8288public:
8289 enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr };
8290
8291private:
8292 DiagnosticKind Diagnose;
8293
8294public:
8295 using Base = DefaultedComparisonVisitor;
8296 using Result = DefaultedComparisonInfo;
8297 using Subobject = DefaultedComparisonSubobject;
8298
8299 friend Base;
8300
8301 DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8303 DiagnosticKind Diagnose = NoDiagnostics)
8304 : Base(S, RD, FD, DCK), Diagnose(Diagnose) {}
8305
8306 Result visit() {
8307 if ((DCK == DefaultedComparisonKind::Equal ||
8308 DCK == DefaultedComparisonKind::ThreeWay) &&
8309 RD->hasVariantMembers()) {
8310 // C++2a [class.compare.default]p2 [P2002R0]:
8311 // A defaulted comparison operator function for class C is defined as
8312 // deleted if [...] C has variant members.
8313 if (Diagnose == ExplainDeleted) {
8314 S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union)
8315 << FD << RD->isUnion() << RD;
8316 }
8317 return Result::deleted();
8318 }
8319
8320 return Base::visit();
8321 }
8322
8323private:
8324 Subobject getCompleteObject() {
8325 return Subobject{Subobject::CompleteObject, RD, FD->getLocation()};
8326 }
8327
8328 Subobject getBase(CXXBaseSpecifier *Base) {
8329 return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(),
8330 Base->getBaseTypeLoc()};
8331 }
8332
8333 Subobject getField(FieldDecl *Field) {
8334 return Subobject{Subobject::Member, Field, Field->getLocation()};
8335 }
8336
8337 Result visitExpandedSubobject(QualType Type, Subobject Subobj) {
8338 // C++2a [class.compare.default]p2 [P2002R0]:
8339 // A defaulted <=> or == operator function for class C is defined as
8340 // deleted if any non-static data member of C is of reference type
8341 if (Type->isReferenceType()) {
8342 if (Diagnose == ExplainDeleted) {
8343 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member)
8344 << FD << RD;
8345 }
8346 return Result::deleted();
8347 }
8348
8349 // [...] Let xi be an lvalue denoting the ith element [...]
8350 OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue);
8351 Expr *Args[] = {&Xi, &Xi};
8352
8353 // All operators start by trying to apply that same operator recursively.
8355 assert(OO != OO_None && "not an overloaded operator!");
8356 return visitBinaryOperator(OO, Args, Subobj);
8357 }
8358
8359 Result
8360 visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args,
8361 Subobject Subobj,
8362 OverloadCandidateSet *SpaceshipCandidates = nullptr) {
8363 // Note that there is no need to consider rewritten candidates here if
8364 // we've already found there is no viable 'operator<=>' candidate (and are
8365 // considering synthesizing a '<=>' from '==' and '<').
8366 OverloadCandidateSet CandidateSet(
8368 OverloadCandidateSet::OperatorRewriteInfo(
8369 OO, FD->getLocation(),
8370 /*AllowRewrittenCandidates=*/!SpaceshipCandidates));
8371
8372 /// C++2a [class.compare.default]p1 [P2002R0]:
8373 /// [...] the defaulted function itself is never a candidate for overload
8374 /// resolution [...]
8375 CandidateSet.exclude(FD);
8376
8377 if (Args[0]->getType()->isOverloadableType())
8378 S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args);
8379 else
8380 // FIXME: We determine whether this is a valid expression by checking to
8381 // see if there's a viable builtin operator candidate for it. That isn't
8382 // really what the rules ask us to do, but should give the right results.
8383 S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet);
8384
8385 Result R;
8386
8388 switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) {
8389 case OR_Success: {
8390 // C++2a [class.compare.secondary]p2 [P2002R0]:
8391 // The operator function [...] is defined as deleted if [...] the
8392 // candidate selected by overload resolution is not a rewritten
8393 // candidate.
8394 if ((DCK == DefaultedComparisonKind::NotEqual ||
8395 DCK == DefaultedComparisonKind::Relational) &&
8396 !Best->RewriteKind) {
8397 if (Diagnose == ExplainDeleted) {
8398 if (Best->Function) {
8399 S.Diag(Best->Function->getLocation(),
8400 diag::note_defaulted_comparison_not_rewritten_callee)
8401 << FD;
8402 } else {
8403 assert(Best->Conversions.size() == 2 &&
8404 Best->Conversions[0].isUserDefined() &&
8405 "non-user-defined conversion from class to built-in "
8406 "comparison");
8407 S.Diag(Best->Conversions[0]
8408 .UserDefined.FoundConversionFunction.getDecl()
8409 ->getLocation(),
8410 diag::note_defaulted_comparison_not_rewritten_conversion)
8411 << FD;
8412 }
8413 }
8414 return Result::deleted();
8415 }
8416
8417 // Throughout C++2a [class.compare]: if overload resolution does not
8418 // result in a usable function, the candidate function is defined as
8419 // deleted. This requires that we selected an accessible function.
8420 //
8421 // Note that this only considers the access of the function when named
8422 // within the type of the subobject, and not the access path for any
8423 // derived-to-base conversion.
8424 CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl();
8425 if (ArgClass && Best->FoundDecl.getDecl() &&
8426 Best->FoundDecl.getDecl()->isCXXClassMember()) {
8427 QualType ObjectType = Subobj.Kind == Subobject::Member
8428 ? Args[0]->getType()
8431 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc,
8432 Diagnose == ExplainDeleted
8433 ? S.PDiag(diag::note_defaulted_comparison_inaccessible)
8434 << FD << Subobj.Kind << Subobj.Decl
8435 : S.PDiag()))
8436 return Result::deleted();
8437 }
8438
8439 bool NeedsDeducing =
8440 OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType();
8441
8442 if (FunctionDecl *BestFD = Best->Function) {
8443 // C++2a [class.compare.default]p3 [P2002R0]:
8444 // A defaulted comparison function is constexpr-compatible if
8445 // [...] no overlod resolution performed [...] results in a
8446 // non-constexpr function.
8447 assert(!BestFD->isDeleted() && "wrong overload resolution result");
8448 // If it's not constexpr, explain why not.
8449 if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) {
8450 if (Subobj.Kind != Subobject::CompleteObject)
8451 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr)
8452 << Subobj.Kind << Subobj.Decl;
8453 S.Diag(BestFD->getLocation(),
8454 diag::note_defaulted_comparison_not_constexpr_here);
8455 // Bail out after explaining; we don't want any more notes.
8456 return Result::deleted();
8457 }
8458 R.Constexpr &= BestFD->isConstexpr();
8459
8460 if (NeedsDeducing) {
8461 // If any callee has an undeduced return type, deduce it now.
8462 // FIXME: It's not clear how a failure here should be handled. For
8463 // now, we produce an eager diagnostic, because that is forward
8464 // compatible with most (all?) other reasonable options.
8465 if (BestFD->getReturnType()->isUndeducedType() &&
8466 S.DeduceReturnType(BestFD, FD->getLocation(),
8467 /*Diagnose=*/false)) {
8468 // Don't produce a duplicate error when asked to explain why the
8469 // comparison is deleted: we diagnosed that when initially checking
8470 // the defaulted operator.
8471 if (Diagnose == NoDiagnostics) {
8472 S.Diag(
8473 FD->getLocation(),
8474 diag::err_defaulted_comparison_cannot_deduce_undeduced_auto)
8475 << Subobj.Kind << Subobj.Decl;
8476 S.Diag(
8477 Subobj.Loc,
8478 diag::note_defaulted_comparison_cannot_deduce_undeduced_auto)
8479 << Subobj.Kind << Subobj.Decl;
8480 S.Diag(BestFD->getLocation(),
8481 diag::note_defaulted_comparison_cannot_deduce_callee)
8482 << Subobj.Kind << Subobj.Decl;
8483 }
8484 return Result::deleted();
8485 }
8487 BestFD->getCallResultType());
8488 if (!Info) {
8489 if (Diagnose == ExplainDeleted) {
8490 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce)
8491 << Subobj.Kind << Subobj.Decl
8492 << BestFD->getCallResultType().withoutLocalFastQualifiers();
8493 S.Diag(BestFD->getLocation(),
8494 diag::note_defaulted_comparison_cannot_deduce_callee)
8495 << Subobj.Kind << Subobj.Decl;
8496 }
8497 return Result::deleted();
8498 }
8499 R.Category = Info->Kind;
8500 }
8501 } else {
8502 QualType T = Best->BuiltinParamTypes[0];
8503 assert(T == Best->BuiltinParamTypes[1] &&
8504 "builtin comparison for different types?");
8505 assert(Best->BuiltinParamTypes[2].isNull() &&
8506 "invalid builtin comparison");
8507
8508 // FIXME: If the type we deduced is a vector type, we mark the
8509 // comparison as deleted because we don't yet support this.
8510 if (isa<VectorType>(T)) {
8511 if (Diagnose == ExplainDeleted) {
8512 S.Diag(FD->getLocation(),
8513 diag::note_defaulted_comparison_vector_types)
8514 << FD;
8515 S.Diag(Subobj.Decl->getLocation(), diag::note_declared_at);
8516 }
8517 return Result::deleted();
8518 }
8519
8520 if (NeedsDeducing) {
8521 std::optional<ComparisonCategoryType> Cat =
8523 assert(Cat && "no category for builtin comparison?");
8524 R.Category = *Cat;
8525 }
8526 }
8527
8528 // Note that we might be rewriting to a different operator. That call is
8529 // not considered until we come to actually build the comparison function.
8530 break;
8531 }
8532
8533 case OR_Ambiguous:
8534 if (Diagnose == ExplainDeleted) {
8535 unsigned Kind = 0;
8536 if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship)
8537 Kind = OO == OO_EqualEqual ? 1 : 2;
8538 CandidateSet.NoteCandidates(
8540 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous)
8541 << FD << Kind << Subobj.Kind << Subobj.Decl),
8542 S, OCD_AmbiguousCandidates, Args);
8543 }
8544 R = Result::deleted();
8545 break;
8546
8547 case OR_Deleted:
8548 if (Diagnose == ExplainDeleted) {
8549 if ((DCK == DefaultedComparisonKind::NotEqual ||
8550 DCK == DefaultedComparisonKind::Relational) &&
8551 !Best->RewriteKind) {
8552 S.Diag(Best->Function->getLocation(),
8553 diag::note_defaulted_comparison_not_rewritten_callee)
8554 << FD;
8555 } else {
8556 S.Diag(Subobj.Loc,
8557 diag::note_defaulted_comparison_calls_deleted)
8558 << FD << Subobj.Kind << Subobj.Decl;
8559 S.NoteDeletedFunction(Best->Function);
8560 }
8561 }
8562 R = Result::deleted();
8563 break;
8564
8566 // If there's no usable candidate, we're done unless we can rewrite a
8567 // '<=>' in terms of '==' and '<'.
8568 if (OO == OO_Spaceship &&
8570 // For any kind of comparison category return type, we need a usable
8571 // '==' and a usable '<'.
8572 if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj,
8573 &CandidateSet)))
8574 R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet));
8575 break;
8576 }
8577
8578 if (Diagnose == ExplainDeleted) {
8579 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function)
8580 << FD << (OO == OO_EqualEqual || OO == OO_ExclaimEqual)
8581 << Subobj.Kind << Subobj.Decl;
8582
8583 // For a three-way comparison, list both the candidates for the
8584 // original operator and the candidates for the synthesized operator.
8585 if (SpaceshipCandidates) {
8586 SpaceshipCandidates->NoteCandidates(
8587 S, Args,
8588 SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates,
8589 Args, FD->getLocation()));
8590 S.Diag(Subobj.Loc,
8591 diag::note_defaulted_comparison_no_viable_function_synthesized)
8592 << (OO == OO_EqualEqual ? 0 : 1);
8593 }
8594
8595 CandidateSet.NoteCandidates(
8596 S, Args,
8597 CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args,
8598 FD->getLocation()));
8599 }
8600 R = Result::deleted();
8601 break;
8602 }
8603
8604 return R;
8605 }
8606};
8607
8608/// A list of statements.
8609struct StmtListResult {
8610 bool IsInvalid = false;
8611 llvm::SmallVector<Stmt*, 16> Stmts;
8612
8613 bool add(const StmtResult &S) {
8614 IsInvalid |= S.isInvalid();
8615 if (IsInvalid)
8616 return true;
8617 Stmts.push_back(S.get());
8618 return false;
8619 }
8620};
8621
8622/// A visitor over the notional body of a defaulted comparison that synthesizes
8623/// the actual body.
8624class DefaultedComparisonSynthesizer
8625 : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer,
8626 StmtListResult, StmtResult,
8627 std::pair<ExprResult, ExprResult>> {
8628 SourceLocation Loc;
8629 unsigned ArrayDepth = 0;
8630
8631public:
8632 using Base = DefaultedComparisonVisitor;
8633 using ExprPair = std::pair<ExprResult, ExprResult>;
8634
8635 friend Base;
8636
8637 DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8639 SourceLocation BodyLoc)
8640 : Base(S, RD, FD, DCK), Loc(BodyLoc) {}
8641
8642 /// Build a suitable function body for this defaulted comparison operator.
8643 StmtResult build() {
8644 Sema::CompoundScopeRAII CompoundScope(S);
8645
8646 StmtListResult Stmts = visit();
8647 if (Stmts.IsInvalid)
8648 return StmtError();
8649
8650 ExprResult RetVal;
8651 switch (DCK) {
8652 case DefaultedComparisonKind::None:
8653 llvm_unreachable("not a defaulted comparison");
8654
8655 case DefaultedComparisonKind::Equal: {
8656 // C++2a [class.eq]p3:
8657 // [...] compar[e] the corresponding elements [...] until the first
8658 // index i where xi == yi yields [...] false. If no such index exists,
8659 // V is true. Otherwise, V is false.
8660 //
8661 // Join the comparisons with '&&'s and return the result. Use a right
8662 // fold (traversing the conditions right-to-left), because that
8663 // short-circuits more naturally.
8664 auto OldStmts = std::move(Stmts.Stmts);
8665 Stmts.Stmts.clear();
8666 ExprResult CmpSoFar;
8667 // Finish a particular comparison chain.
8668 auto FinishCmp = [&] {
8669 if (Expr *Prior = CmpSoFar.get()) {
8670 // Convert the last expression to 'return ...;'
8671 if (RetVal.isUnset() && Stmts.Stmts.empty())
8672 RetVal = CmpSoFar;
8673 // Convert any prior comparison to 'if (!(...)) return false;'
8674 else if (Stmts.add(buildIfNotCondReturnFalse(Prior)))
8675 return true;
8676 CmpSoFar = ExprResult();
8677 }
8678 return false;
8679 };
8680 for (Stmt *EAsStmt : llvm::reverse(OldStmts)) {
8681 Expr *E = dyn_cast<Expr>(EAsStmt);
8682 if (!E) {
8683 // Found an array comparison.
8684 if (FinishCmp() || Stmts.add(EAsStmt))
8685 return StmtError();
8686 continue;
8687 }
8688
8689 if (CmpSoFar.isUnset()) {
8690 CmpSoFar = E;
8691 continue;
8692 }
8693 CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get());
8694 if (CmpSoFar.isInvalid())
8695 return StmtError();
8696 }
8697 if (FinishCmp())
8698 return StmtError();
8699 std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end());
8700 // If no such index exists, V is true.
8701 if (RetVal.isUnset())
8702 RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true);
8703 break;
8704 }
8705
8706 case DefaultedComparisonKind::ThreeWay: {
8707 // Per C++2a [class.spaceship]p3, as a fallback add:
8708 // return static_cast<R>(std::strong_ordering::equal);
8709 QualType StrongOrdering = S.CheckComparisonCategoryType(
8710 ComparisonCategoryType::StrongOrdering, Loc,
8711 Sema::ComparisonCategoryUsage::DefaultedOperator);
8712 if (StrongOrdering.isNull())
8713 return StmtError();
8714 VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(StrongOrdering)
8715 .getValueInfo(ComparisonCategoryResult::Equal)
8716 ->VD;
8717 RetVal = getDecl(EqualVD);
8718 if (RetVal.isInvalid())
8719 return StmtError();
8720 RetVal = buildStaticCastToR(RetVal.get());
8721 break;
8722 }
8723
8724 case DefaultedComparisonKind::NotEqual:
8725 case DefaultedComparisonKind::Relational:
8726 RetVal = cast<Expr>(Stmts.Stmts.pop_back_val());
8727 break;
8728 }
8729
8730 // Build the final return statement.
8731 if (RetVal.isInvalid())
8732 return StmtError();
8733 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get());
8734 if (ReturnStmt.isInvalid())
8735 return StmtError();
8736 Stmts.Stmts.push_back(ReturnStmt.get());
8737
8738 return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false);
8739 }
8740
8741private:
8742 ExprResult getDecl(ValueDecl *VD) {
8743 return S.BuildDeclarationNameExpr(
8744 CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD);
8745 }
8746
8747 ExprResult getParam(unsigned I) {
8748 ParmVarDecl *PD = FD->getParamDecl(I);
8749 return getDecl(PD);
8750 }
8751
8752 ExprPair getCompleteObject() {
8753 unsigned Param = 0;
8754 ExprResult LHS;
8755 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD);
8756 MD && MD->isImplicitObjectMemberFunction()) {
8757 // LHS is '*this'.
8758 LHS = S.ActOnCXXThis(Loc);
8759 if (!LHS.isInvalid())
8760 LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get());
8761 } else {
8762 LHS = getParam(Param++);
8763 }
8764 ExprResult RHS = getParam(Param++);
8765 assert(Param == FD->getNumParams());
8766 return {LHS, RHS};
8767 }
8768
8769 ExprPair getBase(CXXBaseSpecifier *Base) {
8770 ExprPair Obj = getCompleteObject();
8771 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8772 return {ExprError(), ExprError()};
8773 CXXCastPath Path = {Base};
8774 const auto CastToBase = [&](Expr *E) {
8775 QualType ToType = S.Context.getQualifiedType(
8776 Base->getType(), E->getType().getQualifiers());
8777 return S.ImpCastExprToType(E, ToType, CK_DerivedToBase, VK_LValue, &Path);
8778 };
8779 return {CastToBase(Obj.first.get()), CastToBase(Obj.second.get())};
8780 }
8781
8782 ExprPair getField(FieldDecl *Field) {
8783 ExprPair Obj = getCompleteObject();
8784 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8785 return {ExprError(), ExprError()};
8786
8787 DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess());
8788 DeclarationNameInfo NameInfo(Field->getDeclName(), Loc);
8789 return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc,
8790 CXXScopeSpec(), Field, Found, NameInfo),
8791 S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc,
8792 CXXScopeSpec(), Field, Found, NameInfo)};
8793 }
8794
8795 // FIXME: When expanding a subobject, register a note in the code synthesis
8796 // stack to say which subobject we're comparing.
8797
8798 StmtResult buildIfNotCondReturnFalse(ExprResult Cond) {
8799 if (Cond.isInvalid())
8800 return StmtError();
8801
8802 ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get());
8803 if (NotCond.isInvalid())
8804 return StmtError();
8805
8806 ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false);
8807 assert(!False.isInvalid() && "should never fail");
8808 StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get());
8809 if (ReturnFalse.isInvalid())
8810 return StmtError();
8811
8812 return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, nullptr,
8813 S.ActOnCondition(nullptr, Loc, NotCond.get(),
8814 Sema::ConditionKind::Boolean),
8815 Loc, ReturnFalse.get(), SourceLocation(), nullptr);
8816 }
8817
8818 StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size,
8819 ExprPair Subobj) {
8820 QualType SizeType = S.Context.getSizeType();
8821 Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType));
8822
8823 // Build 'size_t i$n = 0'.
8824 IdentifierInfo *IterationVarName = nullptr;
8825 {
8826 SmallString<8> Str;
8827 llvm::raw_svector_ostream OS(Str);
8828 OS << "i" << ArrayDepth;
8829 IterationVarName = &S.Context.Idents.get(OS.str());
8830 }
8831 VarDecl *IterationVar = VarDecl::Create(
8832 S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType,
8833 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None);
8834 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
8835 IterationVar->setInit(
8836 IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
8837 Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc);
8838
8839 auto IterRef = [&] {
8840 ExprResult Ref = S.BuildDeclarationNameExpr(
8841 CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc),
8842 IterationVar);
8843 assert(!Ref.isInvalid() && "can't reference our own variable?");
8844 return Ref.get();
8845 };
8846
8847 // Build 'i$n != Size'.
8848 ExprResult Cond = S.CreateBuiltinBinOp(
8849 Loc, BO_NE, IterRef(),
8850 IntegerLiteral::Create(S.Context, Size, SizeType, Loc));
8851 assert(!Cond.isInvalid() && "should never fail");
8852
8853 // Build '++i$n'.
8854 ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef());
8855 assert(!Inc.isInvalid() && "should never fail");
8856
8857 // Build 'a[i$n]' and 'b[i$n]'.
8858 auto Index = [&](ExprResult E) {
8859 if (E.isInvalid())
8860 return ExprError();
8861 return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc);
8862 };
8863 Subobj.first = Index(Subobj.first);
8864 Subobj.second = Index(Subobj.second);
8865
8866 // Compare the array elements.
8867 ++ArrayDepth;
8868 StmtResult Substmt = visitSubobject(Type, Subobj);
8869 --ArrayDepth;
8870
8871 if (Substmt.isInvalid())
8872 return StmtError();
8873
8874 // For the inner level of an 'operator==', build 'if (!cmp) return false;'.
8875 // For outer levels or for an 'operator<=>' we already have a suitable
8876 // statement that returns as necessary.
8877 if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) {
8878 assert(DCK == DefaultedComparisonKind::Equal &&
8879 "should have non-expression statement");
8880 Substmt = buildIfNotCondReturnFalse(ElemCmp);
8881 if (Substmt.isInvalid())
8882 return StmtError();
8883 }
8884
8885 // Build 'for (...) ...'
8886 return S.ActOnForStmt(Loc, Loc, Init,
8887 S.ActOnCondition(nullptr, Loc, Cond.get(),
8888 Sema::ConditionKind::Boolean),
8889 S.MakeFullDiscardedValueExpr(Inc.get()), Loc,
8890 Substmt.get());
8891 }
8892
8893 StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) {
8894 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8895 return StmtError();
8896
8899 ExprResult Op;
8900 if (Type->isOverloadableType())
8901 Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(),
8902 Obj.second.get(), /*PerformADL=*/true,
8903 /*AllowRewrittenCandidates=*/true, FD);
8904 else
8905 Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get());
8906 if (Op.isInvalid())
8907 return StmtError();
8908
8909 switch (DCK) {
8910 case DefaultedComparisonKind::None:
8911 llvm_unreachable("not a defaulted comparison");
8912
8913 case DefaultedComparisonKind::Equal:
8914 // Per C++2a [class.eq]p2, each comparison is individually contextually
8915 // converted to bool.
8916 Op = S.PerformContextuallyConvertToBool(Op.get());
8917 if (Op.isInvalid())
8918 return StmtError();
8919 return Op.get();
8920
8921 case DefaultedComparisonKind::ThreeWay: {
8922 // Per C++2a [class.spaceship]p3, form:
8923 // if (R cmp = static_cast<R>(op); cmp != 0)
8924 // return cmp;
8925 QualType R = FD->getReturnType();
8926 Op = buildStaticCastToR(Op.get());
8927 if (Op.isInvalid())
8928 return StmtError();
8929
8930 // R cmp = ...;
8931 IdentifierInfo *Name = &S.Context.Idents.get("cmp");
8932 VarDecl *VD =
8933 VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R,
8934 S.Context.getTrivialTypeSourceInfo(R, Loc), SC_None);
8935 S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false);
8936 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc);
8937
8938 // cmp != 0
8939 ExprResult VDRef = getDecl(VD);
8940 if (VDRef.isInvalid())
8941 return StmtError();
8942 llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0);
8943 Expr *Zero =
8944 IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc);
8946 if (VDRef.get()->getType()->isOverloadableType())
8947 Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true,
8948 true, FD);
8949 else
8950 Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero);
8951 if (Comp.isInvalid())
8952 return StmtError();
8953 Sema::ConditionResult Cond = S.ActOnCondition(
8954 nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean);
8955 if (Cond.isInvalid())
8956 return StmtError();
8957
8958 // return cmp;
8959 VDRef = getDecl(VD);
8960 if (VDRef.isInvalid())
8961 return StmtError();
8962 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get());
8963 if (ReturnStmt.isInvalid())
8964 return StmtError();
8965
8966 // if (...)
8967 return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, InitStmt, Cond,
8968 Loc, ReturnStmt.get(),
8969 /*ElseLoc=*/SourceLocation(), /*Else=*/nullptr);
8970 }
8971
8972 case DefaultedComparisonKind::NotEqual:
8973 case DefaultedComparisonKind::Relational:
8974 // C++2a [class.compare.secondary]p2:
8975 // Otherwise, the operator function yields x @ y.
8976 return Op.get();
8977 }
8978 llvm_unreachable("");
8979 }
8980
8981 /// Build "static_cast<R>(E)".
8982 ExprResult buildStaticCastToR(Expr *E) {
8983 QualType R = FD->getReturnType();
8984 assert(!R->isUndeducedType() && "type should have been deduced already");
8985
8986 // Don't bother forming a no-op cast in the common case.
8987 if (E->isPRValue() && S.Context.hasSameType(E->getType(), R))
8988 return E;
8989 return S.BuildCXXNamedCast(Loc, tok::kw_static_cast,
8990 S.Context.getTrivialTypeSourceInfo(R, Loc), E,
8991 SourceRange(Loc, Loc), SourceRange(Loc, Loc));
8992 }
8993};
8994}
8995
8996/// Perform the unqualified lookups that might be needed to form a defaulted
8997/// comparison function for the given operator.
8999 UnresolvedSetImpl &Operators,
9001 auto Lookup = [&](OverloadedOperatorKind OO) {
9002 Self.LookupOverloadedOperatorName(OO, S, Operators);
9003 };
9004
9005 // Every defaulted operator looks up itself.
9006 Lookup(Op);
9007 // ... and the rewritten form of itself, if any.
9009 Lookup(ExtraOp);
9010
9011 // For 'operator<=>', we also form a 'cmp != 0' expression, and might
9012 // synthesize a three-way comparison from '<' and '=='. In a dependent
9013 // context, we also need to look up '==' in case we implicitly declare a
9014 // defaulted 'operator=='.
9015 if (Op == OO_Spaceship) {
9016 Lookup(OO_ExclaimEqual);
9017 Lookup(OO_Less);
9018 Lookup(OO_EqualEqual);
9019 }
9020}
9021
9024 assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison");
9025
9026 // Perform any unqualified lookups we're going to need to default this
9027 // function.
9028 if (S) {
9029 UnresolvedSet<32> Operators;
9030 lookupOperatorsForDefaultedComparison(*this, S, Operators,
9031 FD->getOverloadedOperator());
9034 Context, Operators.pairs(), CurFPFeatureOverrides()));
9035 }
9036
9037 // C++2a [class.compare.default]p1:
9038 // A defaulted comparison operator function for some class C shall be a
9039 // non-template function declared in the member-specification of C that is
9040 // -- a non-static const non-volatile member of C having one parameter of
9041 // type const C& and either no ref-qualifier or the ref-qualifier &, or
9042 // -- a friend of C having two parameters of type const C& or two
9043 // parameters of type C.
9044
9045 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext());
9046 bool IsMethod = isa<CXXMethodDecl>(FD);
9047 if (IsMethod) {
9048 auto *MD = cast<CXXMethodDecl>(FD);
9049 assert(!MD->isStatic() && "comparison function cannot be a static member");
9050
9051 if (MD->getRefQualifier() == RQ_RValue) {
9052 Diag(MD->getLocation(), diag::err_ref_qualifier_comparison_operator);
9053
9054 // Remove the ref qualifier to recover.
9055 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
9056 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9057 EPI.RefQualifier = RQ_None;
9058 MD->setType(Context.getFunctionType(FPT->getReturnType(),
9059 FPT->getParamTypes(), EPI));
9060 }
9061
9062 // If we're out-of-class, this is the class we're comparing.
9063 if (!RD)
9064 RD = MD->getParent();
9065 QualType T = MD->getFunctionObjectParameterReferenceType();
9066 if (!T.getNonReferenceType().isConstQualified() &&
9067 (MD->isImplicitObjectMemberFunction() || T->isLValueReferenceType())) {
9068 SourceLocation Loc, InsertLoc;
9069 if (MD->isExplicitObjectMemberFunction()) {
9070 Loc = MD->getParamDecl(0)->getBeginLoc();
9071 InsertLoc = getLocForEndOfToken(
9072 MD->getParamDecl(0)->getExplicitObjectParamThisLoc());
9073 } else {
9074 Loc = MD->getLocation();
9075 if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc())
9076 InsertLoc = getLocForEndOfToken(Loc.getRParenLoc());
9077 }
9078 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
9079 // corresponding defaulted 'operator<=>' already.
9080 if (!MD->isImplicit()) {
9081 Diag(Loc, diag::err_defaulted_comparison_non_const)
9082 << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const");
9083 }
9084
9085 // Add the 'const' to the type to recover.
9086 if (MD->isExplicitObjectMemberFunction()) {
9087 assert(T->isLValueReferenceType());
9088 MD->getParamDecl(0)->setType(Context.getLValueReferenceType(
9089 T.getNonReferenceType().withConst()));
9090 } else {
9091 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
9092 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9093 EPI.TypeQuals.addConst();
9094 MD->setType(Context.getFunctionType(FPT->getReturnType(),
9095 FPT->getParamTypes(), EPI));
9096 }
9097 }
9098
9099 if (MD->isVolatile()) {
9100 Diag(MD->getLocation(), diag::err_volatile_comparison_operator);
9101
9102 // Remove the 'volatile' from the type to recover.
9103 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
9104 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9106 MD->setType(Context.getFunctionType(FPT->getReturnType(),
9107 FPT->getParamTypes(), EPI));
9108 }
9109 }
9110
9111 if ((FD->getNumParams() -
9112 (unsigned)FD->hasCXXExplicitFunctionObjectParameter()) !=
9113 (IsMethod ? 1 : 2)) {
9114 // Let's not worry about using a variadic template pack here -- who would do
9115 // such a thing?
9116 Diag(FD->getLocation(), diag::err_defaulted_comparison_num_args)
9117 << int(IsMethod) << int(DCK);
9118 return true;
9119 }
9120
9121 const ParmVarDecl *KnownParm = nullptr;
9122 for (const ParmVarDecl *Param : FD->parameters()) {
9123 QualType ParmTy = Param->getType();
9124 if (!KnownParm) {
9125 auto CTy = ParmTy;
9126 // Is it `T const &`?
9127 bool Ok = !IsMethod || FD->hasCXXExplicitFunctionObjectParameter();
9128 QualType ExpectedTy;
9129 if (RD)
9130 ExpectedTy = Context.getCanonicalTagType(RD);
9131 if (auto *Ref = CTy->getAs<LValueReferenceType>()) {
9132 CTy = Ref->getPointeeType();
9133 if (RD)
9134 ExpectedTy.addConst();
9135 Ok = true;
9136 }
9137
9138 // Is T a class?
9139 if (RD) {
9140 Ok &= RD->isDependentType() || Context.hasSameType(CTy, ExpectedTy);
9141 } else {
9142 RD = CTy->getAsCXXRecordDecl();
9143 Ok &= RD != nullptr;
9144 }
9145
9146 if (Ok) {
9147 KnownParm = Param;
9148 } else {
9149 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
9150 // corresponding defaulted 'operator<=>' already.
9151 if (!FD->isImplicit()) {
9152 if (RD) {
9153 CanQualType PlainTy = Context.getCanonicalTagType(RD);
9154 QualType RefTy =
9155 Context.getLValueReferenceType(PlainTy.withConst());
9156 Diag(FD->getLocation(), diag::err_defaulted_comparison_param)
9157 << int(DCK) << ParmTy << RefTy << int(!IsMethod) << PlainTy
9158 << Param->getSourceRange();
9159 } else {
9160 assert(!IsMethod && "should know expected type for method");
9161 Diag(FD->getLocation(),
9162 diag::err_defaulted_comparison_param_unknown)
9163 << int(DCK) << ParmTy << Param->getSourceRange();
9164 }
9165 }
9166 return true;
9167 }
9168 } else if (!Context.hasSameType(KnownParm->getType(), ParmTy)) {
9169 Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch)
9170 << int(DCK) << KnownParm->getType() << KnownParm->getSourceRange()
9171 << ParmTy << Param->getSourceRange();
9172 return true;
9173 }
9174 }
9175
9176 assert(RD && "must have determined class");
9177 if (IsMethod) {
9178 } else if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
9179 // In-class, must be a friend decl.
9180 assert(FD->getFriendObjectKind() && "expected a friend declaration");
9181 } else {
9182 // Out of class, require the defaulted comparison to be a friend (of a
9183 // complete type, per CWG2547).
9184 if (RequireCompleteType(FD->getLocation(), Context.getCanonicalTagType(RD),
9185 diag::err_defaulted_comparison_not_friend, int(DCK),
9186 int(1)))
9187 return true;
9188
9189 if (llvm::none_of(RD->friends(), [&](const FriendDecl *F) {
9190 return declaresSameEntity(F->getFriendDecl(), FD);
9191 })) {
9192 Diag(FD->getLocation(), diag::err_defaulted_comparison_not_friend)
9193 << int(DCK) << int(0) << RD;
9194 Diag(RD->getCanonicalDecl()->getLocation(), diag::note_declared_at);
9195 return true;
9196 }
9197 }
9198
9199 // C++2a [class.eq]p1, [class.rel]p1:
9200 // A [defaulted comparison other than <=>] shall have a declared return
9201 // type bool.
9204 !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) {
9205 Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool)
9206 << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy
9207 << FD->getReturnTypeSourceRange();
9208 return true;
9209 }
9210 // C++2a [class.spaceship]p2 [P2002R0]:
9211 // Let R be the declared return type [...]. If R is auto, [...]. Otherwise,
9212 // R shall not contain a placeholder type.
9213 if (QualType RT = FD->getDeclaredReturnType();
9215 RT->getContainedDeducedType() &&
9216 (!Context.hasSameType(RT, Context.getAutoDeductType()) ||
9217 RT->getContainedAutoType()->isConstrained())) {
9218 Diag(FD->getLocation(),
9219 diag::err_defaulted_comparison_deduced_return_type_not_auto)
9220 << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy
9221 << FD->getReturnTypeSourceRange();
9222 return true;
9223 }
9224
9225 // For a defaulted function in a dependent class, defer all remaining checks
9226 // until instantiation.
9227 if (RD->isDependentType())
9228 return false;
9229
9230 // Determine whether the function should be defined as deleted.
9231 DefaultedComparisonInfo Info =
9232 DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit();
9233
9234 bool First = FD == FD->getCanonicalDecl();
9235
9236 if (!First) {
9237 if (Info.Deleted) {
9238 // C++11 [dcl.fct.def.default]p4:
9239 // [For a] user-provided explicitly-defaulted function [...] if such a
9240 // function is implicitly defined as deleted, the program is ill-formed.
9241 //
9242 // This is really just a consequence of the general rule that you can
9243 // only delete a function on its first declaration.
9244 Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes)
9245 << FD->isImplicit() << (int)DCK;
9246 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9247 DefaultedComparisonAnalyzer::ExplainDeleted)
9248 .visit();
9249 return true;
9250 }
9252 // C++20 [class.compare.default]p1:
9253 // [...] A definition of a comparison operator as defaulted that appears
9254 // in a class shall be the first declaration of that function.
9255 Diag(FD->getLocation(), diag::err_non_first_default_compare_in_class)
9256 << (int)DCK;
9258 diag::note_previous_declaration);
9259 return true;
9260 }
9261 }
9262
9263 // If we want to delete the function, then do so; there's nothing else to
9264 // check in that case.
9265 if (Info.Deleted) {
9266 SetDeclDeleted(FD, FD->getLocation());
9267 if (!inTemplateInstantiation() && !FD->isImplicit()) {
9268 Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted)
9269 << (int)DCK;
9270 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9271 DefaultedComparisonAnalyzer::ExplainDeleted)
9272 .visit();
9273 if (FD->getDefaultLoc().isValid())
9274 Diag(FD->getDefaultLoc(), diag::note_replace_equals_default_to_delete)
9275 << FixItHint::CreateReplacement(FD->getDefaultLoc(), "delete");
9276 }
9277 return false;
9278 }
9279
9280 // C++2a [class.spaceship]p2:
9281 // The return type is deduced as the common comparison type of R0, R1, ...
9285 if (RetLoc.isInvalid())
9286 RetLoc = FD->getBeginLoc();
9287 // FIXME: Should we really care whether we have the complete type and the
9288 // 'enumerator' constants here? A forward declaration seems sufficient.
9290 Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator);
9291 if (Cat.isNull())
9292 return true;
9293 Context.adjustDeducedFunctionResultType(
9294 FD, SubstAutoType(FD->getDeclaredReturnType(), Cat));
9295 }
9296
9297 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
9298 // An explicitly-defaulted function that is not defined as deleted may be
9299 // declared constexpr or consteval only if it is constexpr-compatible.
9300 // C++2a [class.compare.default]p3 [P2002R0]:
9301 // A defaulted comparison function is constexpr-compatible if it satisfies
9302 // the requirements for a constexpr function [...]
9303 // The only relevant requirements are that the parameter and return types are
9304 // literal types. The remaining conditions are checked by the analyzer.
9305 //
9306 // We support P2448R2 in language modes earlier than C++23 as an extension.
9307 // The concept of constexpr-compatible was removed.
9308 // C++23 [dcl.fct.def.default]p3 [P2448R2]
9309 // A function explicitly defaulted on its first declaration is implicitly
9310 // inline, and is implicitly constexpr if it is constexpr-suitable.
9311 // C++23 [dcl.constexpr]p3
9312 // A function is constexpr-suitable if
9313 // - it is not a coroutine, and
9314 // - if the function is a constructor or destructor, its class does not
9315 // have any virtual base classes.
9316 if (FD->isConstexpr()) {
9317 if (!getLangOpts().CPlusPlus23 &&
9320 !Info.Constexpr) {
9321 Diag(FD->getBeginLoc(), diag::err_defaulted_comparison_constexpr_mismatch)
9322 << FD->isImplicit() << (int)DCK << FD->isConsteval();
9323 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9324 DefaultedComparisonAnalyzer::ExplainConstexpr)
9325 .visit();
9326 }
9327 }
9328
9329 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
9330 // If a constexpr-compatible function is explicitly defaulted on its first
9331 // declaration, it is implicitly considered to be constexpr.
9332 // FIXME: Only applying this to the first declaration seems problematic, as
9333 // simple reorderings can affect the meaning of the program.
9334 if (First && !FD->isConstexpr() && Info.Constexpr)
9336
9337 // C++2a [except.spec]p3:
9338 // If a declaration of a function does not have a noexcept-specifier
9339 // [and] is defaulted on its first declaration, [...] the exception
9340 // specification is as specified below
9341 if (FD->getExceptionSpecType() == EST_None) {
9342 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9343 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9345 EPI.ExceptionSpec.SourceDecl = FD;
9346 FD->setType(Context.getFunctionType(FPT->getReturnType(),
9347 FPT->getParamTypes(), EPI));
9348 }
9349
9350 return false;
9351}
9352
9354 FunctionDecl *Spaceship) {
9357 Ctx.PointOfInstantiation = Spaceship->getEndLoc();
9358 Ctx.Entity = Spaceship;
9360
9361 if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship))
9362 EqualEqual->setImplicit();
9363
9365}
9366
9369 assert(FD->isDefaulted() && !FD->isDeleted() &&
9371 if (FD->willHaveBody() || FD->isInvalidDecl())
9372 return;
9373
9375
9376 // Add a context note for diagnostics produced after this point.
9377 Scope.addContextNote(UseLoc);
9378
9379 DefaultedFunctionFPFeaturesRAII RestoreFP(*this, FD);
9380
9381 {
9382 // Build and set up the function body.
9383 // The first parameter has type maybe-ref-to maybe-const T, use that to get
9384 // the type of the class being compared.
9385 auto PT = FD->getParamDecl(0)->getType();
9386 CXXRecordDecl *RD = PT.getNonReferenceType()->getAsCXXRecordDecl();
9387 SourceLocation BodyLoc =
9388 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
9389 StmtResult Body =
9390 DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build();
9391 if (Body.isInvalid()) {
9392 FD->setInvalidDecl();
9393 return;
9394 }
9395 FD->setBody(Body.get());
9396 FD->markUsed(Context);
9397 }
9398
9399 // The exception specification is needed because we are defining the
9400 // function. Note that this will reuse the body we just built.
9402
9404 L->CompletedImplicitDefinition(FD);
9405}
9406
9409 FunctionDecl *FD,
9411 ComputingExceptionSpec CES(S, FD, Loc);
9413
9414 if (FD->isInvalidDecl())
9415 return ExceptSpec;
9416
9417 // The common case is that we just defined the comparison function. In that
9418 // case, just look at whether the body can throw.
9419 if (FD->hasBody()) {
9420 ExceptSpec.CalledStmt(FD->getBody());
9421 } else {
9422 // Otherwise, build a body so we can check it. This should ideally only
9423 // happen when we're not actually marking the function referenced. (This is
9424 // only really important for efficiency: we don't want to build and throw
9425 // away bodies for comparison functions more than we strictly need to.)
9426
9427 // Pretend to synthesize the function body in an unevaluated context.
9428 // Note that we can't actually just go ahead and define the function here:
9429 // we are not permitted to mark its callees as referenced.
9433
9434 CXXRecordDecl *RD =
9436 ? FD->getDeclContext()
9437 : FD->getLexicalDeclContext());
9438 SourceLocation BodyLoc =
9439 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
9440 StmtResult Body =
9441 DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build();
9442 if (!Body.isInvalid())
9443 ExceptSpec.CalledStmt(Body.get());
9444
9445 // FIXME: Can we hold onto this body and just transform it to potentially
9446 // evaluated when we're asked to define the function rather than rebuilding
9447 // it? Either that, or we should only build the bits of the body that we
9448 // need (the expressions, not the statements).
9449 }
9450
9451 return ExceptSpec;
9452}
9453
9455 decltype(DelayedOverridingExceptionSpecChecks) Overriding;
9457
9458 std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
9460
9461 // Perform any deferred checking of exception specifications for virtual
9462 // destructors.
9463 for (auto &Check : Overriding)
9464 CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
9465
9466 // Perform any deferred checking of exception specifications for befriended
9467 // special members.
9468 for (auto &Check : Equivalent)
9469 CheckEquivalentExceptionSpec(Check.second, Check.first);
9470}
9471
9472namespace {
9473/// CRTP base class for visiting operations performed by a special member
9474/// function (or inherited constructor).
9475template<typename Derived>
9476struct SpecialMemberVisitor {
9477 Sema &S;
9478 CXXMethodDecl *MD;
9481
9482 // Properties of the special member, computed for convenience.
9483 bool IsConstructor = false, IsAssignment = false, ConstArg = false;
9484
9485 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, CXXSpecialMemberKind CSM,
9487 : S(S), MD(MD), CSM(CSM), ICI(ICI) {
9488 switch (CSM) {
9492 IsConstructor = true;
9493 break;
9496 IsAssignment = true;
9497 break;
9499 break;
9501 llvm_unreachable("invalid special member kind");
9502 }
9503
9504 if (MD->getNumExplicitParams()) {
9505 if (const ReferenceType *RT =
9506 MD->getNonObjectParameter(0)->getType()->getAs<ReferenceType>())
9507 ConstArg = RT->getPointeeType().isConstQualified();
9508 }
9509 }
9510
9511 Derived &getDerived() { return static_cast<Derived&>(*this); }
9512
9513 /// Is this a "move" special member?
9514 bool isMove() const {
9515 return CSM == CXXSpecialMemberKind::MoveConstructor ||
9516 CSM == CXXSpecialMemberKind::MoveAssignment;
9517 }
9518
9519 /// Look up the corresponding special member in the given class.
9520 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
9521 unsigned Quals, bool IsMutable) {
9522 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
9523 ConstArg && !IsMutable);
9524 }
9525
9526 /// Look up the constructor for the specified base class to see if it's
9527 /// overridden due to this being an inherited constructor.
9528 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
9529 if (!ICI)
9530 return {};
9531 assert(CSM == CXXSpecialMemberKind::DefaultConstructor);
9532 auto *BaseCtor =
9533 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
9534 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
9535 return MD;
9536 return {};
9537 }
9538
9539 /// A base or member subobject.
9540 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
9541
9542 /// Get the location to use for a subobject in diagnostics.
9543 static SourceLocation getSubobjectLoc(Subobject Subobj) {
9544 // FIXME: For an indirect virtual base, the direct base leading to
9545 // the indirect virtual base would be a more useful choice.
9546 if (auto *B = dyn_cast<CXXBaseSpecifier *>(Subobj))
9547 return B->getBaseTypeLoc();
9548 else
9549 return cast<FieldDecl *>(Subobj)->getLocation();
9550 }
9551
9552 enum BasesToVisit {
9553 /// Visit all non-virtual (direct) bases.
9554 VisitNonVirtualBases,
9555 /// Visit all direct bases, virtual or not.
9556 VisitDirectBases,
9557 /// Visit all non-virtual bases, and all virtual bases if the class
9558 /// is not abstract.
9559 VisitPotentiallyConstructedBases,
9560 /// Visit all direct or virtual bases.
9561 VisitAllBases
9562 };
9563
9564 // Visit the bases and members of the class.
9565 bool visit(BasesToVisit Bases) {
9566 CXXRecordDecl *RD = MD->getParent();
9567
9568 if (Bases == VisitPotentiallyConstructedBases)
9569 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
9570
9571 for (auto &B : RD->bases())
9572 if ((Bases == VisitDirectBases || !B.isVirtual()) &&
9573 getDerived().visitBase(&B))
9574 return true;
9575
9576 if (Bases == VisitAllBases)
9577 for (auto &B : RD->vbases())
9578 if (getDerived().visitBase(&B))
9579 return true;
9580
9581 for (auto *F : RD->fields())
9582 if (!F->isInvalidDecl() && !F->isUnnamedBitField() &&
9583 getDerived().visitField(F))
9584 return true;
9585
9586 return false;
9587 }
9588};
9589}
9590
9591namespace {
9592struct SpecialMemberDeletionInfo
9593 : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
9594 bool Diagnose;
9595
9596 SourceLocation Loc;
9597
9598 bool AllFieldsAreConst;
9599
9600 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
9602 Sema::InheritedConstructorInfo *ICI, bool Diagnose)
9603 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
9604 Loc(MD->getLocation()), AllFieldsAreConst(true) {}
9605
9606 bool inUnion() const { return MD->getParent()->isUnion(); }
9607
9608 CXXSpecialMemberKind getEffectiveCSM() {
9609 return ICI ? CXXSpecialMemberKind::Invalid : CSM;
9610 }
9611
9612 bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
9613
9614 bool shouldDeleteForVariantPtrAuthMember(const FieldDecl *FD);
9615
9616 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
9617 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
9618
9619 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
9620 bool shouldDeleteForField(FieldDecl *FD);
9621 bool shouldDeleteForAllConstMembers();
9622
9623 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
9624 unsigned Quals);
9625 bool shouldDeleteForSubobjectCall(Subobject Subobj,
9626 Sema::SpecialMemberOverloadResult SMOR,
9627 bool IsDtorCallInCtor);
9628
9629 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
9630};
9631}
9632
9633/// Is the given special member inaccessible when used on the given
9634/// sub-object.
9635bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
9636 CXXMethodDecl *target) {
9637 /// If we're operating on a base class, the object type is the
9638 /// type of this special member.
9639 CanQualType objectTy;
9640 AccessSpecifier access = target->getAccess();
9641 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
9642 objectTy = S.Context.getCanonicalTagType(MD->getParent());
9643 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
9644
9645 // If we're operating on a field, the object type is the type of the field.
9646 } else {
9647 objectTy = S.Context.getCanonicalTagType(target->getParent());
9648 }
9649
9651 target->getParent(), DeclAccessPair::make(target, access), objectTy);
9652}
9653
9654/// Check whether we should delete a special member due to the implicit
9655/// definition containing a call to a special member of a subobject.
9656bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
9657 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
9658 bool IsDtorCallInCtor) {
9659 CXXMethodDecl *Decl = SMOR.getMethod();
9660 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9661
9662 enum {
9663 NotSet = -1,
9664 NoDecl,
9665 DeletedDecl,
9666 MultipleDecl,
9667 InaccessibleDecl,
9668 NonTrivialDecl
9669 } DiagKind = NotSet;
9670
9672 if (CSM == CXXSpecialMemberKind::DefaultConstructor && Field &&
9673 Field->getParent()->isUnion()) {
9674 // [class.default.ctor]p2:
9675 // A defaulted default constructor for class X is defined as deleted if
9676 // - X is a union that has a variant member with a non-trivial default
9677 // constructor and no variant member of X has a default member
9678 // initializer
9679 const auto *RD = cast<CXXRecordDecl>(Field->getParent());
9680 if (RD->hasInClassInitializer())
9681 return false;
9682 }
9683 DiagKind = !Decl ? NoDecl : DeletedDecl;
9685 DiagKind = MultipleDecl;
9686 else if (!isAccessible(Subobj, Decl))
9687 DiagKind = InaccessibleDecl;
9688 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
9689 !Decl->isTrivial()) {
9690 // A member of a union must have a trivial corresponding special member.
9691 // As a weird special case, a destructor call from a union's constructor
9692 // must be accessible and non-deleted, but need not be trivial. Such a
9693 // destructor is never actually called, but is semantically checked as
9694 // if it were.
9695 if (CSM == CXXSpecialMemberKind::DefaultConstructor) {
9696 // [class.default.ctor]p2:
9697 // A defaulted default constructor for class X is defined as deleted if
9698 // - X is a union that has a variant member with a non-trivial default
9699 // constructor and no variant member of X has a default member
9700 // initializer
9701 const auto *RD = cast<CXXRecordDecl>(Field->getParent());
9702 if (!RD->hasInClassInitializer())
9703 DiagKind = NonTrivialDecl;
9704 } else {
9705 DiagKind = NonTrivialDecl;
9706 }
9707 }
9708
9709 if (DiagKind == NotSet)
9710 return false;
9711
9712 if (Diagnose) {
9713 if (Field) {
9714 S.Diag(Field->getLocation(),
9715 diag::note_deleted_special_member_class_subobject)
9716 << getEffectiveCSM() << MD->getParent() << /*IsField*/ true << Field
9717 << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/ false;
9718 } else {
9719 CXXBaseSpecifier *Base = cast<CXXBaseSpecifier *>(Subobj);
9720 S.Diag(Base->getBeginLoc(),
9721 diag::note_deleted_special_member_class_subobject)
9722 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9723 << Base->getType() << DiagKind << IsDtorCallInCtor
9724 << /*IsObjCPtr*/ false;
9725 }
9726
9727 if (DiagKind == DeletedDecl)
9728 S.NoteDeletedFunction(Decl);
9729 // FIXME: Explain inaccessibility if DiagKind == InaccessibleDecl.
9730 }
9731
9732 return true;
9733}
9734
9735/// Check whether we should delete a special member function due to having a
9736/// direct or virtual base class or non-static data member of class type M.
9737bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
9738 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
9739 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9740 bool IsMutable = Field && Field->isMutable();
9741
9742 // C++11 [class.ctor]p5:
9743 // -- any direct or virtual base class, or non-static data member with no
9744 // brace-or-equal-initializer, has class type M (or array thereof) and
9745 // either M has no default constructor or overload resolution as applied
9746 // to M's default constructor results in an ambiguity or in a function
9747 // that is deleted or inaccessible
9748 // C++11 [class.copy]p11, C++11 [class.copy]p23:
9749 // -- a direct or virtual base class B that cannot be copied/moved because
9750 // overload resolution, as applied to B's corresponding special member,
9751 // results in an ambiguity or a function that is deleted or inaccessible
9752 // from the defaulted special member
9753 // C++11 [class.dtor]p5:
9754 // -- any direct or virtual base class [...] has a type with a destructor
9755 // that is deleted or inaccessible
9756 if (!(CSM == CXXSpecialMemberKind::DefaultConstructor && Field &&
9757 Field->hasInClassInitializer()) &&
9758 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
9759 false))
9760 return true;
9761
9762 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
9763 // -- any direct or virtual base class or non-static data member has a
9764 // type with a destructor that is deleted or inaccessible
9765 if (IsConstructor) {
9766 Sema::SpecialMemberOverloadResult SMOR =
9767 S.LookupSpecialMember(Class, CXXSpecialMemberKind::Destructor, false,
9768 false, false, false, false);
9769 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
9770 return true;
9771 }
9772
9773 return false;
9774}
9775
9776bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
9777 FieldDecl *FD, QualType FieldType) {
9778 // The defaulted special functions are defined as deleted if this is a variant
9779 // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
9780 // type under ARC.
9781 if (!FieldType.hasNonTrivialObjCLifetime())
9782 return false;
9783
9784 // Don't make the defaulted default constructor defined as deleted if the
9785 // member has an in-class initializer.
9786 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
9788 return false;
9789
9790 if (Diagnose) {
9791 auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
9792 S.Diag(FD->getLocation(), diag::note_deleted_special_member_class_subobject)
9793 << getEffectiveCSM() << ParentClass << /*IsField*/ true << FD << 4
9794 << /*IsDtorCallInCtor*/ false << /*IsObjCPtr*/ true;
9795 }
9796
9797 return true;
9798}
9799
9800bool SpecialMemberDeletionInfo::shouldDeleteForVariantPtrAuthMember(
9801 const FieldDecl *FD) {
9802 QualType FieldType = S.Context.getBaseElementType(FD->getType());
9803 // Copy/move constructors/assignment operators are deleted if the field has an
9804 // address-discriminated ptrauth qualifier.
9805 PointerAuthQualifier Q = FieldType.getPointerAuth();
9806
9807 if (!Q || !Q.isAddressDiscriminated())
9808 return false;
9809
9810 if (CSM == CXXSpecialMemberKind::DefaultConstructor ||
9811 CSM == CXXSpecialMemberKind::Destructor)
9812 return false;
9813
9814 if (Diagnose) {
9815 auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
9816 S.Diag(FD->getLocation(), diag::note_deleted_special_member_class_subobject)
9817 << getEffectiveCSM() << ParentClass << /*IsField*/ true << FD << 4
9818 << /*IsDtorCallInCtor*/ false << 2;
9819 }
9820
9821 return true;
9822}
9823
9824/// Check whether we should delete a special member function due to the class
9825/// having a particular direct or virtual base class.
9826bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
9827 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
9828 // If program is correct, BaseClass cannot be null, but if it is, the error
9829 // must be reported elsewhere.
9830 if (!BaseClass)
9831 return false;
9832 // If we have an inheriting constructor, check whether we're calling an
9833 // inherited constructor instead of a default constructor.
9834 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
9835 if (auto *BaseCtor = SMOR.getMethod()) {
9836 // Note that we do not check access along this path; other than that,
9837 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
9838 // FIXME: Check that the base has a usable destructor! Sink this into
9839 // shouldDeleteForClassSubobject.
9840 if (BaseCtor->isDeleted() && Diagnose) {
9841 S.Diag(Base->getBeginLoc(),
9842 diag::note_deleted_special_member_class_subobject)
9843 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9844 << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
9845 << /*IsObjCPtr*/ false;
9846 S.NoteDeletedFunction(BaseCtor);
9847 }
9848 return BaseCtor->isDeleted();
9849 }
9850 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
9851}
9852
9853/// Check whether we should delete a special member function due to the class
9854/// having a particular non-static data member.
9855bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
9856 QualType FieldType = S.Context.getBaseElementType(FD->getType());
9857 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
9858
9859 if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
9860 return true;
9861
9862 if (inUnion() && shouldDeleteForVariantPtrAuthMember(FD))
9863 return true;
9864
9865 if (CSM == CXXSpecialMemberKind::DefaultConstructor) {
9866 // For a default constructor, all references must be initialized in-class
9867 // and, if a union, it must have a non-const member.
9868 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
9869 if (Diagnose)
9870 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9871 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
9872 return true;
9873 }
9874 // C++11 [class.ctor]p5 (modified by DR2394): any non-variant non-static
9875 // data member of const-qualified type (or array thereof) with no
9876 // brace-or-equal-initializer is not const-default-constructible.
9877 if (!inUnion() && FieldType.isConstQualified() &&
9878 !FD->hasInClassInitializer() &&
9879 (!FieldRecord || !FieldRecord->allowConstDefaultInit())) {
9880 if (Diagnose)
9881 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9882 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
9883 return true;
9884 }
9885
9886 if (inUnion() && !FieldType.isConstQualified())
9887 AllFieldsAreConst = false;
9888 } else if (CSM == CXXSpecialMemberKind::CopyConstructor) {
9889 // For a copy constructor, data members must not be of rvalue reference
9890 // type.
9891 if (FieldType->isRValueReferenceType()) {
9892 if (Diagnose)
9893 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
9894 << MD->getParent() << FD << FieldType;
9895 return true;
9896 }
9897 } else if (IsAssignment) {
9898 // For an assignment operator, data members must not be of reference type.
9899 if (FieldType->isReferenceType()) {
9900 if (Diagnose)
9901 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9902 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
9903 return true;
9904 }
9905 if (!FieldRecord && FieldType.isConstQualified()) {
9906 // C++11 [class.copy]p23:
9907 // -- a non-static data member of const non-class type (or array thereof)
9908 if (Diagnose)
9909 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9910 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
9911 return true;
9912 }
9913 }
9914
9915 if (FieldRecord) {
9916 // Some additional restrictions exist on the variant members.
9917 if (!inUnion() && FieldRecord->isUnion() &&
9918 FieldRecord->isAnonymousStructOrUnion()) {
9919 bool AllVariantFieldsAreConst = true;
9920
9921 // FIXME: Handle anonymous unions declared within anonymous unions.
9922 for (auto *UI : FieldRecord->fields()) {
9923 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
9924
9925 if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
9926 return true;
9927
9928 if (shouldDeleteForVariantPtrAuthMember(&*UI))
9929 return true;
9930
9931 if (!UnionFieldType.isConstQualified())
9932 AllVariantFieldsAreConst = false;
9933
9934 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
9935 if (UnionFieldRecord &&
9936 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
9937 UnionFieldType.getCVRQualifiers()))
9938 return true;
9939 }
9940
9941 // At least one member in each anonymous union must be non-const
9942 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
9943 AllVariantFieldsAreConst && !FieldRecord->field_empty()) {
9944 if (Diagnose)
9945 S.Diag(FieldRecord->getLocation(),
9946 diag::note_deleted_default_ctor_all_const)
9947 << !!ICI << MD->getParent() << /*anonymous union*/1;
9948 return true;
9949 }
9950
9951 // Don't check the implicit member of the anonymous union type.
9952 // This is technically non-conformant but supported, and we have a
9953 // diagnostic for this elsewhere.
9954 return false;
9955 }
9956
9957 if (shouldDeleteForClassSubobject(FieldRecord, FD,
9958 FieldType.getCVRQualifiers()))
9959 return true;
9960 }
9961
9962 return false;
9963}
9964
9965/// C++11 [class.ctor] p5:
9966/// A defaulted default constructor for a class X is defined as deleted if
9967/// X is a union and all of its variant members are of const-qualified type.
9968bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
9969 // This is a silly definition, because it gives an empty union a deleted
9970 // default constructor. Don't do that.
9971 if (CSM == CXXSpecialMemberKind::DefaultConstructor && inUnion() &&
9972 AllFieldsAreConst) {
9973 bool AnyFields = false;
9974 for (auto *F : MD->getParent()->fields())
9975 if ((AnyFields = !F->isUnnamedBitField()))
9976 break;
9977 if (!AnyFields)
9978 return false;
9979 if (Diagnose)
9980 S.Diag(MD->getParent()->getLocation(),
9981 diag::note_deleted_default_ctor_all_const)
9982 << !!ICI << MD->getParent() << /*not anonymous union*/0;
9983 return true;
9984 }
9985 return false;
9986}
9987
9988/// Determine whether a defaulted special member function should be defined as
9989/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
9990/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
9994 bool Diagnose) {
9995 if (MD->isInvalidDecl())
9996 return false;
9997 CXXRecordDecl *RD = MD->getParent();
9998 assert(!RD->isDependentType() && "do deletion after instantiation");
9999 if (!LangOpts.CPlusPlus || (!LangOpts.CPlusPlus11 && !RD->isLambda()) ||
10000 RD->isInvalidDecl())
10001 return false;
10002
10003 // C++11 [expr.lambda.prim]p19:
10004 // The closure type associated with a lambda-expression has a
10005 // deleted (8.4.3) default constructor and a deleted copy
10006 // assignment operator.
10007 // C++2a adds back these operators if the lambda has no lambda-capture.
10011 if (Diagnose)
10012 Diag(RD->getLocation(), diag::note_lambda_decl);
10013 return true;
10014 }
10015
10016 // C++11 [class.copy]p7, p18:
10017 // If the class definition declares a move constructor or move assignment
10018 // operator, an implicitly declared copy constructor or copy assignment
10019 // operator is defined as deleted.
10022 CXXMethodDecl *UserDeclaredMove = nullptr;
10023
10024 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
10025 // deletion of the corresponding copy operation, not both copy operations.
10026 // MSVC 2015 has adopted the standards conforming behavior.
10027 bool DeletesOnlyMatchingCopy =
10028 getLangOpts().MSVCCompat &&
10029 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
10030
10032 (!DeletesOnlyMatchingCopy ||
10034 if (!Diagnose) return true;
10035
10036 // Find any user-declared move constructor.
10037 for (auto *I : RD->ctors()) {
10038 if (I->isMoveConstructor()) {
10039 UserDeclaredMove = I;
10040 break;
10041 }
10042 }
10043 assert(UserDeclaredMove);
10044 } else if (RD->hasUserDeclaredMoveAssignment() &&
10045 (!DeletesOnlyMatchingCopy ||
10047 if (!Diagnose) return true;
10048
10049 // Find any user-declared move assignment operator.
10050 for (auto *I : RD->methods()) {
10051 if (I->isMoveAssignmentOperator()) {
10052 UserDeclaredMove = I;
10053 break;
10054 }
10055 }
10056 assert(UserDeclaredMove);
10057 }
10058
10059 if (UserDeclaredMove) {
10060 Diag(UserDeclaredMove->getLocation(),
10061 diag::note_deleted_copy_user_declared_move)
10062 << (CSM == CXXSpecialMemberKind::CopyAssignment) << RD
10063 << UserDeclaredMove->isMoveAssignmentOperator();
10064 return true;
10065 }
10066 }
10067
10068 // Do access control from the special member function
10069 ContextRAII MethodContext(*this, MD);
10070
10071 // C++11 [class.dtor]p5:
10072 // -- for a virtual destructor, lookup of the non-array deallocation function
10073 // results in an ambiguity or in a function that is deleted or inaccessible
10074 if (CSM == CXXSpecialMemberKind::Destructor && MD->isVirtual()) {
10075 FunctionDecl *OperatorDelete = nullptr;
10076 CanQualType DeallocType = Context.getCanonicalTagType(RD);
10077 DeclarationName Name =
10078 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
10082 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
10083 OperatorDelete, IDP,
10084 /*Diagnose=*/false)) {
10085 if (Diagnose)
10086 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
10087 return true;
10088 }
10089 }
10090
10091 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
10092
10093 // Per DR1611, do not consider virtual bases of constructors of abstract
10094 // classes, since we are not going to construct them.
10095 // Per DR1658, do not consider virtual bases of destructors of abstract
10096 // classes either.
10097 // Per DR2180, for assignment operators we only assign (and thus only
10098 // consider) direct bases.
10099 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
10100 : SMI.VisitPotentiallyConstructedBases))
10101 return true;
10102
10103 if (SMI.shouldDeleteForAllConstMembers())
10104 return true;
10105
10106 if (getLangOpts().CUDA) {
10107 // We should delete the special member in CUDA mode if target inference
10108 // failed.
10109 // For inherited constructors (non-null ICI), CSM may be passed so that MD
10110 // is treated as certain special member, which may not reflect what special
10111 // member MD really is. However inferTargetForImplicitSpecialMember
10112 // expects CSM to match MD, therefore recalculate CSM.
10113 assert(ICI || CSM == MD->getSpecialMemberKind());
10114 auto RealCSM = CSM;
10115 if (ICI)
10116 RealCSM = MD->getSpecialMemberKind();
10117
10118 return CUDA().inferTargetForImplicitSpecialMember(RD, RealCSM, MD,
10119 SMI.ConstArg, Diagnose);
10120 }
10121
10122 return false;
10123}
10124
10127 assert(DFK && "not a defaultable function");
10128 assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted");
10129
10130 if (DFK.isSpecialMember()) {
10132 nullptr, /*Diagnose=*/true);
10133 } else {
10134 DefaultedComparisonAnalyzer(
10136 DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted)
10137 .visit();
10138 }
10139}
10140
10141/// Perform lookup for a special member of the specified kind, and determine
10142/// whether it is trivial. If the triviality can be determined without the
10143/// lookup, skip it. This is intended for use when determining whether a
10144/// special member of a containing object is trivial, and thus does not ever
10145/// perform overload resolution for default constructors.
10146///
10147/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
10148/// member that was most likely to be intended to be trivial, if any.
10149///
10150/// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
10151/// determine whether the special member is trivial.
10153 CXXSpecialMemberKind CSM, unsigned Quals,
10154 bool ConstRHS, TrivialABIHandling TAH,
10155 CXXMethodDecl **Selected) {
10156 if (Selected)
10157 *Selected = nullptr;
10158
10159 switch (CSM) {
10161 llvm_unreachable("not a special member");
10162
10164 // C++11 [class.ctor]p5:
10165 // A default constructor is trivial if:
10166 // - all the [direct subobjects] have trivial default constructors
10167 //
10168 // Note, no overload resolution is performed in this case.
10170 return true;
10171
10172 if (Selected) {
10173 // If there's a default constructor which could have been trivial, dig it
10174 // out. Otherwise, if there's any user-provided default constructor, point
10175 // to that as an example of why there's not a trivial one.
10176 CXXConstructorDecl *DefCtor = nullptr;
10179 for (auto *CI : RD->ctors()) {
10180 if (!CI->isDefaultConstructor())
10181 continue;
10182 DefCtor = CI;
10183 if (!DefCtor->isUserProvided())
10184 break;
10185 }
10186
10187 *Selected = DefCtor;
10188 }
10189
10190 return false;
10191
10193 // C++11 [class.dtor]p5:
10194 // A destructor is trivial if:
10195 // - all the direct [subobjects] have trivial destructors
10196 if (RD->hasTrivialDestructor() ||
10199 return true;
10200
10201 if (Selected) {
10202 if (RD->needsImplicitDestructor())
10204 *Selected = RD->getDestructor();
10205 }
10206
10207 return false;
10208
10210 // C++11 [class.copy]p12:
10211 // A copy constructor is trivial if:
10212 // - the constructor selected to copy each direct [subobject] is trivial
10213 if (RD->hasTrivialCopyConstructor() ||
10216 if (Quals == Qualifiers::Const)
10217 // We must either select the trivial copy constructor or reach an
10218 // ambiguity; no need to actually perform overload resolution.
10219 return true;
10220 } else if (!Selected) {
10221 return false;
10222 }
10223 // In C++98, we are not supposed to perform overload resolution here, but we
10224 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
10225 // cases like B as having a non-trivial copy constructor:
10226 // struct A { template<typename T> A(T&); };
10227 // struct B { mutable A a; };
10228 goto NeedOverloadResolution;
10229
10231 // C++11 [class.copy]p25:
10232 // A copy assignment operator is trivial if:
10233 // - the assignment operator selected to copy each direct [subobject] is
10234 // trivial
10235 if (RD->hasTrivialCopyAssignment()) {
10236 if (Quals == Qualifiers::Const)
10237 return true;
10238 } else if (!Selected) {
10239 return false;
10240 }
10241 // In C++98, we are not supposed to perform overload resolution here, but we
10242 // treat that as a language defect.
10243 goto NeedOverloadResolution;
10244
10247 NeedOverloadResolution:
10249 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
10250
10251 // The standard doesn't describe how to behave if the lookup is ambiguous.
10252 // We treat it as not making the member non-trivial, just like the standard
10253 // mandates for the default constructor. This should rarely matter, because
10254 // the member will also be deleted.
10256 return true;
10257
10258 if (!SMOR.getMethod()) {
10259 assert(SMOR.getKind() ==
10261 return false;
10262 }
10263
10264 // We deliberately don't check if we found a deleted special member. We're
10265 // not supposed to!
10266 if (Selected)
10267 *Selected = SMOR.getMethod();
10268
10272 return SMOR.getMethod()->isTrivialForCall();
10273 return SMOR.getMethod()->isTrivial();
10274 }
10275
10276 llvm_unreachable("unknown special method kind");
10277}
10278
10280 for (auto *CI : RD->ctors())
10281 if (!CI->isImplicit())
10282 return CI;
10283
10284 // Look for constructor templates.
10286 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
10287 if (CXXConstructorDecl *CD =
10288 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
10289 return CD;
10290 }
10291
10292 return nullptr;
10293}
10294
10295/// The kind of subobject we are checking for triviality. The values of this
10296/// enumeration are used in diagnostics.
10298 /// The subobject is a base class.
10300 /// The subobject is a non-static data member.
10302 /// The object is actually the complete object.
10304};
10305
10306/// Check whether the special member selected for a given type would be trivial.
10308 QualType SubType, bool ConstRHS,
10311 TrivialABIHandling TAH, bool Diagnose) {
10312 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
10313 if (!SubRD)
10314 return true;
10315
10316 CXXMethodDecl *Selected;
10317 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
10318 ConstRHS, TAH, Diagnose ? &Selected : nullptr))
10319 return true;
10320
10321 if (Diagnose) {
10322 if (ConstRHS)
10323 SubType.addConst();
10324
10325 if (!Selected && CSM == CXXSpecialMemberKind::DefaultConstructor) {
10326 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
10327 << Kind << SubType.getUnqualifiedType();
10329 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
10330 } else if (!Selected)
10331 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
10332 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
10333 else if (Selected->isUserProvided()) {
10334 if (Kind == TSK_CompleteObject)
10335 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
10336 << Kind << SubType.getUnqualifiedType() << CSM;
10337 else {
10338 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
10339 << Kind << SubType.getUnqualifiedType() << CSM;
10340 S.Diag(Selected->getLocation(), diag::note_declared_at);
10341 }
10342 } else {
10343 if (Kind != TSK_CompleteObject)
10344 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
10345 << Kind << SubType.getUnqualifiedType() << CSM;
10346
10347 // Explain why the defaulted or deleted special member isn't trivial.
10348 S.SpecialMemberIsTrivial(Selected, CSM,
10350 }
10351 }
10352
10353 return false;
10354}
10355
10356/// Check whether the members of a class type allow a special member to be
10357/// trivial.
10359 CXXSpecialMemberKind CSM, bool ConstArg,
10360 TrivialABIHandling TAH, bool Diagnose) {
10361 for (const auto *FI : RD->fields()) {
10362 if (FI->isInvalidDecl() || FI->isUnnamedBitField())
10363 continue;
10364
10365 QualType FieldType = S.Context.getBaseElementType(FI->getType());
10366
10367 // Pretend anonymous struct or union members are members of this class.
10368 if (FI->isAnonymousStructOrUnion()) {
10369 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
10370 CSM, ConstArg, TAH, Diagnose))
10371 return false;
10372 continue;
10373 }
10374
10375 // C++11 [class.ctor]p5:
10376 // A default constructor is trivial if [...]
10377 // -- no non-static data member of its class has a
10378 // brace-or-equal-initializer
10380 FI->hasInClassInitializer()) {
10381 if (Diagnose)
10382 S.Diag(FI->getLocation(), diag::note_nontrivial_default_member_init)
10383 << FI;
10384 return false;
10385 }
10386
10387 // Objective C ARC 4.3.5:
10388 // [...] nontrivally ownership-qualified types are [...] not trivially
10389 // default constructible, copy constructible, move constructible, copy
10390 // assignable, move assignable, or destructible [...]
10391 if (FieldType.hasNonTrivialObjCLifetime()) {
10392 if (Diagnose)
10393 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
10394 << RD << FieldType.getObjCLifetime();
10395 return false;
10396 }
10397
10398 bool ConstRHS = ConstArg && !FI->isMutable();
10399 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
10400 CSM, TSK_Field, TAH, Diagnose))
10401 return false;
10402 }
10403
10404 return true;
10405}
10406
10409 CanQualType Ty = Context.getCanonicalTagType(RD);
10410
10411 bool ConstArg = (CSM == CXXSpecialMemberKind::CopyConstructor ||
10413 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
10416 /*Diagnose*/ true);
10417}
10418
10420 TrivialABIHandling TAH, bool Diagnose) {
10421 assert(!MD->isUserProvided() && CSM != CXXSpecialMemberKind::Invalid &&
10422 "not special enough");
10423
10424 CXXRecordDecl *RD = MD->getParent();
10425
10426 bool ConstArg = false;
10427
10428 // C++11 [class.copy]p12, p25: [DR1593]
10429 // A [special member] is trivial if [...] its parameter-type-list is
10430 // equivalent to the parameter-type-list of an implicit declaration [...]
10431 switch (CSM) {
10434 // Trivial default constructors and destructors cannot have parameters.
10435 break;
10436
10439 const ParmVarDecl *Param0 = MD->getNonObjectParameter(0);
10440 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
10441
10442 // When ClangABICompat14 is true, CXX copy constructors will only be trivial
10443 // if they are not user-provided and their parameter-type-list is equivalent
10444 // to the parameter-type-list of an implicit declaration. This maintains the
10445 // behavior before dr2171 was implemented.
10446 //
10447 // Otherwise, if ClangABICompat14 is false, All copy constructors can be
10448 // trivial, if they are not user-provided, regardless of the qualifiers on
10449 // the reference type.
10450 const bool ClangABICompat14 =
10451 Context.getLangOpts().isCompatibleWith(LangOptions::ClangABI::Ver14);
10452 if (!RT ||
10454 ClangABICompat14)) {
10455 if (Diagnose)
10456 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
10457 << Param0->getSourceRange() << Param0->getType()
10458 << Context.getLValueReferenceType(
10459 Context.getCanonicalTagType(RD).withConst());
10460 return false;
10461 }
10462
10463 ConstArg = RT->getPointeeType().isConstQualified();
10464 break;
10465 }
10466
10469 // Trivial move operations always have non-cv-qualified parameters.
10470 const ParmVarDecl *Param0 = MD->getNonObjectParameter(0);
10471 const RValueReferenceType *RT =
10472 Param0->getType()->getAs<RValueReferenceType>();
10473 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
10474 if (Diagnose)
10475 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
10476 << Param0->getSourceRange() << Param0->getType()
10477 << Context.getRValueReferenceType(Context.getCanonicalTagType(RD));
10478 return false;
10479 }
10480 break;
10481 }
10482
10484 llvm_unreachable("not a special member");
10485 }
10486
10487 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
10488 if (Diagnose)
10490 diag::note_nontrivial_default_arg)
10492 return false;
10493 }
10494 if (MD->isVariadic()) {
10495 if (Diagnose)
10496 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
10497 return false;
10498 }
10499
10500 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
10501 // A copy/move [constructor or assignment operator] is trivial if
10502 // -- the [member] selected to copy/move each direct base class subobject
10503 // is trivial
10504 //
10505 // C++11 [class.copy]p12, C++11 [class.copy]p25:
10506 // A [default constructor or destructor] is trivial if
10507 // -- all the direct base classes have trivial [default constructors or
10508 // destructors]
10509 for (const auto &BI : RD->bases())
10510 if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
10511 ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
10512 return false;
10513
10514 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
10515 // A copy/move [constructor or assignment operator] for a class X is
10516 // trivial if
10517 // -- for each non-static data member of X that is of class type (or array
10518 // thereof), the constructor selected to copy/move that member is
10519 // trivial
10520 //
10521 // C++11 [class.copy]p12, C++11 [class.copy]p25:
10522 // A [default constructor or destructor] is trivial if
10523 // -- for all of the non-static data members of its class that are of class
10524 // type (or array thereof), each such class has a trivial [default
10525 // constructor or destructor]
10526 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
10527 return false;
10528
10529 // C++11 [class.dtor]p5:
10530 // A destructor is trivial if [...]
10531 // -- the destructor is not virtual
10532 if (CSM == CXXSpecialMemberKind::Destructor && MD->isVirtual()) {
10533 if (Diagnose)
10534 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
10535 return false;
10536 }
10537
10538 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
10539 // A [special member] for class X is trivial if [...]
10540 // -- class X has no virtual functions and no virtual base classes
10542 MD->getParent()->isDynamicClass()) {
10543 if (!Diagnose)
10544 return false;
10545
10546 if (RD->getNumVBases()) {
10547 // Check for virtual bases. We already know that the corresponding
10548 // member in all bases is trivial, so vbases must all be direct.
10549 CXXBaseSpecifier &BS = *RD->vbases_begin();
10550 assert(BS.isVirtual());
10551 Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
10552 return false;
10553 }
10554
10555 // Must have a virtual method.
10556 for (const auto *MI : RD->methods()) {
10557 if (MI->isVirtual()) {
10558 SourceLocation MLoc = MI->getBeginLoc();
10559 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
10560 return false;
10561 }
10562 }
10563
10564 llvm_unreachable("dynamic class with no vbases and no virtual functions");
10565 }
10566
10567 // Looks like it's trivial!
10568 return true;
10569}
10570
10571namespace {
10572struct FindHiddenVirtualMethod {
10573 Sema *S;
10575 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
10576 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10577
10578private:
10579 /// Check whether any most overridden method from MD in Methods
10580 static bool CheckMostOverridenMethods(
10581 const CXXMethodDecl *MD,
10582 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
10583 if (MD->size_overridden_methods() == 0)
10584 return Methods.count(MD->getCanonicalDecl());
10585 for (const CXXMethodDecl *O : MD->overridden_methods())
10586 if (CheckMostOverridenMethods(O, Methods))
10587 return true;
10588 return false;
10589 }
10590
10591public:
10592 /// Member lookup function that determines whether a given C++
10593 /// method overloads virtual methods in a base class without overriding any,
10594 /// to be used with CXXRecordDecl::lookupInBases().
10595 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
10596 auto *BaseRecord = Specifier->getType()->castAsRecordDecl();
10597 DeclarationName Name = Method->getDeclName();
10598 assert(Name.getNameKind() == DeclarationName::Identifier);
10599
10600 bool foundSameNameMethod = false;
10601 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
10602 for (Path.Decls = BaseRecord->lookup(Name).begin();
10603 Path.Decls != DeclContext::lookup_iterator(); ++Path.Decls) {
10604 NamedDecl *D = *Path.Decls;
10605 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
10606 MD = MD->getCanonicalDecl();
10607 foundSameNameMethod = true;
10608 // Interested only in hidden virtual methods.
10609 if (!MD->isVirtual())
10610 continue;
10611 // If the method we are checking overrides a method from its base
10612 // don't warn about the other overloaded methods. Clang deviates from
10613 // GCC by only diagnosing overloads of inherited virtual functions that
10614 // do not override any other virtual functions in the base. GCC's
10615 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
10616 // function from a base class. These cases may be better served by a
10617 // warning (not specific to virtual functions) on call sites when the
10618 // call would select a different function from the base class, were it
10619 // visible.
10620 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
10621 if (!S->IsOverload(Method, MD, false))
10622 return true;
10623 // Collect the overload only if its hidden.
10624 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
10625 overloadedMethods.push_back(MD);
10626 }
10627 }
10628
10629 if (foundSameNameMethod)
10630 OverloadedMethods.append(overloadedMethods.begin(),
10631 overloadedMethods.end());
10632 return foundSameNameMethod;
10633 }
10634};
10635} // end anonymous namespace
10636
10637/// Add the most overridden methods from MD to Methods
10639 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
10640 if (MD->size_overridden_methods() == 0)
10641 Methods.insert(MD->getCanonicalDecl());
10642 else
10643 for (const CXXMethodDecl *O : MD->overridden_methods())
10644 AddMostOverridenMethods(O, Methods);
10645}
10646
10648 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10649 if (!MD->getDeclName().isIdentifier())
10650 return;
10651
10652 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
10653 /*bool RecordPaths=*/false,
10654 /*bool DetectVirtual=*/false);
10655 FindHiddenVirtualMethod FHVM;
10656 FHVM.Method = MD;
10657 FHVM.S = this;
10658
10659 // Keep the base methods that were overridden or introduced in the subclass
10660 // by 'using' in a set. A base method not in this set is hidden.
10661 CXXRecordDecl *DC = MD->getParent();
10662 for (NamedDecl *ND : DC->lookup(MD->getDeclName())) {
10663 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(ND))
10664 ND = shad->getTargetDecl();
10665 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
10666 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
10667 }
10668
10669 if (DC->lookupInBases(FHVM, Paths))
10670 OverloadedMethods = FHVM.OverloadedMethods;
10671}
10672
10674 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10675 for (const CXXMethodDecl *overloadedMD : OverloadedMethods) {
10677 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
10678 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
10679 Diag(overloadedMD->getLocation(), PD);
10680 }
10681}
10682
10684 if (MD->isInvalidDecl())
10685 return;
10686
10687 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
10688 return;
10689
10690 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10691 FindHiddenVirtualMethods(MD, OverloadedMethods);
10692 if (!OverloadedMethods.empty()) {
10693 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
10694 << MD << (OverloadedMethods.size() > 1);
10695
10696 NoteHiddenVirtualMethods(MD, OverloadedMethods);
10697 }
10698}
10699
10701 auto PrintDiagAndRemoveAttr = [&](unsigned N) {
10702 // No diagnostics if this is a template instantiation.
10704 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
10705 diag::ext_cannot_use_trivial_abi) << &RD;
10706 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
10707 diag::note_cannot_use_trivial_abi_reason) << &RD << N;
10708 }
10709 RD.dropAttr<TrivialABIAttr>();
10710 };
10711
10712 // Ill-formed if the struct has virtual functions.
10713 if (RD.isPolymorphic()) {
10714 PrintDiagAndRemoveAttr(1);
10715 return;
10716 }
10717
10718 for (const auto &B : RD.bases()) {
10719 // Ill-formed if the base class is non-trivial for the purpose of calls or a
10720 // virtual base.
10721 if (!B.getType()->isDependentType() &&
10722 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) {
10723 PrintDiagAndRemoveAttr(2);
10724 return;
10725 }
10726
10727 if (B.isVirtual()) {
10728 PrintDiagAndRemoveAttr(3);
10729 return;
10730 }
10731 }
10732
10733 for (const auto *FD : RD.fields()) {
10734 // Ill-formed if the field is an ObjectiveC pointer or of a type that is
10735 // non-trivial for the purpose of calls.
10736 QualType FT = FD->getType();
10738 PrintDiagAndRemoveAttr(4);
10739 return;
10740 }
10741
10742 // Ill-formed if the field is an address-discriminated value.
10744 PrintDiagAndRemoveAttr(6);
10745 return;
10746 }
10747
10748 if (const auto *RT =
10749 FT->getBaseElementTypeUnsafe()->getAsCanonical<RecordType>())
10750 if (!RT->isDependentType() &&
10751 !cast<CXXRecordDecl>(RT->getDecl()->getDefinitionOrSelf())
10752 ->canPassInRegisters()) {
10753 PrintDiagAndRemoveAttr(5);
10754 return;
10755 }
10756 }
10757
10759 return;
10760
10761 // Ill-formed if the copy and move constructors are deleted.
10762 auto HasNonDeletedCopyOrMoveConstructor = [&]() {
10763 // If the type is dependent, then assume it might have
10764 // implicit copy or move ctor because we won't know yet at this point.
10765 if (RD.isDependentType())
10766 return true;
10769 return true;
10772 return true;
10773 for (const CXXConstructorDecl *CD : RD.ctors())
10774 if (CD->isCopyOrMoveConstructor() && !CD->isDeleted())
10775 return true;
10776 return false;
10777 };
10778
10779 if (!HasNonDeletedCopyOrMoveConstructor()) {
10780 PrintDiagAndRemoveAttr(0);
10781 return;
10782 }
10783}
10784
10786 CXXRecordDecl &RD) {
10787 if (RequireCompleteType(RD.getLocation(), Context.getCanonicalTagType(&RD),
10788 diag::err_incomplete_type_vtable_pointer_auth))
10789 return;
10790
10791 const CXXRecordDecl *PrimaryBase = &RD;
10792 if (PrimaryBase->hasAnyDependentBases())
10793 return;
10794
10795 while (1) {
10796 assert(PrimaryBase);
10797 const CXXRecordDecl *Base = nullptr;
10798 for (const CXXBaseSpecifier &BasePtr : PrimaryBase->bases()) {
10799 if (!BasePtr.getType()->getAsCXXRecordDecl()->isDynamicClass())
10800 continue;
10801 Base = BasePtr.getType()->getAsCXXRecordDecl();
10802 break;
10803 }
10804 if (!Base || Base == PrimaryBase || !Base->isPolymorphic())
10805 break;
10806 Diag(RD.getAttr<VTablePointerAuthenticationAttr>()->getLocation(),
10807 diag::err_non_top_level_vtable_pointer_auth)
10808 << &RD << Base;
10809 PrimaryBase = Base;
10810 }
10811
10812 if (!RD.isPolymorphic())
10813 Diag(RD.getAttr<VTablePointerAuthenticationAttr>()->getLocation(),
10814 diag::err_non_polymorphic_vtable_pointer_auth)
10815 << &RD;
10816}
10817
10820 SourceLocation RBrac, const ParsedAttributesView &AttrList) {
10821 if (!TagDecl)
10822 return;
10823
10825
10826 for (const ParsedAttr &AL : AttrList) {
10827 if (AL.getKind() != ParsedAttr::AT_Visibility)
10828 continue;
10829 AL.setInvalid();
10830 Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL;
10831 }
10832
10833 ActOnFields(S, RLoc, TagDecl,
10835 // strict aliasing violation!
10836 reinterpret_cast<Decl **>(FieldCollector->getCurFields()),
10837 FieldCollector->getCurNumFields()),
10838 LBrac, RBrac, AttrList);
10839
10841}
10842
10843/// Find the equality comparison functions that should be implicitly declared
10844/// in a given class definition, per C++2a [class.compare.default]p3.
10846 ASTContext &Ctx, CXXRecordDecl *RD,
10848 DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual);
10849 if (!RD->lookup(EqEq).empty())
10850 // Member operator== explicitly declared: no implicit operator==s.
10851 return;
10852
10853 // Traverse friends looking for an '==' or a '<=>'.
10854 for (FriendDecl *Friend : RD->friends()) {
10855 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl());
10856 if (!FD) continue;
10857
10858 if (FD->getOverloadedOperator() == OO_EqualEqual) {
10859 // Friend operator== explicitly declared: no implicit operator==s.
10860 Spaceships.clear();
10861 return;
10862 }
10863
10864 if (FD->getOverloadedOperator() == OO_Spaceship &&
10866 Spaceships.push_back(FD);
10867 }
10868
10869 // Look for members named 'operator<=>'.
10871 for (NamedDecl *ND : RD->lookup(Cmp)) {
10872 // Note that we could find a non-function here (either a function template
10873 // or a using-declaration). Neither case results in an implicit
10874 // 'operator=='.
10875 if (auto *FD = dyn_cast<FunctionDecl>(ND))
10876 if (FD->isExplicitlyDefaulted())
10877 Spaceships.push_back(FD);
10878 }
10879}
10880
10882 // Don't add implicit special members to templated classes.
10883 // FIXME: This means unqualified lookups for 'operator=' within a class
10884 // template don't work properly.
10885 if (!ClassDecl->isDependentType()) {
10886 if (ClassDecl->needsImplicitDefaultConstructor()) {
10887 ++getASTContext().NumImplicitDefaultConstructors;
10888
10889 if (ClassDecl->hasInheritedConstructor())
10891 }
10892
10893 if (ClassDecl->needsImplicitCopyConstructor()) {
10894 ++getASTContext().NumImplicitCopyConstructors;
10895
10896 // If the properties or semantics of the copy constructor couldn't be
10897 // determined while the class was being declared, force a declaration
10898 // of it now.
10900 ClassDecl->hasInheritedConstructor())
10902 // For the MS ABI we need to know whether the copy ctor is deleted. A
10903 // prerequisite for deleting the implicit copy ctor is that the class has
10904 // a move ctor or move assignment that is either user-declared or whose
10905 // semantics are inherited from a subobject. FIXME: We should provide a
10906 // more direct way for CodeGen to ask whether the constructor was deleted.
10907 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
10908 (ClassDecl->hasUserDeclaredMoveConstructor() ||
10910 ClassDecl->hasUserDeclaredMoveAssignment() ||
10913 }
10914
10915 if (getLangOpts().CPlusPlus11 &&
10916 ClassDecl->needsImplicitMoveConstructor()) {
10917 ++getASTContext().NumImplicitMoveConstructors;
10918
10920 ClassDecl->hasInheritedConstructor())
10922 }
10923
10924 if (ClassDecl->needsImplicitCopyAssignment()) {
10925 ++getASTContext().NumImplicitCopyAssignmentOperators;
10926
10927 // If we have a dynamic class, then the copy assignment operator may be
10928 // virtual, so we have to declare it immediately. This ensures that, e.g.,
10929 // it shows up in the right place in the vtable and that we diagnose
10930 // problems with the implicit exception specification.
10931 if (ClassDecl->isDynamicClass() ||
10933 ClassDecl->hasInheritedAssignment())
10935 }
10936
10937 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
10938 ++getASTContext().NumImplicitMoveAssignmentOperators;
10939
10940 // Likewise for the move assignment operator.
10941 if (ClassDecl->isDynamicClass() ||
10943 ClassDecl->hasInheritedAssignment())
10945 }
10946
10947 if (ClassDecl->needsImplicitDestructor()) {
10948 ++getASTContext().NumImplicitDestructors;
10949
10950 // If we have a dynamic class, then the destructor may be virtual, so we
10951 // have to declare the destructor immediately. This ensures that, e.g., it
10952 // shows up in the right place in the vtable and that we diagnose problems
10953 // with the implicit exception specification.
10954 if (ClassDecl->isDynamicClass() ||
10956 DeclareImplicitDestructor(ClassDecl);
10957 }
10958 }
10959
10960 // C++2a [class.compare.default]p3:
10961 // If the member-specification does not explicitly declare any member or
10962 // friend named operator==, an == operator function is declared implicitly
10963 // for each defaulted three-way comparison operator function defined in
10964 // the member-specification
10965 // FIXME: Consider doing this lazily.
10966 // We do this during the initial parse for a class template, not during
10967 // instantiation, so that we can handle unqualified lookups for 'operator=='
10968 // when parsing the template.
10970 llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships;
10972 DefaultedSpaceships);
10973 for (auto *FD : DefaultedSpaceships)
10974 DeclareImplicitEqualityComparison(ClassDecl, FD);
10975 }
10976}
10977
10978unsigned
10980 llvm::function_ref<Scope *()> EnterScope) {
10981 if (!D)
10982 return 0;
10984
10985 // In order to get name lookup right, reenter template scopes in order from
10986 // outermost to innermost.
10988 DeclContext *LookupDC = dyn_cast<DeclContext>(D);
10989
10990 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
10991 for (TemplateParameterList *TPL : DD->getTemplateParameterLists())
10992 ParameterLists.push_back(TPL);
10993
10994 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
10995 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
10996 ParameterLists.push_back(FTD->getTemplateParameters());
10997 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
10998 LookupDC = VD->getDeclContext();
10999
11001 ParameterLists.push_back(VTD->getTemplateParameters());
11002 else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D))
11003 ParameterLists.push_back(PSD->getTemplateParameters());
11004 }
11005 } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
11006 for (TemplateParameterList *TPL : TD->getTemplateParameterLists())
11007 ParameterLists.push_back(TPL);
11008
11009 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
11011 ParameterLists.push_back(CTD->getTemplateParameters());
11012 else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
11013 ParameterLists.push_back(PSD->getTemplateParameters());
11014 }
11015 }
11016 // FIXME: Alias declarations and concepts.
11017
11018 unsigned Count = 0;
11019 Scope *InnermostTemplateScope = nullptr;
11020 for (TemplateParameterList *Params : ParameterLists) {
11021 // Ignore explicit specializations; they don't contribute to the template
11022 // depth.
11023 if (Params->size() == 0)
11024 continue;
11025
11026 InnermostTemplateScope = EnterScope();
11027 for (NamedDecl *Param : *Params) {
11028 if (Param->getDeclName()) {
11029 InnermostTemplateScope->AddDecl(Param);
11030 IdResolver.AddDecl(Param);
11031 }
11032 }
11033 ++Count;
11034 }
11035
11036 // Associate the new template scopes with the corresponding entities.
11037 if (InnermostTemplateScope) {
11038 assert(LookupDC && "no enclosing DeclContext for template lookup");
11039 EnterTemplatedContext(InnermostTemplateScope, LookupDC);
11040 }
11041
11042 return Count;
11043}
11044
11046 if (!RecordD) return;
11047 AdjustDeclIfTemplate(RecordD);
11050}
11051
11053 if (!RecordD) return;
11055}
11056
11058 if (!Param)
11059 return;
11060
11061 S->AddDecl(Param);
11062 if (Param->getDeclName())
11063 IdResolver.AddDecl(Param);
11064}
11065
11068
11069/// ActOnDelayedCXXMethodParameter - We've already started a delayed
11070/// C++ method declaration. We're (re-)introducing the given
11071/// function parameter into scope for use in parsing later parts of
11072/// the method declaration. For example, we could see an
11073/// ActOnParamDefaultArgument event for this parameter.
11075 if (!ParamD)
11076 return;
11077
11078 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
11079
11080 S->AddDecl(Param);
11081 if (Param->getDeclName())
11082 IdResolver.AddDecl(Param);
11083}
11084
11086 if (!MethodD)
11087 return;
11088
11089 AdjustDeclIfTemplate(MethodD);
11090
11092
11093 // Now that we have our default arguments, check the constructor
11094 // again. It could produce additional diagnostics or affect whether
11095 // the class has implicitly-declared destructors, among other
11096 // things.
11097 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
11099
11100 // Check the default arguments, which we may have added.
11101 if (!Method->isInvalidDecl())
11103}
11104
11105// Emit the given diagnostic for each non-address-space qualifier.
11106// Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
11107static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
11109 if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
11110 bool DiagOccurred = false;
11112 [DiagID, &S, &DiagOccurred](DeclSpec::TQ, StringRef QualName,
11113 SourceLocation SL) {
11114 // This diagnostic should be emitted on any qualifier except an addr
11115 // space qualifier. However, forEachQualifier currently doesn't visit
11116 // addr space qualifiers, so there's no way to write this condition
11117 // right now; we just diagnose on everything.
11118 S.Diag(SL, DiagID) << QualName << SourceRange(SL);
11119 DiagOccurred = true;
11120 });
11121 if (DiagOccurred)
11122 D.setInvalidType();
11123 }
11124}
11125
11127 unsigned Kind) {
11128 if (D.isInvalidType() || D.getNumTypeObjects() <= 1)
11129 return;
11130
11132 if (Chunk.Kind == DeclaratorChunk::Paren ||
11134 return;
11135
11136 SourceLocation PointerLoc = Chunk.getSourceRange().getBegin();
11137 S.Diag(PointerLoc, diag::err_invalid_ctor_dtor_decl)
11138 << Kind << Chunk.getSourceRange();
11139 D.setInvalidType();
11140}
11141
11143 StorageClass &SC) {
11144 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
11145
11146 // C++ [class.ctor]p3:
11147 // A constructor shall not be virtual (10.3) or static (9.4). A
11148 // constructor can be invoked for a const, volatile or const
11149 // volatile object. A constructor shall not be declared const,
11150 // volatile, or const volatile (9.3.2).
11151 if (isVirtual) {
11152 if (!D.isInvalidType())
11153 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
11154 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
11156 D.setInvalidType();
11157 }
11158 if (SC == SC_Static) {
11159 if (!D.isInvalidType())
11160 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
11161 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
11163 D.setInvalidType();
11164 SC = SC_None;
11165 }
11166
11167 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
11169 diag::err_constructor_return_type, TypeQuals, SourceLocation(),
11173 D.setInvalidType();
11174 }
11175
11176 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor);
11177 diagnoseInvalidDeclaratorChunks(*this, D, /*constructor*/ 0);
11178
11179 // C++0x [class.ctor]p4:
11180 // A constructor shall not be declared with a ref-qualifier.
11182 if (FTI.hasRefQualifier()) {
11183 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
11186 D.setInvalidType();
11187 }
11188
11189 // Rebuild the function type "R" without any type qualifiers (in
11190 // case any of the errors above fired) and with "void" as the
11191 // return type, since constructors don't have return types.
11192 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
11193 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
11194 return R;
11195
11197 EPI.TypeQuals = Qualifiers();
11198 EPI.RefQualifier = RQ_None;
11199
11200 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
11201}
11202
11204 CXXRecordDecl *ClassDecl
11205 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
11206 if (!ClassDecl)
11207 return Constructor->setInvalidDecl();
11208
11209 // C++ [class.copy]p3:
11210 // A declaration of a constructor for a class X is ill-formed if
11211 // its first parameter is of type (optionally cv-qualified) X and
11212 // either there are no other parameters or else all other
11213 // parameters have default arguments.
11214 if (!Constructor->isInvalidDecl() &&
11215 Constructor->hasOneParamOrDefaultArgs() &&
11216 !Constructor->isFunctionTemplateSpecialization()) {
11217 CanQualType ParamType =
11218 Constructor->getParamDecl(0)->getType()->getCanonicalTypeUnqualified();
11219 CanQualType ClassTy = Context.getCanonicalTagType(ClassDecl);
11220 if (ParamType == ClassTy) {
11221 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
11222 const char *ConstRef
11223 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
11224 : " const &";
11225 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
11226 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
11227
11228 // FIXME: Rather that making the constructor invalid, we should endeavor
11229 // to fix the type.
11230 Constructor->setInvalidDecl();
11231 }
11232 }
11233}
11234
11236 CXXRecordDecl *RD = Destructor->getParent();
11237
11238 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
11239 SourceLocation Loc;
11240
11241 if (!Destructor->isImplicit())
11242 Loc = Destructor->getLocation();
11243 else
11244 Loc = RD->getLocation();
11245
11246 DeclarationName Name =
11247 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
11248 // If we have a virtual destructor, look up the deallocation function
11250 Loc, RD, /*Diagnose=*/true, /*LookForGlobal=*/false, Name)) {
11251 Expr *ThisArg = nullptr;
11252
11253 // If the notional 'delete this' expression requires a non-trivial
11254 // conversion from 'this' to the type of a destroying operator delete's
11255 // first parameter, perform that conversion now.
11256 if (OperatorDelete->isDestroyingOperatorDelete()) {
11257 unsigned AddressParamIndex = 0;
11258 if (OperatorDelete->isTypeAwareOperatorNewOrDelete())
11259 ++AddressParamIndex;
11260 QualType ParamType =
11261 OperatorDelete->getParamDecl(AddressParamIndex)->getType();
11262 if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
11263 // C++ [class.dtor]p13:
11264 // ... as if for the expression 'delete this' appearing in a
11265 // non-virtual destructor of the destructor's class.
11266 ContextRAII SwitchContext(*this, Destructor);
11268 OperatorDelete->getParamDecl(AddressParamIndex)->getLocation());
11269 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
11270 This = PerformImplicitConversion(This.get(), ParamType,
11272 if (This.isInvalid()) {
11273 // FIXME: Register this as a context note so that it comes out
11274 // in the right order.
11275 Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
11276 return true;
11277 }
11278 ThisArg = This.get();
11279 }
11280 }
11281
11282 DiagnoseUseOfDecl(OperatorDelete, Loc);
11283 MarkFunctionReferenced(Loc, OperatorDelete);
11284 Destructor->setOperatorDelete(OperatorDelete, ThisArg);
11285
11286 if (isa<CXXMethodDecl>(OperatorDelete) &&
11287 Context.getTargetInfo().callGlobalDeleteInDeletingDtor(
11288 Context.getLangOpts())) {
11289 // In Microsoft ABI whenever a class has a defined operator delete,
11290 // scalar deleting destructors check the 3rd bit of the implicit
11291 // parameter and if it is set, then, global operator delete must be
11292 // called instead of the class-specific one. Find and save the global
11293 // operator delete for that case. Do not diagnose at this point because
11294 // the lack of a global operator delete is not an error if there are no
11295 // delete calls that require it.
11296 FunctionDecl *GlobalOperatorDelete =
11297 FindDeallocationFunctionForDestructor(Loc, RD, /*Diagnose*/ false,
11298 /*LookForGlobal*/ true, Name);
11299 if (GlobalOperatorDelete) {
11300 MarkFunctionReferenced(Loc, GlobalOperatorDelete);
11301 Destructor->setOperatorGlobalDelete(GlobalOperatorDelete);
11302 }
11303 }
11304
11305 if (Context.getTargetInfo().emitVectorDeletingDtors(
11306 Context.getLangOpts())) {
11307 bool DestructorIsExported = Destructor->hasAttr<DLLExportAttr>();
11308 // Lookup delete[] too in case we have to emit a vector deleting dtor.
11309 DeclarationName VDeleteName =
11310 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
11312 Loc, RD, /*Diagnose*/ false,
11313 /*LookForGlobal*/ false, VDeleteName);
11314 if (ArrOperatorDelete && isa<CXXMethodDecl>(ArrOperatorDelete)) {
11315 FunctionDecl *GlobalArrOperatorDelete =
11316 FindDeallocationFunctionForDestructor(Loc, RD, /*Diagnose*/ false,
11317 /*LookForGlobal*/ true,
11318 VDeleteName);
11319 Destructor->setGlobalOperatorArrayDelete(GlobalArrOperatorDelete);
11320 if (GlobalArrOperatorDelete &&
11321 (Context.classMaybeNeedsVectorDeletingDestructor(RD) ||
11322 DestructorIsExported))
11323 MarkFunctionReferenced(Loc, GlobalArrOperatorDelete);
11324 } else if (!ArrOperatorDelete) {
11325 ArrOperatorDelete = FindDeallocationFunctionForDestructor(
11326 Loc, RD, /*Diagnose*/ false,
11327 /*LookForGlobal*/ true, VDeleteName);
11328 }
11329 Destructor->setOperatorArrayDelete(ArrOperatorDelete);
11330 if (ArrOperatorDelete &&
11331 (Context.classMaybeNeedsVectorDeletingDestructor(RD) ||
11332 DestructorIsExported))
11333 MarkFunctionReferenced(Loc, ArrOperatorDelete);
11334 }
11335 }
11336 }
11337
11338 return false;
11339}
11340
11342 StorageClass& SC) {
11343 // C++ [class.dtor]p1:
11344 // [...] A typedef-name that names a class is a class-name
11345 // (7.1.3); however, a typedef-name that names a class shall not
11346 // be used as the identifier in the declarator for a destructor
11347 // declaration.
11348 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
11349 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
11350 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
11351 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
11352 else if (const TemplateSpecializationType *TST =
11353 DeclaratorType->getAs<TemplateSpecializationType>())
11354 if (TST->isTypeAlias())
11355 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
11356 << DeclaratorType << 1;
11357
11358 // C++ [class.dtor]p2:
11359 // A destructor is used to destroy objects of its class type. A
11360 // destructor takes no parameters, and no return type can be
11361 // specified for it (not even void). The address of a destructor
11362 // shall not be taken. A destructor shall not be static. A
11363 // destructor can be invoked for a const, volatile or const
11364 // volatile object. A destructor shall not be declared const,
11365 // volatile or const volatile (9.3.2).
11366 if (SC == SC_Static) {
11367 if (!D.isInvalidType())
11368 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
11369 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
11372
11373 SC = SC_None;
11374 }
11375 if (!D.isInvalidType()) {
11376 // Destructors don't have return types, but the parser will
11377 // happily parse something like:
11378 //
11379 // class X {
11380 // float ~X();
11381 // };
11382 //
11383 // The return type will be eliminated later.
11384 if (D.getDeclSpec().hasTypeSpecifier())
11385 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
11388 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
11389 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
11395 D.setInvalidType();
11396 }
11397 }
11398
11399 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor);
11400 diagnoseInvalidDeclaratorChunks(*this, D, /*destructor*/ 1);
11401
11402 // C++0x [class.dtor]p2:
11403 // A destructor shall not be declared with a ref-qualifier.
11405 if (FTI.hasRefQualifier()) {
11406 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
11409 D.setInvalidType();
11410 }
11411
11412 // Make sure we don't have any parameters.
11413 if (FTIHasNonVoidParameters(FTI)) {
11414 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
11415
11416 // Delete the parameters.
11417 FTI.freeParams();
11418 D.setInvalidType();
11419 }
11420
11421 // Make sure the destructor isn't variadic.
11422 if (FTI.isVariadic) {
11423 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
11424 D.setInvalidType();
11425 }
11426
11427 // Rebuild the function type "R" without any type qualifiers or
11428 // parameters (in case any of the errors above fired) and with
11429 // "void" as the return type, since destructors don't have return
11430 // types.
11431 if (!D.isInvalidType())
11432 return R;
11433
11434 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
11436 EPI.Variadic = false;
11437 EPI.TypeQuals = Qualifiers();
11438 EPI.RefQualifier = RQ_None;
11439 return Context.getFunctionType(Context.VoidTy, {}, EPI);
11440}
11441
11442static void extendLeft(SourceRange &R, SourceRange Before) {
11443 if (Before.isInvalid())
11444 return;
11445 R.setBegin(Before.getBegin());
11446 if (R.getEnd().isInvalid())
11447 R.setEnd(Before.getEnd());
11448}
11449
11450static void extendRight(SourceRange &R, SourceRange After) {
11451 if (After.isInvalid())
11452 return;
11453 if (R.getBegin().isInvalid())
11454 R.setBegin(After.getBegin());
11455 R.setEnd(After.getEnd());
11456}
11457
11459 StorageClass& SC) {
11460 // C++ [class.conv.fct]p1:
11461 // Neither parameter types nor return type can be specified. The
11462 // type of a conversion function (8.3.5) is "function taking no
11463 // parameter returning conversion-type-id."
11464 if (SC == SC_Static) {
11465 if (!D.isInvalidType())
11466 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
11468 << D.getName().getSourceRange();
11469 D.setInvalidType();
11470 SC = SC_None;
11471 }
11472
11473 TypeSourceInfo *ConvTSI = nullptr;
11474 QualType ConvType =
11476
11477 const DeclSpec &DS = D.getDeclSpec();
11478 if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
11479 // Conversion functions don't have return types, but the parser will
11480 // happily parse something like:
11481 //
11482 // class X {
11483 // float operator bool();
11484 // };
11485 //
11486 // The return type will be changed later anyway.
11487 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
11490 D.setInvalidType();
11491 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
11492 // It's also plausible that the user writes type qualifiers in the wrong
11493 // place, such as:
11494 // struct S { const operator int(); };
11495 // FIXME: we could provide a fixit to move the qualifiers onto the
11496 // conversion type.
11497 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
11498 << SourceRange(D.getIdentifierLoc()) << 0;
11499 D.setInvalidType();
11500 }
11501 const auto *Proto = R->castAs<FunctionProtoType>();
11502 // Make sure we don't have any parameters.
11504 unsigned NumParam = Proto->getNumParams();
11505
11506 // [C++2b]
11507 // A conversion function shall have no non-object parameters.
11508 if (NumParam == 1) {
11510 if (const auto *First =
11511 dyn_cast_if_present<ParmVarDecl>(FTI.Params[0].Param);
11512 First && First->isExplicitObjectParameter())
11513 NumParam--;
11514 }
11515
11516 if (NumParam != 0) {
11517 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
11518 // Delete the parameters.
11519 FTI.freeParams();
11520 D.setInvalidType();
11521 } else if (Proto->isVariadic()) {
11522 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
11523 D.setInvalidType();
11524 }
11525
11526 // Diagnose "&operator bool()" and other such nonsense. This
11527 // is actually a gcc extension which we don't support.
11528 if (Proto->getReturnType() != ConvType) {
11529 bool NeedsTypedef = false;
11530 SourceRange Before, After;
11531
11532 // Walk the chunks and extract information on them for our diagnostic.
11533 bool PastFunctionChunk = false;
11534 for (auto &Chunk : D.type_objects()) {
11535 switch (Chunk.Kind) {
11537 if (!PastFunctionChunk) {
11538 if (Chunk.Fun.HasTrailingReturnType) {
11539 TypeSourceInfo *TRT = nullptr;
11540 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
11541 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
11542 }
11543 PastFunctionChunk = true;
11544 break;
11545 }
11546 [[fallthrough]];
11548 NeedsTypedef = true;
11549 extendRight(After, Chunk.getSourceRange());
11550 break;
11551
11557 extendLeft(Before, Chunk.getSourceRange());
11558 break;
11559
11561 extendLeft(Before, Chunk.Loc);
11562 extendRight(After, Chunk.EndLoc);
11563 break;
11564 }
11565 }
11566
11567 SourceLocation Loc = Before.isValid() ? Before.getBegin() :
11568 After.isValid() ? After.getBegin() :
11569 D.getIdentifierLoc();
11570 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
11571 DB << Before << After;
11572
11573 if (!NeedsTypedef) {
11574 DB << /*don't need a typedef*/0;
11575
11576 // If we can provide a correct fix-it hint, do so.
11577 if (After.isInvalid() && ConvTSI) {
11578 SourceLocation InsertLoc =
11580 DB << FixItHint::CreateInsertion(InsertLoc, " ")
11582 InsertLoc, CharSourceRange::getTokenRange(Before))
11583 << FixItHint::CreateRemoval(Before);
11584 }
11585 } else if (!Proto->getReturnType()->isDependentType()) {
11586 DB << /*typedef*/1 << Proto->getReturnType();
11587 } else if (getLangOpts().CPlusPlus11) {
11588 DB << /*alias template*/2 << Proto->getReturnType();
11589 } else {
11590 DB << /*might not be fixable*/3;
11591 }
11592
11593 // Recover by incorporating the other type chunks into the result type.
11594 // Note, this does *not* change the name of the function. This is compatible
11595 // with the GCC extension:
11596 // struct S { &operator int(); } s;
11597 // int &r = s.operator int(); // ok in GCC
11598 // S::operator int&() {} // error in GCC, function name is 'operator int'.
11599 ConvType = Proto->getReturnType();
11600 }
11601
11602 // C++ [class.conv.fct]p4:
11603 // The conversion-type-id shall not represent a function type nor
11604 // an array type.
11605 if (ConvType->isArrayType()) {
11606 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
11607 ConvType = Context.getPointerType(ConvType);
11608 D.setInvalidType();
11609 } else if (ConvType->isFunctionType()) {
11610 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
11611 ConvType = Context.getPointerType(ConvType);
11612 D.setInvalidType();
11613 }
11614
11615 // Rebuild the function type "R" without any parameters (in case any
11616 // of the errors above fired) and with the conversion type as the
11617 // return type.
11618 if (D.isInvalidType())
11619 R = Context.getFunctionType(ConvType, {}, Proto->getExtProtoInfo());
11620
11621 // C++0x explicit conversion operators.
11622 if (DS.hasExplicitSpecifier())
11624 diag_compat::explicit_conversion_functions)
11626}
11627
11629 assert(Conversion && "Expected to receive a conversion function declaration");
11630
11631 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
11632
11633 // Make sure we aren't redeclaring the conversion function.
11634 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
11635 // C++ [class.conv.fct]p1:
11636 // [...] A conversion function is never used to convert a
11637 // (possibly cv-qualified) object to the (possibly cv-qualified)
11638 // same object type (or a reference to it), to a (possibly
11639 // cv-qualified) base class of that type (or a reference to it),
11640 // or to (possibly cv-qualified) void.
11641 CanQualType ClassType = Context.getCanonicalTagType(ClassDecl);
11642 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
11643 ConvType = ConvTypeRef->getPointeeType();
11644 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
11646 /* Suppress diagnostics for instantiations. */;
11647 else if (Conversion->size_overridden_methods() != 0)
11648 /* Suppress diagnostics for overriding virtual function in a base class. */;
11649 else if (ConvType->isRecordType()) {
11650 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
11651 if (ConvType == ClassType)
11652 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
11653 << ClassType;
11654 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
11655 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
11656 << ClassType << ConvType;
11657 } else if (ConvType->isVoidType()) {
11658 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
11659 << ClassType << ConvType;
11660 }
11661
11662 if (FunctionTemplateDecl *ConversionTemplate =
11663 Conversion->getDescribedFunctionTemplate()) {
11664 if (const auto *ConvTypePtr = ConvType->getAs<PointerType>()) {
11665 ConvType = ConvTypePtr->getPointeeType();
11666 }
11667 if (ConvType->isUndeducedAutoType()) {
11668 Diag(Conversion->getTypeSpecStartLoc(), diag::err_auto_not_allowed)
11669 << getReturnTypeLoc(Conversion).getSourceRange()
11670 << ConvType->castAs<AutoType>()->getKeyword()
11671 << /* in declaration of conversion function template= */ 24;
11672 }
11673
11674 return ConversionTemplate;
11675 }
11676
11677 return Conversion;
11678}
11679
11684
11688
11690 DeclarationName Name, QualType R,
11691 bool IsLambda, DeclContext *DC) {
11692 if (!D.isFunctionDeclarator())
11693 return;
11694
11696 if (FTI.NumParams == 0)
11697 return;
11698 ParmVarDecl *ExplicitObjectParam = nullptr;
11699 for (unsigned Idx = 0; Idx < FTI.NumParams; Idx++) {
11700 const auto &ParamInfo = FTI.Params[Idx];
11701 if (!ParamInfo.Param)
11702 continue;
11703 ParmVarDecl *Param = cast<ParmVarDecl>(ParamInfo.Param);
11704 if (!Param->isExplicitObjectParameter())
11705 continue;
11706 if (Idx == 0) {
11707 ExplicitObjectParam = Param;
11708 continue;
11709 } else {
11710 Diag(Param->getLocation(),
11711 diag::err_explicit_object_parameter_must_be_first)
11712 << IsLambda << Param->getSourceRange();
11713 }
11714 }
11715 if (!ExplicitObjectParam)
11716 return;
11717
11718 if (ExplicitObjectParam->hasDefaultArg()) {
11719 Diag(ExplicitObjectParam->getLocation(),
11720 diag::err_explicit_object_default_arg)
11721 << ExplicitObjectParam->getSourceRange();
11722 D.setInvalidType();
11723 }
11724
11727 D.isStaticMember())) {
11728 Diag(ExplicitObjectParam->getBeginLoc(),
11729 diag::err_explicit_object_parameter_nonmember)
11730 << D.getSourceRange() << /*static=*/0 << IsLambda;
11731 D.setInvalidType();
11732 }
11733
11734 if (D.getDeclSpec().isVirtualSpecified()) {
11735 Diag(ExplicitObjectParam->getBeginLoc(),
11736 diag::err_explicit_object_parameter_nonmember)
11737 << D.getSourceRange() << /*virtual=*/1 << IsLambda;
11738 D.setInvalidType();
11739 }
11740
11741 // Friend declarations require some care. Consider:
11742 //
11743 // namespace N {
11744 // struct A{};
11745 // int f(A);
11746 // }
11747 //
11748 // struct S {
11749 // struct T {
11750 // int f(this T);
11751 // };
11752 //
11753 // friend int T::f(this T); // Allow this.
11754 // friend int f(this S); // But disallow this.
11755 // friend int N::f(this A); // And disallow this.
11756 // };
11757 //
11758 // Here, it seems to suffice to check whether the scope
11759 // specifier designates a class type.
11760 if (D.getDeclSpec().isFriendSpecified() &&
11761 !isa_and_present<CXXRecordDecl>(
11763 Diag(ExplicitObjectParam->getBeginLoc(),
11764 diag::err_explicit_object_parameter_nonmember)
11765 << D.getSourceRange() << /*non-member=*/2 << IsLambda;
11766 D.setInvalidType();
11767 }
11768
11769 if (IsLambda && FTI.hasMutableQualifier()) {
11770 Diag(ExplicitObjectParam->getBeginLoc(),
11771 diag::err_explicit_object_parameter_mutable)
11772 << D.getSourceRange();
11773 }
11774
11775 if (IsLambda)
11776 return;
11777
11778 if (!DC || !DC->isRecord()) {
11779 assert(D.isInvalidType() && "Explicit object parameter in non-member "
11780 "should have been diagnosed already");
11781 return;
11782 }
11783
11784 // CWG2674: constructors and destructors cannot have explicit parameters.
11787 Diag(ExplicitObjectParam->getBeginLoc(),
11788 diag::err_explicit_object_parameter_constructor)
11790 << D.getSourceRange();
11791 D.setInvalidType();
11792 }
11793}
11794
11795namespace {
11796/// Utility class to accumulate and print a diagnostic listing the invalid
11797/// specifier(s) on a declaration.
11798struct BadSpecifierDiagnoser {
11799 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
11800 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
11801 ~BadSpecifierDiagnoser() {
11802 Diagnostic << Specifiers;
11803 }
11804
11805 template<typename T> void check(SourceLocation SpecLoc, T Spec) {
11806 return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
11807 }
11808 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
11809 return check(SpecLoc,
11811 }
11812 void check(SourceLocation SpecLoc, const char *Spec) {
11813 if (SpecLoc.isInvalid()) return;
11814 Diagnostic << SourceRange(SpecLoc, SpecLoc);
11815 if (!Specifiers.empty()) Specifiers += " ";
11816 Specifiers += Spec;
11817 }
11818
11819 Sema &S;
11820 Sema::SemaDiagnosticBuilder Diagnostic;
11821 std::string Specifiers;
11822};
11823}
11824
11826 StorageClass &SC) {
11827 TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
11828 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
11829 assert(GuidedTemplateDecl && "missing template decl for deduction guide");
11830
11831 // C++ [temp.deduct.guide]p3:
11832 // A deduction-gide shall be declared in the same scope as the
11833 // corresponding class template.
11834 if (!CurContext->getRedeclContext()->Equals(
11835 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
11836 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
11837 << GuidedTemplateDecl;
11838 NoteTemplateLocation(*GuidedTemplateDecl);
11839 }
11840
11841 auto &DS = D.getMutableDeclSpec();
11842 // We leave 'friend' and 'virtual' to be rejected in the normal way.
11843 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
11844 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
11845 DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
11846 BadSpecifierDiagnoser Diagnoser(
11847 *this, D.getIdentifierLoc(),
11848 diag::err_deduction_guide_invalid_specifier);
11849
11850 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
11851 DS.ClearStorageClassSpecs();
11852 SC = SC_None;
11853
11854 // 'explicit' is permitted.
11855 Diagnoser.check(DS.getInlineSpecLoc(), "inline");
11856 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
11857 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
11858 DS.ClearConstexprSpec();
11859
11860 Diagnoser.check(DS.getConstSpecLoc(), "const");
11861 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
11862 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
11863 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
11864 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
11865 DS.ClearTypeQualifiers();
11866
11867 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
11868 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
11869 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
11870 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
11871 DS.ClearTypeSpecType();
11872 }
11873
11874 if (D.isInvalidType())
11875 return true;
11876
11877 // Check the declarator is simple enough.
11878 bool FoundFunction = false;
11879 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
11880 if (Chunk.Kind == DeclaratorChunk::Paren)
11881 continue;
11882 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
11884 diag::err_deduction_guide_with_complex_decl)
11885 << D.getSourceRange();
11886 break;
11887 }
11888 if (!Chunk.Fun.hasTrailingReturnType())
11889 return Diag(D.getName().getBeginLoc(),
11890 diag::err_deduction_guide_no_trailing_return_type);
11891
11892 // Check that the return type is written as a specialization of
11893 // the template specified as the deduction-guide's name.
11894 // The template name may not be qualified. [temp.deduct.guide]
11895 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
11896 TypeSourceInfo *TSI = nullptr;
11897 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
11898 assert(TSI && "deduction guide has valid type but invalid return type?");
11899 bool AcceptableReturnType = false;
11900 bool MightInstantiateToSpecialization = false;
11901 if (auto RetTST =
11903 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
11904 bool TemplateMatches = Context.hasSameTemplateName(
11905 SpecifiedName, GuidedTemplate, /*IgnoreDeduced=*/true);
11906
11908 SpecifiedName.getAsQualifiedTemplateName();
11909 // A Template template parameter is never wrapped in a
11910 // QualifiedTemplateName, but it's always simply-written.
11911 bool SimplyWritten = !Qualifiers || (!Qualifiers->hasTemplateKeyword() &&
11912 !Qualifiers->getQualifier());
11913 if (SimplyWritten && TemplateMatches)
11914 AcceptableReturnType = true;
11915 else {
11916 // This could still instantiate to the right type, unless we know it
11917 // names the wrong class template.
11918 auto *TD = SpecifiedName.getAsTemplateDecl();
11919 MightInstantiateToSpecialization =
11920 !(TD && isa<ClassTemplateDecl>(TD) && !TemplateMatches);
11921 }
11922 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
11923 MightInstantiateToSpecialization = true;
11924 }
11925
11926 if (!AcceptableReturnType)
11927 return Diag(TSI->getTypeLoc().getBeginLoc(),
11928 diag::err_deduction_guide_bad_trailing_return_type)
11929 << GuidedTemplate << TSI->getType()
11930 << MightInstantiateToSpecialization
11931 << TSI->getTypeLoc().getSourceRange();
11932
11933 // Keep going to check that we don't have any inner declarator pieces (we
11934 // could still have a function returning a pointer to a function).
11935 FoundFunction = true;
11936 }
11937
11938 if (D.isFunctionDefinition())
11939 // we can still create a valid deduction guide here.
11940 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
11941 return false;
11942}
11943
11944//===----------------------------------------------------------------------===//
11945// Namespace Handling
11946//===----------------------------------------------------------------------===//
11947
11948/// Diagnose a mismatch in 'inline' qualifiers when a namespace is
11949/// reopened.
11951 SourceLocation Loc,
11952 IdentifierInfo *II, bool *IsInline,
11953 NamespaceDecl *PrevNS) {
11954 assert(*IsInline != PrevNS->isInline());
11955
11956 // 'inline' must appear on the original definition, but not necessarily
11957 // on all extension definitions, so the note should point to the first
11958 // definition to avoid confusion.
11959 PrevNS = PrevNS->getFirstDecl();
11960
11961 if (PrevNS->isInline())
11962 // The user probably just forgot the 'inline', so suggest that it
11963 // be added back.
11964 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
11965 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
11966 else
11967 S.Diag(Loc, diag::err_inline_namespace_mismatch);
11968
11969 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
11970 *IsInline = PrevNS->isInline();
11971}
11972
11973/// ActOnStartNamespaceDef - This is called at the start of a namespace
11974/// definition.
11976 SourceLocation InlineLoc,
11977 SourceLocation NamespaceLoc,
11978 SourceLocation IdentLoc, IdentifierInfo *II,
11979 SourceLocation LBrace,
11980 const ParsedAttributesView &AttrList,
11981 UsingDirectiveDecl *&UD, bool IsNested) {
11982 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
11983 // For anonymous namespace, take the location of the left brace.
11984 SourceLocation Loc = II ? IdentLoc : LBrace;
11985 bool IsInline = InlineLoc.isValid();
11986 bool IsInvalid = false;
11987 bool IsStd = false;
11988 bool AddToKnown = false;
11989 Scope *DeclRegionScope = NamespcScope->getParent();
11990
11991 NamespaceDecl *PrevNS = nullptr;
11992 if (II) {
11993 // C++ [namespace.std]p7:
11994 // A translation unit shall not declare namespace std to be an inline
11995 // namespace (9.8.2).
11996 //
11997 // Precondition: the std namespace is in the file scope and is declared to
11998 // be inline
11999 auto DiagnoseInlineStdNS = [&]() {
12000 assert(IsInline && II->isStr("std") &&
12001 CurContext->getRedeclContext()->isTranslationUnit() &&
12002 "Precondition of DiagnoseInlineStdNS not met");
12003 Diag(InlineLoc, diag::err_inline_namespace_std)
12004 << SourceRange(InlineLoc, InlineLoc.getLocWithOffset(6));
12005 IsInline = false;
12006 };
12007 // C++ [namespace.def]p2:
12008 // The identifier in an original-namespace-definition shall not
12009 // have been previously defined in the declarative region in
12010 // which the original-namespace-definition appears. The
12011 // identifier in an original-namespace-definition is the name of
12012 // the namespace. Subsequently in that declarative region, it is
12013 // treated as an original-namespace-name.
12014 //
12015 // Since namespace names are unique in their scope, and we don't
12016 // look through using directives, just look for any ordinary names
12017 // as if by qualified name lookup.
12018 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
12020 LookupQualifiedName(R, CurContext->getRedeclContext());
12021 NamedDecl *PrevDecl =
12022 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
12023 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
12024
12025 if (PrevNS) {
12026 // This is an extended namespace definition.
12027 if (IsInline && II->isStr("std") &&
12028 CurContext->getRedeclContext()->isTranslationUnit())
12029 DiagnoseInlineStdNS();
12030 else if (IsInline != PrevNS->isInline())
12031 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
12032 &IsInline, PrevNS);
12033 } else if (PrevDecl) {
12034 // This is an invalid name redefinition.
12035 Diag(Loc, diag::err_redefinition_different_kind)
12036 << II;
12037 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12038 IsInvalid = true;
12039 // Continue on to push Namespc as current DeclContext and return it.
12040 } else if (II->isStr("std") &&
12041 CurContext->getRedeclContext()->isTranslationUnit()) {
12042 if (IsInline)
12043 DiagnoseInlineStdNS();
12044 // This is the first "real" definition of the namespace "std", so update
12045 // our cache of the "std" namespace to point at this definition.
12046 PrevNS = getStdNamespace();
12047 IsStd = true;
12048 AddToKnown = !IsInline;
12049 } else {
12050 // We've seen this namespace for the first time.
12051 AddToKnown = !IsInline;
12052 }
12053 } else {
12054 // Anonymous namespaces.
12055
12056 // Determine whether the parent already has an anonymous namespace.
12057 DeclContext *Parent = CurContext->getRedeclContext();
12058 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
12059 PrevNS = TU->getAnonymousNamespace();
12060 } else {
12061 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
12062 PrevNS = ND->getAnonymousNamespace();
12063 }
12064
12065 if (PrevNS && IsInline != PrevNS->isInline())
12066 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
12067 &IsInline, PrevNS);
12068 }
12069
12071 Context, CurContext, IsInline, StartLoc, Loc, II, PrevNS, IsNested);
12072 if (IsInvalid)
12073 Namespc->setInvalidDecl();
12074
12075 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
12076 AddPragmaAttributes(DeclRegionScope, Namespc);
12077 ProcessAPINotes(Namespc);
12078
12079 // FIXME: Should we be merging attributes?
12080 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
12082
12083 if (IsStd)
12084 StdNamespace = Namespc;
12085 if (AddToKnown)
12086 KnownNamespaces[Namespc] = false;
12087
12088 if (II) {
12089 PushOnScopeChains(Namespc, DeclRegionScope);
12090 } else {
12091 // Link the anonymous namespace into its parent.
12092 DeclContext *Parent = CurContext->getRedeclContext();
12093 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
12094 TU->setAnonymousNamespace(Namespc);
12095 } else {
12096 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
12097 }
12098
12099 CurContext->addDecl(Namespc);
12100
12101 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
12102 // behaves as if it were replaced by
12103 // namespace unique { /* empty body */ }
12104 // using namespace unique;
12105 // namespace unique { namespace-body }
12106 // where all occurrences of 'unique' in a translation unit are
12107 // replaced by the same identifier and this identifier differs
12108 // from all other identifiers in the entire program.
12109
12110 // We just create the namespace with an empty name and then add an
12111 // implicit using declaration, just like the standard suggests.
12112 //
12113 // CodeGen enforces the "universally unique" aspect by giving all
12114 // declarations semantically contained within an anonymous
12115 // namespace internal linkage.
12116
12117 if (!PrevNS) {
12119 /* 'using' */ LBrace,
12120 /* 'namespace' */ SourceLocation(),
12121 /* qualifier */ NestedNameSpecifierLoc(),
12122 /* identifier */ SourceLocation(),
12123 Namespc,
12124 /* Ancestor */ Parent);
12125 UD->setImplicit();
12126 Parent->addDecl(UD);
12127 }
12128 }
12129
12130 ActOnDocumentableDecl(Namespc);
12131
12132 // Although we could have an invalid decl (i.e. the namespace name is a
12133 // redefinition), push it as current DeclContext and try to continue parsing.
12134 // FIXME: We should be able to push Namespc here, so that the each DeclContext
12135 // for the namespace has the declarations that showed up in that particular
12136 // namespace definition.
12137 PushDeclContext(NamespcScope, Namespc);
12138 return Namespc;
12139}
12140
12141/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
12142/// is a namespace alias, returns the namespace it points to.
12144 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
12145 return AD->getNamespace();
12146 return dyn_cast_or_null<NamespaceDecl>(D);
12147}
12148
12150 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
12151 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
12152 Namespc->setRBraceLoc(RBrace);
12154 if (Namespc->hasAttr<VisibilityAttr>())
12155 PopPragmaVisibility(true, RBrace);
12156 // If this namespace contains an export-declaration, export it now.
12157 if (DeferredExportedNamespaces.erase(Namespc))
12159}
12160
12162 return cast_or_null<CXXRecordDecl>(
12163 StdBadAlloc.get(Context.getExternalSource()));
12164}
12165
12167 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
12168}
12169
12171 return cast_or_null<NamespaceDecl>(
12172 StdNamespace.get(Context.getExternalSource()));
12173}
12174
12175namespace {
12176
12177enum UnsupportedSTLSelect {
12178 USS_InvalidMember,
12179 USS_MissingMember,
12180 USS_NonTrivial,
12181 USS_Other
12182};
12183
12184struct InvalidSTLDiagnoser {
12185 Sema &S;
12186 SourceLocation Loc;
12187 QualType TyForDiags;
12188
12189 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
12190 const VarDecl *VD = nullptr) {
12191 {
12192 auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
12193 << TyForDiags << ((int)Sel);
12194 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
12195 assert(!Name.empty());
12196 D << Name;
12197 }
12198 }
12199 if (Sel == USS_InvalidMember) {
12200 S.Diag(VD->getLocation(), diag::note_var_declared_here)
12201 << VD << VD->getSourceRange();
12202 }
12203 return QualType();
12204 }
12205};
12206} // namespace
12207
12209 SourceLocation Loc,
12211 assert(getLangOpts().CPlusPlus &&
12212 "Looking for comparison category type outside of C++.");
12213
12214 // Use an elaborated type for diagnostics which has a name containing the
12215 // prepended 'std' namespace but not any inline namespace names.
12216 auto TyForDiags = [&](ComparisonCategoryInfo *Info) {
12218 /*Prefix=*/std::nullopt);
12219 return Context.getTagType(ElaboratedTypeKeyword::None, Qualifier,
12220 Info->Record,
12221 /*OwnsTag=*/false);
12222 };
12223
12224 // Check if we've already successfully checked the comparison category type
12225 // before. If so, skip checking it again.
12226 ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
12227 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) {
12228 // The only thing we need to check is that the type has a reachable
12229 // definition in the current context.
12230 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
12231 return QualType();
12232
12233 return Info->getType();
12234 }
12235
12236 // If lookup failed
12237 if (!Info) {
12238 std::string NameForDiags = "std::";
12239 NameForDiags += ComparisonCategories::getCategoryString(Kind);
12240 Diag(Loc, diag::err_implied_comparison_category_type_not_found)
12241 << NameForDiags << (int)Usage;
12242 return QualType();
12243 }
12244
12245 assert(Info->Kind == Kind);
12246 assert(Info->Record);
12247
12248 // Update the Record decl in case we encountered a forward declaration on our
12249 // first pass. FIXME: This is a bit of a hack.
12250 if (Info->Record->hasDefinition())
12251 Info->Record = Info->Record->getDefinition();
12252
12253 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
12254 return QualType();
12255
12256 InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)};
12257
12258 if (!Info->Record->isTriviallyCopyable())
12259 return UnsupportedSTLError(USS_NonTrivial);
12260
12261 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
12262 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
12263 // Tolerate empty base classes.
12264 if (Base->isEmpty())
12265 continue;
12266 // Reject STL implementations which have at least one non-empty base.
12267 return UnsupportedSTLError();
12268 }
12269
12270 // Check that the STL has implemented the types using a single integer field.
12271 // This expectation allows better codegen for builtin operators. We require:
12272 // (1) The class has exactly one field.
12273 // (2) The field is an integral or enumeration type.
12274 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
12275 if (std::distance(FIt, FEnd) != 1 ||
12276 !FIt->getType()->isIntegralOrEnumerationType()) {
12277 return UnsupportedSTLError();
12278 }
12279
12280 // Build each of the require values and store them in Info.
12281 for (ComparisonCategoryResult CCR :
12283 StringRef MemName = ComparisonCategories::getResultString(CCR);
12284 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
12285
12286 if (!ValInfo)
12287 return UnsupportedSTLError(USS_MissingMember, MemName);
12288
12289 VarDecl *VD = ValInfo->VD;
12290 assert(VD && "should not be null!");
12291
12292 // Attempt to diagnose reasons why the STL definition of this type
12293 // might be foobar, including it failing to be a constant expression.
12294 // TODO Handle more ways the lookup or result can be invalid.
12295 if (!VD->isStaticDataMember() ||
12297 return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
12298
12299 // Attempt to evaluate the var decl as a constant expression and extract
12300 // the value of its first field as a ICE. If this fails, the STL
12301 // implementation is not supported.
12302 if (!ValInfo->hasValidIntValue())
12303 return UnsupportedSTLError();
12304
12305 MarkVariableReferenced(Loc, VD);
12306 }
12307
12308 // We've successfully built the required types and expressions. Update
12309 // the cache and return the newly cached value.
12310 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
12311 return Info->getType();
12312}
12313
12315 if (!StdNamespace) {
12316 // The "std" namespace has not yet been defined, so build one implicitly.
12318 Context, Context.getTranslationUnitDecl(),
12319 /*Inline=*/false, SourceLocation(), SourceLocation(),
12320 &PP.getIdentifierTable().get("std"),
12321 /*PrevDecl=*/nullptr, /*Nested=*/false);
12322 getStdNamespace()->setImplicit(true);
12323 // We want the created NamespaceDecl to be available for redeclaration
12324 // lookups, but not for regular name lookups.
12325 Context.getTranslationUnitDecl()->addDecl(getStdNamespace());
12326 getStdNamespace()->clearIdentifierNamespace();
12327 }
12328
12329 return getStdNamespace();
12330}
12331
12332static bool isStdClassTemplate(Sema &S, QualType SugaredType, QualType *TypeArg,
12333 const char *ClassName,
12334 ClassTemplateDecl **CachedDecl,
12335 const Decl **MalformedDecl) {
12336 // We're looking for implicit instantiations of
12337 // template <typename U> class std::{ClassName}.
12338
12339 if (!S.StdNamespace) // If we haven't seen namespace std yet, this can't be
12340 // it.
12341 return false;
12342
12343 auto ReportMatchingNameAsMalformed = [&](NamedDecl *D) {
12344 if (!MalformedDecl)
12345 return;
12346 if (!D)
12347 D = SugaredType->getAsTagDecl();
12348 if (!D || !D->isInStdNamespace())
12349 return;
12350 IdentifierInfo *II = D->getDeclName().getAsIdentifierInfo();
12351 if (II && II == &S.PP.getIdentifierTable().get(ClassName))
12352 *MalformedDecl = D;
12353 };
12354
12355 ClassTemplateDecl *Template = nullptr;
12357 if (const TemplateSpecializationType *TST =
12359 Template = dyn_cast_or_null<ClassTemplateDecl>(
12360 TST->getTemplateName().getAsTemplateDecl());
12361 Arguments = TST->template_arguments();
12362 } else if (const auto *TT = SugaredType->getAs<TagType>()) {
12363 Template = TT->getTemplateDecl();
12364 Arguments = TT->getTemplateArgs(S.Context);
12365 }
12366
12367 if (!Template) {
12368 ReportMatchingNameAsMalformed(SugaredType->getAsTagDecl());
12369 return false;
12370 }
12371
12372 if (!*CachedDecl) {
12373 // Haven't recognized std::{ClassName} yet, maybe this is it.
12374 // FIXME: It seems we should just reuse LookupStdClassTemplate but the
12375 // semantics of this are slightly different, most notably the existing
12376 // "lookup" semantics explicitly diagnose an invalid definition as an
12377 // error.
12378 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
12379 if (TemplateClass->getIdentifier() !=
12380 &S.PP.getIdentifierTable().get(ClassName) ||
12382 TemplateClass->getNonTransparentDeclContext()))
12383 return false;
12384 // This is a template called std::{ClassName}, but is it the right
12385 // template?
12386 TemplateParameterList *Params = Template->getTemplateParameters();
12387 if (Params->getMinRequiredArguments() != 1 ||
12388 !isa<TemplateTypeParmDecl>(Params->getParam(0)) ||
12389 Params->getParam(0)->isTemplateParameterPack()) {
12390 if (MalformedDecl)
12391 *MalformedDecl = TemplateClass;
12392 return false;
12393 }
12394
12395 // It's the right template.
12396 *CachedDecl = Template;
12397 }
12398
12399 if (Template->getCanonicalDecl() != (*CachedDecl)->getCanonicalDecl())
12400 return false;
12401
12402 // This is an instance of std::{ClassName}. Find the argument type.
12403 if (TypeArg) {
12404 QualType ArgType = Arguments[0].getAsType();
12405 // FIXME: Since TST only has as-written arguments, we have to perform the
12406 // only kind of conversion applicable to type arguments; in Objective-C ARC:
12407 // - If an explicitly-specified template argument type is a lifetime type
12408 // with no lifetime qualifier, the __strong lifetime qualifier is
12409 // inferred.
12410 if (S.getLangOpts().ObjCAutoRefCount && ArgType->isObjCLifetimeType() &&
12411 !ArgType.getObjCLifetime()) {
12412 Qualifiers Qs;
12414 ArgType = S.Context.getQualifiedType(ArgType, Qs);
12415 }
12416 *TypeArg = ArgType;
12417 }
12418
12419 return true;
12420}
12421
12423 assert(getLangOpts().CPlusPlus &&
12424 "Looking for std::initializer_list outside of C++.");
12425
12426 // We're looking for implicit instantiations of
12427 // template <typename E> class std::initializer_list.
12428
12429 return isStdClassTemplate(*this, Ty, Element, "initializer_list",
12430 &StdInitializerList, /*MalformedDecl=*/nullptr);
12431}
12432
12434 const Decl **MalformedDecl) {
12435 assert(getLangOpts().CPlusPlus &&
12436 "Looking for std::type_identity outside of C++.");
12437
12438 // We're looking for implicit instantiations of
12439 // template <typename T> struct std::type_identity.
12440
12441 return isStdClassTemplate(*this, Ty, Element, "type_identity",
12442 &StdTypeIdentity, MalformedDecl);
12443}
12444
12446 const char *ClassName,
12447 bool *WasMalformed) {
12448 if (!S.StdNamespace)
12449 return nullptr;
12450
12451 LookupResult Result(S, &S.PP.getIdentifierTable().get(ClassName), Loc,
12454 return nullptr;
12455
12457 if (!Template) {
12458 Result.suppressDiagnostics();
12459 // We found something weird. Complain about the first thing we found.
12460 NamedDecl *Found = *Result.begin();
12461 S.Diag(Found->getLocation(), diag::err_malformed_std_class_template)
12462 << ClassName;
12463 if (WasMalformed)
12464 *WasMalformed = true;
12465 return nullptr;
12466 }
12467
12468 // We found some template with the correct name. Now verify that it's
12469 // correct.
12470 TemplateParameterList *Params = Template->getTemplateParameters();
12471 if (Params->getMinRequiredArguments() != 1 ||
12472 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
12473 S.Diag(Template->getLocation(), diag::err_malformed_std_class_template)
12474 << ClassName;
12475 if (WasMalformed)
12476 *WasMalformed = true;
12477 return nullptr;
12478 }
12479
12480 return Template;
12481}
12482
12484 QualType TypeParam, SourceLocation Loc) {
12485 assert(S.getStdNamespace());
12486 TemplateArgumentListInfo Args(Loc, Loc);
12487 auto TSI = S.Context.getTrivialTypeSourceInfo(TypeParam, Loc);
12488 Args.addArgument(TemplateArgumentLoc(TemplateArgument(TypeParam), TSI));
12489
12491 Loc, Args, /*Scope=*/nullptr,
12492 /*ForNestedNameSpecifier=*/false);
12493}
12494
12496 if (!StdInitializerList) {
12497 bool WasMalformed = false;
12499 LookupStdClassTemplate(*this, Loc, "initializer_list", &WasMalformed);
12500 if (!StdInitializerList) {
12501 if (!WasMalformed)
12502 Diag(Loc, diag::err_implied_std_initializer_list_not_found);
12503 return QualType();
12504 }
12505 }
12506 return BuildStdClassTemplate(*this, StdInitializerList, Element, Loc);
12507}
12508
12510 if (!StdTypeIdentity) {
12511 StdTypeIdentity = LookupStdClassTemplate(*this, Loc, "type_identity",
12512 /*WasMalformed=*/nullptr);
12513 if (!StdTypeIdentity)
12514 return QualType();
12515 }
12516 return BuildStdClassTemplate(*this, StdTypeIdentity, Type, Loc);
12517}
12518
12520 // C++ [dcl.init.list]p2:
12521 // A constructor is an initializer-list constructor if its first parameter
12522 // is of type std::initializer_list<E> or reference to possibly cv-qualified
12523 // std::initializer_list<E> for some type E, and either there are no other
12524 // parameters or else all other parameters have default arguments.
12525 if (!Ctor->hasOneParamOrDefaultArgs())
12526 return false;
12527
12528 QualType ArgType = Ctor->getParamDecl(0)->getType();
12529 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
12530 ArgType = RT->getPointeeType().getUnqualifiedType();
12531
12532 return isStdInitializerList(ArgType, nullptr);
12533}
12534
12535/// Determine whether a using statement is in a context where it will be
12536/// apply in all contexts.
12538 switch (CurContext->getDeclKind()) {
12539 case Decl::TranslationUnit:
12540 return true;
12541 case Decl::LinkageSpec:
12542 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
12543 default:
12544 return false;
12545 }
12546}
12547
12548namespace {
12549
12550// Callback to only accept typo corrections that are namespaces.
12551class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
12552public:
12553 bool ValidateCandidate(const TypoCorrection &candidate) override {
12554 if (NamedDecl *ND = candidate.getCorrectionDecl())
12556 return false;
12557 }
12558
12559 std::unique_ptr<CorrectionCandidateCallback> clone() override {
12560 return std::make_unique<NamespaceValidatorCCC>(*this);
12561 }
12562};
12563
12564}
12565
12566static void DiagnoseInvisibleNamespace(const TypoCorrection &Corrected,
12567 Sema &S) {
12568 auto *ND = cast<NamespaceDecl>(Corrected.getFoundDecl());
12569 Module *M = ND->getOwningModule();
12570 assert(M && "hidden namespace definition not in a module?");
12571
12572 if (M->isExplicitGlobalModule())
12573 S.Diag(Corrected.getCorrectionRange().getBegin(),
12574 diag::err_module_unimported_use_header)
12576 << /*Header Name*/ false;
12577 else
12578 S.Diag(Corrected.getCorrectionRange().getBegin(),
12579 diag::err_module_unimported_use)
12581 << M->getTopLevelModuleName();
12582}
12583
12585 CXXScopeSpec &SS,
12586 SourceLocation IdentLoc,
12587 IdentifierInfo *Ident) {
12588 R.clear();
12589 NamespaceValidatorCCC CCC{};
12590 if (TypoCorrection Corrected =
12591 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
12593 // Generally we find it is confusing more than helpful to diagnose the
12594 // invisible namespace.
12595 // See https://github.com/llvm/llvm-project/issues/73893.
12596 //
12597 // However, we should diagnose when the users are trying to using an
12598 // invisible namespace. So we handle the case specially here.
12599 if (isa_and_nonnull<NamespaceDecl>(Corrected.getFoundDecl()) &&
12600 Corrected.requiresImport()) {
12601 DiagnoseInvisibleNamespace(Corrected, S);
12602 } else if (DeclContext *DC = S.computeDeclContext(SS, false)) {
12603 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
12604 bool DroppedSpecifier =
12605 Corrected.WillReplaceSpecifier() && Ident->getName() == CorrectedStr;
12606 S.diagnoseTypo(Corrected,
12607 S.PDiag(diag::err_using_directive_member_suggest)
12608 << Ident << DC << DroppedSpecifier << SS.getRange(),
12609 S.PDiag(diag::note_namespace_defined_here));
12610 } else {
12611 S.diagnoseTypo(Corrected,
12612 S.PDiag(diag::err_using_directive_suggest) << Ident,
12613 S.PDiag(diag::note_namespace_defined_here));
12614 }
12615 R.addDecl(Corrected.getFoundDecl());
12616 return true;
12617 }
12618 return false;
12619}
12620
12622 SourceLocation NamespcLoc, CXXScopeSpec &SS,
12623 SourceLocation IdentLoc,
12624 IdentifierInfo *NamespcName,
12625 const ParsedAttributesView &AttrList) {
12626 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
12627 assert(NamespcName && "Invalid NamespcName.");
12628 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
12629
12630 // Get the innermost enclosing declaration scope.
12631 S = S->getDeclParent();
12632
12633 UsingDirectiveDecl *UDir = nullptr;
12634 NestedNameSpecifier Qualifier = SS.getScopeRep();
12635
12636 // Lookup namespace name.
12637 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
12638 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
12639 if (R.isAmbiguous())
12640 return nullptr;
12641
12642 if (R.empty()) {
12643 R.clear();
12644 // Allow "using namespace std;" or "using namespace ::std;" even if
12645 // "std" hasn't been defined yet, for GCC compatibility.
12646 if ((!Qualifier ||
12647 Qualifier.getKind() == NestedNameSpecifier::Kind::Global) &&
12648 NamespcName->isStr("std")) {
12649 Diag(IdentLoc, diag::ext_using_undefined_std);
12650 R.addDecl(getOrCreateStdNamespace());
12651 R.resolveKind();
12652 }
12653 // Otherwise, attempt typo correction.
12654 else
12655 TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
12656 }
12657
12658 if (!R.empty()) {
12659 NamedDecl *Named = R.getRepresentativeDecl();
12660 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
12661 assert(NS && "expected namespace decl");
12662
12663 // The use of a nested name specifier may trigger deprecation warnings.
12664 DiagnoseUseOfDecl(Named, IdentLoc);
12665
12666 // C++ [namespace.udir]p1:
12667 // A using-directive specifies that the names in the nominated
12668 // namespace can be used in the scope in which the
12669 // using-directive appears after the using-directive. During
12670 // unqualified name lookup (3.4.1), the names appear as if they
12671 // were declared in the nearest enclosing namespace which
12672 // contains both the using-directive and the nominated
12673 // namespace. [Note: in this context, "contains" means "contains
12674 // directly or indirectly". ]
12675
12676 // Find enclosing context containing both using-directive and
12677 // nominated namespace.
12678 DeclContext *CommonAncestor = NS;
12679 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
12680 CommonAncestor = CommonAncestor->getParent();
12681
12682 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
12684 IdentLoc, Named, CommonAncestor);
12685
12687 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
12688 Diag(IdentLoc, diag::warn_using_directive_in_header);
12689 }
12690
12691 PushUsingDirective(S, UDir);
12692 } else {
12693 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
12694 }
12695
12696 if (UDir) {
12697 ProcessDeclAttributeList(S, UDir, AttrList);
12698 ProcessAPINotes(UDir);
12699 }
12700
12701 return UDir;
12702}
12703
12705 // If the scope has an associated entity and the using directive is at
12706 // namespace or translation unit scope, add the UsingDirectiveDecl into
12707 // its lookup structure so qualified name lookup can find it.
12708 DeclContext *Ctx = S->getEntity();
12709 if (Ctx && !Ctx->isFunctionOrMethod())
12710 Ctx->addDecl(UDir);
12711 else
12712 // Otherwise, it is at block scope. The using-directives will affect lookup
12713 // only to the end of the scope.
12714 S->PushUsingDirective(UDir);
12715}
12716
12718 SourceLocation UsingLoc,
12719 SourceLocation TypenameLoc, CXXScopeSpec &SS,
12720 UnqualifiedId &Name,
12721 SourceLocation EllipsisLoc,
12722 const ParsedAttributesView &AttrList) {
12723 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
12724
12725 if (SS.isEmpty()) {
12726 Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
12727 return nullptr;
12728 }
12729
12730 switch (Name.getKind()) {
12736 break;
12737
12740 // C++11 inheriting constructors.
12741 Diag(Name.getBeginLoc(),
12743 ? diag::warn_cxx98_compat_using_decl_constructor
12744 : diag::err_using_decl_constructor)
12745 << SS.getRange();
12746
12747 if (getLangOpts().CPlusPlus11) break;
12748
12749 return nullptr;
12750
12752 Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
12753 return nullptr;
12754
12756 Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
12758 return nullptr;
12759
12761 llvm_unreachable("cannot parse qualified deduction guide name");
12762 }
12763
12764 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
12765 DeclarationName TargetName = TargetNameInfo.getName();
12766 if (!TargetName)
12767 return nullptr;
12768
12769 // Warn about access declarations.
12770 if (UsingLoc.isInvalid()) {
12772 ? diag::err_access_decl
12773 : diag::warn_access_decl_deprecated)
12774 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
12775 }
12776
12777 if (EllipsisLoc.isInvalid()) {
12780 return nullptr;
12781 } else {
12783 !TargetNameInfo.containsUnexpandedParameterPack()) {
12784 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
12785 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
12786 EllipsisLoc = SourceLocation();
12787 }
12788 }
12789
12790 NamedDecl *UD =
12791 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
12792 SS, TargetNameInfo, EllipsisLoc, AttrList,
12793 /*IsInstantiation*/ false,
12794 AttrList.hasAttribute(ParsedAttr::AT_UsingIfExists));
12795 if (UD)
12796 PushOnScopeChains(UD, S, /*AddToContext*/ false);
12797
12798 return UD;
12799}
12800
12802 SourceLocation UsingLoc,
12803 SourceLocation EnumLoc, SourceRange TyLoc,
12804 const IdentifierInfo &II, ParsedType Ty,
12805 const CXXScopeSpec &SS) {
12806 TypeSourceInfo *TSI = nullptr;
12807 SourceLocation IdentLoc = TyLoc.getBegin();
12808 QualType EnumTy = GetTypeFromParser(Ty, &TSI);
12809 if (EnumTy.isNull()) {
12810 Diag(IdentLoc, isDependentScopeSpecifier(SS)
12811 ? diag::err_using_enum_is_dependent
12812 : diag::err_unknown_typename)
12813 << II.getName()
12814 << SourceRange(SS.isValid() ? SS.getBeginLoc() : IdentLoc,
12815 TyLoc.getEnd());
12816 return nullptr;
12817 }
12818
12819 if (EnumTy->isDependentType()) {
12820 Diag(IdentLoc, diag::err_using_enum_is_dependent);
12821 return nullptr;
12822 }
12823
12824 auto *Enum = EnumTy->getAsEnumDecl();
12825 if (!Enum) {
12826 Diag(IdentLoc, diag::err_using_enum_not_enum) << EnumTy;
12827 return nullptr;
12828 }
12829
12830 if (TSI == nullptr)
12831 TSI = Context.getTrivialTypeSourceInfo(EnumTy, IdentLoc);
12832
12833 auto *UD =
12834 BuildUsingEnumDeclaration(S, AS, UsingLoc, EnumLoc, IdentLoc, TSI, Enum);
12835
12836 if (UD)
12837 PushOnScopeChains(UD, S, /*AddToContext*/ false);
12838
12839 return UD;
12840}
12841
12842/// Determine whether a using declaration considers the given
12843/// declarations as "equivalent", e.g., if they are redeclarations of
12844/// the same entity or are both typedefs of the same type.
12845static bool
12847 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
12848 return true;
12849
12850 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
12851 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
12852 return Context.hasSameType(TD1->getUnderlyingType(),
12853 TD2->getUnderlyingType());
12854
12855 // Two using_if_exists using-declarations are equivalent if both are
12856 // unresolved.
12859 return true;
12860
12861 return false;
12862}
12863
12865 const LookupResult &Previous,
12866 UsingShadowDecl *&PrevShadow) {
12867 // Diagnose finding a decl which is not from a base class of the
12868 // current class. We do this now because there are cases where this
12869 // function will silently decide not to build a shadow decl, which
12870 // will pre-empt further diagnostics.
12871 //
12872 // We don't need to do this in C++11 because we do the check once on
12873 // the qualifier.
12874 //
12875 // FIXME: diagnose the following if we care enough:
12876 // struct A { int foo; };
12877 // struct B : A { using A::foo; };
12878 // template <class T> struct C : A {};
12879 // template <class T> struct D : C<T> { using B::foo; } // <---
12880 // This is invalid (during instantiation) in C++03 because B::foo
12881 // resolves to the using decl in B, which is not a base class of D<T>.
12882 // We can't diagnose it immediately because C<T> is an unknown
12883 // specialization. The UsingShadowDecl in D<T> then points directly
12884 // to A::foo, which will look well-formed when we instantiate.
12885 // The right solution is to not collapse the shadow-decl chain.
12886 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord())
12887 if (auto *Using = dyn_cast<UsingDecl>(BUD)) {
12888 DeclContext *OrigDC = Orig->getDeclContext();
12889
12890 // Handle enums and anonymous structs.
12891 if (isa<EnumDecl>(OrigDC))
12892 OrigDC = OrigDC->getParent();
12893 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
12894 while (OrigRec->isAnonymousStructOrUnion())
12895 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
12896
12898 if (OrigDC == CurContext) {
12899 Diag(Using->getLocation(),
12900 diag::err_using_decl_nested_name_specifier_is_current_class)
12901 << Using->getQualifierLoc().getSourceRange();
12902 Diag(Orig->getLocation(), diag::note_using_decl_target);
12903 Using->setInvalidDecl();
12904 return true;
12905 }
12906
12907 Diag(Using->getQualifierLoc().getBeginLoc(),
12908 diag::err_using_decl_nested_name_specifier_is_not_base_class)
12909 << Using->getQualifier() << cast<CXXRecordDecl>(CurContext)
12910 << Using->getQualifierLoc().getSourceRange();
12911 Diag(Orig->getLocation(), diag::note_using_decl_target);
12912 Using->setInvalidDecl();
12913 return true;
12914 }
12915 }
12916
12917 if (Previous.empty()) return false;
12918
12919 NamedDecl *Target = Orig;
12921 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
12922
12923 // If the target happens to be one of the previous declarations, we
12924 // don't have a conflict.
12925 //
12926 // FIXME: but we might be increasing its access, in which case we
12927 // should redeclare it.
12928 NamedDecl *NonTag = nullptr, *Tag = nullptr;
12929 bool FoundEquivalentDecl = false;
12930 for (NamedDecl *Element : Previous) {
12931 NamedDecl *D = Element->getUnderlyingDecl();
12932 // We can have UsingDecls in our Previous results because we use the same
12933 // LookupResult for checking whether the UsingDecl itself is a valid
12934 // redeclaration.
12936 continue;
12937
12938 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
12939 // C++ [class.mem]p19:
12940 // If T is the name of a class, then [every named member other than
12941 // a non-static data member] shall have a name different from T
12942 if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
12946 CurContext,
12948 return true;
12949 }
12950
12952 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Element))
12953 PrevShadow = Shadow;
12954 FoundEquivalentDecl = true;
12956 // We don't conflict with an existing using shadow decl of an equivalent
12957 // declaration, but we're not a redeclaration of it.
12958 FoundEquivalentDecl = true;
12959 }
12960
12961 if (isVisible(D))
12962 (isa<TagDecl>(D) ? Tag : NonTag) = D;
12963 }
12964
12965 if (FoundEquivalentDecl)
12966 return false;
12967
12968 // Always emit a diagnostic for a mismatch between an unresolved
12969 // using_if_exists and a resolved using declaration in either direction.
12971 (isa_and_nonnull<UnresolvedUsingIfExistsDecl>(NonTag))) {
12972 if (!NonTag && !Tag)
12973 return false;
12974 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12975 Diag(Target->getLocation(), diag::note_using_decl_target);
12976 Diag((NonTag ? NonTag : Tag)->getLocation(),
12977 diag::note_using_decl_conflict);
12978 BUD->setInvalidDecl();
12979 return true;
12980 }
12981
12982 if (FunctionDecl *FD = Target->getAsFunction()) {
12983 NamedDecl *OldDecl = nullptr;
12984 switch (CheckOverload(nullptr, FD, Previous, OldDecl,
12985 /*IsForUsingDecl*/ true)) {
12987 return false;
12988
12990 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12991 break;
12992
12993 // We found a decl with the exact signature.
12995 // If we're in a record, we want to hide the target, so we
12996 // return true (without a diagnostic) to tell the caller not to
12997 // build a shadow decl.
12998 if (CurContext->isRecord())
12999 return true;
13000
13001 // If we're not in a record, this is an error.
13002 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
13003 break;
13004 }
13005
13006 Diag(Target->getLocation(), diag::note_using_decl_target);
13007 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
13008 BUD->setInvalidDecl();
13009 return true;
13010 }
13011
13012 // Target is not a function.
13013
13014 if (isa<TagDecl>(Target)) {
13015 // No conflict between a tag and a non-tag.
13016 if (!Tag) return false;
13017
13018 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
13019 Diag(Target->getLocation(), diag::note_using_decl_target);
13020 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
13021 BUD->setInvalidDecl();
13022 return true;
13023 }
13024
13025 // No conflict between a tag and a non-tag.
13026 if (!NonTag) return false;
13027
13028 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
13029 Diag(Target->getLocation(), diag::note_using_decl_target);
13030 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
13031 BUD->setInvalidDecl();
13032 return true;
13033}
13034
13035/// Determine whether a direct base class is a virtual base class.
13037 if (!Derived->getNumVBases())
13038 return false;
13039 for (auto &B : Derived->bases())
13040 if (B.getType()->getAsCXXRecordDecl() == Base)
13041 return B.isVirtual();
13042 llvm_unreachable("not a direct base class");
13043}
13044
13046 NamedDecl *Orig,
13047 UsingShadowDecl *PrevDecl) {
13048 // If we resolved to another shadow declaration, just coalesce them.
13049 NamedDecl *Target = Orig;
13051 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
13052 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
13053 }
13054
13055 NamedDecl *NonTemplateTarget = Target;
13056 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
13057 NonTemplateTarget = TargetTD->getTemplatedDecl();
13058
13059 UsingShadowDecl *Shadow;
13060 if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) {
13061 UsingDecl *Using = cast<UsingDecl>(BUD);
13062 bool IsVirtualBase =
13064 Using->getQualifier().getAsRecordDecl());
13066 Context, CurContext, Using->getLocation(), Using, Orig, IsVirtualBase);
13067 } else {
13069 Target->getDeclName(), BUD, Target);
13070 }
13071 BUD->addShadowDecl(Shadow);
13072
13073 Shadow->setAccess(BUD->getAccess());
13074 if (Orig->isInvalidDecl() || BUD->isInvalidDecl())
13075 Shadow->setInvalidDecl();
13076
13077 Shadow->setPreviousDecl(PrevDecl);
13078
13079 if (S)
13080 PushOnScopeChains(Shadow, S);
13081 else
13082 CurContext->addDecl(Shadow);
13083
13084
13085 return Shadow;
13086}
13087
13089 if (Shadow->getDeclName().getNameKind() ==
13091 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
13092
13093 // Remove it from the DeclContext...
13094 Shadow->getDeclContext()->removeDecl(Shadow);
13095
13096 // ...and the scope, if applicable...
13097 if (S) {
13098 S->RemoveDecl(Shadow);
13099 IdResolver.RemoveDecl(Shadow);
13100 }
13101
13102 // ...and the using decl.
13103 Shadow->getIntroducer()->removeShadowDecl(Shadow);
13104
13105 // TODO: complain somehow if Shadow was used. It shouldn't
13106 // be possible for this to happen, because...?
13107}
13108
13109/// Find the base specifier for a base class with the given type.
13111 QualType DesiredBase,
13112 bool &AnyDependentBases) {
13113 // Check whether the named type is a direct base class.
13114 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
13115 for (auto &Base : Derived->bases()) {
13116 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
13117 if (CanonicalDesiredBase == BaseType)
13118 return &Base;
13119 if (BaseType->isDependentType())
13120 AnyDependentBases = true;
13121 }
13122 return nullptr;
13123}
13124
13125namespace {
13126class UsingValidatorCCC final : public CorrectionCandidateCallback {
13127public:
13128 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
13129 NestedNameSpecifier NNS, CXXRecordDecl *RequireMemberOf)
13130 : HasTypenameKeyword(HasTypenameKeyword),
13131 IsInstantiation(IsInstantiation), OldNNS(NNS),
13132 RequireMemberOf(RequireMemberOf) {}
13133
13134 bool ValidateCandidate(const TypoCorrection &Candidate) override {
13135 NamedDecl *ND = Candidate.getCorrectionDecl();
13136
13137 // Keywords are not valid here.
13138 if (!ND || isa<NamespaceDecl>(ND))
13139 return false;
13140
13141 // Completely unqualified names are invalid for a 'using' declaration.
13142 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
13143 return false;
13144
13145 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
13146 // reject.
13147
13148 if (RequireMemberOf) {
13149 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
13150 if (FoundRecord && FoundRecord->isInjectedClassName()) {
13151 // No-one ever wants a using-declaration to name an injected-class-name
13152 // of a base class, unless they're declaring an inheriting constructor.
13153 ASTContext &Ctx = ND->getASTContext();
13154 if (!Ctx.getLangOpts().CPlusPlus11)
13155 return false;
13156 CanQualType FoundType = Ctx.getCanonicalTagType(FoundRecord);
13157
13158 // Check that the injected-class-name is named as a member of its own
13159 // type; we don't want to suggest 'using Derived::Base;', since that
13160 // means something else.
13161 NestedNameSpecifier Specifier = Candidate.WillReplaceSpecifier()
13162 ? Candidate.getCorrectionSpecifier()
13163 : OldNNS;
13164 if (Specifier.getKind() != NestedNameSpecifier::Kind::Type ||
13165 !Ctx.hasSameType(QualType(Specifier.getAsType(), 0), FoundType))
13166 return false;
13167
13168 // Check that this inheriting constructor declaration actually names a
13169 // direct base class of the current class.
13170 bool AnyDependentBases = false;
13171 if (!findDirectBaseWithType(RequireMemberOf,
13172 Ctx.getCanonicalTagType(FoundRecord),
13173 AnyDependentBases) &&
13174 !AnyDependentBases)
13175 return false;
13176 } else {
13177 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
13178 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
13179 return false;
13180
13181 // FIXME: Check that the base class member is accessible?
13182 }
13183 } else {
13184 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
13185 if (FoundRecord && FoundRecord->isInjectedClassName())
13186 return false;
13187 }
13188
13189 if (isa<TypeDecl>(ND))
13190 return HasTypenameKeyword || !IsInstantiation;
13191
13192 return !HasTypenameKeyword;
13193 }
13194
13195 std::unique_ptr<CorrectionCandidateCallback> clone() override {
13196 return std::make_unique<UsingValidatorCCC>(*this);
13197 }
13198
13199private:
13200 bool HasTypenameKeyword;
13201 bool IsInstantiation;
13202 NestedNameSpecifier OldNNS;
13203 CXXRecordDecl *RequireMemberOf;
13204};
13205} // end anonymous namespace
13206
13208 // It is really dumb that we have to do this.
13209 LookupResult::Filter F = Previous.makeFilter();
13210 while (F.hasNext()) {
13211 NamedDecl *D = F.next();
13212 if (!isDeclInScope(D, CurContext, S))
13213 F.erase();
13214 // If we found a local extern declaration that's not ordinarily visible,
13215 // and this declaration is being added to a non-block scope, ignore it.
13216 // We're only checking for scope conflicts here, not also for violations
13217 // of the linkage rules.
13218 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
13220 F.erase();
13221 }
13222 F.done();
13223}
13224
13226 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
13227 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
13228 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
13229 const ParsedAttributesView &AttrList, bool IsInstantiation,
13230 bool IsUsingIfExists) {
13231 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
13232 SourceLocation IdentLoc = NameInfo.getLoc();
13233 assert(IdentLoc.isValid() && "Invalid TargetName location.");
13234
13235 // FIXME: We ignore attributes for now.
13236
13237 // For an inheriting constructor declaration, the name of the using
13238 // declaration is the name of a constructor in this class, not in the
13239 // base class.
13240 DeclarationNameInfo UsingName = NameInfo;
13242 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
13243 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
13244 Context.getCanonicalTagType(RD)));
13245
13246 // Do the redeclaration lookup in the current scope.
13247 LookupResult Previous(*this, UsingName, LookupUsingDeclName,
13249 Previous.setHideTags(false);
13250 if (S) {
13251 LookupName(Previous, S);
13252
13254 } else {
13255 assert(IsInstantiation && "no scope in non-instantiation");
13256 if (CurContext->isRecord())
13258 else {
13259 // No redeclaration check is needed here; in non-member contexts we
13260 // diagnosed all possible conflicts with other using-declarations when
13261 // building the template:
13262 //
13263 // For a dependent non-type using declaration, the only valid case is
13264 // if we instantiate to a single enumerator. We check for conflicts
13265 // between shadow declarations we introduce, and we check in the template
13266 // definition for conflicts between a non-type using declaration and any
13267 // other declaration, which together covers all cases.
13268 //
13269 // A dependent typename using declaration will never successfully
13270 // instantiate, since it will always name a class member, so we reject
13271 // that in the template definition.
13272 }
13273 }
13274
13275 // Check for invalid redeclarations.
13276 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
13277 SS, IdentLoc, Previous))
13278 return nullptr;
13279
13280 // 'using_if_exists' doesn't make sense on an inherited constructor.
13281 if (IsUsingIfExists && UsingName.getName().getNameKind() ==
13283 Diag(UsingLoc, diag::err_using_if_exists_on_ctor);
13284 return nullptr;
13285 }
13286
13287 DeclContext *LookupContext = computeDeclContext(SS);
13289 if (!LookupContext || EllipsisLoc.isValid()) {
13290 NamedDecl *D;
13291 // Dependent scope, or an unexpanded pack
13292 if (!LookupContext && CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword,
13293 SS, NameInfo, IdentLoc))
13294 return nullptr;
13295
13296 if (Previous.isSingleResult() &&
13297 Previous.getFoundDecl()->isTemplateParameter())
13298 DiagnoseTemplateParameterShadow(IdentLoc, Previous.getFoundDecl());
13299
13300 if (HasTypenameKeyword) {
13301 // FIXME: not all declaration name kinds are legal here
13303 UsingLoc, TypenameLoc,
13304 QualifierLoc,
13305 IdentLoc, NameInfo.getName(),
13306 EllipsisLoc);
13307 } else {
13309 QualifierLoc, NameInfo, EllipsisLoc);
13310 }
13311 D->setAccess(AS);
13312 CurContext->addDecl(D);
13313 ProcessDeclAttributeList(S, D, AttrList);
13314 return D;
13315 }
13316
13317 auto Build = [&](bool Invalid) {
13318 UsingDecl *UD =
13319 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
13320 UsingName, HasTypenameKeyword);
13321 UD->setAccess(AS);
13322 CurContext->addDecl(UD);
13323 ProcessDeclAttributeList(S, UD, AttrList);
13325 return UD;
13326 };
13327 auto BuildInvalid = [&]{ return Build(true); };
13328 auto BuildValid = [&]{ return Build(false); };
13329
13330 if (RequireCompleteDeclContext(SS, LookupContext))
13331 return BuildInvalid();
13332
13333 // Look up the target name.
13334 LookupResult R(*this, NameInfo, LookupOrdinaryName);
13335
13336 // Unlike most lookups, we don't always want to hide tag
13337 // declarations: tag names are visible through the using declaration
13338 // even if hidden by ordinary names, *except* in a dependent context
13339 // where they may be used by two-phase lookup.
13340 if (!IsInstantiation)
13341 R.setHideTags(false);
13342
13343 // For the purposes of this lookup, we have a base object type
13344 // equal to that of the current context.
13345 if (CurContext->isRecord()) {
13346 R.setBaseObjectType(
13347 Context.getCanonicalTagType(cast<CXXRecordDecl>(CurContext)));
13348 }
13349
13350 LookupQualifiedName(R, LookupContext);
13351
13352 // Validate the context, now we have a lookup
13353 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
13354 IdentLoc, &R))
13355 return nullptr;
13356
13357 if (R.empty() && IsUsingIfExists)
13359 UsingName.getName()),
13360 AS_public);
13361
13362 // Try to correct typos if possible. If constructor name lookup finds no
13363 // results, that means the named class has no explicit constructors, and we
13364 // suppressed declaring implicit ones (probably because it's dependent or
13365 // invalid).
13366 if (R.empty() &&
13368 // HACK 2017-01-08: Work around an issue with libstdc++'s detection of
13369 // ::gets. Sometimes it believes that glibc provides a ::gets in cases where
13370 // it does not. The issue was fixed in libstdc++ 6.3 (2016-12-21) and later.
13371 auto *II = NameInfo.getName().getAsIdentifierInfo();
13372 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
13373 CurContext->isStdNamespace() &&
13374 isa<TranslationUnitDecl>(LookupContext) &&
13375 PP.NeedsStdLibCxxWorkaroundBefore(2016'12'21) &&
13376 getSourceManager().isInSystemHeader(UsingLoc))
13377 return nullptr;
13378 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
13379 dyn_cast<CXXRecordDecl>(CurContext));
13380 if (TypoCorrection Corrected =
13381 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
13383 // We reject candidates where DroppedSpecifier == true, hence the
13384 // literal '0' below.
13385 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
13386 << NameInfo.getName() << LookupContext << 0
13387 << SS.getRange());
13388
13389 // If we picked a correction with no attached Decl we can't do anything
13390 // useful with it, bail out.
13391 NamedDecl *ND = Corrected.getCorrectionDecl();
13392 if (!ND)
13393 return BuildInvalid();
13394
13395 // If we corrected to an inheriting constructor, handle it as one.
13396 auto *RD = dyn_cast<CXXRecordDecl>(ND);
13397 if (RD && RD->isInjectedClassName()) {
13398 // The parent of the injected class name is the class itself.
13399 RD = cast<CXXRecordDecl>(RD->getParent());
13400
13401 // Fix up the information we'll use to build the using declaration.
13402 if (Corrected.WillReplaceSpecifier()) {
13404 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
13405 QualifierLoc.getSourceRange());
13406 QualifierLoc = Builder.getWithLocInContext(Context);
13407 }
13408
13409 // In this case, the name we introduce is the name of a derived class
13410 // constructor.
13411 auto *CurClass = cast<CXXRecordDecl>(CurContext);
13412 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
13413 Context.getCanonicalTagType(CurClass)));
13414 UsingName.setNamedTypeInfo(nullptr);
13415 for (auto *Ctor : LookupConstructors(RD))
13416 R.addDecl(Ctor);
13417 R.resolveKind();
13418 } else {
13419 // FIXME: Pick up all the declarations if we found an overloaded
13420 // function.
13421 UsingName.setName(ND->getDeclName());
13422 R.addDecl(ND);
13423 }
13424 } else {
13425 Diag(IdentLoc, diag::err_no_member)
13426 << NameInfo.getName() << LookupContext << SS.getRange();
13427 return BuildInvalid();
13428 }
13429 }
13430
13431 if (R.isAmbiguous())
13432 return BuildInvalid();
13433
13434 if (HasTypenameKeyword) {
13435 // If we asked for a typename and got a non-type decl, error out.
13436 if (!R.getAsSingle<TypeDecl>() &&
13437 !R.getAsSingle<UnresolvedUsingIfExistsDecl>()) {
13438 Diag(IdentLoc, diag::err_using_typename_non_type);
13439 for (const NamedDecl *D : R)
13440 Diag(D->getUnderlyingDecl()->getLocation(),
13441 diag::note_using_decl_target);
13442 return BuildInvalid();
13443 }
13444 } else {
13445 // If we asked for a non-typename and we got a type, error out,
13446 // but only if this is an instantiation of an unresolved using
13447 // decl. Otherwise just silently find the type name.
13448 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
13449 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
13450 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
13451 return BuildInvalid();
13452 }
13453 }
13454
13455 // C++14 [namespace.udecl]p6:
13456 // A using-declaration shall not name a namespace.
13457 if (R.getAsSingle<NamespaceDecl>()) {
13458 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
13459 << SS.getRange();
13460 // Suggest using 'using namespace ...' instead.
13461 Diag(SS.getBeginLoc(), diag::note_namespace_using_decl)
13462 << FixItHint::CreateInsertion(SS.getBeginLoc(), "namespace ");
13463 return BuildInvalid();
13464 }
13465
13466 UsingDecl *UD = BuildValid();
13467
13468 // Some additional rules apply to inheriting constructors.
13469 if (UsingName.getName().getNameKind() ==
13471 // Suppress access diagnostics; the access check is instead performed at the
13472 // point of use for an inheriting constructor.
13473 R.suppressDiagnostics();
13475 return UD;
13476 }
13477
13478 for (NamedDecl *D : R) {
13479 UsingShadowDecl *PrevDecl = nullptr;
13480 if (!CheckUsingShadowDecl(UD, D, Previous, PrevDecl))
13481 BuildUsingShadowDecl(S, UD, D, PrevDecl);
13482 }
13483
13484 return UD;
13485}
13486
13488 SourceLocation UsingLoc,
13489 SourceLocation EnumLoc,
13490 SourceLocation NameLoc,
13491 TypeSourceInfo *EnumType,
13492 EnumDecl *ED) {
13493 bool Invalid = false;
13494
13495 if (CurContext->getRedeclContext()->isRecord()) {
13496 /// In class scope, check if this is a duplicate, for better a diagnostic.
13497 DeclarationNameInfo UsingEnumName(ED->getDeclName(), NameLoc);
13498 LookupResult Previous(*this, UsingEnumName, LookupUsingDeclName,
13500
13502
13503 for (NamedDecl *D : Previous)
13504 if (UsingEnumDecl *UED = dyn_cast<UsingEnumDecl>(D))
13505 if (UED->getEnumDecl() == ED) {
13506 Diag(UsingLoc, diag::err_using_enum_decl_redeclaration)
13507 << SourceRange(EnumLoc, NameLoc);
13508 Diag(D->getLocation(), diag::note_using_enum_decl) << 1;
13509 Invalid = true;
13510 break;
13511 }
13512 }
13513
13514 if (RequireCompleteEnumDecl(ED, NameLoc))
13515 Invalid = true;
13516
13518 EnumLoc, NameLoc, EnumType);
13519 UD->setAccess(AS);
13520 CurContext->addDecl(UD);
13521
13522 if (Invalid) {
13523 UD->setInvalidDecl();
13524 return UD;
13525 }
13526
13527 // Create the shadow decls for each enumerator
13528 for (EnumConstantDecl *EC : ED->enumerators()) {
13529 UsingShadowDecl *PrevDecl = nullptr;
13530 DeclarationNameInfo DNI(EC->getDeclName(), EC->getLocation());
13533 LookupName(Previous, S);
13535
13536 if (!CheckUsingShadowDecl(UD, EC, Previous, PrevDecl))
13537 BuildUsingShadowDecl(S, UD, EC, PrevDecl);
13538 }
13539
13540 return UD;
13541}
13542
13544 ArrayRef<NamedDecl *> Expansions) {
13545 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
13546 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
13547 isa<UsingPackDecl>(InstantiatedFrom));
13548
13549 auto *UPD =
13550 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
13551 UPD->setAccess(InstantiatedFrom->getAccess());
13552 CurContext->addDecl(UPD);
13553 return UPD;
13554}
13555
13557 assert(!UD->hasTypename() && "expecting a constructor name");
13558
13559 QualType SourceType(UD->getQualifier().getAsType(), 0);
13561
13562 // Check whether the named type is a direct base class.
13563 bool AnyDependentBases = false;
13564 auto *Base =
13565 findDirectBaseWithType(TargetClass, SourceType, AnyDependentBases);
13566 if (!Base && !AnyDependentBases) {
13567 Diag(UD->getUsingLoc(), diag::err_using_decl_constructor_not_in_direct_base)
13568 << UD->getNameInfo().getSourceRange() << SourceType << TargetClass;
13569 UD->setInvalidDecl();
13570 return true;
13571 }
13572
13573 if (Base)
13574 Base->setInheritConstructors();
13575
13576 return false;
13577}
13578
13580 bool HasTypenameKeyword,
13581 const CXXScopeSpec &SS,
13582 SourceLocation NameLoc,
13583 const LookupResult &Prev) {
13584 NestedNameSpecifier Qual = SS.getScopeRep();
13585
13586 // C++03 [namespace.udecl]p8:
13587 // C++0x [namespace.udecl]p10:
13588 // A using-declaration is a declaration and can therefore be used
13589 // repeatedly where (and only where) multiple declarations are
13590 // allowed.
13591 //
13592 // That's in non-member contexts.
13593 if (!CurContext->getRedeclContext()->isRecord()) {
13594 // A dependent qualifier outside a class can only ever resolve to an
13595 // enumeration type. Therefore it conflicts with any other non-type
13596 // declaration in the same scope.
13597 // FIXME: How should we check for dependent type-type conflicts at block
13598 // scope?
13599 if (Qual.isDependent() && !HasTypenameKeyword) {
13600 for (auto *D : Prev) {
13601 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
13602 bool OldCouldBeEnumerator =
13604 Diag(NameLoc,
13605 OldCouldBeEnumerator ? diag::err_redefinition
13606 : diag::err_redefinition_different_kind)
13607 << Prev.getLookupName();
13608 Diag(D->getLocation(), diag::note_previous_definition);
13609 return true;
13610 }
13611 }
13612 }
13613 return false;
13614 }
13615
13616 NestedNameSpecifier CNNS = Qual.getCanonical();
13617 for (const NamedDecl *D : Prev) {
13618 bool DTypename;
13619 NestedNameSpecifier DQual = std::nullopt;
13620 if (const auto *UD = dyn_cast<UsingDecl>(D)) {
13621 DTypename = UD->hasTypename();
13622 DQual = UD->getQualifier();
13623 } else if (const auto *UD = dyn_cast<UnresolvedUsingValueDecl>(D)) {
13624 DTypename = false;
13625 DQual = UD->getQualifier();
13626 } else if (const auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
13627 DTypename = true;
13628 DQual = UD->getQualifier();
13629 } else
13630 continue;
13631
13632 // using decls differ if one says 'typename' and the other doesn't.
13633 // FIXME: non-dependent using decls?
13634 if (HasTypenameKeyword != DTypename) continue;
13635
13636 // using decls differ if they name different scopes (but note that
13637 // template instantiation can cause this check to trigger when it
13638 // didn't before instantiation).
13639 if (CNNS != DQual.getCanonical())
13640 continue;
13641
13642 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
13643 Diag(D->getLocation(), diag::note_using_decl) << 1;
13644 return true;
13645 }
13646
13647 return false;
13648}
13649
13650bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
13651 const CXXScopeSpec &SS,
13652 const DeclarationNameInfo &NameInfo,
13653 SourceLocation NameLoc,
13654 const LookupResult *R, const UsingDecl *UD) {
13655 DeclContext *NamedContext = computeDeclContext(SS);
13656 assert(bool(NamedContext) == (R || UD) && !(R && UD) &&
13657 "resolvable context must have exactly one set of decls");
13658
13659 // C++ 20 permits using an enumerator that does not have a class-hierarchy
13660 // relationship.
13661 bool Cxx20Enumerator = false;
13662 if (NamedContext) {
13663 EnumConstantDecl *EC = nullptr;
13664 if (R)
13665 EC = R->getAsSingle<EnumConstantDecl>();
13666 else if (UD && UD->shadow_size() == 1)
13667 EC = dyn_cast<EnumConstantDecl>(UD->shadow_begin()->getTargetDecl());
13668 if (EC)
13669 Cxx20Enumerator = getLangOpts().CPlusPlus20;
13670
13671 if (auto *ED = dyn_cast<EnumDecl>(NamedContext)) {
13672 // C++14 [namespace.udecl]p7:
13673 // A using-declaration shall not name a scoped enumerator.
13674 // C++20 p1099 permits enumerators.
13675 if (EC && R && ED->isScoped())
13676 DiagCompat(SS.getBeginLoc(), diag_compat::using_decl_scoped_enumerator)
13677 << SS.getRange();
13678
13679 // We want to consider the scope of the enumerator
13680 NamedContext = ED->getDeclContext();
13681 }
13682 }
13683
13684 if (!CurContext->isRecord()) {
13685 // C++03 [namespace.udecl]p3:
13686 // C++0x [namespace.udecl]p8:
13687 // A using-declaration for a class member shall be a member-declaration.
13688 // C++20 [namespace.udecl]p7
13689 // ... other than an enumerator ...
13690
13691 // If we weren't able to compute a valid scope, it might validly be a
13692 // dependent class or enumeration scope. If we have a 'typename' keyword,
13693 // the scope must resolve to a class type.
13694 if (NamedContext ? !NamedContext->getRedeclContext()->isRecord()
13695 : !HasTypename)
13696 return false; // OK
13697
13698 Diag(NameLoc,
13699 Cxx20Enumerator
13700 ? diag::warn_cxx17_compat_using_decl_class_member_enumerator
13701 : diag::err_using_decl_can_not_refer_to_class_member)
13702 << SS.getRange();
13703
13704 if (Cxx20Enumerator)
13705 return false; // OK
13706
13707 auto *RD = NamedContext
13708 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
13709 : nullptr;
13710 if (RD && !RequireCompleteDeclContext(const_cast<CXXScopeSpec &>(SS), RD)) {
13711 // See if there's a helpful fixit
13712
13713 if (!R) {
13714 // We will have already diagnosed the problem on the template
13715 // definition, Maybe we should do so again?
13716 } else if (R->getAsSingle<TypeDecl>()) {
13717 if (getLangOpts().CPlusPlus11) {
13718 // Convert 'using X::Y;' to 'using Y = X::Y;'.
13719 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
13720 << diag::MemClassWorkaround::AliasDecl
13722 NameInfo.getName().getAsString() +
13723 " = ");
13724 } else {
13725 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
13726 SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
13727 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
13728 << diag::MemClassWorkaround::TypedefDecl
13729 << FixItHint::CreateReplacement(UsingLoc, "typedef")
13731 InsertLoc, " " + NameInfo.getName().getAsString());
13732 }
13733 } else if (R->getAsSingle<VarDecl>()) {
13734 // Don't provide a fixit outside C++11 mode; we don't want to suggest
13735 // repeating the type of the static data member here.
13736 FixItHint FixIt;
13737 if (getLangOpts().CPlusPlus11) {
13738 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
13740 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
13741 }
13742
13743 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
13744 << diag::MemClassWorkaround::ReferenceDecl << FixIt;
13745 } else if (R->getAsSingle<EnumConstantDecl>()) {
13746 // Don't provide a fixit outside C++11 mode; we don't want to suggest
13747 // repeating the type of the enumeration here, and we can't do so if
13748 // the type is anonymous.
13749 FixItHint FixIt;
13750 if (getLangOpts().CPlusPlus11) {
13751 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
13753 UsingLoc,
13754 "constexpr auto " + NameInfo.getName().getAsString() + " = ");
13755 }
13756
13757 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
13758 << (getLangOpts().CPlusPlus11
13759 ? diag::MemClassWorkaround::ConstexprVar
13760 : diag::MemClassWorkaround::ConstVar)
13761 << FixIt;
13762 }
13763 }
13764
13765 return true; // Fail
13766 }
13767
13768 // If the named context is dependent, we can't decide much.
13769 if (!NamedContext) {
13770 // FIXME: in C++0x, we can diagnose if we can prove that the
13771 // nested-name-specifier does not refer to a base class, which is
13772 // still possible in some cases.
13773
13774 // Otherwise we have to conservatively report that things might be
13775 // okay.
13776 return false;
13777 }
13778
13779 // The current scope is a record.
13780 if (!NamedContext->isRecord()) {
13781 // Ideally this would point at the last name in the specifier,
13782 // but we don't have that level of source info.
13783 Diag(SS.getBeginLoc(),
13784 Cxx20Enumerator
13785 ? diag::warn_cxx17_compat_using_decl_non_member_enumerator
13786 : diag::err_using_decl_nested_name_specifier_is_not_class)
13787 << SS.getScopeRep() << SS.getRange();
13788
13789 if (Cxx20Enumerator)
13790 return false; // OK
13791
13792 return true;
13793 }
13794
13795 if (!NamedContext->isDependentContext() &&
13796 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
13797 return true;
13798
13799 // C++26 [namespace.udecl]p3:
13800 // In a using-declaration used as a member-declaration, each
13801 // using-declarator shall either name an enumerator or have a
13802 // nested-name-specifier naming a base class of the current class
13803 // ([expr.prim.this]). ...
13804 // "have a nested-name-specifier naming a base class of the current class"
13805 // was introduced by CWG400.
13806
13809
13810 if (Cxx20Enumerator) {
13811 Diag(NameLoc, diag::warn_cxx17_compat_using_decl_non_member_enumerator)
13812 << SS.getScopeRep() << SS.getRange();
13813 return false;
13814 }
13815
13816 if (CurContext == NamedContext) {
13817 Diag(SS.getBeginLoc(),
13818 diag::err_using_decl_nested_name_specifier_is_current_class)
13819 << SS.getRange();
13820 return true;
13821 }
13822
13823 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
13824 Diag(SS.getBeginLoc(),
13825 diag::err_using_decl_nested_name_specifier_is_not_base_class)
13827 << SS.getRange();
13828 }
13829 return true;
13830 }
13831
13832 return false;
13833}
13834
13836 MultiTemplateParamsArg TemplateParamLists,
13837 SourceLocation UsingLoc, UnqualifiedId &Name,
13838 const ParsedAttributesView &AttrList,
13839 TypeResult Type, Decl *DeclFromDeclSpec) {
13840
13841 if (Type.isInvalid())
13842 return nullptr;
13843
13844 bool Invalid = false;
13846 TypeSourceInfo *TInfo = nullptr;
13847 GetTypeFromParser(Type.get(), &TInfo);
13848
13849 if (DiagnoseClassNameShadow(CurContext, NameInfo))
13850 return nullptr;
13851
13854 Invalid = true;
13855 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
13856 TInfo->getTypeLoc().getBeginLoc());
13857 }
13858
13859 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
13860 TemplateParamLists.size()
13863 LookupName(Previous, S);
13864
13865 // Warn about shadowing the name of a template parameter.
13866 if (Previous.isSingleResult() &&
13867 Previous.getFoundDecl()->isTemplateParameter()) {
13869 Previous.clear();
13870 }
13871
13872 assert(Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
13873 "name in alias declaration must be an identifier");
13875 Name.StartLocation,
13876 Name.Identifier, TInfo);
13877
13878 NewTD->setAccess(AS);
13879
13880 if (Invalid)
13881 NewTD->setInvalidDecl();
13882
13883 ProcessDeclAttributeList(S, NewTD, AttrList);
13884 AddPragmaAttributes(S, NewTD);
13885 ProcessAPINotes(NewTD);
13886
13888 Invalid |= NewTD->isInvalidDecl();
13889
13890 // Get the innermost enclosing declaration scope.
13891 S = S->getDeclParent();
13892
13893 bool Redeclaration = false;
13894
13895 NamedDecl *NewND;
13896 if (TemplateParamLists.size()) {
13897 TypeAliasTemplateDecl *OldDecl = nullptr;
13898 TemplateParameterList *OldTemplateParams = nullptr;
13899
13900 TemplateParameterList *TemplateParams = TemplateParamLists[0];
13901 if (TemplateParamLists.size() != 1) {
13902 Diag(UsingLoc, diag::err_alias_template_extra_headers)
13903 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
13904 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
13905 Invalid = true;
13906
13907 // Recover by picking the last non-empty template parameter list.
13908 auto It = llvm::find_if(
13909 llvm::reverse(TemplateParamLists),
13910 [](TemplateParameterList *TPL) { return !TPL->empty(); });
13911 assert(It != TemplateParamLists.rend() &&
13912 "if all template parameter lists were empty, this should have "
13913 "been rejected as an explicit specialization");
13914 TemplateParams = *It;
13915 }
13916
13917 // Check that we can declare a template here.
13918 if (CheckTemplateDeclScope(S, TemplateParams))
13919 return nullptr;
13920
13921 // Only consider previous declarations in the same scope.
13922 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
13923 /*ExplicitInstantiationOrSpecialization*/false);
13924 if (!Previous.empty()) {
13925 Redeclaration = true;
13926
13927 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
13928 if (!OldDecl && !Invalid) {
13929 Diag(UsingLoc, diag::err_redefinition_different_kind)
13930 << Name.Identifier;
13931
13932 NamedDecl *OldD = Previous.getRepresentativeDecl();
13933 if (OldD->getLocation().isValid())
13934 Diag(OldD->getLocation(), diag::note_previous_definition);
13935
13936 Invalid = true;
13937 }
13938
13939 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
13940 if (TemplateParameterListsAreEqual(TemplateParams,
13941 OldDecl->getTemplateParameters(),
13942 /*Complain=*/true,
13944 OldTemplateParams =
13946 else
13947 Invalid = true;
13948
13949 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
13950 if (!Invalid &&
13951 !Context.hasSameType(OldTD->getUnderlyingType(),
13952 NewTD->getUnderlyingType())) {
13953 // FIXME: The C++0x standard does not clearly say this is ill-formed,
13954 // but we can't reasonably accept it.
13955 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
13956 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
13957 if (OldTD->getLocation().isValid())
13958 Diag(OldTD->getLocation(), diag::note_previous_definition);
13959 Invalid = true;
13960 }
13961 }
13962 }
13963
13964 // Merge any previous default template arguments into our parameters,
13965 // and check the parameter list.
13966 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
13967 TPC_Other))
13968 return nullptr;
13969
13970 TypeAliasTemplateDecl *NewDecl =
13972 Name.Identifier, TemplateParams,
13973 NewTD);
13974 NewTD->setDescribedAliasTemplate(NewDecl);
13975
13976 NewDecl->setAccess(AS);
13977
13978 if (Invalid)
13979 NewDecl->setInvalidDecl();
13980 else if (OldDecl) {
13981 NewDecl->setPreviousDecl(OldDecl);
13982 CheckRedeclarationInModule(NewDecl, OldDecl);
13983 }
13984
13985 NewND = NewDecl;
13986 } else {
13987 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
13989 handleTagNumbering(TD, S);
13990 }
13992 NewND = NewTD;
13993 }
13994
13995 PushOnScopeChains(NewND, S);
13996 ActOnDocumentableDecl(NewND);
13997 return NewND;
13998}
13999
14001 SourceLocation AliasLoc,
14002 IdentifierInfo *Alias, CXXScopeSpec &SS,
14003 SourceLocation IdentLoc,
14004 IdentifierInfo *Ident) {
14005
14006 // Lookup the namespace name.
14007 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
14008 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
14009
14010 if (R.isAmbiguous())
14011 return nullptr;
14012
14013 if (R.empty()) {
14014 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
14015 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
14016 return nullptr;
14017 }
14018 }
14019 assert(!R.isAmbiguous() && !R.empty());
14020 auto *ND = cast<NamespaceBaseDecl>(R.getRepresentativeDecl());
14021
14022 // Check if we have a previous declaration with the same name.
14023 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
14025 LookupName(PrevR, S);
14026
14027 // Check we're not shadowing a template parameter.
14028 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
14030 PrevR.clear();
14031 }
14032
14033 // Filter out any other lookup result from an enclosing scope.
14034 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
14035 /*AllowInlineNamespace*/false);
14036
14037 // Find the previous declaration and check that we can redeclare it.
14038 NamespaceAliasDecl *Prev = nullptr;
14039 if (PrevR.isSingleResult()) {
14040 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
14041 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
14042 // We already have an alias with the same name that points to the same
14043 // namespace; check that it matches.
14044 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
14045 Prev = AD;
14046 } else if (isVisible(PrevDecl)) {
14047 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
14048 << Alias;
14049 Diag(AD->getLocation(), diag::note_previous_namespace_alias)
14050 << AD->getNamespace();
14051 return nullptr;
14052 }
14053 } else if (isVisible(PrevDecl)) {
14054 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
14055 ? diag::err_redefinition
14056 : diag::err_redefinition_different_kind;
14057 Diag(AliasLoc, DiagID) << Alias;
14058 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
14059 return nullptr;
14060 }
14061 }
14062
14063 // The use of a nested name specifier may trigger deprecation warnings.
14064 DiagnoseUseOfDecl(ND, IdentLoc);
14065
14067 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
14068 Alias, SS.getWithLocInContext(Context),
14069 IdentLoc, ND);
14070 if (Prev)
14071 AliasDecl->setPreviousDecl(Prev);
14072
14074 return AliasDecl;
14075}
14076
14077namespace {
14078struct SpecialMemberExceptionSpecInfo
14079 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
14080 SourceLocation Loc;
14082
14083 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
14086 SourceLocation Loc)
14087 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
14088
14089 bool visitBase(CXXBaseSpecifier *Base);
14090 bool visitField(FieldDecl *FD);
14091
14092 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
14093 unsigned Quals);
14094
14095 void visitSubobjectCall(Subobject Subobj,
14097};
14098}
14099
14100bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
14101 auto *BaseClass = Base->getType()->getAsCXXRecordDecl();
14102 if (!BaseClass)
14103 return false;
14104
14105 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
14106 if (auto *BaseCtor = SMOR.getMethod()) {
14107 visitSubobjectCall(Base, BaseCtor);
14108 return false;
14109 }
14110
14111 visitClassSubobject(BaseClass, Base, 0);
14112 return false;
14113}
14114
14115bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
14116 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
14117 FD->hasInClassInitializer()) {
14118 Expr *E = FD->getInClassInitializer();
14119 if (!E)
14120 // FIXME: It's a little wasteful to build and throw away a
14121 // CXXDefaultInitExpr here.
14122 // FIXME: We should have a single context note pointing at Loc, and
14123 // this location should be MD->getLocation() instead, since that's
14124 // the location where we actually use the default init expression.
14125 E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
14126 if (E)
14127 ExceptSpec.CalledExpr(E);
14128 } else if (auto *RD = S.Context.getBaseElementType(FD->getType())
14129 ->getAsCXXRecordDecl()) {
14130 visitClassSubobject(RD, FD, FD->getType().getCVRQualifiers());
14131 }
14132 return false;
14133}
14134
14135void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
14136 Subobject Subobj,
14137 unsigned Quals) {
14138 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
14139 bool IsMutable = Field && Field->isMutable();
14140 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
14141}
14142
14143void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
14144 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
14145 // Note, if lookup fails, it doesn't matter what exception specification we
14146 // choose because the special member will be deleted.
14147 if (CXXMethodDecl *MD = SMOR.getMethod())
14148 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
14149}
14150
14152 llvm::APSInt Result;
14154 ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEKind::ExplicitBool);
14155 ExplicitSpec.setExpr(Converted.get());
14156 if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
14157 ExplicitSpec.setKind(Result.getBoolValue()
14160 return true;
14161 }
14163 return false;
14164}
14165
14168 if (!ExplicitExpr->isTypeDependent())
14170 return ES;
14171}
14172
14177 ComputingExceptionSpec CES(S, MD, Loc);
14178
14179 CXXRecordDecl *ClassDecl = MD->getParent();
14180
14181 // C++ [except.spec]p14:
14182 // An implicitly declared special member function (Clause 12) shall have an
14183 // exception-specification. [...]
14184 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
14185 if (ClassDecl->isInvalidDecl())
14186 return Info.ExceptSpec;
14187
14188 // FIXME: If this diagnostic fires, we're probably missing a check for
14189 // attempting to resolve an exception specification before it's known
14190 // at a higher level.
14191 if (S.RequireCompleteType(MD->getLocation(),
14192 S.Context.getCanonicalTagType(ClassDecl),
14193 diag::err_exception_spec_incomplete_type))
14194 return Info.ExceptSpec;
14195
14196 // C++1z [except.spec]p7:
14197 // [Look for exceptions thrown by] a constructor selected [...] to
14198 // initialize a potentially constructed subobject,
14199 // C++1z [except.spec]p8:
14200 // The exception specification for an implicitly-declared destructor, or a
14201 // destructor without a noexcept-specifier, is potentially-throwing if and
14202 // only if any of the destructors for any of its potentially constructed
14203 // subojects is potentially throwing.
14204 // FIXME: We respect the first rule but ignore the "potentially constructed"
14205 // in the second rule to resolve a core issue (no number yet) that would have
14206 // us reject:
14207 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
14208 // struct B : A {};
14209 // struct C : B { void f(); };
14210 // ... due to giving B::~B() a non-throwing exception specification.
14211 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
14212 : Info.VisitAllBases);
14213
14214 return Info.ExceptSpec;
14215}
14216
14217namespace {
14218/// RAII object to register a special member as being currently declared.
14219struct DeclaringSpecialMember {
14220 Sema &S;
14222 Sema::ContextRAII SavedContext;
14223 bool WasAlreadyBeingDeclared;
14224
14225 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, CXXSpecialMemberKind CSM)
14226 : S(S), D(RD, CSM), SavedContext(S, RD) {
14227 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
14228 if (WasAlreadyBeingDeclared)
14229 // This almost never happens, but if it does, ensure that our cache
14230 // doesn't contain a stale result.
14231 S.SpecialMemberCache.clear();
14232 else {
14233 // Register a note to be produced if we encounter an error while
14234 // declaring the special member.
14235 Sema::CodeSynthesisContext Ctx;
14236 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
14237 // FIXME: We don't have a location to use here. Using the class's
14238 // location maintains the fiction that we declare all special members
14239 // with the class, but (1) it's not clear that lying about that helps our
14240 // users understand what's going on, and (2) there may be outer contexts
14241 // on the stack (some of which are relevant) and printing them exposes
14242 // our lies.
14243 Ctx.PointOfInstantiation = RD->getLocation();
14244 Ctx.Entity = RD;
14245 Ctx.SpecialMember = CSM;
14246 S.pushCodeSynthesisContext(Ctx);
14247 }
14248 }
14249 ~DeclaringSpecialMember() {
14250 if (!WasAlreadyBeingDeclared) {
14251 S.SpecialMembersBeingDeclared.erase(D);
14253 }
14254 }
14255
14256 /// Are we already trying to declare this special member?
14257 bool isAlreadyBeingDeclared() const {
14258 return WasAlreadyBeingDeclared;
14259 }
14260};
14261}
14262
14264 // Look up any existing declarations, but don't trigger declaration of all
14265 // implicit special members with this name.
14266 DeclarationName Name = FD->getDeclName();
14269 for (auto *D : FD->getParent()->lookup(Name))
14270 if (auto *Acceptable = R.getAcceptableDecl(D))
14271 R.addDecl(Acceptable);
14272 R.resolveKind();
14273 R.suppressDiagnostics();
14274
14275 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/ false,
14277}
14278
14279void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
14280 QualType ResultTy,
14281 ArrayRef<QualType> Args) {
14282 // Build an exception specification pointing back at this constructor.
14284
14285 LangAS AS = getDefaultCXXMethodAddrSpace();
14286 if (AS != LangAS::Default) {
14287 EPI.TypeQuals.addAddressSpace(AS);
14288 }
14289
14290 auto QT = Context.getFunctionType(ResultTy, Args, EPI);
14291 SpecialMem->setType(QT);
14292
14293 // During template instantiation of implicit special member functions we need
14294 // a reliable TypeSourceInfo for the function prototype in order to allow
14295 // functions to be substituted.
14296 if (inTemplateInstantiation() && isLambdaMethod(SpecialMem)) {
14297 TypeSourceInfo *TSI =
14298 Context.getTrivialTypeSourceInfo(SpecialMem->getType());
14299 SpecialMem->setTypeSourceInfo(TSI);
14300 }
14301}
14302
14304 CXXRecordDecl *ClassDecl) {
14305 // C++ [class.ctor]p5:
14306 // A default constructor for a class X is a constructor of class X
14307 // that can be called without an argument. If there is no
14308 // user-declared constructor for class X, a default constructor is
14309 // implicitly declared. An implicitly-declared default constructor
14310 // is an inline public member of its class.
14311 assert(ClassDecl->needsImplicitDefaultConstructor() &&
14312 "Should not build implicit default constructor!");
14313
14314 DeclaringSpecialMember DSM(*this, ClassDecl,
14316 if (DSM.isAlreadyBeingDeclared())
14317 return nullptr;
14318
14320 *this, ClassDecl, CXXSpecialMemberKind::DefaultConstructor, false);
14321
14322 // Create the actual constructor declaration.
14323 CanQualType ClassType = Context.getCanonicalTagType(ClassDecl);
14324 SourceLocation ClassLoc = ClassDecl->getLocation();
14325 DeclarationName Name
14326 = Context.DeclarationNames.getCXXConstructorName(ClassType);
14327 DeclarationNameInfo NameInfo(Name, ClassLoc);
14329 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),
14330 /*TInfo=*/nullptr, ExplicitSpecifier(),
14331 getCurFPFeatures().isFPConstrained(),
14332 /*isInline=*/true, /*isImplicitlyDeclared=*/true,
14335 DefaultCon->setAccess(AS_public);
14336 DefaultCon->setDefaulted();
14337
14338 setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, {});
14339
14340 if (getLangOpts().CUDA)
14341 CUDA().inferTargetForImplicitSpecialMember(
14342 ClassDecl, CXXSpecialMemberKind::DefaultConstructor, DefaultCon,
14343 /* ConstRHS */ false,
14344 /* Diagnose */ false);
14345
14346 // We don't need to use SpecialMemberIsTrivial here; triviality for default
14347 // constructors is easy to compute.
14348 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
14349
14350 // Note that we have declared this constructor.
14351 ++getASTContext().NumImplicitDefaultConstructorsDeclared;
14352
14353 Scope *S = getScopeForContext(ClassDecl);
14355
14356 if (ShouldDeleteSpecialMember(DefaultCon,
14358 SetDeclDeleted(DefaultCon, ClassLoc);
14359
14360 if (S)
14361 PushOnScopeChains(DefaultCon, S, false);
14362 ClassDecl->addDecl(DefaultCon);
14363
14364 return DefaultCon;
14365}
14366
14369 DefaultedFunctionFPFeaturesRAII RestoreFP(*this, Constructor);
14370 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
14371 !Constructor->doesThisDeclarationHaveABody() &&
14372 !Constructor->isDeleted()) &&
14373 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
14374 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
14375 return;
14376
14377 CXXRecordDecl *ClassDecl = Constructor->getParent();
14378 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
14379 if (ClassDecl->isInvalidDecl()) {
14380 return;
14381 }
14382
14384
14385 // The exception specification is needed because we are defining the
14386 // function.
14387 ResolveExceptionSpec(CurrentLocation,
14388 Constructor->getType()->castAs<FunctionProtoType>());
14389 MarkVTableUsed(CurrentLocation, ClassDecl);
14390
14391 // Add a context note for diagnostics produced after this point.
14392 Scope.addContextNote(CurrentLocation);
14393
14394 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
14395 Constructor->setInvalidDecl();
14396 return;
14397 }
14398
14399 SourceLocation Loc = Constructor->getEndLoc().isValid()
14400 ? Constructor->getEndLoc()
14401 : Constructor->getLocation();
14402 Constructor->setBody(new (Context) CompoundStmt(Loc));
14403 Constructor->markUsed(Context);
14404
14406 L->CompletedImplicitDefinition(Constructor);
14407 }
14408
14409 DiagnoseUninitializedFields(*this, Constructor);
14410
14411 // The synthesized body applies the class's NSDMIs and never reaches the
14412 // normal IssueWarnings path, so run lifetime safety on it here.
14413 AnalysisWarnings.IssueWarningsForImplicitFunction(Constructor);
14414}
14415
14417 // Perform any delayed checks on exception specifications.
14419}
14420
14421/// Find or create the fake constructor we synthesize to model constructing an
14422/// object of a derived class via a constructor of a base class.
14425 CXXConstructorDecl *BaseCtor,
14427 CXXRecordDecl *Derived = Shadow->getParent();
14428 SourceLocation UsingLoc = Shadow->getLocation();
14429
14430 // FIXME: Add a new kind of DeclarationName for an inherited constructor.
14431 // For now we use the name of the base class constructor as a member of the
14432 // derived class to indicate a (fake) inherited constructor name.
14433 DeclarationName Name = BaseCtor->getDeclName();
14434
14435 // Check to see if we already have a fake constructor for this inherited
14436 // constructor call.
14437 for (NamedDecl *Ctor : Derived->lookup(Name))
14439 ->getInheritedConstructor()
14440 .getConstructor(),
14441 BaseCtor))
14442 return cast<CXXConstructorDecl>(Ctor);
14443
14444 DeclarationNameInfo NameInfo(Name, UsingLoc);
14445 TypeSourceInfo *TInfo =
14446 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
14447 FunctionProtoTypeLoc ProtoLoc =
14449
14450 // Check the inherited constructor is valid and find the list of base classes
14451 // from which it was inherited.
14452 InheritedConstructorInfo ICI(*this, Loc, Shadow);
14453
14454 bool Constexpr = BaseCtor->isConstexpr() &&
14457 false, BaseCtor, &ICI);
14458
14460 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
14461 BaseCtor->getExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
14462 /*isInline=*/true,
14463 /*isImplicitlyDeclared=*/true,
14465 InheritedConstructor(Shadow, BaseCtor),
14466 BaseCtor->getTrailingRequiresClause());
14467 if (Shadow->isInvalidDecl())
14468 DerivedCtor->setInvalidDecl();
14469
14470 // Build an unevaluated exception specification for this fake constructor.
14471 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
14474 EPI.ExceptionSpec.SourceDecl = DerivedCtor;
14475 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
14476 FPT->getParamTypes(), EPI));
14477
14478 // Build the parameter declarations.
14480 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
14481 TypeSourceInfo *TInfo =
14482 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
14484 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
14485 FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr);
14486 PD->setScopeInfo(0, I);
14487 PD->setImplicit();
14488 // Ensure attributes are propagated onto parameters (this matters for
14489 // format, pass_object_size, ...).
14490 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
14491 ParamDecls.push_back(PD);
14492 ProtoLoc.setParam(I, PD);
14493 }
14494
14495 // Set up the new constructor.
14496 assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
14497 DerivedCtor->setAccess(BaseCtor->getAccess());
14498 DerivedCtor->setParams(ParamDecls);
14499 Derived->addDecl(DerivedCtor);
14500
14501 if (ShouldDeleteSpecialMember(DerivedCtor,
14503 SetDeclDeleted(DerivedCtor, UsingLoc);
14504
14505 return DerivedCtor;
14506}
14507
14515
14518 CXXRecordDecl *ClassDecl = Constructor->getParent();
14519 assert(Constructor->getInheritedConstructor() &&
14520 !Constructor->doesThisDeclarationHaveABody() &&
14521 !Constructor->isDeleted());
14522 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
14523 return;
14524
14525 // Initializations are performed "as if by a defaulted default constructor",
14526 // so enter the appropriate scope.
14528
14529 // The exception specification is needed because we are defining the
14530 // function.
14531 ResolveExceptionSpec(CurrentLocation,
14532 Constructor->getType()->castAs<FunctionProtoType>());
14533 MarkVTableUsed(CurrentLocation, ClassDecl);
14534
14535 // Add a context note for diagnostics produced after this point.
14536 Scope.addContextNote(CurrentLocation);
14537
14539 Constructor->getInheritedConstructor().getShadowDecl();
14540 CXXConstructorDecl *InheritedCtor =
14541 Constructor->getInheritedConstructor().getConstructor();
14542
14543 // [class.inhctor.init]p1:
14544 // initialization proceeds as if a defaulted default constructor is used to
14545 // initialize the D object and each base class subobject from which the
14546 // constructor was inherited
14547
14548 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
14549 CXXRecordDecl *RD = Shadow->getParent();
14550 SourceLocation InitLoc = Shadow->getLocation();
14551
14552 // Build explicit initializers for all base classes from which the
14553 // constructor was inherited.
14555 for (bool VBase : {false, true}) {
14556 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
14557 if (B.isVirtual() != VBase)
14558 continue;
14559
14560 auto *BaseRD = B.getType()->getAsCXXRecordDecl();
14561 if (!BaseRD)
14562 continue;
14563
14564 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
14565 if (!BaseCtor.first)
14566 continue;
14567
14568 MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
14570 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
14571
14572 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
14573 Inits.push_back(new (Context) CXXCtorInitializer(
14574 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
14575 SourceLocation()));
14576 }
14577 }
14578
14579 // We now proceed as if for a defaulted default constructor, with the relevant
14580 // initializers replaced.
14581
14582 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
14583 Constructor->setInvalidDecl();
14584 return;
14585 }
14586
14587 Constructor->setBody(new (Context) CompoundStmt(InitLoc));
14588 Constructor->markUsed(Context);
14589
14591 L->CompletedImplicitDefinition(Constructor);
14592 }
14593
14594 DiagnoseUninitializedFields(*this, Constructor);
14595
14596 // The synthesized body applies the class's NSDMIs and never reaches the
14597 // normal IssueWarnings path, so run lifetime safety on it here.
14598 AnalysisWarnings.IssueWarningsForImplicitFunction(Constructor);
14599}
14600
14602 // C++ [class.dtor]p2:
14603 // If a class has no user-declared destructor, a destructor is
14604 // declared implicitly. An implicitly-declared destructor is an
14605 // inline public member of its class.
14606 assert(ClassDecl->needsImplicitDestructor());
14607
14608 DeclaringSpecialMember DSM(*this, ClassDecl,
14610 if (DSM.isAlreadyBeingDeclared())
14611 return nullptr;
14612
14614 *this, ClassDecl, CXXSpecialMemberKind::Destructor, false);
14615
14616 // Create the actual destructor declaration.
14617 CanQualType ClassType = Context.getCanonicalTagType(ClassDecl);
14618 SourceLocation ClassLoc = ClassDecl->getLocation();
14619 DeclarationName Name
14620 = Context.DeclarationNames.getCXXDestructorName(ClassType);
14621 DeclarationNameInfo NameInfo(Name, ClassLoc);
14623 Context, ClassDecl, ClassLoc, NameInfo, QualType(), nullptr,
14624 getCurFPFeatures().isFPConstrained(),
14625 /*isInline=*/true,
14626 /*isImplicitlyDeclared=*/true,
14629 Destructor->setAccess(AS_public);
14630 Destructor->setDefaulted();
14631
14632 setupImplicitSpecialMemberType(Destructor, Context.VoidTy, {});
14633
14634 if (getLangOpts().CUDA)
14635 CUDA().inferTargetForImplicitSpecialMember(
14637 /* ConstRHS */ false,
14638 /* Diagnose */ false);
14639
14640 // We don't need to use SpecialMemberIsTrivial here; triviality for
14641 // destructors is easy to compute.
14642 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
14643 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
14644 ClassDecl->hasTrivialDestructorForCall());
14645
14646 // Note that we have declared this destructor.
14647 ++getASTContext().NumImplicitDestructorsDeclared;
14648
14649 Scope *S = getScopeForContext(ClassDecl);
14651
14652 // We can't check whether an implicit destructor is deleted before we complete
14653 // the definition of the class, because its validity depends on the alignment
14654 // of the class. We'll check this from ActOnFields once the class is complete.
14655 if (ClassDecl->isCompleteDefinition() &&
14657 SetDeclDeleted(Destructor, ClassLoc);
14658
14659 // Introduce this destructor into its scope.
14660 if (S)
14661 PushOnScopeChains(Destructor, S, false);
14662 ClassDecl->addDecl(Destructor);
14663
14664 return Destructor;
14665}
14666
14669 DefaultedFunctionFPFeaturesRAII RestoreFP(*this, Destructor);
14670 assert((Destructor->isDefaulted() &&
14671 !Destructor->doesThisDeclarationHaveABody() &&
14672 !Destructor->isDeleted()) &&
14673 "DefineImplicitDestructor - call it for implicit default dtor");
14674 if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
14675 return;
14676
14677 CXXRecordDecl *ClassDecl = Destructor->getParent();
14678 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
14679
14681
14682 // The exception specification is needed because we are defining the
14683 // function.
14684 ResolveExceptionSpec(CurrentLocation,
14685 Destructor->getType()->castAs<FunctionProtoType>());
14686 MarkVTableUsed(CurrentLocation, ClassDecl);
14687
14688 // Add a context note for diagnostics produced after this point.
14689 Scope.addContextNote(CurrentLocation);
14690
14692 Destructor->getParent());
14693
14695 Destructor->setInvalidDecl();
14696 return;
14697 }
14698
14699 SourceLocation Loc = Destructor->getEndLoc().isValid()
14700 ? Destructor->getEndLoc()
14701 : Destructor->getLocation();
14702 Destructor->setBody(new (Context) CompoundStmt(Loc));
14703 Destructor->markUsed(Context);
14704
14706 L->CompletedImplicitDefinition(Destructor);
14707 }
14708}
14709
14712 if (Destructor->isInvalidDecl())
14713 return;
14714
14715 CXXRecordDecl *ClassDecl = Destructor->getParent();
14716 assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&
14717 "implicit complete dtors unneeded outside MS ABI");
14718 assert(ClassDecl->getNumVBases() > 0 &&
14719 "complete dtor only exists for classes with vbases");
14720
14722
14723 // Add a context note for diagnostics produced after this point.
14724 Scope.addContextNote(CurrentLocation);
14725
14726 MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl);
14727}
14728
14730 // If the context is an invalid C++ class, just suppress these checks.
14731 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
14732 if (Record->isInvalidDecl()) {
14735 return;
14736 }
14738 }
14739}
14740
14743
14744 if (!DelayedDllExportMemberFunctions.empty()) {
14746 std::swap(DelayedDllExportMemberFunctions, WorkList);
14747 for (CXXMethodDecl *M : WorkList) {
14748 DefineDefaultedFunction(*this, M, M->getLocation());
14749
14750 // Pass the method to the consumer to get emitted. This is not necessary
14751 // for explicit instantiation definitions, as they will get emitted
14752 // anyway.
14753 if (M->getParent()->getTemplateSpecializationKind() !=
14756 }
14757 }
14758}
14759
14761 if (!DelayedDllExportClasses.empty()) {
14762 // Calling ReferenceDllExportedMembers might cause the current function to
14763 // be called again, so use a local copy of DelayedDllExportClasses.
14765 std::swap(DelayedDllExportClasses, WorkList);
14766 for (CXXRecordDecl *Class : WorkList)
14768 }
14769}
14770
14772 assert(getLangOpts().CPlusPlus11 &&
14773 "adjusting dtor exception specs was introduced in c++11");
14774
14775 if (Destructor->isDependentContext())
14776 return;
14777
14778 // C++11 [class.dtor]p3:
14779 // A declaration of a destructor that does not have an exception-
14780 // specification is implicitly considered to have the same exception-
14781 // specification as an implicit declaration.
14782 const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>();
14783 if (DtorType->hasExceptionSpec())
14784 return;
14785
14786 // Replace the destructor's type, building off the existing one. Fortunately,
14787 // the only thing of interest in the destructor type is its extended info.
14788 // The return and arguments are fixed.
14789 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
14792 Destructor->setType(Context.getFunctionType(Context.VoidTy, {}, EPI));
14793
14794 // FIXME: If the destructor has a body that could throw, and the newly created
14795 // spec doesn't allow exceptions, we should emit a warning, because this
14796 // change in behavior can break conforming C++03 programs at runtime.
14797 // However, we don't have a body or an exception specification yet, so it
14798 // needs to be done somewhere else.
14799}
14800
14801namespace {
14802/// An abstract base class for all helper classes used in building the
14803// copy/move operators. These classes serve as factory functions and help us
14804// avoid using the same Expr* in the AST twice.
14805class ExprBuilder {
14806 ExprBuilder(const ExprBuilder&) = delete;
14807 ExprBuilder &operator=(const ExprBuilder&) = delete;
14808
14809protected:
14810 static Expr *assertNotNull(Expr *E) {
14811 assert(E && "Expression construction must not fail.");
14812 return E;
14813 }
14814
14815public:
14816 ExprBuilder() {}
14817 virtual ~ExprBuilder() {}
14818
14819 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
14820};
14821
14822class RefBuilder: public ExprBuilder {
14823 VarDecl *Var;
14824 QualType VarType;
14825
14826public:
14827 Expr *build(Sema &S, SourceLocation Loc) const override {
14828 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));
14829 }
14830
14831 RefBuilder(VarDecl *Var, QualType VarType)
14832 : Var(Var), VarType(VarType) {}
14833};
14834
14835class ThisBuilder: public ExprBuilder {
14836public:
14837 Expr *build(Sema &S, SourceLocation Loc) const override {
14838 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
14839 }
14840};
14841
14842class CastBuilder: public ExprBuilder {
14843 const ExprBuilder &Builder;
14844 QualType Type;
14846 const CXXCastPath &Path;
14847
14848public:
14849 Expr *build(Sema &S, SourceLocation Loc) const override {
14850 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
14851 CK_UncheckedDerivedToBase, Kind,
14852 &Path).get());
14853 }
14854
14855 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
14856 const CXXCastPath &Path)
14857 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
14858};
14859
14860class DerefBuilder: public ExprBuilder {
14861 const ExprBuilder &Builder;
14862
14863public:
14864 Expr *build(Sema &S, SourceLocation Loc) const override {
14865 return assertNotNull(
14866 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
14867 }
14868
14869 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14870};
14871
14872class MemberBuilder: public ExprBuilder {
14873 const ExprBuilder &Builder;
14874 QualType Type;
14875 CXXScopeSpec SS;
14876 bool IsArrow;
14877 LookupResult &MemberLookup;
14878
14879public:
14880 Expr *build(Sema &S, SourceLocation Loc) const override {
14881 return assertNotNull(S.BuildMemberReferenceExpr(
14882 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
14883 nullptr, MemberLookup, nullptr, nullptr).get());
14884 }
14885
14886 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
14887 LookupResult &MemberLookup)
14888 : Builder(Builder), Type(Type), IsArrow(IsArrow),
14889 MemberLookup(MemberLookup) {}
14890};
14891
14892class MoveCastBuilder: public ExprBuilder {
14893 const ExprBuilder &Builder;
14894
14895public:
14896 Expr *build(Sema &S, SourceLocation Loc) const override {
14897 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
14898 }
14899
14900 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14901};
14902
14903class LvalueConvBuilder: public ExprBuilder {
14904 const ExprBuilder &Builder;
14905
14906public:
14907 Expr *build(Sema &S, SourceLocation Loc) const override {
14908 return assertNotNull(
14909 S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
14910 }
14911
14912 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14913};
14914
14915class SubscriptBuilder: public ExprBuilder {
14916 const ExprBuilder &Base;
14917 const ExprBuilder &Index;
14918
14919public:
14920 Expr *build(Sema &S, SourceLocation Loc) const override {
14921 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
14922 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
14923 }
14924
14925 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
14926 : Base(Base), Index(Index) {}
14927};
14928
14929} // end anonymous namespace
14930
14931/// When generating a defaulted copy or move assignment operator, if a field
14932/// should be copied with __builtin_memcpy rather than via explicit assignments,
14933/// do so. This optimization only applies for arrays of scalars, and for arrays
14934/// of class type where the selected copy/move-assignment operator is trivial.
14935static StmtResult
14937 const ExprBuilder &ToB, const ExprBuilder &FromB) {
14938 // Compute the size of the memory buffer to be copied.
14939 QualType SizeType = S.Context.getSizeType();
14940 llvm::APInt Size(S.Context.getTypeSize(SizeType),
14942
14943 // Take the address of the field references for "from" and "to". We
14944 // directly construct UnaryOperators here because semantic analysis
14945 // does not permit us to take the address of an xvalue.
14946 Expr *From = FromB.build(S, Loc);
14947 From = UnaryOperator::Create(
14948 S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()),
14949 VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
14950 Expr *To = ToB.build(S, Loc);
14952 S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()),
14953 VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
14954
14955 bool NeedsCollectableMemCpy = false;
14956 if (auto *RD = T->getBaseElementTypeUnsafe()->getAsRecordDecl())
14957 NeedsCollectableMemCpy = RD->hasObjectMember();
14958
14959 // Create a reference to the __builtin_objc_memmove_collectable function
14960 StringRef MemCpyName = NeedsCollectableMemCpy ?
14961 "__builtin_objc_memmove_collectable" :
14962 "__builtin_memcpy";
14963 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
14965 S.LookupName(R, S.TUScope, true);
14966
14967 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
14968 if (!MemCpy)
14969 // Something went horribly wrong earlier, and we will have complained
14970 // about it.
14971 return StmtError();
14972
14973 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
14974 VK_PRValue, Loc, nullptr);
14975 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
14976
14977 Expr *CallArgs[] = {
14978 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
14979 };
14980 ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
14981 Loc, CallArgs, Loc);
14982
14983 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
14984 return Call.getAs<Stmt>();
14985}
14986
14987/// Builds a statement that copies/moves the given entity from \p From to
14988/// \c To.
14989///
14990/// This routine is used to copy/move the members of a class with an
14991/// implicitly-declared copy/move assignment operator. When the entities being
14992/// copied are arrays, this routine builds for loops to copy them.
14993///
14994/// \param S The Sema object used for type-checking.
14995///
14996/// \param Loc The location where the implicit copy/move is being generated.
14997///
14998/// \param T The type of the expressions being copied/moved. Both expressions
14999/// must have this type.
15000///
15001/// \param To The expression we are copying/moving to.
15002///
15003/// \param From The expression we are copying/moving from.
15004///
15005/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
15006/// Otherwise, it's a non-static member subobject.
15007///
15008/// \param Copying Whether we're copying or moving.
15009///
15010/// \param Depth Internal parameter recording the depth of the recursion.
15011///
15012/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
15013/// if a memcpy should be used instead.
15014static StmtResult
15016 const ExprBuilder &To, const ExprBuilder &From,
15017 bool CopyingBaseSubobject, bool Copying,
15018 unsigned Depth = 0) {
15019 // C++11 [class.copy]p28:
15020 // Each subobject is assigned in the manner appropriate to its type:
15021 //
15022 // - if the subobject is of class type, as if by a call to operator= with
15023 // the subobject as the object expression and the corresponding
15024 // subobject of x as a single function argument (as if by explicit
15025 // qualification; that is, ignoring any possible virtual overriding
15026 // functions in more derived classes);
15027 //
15028 // C++03 [class.copy]p13:
15029 // - if the subobject is of class type, the copy assignment operator for
15030 // the class is used (as if by explicit qualification; that is,
15031 // ignoring any possible virtual overriding functions in more derived
15032 // classes);
15033 if (auto *ClassDecl = T->getAsCXXRecordDecl()) {
15034 // Look for operator=.
15035 DeclarationName Name
15037 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
15038 S.LookupQualifiedName(OpLookup, ClassDecl, false);
15039
15040 // Prior to C++11, filter out any result that isn't a copy/move-assignment
15041 // operator.
15042 if (!S.getLangOpts().CPlusPlus11) {
15043 LookupResult::Filter F = OpLookup.makeFilter();
15044 while (F.hasNext()) {
15045 NamedDecl *D = F.next();
15046 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
15047 if (Method->isCopyAssignmentOperator() ||
15048 (!Copying && Method->isMoveAssignmentOperator()))
15049 continue;
15050
15051 F.erase();
15052 }
15053 F.done();
15054 }
15055
15056 // Suppress the protected check (C++ [class.protected]) for each of the
15057 // assignment operators we found. This strange dance is required when
15058 // we're assigning via a base classes's copy-assignment operator. To
15059 // ensure that we're getting the right base class subobject (without
15060 // ambiguities), we need to cast "this" to that subobject type; to
15061 // ensure that we don't go through the virtual call mechanism, we need
15062 // to qualify the operator= name with the base class (see below). However,
15063 // this means that if the base class has a protected copy assignment
15064 // operator, the protected member access check will fail. So, we
15065 // rewrite "protected" access to "public" access in this case, since we
15066 // know by construction that we're calling from a derived class.
15067 if (CopyingBaseSubobject) {
15068 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
15069 L != LEnd; ++L) {
15070 if (L.getAccess() == AS_protected)
15071 L.setAccess(AS_public);
15072 }
15073 }
15074
15075 // Create the nested-name-specifier that will be used to qualify the
15076 // reference to operator=; this is required to suppress the virtual
15077 // call mechanism.
15078 CXXScopeSpec SS;
15079 // FIXME: Don't canonicalize this.
15080 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
15081 SS.MakeTrivial(S.Context, NestedNameSpecifier(CanonicalT), Loc);
15082
15083 // Create the reference to operator=.
15084 ExprResult OpEqualRef
15085 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false,
15086 SS, /*TemplateKWLoc=*/SourceLocation(),
15087 /*FirstQualifierInScope=*/nullptr,
15088 OpLookup,
15089 /*TemplateArgs=*/nullptr, /*S*/nullptr,
15090 /*SuppressQualifierCheck=*/true);
15091 if (OpEqualRef.isInvalid())
15092 return StmtError();
15093
15094 // Build the call to the assignment operator.
15095
15096 Expr *FromInst = From.build(S, Loc);
15097 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
15098 OpEqualRef.getAs<Expr>(),
15099 Loc, FromInst, Loc);
15100 if (Call.isInvalid())
15101 return StmtError();
15102
15103 // If we built a call to a trivial 'operator=' while copying an array,
15104 // bail out. We'll replace the whole shebang with a memcpy.
15105 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
15106 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
15107 return StmtResult((Stmt*)nullptr);
15108
15109 // Convert to an expression-statement, and clean up any produced
15110 // temporaries.
15111 return S.ActOnExprStmt(Call);
15112 }
15113
15114 // - if the subobject is of scalar type, the built-in assignment
15115 // operator is used.
15117 if (!ArrayTy) {
15119 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
15120 if (Assignment.isInvalid())
15121 return StmtError();
15122 return S.ActOnExprStmt(Assignment);
15123 }
15124
15125 // - if the subobject is an array, each element is assigned, in the
15126 // manner appropriate to the element type;
15127
15128 // Construct a loop over the array bounds, e.g.,
15129 //
15130 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
15131 //
15132 // that will copy each of the array elements.
15133 QualType SizeType = S.Context.getSizeType();
15134
15135 // Create the iteration variable.
15136 IdentifierInfo *IterationVarName = nullptr;
15137 {
15138 SmallString<8> Str;
15139 llvm::raw_svector_ostream OS(Str);
15140 OS << "__i" << Depth;
15141 IterationVarName = &S.Context.Idents.get(OS.str());
15142 }
15143 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
15144 IterationVarName, SizeType,
15145 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
15146 SC_None);
15147
15148 // Initialize the iteration variable to zero.
15149 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
15150 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
15151
15152 // Creates a reference to the iteration variable.
15153 RefBuilder IterationVarRef(IterationVar, SizeType);
15154 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
15155
15156 // Create the DeclStmt that holds the iteration variable.
15157 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
15158
15159 // Subscript the "from" and "to" expressions with the iteration variable.
15160 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
15161 MoveCastBuilder FromIndexMove(FromIndexCopy);
15162 const ExprBuilder *FromIndex;
15163 if (Copying)
15164 FromIndex = &FromIndexCopy;
15165 else
15166 FromIndex = &FromIndexMove;
15167
15168 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
15169
15170 // Build the copy/move for an individual element of the array.
15171 StmtResult Copy =
15173 ToIndex, *FromIndex, CopyingBaseSubobject,
15174 Copying, Depth + 1);
15175 // Bail out if copying fails or if we determined that we should use memcpy.
15176 if (Copy.isInvalid() || !Copy.get())
15177 return Copy;
15178
15179 // Create the comparison against the array bound.
15180 llvm::APInt Upper
15181 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
15183 S.Context, IterationVarRefRVal.build(S, Loc),
15184 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE,
15187
15188 // Create the pre-increment of the iteration variable. We can determine
15189 // whether the increment will overflow based on the value of the array
15190 // bound.
15191 Expr *Increment = UnaryOperator::Create(
15192 S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue,
15193 OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides());
15194
15195 // Construct the loop that copies all elements of this array.
15196 return S.ActOnForStmt(
15197 Loc, Loc, InitStmt,
15199 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
15200}
15201
15202static StmtResult
15204 const ExprBuilder &To, const ExprBuilder &From,
15205 bool CopyingBaseSubobject, bool Copying) {
15206 // Maybe we should use a memcpy?
15207 if (T->isArrayType() && !T.hasQualifiers() &&
15208 T.isTriviallyCopyableType(S.Context))
15209 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
15210
15211 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
15212 CopyingBaseSubobject,
15213 Copying, 0));
15214
15215 // If we ended up picking a trivial assignment operator for an array of a
15216 // non-trivially-copyable class type, just emit a memcpy.
15217 if (!Result.isInvalid() && !Result.get())
15218 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
15219
15220 return Result;
15221}
15222
15224 // Note: The following rules are largely analoguous to the copy
15225 // constructor rules. Note that virtual bases are not taken into account
15226 // for determining the argument type of the operator. Note also that
15227 // operators taking an object instead of a reference are allowed.
15228 assert(ClassDecl->needsImplicitCopyAssignment());
15229
15230 DeclaringSpecialMember DSM(*this, ClassDecl,
15232 if (DSM.isAlreadyBeingDeclared())
15233 return nullptr;
15234
15236 /*Qualifier=*/std::nullopt, ClassDecl,
15237 /*OwnsTag=*/false);
15239 if (AS != LangAS::Default)
15240 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
15241 QualType RetType = Context.getLValueReferenceType(ArgType);
15242 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
15243 if (Const)
15244 ArgType = ArgType.withConst();
15245
15246 ArgType = Context.getLValueReferenceType(ArgType);
15247
15249 *this, ClassDecl, CXXSpecialMemberKind::CopyAssignment, Const);
15250
15251 // An implicitly-declared copy assignment operator is an inline public
15252 // member of its class.
15253 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
15254 SourceLocation ClassLoc = ClassDecl->getLocation();
15255 DeclarationNameInfo NameInfo(Name, ClassLoc);
15257 Context, ClassDecl, ClassLoc, NameInfo, QualType(),
15258 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
15259 getCurFPFeatures().isFPConstrained(),
15260 /*isInline=*/true,
15262 SourceLocation());
15263 CopyAssignment->setAccess(AS_public);
15264 CopyAssignment->setDefaulted();
15265 CopyAssignment->setImplicit();
15266
15267 setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
15268
15269 if (getLangOpts().CUDA)
15270 CUDA().inferTargetForImplicitSpecialMember(
15272 /* ConstRHS */ Const,
15273 /* Diagnose */ false);
15274
15275 // Add the parameter to the operator.
15277 ClassLoc, ClassLoc,
15278 /*Id=*/nullptr, ArgType,
15279 /*TInfo=*/nullptr, SC_None,
15280 nullptr);
15281 CopyAssignment->setParams(FromParam);
15282
15283 CopyAssignment->setTrivial(
15287 : ClassDecl->hasTrivialCopyAssignment());
15288
15289 // Note that we have added this copy-assignment operator.
15290 ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
15291
15292 Scope *S = getScopeForContext(ClassDecl);
15294
15298 SetDeclDeleted(CopyAssignment, ClassLoc);
15299 }
15300
15301 if (S)
15303 ClassDecl->addDecl(CopyAssignment);
15304
15305 return CopyAssignment;
15306}
15307
15308/// Diagnose an implicit copy operation for a class which is odr-used, but
15309/// which is deprecated because the class has a user-declared copy constructor,
15310/// copy assignment operator, or destructor.
15312 assert(CopyOp->isImplicit());
15313
15314 CXXRecordDecl *RD = CopyOp->getParent();
15315 CXXMethodDecl *UserDeclaredOperation = nullptr;
15316
15317 if (RD->hasUserDeclaredDestructor()) {
15318 UserDeclaredOperation = RD->getDestructor();
15319 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
15321 // Find any user-declared copy constructor.
15322 for (auto *I : RD->ctors()) {
15323 if (I->isCopyConstructor()) {
15324 UserDeclaredOperation = I;
15325 break;
15326 }
15327 }
15328 assert(UserDeclaredOperation);
15329 } else if (isa<CXXConstructorDecl>(CopyOp) &&
15331 // Find any user-declared move assignment operator.
15332 for (auto *I : RD->methods()) {
15333 if (I->isCopyAssignmentOperator()) {
15334 UserDeclaredOperation = I;
15335 break;
15336 }
15337 }
15338 assert(UserDeclaredOperation);
15339 }
15340
15341 if (UserDeclaredOperation) {
15342 bool UDOIsUserProvided = UserDeclaredOperation->isUserProvided();
15343 bool UDOIsDestructor = isa<CXXDestructorDecl>(UserDeclaredOperation);
15344 bool IsCopyAssignment = !isa<CXXConstructorDecl>(CopyOp);
15345 unsigned DiagID =
15346 (UDOIsUserProvided && UDOIsDestructor)
15347 ? diag::warn_deprecated_copy_with_user_provided_dtor
15348 : (UDOIsUserProvided && !UDOIsDestructor)
15349 ? diag::warn_deprecated_copy_with_user_provided_copy
15350 : (!UDOIsUserProvided && UDOIsDestructor)
15351 ? diag::warn_deprecated_copy_with_dtor
15352 : diag::warn_deprecated_copy;
15353 S.Diag(UserDeclaredOperation->getLocation(), DiagID)
15354 << RD << IsCopyAssignment;
15355 }
15356}
15357
15359 CXXMethodDecl *CopyAssignOperator) {
15360 DefaultedFunctionFPFeaturesRAII RestoreFP(*this, CopyAssignOperator);
15361 assert((CopyAssignOperator->isDefaulted() &&
15362 CopyAssignOperator->isOverloadedOperator() &&
15363 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
15364 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
15365 !CopyAssignOperator->isDeleted()) &&
15366 "DefineImplicitCopyAssignment called for wrong function");
15367 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
15368 return;
15369
15370 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
15371 if (ClassDecl->isInvalidDecl()) {
15372 CopyAssignOperator->setInvalidDecl();
15373 return;
15374 }
15375
15376 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
15377
15378 // The exception specification is needed because we are defining the
15379 // function.
15380 ResolveExceptionSpec(CurrentLocation,
15381 CopyAssignOperator->getType()->castAs<FunctionProtoType>());
15382
15383 // Add a context note for diagnostics produced after this point.
15384 Scope.addContextNote(CurrentLocation);
15385
15386 // C++11 [class.copy]p18:
15387 // The [definition of an implicitly declared copy assignment operator] is
15388 // deprecated if the class has a user-declared copy constructor or a
15389 // user-declared destructor.
15390 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
15391 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
15392
15393 // C++0x [class.copy]p30:
15394 // The implicitly-defined or explicitly-defaulted copy assignment operator
15395 // for a non-union class X performs memberwise copy assignment of its
15396 // subobjects. The direct base classes of X are assigned first, in the
15397 // order of their declaration in the base-specifier-list, and then the
15398 // immediate non-static data members of X are assigned, in the order in
15399 // which they were declared in the class definition.
15400
15401 // The statements that form the synthesized function body.
15402 SmallVector<Stmt*, 8> Statements;
15403
15404 // The parameter for the "other" object, which we are copying from.
15405 ParmVarDecl *Other = CopyAssignOperator->getNonObjectParameter(0);
15406 Qualifiers OtherQuals = Other->getType().getQualifiers();
15407 QualType OtherRefType = Other->getType();
15408 if (OtherRefType->isLValueReferenceType()) {
15409 OtherRefType = OtherRefType->getPointeeType();
15410 OtherQuals = OtherRefType.getQualifiers();
15411 }
15412
15413 // Our location for everything implicitly-generated.
15414 SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
15415 ? CopyAssignOperator->getEndLoc()
15416 : CopyAssignOperator->getLocation();
15417
15418 // Builds a DeclRefExpr for the "other" object.
15419 RefBuilder OtherRef(Other, OtherRefType);
15420
15421 // Builds the function object parameter.
15422 std::optional<ThisBuilder> This;
15423 std::optional<DerefBuilder> DerefThis;
15424 std::optional<RefBuilder> ExplicitObject;
15425 bool IsArrow = false;
15426 QualType ObjectType;
15427 if (CopyAssignOperator->isExplicitObjectMemberFunction()) {
15428 ObjectType = CopyAssignOperator->getParamDecl(0)->getType();
15429 if (ObjectType->isReferenceType())
15430 ObjectType = ObjectType->getPointeeType();
15431 ExplicitObject.emplace(CopyAssignOperator->getParamDecl(0), ObjectType);
15432 } else {
15433 ObjectType = getCurrentThisType();
15434 This.emplace();
15435 DerefThis.emplace(*This);
15436 IsArrow = !LangOpts.HLSL;
15437 }
15438 ExprBuilder &ObjectParameter =
15439 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15440 : static_cast<ExprBuilder &>(*This);
15441
15442 // Assign base classes.
15443 bool Invalid = false;
15444 for (auto &Base : ClassDecl->bases()) {
15445 // Form the assignment:
15446 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
15447 QualType BaseType = Base.getType().getUnqualifiedType();
15448 if (!BaseType->isRecordType()) {
15449 Invalid = true;
15450 continue;
15451 }
15452
15453 CXXCastPath BasePath;
15454 BasePath.push_back(&Base);
15455
15456 // Construct the "from" expression, which is an implicit cast to the
15457 // appropriately-qualified base type.
15458 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
15459 VK_LValue, BasePath);
15460
15461 // Dereference "this".
15462 CastBuilder To(
15463 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15464 : static_cast<ExprBuilder &>(*DerefThis),
15465 Context.getQualifiedType(BaseType, ObjectType.getQualifiers()),
15466 VK_LValue, BasePath);
15467
15468 // Build the copy.
15469 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
15470 To, From,
15471 /*CopyingBaseSubobject=*/true,
15472 /*Copying=*/true);
15473 if (Copy.isInvalid()) {
15474 CopyAssignOperator->setInvalidDecl();
15475 return;
15476 }
15477
15478 // Success! Record the copy.
15479 Statements.push_back(Copy.getAs<Expr>());
15480 }
15481
15482 // A defaulted copy assignment operator for a union copies the object
15483 // representation as if by a memcpy, the same way the defaulted union copy
15484 // constructor does. The memberwise loop below skips union members.
15485 if (ClassDecl->isUnion()) {
15486 ExprBuilder &To = ExplicitObject
15487 ? static_cast<ExprBuilder &>(*ExplicitObject)
15488 : static_cast<ExprBuilder &>(*DerefThis);
15489 // Copying the object representation is correct even for a union that is
15490 // not trivially copyable, so -Wnontrivial-memcall is a false positive
15491 // here. Ignoring warnings rather than casting the arguments to void*
15492 // keeps them typed, which preserves their address space.
15493 IgnoreAllWarningDiagRAII IgnoreWarnings(Diags);
15495 *this, Loc, Context.getCanonicalTagType(ClassDecl), To, OtherRef);
15496 if (Copy.isInvalid()) {
15497 CopyAssignOperator->setInvalidDecl();
15498 return;
15499 }
15500 Statements.push_back(Copy.getAs<Stmt>());
15501 }
15502
15503 // Assign non-static members.
15504 for (auto *Field : ClassDecl->fields()) {
15505 // Union members are copied by the whole-object memcpy emitted above.
15506 if (Field->isUnnamedBitField() || Field->getParent()->isUnion())
15507 continue;
15508
15509 if (Field->isInvalidDecl()) {
15510 Invalid = true;
15511 continue;
15512 }
15513
15514 // Check for members of reference type; we can't copy those.
15515 if (Field->getType()->isReferenceType()) {
15516 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15517 << Context.getCanonicalTagType(ClassDecl) << 0
15518 << Field->getDeclName();
15519 Diag(Field->getLocation(), diag::note_declared_at);
15520 Invalid = true;
15521 continue;
15522 }
15523
15524 // Check for members of const-qualified, non-class type.
15525 QualType BaseType = Context.getBaseElementType(Field->getType());
15526 if (!BaseType->isRecordType() && BaseType.isConstQualified()) {
15527 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15528 << Context.getCanonicalTagType(ClassDecl) << 1
15529 << Field->getDeclName();
15530 Diag(Field->getLocation(), diag::note_declared_at);
15531 Invalid = true;
15532 continue;
15533 }
15534
15535 // Suppress assigning zero-width bitfields.
15536 if (Field->isZeroLengthBitField())
15537 continue;
15538
15539 QualType FieldType = Field->getType().getNonReferenceType();
15540 if (FieldType->isIncompleteArrayType()) {
15541 assert(ClassDecl->hasFlexibleArrayMember() &&
15542 "Incomplete array type is not valid");
15543 continue;
15544 }
15545
15546 // Build references to the field in the object we're copying from and to.
15547 CXXScopeSpec SS; // Intentionally empty
15548 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
15550 MemberLookup.addDecl(Field);
15551 MemberLookup.resolveKind();
15552
15553 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
15554 MemberBuilder To(ObjectParameter, ObjectType, IsArrow, MemberLookup);
15555 // Build the copy of this field.
15556 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
15557 To, From,
15558 /*CopyingBaseSubobject=*/false,
15559 /*Copying=*/true);
15560 if (Copy.isInvalid()) {
15561 CopyAssignOperator->setInvalidDecl();
15562 return;
15563 }
15564
15565 // Success! Record the copy.
15566 Statements.push_back(Copy.getAs<Stmt>());
15567 }
15568
15569 if (!Invalid) {
15570 // Add a "return *this;"
15571 Expr *ThisExpr =
15572 (ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15573 : LangOpts.HLSL ? static_cast<ExprBuilder &>(*This)
15574 : static_cast<ExprBuilder &>(*DerefThis))
15575 .build(*this, Loc);
15576 StmtResult Return = BuildReturnStmt(Loc, ThisExpr);
15577 if (Return.isInvalid())
15578 Invalid = true;
15579 else
15580 Statements.push_back(Return.getAs<Stmt>());
15581 }
15582
15583 if (Invalid) {
15584 CopyAssignOperator->setInvalidDecl();
15585 return;
15586 }
15587
15588 StmtResult Body;
15589 {
15590 CompoundScopeRAII CompoundScope(*this);
15591 Body = ActOnCompoundStmt(Loc, Loc, Statements,
15592 /*isStmtExpr=*/false);
15593 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
15594 }
15595 CopyAssignOperator->setBody(Body.getAs<Stmt>());
15596 CopyAssignOperator->markUsed(Context);
15597
15599 L->CompletedImplicitDefinition(CopyAssignOperator);
15600 }
15601}
15602
15604 assert(ClassDecl->needsImplicitMoveAssignment());
15605
15606 DeclaringSpecialMember DSM(*this, ClassDecl,
15608 if (DSM.isAlreadyBeingDeclared())
15609 return nullptr;
15610
15611 // Note: The following rules are largely analoguous to the move
15612 // constructor rules.
15613
15615 /*Qualifier=*/std::nullopt, ClassDecl,
15616 /*OwnsTag=*/false);
15618 if (AS != LangAS::Default)
15619 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
15620 QualType RetType = Context.getLValueReferenceType(ArgType);
15621 ArgType = Context.getRValueReferenceType(ArgType);
15622
15624 *this, ClassDecl, CXXSpecialMemberKind::MoveAssignment, false);
15625
15626 // An implicitly-declared move assignment operator is an inline public
15627 // member of its class.
15628 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
15629 SourceLocation ClassLoc = ClassDecl->getLocation();
15630 DeclarationNameInfo NameInfo(Name, ClassLoc);
15632 Context, ClassDecl, ClassLoc, NameInfo, QualType(),
15633 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
15634 getCurFPFeatures().isFPConstrained(),
15635 /*isInline=*/true,
15637 SourceLocation());
15638 MoveAssignment->setAccess(AS_public);
15639 MoveAssignment->setDefaulted();
15640 MoveAssignment->setImplicit();
15641
15642 setupImplicitSpecialMemberType(MoveAssignment, RetType, ArgType);
15643
15644 if (getLangOpts().CUDA)
15645 CUDA().inferTargetForImplicitSpecialMember(
15647 /* ConstRHS */ false,
15648 /* Diagnose */ false);
15649
15650 // Add the parameter to the operator.
15652 ClassLoc, ClassLoc,
15653 /*Id=*/nullptr, ArgType,
15654 /*TInfo=*/nullptr, SC_None,
15655 nullptr);
15656 MoveAssignment->setParams(FromParam);
15657
15658 MoveAssignment->setTrivial(
15662 : ClassDecl->hasTrivialMoveAssignment());
15663
15664 // Note that we have added this copy-assignment operator.
15665 ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
15666
15667 Scope *S = getScopeForContext(ClassDecl);
15669
15673 SetDeclDeleted(MoveAssignment, ClassLoc);
15674 }
15675
15676 if (S)
15678 ClassDecl->addDecl(MoveAssignment);
15679
15680 return MoveAssignment;
15681}
15682
15683/// Check if we're implicitly defining a move assignment operator for a class
15684/// with virtual bases. Such a move assignment might move-assign the virtual
15685/// base multiple times.
15687 SourceLocation CurrentLocation) {
15688 assert(!Class->isDependentContext() && "should not define dependent move");
15689
15690 // Only a virtual base could get implicitly move-assigned multiple times.
15691 // Only a non-trivial move assignment can observe this. We only want to
15692 // diagnose if we implicitly define an assignment operator that assigns
15693 // two base classes, both of which move-assign the same virtual base.
15694 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
15695 Class->getNumBases() < 2)
15696 return;
15697
15699 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
15700 VBaseMap VBases;
15701
15702 for (auto &BI : Class->bases()) {
15703 Worklist.push_back(&BI);
15704 while (!Worklist.empty()) {
15705 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
15706 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
15707
15708 // If the base has no non-trivial move assignment operators,
15709 // we don't care about moves from it.
15710 if (!Base->hasNonTrivialMoveAssignment())
15711 continue;
15712
15713 // If there's nothing virtual here, skip it.
15714 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
15715 continue;
15716
15717 // If we're not actually going to call a move assignment for this base,
15718 // or the selected move assignment is trivial, skip it.
15721 /*ConstArg*/ false, /*VolatileArg*/ false,
15722 /*RValueThis*/ true, /*ConstThis*/ false,
15723 /*VolatileThis*/ false);
15724 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
15726 continue;
15727
15728 if (BaseSpec->isVirtual()) {
15729 // We're going to move-assign this virtual base, and its move
15730 // assignment operator is not trivial. If this can happen for
15731 // multiple distinct direct bases of Class, diagnose it. (If it
15732 // only happens in one base, we'll diagnose it when synthesizing
15733 // that base class's move assignment operator.)
15734 CXXBaseSpecifier *&Existing =
15735 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
15736 .first->second;
15737 if (Existing && Existing != &BI) {
15738 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
15739 << Class << Base;
15740 S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
15741 << (Base->getCanonicalDecl() ==
15743 << Base << Existing->getType() << Existing->getSourceRange();
15744 S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
15745 << (Base->getCanonicalDecl() ==
15746 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
15747 << Base << BI.getType() << BaseSpec->getSourceRange();
15748
15749 // Only diagnose each vbase once.
15750 Existing = nullptr;
15751 }
15752 } else {
15753 // Only walk over bases that have defaulted move assignment operators.
15754 // We assume that any user-provided move assignment operator handles
15755 // the multiple-moves-of-vbase case itself somehow.
15756 if (!SMOR.getMethod()->isDefaulted())
15757 continue;
15758
15759 // We're going to move the base classes of Base. Add them to the list.
15760 llvm::append_range(Worklist, llvm::make_pointer_range(Base->bases()));
15761 }
15762 }
15763 }
15764}
15765
15767 CXXMethodDecl *MoveAssignOperator) {
15768 DefaultedFunctionFPFeaturesRAII RestoreFP(*this, MoveAssignOperator);
15769 assert((MoveAssignOperator->isDefaulted() &&
15770 MoveAssignOperator->isOverloadedOperator() &&
15771 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
15772 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
15773 !MoveAssignOperator->isDeleted()) &&
15774 "DefineImplicitMoveAssignment called for wrong function");
15775 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
15776 return;
15777
15778 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
15779 if (ClassDecl->isInvalidDecl()) {
15780 MoveAssignOperator->setInvalidDecl();
15781 return;
15782 }
15783
15784 // C++0x [class.copy]p28:
15785 // The implicitly-defined or move assignment operator for a non-union class
15786 // X performs memberwise move assignment of its subobjects. The direct base
15787 // classes of X are assigned first, in the order of their declaration in the
15788 // base-specifier-list, and then the immediate non-static data members of X
15789 // are assigned, in the order in which they were declared in the class
15790 // definition.
15791
15792 // Issue a warning if our implicit move assignment operator will move
15793 // from a virtual base more than once.
15794 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
15795
15796 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
15797
15798 // The exception specification is needed because we are defining the
15799 // function.
15800 ResolveExceptionSpec(CurrentLocation,
15801 MoveAssignOperator->getType()->castAs<FunctionProtoType>());
15802
15803 // Add a context note for diagnostics produced after this point.
15804 Scope.addContextNote(CurrentLocation);
15805
15806 // The statements that form the synthesized function body.
15807 SmallVector<Stmt*, 8> Statements;
15808
15809 // The parameter for the "other" object, which we are move from.
15810 ParmVarDecl *Other = MoveAssignOperator->getNonObjectParameter(0);
15811 QualType OtherRefType =
15812 Other->getType()->castAs<RValueReferenceType>()->getPointeeType();
15813
15814 // Our location for everything implicitly-generated.
15815 SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
15816 ? MoveAssignOperator->getEndLoc()
15817 : MoveAssignOperator->getLocation();
15818
15819 // Builds a reference to the "other" object.
15820 RefBuilder OtherRef(Other, OtherRefType);
15821 // Cast to rvalue.
15822 MoveCastBuilder MoveOther(OtherRef);
15823
15824 // Builds the function object parameter.
15825 std::optional<ThisBuilder> This;
15826 std::optional<DerefBuilder> DerefThis;
15827 std::optional<RefBuilder> ExplicitObject;
15828 QualType ObjectType;
15829 bool IsArrow = false;
15830 if (MoveAssignOperator->isExplicitObjectMemberFunction()) {
15831 ObjectType = MoveAssignOperator->getParamDecl(0)->getType();
15832 if (ObjectType->isReferenceType())
15833 ObjectType = ObjectType->getPointeeType();
15834 ExplicitObject.emplace(MoveAssignOperator->getParamDecl(0), ObjectType);
15835 } else {
15836 ObjectType = getCurrentThisType();
15837 This.emplace();
15838 DerefThis.emplace(*This);
15839 IsArrow = !getLangOpts().HLSL;
15840 }
15841 ExprBuilder &ObjectParameter =
15842 ExplicitObject ? *ExplicitObject : static_cast<ExprBuilder &>(*This);
15843
15844 // Assign base classes.
15845 bool Invalid = false;
15846 for (auto &Base : ClassDecl->bases()) {
15847 // C++11 [class.copy]p28:
15848 // It is unspecified whether subobjects representing virtual base classes
15849 // are assigned more than once by the implicitly-defined copy assignment
15850 // operator.
15851 // FIXME: Do not assign to a vbase that will be assigned by some other base
15852 // class. For a move-assignment, this can result in the vbase being moved
15853 // multiple times.
15854
15855 // Form the assignment:
15856 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
15857 QualType BaseType = Base.getType().getUnqualifiedType();
15858 if (!BaseType->isRecordType()) {
15859 Invalid = true;
15860 continue;
15861 }
15862
15863 CXXCastPath BasePath;
15864 BasePath.push_back(&Base);
15865
15866 // Construct the "from" expression, which is an implicit cast to the
15867 // appropriately-qualified base type.
15868 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
15869
15870 // Implicitly cast "this" to the appropriately-qualified base type.
15871 // Dereference "this".
15872 CastBuilder To(
15873 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15874 : static_cast<ExprBuilder &>(*DerefThis),
15875 Context.getQualifiedType(BaseType, ObjectType.getQualifiers()),
15876 VK_LValue, BasePath);
15877
15878 // Build the move.
15879 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
15880 To, From,
15881 /*CopyingBaseSubobject=*/true,
15882 /*Copying=*/false);
15883 if (Move.isInvalid()) {
15884 MoveAssignOperator->setInvalidDecl();
15885 return;
15886 }
15887
15888 // Success! Record the move.
15889 Statements.push_back(Move.getAs<Expr>());
15890 }
15891
15892 // A defaulted move assignment operator for a union copies the object
15893 // representation as if by a memcpy, the same way the defaulted union copy
15894 // constructor does. The memberwise loop below skips union members.
15895 if (ClassDecl->isUnion()) {
15896 ExprBuilder &To = ExplicitObject
15897 ? static_cast<ExprBuilder &>(*ExplicitObject)
15898 : static_cast<ExprBuilder &>(*DerefThis);
15899 // Copying the object representation is correct even for a union that is
15900 // not trivially copyable, so -Wnontrivial-memcall is a false positive
15901 // here. Ignoring warnings rather than casting the arguments to void*
15902 // keeps them typed, which preserves their address space.
15903 IgnoreAllWarningDiagRAII IgnoreWarnings(Diags);
15905 *this, Loc, Context.getCanonicalTagType(ClassDecl), To, OtherRef);
15906 if (Copy.isInvalid()) {
15907 MoveAssignOperator->setInvalidDecl();
15908 return;
15909 }
15910 Statements.push_back(Copy.getAs<Stmt>());
15911 }
15912
15913 // Assign non-static members.
15914 for (auto *Field : ClassDecl->fields()) {
15915 // Union members are copied by the whole-object memcpy emitted above.
15916 if (Field->isUnnamedBitField() || Field->getParent()->isUnion())
15917 continue;
15918
15919 if (Field->isInvalidDecl()) {
15920 Invalid = true;
15921 continue;
15922 }
15923
15924 // Check for members of reference type; we can't move those.
15925 if (Field->getType()->isReferenceType()) {
15926 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15927 << Context.getCanonicalTagType(ClassDecl) << 0
15928 << Field->getDeclName();
15929 Diag(Field->getLocation(), diag::note_declared_at);
15930 Invalid = true;
15931 continue;
15932 }
15933
15934 // Check for members of const-qualified, non-class type.
15935 QualType BaseType = Context.getBaseElementType(Field->getType());
15936 if (!BaseType->isRecordType() && BaseType.isConstQualified()) {
15937 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15938 << Context.getCanonicalTagType(ClassDecl) << 1
15939 << Field->getDeclName();
15940 Diag(Field->getLocation(), diag::note_declared_at);
15941 Invalid = true;
15942 continue;
15943 }
15944
15945 // Suppress assigning zero-width bitfields.
15946 if (Field->isZeroLengthBitField())
15947 continue;
15948
15949 QualType FieldType = Field->getType().getNonReferenceType();
15950 if (FieldType->isIncompleteArrayType()) {
15951 assert(ClassDecl->hasFlexibleArrayMember() &&
15952 "Incomplete array type is not valid");
15953 continue;
15954 }
15955
15956 // Build references to the field in the object we're copying from and to.
15957 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
15959 MemberLookup.addDecl(Field);
15960 MemberLookup.resolveKind();
15961 MemberBuilder From(MoveOther, OtherRefType,
15962 /*IsArrow=*/false, MemberLookup);
15963 MemberBuilder To(ObjectParameter, ObjectType, IsArrow, MemberLookup);
15964
15965 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
15966 "Member reference with rvalue base must be rvalue except for reference "
15967 "members, which aren't allowed for move assignment.");
15968
15969 // Build the move of this field.
15970 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
15971 To, From,
15972 /*CopyingBaseSubobject=*/false,
15973 /*Copying=*/false);
15974 if (Move.isInvalid()) {
15975 MoveAssignOperator->setInvalidDecl();
15976 return;
15977 }
15978
15979 // Success! Record the copy.
15980 Statements.push_back(Move.getAs<Stmt>());
15981 }
15982
15983 if (!Invalid) {
15984 // Add a "return *this;"
15985 Expr *ThisExpr =
15986 (ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15987 : LangOpts.HLSL ? static_cast<ExprBuilder &>(*This)
15988 : static_cast<ExprBuilder &>(*DerefThis))
15989 .build(*this, Loc);
15990
15991 StmtResult Return = BuildReturnStmt(Loc, ThisExpr);
15992 if (Return.isInvalid())
15993 Invalid = true;
15994 else
15995 Statements.push_back(Return.getAs<Stmt>());
15996 }
15997
15998 if (Invalid) {
15999 MoveAssignOperator->setInvalidDecl();
16000 return;
16001 }
16002
16003 StmtResult Body;
16004 {
16005 CompoundScopeRAII CompoundScope(*this);
16006 Body = ActOnCompoundStmt(Loc, Loc, Statements,
16007 /*isStmtExpr=*/false);
16008 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
16009 }
16010 MoveAssignOperator->setBody(Body.getAs<Stmt>());
16011 MoveAssignOperator->markUsed(Context);
16012
16014 L->CompletedImplicitDefinition(MoveAssignOperator);
16015 }
16016}
16017
16019 CXXRecordDecl *ClassDecl) {
16020 // C++ [class.copy]p4:
16021 // If the class definition does not explicitly declare a copy
16022 // constructor, one is declared implicitly.
16023 assert(ClassDecl->needsImplicitCopyConstructor());
16024
16025 DeclaringSpecialMember DSM(*this, ClassDecl,
16027 if (DSM.isAlreadyBeingDeclared())
16028 return nullptr;
16029
16030 QualType ClassType = Context.getTagType(ElaboratedTypeKeyword::None,
16031 /*Qualifier=*/std::nullopt, ClassDecl,
16032 /*OwnsTag=*/false);
16033 QualType ArgType = ClassType;
16034 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
16035 if (Const)
16036 ArgType = ArgType.withConst();
16037
16039 if (AS != LangAS::Default)
16040 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
16041
16042 ArgType = Context.getLValueReferenceType(ArgType);
16043
16045 *this, ClassDecl, CXXSpecialMemberKind::CopyConstructor, Const);
16046
16047 DeclarationName Name
16048 = Context.DeclarationNames.getCXXConstructorName(
16049 Context.getCanonicalType(ClassType));
16050 SourceLocation ClassLoc = ClassDecl->getLocation();
16051 DeclarationNameInfo NameInfo(Name, ClassLoc);
16052
16053 // An implicitly-declared copy constructor is an inline public
16054 // member of its class.
16056 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
16057 ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
16058 /*isInline=*/true,
16059 /*isImplicitlyDeclared=*/true,
16062 CopyConstructor->setAccess(AS_public);
16063 CopyConstructor->setDefaulted();
16064
16065 setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
16066
16067 if (getLangOpts().CUDA)
16068 CUDA().inferTargetForImplicitSpecialMember(
16070 /* ConstRHS */ Const,
16071 /* Diagnose */ false);
16072
16073 // During template instantiation of special member functions we need a
16074 // reliable TypeSourceInfo for the parameter types in order to allow functions
16075 // to be substituted.
16076 TypeSourceInfo *TSI = nullptr;
16077 if (inTemplateInstantiation() && ClassDecl->isLambda())
16078 TSI = Context.getTrivialTypeSourceInfo(ArgType);
16079
16080 // Add the parameter to the constructor.
16081 ParmVarDecl *FromParam =
16082 ParmVarDecl::Create(Context, CopyConstructor, ClassLoc, ClassLoc,
16083 /*IdentifierInfo=*/nullptr, ArgType,
16084 /*TInfo=*/TSI, SC_None, nullptr);
16085 CopyConstructor->setParams(FromParam);
16086
16087 CopyConstructor->setTrivial(
16091 : ClassDecl->hasTrivialCopyConstructor());
16092
16093 CopyConstructor->setTrivialForCall(
16094 ClassDecl->hasAttr<TrivialABIAttr>() ||
16099 : ClassDecl->hasTrivialCopyConstructorForCall()));
16100
16101 // Note that we have declared this constructor.
16102 ++getASTContext().NumImplicitCopyConstructorsDeclared;
16103
16104 Scope *S = getScopeForContext(ClassDecl);
16106
16111 }
16112
16113 if (S)
16115 ClassDecl->addDecl(CopyConstructor);
16116
16117 return CopyConstructor;
16118}
16119
16122 DefaultedFunctionFPFeaturesRAII RestoreFP(*this, CopyConstructor);
16123 assert((CopyConstructor->isDefaulted() &&
16124 CopyConstructor->isCopyConstructor() &&
16125 !CopyConstructor->doesThisDeclarationHaveABody() &&
16126 !CopyConstructor->isDeleted()) &&
16127 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
16128 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
16129 return;
16130
16131 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
16132 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
16133
16135
16136 // The exception specification is needed because we are defining the
16137 // function.
16138 ResolveExceptionSpec(CurrentLocation,
16139 CopyConstructor->getType()->castAs<FunctionProtoType>());
16140 MarkVTableUsed(CurrentLocation, ClassDecl);
16141
16142 // Add a context note for diagnostics produced after this point.
16143 Scope.addContextNote(CurrentLocation);
16144
16145 // C++11 [class.copy]p7:
16146 // The [definition of an implicitly declared copy constructor] is
16147 // deprecated if the class has a user-declared copy assignment operator
16148 // or a user-declared destructor.
16149 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
16151
16152 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
16153 CopyConstructor->setInvalidDecl();
16154 } else {
16155 SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
16156 ? CopyConstructor->getEndLoc()
16157 : CopyConstructor->getLocation();
16158 Sema::CompoundScopeRAII CompoundScope(*this);
16159 CopyConstructor->setBody(
16160 ActOnCompoundStmt(Loc, Loc, {}, /*isStmtExpr=*/false).getAs<Stmt>());
16161 CopyConstructor->markUsed(Context);
16162 }
16163
16165 L->CompletedImplicitDefinition(CopyConstructor);
16166 }
16167}
16168
16170 CXXRecordDecl *ClassDecl) {
16171 assert(ClassDecl->needsImplicitMoveConstructor());
16172
16173 DeclaringSpecialMember DSM(*this, ClassDecl,
16175 if (DSM.isAlreadyBeingDeclared())
16176 return nullptr;
16177
16178 QualType ClassType = Context.getTagType(ElaboratedTypeKeyword::None,
16179 /*Qualifier=*/std::nullopt, ClassDecl,
16180 /*OwnsTag=*/false);
16181
16182 QualType ArgType = ClassType;
16184 if (AS != LangAS::Default)
16185 ArgType = Context.getAddrSpaceQualType(ClassType, AS);
16186 ArgType = Context.getRValueReferenceType(ArgType);
16187
16189 *this, ClassDecl, CXXSpecialMemberKind::MoveConstructor, false);
16190
16191 DeclarationName Name
16192 = Context.DeclarationNames.getCXXConstructorName(
16193 Context.getCanonicalType(ClassType));
16194 SourceLocation ClassLoc = ClassDecl->getLocation();
16195 DeclarationNameInfo NameInfo(Name, ClassLoc);
16196
16197 // C++11 [class.copy]p11:
16198 // An implicitly-declared copy/move constructor is an inline public
16199 // member of its class.
16201 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
16202 ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
16203 /*isInline=*/true,
16204 /*isImplicitlyDeclared=*/true,
16207 MoveConstructor->setAccess(AS_public);
16208 MoveConstructor->setDefaulted();
16209
16210 setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
16211
16212 if (getLangOpts().CUDA)
16213 CUDA().inferTargetForImplicitSpecialMember(
16215 /* ConstRHS */ false,
16216 /* Diagnose */ false);
16217
16218 // Add the parameter to the constructor.
16220 ClassLoc, ClassLoc,
16221 /*IdentifierInfo=*/nullptr,
16222 ArgType, /*TInfo=*/nullptr,
16223 SC_None, nullptr);
16224 MoveConstructor->setParams(FromParam);
16225
16226 MoveConstructor->setTrivial(
16230 : ClassDecl->hasTrivialMoveConstructor());
16231
16232 MoveConstructor->setTrivialForCall(
16233 ClassDecl->hasAttr<TrivialABIAttr>() ||
16238 : ClassDecl->hasTrivialMoveConstructorForCall()));
16239
16240 // Note that we have declared this constructor.
16241 ++getASTContext().NumImplicitMoveConstructorsDeclared;
16242
16243 Scope *S = getScopeForContext(ClassDecl);
16245
16250 }
16251
16252 if (S)
16254 ClassDecl->addDecl(MoveConstructor);
16255
16256 return MoveConstructor;
16257}
16258
16261 DefaultedFunctionFPFeaturesRAII RestoreFP(*this, MoveConstructor);
16262 assert((MoveConstructor->isDefaulted() &&
16263 MoveConstructor->isMoveConstructor() &&
16264 !MoveConstructor->doesThisDeclarationHaveABody() &&
16265 !MoveConstructor->isDeleted()) &&
16266 "DefineImplicitMoveConstructor - call it for implicit move ctor");
16267 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
16268 return;
16269
16270 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
16271 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
16272
16274
16275 // The exception specification is needed because we are defining the
16276 // function.
16277 ResolveExceptionSpec(CurrentLocation,
16278 MoveConstructor->getType()->castAs<FunctionProtoType>());
16279 MarkVTableUsed(CurrentLocation, ClassDecl);
16280
16281 // Add a context note for diagnostics produced after this point.
16282 Scope.addContextNote(CurrentLocation);
16283
16284 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
16285 MoveConstructor->setInvalidDecl();
16286 } else {
16287 SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
16288 ? MoveConstructor->getEndLoc()
16289 : MoveConstructor->getLocation();
16290 Sema::CompoundScopeRAII CompoundScope(*this);
16291 MoveConstructor->setBody(
16292 ActOnCompoundStmt(Loc, Loc, {}, /*isStmtExpr=*/false).getAs<Stmt>());
16293 MoveConstructor->markUsed(Context);
16294 }
16295
16297 L->CompletedImplicitDefinition(MoveConstructor);
16298 }
16299}
16300
16302 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
16303}
16304
16306 SourceLocation CurrentLocation,
16307 CXXConversionDecl *Conv) {
16308 SynthesizedFunctionScope Scope(*this, Conv);
16309 assert(!Conv->getReturnType()->isUndeducedType());
16310
16311 QualType ConvRT = Conv->getType()->castAs<FunctionType>()->getReturnType();
16312 CallingConv CC =
16313 ConvRT->getPointeeType()->castAs<FunctionType>()->getCallConv();
16314
16315 CXXRecordDecl *Lambda = Conv->getParent();
16316 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
16317 FunctionDecl *Invoker =
16318 CallOp->hasCXXExplicitFunctionObjectParameter() || CallOp->isStatic()
16319 ? CallOp
16320 : Lambda->getLambdaStaticInvoker(CC);
16321
16322 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
16324 CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
16325 if (!CallOp)
16326 return;
16327
16328 if (CallOp != Invoker) {
16330 Invoker->getDescribedFunctionTemplate(), TemplateArgs,
16331 CurrentLocation);
16332 if (!Invoker)
16333 return;
16334 }
16335 }
16336
16337 if (CallOp->isInvalidDecl())
16338 return;
16339
16340 // Mark the call operator referenced (and add to pending instantiations
16341 // if necessary).
16342 // For both the conversion and static-invoker template specializations
16343 // we construct their body's in this function, so no need to add them
16344 // to the PendingInstantiations.
16345 MarkFunctionReferenced(CurrentLocation, CallOp);
16346
16347 if (Invoker != CallOp) {
16348 // Fill in the __invoke function with a dummy implementation. IR generation
16349 // will fill in the actual details. Update its type in case it contained
16350 // an 'auto'.
16351 Invoker->markUsed(Context);
16352 Invoker->setReferenced();
16353 Invoker->setType(Conv->getReturnType()->getPointeeType());
16354 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
16355 }
16356
16357 // Construct the body of the conversion function { return __invoke; }.
16358 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), VK_LValue,
16359 Conv->getLocation());
16360 assert(FunctionRef && "Can't refer to __invoke function?");
16361 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
16363 Conv->getLocation(), Conv->getLocation()));
16364 Conv->markUsed(Context);
16365 Conv->setReferenced();
16366
16368 L->CompletedImplicitDefinition(Conv);
16369 if (Invoker != CallOp)
16370 L->CompletedImplicitDefinition(Invoker);
16371 }
16372}
16373
16375 SourceLocation CurrentLocation, CXXConversionDecl *Conv) {
16376 assert(!Conv->getParent()->isGenericLambda());
16377
16378 SynthesizedFunctionScope Scope(*this, Conv);
16379
16380 // Copy-initialize the lambda object as needed to capture it.
16381 Expr *This = ActOnCXXThis(CurrentLocation).get();
16382 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
16383
16384 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
16385 Conv->getLocation(),
16386 Conv, DerefThis);
16387
16388 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
16389 // behavior. Note that only the general conversion function does this
16390 // (since it's unusable otherwise); in the case where we inline the
16391 // block literal, it has block literal lifetime semantics.
16392 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
16393 BuildBlock = ImplicitCastExpr::Create(
16394 Context, BuildBlock.get()->getType(), CK_CopyAndAutoreleaseBlockObject,
16395 BuildBlock.get(), nullptr, VK_PRValue, FPOptionsOverride());
16396
16397 if (BuildBlock.isInvalid()) {
16398 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
16399 Conv->setInvalidDecl();
16400 return;
16401 }
16402
16403 // Create the return statement that returns the block from the conversion
16404 // function.
16405 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
16406 if (Return.isInvalid()) {
16407 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
16408 Conv->setInvalidDecl();
16409 return;
16410 }
16411
16412 // Set the body of the conversion function.
16413 Stmt *ReturnS = Return.get();
16415 Conv->getLocation(), Conv->getLocation()));
16416 Conv->markUsed(Context);
16417
16418 // We're done; notify the mutation listener, if any.
16420 L->CompletedImplicitDefinition(Conv);
16421 }
16422}
16423
16424/// Determine whether the given list arguments contains exactly one
16425/// "real" (non-default) argument.
16427 switch (Args.size()) {
16428 case 0:
16429 return false;
16430
16431 default:
16432 if (!Args[1]->isDefaultArgument())
16433 return false;
16434
16435 [[fallthrough]];
16436 case 1:
16437 return !Args[0]->isDefaultArgument();
16438 }
16439
16440 return false;
16441}
16442
16444 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
16446 bool HadMultipleCandidates, bool IsListInitialization,
16447 bool IsStdInitListInitialization, bool RequiresZeroInit,
16448 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16449 bool Elidable = false;
16450
16451 // C++0x [class.copy]p34:
16452 // When certain criteria are met, an implementation is allowed to
16453 // omit the copy/move construction of a class object, even if the
16454 // copy/move constructor and/or destructor for the object have
16455 // side effects. [...]
16456 // - when a temporary class object that has not been bound to a
16457 // reference (12.2) would be copied/moved to a class object
16458 // with the same cv-unqualified type, the copy/move operation
16459 // can be omitted by constructing the temporary object
16460 // directly into the target of the omitted copy/move
16461 if (ConstructKind == CXXConstructionKind::Complete && Constructor &&
16462 // FIXME: Converting constructors should also be accepted.
16463 // But to fix this, the logic that digs down into a CXXConstructExpr
16464 // to find the source object needs to handle it.
16465 // Right now it assumes the source object is passed directly as the
16466 // first argument.
16467 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
16468 Expr *SubExpr = ExprArgs[0];
16469 // FIXME: Per above, this is also incorrect if we want to accept
16470 // converting constructors, as isTemporaryObject will
16471 // reject temporaries with different type from the
16472 // CXXRecord itself.
16473 Elidable = SubExpr->isTemporaryObject(
16475 }
16476
16477 return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
16478 FoundDecl, Constructor,
16479 Elidable, ExprArgs, HadMultipleCandidates,
16480 IsListInitialization,
16481 IsStdInitListInitialization, RequiresZeroInit,
16482 ConstructKind, ParenRange);
16483}
16484
16486 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
16487 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg ExprArgs,
16488 bool HadMultipleCandidates, bool IsListInitialization,
16489 bool IsStdInitListInitialization, bool RequiresZeroInit,
16490 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16491 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
16492 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
16493 // The only way to get here is if we did overload resolution to find the
16494 // shadow decl, so we don't need to worry about re-checking the trailing
16495 // requires clause.
16496 if (DiagnoseUseOfOverloadedDecl(Constructor, ConstructLoc))
16497 return ExprError();
16498 }
16499
16500 return BuildCXXConstructExpr(
16501 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
16502 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
16503 RequiresZeroInit, ConstructKind, ParenRange);
16504}
16505
16506/// BuildCXXConstructExpr - Creates a complete call to a constructor,
16507/// including handling of its default argument expressions.
16509 SourceLocation ConstructLoc, QualType DeclInitType,
16510 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg ExprArgs,
16511 bool HadMultipleCandidates, bool IsListInitialization,
16512 bool IsStdInitListInitialization, bool RequiresZeroInit,
16513 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16514 assert(declaresSameEntity(
16515 Constructor->getParent(),
16516 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
16517 "given constructor for wrong type");
16518 MarkFunctionReferenced(ConstructLoc, Constructor);
16519 if (getLangOpts().CUDA && !CUDA().CheckCall(ConstructLoc, Constructor))
16520 return ExprError();
16521
16524 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
16525 HadMultipleCandidates, IsListInitialization,
16526 IsStdInitListInitialization, RequiresZeroInit,
16527 static_cast<CXXConstructionKind>(ConstructKind), ParenRange),
16528 Constructor);
16529}
16530
16532 if (VD->isInvalidDecl()) return;
16533 // If initializing the variable failed, don't also diagnose problems with
16534 // the destructor, they're likely related.
16535 if (VD->getInit() && VD->getInit()->containsErrors())
16536 return;
16537
16538 ClassDecl = ClassDecl->getDefinitionOrSelf();
16539 if (ClassDecl->isInvalidDecl()) return;
16540 if (ClassDecl->hasIrrelevantDestructor()) return;
16541 if (ClassDecl->isDependentContext()) return;
16542
16543 if (VD->isNoDestroy(getASTContext()))
16544 return;
16545
16547 // The result of `LookupDestructor` might be nullptr if the destructor is
16548 // invalid, in which case it is marked as `IneligibleOrNotSelected` and
16549 // will not be selected by `CXXRecordDecl::getDestructor()`.
16550 if (!Destructor)
16551 return;
16552 // If this is an array, we'll require the destructor during initialization, so
16553 // we can skip over this. We still want to emit exit-time destructor warnings
16554 // though.
16555 if (!VD->getType()->isArrayType()) {
16558 PDiag(diag::err_access_dtor_var)
16559 << VD->getDeclName() << VD->getType());
16561 }
16562
16563 if (Destructor->isTrivial()) return;
16564
16565 // If the destructor is constexpr, check whether the variable has constant
16566 // destruction now.
16567 if (Destructor->isConstexpr()) {
16568 bool HasConstantInit = false;
16569 if (VD->getInit() && !VD->getInit()->isValueDependent())
16570 HasConstantInit = VD->evaluateValue();
16572 if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() &&
16573 HasConstantInit) {
16574 Diag(VD->getLocation(),
16575 diag::err_constexpr_var_requires_const_destruction) << VD;
16576 for (const PartialDiagnosticAt &Note : Notes)
16577 Diag(Note.first, Note.second);
16578 }
16579 }
16580
16581 if (!VD->hasGlobalStorage() || !VD->needsDestruction(Context))
16582 return;
16583
16584 // Emit warning for non-trivial dtor in global scope (a real global,
16585 // class-static, function-static).
16586 if (!VD->hasAttr<AlwaysDestroyAttr>())
16587 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
16588
16589 // TODO: this should be re-enabled for static locals by !CXAAtExit
16590 if (!VD->isStaticLocal())
16591 Diag(VD->getLocation(), diag::warn_global_destructor);
16592}
16593
16595 QualType DeclInitType, MultiExprArg ArgsPtr,
16596 SourceLocation Loc,
16597 SmallVectorImpl<Expr *> &ConvertedArgs,
16598 bool AllowExplicit,
16599 bool IsListInitialization) {
16600 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
16601 unsigned NumArgs = ArgsPtr.size();
16602 Expr **Args = ArgsPtr.data();
16603
16604 const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>();
16605 unsigned NumParams = Proto->getNumParams();
16606
16607 // If too few arguments are available, we'll fill in the rest with defaults.
16608 if (NumArgs < NumParams)
16609 ConvertedArgs.reserve(NumParams);
16610 else
16611 ConvertedArgs.reserve(NumArgs);
16612
16613 VariadicCallType CallType = Proto->isVariadic()
16616 SmallVector<Expr *, 8> AllArgs;
16618 Loc, Constructor, Proto, 0, llvm::ArrayRef(Args, NumArgs), AllArgs,
16619 CallType, AllowExplicit, IsListInitialization);
16620 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
16621
16622 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
16623
16624 CheckConstructorCall(Constructor, DeclInitType, llvm::ArrayRef(AllArgs),
16625 Proto, Loc);
16626
16627 return Invalid;
16628}
16629
16631 bool SeenTypedOperators = Context.hasSeenTypeAwareOperatorNewOrDelete();
16632 return typeAwareAllocationModeFromBool(SeenTypedOperators);
16633}
16634
16637 QualType DeallocType, SourceLocation Loc) {
16638 if (DeallocType.isNull())
16639 return nullptr;
16640
16641 FunctionDecl *FnDecl = FnTemplateDecl->getTemplatedDecl();
16642 if (!FnDecl->isTypeAwareOperatorNewOrDelete())
16643 return nullptr;
16644
16645 if (FnDecl->isVariadic())
16646 return nullptr;
16647
16648 unsigned NumParams = FnDecl->getNumParams();
16649 constexpr unsigned RequiredParameterCount =
16651 // A usual deallocation function has no placement parameters
16652 if (NumParams != RequiredParameterCount)
16653 return nullptr;
16654
16655 // A type aware allocation is only usual if the only dependent parameter is
16656 // the first parameter.
16657 if (llvm::any_of(FnDecl->parameters().drop_front(),
16658 [](const ParmVarDecl *ParamDecl) {
16659 return ParamDecl->getType()->isDependentType();
16660 }))
16661 return nullptr;
16662
16663 QualType SpecializedTypeIdentity = tryBuildStdTypeIdentity(DeallocType, Loc);
16664 if (SpecializedTypeIdentity.isNull())
16665 return nullptr;
16666
16668 ArgTypes.reserve(NumParams);
16669
16670 // The first parameter to a type aware operator delete is by definition the
16671 // type-identity argument, so we explicitly set this to the target
16672 // type-identity type, the remaining usual parameters should then simply match
16673 // the type declared in the function template.
16674 ArgTypes.push_back(SpecializedTypeIdentity);
16675 for (unsigned ParamIdx = 1; ParamIdx < RequiredParameterCount; ++ParamIdx)
16676 ArgTypes.push_back(FnDecl->getParamDecl(ParamIdx)->getType());
16677
16679 QualType ExpectedFunctionType =
16680 Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
16683 if (DeduceTemplateArguments(FnTemplateDecl, nullptr, ExpectedFunctionType,
16685 return nullptr;
16686 return Result;
16687}
16688
16689static inline bool
16691 const FunctionDecl *FnDecl) {
16692 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
16693 if (isa<NamespaceDecl>(DC)) {
16694 return SemaRef.Diag(FnDecl->getLocation(),
16695 diag::err_operator_new_delete_declared_in_namespace)
16696 << FnDecl->getDeclName();
16697 }
16698
16699 if (isa<TranslationUnitDecl>(DC) &&
16700 FnDecl->getStorageClass() == SC_Static) {
16701 return SemaRef.Diag(FnDecl->getLocation(),
16702 diag::err_operator_new_delete_declared_static)
16703 << FnDecl->getDeclName();
16704 }
16705
16706 return false;
16707}
16708
16710 const PointerType *PtrTy) {
16711 auto &Ctx = SemaRef.Context;
16712 Qualifiers PtrQuals = PtrTy->getPointeeType().getQualifiers();
16713 PtrQuals.removeAddressSpace();
16715 PtrTy->getPointeeType().getUnqualifiedType(), PtrQuals)));
16716}
16717
16719
16721 const FunctionDecl *FD,
16722 bool *WasMalformed) {
16723 const Decl *MalformedDecl = nullptr;
16724 if (FD->getNumParams() > 0 &&
16725 SemaRef.isStdTypeIdentity(FD->getParamDecl(0)->getType(),
16726 /*TypeArgument=*/nullptr, &MalformedDecl))
16727 return true;
16728
16729 if (!MalformedDecl)
16730 return false;
16731
16732 if (WasMalformed)
16733 *WasMalformed = true;
16734
16735 return true;
16736}
16737
16739 auto *RD = Type->getAsCXXRecordDecl();
16740 return RD && RD->isInStdNamespace() && RD->getIdentifier() &&
16741 RD->getIdentifier()->isStr("destroying_delete_t");
16742}
16743
16745 const FunctionDecl *FD) {
16746 // C++ P0722:
16747 // Within a class C, a single object deallocation function with signature
16748 // (T, std::destroying_delete_t, <more params>)
16749 // is a destroying operator delete.
16750 bool IsPotentiallyTypeAware = IsPotentiallyTypeAwareOperatorNewOrDelete(
16751 SemaRef, FD, /*WasMalformed=*/nullptr);
16752 unsigned DestroyingDeleteIdx = IsPotentiallyTypeAware + /* address */ 1;
16753 return isa<CXXMethodDecl>(FD) && FD->getOverloadedOperator() == OO_Delete &&
16754 FD->getNumParams() > DestroyingDeleteIdx &&
16755 isDestroyingDeleteT(FD->getParamDecl(DestroyingDeleteIdx)->getType());
16756}
16757
16759 Sema &SemaRef, FunctionDecl *FnDecl, AllocationOperatorKind OperatorKind,
16760 CanQualType ExpectedResultType, CanQualType ExpectedSizeOrAddressParamType,
16761 unsigned DependentParamTypeDiag, unsigned InvalidParamTypeDiag) {
16762 auto NormalizeType = [&SemaRef](QualType T) {
16763 if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
16764 // The operator is valid on any address space for OpenCL.
16765 // Drop address space from actual and expected result types.
16766 if (const auto PtrTy = T->template getAs<PointerType>())
16767 T = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
16768 }
16769 return SemaRef.Context.getCanonicalType(T);
16770 };
16771
16772 const unsigned NumParams = FnDecl->getNumParams();
16773 unsigned FirstNonTypeParam = 0;
16774 bool MalformedTypeIdentity = false;
16775 bool IsPotentiallyTypeAware = IsPotentiallyTypeAwareOperatorNewOrDelete(
16776 SemaRef, FnDecl, &MalformedTypeIdentity);
16777 unsigned MinimumMandatoryArgumentCount = 1;
16778 unsigned SizeParameterIndex = 0;
16779 if (IsPotentiallyTypeAware) {
16780 // We don't emit this diagnosis for template instantiations as we will
16781 // have already emitted it for the original template declaration.
16782 if (!FnDecl->isTemplateInstantiation())
16783 SemaRef.Diag(FnDecl->getLocation(), diag::warn_ext_type_aware_allocators);
16784
16785 if (OperatorKind == AllocationOperatorKind::New) {
16786 SizeParameterIndex = 1;
16787 MinimumMandatoryArgumentCount =
16789 } else {
16790 SizeParameterIndex = 2;
16791 MinimumMandatoryArgumentCount =
16793 }
16794 FirstNonTypeParam = 1;
16795 }
16796
16797 bool IsPotentiallyDestroyingDelete =
16799
16800 if (IsPotentiallyDestroyingDelete) {
16801 ++MinimumMandatoryArgumentCount;
16802 ++SizeParameterIndex;
16803 }
16804
16805 if (NumParams < MinimumMandatoryArgumentCount)
16806 return SemaRef.Diag(FnDecl->getLocation(),
16807 diag::err_operator_new_delete_too_few_parameters)
16808 << IsPotentiallyTypeAware << IsPotentiallyDestroyingDelete
16809 << FnDecl->getDeclName() << MinimumMandatoryArgumentCount;
16810
16811 for (unsigned Idx = 0; Idx < MinimumMandatoryArgumentCount; ++Idx) {
16812 const ParmVarDecl *ParamDecl = FnDecl->getParamDecl(Idx);
16813 if (ParamDecl->hasDefaultArg())
16814 return SemaRef.Diag(FnDecl->getLocation(),
16815 diag::err_operator_new_default_arg)
16816 << FnDecl->getDeclName() << Idx << ParamDecl->getDefaultArgRange();
16817 }
16818
16819 auto *FnType = FnDecl->getType()->castAs<FunctionType>();
16820 QualType CanResultType = NormalizeType(FnType->getReturnType());
16821 QualType CanExpectedResultType = NormalizeType(ExpectedResultType);
16822 QualType CanExpectedSizeOrAddressParamType =
16823 NormalizeType(ExpectedSizeOrAddressParamType);
16824
16825 // Check that the result type is what we expect.
16826 if (CanResultType != CanExpectedResultType) {
16827 // Reject even if the type is dependent; an operator delete function is
16828 // required to have a non-dependent result type.
16829 return SemaRef.Diag(
16830 FnDecl->getLocation(),
16831 CanResultType->isDependentType()
16832 ? diag::err_operator_new_delete_dependent_result_type
16833 : diag::err_operator_new_delete_invalid_result_type)
16834 << FnDecl->getDeclName() << ExpectedResultType;
16835 }
16836
16837 // A function template must have at least 2 parameters.
16838 if (FnDecl->getDescribedFunctionTemplate() && NumParams < 2)
16839 return SemaRef.Diag(FnDecl->getLocation(),
16840 diag::err_operator_new_delete_template_too_few_parameters)
16841 << FnDecl->getDeclName();
16842
16843 auto CheckType = [&](unsigned ParamIdx, QualType ExpectedType,
16844 auto FallbackType) -> bool {
16845 const ParmVarDecl *ParamDecl = FnDecl->getParamDecl(ParamIdx);
16846 if (ExpectedType.isNull()) {
16847 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
16848 << IsPotentiallyTypeAware << IsPotentiallyDestroyingDelete
16849 << FnDecl->getDeclName() << (1 + ParamIdx) << FallbackType
16850 << ParamDecl->getSourceRange();
16851 }
16852 CanQualType CanExpectedTy =
16853 NormalizeType(SemaRef.Context.getCanonicalType(ExpectedType));
16854 auto ActualParamType =
16855 NormalizeType(ParamDecl->getType().getUnqualifiedType());
16856 if (ActualParamType == CanExpectedTy)
16857 return false;
16858 unsigned Diagnostic = ActualParamType->isDependentType()
16859 ? DependentParamTypeDiag
16860 : InvalidParamTypeDiag;
16861 return SemaRef.Diag(FnDecl->getLocation(), Diagnostic)
16862 << IsPotentiallyTypeAware << IsPotentiallyDestroyingDelete
16863 << FnDecl->getDeclName() << (1 + ParamIdx) << ExpectedType
16864 << FallbackType << ParamDecl->getSourceRange();
16865 };
16866
16867 // Check that the first parameter type is what we expect.
16868 if (CheckType(FirstNonTypeParam, CanExpectedSizeOrAddressParamType, "size_t"))
16869 return true;
16870
16871 FnDecl->setIsDestroyingOperatorDelete(IsPotentiallyDestroyingDelete);
16872
16873 // If the first parameter type is not a type-identity we're done, otherwise
16874 // we need to ensure the size and alignment parameters have the correct type
16875 if (!IsPotentiallyTypeAware)
16876 return false;
16877
16878 if (CheckType(SizeParameterIndex, SemaRef.Context.getSizeType(), "size_t"))
16879 return true;
16880 TagDecl *StdAlignValTDecl = SemaRef.getStdAlignValT();
16881 CanQualType StdAlignValT =
16882 StdAlignValTDecl ? SemaRef.Context.getCanonicalTagType(StdAlignValTDecl)
16883 : CanQualType();
16884 if (CheckType(SizeParameterIndex + 1, StdAlignValT, "std::align_val_t"))
16885 return true;
16886
16888 return MalformedTypeIdentity;
16889}
16890
16891static bool CheckOperatorNewDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
16892 // C++ [basic.stc.dynamic.allocation]p1:
16893 // A program is ill-formed if an allocation function is declared in a
16894 // namespace scope other than global scope or declared static in global
16895 // scope.
16896 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
16897 return true;
16898
16899 CanQualType SizeTy =
16900 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
16901
16902 // C++ [basic.stc.dynamic.allocation]p1:
16903 // The return type shall be void*. The first parameter shall have type
16904 // std::size_t.
16906 SemaRef, FnDecl, AllocationOperatorKind::New, SemaRef.Context.VoidPtrTy,
16907 SizeTy, diag::err_operator_new_dependent_param_type,
16908 diag::err_operator_new_param_type);
16909}
16910
16911static bool
16913 // C++ [basic.stc.dynamic.deallocation]p1:
16914 // A program is ill-formed if deallocation functions are declared in a
16915 // namespace scope other than global scope or declared static in global
16916 // scope.
16917 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
16918 return true;
16919
16920 auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
16921 auto ConstructDestroyingDeleteAddressType = [&]() {
16922 assert(MD);
16923 return SemaRef.Context.getPointerType(
16924 SemaRef.Context.getCanonicalTagType(MD->getParent()));
16925 };
16926
16927 // C++ P2719: A destroying operator delete cannot be type aware
16928 // so for QoL we actually check for this explicitly by considering
16929 // an destroying-delete appropriate address type and the presence of
16930 // any parameter of type destroying_delete_t as an erroneous attempt
16931 // to declare a type aware destroying delete, rather than emitting a
16932 // pile of incorrect parameter type errors.
16934 SemaRef, MD, /*WasMalformed=*/nullptr)) {
16935 QualType AddressParamType =
16936 SemaRef.Context.getCanonicalType(MD->getParamDecl(1)->getType());
16937 if (AddressParamType != SemaRef.Context.VoidPtrTy &&
16938 AddressParamType == ConstructDestroyingDeleteAddressType()) {
16939 // The address parameter type implies an author trying to construct a
16940 // type aware destroying delete, so we'll see if we can find a parameter
16941 // of type `std::destroying_delete_t`, and if we find it we'll report
16942 // this as being an attempt at a type aware destroying delete just stop
16943 // here. If we don't do this, the resulting incorrect parameter ordering
16944 // results in a pile mismatched argument type errors that don't explain
16945 // the core problem.
16946 for (auto Param : MD->parameters()) {
16947 if (isDestroyingDeleteT(Param->getType())) {
16948 SemaRef.Diag(MD->getLocation(),
16949 diag::err_type_aware_destroying_operator_delete)
16950 << Param->getSourceRange();
16951 return true;
16952 }
16953 }
16954 }
16955 }
16956
16957 // C++ P0722:
16958 // Within a class C, the first parameter of a destroying operator delete
16959 // shall be of type C *. The first parameter of any other deallocation
16960 // function shall be of type void *.
16961 CanQualType ExpectedAddressParamType =
16962 MD && IsPotentiallyDestroyingOperatorDelete(SemaRef, MD)
16963 ? SemaRef.Context.getPointerType(
16964 SemaRef.Context.getCanonicalTagType(MD->getParent()))
16965 : SemaRef.Context.VoidPtrTy;
16966
16967 // C++ [basic.stc.dynamic.deallocation]p2:
16968 // Each deallocation function shall return void
16970 SemaRef, FnDecl, AllocationOperatorKind::Delete,
16971 SemaRef.Context.VoidTy, ExpectedAddressParamType,
16972 diag::err_operator_delete_dependent_param_type,
16973 diag::err_operator_delete_param_type))
16974 return true;
16975
16976 // C++ P0722:
16977 // A destroying operator delete shall be a usual deallocation function.
16978 if (MD && !MD->getParent()->isDependentContext() &&
16980 if (!SemaRef.isUsualDeallocationFunction(MD)) {
16981 SemaRef.Diag(MD->getLocation(),
16982 diag::err_destroying_operator_delete_not_usual);
16983 return true;
16984 }
16985 }
16986
16987 return false;
16988}
16989
16991 assert(FnDecl && FnDecl->isOverloadedOperator() &&
16992 "Expected an overloaded operator declaration");
16993
16995
16996 // C++ [over.oper]p5:
16997 // The allocation and deallocation functions, operator new,
16998 // operator new[], operator delete and operator delete[], are
16999 // described completely in 3.7.3. The attributes and restrictions
17000 // found in the rest of this subclause do not apply to them unless
17001 // explicitly stated in 3.7.3.
17002 if (Op == OO_Delete || Op == OO_Array_Delete)
17003 return CheckOperatorDeleteDeclaration(*this, FnDecl);
17004
17005 if (Op == OO_New || Op == OO_Array_New)
17006 return CheckOperatorNewDeclaration(*this, FnDecl);
17007
17008 // C++ [over.oper]p7:
17009 // An operator function shall either be a member function or
17010 // be a non-member function and have at least one parameter
17011 // whose type is a class, a reference to a class, an enumeration,
17012 // or a reference to an enumeration.
17013 // Note: Before C++23, a member function could not be static. The only member
17014 // function allowed to be static is the call operator function.
17015 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
17016 if (MethodDecl->isStatic()) {
17017 if (Op == OO_Call || Op == OO_Subscript)
17018 DiagCompat(FnDecl->getLocation(), diag_compat::operator_overload_static)
17019 << FnDecl;
17020 else
17021 return Diag(FnDecl->getLocation(), diag::err_operator_overload_static)
17022 << FnDecl;
17023 }
17024 } else {
17025 bool ClassOrEnumParam = false;
17026 for (auto *Param : FnDecl->parameters()) {
17027 QualType ParamType = Param->getType().getNonReferenceType();
17028 if (ParamType->isDependentType() || ParamType->isRecordType() ||
17029 ParamType->isEnumeralType()) {
17030 ClassOrEnumParam = true;
17031 break;
17032 }
17033 }
17034
17035 if (!ClassOrEnumParam)
17036 return Diag(FnDecl->getLocation(),
17037 diag::err_operator_overload_needs_class_or_enum)
17038 << FnDecl->getDeclName();
17039 }
17040
17041 // C++ [over.oper]p8:
17042 // An operator function cannot have default arguments (8.3.6),
17043 // except where explicitly stated below.
17044 //
17045 // Only the function-call operator (C++ [over.call]p1) and the subscript
17046 // operator (CWG2507) allow default arguments.
17047 if (Op != OO_Call) {
17048 ParmVarDecl *FirstDefaultedParam = nullptr;
17049 for (auto *Param : FnDecl->parameters()) {
17050 if (Param->hasDefaultArg()) {
17051 FirstDefaultedParam = Param;
17052 break;
17053 }
17054 }
17055 if (FirstDefaultedParam) {
17056 if (Op == OO_Subscript) {
17057 Diag(FnDecl->getLocation(), LangOpts.CPlusPlus23
17058 ? diag::ext_subscript_overload
17059 : diag::error_subscript_overload)
17060 << FnDecl->getDeclName() << 1
17061 << FirstDefaultedParam->getDefaultArgRange();
17062 } else {
17063 return Diag(FirstDefaultedParam->getLocation(),
17064 diag::err_operator_overload_default_arg)
17065 << FnDecl->getDeclName()
17066 << FirstDefaultedParam->getDefaultArgRange();
17067 }
17068 }
17069 }
17070
17071 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
17072 { false, false, false }
17073#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
17074 , { Unary, Binary, MemberOnly }
17075#include "clang/Basic/OperatorKinds.def"
17076 };
17077
17078 bool CanBeUnaryOperator = OperatorUses[Op][0];
17079 bool CanBeBinaryOperator = OperatorUses[Op][1];
17080 bool MustBeMemberOperator = OperatorUses[Op][2];
17081
17082 // C++ [over.oper]p8:
17083 // [...] Operator functions cannot have more or fewer parameters
17084 // than the number required for the corresponding operator, as
17085 // described in the rest of this subclause.
17086 unsigned NumParams = FnDecl->getNumParams() +
17087 (isa<CXXMethodDecl>(FnDecl) &&
17089 ? 1
17090 : 0);
17091 if (Op != OO_Call && Op != OO_Subscript &&
17092 ((NumParams == 1 && !CanBeUnaryOperator) ||
17093 (NumParams == 2 && !CanBeBinaryOperator) || (NumParams < 1) ||
17094 (NumParams > 2))) {
17095 // We have the wrong number of parameters.
17096 unsigned ErrorKind;
17097 if (CanBeUnaryOperator && CanBeBinaryOperator) {
17098 ErrorKind = 2; // 2 -> unary or binary.
17099 } else if (CanBeUnaryOperator) {
17100 ErrorKind = 0; // 0 -> unary
17101 } else {
17102 assert(CanBeBinaryOperator &&
17103 "All non-call overloaded operators are unary or binary!");
17104 ErrorKind = 1; // 1 -> binary
17105 }
17106 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
17107 << FnDecl->getDeclName() << NumParams << ErrorKind;
17108 }
17109
17110 if (Op == OO_Subscript && NumParams != 2) {
17111 Diag(FnDecl->getLocation(), LangOpts.CPlusPlus23
17112 ? diag::ext_subscript_overload
17113 : diag::error_subscript_overload)
17114 << FnDecl->getDeclName() << (NumParams == 1 ? 0 : 2);
17115 }
17116
17117 // Overloaded operators other than operator() and operator[] cannot be
17118 // variadic.
17119 if (Op != OO_Call &&
17120 FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) {
17121 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
17122 << FnDecl->getDeclName();
17123 }
17124
17125 // Some operators must be member functions.
17126 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
17127 return Diag(FnDecl->getLocation(),
17128 diag::err_operator_overload_must_be_member)
17129 << FnDecl->getDeclName();
17130 }
17131
17132 // C++ [over.inc]p1:
17133 // The user-defined function called operator++ implements the
17134 // prefix and postfix ++ operator. If this function is a member
17135 // function with no parameters, or a non-member function with one
17136 // parameter of class or enumeration type, it defines the prefix
17137 // increment operator ++ for objects of that type. If the function
17138 // is a member function with one parameter (which shall be of type
17139 // int) or a non-member function with two parameters (the second
17140 // of which shall be of type int), it defines the postfix
17141 // increment operator ++ for objects of that type.
17142 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
17143 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
17144 QualType ParamType = LastParam->getType();
17145
17146 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
17147 !ParamType->isDependentType())
17148 return Diag(LastParam->getLocation(),
17149 diag::err_operator_overload_post_incdec_must_be_int)
17150 << LastParam->getType() << (Op == OO_MinusMinus);
17151 }
17152
17153 return false;
17154}
17155
17156static bool
17158 FunctionTemplateDecl *TpDecl) {
17159 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
17160
17161 // Must have one or two template parameters.
17162 if (TemplateParams->size() == 1) {
17163 NonTypeTemplateParmDecl *PmDecl =
17164 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
17165
17166 // The template parameter must be a char parameter pack.
17167 if (PmDecl && PmDecl->isTemplateParameterPack() &&
17168 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
17169 return false;
17170
17171 // C++20 [over.literal]p5:
17172 // A string literal operator template is a literal operator template
17173 // whose template-parameter-list comprises a single non-type
17174 // template-parameter of class type.
17175 //
17176 // As a DR resolution, we also allow placeholders for deduced class
17177 // template specializations.
17178 if (SemaRef.getLangOpts().CPlusPlus20 && PmDecl &&
17179 !PmDecl->isTemplateParameterPack() &&
17180 (PmDecl->getType()->isRecordType() ||
17181 PmDecl->getType()->getAs<DeducedTemplateSpecializationType>()))
17182 return false;
17183 } else if (TemplateParams->size() == 2) {
17184 TemplateTypeParmDecl *PmType =
17185 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
17186 NonTypeTemplateParmDecl *PmArgs =
17187 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
17188
17189 // The second template parameter must be a parameter pack with the
17190 // first template parameter as its type.
17191 if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
17192 PmArgs->isTemplateParameterPack()) {
17193 if (const auto *TArgs =
17194 PmArgs->getType()->getAsCanonical<TemplateTypeParmType>();
17195 TArgs && TArgs->getDepth() == PmType->getDepth() &&
17196 TArgs->getIndex() == PmType->getIndex()) {
17197 if (!SemaRef.inTemplateInstantiation())
17198 SemaRef.Diag(TpDecl->getLocation(),
17199 diag::ext_string_literal_operator_template);
17200 return false;
17201 }
17202 }
17203 }
17204
17205 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
17206 diag::err_literal_operator_template)
17207 << TpDecl->getTemplateParameters()->getSourceRange();
17208 return true;
17209}
17210
17212 if (isa<CXXMethodDecl>(FnDecl)) {
17213 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
17214 << FnDecl->getDeclName();
17215 return true;
17216 }
17217
17218 if (FnDecl->isExternC()) {
17219 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
17220 if (const LinkageSpecDecl *LSD =
17221 FnDecl->getDeclContext()->getExternCContext())
17222 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
17223 return true;
17224 }
17225
17226 // This might be the definition of a literal operator template.
17228
17229 // This might be a specialization of a literal operator template.
17230 if (!TpDecl)
17231 TpDecl = FnDecl->getPrimaryTemplate();
17232
17233 // template <char...> type operator "" name() and
17234 // template <class T, T...> type operator "" name() are the only valid
17235 // template signatures, and the only valid signatures with no parameters.
17236 //
17237 // C++20 also allows template <SomeClass T> type operator "" name().
17238 if (TpDecl) {
17239 if (FnDecl->param_size() != 0) {
17240 Diag(FnDecl->getLocation(),
17241 diag::err_literal_operator_template_with_params);
17242 return true;
17243 }
17244
17246 return true;
17247
17248 } else if (FnDecl->param_size() == 1) {
17249 const ParmVarDecl *Param = FnDecl->getParamDecl(0);
17250
17251 QualType ParamType = Param->getType().getUnqualifiedType();
17252
17253 // Only unsigned long long int, long double, any character type, and const
17254 // char * are allowed as the only parameters.
17255 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
17256 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
17257 Context.hasSameType(ParamType, Context.CharTy) ||
17258 Context.hasSameType(ParamType, Context.WideCharTy) ||
17259 Context.hasSameType(ParamType, Context.Char8Ty) ||
17260 Context.hasSameType(ParamType, Context.Char16Ty) ||
17261 Context.hasSameType(ParamType, Context.Char32Ty)) {
17262 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
17263 QualType InnerType = Ptr->getPointeeType();
17264
17265 // Pointer parameter must be a const char *.
17266 if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
17267 Context.CharTy) &&
17268 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
17269 Diag(Param->getSourceRange().getBegin(),
17270 diag::err_literal_operator_param)
17271 << ParamType << "'const char *'" << Param->getSourceRange();
17272 return true;
17273 }
17274
17275 } else if (ParamType->isRealFloatingType()) {
17276 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
17277 << ParamType << Context.LongDoubleTy << Param->getSourceRange();
17278 return true;
17279
17280 } else if (ParamType->isIntegerType()) {
17281 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
17282 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
17283 return true;
17284
17285 } else {
17286 Diag(Param->getSourceRange().getBegin(),
17287 diag::err_literal_operator_invalid_param)
17288 << ParamType << Param->getSourceRange();
17289 return true;
17290 }
17291
17292 } else if (FnDecl->param_size() == 2) {
17293 FunctionDecl::param_iterator Param = FnDecl->param_begin();
17294
17295 // First, verify that the first parameter is correct.
17296
17297 QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
17298
17299 // Two parameter function must have a pointer to const as a
17300 // first parameter; let's strip those qualifiers.
17301 const PointerType *PT = FirstParamType->getAs<PointerType>();
17302
17303 if (!PT) {
17304 Diag((*Param)->getSourceRange().getBegin(),
17305 diag::err_literal_operator_param)
17306 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
17307 return true;
17308 }
17309
17310 QualType PointeeType = PT->getPointeeType();
17311 // First parameter must be const
17312 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
17313 Diag((*Param)->getSourceRange().getBegin(),
17314 diag::err_literal_operator_param)
17315 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
17316 return true;
17317 }
17318
17319 QualType InnerType = PointeeType.getUnqualifiedType();
17320 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
17321 // const char32_t* are allowed as the first parameter to a two-parameter
17322 // function
17323 if (!(Context.hasSameType(InnerType, Context.CharTy) ||
17324 Context.hasSameType(InnerType, Context.WideCharTy) ||
17325 Context.hasSameType(InnerType, Context.Char8Ty) ||
17326 Context.hasSameType(InnerType, Context.Char16Ty) ||
17327 Context.hasSameType(InnerType, Context.Char32Ty))) {
17328 Diag((*Param)->getSourceRange().getBegin(),
17329 diag::err_literal_operator_param)
17330 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
17331 return true;
17332 }
17333
17334 // Move on to the second and final parameter.
17335 ++Param;
17336
17337 // The second parameter must be a std::size_t.
17338 QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
17339 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
17340 Diag((*Param)->getSourceRange().getBegin(),
17341 diag::err_literal_operator_param)
17342 << SecondParamType << Context.getSizeType()
17343 << (*Param)->getSourceRange();
17344 return true;
17345 }
17346 } else {
17347 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
17348 return true;
17349 }
17350
17351 // Parameters are good.
17352
17353 // A parameter-declaration-clause containing a default argument is not
17354 // equivalent to any of the permitted forms.
17355 for (auto *Param : FnDecl->parameters()) {
17356 if (Param->hasDefaultArg()) {
17357 Diag(Param->getDefaultArgRange().getBegin(),
17358 diag::err_literal_operator_default_argument)
17359 << Param->getDefaultArgRange();
17360 break;
17361 }
17362 }
17363
17364 const IdentifierInfo *II = FnDecl->getDeclName().getCXXLiteralIdentifier();
17367 !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
17368 // C++23 [usrlit.suffix]p1:
17369 // Literal suffix identifiers that do not start with an underscore are
17370 // reserved for future standardization. Literal suffix identifiers that
17371 // contain a double underscore __ are reserved for use by C++
17372 // implementations.
17373 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
17374 << static_cast<int>(Status)
17376 }
17377
17378 return false;
17379}
17380
17382 Expr *LangStr,
17383 SourceLocation LBraceLoc) {
17384 StringLiteral *Lit = cast<StringLiteral>(LangStr);
17385 assert(Lit->isUnevaluated() && "Unexpected string literal kind");
17386
17387 StringRef Lang = Lit->getString();
17389 if (Lang == "C")
17391 else if (Lang == "C++")
17393 else {
17394 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
17395 << LangStr->getSourceRange();
17396 return nullptr;
17397 }
17398
17399 // FIXME: Add all the various semantics of linkage specifications
17400
17402 LangStr->getExprLoc(), Language,
17403 LBraceLoc.isValid());
17404
17405 /// C++ [module.unit]p7.2.3
17406 /// - Otherwise, if the declaration
17407 /// - ...
17408 /// - ...
17409 /// - appears within a linkage-specification,
17410 /// it is attached to the global module.
17411 ///
17412 /// If the declaration is already in global module fragment, we don't
17413 /// need to attach it again.
17414 if (getLangOpts().CPlusPlusModules && isCurrentModulePurview()) {
17415 Module *GlobalModule = PushImplicitGlobalModuleFragment(ExternLoc);
17416 D->setLocalOwningModule(GlobalModule);
17417 }
17418
17419 CurContext->addDecl(D);
17420 PushDeclContext(S, D);
17421 return D;
17422}
17423
17425 Decl *LinkageSpec,
17426 SourceLocation RBraceLoc) {
17427 if (RBraceLoc.isValid()) {
17428 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
17429 LSDecl->setRBraceLoc(RBraceLoc);
17430 }
17431
17432 // If the current module doesn't has Parent, it implies that the
17433 // LinkageSpec isn't in the module created by itself. So we don't
17434 // need to pop it.
17435 if (getLangOpts().CPlusPlusModules && getCurrentModule() &&
17436 getCurrentModule()->isImplicitGlobalModule() &&
17437 getCurrentModule()->Parent)
17438 PopImplicitGlobalModuleFragment();
17439
17441 return LinkageSpec;
17442}
17443
17445 const ParsedAttributesView &AttrList,
17446 SourceLocation SemiLoc) {
17447 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
17448 // Attribute declarations appertain to empty declaration so we handle
17449 // them here.
17450 ProcessDeclAttributeList(S, ED, AttrList);
17451
17452 CurContext->addDecl(ED);
17453 return ED;
17454}
17455
17457 SourceLocation StartLoc,
17458 SourceLocation Loc,
17459 const IdentifierInfo *Name) {
17460 bool Invalid = false;
17461 QualType ExDeclType = TInfo->getType();
17462
17463 // Arrays and functions decay.
17464 if (ExDeclType->isArrayType())
17465 ExDeclType = Context.getArrayDecayedType(ExDeclType);
17466 else if (ExDeclType->isFunctionType())
17467 ExDeclType = Context.getPointerType(ExDeclType);
17468
17469 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
17470 // The exception-declaration shall not denote a pointer or reference to an
17471 // incomplete type, other than [cv] void*.
17472 // N2844 forbids rvalue references.
17473 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
17474 Diag(Loc, diag::err_catch_rvalue_ref);
17475 Invalid = true;
17476 }
17477
17478 if (ExDeclType->isVariablyModifiedType()) {
17479 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
17480 Invalid = true;
17481 }
17482
17483 QualType BaseType = ExDeclType;
17484 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
17485 unsigned DK = diag::err_catch_incomplete;
17486 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
17487 BaseType = Ptr->getPointeeType();
17488 Mode = 1;
17489 DK = diag::err_catch_incomplete_ptr;
17490 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
17491 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
17492 BaseType = Ref->getPointeeType();
17493 Mode = 2;
17494 DK = diag::err_catch_incomplete_ref;
17495 }
17496 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
17497 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
17498 Invalid = true;
17499
17500 if (!Invalid && BaseType.isWebAssemblyReferenceType()) {
17501 Diag(Loc, diag::err_wasm_reftype_tc) << 1;
17502 Invalid = true;
17503 }
17504
17505 if (!Invalid && Mode != 1 && BaseType->isSizelessType()) {
17506 Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType;
17507 Invalid = true;
17508 }
17509
17510 if (!Invalid && !ExDeclType->isDependentType() &&
17511 RequireNonAbstractType(Loc, ExDeclType,
17512 diag::err_abstract_type_in_decl,
17514 Invalid = true;
17515
17516 // Only the non-fragile NeXT runtime currently supports C++ catches
17517 // of ObjC types, and no runtime supports catching ObjC types by value.
17518 if (!Invalid && getLangOpts().ObjC) {
17519 QualType T = ExDeclType;
17520 if (const ReferenceType *RT = T->getAs<ReferenceType>())
17521 T = RT->getPointeeType();
17522
17523 if (T->isObjCObjectType()) {
17524 Diag(Loc, diag::err_objc_object_catch);
17525 Invalid = true;
17526 } else if (T->isObjCObjectPointerType()) {
17527 // FIXME: should this be a test for macosx-fragile specifically?
17529 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
17530 }
17531 }
17532
17533 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
17534 ExDeclType, TInfo, SC_None);
17535 ExDecl->setExceptionVariable(true);
17536
17537 // In ARC, infer 'retaining' for variables of retainable type.
17538 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(ExDecl))
17539 Invalid = true;
17540
17541 if (!Invalid && !ExDeclType->isDependentType()) {
17542 if (auto *ClassDecl = ExDeclType->getAsCXXRecordDecl()) {
17543 // Insulate this from anything else we might currently be parsing.
17546
17547 // C++ [except.handle]p16:
17548 // The object declared in an exception-declaration or, if the
17549 // exception-declaration does not specify a name, a temporary (12.2) is
17550 // copy-initialized (8.5) from the exception object. [...]
17551 // The object is destroyed when the handler exits, after the destruction
17552 // of any automatic objects initialized within the handler.
17553 //
17554 // We just pretend to initialize the object with itself, then make sure
17555 // it can be destroyed later.
17556 QualType initType = Context.getExceptionObjectType(ExDeclType);
17557
17558 InitializedEntity entity =
17560 InitializationKind initKind =
17562
17563 Expr *opaqueValue =
17564 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
17565 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
17566 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
17567 if (result.isInvalid())
17568 Invalid = true;
17569 else {
17570 // If the constructor used was non-trivial, set this as the
17571 // "initializer".
17572 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
17573 if (!construct->getConstructor()->isTrivial()) {
17574 Expr *init = MaybeCreateExprWithCleanups(construct);
17575 ExDecl->setInit(init);
17576 }
17577
17578 // And make sure it's destructable.
17579 FinalizeVarWithDestructor(ExDecl, ClassDecl);
17580 }
17581 }
17582 }
17583
17584 if (Invalid)
17585 ExDecl->setInvalidDecl();
17586
17587 return ExDecl;
17588}
17589
17592 bool Invalid = D.isInvalidType();
17593
17594 // Check for unexpanded parameter packs.
17597 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
17598 D.getIdentifierLoc());
17599 Invalid = true;
17600 }
17601
17602 const IdentifierInfo *II = D.getIdentifier();
17603 if (NamedDecl *PrevDecl =
17606 // The scope should be freshly made just for us. There is just no way
17607 // it contains any previous declaration, except for function parameters in
17608 // a function-try-block's catch statement.
17609 assert(!S->isDeclScope(PrevDecl));
17610 if (isDeclInScope(PrevDecl, CurContext, S)) {
17611 Diag(D.getIdentifierLoc(), diag::err_redefinition)
17612 << D.getIdentifier();
17613 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
17614 Invalid = true;
17615 } else if (PrevDecl->isTemplateParameter())
17616 // Maybe we will complain about the shadowed template parameter.
17618 }
17619
17620 if (D.getCXXScopeSpec().isSet() && !Invalid) {
17621 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
17622 << D.getCXXScopeSpec().getRange();
17623 Invalid = true;
17624 }
17625
17627 S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
17628 if (Invalid)
17629 ExDecl->setInvalidDecl();
17630
17631 // Add the exception declaration into this scope.
17632 if (II)
17633 PushOnScopeChains(ExDecl, S);
17634 else
17635 CurContext->addDecl(ExDecl);
17636
17637 ProcessDeclAttributes(S, ExDecl, D);
17638 return ExDecl;
17639}
17640
17642 Expr *AssertExpr,
17643 Expr *AssertMessageExpr,
17644 SourceLocation RParenLoc) {
17646 return nullptr;
17647
17648 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
17649 AssertMessageExpr, RParenLoc, false);
17650}
17651
17652static void WriteCharTypePrefix(BuiltinType::Kind BTK, llvm::raw_ostream &OS) {
17653 switch (BTK) {
17654 case BuiltinType::Char_S:
17655 case BuiltinType::Char_U:
17656 break;
17657 case BuiltinType::Char8:
17658 OS << "u8";
17659 break;
17660 case BuiltinType::Char16:
17661 OS << 'u';
17662 break;
17663 case BuiltinType::Char32:
17664 OS << 'U';
17665 break;
17666 case BuiltinType::WChar_S:
17667 case BuiltinType::WChar_U:
17668 OS << 'L';
17669 break;
17670 default:
17671 llvm_unreachable("Non-character type");
17672 }
17673}
17674
17675/// Convert character's value, interpreted as a code unit, to a string.
17676/// The value needs to be zero-extended to 32-bits.
17677/// FIXME: This assumes Unicode literal encodings
17679 unsigned TyWidth,
17680 SmallVectorImpl<char> &Str) {
17681 char Arr[UNI_MAX_UTF8_BYTES_PER_CODE_POINT];
17682 char *Ptr = Arr;
17683 BuiltinType::Kind K = BTy->getKind();
17684 llvm::raw_svector_ostream OS(Str);
17685
17686 // This should catch Char_S, Char_U, Char8, and use of escaped characters in
17687 // other types.
17688 if (K == BuiltinType::Char_S || K == BuiltinType::Char_U ||
17689 K == BuiltinType::Char8 || Value <= 0x7F) {
17690 StringRef Escaped = escapeCStyle<EscapeChar::Single>(Value);
17691 if (!Escaped.empty())
17692 EscapeStringForDiagnostic(Escaped, Str);
17693 else
17694 OS << static_cast<char>(Value);
17695 return;
17696 }
17697
17698 switch (K) {
17699 case BuiltinType::Char16:
17700 case BuiltinType::Char32:
17701 case BuiltinType::WChar_S:
17702 case BuiltinType::WChar_U: {
17703 if (llvm::ConvertCodePointToUTF8(Value, Ptr))
17704 EscapeStringForDiagnostic(StringRef(Arr, Ptr - Arr), Str);
17705 else
17706 OS << "\\x"
17707 << llvm::format_hex_no_prefix(Value, TyWidth / 4, /*Upper=*/true);
17708 break;
17709 }
17710 default:
17711 llvm_unreachable("Non-character type is passed");
17712 }
17713}
17714
17715/// Convert \V to a string we can present to the user in a diagnostic
17716/// \T is the type of the expression that has been evaluated into \V
17719 ASTContext &Context) {
17720 if (!V.hasValue())
17721 return false;
17722
17723 switch (V.getKind()) {
17725 if (T->isBooleanType()) {
17726 // Bools are reduced to ints during evaluation, but for
17727 // diagnostic purposes we want to print them as
17728 // true or false.
17729 int64_t BoolValue = V.getInt().getExtValue();
17730 assert((BoolValue == 0 || BoolValue == 1) &&
17731 "Bool type, but value is not 0 or 1");
17732 llvm::raw_svector_ostream OS(Str);
17733 OS << (BoolValue ? "true" : "false");
17734 } else {
17735 llvm::raw_svector_ostream OS(Str);
17736 // Same is true for chars.
17737 // We want to print the character representation for textual types
17738 const auto *BTy = T->getAs<BuiltinType>();
17739 if (BTy) {
17740 switch (BTy->getKind()) {
17741 case BuiltinType::Char_S:
17742 case BuiltinType::Char_U:
17743 case BuiltinType::Char8:
17744 case BuiltinType::Char16:
17745 case BuiltinType::Char32:
17746 case BuiltinType::WChar_S:
17747 case BuiltinType::WChar_U: {
17748 unsigned TyWidth = Context.getIntWidth(T);
17749 assert(8 <= TyWidth && TyWidth <= 32 && "Unexpected integer width");
17750 uint32_t CodeUnit = static_cast<uint32_t>(V.getInt().getZExtValue());
17751 WriteCharTypePrefix(BTy->getKind(), OS);
17752 OS << '\'';
17753 WriteCharValueForDiagnostic(CodeUnit, BTy, TyWidth, Str);
17754 OS << "' (0x"
17755 << llvm::format_hex_no_prefix(CodeUnit, /*Width=*/2,
17756 /*Upper=*/true)
17757 << ", " << V.getInt() << ')';
17758 return true;
17759 }
17760 default:
17761 break;
17762 }
17763 }
17764 V.getInt().toString(Str);
17765 }
17766
17767 break;
17768
17770 V.getFloat().toString(Str);
17771 break;
17772
17774 if (V.isNullPointer()) {
17775 llvm::raw_svector_ostream OS(Str);
17776 OS << "nullptr";
17777 } else
17778 return false;
17779 break;
17780
17782 llvm::raw_svector_ostream OS(Str);
17783 OS << '(';
17784 V.getComplexFloatReal().toString(Str);
17785 OS << " + ";
17786 V.getComplexFloatImag().toString(Str);
17787 OS << "i)";
17788 } break;
17789
17791 llvm::raw_svector_ostream OS(Str);
17792 OS << '(';
17793 V.getComplexIntReal().toString(Str);
17794 OS << " + ";
17795 V.getComplexIntImag().toString(Str);
17796 OS << "i)";
17797 } break;
17798
17799 default:
17800 return false;
17801 }
17802
17803 return true;
17804}
17805
17806/// Some Expression types are not useful to print notes about,
17807/// e.g. literals and values that have already been expanded
17808/// before such as int-valued template parameters.
17809static bool UsefulToPrintExpr(const Expr *E) {
17810 E = E->IgnoreParenImpCasts();
17811 // Literals are pretty easy for humans to understand.
17814 return false;
17815
17816 // These have been substituted from template parameters
17817 // and appear as literals in the static assert error.
17819 return false;
17820
17821 // -5 is also simple to understand.
17822 if (const auto *UnaryOp = dyn_cast<UnaryOperator>(E))
17823 return UsefulToPrintExpr(UnaryOp->getSubExpr());
17824
17825 // Only print nested arithmetic operators.
17826 if (const auto *BO = dyn_cast<BinaryOperator>(E))
17827 return (BO->isShiftOp() || BO->isAdditiveOp() || BO->isMultiplicativeOp() ||
17828 BO->isBitwiseOp());
17829
17830 return true;
17831}
17832
17834 // FIXME: Should we also ignore explicit casts?
17835 E = E->IgnoreParenImpCasts();
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 if (const auto *RE = dyn_cast<RequiresExpr>(E)) {
17872 } else {
17874 }
17875}
17876
17877template <typename ResultType>
17878static bool EvaluateAsStringImpl(Sema &SemaRef, Expr *Message,
17879 ResultType &Result, ASTContext &Ctx,
17881 bool ErrorOnInvalidMessage) {
17882
17883 assert(Message);
17884 assert(!Message->isTypeDependent() && !Message->isValueDependent() &&
17885 "can't evaluate a dependant static assert message");
17886
17887 if (const auto *SL = dyn_cast<StringLiteral>(Message)) {
17888 assert(SL->isUnevaluated() && "expected an unevaluated string");
17889 if constexpr (std::is_same_v<APValue, ResultType>) {
17890 Result =
17891 APValue(APValue::UninitArray{}, SL->getLength(), SL->getLength());
17892 const ConstantArrayType *CAT =
17893 SemaRef.getASTContext().getAsConstantArrayType(SL->getType());
17894 assert(CAT && "string literal isn't an array");
17895 QualType CharType = CAT->getElementType();
17896 llvm::APSInt Value(SemaRef.getASTContext().getTypeSize(CharType),
17897 CharType->isUnsignedIntegerType());
17898 for (unsigned I = 0; I < SL->getLength(); I++) {
17899 Value = SL->getCodeUnit(I);
17900 Result.getArrayInitializedElt(I) = APValue(Value);
17901 }
17902 } else {
17903 Result.assign(SL->getString().begin(), SL->getString().end());
17904 }
17905 return true;
17906 }
17907
17908 SourceLocation Loc = Message->getBeginLoc();
17909 QualType T = Message->getType().getNonReferenceType();
17910 auto *RD = T->getAsCXXRecordDecl();
17911 if (!RD) {
17912 SemaRef.Diag(Loc, diag::err_user_defined_msg_invalid) << EvalContext;
17913 return false;
17914 }
17915
17916 auto FindMember = [&](StringRef Member) -> std::optional<LookupResult> {
17918 LookupResult MemberLookup(SemaRef, DN, Loc, Sema::LookupMemberName);
17919 SemaRef.LookupQualifiedName(MemberLookup, RD);
17920 OverloadCandidateSet Candidates(MemberLookup.getNameLoc(),
17922 if (MemberLookup.empty())
17923 return std::nullopt;
17924 return std::move(MemberLookup);
17925 };
17926
17927 std::optional<LookupResult> SizeMember = FindMember("size");
17928 std::optional<LookupResult> DataMember = FindMember("data");
17929 if (!SizeMember || !DataMember) {
17930 SemaRef.Diag(Loc, diag::err_user_defined_msg_missing_member_function)
17931 << EvalContext
17932 << ((!SizeMember && !DataMember) ? 2
17933 : !SizeMember ? 0
17934 : 1);
17935 return false;
17936 }
17937
17938 auto BuildExpr = [&](LookupResult &LR) {
17940 Message, Message->getType(), Message->getBeginLoc(), false,
17941 CXXScopeSpec(), SourceLocation(), nullptr, LR, nullptr, nullptr);
17942 if (Res.isInvalid())
17943 return ExprError();
17944 Res = SemaRef.BuildCallExpr(nullptr, Res.get(), Loc, {}, Loc, nullptr,
17945 false, true);
17946 if (Res.isInvalid())
17947 return ExprError();
17948 if (Res.get()->isTypeDependent() || Res.get()->isValueDependent())
17949 return ExprError();
17950 return SemaRef.TemporaryMaterializationConversion(Res.get());
17951 };
17952
17953 ExprResult SizeE = BuildExpr(*SizeMember);
17954 ExprResult DataE = BuildExpr(*DataMember);
17955
17956 QualType SizeT = SemaRef.Context.getSizeType();
17957 QualType ConstCharPtr = SemaRef.Context.getPointerType(
17958 SemaRef.Context.getConstType(SemaRef.Context.CharTy));
17959
17960 ExprResult EvaluatedSize =
17961 SizeE.isInvalid()
17962 ? ExprError()
17965 if (EvaluatedSize.isInvalid()) {
17966 SemaRef.Diag(Loc, diag::err_user_defined_msg_invalid_mem_fn_ret_ty)
17967 << EvalContext << /*size*/ 0;
17968 return false;
17969 }
17970
17971 ExprResult EvaluatedData =
17972 DataE.isInvalid()
17973 ? ExprError()
17975 DataE.get(), ConstCharPtr, CCEKind::StaticAssertMessageData);
17976 if (EvaluatedData.isInvalid()) {
17977 SemaRef.Diag(Loc, diag::err_user_defined_msg_invalid_mem_fn_ret_ty)
17978 << EvalContext << /*data*/ 1;
17979 return false;
17980 }
17981
17982 if (!ErrorOnInvalidMessage &&
17983 SemaRef.Diags.isIgnored(diag::warn_user_defined_msg_constexpr, Loc))
17984 return true;
17985
17986 Expr::EvalResult Status;
17988 Status.Diag = &Notes;
17989 if (!Message->EvaluateCharRangeAsString(Result, EvaluatedSize.get(),
17990 EvaluatedData.get(), Ctx, Status) ||
17991 !Notes.empty()) {
17992 SemaRef.Diag(Message->getBeginLoc(),
17993 ErrorOnInvalidMessage ? diag::err_user_defined_msg_constexpr
17994 : diag::warn_user_defined_msg_constexpr)
17995 << EvalContext;
17996 for (const auto &Note : Notes)
17997 SemaRef.Diag(Note.first, Note.second);
17998 return !ErrorOnInvalidMessage;
17999 }
18000 return true;
18001}
18002
18004 StringEvaluationContext EvalContext,
18005 bool ErrorOnInvalidMessage) {
18006 return EvaluateAsStringImpl(*this, Message, Result, Ctx, EvalContext,
18007 ErrorOnInvalidMessage);
18008}
18009
18010bool Sema::EvaluateAsString(Expr *Message, std::string &Result, ASTContext &Ctx,
18011 StringEvaluationContext EvalContext,
18012 bool ErrorOnInvalidMessage) {
18013 return EvaluateAsStringImpl(*this, Message, Result, Ctx, EvalContext,
18014 ErrorOnInvalidMessage);
18015}
18016
18018 Expr *AssertExpr, Expr *AssertMessage,
18019 SourceLocation RParenLoc,
18020 bool Failed) {
18021 assert(AssertExpr != nullptr && "Expected non-null condition");
18022 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
18023 (!AssertMessage || (!AssertMessage->isTypeDependent() &&
18024 !AssertMessage->isValueDependent())) &&
18025 !Failed) {
18026 // In a static_assert-declaration, the constant-expression shall be a
18027 // constant expression that can be contextually converted to bool.
18028 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
18029 if (Converted.isInvalid())
18030 Failed = true;
18031
18032 ExprResult FullAssertExpr =
18033 ActOnFinishFullExpr(Converted.get(), StaticAssertLoc,
18034 /*DiscardedValue*/ false,
18035 /*IsConstexpr*/ true);
18036 if (FullAssertExpr.isInvalid())
18037 Failed = true;
18038 else
18039 AssertExpr = FullAssertExpr.get();
18040
18041 llvm::APSInt Cond;
18042 Expr *BaseExpr = AssertExpr;
18044
18045 if (!getLangOpts().CPlusPlus) {
18046 // In C mode, allow folding as an extension for better compatibility with
18047 // C++ in terms of expressions like static_assert("test") or
18048 // static_assert(nullptr).
18049 FoldKind = AllowFoldKind::Allow;
18050 }
18051
18052 if (!Failed && VerifyIntegerConstantExpression(
18053 BaseExpr, &Cond,
18054 diag::err_static_assert_expression_is_not_constant,
18055 FoldKind).isInvalid())
18056 Failed = true;
18057
18058 // If the static_assert passes, only verify that
18059 // the message is grammatically valid without evaluating it.
18060 if (!Failed && AssertMessage && Cond.getBoolValue()) {
18061 std::string Str;
18062 EvaluateAsString(AssertMessage, Str, Context,
18064 /*ErrorOnInvalidMessage=*/false);
18065 }
18066
18067 // CWG2518
18068 // [dcl.pre]/p10 If [...] the expression is evaluated in the context of a
18069 // template definition, the declaration has no effect.
18070 bool InTemplateDefinition =
18071 getLangOpts().CPlusPlus && CurContext->isDependentContext();
18072
18073 if (!Failed && !Cond && !InTemplateDefinition) {
18074 SmallString<256> MsgBuffer;
18075 llvm::raw_svector_ostream Msg(MsgBuffer);
18076 bool HasMessage = AssertMessage;
18077 if (AssertMessage) {
18078 std::string Str;
18079 HasMessage = EvaluateAsString(AssertMessage, Str, Context,
18081 /*ErrorOnInvalidMessage=*/true) ||
18082 !Str.empty();
18083 Msg << Str;
18084 }
18085 Expr *InnerCond = nullptr;
18086 std::string InnerCondDescription;
18087 std::tie(InnerCond, InnerCondDescription) =
18088 findFailedBooleanCondition(Converted.get());
18089 if (const auto *ConceptIDExpr =
18090 dyn_cast_or_null<ConceptSpecializationExpr>(InnerCond)) {
18091 const ASTConstraintSatisfaction &Satisfaction =
18092 ConceptIDExpr->getSatisfaction();
18093 if (!Satisfaction.ContainsErrors || Satisfaction.NumRecords) {
18094 Diag(AssertExpr->getBeginLoc(), diag::err_static_assert_failed)
18095 << !HasMessage << Msg.str() << AssertExpr->getSourceRange();
18096 // Drill down into concept specialization expressions to see why they
18097 // weren't satisfied.
18098 DiagnoseUnsatisfiedConstraint(ConceptIDExpr);
18099 }
18100 } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond) &&
18101 !isa<IntegerLiteral>(InnerCond)) {
18102 Diag(InnerCond->getBeginLoc(),
18103 diag::err_static_assert_requirement_failed)
18104 << InnerCondDescription << !HasMessage << Msg.str()
18105 << InnerCond->getSourceRange();
18106 DiagnoseStaticAssertDetails(InnerCond);
18107 } else {
18108 Diag(AssertExpr->getBeginLoc(), diag::err_static_assert_failed)
18109 << !HasMessage << Msg.str() << AssertExpr->getSourceRange();
18111 }
18112 Failed = true;
18113 }
18114 } else {
18115 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
18116 /*DiscardedValue*/false,
18117 /*IsConstexpr*/true);
18118 if (FullAssertExpr.isInvalid())
18119 Failed = true;
18120 else
18121 AssertExpr = FullAssertExpr.get();
18122 }
18123
18125 AssertExpr, AssertMessage, RParenLoc,
18126 Failed);
18127
18128 CurContext->addDecl(Decl);
18129 return Decl;
18130}
18131
18133 if (const auto *PIT = dyn_cast<PackIndexingType>(T))
18134 return PIT->getPattern();
18135 return T;
18136}
18137
18138static const TemplateSpecializationType *
18141 if (const auto *ICNT = dyn_cast<InjectedClassNameType>(T))
18142 T = ICNT->getDecl()->getCanonicalTemplateSpecializationType(Context);
18143
18144 const auto *TST = dyn_cast<TemplateSpecializationType>(T);
18145 if (!TST)
18146 return nullptr;
18147
18148 TemplateDecl *TD = TST->getTemplateName().getAsTemplateDecl();
18149 if (!TD || isa<ClassTemplateDecl>(TD))
18150 return TST;
18151 return nullptr;
18152}
18153
18155 NestedNameSpecifierLoc NNSLoc) {
18156 for (TypeLoc TL = NNSLoc.getAsTypeLoc(); TL;
18157 TL = TL.getPrefix().getAsTypeLoc()) {
18158 if (TL.getTypeLocClass() != TypeLoc::PackIndexing)
18159 continue;
18160
18161 Diag(Loc, diag::err_pack_indexing_in_friend) << TL.getSourceRange();
18162 return true;
18163 }
18164 return false;
18165}
18166
18168 NestedNameSpecifier NNS) {
18169 QualType T(NNS.getAsType(), 0);
18170 if (const auto *TST =
18171 dyn_cast<TemplateSpecializationType>(IgnorePackIndexing(T))) {
18172 if (isa_and_nonnull<TypeAliasTemplateDecl>(
18173 TST->getTemplateName().getAsTemplateDecl())) {
18174 S.Diag(Loc, diag::err_dependent_friend_not_member_of_template_spec)
18175 << NNS;
18176 return;
18177 }
18178 }
18179
18180 if (NNS.getAsRecordDecl()) {
18181 S.Diag(Loc, diag::err_dependent_friend_not_member_of_template_spec) << NNS;
18182 } else {
18183 S.Diag(Loc, diag::err_dependent_friend_not_member);
18184 }
18185}
18186
18190 bool IsInstantiation) {
18192 if (!NNS.isDependent() && !IsInstantiation)
18193 return false;
18194
18195 assert(NNS.getKind() == NestedNameSpecifier::Kind::Type &&
18196 "nested-name-specifier of dependent friend must be a type");
18197
18198 QualType T(NNS.getAsType(), 0);
18199 if (DiagnosePackIndexingInFriendNNS(Loc, NNSLoc))
18200 return true;
18201
18202 const TemplateSpecializationType *TST =
18204 if (!TST) {
18205 DiagnoseDependentFriendNotMember(*this, Loc, NNS);
18206 return true;
18207 }
18208
18209 if (TPLs.empty())
18210 return false;
18211
18212 SmallVector<NamedDecl *, 4> UndeducedParameters;
18213 for (TemplateParameterList *Params : TPLs) {
18214 llvm::SmallBitVector UsedParameters(Params->size());
18215 MarkUsedTemplateParameters(TST->template_arguments(),
18216 /*OnlyDeduced=*/true, Params->getDepth(),
18217 UsedParameters);
18218
18219 for (unsigned I = 0, N = UsedParameters.size(); I != N; ++I)
18220 if (!UsedParameters[I])
18221 UndeducedParameters.push_back(Params->getParam(I));
18222 }
18223
18224 if (UndeducedParameters.empty())
18225 return false;
18226
18227 Diag(Loc, diag::err_dependent_friend_undeduced_params)
18228 << (UndeducedParameters.size() > 1) << QualType(TST, 0);
18229
18230 for (NamedDecl *Param : UndeducedParameters) {
18231 if (Param->getDeclName())
18232 Diag(Param->getLocation(), diag::note_non_deducible_parameter)
18233 << Param->getDeclName();
18234 else
18235 Diag(Param->getLocation(), diag::note_non_deducible_parameter)
18236 << "(anonymous)";
18237 }
18238
18239 return true;
18240}
18241
18243 Scope *S, SourceLocation FriendLoc, unsigned TagSpec, SourceLocation TagLoc,
18244 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
18245 SourceLocation EllipsisLoc, const ParsedAttributesView &Attr,
18246 MultiTemplateParamsArg TempParamLists, TemplateIdAnnotation *TemplateId) {
18248
18249 bool IsMemberSpecialization = false;
18250 bool Invalid = false;
18251
18252 TemplateParameterList *TemplateParams =
18253 MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS, TemplateId,
18254 TempParamLists, /*friend*/ true,
18255 IsMemberSpecialization, Invalid);
18256 if (TemplateId) {
18257 if (Invalid)
18258 return true;
18259
18260 if (TemplateParams) {
18261 Diag(NameLoc, diag::err_not_class_template_specialization) << 0;
18262 return true;
18263 }
18264 }
18265
18266 if (TemplateParams) {
18267 if (TemplateParams->size() > 0) {
18268 if (Invalid)
18269 return true;
18270
18271 if (SS.isEmpty() || !SS.getScopeRep().isDependent()) {
18273 S, TagSpec, TagUseKind::Friend, TagLoc, SS, Name, NameLoc, Attr,
18274 TemplateParams, AS_public, /*ModulePrivateLoc=*/SourceLocation(),
18275 FriendLoc, TempParamLists.size() - 1, TempParamLists.data(),
18276 IsMemberSpecialization);
18277 return Result.get();
18278 }
18279 } else {
18280 // The "template<>" header is extraneous.
18281 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
18282 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
18283 }
18284 }
18285
18286 if (Invalid)
18287 return true;
18288
18289 bool IsAllExplicitSpecializations =
18290 llvm::all_of(TempParamLists, [](const TemplateParameterList *List) {
18291 return List->size() == 0;
18292 });
18293
18294 // FIXME: don't ignore attributes.
18295
18296 // If it's explicit specializations all the way down, just forget
18297 // about the template header and build an appropriate non-templated
18298 // friend. TODO: for source fidelity, remember the headers.
18300 if (!TemplateId && IsAllExplicitSpecializations) {
18301 if (SS.isEmpty()) {
18302 bool Owned = false;
18303 bool IsDependent = false;
18304 return ActOnTag(S, TagSpec, TagUseKind::Friend, TagLoc, SS, Name, NameLoc,
18305 Attr, AS_public,
18306 /*ModulePrivateLoc=*/SourceLocation(),
18307 MultiTemplateParamsArg(), Owned, IsDependent,
18308 /*ScopedEnumKWLoc=*/SourceLocation(),
18309 /*ScopedEnumUsesClassTag=*/false,
18310 /*UnderlyingType=*/TypeResult(),
18311 /*IsTypeSpecifier=*/false,
18312 /*IsTemplateParamOrArg=*/false,
18313 /*OOK=*/OffsetOfKind::Outside);
18314 }
18315
18316 TypeSourceInfo *TSI = nullptr;
18319 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, *Name,
18320 NameLoc, &TSI, /*DeducedTSTContext=*/true);
18321 if (T.isNull())
18322 return true;
18323
18325 FriendLoc, EllipsisLoc);
18326 Friend->setAccess(AS_public);
18327 CurContext->addDecl(Friend);
18328 return Friend;
18329 }
18330
18331 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
18332
18333 ArrayRef<TemplateParameterList *> TPLs = TempParamLists;
18334 if (TemplateParams)
18335 TPLs = TPLs.drop_back();
18336 if (CheckDependentFriend(TagLoc, QualifierLoc, TPLs,
18337 /*IsInstantiation=*/false))
18338 return true;
18339
18340 TypeSourceInfo *TSI = nullptr;
18341 if (TemplateId) {
18342 ASTTemplateArgsPtr ParsedArgs(TemplateId->getTemplateArgs(),
18343 TemplateId->NumArgs);
18345 TagUseKind::Friend, static_cast<TypeSpecifierType>(TagSpec), TagLoc, SS,
18346 TemplateId->TemplateKWLoc, TemplateId->Template, NameLoc,
18347 TemplateId->LAngleLoc, ParsedArgs, TemplateId->RAngleLoc);
18348 if (ParsedType.isInvalid())
18349 return true;
18350
18351 GetTypeFromParser(ParsedType.get(), &TSI);
18352 } else {
18354 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
18355 TSI = Context.CreateTypeSourceInfo(T);
18356
18358 TL.setElaboratedKeywordLoc(TagLoc);
18359 TL.setQualifierLoc(QualifierLoc);
18360 TL.setNameLoc(NameLoc);
18361 }
18362
18364 collectUnexpandedParameterPacks(TSI->getTypeLoc(), Unexpanded);
18365 if (EllipsisLoc.isInvalid()) {
18367 return true;
18368 } else if (Unexpanded.empty()) {
18369 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
18370 << TSI->getTypeLoc().getSourceRange();
18371 return true;
18372 } else {
18373 // CWG 2917: a pack expanded by a friend-type-specifier cannot have been
18374 // introduced by the template-declaration containing that specifier.
18375 if (!TempParamLists.empty()) {
18376 unsigned FriendDeclDepth = TempParamLists.front()->getDepth();
18377 for (UnexpandedParameterPack &U : Unexpanded) {
18378 if (std::optional<std::pair<unsigned, unsigned>> DI =
18380 DI && DI->first >= FriendDeclDepth) {
18381 auto *ND = dyn_cast<NamedDecl *>(U.first);
18382 if (!ND)
18383 ND = cast<const TemplateTypeParmType *>(U.first)->getDecl();
18384 Diag(U.second, diag::friend_template_decl_malformed_pack_expansion)
18385 << ND->getDeclName()
18386 << SourceRange(TSI->getTypeLoc().getBeginLoc(), EllipsisLoc);
18387 return true;
18388 }
18389 }
18390 }
18391 }
18392
18394 if (TempParamLists.empty())
18395 Friend = FriendDecl::Create(Context, CurContext, NameLoc, TSI, FriendLoc,
18396 EllipsisLoc);
18397 else {
18398 if (CheckTemplateDeclScope(S, TempParamLists.back()))
18399 return true;
18400
18402 if (TemplateParams)
18403 FriendTemplate = Context.getDependentTemplateName(
18404 {SS.getScopeRep(), Name, /*HasTemplateKeyword=*/false});
18405 Friend =
18406 FriendTemplateDecl::Create(Context, CurContext, NameLoc, TSI, FriendLoc,
18407 TempParamLists, EllipsisLoc, FriendTemplate);
18408 }
18409
18410 Friend->setAccess(AS_public);
18411 CurContext->addDecl(Friend);
18412
18413 return Friend;
18414}
18415
18417 MultiTemplateParamsArg TempParams,
18418 SourceLocation EllipsisLoc) {
18419 SourceLocation Loc = DS.getBeginLoc();
18420 SourceLocation FriendLoc = DS.getFriendSpecLoc();
18421
18422 assert(DS.isFriendSpecified());
18424
18425 // C++ [class.friend]p3:
18426 // A friend declaration that does not declare a function shall have one of
18427 // the following forms:
18428 // friend elaborated-type-specifier ;
18429 // friend simple-type-specifier ;
18430 // friend typename-specifier ;
18431 //
18432 // If the friend keyword isn't first, or if the declarations has any type
18433 // qualifiers, then the declaration doesn't have that form.
18435 Diag(FriendLoc, diag::err_friend_not_first_in_declaration);
18436 if (DS.getTypeQualifiers()) {
18438 Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
18440 Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
18442 Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
18444 Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
18446 Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
18447 }
18448
18449 // Try to convert the decl specifier to a type. This works for
18450 // friend templates because ActOnTag never produces a ClassTemplateDecl
18451 // for a TagUseKind::Friend.
18452 Declarator TheDeclarator(DS, ParsedAttributesView::none(),
18454 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator);
18455 QualType T = TSI->getType();
18456 if (TheDeclarator.isInvalidType())
18457 return nullptr;
18458
18459 // If '...' is present, the type must contain an unexpanded parameter
18460 // pack, and vice versa.
18461 bool Invalid = false;
18462 if (EllipsisLoc.isInvalid() &&
18464 return nullptr;
18465 if (EllipsisLoc.isValid() &&
18467 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
18468 << TSI->getTypeLoc().getSourceRange();
18469 Invalid = true;
18470 }
18471
18472 if (!T->isElaboratedTypeSpecifier()) {
18473 if (TempParams.size()) {
18474 // C++23 [dcl.pre]p5:
18475 // In a simple-declaration, the optional init-declarator-list can be
18476 // omitted only when declaring a class or enumeration, that is, when
18477 // the decl-specifier-seq contains either a class-specifier, an
18478 // elaborated-type-specifier with a class-key, or an enum-specifier.
18479 //
18480 // The declaration of a template-declaration or explicit-specialization
18481 // is never a member-declaration, so this must be a simple-declaration
18482 // with no init-declarator-list. Therefore, this is ill-formed.
18483 Diag(Loc, diag::err_tagless_friend_type_template) << DS.getSourceRange();
18484 return nullptr;
18485 } else if (const RecordDecl *RD = T->getAsRecordDecl()) {
18486 SmallString<16> InsertionText(" ");
18487 InsertionText += RD->getKindName();
18488
18490 ? diag::warn_cxx98_compat_unelaborated_friend_type
18491 : diag::ext_unelaborated_friend_type)
18492 << (unsigned)RD->getTagKind() << T
18494 InsertionText);
18495 } else {
18496 DiagCompat(FriendLoc, diag_compat::nonclass_type_friend)
18497 << T << DS.getSourceRange();
18498 }
18499 }
18500
18501 // C++98 [class.friend]p1: A friend of a class is a function
18502 // or class that is not a member of the class . . .
18503 // This is fixed in DR77, which just barely didn't make the C++03
18504 // deadline. It's also a very silly restriction that seriously
18505 // affects inner classes and which nobody else seems to implement;
18506 // thus we never diagnose it, not even in -pedantic.
18507 //
18508 // But note that we could warn about it: it's always useless to
18509 // friend one of your own members (it's not, however, worthless to
18510 // friend a member of an arbitrary specialization of your template).
18511
18512 Decl *D;
18513 if (!TempParams.empty()) {
18514 if (CheckTemplateDeclScope(S, TempParams.back()))
18515 return nullptr;
18516
18517 // TODO: Support variadic friend template decls?
18518 D = FriendTemplateDecl::Create(Context, CurContext, Loc, TSI, FriendLoc,
18519 TempParams, EllipsisLoc);
18520 } else
18522 TSI, FriendLoc, EllipsisLoc);
18523
18524 if (!D)
18525 return nullptr;
18526
18527 D->setAccess(AS_public);
18528 CurContext->addDecl(D);
18529
18530 if (Invalid)
18531 D->setInvalidDecl();
18532
18533 return D;
18534}
18535
18537 MultiTemplateParamsArg TemplateParams) {
18538 const DeclSpec &DS = D.getDeclSpec();
18539
18540 assert(DS.isFriendSpecified());
18542
18545
18546 // C++ [class.friend]p1
18547 // A friend of a class is a function or class....
18548 // Note that this sees through typedefs, which is intended.
18549 // It *doesn't* see through dependent types, which is correct
18550 // according to [temp.arg.type]p3:
18551 // If a declaration acquires a function type through a
18552 // type dependent on a template-parameter and this causes
18553 // a declaration that does not use the syntactic form of a
18554 // function declarator to have a function type, the program
18555 // is ill-formed.
18556 if (!TInfo->getType()->isFunctionType()) {
18557 Diag(Loc, diag::err_unexpected_friend);
18558
18559 // It might be worthwhile to try to recover by creating an
18560 // appropriate declaration.
18561 return nullptr;
18562 }
18563
18564 // C++ [namespace.memdef]p3
18565 // - If a friend declaration in a non-local class first declares a
18566 // class or function, the friend class or function is a member
18567 // of the innermost enclosing namespace.
18568 // - The name of the friend is not found by simple name lookup
18569 // until a matching declaration is provided in that namespace
18570 // scope (either before or after the class declaration granting
18571 // friendship).
18572 // - If a friend function is called, its name may be found by the
18573 // name lookup that considers functions from namespaces and
18574 // classes associated with the types of the function arguments.
18575 // - When looking for a prior declaration of a class or a function
18576 // declared as a friend, scopes outside the innermost enclosing
18577 // namespace scope are not considered.
18578
18579 CXXScopeSpec &SS = D.getCXXScopeSpec();
18581 assert(NameInfo.getName());
18582
18584 NameInfo.getLoc(), SS.getWithLocInContext(Context)))
18585 return nullptr;
18586
18587 // Check for unexpanded parameter packs.
18591 return nullptr;
18592
18593 bool isTemplateId = D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
18594
18595 if (D.isFunctionDefinition() && SS.isNotEmpty() && !isTemplateId) {
18596 auto Kind = SS.getScopeRep().getKind();
18597 bool IsNamespaceOrGlobal = Kind == NestedNameSpecifier::Kind::Global ||
18599 if (IsNamespaceOrGlobal) {
18600 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
18601 << SS.getScopeRep();
18602 SS.clear();
18603 }
18604 }
18605
18606 // The context we found the declaration in, or in which we should
18607 // create the declaration.
18608 DeclContext *DC;
18609 Scope *DCScope = S;
18610 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
18612
18613 // There are five cases here.
18614 // - There's no scope specifier and we're in a local class. Only look
18615 // for functions declared in the immediately-enclosing block scope.
18616 // We recover from invalid scope qualifiers as if they just weren't there.
18617 FunctionDecl *FunctionContainingLocalClass = nullptr;
18618 if ((SS.isInvalid() || !SS.isSet()) &&
18619 (FunctionContainingLocalClass =
18620 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
18621 // C++11 [class.friend]p11:
18622 // If a friend declaration appears in a local class and the name
18623 // specified is an unqualified name, a prior declaration is
18624 // looked up without considering scopes that are outside the
18625 // innermost enclosing non-class scope. For a friend function
18626 // declaration, if there is no prior declaration, the program is
18627 // ill-formed.
18628
18629 // Find the innermost enclosing non-class scope. This is the block
18630 // scope containing the local class definition (or for a nested class,
18631 // the outer local class).
18632 DCScope = S->getFnParent();
18633
18634 // Look up the function name in the scope.
18636 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
18637
18638 if (!Previous.empty()) {
18639 // All possible previous declarations must have the same context:
18640 // either they were declared at block scope or they are members of
18641 // one of the enclosing local classes.
18642 DC = Previous.getRepresentativeDecl()->getDeclContext();
18643 } else {
18644 // This is ill-formed, but provide the context that we would have
18645 // declared the function in, if we were permitted to, for error recovery.
18646 DC = FunctionContainingLocalClass;
18647 }
18649
18650 // - There's no scope specifier, in which case we just go to the
18651 // appropriate scope and look for a function or function template
18652 // there as appropriate.
18653 } else if (SS.isInvalid() || !SS.isSet()) {
18654 // C++11 [namespace.memdef]p3:
18655 // If the name in a friend declaration is neither qualified nor
18656 // a template-id and the declaration is a function or an
18657 // elaborated-type-specifier, the lookup to determine whether
18658 // the entity has been previously declared shall not consider
18659 // any scopes outside the innermost enclosing namespace.
18660
18661 // Find the appropriate context according to the above.
18662 DC = CurContext;
18663
18664 // Skip class contexts. If someone can cite chapter and verse
18665 // for this behavior, that would be nice --- it's what GCC and
18666 // EDG do, and it seems like a reasonable intent, but the spec
18667 // really only says that checks for unqualified existing
18668 // declarations should stop at the nearest enclosing namespace,
18669 // not that they should only consider the nearest enclosing
18670 // namespace.
18671 while (DC->isRecord())
18672 DC = DC->getParent();
18673
18674 DeclContext *LookupDC = DC->getNonTransparentContext();
18675 while (true) {
18676 LookupQualifiedName(Previous, LookupDC);
18677
18678 if (!Previous.empty()) {
18679 DC = LookupDC;
18680 break;
18681 }
18682
18683 if (isTemplateId) {
18684 if (isa<TranslationUnitDecl>(LookupDC)) break;
18685 } else {
18686 if (LookupDC->isFileContext()) break;
18687 }
18688 LookupDC = LookupDC->getParent();
18689 }
18690
18691 DCScope = getScopeForDeclContext(S, DC);
18692
18693 // - There's a non-dependent scope specifier, in which case we
18694 // compute it and do a previous lookup there for a function
18695 // or function template.
18696 } else if (!SS.getScopeRep().isDependent()) {
18697 DC = computeDeclContext(SS);
18698 if (!DC) return nullptr;
18699
18700 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
18701
18703
18704 // C++ [class.friend]p1: A friend of a class is a function or
18705 // class that is not a member of the class . . .
18706 if (DC->Equals(CurContext))
18709 diag::warn_cxx98_compat_friend_is_member :
18710 diag::err_friend_is_member);
18711
18712 // - There's a dependent scope specifier, in which case we use an
18713 // arbitrary context and wait for instantiation.
18714 } else {
18715 DC = CurContext;
18716 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
18717 }
18718
18719 if (!DC->isRecord()) {
18720 int DiagArg = -1;
18721 switch (D.getName().getKind()) {
18724 DiagArg = 0;
18725 break;
18727 DiagArg = 1;
18728 break;
18730 DiagArg = 2;
18731 break;
18733 DiagArg = 3;
18734 break;
18740 break;
18741 }
18742 // This implies that it has to be an operator or function.
18743 if (DiagArg >= 0) {
18744 Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
18745 return nullptr;
18746 }
18747 } else {
18748 CXXRecordDecl *RC = dyn_cast<CXXRecordDecl>(DC);
18749 if (RC->isLambda()) {
18750 Diag(NameInfo.getBeginLoc(), diag::err_friend_lambda_decl);
18751 }
18752 }
18753
18754 // FIXME: This is an egregious hack to cope with cases where the scope stack
18755 // does not contain the declaration context, i.e., in an out-of-line
18756 // definition of a class.
18757 Scope FakeDCScope(S, Scope::DeclScope, Diags);
18758 if (!DCScope) {
18759 FakeDCScope.setEntity(DC);
18760 DCScope = &FakeDCScope;
18761 }
18762
18763 bool AddToScope = true;
18764 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
18765 TemplateParams, AddToScope);
18766 if (!ND) return nullptr;
18767
18768 assert(ND->getLexicalDeclContext() == CurContext);
18769
18770 // If we performed typo correction, we might have added a scope specifier
18771 // and changed the decl context.
18772 DC = ND->getDeclContext();
18773
18774 // Add the function declaration to the appropriate lookup tables,
18775 // adjusting the redeclarations list as necessary. We don't
18776 // want to do this yet if the friending class is dependent.
18777 //
18778 // Also update the scope-based lookup if the target context's
18779 // lookup context is in lexical scope.
18780 if (!CurContext->isDependentContext()) {
18781 DC = DC->getRedeclContext();
18783 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
18784 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
18785 }
18786
18788
18789 if (ND->isInvalidDecl()) {
18792 Friend->setAccess(AS_public);
18794 Friend->setInvalidDecl();
18795 CurContext->addDecl(Friend);
18796 return ND;
18797 }
18798
18799 FunctionDecl *FD = ND->getAsFunction();
18800 assert(FD && "Expected a function declaration!");
18801
18803 if (!TPLs.empty() && SS.isValid() && CheckTemplateDeclScope(S, TPLs.back()))
18804 return nullptr;
18805
18807 if (!TPLs.empty() && SS.isValid())
18808 Friend =
18810 ND, DS.getFriendSpecLoc(), TPLs);
18811 else
18813 DS.getFriendSpecLoc());
18814
18815 Friend->setAccess(AS_public);
18816 CurContext->addDecl(Friend);
18817
18818 if (DC->isRecord())
18820
18821 if (!TemplateParams.empty() && SS.isValid() &&
18824 /*IsInstantiation=*/false))
18825 return ND;
18826
18827 // C++ [class.friend]p6:
18828 // A function may be defined in a friend declaration of a class if and
18829 // only if the class is a non-local class, and the function name is
18830 // unqualified.
18831 if (D.isFunctionDefinition()) {
18832 // Qualified friend function definition.
18833 if (SS.isNotEmpty()) {
18835 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
18836
18837 DB << SS.getScopeRep();
18838
18839 // Friend function defined in a local class.
18840 } else if (FunctionContainingLocalClass) {
18841 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
18842
18843 // Per [basic.pre]p4, a template-id is not a name. Therefore, if we have
18844 // a template-id, the function name is not unqualified because these is
18845 // no name. While the wording requires some reading in-between the
18846 // lines, GCC, MSVC, and EDG all consider a friend function
18847 // specialization definitions to be de facto explicit specialization
18848 // and diagnose them as such.
18849 } else if (isTemplateId) {
18850 Diag(NameInfo.getBeginLoc(), diag::err_friend_specialization_def);
18851 }
18852 }
18853
18854 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
18855 // default argument expression, that declaration shall be a definition
18856 // and shall be the only declaration of the function or function
18857 // template in the translation unit.
18859 // We can't look at FD->getPreviousDecl() because it may not have been set
18860 // if we're in a dependent context. If the function is known to be a
18861 // redeclaration, we will have narrowed Previous down to the right decl.
18862 if (D.isRedeclaration()) {
18863 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
18864 Diag(Previous.getRepresentativeDecl()->getLocation(),
18865 diag::note_previous_declaration);
18866 } else if (!D.isFunctionDefinition())
18867 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
18868 }
18869
18870 return ND;
18871}
18872
18874 StringLiteral *Message) {
18876
18877 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
18878 if (!Fn) {
18879 Diag(DelLoc, diag::err_deleted_non_function);
18880 return;
18881 }
18882
18883 // Deleted function does not have a body.
18884 Fn->setWillHaveBody(false);
18885
18886 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
18887 // Don't consider the implicit declaration we generate for explicit
18888 // specializations. FIXME: Do not generate these implicit declarations.
18889 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
18890 Prev->getPreviousDecl()) &&
18891 !Prev->isDefined()) {
18892 Diag(DelLoc, diag::err_deleted_decl_not_first);
18893 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
18894 Prev->isImplicit() ? diag::note_previous_implicit_declaration
18895 : diag::note_previous_declaration);
18896 // We can't recover from this; the declaration might have already
18897 // been used.
18898 Fn->setInvalidDecl();
18899 return;
18900 }
18901
18902 // To maintain the invariant that functions are only deleted on their first
18903 // declaration, mark the implicitly-instantiated declaration of the
18904 // explicitly-specialized function as deleted instead of marking the
18905 // instantiated redeclaration.
18906 Fn = Fn->getCanonicalDecl();
18907 }
18908
18909 // dllimport/dllexport cannot be deleted.
18910 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
18911 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
18912 Fn->setInvalidDecl();
18913 }
18914
18915 // C++11 [basic.start.main]p3:
18916 // A program that defines main as deleted [...] is ill-formed.
18917 if (Fn->isMain())
18918 Diag(DelLoc, diag::err_deleted_main);
18919
18920 // C++11 [dcl.fct.def.delete]p4:
18921 // A deleted function is implicitly inline.
18922 Fn->setImplicitlyInline();
18923 Fn->setDeletedAsWritten(true, Message);
18924}
18925
18927 if (!Dcl || Dcl->isInvalidDecl())
18928 return;
18929
18930 auto *FD = dyn_cast<FunctionDecl>(Dcl);
18931 if (!FD) {
18932 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) {
18933 if (FTD->getTemplatedDecl()->getDefaultedFunctionKind().isComparison()) {
18934 Diag(DefaultLoc, diag::err_defaulted_comparison_template);
18935 return;
18936 }
18937 }
18938
18939 Diag(DefaultLoc, diag::err_default_special_members)
18940 << getLangOpts().CPlusPlus20;
18941 return;
18942 }
18943
18944 // Reject if this can't possibly be a defaultable function.
18945 FunctionDecl::DefaultedFunctionKind DefKind = FD->getDefaultedFunctionKind();
18946 if (!DefKind &&
18947 // A dependent function that doesn't locally look defaultable can
18948 // still instantiate to a defaultable function if it's a constructor
18949 // or assignment operator.
18950 (!FD->isDependentContext() ||
18952 FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) {
18953 Diag(DefaultLoc, diag::err_default_special_members)
18954 << getLangOpts().CPlusPlus20;
18955 return;
18956 }
18957
18958 // Issue compatibility warning. We already warned if the operator is
18959 // 'operator<=>' when parsing the '<=>' token.
18960 if (DefKind.isComparison() &&
18962 DiagCompat(DefaultLoc, diag_compat::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:832
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:828
const LangOptions & getLangOpts() const
Definition ASTContext.h:985
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:881
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:947
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:3525
unsigned shadow_size() const
Return the number of shadowed declarations associated with this using declaration.
Definition DeclCXX.h:3603
void addShadowDecl(UsingShadowDecl *S)
Definition DeclCXX.cpp:3516
shadow_iterator shadow_begin() const
Definition DeclCXX.h:3595
void removeShadowDecl(UsingShadowDecl *S)
Definition DeclCXX.cpp:3525
Expr * getLHS() const
Definition Expr.h:4132
Expr * getRHS() const
Definition Expr.h:4134
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:5131
static bool isCompoundAssignmentOp(Opcode Opc)
Definition Expr.h:4223
Opcode getOpcode() const
Definition Expr.h:4127
static Opcode getOverloadedOpcode(OverloadedOperatorKind OO)
Retrieve the binary opcode that corresponds to the given overloaded operator.
Definition Expr.cpp:2173
A binding in a decomposition declaration.
Definition DeclCXX.h:4214
void setDecomposedDecl(DecompositionDecl *Decomposed)
Set the decomposed variable for this BindingDecl.
Definition DeclCXX.h:4258
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:4252
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition Expr.h:6722
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:727
CXXCatchStmt - This represents a C++ catch block.
Definition StmtCXX.h:29
Represents a call to a C++ constructor.
Definition ExprCXX.h:1552
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:1213
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition ExprCXX.h:1695
bool isImmediateEscalating() const
Definition ExprCXX.h:1710
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition ExprCXX.h:1615
Represents a C++ constructor within a class.
Definition DeclCXX.h:2641
CXXConstructorDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:2881
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:2735
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:2876
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:2713
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2976
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition DeclCXX.h:3012
Represents a C++ base or member initializer.
Definition DeclCXX.h:2406
bool isWritten() const
Determine whether this initializer is explicitly written in the source code.
Definition DeclCXX.h:2578
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:2486
TypeSourceInfo * getTypeSourceInfo() const
Returns the declarator information for a base class or delegating initializer.
Definition DeclCXX.h:2540
FieldDecl * getAnyMember() const
Definition DeclCXX.h:2552
A default argument (C++ [dcl.fct.default]).
Definition ExprCXX.h:1274
Represents a C++ destructor within a class.
Definition DeclCXX.h:2906
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:1755
Represents a call to a member function that may be written either with member call syntax (e....
Definition ExprCXX.h:183
CXXMethodDecl * getMethodDecl() const
Retrieve the declaration of the called method.
Definition ExprCXX.cpp:774
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2149
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:2204
CXXSpecialMemberKind getSpecialMemberKind() const
Definition DeclCXX.h:2228
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:2320
CXXMethodDecl * getMostRecentDecl()
Definition DeclCXX.h:2269
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:2292
bool isInstance() const
Definition DeclCXX.h:2176
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition DeclCXX.cpp:2751
QualType getFunctionObjectParameterType() const
Definition DeclCXX.h:2316
bool isStatic() const
Definition DeclCXX.cpp:2417
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:2262
The null pointer literal (C++11 [lex.nullptr])
Definition ExprCXX.h:772
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:1285
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:1356
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:1255
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:1381
bool hasUserDeclaredDestructor() const
Determine whether this class has a user-declared destructor.
Definition DeclCXX.h:1010
bool implicitCopyConstructorHasConstParam() const
Determine whether an implicit copy constructor for this type would have a parameter with a const-qual...
Definition DeclCXX.h:826
bool defaultedDestructorIsDeleted() const
true if a defaulted destructor for this class would be deleted.
Definition DeclCXX.h:718
bool hasInheritedAssignment() const
Determine whether this class has a using-declaration that names a base class assignment operator.
Definition DeclCXX.h:1435
bool allowConstDefaultInit() const
Determine whether declaring a const variable with this type is ok per core issue 253.
Definition DeclCXX.h:1406
bool hasTrivialDestructorForCall() const
Definition DeclCXX.h:1385
bool defaultedMoveConstructorIsDeleted() const
true if a defaulted move constructor for this class would be deleted.
Definition DeclCXX.h:710
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:969
bool defaultedDestructorIsConstexpr() const
Determine whether a defaulted default constructor for this class would be constexpr.
Definition DeclCXX.h:1371
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:1027
bool hasTrivialMoveConstructor() const
Determine whether this class has a trivial move constructor (C++11 [class.copy]p12)
Definition DeclCXX.h:1316
bool needsImplicitDefaultConstructor() const
Determine if we need to declare a default constructor for this class.
Definition DeclCXX.h:770
bool needsImplicitMoveConstructor() const
Determine whether this class should get an implicit move constructor or if any existing special membe...
Definition DeclCXX.h:898
bool hasUserDeclaredCopyAssignment() const
Determine whether this class has a user-declared copy assignment operator.
Definition DeclCXX.h:917
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:939
static AccessSpecifier MergeAccess(AccessSpecifier PathAccess, AccessSpecifier DeclAccess)
Calculates the access of a decl that is reached along a path.
Definition DeclCXX.h:1744
bool defaultedDefaultConstructorIsConstexpr() const
Determine whether a defaulted default constructor for this class would be constexpr.
Definition DeclCXX.h:1278
bool hasTrivialCopyConstructor() const
Determine whether this class has a trivial copy constructor (C++ [class.copy]p6, C++11 [class....
Definition DeclCXX.h:1293
void setImplicitMoveAssignmentIsDeleted()
Set that we attempted to declare an implicit move assignment operator, but overload resolution failed...
Definition DeclCXX.h:981
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:1223
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:701
bool hasTrivialCopyConstructorForCall() const
Definition DeclCXX.h:1297
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:1343
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:873
bool isAbstract() const
Determine whether this class has a pure virtual function.
Definition DeclCXX.h:1230
bool hasVariantMembers() const
Determine whether this class has any variant members.
Definition DeclCXX.h:1245
void setImplicitCopyConstructorIsDeleted()
Set that we attempted to declare an implicit copy constructor, but overload resolution failed so we d...
Definition DeclCXX.h:864
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:1157
bool needsImplicitCopyConstructor() const
Determine whether this class needs an implicit copy constructor to be lazily declared.
Definition DeclCXX.h:804
bool hasIrrelevantDestructor() const
Determine whether this class has a destructor which has no semantic effect.
Definition DeclCXX.h:1417
bool hasNonTrivialCopyConstructorForCall() const
Definition DeclCXX.h:1308
bool hasDirectFields() const
Determine whether this class has direct non-static data members.
Definition DeclCXX.h:1209
bool hasUserDeclaredCopyConstructor() const
Determine whether this class has a user-declared copy constructor.
Definition DeclCXX.h:798
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:923
bool needsImplicitDestructor() const
Determine whether this class needs an implicit destructor to be lazily declared.
Definition DeclCXX.h:1016
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:909
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:1003
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
Definition DeclCXX.cpp:2129
bool hasNonTrivialDestructorForCall() const
Definition DeclCXX.h:1395
bool needsOverloadResolutionForDestructor() const
Determine whether we need to eagerly declare a destructor for this class.
Definition DeclCXX.h:1022
bool hasInheritedConstructor() const
Determine whether this class has a using-declaration that names a user-declared base class constructo...
Definition DeclCXX.h:1429
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:811
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:852
bool needsImplicitMoveAssignment() const
Determine whether this class should get an implicit move assignment operator or if any existing speci...
Definition DeclCXX.h:991
bool needsImplicitCopyAssignment() const
Determine whether this class needs an implicit copy assignment operator to be lazily declared.
Definition DeclCXX.h:932
bool hasTrivialMoveConstructorForCall() const
Definition DeclCXX.h:1321
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:954
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:1158
SourceLocation getBeginLoc() const
Definition ExprCXX.h:1178
bool isImplicit() const
Definition ExprCXX.h:1181
SourceLocation getLocation() const
Definition ExprCXX.h:1175
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:2987
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3191
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3170
bool isCallToStdMove() const
Definition Expr.cpp:3676
Expr * getCallee()
Definition Expr.h:3134
arg_range arguments()
Definition Expr.h:3239
QualType withConst() const
Retrieves a version of this type with const applied.
CastKind getCastKind() const
Definition Expr.h:3764
Expr * getSubExpr()
Definition Expr.h:3770
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:1752
body_range body()
Definition Stmt.h:1815
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:3706
const CXXRecordDecl * getParent() const
Returns the parent of this using shadow declaration, which is the class in which this is declared.
Definition DeclCXX.h:3770
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:5401
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:1290
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:1358
NonOdrUseReason isNonOdrUse() const
Is this expression a non-odr-use reference, and if so, why?
Definition Expr.h:1488
SourceLocation getBeginLoc() const
Definition Expr.h:1369
bool isImmediateEscalating() const
Definition Expr.h:1498
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:1643
decl_range decls()
Definition Stmt.h:1691
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.h:1669
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:100
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:781
SourceLocation getTypeSpecStartLoc() const
Definition Decl.cpp:2006
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:832
const AssociatedConstraint & getTrailingRequiresClause() const
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition Decl.h:856
void setTypeSourceInfo(TypeSourceInfo *TI)
Definition Decl.h:815
ArrayRef< TemplateParameterList * > getTemplateParameterLists() const
Definition Decl.h:863
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:810
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:4278
ArrayRef< BindingDecl * > bindings() const
Definition DeclCXX.h:4318
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:5959
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:3558
Represents an enum.
Definition Decl.h:4146
enumerator_range enumerators() const
Definition Decl.h:4292
EvaluatedExprVisitor - This class visits 'Expr *'s.
Store information needed for an explicit specifier.
Definition DeclCXX.h:1948
const Expr * getExpr() const
Definition DeclCXX.h:1957
void setExpr(Expr *E)
Definition DeclCXX.h:1982
void setKind(ExplicitSpecKind Kind)
Definition DeclCXX.h:1981
This represents one expression.
Definition Expr.h:113
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:178
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:195
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3123
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3111
bool containsErrors() const
Whether this expression contains subexpressions which had errors.
Definition Expr.h:247
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3119
bool isPRValue() const
Definition Expr.h:286
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition Expr.h:285
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:3286
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:145
Represents difference between two FPOptions values.
FPOptions applyOverrides(FPOptions Base)
Represents a member of a struct/union/class.
Definition Decl.h:3295
bool isMutable() const
Determines whether this field is mutable (C++ only).
Definition Decl.h:3395
Expr * getInClassInitializer() const
Get the C++11 default member initializer for this member, or null if one has not been set.
Definition Decl.cpp:4789
bool hasInClassInitializer() const
Determine whether this member has a C++11 default member initializer.
Definition Decl.h:3475
bool isAnonymousStructOrUnion() const
Determines whether this field is a representative for an anonymous struct or union.
Definition Decl.cpp:4779
InClassInitStyle getInClassInitStyle() const
Get the kind of (C++11) default member initializer that this field has.
Definition Decl.h:3469
void setInClassInitializer(Expr *NewInit)
Set the C++11 in-class initializer for this member.
Definition Decl.cpp:4799
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3531
FieldDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this field.
Definition Decl.h:3542
bool isUnnamedBitField() const
Determines whether this is an unnamed bitfield.
Definition Decl.h:3401
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:2123
CXXSpecialMemberKind asSpecialMember() const
Definition Decl.h:2152
DefaultedComparisonKind asComparison() const
Definition Decl.h:2155
static DefaultedOrDeletedFunctionInfo * Create(ASTContext &Context, ArrayRef< DeclAccessPair > Lookups, FPOptionsOverride FPFeatures, StringLiteral *DeletedMessage=nullptr)
Definition Decl.cpp:3128
Represents a function declaration or definition.
Definition Decl.h:2059
static constexpr unsigned RequiredTypeAwareDeleteParameterCount
Count of mandatory parameters for type aware operator delete.
Definition Decl.h:2773
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2928
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition Decl.cpp:3268
ExceptionSpecificationType getExceptionSpecType() const
Gets the ExceptionSpecificationType as declared.
Definition Decl.h:3000
bool isTrivialForCall() const
Definition Decl.h:2507
ConstexprSpecKind getConstexprKind() const
Definition Decl.h:2603
DefaultedOrDeletedFunctionInfo * getDefaultedOrDeletedInfo() const
Definition Decl.cpp:3183
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to call this function.
Definition Decl.cpp:3891
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4234
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
Definition Decl.h:2428
bool isImmediateFunction() const
Definition Decl.cpp:3384
void setDefaultedOrDeletedInfo(DefaultedOrDeletedFunctionInfo *Info)
Definition Decl.cpp:3149
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type.
Definition Decl.cpp:4068
bool isDestroyingOperatorDelete() const
Determine whether this is a destroying operator delete.
Definition Decl.cpp:3595
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3909
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition Decl.h:3052
SourceLocation getDefaultLoc() const
Definition Decl.h:2525
QualType getReturnType() const
Definition Decl.h:2976
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2905
bool isExplicitlyDefaulted() const
Whether this function is explicitly defaulted.
Definition Decl.h:2516
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition Decl.h:2504
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition Decl.cpp:4354
MutableArrayRef< ParmVarDecl * >::iterator param_iterator
Definition Decl.h:2913
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3791
param_iterator param_begin()
Definition Decl.h:2917
const ParmVarDecl * getNonObjectParameter(unsigned I) const
Definition Decl.h:2954
bool isVariadic() const
Whether this function is variadic.
Definition Decl.cpp:3121
bool doesThisDeclarationHaveABody() const
Returns whether this specific declaration of the function has a body.
Definition Decl.h:2440
bool isDeleted() const
Whether this function has been deleted.
Definition Decl.h:2667
void setBodyContainsImmediateEscalatingExpressions(bool Set)
Definition Decl.h:2613
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4370
FunctionEffectsRef getFunctionEffects() const
Definition Decl.h:3269
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition Decl.cpp:4298
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition Decl.h:3019
bool isStatic() const
Definition Decl.h:3060
void setTrivial(bool IT)
Definition Decl.h:2505
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition Decl.cpp:4185
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition Decl.h:2597
static constexpr unsigned RequiredTypeAwareNewParameterCount
Count of mandatory parameters for type aware operator new.
Definition Decl.h:2769
bool isPureVirtual() const
Whether this virtual function is pure, i.e.
Definition Decl.h:2480
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition Decl.cpp:3662
FunctionDecl * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
bool isImmediateEscalating() const
Definition Decl.cpp:3355
void setIsDestroyingOperatorDelete(bool IsDestroyingDelete)
Definition Decl.cpp:3599
bool isTypeAwareOperatorNewOrDelete() const
Determine whether this is a type aware operator new or delete.
Definition Decl.cpp:3603
void setIsTypeAwareOperatorNewOrDelete(bool IsTypeAwareOperator=true)
Definition Decl.cpp:3607
bool isDefaulted() const
Whether this function is defaulted.
Definition Decl.h:2512
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:4610
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
Definition Decl.h:3064
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition Decl.cpp:4171
void setConstexprKind(ConstexprSpecKind CSK)
Definition Decl.h:2600
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition Decl.cpp:4458
void setDefaulted(bool D=true)
Definition Decl.h:2513
bool isConsteval() const
Definition Decl.h:2609
bool isUserProvided() const
True if this method is user-declared and was not deleted or defaulted on its first declaration.
Definition Decl.h:2537
DefaultedFunctionKind getDefaultedFunctionKind() const
Determine the kind of defaulting that would be done for a given function.
Definition Decl.cpp:3288
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:2993
void setBody(Stmt *B)
Definition Decl.cpp:3280
bool isVirtualAsWritten() const
Whether this function is marked as virtual explicitly.
Definition Decl.h:2471
bool hasOneParamOrDefaultArgs() const
Determine whether this function has a single parameter, or multiple parameters where all but the firs...
Definition Decl.cpp:3923
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3870
size_t param_size() const
Definition Decl.h:2921
DeclarationNameInfo getNameInfo() const
Definition Decl.h:2325
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition Decl.cpp:3188
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:3235
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:2936
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition Decl.h:2816
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:5865
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:1834
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:2271
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:1751
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition Expr.cpp:2103
Represents an implicitly-generated value initialization of an object of a given type.
Definition Expr.h:6107
Represents a field injected from an anonymous union/struct into the parent scope.
Definition Decl.h:3602
ArrayRef< NamedDecl * > chain() const
Definition Decl.h:3623
void setInherited(bool I)
Definition Attr.h:163
Description of a constructor that was inherited from a base class.
Definition DeclCXX.h:2612
ConstructorUsingShadowDecl * getShadowDecl() const
Definition DeclCXX.h:2624
const TypeClass * getTypePtr() const
Definition TypeLoc.h:526
Describes an C or C++ initializer list.
Definition Expr.h:5352
unsigned getNumInits() const
Definition Expr.h:5385
const Expr * getInit(unsigned Init) const
Definition Expr.h:5407
child_range children()
Definition Expr.h:5548
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:1391
capture_range captures() const
Retrieve this lambda's captures.
Definition ExprCXX.cpp:1404
@ 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:3044
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:3086
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:4378
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:3408
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3491
Expr * getBase() const
Definition Expr.h:3485
SourceLocation getExprLoc() const LLVM_READONLY
Definition Expr.h:3603
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:275
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:488
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:296
bool isPlaceholderVar(const LangOptions &LangOpts) const
Definition Decl.cpp:1096
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:341
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:3230
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:574
NamespaceDecl * getNamespace()
Definition DeclCXX.cpp:3351
Represent a C++ namespace.
Definition Decl.h:593
bool isInline() const
Returns true if this is an inline namespace declaration.
Definition Decl.h:649
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:676
void setRBraceLoc(SourceLocation L)
Definition Decl.h:695
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:1198
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:5003
Represents a parameter to a function.
Definition Decl.h:1820
void setDefaultArg(Expr *defarg)
Definition Decl.cpp:3010
void setUnparsedDefaultArg()
Specify that this parameter has an unparsed default argument.
Definition Decl.h:1961
bool hasUnparsedDefaultArg() const
Determines whether this parameter has a default argument that has not yet been parsed.
Definition Decl.h:1949
SourceRange getDefaultArgRange() const
Retrieve the source range that covers the entire default argument.
Definition Decl.cpp:3015
void setUninstantiatedDefaultArg(Expr *arg)
Definition Decl.cpp:3035
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition Decl.h:1853
bool hasUninstantiatedDefaultArg() const
Definition Decl.h:1953
bool hasInheritedDefaultArg() const
Definition Decl.h:1965
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:2945
Expr * getUninstantiatedDefaultArg()
Definition Decl.cpp:3040
bool hasDefaultArg() const
Determines whether this parameter has a default argument, either parsed or not.
Definition Decl.cpp:3046
void setHasInheritedDefaultArg(bool I=true)
Definition Decl.h:1969
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:2968
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:6926
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:8585
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8590
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:8501
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8541
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:8686
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8595
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:8574
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition TypeBase.h:8547
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:2820
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:8666
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:4460
bool hasFlexibleArrayMember() const
Definition Decl.h:4493
bool hasObjectMember() const
Definition Decl.h:4520
field_iterator field_end() const
Definition Decl.h:4666
field_range fields() const
Definition Decl.h:4663
specific_decl_iterator< FieldDecl > field_iterator
Definition Decl.h:4660
RecordDecl * getDefinitionOrSelf() const
Definition Decl.h:4648
bool isAnonymousStructOrUnion() const
Whether this is an anonymous struct or union.
Definition Decl.h:4512
bool field_empty() const
Definition Decl.h:4671
field_iterator field_begin() const
Definition Decl.cpp:5339
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:5465
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:1313
A RAII object to temporarily push a declaration context.
Definition Sema.h:3532
Records and restores the CurFPFeatures state on entry/exit of compound statements.
Definition Sema.h:14155
Helper class that collects exception specifications for implicitly-declared special member functions.
Definition Sema.h:5560
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:5602
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:9332
CXXMethodDecl * getMethod() const
Definition Sema.h:9344
RAII object to handle the state changes required to synthesize a function body.
Definition Sema.h:13640
Abstract base class used for diagnosing integer constant expression violations.
Definition Sema.h:7746
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:863
void DefineImplicitLambdaToFunctionPointerConversion(SourceLocation CurrentLoc, CXXConversionDecl *Conv)
Define the "body" of the conversion from a lambda object to a function pointer.
QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement)
Substitute Replacement for auto in TypeWithAuto.
CXXConstructorDecl * DeclareImplicitDefaultConstructor(CXXRecordDecl *ClassDecl)
Declare the implicit default constructor for the given class.
bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S)
MergeCXXFunctionDecl - Merge two declarations of the same C++ function, once we already know that the...
Attr * getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, bool IsDefinition)
Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a containing class.
MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, CXXRecordDecl *ClassDecl)
void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D)
QualType getCurrentThisType()
Try to retrieve the type of the 'this' pointer.
bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range)
CheckSpecifiedExceptionType - Check if the given type is valid in an exception specification.
ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation, SourceLocation ConvLocation, CXXConversionDecl *Conv, Expr *Src)
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition Sema.h:13158
sema::CapturingScopeInfo * getEnclosingLambdaOrBlock() const
Get the innermost lambda or block enclosing the current location, if any.
Definition Sema.cpp:2701
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:6580
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:9370
@ LookupUsingDeclName
Look up all declarations in a scope with the given name, including resolved using declarations.
Definition Sema.h:9397
@ LookupLocalFriendName
Look up a friend of a local class.
Definition Sema.h:9405
@ LookupNamespaceName
Look up a namespace name within a C++ using directive or namespace alias definition,...
Definition Sema.h:9393
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9378
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:418
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:13777
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:1531
void CheckDelegatingCtorCycles()
SmallVector< CXXMethodDecl *, 4 > DelayedDllExportMemberFunctions
Definition Sema.h:6370
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:1258
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:6553
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:6534
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:1471
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:7867
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:1690
@ AR_accessible
Definition Sema.h:1688
@ AR_inaccessible
Definition Sema.h:1689
@ AR_delayed
Definition Sema.h:1691
Scope * getScopeForContext(DeclContext *Ctx)
Determines the active Scope associated with the given declaration context.
Definition Sema.cpp:2473
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:2078
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:4213
@ Default
= default ;
Definition Sema.h:4215
@ Delete
deleted-function-body
Definition Sema.h:4221
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:2079
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:1304
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:228
DeclarationNameInfo GetNameForDeclarator(Declarator &D)
GetNameForDeclarator - Determine the full declaration name for the given Declarator.
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:932
void DiagnoseTypeTraitDetails(const Expr *E)
If E represents a built-in type trait, or a known standard type trait, try to print more information ...
AccessResult CheckDestructorAccess(SourceLocation Loc, CXXDestructorDecl *Dtor, const PartialDiagnostic &PDiag, QualType objectType=QualType())
bool isStdTypeIdentity(QualType Ty, QualType *TypeArgument, const Decl **MalformedDecl=nullptr)
Tests whether Ty is an instance of std::type_identity and, if it is and TypeArgument is not NULL,...
SemaObjC & ObjC()
Definition Sema.h:1516
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:935
ClassTemplateDecl * StdInitializerList
The C++ "std::initializer_list" template, which is defined in <initializer_list>.
Definition Sema.h:6560
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:6644
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:6575
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:1208
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:12247
EnumDecl * getStdAlignValT() const
void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record)
LangAS getDefaultCXXMethodAddrSpace() const
Returns default addr space for method qualifiers.
Definition Sema.cpp:1787
LazyDeclPtr StdBadAlloc
The C++ "std::bad_alloc" class, which is defined by the C++ standard library.
Definition Sema.h:8390
QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs, const DeclSpec *DS=nullptr)
void PushFunctionScope()
Enter a new function scope.
Definition Sema.cpp:2492
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:930
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
void DiagnoseUnsatisfiedRequiresExpr(const RequiresExpr *RequiresExpr, bool First=true)
@ UPPC_RequiresClause
Definition Sema.h:14575
@ UPPC_UsingDeclaration
A using declaration.
Definition Sema.h:14530
@ UPPC_ExceptionType
The type of an exception.
Definition Sema.h:14548
@ UPPC_Initializer
An initializer.
Definition Sema.h:14539
@ UPPC_BaseType
The base type of a class type.
Definition Sema.h:14509
@ UPPC_FriendDeclaration
A friend declaration.
Definition Sema.h:14533
@ UPPC_DefaultArgument
A default argument.
Definition Sema.h:14542
@ UPPC_DeclarationType
The type of an arbitrary declaration.
Definition Sema.h:14512
@ UPPC_DataMemberType
The type of a data member.
Definition Sema.h:14515
@ UPPC_StaticAssertExpression
The expression in a static assertion.
Definition Sema.h:14521
Decl * ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc, SourceLocation NamespaceLoc, SourceLocation IdentLoc, IdentifierInfo *Ident, SourceLocation LBrace, const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UsingDecl, bool IsNested)
ActOnStartNamespaceDef - This is called at the start of a namespace definition.
const LangOptions & getLangOpts() const
Definition Sema.h:928
void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl, bool SupportedForCompatibility=false)
DiagnoseTemplateParameterShadow - Produce a diagnostic complaining that the template parameter 'PrevD...
TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, CorrectTypoKind Mode, DeclContext *MemberContext=nullptr, bool EnteringContext=false, const ObjCObjectPointerType *OPT=nullptr, bool RecordFailure=true)
Try to "correct" a typo in the source code by finding visible declarations whose names are similar to...
QualType CheckComparisonCategoryType(ComparisonCategoryType Kind, SourceLocation Loc, ComparisonCategoryUsage Usage)
Lookup the specified comparison category types in the standard library, an check the VarDecls possibl...
void DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent)
DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was not used in the declaration of ...
SmallVector< VTableUse, 16 > VTableUses
The list of vtables that are required but have not yet been materialized.
Definition Sema.h:5962
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:2604
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:1303
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:1302
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:6538
SemaHLSL & HLSL()
Definition Sema.h:1481
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:5968
void CheckCXXDefaultArguments(FunctionDecl *FD)
Helpers for dealing with blocks and functions.
ComparisonCategoryUsage
Definition Sema.h:5340
@ DefaultedOperator
A defaulted 'operator<=>' needed the comparison category.
Definition Sema.h:5347
SmallVector< InventedTemplateParameterInfo, 4 > InventedParameterInfos
Stack containing information needed when in C++2a an 'auto' is encountered in a function declaration ...
Definition Sema.h:6531
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:6636
llvm::DenseMap< ParmVarDecl *, SourceLocation > UnparsedDefaultArgLocs
Definition Sema.h:6568
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:13170
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:5958
ExprResult DefaultLvalueConversion(Expr *E)
Definition SemaExpr.cpp:648
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:15639
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:9898
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:7013
std::unique_ptr< RecordDeclSetTy > PureVirtualClassDiagSet
PureVirtualClassDiagSet - a set of class declarations which we have emitted a list of pure virtual fu...
Definition Sema.h:6545
void ActOnFinishInlineFunctionDef(FunctionDecl *D)
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition Sema.h:1444
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:6564
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:8209
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:14055
SourceManager & getSourceManager() const
Definition Sema.h:933
FunctionDecl * SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD, FunctionDecl *Spaceship)
Substitute the name and return type of a defaulted 'operator<=>' to form an implicit 'operator=='.
NamedDecl * ActOnDecompositionDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists)
ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow, SourceLocation OpLoc, const CXXScopeSpec &SS, FieldDecl *Field, DeclAccessPair FoundDecl, const DeclarationNameInfo &MemberNameInfo)
void diagnoseFunctionEffectMergeConflicts(const FunctionEffectSet::Conflicts &Errs, SourceLocation NewLoc, SourceLocation OldLoc)
void EnterDeclaratorContext(Scope *S, DeclContext *DC)
EnterDeclaratorContext - Used when we must lookup names in the context of a declarator's nested name ...
bool CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *MD, DefaultedComparisonKind DCK)
bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method)
Whether this' shows up in the exception specification of a static member function.
void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl, SourceLocation EqualLoc, ExprResult Init)
This is invoked after parsing an in-class initializer for a non-static C++ class member,...
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:6078
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:15594
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:6556
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:1582
ASTConsumer & Consumer
Definition Sema.h:1305
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:4720
void NoteDeletedFunction(FunctionDecl *FD)
Emit a note explaining that this function is deleted.
Definition SemaExpr.cpp:127
sema::AnalysisBasedWarnings AnalysisWarnings
Worker object for performing CFG-based warnings.
Definition Sema.h:1344
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:6766
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
Definition Sema.h:6776
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6745
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:1263
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:1307
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:1306
FullExprArg MakeFullDiscardedValueExpr(Expr *Arg)
Definition Sema.h:7816
FPOptions CurFPFeatures
Definition Sema.h:1300
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:6540
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:1586
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:6572
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:6369
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:6315
@ AbstractVariableType
Definition Sema.h:6319
@ AbstractReturnType
Definition Sema.h:6317
@ AbstractNone
Definition Sema.h:6316
@ AbstractFieldType
Definition Sema.h:6320
@ AbstractArrayType
Definition Sema.h:6323
@ AbstractParamType
Definition Sema.h:6318
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:8394
llvm::DenseMap< SpecialMemberCacheKey, SpecialMemberOverloadResult > SpecialMemberCache
A cache of special member function overload resolution results for C++ records.
Definition Sema.h:9356
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:6451
@ CheckValid
Identify whether this function satisfies the formal rules for constexpr functions in the current lanu...
Definition Sema.h:6456
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
Definition Sema.h:6453
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:3525
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:8689
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:1505
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:1819
bool isUnevaluated() const
Definition Expr.h:1957
StringRef getString() const
Definition Expr.h:1887
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3852
bool isBeingDefined() const
Return true if this decl is currently being defined.
Definition Decl.h:3973
StringRef getKindName() const
Definition Decl.h:4048
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3953
TagDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:4963
bool isUnion() const
Definition Decl.h:4063
TagKind getTagKind() const
Definition Decl.h:4052
bool isDependentType() const
Whether this declaration declares a type that is dependent, i.e., a type that somehow depends on temp...
Definition Decl.h:3998
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:106
Represents the declaration of a typedef-name via a C++11 alias-declaration.
Definition Decl.h:3823
static TypeAliasDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition Decl.cpp:5881
void setDescribedAliasTemplate(TypeAliasTemplateDecl *TAT)
Definition Decl.h:3842
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:3648
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:8472
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:8483
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:9110
bool isBooleanType() const
Definition TypeBase.h:9247
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:8845
bool isUndeducedAutoType() const
Definition TypeBase.h:8934
bool isRValueReferenceType() const
Definition TypeBase.h:8770
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:8837
bool isPointerType() const
Definition TypeBase.h:8738
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9154
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9404
bool isReferenceType() const
Definition TypeBase.h:8762
bool isEnumeralType() const
Definition TypeBase.h:8869
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:8766
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition TypeBase.h:9079
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:9290
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:9260
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:9253
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition Type.h:53
bool isFunctionType() const
Definition TypeBase.h:8734
bool isStructureOrClassType() const
Definition Type.cpp:743
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2437
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:2364
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9337
bool isRecordType() const
Definition TypeBase.h:8865
bool isUnionType() const
Definition Type.cpp:755
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3697
QualType getUnderlyingType() const
Definition Decl.h:3752
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:2329
Opcode getOpcode() const
Definition Expr.h:2324
static bool isIncrementDecrementOp(Opcode Op)
Definition Expr.h:2384
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:5188
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:463
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:4147
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:3620
bool hasTypename() const
Return true if the using declaration has 'typename'.
Definition DeclCXX.h:3669
NestedNameSpecifier getQualifier() const
Retrieve the nested-name-specifier that qualifies the name.
Definition DeclCXX.h:3657
DeclarationNameInfo getNameInfo() const
Definition DeclCXX.h:3661
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:3647
Represents C++ using-directive.
Definition DeclCXX.h:3125
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:3821
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:3428
static UsingShadowDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation Loc, DeclarationName Name, BaseUsingDecl *Introducer, NamedDecl *Target)
Definition DeclCXX.h:3464
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition DeclCXX.h:3492
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:713
void setType(QualType newType)
Definition Decl.h:725
QualType getType() const
Definition Decl.h:724
bool isParameterPack() const
Determine whether this value is actually a function parameter pack, init-capture pack,...
Definition Decl.cpp:5657
Represents a variable declaration or definition.
Definition Decl.h:933
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition Decl.cpp:2782
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition Decl.cpp:2133
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition Decl.h:1594
DefinitionKind isThisDeclarationADefinition(ASTContext &) const
Check whether this declaration is a definition.
Definition Decl.cpp:2242
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:2172
bool isNoDestroy(const ASTContext &) const
Is destruction of this variable entirely suppressed?
Definition Decl.cpp:2808
void setCXXCondDecl()
Definition Decl.h:1640
bool isInlineSpecified() const
Definition Decl.h:1579
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1307
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition Decl.h:1248
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:1215
QualType::DestructionKind needsDestruction(const ASTContext &Ctx) const
Would the destruction of this variable have any effect, and if so, what kind?
Definition Decl.cpp:2823
ThreadStorageClassSpecifier getTSCSpec() const
Definition Decl.h:1184
const Expr * getInit() const
Definition Decl.h:1392
const APValue * evaluateValue() const
Attempt to evaluate the value of the initializer attached to this declaration, and produce notes expl...
Definition Decl.cpp:2557
@ TLS_Dynamic
TLS with a dynamic initializer.
Definition Decl.h:959
void setInit(Expr *I)
Definition Decl.cpp:2459
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition Decl.h:1175
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:2510
void setExceptionVariable(bool EV)
Definition Decl.h:1522
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:1202
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:986
std::variant< struct RequiresDecl, struct HeaderDecl, struct UmbrellaDirDecl, struct ModuleDecl, struct ExcludeDecl, struct ExportDecl, struct ExportAsDecl, struct ExternModuleDecl, struct UseDecl, struct LinkDecl, struct ConfigMacrosDecl, struct ConflictDecl > Decl
All declarations that can appear in a module declaration.
Stencil access(llvm::StringRef BaseId, Stencil Member)
Constructs a MemberExpr that accesses the named member (Member) of the object bound to BaseId.
Top level wrappers for InstallAPI frontend operations.
bool FTIHasNonVoidParameters(const DeclaratorChunk::FunctionTypeInfo &FTI)
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
TypeSpecifierType
Specifies the kind of type.
Definition Specifiers.h:56
@ TST_decltype
Definition Specifiers.h:90
@ TST_typename_pack_indexing
Definition Specifiers.h:98
@ TST_decltype_auto
Definition Specifiers.h:94
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
@ OO_None
Not an overloaded operator.
@ NUM_OVERLOADED_OPERATORS
@ NonFunction
This is not an overload because the lookup results contain a non-function.
Definition Sema.h:828
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:824
@ Overload
This is a legitimate overload: the existing declarations are functions or function templates with dif...
Definition Sema.h:820
bool isa(CodeGen::Address addr)
Definition Address.h:330
bool isTemplateInstantiation(TemplateSpecializationKind Kind)
Determine whether this template specialization kind refers to an instantiation of an entity (as oppos...
Definition Specifiers.h: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:507
ConstexprSpecKind
Define the kind of constexpr specifier.
Definition Specifiers.h:36
LinkageSpecLanguageIDs
Represents the language in a linkage specification.
Definition DeclCXX.h:3036
@ Ambiguous
Name lookup results in an ambiguity; use getAmbiguityKind to figure out what kind of ambiguity we hav...
Definition Lookup.h:64
@ NotFound
No entity found met the criteria.
Definition Lookup.h:41
@ FoundOverloaded
Name lookup found a set of overloaded functions that met the criteria.
Definition Lookup.h:54
@ Found
Name lookup found a single declaration that met the criteria.
Definition Lookup.h:50
@ FoundUnresolvedValue
Name lookup found an unresolvable value declaration and cannot yet complete.
Definition Lookup.h:59
@ NotFoundInCurrentInstantiation
No entity found met the criteria within the current instantiation,, but there were dependent base cla...
Definition Lookup.h:46
LLVM_READONLY auto escapeCStyle(CharT Ch) -> StringRef
Return C-style escaped string for special characters, or an empty string if there is no such mapping.
Definition CharInfo.h:191
@ Comparison
A comparison.
Definition Sema.h:661
InClassInitStyle
In-class initialization styles for non-static data members.
Definition Specifiers.h: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:1544
@ 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:627
std::pair< llvm::PointerUnion< const TemplateTypeParmType *, NamedDecl *, const TemplateSpecializationType *, const SubstBuiltinTemplatePackType * >, SourceLocation > UnexpandedParameterPack
Definition Sema.h:243
@ If
'if' clause, allowed on all the Compute Constructs, Data Constructs, Executable Constructs,...
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
@ Seq
'seq' clause, allowed on 'loop' and 'routine' directives.
@ Delete
'delete' clause, allowed on the 'exit data' construct.
@ IK_DeductionGuideName
A deduction-guide name (a template-name)
Definition DeclSpec.h: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.
@ 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:6044
@ Interface
The "__interface" keyword.
Definition TypeBase.h:6049
@ Struct
The "struct" keyword.
Definition TypeBase.h:6046
@ Class
The "class" keyword.
Definition TypeBase.h:6055
ExprResult ExprError()
Definition Ownership.h:265
@ Keyword
The name has been typo-corrected to a keyword.
Definition Sema.h:556
@ Type
The name was classified as a type.
Definition Sema.h:558
DefaultedComparisonKind
Kinds of defaulted comparison operator functions.
Definition Decl.h:2030
@ Relational
This is an <, <=, >, or >= that should be implemented as a rewrite in terms of a <=> comparison.
Definition Decl.h:2044
@ NotEqual
This is an operator!= that should be implemented as a rewrite in terms of a == comparison.
Definition Decl.h:2041
@ ThreeWay
This is an operator<=> that should be implemented as a series of subobject comparisons.
Definition Decl.h:2038
@ None
This is not a defaultable comparison operator.
Definition Decl.h:2032
@ Equal
This is an operator== that should be implemented as a series of subobject comparisons.
Definition Decl.h:2035
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:4439
@ CanNeverPassInRegs
The argument of this type cannot be passed directly in registers.
Definition Decl.h:4453
@ CannotPassInRegs
The argument of this type cannot be passed directly in registers.
Definition Decl.h:4448
AllowFoldKind
Definition Sema.h:649
@ TU_Prefix
The translation unit is a prefix to a translation unit, and is not complete.
ComparisonCategoryType
An enumeration representing the different comparison categories types.
MutableArrayRef< ParsedTemplateArgument > ASTTemplateArgsPtr
Definition Ownership.h:261
CXXSpecialMemberKind
Kinds of C++ special members.
Definition Decl.h:2019
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:2255
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:639
@ ConsiderTrivialABI
The triviality of a method affected by "trivial_abi".
Definition Sema.h:644
@ IgnoreTrivialABI
The triviality of a method unaffected by "trivial_abi".
Definition Sema.h:641
@ Incomplete
Template argument deduction did not deduce a value for every template parameter.
Definition Sema.h:384
@ Success
Template argument deduction was successful.
Definition Sema.h:376
@ Inconsistent
Template argument deduction produced inconsistent deduced values for the given template parameter.
Definition Sema.h:390
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:2262
U cast(CodeGen::Address addr)
Definition Address.h:327
@ StaticAssertMessageData
Call to data() in a static assert message.
Definition Sema.h:843
@ StaticAssertMessageSize
Call to size() in a static assert message.
Definition Sema.h:841
@ ExplicitBool
Condition in an explicit(bool) specifier.
Definition Sema.h:839
OpaquePtr< QualType > ParsedType
An opaque type for threading parsed type information through the parser.
Definition Ownership.h:230
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition TypeBase.h:6019
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:6040
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6030
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6033
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:666
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:6083
static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag)
Converts a TagTypeKind into an elaborated type keyword.
Definition Type.cpp:3417
static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into a tag type kind.
Definition Type.cpp:3399
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:13209
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
SourceLocation PointOfInstantiation
The point of instantiation or synthesis within the source code.
Definition Sema.h:13340
@ MarkingClassDllexported
We are marking a class as __dllexport.
Definition Sema.h:13300
@ InitializingStructuredBinding
We are initializing a structured binding.
Definition Sema.h:13297
@ ExceptionSpecEvaluation
We are computing the exception specification for a defaulted special member function.
Definition Sema.h:13253
@ DeclaringImplicitEqualityComparison
We are declaring an implicit 'operator==' for a defaulted 'operator<=>'.
Definition Sema.h:13271
Decl * Entity
The entity that is being synthesized.
Definition Sema.h:13343
Abstract class used to diagnose incomplete types.
Definition Sema.h:8286
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