clang 19.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
15#include "clang/AST/ASTLambda.h"
18#include "clang/AST/CharUnits.h"
20#include "clang/AST/DeclCXX.h"
23#include "clang/AST/Expr.h"
24#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"
50#include "llvm/ADT/ArrayRef.h"
51#include "llvm/ADT/STLExtras.h"
52#include "llvm/ADT/STLForwardCompat.h"
53#include "llvm/ADT/ScopeExit.h"
54#include "llvm/ADT/SmallString.h"
55#include "llvm/ADT/StringExtras.h"
56#include "llvm/Support/ConvertUTF.h"
57#include "llvm/Support/SaveAndRestore.h"
58#include <map>
59#include <optional>
60#include <set>
61
62using namespace clang;
63
64//===----------------------------------------------------------------------===//
65// CheckDefaultArgumentVisitor
66//===----------------------------------------------------------------------===//
67
68namespace {
69/// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
70/// the default argument of a parameter to determine whether it
71/// contains any ill-formed subexpressions. For example, this will
72/// diagnose the use of local variables or parameters within the
73/// default argument expression.
74class CheckDefaultArgumentVisitor
75 : public ConstStmtVisitor<CheckDefaultArgumentVisitor, bool> {
76 Sema &S;
77 const Expr *DefaultArg;
78
79public:
80 CheckDefaultArgumentVisitor(Sema &S, const Expr *DefaultArg)
81 : S(S), DefaultArg(DefaultArg) {}
82
83 bool VisitExpr(const Expr *Node);
84 bool VisitDeclRefExpr(const DeclRefExpr *DRE);
85 bool VisitCXXThisExpr(const CXXThisExpr *ThisE);
86 bool VisitLambdaExpr(const LambdaExpr *Lambda);
87 bool VisitPseudoObjectExpr(const PseudoObjectExpr *POE);
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 = dyn_cast<ValueDecl>(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} // namespace
184
185void
187 const CXXMethodDecl *Method) {
188 // If we have an MSAny spec already, don't bother.
189 if (!Method || ComputedEST == EST_MSAny)
190 return;
191
192 const FunctionProtoType *Proto
193 = Method->getType()->getAs<FunctionProtoType>();
194 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
195 if (!Proto)
196 return;
197
199
200 // If we have a throw-all spec at this point, ignore the function.
201 if (ComputedEST == EST_None)
202 return;
203
204 if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
205 EST = EST_BasicNoexcept;
206
207 switch (EST) {
208 case EST_Unparsed:
210 case EST_Unevaluated:
211 llvm_unreachable("should not see unresolved exception specs here");
212
213 // If this function can throw any exceptions, make a note of that.
214 case EST_MSAny:
215 case EST_None:
216 // FIXME: Whichever we see last of MSAny and None determines our result.
217 // We should make a consistent, order-independent choice here.
218 ClearExceptions();
219 ComputedEST = EST;
220 return;
222 ClearExceptions();
223 ComputedEST = EST_None;
224 return;
225 // FIXME: If the call to this decl is using any of its default arguments, we
226 // need to search them for potentially-throwing calls.
227 // If this function has a basic noexcept, it doesn't affect the outcome.
229 case EST_NoexceptTrue:
230 case EST_NoThrow:
231 return;
232 // If we're still at noexcept(true) and there's a throw() callee,
233 // change to that specification.
234 case EST_DynamicNone:
235 if (ComputedEST == EST_BasicNoexcept)
236 ComputedEST = EST_DynamicNone;
237 return;
239 llvm_unreachable(
240 "should not generate implicit declarations for dependent cases");
241 case EST_Dynamic:
242 break;
243 }
244 assert(EST == EST_Dynamic && "EST case not considered earlier.");
245 assert(ComputedEST != EST_None &&
246 "Shouldn't collect exceptions when throw-all is guaranteed.");
247 ComputedEST = EST_Dynamic;
248 // Record the exceptions in this function's exception specification.
249 for (const auto &E : Proto->exceptions())
250 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
251 Exceptions.push_back(E);
252}
253
255 if (!S || ComputedEST == EST_MSAny)
256 return;
257
258 // FIXME:
259 //
260 // C++0x [except.spec]p14:
261 // [An] implicit exception-specification specifies the type-id T if and
262 // only if T is allowed by the exception-specification of a function directly
263 // invoked by f's implicit definition; f shall allow all exceptions if any
264 // function it directly invokes allows all exceptions, and f shall allow no
265 // exceptions if every function it directly invokes allows no exceptions.
266 //
267 // Note in particular that if an implicit exception-specification is generated
268 // for a function containing a throw-expression, that specification can still
269 // be noexcept(true).
270 //
271 // Note also that 'directly invoked' is not defined in the standard, and there
272 // is no indication that we should only consider potentially-evaluated calls.
273 //
274 // Ultimately we should implement the intent of the standard: the exception
275 // specification should be the set of exceptions which can be thrown by the
276 // implicit definition. For now, we assume that any non-nothrow expression can
277 // throw any exception.
278
279 if (Self->canThrow(S))
280 ComputedEST = EST_None;
281}
282
284 SourceLocation EqualLoc) {
285 if (RequireCompleteType(Param->getLocation(), Param->getType(),
286 diag::err_typecheck_decl_incomplete_type))
287 return true;
288
289 // C++ [dcl.fct.default]p5
290 // A default argument expression is implicitly converted (clause
291 // 4) to the parameter type. The default argument expression has
292 // the same semantic constraints as the initializer expression in
293 // a declaration of a variable of the parameter type, using the
294 // copy-initialization semantics (8.5).
296 Param);
298 EqualLoc);
299 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
300 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
301 if (Result.isInvalid())
302 return true;
303 Arg = Result.getAs<Expr>();
304
305 CheckCompletedExpr(Arg, EqualLoc);
307
308 return Arg;
309}
310
312 SourceLocation EqualLoc) {
313 // Add the default argument to the parameter
314 Param->setDefaultArg(Arg);
315
316 // We have already instantiated this parameter; provide each of the
317 // instantiations with the uninstantiated default argument.
318 UnparsedDefaultArgInstantiationsMap::iterator InstPos
320 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
321 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
322 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
323
324 // We're done tracking this parameter's instantiations.
326 }
327}
328
329/// ActOnParamDefaultArgument - Check whether the default argument
330/// provided for a function parameter is well-formed. If so, attach it
331/// to the parameter declaration.
332void
334 Expr *DefaultArg) {
335 if (!param || !DefaultArg)
336 return;
337
338 ParmVarDecl *Param = cast<ParmVarDecl>(param);
339 UnparsedDefaultArgLocs.erase(Param);
340
341 // Default arguments are only permitted in C++
342 if (!getLangOpts().CPlusPlus) {
343 Diag(EqualLoc, diag::err_param_default_argument)
344 << DefaultArg->getSourceRange();
345 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
346 }
347
348 // Check for unexpanded parameter packs.
350 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
351
352 // C++11 [dcl.fct.default]p3
353 // A default argument expression [...] shall not be specified for a
354 // parameter pack.
355 if (Param->isParameterPack()) {
356 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
357 << DefaultArg->getSourceRange();
358 // Recover by discarding the default argument.
359 Param->setDefaultArg(nullptr);
360 return;
361 }
362
363 ExprResult Result = ConvertParamDefaultArgument(Param, DefaultArg, EqualLoc);
364 if (Result.isInvalid())
365 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
366
367 DefaultArg = Result.getAs<Expr>();
368
369 // Check that the default argument is well-formed
370 CheckDefaultArgumentVisitor DefaultArgChecker(*this, DefaultArg);
371 if (DefaultArgChecker.Visit(DefaultArg))
372 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
373
374 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
375}
376
377/// ActOnParamUnparsedDefaultArgument - We've seen a default
378/// argument for a function parameter, but we can't parse it yet
379/// because we're inside a class definition. Note that this default
380/// argument will be parsed later.
382 SourceLocation EqualLoc,
383 SourceLocation ArgLoc) {
384 if (!param)
385 return;
386
387 ParmVarDecl *Param = cast<ParmVarDecl>(param);
388 Param->setUnparsedDefaultArg();
389 UnparsedDefaultArgLocs[Param] = ArgLoc;
390}
391
392/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
393/// the default argument for the parameter param failed.
395 Expr *DefaultArg) {
396 if (!param)
397 return;
398
399 ParmVarDecl *Param = cast<ParmVarDecl>(param);
400 Param->setInvalidDecl();
401 UnparsedDefaultArgLocs.erase(Param);
402 ExprResult RE;
403 if (DefaultArg) {
404 RE = CreateRecoveryExpr(EqualLoc, DefaultArg->getEndLoc(), {DefaultArg},
405 Param->getType().getNonReferenceType());
406 } else {
407 RE = CreateRecoveryExpr(EqualLoc, EqualLoc, {},
408 Param->getType().getNonReferenceType());
409 }
410 Param->setDefaultArg(RE.get());
411}
412
413/// CheckExtraCXXDefaultArguments - Check for any extra default
414/// arguments in the declarator, which is not a function declaration
415/// or definition and therefore is not permitted to have default
416/// arguments. This routine should be invoked for every declarator
417/// that is not a function declaration or definition.
419 // C++ [dcl.fct.default]p3
420 // A default argument expression shall be specified only in the
421 // parameter-declaration-clause of a function declaration or in a
422 // template-parameter (14.1). It shall not be specified for a
423 // parameter pack. If it is specified in a
424 // parameter-declaration-clause, it shall not occur within a
425 // declarator or abstract-declarator of a parameter-declaration.
426 bool MightBeFunction = D.isFunctionDeclarationContext();
427 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
428 DeclaratorChunk &chunk = D.getTypeObject(i);
429 if (chunk.Kind == DeclaratorChunk::Function) {
430 if (MightBeFunction) {
431 // This is a function declaration. It can have default arguments, but
432 // keep looking in case its return type is a function type with default
433 // arguments.
434 MightBeFunction = false;
435 continue;
436 }
437 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
438 ++argIdx) {
439 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
440 if (Param->hasUnparsedDefaultArg()) {
441 std::unique_ptr<CachedTokens> Toks =
442 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
443 SourceRange SR;
444 if (Toks->size() > 1)
445 SR = SourceRange((*Toks)[1].getLocation(),
446 Toks->back().getLocation());
447 else
448 SR = UnparsedDefaultArgLocs[Param];
449 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
450 << SR;
451 } else if (Param->getDefaultArg()) {
452 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
453 << Param->getDefaultArg()->getSourceRange();
454 Param->setDefaultArg(nullptr);
455 }
456 }
457 } else if (chunk.Kind != DeclaratorChunk::Paren) {
458 MightBeFunction = false;
459 }
460 }
461}
462
464 return llvm::any_of(FD->parameters(), [](ParmVarDecl *P) {
465 return P->hasDefaultArg() && !P->hasInheritedDefaultArg();
466 });
467}
468
469/// MergeCXXFunctionDecl - Merge two declarations of the same C++
470/// function, once we already know that they have the same
471/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
472/// error, false otherwise.
474 Scope *S) {
475 bool Invalid = false;
476
477 // The declaration context corresponding to the scope is the semantic
478 // parent, unless this is a local function declaration, in which case
479 // it is that surrounding function.
480 DeclContext *ScopeDC = New->isLocalExternDecl()
481 ? New->getLexicalDeclContext()
482 : New->getDeclContext();
483
484 // Find the previous declaration for the purpose of default arguments.
485 FunctionDecl *PrevForDefaultArgs = Old;
486 for (/**/; PrevForDefaultArgs;
487 // Don't bother looking back past the latest decl if this is a local
488 // extern declaration; nothing else could work.
489 PrevForDefaultArgs = New->isLocalExternDecl()
490 ? nullptr
491 : PrevForDefaultArgs->getPreviousDecl()) {
492 // Ignore hidden declarations.
493 if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
494 continue;
495
496 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
497 !New->isCXXClassMember()) {
498 // Ignore default arguments of old decl if they are not in
499 // the same scope and this is not an out-of-line definition of
500 // a member function.
501 continue;
502 }
503
504 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
505 // If only one of these is a local function declaration, then they are
506 // declared in different scopes, even though isDeclInScope may think
507 // they're in the same scope. (If both are local, the scope check is
508 // sufficient, and if neither is local, then they are in the same scope.)
509 continue;
510 }
511
512 // We found the right previous declaration.
513 break;
514 }
515
516 // C++ [dcl.fct.default]p4:
517 // For non-template functions, default arguments can be added in
518 // later declarations of a function in the same
519 // scope. Declarations in different scopes have completely
520 // distinct sets of default arguments. That is, declarations in
521 // inner scopes do not acquire default arguments from
522 // declarations in outer scopes, and vice versa. In a given
523 // function declaration, all parameters subsequent to a
524 // parameter with a default argument shall have default
525 // arguments supplied in this or previous declarations. A
526 // default argument shall not be redefined by a later
527 // declaration (not even to the same value).
528 //
529 // C++ [dcl.fct.default]p6:
530 // Except for member functions of class templates, the default arguments
531 // in a member function definition that appears outside of the class
532 // definition are added to the set of default arguments provided by the
533 // member function declaration in the class definition.
534 for (unsigned p = 0, NumParams = PrevForDefaultArgs
535 ? PrevForDefaultArgs->getNumParams()
536 : 0;
537 p < NumParams; ++p) {
538 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
539 ParmVarDecl *NewParam = New->getParamDecl(p);
540
541 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
542 bool NewParamHasDfl = NewParam->hasDefaultArg();
543
544 if (OldParamHasDfl && NewParamHasDfl) {
545 unsigned DiagDefaultParamID =
546 diag::err_param_default_argument_redefinition;
547
548 // MSVC accepts that default parameters be redefined for member functions
549 // of template class. The new default parameter's value is ignored.
550 Invalid = true;
551 if (getLangOpts().MicrosoftExt) {
552 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
553 if (MD && MD->getParent()->getDescribedClassTemplate()) {
554 // Merge the old default argument into the new parameter.
555 NewParam->setHasInheritedDefaultArg();
556 if (OldParam->hasUninstantiatedDefaultArg())
558 OldParam->getUninstantiatedDefaultArg());
559 else
560 NewParam->setDefaultArg(OldParam->getInit());
561 DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
562 Invalid = false;
563 }
564 }
565
566 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
567 // hint here. Alternatively, we could walk the type-source information
568 // for NewParam to find the last source location in the type... but it
569 // isn't worth the effort right now. This is the kind of test case that
570 // is hard to get right:
571 // int f(int);
572 // void g(int (*fp)(int) = f);
573 // void g(int (*fp)(int) = &f);
574 Diag(NewParam->getLocation(), DiagDefaultParamID)
575 << NewParam->getDefaultArgRange();
576
577 // Look for the function declaration where the default argument was
578 // actually written, which may be a declaration prior to Old.
579 for (auto Older = PrevForDefaultArgs;
580 OldParam->hasInheritedDefaultArg(); /**/) {
581 Older = Older->getPreviousDecl();
582 OldParam = Older->getParamDecl(p);
583 }
584
585 Diag(OldParam->getLocation(), diag::note_previous_definition)
586 << OldParam->getDefaultArgRange();
587 } else if (OldParamHasDfl) {
588 // Merge the old default argument into the new parameter unless the new
589 // function is a friend declaration in a template class. In the latter
590 // case the default arguments will be inherited when the friend
591 // declaration will be instantiated.
592 if (New->getFriendObjectKind() == Decl::FOK_None ||
594 // It's important to use getInit() here; getDefaultArg()
595 // strips off any top-level ExprWithCleanups.
596 NewParam->setHasInheritedDefaultArg();
597 if (OldParam->hasUnparsedDefaultArg())
598 NewParam->setUnparsedDefaultArg();
599 else if (OldParam->hasUninstantiatedDefaultArg())
601 OldParam->getUninstantiatedDefaultArg());
602 else
603 NewParam->setDefaultArg(OldParam->getInit());
604 }
605 } else if (NewParamHasDfl) {
606 if (New->getDescribedFunctionTemplate()) {
607 // Paragraph 4, quoted above, only applies to non-template functions.
608 Diag(NewParam->getLocation(),
609 diag::err_param_default_argument_template_redecl)
610 << NewParam->getDefaultArgRange();
611 Diag(PrevForDefaultArgs->getLocation(),
612 diag::note_template_prev_declaration)
613 << false;
614 } else if (New->getTemplateSpecializationKind()
617 // C++ [temp.expr.spec]p21:
618 // Default function arguments shall not be specified in a declaration
619 // or a definition for one of the following explicit specializations:
620 // - the explicit specialization of a function template;
621 // - the explicit specialization of a member function template;
622 // - the explicit specialization of a member function of a class
623 // template where the class template specialization to which the
624 // member function specialization belongs is implicitly
625 // instantiated.
626 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
628 << New->getDeclName()
629 << NewParam->getDefaultArgRange();
630 } else if (New->getDeclContext()->isDependentContext()) {
631 // C++ [dcl.fct.default]p6 (DR217):
632 // Default arguments for a member function of a class template shall
633 // be specified on the initial declaration of the member function
634 // within the class template.
635 //
636 // Reading the tea leaves a bit in DR217 and its reference to DR205
637 // leads me to the conclusion that one cannot add default function
638 // arguments for an out-of-line definition of a member function of a
639 // dependent type.
640 int WhichKind = 2;
642 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
643 if (Record->getDescribedClassTemplate())
644 WhichKind = 0;
645 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
646 WhichKind = 1;
647 else
648 WhichKind = 2;
649 }
650
651 Diag(NewParam->getLocation(),
652 diag::err_param_default_argument_member_template_redecl)
653 << WhichKind
654 << NewParam->getDefaultArgRange();
655 }
656 }
657 }
658
659 // DR1344: If a default argument is added outside a class definition and that
660 // default argument makes the function a special member function, the program
661 // is ill-formed. This can only happen for constructors.
662 if (isa<CXXConstructorDecl>(New) &&
664 CXXSpecialMemberKind NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
665 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
666 if (NewSM != OldSM) {
667 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
668 assert(NewParam->hasDefaultArg());
669 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
670 << NewParam->getDefaultArgRange() << llvm::to_underlying(NewSM);
671 Diag(Old->getLocation(), diag::note_previous_declaration);
672 }
673 }
674
675 const FunctionDecl *Def;
676 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
677 // template has a constexpr specifier then all its declarations shall
678 // contain the constexpr specifier.
679 if (New->getConstexprKind() != Old->getConstexprKind()) {
680 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
681 << New << static_cast<int>(New->getConstexprKind())
682 << static_cast<int>(Old->getConstexprKind());
683 Diag(Old->getLocation(), diag::note_previous_declaration);
684 Invalid = true;
685 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
686 Old->isDefined(Def) &&
687 // If a friend function is inlined but does not have 'inline'
688 // specifier, it is a definition. Do not report attribute conflict
689 // in this case, redefinition will be diagnosed later.
690 (New->isInlineSpecified() ||
692 // C++11 [dcl.fcn.spec]p4:
693 // If the definition of a function appears in a translation unit before its
694 // first declaration as inline, the program is ill-formed.
695 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
696 Diag(Def->getLocation(), diag::note_previous_definition);
697 Invalid = true;
698 }
699
700 // C++17 [temp.deduct.guide]p3:
701 // Two deduction guide declarations in the same translation unit
702 // for the same class template shall not have equivalent
703 // parameter-declaration-clauses.
704 if (isa<CXXDeductionGuideDecl>(New) &&
706 Diag(New->getLocation(), diag::err_deduction_guide_redeclared);
707 Diag(Old->getLocation(), diag::note_previous_declaration);
708 }
709
710 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
711 // argument expression, that declaration shall be a definition and shall be
712 // the only declaration of the function or function template in the
713 // translation unit.
716 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
717 Diag(Old->getLocation(), diag::note_previous_declaration);
718 Invalid = true;
719 }
720
721 // C++11 [temp.friend]p4 (DR329):
722 // When a function is defined in a friend function declaration in a class
723 // template, the function is instantiated when the function is odr-used.
724 // The same restrictions on multiple declarations and definitions that
725 // apply to non-template function declarations and definitions also apply
726 // to these implicit definitions.
727 const FunctionDecl *OldDefinition = nullptr;
729 Old->isDefined(OldDefinition, true))
730 CheckForFunctionRedefinition(New, OldDefinition);
731
732 return Invalid;
733}
734
737 ? diag::warn_cxx23_placeholder_var_definition
738 : diag::ext_placeholder_var_definition);
739}
740
741NamedDecl *
743 MultiTemplateParamsArg TemplateParamLists) {
744 assert(D.isDecompositionDeclarator());
746
747 // The syntax only allows a decomposition declarator as a simple-declaration,
748 // a for-range-declaration, or a condition in Clang, but we parse it in more
749 // cases than that.
751 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
752 << Decomp.getSourceRange();
753 return nullptr;
754 }
755
756 if (!TemplateParamLists.empty()) {
757 // FIXME: There's no rule against this, but there are also no rules that
758 // would actually make it usable, so we reject it for now.
759 Diag(TemplateParamLists.front()->getTemplateLoc(),
760 diag::err_decomp_decl_template);
761 return nullptr;
762 }
763
764 Diag(Decomp.getLSquareLoc(),
766 ? diag::ext_decomp_decl
768 ? diag::ext_decomp_decl_cond
769 : diag::warn_cxx14_compat_decomp_decl)
770 << Decomp.getSourceRange();
771
772 // The semantic context is always just the current context.
773 DeclContext *const DC = CurContext;
774
775 // C++17 [dcl.dcl]/8:
776 // The decl-specifier-seq shall contain only the type-specifier auto
777 // and cv-qualifiers.
778 // C++20 [dcl.dcl]/8:
779 // If decl-specifier-seq contains any decl-specifier other than static,
780 // thread_local, auto, or cv-qualifiers, the program is ill-formed.
781 // C++23 [dcl.pre]/6:
782 // Each decl-specifier in the decl-specifier-seq shall be static,
783 // thread_local, auto (9.2.9.6 [dcl.spec.auto]), or a cv-qualifier.
784 auto &DS = D.getDeclSpec();
785 {
786 // Note: While constrained-auto needs to be checked, we do so separately so
787 // we can emit a better diagnostic.
788 SmallVector<StringRef, 8> BadSpecifiers;
789 SmallVector<SourceLocation, 8> BadSpecifierLocs;
790 SmallVector<StringRef, 8> CPlusPlus20Specifiers;
791 SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs;
792 if (auto SCS = DS.getStorageClassSpec()) {
793 if (SCS == DeclSpec::SCS_static) {
794 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS));
795 CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc());
796 } else {
797 BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
798 BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
799 }
800 }
801 if (auto TSCS = DS.getThreadStorageClassSpec()) {
802 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS));
803 CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
804 }
805 if (DS.hasConstexprSpecifier()) {
806 BadSpecifiers.push_back(
807 DeclSpec::getSpecifierName(DS.getConstexprSpecifier()));
808 BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
809 }
810 if (DS.isInlineSpecified()) {
811 BadSpecifiers.push_back("inline");
812 BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
813 }
814
815 if (!BadSpecifiers.empty()) {
816 auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
817 Err << (int)BadSpecifiers.size()
818 << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
819 // Don't add FixItHints to remove the specifiers; we do still respect
820 // them when building the underlying variable.
821 for (auto Loc : BadSpecifierLocs)
822 Err << SourceRange(Loc, Loc);
823 } else if (!CPlusPlus20Specifiers.empty()) {
824 auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(),
826 ? diag::warn_cxx17_compat_decomp_decl_spec
827 : diag::ext_decomp_decl_spec);
828 Warn << (int)CPlusPlus20Specifiers.size()
829 << llvm::join(CPlusPlus20Specifiers.begin(),
830 CPlusPlus20Specifiers.end(), " ");
831 for (auto Loc : CPlusPlus20SpecifierLocs)
832 Warn << SourceRange(Loc, Loc);
833 }
834 // We can't recover from it being declared as a typedef.
835 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
836 return nullptr;
837 }
838
839 // C++2a [dcl.struct.bind]p1:
840 // A cv that includes volatile is deprecated
841 if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) &&
843 Diag(DS.getVolatileSpecLoc(),
844 diag::warn_deprecated_volatile_structured_binding);
845
847 QualType R = TInfo->getType();
848
851 D.setInvalidType();
852
853 // The syntax only allows a single ref-qualifier prior to the decomposition
854 // declarator. No other declarator chunks are permitted. Also check the type
855 // specifier here.
856 if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
857 D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
858 (D.getNumTypeObjects() == 1 &&
860 Diag(Decomp.getLSquareLoc(),
861 (D.hasGroupingParens() ||
862 (D.getNumTypeObjects() &&
864 ? diag::err_decomp_decl_parens
865 : diag::err_decomp_decl_type)
866 << R;
867
868 // In most cases, there's no actual problem with an explicitly-specified
869 // type, but a function type won't work here, and ActOnVariableDeclarator
870 // shouldn't be called for such a type.
871 if (R->isFunctionType())
872 D.setInvalidType();
873 }
874
875 // Constrained auto is prohibited by [decl.pre]p6, so check that here.
876 if (DS.isConstrainedAuto()) {
877 TemplateIdAnnotation *TemplRep = DS.getRepAsTemplateId();
878 assert(TemplRep->Kind == TNK_Concept_template &&
879 "No other template kind should be possible for a constrained auto");
880
881 SourceRange TemplRange{TemplRep->TemplateNameLoc,
882 TemplRep->RAngleLoc.isValid()
883 ? TemplRep->RAngleLoc
884 : TemplRep->TemplateNameLoc};
885 Diag(TemplRep->TemplateNameLoc, diag::err_decomp_decl_constraint)
886 << TemplRange << FixItHint::CreateRemoval(TemplRange);
887 }
888
889 // Build the BindingDecls.
891
892 // Build the BindingDecls.
893 for (auto &B : D.getDecompositionDeclarator().bindings()) {
894 // Check for name conflicts.
895 DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
896 IdentifierInfo *VarName = B.Name;
897 assert(VarName && "Cannot have an unnamed binding declaration");
898
900 RedeclarationKind::ForVisibleRedeclaration);
902 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
903
904 // It's not permitted to shadow a template parameter name.
905 if (Previous.isSingleResult() &&
906 Previous.getFoundDecl()->isTemplateParameter()) {
908 Previous.getFoundDecl());
909 Previous.clear();
910 }
911
912 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, VarName);
913
914 ProcessDeclAttributeList(S, BD, *B.Attrs);
915
916 // Find the shadowed declaration before filtering for scope.
917 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
919 : nullptr;
920
921 bool ConsiderLinkage = DC->isFunctionOrMethod() &&
922 DS.getStorageClassSpec() == DeclSpec::SCS_extern;
923 FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
924 /*AllowInlineNamespace*/false);
925
926 bool IsPlaceholder = DS.getStorageClassSpec() != DeclSpec::SCS_static &&
927 DC->isFunctionOrMethod() && VarName->isPlaceholder();
928 if (!Previous.empty()) {
929 if (IsPlaceholder) {
930 bool sameDC = (Previous.end() - 1)
931 ->getDeclContext()
932 ->getRedeclContext()
933 ->Equals(DC->getRedeclContext());
934 if (sameDC &&
935 isDeclInScope(*(Previous.end() - 1), CurContext, S, false)) {
936 Previous.clear();
938 }
939 } else {
940 auto *Old = Previous.getRepresentativeDecl();
941 Diag(B.NameLoc, diag::err_redefinition) << B.Name;
942 Diag(Old->getLocation(), diag::note_previous_definition);
943 }
944 } else if (ShadowedDecl && !D.isRedeclaration()) {
945 CheckShadow(BD, ShadowedDecl, Previous);
946 }
947 PushOnScopeChains(BD, S, true);
948 Bindings.push_back(BD);
949 ParsingInitForAutoVars.insert(BD);
950 }
951
952 // There are no prior lookup results for the variable itself, because it
953 // is unnamed.
954 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
955 Decomp.getLSquareLoc());
957 RedeclarationKind::ForVisibleRedeclaration);
958
959 // Build the variable that holds the non-decomposed object.
960 bool AddToScope = true;
961 NamedDecl *New =
962 ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
963 MultiTemplateParamsArg(), AddToScope, Bindings);
964 if (AddToScope) {
965 S->AddDecl(New);
967 }
968
969 if (OpenMP().isInOpenMPDeclareTargetContext())
971
972 return New;
973}
974
977 QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
978 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
979 if ((int64_t)Bindings.size() != NumElems) {
980 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
981 << DecompType << (unsigned)Bindings.size()
982 << (unsigned)NumElems.getLimitedValue(UINT_MAX)
983 << toString(NumElems, 10) << (NumElems < Bindings.size());
984 return true;
985 }
986
987 unsigned I = 0;
988 for (auto *B : Bindings) {
989 SourceLocation Loc = B->getLocation();
990 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
991 if (E.isInvalid())
992 return true;
993 E = GetInit(Loc, E.get(), I++);
994 if (E.isInvalid())
995 return true;
996 B->setBinding(ElemType, E.get());
997 }
998
999 return false;
1000}
1001
1004 ValueDecl *Src, QualType DecompType,
1005 const llvm::APSInt &NumElems,
1006 QualType ElemType) {
1008 S, Bindings, Src, DecompType, NumElems, ElemType,
1009 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
1011 if (E.isInvalid())
1012 return ExprError();
1014 });
1015}
1016
1018 ValueDecl *Src, QualType DecompType,
1019 const ConstantArrayType *CAT) {
1020 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
1021 llvm::APSInt(CAT->getSize()),
1022 CAT->getElementType());
1023}
1024
1026 ValueDecl *Src, QualType DecompType,
1027 const VectorType *VT) {
1029 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
1031 DecompType.getQualifiers()));
1032}
1033
1036 ValueDecl *Src, QualType DecompType,
1037 const ComplexType *CT) {
1039 S, Bindings, Src, DecompType, llvm::APSInt::get(2),
1041 DecompType.getQualifiers()),
1042 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
1043 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
1044 });
1045}
1046
1049 const TemplateParameterList *Params) {
1051 llvm::raw_svector_ostream OS(SS);
1052 bool First = true;
1053 unsigned I = 0;
1054 for (auto &Arg : Args.arguments()) {
1055 if (!First)
1056 OS << ", ";
1057 Arg.getArgument().print(PrintingPolicy, OS,
1059 PrintingPolicy, Params, I));
1060 First = false;
1061 I++;
1062 }
1063 return std::string(OS.str());
1064}
1065
1066static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
1067 SourceLocation Loc, StringRef Trait,
1069 unsigned DiagID) {
1070 auto DiagnoseMissing = [&] {
1071 if (DiagID)
1073 Args, /*Params*/ nullptr);
1074 return true;
1075 };
1076
1077 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
1079 if (!Std)
1080 return DiagnoseMissing();
1081
1082 // Look up the trait itself, within namespace std. We can diagnose various
1083 // problems with this lookup even if we've been asked to not diagnose a
1084 // missing specialization, because this can only fail if the user has been
1085 // declaring their own names in namespace std or we don't support the
1086 // standard library implementation in use.
1090 return DiagnoseMissing();
1091 if (Result.isAmbiguous())
1092 return true;
1093
1094 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
1095 if (!TraitTD) {
1096 Result.suppressDiagnostics();
1097 NamedDecl *Found = *Result.begin();
1098 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
1099 S.Diag(Found->getLocation(), diag::note_declared_at);
1100 return true;
1101 }
1102
1103 // Build the template-id.
1104 QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
1105 if (TraitTy.isNull())
1106 return true;
1107 if (!S.isCompleteType(Loc, TraitTy)) {
1108 if (DiagID)
1110 Loc, TraitTy, DiagID,
1112 TraitTD->getTemplateParameters()));
1113 return true;
1114 }
1115
1116 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
1117 assert(RD && "specialization of class template is not a class?");
1118
1119 // Look up the member of the trait type.
1120 S.LookupQualifiedName(TraitMemberLookup, RD);
1121 return TraitMemberLookup.isAmbiguous();
1122}
1123
1126 uint64_t I) {
1128 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
1129}
1130
1134}
1135
1136namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1137
1139 llvm::APSInt &Size) {
1142
1145
1146 // Form template argument list for tuple_size<T>.
1149
1150 // If there's no tuple_size specialization or the lookup of 'value' is empty,
1151 // it's not tuple-like.
1152 if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) ||
1153 R.empty())
1154 return IsTupleLike::NotTupleLike;
1155
1156 // If we get this far, we've committed to the tuple interpretation, but
1157 // we can still fail if there actually isn't a usable ::value.
1158
1159 struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1160 LookupResult &R;
1162 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1163 : R(R), Args(Args) {}
1164 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
1165 SourceLocation Loc) override {
1166 return S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1168 /*Params*/ nullptr);
1169 }
1170 } Diagnoser(R, Args);
1171
1172 ExprResult E =
1173 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1174 if (E.isInvalid())
1175 return IsTupleLike::Error;
1176
1177 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser);
1178 if (E.isInvalid())
1179 return IsTupleLike::Error;
1180
1181 return IsTupleLike::TupleLike;
1182}
1183
1184/// \return std::tuple_element<I, T>::type.
1186 unsigned I, QualType T) {
1187 // Form template argument list for tuple_element<I, T>.
1189 Args.addArgument(
1192
1193 DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1196 S, R, Loc, "tuple_element", Args,
1197 diag::err_decomp_decl_std_tuple_element_not_specialized))
1198 return QualType();
1199
1200 auto *TD = R.getAsSingle<TypeDecl>();
1201 if (!TD) {
1203 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1205 /*Params*/ nullptr);
1206 if (!R.empty())
1207 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1208 return QualType();
1209 }
1210
1211 return S.Context.getTypeDeclType(TD);
1212}
1213
1214namespace {
1215struct InitializingBinding {
1216 Sema &S;
1217 InitializingBinding(Sema &S, BindingDecl *BD) : S(S) {
1221 Ctx.Entity = BD;
1223 }
1224 ~InitializingBinding() {
1226 }
1227};
1228}
1229
1232 VarDecl *Src, QualType DecompType,
1233 const llvm::APSInt &TupleSize) {
1234 if ((int64_t)Bindings.size() != TupleSize) {
1235 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1236 << DecompType << (unsigned)Bindings.size()
1237 << (unsigned)TupleSize.getLimitedValue(UINT_MAX)
1238 << toString(TupleSize, 10) << (TupleSize < Bindings.size());
1239 return true;
1240 }
1241
1242 if (Bindings.empty())
1243 return false;
1244
1245 DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1246
1247 // [dcl.decomp]p3:
1248 // The unqualified-id get is looked up in the scope of E by class member
1249 // access lookup ...
1250 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1251 bool UseMemberGet = false;
1252 if (S.isCompleteType(Src->getLocation(), DecompType)) {
1253 if (auto *RD = DecompType->getAsCXXRecordDecl())
1254 S.LookupQualifiedName(MemberGet, RD);
1255 if (MemberGet.isAmbiguous())
1256 return true;
1257 // ... and if that finds at least one declaration that is a function
1258 // template whose first template parameter is a non-type parameter ...
1259 for (NamedDecl *D : MemberGet) {
1260 if (FunctionTemplateDecl *FTD =
1261 dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
1262 TemplateParameterList *TPL = FTD->getTemplateParameters();
1263 if (TPL->size() != 0 &&
1264 isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) {
1265 // ... the initializer is e.get<i>().
1266 UseMemberGet = true;
1267 break;
1268 }
1269 }
1270 }
1271 }
1272
1273 unsigned I = 0;
1274 for (auto *B : Bindings) {
1275 InitializingBinding InitContext(S, B);
1276 SourceLocation Loc = B->getLocation();
1277
1278 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1279 if (E.isInvalid())
1280 return true;
1281
1282 // e is an lvalue if the type of the entity is an lvalue reference and
1283 // an xvalue otherwise
1284 if (!Src->getType()->isLValueReferenceType())
1285 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1286 E.get(), nullptr, VK_XValue,
1288
1290 Args.addArgument(
1292
1293 if (UseMemberGet) {
1294 // if [lookup of member get] finds at least one declaration, the
1295 // initializer is e.get<i-1>().
1296 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1297 CXXScopeSpec(), SourceLocation(), nullptr,
1298 MemberGet, &Args, nullptr);
1299 if (E.isInvalid())
1300 return true;
1301
1302 E = S.BuildCallExpr(nullptr, E.get(), Loc, std::nullopt, Loc);
1303 } else {
1304 // Otherwise, the initializer is get<i-1>(e), where get is looked up
1305 // in the associated namespaces.
1308 DeclarationNameInfo(GetDN, Loc), /*RequiresADL=*/true, &Args,
1310 /*KnownDependent=*/false);
1311
1312 Expr *Arg = E.get();
1313 E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc);
1314 }
1315 if (E.isInvalid())
1316 return true;
1317 Expr *Init = E.get();
1318
1319 // Given the type T designated by std::tuple_element<i - 1, E>::type,
1320 QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1321 if (T.isNull())
1322 return true;
1323
1324 // each vi is a variable of type "reference to T" initialized with the
1325 // initializer, where the reference is an lvalue reference if the
1326 // initializer is an lvalue and an rvalue reference otherwise
1327 QualType RefType =
1328 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1329 if (RefType.isNull())
1330 return true;
1331 auto *RefVD = VarDecl::Create(
1332 S.Context, Src->getDeclContext(), Loc, Loc,
1333 B->getDeclName().getAsIdentifierInfo(), RefType,
1335 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1336 RefVD->setTSCSpec(Src->getTSCSpec());
1337 RefVD->setImplicit();
1338 if (Src->isInlineSpecified())
1339 RefVD->setInlineSpecified();
1340 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1341
1344 InitializationSequence Seq(S, Entity, Kind, Init);
1345 E = Seq.Perform(S, Entity, Kind, Init);
1346 if (E.isInvalid())
1347 return true;
1348 E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
1349 if (E.isInvalid())
1350 return true;
1351 RefVD->setInit(E.get());
1353
1355 DeclarationNameInfo(B->getDeclName(), Loc),
1356 RefVD);
1357 if (E.isInvalid())
1358 return true;
1359
1360 B->setBinding(T, E.get());
1361 I++;
1362 }
1363
1364 return false;
1365}
1366
1367/// Find the base class to decompose in a built-in decomposition of a class type.
1368/// This base class search is, unfortunately, not quite like any other that we
1369/// perform anywhere else in C++.
1371 const CXXRecordDecl *RD,
1372 CXXCastPath &BasePath) {
1373 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1374 CXXBasePath &Path) {
1375 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1376 };
1377
1378 const CXXRecordDecl *ClassWithFields = nullptr;
1380 if (RD->hasDirectFields())
1381 // [dcl.decomp]p4:
1382 // Otherwise, all of E's non-static data members shall be public direct
1383 // members of E ...
1384 ClassWithFields = RD;
1385 else {
1386 // ... or of ...
1387 CXXBasePaths Paths;
1388 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1389 if (!RD->lookupInBases(BaseHasFields, Paths)) {
1390 // If no classes have fields, just decompose RD itself. (This will work
1391 // if and only if zero bindings were provided.)
1392 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
1393 }
1394
1395 CXXBasePath *BestPath = nullptr;
1396 for (auto &P : Paths) {
1397 if (!BestPath)
1398 BestPath = &P;
1399 else if (!S.Context.hasSameType(P.back().Base->getType(),
1400 BestPath->back().Base->getType())) {
1401 // ... the same ...
1402 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1403 << false << RD << BestPath->back().Base->getType()
1404 << P.back().Base->getType();
1405 return DeclAccessPair();
1406 } else if (P.Access < BestPath->Access) {
1407 BestPath = &P;
1408 }
1409 }
1410
1411 // ... unambiguous ...
1412 QualType BaseType = BestPath->back().Base->getType();
1413 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1414 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1415 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1416 return DeclAccessPair();
1417 }
1418
1419 // ... [accessible, implied by other rules] base class of E.
1420 S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD),
1421 *BestPath, diag::err_decomp_decl_inaccessible_base);
1422 AS = BestPath->Access;
1423
1424 ClassWithFields = BaseType->getAsCXXRecordDecl();
1425 S.BuildBasePathArray(Paths, BasePath);
1426 }
1427
1428 // The above search did not check whether the selected class itself has base
1429 // classes with fields, so check that now.
1430 CXXBasePaths Paths;
1431 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1432 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1433 << (ClassWithFields == RD) << RD << ClassWithFields
1434 << Paths.front().back().Base->getType();
1435 return DeclAccessPair();
1436 }
1437
1438 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1439}
1440
1442 ValueDecl *Src, QualType DecompType,
1443 const CXXRecordDecl *OrigRD) {
1444 if (S.RequireCompleteType(Src->getLocation(), DecompType,
1445 diag::err_incomplete_type))
1446 return true;
1447
1448 CXXCastPath BasePath;
1449 DeclAccessPair BasePair =
1450 findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1451 const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1452 if (!RD)
1453 return true;
1455 DecompType.getQualifiers());
1456
1457 auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1458 unsigned NumFields = llvm::count_if(
1459 RD->fields(), [](FieldDecl *FD) { return !FD->isUnnamedBitField(); });
1460 assert(Bindings.size() != NumFields);
1461 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1462 << DecompType << (unsigned)Bindings.size() << NumFields << NumFields
1463 << (NumFields < Bindings.size());
1464 return true;
1465 };
1466
1467 // all of E's non-static data members shall be [...] well-formed
1468 // when named as e.name in the context of the structured binding,
1469 // E shall not have an anonymous union member, ...
1470 unsigned I = 0;
1471 for (auto *FD : RD->fields()) {
1472 if (FD->isUnnamedBitField())
1473 continue;
1474
1475 // All the non-static data members are required to be nameable, so they
1476 // must all have names.
1477 if (!FD->getDeclName()) {
1478 if (RD->isLambda()) {
1479 S.Diag(Src->getLocation(), diag::err_decomp_decl_lambda);
1480 S.Diag(RD->getLocation(), diag::note_lambda_decl);
1481 return true;
1482 }
1483
1484 if (FD->isAnonymousStructOrUnion()) {
1485 S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1486 << DecompType << FD->getType()->isUnionType();
1487 S.Diag(FD->getLocation(), diag::note_declared_at);
1488 return true;
1489 }
1490
1491 // FIXME: Are there any other ways we could have an anonymous member?
1492 }
1493
1494 // We have a real field to bind.
1495 if (I >= Bindings.size())
1496 return DiagnoseBadNumberOfBindings();
1497 auto *B = Bindings[I++];
1498 SourceLocation Loc = B->getLocation();
1499
1500 // The field must be accessible in the context of the structured binding.
1501 // We already checked that the base class is accessible.
1502 // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1503 // const_cast here.
1505 Loc, const_cast<CXXRecordDecl *>(OrigRD),
1507 BasePair.getAccess(), FD->getAccess())));
1508
1509 // Initialize the binding to Src.FD.
1510 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1511 if (E.isInvalid())
1512 return true;
1513 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1514 VK_LValue, &BasePath);
1515 if (E.isInvalid())
1516 return true;
1517 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1518 CXXScopeSpec(), FD,
1519 DeclAccessPair::make(FD, FD->getAccess()),
1520 DeclarationNameInfo(FD->getDeclName(), Loc));
1521 if (E.isInvalid())
1522 return true;
1523
1524 // If the type of the member is T, the referenced type is cv T, where cv is
1525 // the cv-qualification of the decomposition expression.
1526 //
1527 // FIXME: We resolve a defect here: if the field is mutable, we do not add
1528 // 'const' to the type of the field.
1529 Qualifiers Q = DecompType.getQualifiers();
1530 if (FD->isMutable())
1531 Q.removeConst();
1532 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1533 }
1534
1535 if (I != Bindings.size())
1536 return DiagnoseBadNumberOfBindings();
1537
1538 return false;
1539}
1540
1542 QualType DecompType = DD->getType();
1543
1544 // If the type of the decomposition is dependent, then so is the type of
1545 // each binding.
1546 if (DecompType->isDependentType()) {
1547 for (auto *B : DD->bindings())
1548 B->setType(Context.DependentTy);
1549 return;
1550 }
1551
1552 DecompType = DecompType.getNonReferenceType();
1554
1555 // C++1z [dcl.decomp]/2:
1556 // If E is an array type [...]
1557 // As an extension, we also support decomposition of built-in complex and
1558 // vector types.
1559 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1560 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1561 DD->setInvalidDecl();
1562 return;
1563 }
1564 if (auto *VT = DecompType->getAs<VectorType>()) {
1565 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1566 DD->setInvalidDecl();
1567 return;
1568 }
1569 if (auto *CT = DecompType->getAs<ComplexType>()) {
1570 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1571 DD->setInvalidDecl();
1572 return;
1573 }
1574
1575 // C++1z [dcl.decomp]/3:
1576 // if the expression std::tuple_size<E>::value is a well-formed integral
1577 // constant expression, [...]
1578 llvm::APSInt TupleSize(32);
1579 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1580 case IsTupleLike::Error:
1581 DD->setInvalidDecl();
1582 return;
1583
1584 case IsTupleLike::TupleLike:
1585 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1586 DD->setInvalidDecl();
1587 return;
1588
1589 case IsTupleLike::NotTupleLike:
1590 break;
1591 }
1592
1593 // C++1z [dcl.dcl]/8:
1594 // [E shall be of array or non-union class type]
1595 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1596 if (!RD || RD->isUnion()) {
1597 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1598 << DD << !RD << DecompType;
1599 DD->setInvalidDecl();
1600 return;
1601 }
1602
1603 // C++1z [dcl.decomp]/4:
1604 // all of E's non-static data members shall be [...] direct members of
1605 // E or of the same unambiguous public base class of E, ...
1606 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1607 DD->setInvalidDecl();
1608}
1609
1610/// Merge the exception specifications of two variable declarations.
1611///
1612/// This is called when there's a redeclaration of a VarDecl. The function
1613/// checks if the redeclaration might have an exception specification and
1614/// validates compatibility and merges the specs if necessary.
1616 // Shortcut if exceptions are disabled.
1617 if (!getLangOpts().CXXExceptions)
1618 return;
1619
1620 assert(Context.hasSameType(New->getType(), Old->getType()) &&
1621 "Should only be called if types are otherwise the same.");
1622
1623 QualType NewType = New->getType();
1624 QualType OldType = Old->getType();
1625
1626 // We're only interested in pointers and references to functions, as well
1627 // as pointers to member functions.
1628 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1629 NewType = R->getPointeeType();
1630 OldType = OldType->castAs<ReferenceType>()->getPointeeType();
1631 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1632 NewType = P->getPointeeType();
1633 OldType = OldType->castAs<PointerType>()->getPointeeType();
1634 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1635 NewType = M->getPointeeType();
1636 OldType = OldType->castAs<MemberPointerType>()->getPointeeType();
1637 }
1638
1639 if (!NewType->isFunctionProtoType())
1640 return;
1641
1642 // There's lots of special cases for functions. For function pointers, system
1643 // libraries are hopefully not as broken so that we don't need these
1644 // workarounds.
1646 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1647 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1648 New->setInvalidDecl();
1649 }
1650}
1651
1652/// CheckCXXDefaultArguments - Verify that the default arguments for a
1653/// function declaration are well-formed according to C++
1654/// [dcl.fct.default].
1656 unsigned NumParams = FD->getNumParams();
1657 unsigned ParamIdx = 0;
1658
1659 // This checking doesn't make sense for explicit specializations; their
1660 // default arguments are determined by the declaration we're specializing,
1661 // not by FD.
1663 return;
1664 if (auto *FTD = FD->getDescribedFunctionTemplate())
1665 if (FTD->isMemberSpecialization())
1666 return;
1667
1668 // Find first parameter with a default argument
1669 for (; ParamIdx < NumParams; ++ParamIdx) {
1670 ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1671 if (Param->hasDefaultArg())
1672 break;
1673 }
1674
1675 // C++20 [dcl.fct.default]p4:
1676 // In a given function declaration, each parameter subsequent to a parameter
1677 // with a default argument shall have a default argument supplied in this or
1678 // a previous declaration, unless the parameter was expanded from a
1679 // parameter pack, or shall be a function parameter pack.
1680 for (; ParamIdx < NumParams; ++ParamIdx) {
1681 ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1682 if (!Param->hasDefaultArg() && !Param->isParameterPack() &&
1685 if (Param->isInvalidDecl())
1686 /* We already complained about this parameter. */;
1687 else if (Param->getIdentifier())
1688 Diag(Param->getLocation(),
1689 diag::err_param_default_argument_missing_name)
1690 << Param->getIdentifier();
1691 else
1692 Diag(Param->getLocation(),
1693 diag::err_param_default_argument_missing);
1694 }
1695 }
1696}
1697
1698/// Check that the given type is a literal type. Issue a diagnostic if not,
1699/// if Kind is Diagnose.
1700/// \return \c true if a problem has been found (and optionally diagnosed).
1701template <typename... Ts>
1703 SourceLocation Loc, QualType T, unsigned DiagID,
1704 Ts &&...DiagArgs) {
1705 if (T->isDependentType())
1706 return false;
1707
1708 switch (Kind) {
1710 return SemaRef.RequireLiteralType(Loc, T, DiagID,
1711 std::forward<Ts>(DiagArgs)...);
1712
1714 return !T->isLiteralType(SemaRef.Context);
1715 }
1716
1717 llvm_unreachable("unknown CheckConstexprKind");
1718}
1719
1720/// Determine whether a destructor cannot be constexpr due to
1722 const CXXDestructorDecl *DD,
1724 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1725 "this check is obsolete for C++23");
1726 auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) {
1727 const CXXRecordDecl *RD =
1729 if (!RD || RD->hasConstexprDestructor())
1730 return true;
1731
1733 SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject)
1734 << static_cast<int>(DD->getConstexprKind()) << !FD
1735 << (FD ? FD->getDeclName() : DeclarationName()) << T;
1736 SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject)
1737 << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T;
1738 }
1739 return false;
1740 };
1741
1742 const CXXRecordDecl *RD = DD->getParent();
1743 for (const CXXBaseSpecifier &B : RD->bases())
1744 if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr))
1745 return false;
1746 for (const FieldDecl *FD : RD->fields())
1747 if (!Check(FD->getLocation(), FD->getType(), FD))
1748 return false;
1749 return true;
1750}
1751
1752/// Check whether a function's parameter types are all literal types. If so,
1753/// return true. If not, produce a suitable diagnostic and return false.
1755 const FunctionDecl *FD,
1757 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1758 "this check is obsolete for C++23");
1759 unsigned ArgIndex = 0;
1760 const auto *FT = FD->getType()->castAs<FunctionProtoType>();
1761 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1762 e = FT->param_type_end();
1763 i != e; ++i, ++ArgIndex) {
1764 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1765 assert(PD && "null in a parameter list");
1766 SourceLocation ParamLoc = PD->getLocation();
1767 if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i,
1768 diag::err_constexpr_non_literal_param, ArgIndex + 1,
1769 PD->getSourceRange(), isa<CXXConstructorDecl>(FD),
1770 FD->isConsteval()))
1771 return false;
1772 }
1773 return true;
1774}
1775
1776/// Check whether a function's return type is a literal type. If so, return
1777/// true. If not, produce a suitable diagnostic and return false.
1780 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1781 "this check is obsolete for C++23");
1782 if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(),
1783 diag::err_constexpr_non_literal_return,
1784 FD->isConsteval()))
1785 return false;
1786 return true;
1787}
1788
1789/// Get diagnostic %select index for tag kind for
1790/// record diagnostic message.
1791/// WARNING: Indexes apply to particular diagnostics only!
1792///
1793/// \returns diagnostic %select index.
1795 switch (Tag) {
1797 return 0;
1799 return 1;
1800 case TagTypeKind::Class:
1801 return 2;
1802 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1803 }
1804}
1805
1806static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
1807 Stmt *Body,
1809
1810// Check whether a function declaration satisfies the requirements of a
1811// constexpr function definition or a constexpr constructor definition. If so,
1812// return true. If not, produce appropriate diagnostics (unless asked not to by
1813// Kind) and return false.
1814//
1815// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1817 CheckConstexprKind Kind) {
1818 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1819 if (MD && MD->isInstance()) {
1820 // C++11 [dcl.constexpr]p4:
1821 // The definition of a constexpr constructor shall satisfy the following
1822 // constraints:
1823 // - the class shall not have any virtual base classes;
1824 //
1825 // FIXME: This only applies to constructors and destructors, not arbitrary
1826 // member functions.
1827 const CXXRecordDecl *RD = MD->getParent();
1828 if (RD->getNumVBases()) {
1830 return false;
1831
1832 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1833 << isa<CXXConstructorDecl>(NewFD)
1835 for (const auto &I : RD->vbases())
1836 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1837 << I.getSourceRange();
1838 return false;
1839 }
1840 }
1841
1842 if (!isa<CXXConstructorDecl>(NewFD)) {
1843 // C++11 [dcl.constexpr]p3:
1844 // The definition of a constexpr function shall satisfy the following
1845 // constraints:
1846 // - it shall not be virtual; (removed in C++20)
1847 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1848 if (Method && Method->isVirtual()) {
1849 if (getLangOpts().CPlusPlus20) {
1850 if (Kind == CheckConstexprKind::Diagnose)
1851 Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
1852 } else {
1854 return false;
1855
1856 Method = Method->getCanonicalDecl();
1857 Diag(Method->getLocation(), diag::err_constexpr_virtual);
1858
1859 // If it's not obvious why this function is virtual, find an overridden
1860 // function which uses the 'virtual' keyword.
1861 const CXXMethodDecl *WrittenVirtual = Method;
1862 while (!WrittenVirtual->isVirtualAsWritten())
1863 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1864 if (WrittenVirtual != Method)
1865 Diag(WrittenVirtual->getLocation(),
1866 diag::note_overridden_virtual_function);
1867 return false;
1868 }
1869 }
1870
1871 // - its return type shall be a literal type; (removed in C++23)
1872 if (!getLangOpts().CPlusPlus23 &&
1873 !CheckConstexprReturnType(*this, NewFD, Kind))
1874 return false;
1875 }
1876
1877 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) {
1878 // A destructor can be constexpr only if the defaulted destructor could be;
1879 // we don't need to check the members and bases if we already know they all
1880 // have constexpr destructors. (removed in C++23)
1881 if (!getLangOpts().CPlusPlus23 &&
1882 !Dtor->getParent()->defaultedDestructorIsConstexpr()) {
1884 return false;
1885 if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind))
1886 return false;
1887 }
1888 }
1889
1890 // - each of its parameter types shall be a literal type; (removed in C++23)
1891 if (!getLangOpts().CPlusPlus23 &&
1892 !CheckConstexprParameterTypes(*this, NewFD, Kind))
1893 return false;
1894
1895 Stmt *Body = NewFD->getBody();
1896 assert(Body &&
1897 "CheckConstexprFunctionDefinition called on function with no body");
1898 return CheckConstexprFunctionBody(*this, NewFD, Body, Kind);
1899}
1900
1901/// Check the given declaration statement is legal within a constexpr function
1902/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1903///
1904/// \return true if the body is OK (maybe only as an extension), false if we
1905/// have diagnosed a problem.
1907 DeclStmt *DS, SourceLocation &Cxx1yLoc,
1909 // C++11 [dcl.constexpr]p3 and p4:
1910 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
1911 // contain only
1912 for (const auto *DclIt : DS->decls()) {
1913 switch (DclIt->getKind()) {
1914 case Decl::StaticAssert:
1915 case Decl::Using:
1916 case Decl::UsingShadow:
1917 case Decl::UsingDirective:
1918 case Decl::UnresolvedUsingTypename:
1919 case Decl::UnresolvedUsingValue:
1920 case Decl::UsingEnum:
1921 // - static_assert-declarations
1922 // - using-declarations,
1923 // - using-directives,
1924 // - using-enum-declaration
1925 continue;
1926
1927 case Decl::Typedef:
1928 case Decl::TypeAlias: {
1929 // - typedef declarations and alias-declarations that do not define
1930 // classes or enumerations,
1931 const auto *TN = cast<TypedefNameDecl>(DclIt);
1932 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1933 // Don't allow variably-modified types in constexpr functions.
1935 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1936 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1937 << TL.getSourceRange() << TL.getType()
1938 << isa<CXXConstructorDecl>(Dcl);
1939 }
1940 return false;
1941 }
1942 continue;
1943 }
1944
1945 case Decl::Enum:
1946 case Decl::CXXRecord:
1947 // C++1y allows types to be defined, not just declared.
1948 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) {
1950 SemaRef.Diag(DS->getBeginLoc(),
1951 SemaRef.getLangOpts().CPlusPlus14
1952 ? diag::warn_cxx11_compat_constexpr_type_definition
1953 : diag::ext_constexpr_type_definition)
1954 << isa<CXXConstructorDecl>(Dcl);
1955 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1956 return false;
1957 }
1958 }
1959 continue;
1960
1961 case Decl::EnumConstant:
1962 case Decl::IndirectField:
1963 case Decl::ParmVar:
1964 // These can only appear with other declarations which are banned in
1965 // C++11 and permitted in C++1y, so ignore them.
1966 continue;
1967
1968 case Decl::Var:
1969 case Decl::Decomposition: {
1970 // C++1y [dcl.constexpr]p3 allows anything except:
1971 // a definition of a variable of non-literal type or of static or
1972 // thread storage duration or [before C++2a] for which no
1973 // initialization is performed.
1974 const auto *VD = cast<VarDecl>(DclIt);
1975 if (VD->isThisDeclarationADefinition()) {
1976 if (VD->isStaticLocal()) {
1978 SemaRef.Diag(VD->getLocation(),
1979 SemaRef.getLangOpts().CPlusPlus23
1980 ? diag::warn_cxx20_compat_constexpr_var
1981 : diag::ext_constexpr_static_var)
1982 << isa<CXXConstructorDecl>(Dcl)
1983 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1984 } else if (!SemaRef.getLangOpts().CPlusPlus23) {
1985 return false;
1986 }
1987 }
1988 if (SemaRef.LangOpts.CPlusPlus23) {
1989 CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(),
1990 diag::warn_cxx20_compat_constexpr_var,
1991 isa<CXXConstructorDecl>(Dcl),
1992 /*variable of non-literal type*/ 2);
1993 } else if (CheckLiteralType(
1994 SemaRef, Kind, VD->getLocation(), VD->getType(),
1995 diag::err_constexpr_local_var_non_literal_type,
1996 isa<CXXConstructorDecl>(Dcl))) {
1997 return false;
1998 }
1999 if (!VD->getType()->isDependentType() &&
2000 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
2002 SemaRef.Diag(
2003 VD->getLocation(),
2004 SemaRef.getLangOpts().CPlusPlus20
2005 ? diag::warn_cxx17_compat_constexpr_local_var_no_init
2006 : diag::ext_constexpr_local_var_no_init)
2007 << isa<CXXConstructorDecl>(Dcl);
2008 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2009 return false;
2010 }
2011 continue;
2012 }
2013 }
2015 SemaRef.Diag(VD->getLocation(),
2016 SemaRef.getLangOpts().CPlusPlus14
2017 ? diag::warn_cxx11_compat_constexpr_local_var
2018 : diag::ext_constexpr_local_var)
2019 << isa<CXXConstructorDecl>(Dcl);
2020 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
2021 return false;
2022 }
2023 continue;
2024 }
2025
2026 case Decl::NamespaceAlias:
2027 case Decl::Function:
2028 // These are disallowed in C++11 and permitted in C++1y. Allow them
2029 // everywhere as an extension.
2030 if (!Cxx1yLoc.isValid())
2031 Cxx1yLoc = DS->getBeginLoc();
2032 continue;
2033
2034 default:
2036 SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2037 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2038 }
2039 return false;
2040 }
2041 }
2042
2043 return true;
2044}
2045
2046/// Check that the given field is initialized within a constexpr constructor.
2047///
2048/// \param Dcl The constexpr constructor being checked.
2049/// \param Field The field being checked. This may be a member of an anonymous
2050/// struct or union nested within the class being checked.
2051/// \param Inits All declarations, including anonymous struct/union members and
2052/// indirect members, for which any initialization was provided.
2053/// \param Diagnosed Whether we've emitted the error message yet. Used to attach
2054/// multiple notes for different members to the same error.
2055/// \param Kind Whether we're diagnosing a constructor as written or determining
2056/// whether the formal requirements are satisfied.
2057/// \return \c false if we're checking for validity and the constructor does
2058/// not satisfy the requirements on a constexpr constructor.
2060 const FunctionDecl *Dcl,
2061 FieldDecl *Field,
2062 llvm::SmallSet<Decl*, 16> &Inits,
2063 bool &Diagnosed,
2065 // In C++20 onwards, there's nothing to check for validity.
2067 SemaRef.getLangOpts().CPlusPlus20)
2068 return true;
2069
2070 if (Field->isInvalidDecl())
2071 return true;
2072
2073 if (Field->isUnnamedBitField())
2074 return true;
2075
2076 // Anonymous unions with no variant members and empty anonymous structs do not
2077 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
2078 // indirect fields don't need initializing.
2079 if (Field->isAnonymousStructOrUnion() &&
2080 (Field->getType()->isUnionType()
2081 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
2082 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
2083 return true;
2084
2085 if (!Inits.count(Field)) {
2087 if (!Diagnosed) {
2088 SemaRef.Diag(Dcl->getLocation(),
2089 SemaRef.getLangOpts().CPlusPlus20
2090 ? diag::warn_cxx17_compat_constexpr_ctor_missing_init
2091 : diag::ext_constexpr_ctor_missing_init);
2092 Diagnosed = true;
2093 }
2094 SemaRef.Diag(Field->getLocation(),
2095 diag::note_constexpr_ctor_missing_init);
2096 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2097 return false;
2098 }
2099 } else if (Field->isAnonymousStructOrUnion()) {
2100 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
2101 for (auto *I : RD->fields())
2102 // If an anonymous union contains an anonymous struct of which any member
2103 // is initialized, all members must be initialized.
2104 if (!RD->isUnion() || Inits.count(I))
2105 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2106 Kind))
2107 return false;
2108 }
2109 return true;
2110}
2111
2112/// Check the provided statement is allowed in a constexpr function
2113/// definition.
2114static bool
2117 SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
2118 SourceLocation &Cxx2bLoc,
2120 // - its function-body shall be [...] a compound-statement that contains only
2121 switch (S->getStmtClass()) {
2122 case Stmt::NullStmtClass:
2123 // - null statements,
2124 return true;
2125
2126 case Stmt::DeclStmtClass:
2127 // - static_assert-declarations
2128 // - using-declarations,
2129 // - using-directives,
2130 // - typedef declarations and alias-declarations that do not define
2131 // classes or enumerations,
2132 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind))
2133 return false;
2134 return true;
2135
2136 case Stmt::ReturnStmtClass:
2137 // - and exactly one return statement;
2138 if (isa<CXXConstructorDecl>(Dcl)) {
2139 // C++1y allows return statements in constexpr constructors.
2140 if (!Cxx1yLoc.isValid())
2141 Cxx1yLoc = S->getBeginLoc();
2142 return true;
2143 }
2144
2145 ReturnStmts.push_back(S->getBeginLoc());
2146 return true;
2147
2148 case Stmt::AttributedStmtClass:
2149 // Attributes on a statement don't affect its formal kind and hence don't
2150 // affect its validity in a constexpr function.
2152 SemaRef, Dcl, cast<AttributedStmt>(S)->getSubStmt(), ReturnStmts,
2153 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind);
2154
2155 case Stmt::CompoundStmtClass: {
2156 // C++1y allows compound-statements.
2157 if (!Cxx1yLoc.isValid())
2158 Cxx1yLoc = S->getBeginLoc();
2159
2160 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
2161 for (auto *BodyIt : CompStmt->body()) {
2162 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
2163 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2164 return false;
2165 }
2166 return true;
2167 }
2168
2169 case Stmt::IfStmtClass: {
2170 // C++1y allows if-statements.
2171 if (!Cxx1yLoc.isValid())
2172 Cxx1yLoc = S->getBeginLoc();
2173
2174 IfStmt *If = cast<IfStmt>(S);
2175 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
2176 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2177 return false;
2178 if (If->getElse() &&
2179 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
2180 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2181 return false;
2182 return true;
2183 }
2184
2185 case Stmt::WhileStmtClass:
2186 case Stmt::DoStmtClass:
2187 case Stmt::ForStmtClass:
2188 case Stmt::CXXForRangeStmtClass:
2189 case Stmt::ContinueStmtClass:
2190 // C++1y allows all of these. We don't allow them as extensions in C++11,
2191 // because they don't make sense without variable mutation.
2192 if (!SemaRef.getLangOpts().CPlusPlus14)
2193 break;
2194 if (!Cxx1yLoc.isValid())
2195 Cxx1yLoc = S->getBeginLoc();
2196 for (Stmt *SubStmt : S->children()) {
2197 if (SubStmt &&
2198 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2199 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2200 return false;
2201 }
2202 return true;
2203
2204 case Stmt::SwitchStmtClass:
2205 case Stmt::CaseStmtClass:
2206 case Stmt::DefaultStmtClass:
2207 case Stmt::BreakStmtClass:
2208 // C++1y allows switch-statements, and since they don't need variable
2209 // mutation, we can reasonably allow them in C++11 as an extension.
2210 if (!Cxx1yLoc.isValid())
2211 Cxx1yLoc = S->getBeginLoc();
2212 for (Stmt *SubStmt : S->children()) {
2213 if (SubStmt &&
2214 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2215 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2216 return false;
2217 }
2218 return true;
2219
2220 case Stmt::LabelStmtClass:
2221 case Stmt::GotoStmtClass:
2222 if (Cxx2bLoc.isInvalid())
2223 Cxx2bLoc = S->getBeginLoc();
2224 for (Stmt *SubStmt : S->children()) {
2225 if (SubStmt &&
2226 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2227 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2228 return false;
2229 }
2230 return true;
2231
2232 case Stmt::GCCAsmStmtClass:
2233 case Stmt::MSAsmStmtClass:
2234 // C++2a allows inline assembly statements.
2235 case Stmt::CXXTryStmtClass:
2236 if (Cxx2aLoc.isInvalid())
2237 Cxx2aLoc = S->getBeginLoc();
2238 for (Stmt *SubStmt : S->children()) {
2239 if (SubStmt &&
2240 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2241 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2242 return false;
2243 }
2244 return true;
2245
2246 case Stmt::CXXCatchStmtClass:
2247 // Do not bother checking the language mode (already covered by the
2248 // try block check).
2250 SemaRef, Dcl, cast<CXXCatchStmt>(S)->getHandlerBlock(), ReturnStmts,
2251 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2252 return false;
2253 return true;
2254
2255 default:
2256 if (!isa<Expr>(S))
2257 break;
2258
2259 // C++1y allows expression-statements.
2260 if (!Cxx1yLoc.isValid())
2261 Cxx1yLoc = S->getBeginLoc();
2262 return true;
2263 }
2264
2266 SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2267 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2268 }
2269 return false;
2270}
2271
2272/// Check the body for the given constexpr function declaration only contains
2273/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
2274///
2275/// \return true if the body is OK, false if we have found or diagnosed a
2276/// problem.
2278 Stmt *Body,
2281
2282 if (isa<CXXTryStmt>(Body)) {
2283 // C++11 [dcl.constexpr]p3:
2284 // The definition of a constexpr function shall satisfy the following
2285 // constraints: [...]
2286 // - its function-body shall be = delete, = default, or a
2287 // compound-statement
2288 //
2289 // C++11 [dcl.constexpr]p4:
2290 // In the definition of a constexpr constructor, [...]
2291 // - its function-body shall not be a function-try-block;
2292 //
2293 // This restriction is lifted in C++2a, as long as inner statements also
2294 // apply the general constexpr rules.
2295 switch (Kind) {
2297 if (!SemaRef.getLangOpts().CPlusPlus20)
2298 return false;
2299 break;
2300
2302 SemaRef.Diag(Body->getBeginLoc(),
2303 !SemaRef.getLangOpts().CPlusPlus20
2304 ? diag::ext_constexpr_function_try_block_cxx20
2305 : diag::warn_cxx17_compat_constexpr_function_try_block)
2306 << isa<CXXConstructorDecl>(Dcl);
2307 break;
2308 }
2309 }
2310
2311 // - its function-body shall be [...] a compound-statement that contains only
2312 // [... list of cases ...]
2313 //
2314 // Note that walking the children here is enough to properly check for
2315 // CompoundStmt and CXXTryStmt body.
2316 SourceLocation Cxx1yLoc, Cxx2aLoc, Cxx2bLoc;
2317 for (Stmt *SubStmt : Body->children()) {
2318 if (SubStmt &&
2319 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2320 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2321 return false;
2322 }
2323
2325 // If this is only valid as an extension, report that we don't satisfy the
2326 // constraints of the current language.
2327 if ((Cxx2bLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus23) ||
2328 (Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) ||
2329 (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
2330 return false;
2331 } else if (Cxx2bLoc.isValid()) {
2332 SemaRef.Diag(Cxx2bLoc,
2333 SemaRef.getLangOpts().CPlusPlus23
2334 ? diag::warn_cxx20_compat_constexpr_body_invalid_stmt
2335 : diag::ext_constexpr_body_invalid_stmt_cxx23)
2336 << isa<CXXConstructorDecl>(Dcl);
2337 } else if (Cxx2aLoc.isValid()) {
2338 SemaRef.Diag(Cxx2aLoc,
2339 SemaRef.getLangOpts().CPlusPlus20
2340 ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
2341 : diag::ext_constexpr_body_invalid_stmt_cxx20)
2342 << isa<CXXConstructorDecl>(Dcl);
2343 } else if (Cxx1yLoc.isValid()) {
2344 SemaRef.Diag(Cxx1yLoc,
2345 SemaRef.getLangOpts().CPlusPlus14
2346 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
2347 : diag::ext_constexpr_body_invalid_stmt)
2348 << isa<CXXConstructorDecl>(Dcl);
2349 }
2350
2351 if (const CXXConstructorDecl *Constructor
2352 = dyn_cast<CXXConstructorDecl>(Dcl)) {
2353 const CXXRecordDecl *RD = Constructor->getParent();
2354 // DR1359:
2355 // - every non-variant non-static data member and base class sub-object
2356 // shall be initialized;
2357 // DR1460:
2358 // - if the class is a union having variant members, exactly one of them
2359 // shall be initialized;
2360 if (RD->isUnion()) {
2361 if (Constructor->getNumCtorInitializers() == 0 &&
2362 RD->hasVariantMembers()) {
2364 SemaRef.Diag(
2365 Dcl->getLocation(),
2366 SemaRef.getLangOpts().CPlusPlus20
2367 ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init
2368 : diag::ext_constexpr_union_ctor_no_init);
2369 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2370 return false;
2371 }
2372 }
2373 } else if (!Constructor->isDependentContext() &&
2374 !Constructor->isDelegatingConstructor()) {
2375 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
2376
2377 // Skip detailed checking if we have enough initializers, and we would
2378 // allow at most one initializer per member.
2379 bool AnyAnonStructUnionMembers = false;
2380 unsigned Fields = 0;
2382 E = RD->field_end(); I != E; ++I, ++Fields) {
2383 if (I->isAnonymousStructOrUnion()) {
2384 AnyAnonStructUnionMembers = true;
2385 break;
2386 }
2387 }
2388 // DR1460:
2389 // - if the class is a union-like class, but is not a union, for each of
2390 // its anonymous union members having variant members, exactly one of
2391 // them shall be initialized;
2392 if (AnyAnonStructUnionMembers ||
2393 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2394 // Check initialization of non-static data members. Base classes are
2395 // always initialized so do not need to be checked. Dependent bases
2396 // might not have initializers in the member initializer list.
2397 llvm::SmallSet<Decl*, 16> Inits;
2398 for (const auto *I: Constructor->inits()) {
2399 if (FieldDecl *FD = I->getMember())
2400 Inits.insert(FD);
2401 else if (IndirectFieldDecl *ID = I->getIndirectMember())
2402 Inits.insert(ID->chain_begin(), ID->chain_end());
2403 }
2404
2405 bool Diagnosed = false;
2406 for (auto *I : RD->fields())
2407 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2408 Kind))
2409 return false;
2410 }
2411 }
2412 } else {
2413 if (ReturnStmts.empty()) {
2414 // C++1y doesn't require constexpr functions to contain a 'return'
2415 // statement. We still do, unless the return type might be void, because
2416 // otherwise if there's no return statement, the function cannot
2417 // be used in a core constant expression.
2418 bool OK = SemaRef.getLangOpts().CPlusPlus14 &&
2419 (Dcl->getReturnType()->isVoidType() ||
2420 Dcl->getReturnType()->isDependentType());
2421 switch (Kind) {
2423 SemaRef.Diag(Dcl->getLocation(),
2424 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2425 : diag::err_constexpr_body_no_return)
2426 << Dcl->isConsteval();
2427 if (!OK)
2428 return false;
2429 break;
2430
2432 // The formal requirements don't include this rule in C++14, even
2433 // though the "must be able to produce a constant expression" rules
2434 // still imply it in some cases.
2435 if (!SemaRef.getLangOpts().CPlusPlus14)
2436 return false;
2437 break;
2438 }
2439 } else if (ReturnStmts.size() > 1) {
2440 switch (Kind) {
2442 SemaRef.Diag(
2443 ReturnStmts.back(),
2444 SemaRef.getLangOpts().CPlusPlus14
2445 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2446 : diag::ext_constexpr_body_multiple_return);
2447 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2448 SemaRef.Diag(ReturnStmts[I],
2449 diag::note_constexpr_body_previous_return);
2450 break;
2451
2453 if (!SemaRef.getLangOpts().CPlusPlus14)
2454 return false;
2455 break;
2456 }
2457 }
2458 }
2459
2460 // C++11 [dcl.constexpr]p5:
2461 // if no function argument values exist such that the function invocation
2462 // substitution would produce a constant expression, the program is
2463 // ill-formed; no diagnostic required.
2464 // C++11 [dcl.constexpr]p3:
2465 // - every constructor call and implicit conversion used in initializing the
2466 // return value shall be one of those allowed in a constant expression.
2467 // C++11 [dcl.constexpr]p4:
2468 // - every constructor involved in initializing non-static data members and
2469 // base class sub-objects shall be a constexpr constructor.
2470 //
2471 // Note that this rule is distinct from the "requirements for a constexpr
2472 // function", so is not checked in CheckValid mode.
2476 !SemaRef.getLangOpts().CPlusPlus23) {
2477 SemaRef.Diag(Dcl->getLocation(),
2478 diag::ext_constexpr_function_never_constant_expr)
2479 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval()
2480 << Dcl->getNameInfo().getSourceRange();
2481 for (size_t I = 0, N = Diags.size(); I != N; ++I)
2482 SemaRef.Diag(Diags[I].first, Diags[I].second);
2483 // Don't return false here: we allow this for compatibility in
2484 // system headers.
2485 }
2486
2487 return true;
2488}
2489
2491 FunctionDecl *FD, const sema::FunctionScopeInfo *FSI) {
2493 return true;
2497 auto it = UndefinedButUsed.find(FD->getCanonicalDecl());
2498 if (it != UndefinedButUsed.end()) {
2499 Diag(it->second, diag::err_immediate_function_used_before_definition)
2500 << it->first;
2501 Diag(FD->getLocation(), diag::note_defined_here) << FD;
2502 if (FD->isImmediateFunction() && !FD->isConsteval())
2504 return false;
2505 }
2506 }
2507 return true;
2508}
2509
2511 assert(FD->isImmediateEscalating() && !FD->isConsteval() &&
2512 "expected an immediate function");
2513 assert(FD->hasBody() && "expected the function to have a body");
2514 struct ImmediateEscalatingExpressionsVisitor
2515 : public RecursiveASTVisitor<ImmediateEscalatingExpressionsVisitor> {
2516
2518 Sema &SemaRef;
2519
2520 const FunctionDecl *ImmediateFn;
2521 bool ImmediateFnIsConstructor;
2522 CXXConstructorDecl *CurrentConstructor = nullptr;
2523 CXXCtorInitializer *CurrentInit = nullptr;
2524
2525 ImmediateEscalatingExpressionsVisitor(Sema &SemaRef, FunctionDecl *FD)
2526 : SemaRef(SemaRef), ImmediateFn(FD),
2527 ImmediateFnIsConstructor(isa<CXXConstructorDecl>(FD)) {}
2528
2529 bool shouldVisitImplicitCode() const { return true; }
2530 bool shouldVisitLambdaBody() const { return false; }
2531
2532 void Diag(const Expr *E, const FunctionDecl *Fn, bool IsCall) {
2535 if (CurrentConstructor && CurrentInit) {
2536 Loc = CurrentConstructor->getLocation();
2537 Range = CurrentInit->isWritten() ? CurrentInit->getSourceRange()
2538 : SourceRange();
2539 }
2540
2541 FieldDecl* InitializedField = CurrentInit ? CurrentInit->getAnyMember() : nullptr;
2542
2543 SemaRef.Diag(Loc, diag::note_immediate_function_reason)
2544 << ImmediateFn << Fn << Fn->isConsteval() << IsCall
2545 << isa<CXXConstructorDecl>(Fn) << ImmediateFnIsConstructor
2546 << (InitializedField != nullptr)
2547 << (CurrentInit && !CurrentInit->isWritten())
2548 << InitializedField << Range;
2549 }
2550 bool TraverseCallExpr(CallExpr *E) {
2551 if (const auto *DR =
2552 dyn_cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit());
2553 DR && DR->isImmediateEscalating()) {
2554 Diag(E, E->getDirectCallee(), /*IsCall=*/true);
2555 return false;
2556 }
2557
2558 for (Expr *A : E->arguments())
2559 if (!getDerived().TraverseStmt(A))
2560 return false;
2561
2562 return true;
2563 }
2564
2565 bool VisitDeclRefExpr(DeclRefExpr *E) {
2566 if (const auto *ReferencedFn = dyn_cast<FunctionDecl>(E->getDecl());
2567 ReferencedFn && E->isImmediateEscalating()) {
2568 Diag(E, ReferencedFn, /*IsCall=*/false);
2569 return false;
2570 }
2571
2572 return true;
2573 }
2574
2575 bool VisitCXXConstructExpr(CXXConstructExpr *E) {
2577 if (E->isImmediateEscalating()) {
2578 Diag(E, D, /*IsCall=*/true);
2579 return false;
2580 }
2581 return true;
2582 }
2583
2584 bool TraverseConstructorInitializer(CXXCtorInitializer *Init) {
2585 llvm::SaveAndRestore RAII(CurrentInit, Init);
2586 return Base::TraverseConstructorInitializer(Init);
2587 }
2588
2589 bool TraverseCXXConstructorDecl(CXXConstructorDecl *Ctr) {
2590 llvm::SaveAndRestore RAII(CurrentConstructor, Ctr);
2591 return Base::TraverseCXXConstructorDecl(Ctr);
2592 }
2593
2594 bool TraverseType(QualType T) { return true; }
2595 bool VisitBlockExpr(BlockExpr *T) { return true; }
2596
2597 } Visitor(*this, FD);
2598 Visitor.TraverseDecl(FD);
2599}
2600
2601/// Get the class that is directly named by the current context. This is the
2602/// class for which an unqualified-id in this scope could name a constructor
2603/// or destructor.
2604///
2605/// If the scope specifier denotes a class, this will be that class.
2606/// If the scope specifier is empty, this will be the class whose
2607/// member-specification we are currently within. Otherwise, there
2608/// is no such class.
2610 assert(getLangOpts().CPlusPlus && "No class names in C!");
2611
2612 if (SS && SS->isInvalid())
2613 return nullptr;
2614
2615 if (SS && SS->isNotEmpty()) {
2616 DeclContext *DC = computeDeclContext(*SS, true);
2617 return dyn_cast_or_null<CXXRecordDecl>(DC);
2618 }
2619
2620 return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2621}
2622
2623/// isCurrentClassName - Determine whether the identifier II is the
2624/// name of the class type currently being defined. In the case of
2625/// nested classes, this will only return true if II is the name of
2626/// the innermost class.
2628 const CXXScopeSpec *SS) {
2629 CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2630 return CurDecl && &II == CurDecl->getIdentifier();
2631}
2632
2633/// Determine whether the identifier II is a typo for the name of
2634/// the class type currently being defined. If so, update it to the identifier
2635/// that should have been used.
2637 assert(getLangOpts().CPlusPlus && "No class names in C!");
2638
2639 if (!getLangOpts().SpellChecking)
2640 return false;
2641
2642 CXXRecordDecl *CurDecl;
2643 if (SS && SS->isSet() && !SS->isInvalid()) {
2644 DeclContext *DC = computeDeclContext(*SS, true);
2645 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2646 } else
2647 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2648
2649 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2650 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2651 < II->getLength()) {
2652 II = CurDecl->getIdentifier();
2653 return true;
2654 }
2655
2656 return false;
2657}
2658
2659/// Check the validity of a C++ base class specifier.
2660///
2661/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2662/// and returns NULL otherwise.
2664 SourceRange SpecifierRange,
2665 bool Virtual, AccessSpecifier Access,
2666 TypeSourceInfo *TInfo,
2667 SourceLocation EllipsisLoc) {
2668 QualType BaseType = TInfo->getType();
2669 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2670 if (BaseType->containsErrors()) {
2671 // Already emitted a diagnostic when parsing the error type.
2672 return nullptr;
2673 }
2674
2675 if (EllipsisLoc.isValid() && !BaseType->containsUnexpandedParameterPack()) {
2676 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2677 << TInfo->getTypeLoc().getSourceRange();
2678 EllipsisLoc = SourceLocation();
2679 }
2680
2681 auto *BaseDecl =
2682 dyn_cast_if_present<CXXRecordDecl>(computeDeclContext(BaseType));
2683 // C++ [class.derived.general]p2:
2684 // A class-or-decltype shall denote a (possibly cv-qualified) class type
2685 // that is not an incompletely defined class; any cv-qualifiers are
2686 // ignored.
2687 if (BaseDecl) {
2688 // C++ [class.union.general]p4:
2689 // [...] A union shall not be used as a base class.
2690 if (BaseDecl->isUnion()) {
2691 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2692 return nullptr;
2693 }
2694
2695 // For the MS ABI, propagate DLL attributes to base class templates.
2697 Context.getTargetInfo().getTriple().isPS()) {
2698 if (Attr *ClassAttr = getDLLAttr(Class)) {
2699 if (auto *BaseSpec =
2700 dyn_cast<ClassTemplateSpecializationDecl>(BaseDecl)) {
2701 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseSpec,
2702 BaseLoc);
2703 }
2704 }
2705 }
2706
2707 if (RequireCompleteType(BaseLoc, BaseType, diag::err_incomplete_base_class,
2708 SpecifierRange)) {
2709 Class->setInvalidDecl();
2710 return nullptr;
2711 }
2712
2713 BaseDecl = BaseDecl->getDefinition();
2714 assert(BaseDecl && "Base type is not incomplete, but has no definition");
2715
2716 // Microsoft docs say:
2717 // "If a base-class has a code_seg attribute, derived classes must have the
2718 // same attribute."
2719 const auto *BaseCSA = BaseDecl->getAttr<CodeSegAttr>();
2720 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2721 if ((DerivedCSA || BaseCSA) &&
2722 (!BaseCSA || !DerivedCSA ||
2723 BaseCSA->getName() != DerivedCSA->getName())) {
2724 Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2725 Diag(BaseDecl->getLocation(), diag::note_base_class_specified_here)
2726 << BaseDecl;
2727 return nullptr;
2728 }
2729
2730 // A class which contains a flexible array member is not suitable for use as
2731 // a base class:
2732 // - If the layout determines that a base comes before another base,
2733 // the flexible array member would index into the subsequent base.
2734 // - If the layout determines that base comes before the derived class,
2735 // the flexible array member would index into the derived class.
2736 if (BaseDecl->hasFlexibleArrayMember()) {
2737 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2738 << BaseDecl->getDeclName();
2739 return nullptr;
2740 }
2741
2742 // C++ [class]p3:
2743 // If a class is marked final and it appears as a base-type-specifier in
2744 // base-clause, the program is ill-formed.
2745 if (FinalAttr *FA = BaseDecl->getAttr<FinalAttr>()) {
2746 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2747 << BaseDecl->getDeclName() << FA->isSpelledAsSealed();
2748 Diag(BaseDecl->getLocation(), diag::note_entity_declared_at)
2749 << BaseDecl->getDeclName() << FA->getRange();
2750 return nullptr;
2751 }
2752
2753 // If the base class is invalid the derived class is as well.
2754 if (BaseDecl->isInvalidDecl())
2755 Class->setInvalidDecl();
2756 } else if (BaseType->isDependentType()) {
2757 // Make sure that we don't make an ill-formed AST where the type of the
2758 // Class is non-dependent and its attached base class specifier is an
2759 // dependent type, which violates invariants in many clang code paths (e.g.
2760 // constexpr evaluator). If this case happens (in errory-recovery mode), we
2761 // explicitly mark the Class decl invalid. The diagnostic was already
2762 // emitted.
2763 if (!Class->isDependentContext())
2764 Class->setInvalidDecl();
2765 } else {
2766 // The base class is some non-dependent non-class type.
2767 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2768 return nullptr;
2769 }
2770
2771 // In HLSL, unspecified class access is public rather than private.
2772 if (getLangOpts().HLSL && Class->getTagKind() == TagTypeKind::Class &&
2773 Access == AS_none)
2774 Access = AS_public;
2775
2776 // Create the base specifier.
2777 return new (Context) CXXBaseSpecifier(
2778 SpecifierRange, Virtual, Class->getTagKind() == TagTypeKind::Class,
2779 Access, TInfo, EllipsisLoc);
2780}
2781
2782/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2783/// one entry in the base class list of a class specifier, for
2784/// example:
2785/// class foo : public bar, virtual private baz {
2786/// 'public bar' and 'virtual private baz' are each base-specifiers.
2788 const ParsedAttributesView &Attributes,
2789 bool Virtual, AccessSpecifier Access,
2790 ParsedType basetype, SourceLocation BaseLoc,
2791 SourceLocation EllipsisLoc) {
2792 if (!classdecl)
2793 return true;
2794
2795 AdjustDeclIfTemplate(classdecl);
2796 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2797 if (!Class)
2798 return true;
2799
2800 // We haven't yet attached the base specifiers.
2801 Class->setIsParsingBaseSpecifiers();
2802
2803 // We do not support any C++11 attributes on base-specifiers yet.
2804 // Diagnose any attributes we see.
2805 for (const ParsedAttr &AL : Attributes) {
2806 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2807 continue;
2808 if (AL.getKind() == ParsedAttr::UnknownAttribute)
2809 Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored)
2810 << AL << AL.getRange();
2811 else
2812 Diag(AL.getLoc(), diag::err_base_specifier_attribute)
2813 << AL << AL.isRegularKeywordAttribute() << AL.getRange();
2814 }
2815
2816 TypeSourceInfo *TInfo = nullptr;
2817 GetTypeFromParser(basetype, &TInfo);
2818
2819 if (EllipsisLoc.isInvalid() &&
2820 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2822 return true;
2823
2824 // C++ [class.union.general]p4:
2825 // [...] A union shall not have base classes.
2826 if (Class->isUnion()) {
2827 Diag(Class->getLocation(), diag::err_base_clause_on_union)
2828 << SpecifierRange;
2829 return true;
2830 }
2831
2832 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2833 Virtual, Access, TInfo,
2834 EllipsisLoc))
2835 return BaseSpec;
2836
2837 Class->setInvalidDecl();
2838 return true;
2839}
2840
2841/// Use small set to collect indirect bases. As this is only used
2842/// locally, there's no need to abstract the small size parameter.
2844
2845/// Recursively add the bases of Type. Don't add Type itself.
2846static void
2848 const QualType &Type)
2849{
2850 // Even though the incoming type is a base, it might not be
2851 // a class -- it could be a template parm, for instance.
2852 if (auto Rec = Type->getAs<RecordType>()) {
2853 auto Decl = Rec->getAsCXXRecordDecl();
2854
2855 // Iterate over its bases.
2856 for (const auto &BaseSpec : Decl->bases()) {
2857 QualType Base = Context.getCanonicalType(BaseSpec.getType())
2859 if (Set.insert(Base).second)
2860 // If we've not already seen it, recurse.
2862 }
2863 }
2864}
2865
2866/// Performs the actual work of attaching the given base class
2867/// specifiers to a C++ class.
2870 if (Bases.empty())
2871 return false;
2872
2873 // Used to keep track of which base types we have already seen, so
2874 // that we can properly diagnose redundant direct base types. Note
2875 // that the key is always the unqualified canonical type of the base
2876 // class.
2877 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2878
2879 // Used to track indirect bases so we can see if a direct base is
2880 // ambiguous.
2881 IndirectBaseSet IndirectBaseTypes;
2882
2883 // Copy non-redundant base specifiers into permanent storage.
2884 unsigned NumGoodBases = 0;
2885 bool Invalid = false;
2886 for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2887 QualType NewBaseType
2888 = Context.getCanonicalType(Bases[idx]->getType());
2889 NewBaseType = NewBaseType.getLocalUnqualifiedType();
2890
2891 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2892 if (KnownBase) {
2893 // C++ [class.mi]p3:
2894 // A class shall not be specified as a direct base class of a
2895 // derived class more than once.
2896 Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2897 << KnownBase->getType() << Bases[idx]->getSourceRange();
2898
2899 // Delete the duplicate base class specifier; we're going to
2900 // overwrite its pointer later.
2901 Context.Deallocate(Bases[idx]);
2902
2903 Invalid = true;
2904 } else {
2905 // Okay, add this new base class.
2906 KnownBase = Bases[idx];
2907 Bases[NumGoodBases++] = Bases[idx];
2908
2909 if (NewBaseType->isDependentType())
2910 continue;
2911 // Note this base's direct & indirect bases, if there could be ambiguity.
2912 if (Bases.size() > 1)
2913 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2914
2915 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2916 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2917 if (Class->isInterface() &&
2918 (!RD->isInterfaceLike() ||
2919 KnownBase->getAccessSpecifier() != AS_public)) {
2920 // The Microsoft extension __interface does not permit bases that
2921 // are not themselves public interfaces.
2922 Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
2923 << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2924 << RD->getSourceRange();
2925 Invalid = true;
2926 }
2927 if (RD->hasAttr<WeakAttr>())
2928 Class->addAttr(WeakAttr::CreateImplicit(Context));
2929 }
2930 }
2931 }
2932
2933 // Attach the remaining base class specifiers to the derived class.
2934 Class->setBases(Bases.data(), NumGoodBases);
2935
2936 // Check that the only base classes that are duplicate are virtual.
2937 for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2938 // Check whether this direct base is inaccessible due to ambiguity.
2939 QualType BaseType = Bases[idx]->getType();
2940
2941 // Skip all dependent types in templates being used as base specifiers.
2942 // Checks below assume that the base specifier is a CXXRecord.
2943 if (BaseType->isDependentType())
2944 continue;
2945
2946 CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2948
2949 if (IndirectBaseTypes.count(CanonicalBase)) {
2950 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2951 /*DetectVirtual=*/true);
2952 bool found
2953 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2954 assert(found);
2955 (void)found;
2956
2957 if (Paths.isAmbiguous(CanonicalBase))
2958 Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
2959 << BaseType << getAmbiguousPathsDisplayString(Paths)
2960 << Bases[idx]->getSourceRange();
2961 else
2962 assert(Bases[idx]->isVirtual());
2963 }
2964
2965 // Delete the base class specifier, since its data has been copied
2966 // into the CXXRecordDecl.
2967 Context.Deallocate(Bases[idx]);
2968 }
2969
2970 return Invalid;
2971}
2972
2973/// ActOnBaseSpecifiers - Attach the given base specifiers to the
2974/// class, after checking whether there are any duplicate base
2975/// classes.
2978 if (!ClassDecl || Bases.empty())
2979 return;
2980
2981 AdjustDeclIfTemplate(ClassDecl);
2982 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2983}
2984
2985/// Determine whether the type \p Derived is a C++ class that is
2986/// derived from the type \p Base.
2988 if (!getLangOpts().CPlusPlus)
2989 return false;
2990
2991 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2992 if (!DerivedRD)
2993 return false;
2994
2995 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2996 if (!BaseRD)
2997 return false;
2998
2999 // If either the base or the derived type is invalid, don't try to
3000 // check whether one is derived from the other.
3001 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
3002 return false;
3003
3004 // FIXME: In a modules build, do we need the entire path to be visible for us
3005 // to be able to use the inheritance relationship?
3006 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
3007 return false;
3008
3009 return DerivedRD->isDerivedFrom(BaseRD);
3010}
3011
3012/// Determine whether the type \p Derived is a C++ class that is
3013/// derived from the type \p Base.
3015 CXXBasePaths &Paths) {
3016 if (!getLangOpts().CPlusPlus)
3017 return false;
3018
3019 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
3020 if (!DerivedRD)
3021 return false;
3022
3023 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
3024 if (!BaseRD)
3025 return false;
3026
3027 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
3028 return false;
3029
3030 return DerivedRD->isDerivedFrom(BaseRD, Paths);
3031}
3032
3033static void BuildBasePathArray(const CXXBasePath &Path,
3034 CXXCastPath &BasePathArray) {
3035 // We first go backward and check if we have a virtual base.
3036 // FIXME: It would be better if CXXBasePath had the base specifier for
3037 // the nearest virtual base.
3038 unsigned Start = 0;
3039 for (unsigned I = Path.size(); I != 0; --I) {
3040 if (Path[I - 1].Base->isVirtual()) {
3041 Start = I - 1;
3042 break;
3043 }
3044 }
3045
3046 // Now add all bases.
3047 for (unsigned I = Start, E = Path.size(); I != E; ++I)
3048 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
3049}
3050
3051
3053 CXXCastPath &BasePathArray) {
3054 assert(BasePathArray.empty() && "Base path array must be empty!");
3055 assert(Paths.isRecordingPaths() && "Must record paths!");
3056 return ::BuildBasePathArray(Paths.front(), BasePathArray);
3057}
3058/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
3059/// conversion (where Derived and Base are class types) is
3060/// well-formed, meaning that the conversion is unambiguous (and
3061/// that all of the base classes are accessible). Returns true
3062/// and emits a diagnostic if the code is ill-formed, returns false
3063/// otherwise. Loc is the location where this routine should point to
3064/// if there is an error, and Range is the source range to highlight
3065/// if there is an error.
3066///
3067/// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the
3068/// diagnostic for the respective type of error will be suppressed, but the
3069/// check for ill-formed code will still be performed.
3070bool
3072 unsigned InaccessibleBaseID,
3073 unsigned AmbiguousBaseConvID,
3075 DeclarationName Name,
3076 CXXCastPath *BasePath,
3077 bool IgnoreAccess) {
3078 // First, determine whether the path from Derived to Base is
3079 // ambiguous. This is slightly more expensive than checking whether
3080 // the Derived to Base conversion exists, because here we need to
3081 // explore multiple paths to determine if there is an ambiguity.
3082 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3083 /*DetectVirtual=*/false);
3084 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
3085 if (!DerivationOkay)
3086 return true;
3087
3088 const CXXBasePath *Path = nullptr;
3089 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
3090 Path = &Paths.front();
3091
3092 // For MSVC compatibility, check if Derived directly inherits from Base. Clang
3093 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
3094 // user to access such bases.
3095 if (!Path && getLangOpts().MSVCCompat) {
3096 for (const CXXBasePath &PossiblePath : Paths) {
3097 if (PossiblePath.size() == 1) {
3098 Path = &PossiblePath;
3099 if (AmbiguousBaseConvID)
3100 Diag(Loc, diag::ext_ms_ambiguous_direct_base)
3101 << Base << Derived << Range;
3102 break;
3103 }
3104 }
3105 }
3106
3107 if (Path) {
3108 if (!IgnoreAccess) {
3109 // Check that the base class can be accessed.
3110 switch (
3111 CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
3112 case AR_inaccessible:
3113 return true;
3114 case AR_accessible:
3115 case AR_dependent:
3116 case AR_delayed:
3117 break;
3118 }
3119 }
3120
3121 // Build a base path if necessary.
3122 if (BasePath)
3123 ::BuildBasePathArray(*Path, *BasePath);
3124 return false;
3125 }
3126
3127 if (AmbiguousBaseConvID) {
3128 // We know that the derived-to-base conversion is ambiguous, and
3129 // we're going to produce a diagnostic. Perform the derived-to-base
3130 // search just one more time to compute all of the possible paths so
3131 // that we can print them out. This is more expensive than any of
3132 // the previous derived-to-base checks we've done, but at this point
3133 // performance isn't as much of an issue.
3134 Paths.clear();
3135 Paths.setRecordingPaths(true);
3136 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
3137 assert(StillOkay && "Can only be used with a derived-to-base conversion");
3138 (void)StillOkay;
3139
3140 // Build up a textual representation of the ambiguous paths, e.g.,
3141 // D -> B -> A, that will be used to illustrate the ambiguous
3142 // conversions in the diagnostic. We only print one of the paths
3143 // to each base class subobject.
3144 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3145
3146 Diag(Loc, AmbiguousBaseConvID)
3147 << Derived << Base << PathDisplayStr << Range << Name;
3148 }
3149 return true;
3150}
3151
3152bool
3155 CXXCastPath *BasePath,
3156 bool IgnoreAccess) {
3158 Derived, Base, diag::err_upcast_to_inaccessible_base,
3159 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
3160 BasePath, IgnoreAccess);
3161}
3162
3163
3164/// Builds a string representing ambiguous paths from a
3165/// specific derived class to different subobjects of the same base
3166/// class.
3167///
3168/// This function builds a string that can be used in error messages
3169/// to show the different paths that one can take through the
3170/// inheritance hierarchy to go from the derived class to different
3171/// subobjects of a base class. The result looks something like this:
3172/// @code
3173/// struct D -> struct B -> struct A
3174/// struct D -> struct C -> struct A
3175/// @endcode
3177 std::string PathDisplayStr;
3178 std::set<unsigned> DisplayedPaths;
3179 for (CXXBasePaths::paths_iterator Path = Paths.begin();
3180 Path != Paths.end(); ++Path) {
3181 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
3182 // We haven't displayed a path to this particular base
3183 // class subobject yet.
3184 PathDisplayStr += "\n ";
3185 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
3186 for (CXXBasePath::const_iterator Element = Path->begin();
3187 Element != Path->end(); ++Element)
3188 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
3189 }
3190 }
3191
3192 return PathDisplayStr;
3193}
3194
3195//===----------------------------------------------------------------------===//
3196// C++ class member Handling
3197//===----------------------------------------------------------------------===//
3198
3199/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
3201 SourceLocation ColonLoc,
3202 const ParsedAttributesView &Attrs) {
3203 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
3205 ASLoc, ColonLoc);
3206 CurContext->addHiddenDecl(ASDecl);
3207 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
3208}
3209
3210/// CheckOverrideControl - Check C++11 override control semantics.
3212 if (D->isInvalidDecl())
3213 return;
3214
3215 // We only care about "override" and "final" declarations.
3216 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
3217 return;
3218
3219 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3220
3221 // We can't check dependent instance methods.
3222 if (MD && MD->isInstance() &&
3223 (MD->getParent()->hasAnyDependentBases() ||
3224 MD->getType()->isDependentType()))
3225 return;
3226
3227 if (MD && !MD->isVirtual()) {
3228 // If we have a non-virtual method, check if it hides a virtual method.
3229 // (In that case, it's most likely the method has the wrong type.)
3230 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3231 FindHiddenVirtualMethods(MD, OverloadedMethods);
3232
3233 if (!OverloadedMethods.empty()) {
3234 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3235 Diag(OA->getLocation(),
3236 diag::override_keyword_hides_virtual_member_function)
3237 << "override" << (OverloadedMethods.size() > 1);
3238 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3239 Diag(FA->getLocation(),
3240 diag::override_keyword_hides_virtual_member_function)
3241 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3242 << (OverloadedMethods.size() > 1);
3243 }
3244 NoteHiddenVirtualMethods(MD, OverloadedMethods);
3245 MD->setInvalidDecl();
3246 return;
3247 }
3248 // Fall through into the general case diagnostic.
3249 // FIXME: We might want to attempt typo correction here.
3250 }
3251
3252 if (!MD || !MD->isVirtual()) {
3253 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3254 Diag(OA->getLocation(),
3255 diag::override_keyword_only_allowed_on_virtual_member_functions)
3256 << "override" << FixItHint::CreateRemoval(OA->getLocation());
3257 D->dropAttr<OverrideAttr>();
3258 }
3259 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3260 Diag(FA->getLocation(),
3261 diag::override_keyword_only_allowed_on_virtual_member_functions)
3262 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3263 << FixItHint::CreateRemoval(FA->getLocation());
3264 D->dropAttr<FinalAttr>();
3265 }
3266 return;
3267 }
3268
3269 // C++11 [class.virtual]p5:
3270 // If a function is marked with the virt-specifier override and
3271 // does not override a member function of a base class, the program is
3272 // ill-formed.
3273 bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
3274 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
3275 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
3276 << MD->getDeclName();
3277}
3278
3280 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
3281 return;
3282 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3283 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
3284 return;
3285
3287 SourceLocation SpellingLoc = Loc;
3288 if (getSourceManager().isMacroArgExpansion(Loc))
3290 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
3291 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
3292 return;
3293
3294 if (MD->size_overridden_methods() > 0) {
3295 auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) {
3296 unsigned DiagID =
3297 Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation())
3298 ? DiagInconsistent
3299 : DiagSuggest;
3300 Diag(MD->getLocation(), DiagID) << MD->getDeclName();
3301 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
3302 Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
3303 };
3304 if (isa<CXXDestructorDecl>(MD))
3305 EmitDiag(
3306 diag::warn_inconsistent_destructor_marked_not_override_overriding,
3307 diag::warn_suggest_destructor_marked_not_override_overriding);
3308 else
3309 EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding,
3310 diag::warn_suggest_function_marked_not_override_overriding);
3311 }
3312}
3313
3314/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
3315/// function overrides a virtual member function marked 'final', according to
3316/// C++11 [class.virtual]p4.
3318 const CXXMethodDecl *Old) {
3319 FinalAttr *FA = Old->getAttr<FinalAttr>();
3320 if (!FA)
3321 return false;
3322
3323 Diag(New->getLocation(), diag::err_final_function_overridden)
3324 << New->getDeclName()
3325 << FA->isSpelledAsSealed();
3326 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3327 return true;
3328}
3329
3331 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
3332 // FIXME: Destruction of ObjC lifetime types has side-effects.
3333 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3334 return !RD->isCompleteDefinition() ||
3335 !RD->hasTrivialDefaultConstructor() ||
3336 !RD->hasTrivialDestructor();
3337 return false;
3338}
3339
3340// Check if there is a field shadowing.
3341void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
3342 DeclarationName FieldName,
3343 const CXXRecordDecl *RD,
3344 bool DeclIsField) {
3345 if (Diags.isIgnored(diag::warn_shadow_field, Loc))
3346 return;
3347
3348 // To record a shadowed field in a base
3349 std::map<CXXRecordDecl*, NamedDecl*> Bases;
3350 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
3351 CXXBasePath &Path) {
3352 const auto Base = Specifier->getType()->getAsCXXRecordDecl();
3353 // Record an ambiguous path directly
3354 if (Bases.find(Base) != Bases.end())
3355 return true;
3356 for (const auto Field : Base->lookup(FieldName)) {
3357 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
3358 Field->getAccess() != AS_private) {
3359 assert(Field->getAccess() != AS_none);
3360 assert(Bases.find(Base) == Bases.end());
3361 Bases[Base] = Field;
3362 return true;
3363 }
3364 }
3365 return false;
3366 };
3367
3368 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3369 /*DetectVirtual=*/true);
3370 if (!RD->lookupInBases(FieldShadowed, Paths))
3371 return;
3372
3373 for (const auto &P : Paths) {
3374 auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
3375 auto It = Bases.find(Base);
3376 // Skip duplicated bases
3377 if (It == Bases.end())
3378 continue;
3379 auto BaseField = It->second;
3380 assert(BaseField->getAccess() != AS_private);
3381 if (AS_none !=
3382 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
3383 Diag(Loc, diag::warn_shadow_field)
3384 << FieldName << RD << Base << DeclIsField;
3385 Diag(BaseField->getLocation(), diag::note_shadow_field);
3386 Bases.erase(It);
3387 }
3388 }
3389}
3390
3391/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
3392/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
3393/// bitfield width if there is one, 'InitExpr' specifies the initializer if
3394/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
3395/// present (but parsing it has been deferred).
3396NamedDecl *
3398 MultiTemplateParamsArg TemplateParameterLists,
3399 Expr *BW, const VirtSpecifiers &VS,
3400 InClassInitStyle InitStyle) {
3401 const DeclSpec &DS = D.getDeclSpec();
3403 DeclarationName Name = NameInfo.getName();
3404 SourceLocation Loc = NameInfo.getLoc();
3405
3406 // For anonymous bitfields, the location should point to the type.
3407 if (Loc.isInvalid())
3408 Loc = D.getBeginLoc();
3409
3410 Expr *BitWidth = static_cast<Expr*>(BW);
3411
3412 assert(isa<CXXRecordDecl>(CurContext));
3413 assert(!DS.isFriendSpecified());
3414
3415 bool isFunc = D.isDeclarationOfFunction();
3416 const ParsedAttr *MSPropertyAttr =
3418
3419 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
3420 // The Microsoft extension __interface only permits public member functions
3421 // and prohibits constructors, destructors, operators, non-public member
3422 // functions, static methods and data members.
3423 unsigned InvalidDecl;
3424 bool ShowDeclName = true;
3425 if (!isFunc &&
3426 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
3427 InvalidDecl = 0;
3428 else if (!isFunc)
3429 InvalidDecl = 1;
3430 else if (AS != AS_public)
3431 InvalidDecl = 2;
3433 InvalidDecl = 3;
3434 else switch (Name.getNameKind()) {
3436 InvalidDecl = 4;
3437 ShowDeclName = false;
3438 break;
3439
3441 InvalidDecl = 5;
3442 ShowDeclName = false;
3443 break;
3444
3447 InvalidDecl = 6;
3448 break;
3449
3450 default:
3451 InvalidDecl = 0;
3452 break;
3453 }
3454
3455 if (InvalidDecl) {
3456 if (ShowDeclName)
3457 Diag(Loc, diag::err_invalid_member_in_interface)
3458 << (InvalidDecl-1) << Name;
3459 else
3460 Diag(Loc, diag::err_invalid_member_in_interface)
3461 << (InvalidDecl-1) << "";
3462 return nullptr;
3463 }
3464 }
3465
3466 // C++ 9.2p6: A member shall not be declared to have automatic storage
3467 // duration (auto, register) or with the extern storage-class-specifier.
3468 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3469 // data members and cannot be applied to names declared const or static,
3470 // and cannot be applied to reference members.
3471 switch (DS.getStorageClassSpec()) {
3475 break;
3477 if (isFunc) {
3478 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3479
3480 // FIXME: It would be nicer if the keyword was ignored only for this
3481 // declarator. Otherwise we could get follow-up errors.
3483 }
3484 break;
3485 default:
3487 diag::err_storageclass_invalid_for_member);
3489 break;
3490 }
3491
3492 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3494 !isFunc);
3495
3496 if (DS.hasConstexprSpecifier() && isInstField) {
3498 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3499 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3500 if (InitStyle == ICIS_NoInit) {
3501 B << 0 << 0;
3503 B << FixItHint::CreateRemoval(ConstexprLoc);
3504 else {
3505 B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3507 const char *PrevSpec;
3508 unsigned DiagID;
3509 bool Failed = D.getMutableDeclSpec().SetTypeQual(
3510 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3511 (void)Failed;
3512 assert(!Failed && "Making a constexpr member const shouldn't fail");
3513 }
3514 } else {
3515 B << 1;
3516 const char *PrevSpec;
3517 unsigned DiagID;
3519 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3522 "This is the only DeclSpec that should fail to be applied");
3523 B << 1;
3524 } else {
3525 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3526 isInstField = false;
3527 }
3528 }
3529 }
3530
3532 if (isInstField) {
3533 CXXScopeSpec &SS = D.getCXXScopeSpec();
3534
3535 // Data members must have identifiers for names.
3536 if (!Name.isIdentifier()) {
3537 Diag(Loc, diag::err_bad_variable_name)
3538 << Name;
3539 return nullptr;
3540 }
3541
3542 IdentifierInfo *II = Name.getAsIdentifierInfo();
3543
3544 // Member field could not be with "template" keyword.
3545 // So TemplateParameterLists should be empty in this case.
3546 if (TemplateParameterLists.size()) {
3547 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
3548 if (TemplateParams->size()) {
3549 // There is no such thing as a member field template.
3550 Diag(D.getIdentifierLoc(), diag::err_template_member)
3551 << II
3552 << SourceRange(TemplateParams->getTemplateLoc(),
3553 TemplateParams->getRAngleLoc());
3554 } else {
3555 // There is an extraneous 'template<>' for this member.
3556 Diag(TemplateParams->getTemplateLoc(),
3557 diag::err_template_member_noparams)
3558 << II
3559 << SourceRange(TemplateParams->getTemplateLoc(),
3560 TemplateParams->getRAngleLoc());
3561 }
3562 return nullptr;
3563 }
3564
3566 Diag(D.getIdentifierLoc(), diag::err_member_with_template_arguments)
3567 << II
3571 D.SetIdentifier(II, Loc);
3572 }
3573
3574 if (SS.isSet() && !SS.isInvalid()) {
3575 // The user provided a superfluous scope specifier inside a class
3576 // definition:
3577 //
3578 // class X {
3579 // int X::member;
3580 // };
3581 if (DeclContext *DC = computeDeclContext(SS, false)) {
3582 TemplateIdAnnotation *TemplateId =
3584 ? D.getName().TemplateId
3585 : nullptr;
3587 TemplateId,
3588 /*IsMemberSpecialization=*/false);
3589 } else {
3590 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3591 << Name << SS.getRange();
3592 }
3593 SS.clear();
3594 }
3595
3596 if (MSPropertyAttr) {
3597 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3598 BitWidth, InitStyle, AS, *MSPropertyAttr);
3599 if (!Member)
3600 return nullptr;
3601 isInstField = false;
3602 } else {
3603 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3604 BitWidth, InitStyle, AS);
3605 if (!Member)
3606 return nullptr;
3607 }
3608
3609 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3610 } else {
3611 Member = HandleDeclarator(S, D, TemplateParameterLists);
3612 if (!Member)
3613 return nullptr;
3614
3615 // Non-instance-fields can't have a bitfield.
3616 if (BitWidth) {
3617 if (Member->isInvalidDecl()) {
3618 // don't emit another diagnostic.
3619 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3620 // C++ 9.6p3: A bit-field shall not be a static member.
3621 // "static member 'A' cannot be a bit-field"
3622 Diag(Loc, diag::err_static_not_bitfield)
3623 << Name << BitWidth->getSourceRange();
3624 } else if (isa<TypedefDecl>(Member)) {
3625 // "typedef member 'x' cannot be a bit-field"
3626 Diag(Loc, diag::err_typedef_not_bitfield)
3627 << Name << BitWidth->getSourceRange();
3628 } else {
3629 // A function typedef ("typedef int f(); f a;").
3630 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3631 Diag(Loc, diag::err_not_integral_type_bitfield)
3632 << Name << cast<ValueDecl>(Member)->getType()
3633 << BitWidth->getSourceRange();
3634 }
3635
3636 BitWidth = nullptr;
3637 Member->setInvalidDecl();
3638 }
3639
3640 NamedDecl *NonTemplateMember = Member;
3641 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3642 NonTemplateMember = FunTmpl->getTemplatedDecl();
3643 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3644 NonTemplateMember = VarTmpl->getTemplatedDecl();
3645
3646 Member->setAccess(AS);
3647
3648 // If we have declared a member function template or static data member
3649 // template, set the access of the templated declaration as well.
3650 if (NonTemplateMember != Member)
3651 NonTemplateMember->setAccess(AS);
3652
3653 // C++ [temp.deduct.guide]p3:
3654 // A deduction guide [...] for a member class template [shall be
3655 // declared] with the same access [as the template].
3656 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3657 auto *TD = DG->getDeducedTemplate();
3658 // Access specifiers are only meaningful if both the template and the
3659 // deduction guide are from the same scope.
3660 if (AS != TD->getAccess() &&
3661 TD->getDeclContext()->getRedeclContext()->Equals(
3662 DG->getDeclContext()->getRedeclContext())) {
3663 Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3664 Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3665 << TD->getAccess();
3666 const AccessSpecDecl *LastAccessSpec = nullptr;
3667 for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3668 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3669 LastAccessSpec = AccessSpec;
3670 }
3671 assert(LastAccessSpec && "differing access with no access specifier");
3672 Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3673 << AS;
3674 }
3675 }
3676 }
3677
3678 if (VS.isOverrideSpecified())
3679 Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc()));
3680 if (VS.isFinalSpecified())
3681 Member->addAttr(FinalAttr::Create(Context, VS.getFinalLoc(),
3683 ? FinalAttr::Keyword_sealed
3684 : FinalAttr::Keyword_final));
3685
3686 if (VS.getLastLocation().isValid()) {
3687 // Update the end location of a method that has a virt-specifiers.
3688 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3689 MD->setRangeEnd(VS.getLastLocation());
3690 }
3691
3693
3694 assert((Name || isInstField) && "No identifier for non-field ?");
3695
3696 if (isInstField) {
3697 FieldDecl *FD = cast<FieldDecl>(Member);
3698 FieldCollector->Add(FD);
3699
3700 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3701 // Remember all explicit private FieldDecls that have a name, no side
3702 // effects and are not part of a dependent type declaration.
3703
3704 auto DeclHasUnusedAttr = [](const QualType &T) {
3705 if (const TagDecl *TD = T->getAsTagDecl())
3706 return TD->hasAttr<UnusedAttr>();
3707 if (const TypedefType *TDT = T->getAs<TypedefType>())
3708 return TDT->getDecl()->hasAttr<UnusedAttr>();
3709 return false;
3710 };
3711
3712 if (!FD->isImplicit() && FD->getDeclName() &&
3713 FD->getAccess() == AS_private &&
3714 !FD->hasAttr<UnusedAttr>() &&
3715 !FD->getParent()->isDependentContext() &&
3716 !DeclHasUnusedAttr(FD->getType()) &&
3718 UnusedPrivateFields.insert(FD);
3719 }
3720 }
3721
3722 return Member;
3723}
3724
3725namespace {
3726 class UninitializedFieldVisitor
3727 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3728 Sema &S;
3729 // List of Decls to generate a warning on. Also remove Decls that become
3730 // initialized.
3731 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3732 // List of base classes of the record. Classes are removed after their
3733 // initializers.
3734 llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3735 // Vector of decls to be removed from the Decl set prior to visiting the
3736 // nodes. These Decls may have been initialized in the prior initializer.
3738 // If non-null, add a note to the warning pointing back to the constructor.
3739 const CXXConstructorDecl *Constructor;
3740 // Variables to hold state when processing an initializer list. When
3741 // InitList is true, special case initialization of FieldDecls matching
3742 // InitListFieldDecl.
3743 bool InitList;
3744 FieldDecl *InitListFieldDecl;
3745 llvm::SmallVector<unsigned, 4> InitFieldIndex;
3746
3747 public:
3749 UninitializedFieldVisitor(Sema &S,
3750 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3751 llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3752 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3753 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3754
3755 // Returns true if the use of ME is not an uninitialized use.
3756 bool IsInitListMemberExprInitialized(MemberExpr *ME,
3757 bool CheckReferenceOnly) {
3759 bool ReferenceField = false;
3760 while (ME) {
3761 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3762 if (!FD)
3763 return false;
3764 Fields.push_back(FD);
3765 if (FD->getType()->isReferenceType())
3766 ReferenceField = true;
3767 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3768 }
3769
3770 // Binding a reference to an uninitialized field is not an
3771 // uninitialized use.
3772 if (CheckReferenceOnly && !ReferenceField)
3773 return true;
3774
3775 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3776 // Discard the first field since it is the field decl that is being
3777 // initialized.
3778 for (const FieldDecl *FD : llvm::drop_begin(llvm::reverse(Fields)))
3779 UsedFieldIndex.push_back(FD->getFieldIndex());
3780
3781 for (auto UsedIter = UsedFieldIndex.begin(),
3782 UsedEnd = UsedFieldIndex.end(),
3783 OrigIter = InitFieldIndex.begin(),
3784 OrigEnd = InitFieldIndex.end();
3785 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3786 if (*UsedIter < *OrigIter)
3787 return true;
3788 if (*UsedIter > *OrigIter)
3789 break;
3790 }
3791
3792 return false;
3793 }
3794
3795 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3796 bool AddressOf) {
3797 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3798 return;
3799
3800 // FieldME is the inner-most MemberExpr that is not an anonymous struct
3801 // or union.
3802 MemberExpr *FieldME = ME;
3803
3804 bool AllPODFields = FieldME->getType().isPODType(S.Context);
3805
3806 Expr *Base = ME;
3807 while (MemberExpr *SubME =
3808 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3809
3810 if (isa<VarDecl>(SubME->getMemberDecl()))
3811 return;
3812
3813 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3814 if (!FD->isAnonymousStructOrUnion())
3815 FieldME = SubME;
3816
3817 if (!FieldME->getType().isPODType(S.Context))
3818 AllPODFields = false;
3819
3820 Base = SubME->getBase();
3821 }
3822
3823 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) {
3824 Visit(Base);
3825 return;
3826 }
3827
3828 if (AddressOf && AllPODFields)
3829 return;
3830
3831 ValueDecl* FoundVD = FieldME->getMemberDecl();
3832
3833 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3834 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3835 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3836 }
3837
3838 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3839 QualType T = BaseCast->getType();
3840 if (T->isPointerType() &&
3841 BaseClasses.count(T->getPointeeType())) {
3842 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3843 << T->getPointeeType() << FoundVD;
3844 }
3845 }
3846 }
3847
3848 if (!Decls.count(FoundVD))
3849 return;
3850
3851 const bool IsReference = FoundVD->getType()->isReferenceType();
3852
3853 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3854 // Special checking for initializer lists.
3855 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3856 return;
3857 }
3858 } else {
3859 // Prevent double warnings on use of unbounded references.
3860 if (CheckReferenceOnly && !IsReference)
3861 return;
3862 }
3863
3864 unsigned diag = IsReference
3865 ? diag::warn_reference_field_is_uninit
3866 : diag::warn_field_is_uninit;
3867 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3868 if (Constructor)
3869 S.Diag(Constructor->getLocation(),
3870 diag::note_uninit_in_this_constructor)
3871 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3872
3873 }
3874
3875 void HandleValue(Expr *E, bool AddressOf) {
3876 E = E->IgnoreParens();
3877
3878 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3879 HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3880 AddressOf /*AddressOf*/);
3881 return;
3882 }
3883
3884 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3885 Visit(CO->getCond());
3886 HandleValue(CO->getTrueExpr(), AddressOf);
3887 HandleValue(CO->getFalseExpr(), AddressOf);
3888 return;
3889 }
3890
3891 if (BinaryConditionalOperator *BCO =
3892 dyn_cast<BinaryConditionalOperator>(E)) {
3893 Visit(BCO->getCond());
3894 HandleValue(BCO->getFalseExpr(), AddressOf);
3895 return;
3896 }
3897
3898 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3899 HandleValue(OVE->getSourceExpr(), AddressOf);
3900 return;
3901 }
3902
3903 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3904 switch (BO->getOpcode()) {
3905 default:
3906 break;
3907 case(BO_PtrMemD):
3908 case(BO_PtrMemI):
3909 HandleValue(BO->getLHS(), AddressOf);
3910 Visit(BO->getRHS());
3911 return;
3912 case(BO_Comma):
3913 Visit(BO->getLHS());
3914 HandleValue(BO->getRHS(), AddressOf);
3915 return;
3916 }
3917 }
3918
3919 Visit(E);
3920 }
3921
3922 void CheckInitListExpr(InitListExpr *ILE) {
3923 InitFieldIndex.push_back(0);
3924 for (auto *Child : ILE->children()) {
3925 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3926 CheckInitListExpr(SubList);
3927 } else {
3928 Visit(Child);
3929 }
3930 ++InitFieldIndex.back();
3931 }
3932 InitFieldIndex.pop_back();
3933 }
3934
3935 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3936 FieldDecl *Field, const Type *BaseClass) {
3937 // Remove Decls that may have been initialized in the previous
3938 // initializer.
3939 for (ValueDecl* VD : DeclsToRemove)
3940 Decls.erase(VD);
3941 DeclsToRemove.clear();
3942
3943 Constructor = FieldConstructor;
3944 InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3945
3946 if (ILE && Field) {
3947 InitList = true;
3948 InitListFieldDecl = Field;
3949 InitFieldIndex.clear();
3950 CheckInitListExpr(ILE);
3951 } else {
3952 InitList = false;
3953 Visit(E);
3954 }
3955
3956 if (Field)
3957 Decls.erase(Field);
3958 if (BaseClass)
3959 BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3960 }
3961
3962 void VisitMemberExpr(MemberExpr *ME) {
3963 // All uses of unbounded reference fields will warn.
3964 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3965 }
3966
3967 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3968 if (E->getCastKind() == CK_LValueToRValue) {
3969 HandleValue(E->getSubExpr(), false /*AddressOf*/);
3970 return;
3971 }
3972
3973 Inherited::VisitImplicitCastExpr(E);
3974 }
3975
3976 void VisitCXXConstructExpr(CXXConstructExpr *E) {
3977 if (E->getConstructor()->isCopyConstructor()) {
3978 Expr *ArgExpr = E->getArg(0);
3979 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3980 if (ILE->getNumInits() == 1)
3981 ArgExpr = ILE->getInit(0);
3982 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3983 if (ICE->getCastKind() == CK_NoOp)
3984 ArgExpr = ICE->getSubExpr();
3985 HandleValue(ArgExpr, false /*AddressOf*/);
3986 return;
3987 }
3988 Inherited::VisitCXXConstructExpr(E);
3989 }
3990
3991 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3992 Expr *Callee = E->getCallee();
3993 if (isa<MemberExpr>(Callee)) {
3994 HandleValue(Callee, false /*AddressOf*/);
3995 for (auto *Arg : E->arguments())
3996 Visit(Arg);
3997 return;
3998 }
3999
4000 Inherited::VisitCXXMemberCallExpr(E);
4001 }
4002
4003 void VisitCallExpr(CallExpr *E) {
4004 // Treat std::move as a use.
4005 if (E->isCallToStdMove()) {
4006 HandleValue(E->getArg(0), /*AddressOf=*/false);
4007 return;
4008 }
4009
4010 Inherited::VisitCallExpr(E);
4011 }
4012
4013 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
4014 Expr *Callee = E->getCallee();
4015
4016 if (isa<UnresolvedLookupExpr>(Callee))
4017 return Inherited::VisitCXXOperatorCallExpr(E);
4018
4019 Visit(Callee);
4020 for (auto *Arg : E->arguments())
4021 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
4022 }
4023
4024 void VisitBinaryOperator(BinaryOperator *E) {
4025 // If a field assignment is detected, remove the field from the
4026 // uninitiailized field set.
4027 if (E->getOpcode() == BO_Assign)
4028 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
4029 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
4030 if (!FD->getType()->isReferenceType())
4031 DeclsToRemove.push_back(FD);
4032
4033 if (E->isCompoundAssignmentOp()) {
4034 HandleValue(E->getLHS(), false /*AddressOf*/);
4035 Visit(E->getRHS());
4036 return;
4037 }
4038
4039 Inherited::VisitBinaryOperator(E);
4040 }
4041
4042 void VisitUnaryOperator(UnaryOperator *E) {
4043 if (E->isIncrementDecrementOp()) {
4044 HandleValue(E->getSubExpr(), false /*AddressOf*/);
4045 return;
4046 }
4047 if (E->getOpcode() == UO_AddrOf) {
4048 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
4049 HandleValue(ME->getBase(), true /*AddressOf*/);
4050 return;
4051 }
4052 }
4053
4054 Inherited::VisitUnaryOperator(E);
4055 }
4056 };
4057
4058 // Diagnose value-uses of fields to initialize themselves, e.g.
4059 // foo(foo)
4060 // where foo is not also a parameter to the constructor.
4061 // Also diagnose across field uninitialized use such as
4062 // x(y), y(x)
4063 // TODO: implement -Wuninitialized and fold this into that framework.
4064 static void DiagnoseUninitializedFields(
4065 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
4066
4067 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
4068 Constructor->getLocation())) {
4069 return;
4070 }
4071
4072 if (Constructor->isInvalidDecl())
4073 return;
4074
4075 const CXXRecordDecl *RD = Constructor->getParent();
4076
4077 if (RD->isDependentContext())
4078 return;
4079
4080 // Holds fields that are uninitialized.
4081 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
4082
4083 // At the beginning, all fields are uninitialized.
4084 for (auto *I : RD->decls()) {
4085 if (auto *FD = dyn_cast<FieldDecl>(I)) {
4086 UninitializedFields.insert(FD);
4087 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
4088 UninitializedFields.insert(IFD->getAnonField());
4089 }
4090 }
4091
4092 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
4093 for (const auto &I : RD->bases())
4094 UninitializedBaseClasses.insert(I.getType().getCanonicalType());
4095
4096 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
4097 return;
4098
4099 UninitializedFieldVisitor UninitializedChecker(SemaRef,
4100 UninitializedFields,
4101 UninitializedBaseClasses);
4102
4103 for (const auto *FieldInit : Constructor->inits()) {
4104 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
4105 break;
4106
4107 Expr *InitExpr = FieldInit->getInit();
4108 if (!InitExpr)
4109 continue;
4110
4112 dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
4113 InitExpr = Default->getExpr();
4114 if (!InitExpr)
4115 continue;
4116 // In class initializers will point to the constructor.
4117 UninitializedChecker.CheckInitializer(InitExpr, Constructor,
4118 FieldInit->getAnyMember(),
4119 FieldInit->getBaseClass());
4120 } else {
4121 UninitializedChecker.CheckInitializer(InitExpr, nullptr,
4122 FieldInit->getAnyMember(),
4123 FieldInit->getBaseClass());
4124 }
4125 }
4126 }
4127} // namespace
4128
4129/// Enter a new C++ default initializer scope. After calling this, the
4130/// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
4131/// parsing or instantiating the initializer failed.
4133 // Create a synthetic function scope to represent the call to the constructor
4134 // that notionally surrounds a use of this initializer.
4136}
4137
4139 if (!D.isFunctionDeclarator())
4140 return;
4141 auto &FTI = D.getFunctionTypeInfo();
4142 if (!FTI.Params)
4143 return;
4144 for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params,
4145 FTI.NumParams)) {
4146 auto *ParamDecl = cast<NamedDecl>(Param.Param);
4147 if (ParamDecl->getDeclName())
4148 PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false);
4149 }
4150}
4151
4153 return ActOnRequiresClause(ConstraintExpr);
4154}
4155
4157 if (ConstraintExpr.isInvalid())
4158 return ExprError();
4159
4160 ConstraintExpr = CorrectDelayedTyposInExpr(ConstraintExpr);
4161 if (ConstraintExpr.isInvalid())
4162 return ExprError();
4163
4164 if (DiagnoseUnexpandedParameterPack(ConstraintExpr.get(),
4166 return ExprError();
4167
4168 return ConstraintExpr;
4169}
4170
4172 Expr *InitExpr,
4173 SourceLocation InitLoc) {
4174 InitializedEntity Entity =
4176 InitializationKind Kind =
4179 InitExpr->getBeginLoc(),
4180 InitExpr->getEndLoc())
4181 : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
4182 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
4183 return Seq.Perform(*this, Entity, Kind, InitExpr);
4184}
4185
4186/// This is invoked after parsing an in-class initializer for a
4187/// non-static C++ class member, and after instantiating an in-class initializer
4188/// in a class template. Such actions are deferred until the class is complete.
4190 SourceLocation InitLoc,
4191 Expr *InitExpr) {
4192 // Pop the notional constructor scope we created earlier.
4193 PopFunctionScopeInfo(nullptr, D);
4194
4195 FieldDecl *FD = dyn_cast<FieldDecl>(D);
4196 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
4197 "must set init style when field is created");
4198
4199 if (!InitExpr) {
4200 D->setInvalidDecl();
4201 if (FD)
4203 return;
4204 }
4205
4207 FD->setInvalidDecl();
4209 return;
4210 }
4211
4212 ExprResult Init = CorrectDelayedTyposInExpr(InitExpr, /*InitDecl=*/nullptr,
4213 /*RecoverUncorrectedTypos=*/true);
4214 assert(Init.isUsable() && "Init should at least have a RecoveryExpr");
4215 if (!FD->getType()->isDependentType() && !Init.get()->isTypeDependent()) {
4216 Init = ConvertMemberDefaultInitExpression(FD, Init.get(), InitLoc);
4217 // C++11 [class.base.init]p7:
4218 // The initialization of each base and member constitutes a
4219 // full-expression.
4220 if (!Init.isInvalid())
4221 Init = ActOnFinishFullExpr(Init.get(), /*DiscarededValue=*/false);
4222 if (Init.isInvalid()) {
4223 FD->setInvalidDecl();
4224 return;
4225 }
4226 }
4227
4228 FD->setInClassInitializer(Init.get());
4229}
4230
4231/// Find the direct and/or virtual base specifiers that
4232/// correspond to the given base type, for use in base initialization
4233/// within a constructor.
4235 CXXRecordDecl *ClassDecl,
4236 QualType BaseType,
4237 const CXXBaseSpecifier *&DirectBaseSpec,
4238 const CXXBaseSpecifier *&VirtualBaseSpec) {
4239 // First, check for a direct base class.
4240 DirectBaseSpec = nullptr;
4241 for (const auto &Base : ClassDecl->bases()) {
4242 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
4243 // We found a direct base of this type. That's what we're
4244 // initializing.
4245 DirectBaseSpec = &Base;
4246 break;
4247 }
4248 }
4249
4250 // Check for a virtual base class.
4251 // FIXME: We might be able to short-circuit this if we know in advance that
4252 // there are no virtual bases.
4253 VirtualBaseSpec = nullptr;
4254 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
4255 // We haven't found a base yet; search the class hierarchy for a
4256 // virtual base class.
4257 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
4258 /*DetectVirtual=*/false);
4259 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
4260 SemaRef.Context.getTypeDeclType(ClassDecl),
4261 BaseType, Paths)) {
4262 for (CXXBasePaths::paths_iterator Path = Paths.begin();
4263 Path != Paths.end(); ++Path) {
4264 if (Path->back().Base->isVirtual()) {
4265 VirtualBaseSpec = Path->back().Base;
4266 break;
4267 }
4268 }
4269 }
4270 }
4271
4272 return DirectBaseSpec || VirtualBaseSpec;
4273}
4274
4275/// Handle a C++ member initializer using braced-init-list syntax.
4278 Scope *S,
4279 CXXScopeSpec &SS,
4280 IdentifierInfo *MemberOrBase,
4281 ParsedType TemplateTypeTy,
4282 const DeclSpec &DS,
4283 SourceLocation IdLoc,
4284 Expr *InitList,
4285 SourceLocation EllipsisLoc) {
4286 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4287 DS, IdLoc, InitList,
4288 EllipsisLoc);
4289}
4290
4291/// Handle a C++ member initializer using parentheses syntax.
4294 Scope *S,
4295 CXXScopeSpec &SS,
4296 IdentifierInfo *MemberOrBase,
4297 ParsedType TemplateTypeTy,
4298 const DeclSpec &DS,
4299 SourceLocation IdLoc,
4300 SourceLocation LParenLoc,
4301 ArrayRef<Expr *> Args,
4302 SourceLocation RParenLoc,
4303 SourceLocation EllipsisLoc) {
4304 Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
4305 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4306 DS, IdLoc, List, EllipsisLoc);
4307}
4308
4309namespace {
4310
4311// Callback to only accept typo corrections that can be a valid C++ member
4312// initializer: either a non-static field member or a base class.
4313class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
4314public:
4315 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
4316 : ClassDecl(ClassDecl) {}
4317
4318 bool ValidateCandidate(const TypoCorrection &candidate) override {
4319 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
4320 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
4321 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
4322 return isa<TypeDecl>(ND);
4323 }
4324 return false;
4325 }
4326
4327 std::unique_ptr<CorrectionCandidateCallback> clone() override {
4328 return std::make_unique<MemInitializerValidatorCCC>(*this);
4329 }
4330
4331private:
4332 CXXRecordDecl *ClassDecl;
4333};
4334
4335}
4336
4338 RecordDecl *ClassDecl,
4339 const IdentifierInfo *Name) {
4340 DeclContextLookupResult Result = ClassDecl->lookup(Name);
4342 llvm::find_if(Result, [this](const NamedDecl *Elem) {
4343 return isa<FieldDecl, IndirectFieldDecl>(Elem) &&
4345 });
4346 // We did not find a placeholder variable
4347 if (Found == Result.end())
4348 return false;
4349 Diag(Loc, diag::err_using_placeholder_variable) << Name;
4350 for (DeclContextLookupResult::iterator It = Found; It != Result.end(); It++) {
4351 const NamedDecl *ND = *It;
4352 if (ND->getDeclContext() != ND->getDeclContext())
4353 break;
4354 if (isa<FieldDecl, IndirectFieldDecl>(ND) &&
4356 Diag(ND->getLocation(), diag::note_reference_placeholder) << ND;
4357 }
4358 return true;
4359}
4360
4361ValueDecl *
4363 const IdentifierInfo *MemberOrBase) {
4364 ValueDecl *ND = nullptr;
4365 for (auto *D : ClassDecl->lookup(MemberOrBase)) {
4366 if (isa<FieldDecl, IndirectFieldDecl>(D)) {
4367 bool IsPlaceholder = D->isPlaceholderVar(getLangOpts());
4368 if (ND) {
4369 if (IsPlaceholder && D->getDeclContext() == ND->getDeclContext())
4370 return nullptr;
4371 break;
4372 }
4373 if (!IsPlaceholder)
4374 return cast<ValueDecl>(D);
4375 ND = cast<ValueDecl>(D);
4376 }
4377 }
4378 return ND;
4379}
4380
4382 CXXScopeSpec &SS,
4383 ParsedType TemplateTypeTy,
4384 IdentifierInfo *MemberOrBase) {
4385 if (SS.getScopeRep() || TemplateTypeTy)
4386 return nullptr;
4387 return tryLookupUnambiguousFieldDecl(ClassDecl, MemberOrBase);
4388}
4389
4390/// Handle a C++ member initializer.
4393 Scope *S,
4394 CXXScopeSpec &SS,
4395 IdentifierInfo *MemberOrBase,
4396 ParsedType TemplateTypeTy,
4397 const DeclSpec &DS,
4398 SourceLocation IdLoc,
4399 Expr *Init,
4400 SourceLocation EllipsisLoc) {
4401 ExprResult Res = CorrectDelayedTyposInExpr(Init, /*InitDecl=*/nullptr,
4402 /*RecoverUncorrectedTypos=*/true);
4403 if (!Res.isUsable())
4404 return true;
4405 Init = Res.get();
4406
4407 if (!ConstructorD)
4408 return true;
4409
4410 AdjustDeclIfTemplate(ConstructorD);
4411
4412 CXXConstructorDecl *Constructor
4413 = dyn_cast<CXXConstructorDecl>(ConstructorD);
4414 if (!Constructor) {
4415 // The user wrote a constructor initializer on a function that is
4416 // not a C++ constructor. Ignore the error for now, because we may
4417 // have more member initializers coming; we'll diagnose it just
4418 // once in ActOnMemInitializers.
4419 return true;
4420 }
4421
4422 CXXRecordDecl *ClassDecl = Constructor->getParent();
4423
4424 // C++ [class.base.init]p2:
4425 // Names in a mem-initializer-id are looked up in the scope of the
4426 // constructor's class and, if not found in that scope, are looked
4427 // up in the scope containing the constructor's definition.
4428 // [Note: if the constructor's class contains a member with the
4429 // same name as a direct or virtual base class of the class, a
4430 // mem-initializer-id naming the member or base class and composed
4431 // of a single identifier refers to the class member. A
4432 // mem-initializer-id for the hidden base class may be specified
4433 // using a qualified name. ]
4434
4435 // Look for a member, first.
4437 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
4438 if (EllipsisLoc.isValid())
4439 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
4440 << MemberOrBase
4441 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4442
4443 return BuildMemberInitializer(Member, Init, IdLoc);
4444 }
4445 // It didn't name a member, so see if it names a class.
4446 QualType BaseType;
4447 TypeSourceInfo *TInfo = nullptr;
4448
4449 if (TemplateTypeTy) {
4450 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
4451 if (BaseType.isNull())
4452 return true;
4453 } else if (DS.getTypeSpecType() == TST_decltype) {
4454 BaseType = BuildDecltypeType(DS.getRepAsExpr());
4455 } else if (DS.getTypeSpecType() == TST_decltype_auto) {
4456 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
4457 return true;
4458 } else if (DS.getTypeSpecType() == TST_typename_pack_indexing) {
4459 BaseType =
4461 DS.getBeginLoc(), DS.getEllipsisLoc());
4462 } else {
4463 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
4464 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
4465
4466 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
4467 if (!TyD) {
4468 if (R.isAmbiguous()) return true;
4469
4470 // We don't want access-control diagnostics here.
4472
4473 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
4474 bool NotUnknownSpecialization = false;
4475 DeclContext *DC = computeDeclContext(SS, false);
4476 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
4477 NotUnknownSpecialization = !Record->hasAnyDependentBases();
4478
4479 if (!NotUnknownSpecialization) {
4480 // When the scope specifier can refer to a member of an unknown
4481 // specialization, we take it as a type name.
4482 BaseType = CheckTypenameType(
4484 SS.getWithLocInContext(Context), *MemberOrBase, IdLoc);
4485 if (BaseType.isNull())
4486 return true;
4487
4488 TInfo = Context.CreateTypeSourceInfo(BaseType);
4491 if (!TL.isNull()) {
4492 TL.setNameLoc(IdLoc);
4495 }
4496
4497 R.clear();
4498 R.setLookupName(MemberOrBase);
4499 }
4500 }
4501
4502 if (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus20) {
4503 if (auto UnqualifiedBase = R.getAsSingle<ClassTemplateDecl>()) {
4504 auto *TempSpec = cast<TemplateSpecializationType>(
4505 UnqualifiedBase->getInjectedClassNameSpecialization());
4506 TemplateName TN = TempSpec->getTemplateName();
4507 for (auto const &Base : ClassDecl->bases()) {
4508 auto BaseTemplate =
4509 Base.getType()->getAs<TemplateSpecializationType>();
4510 if (BaseTemplate && Context.hasSameTemplateName(
4511 BaseTemplate->getTemplateName(), TN)) {
4512 Diag(IdLoc, diag::ext_unqualified_base_class)
4513 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4514 BaseType = Base.getType();
4515 break;
4516 }
4517 }
4518 }
4519 }
4520
4521 // If no results were found, try to correct typos.
4522 TypoCorrection Corr;
4523 MemInitializerValidatorCCC CCC(ClassDecl);
4524 if (R.empty() && BaseType.isNull() &&
4525 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
4526 CCC, CTK_ErrorRecovery, ClassDecl))) {
4528 // We have found a non-static data member with a similar
4529 // name to what was typed; complain and initialize that
4530 // member.
4531 diagnoseTypo(Corr,
4532 PDiag(diag::err_mem_init_not_member_or_class_suggest)
4533 << MemberOrBase << true);
4534 return BuildMemberInitializer(Member, Init, IdLoc);
4535 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
4536 const CXXBaseSpecifier *DirectBaseSpec;
4537 const CXXBaseSpecifier *VirtualBaseSpec;
4538 if (FindBaseInitializer(*this, ClassDecl,
4540 DirectBaseSpec, VirtualBaseSpec)) {
4541 // We have found a direct or virtual base class with a
4542 // similar name to what was typed; complain and initialize
4543 // that base class.
4544 diagnoseTypo(Corr,
4545 PDiag(diag::err_mem_init_not_member_or_class_suggest)
4546 << MemberOrBase << false,
4547 PDiag() /*Suppress note, we provide our own.*/);
4548
4549 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
4550 : VirtualBaseSpec;
4551 Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
4552 << BaseSpec->getType() << BaseSpec->getSourceRange();
4553
4554 TyD = Type;
4555 }
4556 }
4557 }
4558
4559 if (!TyD && BaseType.isNull()) {
4560 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
4561 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4562 return true;
4563 }
4564 }
4565
4566 if (BaseType.isNull()) {
4569 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
4570 TInfo = Context.CreateTypeSourceInfo(BaseType);
4572 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
4575 }
4576 }
4577
4578 if (!TInfo)
4579 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
4580
4581 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
4582}
4583
4586 SourceLocation IdLoc) {
4587 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
4588 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
4589 assert((DirectMember || IndirectMember) &&
4590 "Member must be a FieldDecl or IndirectFieldDecl");
4591
4593 return true;
4594
4595 if (Member->isInvalidDecl())
4596 return true;
4597
4598 MultiExprArg Args;
4599 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4600 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4601 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4602 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4603 } else {
4604 // Template instantiation doesn't reconstruct ParenListExprs for us.
4605 Args = Init;
4606 }
4607
4608 SourceRange InitRange = Init->getSourceRange();
4609
4610 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4611 // Can't check initialization for a member of dependent type or when
4612 // any of the arguments are type-dependent expressions.
4614 } else {
4615 bool InitList = false;
4616 if (isa<InitListExpr>(Init)) {
4617 InitList = true;
4618 Args = Init;
4619 }
4620
4621 // Initialize the member.
4622 InitializedEntity MemberEntity =
4623 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4624 : InitializedEntity::InitializeMember(IndirectMember,
4625 nullptr);
4626 InitializationKind Kind =
4628 IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4629 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4630 InitRange.getEnd());
4631
4632 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4633 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4634 nullptr);
4635 if (!MemberInit.isInvalid()) {
4636 // C++11 [class.base.init]p7:
4637 // The initialization of each base and member constitutes a
4638 // full-expression.
4639 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
4640 /*DiscardedValue*/ false);
4641 }
4642
4643 if (MemberInit.isInvalid()) {
4644 // Args were sensible expressions but we couldn't initialize the member
4645 // from them. Preserve them in a RecoveryExpr instead.
4646 Init = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,
4647 Member->getType())
4648 .get();
4649 if (!Init)
4650 return true;
4651 } else {
4652 Init = MemberInit.get();
4653 }
4654 }
4655
4656 if (DirectMember) {
4657 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4658 InitRange.getBegin(), Init,
4659 InitRange.getEnd());
4660 } else {
4661 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4662 InitRange.getBegin(), Init,
4663 InitRange.getEnd());
4664 }
4665}
4666
4669 CXXRecordDecl *ClassDecl) {
4670 SourceLocation NameLoc = TInfo->getTypeLoc().getSourceRange().getBegin();
4671 if (!LangOpts.CPlusPlus11)
4672 return Diag(NameLoc, diag::err_delegating_ctor)
4673 << TInfo->getTypeLoc().getSourceRange();
4674 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4675
4676 bool InitList = true;
4677 MultiExprArg Args = Init;
4678 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4679 InitList = false;
4680 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4681 }
4682
4683 SourceRange InitRange = Init->getSourceRange();
4684 // Initialize the object.
4686 QualType(ClassDecl->getTypeForDecl(), 0));
4687 InitializationKind Kind =
4689 NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4690 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4691 InitRange.getEnd());
4692 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4693 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4694 Args, nullptr);
4695 if (!DelegationInit.isInvalid()) {
4696 assert((DelegationInit.get()->containsErrors() ||
4697 cast<CXXConstructExpr>(DelegationInit.get())->getConstructor()) &&
4698 "Delegating constructor with no target?");
4699
4700 // C++11 [class.base.init]p7:
4701 // The initialization of each base and member constitutes a
4702 // full-expression.
4703 DelegationInit = ActOnFinishFullExpr(
4704 DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
4705 }
4706
4707 if (DelegationInit.isInvalid()) {
4708 DelegationInit =
4709 CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,
4710 QualType(ClassDecl->getTypeForDecl(), 0));
4711 if (DelegationInit.isInvalid())
4712 return true;
4713 } else {
4714 // If we are in a dependent context, template instantiation will
4715 // perform this type-checking again. Just save the arguments that we
4716 // received in a ParenListExpr.
4717 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4718 // of the information that we have about the base
4719 // initializer. However, deconstructing the ASTs is a dicey process,
4720 // and this approach is far more likely to get the corner cases right.
4722 DelegationInit = Init;
4723 }
4724
4725 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4726 DelegationInit.getAs<Expr>(),
4727 InitRange.getEnd());
4728}
4729
4732 Expr *Init, CXXRecordDecl *ClassDecl,
4733 SourceLocation EllipsisLoc) {
4734 SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getBeginLoc();
4735
4736 if (!BaseType->isDependentType() && !BaseType->isRecordType())
4737 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4738 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
4739
4740 // C++ [class.base.init]p2:
4741 // [...] Unless the mem-initializer-id names a nonstatic data
4742 // member of the constructor's class or a direct or virtual base
4743 // of that class, the mem-initializer is ill-formed. A
4744 // mem-initializer-list can initialize a base class using any
4745 // name that denotes that base class type.
4746
4747 // We can store the initializers in "as-written" form and delay analysis until
4748 // instantiation if the constructor is dependent. But not for dependent
4749 // (broken) code in a non-template! SetCtorInitializers does not expect this.
4750 bool Dependent = CurContext->isDependentContext() &&
4751 (BaseType->isDependentType() || Init->isTypeDependent());
4752
4753 SourceRange InitRange = Init->getSourceRange();
4754 if (EllipsisLoc.isValid()) {
4755 // This is a pack expansion.
4756 if (!BaseType->containsUnexpandedParameterPack()) {
4757 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4758 << SourceRange(BaseLoc, InitRange.getEnd());
4759
4760 EllipsisLoc = SourceLocation();
4761 }
4762 } else {
4763 // Check for any unexpanded parameter packs.
4764 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4765 return true;
4766
4768 return true;
4769 }
4770
4771 // Check for direct and virtual base classes.
4772 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4773 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4774 if (!Dependent) {
4776 BaseType))
4777 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4778
4779 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4780 VirtualBaseSpec);
4781
4782 // C++ [base.class.init]p2:
4783 // Unless the mem-initializer-id names a nonstatic data member of the
4784 // constructor's class or a direct or virtual base of that class, the
4785 // mem-initializer is ill-formed.
4786 if (!DirectBaseSpec && !VirtualBaseSpec) {
4787 // If the class has any dependent bases, then it's possible that
4788 // one of those types will resolve to the same type as
4789 // BaseType. Therefore, just treat this as a dependent base
4790 // class initialization. FIXME: Should we try to check the
4791 // initialization anyway? It seems odd.
4792 if (ClassDecl->hasAnyDependentBases())
4793 Dependent = true;
4794 else
4795 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4796 << BaseType << Context.getTypeDeclType(ClassDecl)
4797 << BaseTInfo->getTypeLoc().getSourceRange();
4798 }
4799 }
4800
4801 if (Dependent) {
4803
4804 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4805 /*IsVirtual=*/false,
4806 InitRange.getBegin(), Init,
4807 InitRange.getEnd(), EllipsisLoc);
4808 }
4809
4810 // C++ [base.class.init]p2:
4811 // If a mem-initializer-id is ambiguous because it designates both
4812 // a direct non-virtual base class and an inherited virtual base
4813 // class, the mem-initializer is ill-formed.
4814 if (DirectBaseSpec && VirtualBaseSpec)
4815 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4816 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4817
4818 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4819 if (!BaseSpec)
4820 BaseSpec = VirtualBaseSpec;
4821
4822 // Initialize the base.
4823 bool InitList = true;
4824 MultiExprArg Args = Init;
4825 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4826 InitList = false;
4827 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4828 }
4829
4830 InitializedEntity BaseEntity =
4831 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4832 InitializationKind Kind =
4833 InitList ? InitializationKind::CreateDirectList(BaseLoc)
4834 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4835 InitRange.getEnd());
4836 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4837 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4838 if (!BaseInit.isInvalid()) {
4839 // C++11 [class.base.init]p7:
4840 // The initialization of each base and member constitutes a
4841 // full-expression.
4842 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
4843 /*DiscardedValue*/ false);
4844 }
4845
4846 if (BaseInit.isInvalid()) {
4847 BaseInit = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(),
4848 Args, BaseType);
4849 if (BaseInit.isInvalid())
4850 return true;
4851 } else {
4852 // If we are in a dependent context, template instantiation will
4853 // perform this type-checking again. Just save the arguments that we
4854 // received in a ParenListExpr.
4855 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4856 // of the information that we have about the base
4857 // initializer. However, deconstructing the ASTs is a dicey process,
4858 // and this approach is far more likely to get the corner cases right.
4860 BaseInit = Init;
4861 }
4862
4863 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4864 BaseSpec->isVirtual(),
4865 InitRange.getBegin(),
4866 BaseInit.getAs<Expr>(),
4867 InitRange.getEnd(), EllipsisLoc);
4868}
4869
4870// Create a static_cast<T&&>(expr).
4872 QualType TargetType =
4873 SemaRef.BuildReferenceType(E->getType(), /*SpelledAsLValue*/ false,
4875 SourceLocation ExprLoc = E->getBeginLoc();
4877 TargetType, ExprLoc);
4878
4879 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4880 SourceRange(ExprLoc, ExprLoc),
4881 E->getSourceRange()).get();
4882}
4883
4884/// ImplicitInitializerKind - How an implicit base or member initializer should
4885/// initialize its base or member.
4892
4893static bool
4895 ImplicitInitializerKind ImplicitInitKind,
4896 CXXBaseSpecifier *BaseSpec,
4897 bool IsInheritedVirtualBase,
4898 CXXCtorInitializer *&CXXBaseInit) {
4899 InitializedEntity InitEntity
4901 IsInheritedVirtualBase);
4902
4903 ExprResult BaseInit;
4904
4905 switch (ImplicitInitKind) {
4906 case IIK_Inherit:
4907 case IIK_Default: {
4908 InitializationKind InitKind
4909 = InitializationKind::CreateDefault(Constructor->getLocation());
4910 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, std::nullopt);
4911 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, std::nullopt);
4912 break;
4913 }
4914
4915 case IIK_Move:
4916 case IIK_Copy: {
4917 bool Moving = ImplicitInitKind == IIK_Move;
4918 ParmVarDecl *Param = Constructor->getParamDecl(0);
4919 QualType ParamType = Param->getType().getNonReferenceType();
4920
4921 Expr *CopyCtorArg =
4923 SourceLocation(), Param, false,
4924 Constructor->getLocation(), ParamType,
4925 VK_LValue, nullptr);
4926
4927 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4928
4929 // Cast to the base class to avoid ambiguities.
4930 QualType ArgTy =
4932 ParamType.getQualifiers());
4933
4934 if (Moving) {
4935 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4936 }
4937
4938 CXXCastPath BasePath;
4939 BasePath.push_back(BaseSpec);
4940 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4941 CK_UncheckedDerivedToBase,
4942 Moving ? VK_XValue : VK_LValue,
4943 &BasePath).get();
4944
4945 InitializationKind InitKind
4946 = InitializationKind::CreateDirect(Constructor->getLocation(),
4948 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4949 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4950 break;
4951 }
4952 }
4953
4954 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4955 if (BaseInit.isInvalid())
4956 return true;
4957
4958 CXXBaseInit =
4961 SourceLocation()),
4962 BaseSpec->isVirtual(),
4964 BaseInit.getAs<Expr>(),
4966 SourceLocation());
4967
4968 return false;
4969}
4970
4971static bool RefersToRValueRef(Expr *MemRef) {
4972 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4973 return Referenced->getType()->isRValueReferenceType();
4974}
4975
4976static bool
4978 ImplicitInitializerKind ImplicitInitKind,
4980 CXXCtorInitializer *&CXXMemberInit) {
4981 if (Field->isInvalidDecl())
4982 return true;
4983
4984 SourceLocation Loc = Constructor->getLocation();
4985
4986 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4987 bool Moving = ImplicitInitKind == IIK_Move;
4988 ParmVarDecl *Param = Constructor->getParamDecl(0);
4989 QualType ParamType = Param->getType().getNonReferenceType();
4990
4991 // Suppress copying zero-width bitfields.
4992 if (Field->isZeroLengthBitField(SemaRef.Context))
4993 return false;
4994
4995 Expr *MemberExprBase =
4997 SourceLocation(), Param, false,
4998 Loc, ParamType, VK_LValue, nullptr);
4999
5000 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
5001
5002 if (Moving) {
5003 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
5004 }
5005
5006 // Build a reference to this field within the parameter.
5007 CXXScopeSpec SS;
5008 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
5010 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
5011 : cast<ValueDecl>(Field), AS_public);
5012 MemberLookup.resolveKind();
5013 ExprResult CtorArg
5014 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
5015 ParamType, Loc,
5016 /*IsArrow=*/false,
5017 SS,
5018 /*TemplateKWLoc=*/SourceLocation(),
5019 /*FirstQualifierInScope=*/nullptr,
5020 MemberLookup,
5021 /*TemplateArgs=*/nullptr,
5022 /*S*/nullptr);
5023 if (CtorArg.isInvalid())
5024 return true;
5025
5026 // C++11 [class.copy]p15:
5027 // - if a member m has rvalue reference type T&&, it is direct-initialized
5028 // with static_cast<T&&>(x.m);
5029 if (RefersToRValueRef(CtorArg.get())) {
5030 CtorArg = CastForMoving(SemaRef, CtorArg.get());
5031 }
5032
5033 InitializedEntity Entity =
5035 /*Implicit*/ true)
5036 : InitializedEntity::InitializeMember(Field, nullptr,
5037 /*Implicit*/ true);
5038
5039 // Direct-initialize to use the copy constructor.
5040 InitializationKind InitKind =
5042
5043 Expr *CtorArgE = CtorArg.getAs<Expr>();
5044 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
5045 ExprResult MemberInit =
5046 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
5047 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
5048 if (MemberInit.isInvalid())
5049 return true;
5050
5051 if (Indirect)
5052 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
5053 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
5054 else
5055 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
5056 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
5057 return false;
5058 }
5059
5060 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
5061 "Unhandled implicit init kind!");
5062
5063 QualType FieldBaseElementType =
5064 SemaRef.Context.getBaseElementType(Field->getType());
5065
5066 if (FieldBaseElementType->isRecordType()) {
5067 InitializedEntity InitEntity =
5069 /*Implicit*/ true)
5070 : InitializedEntity::InitializeMember(Field, nullptr,
5071 /*Implicit*/ true);
5072 InitializationKind InitKind =
5074
5075 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, std::nullopt);
5076 ExprResult MemberInit =
5077 InitSeq.Perform(SemaRef, InitEntity, InitKind, std::nullopt);
5078
5079 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
5080 if (MemberInit.isInvalid())
5081 return true;
5082
5083 if (Indirect)
5084 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5085 Indirect, Loc,
5086 Loc,
5087 MemberInit.get(),
5088 Loc);
5089 else
5090 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5091 Field, Loc, Loc,
5092 MemberInit.get(),
5093 Loc);
5094 return false;
5095 }
5096
5097 if (!Field->getParent()->isUnion()) {
5098 if (FieldBaseElementType->isReferenceType()) {
5099 SemaRef.Diag(Constructor->getLocation(),
5100 diag::err_uninitialized_member_in_ctor)
5101 << (int)Constructor->isImplicit()
5102 << SemaRef.Context.getTagDeclType(Constructor->getParent())
5103 << 0 << Field->getDeclName();
5104 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
5105 return true;
5106 }
5107
5108 if (FieldBaseElementType.isConstQualified()) {
5109 SemaRef.Diag(Constructor->getLocation(),
5110 diag::err_uninitialized_member_in_ctor)
5111 << (int)Constructor->isImplicit()
5112 << SemaRef.Context.getTagDeclType(Constructor->getParent())
5113 << 1 << Field->getDeclName();
5114 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
5115 return true;
5116 }
5117 }
5118
5119 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
5120 // ARC and Weak:
5121 // Default-initialize Objective-C pointers to NULL.
5122 CXXMemberInit
5124 Loc, Loc,
5125 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
5126 Loc);
5127 return false;
5128 }
5129
5130 // Nothing to initialize.
5131 CXXMemberInit = nullptr;
5132 return false;
5133}
5134
5135namespace {
5136struct BaseAndFieldInfo {
5137 Sema &S;
5138 CXXConstructorDecl *Ctor;
5139 bool AnyErrorsInInits;
5141 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
5143 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
5144
5145 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
5146 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
5147 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
5148 if (Ctor->getInheritedConstructor())
5149 IIK = IIK_Inherit;
5150 else if (Generated && Ctor->isCopyConstructor())
5151 IIK = IIK_Copy;
5152 else if (Generated && Ctor->isMoveConstructor())
5153 IIK = IIK_Move;
5154 else
5155 IIK = IIK_Default;
5156 }
5157
5158 bool isImplicitCopyOrMove() const {
5159 switch (IIK) {
5160 case IIK_Copy:
5161 case IIK_Move:
5162 return true;
5163
5164 case IIK_Default:
5165 case IIK_Inherit:
5166 return false;
5167 }
5168
5169 llvm_unreachable("Invalid ImplicitInitializerKind!");
5170 }
5171
5172 bool addFieldInitializer(CXXCtorInitializer *Init) {
5173 AllToInit.push_back(Init);
5174
5175 // Check whether this initializer makes the field "used".
5176 if (Init->getInit()->HasSideEffects(S.Context))
5177 S.UnusedPrivateFields.remove(Init->getAnyMember());
5178
5179 return false;
5180 }
5181
5182 bool isInactiveUnionMember(FieldDecl *Field) {
5183 RecordDecl *Record = Field->getParent();
5184 if (!Record->isUnion())
5185 return false;
5186
5187 if (FieldDecl *Active =
5188 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
5189 return Active != Field->getCanonicalDecl();
5190
5191 // In an implicit copy or move constructor, ignore any in-class initializer.
5192 if (isImplicitCopyOrMove())
5193 return true;
5194
5195 // If there's no explicit initialization, the field is active only if it
5196 // has an in-class initializer...
5197 if (Field->hasInClassInitializer())
5198 return false;
5199 // ... or it's an anonymous struct or union whose class has an in-class
5200 // initializer.
5201 if (!Field->isAnonymousStructOrUnion())
5202 return true;
5203 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
5204 return !FieldRD->hasInClassInitializer();
5205 }
5206
5207 /// Determine whether the given field is, or is within, a union member
5208 /// that is inactive (because there was an initializer given for a different
5209 /// member of the union, or because the union was not initialized at all).
5210 bool isWithinInactiveUnionMember(FieldDecl *Field,
5212 if (!Indirect)
5213 return isInactiveUnionMember(Field);
5214
5215 for (auto *C : Indirect->chain()) {
5216 FieldDecl *Field = dyn_cast<FieldDecl>(C);
5217 if (Field && isInactiveUnionMember(Field))
5218 return true;
5219 }
5220 return false;
5221 }
5222};
5223}
5224
5225/// Determine whether the given type is an incomplete or zero-lenfgth
5226/// array type.
5228 if (T->isIncompleteArrayType())
5229 return true;
5230
5231 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
5232 if (ArrayT->isZeroSize())
5233 return true;
5234
5235 T = ArrayT->getElementType();
5236 }
5237
5238 return false;
5239}
5240
5241static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
5242 FieldDecl *Field,
5243 IndirectFieldDecl *Indirect = nullptr) {
5244 if (Field->isInvalidDecl())
5245 return false;
5246
5247 // Overwhelmingly common case: we have a direct initializer for this field.
5249 Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
5250 return Info.addFieldInitializer(Init);
5251
5252 // C++11 [class.base.init]p8:
5253 // if the entity is a non-static data member that has a
5254 // brace-or-equal-initializer and either
5255 // -- the constructor's class is a union and no other variant member of that
5256 // union is designated by a mem-initializer-id or
5257 // -- the constructor's class is not a union, and, if the entity is a member
5258 // of an anonymous union, no other member of that union is designated by
5259 // a mem-initializer-id,
5260 // the entity is initialized as specified in [dcl.init].
5261 //
5262 // We also apply the same rules to handle anonymous structs within anonymous
5263 // unions.
5264 if (Info.isWithinInactiveUnionMember(Field, Indirect))
5265 return false;
5266
5267 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
5268 ExprResult DIE =
5269 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
5270 if (DIE.isInvalid())
5271 return true;
5272
5273 auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
5274 SemaRef.checkInitializerLifetime(Entity, DIE.get());
5275
5277 if (Indirect)
5278 Init = new (SemaRef.Context)
5280 SourceLocation(), DIE.get(), SourceLocation());
5281 else
5282 Init = new (SemaRef.Context)
5284 SourceLocation(), DIE.get(), SourceLocation());
5285 return Info.addFieldInitializer(Init);
5286 }
5287
5288 // Don't initialize incomplete or zero-length arrays.
5289 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
5290 return false;
5291
5292 // Don't try to build an implicit initializer if there were semantic
5293 // errors in any of the initializers (and therefore we might be
5294 // missing some that the user actually wrote).
5295 if (Info.AnyErrorsInInits)
5296 return false;
5297
5298 CXXCtorInitializer *Init = nullptr;
5299 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
5300 Indirect, Init))
5301 return true;
5302
5303 if (!Init)
5304 return false;
5305
5306 return Info.addFieldInitializer(Init);
5307}
5308
5309bool
5312 assert(Initializer->isDelegatingInitializer());
5313 Constructor->setNumCtorInitializers(1);
5314 CXXCtorInitializer **initializer =
5315 new (Context) CXXCtorInitializer*[1];
5316 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
5317 Constructor->setCtorInitializers(initializer);
5318
5319 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
5320 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
5321 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
5322 }
5323
5324 DelegatingCtorDecls.push_back(Constructor);
5325
5326 DiagnoseUninitializedFields(*this, Constructor);
5327
5328 return false;
5329}
5330
5331bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5332 ArrayRef<CXXCtorInitializer *> Initializers) {
5333 if (Constructor->isDependentContext()) {
5334 // Just store the initializers as written, they will be checked during
5335 // instantiation.
5336 if (!Initializers.empty()) {
5337 Constructor->setNumCtorInitializers(Initializers.size());
5338 CXXCtorInitializer **baseOrMemberInitializers =
5339 new (Context) CXXCtorInitializer*[Initializers.size()];
5340 memcpy(baseOrMemberInitializers, Initializers.data(),
5341 Initializers.size() * sizeof(CXXCtorInitializer*));
5342 Constructor->setCtorInitializers(baseOrMemberInitializers);
5343 }
5344
5345 // Let template instantiation know whether we had errors.
5346 if (AnyErrors)
5347 Constructor->setInvalidDecl();
5348
5349 return false;
5350 }
5351
5352 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
5353
5354 // We need to build the initializer AST according to order of construction
5355 // and not what user specified in the Initializers list.
5356 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
5357 if (!ClassDecl)
5358 return true;
5359
5360 bool HadError = false;
5361
5362 for (unsigned i = 0; i < Initializers.size(); i++) {
5363 CXXCtorInitializer *Member = Initializers[i];
5364
5365 if (Member->isBaseInitializer())
5366 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
5367 else {
5368 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
5369
5370 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
5371 for (auto *C : F->chain()) {
5372 FieldDecl *FD = dyn_cast<FieldDecl>(C);
5373 if (FD && FD->getParent()->isUnion())
5374 Info.ActiveUnionMember.insert(std::make_pair(
5376 }
5377 } else if (FieldDecl *FD = Member->getMember()) {
5378 if (FD->getParent()->isUnion())
5379 Info.ActiveUnionMember.insert(std::make_pair(
5381 }
5382 }
5383 }
5384
5385 // Keep track of the direct virtual bases.
5387 for (auto &I : ClassDecl->bases()) {
5388 if (I.isVirtual())
5389 DirectVBases.insert(&I);
5390 }
5391
5392 // Push virtual bases before others.
5393 for (auto &VBase : ClassDecl->vbases()) {
5395 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
5396 // [class.base.init]p7, per DR257:
5397 // A mem-initializer where the mem-initializer-id names a virtual base
5398 // class is ignored during execution of a constructor of any class that
5399 // is not the most derived class.
5400 if (ClassDecl->isAbstract()) {
5401 // FIXME: Provide a fixit to remove the base specifier. This requires
5402 // tracking the location of the associated comma for a base specifier.
5403 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
5404 << VBase.getType() << ClassDecl;
5405 DiagnoseAbstractType(ClassDecl);
5406 }
5407
5408 Info.AllToInit.push_back(Value);
5409 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
5410 // [class.base.init]p8, per DR257:
5411 // If a given [...] base class is not named by a mem-initializer-id
5412 // [...] and the entity is not a virtual base class of an abstract
5413 // class, then [...] the entity is default-initialized.
5414 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
5415 CXXCtorInitializer *CXXBaseInit;
5416 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5417 &VBase, IsInheritedVirtualBase,
5418 CXXBaseInit)) {
5419 HadError = true;
5420 continue;
5421 }
5422
5423 Info.AllToInit.push_back(CXXBaseInit);
5424 }
5425 }
5426
5427 // Non-virtual bases.
5428 for (auto &Base : ClassDecl->bases()) {
5429 // Virtuals are in the virtual base list and already constructed.
5430 if (Base.isVirtual())
5431 continue;
5432
5434 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
5435 Info.AllToInit.push_back(Value);
5436 } else if (!AnyErrors) {
5437 CXXCtorInitializer *CXXBaseInit;
5438 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5439 &Base, /*IsInheritedVirtualBase=*/false,
5440 CXXBaseInit)) {
5441 HadError = true;
5442 continue;
5443 }
5444
5445 Info.AllToInit.push_back(CXXBaseInit);
5446 }
5447 }
5448
5449 // Fields.
5450 for (auto *Mem : ClassDecl->decls()) {
5451 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
5452 // C++ [class.bit]p2:
5453 // A declaration for a bit-field that omits the identifier declares an
5454 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
5455 // initialized.
5456 if (F->isUnnamedBitField())
5457 continue;
5458
5459 // If we're not generating the implicit copy/move constructor, then we'll
5460 // handle anonymous struct/union fields based on their individual
5461 // indirect fields.
5462 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
5463 continue;
5464
5465 if (CollectFieldInitializer(*this, Info, F))
5466 HadError = true;
5467 continue;
5468 }
5469
5470 // Beyond this point, we only consider default initialization.
5471 if (Info.isImplicitCopyOrMove())
5472 continue;
5473
5474 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
5475 if (F->getType()->isIncompleteArrayType()) {
5476 assert(ClassDecl->hasFlexibleArrayMember() &&
5477 "Incomplete array type is not valid");
5478 continue;
5479 }
5480
5481 // Initialize each field of an anonymous struct individually.
5482 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
5483 HadError = true;
5484
5485 continue;
5486 }
5487 }
5488
5489 unsigned NumInitializers = Info.AllToInit.size();
5490 if (NumInitializers > 0) {
5491 Constructor->setNumCtorInitializers(NumInitializers);
5492 CXXCtorInitializer **baseOrMemberInitializers =
5493 new (Context) CXXCtorInitializer*[NumInitializers];
5494 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
5495 NumInitializers * sizeof(CXXCtorInitializer*));
5496 Constructor->setCtorInitializers(baseOrMemberInitializers);
5497
5498 // Constructors implicitly reference the base and member
5499 // destructors.
5500 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
5501 Constructor->getParent());
5502 }
5503
5504 return HadError;
5505}
5506
5508 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
5509 const RecordDecl *RD = RT->getDecl();
5510 if (RD->isAnonymousStructOrUnion()) {
5511 for (auto *Field : RD->fields())
5512 PopulateKeysForFields(Field, IdealInits);
5513 return;
5514 }
5515 }
5516 IdealInits.push_back(Field->getCanonicalDecl());
5517}
5518
5519static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
5520 return Context.getCanonicalType(BaseType).getTypePtr();
5521}
5522
5525 if (!Member->isAnyMemberInitializer())
5526 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
5527
5528 return Member->getAnyMember()->getCanonicalDecl();
5529}
5530
5533 const CXXCtorInitializer *Current) {
5534 if (Previous->isAnyMemberInitializer())
5535 Diag << 0 << Previous->getAnyMember();
5536 else
5537 Diag << 1 << Previous->getTypeSourceInfo()->getType();
5538
5539 if (Current->isAnyMemberInitializer())
5540 Diag << 0 << Current->getAnyMember();
5541 else
5542 Diag << 1 << Current->getTypeSourceInfo()->getType();
5543}
5544
5546 Sema &SemaRef, const CXXConstructorDecl *Constructor,
5548 if (Constructor->getDeclContext()->isDependentContext())
5549 return;
5550
5551 // Don't check initializers order unless the warning is enabled at the
5552 // location of at least one initializer.
5553 bool ShouldCheckOrder = false;
5554 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5555 CXXCtorInitializer *Init = Inits[InitIndex];
5556 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
5557 Init->getSourceLocation())) {
5558 ShouldCheckOrder = true;
5559 break;
5560 }
5561 }
5562 if (!ShouldCheckOrder)
5563 return;
5564
5565 // Build the list of bases and members in the order that they'll
5566 // actually be initialized. The explicit initializers should be in
5567 // this same order but may be missing things.
5568 SmallVector<const void*, 32> IdealInitKeys;
5569
5570 const CXXRecordDecl *ClassDecl = Constructor->getParent();
5571
5572 // 1. Virtual bases.
5573 for (const auto &VBase : ClassDecl->vbases())
5574 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
5575
5576 // 2. Non-virtual bases.
5577 for (const auto &Base : ClassDecl->bases()) {
5578 if (Base.isVirtual())
5579 continue;
5580 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
5581 }
5582
5583 // 3. Direct fields.
5584 for (auto *Field : ClassDecl->fields()) {
5585 if (Field->isUnnamedBitField())
5586 continue;
5587
5588 PopulateKeysForFields(Field, IdealInitKeys);
5589 }
5590
5591 unsigned NumIdealInits = IdealInitKeys.size();
5592 unsigned IdealIndex = 0;
5593
5594 // Track initializers that are in an incorrect order for either a warning or
5595 // note if multiple ones occur.
5596 SmallVector<unsigned> WarnIndexes;
5597 // Correlates the index of an initializer in the init-list to the index of
5598 // the field/base in the class.
5599 SmallVector<std::pair<unsigned, unsigned>, 32> CorrelatedInitOrder;
5600
5601 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5602 const void *InitKey = GetKeyForMember(SemaRef.Context, Inits[InitIndex]);
5603
5604 // Scan forward to try to find this initializer in the idealized
5605 // initializers list.
5606 for (; IdealIndex != NumIdealInits; ++IdealIndex)
5607 if (InitKey == IdealInitKeys[IdealIndex])
5608 break;
5609
5610 // If we didn't find this initializer, it must be because we
5611 // scanned past it on a previous iteration. That can only
5612 // happen if we're out of order; emit a warning.
5613 if (IdealIndex == NumIdealInits && InitIndex) {
5614 WarnIndexes.push_back(InitIndex);
5615
5616 // Move back to the initializer's location in the ideal list.
5617 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5618 if (InitKey == IdealInitKeys[IdealIndex])
5619 break;
5620
5621 assert(IdealIndex < NumIdealInits &&
5622 "initializer not found in initializer list");
5623 }
5624 CorrelatedInitOrder.emplace_back(IdealIndex, InitIndex);
5625 }
5626
5627 if (WarnIndexes.empty())
5628 return;
5629
5630 // Sort based on the ideal order, first in the pair.
5631 llvm::sort(CorrelatedInitOrder, llvm::less_first());
5632
5633 // Introduce a new scope as SemaDiagnosticBuilder needs to be destroyed to
5634 // emit the diagnostic before we can try adding notes.
5635 {
5637 Inits[WarnIndexes.front() - 1]->getSourceLocation(),
5638 WarnIndexes.size() == 1 ? diag::warn_initializer_out_of_order
5639 : diag::warn_some_initializers_out_of_order);
5640
5641 for (unsigned I = 0; I < CorrelatedInitOrder.size(); ++I) {
5642 if (CorrelatedInitOrder[I].second == I)
5643 continue;
5644 // Ideally we would be using InsertFromRange here, but clang doesn't
5645 // appear to handle InsertFromRange correctly when the source range is
5646 // modified by another fix-it.
5648 Inits[I]->getSourceRange(),
5651 Inits[CorrelatedInitOrder[I].second]->getSourceRange()),
5653 }
5654
5655 // If there is only 1 item out of order, the warning expects the name and
5656 // type of each being added to it.
5657 if (WarnIndexes.size() == 1) {
5658 AddInitializerToDiag(D, Inits[WarnIndexes.front() - 1],
5659 Inits[WarnIndexes.front()]);
5660 return;
5661 }
5662 }
5663 // More than 1 item to warn, create notes letting the user know which ones
5664 // are bad.
5665 for (unsigned WarnIndex : WarnIndexes) {
5666 const clang::CXXCtorInitializer *PrevInit = Inits[WarnIndex - 1];
5667 auto D = SemaRef.Diag(PrevInit->getSourceLocation(),
5668 diag::note_initializer_out_of_order);
5669 AddInitializerToDiag(D, PrevInit, Inits[WarnIndex]);
5670 D << PrevInit->getSourceRange();
5671 }
5672}
5673
5674namespace {
5675bool CheckRedundantInit(Sema &S,
5677 CXXCtorInitializer *&PrevInit) {
5678 if (!PrevInit) {
5679 PrevInit = Init;
5680 return false;
5681 }
5682
5683 if (FieldDecl *Field = Init->getAnyMember())
5684 S.Diag(Init->getSourceLocation(),
5685 diag::err_multiple_mem_initialization)
5686 << Field->getDeclName()
5687 << Init->getSourceRange();
5688 else {
5689 const Type *BaseClass = Init->getBaseClass();
5690 assert(BaseClass && "neither field nor base");
5691 S.Diag(Init->getSourceLocation(),
5692 diag::err_multiple_base_initialization)
5693 << QualType(BaseClass, 0)
5694 << Init->getSourceRange();
5695 }
5696 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5697 << 0 << PrevInit->getSourceRange();
5698
5699 return true;
5700}
5701
5702typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5703typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5704
5705bool CheckRedundantUnionInit(Sema &S,
5707 RedundantUnionMap &Unions) {
5708 FieldDecl *Field = Init->getAnyMember();
5709 RecordDecl *Parent = Field->getParent();
5710 NamedDecl *Child = Field;
5711
5712 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5713 if (Parent->isUnion()) {
5714 UnionEntry &En = Unions[Parent];
5715 if (En.first && En.first != Child) {
5716 S.Diag(Init->getSourceLocation(),
5717 diag::err_multiple_mem_union_initialization)
5718 << Field->getDeclName()
5719 << Init->getSourceRange();
5720 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5721 << 0 << En.second->getSourceRange();
5722 return true;
5723 }
5724 if (!En.first) {
5725 En.first = Child;
5726 En.second = Init;
5727 }
5728 if (!Parent->isAnonymousStructOrUnion())
5729 return false;
5730 }
5731
5732 Child = Parent;
5733 Parent = cast<RecordDecl>(Parent->getDeclContext());
5734 }
5735
5736 return false;
5737}
5738} // namespace
5739
5740/// ActOnMemInitializers - Handle the member initializers for a constructor.
5741void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5742 SourceLocation ColonLoc,
5744 bool AnyErrors) {
5745 if (!ConstructorDecl)
5746 return;
5747
5748 AdjustDeclIfTemplate(ConstructorDecl);
5749
5750 CXXConstructorDecl *Constructor
5751 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5752
5753 if (!Constructor) {
5754 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5755 return;
5756 }
5757
5758 // Mapping for the duplicate initializers check.
5759 // For member initializers, this is keyed with a FieldDecl*.
5760 // For base initializers, this is keyed with a Type*.
5761 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5762
5763 // Mapping for the inconsistent anonymous-union initializers check.
5764 RedundantUnionMap MemberUnions;
5765
5766 bool HadError = false;
5767 for (unsigned i = 0; i < MemInits.size(); i++) {
5768 CXXCtorInitializer *Init = MemInits[i];
5769
5770 // Set the source order index.
5771 Init->setSourceOrder(i);
5772
5773 if (Init->isAnyMemberInitializer()) {
5774 const void *Key = GetKeyForMember(Context, Init);
5775 if (CheckRedundantInit(*this, Init, Members[Key]) ||
5776 CheckRedundantUnionInit(*this, Init, MemberUnions))
5777 HadError = true;
5778 } else if (Init->isBaseInitializer()) {
5779 const void *Key = GetKeyForMember(Context, Init);
5780 if (CheckRedundantInit(*this, Init, Members[Key]))
5781 HadError = true;
5782 } else {
5783 assert(Init->isDelegatingInitializer());
5784 // This must be the only initializer
5785 if (MemInits.size() != 1) {
5786 Diag(Init->getSourceLocation(),
5787 diag::err_delegating_initializer_alone)
5788 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5789 // We will treat this as being the only initializer.
5790 }
5791 SetDelegatingInitializer(Constructor, MemInits[i]);
5792 // Return immediately as the initializer is set.
5793 return;
5794 }
5795 }
5796
5797 if (HadError)
5798 return;
5799
5800 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5801
5802 SetCtorInitializers(Constructor, AnyErrors, MemInits);
5803
5804 DiagnoseUninitializedFields(*this, Constructor);
5805}
5806
5807void
5809 CXXRecordDecl *ClassDecl) {
5810 // Ignore dependent contexts. Also ignore unions, since their members never
5811 // have destructors implicitly called.
5812 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5813 return;
5814
5815 // FIXME: all the access-control diagnostics are positioned on the
5816 // field/base declaration. That's probably good; that said, the
5817 // user might reasonably want to know why the destructor is being
5818 // emitted, and we currently don't say.
5819
5820 // Non-static data members.
5821 for (auto *Field : ClassDecl->fields()) {
5822 if (Field->isInvalidDecl())
5823 continue;
5824
5825 // Don't destroy incomplete or zero-length arrays.
5826 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5827 continue;
5828
5829 QualType FieldType = Context.getBaseElementType(Field->getType());
5830
5831 const RecordType* RT = FieldType->getAs<RecordType>();
5832 if (!RT)
5833 continue;
5834
5835 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5836 if (FieldClassDecl->isInvalidDecl())
5837 continue;
5838 if (FieldClassDecl->hasIrrelevantDestructor())
5839 continue;
5840 // The destructor for an implicit anonymous union member is never invoked.
5841 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5842 continue;
5843
5844 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5845 // Dtor might still be missing, e.g because it's invalid.
5846 if (!Dtor)
5847 continue;
5848 CheckDestructorAccess(Field->getLocation(), Dtor,
5849 PDiag(diag::err_access_dtor_field)
5850 << Field->getDeclName()
5851 << FieldType);
5852
5853 MarkFunctionReferenced(Location, Dtor);
5854 DiagnoseUseOfDecl(Dtor, Location);
5855 }
5856
5857 // We only potentially invoke the destructors of potentially constructed
5858 // subobjects.
5859 bool VisitVirtualBases = !ClassDecl->isAbstract();
5860
5861 // If the destructor exists and has already been marked used in the MS ABI,
5862 // then virtual base destructors have already been checked and marked used.
5863 // Skip checking them again to avoid duplicate diagnostics.
5865 CXXDestructorDecl *Dtor = ClassDecl->getDestructor();
5866 if (Dtor && Dtor->isUsed())
5867 VisitVirtualBases = false;
5868 }
5869
5871
5872 // Bases.
5873 for (const auto &Base : ClassDecl->bases()) {
5874 const RecordType *RT = Base.getType()->getAs<RecordType>();
5875 if (!RT)
5876 continue;
5877
5878 // Remember direct virtual bases.
5879 if (Base.isVirtual()) {
5880 if (!VisitVirtualBases)
5881 continue;
5882 DirectVirtualBases.insert(RT);
5883 }
5884
5885 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5886 // If our base class is invalid, we probably can't get its dtor anyway.
5887 if (BaseClassDecl->isInvalidDecl())
5888 continue;
5889 if (BaseClassDecl->hasIrrelevantDestructor())
5890 continue;
5891
5892 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5893 // Dtor might still be missing, e.g because it's invalid.
5894 if (!Dtor)
5895 continue;
5896
5897 // FIXME: caret should be on the start of the class name
5898 CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5899 PDiag(diag::err_access_dtor_base)
5900 << Base.getType() << Base.getSourceRange(),
5901 Context.getTypeDeclType(ClassDecl));
5902
5903 MarkFunctionReferenced(Location, Dtor);
5904 DiagnoseUseOfDecl(Dtor, Location);
5905 }
5906
5907 if (VisitVirtualBases)
5908 MarkVirtualBaseDestructorsReferenced(Location, ClassDecl,
5909 &DirectVirtualBases);
5910}
5911
5913 SourceLocation Location, CXXRecordDecl *ClassDecl,
5914 llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases) {
5915 // Virtual bases.
5916 for (const auto &VBase : ClassDecl->vbases()) {
5917 // Bases are always records in a well-formed non-dependent class.
5918 const RecordType *RT = VBase.getType()->castAs<RecordType>();
5919
5920 // Ignore already visited direct virtual bases.
5921 if (DirectVirtualBases && DirectVirtualBases->count(RT))
5922 continue;
5923
5924 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5925 // If our base class is invalid, we probably can't get its dtor anyway.
5926 if (BaseClassDecl->isInvalidDecl())
5927 continue;
5928 if (BaseClassDecl->hasIrrelevantDestructor())
5929 continue;
5930
5931 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5932 // Dtor might still be missing, e.g because it's invalid.
5933 if (!Dtor)
5934 continue;
5936 ClassDecl->getLocation(), Dtor,
5937 PDiag(diag::err_access_dtor_vbase)
5938 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5939 Context.getTypeDeclType(ClassDecl)) ==
5940 AR_accessible) {
5942 Context.getTypeDeclType(ClassDecl), VBase.getType(),
5943 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5944 SourceRange(), DeclarationName(), nullptr);
5945 }
5946
5947 MarkFunctionReferenced(Location, Dtor);
5948 DiagnoseUseOfDecl(Dtor, Location);
5949 }
5950}
5951
5953 if (!CDtorDecl)
5954 return;
5955
5956 if (CXXConstructorDecl *Constructor
5957 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5958 if (CXXRecordDecl *ClassDecl = Constructor->getParent();
5959 !ClassDecl || ClassDecl->isInvalidDecl()) {
5960 return;
5961 }
5962 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5963 DiagnoseUninitializedFields(*this, Constructor);
5964 }
5965}
5966
5968 if (!getLangOpts().CPlusPlus)
5969 return false;
5970
5971 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5972 if (!RD)
5973 return false;
5974
5975 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5976 // class template specialization here, but doing so breaks a lot of code.
5977
5978 // We can't answer whether something is abstract until it has a
5979 // definition. If it's currently being defined, we'll walk back
5980 // over all the declarations when we have a full definition.
5981 const CXXRecordDecl *Def = RD->getDefinition();
5982 if (!Def || Def->isBeingDefined())
5983 return false;
5984
5985 return RD->isAbstract();
5986}
5987
5989 TypeDiagnoser &Diagnoser) {
5990 if (!isAbstractType(Loc, T))
5991 return false;
5992
5994 Diagnoser.diagnose(*this, Loc, T);
5996 return true;
5997}
5998
6000 // Check if we've already emitted the list of pure virtual functions
6001 // for this class.
6003 return;
6004
6005 // If the diagnostic is suppressed, don't emit the notes. We're only
6006 // going to emit them once, so try to attach them to a diagnostic we're
6007 // actually going to show.
6009 return;
6010
6011 CXXFinalOverriderMap FinalOverriders;
6012 RD->getFinalOverriders(FinalOverriders);
6013
6014 // Keep a set of seen pure methods so we won't diagnose the same method
6015 // more than once.
6017
6018 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
6019 MEnd = FinalOverriders.end();
6020 M != MEnd;
6021 ++M) {
6022 for (OverridingMethods::iterator SO = M->second.begin(),
6023 SOEnd = M->second.end();
6024 SO != SOEnd; ++SO) {
6025 // C++ [class.abstract]p4:
6026 // A class is abstract if it contains or inherits at least one
6027 // pure virtual function for which the final overrider is pure
6028 // virtual.
6029
6030 //
6031 if (SO->second.size() != 1)
6032 continue;
6033
6034 if (!SO->second.front().Method->isPureVirtual())
6035 continue;
6036
6037 if (!SeenPureMethods.insert(SO->second.front().Method).second)
6038 continue;
6039
6040 Diag(SO->second.front().Method->getLocation(),
6041 diag::note_pure_virtual_function)
6042 << SO->second.front().Method->getDeclName() << RD->getDeclName();
6043 }
6044 }
6045
6048 PureVirtualClassDiagSet->insert(RD);
6049}
6050
6051namespace {
6052struct AbstractUsageInfo {
6053 Sema &S;
6055 CanQualType AbstractType;
6056 bool Invalid;
6057
6058 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
6059 : S(S), Record(Record),
6060 AbstractType(S.Context.getCanonicalType(
6061 S.Context.getTypeDeclType(Record))),
6062 Invalid(false) {}
6063
6064 void DiagnoseAbstractType() {
6065 if (Invalid) return;
6067 Invalid = true;
6068 }
6069
6070 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
6071};
6072
6073struct CheckAbstractUsage {
6074 AbstractUsageInfo &Info;
6075 const NamedDecl *Ctx;
6076
6077 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
6078 : Info(Info), Ctx(Ctx) {}
6079
6080 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
6081 switch (TL.getTypeLocClass()) {
6082#define ABSTRACT_TYPELOC(CLASS, PARENT)
6083#define TYPELOC(CLASS, PARENT) \
6084 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
6085#include "clang/AST/TypeLocNodes.def"
6086 }
6087 }
6088
6089 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6091 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
6092 if (!TL.getParam(I))
6093 continue;
6094
6096 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
6097 }
6098 }
6099
6100 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6102 }
6103
6105 // Visit the type parameters from a permissive context.
6106 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
6107 TemplateArgumentLoc TAL = TL.getArgLoc(I);
6109 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
6110 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
6111 // TODO: other template argument types?
6112 }
6113 }
6114
6115 // Visit pointee types from a permissive context.
6116#define CheckPolymorphic(Type) \
6117 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
6118 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
6119 }
6125
6126 /// Handle all the types we haven't given a more specific
6127 /// implementation for above.
6128 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
6129 // Every other kind of type that we haven't called out already
6130 // that has an inner type is either (1) sugar or (2) contains that
6131 // inner type in some way as a subobject.
6132 if (TypeLoc Next = TL.getNextTypeLoc())
6133 return Visit(Next, Sel);
6134
6135 // If there's no inner type and we're in a permissive context,
6136 // don't diagnose.
6137 if (Sel == Sema::AbstractNone) return;
6138
6139 // Check whether the type matches the abstract type.
6140 QualType T = TL.getType();
6141 if (T->isArrayType()) {
6143 T = Info.S.Context.getBaseElementType(T);
6144 }
6146 if (CT != Info.AbstractType) return;
6147
6148 // It matched; do some magic.
6149 // FIXME: These should be at most warnings. See P0929R2, CWG1640, CWG1646.
6150 if (Sel == Sema::AbstractArrayType) {
6151 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
6152 << T << TL.getSourceRange();
6153 } else {
6154 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
6155 << Sel << T << TL.getSourceRange();
6156 }
6157 Info.DiagnoseAbstractType();
6158 }
6159};
6160
6161void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
6163 CheckAbstractUsage(*this, D).Visit(TL, Sel);
6164}
6165
6166}
6167
6168/// Check for invalid uses of an abstract type in a function declaration.
6169static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6170 FunctionDecl *FD) {
6171 // Only definitions are required to refer to complete and
6172 // non-abstract types.
6174 return;
6175
6176 // For safety's sake, just ignore it if we don't have type source
6177 // information. This should never happen for non-implicit methods,
6178 // but...
6179 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6180 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractNone);
6181}
6182
6183/// Check for invalid uses of an abstract type in a variable0 declaration.
6184static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6185 VarDecl *VD) {
6186 // No need to do the check on definitions, which require that
6187 // the type is complete.
6189 return;
6190
6191 Info.CheckType(VD, VD->getTypeSourceInfo()->getTypeLoc(),
6193}
6194
6195/// Check for invalid uses of an abstract type within a class definition.
6196static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6197 CXXRecordDecl *RD) {
6198 for (auto *D : RD->decls()) {
6199 if (D->isImplicit()) continue;
6200
6201 // Step through friends to the befriended declaration.
6202 if (auto *FD = dyn_cast<FriendDecl>(D)) {
6203 D = FD->getFriendDecl();
6204 if (!D) continue;
6205 }
6206
6207 // Functions and function templates.
6208 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6209 CheckAbstractClassUsage(Info, FD);
6210 } else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) {
6211 CheckAbstractClassUsage(Info, FTD->getTemplatedDecl());
6212
6213 // Fields and static variables.
6214 } else if (auto *FD = dyn_cast<FieldDecl>(D)) {
6215 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6216 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
6217 } else if (auto *VD = dyn_cast<VarDecl>(D)) {
6218 CheckAbstractClassUsage(Info, VD);
6219 } else if (auto *VTD = dyn_cast<VarTemplateDecl>(D)) {
6220 CheckAbstractClassUsage(Info, VTD->getTemplatedDecl());
6221
6222 // Nested classes and class templates.
6223 } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
6224 CheckAbstractClassUsage(Info, RD);
6225 } else if (auto *CTD = dyn_cast<ClassTemplateDecl>(D)) {
6226 CheckAbstractClassUsage(Info, CTD->getTemplatedDecl());
6227 }
6228 }
6229}
6230
6232 Attr *ClassAttr = getDLLAttr(Class);
6233 if (!ClassAttr)
6234 return;
6235
6236 assert(ClassAttr->getKind() == attr::DLLExport);
6237
6238 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6239
6241 // Don't go any further if this is just an explicit instantiation
6242 // declaration.
6243 return;
6244
6245 // Add a context note to explain how we got to any diagnostics produced below.
6246 struct MarkingClassDllexported {
6247 Sema &S;
6248 MarkingClassDllexported(Sema &S, CXXRecordDecl *Class,
6249 SourceLocation AttrLoc)
6250 : S(S) {
6253 Ctx.PointOfInstantiation = AttrLoc;
6254 Ctx.Entity = Class;
6256 }
6257 ~MarkingClassDllexported() {
6259 }
6260 } MarkingDllexportedContext(S, Class, ClassAttr->getLocation());
6261
6262 if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment())
6263 S.MarkVTableUsed(Class->getLocation(), Class, true);
6264
6265 for (Decl *Member : Class->decls()) {
6266 // Skip members that were not marked exported.
6267 if (!Member->hasAttr<DLLExportAttr>())
6268 continue;
6269
6270 // Defined static variables that are members of an exported base
6271 // class must be marked export too.
6272 auto *VD = dyn_cast<VarDecl>(Member);
6273 if (VD && VD->getStorageClass() == SC_Static &&
6275 S.MarkVariableReferenced(VD->getLocation(), VD);
6276
6277 auto *MD = dyn_cast<CXXMethodDecl>(Member);
6278 if (!MD)
6279 continue;
6280
6281 if (MD->isUserProvided()) {
6282 // Instantiate non-default class member functions ...
6283
6284 // .. except for certain kinds of template specializations.
6285 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
6286 continue;
6287
6288 // If this is an MS ABI dllexport default constructor, instantiate any
6289 // default arguments.
6291 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6292 if (CD && CD->isDefaultConstructor() && TSK == TSK_Undeclared) {
6294 }
6295 }
6296
6297 S.MarkFunctionReferenced(Class->getLocation(), MD);
6298
6299 // The function will be passed to the consumer when its definition is
6300 // encountered.
6301 } else if (MD->isExplicitlyDefaulted()) {
6302 // Synthesize and instantiate explicitly defaulted methods.
6303 S.MarkFunctionReferenced(Class->getLocation(), MD);
6304
6306 // Except for explicit instantiation defs, we will not see the
6307 // definition again later, so pass it to the consumer now.
6309 }
6310 } else if (!MD->isTrivial() ||
6311 MD->isCopyAssignmentOperator() ||
6312 MD->isMoveAssignmentOperator()) {
6313 // Synthesize and instantiate non-trivial implicit methods, and the copy
6314 // and move assignment operators. The latter are exported even if they
6315 // are trivial, because the address of an operator can be taken and
6316 // should compare equal across libraries.
6317 S.MarkFunctionReferenced(Class->getLocation(), MD);
6318
6319 // There is no later point when we will see the definition of this
6320 // function, so pass it to the consumer now.
6322 }
6323 }
6324}
6325
6328 // Only the MS ABI has default constructor closures, so we don't need to do
6329 // this semantic checking anywhere else.
6331 return;
6332
6333 CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
6334 for (Decl *Member : Class->decls()) {
6335 // Look for exported default constructors.
6336 auto *CD = dyn_cast<CXXConstructorDecl>(Member);
6337 if (!CD || !CD->isDefaultConstructor())
6338 continue;
6339 auto *Attr = CD->getAttr<DLLExportAttr>();
6340 if (!Attr)
6341 continue;
6342
6343 // If the class is non-dependent, mark the default arguments as ODR-used so
6344 // that we can properly codegen the constructor closure.
6345 if (!Class->isDependentContext()) {
6346 for (ParmVarDecl *PD : CD->parameters()) {
6347 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
6349 }
6350 }
6351
6352 if (LastExportedDefaultCtor) {
6353 S.Diag(LastExportedDefaultCtor->getLocation(),
6354 diag::err_attribute_dll_ambiguous_default_ctor)
6355 << Class;
6356 S.Diag(CD->getLocation(), diag::note_entity_declared_at)
6357 << CD->getDeclName();
6358 return;
6359 }
6360 LastExportedDefaultCtor = CD;
6361 }
6362}
6363
6366 bool ErrorReported = false;
6367 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6368 ClassTemplateDecl *TD) {
6369 if (ErrorReported)
6370 return;
6371 S.Diag(TD->getLocation(),
6372 diag::err_cuda_device_builtin_surftex_cls_template)
6373 << /*surface*/ 0 << TD;
6374 ErrorReported = true;
6375 };
6376
6377 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6378 if (!TD) {
6379 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6380 if (!SD) {
6381 S.Diag(Class->getLocation(),
6382 diag::err_cuda_device_builtin_surftex_ref_decl)
6383 << /*surface*/ 0 << Class;
6384 S.Diag(Class->getLocation(),
6385 diag::note_cuda_device_builtin_surftex_should_be_template_class)
6386 << Class;
6387 return;
6388 }
6389 TD = SD->getSpecializedTemplate();
6390 }
6391
6393 unsigned N = Params->size();
6394
6395 if (N != 2) {
6396 reportIllegalClassTemplate(S, TD);
6397 S.Diag(TD->getLocation(),
6398 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6399 << TD << 2;
6400 }
6401 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6402 reportIllegalClassTemplate(S, TD);
6403 S.Diag(TD->getLocation(),
6404 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6405 << TD << /*1st*/ 0 << /*type*/ 0;
6406 }
6407 if (N > 1) {
6408 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6409 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6410 reportIllegalClassTemplate(S, TD);
6411 S.Diag(TD->getLocation(),
6412 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6413 << TD << /*2nd*/ 1 << /*integer*/ 1;
6414 }
6415 }
6416}
6417
6420 bool ErrorReported = false;
6421 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6422 ClassTemplateDecl *TD) {
6423 if (ErrorReported)
6424 return;
6425 S.Diag(TD->getLocation(),
6426 diag::err_cuda_device_builtin_surftex_cls_template)
6427 << /*texture*/ 1 << TD;
6428 ErrorReported = true;
6429 };
6430
6431 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6432 if (!TD) {
6433 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6434 if (!SD) {
6435 S.Diag(Class->getLocation(),
6436 diag::err_cuda_device_builtin_surftex_ref_decl)
6437 << /*texture*/ 1 << Class;
6438 S.Diag(Class->getLocation(),
6439 diag::note_cuda_device_builtin_surftex_should_be_template_class)
6440 << Class;
6441 return;
6442 }
6443 TD = SD->getSpecializedTemplate();
6444 }
6445
6447 unsigned N = Params->size();
6448
6449 if (N != 3) {
6450 reportIllegalClassTemplate(S, TD);
6451 S.Diag(TD->getLocation(),
6452 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6453 << TD << 3;
6454 }
6455 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6456 reportIllegalClassTemplate(S, TD);
6457 S.Diag(TD->getLocation(),
6458 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6459 << TD << /*1st*/ 0 << /*type*/ 0;
6460 }
6461 if (N > 1) {
6462 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6463 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6464 reportIllegalClassTemplate(S, TD);
6465 S.Diag(TD->getLocation(),
6466 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6467 << TD << /*2nd*/ 1 << /*integer*/ 1;
6468 }
6469 }
6470 if (N > 2) {
6471 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2));
6472 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6473 reportIllegalClassTemplate(S, TD);
6474 S.Diag(TD->getLocation(),
6475 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6476 << TD << /*3rd*/ 2 << /*integer*/ 1;
6477 }
6478 }
6479}
6480
6482 // Mark any compiler-generated routines with the implicit code_seg attribute.
6483 for (auto *Method : Class->methods()) {
6484 if (Method->isUserProvided())
6485 continue;
6486 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
6487 Method->addAttr(A);
6488 }
6489}
6490
6491/// Check class-level dllimport/dllexport attribute.
6493 Attr *ClassAttr = getDLLAttr(Class);
6494
6495 // MSVC inherits DLL attributes to partial class template specializations.
6496 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) {
6497 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
6498 if (Attr *TemplateAttr =
6499 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
6500 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
6501 A->setInherited(true);
6502 ClassAttr = A;
6503 }
6504 }
6505 }
6506
6507 if (!ClassAttr)
6508 return;
6509
6510 // MSVC allows imported or exported template classes that have UniqueExternal
6511 // linkage. This occurs when the template class has been instantiated with
6512 // a template parameter which itself has internal linkage.
6513 // We drop the attribute to avoid exporting or importing any members.
6515 Context.getTargetInfo().getTriple().isPS()) &&
6516 (!Class->isExternallyVisible() && Class->hasExternalFormalLinkage())) {
6517 Class->dropAttrs<DLLExportAttr, DLLImportAttr>();
6518 return;
6519 }
6520
6521 if (!Class->isExternallyVisible()) {
6522 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
6523 << Class << ClassAttr;
6524 return;
6525 }
6526
6528 !ClassAttr->isInherited()) {
6529 // Diagnose dll attributes on members of class with dll attribute.
6530 for (Decl *Member : Class->decls()) {
6531 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
6532 continue;
6533 InheritableAttr *MemberAttr = getDLLAttr(Member);
6534 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
6535 continue;
6536
6537 Diag(MemberAttr->getLocation(),
6538 diag::err_attribute_dll_member_of_dll_class)
6539 << MemberAttr << ClassAttr;
6540 Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
6541 Member->setInvalidDecl();
6542 }
6543 }
6544
6545 if (Class->getDescribedClassTemplate())
6546 // Don't inherit dll attribute until the template is instantiated.
6547 return;
6548
6549 // The class is either imported or exported.
6550 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
6551
6552 // Check if this was a dllimport attribute propagated from a derived class to
6553 // a base class template specialization. We don't apply these attributes to
6554 // static data members.
6555 const bool PropagatedImport =
6556 !ClassExported &&
6557 cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
6558
6559 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6560
6561 // Ignore explicit dllexport on explicit class template instantiation
6562 // declarations, except in MinGW mode.
6563 if (ClassExported && !ClassAttr->isInherited() &&
6565 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
6566 Class->dropAttr<DLLExportAttr>();
6567 return;
6568 }
6569
6570 // Force declaration of implicit members so they can inherit the attribute.
6572
6573 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
6574 // seem to be true in practice?
6575
6576 for (Decl *Member : Class->decls()) {
6577 VarDecl *VD = dyn_cast<VarDecl>(Member);
6578 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
6579
6580 // Only methods and static fields inherit the attributes.
6581 if (!VD && !MD)
6582 continue;
6583
6584 if (MD) {
6585 // Don't process deleted methods.
6586 if (MD->isDeleted())
6587 continue;
6588
6589 if (MD->isInlined()) {
6590 // MinGW does not import or export inline methods. But do it for
6591 // template instantiations.
6595 continue;
6596
6597 // MSVC versions before 2015 don't export the move assignment operators
6598 // and move constructor, so don't attempt to import/export them if
6599 // we have a definition.
6600 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
6601 if ((MD->isMoveAssignmentOperator() ||
6602 (Ctor && Ctor->isMoveConstructor())) &&
6603 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
6604 continue;
6605
6606 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
6607 // operator is exported anyway.
6608 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6609 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
6610 continue;
6611 }
6612 }
6613
6614 // Don't apply dllimport attributes to static data members of class template
6615 // instantiations when the attribute is propagated from a derived class.
6616 if (VD && PropagatedImport)
6617 continue;
6618
6619 if (!cast<NamedDecl>(Member)->isExternallyVisible())
6620 continue;
6621
6622 if (!getDLLAttr(Member)) {
6623 InheritableAttr *NewAttr = nullptr;
6624
6625 // Do not export/import inline function when -fno-dllexport-inlines is
6626 // passed. But add attribute for later local static var check.
6627 if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
6630 if (ClassExported) {
6631 NewAttr = ::new (getASTContext())
6632 DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);
6633 } else {
6634 NewAttr = ::new (getASTContext())
6635 DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);
6636 }
6637 } else {
6638 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6639 }
6640
6641 NewAttr->setInherited(true);
6642 Member->addAttr(NewAttr);
6643
6644 if (MD) {
6645 // Propagate DLLAttr to friend re-declarations of MD that have already
6646 // been constructed.
6647 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
6648 FD = FD->getPreviousDecl()) {
6650 continue;
6651 assert(!getDLLAttr(FD) &&
6652 "friend re-decl should not already have a DLLAttr");
6653 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6654 NewAttr->setInherited(true);
6655 FD->addAttr(NewAttr);
6656 }
6657 }
6658 }
6659 }
6660
6661 if (ClassExported)
6662 DelayedDllExportClasses.push_back(Class);
6663}
6664
6665/// Perform propagation of DLL attributes from a derived class to a
6666/// templated base class for MS compatibility.
6668 CXXRecordDecl *Class, Attr *ClassAttr,
6669 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
6670 if (getDLLAttr(
6671 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
6672 // If the base class template has a DLL attribute, don't try to change it.
6673 return;
6674 }
6675
6676 auto TSK = BaseTemplateSpec->getSpecializationKind();
6677 if (!getDLLAttr(BaseTemplateSpec) &&
6679 TSK == TSK_ImplicitInstantiation)) {
6680 // The template hasn't been instantiated yet (or it has, but only as an
6681 // explicit instantiation declaration or implicit instantiation, which means
6682 // we haven't codegenned any members yet), so propagate the attribute.
6683 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6684 NewAttr->setInherited(true);
6685 BaseTemplateSpec->addAttr(NewAttr);
6686
6687 // If this was an import, mark that we propagated it from a derived class to
6688 // a base class template specialization.
6689 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
6690 ImportAttr->setPropagatedToBaseTemplate();
6691
6692 // If the template is already instantiated, checkDLLAttributeRedeclaration()
6693 // needs to be run again to work see the new attribute. Otherwise this will
6694 // get run whenever the template is instantiated.
6695 if (TSK != TSK_Undeclared)
6696 checkClassLevelDLLAttribute(BaseTemplateSpec);
6697
6698 return;
6699 }
6700
6701 if (getDLLAttr(BaseTemplateSpec)) {
6702 // The template has already been specialized or instantiated with an
6703 // attribute, explicitly or through propagation. We should not try to change
6704 // it.
6705 return;
6706 }
6707
6708 // The template was previously instantiated or explicitly specialized without
6709 // a dll attribute, It's too late for us to add an attribute, so warn that
6710 // this is unsupported.
6711 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
6712 << BaseTemplateSpec->isExplicitSpecialization();
6713 Diag(ClassAttr->getLocation(), diag::note_attribute);
6714 if (BaseTemplateSpec->isExplicitSpecialization()) {
6715 Diag(BaseTemplateSpec->getLocation(),
6716 diag::note_template_class_explicit_specialization_was_here)
6717 << BaseTemplateSpec;
6718 } else {
6719 Diag(BaseTemplateSpec->getPointOfInstantiation(),
6720 diag::note_template_class_instantiation_was_here)
6721 << BaseTemplateSpec;
6722 }
6723}
6724
6725/// Determine the kind of defaulting that would be done for a given function.
6726///
6727/// If the function is both a default constructor and a copy / move constructor
6728/// (due to having a default argument for the first parameter), this picks
6729/// CXXSpecialMemberKind::DefaultConstructor.
6730///
6731/// FIXME: Check that case is properly handled by all callers.
6734 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
6735 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
6736 if (Ctor->isDefaultConstructor())
6738
6739 if (Ctor->isCopyConstructor())
6741
6742 if (Ctor->isMoveConstructor())
6744 }
6745
6746 if (MD->isCopyAssignmentOperator())
6748
6749 if (MD->isMoveAssignmentOperator())
6751
6752 if (isa<CXXDestructorDecl>(FD))
6754 }
6755
6756 switch (FD->getDeclName().getCXXOverloadedOperator()) {
6757 case OO_EqualEqual:
6759
6760 case OO_ExclaimEqual:
6762
6763 case OO_Spaceship:
6764 // No point allowing this if <=> doesn't exist in the current language mode.
6765 if (!getLangOpts().CPlusPlus20)
6766 break;
6768
6769 case OO_Less:
6770 case OO_LessEqual:
6771 case OO_Greater:
6772 case OO_GreaterEqual:
6773 // No point allowing this if <=> doesn't exist in the current language mode.
6774 if (!getLangOpts().CPlusPlus20)
6775 break;
6777
6778 default:
6779 break;
6780 }
6781
6782 // Not defaultable.
6783 return DefaultedFunctionKind();
6784}
6785
6787 SourceLocation DefaultLoc) {
6789 if (DFK.isComparison())
6790 return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison());
6791
6792 switch (DFK.asSpecialMember()) {
6795 cast<CXXConstructorDecl>(FD));
6796 break;
6798 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6799 break;
6801 S.DefineImplicitCopyAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6802 break;
6804 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(FD));
6805 break;
6807 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6808 break;
6810 S.DefineImplicitMoveAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6811 break;
6813 llvm_unreachable("Invalid special member.");
6814 }
6815}
6816
6817/// Determine whether a type is permitted to be passed or returned in
6818/// registers, per C++ [class.temporary]p3.
6821 if (D->isDependentType() || D->isInvalidDecl())
6822 return false;
6823
6824 // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
6825 // The PS4 platform ABI follows the behavior of Clang 3.2.
6827 return !D->hasNonTrivialDestructorForCall() &&
6829
6830 if (CCK == TargetInfo::CCK_MicrosoftWin64) {
6831 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
6832 bool DtorIsTrivialForCall = false;
6833
6834 // If a class has at least one eligible, trivial copy constructor, it
6835 // is passed according to the C ABI. Otherwise, it is passed indirectly.
6836 //
6837 // Note: This permits classes with non-trivial copy or move ctors to be
6838 // passed in registers, so long as they *also* have a trivial copy ctor,
6839 // which is non-conforming.
6843 CopyCtorIsTrivial = true;
6845 CopyCtorIsTrivialForCall = true;
6846 }
6847 } else {
6848 for (const CXXConstructorDecl *CD : D->ctors()) {
6849 if (CD->isCopyConstructor() && !CD->isDeleted() &&
6850 !CD->isIneligibleOrNotSelected()) {
6851 if (CD->isTrivial())
6852 CopyCtorIsTrivial = true;
6853 if (CD->isTrivialForCall())
6854 CopyCtorIsTrivialForCall = true;
6855 }
6856 }
6857 }
6858
6859 if (D->needsImplicitDestructor()) {
6860 if (!D->defaultedDestructorIsDeleted() &&
6862 DtorIsTrivialForCall = true;
6863 } else if (const auto *DD = D->getDestructor()) {
6864 if (!DD->isDeleted() && DD->isTrivialForCall())
6865 DtorIsTrivialForCall = true;
6866 }
6867
6868 // If the copy ctor and dtor are both trivial-for-calls, pass direct.
6869 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
6870 return true;
6871
6872 // If a class has a destructor, we'd really like to pass it indirectly
6873 // because it allows us to elide copies. Unfortunately, MSVC makes that
6874 // impossible for small types, which it will pass in a single register or
6875 // stack slot. Most objects with dtors are large-ish, so handle that early.
6876 // We can't call out all large objects as being indirect because there are
6877 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
6878 // how we pass large POD types.
6879
6880 // Note: This permits small classes with nontrivial destructors to be
6881 // passed in registers, which is non-conforming.
6882 bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
6883 uint64_t TypeSize = isAArch64 ? 128 : 64;
6884
6885 if (CopyCtorIsTrivial &&
6886 S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize)
6887 return true;
6888 return false;
6889 }
6890
6891 // Per C++ [class.temporary]p3, the relevant condition is:
6892 // each copy constructor, move constructor, and destructor of X is
6893 // either trivial or deleted, and X has at least one non-deleted copy
6894 // or move constructor
6895 bool HasNonDeletedCopyOrMove = false;
6896
6900 return false;
6901 HasNonDeletedCopyOrMove = true;
6902 }
6903
6904 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
6907 return false;
6908 HasNonDeletedCopyOrMove = true;
6909 }
6910
6913 return false;
6914
6915 for (const CXXMethodDecl *MD : D->methods()) {
6916 if (MD->isDeleted() || MD->isIneligibleOrNotSelected())
6917 continue;
6918
6919 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6920 if (CD && CD->isCopyOrMoveConstructor())
6921 HasNonDeletedCopyOrMove = true;
6922 else if (!isa<CXXDestructorDecl>(MD))
6923 continue;
6924
6925 if (!MD->isTrivialForCall())
6926 return false;
6927 }
6928
6929 return HasNonDeletedCopyOrMove;
6930}
6931
6932/// Report an error regarding overriding, along with any relevant
6933/// overridden methods.
6934///
6935/// \param DiagID the primary error to report.
6936/// \param MD the overriding method.
6937static bool
6938ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD,
6939 llvm::function_ref<bool(const CXXMethodDecl *)> Report) {
6940 bool IssuedDiagnostic = false;
6941 for (const CXXMethodDecl *O : MD->overridden_methods()) {
6942 if (Report(O)) {
6943 if (!IssuedDiagnostic) {
6944 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6945 IssuedDiagnostic = true;
6946 }
6947 S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
6948 }
6949 }
6950 return IssuedDiagnostic;
6951}
6952
6953/// Perform semantic checks on a class definition that has been
6954/// completing, introducing implicitly-declared members, checking for
6955/// abstract types, etc.
6956///
6957/// \param S The scope in which the class was parsed. Null if we didn't just
6958/// parse a class definition.
6959/// \param Record The completed class.
6961 if (!Record)
6962 return;
6963
6964 if (Record->isAbstract() && !Record->isInvalidDecl()) {
6965 AbstractUsageInfo Info(*this, Record);
6967 }
6968
6969 // If this is not an aggregate type and has no user-declared constructor,
6970 // complain about any non-static data members of reference or const scalar
6971 // type, since they will never get initializers.
6972 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
6973 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
6974 !Record->isLambda()) {
6975 bool Complained = false;
6976 for (const auto *F : Record->fields()) {
6977 if (F->hasInClassInitializer() || F->isUnnamedBitField())
6978 continue;
6979
6980 if (F->getType()->isReferenceType() ||
6981 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
6982 if (!Complained) {
6983 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
6984 << llvm::to_underlying(Record->getTagKind()) << Record;
6985 Complained = true;
6986 }
6987
6988 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
6989 << F->getType()->isReferenceType()
6990 << F->getDeclName();
6991 }
6992 }
6993 }
6994
6995 if (Record->getIdentifier()) {
6996 // C++ [class.mem]p13:
6997 // If T is the name of a class, then each of the following shall have a
6998 // name different from T:
6999 // - every member of every anonymous union that is a member of class T.
7000 //
7001 // C++ [class.mem]p14:
7002 // In addition, if class T has a user-declared constructor (12.1), every
7003 // non-static data member of class T shall have a name different from T.
7004 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
7005 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
7006 ++I) {
7007 NamedDecl *D = (*I)->getUnderlyingDecl();
7008 if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
7009 Record->hasUserDeclaredConstructor()) ||
7010 isa<IndirectFieldDecl>(D)) {
7011 Diag((*I)->getLocation(), diag::err_member_name_of_class)
7012 << D->getDeclName();
7013 break;
7014 }
7015 }
7016 }
7017
7018 // Warn if the class has virtual methods but non-virtual public destructor.
7019 if (Record->isPolymorphic() && !Record->isDependentType()) {
7020 CXXDestructorDecl *dtor = Record->getDestructor();
7021 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
7022 !Record->hasAttr<FinalAttr>())
7023 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
7024 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
7025 }
7026
7027 if (Record->isAbstract()) {
7028 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
7029 Diag(Record->getLocation(), diag::warn_abstract_final_class)
7030 << FA->isSpelledAsSealed();
7032 }
7033 }
7034
7035 // Warn if the class has a final destructor but is not itself marked final.
7036 if (!Record->hasAttr<FinalAttr>()) {
7037 if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
7038 if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
7039 Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class)
7040 << FA->isSpelledAsSealed()
7042 getLocForEndOfToken(Record->getLocation()),
7043 (FA->isSpelledAsSealed() ? " sealed" : " final"));
7044 Diag(Record->getLocation(),
7045 diag::note_final_dtor_non_final_class_silence)
7046 << Context.getRecordType(Record) << FA->isSpelledAsSealed();
7047 }
7048 }
7049 }
7050
7051 // See if trivial_abi has to be dropped.
7052 if (Record->hasAttr<TrivialABIAttr>())
7054
7055 // Set HasTrivialSpecialMemberForCall if the record has attribute
7056 // "trivial_abi".
7057 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
7058
7059 if (HasTrivialABI)
7060 Record->setHasTrivialSpecialMemberForCall();
7061
7062 // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=).
7063 // We check these last because they can depend on the properties of the
7064 // primary comparison functions (==, <=>).
7065 llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons;
7066
7067 // Perform checks that can't be done until we know all the properties of a
7068 // member function (whether it's defaulted, deleted, virtual, overriding,
7069 // ...).
7070 auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) {
7071 // A static function cannot override anything.
7072 if (MD->getStorageClass() == SC_Static) {
7073 if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD,
7074 [](const CXXMethodDecl *) { return true; }))
7075 return;
7076 }
7077
7078 // A deleted function cannot override a non-deleted function and vice
7079 // versa.
7080 if (ReportOverrides(*this,
7081 MD->isDeleted() ? diag::err_deleted_override
7082 : diag::err_non_deleted_override,
7083 MD, [&](const CXXMethodDecl *V) {
7084 return MD->isDeleted() != V->isDeleted();
7085 })) {
7086 if (MD->isDefaulted() && MD->isDeleted())
7087 // Explain why this defaulted function was deleted.
7089 return;
7090 }
7091
7092 // A consteval function cannot override a non-consteval function and vice
7093 // versa.
7094 if (ReportOverrides(*this,
7095 MD->isConsteval() ? diag::err_consteval_override
7096 : diag::err_non_consteval_override,
7097 MD, [&](const CXXMethodDecl *V) {
7098 return MD->isConsteval() != V->isConsteval();
7099 })) {
7100 if (MD->isDefaulted() && MD->isDeleted())
7101 // Explain why this defaulted function was deleted.
7103 return;
7104 }
7105 };
7106
7107 auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool {
7108 if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted())
7109 return false;
7110
7114 DefaultedSecondaryComparisons.push_back(FD);
7115 return true;
7116 }
7117
7119 return false;
7120 };
7121
7122 auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
7123 // Check whether the explicitly-defaulted members are valid.
7124 bool Incomplete = CheckForDefaultedFunction(M);
7125
7126 // Skip the rest of the checks for a member of a dependent class.
7127 if (Record->isDependentType())
7128 return;
7129
7130 // For an explicitly defaulted or deleted special member, we defer
7131 // determining triviality until the class is complete. That time is now!
7133 if (!M->isImplicit() && !M->isUserProvided()) {
7134 if (CSM != CXXSpecialMemberKind::Invalid) {
7135 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
7136 // Inform the class that we've finished declaring this member.
7137 Record->finishedDefaultedOrDeletedMember(M);
7138 M->setTrivialForCall(
7139 HasTrivialABI ||
7141 Record->setTrivialForCallFlags(M);
7142 }
7143 }
7144
7145 // Set triviality for the purpose of calls if this is a user-provided
7146 // copy/move constructor or destructor.
7150 M->isUserProvided()) {
7151 M->setTrivialForCall(HasTrivialABI);
7152 Record->setTrivialForCallFlags(M);
7153 }
7154
7155 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
7156 M->hasAttr<DLLExportAttr>()) {
7157 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
7158 M->isTrivial() &&
7162 M->dropAttr<DLLExportAttr>();
7163
7164 if (M->hasAttr<DLLExportAttr>()) {
7165 // Define after any fields with in-class initializers have been parsed.
7167 }
7168 }
7169
7170 // Define defaulted constexpr virtual functions that override a base class
7171 // function right away.
7172 // FIXME: We can defer doing this until the vtable is marked as used.
7173 if (CSM != CXXSpecialMemberKind::Invalid && !M->isDeleted() &&
7174 M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods())
7175 DefineDefaultedFunction(*this, M, M->getLocation());
7176
7177 if (!Incomplete)
7178 CheckCompletedMemberFunction(M);
7179 };
7180
7181 // Check the destructor before any other member function. We need to
7182 // determine whether it's trivial in order to determine whether the claas
7183 // type is a literal type, which is a prerequisite for determining whether
7184 // other special member functions are valid and whether they're implicitly
7185 // 'constexpr'.
7186 if (CXXDestructorDecl *Dtor = Record->getDestructor())
7187 CompleteMemberFunction(Dtor);
7188
7189 bool HasMethodWithOverrideControl = false,
7190 HasOverridingMethodWithoutOverrideControl = false;
7191 for (auto *D : Record->decls()) {
7192 if (auto *M = dyn_cast<CXXMethodDecl>(D)) {
7193 // FIXME: We could do this check for dependent types with non-dependent
7194 // bases.
7195 if (!Record->isDependentType()) {
7196 // See if a method overloads virtual methods in a base
7197 // class without overriding any.
7198 if (!M->isStatic())
7200 if (M->hasAttr<OverrideAttr>())
7201 HasMethodWithOverrideControl = true;
7202 else if (M->size_overridden_methods() > 0)
7203 HasOverridingMethodWithoutOverrideControl = true;
7204 }
7205
7206 if (!isa<CXXDestructorDecl>(M))
7207 CompleteMemberFunction(M);
7208 } else if (auto *F = dyn_cast<FriendDecl>(D)) {
7209 CheckForDefaultedFunction(
7210 dyn_cast_or_null<FunctionDecl>(F->getFriendDecl()));
7211 }
7212 }
7213
7214 if (HasOverridingMethodWithoutOverrideControl) {
7215 bool HasInconsistentOverrideControl = HasMethodWithOverrideControl;
7216 for (auto *M : Record->methods())
7217 DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl);
7218 }
7219
7220 // Check the defaulted secondary comparisons after any other member functions.
7221 for (FunctionDecl *FD : DefaultedSecondaryComparisons) {
7223
7224 // If this is a member function, we deferred checking it until now.
7225 if (auto *MD = dyn_cast<CXXMethodDecl>(FD))
7226 CheckCompletedMemberFunction(MD);
7227 }
7228
7229 // ms_struct is a request to use the same ABI rules as MSVC. Check
7230 // whether this class uses any C++ features that are implemented
7231 // completely differently in MSVC, and if so, emit a diagnostic.
7232 // That diagnostic defaults to an error, but we allow projects to
7233 // map it down to a warning (or ignore it). It's a fairly common
7234 // practice among users of the ms_struct pragma to mass-annotate
7235 // headers, sweeping up a bunch of types that the project doesn't
7236 // really rely on MSVC-compatible layout for. We must therefore
7237 // support "ms_struct except for C++ stuff" as a secondary ABI.
7238 // Don't emit this diagnostic if the feature was enabled as a
7239 // language option (as opposed to via a pragma or attribute), as
7240 // the option -mms-bitfields otherwise essentially makes it impossible
7241 // to build C++ code, unless this diagnostic is turned off.
7242 if (Record->isMsStruct(Context) && !Context.getLangOpts().MSBitfields &&
7243 (Record->isPolymorphic() || Record->getNumBases())) {
7244 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
7245 }
7246
7249
7250 bool ClangABICompat4 =
7251 Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
7253 Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
7254 bool CanPass = canPassInRegisters(*this, Record, CCK);
7255
7256 // Do not change ArgPassingRestrictions if it has already been set to
7257 // RecordArgPassingKind::CanNeverPassInRegs.
7258 if (Record->getArgPassingRestrictions() !=
7260 Record->setArgPassingRestrictions(
7263
7264 // If canPassInRegisters returns true despite the record having a non-trivial
7265 // destructor, the record is destructed in the callee. This happens only when
7266 // the record or one of its subobjects has a field annotated with trivial_abi
7267 // or a field qualified with ObjC __strong/__weak.
7269 Record->setParamDestroyedInCallee(true);
7270 else if (Record->hasNonTrivialDestructor())
7271 Record->setParamDestroyedInCallee(CanPass);
7272
7273 if (getLangOpts().ForceEmitVTables) {
7274 // If we want to emit all the vtables, we need to mark it as used. This
7275 // is especially required for cases like vtable assumption loads.
7276 MarkVTableUsed(Record->getInnerLocStart(), Record);
7277 }
7278
7279 if (getLangOpts().CUDA) {
7280 if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>())
7282 else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>())
7284 }
7285}
7286
7287/// Look up the special member function that would be called by a special
7288/// member function for a subobject of class type.
7289///
7290/// \param Class The class type of the subobject.
7291/// \param CSM The kind of special member function.
7292/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
7293/// \param ConstRHS True if this is a copy operation with a const object
7294/// on its RHS, that is, if the argument to the outer special member
7295/// function is 'const' and this is not a field marked 'mutable'.
7298 CXXSpecialMemberKind CSM, unsigned FieldQuals,
7299 bool ConstRHS) {
7300 unsigned LHSQuals = 0;
7303 LHSQuals = FieldQuals;
7304
7305 unsigned RHSQuals = FieldQuals;
7308 RHSQuals = 0;
7309 else if (ConstRHS)
7310 RHSQuals |= Qualifiers::Const;
7311
7312 return S.LookupSpecialMember(Class, CSM,
7313 RHSQuals & Qualifiers::Const,
7314 RHSQuals & Qualifiers::Volatile,
7315 false,
7316 LHSQuals & Qualifiers::Const,
7317 LHSQuals & Qualifiers::Volatile);
7318}
7319
7321 Sema &S;
7322 SourceLocation UseLoc;
7323
7324 /// A mapping from the base classes through which the constructor was
7325 /// inherited to the using shadow declaration in that base class (or a null
7326 /// pointer if the constructor was declared in that base class).
7327 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
7328 InheritedFromBases;
7329
7330public:
7333 : S(S), UseLoc(UseLoc) {
7334 bool DiagnosedMultipleConstructedBases = false;
7335 CXXRecordDecl *ConstructedBase = nullptr;
7336 BaseUsingDecl *ConstructedBaseIntroducer = nullptr;
7337
7338 // Find the set of such base class subobjects and check that there's a
7339 // unique constructed subobject.
7340 for (auto *D : Shadow->redecls()) {
7341 auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
7342 auto *DNominatedBase = DShadow->getNominatedBaseClass();
7343 auto *DConstructedBase = DShadow->getConstructedBaseClass();
7344
7345 InheritedFromBases.insert(
7346 std::make_pair(DNominatedBase->getCanonicalDecl(),
7347 DShadow->getNominatedBaseClassShadowDecl()));
7348 if (DShadow->constructsVirtualBase())
7349 InheritedFromBases.insert(
7350 std::make_pair(DConstructedBase->getCanonicalDecl(),
7351 DShadow->getConstructedBaseClassShadowDecl()));
7352 else
7353 assert(DNominatedBase == DConstructedBase);
7354
7355 // [class.inhctor.init]p2:
7356 // If the constructor was inherited from multiple base class subobjects
7357 // of type B, the program is ill-formed.
7358 if (!ConstructedBase) {
7359 ConstructedBase = DConstructedBase;
7360 ConstructedBaseIntroducer = D->getIntroducer();
7361 } else if (ConstructedBase != DConstructedBase &&
7362 !Shadow->isInvalidDecl()) {
7363 if (!DiagnosedMultipleConstructedBases) {
7364 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
7365 << Shadow->getTargetDecl();
7366 S.Diag(ConstructedBaseIntroducer->getLocation(),
7367 diag::note_ambiguous_inherited_constructor_using)
7368 << ConstructedBase;
7369 DiagnosedMultipleConstructedBases = true;
7370 }
7371 S.Diag(D->getIntroducer()->getLocation(),
7372 diag::note_ambiguous_inherited_constructor_using)
7373 << DConstructedBase;
7374 }
7375 }
7376
7377 if (DiagnosedMultipleConstructedBases)
7378 Shadow->setInvalidDecl();
7379 }
7380
7381 /// Find the constructor to use for inherited construction of a base class,
7382 /// and whether that base class constructor inherits the constructor from a
7383 /// virtual base class (in which case it won't actually invoke it).
7384 std::pair<CXXConstructorDecl *, bool>
7386 auto It = InheritedFromBases.find(Base->getCanonicalDecl());
7387 if (It == InheritedFromBases.end())
7388 return std::make_pair(nullptr, false);
7389
7390 // This is an intermediary class.
7391 if (It->second)
7392 return std::make_pair(
7393 S.findInheritingConstructor(UseLoc, Ctor, It->second),
7394 It->second->constructsVirtualBase());
7395
7396 // This is the base class from which the constructor was inherited.
7397 return std::make_pair(Ctor, false);
7398 }
7399};
7400
7401/// Is the special member function which would be selected to perform the
7402/// specified operation on the specified class type a constexpr constructor?
7404 Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, unsigned Quals,
7405 bool ConstRHS, CXXConstructorDecl *InheritedCtor = nullptr,
7406 Sema::InheritedConstructorInfo *Inherited = nullptr) {
7407 // Suppress duplicate constraint checking here, in case a constraint check
7408 // caused us to decide to do this. Any truely recursive checks will get
7409 // caught during these checks anyway.
7411
7412 // If we're inheriting a constructor, see if we need to call it for this base
7413 // class.
7414 if (InheritedCtor) {
7416 auto BaseCtor =
7417 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
7418 if (BaseCtor)
7419 return BaseCtor->isConstexpr();
7420 }
7421
7423 return ClassDecl->hasConstexprDefaultConstructor();
7425 return ClassDecl->hasConstexprDestructor();
7426
7428 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
7429 if (!SMOR.getMethod())
7430 // A constructor we wouldn't select can't be "involved in initializing"
7431 // anything.
7432 return true;
7433 return SMOR.getMethod()->isConstexpr();
7434}
7435
7436/// Determine whether the specified special member function would be constexpr
7437/// if it were implicitly defined.
7439 Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, bool ConstArg,
7440 CXXConstructorDecl *InheritedCtor = nullptr,
7441 Sema::InheritedConstructorInfo *Inherited = nullptr) {
7442 if (!S.getLangOpts().CPlusPlus11)
7443 return false;
7444
7445 // C++11 [dcl.constexpr]p4:
7446 // In the definition of a constexpr constructor [...]
7447 bool Ctor = true;
7448 switch (CSM) {
7450 if (Inherited)
7451 break;
7452 // Since default constructor lookup is essentially trivial (and cannot
7453 // involve, for instance, template instantiation), we compute whether a
7454 // defaulted default constructor is constexpr directly within CXXRecordDecl.
7455 //
7456 // This is important for performance; we need to know whether the default
7457 // constructor is constexpr to determine whether the type is a literal type.
7458 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
7459
7462 // For copy or move constructors, we need to perform overload resolution.
7463 break;
7464
7467 if (!S.getLangOpts().CPlusPlus14)
7468 return false;
7469 // In C++1y, we need to perform overload resolution.
7470 Ctor = false;
7471 break;
7472
7474 return ClassDecl->defaultedDestructorIsConstexpr();
7475
7477 return false;
7478 }
7479
7480 // -- if the class is a non-empty union, or for each non-empty anonymous
7481 // union member of a non-union class, exactly one non-static data member
7482 // shall be initialized; [DR1359]
7483 //
7484 // If we squint, this is guaranteed, since exactly one non-static data member
7485 // will be initialized (if the constructor isn't deleted), we just don't know
7486 // which one.
7487 if (Ctor && ClassDecl->isUnion())
7489 ? ClassDecl->hasInClassInitializer() ||
7490 !ClassDecl->hasVariantMembers()
7491 : true;
7492
7493 // -- the class shall not have any virtual base classes;
7494 if (Ctor && ClassDecl->getNumVBases())
7495 return false;
7496
7497 // C++1y [class.copy]p26:
7498 // -- [the class] is a literal type, and
7499 if (!Ctor && !ClassDecl->isLiteral() && !S.getLangOpts().CPlusPlus23)
7500 return false;
7501
7502 // -- every constructor involved in initializing [...] base class
7503 // sub-objects shall be a constexpr constructor;
7504 // -- the assignment operator selected to copy/move each direct base
7505 // class is a constexpr function, and
7506 if (!S.getLangOpts().CPlusPlus23) {
7507 for (const auto &B : ClassDecl->bases()) {
7508 const RecordType *BaseType = B.getType()->getAs<RecordType>();
7509 if (!BaseType)
7510 continue;
7511 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7512 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
7513 InheritedCtor, Inherited))
7514 return false;
7515 }
7516 }
7517
7518 // -- every constructor involved in initializing non-static data members
7519 // [...] shall be a constexpr constructor;
7520 // -- every non-static data member and base class sub-object shall be
7521 // initialized
7522 // -- for each non-static data member of X that is of class type (or array
7523 // thereof), the assignment operator selected to copy/move that member is
7524 // a constexpr function
7525 if (!S.getLangOpts().CPlusPlus23) {
7526 for (const auto *F : ClassDecl->fields()) {
7527 if (F->isInvalidDecl())
7528 continue;
7530 F->hasInClassInitializer())
7531 continue;
7532 QualType BaseType = S.Context.getBaseElementType(F->getType());
7533 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
7534 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7535 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
7536 BaseType.getCVRQualifiers(),
7537 ConstArg && !F->isMutable()))
7538 return false;
7539 } else if (CSM == CXXSpecialMemberKind::DefaultConstructor) {
7540 return false;
7541 }
7542 }
7543 }
7544
7545 // All OK, it's constexpr!
7546 return true;
7547}
7548
7549namespace {
7550/// RAII object to register a defaulted function as having its exception
7551/// specification computed.
7552struct ComputingExceptionSpec {
7553 Sema &S;
7554
7555 ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc)
7556 : S(S) {
7560 Ctx.Entity = FD;
7562 }
7563 ~ComputingExceptionSpec() {
7565 }
7566};
7567}
7568
7571 CXXMethodDecl *MD,
7574
7577 FunctionDecl *FD,
7579
7582 auto DFK = S.getDefaultedFunctionKind(FD);
7583 if (DFK.isSpecialMember())
7585 S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr);
7586 if (DFK.isComparison())
7588 DFK.asComparison());
7589
7590 auto *CD = cast<CXXConstructorDecl>(FD);
7591 assert(CD->getInheritedConstructor() &&
7592 "only defaulted functions and inherited constructors have implicit "
7593 "exception specs");
7595 S, Loc, CD->getInheritedConstructor().getShadowDecl());
7598}
7599
7601 CXXMethodDecl *MD) {
7603
7604 // Build an exception specification pointing back at this member.
7606 EPI.ExceptionSpec.SourceDecl = MD;
7607
7608 // Set the calling convention to the default for C++ instance methods.
7610 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
7611 /*IsCXXMethod=*/true));
7612 return EPI;
7613}
7614
7616 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
7618 return;
7619
7620 // Evaluate the exception specification.
7621 auto IES = computeImplicitExceptionSpec(*this, Loc, FD);
7622 auto ESI = IES.getExceptionSpec();
7623
7624 // Update the type of the special member to use it.
7625 UpdateExceptionSpec(FD, ESI);
7626}
7627
7629 assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted");
7630
7632 if (!DefKind) {
7633 assert(FD->getDeclContext()->isDependentContext());
7634 return;
7635 }
7636
7637 if (DefKind.isComparison())
7638 UnusedPrivateFields.clear();
7639
7640 if (DefKind.isSpecialMember()
7641 ? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD),
7642 DefKind.asSpecialMember(),
7643 FD->getDefaultLoc())
7645 FD->setInvalidDecl();
7646}
7647
7650 SourceLocation DefaultLoc) {
7651 CXXRecordDecl *RD = MD->getParent();
7652
7654 "not an explicitly-defaulted special member");
7655
7656 // Defer all checking for special members of a dependent type.
7657 if (RD->isDependentType())
7658 return false;
7659
7660 // Whether this was the first-declared instance of the constructor.
7661 // This affects whether we implicitly add an exception spec and constexpr.
7662 bool First = MD == MD->getCanonicalDecl();
7663
7664 bool HadError = false;
7665
7666 // C++11 [dcl.fct.def.default]p1:
7667 // A function that is explicitly defaulted shall
7668 // -- be a special member function [...] (checked elsewhere),
7669 // -- have the same type (except for ref-qualifiers, and except that a
7670 // copy operation can take a non-const reference) as an implicit
7671 // declaration, and
7672 // -- not have default arguments.
7673 // C++2a changes the second bullet to instead delete the function if it's
7674 // defaulted on its first declaration, unless it's "an assignment operator,
7675 // and its return type differs or its parameter type is not a reference".
7676 bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First;
7677 bool ShouldDeleteForTypeMismatch = false;
7678 unsigned ExpectedParams = 1;
7681 ExpectedParams = 0;
7682 if (MD->getNumExplicitParams() != ExpectedParams) {
7683 // This checks for default arguments: a copy or move constructor with a
7684 // default argument is classified as a default constructor, and assignment
7685 // operations and destructors can't have default arguments.
7686 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
7687 << llvm::to_underlying(CSM) << MD->getSourceRange();
7688 HadError = true;
7689 } else if (MD->isVariadic()) {
7690 if (DeleteOnTypeMismatch)
7691 ShouldDeleteForTypeMismatch = true;
7692 else {
7693 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
7694 << llvm::to_underlying(CSM) << MD->getSourceRange();
7695 HadError = true;
7696 }
7697 }
7698
7700
7701 bool CanHaveConstParam = false;
7703 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
7705 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
7706
7707 QualType ReturnType = Context.VoidTy;
7710 // Check for return type matching.
7711 ReturnType = Type->getReturnType();
7713
7714 QualType DeclType = Context.getTypeDeclType(RD);
7716 DeclType, nullptr);
7717 DeclType = Context.getAddrSpaceQualType(
7718 DeclType, ThisType.getQualifiers().getAddressSpace());
7719 QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
7720
7721 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
7722 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
7724 << ExpectedReturnType;
7725 HadError = true;
7726 }
7727
7728 // A defaulted special member cannot have cv-qualifiers.
7729 if (ThisType.isConstQualified() || ThisType.isVolatileQualified()) {
7730 if (DeleteOnTypeMismatch)
7731 ShouldDeleteForTypeMismatch = true;
7732 else {
7733 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
7735 << getLangOpts().CPlusPlus14;
7736 HadError = true;
7737 }
7738 }
7739 // [C++23][dcl.fct.def.default]/p2.2
7740 // if F2 has an implicit object parameter of type “reference to C”,
7741 // F1 may be an explicit object member function whose explicit object
7742 // parameter is of (possibly different) type “reference to C”,
7743 // in which case the type of F1 would differ from the type of F2
7744 // in that the type of F1 has an additional parameter;
7745 if (!Context.hasSameType(
7747 Context.getRecordType(RD))) {
7748 if (DeleteOnTypeMismatch)
7749 ShouldDeleteForTypeMismatch = true;
7750 else {
7751 Diag(MD->getLocation(),
7752 diag::err_defaulted_special_member_explicit_object_mismatch)
7753 << (CSM == CXXSpecialMemberKind::MoveAssignment) << RD
7754 << MD->getSourceRange();
7755 HadError = true;
7756 }
7757 }
7758 }
7759
7760 // Check for parameter type matching.
7761 QualType ArgType =
7762 ExpectedParams
7763 ? Type->getParamType(MD->isExplicitObjectMemberFunction() ? 1 : 0)
7764 : QualType();
7765 bool HasConstParam = false;
7766 if (ExpectedParams && ArgType->isReferenceType()) {
7767 // Argument must be reference to possibly-const T.
7768 QualType ReferentType = ArgType->getPointeeType();
7769 HasConstParam = ReferentType.isConstQualified();
7770
7771 if (ReferentType.isVolatileQualified()) {
7772 if (DeleteOnTypeMismatch)
7773 ShouldDeleteForTypeMismatch = true;
7774 else {
7775 Diag(MD->getLocation(),
7776 diag::err_defaulted_special_member_volatile_param)
7777 << llvm::to_underlying(CSM);
7778 HadError = true;
7779 }
7780 }
7781
7782 if (HasConstParam && !CanHaveConstParam) {
7783 if (DeleteOnTypeMismatch)
7784 ShouldDeleteForTypeMismatch = true;
7785 else if (CSM == CXXSpecialMemberKind::CopyConstructor ||
7787 Diag(MD->getLocation(),
7788 diag::err_defaulted_special_member_copy_const_param)
7790 // FIXME: Explain why this special member can't be const.
7791 HadError = true;
7792 } else {
7793 Diag(MD->getLocation(),
7794 diag::err_defaulted_special_member_move_const_param)
7796 HadError = true;
7797 }
7798 }
7799 } else if (ExpectedParams) {
7800 // A copy assignment operator can take its argument by value, but a
7801 // defaulted one cannot.
7803 "unexpected non-ref argument");
7804 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
7805 HadError = true;
7806 }
7807
7808 // C++11 [dcl.fct.def.default]p2:
7809 // An explicitly-defaulted function may be declared constexpr only if it
7810 // would have been implicitly declared as constexpr,
7811 // Do not apply this rule to members of class templates, since core issue 1358
7812 // makes such functions always instantiate to constexpr functions. For
7813 // functions which cannot be constexpr (for non-constructors in C++11 and for
7814 // destructors in C++14 and C++17), this is checked elsewhere.
7815 //
7816 // FIXME: This should not apply if the member is deleted.
7817 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
7818 HasConstParam);
7819
7820 // C++14 [dcl.constexpr]p6 (CWG DR647/CWG DR1358):
7821 // If the instantiated template specialization of a constexpr function
7822 // template or member function of a class template would fail to satisfy
7823 // the requirements for a constexpr function or constexpr constructor, that
7824 // specialization is still a constexpr function or constexpr constructor,
7825 // even though a call to such a function cannot appear in a constant
7826 // expression.
7827 if (MD->isTemplateInstantiation() && MD->isConstexpr())
7828 Constexpr = true;
7829
7830 if ((getLangOpts().CPlusPlus20 ||
7831 (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
7832 : isa<CXXConstructorDecl>(MD))) &&
7833 MD->isConstexpr() && !Constexpr &&
7835 if (!MD->isConsteval() && RD->getNumVBases()) {
7836 Diag(MD->getBeginLoc(),
7837 diag::err_incorrect_defaulted_constexpr_with_vb)
7838 << llvm::to_underlying(CSM);
7839 for (const auto &I : RD->vbases())
7840 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here);
7841 } else {
7842 Diag(MD->getBeginLoc(), diag::err_incorrect_defaulted_constexpr)
7843 << llvm::to_underlying(CSM) << MD->isConsteval();
7844 }
7845 HadError = true;
7846 // FIXME: Explain why the special member can't be constexpr.
7847 }
7848
7849 if (First) {
7850 // C++2a [dcl.fct.def.default]p3:
7851 // If a function is explicitly defaulted on its first declaration, it is
7852 // implicitly considered to be constexpr if the implicit declaration
7853 // would be.
7858
7859 if (!Type->hasExceptionSpec()) {
7860 // C++2a [except.spec]p3:
7861 // If a declaration of a function does not have a noexcept-specifier
7862 // [and] is defaulted on its first declaration, [...] the exception
7863 // specification is as specified below
7864 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
7866 EPI.ExceptionSpec.SourceDecl = MD;
7867 MD->setType(
7868 Context.getFunctionType(ReturnType, Type->getParamTypes(), EPI));
7869 }
7870 }
7871
7872 if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
7873 if (First) {
7874 SetDeclDeleted(MD, MD->getLocation());
7875 if (!inTemplateInstantiation() && !HadError) {
7876 Diag(MD->getLocation(), diag::warn_defaulted_method_deleted)
7877 << llvm::to_underlying(CSM);
7878 if (ShouldDeleteForTypeMismatch) {
7879 Diag(MD->getLocation(), diag::note_deleted_type_mismatch)
7880 << llvm::to_underlying(CSM);
7881 } else if (ShouldDeleteSpecialMember(MD, CSM, nullptr,
7882 /*Diagnose*/ true) &&
7883 DefaultLoc.isValid()) {
7884 Diag(DefaultLoc, diag::note_replace_equals_default_to_delete)
7885 << FixItHint::CreateReplacement(DefaultLoc, "delete");
7886 }
7887 }
7888 if (ShouldDeleteForTypeMismatch && !HadError) {
7889 Diag(MD->getLocation(),
7890 diag::warn_cxx17_compat_defaulted_method_type_mismatch)
7891 << llvm::to_underlying(CSM);
7892 }
7893 } else {
7894 // C++11 [dcl.fct.def.default]p4:
7895 // [For a] user-provided explicitly-defaulted function [...] if such a
7896 // function is implicitly defined as deleted, the program is ill-formed.
7897 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
7898 << llvm::to_underlying(CSM);
7899 assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
7900 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
7901 HadError = true;
7902 }
7903 }
7904
7905 return HadError;
7906}
7907
7908namespace {
7909/// Helper class for building and checking a defaulted comparison.
7910///
7911/// Defaulted functions are built in two phases:
7912///
7913/// * First, the set of operations that the function will perform are
7914/// identified, and some of them are checked. If any of the checked
7915/// operations is invalid in certain ways, the comparison function is
7916/// defined as deleted and no body is built.
7917/// * Then, if the function is not defined as deleted, the body is built.
7918///
7919/// This is accomplished by performing two visitation steps over the eventual
7920/// body of the function.
7921template<typename Derived, typename ResultList, typename Result,
7922 typename Subobject>
7923class DefaultedComparisonVisitor {
7924public:
7925 using DefaultedComparisonKind = Sema::DefaultedComparisonKind;
7926
7927 DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7928 DefaultedComparisonKind DCK)
7929 : S(S), RD(RD), FD(FD), DCK(DCK) {
7930 if (auto *Info = FD->getDefalutedOrDeletedInfo()) {
7931 // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an
7932 // UnresolvedSet to avoid this copy.
7933 Fns.assign(Info->getUnqualifiedLookups().begin(),
7934 Info->getUnqualifiedLookups().end());
7935 }
7936 }
7937
7938 ResultList visit() {
7939 // The type of an lvalue naming a parameter of this function.
7940 QualType ParamLvalType =
7942
7943 ResultList Results;
7944
7945 switch (DCK) {
7946 case DefaultedComparisonKind::None:
7947 llvm_unreachable("not a defaulted comparison");
7948
7949 case DefaultedComparisonKind::Equal:
7950 case DefaultedComparisonKind::ThreeWay:
7951 getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers());
7952 return Results;
7953
7954 case DefaultedComparisonKind::NotEqual:
7955 case DefaultedComparisonKind::Relational:
7956 Results.add(getDerived().visitExpandedSubobject(
7957 ParamLvalType, getDerived().getCompleteObject()));
7958 return Results;
7959 }
7960 llvm_unreachable("");
7961 }
7962
7963protected:
7964 Derived &getDerived() { return static_cast<Derived&>(*this); }
7965
7966 /// Visit the expanded list of subobjects of the given type, as specified in
7967 /// C++2a [class.compare.default].
7968 ///
7969 /// \return \c true if the ResultList object said we're done, \c false if not.
7970 bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record,
7971 Qualifiers Quals) {
7972 // C++2a [class.compare.default]p4:
7973 // The direct base class subobjects of C
7974 for (CXXBaseSpecifier &Base : Record->bases())
7975 if (Results.add(getDerived().visitSubobject(
7976 S.Context.getQualifiedType(Base.getType(), Quals),
7977 getDerived().getBase(&Base))))
7978 return true;
7979
7980 // followed by the non-static data members of C
7981 for (FieldDecl *Field : Record->fields()) {
7982 // C++23 [class.bit]p2:
7983 // Unnamed bit-fields are not members ...
7984 if (Field->isUnnamedBitField())
7985 continue;
7986 // Recursively expand anonymous structs.
7987 if (Field->isAnonymousStructOrUnion()) {
7988 if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(),
7989 Quals))
7990 return true;
7991 continue;
7992 }
7993
7994 // Figure out the type of an lvalue denoting this field.
7995 Qualifiers FieldQuals = Quals;
7996 if (Field->isMutable())
7997 FieldQuals.removeConst();
7998 QualType FieldType =
7999 S.Context.getQualifiedType(Field->getType(), FieldQuals);
8000
8001 if (Results.add(getDerived().visitSubobject(
8002 FieldType, getDerived().getField(Field))))
8003 return true;
8004 }
8005
8006 // form a list of subobjects.
8007 return false;
8008 }
8009
8010 Result visitSubobject(QualType Type, Subobject Subobj) {
8011 // In that list, any subobject of array type is recursively expanded
8012 const ArrayType *AT = S.Context.getAsArrayType(Type);
8013 if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT))
8014 return getDerived().visitSubobjectArray(CAT->getElementType(),
8015 CAT->getSize(), Subobj);
8016 return getDerived().visitExpandedSubobject(Type, Subobj);
8017 }
8018
8019 Result visitSubobjectArray(QualType Type, const llvm::APInt &Size,
8020 Subobject Subobj) {
8021 return getDerived().visitSubobject(Type, Subobj);
8022 }
8023
8024protected:
8025 Sema &S;
8026 CXXRecordDecl *RD;
8027 FunctionDecl *FD;
8028 DefaultedComparisonKind DCK;
8030};
8031
8032/// Information about a defaulted comparison, as determined by
8033/// DefaultedComparisonAnalyzer.
8034struct DefaultedComparisonInfo {
8035 bool Deleted = false;
8036 bool Constexpr = true;
8037 ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering;
8038
8039 static DefaultedComparisonInfo deleted() {
8040 DefaultedComparisonInfo Deleted;
8041 Deleted.Deleted = true;
8042 return Deleted;
8043 }
8044
8045 bool add(const DefaultedComparisonInfo &R) {
8046 Deleted |= R.Deleted;
8047 Constexpr &= R.Constexpr;
8048 Category = commonComparisonType(Category, R.Category);
8049 return Deleted;
8050 }
8051};
8052
8053/// An element in the expanded list of subobjects of a defaulted comparison, as
8054/// specified in C++2a [class.compare.default]p4.
8055struct DefaultedComparisonSubobject {
8056 enum { CompleteObject, Member, Base } Kind;
8057 NamedDecl *Decl;
8059};
8060
8061/// A visitor over the notional body of a defaulted comparison that determines
8062/// whether that body would be deleted or constexpr.
8063class DefaultedComparisonAnalyzer
8064 : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer,
8065 DefaultedComparisonInfo,
8066 DefaultedComparisonInfo,
8067 DefaultedComparisonSubobject> {
8068public:
8069 enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr };
8070
8071private:
8072 DiagnosticKind Diagnose;
8073
8074public:
8075 using Base = DefaultedComparisonVisitor;
8076 using Result = DefaultedComparisonInfo;
8077 using Subobject = DefaultedComparisonSubobject;
8078
8079 friend Base;
8080
8081 DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8082 DefaultedComparisonKind DCK,
8083 DiagnosticKind Diagnose = NoDiagnostics)
8084 : Base(S, RD, FD, DCK), Diagnose(Diagnose) {}
8085
8086 Result visit() {
8087 if ((DCK == DefaultedComparisonKind::Equal ||
8088 DCK == DefaultedComparisonKind::ThreeWay) &&
8089 RD->hasVariantMembers()) {
8090 // C++2a [class.compare.default]p2 [P2002R0]:
8091 // A defaulted comparison operator function for class C is defined as
8092 // deleted if [...] C has variant members.
8093 if (Diagnose == ExplainDeleted) {
8094 S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union)
8095 << FD << RD->isUnion() << RD;
8096 }
8097 return Result::deleted();
8098 }
8099
8100 return Base::visit();
8101 }
8102
8103private:
8104 Subobject getCompleteObject() {
8105 return Subobject{Subobject::CompleteObject, RD, FD->getLocation()};
8106 }
8107
8108 Subobject getBase(CXXBaseSpecifier *Base) {
8109 return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(),
8110 Base->getBaseTypeLoc()};
8111 }
8112
8113 Subobject getField(FieldDecl *Field) {
8114 return Subobject{Subobject::Member, Field, Field->getLocation()};
8115 }
8116
8117 Result visitExpandedSubobject(QualType Type, Subobject Subobj) {
8118 // C++2a [class.compare.default]p2 [P2002R0]:
8119 // A defaulted <=> or == operator function for class C is defined as
8120 // deleted if any non-static data member of C is of reference type
8121 if (Type->isReferenceType()) {
8122 if (Diagnose == ExplainDeleted) {
8123 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member)
8124 << FD << RD;
8125 }
8126 return Result::deleted();
8127 }
8128
8129 // [...] Let xi be an lvalue denoting the ith element [...]
8131 Expr *Args[] = {&Xi, &Xi};
8132
8133 // All operators start by trying to apply that same operator recursively.
8135 assert(OO != OO_None && "not an overloaded operator!");
8136 return visitBinaryOperator(OO, Args, Subobj);
8137 }
8138
8139 Result
8140 visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args,
8141 Subobject Subobj,
8142 OverloadCandidateSet *SpaceshipCandidates = nullptr) {
8143 // Note that there is no need to consider rewritten candidates here if
8144 // we've already found there is no viable 'operator<=>' candidate (and are
8145 // considering synthesizing a '<=>' from '==' and '<').
8146 OverloadCandidateSet CandidateSet(
8149 OO, FD->getLocation(),
8150 /*AllowRewrittenCandidates=*/!SpaceshipCandidates));
8151
8152 /// C++2a [class.compare.default]p1 [P2002R0]:
8153 /// [...] the defaulted function itself is never a candidate for overload
8154 /// resolution [...]
8155 CandidateSet.exclude(FD);
8156
8157 if (Args[0]->getType()->isOverloadableType())
8158 S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args);
8159 else
8160 // FIXME: We determine whether this is a valid expression by checking to
8161 // see if there's a viable builtin operator candidate for it. That isn't
8162 // really what the rules ask us to do, but should give the right results.
8163 S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet);
8164
8165 Result R;
8166
8168 switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) {
8169 case OR_Success: {
8170 // C++2a [class.compare.secondary]p2 [P2002R0]:
8171 // The operator function [...] is defined as deleted if [...] the
8172 // candidate selected by overload resolution is not a rewritten
8173 // candidate.
8174 if ((DCK == DefaultedComparisonKind::NotEqual ||
8175 DCK == DefaultedComparisonKind::Relational) &&
8176 !Best->RewriteKind) {
8177 if (Diagnose == ExplainDeleted) {
8178 if (Best->Function) {
8179 S.Diag(Best->Function->getLocation(),
8180 diag::note_defaulted_comparison_not_rewritten_callee)
8181 << FD;
8182 } else {
8183 assert(Best->Conversions.size() == 2 &&
8184 Best->Conversions[0].isUserDefined() &&
8185 "non-user-defined conversion from class to built-in "
8186 "comparison");
8187 S.Diag(Best->Conversions[0]
8188 .UserDefined.FoundConversionFunction.getDecl()
8189 ->getLocation(),
8190 diag::note_defaulted_comparison_not_rewritten_conversion)
8191 << FD;
8192 }
8193 }
8194 return Result::deleted();
8195 }
8196
8197 // Throughout C++2a [class.compare]: if overload resolution does not
8198 // result in a usable function, the candidate function is defined as
8199 // deleted. This requires that we selected an accessible function.
8200 //
8201 // Note that this only considers the access of the function when named
8202 // within the type of the subobject, and not the access path for any
8203 // derived-to-base conversion.
8204 CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl();
8205 if (ArgClass && Best->FoundDecl.getDecl() &&
8206 Best->FoundDecl.getDecl()->isCXXClassMember()) {
8207 QualType ObjectType = Subobj.Kind == Subobject::Member
8208 ? Args[0]->getType()
8209 : S.Context.getRecordType(RD);
8211 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc,
8212 Diagnose == ExplainDeleted
8213 ? S.PDiag(diag::note_defaulted_comparison_inaccessible)
8214 << FD << Subobj.Kind << Subobj.Decl
8215 : S.PDiag()))
8216 return Result::deleted();
8217 }
8218
8219 bool NeedsDeducing =
8220 OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType();
8221
8222 if (FunctionDecl *BestFD = Best->Function) {
8223 // C++2a [class.compare.default]p3 [P2002R0]:
8224 // A defaulted comparison function is constexpr-compatible if
8225 // [...] no overlod resolution performed [...] results in a
8226 // non-constexpr function.
8227 assert(!BestFD->isDeleted() && "wrong overload resolution result");
8228 // If it's not constexpr, explain why not.
8229 if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) {
8230 if (Subobj.Kind != Subobject::CompleteObject)
8231 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr)
8232 << Subobj.Kind << Subobj.Decl;
8233 S.Diag(BestFD->getLocation(),
8234 diag::note_defaulted_comparison_not_constexpr_here);
8235 // Bail out after explaining; we don't want any more notes.
8236 return Result::deleted();
8237 }
8238 R.Constexpr &= BestFD->isConstexpr();
8239
8240 if (NeedsDeducing) {
8241 // If any callee has an undeduced return type, deduce it now.
8242 // FIXME: It's not clear how a failure here should be handled. For
8243 // now, we produce an eager diagnostic, because that is forward
8244 // compatible with most (all?) other reasonable options.
8245 if (BestFD->getReturnType()->isUndeducedType() &&
8246 S.DeduceReturnType(BestFD, FD->getLocation(),
8247 /*Diagnose=*/false)) {
8248 // Don't produce a duplicate error when asked to explain why the
8249 // comparison is deleted: we diagnosed that when initially checking
8250 // the defaulted operator.
8251 if (Diagnose == NoDiagnostics) {
8252 S.Diag(
8253 FD->getLocation(),
8254 diag::err_defaulted_comparison_cannot_deduce_undeduced_auto)
8255 << Subobj.Kind << Subobj.Decl;
8256 S.Diag(
8257 Subobj.Loc,
8258 diag::note_defaulted_comparison_cannot_deduce_undeduced_auto)
8259 << Subobj.Kind << Subobj.Decl;
8260 S.Diag(BestFD->getLocation(),
8261 diag::note_defaulted_comparison_cannot_deduce_callee)
8262 << Subobj.Kind << Subobj.Decl;
8263 }
8264 return Result::deleted();
8265 }
8267 BestFD->getCallResultType());
8268 if (!Info) {
8269 if (Diagnose == ExplainDeleted) {
8270 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce)
8271 << Subobj.Kind << Subobj.Decl
8272 << BestFD->getCallResultType().withoutLocalFastQualifiers();
8273 S.Diag(BestFD->getLocation(),
8274 diag::note_defaulted_comparison_cannot_deduce_callee)
8275 << Subobj.Kind << Subobj.Decl;
8276 }
8277 return Result::deleted();
8278 }
8279 R.Category = Info->Kind;
8280 }
8281 } else {
8282 QualType T = Best->BuiltinParamTypes[0];
8283 assert(T == Best->BuiltinParamTypes[1] &&
8284 "builtin comparison for different types?");
8285 assert(Best->BuiltinParamTypes[2].isNull() &&
8286 "invalid builtin comparison");
8287
8288 if (NeedsDeducing) {
8289 std::optional<ComparisonCategoryType> Cat =
8291 assert(Cat && "no category for builtin comparison?");
8292 R.Category = *Cat;
8293 }
8294 }
8295
8296 // Note that we might be rewriting to a different operator. That call is
8297 // not considered until we come to actually build the comparison function.
8298 break;
8299 }
8300
8301 case OR_Ambiguous:
8302 if (Diagnose == ExplainDeleted) {
8303 unsigned Kind = 0;
8304 if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship)
8305 Kind = OO == OO_EqualEqual ? 1 : 2;
8306 CandidateSet.NoteCandidates(
8308 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous)
8309 << FD << Kind << Subobj.Kind << Subobj.Decl),
8310 S, OCD_AmbiguousCandidates, Args);
8311 }
8312 R = Result::deleted();
8313 break;
8314
8315 case OR_Deleted:
8316 if (Diagnose == ExplainDeleted) {
8317 if ((DCK == DefaultedComparisonKind::NotEqual ||
8318 DCK == DefaultedComparisonKind::Relational) &&
8319 !Best->RewriteKind) {
8320 S.Diag(Best->Function->getLocation(),
8321 diag::note_defaulted_comparison_not_rewritten_callee)
8322 << FD;
8323 } else {
8324 S.Diag(Subobj.Loc,
8325 diag::note_defaulted_comparison_calls_deleted)
8326 << FD << Subobj.Kind << Subobj.Decl;
8327 S.NoteDeletedFunction(Best->Function);
8328 }
8329 }
8330 R = Result::deleted();
8331 break;
8332
8334 // If there's no usable candidate, we're done unless we can rewrite a
8335 // '<=>' in terms of '==' and '<'.
8336 if (OO == OO_Spaceship &&
8338 // For any kind of comparison category return type, we need a usable
8339 // '==' and a usable '<'.
8340 if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj,
8341 &CandidateSet)))
8342 R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet));
8343 break;
8344 }
8345
8346 if (Diagnose == ExplainDeleted) {
8347 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function)
8348 << FD << (OO == OO_EqualEqual || OO == OO_ExclaimEqual)
8349 << Subobj.Kind << Subobj.Decl;
8350
8351 // For a three-way comparison, list both the candidates for the
8352 // original operator and the candidates for the synthesized operator.
8353 if (SpaceshipCandidates) {
8354 SpaceshipCandidates->NoteCandidates(
8355 S, Args,
8356 SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates,
8357 Args, FD->getLocation()));
8358 S.Diag(Subobj.Loc,
8359 diag::note_defaulted_comparison_no_viable_function_synthesized)
8360 << (OO == OO_EqualEqual ? 0 : 1);
8361 }
8362
8363 CandidateSet.NoteCandidates(
8364 S, Args,
8365 CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args,
8366 FD->getLocation()));
8367 }
8368 R = Result::deleted();
8369 break;
8370 }
8371
8372 return R;
8373 }
8374};
8375
8376/// A list of statements.
8377struct StmtListResult {
8378 bool IsInvalid = false;
8380
8381 bool add(const StmtResult &S) {
8382 IsInvalid |= S.isInvalid();
8383 if (IsInvalid)
8384 return true;
8385 Stmts.push_back(S.get());
8386 return false;
8387 }
8388};
8389
8390/// A visitor over the notional body of a defaulted comparison that synthesizes
8391/// the actual body.
8392class DefaultedComparisonSynthesizer
8393 : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer,
8394 StmtListResult, StmtResult,
8395 std::pair<ExprResult, ExprResult>> {
8397 unsigned ArrayDepth = 0;
8398
8399public:
8400 using Base = DefaultedComparisonVisitor;
8401 using ExprPair = std::pair<ExprResult, ExprResult>;
8402
8403 friend Base;
8404
8405 DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8406 DefaultedComparisonKind DCK,
8407 SourceLocation BodyLoc)
8408 : Base(S, RD, FD, DCK), Loc(BodyLoc) {}
8409
8410 /// Build a suitable function body for this defaulted comparison operator.
8411 StmtResult build() {
8412 Sema::CompoundScopeRAII CompoundScope(S);
8413
8414 StmtListResult Stmts = visit();
8415 if (Stmts.IsInvalid)
8416 return StmtError();
8417
8418 ExprResult RetVal;
8419 switch (DCK) {
8420 case DefaultedComparisonKind::None:
8421 llvm_unreachable("not a defaulted comparison");
8422
8423 case DefaultedComparisonKind::Equal: {
8424 // C++2a [class.eq]p3:
8425 // [...] compar[e] the corresponding elements [...] until the first
8426 // index i where xi == yi yields [...] false. If no such index exists,
8427 // V is true. Otherwise, V is false.
8428 //
8429 // Join the comparisons with '&&'s and return the result. Use a right
8430 // fold (traversing the conditions right-to-left), because that
8431 // short-circuits more naturally.
8432 auto OldStmts = std::move(Stmts.Stmts);
8433 Stmts.Stmts.clear();
8434 ExprResult CmpSoFar;
8435 // Finish a particular comparison chain.
8436 auto FinishCmp = [&] {
8437 if (Expr *Prior = CmpSoFar.get()) {
8438 // Convert the last expression to 'return ...;'
8439 if (RetVal.isUnset() && Stmts.Stmts.empty())
8440 RetVal = CmpSoFar;
8441 // Convert any prior comparison to 'if (!(...)) return false;'
8442 else if (Stmts.add(buildIfNotCondReturnFalse(Prior)))
8443 return true;
8444 CmpSoFar = ExprResult();
8445 }
8446 return false;
8447 };
8448 for (Stmt *EAsStmt : llvm::reverse(OldStmts)) {
8449 Expr *E = dyn_cast<Expr>(EAsStmt);
8450 if (!E) {
8451 // Found an array comparison.
8452 if (FinishCmp() || Stmts.add(EAsStmt))
8453 return StmtError();
8454 continue;
8455 }
8456
8457 if (CmpSoFar.isUnset()) {
8458 CmpSoFar = E;
8459 continue;
8460 }
8461 CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get());
8462 if (CmpSoFar.isInvalid())
8463 return StmtError();
8464 }
8465 if (FinishCmp())
8466 return StmtError();
8467 std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end());
8468 // If no such index exists, V is true.
8469 if (RetVal.isUnset())
8470 RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true);
8471 break;
8472 }
8473
8474 case DefaultedComparisonKind::ThreeWay: {
8475 // Per C++2a [class.spaceship]p3, as a fallback add:
8476 // return static_cast<R>(std::strong_ordering::equal);
8478 ComparisonCategoryType::StrongOrdering, Loc,
8479 Sema::ComparisonCategoryUsage::DefaultedOperator);
8480 if (StrongOrdering.isNull())
8481 return StmtError();
8483 .getValueInfo(ComparisonCategoryResult::Equal)
8484 ->VD;
8485 RetVal = getDecl(EqualVD);
8486 if (RetVal.isInvalid())
8487 return StmtError();
8488 RetVal = buildStaticCastToR(RetVal.get());
8489 break;
8490 }
8491
8492 case DefaultedComparisonKind::NotEqual:
8493 case DefaultedComparisonKind::Relational:
8494 RetVal = cast<Expr>(Stmts.Stmts.pop_back_val());
8495 break;
8496 }
8497
8498 // Build the final return statement.
8499 if (RetVal.isInvalid())
8500 return StmtError();
8502 if (ReturnStmt.isInvalid())
8503 return StmtError();
8504 Stmts.Stmts.push_back(ReturnStmt.get());
8505
8506 return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false);
8507 }
8508
8509private:
8510 ExprResult getDecl(ValueDecl *VD) {
8511 return S.BuildDeclarationNameExpr(
8513 }
8514
8515 ExprResult getParam(unsigned I) {
8516 ParmVarDecl *PD = FD->getParamDecl(I);
8517 return getDecl(PD);
8518 }
8519
8520 ExprPair getCompleteObject() {
8521 unsigned Param = 0;
8522 ExprResult LHS;
8523 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD);
8524 MD && MD->isImplicitObjectMemberFunction()) {
8525 // LHS is '*this'.
8526 LHS = S.ActOnCXXThis(Loc);
8527 if (!LHS.isInvalid())
8528 LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get());
8529 } else {
8530 LHS = getParam(Param++);
8531 }
8532 ExprResult RHS = getParam(Param++);
8533 assert(Param == FD->getNumParams());
8534 return {LHS, RHS};
8535 }
8536
8537 ExprPair getBase(CXXBaseSpecifier *Base) {
8538 ExprPair Obj = getCompleteObject();
8539 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8540 return {ExprError(), ExprError()};
8541 CXXCastPath Path = {Base};
8542 return {S.ImpCastExprToType(Obj.first.get(), Base->getType(),
8543 CK_DerivedToBase, VK_LValue, &Path),
8544 S.ImpCastExprToType(Obj.second.get(), Base->getType(),
8545 CK_DerivedToBase, VK_LValue, &Path)};
8546 }
8547
8548 ExprPair getField(FieldDecl *Field) {
8549 ExprPair Obj = getCompleteObject();
8550 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8551 return {ExprError(), ExprError()};
8552
8553 DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess());
8554 DeclarationNameInfo NameInfo(Field->getDeclName(), Loc);
8555 return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc,
8556 CXXScopeSpec(), Field, Found, NameInfo),
8557 S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc,
8558 CXXScopeSpec(), Field, Found, NameInfo)};
8559 }
8560
8561 // FIXME: When expanding a subobject, register a note in the code synthesis
8562 // stack to say which subobject we're comparing.
8563
8564 StmtResult buildIfNotCondReturnFalse(ExprResult Cond) {
8565 if (Cond.isInvalid())
8566 return StmtError();
8567
8568 ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get());
8569 if (NotCond.isInvalid())
8570 return StmtError();
8571
8572 ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false);
8573 assert(!False.isInvalid() && "should never fail");
8574 StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get());
8575 if (ReturnFalse.isInvalid())
8576 return StmtError();
8577
8578 return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, nullptr,
8579 S.ActOnCondition(nullptr, Loc, NotCond.get(),
8580 Sema::ConditionKind::Boolean),
8581 Loc, ReturnFalse.get(), SourceLocation(), nullptr);
8582 }
8583
8584 StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size,
8585 ExprPair Subobj) {
8586 QualType SizeType = S.Context.getSizeType();
8587 Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType));
8588
8589 // Build 'size_t i$n = 0'.
8590 IdentifierInfo *IterationVarName = nullptr;
8591 {
8592 SmallString<8> Str;
8593 llvm::raw_svector_ostream OS(Str);
8594 OS << "i" << ArrayDepth;
8595 IterationVarName = &S.Context.Idents.get(OS.str());
8596 }
8597 VarDecl *IterationVar = VarDecl::Create(
8598 S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType,
8600 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
8601 IterationVar->setInit(
8602 IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
8603 Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc);
8604
8605 auto IterRef = [&] {
8607 CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc),
8608 IterationVar);
8609 assert(!Ref.isInvalid() && "can't reference our own variable?");
8610 return Ref.get();
8611 };
8612
8613 // Build 'i$n != Size'.
8615 Loc, BO_NE, IterRef(),
8616 IntegerLiteral::Create(S.Context, Size, SizeType, Loc));
8617 assert(!Cond.isInvalid() && "should never fail");
8618
8619 // Build '++i$n'.
8620 ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef());
8621 assert(!Inc.isInvalid() && "should never fail");
8622
8623 // Build 'a[i$n]' and 'b[i$n]'.
8624 auto Index = [&](ExprResult E) {
8625 if (E.isInvalid())
8626 return ExprError();
8627 return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc);
8628 };
8629 Subobj.first = Index(Subobj.first);
8630 Subobj.second = Index(Subobj.second);
8631
8632 // Compare the array elements.
8633 ++ArrayDepth;
8634 StmtResult Substmt = visitSubobject(Type, Subobj);
8635 --ArrayDepth;
8636
8637 if (Substmt.isInvalid())
8638 return StmtError();
8639
8640 // For the inner level of an 'operator==', build 'if (!cmp) return false;'.
8641 // For outer levels or for an 'operator<=>' we already have a suitable
8642 // statement that returns as necessary.
8643 if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) {
8644 assert(DCK == DefaultedComparisonKind::Equal &&
8645 "should have non-expression statement");
8646 Substmt = buildIfNotCondReturnFalse(ElemCmp);
8647 if (Substmt.isInvalid())
8648 return StmtError();
8649 }
8650
8651 // Build 'for (...) ...'
8652 return S.ActOnForStmt(Loc, Loc, Init,
8653 S.ActOnCondition(nullptr, Loc, Cond.get(),
8654 Sema::ConditionKind::Boolean),
8656 Substmt.get());
8657 }
8658
8659 StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) {
8660 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8661 return StmtError();
8662
8665 ExprResult Op;
8666 if (Type->isOverloadableType())
8667 Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(),
8668 Obj.second.get(), /*PerformADL=*/true,
8669 /*AllowRewrittenCandidates=*/true, FD);
8670 else
8671 Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get());
8672 if (Op.isInvalid())
8673 return StmtError();
8674
8675 switch (DCK) {
8676 case DefaultedComparisonKind::None:
8677 llvm_unreachable("not a defaulted comparison");
8678
8679 case DefaultedComparisonKind::Equal:
8680 // Per C++2a [class.eq]p2, each comparison is individually contextually
8681 // converted to bool.
8683 if (Op.isInvalid())
8684 return StmtError();
8685 return Op.get();
8686
8687 case DefaultedComparisonKind::ThreeWay: {
8688 // Per C++2a [class.spaceship]p3, form:
8689 // if (R cmp = static_cast<R>(op); cmp != 0)
8690 // return cmp;
8691 QualType R = FD->getReturnType();
8692 Op = buildStaticCastToR(Op.get());
8693 if (Op.isInvalid())
8694 return StmtError();
8695
8696 // R cmp = ...;
8697 IdentifierInfo *Name = &S.Context.Idents.get("cmp");
8698 VarDecl *VD =
8699 VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R,
8701 S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false);
8702 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc);
8703
8704 // cmp != 0
8705 ExprResult VDRef = getDecl(VD);
8706 if (VDRef.isInvalid())
8707 return StmtError();
8708 llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0);
8709 Expr *Zero =
8712 if (VDRef.get()->getType()->isOverloadableType())
8713 Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true,
8714 true, FD);
8715 else
8716 Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero);
8717 if (Comp.isInvalid())
8718 return StmtError();
8720 nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean);
8721 if (Cond.isInvalid())
8722 return StmtError();
8723
8724 // return cmp;
8725 VDRef = getDecl(VD);
8726 if (VDRef.isInvalid())
8727 return StmtError();
8729 if (ReturnStmt.isInvalid())
8730 return StmtError();
8731
8732 // if (...)
8733 return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, InitStmt, Cond,
8734 Loc, ReturnStmt.get(),
8735 /*ElseLoc=*/SourceLocation(), /*Else=*/nullptr);
8736 }
8737
8738 case DefaultedComparisonKind::NotEqual:
8739 case DefaultedComparisonKind::Relational:
8740 // C++2a [class.compare.secondary]p2:
8741 // Otherwise, the operator function yields x @ y.
8742 return Op.get();
8743 }
8744 llvm_unreachable("");
8745 }
8746
8747 /// Build "static_cast<R>(E)".
8748 ExprResult buildStaticCastToR(Expr *E) {
8749 QualType R = FD->getReturnType();
8750 assert(!R->isUndeducedType() && "type should have been deduced already");
8751
8752 // Don't bother forming a no-op cast in the common case.
8753 if (E->isPRValue() && S.Context.hasSameType(E->getType(), R))
8754 return E;
8755 return S.BuildCXXNamedCast(Loc, tok::kw_static_cast,
8758 }
8759};
8760}
8761
8762/// Perform the unqualified lookups that might be needed to form a defaulted
8763/// comparison function for the given operator.
8765 UnresolvedSetImpl &Operators,
8767 auto Lookup = [&](OverloadedOperatorKind OO) {
8768 Self.LookupOverloadedOperatorName(OO, S, Operators);
8769 };
8770
8771 // Every defaulted operator looks up itself.
8772 Lookup(Op);
8773 // ... and the rewritten form of itself, if any.
8775 Lookup(ExtraOp);
8776
8777 // For 'operator<=>', we also form a 'cmp != 0' expression, and might
8778 // synthesize a three-way comparison from '<' and '=='. In a dependent
8779 // context, we also need to look up '==' in case we implicitly declare a
8780 // defaulted 'operator=='.
8781 if (Op == OO_Spaceship) {
8782 Lookup(OO_ExclaimEqual);
8783 Lookup(OO_Less);
8784 Lookup(OO_EqualEqual);
8785 }
8786}
8787
8790 assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison");
8791
8792 // Perform any unqualified lookups we're going to need to default this
8793 // function.
8794 if (S) {
8795 UnresolvedSet<32> Operators;
8796 lookupOperatorsForDefaultedComparison(*this, S, Operators,
8797 FD->getOverloadedOperator());
8800 Context, Operators.pairs()));
8801 }
8802
8803 // C++2a [class.compare.default]p1:
8804 // A defaulted comparison operator function for some class C shall be a
8805 // non-template function declared in the member-specification of C that is
8806 // -- a non-static const non-volatile member of C having one parameter of
8807 // type const C& and either no ref-qualifier or the ref-qualifier &, or
8808 // -- a friend of C having two parameters of type const C& or two
8809 // parameters of type C.
8810
8811 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext());
8812 bool IsMethod = isa<CXXMethodDecl>(FD);
8813 if (IsMethod) {
8814 auto *MD = cast<CXXMethodDecl>(FD);
8815 assert(!MD->isStatic() && "comparison function cannot be a static member");
8816
8817 if (MD->getRefQualifier() == RQ_RValue) {
8818 Diag(MD->getLocation(), diag::err_ref_qualifier_comparison_operator);
8819
8820 // Remove the ref qualifier to recover.
8821 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8822 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8823 EPI.RefQualifier = RQ_None;
8824 MD->setType(Context.getFunctionType(FPT->getReturnType(),
8825 FPT->getParamTypes(), EPI));
8826 }
8827
8828 // If we're out-of-class, this is the class we're comparing.
8829 if (!RD)
8830 RD = MD->getParent();
8832 if (!T.isConstQualified()) {
8833 SourceLocation Loc, InsertLoc;
8835 Loc = MD->getParamDecl(0)->getBeginLoc();
8836 InsertLoc = getLocForEndOfToken(
8838 } else {
8839 Loc = MD->getLocation();
8841 InsertLoc = Loc.getRParenLoc();
8842 }
8843 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8844 // corresponding defaulted 'operator<=>' already.
8845 if (!MD->isImplicit()) {
8846 Diag(Loc, diag::err_defaulted_comparison_non_const)
8847 << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const");
8848 }
8849
8850 // Add the 'const' to the type to recover.
8851 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8852 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8853 EPI.TypeQuals.addConst();
8854 MD->setType(Context.getFunctionType(FPT->getReturnType(),
8855 FPT->getParamTypes(), EPI));
8856 }
8857
8858 if (MD->isVolatile()) {
8859 Diag(MD->getLocation(), diag::err_volatile_comparison_operator);
8860
8861 // Remove the 'volatile' from the type to recover.
8862 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8863 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8865 MD->setType(Context.getFunctionType(FPT->getReturnType(),
8866 FPT->getParamTypes(), EPI));
8867 }
8868 }
8869
8870 if ((FD->getNumParams() -
8871 (unsigned)FD->hasCXXExplicitFunctionObjectParameter()) !=
8872 (IsMethod ? 1 : 2)) {
8873 // Let's not worry about using a variadic template pack here -- who would do
8874 // such a thing?
8875 Diag(FD->getLocation(), diag::err_defaulted_comparison_num_args)
8876 << int(IsMethod) << int(DCK);
8877 return true;
8878 }
8879
8880 const ParmVarDecl *KnownParm = nullptr;
8881 for (const ParmVarDecl *Param : FD->parameters()) {
8882 if (Param->isExplicitObjectParameter())
8883 continue;
8884 QualType ParmTy = Param->getType();
8885
8886 if (!KnownParm) {
8887 auto CTy = ParmTy;
8888 // Is it `T const &`?
8889 bool Ok = !IsMethod;
8890 QualType ExpectedTy;
8891 if (RD)
8892 ExpectedTy = Context.getRecordType(RD);
8893 if (auto *Ref = CTy->getAs<ReferenceType>()) {
8894 CTy = Ref->getPointeeType();
8895 if (RD)
8896 ExpectedTy.addConst();
8897 Ok = true;
8898 }
8899
8900 // Is T a class?
8901 if (!Ok) {
8902 } else if (RD) {
8903 if (!RD->isDependentType() && !Context.hasSameType(CTy, ExpectedTy))
8904 Ok = false;
8905 } else if (auto *CRD = CTy->getAsRecordDecl()) {
8906 RD = cast<CXXRecordDecl>(CRD);
8907 } else {
8908 Ok = false;
8909 }
8910
8911 if (Ok) {
8912 KnownParm = Param;
8913 } else {
8914 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8915 // corresponding defaulted 'operator<=>' already.
8916 if (!FD->isImplicit()) {
8917 if (RD) {
8918 QualType PlainTy = Context.getRecordType(RD);
8919 QualType RefTy =
8921 Diag(FD->getLocation(), diag::err_defaulted_comparison_param)
8922 << int(DCK) << ParmTy << RefTy << int(!IsMethod) << PlainTy
8923 << Param->getSourceRange();
8924 } else {
8925 assert(!IsMethod && "should know expected type for method");
8926 Diag(FD->getLocation(),
8927 diag::err_defaulted_comparison_param_unknown)
8928 << int(DCK) << ParmTy << Param->getSourceRange();
8929 }
8930 }
8931 return true;
8932 }
8933 } else if (!Context.hasSameType(KnownParm->getType(), ParmTy)) {
8934 Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch)
8935 << int(DCK) << KnownParm->getType() << KnownParm->getSourceRange()
8936 << ParmTy << Param->getSourceRange();
8937 return true;
8938 }
8939 }
8940
8941 assert(RD && "must have determined class");
8942 if (IsMethod) {
8943 } else if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
8944 // In-class, must be a friend decl.
8945 assert(FD->getFriendObjectKind() && "expected a friend declaration");
8946 } else {
8947 // Out of class, require the defaulted comparison to be a friend (of a
8948 // complete type).
8950 diag::err_defaulted_comparison_not_friend, int(DCK),
8951 int(1)))
8952 return true;
8953
8954 if (llvm::none_of(RD->friends(), [&](const FriendDecl *F) {
8955 return FD->getCanonicalDecl() ==
8956 F->getFriendDecl()->getCanonicalDecl();
8957 })) {
8958 Diag(FD->getLocation(), diag::err_defaulted_comparison_not_friend)
8959 << int(DCK) << int(0) << RD;
8960 Diag(RD->getCanonicalDecl()->getLocation(), diag::note_declared_at);
8961 return true;
8962 }
8963 }
8964
8965 // C++2a [class.eq]p1, [class.rel]p1:
8966 // A [defaulted comparison other than <=>] shall have a declared return
8967 // type bool.
8971 Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool)
8972 << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy
8973 << FD->getReturnTypeSourceRange();
8974 return true;
8975 }
8976 // C++2a [class.spaceship]p2 [P2002R0]:
8977 // Let R be the declared return type [...]. If R is auto, [...]. Otherwise,
8978 // R shall not contain a placeholder type.
8979 if (QualType RT = FD->getDeclaredReturnType();
8981 RT->getContainedDeducedType() &&
8983 RT->getContainedAutoType()->isConstrained())) {
8984 Diag(FD->getLocation(),
8985 diag::err_defaulted_comparison_deduced_return_type_not_auto)
8986 << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy
8987 << FD->getReturnTypeSourceRange();
8988 return true;
8989 }
8990
8991 // For a defaulted function in a dependent class, defer all remaining checks
8992 // until instantiation.
8993 if (RD->isDependentType())
8994 return false;
8995
8996 // Determine whether the function should be defined as deleted.
8997 DefaultedComparisonInfo Info =
8998 DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit();
8999
9000 bool First = FD == FD->getCanonicalDecl();
9001
9002 if (!First) {
9003 if (Info.Deleted) {
9004 // C++11 [dcl.fct.def.default]p4:
9005 // [For a] user-provided explicitly-defaulted function [...] if such a
9006 // function is implicitly defined as deleted, the program is ill-formed.
9007 //
9008 // This is really just a consequence of the general rule that you can
9009 // only delete a function on its first declaration.
9010 Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes)
9011 << FD->isImplicit() << (int)DCK;
9012 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9013 DefaultedComparisonAnalyzer::ExplainDeleted)
9014 .visit();
9015 return true;
9016 }
9017 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
9018 // C++20 [class.compare.default]p1:
9019 // [...] A definition of a comparison operator as defaulted that appears
9020 // in a class shall be the first declaration of that function.
9021 Diag(FD->getLocation(), diag::err_non_first_default_compare_in_class)
9022 << (int)DCK;
9024 diag::note_previous_declaration);
9025 return true;
9026 }
9027 }
9028
9029 // If we want to delete the function, then do so; there's nothing else to
9030 // check in that case.
9031 if (Info.Deleted) {
9032 SetDeclDeleted(FD, FD->getLocation());
9033 if (!inTemplateInstantiation() && !FD->isImplicit()) {
9034 Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted)
9035 << (int)DCK;
9036 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9037 DefaultedComparisonAnalyzer::ExplainDeleted)
9038 .visit();
9039 if (FD->getDefaultLoc().isValid())
9040 Diag(FD->getDefaultLoc(), diag::note_replace_equals_default_to_delete)
9041 << FixItHint::CreateReplacement(FD->getDefaultLoc(), "delete");
9042 }
9043 return false;
9044 }
9045
9046 // C++2a [class.spaceship]p2:
9047 // The return type is deduced as the common comparison type of R0, R1, ...
9051 if (RetLoc.isInvalid())
9052 RetLoc = FD->getBeginLoc();
9053 // FIXME: Should we really care whether we have the complete type and the
9054 // 'enumerator' constants here? A forward declaration seems sufficient.
9056 Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator);
9057 if (Cat.isNull())
9058 return true;
9060 FD, SubstAutoType(FD->getDeclaredReturnType(), Cat));
9061 }
9062
9063 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
9064 // An explicitly-defaulted function that is not defined as deleted may be
9065 // declared constexpr or consteval only if it is constexpr-compatible.
9066 // C++2a [class.compare.default]p3 [P2002R0]:
9067 // A defaulted comparison function is constexpr-compatible if it satisfies
9068 // the requirements for a constexpr function [...]
9069 // The only relevant requirements are that the parameter and return types are
9070 // literal types. The remaining conditions are checked by the analyzer.
9071 //
9072 // We support P2448R2 in language modes earlier than C++23 as an extension.
9073 // The concept of constexpr-compatible was removed.
9074 // C++23 [dcl.fct.def.default]p3 [P2448R2]
9075 // A function explicitly defaulted on its first declaration is implicitly
9076 // inline, and is implicitly constexpr if it is constexpr-suitable.
9077 // C++23 [dcl.constexpr]p3
9078 // A function is constexpr-suitable if
9079 // - it is not a coroutine, and
9080 // - if the function is a constructor or destructor, its class does not
9081 // have any virtual base classes.
9082 if (FD->isConstexpr()) {
9083 if (!getLangOpts().CPlusPlus23 &&
9086 !Info.Constexpr) {
9087 Diag(FD->getBeginLoc(), diag::err_defaulted_comparison_constexpr_mismatch)
9088 << FD->isImplicit() << (int)DCK << FD->isConsteval();
9089 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9090 DefaultedComparisonAnalyzer::ExplainConstexpr)
9091 .visit();
9092 }
9093 }
9094
9095 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
9096 // If a constexpr-compatible function is explicitly defaulted on its first
9097 // declaration, it is implicitly considered to be constexpr.
9098 // FIXME: Only applying this to the first declaration seems problematic, as
9099 // simple reorderings can affect the meaning of the program.
9100 if (First && !FD->isConstexpr() && Info.Constexpr)
9102
9103 // C++2a [except.spec]p3:
9104 // If a declaration of a function does not have a noexcept-specifier
9105 // [and] is defaulted on its first declaration, [...] the exception
9106 // specification is as specified below
9107 if (FD->getExceptionSpecType() == EST_None) {
9108 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9109 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9111 EPI.ExceptionSpec.SourceDecl = FD;
9112 FD->setType(Context.getFunctionType(FPT->getReturnType(),
9113 FPT->getParamTypes(), EPI));
9114 }
9115
9116 return false;
9117}
9118
9120 FunctionDecl *Spaceship) {
9123 Ctx.PointOfInstantiation = Spaceship->getEndLoc();
9124 Ctx.Entity = Spaceship;
9126
9127 if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship))
9128 EqualEqual->setImplicit();
9129
9131}
9132
9135 assert(FD->isDefaulted() && !FD->isDeleted() &&
9137 if (FD->willHaveBody() || FD->isInvalidDecl())
9138 return;
9139
9141
9142 // Add a context note for diagnostics produced after this point.
9143 Scope.addContextNote(UseLoc);
9144
9145 {
9146 // Build and set up the function body.
9147 // The first parameter has type maybe-ref-to maybe-const T, use that to get
9148 // the type of the class being compared.
9149 auto PT = FD->getParamDecl(0)->getType();
9150 CXXRecordDecl *RD = PT.getNonReferenceType()->getAsCXXRecordDecl();
9151 SourceLocation BodyLoc =
9152 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
9153 StmtResult Body =
9154 DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build();
9155 if (Body.isInvalid()) {
9156 FD->setInvalidDecl();
9157 return;
9158 }
9159 FD->setBody(Body.get());
9160 FD->markUsed(Context);
9161 }
9162
9163 // The exception specification is needed because we are defining the
9164 // function. Note that this will reuse the body we just built.
9166
9168 L->CompletedImplicitDefinition(FD);
9169}
9170
9173 FunctionDecl *FD,
9175 ComputingExceptionSpec CES(S, FD, Loc);
9177
9178 if (FD->isInvalidDecl())
9179 return ExceptSpec;
9180
9181 // The common case is that we just defined the comparison function. In that
9182 // case, just look at whether the body can throw.
9183 if (FD->hasBody()) {
9184 ExceptSpec.CalledStmt(FD->getBody());
9185 } else {
9186 // Otherwise, build a body so we can check it. This should ideally only
9187 // happen when we're not actually marking the function referenced. (This is
9188 // only really important for efficiency: we don't want to build and throw
9189 // away bodies for comparison functions more than we strictly need to.)
9190
9191 // Pretend to synthesize the function body in an unevaluated context.
9192 // Note that we can't actually just go ahead and define the function here:
9193 // we are not permitted to mark its callees as referenced.
9197
9198 CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent());
9199 SourceLocation BodyLoc =
9200 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
9201 StmtResult Body =
9202 DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build();
9203 if (!Body.isInvalid())
9204 ExceptSpec.CalledStmt(Body.get());
9205
9206 // FIXME: Can we hold onto this body and just transform it to potentially
9207 // evaluated when we're asked to define the function rather than rebuilding
9208 // it? Either that, or we should only build the bits of the body that we
9209 // need (the expressions, not the statements).
9210 }
9211
9212 return ExceptSpec;
9213}
9214
9216 decltype(DelayedOverridingExceptionSpecChecks) Overriding;
9218
9219 std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
9221
9222 // Perform any deferred checking of exception specifications for virtual
9223 // destructors.
9224 for (auto &Check : Overriding)
9225 CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
9226
9227 // Perform any deferred checking of exception specifications for befriended
9228 // special members.
9229 for (auto &Check : Equivalent)
9230 CheckEquivalentExceptionSpec(Check.second, Check.first);
9231}
9232
9233namespace {
9234/// CRTP base class for visiting operations performed by a special member
9235/// function (or inherited constructor).
9236template<typename Derived>
9237struct SpecialMemberVisitor {
9238 Sema &S;
9239 CXXMethodDecl *MD;
9242
9243 // Properties of the special member, computed for convenience.
9244 bool IsConstructor = false, IsAssignment = false, ConstArg = false;
9245
9246 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, CXXSpecialMemberKind CSM,
9248 : S(S), MD(MD), CSM(CSM), ICI(ICI) {
9249 switch (CSM) {
9250 case CXXSpecialMemberKind::DefaultConstructor:
9251 case CXXSpecialMemberKind::CopyConstructor:
9252 case CXXSpecialMemberKind::MoveConstructor:
9253 IsConstructor = true;
9254 break;
9255 case CXXSpecialMemberKind::CopyAssignment:
9256 case CXXSpecialMemberKind::MoveAssignment:
9257 IsAssignment = true;
9258 break;
9259 case CXXSpecialMemberKind::Destructor:
9260 break;
9261 case CXXSpecialMemberKind::Invalid:
9262 llvm_unreachable("invalid special member kind");
9263 }
9264
9265 if (MD->getNumExplicitParams()) {
9266 if (const ReferenceType *RT =
9268 ConstArg = RT->getPointeeType().isConstQualified();
9269 }
9270 }
9271
9272 Derived &getDerived() { return static_cast<Derived&>(*this); }
9273
9274 /// Is this a "move" special member?
9275 bool isMove() const {
9276 return CSM == CXXSpecialMemberKind::MoveConstructor ||
9277 CSM == CXXSpecialMemberKind::MoveAssignment;
9278 }
9279
9280 /// Look up the corresponding special member in the given class.
9282 unsigned Quals, bool IsMutable) {
9283 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
9284 ConstArg && !IsMutable);
9285 }
9286
9287 /// Look up the constructor for the specified base class to see if it's
9288 /// overridden due to this being an inherited constructor.
9289 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
9290 if (!ICI)
9291 return {};
9292 assert(CSM == CXXSpecialMemberKind::DefaultConstructor);
9293 auto *BaseCtor =
9294 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
9295 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
9296 return MD;
9297 return {};
9298 }
9299
9300 /// A base or member subobject.
9301 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
9302
9303 /// Get the location to use for a subobject in diagnostics.
9304 static SourceLocation getSubobjectLoc(Subobject Subobj) {
9305 // FIXME: For an indirect virtual base, the direct base leading to
9306 // the indirect virtual base would be a more useful choice.
9307 if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
9308 return B->getBaseTypeLoc();
9309 else
9310 return Subobj.get<FieldDecl*>()->getLocation();
9311 }
9312
9313 enum BasesToVisit {
9314 /// Visit all non-virtual (direct) bases.
9315 VisitNonVirtualBases,
9316 /// Visit all direct bases, virtual or not.
9317 VisitDirectBases,
9318 /// Visit all non-virtual bases, and all virtual bases if the class
9319 /// is not abstract.
9320 VisitPotentiallyConstructedBases,
9321 /// Visit all direct or virtual bases.
9322 VisitAllBases
9323 };
9324
9325 // Visit the bases and members of the class.
9326 bool visit(BasesToVisit Bases) {
9327 CXXRecordDecl *RD = MD->getParent();
9328
9329 if (Bases == VisitPotentiallyConstructedBases)
9330 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
9331
9332 for (auto &B : RD->bases())
9333 if ((Bases == VisitDirectBases || !B.isVirtual()) &&
9334 getDerived().visitBase(&B))
9335 return true;
9336
9337 if (Bases == VisitAllBases)
9338 for (auto &B : RD->vbases())
9339 if (getDerived().visitBase(&B))
9340 return true;
9341
9342 for (auto *F : RD->fields())
9343 if (!F->isInvalidDecl() && !F->isUnnamedBitField() &&
9344 getDerived().visitField(F))
9345 return true;
9346
9347 return false;
9348 }
9349};
9350}
9351
9352namespace {
9353struct SpecialMemberDeletionInfo
9354 : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
9355 bool Diagnose;
9356
9358
9359 bool AllFieldsAreConst;
9360
9361 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
9363 Sema::InheritedConstructorInfo *ICI, bool Diagnose)
9364 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
9365 Loc(MD->getLocation()), AllFieldsAreConst(true) {}
9366
9367 bool inUnion() const { return MD->getParent()->isUnion(); }
9368
9369 CXXSpecialMemberKind getEffectiveCSM() {
9370 return ICI ? CXXSpecialMemberKind::Invalid : CSM;
9371 }
9372
9373 bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
9374
9375 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
9376 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
9377
9378 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
9379 bool shouldDeleteForField(FieldDecl *FD);
9380 bool shouldDeleteForAllConstMembers();
9381
9382 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
9383 unsigned Quals);
9384 bool shouldDeleteForSubobjectCall(Subobject Subobj,
9386 bool IsDtorCallInCtor);
9387
9388 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
9389};
9390}
9391
9392/// Is the given special member inaccessible when used on the given
9393/// sub-object.
9394bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
9395 CXXMethodDecl *target) {
9396 /// If we're operating on a base class, the object type is the
9397 /// type of this special member.
9398 QualType objectTy;
9399 AccessSpecifier access = target->getAccess();
9400 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
9401 objectTy = S.Context.getTypeDeclType(MD->getParent());
9402 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
9403
9404 // If we're operating on a field, the object type is the type of the field.
9405 } else {
9406 objectTy = S.Context.getTypeDeclType(target->getParent());
9407 }
9408
9410 target->getParent(), DeclAccessPair::make(target, access), objectTy);
9411}
9412
9413/// Check whether we should delete a special member due to the implicit
9414/// definition containing a call to a special member of a subobject.
9415bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
9416 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
9417 bool IsDtorCallInCtor) {
9418 CXXMethodDecl *Decl = SMOR.getMethod();
9419 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9420
9421 int DiagKind = -1;
9422
9424 DiagKind = !Decl ? 0 : 1;
9426 DiagKind = 2;
9427 else if (!isAccessible(Subobj, Decl))
9428 DiagKind = 3;
9429 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
9430 !Decl->isTrivial()) {
9431 // A member of a union must have a trivial corresponding special member.
9432 // As a weird special case, a destructor call from a union's constructor
9433 // must be accessible and non-deleted, but need not be trivial. Such a
9434 // destructor is never actually called, but is semantically checked as
9435 // if it were.
9437 // [class.default.ctor]p2:
9438 // A defaulted default constructor for class X is defined as deleted if
9439 // - X is a union that has a variant member with a non-trivial default
9440 // constructor and no variant member of X has a default member
9441 // initializer
9442 const auto *RD = cast<CXXRecordDecl>(Field->getParent());
9443 if (!RD->hasInClassInitializer())
9444 DiagKind = 4;
9445 } else {
9446 DiagKind = 4;
9447 }
9448 }
9449
9450 if (DiagKind == -1)
9451 return false;
9452
9453 if (Diagnose) {
9454 if (Field) {
9455 S.Diag(Field->getLocation(),
9456 diag::note_deleted_special_member_class_subobject)
9457 << llvm::to_underlying(getEffectiveCSM()) << MD->getParent()
9458 << /*IsField*/ true << Field << DiagKind << IsDtorCallInCtor
9459 << /*IsObjCPtr*/ false;
9460 } else {
9461 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
9462 S.Diag(Base->getBeginLoc(),
9463 diag::note_deleted_special_member_class_subobject)
9464 << llvm::to_underlying(getEffectiveCSM()) << MD->getParent()
9465 << /*IsField*/ false << Base->getType() << DiagKind
9466 << IsDtorCallInCtor << /*IsObjCPtr*/ false;
9467 }
9468
9469 if (DiagKind == 1)
9471 // FIXME: Explain inaccessibility if DiagKind == 3.
9472 }
9473
9474 return true;
9475}
9476
9477/// Check whether we should delete a special member function due to having a
9478/// direct or virtual base class or non-static data member of class type M.
9479bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
9480 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
9481 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9482 bool IsMutable = Field && Field->isMutable();
9483
9484 // C++11 [class.ctor]p5:
9485 // -- any direct or virtual base class, or non-static data member with no
9486 // brace-or-equal-initializer, has class type M (or array thereof) and
9487 // either M has no default constructor or overload resolution as applied
9488 // to M's default constructor results in an ambiguity or in a function
9489 // that is deleted or inaccessible
9490 // C++11 [class.copy]p11, C++11 [class.copy]p23:
9491 // -- a direct or virtual base class B that cannot be copied/moved because
9492 // overload resolution, as applied to B's corresponding special member,
9493 // results in an ambiguity or a function that is deleted or inaccessible
9494 // from the defaulted special member
9495 // C++11 [class.dtor]p5:
9496 // -- any direct or virtual base class [...] has a type with a destructor
9497 // that is deleted or inaccessible
9498 if (!(CSM == CXXSpecialMemberKind::DefaultConstructor && Field &&
9499 Field->hasInClassInitializer()) &&
9500 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
9501 false))
9502 return true;
9503
9504 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
9505 // -- any direct or virtual base class or non-static data member has a
9506 // type with a destructor that is deleted or inaccessible
9507 if (IsConstructor) {
9510 false, false, false, false);
9511 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
9512 return true;
9513 }
9514
9515 return false;
9516}
9517
9518bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
9519 FieldDecl *FD, QualType FieldType) {
9520 // The defaulted special functions are defined as deleted if this is a variant
9521 // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
9522 // type under ARC.
9523 if (!FieldType.hasNonTrivialObjCLifetime())
9524 return false;
9525
9526 // Don't make the defaulted default constructor defined as deleted if the
9527 // member has an in-class initializer.
9530 return false;
9531
9532 if (Diagnose) {
9533 auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
9534 S.Diag(FD->getLocation(), diag::note_deleted_special_member_class_subobject)
9535 << llvm::to_underlying(getEffectiveCSM()) << ParentClass
9536 << /*IsField*/ true << FD << 4 << /*IsDtorCallInCtor*/ false
9537 << /*IsObjCPtr*/ true;
9538 }
9539
9540 return true;
9541}
9542
9543/// Check whether we should delete a special member function due to the class
9544/// having a particular direct or virtual base class.
9545bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
9546 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
9547 // If program is correct, BaseClass cannot be null, but if it is, the error
9548 // must be reported elsewhere.
9549 if (!BaseClass)
9550 return false;
9551 // If we have an inheriting constructor, check whether we're calling an
9552 // inherited constructor instead of a default constructor.
9553 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
9554 if (auto *BaseCtor = SMOR.getMethod()) {
9555 // Note that we do not check access along this path; other than that,
9556 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
9557 // FIXME: Check that the base has a usable destructor! Sink this into
9558 // shouldDeleteForClassSubobject.
9559 if (BaseCtor->isDeleted() && Diagnose) {
9560 S.Diag(Base->getBeginLoc(),
9561 diag::note_deleted_special_member_class_subobject)
9562 << llvm::to_underlying(getEffectiveCSM()) << MD->getParent()
9563 << /*IsField*/ false << Base->getType() << /*Deleted*/ 1
9564 << /*IsDtorCallInCtor*/ false << /*IsObjCPtr*/ false;
9565 S.NoteDeletedFunction(BaseCtor);
9566 }
9567 return BaseCtor->isDeleted();
9568 }
9569 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
9570}
9571
9572/// Check whether we should delete a special member function due to the class
9573/// having a particular non-static data member.
9574bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
9575 QualType FieldType = S.Context.getBaseElementType(FD->getType());
9576 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
9577
9578 if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
9579 return true;
9580
9582 // For a default constructor, all references must be initialized in-class
9583 // and, if a union, it must have a non-const member.
9584 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
9585 if (Diagnose)
9586 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9587 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
9588 return true;
9589 }
9590 // C++11 [class.ctor]p5 (modified by DR2394): any non-variant non-static
9591 // data member of const-qualified type (or array thereof) with no
9592 // brace-or-equal-initializer is not const-default-constructible.
9593 if (!inUnion() && FieldType.isConstQualified() &&
9594 !FD->hasInClassInitializer() &&
9595 (!FieldRecord || !FieldRecord->allowConstDefaultInit())) {
9596 if (Diagnose)
9597 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9598 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
9599 return true;
9600 }
9601
9602 if (inUnion() && !FieldType.isConstQualified())
9603 AllFieldsAreConst = false;
9604 } else if (CSM == CXXSpecialMemberKind::CopyConstructor) {
9605 // For a copy constructor, data members must not be of rvalue reference
9606 // type.
9607 if (FieldType->isRValueReferenceType()) {
9608 if (Diagnose)
9609 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
9610 << MD->getParent() << FD << FieldType;
9611 return true;
9612 }
9613 } else if (IsAssignment) {
9614 // For an assignment operator, data members must not be of reference type.
9615 if (FieldType->isReferenceType()) {
9616 if (Diagnose)
9617 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9618 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
9619 return true;
9620 }
9621 if (!FieldRecord && FieldType.isConstQualified()) {
9622 // C++11 [class.copy]p23:
9623 // -- a non-static data member of const non-class type (or array thereof)
9624 if (Diagnose)
9625 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9626 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
9627 return true;
9628 }
9629 }
9630
9631 if (FieldRecord) {
9632 // Some additional restrictions exist on the variant members.
9633 if (!inUnion() && FieldRecord->isUnion() &&
9634 FieldRecord->isAnonymousStructOrUnion()) {
9635 bool AllVariantFieldsAreConst = true;
9636
9637 // FIXME: Handle anonymous unions declared within anonymous unions.
9638 for (auto *UI : FieldRecord->fields()) {
9639 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
9640
9641 if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
9642 return true;
9643
9644 if (!UnionFieldType.isConstQualified())
9645 AllVariantFieldsAreConst = false;
9646
9647 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
9648 if (UnionFieldRecord &&
9649 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
9650 UnionFieldType.getCVRQualifiers()))
9651 return true;
9652 }
9653
9654 // At least one member in each anonymous union must be non-const
9656 AllVariantFieldsAreConst && !FieldRecord->field_empty()) {
9657 if (Diagnose)
9658 S.Diag(FieldRecord->getLocation(),
9659 diag::note_deleted_default_ctor_all_const)
9660 << !!ICI << MD->getParent() << /*anonymous union*/1;
9661 return true;
9662 }
9663
9664 // Don't check the implicit member of the anonymous union type.
9665 // This is technically non-conformant but supported, and we have a
9666 // diagnostic for this elsewhere.
9667 return false;
9668 }
9669
9670 if (shouldDeleteForClassSubobject(FieldRecord, FD,
9671 FieldType.getCVRQualifiers()))
9672 return true;
9673 }
9674
9675 return false;
9676}
9677
9678/// C++11 [class.ctor] p5:
9679/// A defaulted default constructor for a class X is defined as deleted if
9680/// X is a union and all of its variant members are of const-qualified type.
9681bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
9682 // This is a silly definition, because it gives an empty union a deleted
9683 // default constructor. Don't do that.
9684 if (CSM == CXXSpecialMemberKind::DefaultConstructor && inUnion() &&
9685 AllFieldsAreConst) {
9686 bool AnyFields = false;
9687 for (auto *F : MD->getParent()->fields())
9688 if ((AnyFields = !F->isUnnamedBitField()))
9689 break;
9690 if (!AnyFields)
9691 return false;
9692 if (Diagnose)
9693 S.Diag(MD->getParent()->getLocation(),
9694 diag::note_deleted_default_ctor_all_const)
9695 << !!ICI << MD->getParent() << /*not anonymous union*/0;
9696 return true;
9697 }
9698 return false;
9699}
9700
9701/// Determine whether a defaulted special member function should be defined as
9702/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
9703/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
9707 bool Diagnose) {
9708 if (MD->isInvalidDecl())
9709 return false;
9710 CXXRecordDecl *RD = MD->getParent();
9711 assert(!RD->isDependentType() && "do deletion after instantiation");
9712 if (!LangOpts.CPlusPlus || (!LangOpts.CPlusPlus11 && !RD->isLambda()) ||
9713 RD->isInvalidDecl())
9714 return false;
9715
9716 // C++11 [expr.lambda.prim]p19:
9717 // The closure type associated with a lambda-expression has a
9718 // deleted (8.4.3) default constructor and a deleted copy
9719 // assignment operator.
9720 // C++2a adds back these operators if the lambda has no lambda-capture.
9724 if (Diagnose)
9725 Diag(RD->getLocation(), diag::note_lambda_decl);
9726 return true;
9727 }
9728
9729 // For an anonymous struct or union, the copy and assignment special members
9730 // will never be used, so skip the check. For an anonymous union declared at
9731 // namespace scope, the constructor and destructor are used.
9734 return false;
9735
9736 // C++11 [class.copy]p7, p18:
9737 // If the class definition declares a move constructor or move assignment
9738 // operator, an implicitly declared copy constructor or copy assignment
9739 // operator is defined as deleted.
9742 CXXMethodDecl *UserDeclaredMove = nullptr;
9743
9744 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
9745 // deletion of the corresponding copy operation, not both copy operations.
9746 // MSVC 2015 has adopted the standards conforming behavior.
9747 bool DeletesOnlyMatchingCopy =
9748 getLangOpts().MSVCCompat &&
9750
9752 (!DeletesOnlyMatchingCopy ||
9754 if (!Diagnose) return true;
9755
9756 // Find any user-declared move constructor.
9757 for (auto *I : RD->ctors()) {
9758 if (I->isMoveConstructor()) {
9759 UserDeclaredMove = I;
9760 break;
9761 }
9762 }
9763 assert(UserDeclaredMove);
9764 } else if (RD->hasUserDeclaredMoveAssignment() &&
9765 (!DeletesOnlyMatchingCopy ||
9767 if (!Diagnose) return true;
9768
9769 // Find any user-declared move assignment operator.
9770 for (auto *I : RD->methods()) {
9771 if (I->isMoveAssignmentOperator()) {
9772 UserDeclaredMove = I;
9773 break;
9774 }
9775 }
9776 assert(UserDeclaredMove);
9777 }
9778
9779 if (UserDeclaredMove) {
9780 Diag(UserDeclaredMove->getLocation(),
9781 diag::note_deleted_copy_user_declared_move)
9782 << (CSM == CXXSpecialMemberKind::CopyAssignment) << RD
9783 << UserDeclaredMove->isMoveAssignmentOperator();
9784 return true;
9785 }
9786 }
9787
9788 // Do access control from the special member function
9789 ContextRAII MethodContext(*this, MD);
9790
9791 // C++11 [class.dtor]p5:
9792 // -- for a virtual destructor, lookup of the non-array deallocation function
9793 // results in an ambiguity or in a function that is deleted or inaccessible
9794 if (CSM == CXXSpecialMemberKind::Destructor && MD->isVirtual()) {
9795 FunctionDecl *OperatorDelete = nullptr;
9796 DeclarationName Name =
9798 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
9799 OperatorDelete, /*Diagnose*/false)) {
9800 if (Diagnose)
9801 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
9802 return true;
9803 }
9804 }
9805
9806 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
9807
9808 // Per DR1611, do not consider virtual bases of constructors of abstract
9809 // classes, since we are not going to construct them.
9810 // Per DR1658, do not consider virtual bases of destructors of abstract
9811 // classes either.
9812 // Per DR2180, for assignment operators we only assign (and thus only
9813 // consider) direct bases.
9814 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
9815 : SMI.VisitPotentiallyConstructedBases))
9816 return true;
9817
9818 if (SMI.shouldDeleteForAllConstMembers())
9819 return true;
9820
9821 if (getLangOpts().CUDA) {
9822 // We should delete the special member in CUDA mode if target inference
9823 // failed.
9824 // For inherited constructors (non-null ICI), CSM may be passed so that MD
9825 // is treated as certain special member, which may not reflect what special
9826 // member MD really is. However inferTargetForImplicitSpecialMember
9827 // expects CSM to match MD, therefore recalculate CSM.
9828 assert(ICI || CSM == getSpecialMember(MD));
9829 auto RealCSM = CSM;
9830 if (ICI)
9831 RealCSM = getSpecialMember(MD);
9832
9833 return CUDA().inferTargetForImplicitSpecialMember(RD, RealCSM, MD,
9834 SMI.ConstArg, Diagnose);
9835 }
9836
9837 return false;
9838}
9839
9842 assert(DFK && "not a defaultable function");
9843 assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted");
9844
9845 if (DFK.isSpecialMember()) {
9846 ShouldDeleteSpecialMember(cast<CXXMethodDecl>(FD), DFK.asSpecialMember(),
9847 nullptr, /*Diagnose=*/true);
9848 } else {
9849 DefaultedComparisonAnalyzer(
9850 *this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD,
9851 DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted)
9852 .visit();
9853 }
9854}
9855
9856/// Perform lookup for a special member of the specified kind, and determine
9857/// whether it is trivial. If the triviality can be determined without the
9858/// lookup, skip it. This is intended for use when determining whether a
9859/// special member of a containing object is trivial, and thus does not ever
9860/// perform overload resolution for default constructors.
9861///
9862/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
9863/// member that was most likely to be intended to be trivial, if any.
9864///
9865/// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
9866/// determine whether the special member is trivial.
9868 CXXSpecialMemberKind CSM, unsigned Quals,
9869 bool ConstRHS,
9871 CXXMethodDecl **Selected) {
9872 if (Selected)
9873 *Selected = nullptr;
9874
9875 switch (CSM) {
9877 llvm_unreachable("not a special member");
9878
9880 // C++11 [class.ctor]p5:
9881 // A default constructor is trivial if:
9882 // - all the [direct subobjects] have trivial default constructors
9883 //
9884 // Note, no overload resolution is performed in this case.
9886 return true;
9887
9888 if (Selected) {
9889 // If there's a default constructor which could have been trivial, dig it
9890 // out. Otherwise, if there's any user-provided default constructor, point
9891 // to that as an example of why there's not a trivial one.
9892 CXXConstructorDecl *DefCtor = nullptr;
9895 for (auto *CI : RD->ctors()) {
9896 if (!CI->isDefaultConstructor())
9897 continue;
9898 DefCtor = CI;
9899 if (!DefCtor->isUserProvided())
9900 break;
9901 }
9902
9903 *Selected = DefCtor;
9904 }
9905
9906 return false;
9907
9909 // C++11 [class.dtor]p5:
9910 // A destructor is trivial if:
9911 // - all the direct [subobjects] have trivial destructors
9912 if (RD->hasTrivialDestructor() ||
9915 return true;
9916
9917 if (Selected) {
9918 if (RD->needsImplicitDestructor())
9920 *Selected = RD->getDestructor();
9921 }
9922
9923 return false;
9924
9926 // C++11 [class.copy]p12:
9927 // A copy constructor is trivial if:
9928 // - the constructor selected to copy each direct [subobject] is trivial
9929 if (RD->hasTrivialCopyConstructor() ||
9932 if (Quals == Qualifiers::Const)
9933 // We must either select the trivial copy constructor or reach an
9934 // ambiguity; no need to actually perform overload resolution.
9935 return true;
9936 } else if (!Selected) {
9937 return false;
9938 }
9939 // In C++98, we are not supposed to perform overload resolution here, but we
9940 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
9941 // cases like B as having a non-trivial copy constructor:
9942 // struct A { template<typename T> A(T&); };
9943 // struct B { mutable A a; };
9944 goto NeedOverloadResolution;
9945
9947 // C++11 [class.copy]p25:
9948 // A copy assignment operator is trivial if:
9949 // - the assignment operator selected to copy each direct [subobject] is
9950 // trivial
9951 if (RD->hasTrivialCopyAssignment()) {
9952 if (Quals == Qualifiers::Const)
9953 return true;
9954 } else if (!Selected) {
9955 return false;
9956 }
9957 // In C++98, we are not supposed to perform overload resolution here, but we
9958 // treat that as a language defect.
9959 goto NeedOverloadResolution;
9960
9963 NeedOverloadResolution:
9965 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
9966
9967 // The standard doesn't describe how to behave if the lookup is ambiguous.
9968 // We treat it as not making the member non-trivial, just like the standard
9969 // mandates for the default constructor. This should rarely matter, because
9970 // the member will also be deleted.
9972 return true;
9973
9974 if (!SMOR.getMethod()) {
9975 assert(SMOR.getKind() ==
9977 return false;
9978 }
9979
9980 // We deliberately don't check if we found a deleted special member. We're
9981 // not supposed to!
9982 if (Selected)
9983 *Selected = SMOR.getMethod();
9984
9985 if (TAH == Sema::TAH_ConsiderTrivialABI &&
9988 return SMOR.getMethod()->isTrivialForCall();
9989 return SMOR.getMethod()->isTrivial();
9990 }
9991
9992 llvm_unreachable("unknown special method kind");
9993}
9994
9996 for (auto *CI : RD->ctors())
9997 if (!CI->isImplicit())
9998 return CI;
9999
10000 // Look for constructor templates.
10002 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
10003 if (CXXConstructorDecl *CD =
10004 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
10005 return CD;
10006 }
10007
10008 return nullptr;
10009}
10010
10011/// The kind of subobject we are checking for triviality. The values of this
10012/// enumeration are used in diagnostics.
10014 /// The subobject is a base class.
10016 /// The subobject is a non-static data member.
10018 /// The object is actually the complete object.
10021
10022/// Check whether the special member selected for a given type would be trivial.
10024 QualType SubType, bool ConstRHS,
10028 bool Diagnose) {
10029 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
10030 if (!SubRD)
10031 return true;
10032
10033 CXXMethodDecl *Selected;
10034 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
10035 ConstRHS, TAH, Diagnose ? &Selected : nullptr))
10036 return true;
10037
10038 if (Diagnose) {
10039 if (ConstRHS)
10040 SubType.addConst();
10041
10042 if (!Selected && CSM == CXXSpecialMemberKind::DefaultConstructor) {
10043 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
10044 << Kind << SubType.getUnqualifiedType();
10046 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
10047 } else if (!Selected)
10048 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
10049 << Kind << SubType.getUnqualifiedType() << llvm::to_underlying(CSM)
10050 << SubType;
10051 else if (Selected->isUserProvided()) {
10052 if (Kind == TSK_CompleteObject)
10053 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
10054 << Kind << SubType.getUnqualifiedType() << llvm::to_underlying(CSM);
10055 else {
10056 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
10057 << Kind << SubType.getUnqualifiedType() << llvm::to_underlying(CSM);
10058 S.Diag(Selected->getLocation(), diag::note_declared_at);
10059 }
10060 } else {
10061 if (Kind != TSK_CompleteObject)
10062 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
10063 << Kind << SubType.getUnqualifiedType() << llvm::to_underlying(CSM);
10064
10065 // Explain why the defaulted or deleted special member isn't trivial.
10067 Diagnose);
10068 }
10069 }
10070
10071 return false;
10072}
10073
10074/// Check whether the members of a class type allow a special member to be
10075/// trivial.
10077 CXXSpecialMemberKind CSM, bool ConstArg,
10079 bool Diagnose) {
10080 for (const auto *FI : RD->fields()) {
10081 if (FI->isInvalidDecl() || FI->isUnnamedBitField())
10082 continue;
10083
10084 QualType FieldType = S.Context.getBaseElementType(FI->getType());
10085
10086 // Pretend anonymous struct or union members are members of this class.
10087 if (FI->isAnonymousStructOrUnion()) {
10088 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
10089 CSM, ConstArg, TAH, Diagnose))
10090 return false;
10091 continue;
10092 }
10093
10094 // C++11 [class.ctor]p5:
10095 // A default constructor is trivial if [...]
10096 // -- no non-static data member of its class has a
10097 // brace-or-equal-initializer
10099 FI->hasInClassInitializer()) {
10100 if (Diagnose)
10101 S.Diag(FI->getLocation(), diag::note_nontrivial_default_member_init)
10102 << FI;
10103 return false;
10104 }
10105
10106 // Objective C ARC 4.3.5:
10107 // [...] nontrivally ownership-qualified types are [...] not trivially
10108 // default constructible, copy constructible, move constructible, copy
10109 // assignable, move assignable, or destructible [...]
10110 if (FieldType.hasNonTrivialObjCLifetime()) {
10111 if (Diagnose)
10112 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
10113 << RD << FieldType.getObjCLifetime();
10114 return false;
10115 }
10116
10117 bool ConstRHS = ConstArg && !FI->isMutable();
10118 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
10119 CSM, TSK_Field, TAH, Diagnose))
10120 return false;
10121 }
10122
10123 return true;
10124}
10125
10126/// Diagnose why the specified class does not have a trivial special member of
10127/// the given kind.
10131
10132 bool ConstArg = (CSM == CXXSpecialMemberKind::CopyConstructor ||
10134 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
10136 /*Diagnose*/true);
10137}
10138
10139/// Determine whether a defaulted or deleted special member function is trivial,
10140/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
10141/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
10143 TrivialABIHandling TAH, bool Diagnose) {
10144 assert(!MD->isUserProvided() && CSM != CXXSpecialMemberKind::Invalid &&
10145 "not special enough");
10146
10147 CXXRecordDecl *RD = MD->getParent();
10148
10149 bool ConstArg = false;
10150
10151 // C++11 [class.copy]p12, p25: [DR1593]
10152 // A [special member] is trivial if [...] its parameter-type-list is
10153 // equivalent to the parameter-type-list of an implicit declaration [...]
10154 switch (CSM) {
10157 // Trivial default constructors and destructors cannot have parameters.
10158 break;
10159
10162 const ParmVarDecl *Param0 = MD->getNonObjectParameter(0);
10163 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
10164
10165 // When ClangABICompat14 is true, CXX copy constructors will only be trivial
10166 // if they are not user-provided and their parameter-type-list is equivalent
10167 // to the parameter-type-list of an implicit declaration. This maintains the
10168 // behavior before dr2171 was implemented.
10169 //
10170 // Otherwise, if ClangABICompat14 is false, All copy constructors can be
10171 // trivial, if they are not user-provided, regardless of the qualifiers on
10172 // the reference type.
10173 const bool ClangABICompat14 = Context.getLangOpts().getClangABICompat() <=
10175 if (!RT ||
10177 ClangABICompat14)) {
10178 if (Diagnose)
10179 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
10180 << Param0->getSourceRange() << Param0->getType()
10183 return false;
10184 }
10185
10186 ConstArg = RT->getPointeeType().isConstQualified();
10187 break;
10188 }
10189
10192 // Trivial move operations always have non-cv-qualified parameters.
10193 const ParmVarDecl *Param0 = MD->getNonObjectParameter(0);
10194 const RValueReferenceType *RT =
10195 Param0->getType()->getAs<RValueReferenceType>();
10196 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
10197 if (Diagnose)
10198 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
10199 << Param0->getSourceRange() << Param0->getType()
10201 return false;
10202 }
10203 break;
10204 }
10205
10207 llvm_unreachable("not a special member");
10208 }
10209
10210 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
10211 if (Diagnose)
10213 diag::note_nontrivial_default_arg)
10215 return false;
10216 }
10217 if (MD->isVariadic()) {
10218 if (Diagnose)
10219 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
10220 return false;
10221 }
10222
10223 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
10224 // A copy/move [constructor or assignment operator] is trivial if
10225 // -- the [member] selected to copy/move each direct base class subobject
10226 // is trivial
10227 //
10228 // C++11 [class.copy]p12, C++11 [class.copy]p25:
10229 // A [default constructor or destructor] is trivial if
10230 // -- all the direct base classes have trivial [default constructors or
10231 // destructors]
10232 for (const auto &BI : RD->bases())
10233 if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
10234 ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
10235 return false;
10236
10237 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
10238 // A copy/move [constructor or assignment operator] for a class X is
10239 // trivial if
10240 // -- for each non-static data member of X that is of class type (or array
10241 // thereof), the constructor selected to copy/move that member is
10242 // trivial
10243 //
10244 // C++11 [class.copy]p12, C++11 [class.copy]p25:
10245 // A [default constructor or destructor] is trivial if
10246 // -- for all of the non-static data members of its class that are of class
10247 // type (or array thereof), each such class has a trivial [default
10248 // constructor or destructor]
10249 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
10250 return false;
10251
10252 // C++11 [class.dtor]p5:
10253 // A destructor is trivial if [...]
10254 // -- the destructor is not virtual
10255 if (CSM == CXXSpecialMemberKind::Destructor && MD->isVirtual()) {
10256 if (Diagnose)
10257 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
10258 return false;
10259 }
10260
10261 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
10262 // A [special member] for class X is trivial if [...]
10263 // -- class X has no virtual functions and no virtual base classes
10265 MD->getParent()->isDynamicClass()) {
10266 if (!Diagnose)
10267 return false;
10268
10269 if (RD->getNumVBases()) {
10270 // Check for virtual bases. We already know that the corresponding
10271 // member in all bases is trivial, so vbases must all be direct.
10272 CXXBaseSpecifier &BS = *RD->vbases_begin();
10273 assert(BS.isVirtual());
10274 Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
10275 return false;
10276 }
10277
10278 // Must have a virtual method.
10279 for (const auto *MI : RD->methods()) {
10280 if (MI->isVirtual()) {
10281 SourceLocation MLoc = MI->getBeginLoc();
10282 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
10283 return false;
10284 }
10285 }
10286
10287 llvm_unreachable("dynamic class with no vbases and no virtual functions");
10288 }
10289
10290 // Looks like it's trivial!
10291 return true;
10292}
10293
10294namespace {
10295struct FindHiddenVirtualMethod {
10296 Sema *S;
10297 CXXMethodDecl *Method;
10298 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
10299 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10300
10301private:
10302 /// Check whether any most overridden method from MD in Methods
10303 static bool CheckMostOverridenMethods(
10304 const CXXMethodDecl *MD,
10305 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
10306 if (MD->size_overridden_methods() == 0)
10307 return Methods.count(MD->getCanonicalDecl());
10308 for (const CXXMethodDecl *O : MD->overridden_methods())
10309 if (CheckMostOverridenMethods(O, Methods))
10310 return true;
10311 return false;
10312 }
10313
10314public:
10315 /// Member lookup function that determines whether a given C++
10316 /// method overloads virtual methods in a base class without overriding any,
10317 /// to be used with CXXRecordDecl::lookupInBases().
10318 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
10319 RecordDecl *BaseRecord =
10320 Specifier->getType()->castAs<RecordType>()->getDecl();
10321
10322 DeclarationName Name = Method->getDeclName();
10323 assert(Name.getNameKind() == DeclarationName::Identifier);
10324
10325 bool foundSameNameMethod = false;
10326 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
10327 for (Path.Decls = BaseRecord->lookup(Name).begin();
10328 Path.Decls != DeclContext::lookup_iterator(); ++Path.Decls) {
10329 NamedDecl *D = *Path.Decls;
10330 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
10331 MD = MD->getCanonicalDecl();
10332 foundSameNameMethod = true;
10333 // Interested only in hidden virtual methods.
10334 if (!MD->isVirtual())
10335 continue;
10336 // If the method we are checking overrides a method from its base
10337 // don't warn about the other overloaded methods. Clang deviates from
10338 // GCC by only diagnosing overloads of inherited virtual functions that
10339 // do not override any other virtual functions in the base. GCC's
10340 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
10341 // function from a base class. These cases may be better served by a
10342 // warning (not specific to virtual functions) on call sites when the
10343 // call would select a different function from the base class, were it
10344 // visible.
10345 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
10346 if (!S->IsOverload(Method, MD, false))
10347 return true;
10348 // Collect the overload only if its hidden.
10349 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
10350 overloadedMethods.push_back(MD);
10351 }
10352 }
10353
10354 if (foundSameNameMethod)
10355 OverloadedMethods.append(overloadedMethods.begin(),
10356 overloadedMethods.end());
10357 return foundSameNameMethod;
10358 }
10359};
10360} // end anonymous namespace
10361
10362/// Add the most overridden methods from MD to Methods
10364 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
10365 if (MD->size_overridden_methods() == 0)
10366 Methods.insert(MD->getCanonicalDecl());
10367 else
10368 for (const CXXMethodDecl *O : MD->overridden_methods())
10369 AddMostOverridenMethods(O, Methods);
10370}
10371
10372/// Check if a method overloads virtual methods in a base class without
10373/// overriding any.
10375 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10376 if (!MD->getDeclName().isIdentifier())
10377 return;
10378
10379 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
10380 /*bool RecordPaths=*/false,
10381 /*bool DetectVirtual=*/false);
10382 FindHiddenVirtualMethod FHVM;
10383 FHVM.Method = MD;
10384 FHVM.S = this;
10385
10386 // Keep the base methods that were overridden or introduced in the subclass
10387 // by 'using' in a set. A base method not in this set is hidden.
10388 CXXRecordDecl *DC = MD->getParent();
10390 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
10391 NamedDecl *ND = *I;
10392 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
10393 ND = shad->getTargetDecl();
10394 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
10395 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
10396 }
10397
10398 if (DC->lookupInBases(FHVM, Paths))
10399 OverloadedMethods = FHVM.OverloadedMethods;
10400}
10401
10403 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10404 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
10405 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
10407 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
10408 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
10409 Diag(overloadedMD->getLocation(), PD);
10410 }
10411}
10412
10413/// Diagnose methods which overload virtual methods in a base class
10414/// without overriding any.
10416 if (MD->isInvalidDecl())
10417 return;
10418
10419 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
10420 return;
10421
10422 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10423 FindHiddenVirtualMethods(MD, OverloadedMethods);
10424 if (!OverloadedMethods.empty()) {
10425 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
10426 << MD << (OverloadedMethods.size() > 1);
10427
10428 NoteHiddenVirtualMethods(MD, OverloadedMethods);
10429 }
10430}
10431
10433 auto PrintDiagAndRemoveAttr = [&](unsigned N) {
10434 // No diagnostics if this is a template instantiation.
10436 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
10437 diag::ext_cannot_use_trivial_abi) << &RD;
10438 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
10439 diag::note_cannot_use_trivial_abi_reason) << &RD << N;
10440 }
10441 RD.dropAttr<TrivialABIAttr>();
10442 };
10443
10444 // Ill-formed if the copy and move constructors are deleted.
10445 auto HasNonDeletedCopyOrMoveConstructor = [&]() {
10446 // If the type is dependent, then assume it might have
10447 // implicit copy or move ctor because we won't know yet at this point.
10448 if (RD.isDependentType())
10449 return true;
10452 return true;
10455 return true;
10456 for (const CXXConstructorDecl *CD : RD.ctors())
10457 if (CD->isCopyOrMoveConstructor() && !CD->isDeleted())
10458 return true;
10459 return false;
10460 };
10461
10462 if (!HasNonDeletedCopyOrMoveConstructor()) {
10463 PrintDiagAndRemoveAttr(0);
10464 return;
10465 }
10466
10467 // Ill-formed if the struct has virtual functions.
10468 if (RD.isPolymorphic()) {
10469 PrintDiagAndRemoveAttr(1);
10470 return;
10471 }
10472
10473 for (const auto &B : RD.bases()) {
10474 // Ill-formed if the base class is non-trivial for the purpose of calls or a
10475 // virtual base.
10476 if (!B.getType()->isDependentType() &&
10477 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) {
10478 PrintDiagAndRemoveAttr(2);
10479 return;
10480 }
10481
10482 if (B.isVirtual()) {
10483 PrintDiagAndRemoveAttr(3);
10484 return;
10485 }
10486 }
10487
10488 for (const auto *FD : RD.fields()) {
10489 // Ill-formed if the field is an ObjectiveC pointer or of a type that is
10490 // non-trivial for the purpose of calls.
10491 QualType FT = FD->getType();
10493 PrintDiagAndRemoveAttr(4);
10494 return;
10495 }
10496
10497 if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
10498 if (!RT->isDependentType() &&
10499 !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
10500 PrintDiagAndRemoveAttr(5);
10501 return;
10502 }
10503 }
10504}
10505
10508 SourceLocation RBrac, const ParsedAttributesView &AttrList) {
10509 if (!TagDecl)
10510 return;
10511
10513
10514 for (const ParsedAttr &AL : AttrList) {
10515 if (AL.getKind() != ParsedAttr::AT_Visibility)
10516 continue;
10517 AL.setInvalid();
10518 Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL;
10519 }
10520
10521 ActOnFields(S, RLoc, TagDecl,
10523 // strict aliasing violation!
10524 reinterpret_cast<Decl **>(FieldCollector->getCurFields()),
10525 FieldCollector->getCurNumFields()),
10526 LBrac, RBrac, AttrList);
10527
10528 CheckCompletedCXXClass(S, cast<CXXRecordDecl>(TagDecl));
10529}
10530
10531/// Find the equality comparison functions that should be implicitly declared
10532/// in a given class definition, per C++2a [class.compare.default]p3.
10534 ASTContext &Ctx, CXXRecordDecl *RD,
10536 DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual);
10537 if (!RD->lookup(EqEq).empty())
10538 // Member operator== explicitly declared: no implicit operator==s.
10539 return;
10540
10541 // Traverse friends looking for an '==' or a '<=>'.
10542 for (FriendDecl *Friend : RD->friends()) {
10543 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl());
10544 if (!FD) continue;
10545
10546 if (FD->getOverloadedOperator() == OO_EqualEqual) {
10547 // Friend operator== explicitly declared: no implicit operator==s.
10548 Spaceships.clear();
10549 return;
10550 }
10551
10552 if (FD->getOverloadedOperator() == OO_Spaceship &&
10554 Spaceships.push_back(FD);
10555 }
10556
10557 // Look for members named 'operator<=>'.
10558 DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(OO_Spaceship);
10559 for (NamedDecl *ND : RD->lookup(Cmp)) {
10560 // Note that we could find a non-function here (either a function template
10561 // or a using-declaration). Neither case results in an implicit
10562 // 'operator=='.
10563 if (auto *FD = dyn_cast<FunctionDecl>(ND))
10564 if (FD->isExplicitlyDefaulted())
10565 Spaceships.push_back(FD);
10566 }
10567}
10568
10569/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
10570/// special functions, such as the default constructor, copy
10571/// constructor, or destructor, to the given C++ class (C++
10572/// [special]p1). This routine can only be executed just before the
10573/// definition of the class is complete.
10575 // Don't add implicit special members to templated classes.
10576 // FIXME: This means unqualified lookups for 'operator=' within a class
10577 // template don't work properly.
10578 if (!ClassDecl->isDependentType()) {
10579 if (ClassDecl->needsImplicitDefaultConstructor()) {
10581
10582 if (ClassDecl->hasInheritedConstructor())
10584 }
10585
10586 if (ClassDecl->needsImplicitCopyConstructor()) {
10588
10589 // If the properties or semantics of the copy constructor couldn't be
10590 // determined while the class was being declared, force a declaration
10591 // of it now.
10593 ClassDecl->hasInheritedConstructor())
10595 // For the MS ABI we need to know whether the copy ctor is deleted. A
10596 // prerequisite for deleting the implicit copy ctor is that the class has
10597 // a move ctor or move assignment that is either user-declared or whose
10598 // semantics are inherited from a subobject. FIXME: We should provide a
10599 // more direct way for CodeGen to ask whether the constructor was deleted.
10600 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
10601 (ClassDecl->hasUserDeclaredMoveConstructor() ||
10603 ClassDecl->hasUserDeclaredMoveAssignment() ||
10606 }
10607
10608 if (getLangOpts().CPlusPlus11 &&
10609 ClassDecl->needsImplicitMoveConstructor()) {
10611
10613 ClassDecl->hasInheritedConstructor())
10615 }
10616
10617 if (ClassDecl->needsImplicitCopyAssignment()) {
10619
10620 // If we have a dynamic class, then the copy assignment operator may be
10621 // virtual, so we have to declare it immediately. This ensures that, e.g.,
10622 // it shows up in the right place in the vtable and that we diagnose
10623 // problems with the implicit exception specification.
10624 if (ClassDecl->isDynamicClass() ||
10626 ClassDecl->hasInheritedAssignment())
10628 }
10629
10630 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
10632
10633 // Likewise for the move assignment operator.
10634 if (ClassDecl->isDynamicClass() ||
10636 ClassDecl->hasInheritedAssignment())
10638 }
10639
10640 if (ClassDecl->needsImplicitDestructor()) {
10642
10643 // If we have a dynamic class, then the destructor may be virtual, so we
10644 // have to declare the destructor immediately. This ensures that, e.g., it
10645 // shows up in the right place in the vtable and that we diagnose problems
10646 // with the implicit exception specification.
10647 if (ClassDecl->isDynamicClass() ||
10649 DeclareImplicitDestructor(ClassDecl);
10650 }
10651 }
10652
10653 // C++2a [class.compare.default]p3:
10654 // If the member-specification does not explicitly declare any member or
10655 // friend named operator==, an == operator function is declared implicitly
10656 // for each defaulted three-way comparison operator function defined in
10657 // the member-specification
10658 // FIXME: Consider doing this lazily.
10659 // We do this during the initial parse for a class template, not during
10660 // instantiation, so that we can handle unqualified lookups for 'operator=='
10661 // when parsing the template.
10663 llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships;
10665 DefaultedSpaceships);
10666 for (auto *FD : DefaultedSpaceships)
10667 DeclareImplicitEqualityComparison(ClassDecl, FD);
10668 }
10669}
10670
10671unsigned
10673 llvm::function_ref<Scope *()> EnterScope) {
10674 if (!D)
10675 return 0;
10677
10678 // In order to get name lookup right, reenter template scopes in order from
10679 // outermost to innermost.
10681 DeclContext *LookupDC = dyn_cast<DeclContext>(D);
10682
10683 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
10684 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
10685 ParameterLists.push_back(DD->getTemplateParameterList(i));
10686
10687 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
10688 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
10689 ParameterLists.push_back(FTD->getTemplateParameters());
10690 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
10691 LookupDC = VD->getDeclContext();
10692
10694 ParameterLists.push_back(VTD->getTemplateParameters());
10695 else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D))
10696 ParameterLists.push_back(PSD->getTemplateParameters());
10697 }
10698 } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
10699 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
10700 ParameterLists.push_back(TD->getTemplateParameterList(i));
10701
10702 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
10704 ParameterLists.push_back(CTD->getTemplateParameters());
10705 else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
10706 ParameterLists.push_back(PSD->getTemplateParameters());
10707 }
10708 }
10709 // FIXME: Alias declarations and concepts.
10710
10711 unsigned Count = 0;
10712 Scope *InnermostTemplateScope = nullptr;
10713 for (TemplateParameterList *Params : ParameterLists) {
10714 // Ignore explicit specializations; they don't contribute to the template
10715 // depth.
10716 if (Params->size() == 0)
10717 continue;
10718
10719 InnermostTemplateScope = EnterScope();
10720 for (NamedDecl *Param : *Params) {
10721 if (Param->getDeclName()) {
10722 InnermostTemplateScope->AddDecl(Param);
10723 IdResolver.AddDecl(Param);
10724 }
10725 }
10726 ++Count;
10727 }
10728
10729 // Associate the new template scopes with the corresponding entities.
10730 if (InnermostTemplateScope) {
10731 assert(LookupDC && "no enclosing DeclContext for template lookup");
10732 EnterTemplatedContext(InnermostTemplateScope, LookupDC);
10733 }
10734
10735 return Count;
10736}
10737
10739 if (!RecordD) return;
10740 AdjustDeclIfTemplate(RecordD);
10741 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
10743}
10744
10746 if (!RecordD) return;
10748}
10749
10750/// This is used to implement the constant expression evaluation part of the
10751/// attribute enable_if extension. There is nothing in standard C++ which would
10752/// require reentering parameters.
10754 if (!Param)
10755 return;
10756
10757 S->AddDecl(Param);
10758 if (Param->getDeclName())
10759 IdResolver.AddDecl(Param);
10760}
10761
10762/// ActOnStartDelayedCXXMethodDeclaration - We have completed
10763/// parsing a top-level (non-nested) C++ class, and we are now
10764/// parsing those parts of the given Method declaration that could
10765/// not be parsed earlier (C++ [class.mem]p2), such as default
10766/// arguments. This action should enter the scope of the given
10767/// Method declaration as if we had just parsed the qualified method
10768/// name. However, it should not bring the parameters into scope;
10769/// that will be performed by ActOnDelayedCXXMethodParameter.
10771}
10772
10773/// ActOnDelayedCXXMethodParameter - We've already started a delayed
10774/// C++ method declaration. We're (re-)introducing the given
10775/// function parameter into scope for use in parsing later parts of
10776/// the method declaration. For example, we could see an
10777/// ActOnParamDefaultArgument event for this parameter.
10779 if (!ParamD)
10780 return;
10781
10782 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
10783
10784 S->AddDecl(Param);
10785 if (Param->getDeclName())
10786 IdResolver.AddDecl(Param);
10787}
10788
10789/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
10790/// processing the delayed method declaration for Method. The method
10791/// declaration is now considered finished. There may be a separate
10792/// ActOnStartOfFunctionDef action later (not necessarily
10793/// immediately!) for this method, if it was also defined inside the
10794/// class body.
10796 if (!MethodD)
10797 return;
10798
10799 AdjustDeclIfTemplate(MethodD);
10800
10801 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
10802
10803 // Now that we have our default arguments, check the constructor
10804 // again. It could produce additional diagnostics or affect whether
10805 // the class has implicitly-declared destructors, among other
10806 // things.
10807 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
10808 CheckConstructor(Constructor);
10809
10810 // Check the default arguments, which we may have added.
10811 if (!Method->isInvalidDecl())
10813}
10814
10815// Emit the given diagnostic for each non-address-space qualifier.
10816// Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
10817static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
10819 if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
10820 bool DiagOccured = false;
10822 [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName,
10823 SourceLocation SL) {
10824 // This diagnostic should be emitted on any qualifier except an addr
10825 // space qualifier. However, forEachQualifier currently doesn't visit
10826 // addr space qualifiers, so there's no way to write this condition
10827 // right now; we just diagnose on everything.
10828 S.Diag(SL, DiagID) << QualName << SourceRange(SL);
10829 DiagOccured = true;
10830 });
10831 if (DiagOccured)
10832 D.setInvalidType();
10833 }
10834}
10835
10836/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
10837/// the well-formedness of the constructor declarator @p D with type @p
10838/// R. If there are any errors in the declarator, this routine will
10839/// emit diagnostics and set the invalid bit to true. In any case, the type
10840/// will be updated to reflect a well-formed type for the constructor and
10841/// returned.
10843 StorageClass &SC) {
10844 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
10845
10846 // C++ [class.ctor]p3:
10847 // A constructor shall not be virtual (10.3) or static (9.4). A
10848 // constructor can be invoked for a const, volatile or const
10849 // volatile object. A constructor shall not be declared const,
10850 // volatile, or const volatile (9.3.2).
10851 if (isVirtual) {
10852 if (!D.isInvalidType())
10853 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10854 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
10856 D.setInvalidType();
10857 }
10858 if (SC == SC_Static) {
10859 if (!D.isInvalidType())
10860 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10861 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10863 D.setInvalidType();
10864 SC = SC_None;
10865 }
10866
10867 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10869 diag::err_constructor_return_type, TypeQuals, SourceLocation(),
10873 D.setInvalidType();
10874 }
10875
10876 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor);
10877
10878 // C++0x [class.ctor]p4:
10879 // A constructor shall not be declared with a ref-qualifier.
10881 if (FTI.hasRefQualifier()) {
10882 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
10885 D.setInvalidType();
10886 }
10887
10888 // Rebuild the function type "R" without any type qualifiers (in
10889 // case any of the errors above fired) and with "void" as the
10890 // return type, since constructors don't have return types.
10891 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10892 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
10893 return R;
10894
10896 EPI.TypeQuals = Qualifiers();
10897 EPI.RefQualifier = RQ_None;
10898
10899 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
10900}
10901
10902/// CheckConstructor - Checks a fully-formed constructor for
10903/// well-formedness, issuing any diagnostics required. Returns true if
10904/// the constructor declarator is invalid.
10906 CXXRecordDecl *ClassDecl
10907 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
10908 if (!ClassDecl)
10909 return Constructor->setInvalidDecl();
10910
10911 // C++ [class.copy]p3:
10912 // A declaration of a constructor for a class X is ill-formed if
10913 // its first parameter is of type (optionally cv-qualified) X and
10914 // either there are no other parameters or else all other
10915 // parameters have default arguments.
10916 if (!Constructor->isInvalidDecl() &&
10917 Constructor->hasOneParamOrDefaultArgs() &&
10918 Constructor->getTemplateSpecializationKind() !=
10920 QualType ParamType = Constructor->getParamDecl(0)->getType();
10921 QualType ClassTy = Context.getTagDeclType(ClassDecl);
10922 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
10923 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
10924 const char *ConstRef
10925 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
10926 : " const &";
10927 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
10928 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
10929
10930 // FIXME: Rather that making the constructor invalid, we should endeavor
10931 // to fix the type.
10932 Constructor->setInvalidDecl();
10933 }
10934 }
10935}
10936
10937/// CheckDestructor - Checks a fully-formed destructor definition for
10938/// well-formedness, issuing any diagnostics required. Returns true
10939/// on error.
10941 CXXRecordDecl *RD = Destructor->getParent();
10942
10943 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
10945
10946 if (!Destructor->isImplicit())
10947 Loc = Destructor->getLocation();
10948 else
10949 Loc = RD->getLocation();
10950
10951 // If we have a virtual destructor, look up the deallocation function
10952 if (FunctionDecl *OperatorDelete =
10954 Expr *ThisArg = nullptr;
10955
10956 // If the notional 'delete this' expression requires a non-trivial
10957 // conversion from 'this' to the type of a destroying operator delete's
10958 // first parameter, perform that conversion now.
10959 if (OperatorDelete->isDestroyingOperatorDelete()) {
10960 QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
10961 if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
10962 // C++ [class.dtor]p13:
10963 // ... as if for the expression 'delete this' appearing in a
10964 // non-virtual destructor of the destructor's class.
10965 ContextRAII SwitchContext(*this, Destructor);
10966 ExprResult This =
10967 ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
10968 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
10969 This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
10970 if (This.isInvalid()) {
10971 // FIXME: Register this as a context note so that it comes out
10972 // in the right order.
10973 Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
10974 return true;
10975 }
10976 ThisArg = This.get();
10977 }
10978 }
10979
10980 DiagnoseUseOfDecl(OperatorDelete, Loc);
10981 MarkFunctionReferenced(Loc, OperatorDelete);
10982 Destructor->setOperatorDelete(OperatorDelete, ThisArg);
10983 }
10984 }
10985
10986 return false;
10987}
10988
10989/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
10990/// the well-formednes of the destructor declarator @p D with type @p
10991/// R. If there are any errors in the declarator, this routine will
10992/// emit diagnostics and set the declarator to invalid. Even if this happens,
10993/// will be updated to reflect a well-formed type for the destructor and
10994/// returned.
10996 StorageClass& SC) {
10997 // C++ [class.dtor]p1:
10998 // [...] A typedef-name that names a class is a class-name
10999 // (7.1.3); however, a typedef-name that names a class shall not
11000 // be used as the identifier in the declarator for a destructor
11001 // declaration.
11002 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
11003 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
11004 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
11005 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
11006 else if (const TemplateSpecializationType *TST =
11007 DeclaratorType->getAs<TemplateSpecializationType>())
11008 if (TST->isTypeAlias())
11009 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
11010 << DeclaratorType << 1;
11011
11012 // C++ [class.dtor]p2:
11013 // A destructor is used to destroy objects of its class type. A
11014 // destructor takes no parameters, and no return type can be
11015 // specified for it (not even void). The address of a destructor
11016 // shall not be taken. A destructor shall not be static. A
11017 // destructor can be invoked for a const, volatile or const
11018 // volatile object. A destructor shall not be declared const,
11019 // volatile or const volatile (9.3.2).
11020 if (SC == SC_Static) {
11021 if (!D.isInvalidType())
11022 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
11023 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
11026
11027 SC = SC_None;
11028 }
11029 if (!D.isInvalidType()) {
11030 // Destructors don't have return types, but the parser will
11031 // happily parse something like:
11032 //
11033 // class X {
11034 // float ~X();
11035 // };
11036 //
11037 // The return type will be eliminated later.
11038 if (D.getDeclSpec().hasTypeSpecifier())
11039 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
11042 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
11043 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
11049 D.setInvalidType();
11050 }
11051 }
11052
11053 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor);
11054
11055 // C++0x [class.dtor]p2:
11056 // A destructor shall not be declared with a ref-qualifier.
11058 if (FTI.hasRefQualifier()) {
11059 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
11062 D.setInvalidType();
11063 }
11064
11065 // Make sure we don't have any parameters.
11066 if (FTIHasNonVoidParameters(FTI)) {
11067 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
11068
11069 // Delete the parameters.
11070 FTI.freeParams();
11071 D.setInvalidType();
11072 }
11073
11074 // Make sure the destructor isn't variadic.
11075 if (FTI.isVariadic) {
11076 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
11077 D.setInvalidType();
11078 }
11079
11080 // Rebuild the function type "R" without any type qualifiers or
11081 // parameters (in case any of the errors above fired) and with
11082 // "void" as the return type, since destructors don't have return
11083 // types.
11084 if (!D.isInvalidType())
11085 return R;
11086
11087 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
11089 EPI.Variadic = false;
11090 EPI.TypeQuals = Qualifiers();
11091 EPI.RefQualifier = RQ_None;
11092 return Context.getFunctionType(Context.VoidTy, std::nullopt, EPI);
11093}
11094
11095static void extendLeft(SourceRange &R, SourceRange Before) {
11096 if (Before.isInvalid())
11097 return;
11098 R.setBegin(Before.getBegin());
11099 if (R.getEnd().isInvalid())
11100 R.setEnd(Before.getEnd());
11101}
11102
11103static void extendRight(SourceRange &R, SourceRange After) {
11104 if (After.isInvalid())
11105 return;
11106 if (R.getBegin().isInvalid())
11107 R.setBegin(After.getBegin());
11108 R.setEnd(After.getEnd());
11109}
11110
11111/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
11112/// well-formednes of the conversion function declarator @p D with
11113/// type @p R. If there are any errors in the declarator, this routine
11114/// will emit diagnostics and return true. Otherwise, it will return
11115/// false. Either way, the type @p R will be updated to reflect a
11116/// well-formed type for the conversion operator.
11118 StorageClass& SC) {
11119 // C++ [class.conv.fct]p1:
11120 // Neither parameter types nor return type can be specified. The
11121 // type of a conversion function (8.3.5) is "function taking no
11122 // parameter returning conversion-type-id."
11123 if (SC == SC_Static) {
11124 if (!D.isInvalidType())
11125 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
11127 << D.getName().getSourceRange();
11128 D.setInvalidType();
11129 SC = SC_None;
11130 }
11131
11132 TypeSourceInfo *ConvTSI = nullptr;
11133 QualType ConvType =
11135
11136 const DeclSpec &DS = D.getDeclSpec();
11137 if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
11138 // Conversion functions don't have return types, but the parser will
11139 // happily parse something like:
11140 //
11141 // class X {
11142 // float operator bool();
11143 // };
11144 //
11145 // The return type will be changed later anyway.
11146 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
11149 D.setInvalidType();
11150 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
11151 // It's also plausible that the user writes type qualifiers in the wrong
11152 // place, such as:
11153 // struct S { const operator int(); };
11154 // FIXME: we could provide a fixit to move the qualifiers onto the
11155 // conversion type.
11156 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
11157 << SourceRange(D.getIdentifierLoc()) << 0;
11158 D.setInvalidType();
11159 }
11160 const auto *Proto = R->castAs<FunctionProtoType>();
11161 // Make sure we don't have any parameters.
11163 unsigned NumParam = Proto->getNumParams();
11164
11165 // [C++2b]
11166 // A conversion function shall have no non-object parameters.
11167 if (NumParam == 1) {
11169 if (const auto *First =
11170 dyn_cast_if_present<ParmVarDecl>(FTI.Params[0].Param);
11171 First && First->isExplicitObjectParameter())
11172 NumParam--;
11173 }
11174
11175 if (NumParam != 0) {
11176 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
11177 // Delete the parameters.
11178 FTI.freeParams();
11179 D.setInvalidType();
11180 } else if (Proto->isVariadic()) {
11181 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
11182 D.setInvalidType();
11183 }
11184
11185 // Diagnose "&operator bool()" and other such nonsense. This
11186 // is actually a gcc extension which we don't support.
11187 if (Proto->getReturnType() != ConvType) {
11188 bool NeedsTypedef = false;
11189 SourceRange Before, After;
11190
11191 // Walk the chunks and extract information on them for our diagnostic.
11192 bool PastFunctionChunk = false;
11193 for (auto &Chunk : D.type_objects()) {
11194 switch (Chunk.Kind) {
11196 if (!PastFunctionChunk) {
11197 if (Chunk.Fun.HasTrailingReturnType) {
11198 TypeSourceInfo *TRT = nullptr;
11199 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
11200 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
11201 }
11202 PastFunctionChunk = true;
11203 break;
11204 }
11205 [[fallthrough]];
11207 NeedsTypedef = true;
11208 extendRight(After, Chunk.getSourceRange());
11209 break;
11210
11216 extendLeft(Before, Chunk.getSourceRange());
11217 break;
11218
11220 extendLeft(Before, Chunk.Loc);
11221 extendRight(After, Chunk.EndLoc);
11222 break;
11223 }
11224 }
11225
11226 SourceLocation Loc = Before.isValid() ? Before.getBegin() :
11227 After.isValid() ? After.getBegin() :
11228 D.getIdentifierLoc();
11229 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
11230 DB << Before << After;
11231
11232 if (!NeedsTypedef) {
11233 DB << /*don't need a typedef*/0;
11234
11235 // If we can provide a correct fix-it hint, do so.
11236 if (After.isInvalid() && ConvTSI) {
11237 SourceLocation InsertLoc =
11239 DB << FixItHint::CreateInsertion(InsertLoc, " ")
11241 InsertLoc, CharSourceRange::getTokenRange(Before))
11242 << FixItHint::CreateRemoval(Before);
11243 }
11244 } else if (!Proto->getReturnType()->isDependentType()) {
11245 DB << /*typedef*/1 << Proto->getReturnType();
11246 } else if (getLangOpts().CPlusPlus11) {
11247 DB << /*alias template*/2 << Proto->getReturnType();
11248 } else {
11249 DB << /*might not be fixable*/3;
11250 }
11251
11252 // Recover by incorporating the other type chunks into the result type.
11253 // Note, this does *not* change the name of the function. This is compatible
11254 // with the GCC extension:
11255 // struct S { &operator int(); } s;
11256 // int &r = s.operator int(); // ok in GCC
11257 // S::operator int&() {} // error in GCC, function name is 'operator int'.
11258 ConvType = Proto->getReturnType();
11259 }
11260
11261 // C++ [class.conv.fct]p4:
11262 // The conversion-type-id shall not represent a function type nor
11263 // an array type.
11264 if (ConvType->isArrayType()) {
11265 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
11266 ConvType = Context.getPointerType(ConvType);
11267 D.setInvalidType();
11268 } else if (ConvType->isFunctionType()) {
11269 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
11270 ConvType = Context.getPointerType(ConvType);
11271 D.setInvalidType();
11272 }
11273
11274 // Rebuild the function type "R" without any parameters (in case any
11275 // of the errors above fired) and with the conversion type as the
11276 // return type.
11277 if (D.isInvalidType())
11278 R = Context.getFunctionType(ConvType, std::nullopt,
11279 Proto->getExtProtoInfo());
11280
11281 // C++0x explicit conversion operators.
11285 ? diag::warn_cxx98_compat_explicit_conversion_functions
11286 : diag::ext_explicit_conversion_functions)
11288}
11289
11290/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
11291/// the declaration of the given C++ conversion function. This routine
11292/// is responsible for recording the conversion function in the C++
11293/// class, if possible.
11295 assert(Conversion && "Expected to receive a conversion function declaration");
11296
11297 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
11298
11299 // Make sure we aren't redeclaring the conversion function.
11300 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
11301 // C++ [class.conv.fct]p1:
11302 // [...] A conversion function is never used to convert a
11303 // (possibly cv-qualified) object to the (possibly cv-qualified)
11304 // same object type (or a reference to it), to a (possibly
11305 // cv-qualified) base class of that type (or a reference to it),
11306 // or to (possibly cv-qualified) void.
11307 QualType ClassType
11309 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
11310 ConvType = ConvTypeRef->getPointeeType();
11311 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
11313 /* Suppress diagnostics for instantiations. */;
11314 else if (Conversion->size_overridden_methods() != 0)
11315 /* Suppress diagnostics for overriding virtual function in a base class. */;
11316 else if (ConvType->isRecordType()) {
11317 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
11318 if (ConvType == ClassType)
11319 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
11320 << ClassType;
11321 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
11322 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
11323 << ClassType << ConvType;
11324 } else if (ConvType->isVoidType()) {
11325 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
11326 << ClassType << ConvType;
11327 }
11328
11329 if (FunctionTemplateDecl *ConversionTemplate =
11330 Conversion->getDescribedFunctionTemplate()) {
11331 if (const auto *ConvTypePtr = ConvType->getAs<PointerType>()) {
11332 ConvType = ConvTypePtr->getPointeeType();
11333 }
11334 if (ConvType->isUndeducedAutoType()) {
11335 Diag(Conversion->getTypeSpecStartLoc(), diag::err_auto_not_allowed)
11336 << getReturnTypeLoc(Conversion).getSourceRange()
11337 << llvm::to_underlying(ConvType->castAs<AutoType>()->getKeyword())
11338 << /* in declaration of conversion function template= */ 24;
11339 }
11340
11341 return ConversionTemplate;
11342 }
11343
11344 return Conversion;
11345}
11346
11348 DeclarationName Name, QualType R) {
11349 CheckExplicitObjectMemberFunction(D, Name, R, false, DC);
11350}
11351
11353 CheckExplicitObjectMemberFunction(D, {}, {}, true);
11354}
11355
11357 DeclarationName Name, QualType R,
11358 bool IsLambda, DeclContext *DC) {
11359 if (!D.isFunctionDeclarator())
11360 return;
11361
11363 if (FTI.NumParams == 0)
11364 return;
11365 ParmVarDecl *ExplicitObjectParam = nullptr;
11366 for (unsigned Idx = 0; Idx < FTI.NumParams; Idx++) {
11367 const auto &ParamInfo = FTI.Params[Idx];
11368 if (!ParamInfo.Param)
11369 continue;
11370 ParmVarDecl *Param = cast<ParmVarDecl>(ParamInfo.Param);
11371 if (!Param->isExplicitObjectParameter())
11372 continue;
11373 if (Idx == 0) {
11374 ExplicitObjectParam = Param;
11375 continue;
11376 } else {
11377 Diag(Param->getLocation(),
11378 diag::err_explicit_object_parameter_must_be_first)
11379 << IsLambda << Param->getSourceRange();
11380 }
11381 }
11382 if (!ExplicitObjectParam)
11383 return;
11384
11385 if (ExplicitObjectParam->hasDefaultArg()) {
11386 Diag(ExplicitObjectParam->getLocation(),
11387 diag::err_explicit_object_default_arg)
11388 << ExplicitObjectParam->getSourceRange();
11389 }
11390
11393 D.isStaticMember())) {
11394 Diag(ExplicitObjectParam->getBeginLoc(),
11395 diag::err_explicit_object_parameter_nonmember)
11396 << D.getSourceRange() << /*static=*/0 << IsLambda;
11397 D.setInvalidType();
11398 }
11399
11400 if (D.getDeclSpec().isVirtualSpecified()) {
11401 Diag(ExplicitObjectParam->getBeginLoc(),
11402 diag::err_explicit_object_parameter_nonmember)
11403 << D.getSourceRange() << /*virtual=*/1 << IsLambda;
11404 D.setInvalidType();
11405 }
11406
11407 if (IsLambda && FTI.hasMutableQualifier()) {
11408 Diag(ExplicitObjectParam->getBeginLoc(),
11409 diag::err_explicit_object_parameter_mutable)
11410 << D.getSourceRange();
11411 }
11412
11413 if (IsLambda)
11414 return;
11415
11416 if (!DC || !DC->isRecord()) {
11417 Diag(ExplicitObjectParam->getLocation(),
11418 diag::err_explicit_object_parameter_nonmember)
11419 << D.getSourceRange() << /*non-member=*/2 << IsLambda;
11420 D.setInvalidType();
11421 return;
11422 }
11423
11424 // CWG2674: constructors and destructors cannot have explicit parameters.
11425 if (Name.getNameKind() == DeclarationName::CXXConstructorName ||
11426 Name.getNameKind() == DeclarationName::CXXDestructorName) {
11427 Diag(ExplicitObjectParam->getBeginLoc(),
11428 diag::err_explicit_object_parameter_constructor)
11429 << (Name.getNameKind() == DeclarationName::CXXDestructorName)
11430 << D.getSourceRange();
11431 D.setInvalidType();
11432 }
11433}
11434
11435namespace {
11436/// Utility class to accumulate and print a diagnostic listing the invalid
11437/// specifier(s) on a declaration.
11438struct BadSpecifierDiagnoser {
11439 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
11440 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
11441 ~BadSpecifierDiagnoser() {
11442 Diagnostic << Specifiers;
11443 }
11444
11445 template<typename T> void check(SourceLocation SpecLoc, T Spec) {
11446 return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
11447 }
11448 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
11449 return check(SpecLoc,
11451 }
11452 void check(SourceLocation SpecLoc, const char *Spec) {
11453 if (SpecLoc.isInvalid()) return;
11454 Diagnostic << SourceRange(SpecLoc, SpecLoc);
11455 if (!Specifiers.empty()) Specifiers += " ";
11456 Specifiers += Spec;
11457 }
11458
11459 Sema &S;
11461 std::string Specifiers;
11462};
11463}
11464
11465/// Check the validity of a declarator that we parsed for a deduction-guide.
11466/// These aren't actually declarators in the grammar, so we need to check that
11467/// the user didn't specify any pieces that are not part of the deduction-guide
11468/// grammar. Return true on invalid deduction-guide.
11470 StorageClass &SC) {
11471 TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
11472 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
11473 assert(GuidedTemplateDecl && "missing template decl for deduction guide");
11474
11475 // C++ [temp.deduct.guide]p3:
11476 // A deduction-gide shall be declared in the same scope as the
11477 // corresponding class template.
11479 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
11480 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
11481 << GuidedTemplateDecl;
11482 NoteTemplateLocation(*GuidedTemplateDecl);
11483 }
11484
11485 auto &DS = D.getMutableDeclSpec();
11486 // We leave 'friend' and 'virtual' to be rejected in the normal way.
11487 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
11488 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
11489 DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
11490 BadSpecifierDiagnoser Diagnoser(
11491 *this, D.getIdentifierLoc(),
11492 diag::err_deduction_guide_invalid_specifier);
11493
11494 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
11495 DS.ClearStorageClassSpecs();
11496 SC = SC_None;
11497
11498 // 'explicit' is permitted.
11499 Diagnoser.check(DS.getInlineSpecLoc(), "inline");
11500 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
11501 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
11502 DS.ClearConstexprSpec();
11503
11504 Diagnoser.check(DS.getConstSpecLoc(), "const");
11505 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
11506 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
11507 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
11508 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
11509 DS.ClearTypeQualifiers();
11510
11511 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
11512 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
11513 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
11514 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
11515 DS.ClearTypeSpecType();
11516 }
11517
11518 if (D.isInvalidType())
11519 return true;
11520
11521 // Check the declarator is simple enough.
11522 bool FoundFunction = false;
11523 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
11524 if (Chunk.Kind == DeclaratorChunk::Paren)
11525 continue;
11526 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
11528 diag::err_deduction_guide_with_complex_decl)
11529 << D.getSourceRange();
11530 break;
11531 }
11532 if (!Chunk.Fun.hasTrailingReturnType())
11533 return Diag(D.getName().getBeginLoc(),
11534 diag::err_deduction_guide_no_trailing_return_type);
11535
11536 // Check that the return type is written as a specialization of
11537 // the template specified as the deduction-guide's name.
11538 // The template name may not be qualified. [temp.deduct.guide]
11539 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
11540 TypeSourceInfo *TSI = nullptr;
11541 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
11542 assert(TSI && "deduction guide has valid type but invalid return type?");
11543 bool AcceptableReturnType = false;
11544 bool MightInstantiateToSpecialization = false;
11545 if (auto RetTST =
11547 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
11548 bool TemplateMatches =
11549 Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
11550 auto TKind = SpecifiedName.getKind();
11551 // A Using TemplateName can't actually be valid (either it's qualified, or
11552 // we're in the wrong scope). But we have diagnosed these problems
11553 // already.
11554 bool SimplyWritten = TKind == TemplateName::Template ||
11556 if (SimplyWritten && TemplateMatches)
11557 AcceptableReturnType = true;
11558 else {
11559 // This could still instantiate to the right type, unless we know it
11560 // names the wrong class template.
11561 auto *TD = SpecifiedName.getAsTemplateDecl();
11562 MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
11563 !TemplateMatches);
11564 }
11565 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
11566 MightInstantiateToSpecialization = true;
11567 }
11568
11569 if (!AcceptableReturnType)
11570 return Diag(TSI->getTypeLoc().getBeginLoc(),
11571 diag::err_deduction_guide_bad_trailing_return_type)
11572 << GuidedTemplate << TSI->getType()
11573 << MightInstantiateToSpecialization
11574 << TSI->getTypeLoc().getSourceRange();
11575
11576 // Keep going to check that we don't have any inner declarator pieces (we
11577 // could still have a function returning a pointer to a function).
11578 FoundFunction = true;
11579 }
11580
11581 if (D.isFunctionDefinition())
11582 // we can still create a valid deduction guide here.
11583 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
11584 return false;
11585}
11586
11587//===----------------------------------------------------------------------===//
11588// Namespace Handling
11589//===----------------------------------------------------------------------===//
11590
11591/// Diagnose a mismatch in 'inline' qualifiers when a namespace is
11592/// reopened.
11595 IdentifierInfo *II, bool *IsInline,
11596 NamespaceDecl *PrevNS) {
11597 assert(*IsInline != PrevNS->isInline());
11598
11599 // 'inline' must appear on the original definition, but not necessarily
11600 // on all extension definitions, so the note should point to the first
11601 // definition to avoid confusion.
11602 PrevNS = PrevNS->getFirstDecl();
11603
11604 if (PrevNS->isInline())
11605 // The user probably just forgot the 'inline', so suggest that it
11606 // be added back.
11607 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
11608 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
11609 else
11610 S.Diag(Loc, diag::err_inline_namespace_mismatch);
11611
11612 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
11613 *IsInline = PrevNS->isInline();
11614}
11615
11616/// ActOnStartNamespaceDef - This is called at the start of a namespace
11617/// definition.
11619 SourceLocation InlineLoc,
11620 SourceLocation NamespaceLoc,
11621 SourceLocation IdentLoc, IdentifierInfo *II,
11622 SourceLocation LBrace,
11623 const ParsedAttributesView &AttrList,
11624 UsingDirectiveDecl *&UD, bool IsNested) {
11625 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
11626 // For anonymous namespace, take the location of the left brace.
11627 SourceLocation Loc = II ? IdentLoc : LBrace;
11628 bool IsInline = InlineLoc.isValid();
11629 bool IsInvalid = false;
11630 bool IsStd = false;
11631 bool AddToKnown = false;
11632 Scope *DeclRegionScope = NamespcScope->getParent();
11633
11634 NamespaceDecl *PrevNS = nullptr;
11635 if (II) {
11636 // C++ [namespace.std]p7:
11637 // A translation unit shall not declare namespace std to be an inline
11638 // namespace (9.8.2).
11639 //
11640 // Precondition: the std namespace is in the file scope and is declared to
11641 // be inline
11642 auto DiagnoseInlineStdNS = [&]() {
11643 assert(IsInline && II->isStr("std") &&
11645 "Precondition of DiagnoseInlineStdNS not met");
11646 Diag(InlineLoc, diag::err_inline_namespace_std)
11647 << SourceRange(InlineLoc, InlineLoc.getLocWithOffset(6));
11648 IsInline = false;
11649 };
11650 // C++ [namespace.def]p2:
11651 // The identifier in an original-namespace-definition shall not
11652 // have been previously defined in the declarative region in
11653 // which the original-namespace-definition appears. The
11654 // identifier in an original-namespace-definition is the name of
11655 // the namespace. Subsequently in that declarative region, it is
11656 // treated as an original-namespace-name.
11657 //
11658 // Since namespace names are unique in their scope, and we don't
11659 // look through using directives, just look for any ordinary names
11660 // as if by qualified name lookup.
11661 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
11662 RedeclarationKind::ForExternalRedeclaration);
11664 NamedDecl *PrevDecl =
11665 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
11666 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
11667
11668 if (PrevNS) {
11669 // This is an extended namespace definition.
11670 if (IsInline && II->isStr("std") &&
11672 DiagnoseInlineStdNS();
11673 else if (IsInline != PrevNS->isInline())
11674 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
11675 &IsInline, PrevNS);
11676 } else if (PrevDecl) {
11677 // This is an invalid name redefinition.
11678 Diag(Loc, diag::err_redefinition_different_kind)
11679 << II;
11680 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
11681 IsInvalid = true;
11682 // Continue on to push Namespc as current DeclContext and return it.
11683 } else if (II->isStr("std") &&
11685 if (IsInline)
11686 DiagnoseInlineStdNS();
11687 // This is the first "real" definition of the namespace "std", so update
11688 // our cache of the "std" namespace to point at this definition.
11689 PrevNS = getStdNamespace();
11690 IsStd = true;
11691 AddToKnown = !IsInline;
11692 } else {
11693 // We've seen this namespace for the first time.
11694 AddToKnown = !IsInline;
11695 }
11696 } else {
11697 // Anonymous namespaces.
11698
11699 // Determine whether the parent already has an anonymous namespace.
11701 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
11702 PrevNS = TU->getAnonymousNamespace();
11703 } else {
11704 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
11705 PrevNS = ND->getAnonymousNamespace();
11706 }
11707
11708 if (PrevNS && IsInline != PrevNS->isInline())
11709 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
11710 &IsInline, PrevNS);
11711 }
11712
11714 Context, CurContext, IsInline, StartLoc, Loc, II, PrevNS, IsNested);
11715 if (IsInvalid)
11716 Namespc->setInvalidDecl();
11717
11718 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
11719 AddPragmaAttributes(DeclRegionScope, Namespc);
11720 ProcessAPINotes(Namespc);
11721
11722 // FIXME: Should we be merging attributes?
11723 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
11725
11726 if (IsStd)
11727 StdNamespace = Namespc;
11728 if (AddToKnown)
11729 KnownNamespaces[Namespc] = false;
11730
11731 if (II) {
11732 PushOnScopeChains(Namespc, DeclRegionScope);
11733 } else {
11734 // Link the anonymous namespace into its parent.
11736 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
11737 TU->setAnonymousNamespace(Namespc);
11738 } else {
11739 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
11740 }
11741
11742 CurContext->addDecl(Namespc);
11743
11744 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
11745 // behaves as if it were replaced by
11746 // namespace unique { /* empty body */ }
11747 // using namespace unique;
11748 // namespace unique { namespace-body }
11749 // where all occurrences of 'unique' in a translation unit are
11750 // replaced by the same identifier and this identifier differs
11751 // from all other identifiers in the entire program.
11752
11753 // We just create the namespace with an empty name and then add an
11754 // implicit using declaration, just like the standard suggests.
11755 //
11756 // CodeGen enforces the "universally unique" aspect by giving all
11757 // declarations semantically contained within an anonymous
11758 // namespace internal linkage.
11759
11760 if (!PrevNS) {
11762 /* 'using' */ LBrace,
11763 /* 'namespace' */ SourceLocation(),
11764 /* qualifier */ NestedNameSpecifierLoc(),
11765 /* identifier */ SourceLocation(),
11766 Namespc,
11767 /* Ancestor */ Parent);
11768 UD->setImplicit();
11769 Parent->addDecl(UD);
11770 }
11771 }
11772
11773 ActOnDocumentableDecl(Namespc);
11774
11775 // Although we could have an invalid decl (i.e. the namespace name is a
11776 // redefinition), push it as current DeclContext and try to continue parsing.
11777 // FIXME: We should be able to push Namespc here, so that the each DeclContext
11778 // for the namespace has the declarations that showed up in that particular
11779 // namespace definition.
11780 PushDeclContext(NamespcScope, Namespc);
11781 return Namespc;
11782}
11783
11784/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
11785/// is a namespace alias, returns the namespace it points to.
11787 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
11788 return AD->getNamespace();
11789 return dyn_cast_or_null<NamespaceDecl>(D);
11790}
11791
11792/// ActOnFinishNamespaceDef - This callback is called after a namespace is
11793/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
11795 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
11796 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
11797 Namespc->setRBraceLoc(RBrace);
11799 if (Namespc->hasAttr<VisibilityAttr>())
11800 PopPragmaVisibility(true, RBrace);
11801 // If this namespace contains an export-declaration, export it now.
11802 if (DeferredExportedNamespaces.erase(Namespc))
11804}
11805
11807 return cast_or_null<CXXRecordDecl>(
11809}
11810
11812 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
11813}
11814
11816 return cast_or_null<NamespaceDecl>(
11818}
11819namespace {
11820
11821enum UnsupportedSTLSelect {
11822 USS_InvalidMember,
11823 USS_MissingMember,
11824 USS_NonTrivial,
11825 USS_Other
11826};
11827
11828struct InvalidSTLDiagnoser {
11829 Sema &S;
11831 QualType TyForDiags;
11832
11833 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
11834 const VarDecl *VD = nullptr) {
11835 {
11836 auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
11837 << TyForDiags << ((int)Sel);
11838 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
11839 assert(!Name.empty());
11840 D << Name;
11841 }
11842 }
11843 if (Sel == USS_InvalidMember) {
11844 S.Diag(VD->getLocation(), diag::note_var_declared_here)
11845 << VD << VD->getSourceRange();
11846 }
11847 return QualType();
11848 }
11849};
11850} // namespace
11851
11855 assert(getLangOpts().CPlusPlus &&
11856 "Looking for comparison category type outside of C++.");
11857
11858 // Use an elaborated type for diagnostics which has a name containing the
11859 // prepended 'std' namespace but not any inline namespace names.
11860 auto TyForDiags = [&](ComparisonCategoryInfo *Info) {
11861 auto *NNS =
11864 Info->getType());
11865 };
11866
11867 // Check if we've already successfully checked the comparison category type
11868 // before. If so, skip checking it again.
11870 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) {
11871 // The only thing we need to check is that the type has a reachable
11872 // definition in the current context.
11873 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11874 return QualType();
11875
11876 return Info->getType();
11877 }
11878
11879 // If lookup failed
11880 if (!Info) {
11881 std::string NameForDiags = "std::";
11882 NameForDiags += ComparisonCategories::getCategoryString(Kind);
11883 Diag(Loc, diag::err_implied_comparison_category_type_not_found)
11884 << NameForDiags << (int)Usage;
11885 return QualType();
11886 }
11887
11888 assert(Info->Kind == Kind);
11889 assert(Info->Record);
11890
11891 // Update the Record decl in case we encountered a forward declaration on our
11892 // first pass. FIXME: This is a bit of a hack.
11893 if (Info->Record->hasDefinition())
11894 Info->Record = Info->Record->getDefinition();
11895
11896 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11897 return QualType();
11898
11899 InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)};
11900
11901 if (!Info->Record->isTriviallyCopyable())
11902 return UnsupportedSTLError(USS_NonTrivial);
11903
11904 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
11905 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
11906 // Tolerate empty base classes.
11907 if (Base->isEmpty())
11908 continue;
11909 // Reject STL implementations which have at least one non-empty base.
11910 return UnsupportedSTLError();
11911 }
11912
11913 // Check that the STL has implemented the types using a single integer field.
11914 // This expectation allows better codegen for builtin operators. We require:
11915 // (1) The class has exactly one field.
11916 // (2) The field is an integral or enumeration type.
11917 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
11918 if (std::distance(FIt, FEnd) != 1 ||
11919 !FIt->getType()->isIntegralOrEnumerationType()) {
11920 return UnsupportedSTLError();
11921 }
11922
11923 // Build each of the require values and store them in Info.
11924 for (ComparisonCategoryResult CCR :
11926 StringRef MemName = ComparisonCategories::getResultString(CCR);
11927 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
11928
11929 if (!ValInfo)
11930 return UnsupportedSTLError(USS_MissingMember, MemName);
11931
11932 VarDecl *VD = ValInfo->VD;
11933 assert(VD && "should not be null!");
11934
11935 // Attempt to diagnose reasons why the STL definition of this type
11936 // might be foobar, including it failing to be a constant expression.
11937 // TODO Handle more ways the lookup or result can be invalid.
11938 if (!VD->isStaticDataMember() ||
11940 return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
11941
11942 // Attempt to evaluate the var decl as a constant expression and extract
11943 // the value of its first field as a ICE. If this fails, the STL
11944 // implementation is not supported.
11945 if (!ValInfo->hasValidIntValue())
11946 return UnsupportedSTLError();
11947
11949 }
11950
11951 // We've successfully built the required types and expressions. Update
11952 // the cache and return the newly cached value.
11953 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
11954 return Info->getType();
11955}
11956
11957/// Retrieve the special "std" namespace, which may require us to
11958/// implicitly define the namespace.
11960 if (!StdNamespace) {
11961 // The "std" namespace has not yet been defined, so build one implicitly.
11964 /*Inline=*/false, SourceLocation(), SourceLocation(),
11965 &PP.getIdentifierTable().get("std"),
11966 /*PrevDecl=*/nullptr, /*Nested=*/false);
11968 // We want the created NamespaceDecl to be available for redeclaration
11969 // lookups, but not for regular name lookups.
11972 }
11973
11974 return getStdNamespace();
11975}
11976
11978 assert(getLangOpts().CPlusPlus &&
11979 "Looking for std::initializer_list outside of C++.");
11980
11981 // We're looking for implicit instantiations of
11982 // template <typename E> class std::initializer_list.
11983
11984 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
11985 return false;
11986
11987 ClassTemplateDecl *Template = nullptr;
11988 const TemplateArgument *Arguments = nullptr;
11989
11990 if (const RecordType *RT = Ty->getAs<RecordType>()) {
11991
11993 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
11994 if (!Specialization)
11995 return false;
11996
11997 Template = Specialization->getSpecializedTemplate();
11998 Arguments = Specialization->getTemplateArgs().data();
11999 } else {
12000 const TemplateSpecializationType *TST = nullptr;
12001 if (auto *ICN = Ty->getAs<InjectedClassNameType>())
12002 TST = ICN->getInjectedTST();
12003 else
12004 TST = Ty->getAs<TemplateSpecializationType>();
12005 if (TST) {
12006 Template = dyn_cast_or_null<ClassTemplateDecl>(
12008 Arguments = TST->template_arguments().begin();
12009 }
12010 }
12011 if (!Template)
12012 return false;
12013
12014 if (!StdInitializerList) {
12015 // Haven't recognized std::initializer_list yet, maybe this is it.
12016 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
12017 if (TemplateClass->getIdentifier() !=
12018 &PP.getIdentifierTable().get("initializer_list") ||
12019 !getStdNamespace()->InEnclosingNamespaceSetOf(
12020 TemplateClass->getDeclContext()))
12021 return false;
12022 // This is a template called std::initializer_list, but is it the right
12023 // template?
12024 TemplateParameterList *Params = Template->getTemplateParameters();
12025 if (Params->getMinRequiredArguments() != 1)
12026 return false;
12027 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
12028 return false;
12029
12030 // It's the right template.
12031 StdInitializerList = Template;
12032 }
12033
12035 return false;
12036
12037 // This is an instance of std::initializer_list. Find the argument type.
12038 if (Element)
12039 *Element = Arguments[0].getAsType();
12040 return true;
12041}
12042
12045 if (!Std) {
12046 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
12047 return nullptr;
12048 }
12049
12050 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
12052 if (!S.LookupQualifiedName(Result, Std)) {
12053 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
12054 return nullptr;
12055 }
12056 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
12057 if (!Template) {
12058 Result.suppressDiagnostics();
12059 // We found something weird. Complain about the first thing we found.
12060 NamedDecl *Found = *Result.begin();
12061 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
12062 return nullptr;
12063 }
12064
12065 // We found some template called std::initializer_list. Now verify that it's
12066 // correct.
12067 TemplateParameterList *Params = Template->getTemplateParameters();
12068 if (Params->getMinRequiredArguments() != 1 ||
12069 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
12070 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
12071 return nullptr;
12072 }
12073
12074 return Template;
12075}
12076
12078 if (!StdInitializerList) {
12080 if (!StdInitializerList)
12081 return QualType();
12082 }
12083
12087 Loc)));
12092}
12093
12095 // C++ [dcl.init.list]p2:
12096 // A constructor is an initializer-list constructor if its first parameter
12097 // is of type std::initializer_list<E> or reference to possibly cv-qualified
12098 // std::initializer_list<E> for some type E, and either there are no other
12099 // parameters or else all other parameters have default arguments.
12100 if (!Ctor->hasOneParamOrDefaultArgs())
12101 return false;
12102
12103 QualType ArgType = Ctor->getParamDecl(0)->getType();
12104 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
12105 ArgType = RT->getPointeeType().getUnqualifiedType();
12106
12107 return isStdInitializerList(ArgType, nullptr);
12108}
12109
12110/// Determine whether a using statement is in a context where it will be
12111/// apply in all contexts.
12113 switch (CurContext->getDeclKind()) {
12114 case Decl::TranslationUnit:
12115 return true;
12116 case Decl::LinkageSpec:
12118 default:
12119 return false;
12120 }
12121}
12122
12123namespace {
12124
12125// Callback to only accept typo corrections that are namespaces.
12126class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
12127public:
12128 bool ValidateCandidate(const TypoCorrection &candidate) override {
12129 if (NamedDecl *ND = candidate.getCorrectionDecl())
12130 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
12131 return false;
12132 }
12133
12134 std::unique_ptr<CorrectionCandidateCallback> clone() override {
12135 return std::make_unique<NamespaceValidatorCCC>(*this);
12136 }
12137};
12138
12139}
12140
12141static void DiagnoseInvisibleNamespace(const TypoCorrection &Corrected,
12142 Sema &S) {
12143 auto *ND = cast<NamespaceDecl>(Corrected.getFoundDecl());
12144 Module *M = ND->getOwningModule();
12145 assert(M && "hidden namespace definition not in a module?");
12146
12147 if (M->isExplicitGlobalModule())
12148 S.Diag(Corrected.getCorrectionRange().getBegin(),
12149 diag::err_module_unimported_use_header)
12151 << /*Header Name*/ false;
12152 else
12153 S.Diag(Corrected.getCorrectionRange().getBegin(),
12154 diag::err_module_unimported_use)
12156 << M->getTopLevelModuleName();
12157}
12158
12160 CXXScopeSpec &SS,
12161 SourceLocation IdentLoc,
12162 IdentifierInfo *Ident) {
12163 R.clear();
12164 NamespaceValidatorCCC CCC{};
12165 if (TypoCorrection Corrected =
12166 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
12168 // Generally we find it is confusing more than helpful to diagnose the
12169 // invisible namespace.
12170 // See https://github.com/llvm/llvm-project/issues/73893.
12171 //
12172 // However, we should diagnose when the users are trying to using an
12173 // invisible namespace. So we handle the case specially here.
12174 if (isa_and_nonnull<NamespaceDecl>(Corrected.getFoundDecl()) &&
12175 Corrected.requiresImport()) {
12176 DiagnoseInvisibleNamespace(Corrected, S);
12177 } else if (DeclContext *DC = S.computeDeclContext(SS, false)) {
12178 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
12179 bool DroppedSpecifier =
12180 Corrected.WillReplaceSpecifier() && Ident->getName() == CorrectedStr;
12181 S.diagnoseTypo(Corrected,
12182 S.PDiag(diag::err_using_directive_member_suggest)
12183 << Ident << DC << DroppedSpecifier << SS.getRange(),
12184 S.PDiag(diag::note_namespace_defined_here));
12185 } else {
12186 S.diagnoseTypo(Corrected,
12187 S.PDiag(diag::err_using_directive_suggest) << Ident,
12188 S.PDiag(diag::note_namespace_defined_here));
12189 }
12190 R.addDecl(Corrected.getFoundDecl());
12191 return true;
12192 }
12193 return false;
12194}
12195
12197 SourceLocation NamespcLoc, CXXScopeSpec &SS,
12198 SourceLocation IdentLoc,
12199 IdentifierInfo *NamespcName,
12200 const ParsedAttributesView &AttrList) {
12201 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
12202 assert(NamespcName && "Invalid NamespcName.");
12203 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
12204
12205 // Get the innermost enclosing declaration scope.
12206 S = S->getDeclParent();
12207
12208 UsingDirectiveDecl *UDir = nullptr;
12209 NestedNameSpecifier *Qualifier = nullptr;
12210 if (SS.isSet())
12211 Qualifier = SS.getScopeRep();
12212
12213 // Lookup namespace name.
12214 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
12215 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
12216 if (R.isAmbiguous())
12217 return nullptr;
12218
12219 if (R.empty()) {
12220 R.clear();
12221 // Allow "using namespace std;" or "using namespace ::std;" even if
12222 // "std" hasn't been defined yet, for GCC compatibility.
12223 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
12224 NamespcName->isStr("std")) {
12225 Diag(IdentLoc, diag::ext_using_undefined_std);
12227 R.resolveKind();
12228 }
12229 // Otherwise, attempt typo correction.
12230 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
12231 }
12232
12233 if (!R.empty()) {
12234 NamedDecl *Named = R.getRepresentativeDecl();
12236 assert(NS && "expected namespace decl");
12237
12238 // The use of a nested name specifier may trigger deprecation warnings.
12239 DiagnoseUseOfDecl(Named, IdentLoc);
12240
12241 // C++ [namespace.udir]p1:
12242 // A using-directive specifies that the names in the nominated
12243 // namespace can be used in the scope in which the
12244 // using-directive appears after the using-directive. During
12245 // unqualified name lookup (3.4.1), the names appear as if they
12246 // were declared in the nearest enclosing namespace which
12247 // contains both the using-directive and the nominated
12248 // namespace. [Note: in this context, "contains" means "contains
12249 // directly or indirectly". ]
12250
12251 // Find enclosing context containing both using-directive and
12252 // nominated namespace.
12253 DeclContext *CommonAncestor = NS;
12254 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
12255 CommonAncestor = CommonAncestor->getParent();
12256
12257 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
12259 IdentLoc, Named, CommonAncestor);
12260
12263 Diag(IdentLoc, diag::warn_using_directive_in_header);
12264 }
12265
12266 PushUsingDirective(S, UDir);
12267 } else {
12268 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
12269 }
12270
12271 if (UDir) {
12272 ProcessDeclAttributeList(S, UDir, AttrList);
12273 ProcessAPINotes(UDir);
12274 }
12275
12276 return UDir;
12277}
12278
12280 // If the scope has an associated entity and the using directive is at
12281 // namespace or translation unit scope, add the UsingDirectiveDecl into
12282 // its lookup structure so qualified name lookup can find it.
12283 DeclContext *Ctx = S->getEntity();
12284 if (Ctx && !Ctx->isFunctionOrMethod())
12285 Ctx->addDecl(UDir);
12286 else
12287 // Otherwise, it is at block scope. The using-directives will affect lookup
12288 // only to the end of the scope.
12289 S->PushUsingDirective(UDir);
12290}
12291
12293 SourceLocation UsingLoc,
12294 SourceLocation TypenameLoc, CXXScopeSpec &SS,
12295 UnqualifiedId &Name,
12296 SourceLocation EllipsisLoc,
12297 const ParsedAttributesView &AttrList) {
12298 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
12299
12300 if (SS.isEmpty()) {
12301 Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
12302 return nullptr;
12303 }
12304
12305 switch (Name.getKind()) {
12311 break;
12312
12315 // C++11 inheriting constructors.
12316 Diag(Name.getBeginLoc(),
12318 ? diag::warn_cxx98_compat_using_decl_constructor
12319 : diag::err_using_decl_constructor)
12320 << SS.getRange();
12321
12322 if (getLangOpts().CPlusPlus11) break;
12323
12324 return nullptr;
12325
12327 Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
12328 return nullptr;
12329
12331 Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
12332 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
12333 return nullptr;
12334
12336 llvm_unreachable("cannot parse qualified deduction guide name");
12337 }
12338
12339 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
12340 DeclarationName TargetName = TargetNameInfo.getName();
12341 if (!TargetName)
12342 return nullptr;
12343
12344 // Warn about access declarations.
12345 if (UsingLoc.isInvalid()) {
12346 Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
12347 ? diag::err_access_decl
12348 : diag::warn_access_decl_deprecated)
12349 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
12350 }
12351
12352 if (EllipsisLoc.isInvalid()) {
12355 return nullptr;
12356 } else {
12358 !TargetNameInfo.containsUnexpandedParameterPack()) {
12359 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
12360 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
12361 EllipsisLoc = SourceLocation();
12362 }
12363 }
12364
12365 NamedDecl *UD =
12366 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
12367 SS, TargetNameInfo, EllipsisLoc, AttrList,
12368 /*IsInstantiation*/ false,
12369 AttrList.hasAttribute(ParsedAttr::AT_UsingIfExists));
12370 if (UD)
12371 PushOnScopeChains(UD, S, /*AddToContext*/ false);
12372
12373 return UD;
12374}
12375
12377 SourceLocation UsingLoc,
12378 SourceLocation EnumLoc,
12379 SourceLocation IdentLoc,
12380 IdentifierInfo &II, CXXScopeSpec *SS) {
12381 assert(!SS->isInvalid() && "ScopeSpec is invalid");
12382 TypeSourceInfo *TSI = nullptr;
12383 QualType EnumTy = GetTypeFromParser(
12384 getTypeName(II, IdentLoc, S, SS, /*isClassName=*/false,
12385 /*HasTrailingDot=*/false,
12386 /*ObjectType=*/nullptr, /*IsCtorOrDtorName=*/false,
12387 /*WantNontrivialTypeSourceInfo=*/true),
12388 &TSI);
12389 if (EnumTy.isNull()) {
12390 Diag(IdentLoc, SS && isDependentScopeSpecifier(*SS)
12391 ? diag::err_using_enum_is_dependent
12392 : diag::err_unknown_typename)
12393 << II.getName()
12394 << SourceRange(SS ? SS->getBeginLoc() : IdentLoc, IdentLoc);
12395 return nullptr;
12396 }
12397
12398 auto *Enum = dyn_cast_if_present<EnumDecl>(EnumTy->getAsTagDecl());
12399 if (!Enum) {
12400 Diag(IdentLoc, diag::err_using_enum_not_enum) << EnumTy;
12401 return nullptr;
12402 }
12403
12404 if (auto *Def = Enum->getDefinition())
12405 Enum = Def;
12406
12407 if (TSI == nullptr)
12408 TSI = Context.getTrivialTypeSourceInfo(EnumTy, IdentLoc);
12409
12410 auto *UD =
12411 BuildUsingEnumDeclaration(S, AS, UsingLoc, EnumLoc, IdentLoc, TSI, Enum);
12412
12413 if (UD)
12414 PushOnScopeChains(UD, S, /*AddToContext*/ false);
12415
12416 return UD;
12417}
12418
12419/// Determine whether a using declaration considers the given
12420/// declarations as "equivalent", e.g., if they are redeclarations of
12421/// the same entity or are both typedefs of the same type.
12422static bool
12424 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
12425 return true;
12426
12427 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
12428 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
12429 return Context.hasSameType(TD1->getUnderlyingType(),
12430 TD2->getUnderlyingType());
12431
12432 // Two using_if_exists using-declarations are equivalent if both are
12433 // unresolved.
12434 if (isa<UnresolvedUsingIfExistsDecl>(D1) &&
12435 isa<UnresolvedUsingIfExistsDecl>(D2))
12436 return true;
12437
12438 return false;
12439}
12440
12441
12442/// Determines whether to create a using shadow decl for a particular
12443/// decl, given the set of decls existing prior to this using lookup.
12445 const LookupResult &Previous,
12446 UsingShadowDecl *&PrevShadow) {
12447 // Diagnose finding a decl which is not from a base class of the
12448 // current class. We do this now because there are cases where this
12449 // function will silently decide not to build a shadow decl, which
12450 // will pre-empt further diagnostics.
12451 //
12452 // We don't need to do this in C++11 because we do the check once on
12453 // the qualifier.
12454 //
12455 // FIXME: diagnose the following if we care enough:
12456 // struct A { int foo; };
12457 // struct B : A { using A::foo; };
12458 // template <class T> struct C : A {};
12459 // template <class T> struct D : C<T> { using B::foo; } // <---
12460 // This is invalid (during instantiation) in C++03 because B::foo
12461 // resolves to the using decl in B, which is not a base class of D<T>.
12462 // We can't diagnose it immediately because C<T> is an unknown
12463 // specialization. The UsingShadowDecl in D<T> then points directly
12464 // to A::foo, which will look well-formed when we instantiate.
12465 // The right solution is to not collapse the shadow-decl chain.
12467 if (auto *Using = dyn_cast<UsingDecl>(BUD)) {
12468 DeclContext *OrigDC = Orig->getDeclContext();
12469
12470 // Handle enums and anonymous structs.
12471 if (isa<EnumDecl>(OrigDC))
12472 OrigDC = OrigDC->getParent();
12473 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
12474 while (OrigRec->isAnonymousStructOrUnion())
12475 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
12476
12477 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
12478 if (OrigDC == CurContext) {
12479 Diag(Using->getLocation(),
12480 diag::err_using_decl_nested_name_specifier_is_current_class)
12481 << Using->getQualifierLoc().getSourceRange();
12482 Diag(Orig->getLocation(), diag::note_using_decl_target);
12483 Using->setInvalidDecl();
12484 return true;
12485 }
12486
12487 Diag(Using->getQualifierLoc().getBeginLoc(),
12488 diag::err_using_decl_nested_name_specifier_is_not_base_class)
12489 << Using->getQualifier() << cast<CXXRecordDecl>(CurContext)
12490 << Using->getQualifierLoc().getSourceRange();
12491 Diag(Orig->getLocation(), diag::note_using_decl_target);
12492 Using->setInvalidDecl();
12493 return true;
12494 }
12495 }
12496
12497 if (Previous.empty()) return false;
12498
12499 NamedDecl *Target = Orig;
12500 if (isa<UsingShadowDecl>(Target))
12501 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
12502
12503 // If the target happens to be one of the previous declarations, we
12504 // don't have a conflict.
12505 //
12506 // FIXME: but we might be increasing its access, in which case we
12507 // should redeclare it.
12508 NamedDecl *NonTag = nullptr, *Tag = nullptr;
12509 bool FoundEquivalentDecl = false;
12510 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
12511 I != E; ++I) {
12512 NamedDecl *D = (*I)->getUnderlyingDecl();
12513 // We can have UsingDecls in our Previous results because we use the same
12514 // LookupResult for checking whether the UsingDecl itself is a valid
12515 // redeclaration.
12516 if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D) || isa<UsingEnumDecl>(D))
12517 continue;
12518
12519 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
12520 // C++ [class.mem]p19:
12521 // If T is the name of a class, then [every named member other than
12522 // a non-static data member] shall have a name different from T
12523 if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
12524 !isa<IndirectFieldDecl>(Target) &&
12525 !isa<UnresolvedUsingValueDecl>(Target) &&
12527 CurContext,
12529 return true;
12530 }
12531
12533 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
12534 PrevShadow = Shadow;
12535 FoundEquivalentDecl = true;
12537 // We don't conflict with an existing using shadow decl of an equivalent
12538 // declaration, but we're not a redeclaration of it.
12539 FoundEquivalentDecl = true;
12540 }
12541
12542 if (isVisible(D))
12543 (isa<TagDecl>(D) ? Tag : NonTag) = D;
12544 }
12545
12546 if (FoundEquivalentDecl)
12547 return false;
12548
12549 // Always emit a diagnostic for a mismatch between an unresolved
12550 // using_if_exists and a resolved using declaration in either direction.
12551 if (isa<UnresolvedUsingIfExistsDecl>(Target) !=
12552 (isa_and_nonnull<UnresolvedUsingIfExistsDecl>(NonTag))) {
12553 if (!NonTag && !Tag)
12554 return false;
12555 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12556 Diag(Target->getLocation(), diag::note_using_decl_target);
12557 Diag((NonTag ? NonTag : Tag)->getLocation(),
12558 diag::note_using_decl_conflict);
12559 BUD->setInvalidDecl();
12560 return true;
12561 }
12562
12563 if (FunctionDecl *FD = Target->getAsFunction()) {
12564 NamedDecl *OldDecl = nullptr;
12565 switch (CheckOverload(nullptr, FD, Previous, OldDecl,
12566 /*IsForUsingDecl*/ true)) {
12567 case Ovl_Overload:
12568 return false;
12569
12570 case Ovl_NonFunction:
12571 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12572 break;
12573
12574 // We found a decl with the exact signature.
12575 case Ovl_Match:
12576 // If we're in a record, we want to hide the target, so we
12577 // return true (without a diagnostic) to tell the caller not to
12578 // build a shadow decl.
12579 if (CurContext->isRecord())
12580 return true;
12581
12582 // If we're not in a record, this is an error.
12583 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12584 break;
12585 }
12586
12587 Diag(Target->getLocation(), diag::note_using_decl_target);
12588 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
12589 BUD->setInvalidDecl();
12590 return true;
12591 }
12592
12593 // Target is not a function.
12594
12595 if (isa<TagDecl>(Target)) {
12596 // No conflict between a tag and a non-tag.
12597 if (!Tag) return false;
12598
12599 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12600 Diag(Target->getLocation(), diag::note_using_decl_target);
12601 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
12602 BUD->setInvalidDecl();
12603 return true;
12604 }
12605
12606 // No conflict between a tag and a non-tag.
12607 if (!NonTag) return false;
12608
12609 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12610 Diag(Target->getLocation(), diag::note_using_decl_target);
12611 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
12612 BUD->setInvalidDecl();
12613 return true;
12614}
12615
12616/// Determine whether a direct base class is a virtual base class.
12618 if (!Derived->getNumVBases())
12619 return false;
12620 for (auto &B : Derived->bases())
12621 if (B.getType()->getAsCXXRecordDecl() == Base)
12622 return B.isVirtual();
12623 llvm_unreachable("not a direct base class");
12624}
12625
12626/// Builds a shadow declaration corresponding to a 'using' declaration.
12628 NamedDecl *Orig,
12629 UsingShadowDecl *PrevDecl) {
12630 // If we resolved to another shadow declaration, just coalesce them.
12631 NamedDecl *Target = Orig;
12632 if (isa<UsingShadowDecl>(Target)) {
12633 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
12634 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
12635 }
12636
12637 NamedDecl *NonTemplateTarget = Target;
12638 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
12639 NonTemplateTarget = TargetTD->getTemplatedDecl();
12640
12641 UsingShadowDecl *Shadow;
12642 if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) {
12643 UsingDecl *Using = cast<UsingDecl>(BUD);
12644 bool IsVirtualBase =
12645 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
12646 Using->getQualifier()->getAsRecordDecl());
12648 Context, CurContext, Using->getLocation(), Using, Orig, IsVirtualBase);
12649 } else {
12651 Target->getDeclName(), BUD, Target);
12652 }
12653 BUD->addShadowDecl(Shadow);
12654
12655 Shadow->setAccess(BUD->getAccess());
12656 if (Orig->isInvalidDecl() || BUD->isInvalidDecl())
12657 Shadow->setInvalidDecl();
12658
12659 Shadow->setPreviousDecl(PrevDecl);
12660
12661 if (S)
12662 PushOnScopeChains(Shadow, S);
12663 else
12664 CurContext->addDecl(Shadow);
12665
12666
12667 return Shadow;
12668}
12669
12670/// Hides a using shadow declaration. This is required by the current
12671/// using-decl implementation when a resolvable using declaration in a
12672/// class is followed by a declaration which would hide or override
12673/// one or more of the using decl's targets; for example:
12674///
12675/// struct Base { void foo(int); };
12676/// struct Derived : Base {
12677/// using Base::foo;
12678/// void foo(int);
12679/// };
12680///
12681/// The governing language is C++03 [namespace.udecl]p12:
12682///
12683/// When a using-declaration brings names from a base class into a
12684/// derived class scope, member functions in the derived class
12685/// override and/or hide member functions with the same name and
12686/// parameter types in a base class (rather than conflicting).
12687///
12688/// There are two ways to implement this:
12689/// (1) optimistically create shadow decls when they're not hidden
12690/// by existing declarations, or
12691/// (2) don't create any shadow decls (or at least don't make them
12692/// visible) until we've fully parsed/instantiated the class.
12693/// The problem with (1) is that we might have to retroactively remove
12694/// a shadow decl, which requires several O(n) operations because the
12695/// decl structures are (very reasonably) not designed for removal.
12696/// (2) avoids this but is very fiddly and phase-dependent.
12698 if (Shadow->getDeclName().getNameKind() ==
12700 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
12701
12702 // Remove it from the DeclContext...
12703 Shadow->getDeclContext()->removeDecl(Shadow);
12704
12705 // ...and the scope, if applicable...
12706 if (S) {
12707 S->RemoveDecl(Shadow);
12708 IdResolver.RemoveDecl(Shadow);
12709 }
12710
12711 // ...and the using decl.
12712 Shadow->getIntroducer()->removeShadowDecl(Shadow);
12713
12714 // TODO: complain somehow if Shadow was used. It shouldn't
12715 // be possible for this to happen, because...?
12716}
12717
12718/// Find the base specifier for a base class with the given type.
12720 QualType DesiredBase,
12721 bool &AnyDependentBases) {
12722 // Check whether the named type is a direct base class.
12723 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified()
12725 for (auto &Base : Derived->bases()) {
12726 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
12727 if (CanonicalDesiredBase == BaseType)
12728 return &Base;
12729 if (BaseType->isDependentType())
12730 AnyDependentBases = true;
12731 }
12732 return nullptr;
12733}
12734
12735namespace {
12736class UsingValidatorCCC final : public CorrectionCandidateCallback {
12737public:
12738 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
12739 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
12740 : HasTypenameKeyword(HasTypenameKeyword),
12741 IsInstantiation(IsInstantiation), OldNNS(NNS),
12742 RequireMemberOf(RequireMemberOf) {}
12743
12744 bool ValidateCandidate(const TypoCorrection &Candidate) override {
12745 NamedDecl *ND = Candidate.getCorrectionDecl();
12746
12747 // Keywords are not valid here.
12748 if (!ND || isa<NamespaceDecl>(ND))
12749 return false;
12750
12751 // Completely unqualified names are invalid for a 'using' declaration.
12752 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
12753 return false;
12754
12755 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
12756 // reject.
12757
12758 if (RequireMemberOf) {
12759 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
12760 if (FoundRecord && FoundRecord->isInjectedClassName()) {
12761 // No-one ever wants a using-declaration to name an injected-class-name
12762 // of a base class, unless they're declaring an inheriting constructor.
12763 ASTContext &Ctx = ND->getASTContext();
12764 if (!Ctx.getLangOpts().CPlusPlus11)
12765 return false;
12766 QualType FoundType = Ctx.getRecordType(FoundRecord);
12767
12768 // Check that the injected-class-name is named as a member of its own
12769 // type; we don't want to suggest 'using Derived::Base;', since that
12770 // means something else.
12772 Candidate.WillReplaceSpecifier()
12773 ? Candidate.getCorrectionSpecifier()
12774 : OldNNS;
12775 if (!Specifier->getAsType() ||
12776 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
12777 return false;
12778
12779 // Check that this inheriting constructor declaration actually names a
12780 // direct base class of the current class.
12781 bool AnyDependentBases = false;
12782 if (!findDirectBaseWithType(RequireMemberOf,
12783 Ctx.getRecordType(FoundRecord),
12784 AnyDependentBases) &&
12785 !AnyDependentBases)
12786 return false;
12787 } else {
12788 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
12789 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
12790 return false;
12791
12792 // FIXME: Check that the base class member is accessible?
12793 }
12794 } else {
12795 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
12796 if (FoundRecord && FoundRecord->isInjectedClassName())
12797 return false;
12798 }
12799
12800 if (isa<TypeDecl>(ND))
12801 return HasTypenameKeyword || !IsInstantiation;
12802
12803 return !HasTypenameKeyword;
12804 }
12805
12806 std::unique_ptr<CorrectionCandidateCallback> clone() override {
12807 return std::make_unique<UsingValidatorCCC>(*this);
12808 }
12809
12810private:
12811 bool HasTypenameKeyword;
12812 bool IsInstantiation;
12813 NestedNameSpecifier *OldNNS;
12814 CXXRecordDecl *RequireMemberOf;
12815};
12816} // end anonymous namespace
12817
12818/// Remove decls we can't actually see from a lookup being used to declare
12819/// shadow using decls.
12820///
12821/// \param S - The scope of the potential shadow decl
12822/// \param Previous - The lookup of a potential shadow decl's name.
12824 // It is really dumb that we have to do this.
12825 LookupResult::Filter F = Previous.makeFilter();
12826 while (F.hasNext()) {
12827 NamedDecl *D = F.next();
12828 if (!isDeclInScope(D, CurContext, S))
12829 F.erase();
12830 // If we found a local extern declaration that's not ordinarily visible,
12831 // and this declaration is being added to a non-block scope, ignore it.
12832 // We're only checking for scope conflicts here, not also for violations
12833 // of the linkage rules.
12834 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
12836 F.erase();
12837 }
12838 F.done();
12839}
12840
12841/// Builds a using declaration.
12842///
12843/// \param IsInstantiation - Whether this call arises from an
12844/// instantiation of an unresolved using declaration. We treat
12845/// the lookup differently for these declarations.
12847 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
12848 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
12849 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
12850 const ParsedAttributesView &AttrList, bool IsInstantiation,
12851 bool IsUsingIfExists) {
12852 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
12853 SourceLocation IdentLoc = NameInfo.getLoc();
12854 assert(IdentLoc.isValid() && "Invalid TargetName location.");
12855
12856 // FIXME: We ignore attributes for now.
12857
12858 // For an inheriting constructor declaration, the name of the using
12859 // declaration is the name of a constructor in this class, not in the
12860 // base class.
12861 DeclarationNameInfo UsingName = NameInfo;
12863 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
12866
12867 // Do the redeclaration lookup in the current scope.
12868 LookupResult Previous(*this, UsingName, LookupUsingDeclName,
12869 RedeclarationKind::ForVisibleRedeclaration);
12870 Previous.setHideTags(false);
12871 if (S) {
12872 LookupName(Previous, S);
12873
12875 } else {
12876 assert(IsInstantiation && "no scope in non-instantiation");
12877 if (CurContext->isRecord())
12879 else {
12880 // No redeclaration check is needed here; in non-member contexts we
12881 // diagnosed all possible conflicts with other using-declarations when
12882 // building the template:
12883 //
12884 // For a dependent non-type using declaration, the only valid case is
12885 // if we instantiate to a single enumerator. We check for conflicts
12886 // between shadow declarations we introduce, and we check in the template
12887 // definition for conflicts between a non-type using declaration and any
12888 // other declaration, which together covers all cases.
12889 //
12890 // A dependent typename using declaration will never successfully
12891 // instantiate, since it will always name a class member, so we reject
12892 // that in the template definition.
12893 }
12894 }
12895
12896 // Check for invalid redeclarations.
12897 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
12898 SS, IdentLoc, Previous))
12899 return nullptr;
12900
12901 // 'using_if_exists' doesn't make sense on an inherited constructor.
12902 if (IsUsingIfExists && UsingName.getName().getNameKind() ==
12904 Diag(UsingLoc, diag::err_using_if_exists_on_ctor);
12905 return nullptr;
12906 }
12907
12908 DeclContext *LookupContext = computeDeclContext(SS);
12910 if (!LookupContext || EllipsisLoc.isValid()) {
12911 NamedDecl *D;
12912 // Dependent scope, or an unexpanded pack
12913 if (!LookupContext && CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword,
12914 SS, NameInfo, IdentLoc))
12915 return nullptr;
12916
12917 if (HasTypenameKeyword) {
12918 // FIXME: not all declaration name kinds are legal here
12920 UsingLoc, TypenameLoc,
12921 QualifierLoc,
12922 IdentLoc, NameInfo.getName(),
12923 EllipsisLoc);
12924 } else {
12926 QualifierLoc, NameInfo, EllipsisLoc);
12927 }
12928 D->setAccess(AS);
12929 CurContext->addDecl(D);
12930 ProcessDeclAttributeList(S, D, AttrList);
12931 return D;
12932 }
12933
12934 auto Build = [&](bool Invalid) {
12935 UsingDecl *UD =
12936 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
12937 UsingName, HasTypenameKeyword);
12938 UD->setAccess(AS);
12939 CurContext->addDecl(UD);
12940 ProcessDeclAttributeList(S, UD, AttrList);
12942 return UD;
12943 };
12944 auto BuildInvalid = [&]{ return Build(true); };
12945 auto BuildValid = [&]{ return Build(false); };
12946
12947 if (RequireCompleteDeclContext(SS, LookupContext))
12948 return BuildInvalid();
12949
12950 // Look up the target name.
12951 LookupResult R(*this, NameInfo, LookupOrdinaryName);
12952
12953 // Unlike most lookups, we don't always want to hide tag
12954 // declarations: tag names are visible through the using declaration
12955 // even if hidden by ordinary names, *except* in a dependent context
12956 // where they may be used by two-phase lookup.
12957 if (!IsInstantiation)
12958 R.setHideTags(false);
12959
12960 // For the purposes of this lookup, we have a base object type
12961 // equal to that of the current context.
12962 if (CurContext->isRecord()) {
12964 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
12965 }
12966
12967 LookupQualifiedName(R, LookupContext);
12968
12969 // Validate the context, now we have a lookup
12970 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
12971 IdentLoc, &R))
12972 return nullptr;
12973
12974 if (R.empty() && IsUsingIfExists)
12976 UsingName.getName()),
12977 AS_public);
12978
12979 // Try to correct typos if possible. If constructor name lookup finds no
12980 // results, that means the named class has no explicit constructors, and we
12981 // suppressed declaring implicit ones (probably because it's dependent or
12982 // invalid).
12983 if (R.empty() &&
12985 // HACK 2017-01-08: Work around an issue with libstdc++'s detection of
12986 // ::gets. Sometimes it believes that glibc provides a ::gets in cases where
12987 // it does not. The issue was fixed in libstdc++ 6.3 (2016-12-21) and later.
12988 auto *II = NameInfo.getName().getAsIdentifierInfo();
12989 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
12991 isa<TranslationUnitDecl>(LookupContext) &&
12992 getSourceManager().isInSystemHeader(UsingLoc))
12993 return nullptr;
12994 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
12995 dyn_cast<CXXRecordDecl>(CurContext));
12996 if (TypoCorrection Corrected =
12997 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
12999 // We reject candidates where DroppedSpecifier == true, hence the
13000 // literal '0' below.
13001 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
13002 << NameInfo.getName() << LookupContext << 0
13003 << SS.getRange());
13004
13005 // If we picked a correction with no attached Decl we can't do anything
13006 // useful with it, bail out.
13007 NamedDecl *ND = Corrected.getCorrectionDecl();
13008 if (!ND)
13009 return BuildInvalid();
13010
13011 // If we corrected to an inheriting constructor, handle it as one.
13012 auto *RD = dyn_cast<CXXRecordDecl>(ND);
13013 if (RD && RD->isInjectedClassName()) {
13014 // The parent of the injected class name is the class itself.
13015 RD = cast<CXXRecordDecl>(RD->getParent());
13016
13017 // Fix up the information we'll use to build the using declaration.
13018 if (Corrected.WillReplaceSpecifier()) {
13020 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
13021 QualifierLoc.getSourceRange());
13022 QualifierLoc = Builder.getWithLocInContext(Context);
13023 }
13024
13025 // In this case, the name we introduce is the name of a derived class
13026 // constructor.
13027 auto *CurClass = cast<CXXRecordDecl>(CurContext);
13030 UsingName.setNamedTypeInfo(nullptr);
13031 for (auto *Ctor : LookupConstructors(RD))
13032 R.addDecl(Ctor);
13033 R.resolveKind();
13034 } else {
13035 // FIXME: Pick up all the declarations if we found an overloaded
13036 // function.
13037 UsingName.setName(ND->getDeclName());
13038 R.addDecl(ND);
13039 }
13040 } else {
13041 Diag(IdentLoc, diag::err_no_member)
13042 << NameInfo.getName() << LookupContext << SS.getRange();
13043 return BuildInvalid();
13044 }
13045 }
13046
13047 if (R.isAmbiguous())
13048 return BuildInvalid();
13049
13050 if (HasTypenameKeyword) {
13051 // If we asked for a typename and got a non-type decl, error out.
13052 if (!R.getAsSingle<TypeDecl>() &&
13054 Diag(IdentLoc, diag::err_using_typename_non_type);
13055 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
13056 Diag((*I)->getUnderlyingDecl()->getLocation(),
13057 diag::note_using_decl_target);
13058 return BuildInvalid();
13059 }
13060 } else {
13061 // If we asked for a non-typename and we got a type, error out,
13062 // but only if this is an instantiation of an unresolved using
13063 // decl. Otherwise just silently find the type name.
13064 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
13065 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
13066 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
13067 return BuildInvalid();
13068 }
13069 }
13070
13071 // C++14 [namespace.udecl]p6:
13072 // A using-declaration shall not name a namespace.
13073 if (R.getAsSingle<NamespaceDecl>()) {
13074 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
13075 << SS.getRange();
13076 return BuildInvalid();
13077 }
13078
13079 UsingDecl *UD = BuildValid();
13080
13081 // Some additional rules apply to inheriting constructors.
13082 if (UsingName.getName().getNameKind() ==
13084 // Suppress access diagnostics; the access check is instead performed at the
13085 // point of use for an inheriting constructor.
13088 return UD;
13089 }
13090
13091 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
13092 UsingShadowDecl *PrevDecl = nullptr;
13093 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
13094 BuildUsingShadowDecl(S, UD, *I, PrevDecl);
13095 }
13096
13097 return UD;
13098}
13099
13101 SourceLocation UsingLoc,
13102 SourceLocation EnumLoc,
13103 SourceLocation NameLoc,
13105 EnumDecl *ED) {
13106 bool Invalid = false;
13107
13109 /// In class scope, check if this is a duplicate, for better a diagnostic.
13110 DeclarationNameInfo UsingEnumName(ED->getDeclName(), NameLoc);
13111 LookupResult Previous(*this, UsingEnumName, LookupUsingDeclName,
13112 RedeclarationKind::ForVisibleRedeclaration);
13113
13114 LookupName(Previous, S);
13115
13116 for (NamedDecl *D : Previous)
13117 if (UsingEnumDecl *UED = dyn_cast<UsingEnumDecl>(D))
13118 if (UED->getEnumDecl() == ED) {
13119 Diag(UsingLoc, diag::err_using_enum_decl_redeclaration)
13120 << SourceRange(EnumLoc, NameLoc);
13121 Diag(D->getLocation(), diag::note_using_enum_decl) << 1;
13122 Invalid = true;
13123 break;
13124 }
13125 }
13126
13127 if (RequireCompleteEnumDecl(ED, NameLoc))
13128 Invalid = true;
13129
13131 EnumLoc, NameLoc, EnumType);
13132 UD->setAccess(AS);
13133 CurContext->addDecl(UD);
13134
13135 if (Invalid) {
13136 UD->setInvalidDecl();
13137 return UD;
13138 }
13139
13140 // Create the shadow decls for each enumerator
13141 for (EnumConstantDecl *EC : ED->enumerators()) {
13142 UsingShadowDecl *PrevDecl = nullptr;
13143 DeclarationNameInfo DNI(EC->getDeclName(), EC->getLocation());
13145 RedeclarationKind::ForVisibleRedeclaration);
13146 LookupName(Previous, S);
13148
13149 if (!CheckUsingShadowDecl(UD, EC, Previous, PrevDecl))
13150 BuildUsingShadowDecl(S, UD, EC, PrevDecl);
13151 }
13152
13153 return UD;
13154}
13155
13157 ArrayRef<NamedDecl *> Expansions) {
13158 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
13159 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
13160 isa<UsingPackDecl>(InstantiatedFrom));
13161
13162 auto *UPD =
13163 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
13164 UPD->setAccess(InstantiatedFrom->getAccess());
13165 CurContext->addDecl(UPD);
13166 return UPD;
13167}
13168
13169/// Additional checks for a using declaration referring to a constructor name.
13171 assert(!UD->hasTypename() && "expecting a constructor name");
13172
13173 const Type *SourceType = UD->getQualifier()->getAsType();
13174 assert(SourceType &&
13175 "Using decl naming constructor doesn't have type in scope spec.");
13176 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
13177
13178 // Check whether the named type is a direct base class.
13179 bool AnyDependentBases = false;
13180 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
13181 AnyDependentBases);
13182 if (!Base && !AnyDependentBases) {
13183 Diag(UD->getUsingLoc(),
13184 diag::err_using_decl_constructor_not_in_direct_base)
13185 << UD->getNameInfo().getSourceRange()
13186 << QualType(SourceType, 0) << TargetClass;
13187 UD->setInvalidDecl();
13188 return true;
13189 }
13190
13191 if (Base)
13192 Base->setInheritConstructors();
13193
13194 return false;
13195}
13196
13197/// Checks that the given using declaration is not an invalid
13198/// redeclaration. Note that this is checking only for the using decl
13199/// itself, not for any ill-formedness among the UsingShadowDecls.
13201 bool HasTypenameKeyword,
13202 const CXXScopeSpec &SS,
13203 SourceLocation NameLoc,
13204 const LookupResult &Prev) {
13205 NestedNameSpecifier *Qual = SS.getScopeRep();
13206
13207 // C++03 [namespace.udecl]p8:
13208 // C++0x [namespace.udecl]p10:
13209 // A using-declaration is a declaration and can therefore be used
13210 // repeatedly where (and only where) multiple declarations are
13211 // allowed.
13212 //
13213 // That's in non-member contexts.
13215 // A dependent qualifier outside a class can only ever resolve to an
13216 // enumeration type. Therefore it conflicts with any other non-type
13217 // declaration in the same scope.
13218 // FIXME: How should we check for dependent type-type conflicts at block
13219 // scope?
13220 if (Qual->isDependent() && !HasTypenameKeyword) {
13221 for (auto *D : Prev) {
13222 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
13223 bool OldCouldBeEnumerator =
13224 isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
13225 Diag(NameLoc,
13226 OldCouldBeEnumerator ? diag::err_redefinition
13227 : diag::err_redefinition_different_kind)
13228 << Prev.getLookupName();
13229 Diag(D->getLocation(), diag::note_previous_definition);
13230 return true;
13231 }
13232 }
13233 }
13234 return false;
13235 }
13236
13237 const NestedNameSpecifier *CNNS =
13239 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
13240 NamedDecl *D = *I;
13241
13242 bool DTypename;
13243 NestedNameSpecifier *DQual;
13244 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
13245 DTypename = UD->hasTypename();
13246 DQual = UD->getQualifier();
13247 } else if (UnresolvedUsingValueDecl *UD
13248 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
13249 DTypename = false;
13250 DQual = UD->getQualifier();
13251 } else if (UnresolvedUsingTypenameDecl *UD
13252 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
13253 DTypename = true;
13254 DQual = UD->getQualifier();
13255 } else continue;
13256
13257 // using decls differ if one says 'typename' and the other doesn't.
13258 // FIXME: non-dependent using decls?
13259 if (HasTypenameKeyword != DTypename) continue;
13260
13261 // using decls differ if they name different scopes (but note that
13262 // template instantiation can cause this check to trigger when it
13263 // didn't before instantiation).
13264 if (CNNS != Context.getCanonicalNestedNameSpecifier(DQual))
13265 continue;
13266
13267 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
13268 Diag(D->getLocation(), diag::note_using_decl) << 1;
13269 return true;
13270 }
13271
13272 return false;
13273}
13274
13275/// Checks that the given nested-name qualifier used in a using decl
13276/// in the current context is appropriately related to the current
13277/// scope. If an error is found, diagnoses it and returns true.
13278/// R is nullptr, if the caller has not (yet) done a lookup, otherwise it's the
13279/// result of that lookup. UD is likewise nullptr, except when we have an
13280/// already-populated UsingDecl whose shadow decls contain the same information
13281/// (i.e. we're instantiating a UsingDecl with non-dependent scope).
13282bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
13283 const CXXScopeSpec &SS,
13284 const DeclarationNameInfo &NameInfo,
13285 SourceLocation NameLoc,
13286 const LookupResult *R, const UsingDecl *UD) {
13287 DeclContext *NamedContext = computeDeclContext(SS);
13288 assert(bool(NamedContext) == (R || UD) && !(R && UD) &&
13289 "resolvable context must have exactly one set of decls");
13290
13291 // C++ 20 permits using an enumerator that does not have a class-hierarchy
13292 // relationship.
13293 bool Cxx20Enumerator = false;
13294 if (NamedContext) {
13295 EnumConstantDecl *EC = nullptr;
13296 if (R)
13297 EC = R->getAsSingle<EnumConstantDecl>();
13298 else if (UD && UD->shadow_size() == 1)
13299 EC = dyn_cast<EnumConstantDecl>(UD->shadow_begin()->getTargetDecl());
13300 if (EC)
13301 Cxx20Enumerator = getLangOpts().CPlusPlus20;
13302
13303 if (auto *ED = dyn_cast<EnumDecl>(NamedContext)) {
13304 // C++14 [namespace.udecl]p7:
13305 // A using-declaration shall not name a scoped enumerator.
13306 // C++20 p1099 permits enumerators.
13307 if (EC && R && ED->isScoped())
13308 Diag(SS.getBeginLoc(),
13310 ? diag::warn_cxx17_compat_using_decl_scoped_enumerator
13311 : diag::ext_using_decl_scoped_enumerator)
13312 << SS.getRange();
13313
13314 // We want to consider the scope of the enumerator
13315 NamedContext = ED->getDeclContext();
13316 }
13317 }
13318
13319 if (!CurContext->isRecord()) {
13320 // C++03 [namespace.udecl]p3:
13321 // C++0x [namespace.udecl]p8:
13322 // A using-declaration for a class member shall be a member-declaration.
13323 // C++20 [namespace.udecl]p7
13324 // ... other than an enumerator ...
13325
13326 // If we weren't able to compute a valid scope, it might validly be a
13327 // dependent class or enumeration scope. If we have a 'typename' keyword,
13328 // the scope must resolve to a class type.
13329 if (NamedContext ? !NamedContext->getRedeclContext()->isRecord()
13330 : !HasTypename)
13331 return false; // OK
13332
13333 Diag(NameLoc,
13334 Cxx20Enumerator
13335 ? diag::warn_cxx17_compat_using_decl_class_member_enumerator
13336 : diag::err_using_decl_can_not_refer_to_class_member)
13337 << SS.getRange();
13338
13339 if (Cxx20Enumerator)
13340 return false; // OK
13341
13342 auto *RD = NamedContext
13343 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
13344 : nullptr;
13345 if (RD && !RequireCompleteDeclContext(const_cast<CXXScopeSpec &>(SS), RD)) {
13346 // See if there's a helpful fixit
13347
13348 if (!R) {
13349 // We will have already diagnosed the problem on the template
13350 // definition, Maybe we should do so again?
13351 } else if (R->getAsSingle<TypeDecl>()) {
13352 if (getLangOpts().CPlusPlus11) {
13353 // Convert 'using X::Y;' to 'using Y = X::Y;'.
13354 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
13355 << 0 // alias declaration
13357 NameInfo.getName().getAsString() +
13358 " = ");
13359 } else {
13360 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
13361 SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
13362 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
13363 << 1 // typedef declaration
13364 << FixItHint::CreateReplacement(UsingLoc, "typedef")
13366 InsertLoc, " " + NameInfo.getName().getAsString());
13367 }
13368 } else if (R->getAsSingle<VarDecl>()) {
13369 // Don't provide a fixit outside C++11 mode; we don't want to suggest
13370 // repeating the type of the static data member here.
13371 FixItHint FixIt;
13372 if (getLangOpts().CPlusPlus11) {
13373 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
13375 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
13376 }
13377
13378 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
13379 << 2 // reference declaration
13380 << FixIt;
13381 } else if (R->getAsSingle<EnumConstantDecl>()) {
13382 // Don't provide a fixit outside C++11 mode; we don't want to suggest
13383 // repeating the type of the enumeration here, and we can't do so if
13384 // the type is anonymous.
13385 FixItHint FixIt;
13386 if (getLangOpts().CPlusPlus11) {
13387 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
13389 UsingLoc,
13390 "constexpr auto " + NameInfo.getName().getAsString() + " = ");
13391 }
13392
13393 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
13394 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
13395 << FixIt;
13396 }
13397 }
13398
13399 return true; // Fail
13400 }
13401
13402 // If the named context is dependent, we can't decide much.
13403 if (!NamedContext) {
13404 // FIXME: in C++0x, we can diagnose if we can prove that the
13405 // nested-name-specifier does not refer to a base class, which is
13406 // still possible in some cases.
13407
13408 // Otherwise we have to conservatively report that things might be
13409 // okay.
13410 return false;
13411 }
13412
13413 // The current scope is a record.
13414 if (!NamedContext->isRecord()) {
13415 // Ideally this would point at the last name in the specifier,
13416 // but we don't have that level of source info.
13417 Diag(SS.getBeginLoc(),
13418 Cxx20Enumerator
13419 ? diag::warn_cxx17_compat_using_decl_non_member_enumerator
13420 : diag::err_using_decl_nested_name_specifier_is_not_class)
13421 << SS.getScopeRep() << SS.getRange();
13422
13423 if (Cxx20Enumerator)
13424 return false; // OK
13425
13426 return true;
13427 }
13428
13429 if (!NamedContext->isDependentContext() &&
13430 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
13431 return true;
13432
13433 if (getLangOpts().CPlusPlus11) {
13434 // C++11 [namespace.udecl]p3:
13435 // In a using-declaration used as a member-declaration, the
13436 // nested-name-specifier shall name a base class of the class
13437 // being defined.
13438
13439 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
13440 cast<CXXRecordDecl>(NamedContext))) {
13441
13442 if (Cxx20Enumerator) {
13443 Diag(NameLoc, diag::warn_cxx17_compat_using_decl_non_member_enumerator)
13444 << SS.getRange();
13445 return false;
13446 }
13447
13448 if (CurContext == NamedContext) {
13449 Diag(SS.getBeginLoc(),
13450 diag::err_using_decl_nested_name_specifier_is_current_class)
13451 << SS.getRange();
13452 return !getLangOpts().CPlusPlus20;
13453 }
13454
13455 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
13456 Diag(SS.getBeginLoc(),
13457 diag::err_using_decl_nested_name_specifier_is_not_base_class)
13458 << SS.getScopeRep() << cast<CXXRecordDecl>(CurContext)
13459 << SS.getRange();
13460 }
13461 return true;
13462 }
13463
13464 return false;
13465 }
13466
13467 // C++03 [namespace.udecl]p4:
13468 // A using-declaration used as a member-declaration shall refer
13469 // to a member of a base class of the class being defined [etc.].
13470
13471 // Salient point: SS doesn't have to name a base class as long as
13472 // lookup only finds members from base classes. Therefore we can
13473 // diagnose here only if we can prove that can't happen,
13474 // i.e. if the class hierarchies provably don't intersect.
13475
13476 // TODO: it would be nice if "definitely valid" results were cached
13477 // in the UsingDecl and UsingShadowDecl so that these checks didn't
13478 // need to be repeated.
13479
13481 auto Collect = [&Bases](const CXXRecordDecl *Base) {
13482 Bases.insert(Base);
13483 return true;
13484 };
13485
13486 // Collect all bases. Return false if we find a dependent base.
13487 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
13488 return false;
13489
13490 // Returns true if the base is dependent or is one of the accumulated base
13491 // classes.
13492 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
13493 return !Bases.count(Base);
13494 };
13495
13496 // Return false if the class has a dependent base or if it or one
13497 // of its bases is present in the base set of the current context.
13498 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
13499 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
13500 return false;
13501
13502 Diag(SS.getRange().getBegin(),
13503 diag::err_using_decl_nested_name_specifier_is_not_base_class)
13504 << SS.getScopeRep()
13505 << cast<CXXRecordDecl>(CurContext)
13506 << SS.getRange();
13507
13508 return true;
13509}
13510
13512 MultiTemplateParamsArg TemplateParamLists,
13513 SourceLocation UsingLoc, UnqualifiedId &Name,
13514 const ParsedAttributesView &AttrList,
13515 TypeResult Type, Decl *DeclFromDeclSpec) {
13516 // Get the innermost enclosing declaration scope.
13517 S = S->getDeclParent();
13518
13519 if (Type.isInvalid())
13520 return nullptr;
13521
13522 bool Invalid = false;
13524 TypeSourceInfo *TInfo = nullptr;
13525 GetTypeFromParser(Type.get(), &TInfo);
13526
13527 if (DiagnoseClassNameShadow(CurContext, NameInfo))
13528 return nullptr;
13529
13530 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
13532 Invalid = true;
13534 TInfo->getTypeLoc().getBeginLoc());
13535 }
13536
13537 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
13538 TemplateParamLists.size()
13540 : RedeclarationKind::ForVisibleRedeclaration);
13541 LookupName(Previous, S);
13542
13543 // Warn about shadowing the name of a template parameter.
13544 if (Previous.isSingleResult() &&
13545 Previous.getFoundDecl()->isTemplateParameter()) {
13546 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
13547 Previous.clear();
13548 }
13549
13550 assert(Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
13551 "name in alias declaration must be an identifier");
13553 Name.StartLocation,
13554 Name.Identifier, TInfo);
13555
13556 NewTD->setAccess(AS);
13557
13558 if (Invalid)
13559 NewTD->setInvalidDecl();
13560
13561 ProcessDeclAttributeList(S, NewTD, AttrList);
13562 AddPragmaAttributes(S, NewTD);
13563 ProcessAPINotes(NewTD);
13564
13566 Invalid |= NewTD->isInvalidDecl();
13567
13568 bool Redeclaration = false;
13569
13570 NamedDecl *NewND;
13571 if (TemplateParamLists.size()) {
13572 TypeAliasTemplateDecl *OldDecl = nullptr;
13573 TemplateParameterList *OldTemplateParams = nullptr;
13574
13575 if (TemplateParamLists.size() != 1) {
13576 Diag(UsingLoc, diag::err_alias_template_extra_headers)
13577 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
13578 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
13579 Invalid = true;
13580 }
13581 TemplateParameterList *TemplateParams = TemplateParamLists[0];
13582
13583 // Check that we can declare a template here.
13584 if (CheckTemplateDeclScope(S, TemplateParams))
13585 return nullptr;
13586
13587 // Only consider previous declarations in the same scope.
13588 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
13589 /*ExplicitInstantiationOrSpecialization*/false);
13590 if (!Previous.empty()) {
13591 Redeclaration = true;
13592
13593 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
13594 if (!OldDecl && !Invalid) {
13595 Diag(UsingLoc, diag::err_redefinition_different_kind)
13596 << Name.Identifier;
13597
13598 NamedDecl *OldD = Previous.getRepresentativeDecl();
13599 if (OldD->getLocation().isValid())
13600 Diag(OldD->getLocation(), diag::note_previous_definition);
13601
13602 Invalid = true;
13603 }
13604
13605 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
13606 if (TemplateParameterListsAreEqual(TemplateParams,
13607 OldDecl->getTemplateParameters(),
13608 /*Complain=*/true,
13610 OldTemplateParams =
13612 else
13613 Invalid = true;
13614
13615 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
13616 if (!Invalid &&
13618 NewTD->getUnderlyingType())) {
13619 // FIXME: The C++0x standard does not clearly say this is ill-formed,
13620 // but we can't reasonably accept it.
13621 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
13622 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
13623 if (OldTD->getLocation().isValid())
13624 Diag(OldTD->getLocation(), diag::note_previous_definition);
13625 Invalid = true;
13626 }
13627 }
13628 }
13629
13630 // Merge any previous default template arguments into our parameters,
13631 // and check the parameter list.
13632 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
13634 return nullptr;
13635
13636 TypeAliasTemplateDecl *NewDecl =
13638 Name.Identifier, TemplateParams,
13639 NewTD);
13640 NewTD->setDescribedAliasTemplate(NewDecl);
13641
13642 NewDecl->setAccess(AS);
13643
13644 if (Invalid)
13645 NewDecl->setInvalidDecl();
13646 else if (OldDecl) {
13647 NewDecl->setPreviousDecl(OldDecl);
13648 CheckRedeclarationInModule(NewDecl, OldDecl);
13649 }
13650
13651 NewND = NewDecl;
13652 } else {
13653 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
13655 handleTagNumbering(TD, S);
13656 }
13657 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
13658 NewND = NewTD;
13659 }
13660
13661 PushOnScopeChains(NewND, S);
13662 ActOnDocumentableDecl(NewND);
13663 return NewND;
13664}
13665
13667 SourceLocation AliasLoc,
13668 IdentifierInfo *Alias, CXXScopeSpec &SS,
13669 SourceLocation IdentLoc,
13670 IdentifierInfo *Ident) {
13671
13672 // Lookup the namespace name.
13673 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
13674 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
13675
13676 if (R.isAmbiguous())
13677 return nullptr;
13678
13679 if (R.empty()) {
13680 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
13681 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
13682 return nullptr;
13683 }
13684 }
13685 assert(!R.isAmbiguous() && !R.empty());
13687
13688 // Check if we have a previous declaration with the same name.
13689 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
13690 RedeclarationKind::ForVisibleRedeclaration);
13691 LookupName(PrevR, S);
13692
13693 // Check we're not shadowing a template parameter.
13694 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
13696 PrevR.clear();
13697 }
13698
13699 // Filter out any other lookup result from an enclosing scope.
13700 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
13701 /*AllowInlineNamespace*/false);
13702
13703 // Find the previous declaration and check that we can redeclare it.
13704 NamespaceAliasDecl *Prev = nullptr;
13705 if (PrevR.isSingleResult()) {
13706 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
13707 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
13708 // We already have an alias with the same name that points to the same
13709 // namespace; check that it matches.
13710 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
13711 Prev = AD;
13712 } else if (isVisible(PrevDecl)) {
13713 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
13714 << Alias;
13715 Diag(AD->getLocation(), diag::note_previous_namespace_alias)
13716 << AD->getNamespace();
13717 return nullptr;
13718 }
13719 } else if (isVisible(PrevDecl)) {
13720 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
13721 ? diag::err_redefinition
13722 : diag::err_redefinition_different_kind;
13723 Diag(AliasLoc, DiagID) << Alias;
13724 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13725 return nullptr;
13726 }
13727 }
13728
13729 // The use of a nested name specifier may trigger deprecation warnings.
13730 DiagnoseUseOfDecl(ND, IdentLoc);
13731
13733 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
13734 Alias, SS.getWithLocInContext(Context),
13735 IdentLoc, ND);
13736 if (Prev)
13737 AliasDecl->setPreviousDecl(Prev);
13738
13740 return AliasDecl;
13741}
13742
13743namespace {
13744struct SpecialMemberExceptionSpecInfo
13745 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
13748
13749 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
13753 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
13754
13755 bool visitBase(CXXBaseSpecifier *Base);
13756 bool visitField(FieldDecl *FD);
13757
13758 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
13759 unsigned Quals);
13760
13761 void visitSubobjectCall(Subobject Subobj,
13763};
13764}
13765
13766bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
13767 auto *RT = Base->getType()->getAs<RecordType>();
13768 if (!RT)
13769 return false;
13770
13771 auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
13772 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
13773 if (auto *BaseCtor = SMOR.getMethod()) {
13774 visitSubobjectCall(Base, BaseCtor);
13775 return false;
13776 }
13777
13778 visitClassSubobject(BaseClass, Base, 0);
13779 return false;
13780}
13781
13782bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
13784 FD->hasInClassInitializer()) {
13785 Expr *E = FD->getInClassInitializer();
13786 if (!E)
13787 // FIXME: It's a little wasteful to build and throw away a
13788 // CXXDefaultInitExpr here.
13789 // FIXME: We should have a single context note pointing at Loc, and
13790 // this location should be MD->getLocation() instead, since that's
13791 // the location where we actually use the default init expression.
13792 E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
13793 if (E)
13794 ExceptSpec.CalledExpr(E);
13795 } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
13796 ->getAs<RecordType>()) {
13797 visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
13798 FD->getType().getCVRQualifiers());
13799 }
13800 return false;
13801}
13802
13803void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
13804 Subobject Subobj,
13805 unsigned Quals) {
13806 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
13807 bool IsMutable = Field && Field->isMutable();
13808 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
13809}
13810
13811void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
13812 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
13813 // Note, if lookup fails, it doesn't matter what exception specification we
13814 // choose because the special member will be deleted.
13815 if (CXXMethodDecl *MD = SMOR.getMethod())
13816 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
13817}
13818
13820 llvm::APSInt Result;
13822 ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool);
13823 ExplicitSpec.setExpr(Converted.get());
13824 if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
13825 ExplicitSpec.setKind(Result.getBoolValue()
13828 return true;
13829 }
13831 return false;
13832}
13833
13836 if (!ExplicitExpr->isTypeDependent())
13838 return ES;
13839}
13840
13845 ComputingExceptionSpec CES(S, MD, Loc);
13846
13847 CXXRecordDecl *ClassDecl = MD->getParent();
13848
13849 // C++ [except.spec]p14:
13850 // An implicitly declared special member function (Clause 12) shall have an
13851 // exception-specification. [...]
13852 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
13853 if (ClassDecl->isInvalidDecl())
13854 return Info.ExceptSpec;
13855
13856 // FIXME: If this diagnostic fires, we're probably missing a check for
13857 // attempting to resolve an exception specification before it's known
13858 // at a higher level.
13859 if (S.RequireCompleteType(MD->getLocation(),
13860 S.Context.getRecordType(ClassDecl),
13861 diag::err_exception_spec_incomplete_type))
13862 return Info.ExceptSpec;
13863
13864 // C++1z [except.spec]p7:
13865 // [Look for exceptions thrown by] a constructor selected [...] to
13866 // initialize a potentially constructed subobject,
13867 // C++1z [except.spec]p8:
13868 // The exception specification for an implicitly-declared destructor, or a
13869 // destructor without a noexcept-specifier, is potentially-throwing if and
13870 // only if any of the destructors for any of its potentially constructed
13871 // subojects is potentially throwing.
13872 // FIXME: We respect the first rule but ignore the "potentially constructed"
13873 // in the second rule to resolve a core issue (no number yet) that would have
13874 // us reject:
13875 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
13876 // struct B : A {};
13877 // struct C : B { void f(); };
13878 // ... due to giving B::~B() a non-throwing exception specification.
13879 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
13880 : Info.VisitAllBases);
13881
13882 return Info.ExceptSpec;
13883}
13884
13885namespace {
13886/// RAII object to register a special member as being currently declared.
13887struct DeclaringSpecialMember {
13888 Sema &S;
13890 Sema::ContextRAII SavedContext;
13891 bool WasAlreadyBeingDeclared;
13892
13893 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, CXXSpecialMemberKind CSM)
13894 : S(S), D(RD, CSM), SavedContext(S, RD) {
13895 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
13896 if (WasAlreadyBeingDeclared)
13897 // This almost never happens, but if it does, ensure that our cache
13898 // doesn't contain a stale result.
13899 S.SpecialMemberCache.clear();
13900 else {
13901 // Register a note to be produced if we encounter an error while
13902 // declaring the special member.
13905 // FIXME: We don't have a location to use here. Using the class's
13906 // location maintains the fiction that we declare all special members
13907 // with the class, but (1) it's not clear that lying about that helps our
13908 // users understand what's going on, and (2) there may be outer contexts
13909 // on the stack (some of which are relevant) and printing them exposes
13910 // our lies.
13912 Ctx.Entity = RD;
13913 Ctx.SpecialMember = CSM;
13915 }
13916 }
13917 ~DeclaringSpecialMember() {
13918 if (!WasAlreadyBeingDeclared) {
13919 S.SpecialMembersBeingDeclared.erase(D);
13921 }
13922 }
13923
13924 /// Are we already trying to declare this special member?
13925 bool isAlreadyBeingDeclared() const {
13926 return WasAlreadyBeingDeclared;
13927 }
13928};
13929}
13930
13932 // Look up any existing declarations, but don't trigger declaration of all
13933 // implicit special members with this name.
13934 DeclarationName Name = FD->getDeclName();
13936 RedeclarationKind::ForExternalRedeclaration);
13937 for (auto *D : FD->getParent()->lookup(Name))
13938 if (auto *Acceptable = R.getAcceptableDecl(D))
13939 R.addDecl(Acceptable);
13940 R.resolveKind();
13942
13943 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/ false,
13945}
13946
13947void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
13948 QualType ResultTy,
13949 ArrayRef<QualType> Args) {
13950 // Build an exception specification pointing back at this constructor.
13952
13954 if (AS != LangAS::Default) {
13955 EPI.TypeQuals.addAddressSpace(AS);
13956 }
13957
13958 auto QT = Context.getFunctionType(ResultTy, Args, EPI);
13959 SpecialMem->setType(QT);
13960
13961 // During template instantiation of implicit special member functions we need
13962 // a reliable TypeSourceInfo for the function prototype in order to allow
13963 // functions to be substituted.
13965 cast<CXXRecordDecl>(SpecialMem->getParent())->isLambda()) {
13966 TypeSourceInfo *TSI =
13968 SpecialMem->setTypeSourceInfo(TSI);
13969 }
13970}
13971
13973 CXXRecordDecl *ClassDecl) {
13974 // C++ [class.ctor]p5:
13975 // A default constructor for a class X is a constructor of class X
13976 // that can be called without an argument. If there is no
13977 // user-declared constructor for class X, a default constructor is
13978 // implicitly declared. An implicitly-declared default constructor
13979 // is an inline public member of its class.
13980 assert(ClassDecl->needsImplicitDefaultConstructor() &&
13981 "Should not build implicit default constructor!");
13982
13983 DeclaringSpecialMember DSM(*this, ClassDecl,
13985 if (DSM.isAlreadyBeingDeclared())
13986 return nullptr;
13987
13989 *this, ClassDecl, CXXSpecialMemberKind::DefaultConstructor, false);
13990
13991 // Create the actual constructor declaration.
13992 CanQualType ClassType
13994 SourceLocation ClassLoc = ClassDecl->getLocation();
13995 DeclarationName Name
13997 DeclarationNameInfo NameInfo(Name, ClassLoc);
13999 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),
14000 /*TInfo=*/nullptr, ExplicitSpecifier(),
14001 getCurFPFeatures().isFPConstrained(),
14002 /*isInline=*/true, /*isImplicitlyDeclared=*/true,
14005 DefaultCon->setAccess(AS_public);
14006 DefaultCon->setDefaulted();
14007
14008 setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, std::nullopt);
14009
14010 if (getLangOpts().CUDA)
14012 ClassDecl, CXXSpecialMemberKind::DefaultConstructor, DefaultCon,
14013 /* ConstRHS */ false,
14014 /* Diagnose */ false);
14015
14016 // We don't need to use SpecialMemberIsTrivial here; triviality for default
14017 // constructors is easy to compute.
14018 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
14019
14020 // Note that we have declared this constructor.
14022
14023 Scope *S = getScopeForContext(ClassDecl);
14025
14026 if (ShouldDeleteSpecialMember(DefaultCon,
14028 SetDeclDeleted(DefaultCon, ClassLoc);
14029
14030 if (S)
14031 PushOnScopeChains(DefaultCon, S, false);
14032 ClassDecl->addDecl(DefaultCon);
14033
14034 return DefaultCon;
14035}
14036
14038 CXXConstructorDecl *Constructor) {
14039 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
14040 !Constructor->doesThisDeclarationHaveABody() &&
14041 !Constructor->isDeleted()) &&
14042 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
14043 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
14044 return;
14045
14046 CXXRecordDecl *ClassDecl = Constructor->getParent();
14047 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
14048 if (ClassDecl->isInvalidDecl()) {
14049 return;
14050 }
14051
14052 SynthesizedFunctionScope Scope(*this, Constructor);
14053
14054 // The exception specification is needed because we are defining the
14055 // function.
14056 ResolveExceptionSpec(CurrentLocation,
14057 Constructor->getType()->castAs<FunctionProtoType>());
14058 MarkVTableUsed(CurrentLocation, ClassDecl);
14059
14060 // Add a context note for diagnostics produced after this point.
14061 Scope.addContextNote(CurrentLocation);
14062
14063 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
14064 Constructor->setInvalidDecl();
14065 return;
14066 }
14067
14068 SourceLocation Loc = Constructor->getEndLoc().isValid()
14069 ? Constructor->getEndLoc()
14070 : Constructor->getLocation();
14071 Constructor->setBody(new (Context) CompoundStmt(Loc));
14072 Constructor->markUsed(Context);
14073
14075 L->CompletedImplicitDefinition(Constructor);
14076 }
14077
14078 DiagnoseUninitializedFields(*this, Constructor);
14079}
14080
14082 // Perform any delayed checks on exception specifications.
14084}
14085
14086/// Find or create the fake constructor we synthesize to model constructing an
14087/// object of a derived class via a constructor of a base class.
14090 CXXConstructorDecl *BaseCtor,
14092 CXXRecordDecl *Derived = Shadow->getParent();
14093 SourceLocation UsingLoc = Shadow->getLocation();
14094
14095 // FIXME: Add a new kind of DeclarationName for an inherited constructor.
14096 // For now we use the name of the base class constructor as a member of the
14097 // derived class to indicate a (fake) inherited constructor name.
14098 DeclarationName Name = BaseCtor->getDeclName();
14099
14100 // Check to see if we already have a fake constructor for this inherited
14101 // constructor call.
14102 for (NamedDecl *Ctor : Derived->lookup(Name))
14103 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
14104 ->getInheritedConstructor()
14105 .getConstructor(),
14106 BaseCtor))
14107 return cast<CXXConstructorDecl>(Ctor);
14108
14109 DeclarationNameInfo NameInfo(Name, UsingLoc);
14110 TypeSourceInfo *TInfo =
14111 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
14112 FunctionProtoTypeLoc ProtoLoc =
14114
14115 // Check the inherited constructor is valid and find the list of base classes
14116 // from which it was inherited.
14117 InheritedConstructorInfo ICI(*this, Loc, Shadow);
14118
14119 bool Constexpr = BaseCtor->isConstexpr() &&
14122 false, BaseCtor, &ICI);
14123
14125 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
14126 BaseCtor->getExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
14127 /*isInline=*/true,
14128 /*isImplicitlyDeclared=*/true,
14130 InheritedConstructor(Shadow, BaseCtor),
14131 BaseCtor->getTrailingRequiresClause());
14132 if (Shadow->isInvalidDecl())
14133 DerivedCtor->setInvalidDecl();
14134
14135 // Build an unevaluated exception specification for this fake constructor.
14136 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
14139 EPI.ExceptionSpec.SourceDecl = DerivedCtor;
14140 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
14141 FPT->getParamTypes(), EPI));
14142
14143 // Build the parameter declarations.
14145 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
14146 TypeSourceInfo *TInfo =
14149 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
14150 FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr);
14151 PD->setScopeInfo(0, I);
14152 PD->setImplicit();
14153 // Ensure attributes are propagated onto parameters (this matters for
14154 // format, pass_object_size, ...).
14155 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
14156 ParamDecls.push_back(PD);
14157 ProtoLoc.setParam(I, PD);
14158 }
14159
14160 // Set up the new constructor.
14161 assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
14162 DerivedCtor->setAccess(BaseCtor->getAccess());
14163 DerivedCtor->setParams(ParamDecls);
14164 Derived->addDecl(DerivedCtor);
14165
14166 if (ShouldDeleteSpecialMember(DerivedCtor,
14168 SetDeclDeleted(DerivedCtor, UsingLoc);
14169
14170 return DerivedCtor;
14171}
14172
14174 InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
14177 &ICI,
14178 /*Diagnose*/ true);
14179}
14180
14182 CXXConstructorDecl *Constructor) {
14183 CXXRecordDecl *ClassDecl = Constructor->getParent();
14184 assert(Constructor->getInheritedConstructor() &&
14185 !Constructor->doesThisDeclarationHaveABody() &&
14186 !Constructor->isDeleted());
14187 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
14188 return;
14189
14190 // Initializations are performed "as if by a defaulted default constructor",
14191 // so enter the appropriate scope.
14192 SynthesizedFunctionScope Scope(*this, Constructor);
14193
14194 // The exception specification is needed because we are defining the
14195 // function.
14196 ResolveExceptionSpec(CurrentLocation,
14197 Constructor->getType()->castAs<FunctionProtoType>());
14198 MarkVTableUsed(CurrentLocation, ClassDecl);
14199
14200 // Add a context note for diagnostics produced after this point.
14201 Scope.addContextNote(CurrentLocation);
14202
14204 Constructor->getInheritedConstructor().getShadowDecl();
14205 CXXConstructorDecl *InheritedCtor =
14206 Constructor->getInheritedConstructor().getConstructor();
14207
14208 // [class.inhctor.init]p1:
14209 // initialization proceeds as if a defaulted default constructor is used to
14210 // initialize the D object and each base class subobject from which the
14211 // constructor was inherited
14212
14213 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
14214 CXXRecordDecl *RD = Shadow->getParent();
14215 SourceLocation InitLoc = Shadow->getLocation();
14216
14217 // Build explicit initializers for all base classes from which the
14218 // constructor was inherited.
14220 for (bool VBase : {false, true}) {
14221 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
14222 if (B.isVirtual() != VBase)
14223 continue;
14224
14225 auto *BaseRD = B.getType()->getAsCXXRecordDecl();
14226 if (!BaseRD)
14227 continue;
14228
14229 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
14230 if (!BaseCtor.first)
14231 continue;
14232
14233 MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
14235 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
14236
14237 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
14238 Inits.push_back(new (Context) CXXCtorInitializer(
14239 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
14240 SourceLocation()));
14241 }
14242 }
14243
14244 // We now proceed as if for a defaulted default constructor, with the relevant
14245 // initializers replaced.
14246
14247 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
14248 Constructor->setInvalidDecl();
14249 return;
14250 }
14251
14252 Constructor->setBody(new (Context) CompoundStmt(InitLoc));
14253 Constructor->markUsed(Context);
14254
14256 L->CompletedImplicitDefinition(Constructor);
14257 }
14258
14259 DiagnoseUninitializedFields(*this, Constructor);
14260}
14261
14263 // C++ [class.dtor]p2:
14264 // If a class has no user-declared destructor, a destructor is
14265 // declared implicitly. An implicitly-declared destructor is an
14266 // inline public member of its class.
14267 assert(ClassDecl->needsImplicitDestructor());
14268
14269 DeclaringSpecialMember DSM(*this, ClassDecl,
14271 if (DSM.isAlreadyBeingDeclared())
14272 return nullptr;
14273
14275 *this, ClassDecl, CXXSpecialMemberKind::Destructor, false);
14276
14277 // Create the actual destructor declaration.
14278 CanQualType ClassType
14280 SourceLocation ClassLoc = ClassDecl->getLocation();
14281 DeclarationName Name
14283 DeclarationNameInfo NameInfo(Name, ClassLoc);
14285 Context, ClassDecl, ClassLoc, NameInfo, QualType(), nullptr,
14286 getCurFPFeatures().isFPConstrained(),
14287 /*isInline=*/true,
14288 /*isImplicitlyDeclared=*/true,
14291 Destructor->setAccess(AS_public);
14292 Destructor->setDefaulted();
14293
14294 setupImplicitSpecialMemberType(Destructor, Context.VoidTy, std::nullopt);
14295
14296 if (getLangOpts().CUDA)
14299 /* ConstRHS */ false,
14300 /* Diagnose */ false);
14301
14302 // We don't need to use SpecialMemberIsTrivial here; triviality for
14303 // destructors is easy to compute.
14304 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
14305 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
14306 ClassDecl->hasTrivialDestructorForCall());
14307
14308 // Note that we have declared this destructor.
14310
14311 Scope *S = getScopeForContext(ClassDecl);
14313
14314 // We can't check whether an implicit destructor is deleted before we complete
14315 // the definition of the class, because its validity depends on the alignment
14316 // of the class. We'll check this from ActOnFields once the class is complete.
14317 if (ClassDecl->isCompleteDefinition() &&
14319 SetDeclDeleted(Destructor, ClassLoc);
14320
14321 // Introduce this destructor into its scope.
14322 if (S)
14323 PushOnScopeChains(Destructor, S, false);
14324 ClassDecl->addDecl(Destructor);
14325
14326 return Destructor;
14327}
14328
14331 assert((Destructor->isDefaulted() &&
14332 !Destructor->doesThisDeclarationHaveABody() &&
14333 !Destructor->isDeleted()) &&
14334 "DefineImplicitDestructor - call it for implicit default dtor");
14335 if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
14336 return;
14337
14338 CXXRecordDecl *ClassDecl = Destructor->getParent();
14339 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
14340
14342
14343 // The exception specification is needed because we are defining the
14344 // function.
14345 ResolveExceptionSpec(CurrentLocation,
14346 Destructor->getType()->castAs<FunctionProtoType>());
14347 MarkVTableUsed(CurrentLocation, ClassDecl);
14348
14349 // Add a context note for diagnostics produced after this point.
14350 Scope.addContextNote(CurrentLocation);
14351
14353 Destructor->getParent());
14354
14356 Destructor->setInvalidDecl();
14357 return;
14358 }
14359
14360 SourceLocation Loc = Destructor->getEndLoc().isValid()
14361 ? Destructor->getEndLoc()
14362 : Destructor->getLocation();
14363 Destructor->setBody(new (Context) CompoundStmt(Loc));
14364 Destructor->markUsed(Context);
14365
14367 L->CompletedImplicitDefinition(Destructor);
14368 }
14369}
14370
14373 if (Destructor->isInvalidDecl())
14374 return;
14375
14376 CXXRecordDecl *ClassDecl = Destructor->getParent();
14378 "implicit complete dtors unneeded outside MS ABI");
14379 assert(ClassDecl->getNumVBases() > 0 &&
14380 "complete dtor only exists for classes with vbases");
14381
14383
14384 // Add a context note for diagnostics produced after this point.
14385 Scope.addContextNote(CurrentLocation);
14386
14387 MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl);
14388}
14389
14390/// Perform any semantic analysis which needs to be delayed until all
14391/// pending class member declarations have been parsed.
14393 // If the context is an invalid C++ class, just suppress these checks.
14394 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
14395 if (Record->isInvalidDecl()) {
14398 return;
14399 }
14401 }
14402}
14403
14406
14407 if (!DelayedDllExportMemberFunctions.empty()) {
14409 std::swap(DelayedDllExportMemberFunctions, WorkList);
14410 for (CXXMethodDecl *M : WorkList) {
14411 DefineDefaultedFunction(*this, M, M->getLocation());
14412
14413 // Pass the method to the consumer to get emitted. This is not necessary
14414 // for explicit instantiation definitions, as they will get emitted
14415 // anyway.
14416 if (M->getParent()->getTemplateSpecializationKind() !=
14419 }
14420 }
14421}
14422
14424 if (!DelayedDllExportClasses.empty()) {
14425 // Calling ReferenceDllExportedMembers might cause the current function to
14426 // be called again, so use a local copy of DelayedDllExportClasses.
14428 std::swap(DelayedDllExportClasses, WorkList);
14429 for (CXXRecordDecl *Class : WorkList)
14431 }
14432}
14433
14435 assert(getLangOpts().CPlusPlus11 &&
14436 "adjusting dtor exception specs was introduced in c++11");
14437
14438 if (Destructor->isDependentContext())
14439 return;
14440
14441 // C++11 [class.dtor]p3:
14442 // A declaration of a destructor that does not have an exception-
14443 // specification is implicitly considered to have the same exception-
14444 // specification as an implicit declaration.
14445 const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>();
14446 if (DtorType->hasExceptionSpec())
14447 return;
14448
14449 // Replace the destructor's type, building off the existing one. Fortunately,
14450 // the only thing of interest in the destructor type is its extended info.
14451 // The return and arguments are fixed.
14452 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
14455 Destructor->setType(
14456 Context.getFunctionType(Context.VoidTy, std::nullopt, EPI));
14457
14458 // FIXME: If the destructor has a body that could throw, and the newly created
14459 // spec doesn't allow exceptions, we should emit a warning, because this
14460 // change in behavior can break conforming C++03 programs at runtime.
14461 // However, we don't have a body or an exception specification yet, so it
14462 // needs to be done somewhere else.
14463}
14464
14465namespace {
14466/// An abstract base class for all helper classes used in building the
14467// copy/move operators. These classes serve as factory functions and help us
14468// avoid using the same Expr* in the AST twice.
14469class ExprBuilder {
14470 ExprBuilder(const ExprBuilder&) = delete;
14471 ExprBuilder &operator=(const ExprBuilder&) = delete;
14472
14473protected:
14474 static Expr *assertNotNull(Expr *E) {
14475 assert(E && "Expression construction must not fail.");
14476 return E;
14477 }
14478
14479public:
14480 ExprBuilder() {}
14481 virtual ~ExprBuilder() {}
14482
14483 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
14484};
14485
14486class RefBuilder: public ExprBuilder {
14487 VarDecl *Var;
14488 QualType VarType;
14489
14490public:
14491 Expr *build(Sema &S, SourceLocation Loc) const override {
14492 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));
14493 }
14494
14495 RefBuilder(VarDecl *Var, QualType VarType)
14496 : Var(Var), VarType(VarType) {}
14497};
14498
14499class ThisBuilder: public ExprBuilder {
14500public:
14501 Expr *build(Sema &S, SourceLocation Loc) const override {
14502 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
14503 }
14504};
14505
14506class CastBuilder: public ExprBuilder {
14507 const ExprBuilder &Builder;
14508 QualType Type;
14510 const CXXCastPath &Path;
14511
14512public:
14513 Expr *build(Sema &S, SourceLocation Loc) const override {
14514 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
14515 CK_UncheckedDerivedToBase, Kind,
14516 &Path).get());
14517 }
14518
14519 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
14520 const CXXCastPath &Path)
14521 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
14522};
14523
14524class DerefBuilder: public ExprBuilder {
14525 const ExprBuilder &Builder;
14526
14527public:
14528 Expr *build(Sema &S, SourceLocation Loc) const override {
14529 return assertNotNull(
14530 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
14531 }
14532
14533 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14534};
14535
14536class MemberBuilder: public ExprBuilder {
14537 const ExprBuilder &Builder;
14538 QualType Type;
14539 CXXScopeSpec SS;
14540 bool IsArrow;
14541 LookupResult &MemberLookup;
14542
14543public:
14544 Expr *build(Sema &S, SourceLocation Loc) const override {
14545 return assertNotNull(S.BuildMemberReferenceExpr(
14546 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
14547 nullptr, MemberLookup, nullptr, nullptr).get());
14548 }
14549
14550 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
14551 LookupResult &MemberLookup)
14552 : Builder(Builder), Type(Type), IsArrow(IsArrow),
14553 MemberLookup(MemberLookup) {}
14554};
14555
14556class MoveCastBuilder: public ExprBuilder {
14557 const ExprBuilder &Builder;
14558
14559public:
14560 Expr *build(Sema &S, SourceLocation Loc) const override {
14561 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
14562 }
14563
14564 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14565};
14566
14567class LvalueConvBuilder: public ExprBuilder {
14568 const ExprBuilder &Builder;
14569
14570public:
14571 Expr *build(Sema &S, SourceLocation Loc) const override {
14572 return assertNotNull(
14573 S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
14574 }
14575
14576 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14577};
14578
14579class SubscriptBuilder: public ExprBuilder {
14580 const ExprBuilder &Base;
14581 const ExprBuilder &Index;
14582
14583public:
14584 Expr *build(Sema &S, SourceLocation Loc) const override {
14585 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
14586 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
14587 }
14588
14589 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
14590 : Base(Base), Index(Index) {}
14591};
14592
14593} // end anonymous namespace
14594
14595/// When generating a defaulted copy or move assignment operator, if a field
14596/// should be copied with __builtin_memcpy rather than via explicit assignments,
14597/// do so. This optimization only applies for arrays of scalars, and for arrays
14598/// of class type where the selected copy/move-assignment operator is trivial.
14599static StmtResult
14601 const ExprBuilder &ToB, const ExprBuilder &FromB) {
14602 // Compute the size of the memory buffer to be copied.
14603 QualType SizeType = S.Context.getSizeType();
14604 llvm::APInt Size(S.Context.getTypeSize(SizeType),
14606
14607 // Take the address of the field references for "from" and "to". We
14608 // directly construct UnaryOperators here because semantic analysis
14609 // does not permit us to take the address of an xvalue.
14610 Expr *From = FromB.build(S, Loc);
14611 From = UnaryOperator::Create(
14612 S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()),
14614 Expr *To = ToB.build(S, Loc);
14616 S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()),
14618
14619 const Type *E = T->getBaseElementTypeUnsafe();
14620 bool NeedsCollectableMemCpy =
14621 E->isRecordType() &&
14622 E->castAs<RecordType>()->getDecl()->hasObjectMember();
14623
14624 // Create a reference to the __builtin_objc_memmove_collectable function
14625 StringRef MemCpyName = NeedsCollectableMemCpy ?
14626 "__builtin_objc_memmove_collectable" :
14627 "__builtin_memcpy";
14628 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
14630 S.LookupName(R, S.TUScope, true);
14631
14632 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
14633 if (!MemCpy)
14634 // Something went horribly wrong earlier, and we will have complained
14635 // about it.
14636 return StmtError();
14637
14638 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
14639 VK_PRValue, Loc, nullptr);
14640 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
14641
14642 Expr *CallArgs[] = {
14643 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
14644 };
14645 ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
14646 Loc, CallArgs, Loc);
14647
14648 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
14649 return Call.getAs<Stmt>();
14650}
14651
14652/// Builds a statement that copies/moves the given entity from \p From to
14653/// \c To.
14654///
14655/// This routine is used to copy/move the members of a class with an
14656/// implicitly-declared copy/move assignment operator. When the entities being
14657/// copied are arrays, this routine builds for loops to copy them.
14658///
14659/// \param S The Sema object used for type-checking.
14660///
14661/// \param Loc The location where the implicit copy/move is being generated.
14662///
14663/// \param T The type of the expressions being copied/moved. Both expressions
14664/// must have this type.
14665///
14666/// \param To The expression we are copying/moving to.
14667///
14668/// \param From The expression we are copying/moving from.
14669///
14670/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
14671/// Otherwise, it's a non-static member subobject.
14672///
14673/// \param Copying Whether we're copying or moving.
14674///
14675/// \param Depth Internal parameter recording the depth of the recursion.
14676///
14677/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
14678/// if a memcpy should be used instead.
14679static StmtResult
14681 const ExprBuilder &To, const ExprBuilder &From,
14682 bool CopyingBaseSubobject, bool Copying,
14683 unsigned Depth = 0) {
14684 // C++11 [class.copy]p28:
14685 // Each subobject is assigned in the manner appropriate to its type:
14686 //
14687 // - if the subobject is of class type, as if by a call to operator= with
14688 // the subobject as the object expression and the corresponding
14689 // subobject of x as a single function argument (as if by explicit
14690 // qualification; that is, ignoring any possible virtual overriding
14691 // functions in more derived classes);
14692 //
14693 // C++03 [class.copy]p13:
14694 // - if the subobject is of class type, the copy assignment operator for
14695 // the class is used (as if by explicit qualification; that is,
14696 // ignoring any possible virtual overriding functions in more derived
14697 // classes);
14698 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
14699 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
14700
14701 // Look for operator=.
14702 DeclarationName Name
14704 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
14705 S.LookupQualifiedName(OpLookup, ClassDecl, false);
14706
14707 // Prior to C++11, filter out any result that isn't a copy/move-assignment
14708 // operator.
14709 if (!S.getLangOpts().CPlusPlus11) {
14710 LookupResult::Filter F = OpLookup.makeFilter();
14711 while (F.hasNext()) {
14712 NamedDecl *D = F.next();
14713 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
14714 if (Method->isCopyAssignmentOperator() ||
14715 (!Copying && Method->isMoveAssignmentOperator()))
14716 continue;
14717
14718 F.erase();
14719 }
14720 F.done();
14721 }
14722
14723 // Suppress the protected check (C++ [class.protected]) for each of the
14724 // assignment operators we found. This strange dance is required when
14725 // we're assigning via a base classes's copy-assignment operator. To
14726 // ensure that we're getting the right base class subobject (without
14727 // ambiguities), we need to cast "this" to that subobject type; to
14728 // ensure that we don't go through the virtual call mechanism, we need
14729 // to qualify the operator= name with the base class (see below). However,
14730 // this means that if the base class has a protected copy assignment
14731 // operator, the protected member access check will fail. So, we
14732 // rewrite "protected" access to "public" access in this case, since we
14733 // know by construction that we're calling from a derived class.
14734 if (CopyingBaseSubobject) {
14735 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
14736 L != LEnd; ++L) {
14737 if (L.getAccess() == AS_protected)
14738 L.setAccess(AS_public);
14739 }
14740 }
14741
14742 // Create the nested-name-specifier that will be used to qualify the
14743 // reference to operator=; this is required to suppress the virtual
14744 // call mechanism.
14745 CXXScopeSpec SS;
14746 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
14747 SS.MakeTrivial(S.Context,
14748 NestedNameSpecifier::Create(S.Context, nullptr, false,
14749 CanonicalT),
14750 Loc);
14751
14752 // Create the reference to operator=.
14753 ExprResult OpEqualRef
14754 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false,
14755 SS, /*TemplateKWLoc=*/SourceLocation(),
14756 /*FirstQualifierInScope=*/nullptr,
14757 OpLookup,
14758 /*TemplateArgs=*/nullptr, /*S*/nullptr,
14759 /*SuppressQualifierCheck=*/true);
14760 if (OpEqualRef.isInvalid())
14761 return StmtError();
14762
14763 // Build the call to the assignment operator.
14764
14765 Expr *FromInst = From.build(S, Loc);
14766 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
14767 OpEqualRef.getAs<Expr>(),
14768 Loc, FromInst, Loc);
14769 if (Call.isInvalid())
14770 return StmtError();
14771
14772 // If we built a call to a trivial 'operator=' while copying an array,
14773 // bail out. We'll replace the whole shebang with a memcpy.
14774 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
14775 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
14776 return StmtResult((Stmt*)nullptr);
14777
14778 // Convert to an expression-statement, and clean up any produced
14779 // temporaries.
14780 return S.ActOnExprStmt(Call);
14781 }
14782
14783 // - if the subobject is of scalar type, the built-in assignment
14784 // operator is used.
14786 if (!ArrayTy) {
14787 ExprResult Assignment = S.CreateBuiltinBinOp(
14788 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
14789 if (Assignment.isInvalid())
14790 return StmtError();
14791 return S.ActOnExprStmt(Assignment);
14792 }
14793
14794 // - if the subobject is an array, each element is assigned, in the
14795 // manner appropriate to the element type;
14796
14797 // Construct a loop over the array bounds, e.g.,
14798 //
14799 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
14800 //
14801 // that will copy each of the array elements.
14802 QualType SizeType = S.Context.getSizeType();
14803
14804 // Create the iteration variable.
14805 IdentifierInfo *IterationVarName = nullptr;
14806 {
14807 SmallString<8> Str;
14808 llvm::raw_svector_ostream OS(Str);
14809 OS << "__i" << Depth;
14810 IterationVarName = &S.Context.Idents.get(OS.str());
14811 }
14812 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
14813 IterationVarName, SizeType,
14815 SC_None);
14816
14817 // Initialize the iteration variable to zero.
14818 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
14819 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
14820
14821 // Creates a reference to the iteration variable.
14822 RefBuilder IterationVarRef(IterationVar, SizeType);
14823 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
14824
14825 // Create the DeclStmt that holds the iteration variable.
14826 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
14827
14828 // Subscript the "from" and "to" expressions with the iteration variable.
14829 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
14830 MoveCastBuilder FromIndexMove(FromIndexCopy);
14831 const ExprBuilder *FromIndex;
14832 if (Copying)
14833 FromIndex = &FromIndexCopy;
14834 else
14835 FromIndex = &FromIndexMove;
14836
14837 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
14838
14839 // Build the copy/move for an individual element of the array.
14842 ToIndex, *FromIndex, CopyingBaseSubobject,
14843 Copying, Depth + 1);
14844 // Bail out if copying fails or if we determined that we should use memcpy.
14845 if (Copy.isInvalid() || !Copy.get())
14846 return Copy;
14847
14848 // Create the comparison against the array bound.
14849 llvm::APInt Upper
14850 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
14851 Expr *Comparison = BinaryOperator::Create(
14852 S.Context, IterationVarRefRVal.build(S, Loc),
14853 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE,
14856
14857 // Create the pre-increment of the iteration variable. We can determine
14858 // whether the increment will overflow based on the value of the array
14859 // bound.
14860 Expr *Increment = UnaryOperator::Create(
14861 S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue,
14862 OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides());
14863
14864 // Construct the loop that copies all elements of this array.
14865 return S.ActOnForStmt(
14866 Loc, Loc, InitStmt,
14867 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
14868 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
14869}
14870
14871static StmtResult
14873 const ExprBuilder &To, const ExprBuilder &From,
14874 bool CopyingBaseSubobject, bool Copying) {
14875 // Maybe we should use a memcpy?
14876 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
14877 T.isTriviallyCopyableType(S.Context))
14878 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
14879
14881 CopyingBaseSubobject,
14882 Copying, 0));
14883
14884 // If we ended up picking a trivial assignment operator for an array of a
14885 // non-trivially-copyable class type, just emit a memcpy.
14886 if (!Result.isInvalid() && !Result.get())
14887 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
14888
14889 return Result;
14890}
14891
14893 // Note: The following rules are largely analoguous to the copy
14894 // constructor rules. Note that virtual bases are not taken into account
14895 // for determining the argument type of the operator. Note also that
14896 // operators taking an object instead of a reference are allowed.
14897 assert(ClassDecl->needsImplicitCopyAssignment());
14898
14899 DeclaringSpecialMember DSM(*this, ClassDecl,
14901 if (DSM.isAlreadyBeingDeclared())
14902 return nullptr;
14903
14904 QualType ArgType = Context.getTypeDeclType(ClassDecl);
14906 ArgType, nullptr);
14908 if (AS != LangAS::Default)
14909 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14910 QualType RetType = Context.getLValueReferenceType(ArgType);
14911 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
14912 if (Const)
14913 ArgType = ArgType.withConst();
14914
14915 ArgType = Context.getLValueReferenceType(ArgType);
14916
14918 *this, ClassDecl, CXXSpecialMemberKind::CopyAssignment, Const);
14919
14920 // An implicitly-declared copy assignment operator is an inline public
14921 // member of its class.
14923 SourceLocation ClassLoc = ClassDecl->getLocation();
14924 DeclarationNameInfo NameInfo(Name, ClassLoc);
14926 Context, ClassDecl, ClassLoc, NameInfo, QualType(),
14927 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
14928 getCurFPFeatures().isFPConstrained(),
14929 /*isInline=*/true,
14931 SourceLocation());
14932 CopyAssignment->setAccess(AS_public);
14933 CopyAssignment->setDefaulted();
14934 CopyAssignment->setImplicit();
14935
14936 setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
14937
14938 if (getLangOpts().CUDA)
14941 /* ConstRHS */ Const,
14942 /* Diagnose */ false);
14943
14944 // Add the parameter to the operator.
14946 ClassLoc, ClassLoc,
14947 /*Id=*/nullptr, ArgType,
14948 /*TInfo=*/nullptr, SC_None,
14949 nullptr);
14950 CopyAssignment->setParams(FromParam);
14951
14952 CopyAssignment->setTrivial(
14956 : ClassDecl->hasTrivialCopyAssignment());
14957
14958 // Note that we have added this copy-assignment operator.
14960
14961 Scope *S = getScopeForContext(ClassDecl);
14963
14967 SetDeclDeleted(CopyAssignment, ClassLoc);
14968 }
14969
14970 if (S)
14972 ClassDecl->addDecl(CopyAssignment);
14973
14974 return CopyAssignment;
14975}
14976
14977/// Diagnose an implicit copy operation for a class which is odr-used, but
14978/// which is deprecated because the class has a user-declared copy constructor,
14979/// copy assignment operator, or destructor.
14981 assert(CopyOp->isImplicit());
14982
14983 CXXRecordDecl *RD = CopyOp->getParent();
14984 CXXMethodDecl *UserDeclaredOperation = nullptr;
14985
14986 if (RD->hasUserDeclaredDestructor()) {
14987 UserDeclaredOperation = RD->getDestructor();
14988 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
14990 // Find any user-declared copy constructor.
14991 for (auto *I : RD->ctors()) {
14992 if (I->isCopyConstructor()) {
14993 UserDeclaredOperation = I;
14994 break;
14995 }
14996 }
14997 assert(UserDeclaredOperation);
14998 } else if (isa<CXXConstructorDecl>(CopyOp) &&
15000 // Find any user-declared move assignment operator.
15001 for (auto *I : RD->methods()) {
15002 if (I->isCopyAssignmentOperator()) {
15003 UserDeclaredOperation = I;
15004 break;
15005 }
15006 }
15007 assert(UserDeclaredOperation);
15008 }
15009
15010 if (UserDeclaredOperation) {
15011 bool UDOIsUserProvided = UserDeclaredOperation->isUserProvided();
15012 bool UDOIsDestructor = isa<CXXDestructorDecl>(UserDeclaredOperation);
15013 bool IsCopyAssignment = !isa<CXXConstructorDecl>(CopyOp);
15014 unsigned DiagID =
15015 (UDOIsUserProvided && UDOIsDestructor)
15016 ? diag::warn_deprecated_copy_with_user_provided_dtor
15017 : (UDOIsUserProvided && !UDOIsDestructor)
15018 ? diag::warn_deprecated_copy_with_user_provided_copy
15019 : (!UDOIsUserProvided && UDOIsDestructor)
15020 ? diag::warn_deprecated_copy_with_dtor
15021 : diag::warn_deprecated_copy;
15022 S.Diag(UserDeclaredOperation->getLocation(), DiagID)
15023 << RD << IsCopyAssignment;
15024 }
15025}
15026
15028 CXXMethodDecl *CopyAssignOperator) {
15029 assert((CopyAssignOperator->isDefaulted() &&
15030 CopyAssignOperator->isOverloadedOperator() &&
15031 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
15032 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
15033 !CopyAssignOperator->isDeleted()) &&
15034 "DefineImplicitCopyAssignment called for wrong function");
15035 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
15036 return;
15037
15038 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
15039 if (ClassDecl->isInvalidDecl()) {
15040 CopyAssignOperator->setInvalidDecl();
15041 return;
15042 }
15043
15044 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
15045
15046 // The exception specification is needed because we are defining the
15047 // function.
15048 ResolveExceptionSpec(CurrentLocation,
15049 CopyAssignOperator->getType()->castAs<FunctionProtoType>());
15050
15051 // Add a context note for diagnostics produced after this point.
15052 Scope.addContextNote(CurrentLocation);
15053
15054 // C++11 [class.copy]p18:
15055 // The [definition of an implicitly declared copy assignment operator] is
15056 // deprecated if the class has a user-declared copy constructor or a
15057 // user-declared destructor.
15058 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
15059 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
15060
15061 // C++0x [class.copy]p30:
15062 // The implicitly-defined or explicitly-defaulted copy assignment operator
15063 // for a non-union class X performs memberwise copy assignment of its
15064 // subobjects. The direct base classes of X are assigned first, in the
15065 // order of their declaration in the base-specifier-list, and then the
15066 // immediate non-static data members of X are assigned, in the order in
15067 // which they were declared in the class definition.
15068
15069 // The statements that form the synthesized function body.
15070 SmallVector<Stmt*, 8> Statements;
15071
15072 // The parameter for the "other" object, which we are copying from.
15073 ParmVarDecl *Other = CopyAssignOperator->getNonObjectParameter(0);
15074 Qualifiers OtherQuals = Other->getType().getQualifiers();
15075 QualType OtherRefType = Other->getType();
15076 if (OtherRefType->isLValueReferenceType()) {
15077 OtherRefType = OtherRefType->getPointeeType();
15078 OtherQuals = OtherRefType.getQualifiers();
15079 }
15080
15081 // Our location for everything implicitly-generated.
15082 SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
15083 ? CopyAssignOperator->getEndLoc()
15084 : CopyAssignOperator->getLocation();
15085
15086 // Builds a DeclRefExpr for the "other" object.
15087 RefBuilder OtherRef(Other, OtherRefType);
15088
15089 // Builds the function object parameter.
15090 std::optional<ThisBuilder> This;
15091 std::optional<DerefBuilder> DerefThis;
15092 std::optional<RefBuilder> ExplicitObject;
15093 bool IsArrow = false;
15094 QualType ObjectType;
15095 if (CopyAssignOperator->isExplicitObjectMemberFunction()) {
15096 ObjectType = CopyAssignOperator->getParamDecl(0)->getType();
15097 if (ObjectType->isReferenceType())
15098 ObjectType = ObjectType->getPointeeType();
15099 ExplicitObject.emplace(CopyAssignOperator->getParamDecl(0), ObjectType);
15100 } else {
15101 ObjectType = getCurrentThisType();
15102 This.emplace();
15103 DerefThis.emplace(*This);
15104 IsArrow = !LangOpts.HLSL;
15105 }
15106 ExprBuilder &ObjectParameter =
15107 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15108 : static_cast<ExprBuilder &>(*This);
15109
15110 // Assign base classes.
15111 bool Invalid = false;
15112 for (auto &Base : ClassDecl->bases()) {
15113 // Form the assignment:
15114 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
15115 QualType BaseType = Base.getType().getUnqualifiedType();
15116 if (!BaseType->isRecordType()) {
15117 Invalid = true;
15118 continue;
15119 }
15120
15121 CXXCastPath BasePath;
15122 BasePath.push_back(&Base);
15123
15124 // Construct the "from" expression, which is an implicit cast to the
15125 // appropriately-qualified base type.
15126 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
15127 VK_LValue, BasePath);
15128
15129 // Dereference "this".
15130 CastBuilder To(
15131 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15132 : static_cast<ExprBuilder &>(*DerefThis),
15133 Context.getQualifiedType(BaseType, ObjectType.getQualifiers()),
15134 VK_LValue, BasePath);
15135
15136 // Build the copy.
15137 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
15138 To, From,
15139 /*CopyingBaseSubobject=*/true,
15140 /*Copying=*/true);
15141 if (Copy.isInvalid()) {
15142 CopyAssignOperator->setInvalidDecl();
15143 return;
15144 }
15145
15146 // Success! Record the copy.
15147 Statements.push_back(Copy.getAs<Expr>());
15148 }
15149
15150 // Assign non-static members.
15151 for (auto *Field : ClassDecl->fields()) {
15152 // FIXME: We should form some kind of AST representation for the implied
15153 // memcpy in a union copy operation.
15154 if (Field->isUnnamedBitField() || Field->getParent()->isUnion())
15155 continue;
15156
15157 if (Field->isInvalidDecl()) {
15158 Invalid = true;
15159 continue;
15160 }
15161
15162 // Check for members of reference type; we can't copy those.
15163 if (Field->getType()->isReferenceType()) {
15164 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15165 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
15166 Diag(Field->getLocation(), diag::note_declared_at);
15167 Invalid = true;
15168 continue;
15169 }
15170
15171 // Check for members of const-qualified, non-class type.
15172 QualType BaseType = Context.getBaseElementType(Field->getType());
15173 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
15174 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15175 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
15176 Diag(Field->getLocation(), diag::note_declared_at);
15177 Invalid = true;
15178 continue;
15179 }
15180
15181 // Suppress assigning zero-width bitfields.
15182 if (Field->isZeroLengthBitField(Context))
15183 continue;
15184
15185 QualType FieldType = Field->getType().getNonReferenceType();
15186 if (FieldType->isIncompleteArrayType()) {
15187 assert(ClassDecl->hasFlexibleArrayMember() &&
15188 "Incomplete array type is not valid");
15189 continue;
15190 }
15191
15192 // Build references to the field in the object we're copying from and to.
15193 CXXScopeSpec SS; // Intentionally empty
15194 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
15196 MemberLookup.addDecl(Field);
15197 MemberLookup.resolveKind();
15198
15199 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
15200 MemberBuilder To(ObjectParameter, ObjectType, IsArrow, MemberLookup);
15201 // Build the copy of this field.
15202 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
15203 To, From,
15204 /*CopyingBaseSubobject=*/false,
15205 /*Copying=*/true);
15206 if (Copy.isInvalid()) {
15207 CopyAssignOperator->setInvalidDecl();
15208 return;
15209 }
15210
15211 // Success! Record the copy.
15212 Statements.push_back(Copy.getAs<Stmt>());
15213 }
15214
15215 if (!Invalid) {
15216 // Add a "return *this;"
15217 Expr *ThisExpr =
15218 (ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15219 : LangOpts.HLSL ? static_cast<ExprBuilder &>(*This)
15220 : static_cast<ExprBuilder &>(*DerefThis))
15221 .build(*this, Loc);
15222 StmtResult Return = BuildReturnStmt(Loc, ThisExpr);
15223 if (Return.isInvalid())
15224 Invalid = true;
15225 else
15226 Statements.push_back(Return.getAs<Stmt>());
15227 }
15228
15229 if (Invalid) {
15230 CopyAssignOperator->setInvalidDecl();
15231 return;
15232 }
15233
15234 StmtResult Body;
15235 {
15236 CompoundScopeRAII CompoundScope(*this);
15237 Body = ActOnCompoundStmt(Loc, Loc, Statements,
15238 /*isStmtExpr=*/false);
15239 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
15240 }
15241 CopyAssignOperator->setBody(Body.getAs<Stmt>());
15242 CopyAssignOperator->markUsed(Context);
15243
15245 L->CompletedImplicitDefinition(CopyAssignOperator);
15246 }
15247}
15248
15250 assert(ClassDecl->needsImplicitMoveAssignment());
15251
15252 DeclaringSpecialMember DSM(*this, ClassDecl,
15254 if (DSM.isAlreadyBeingDeclared())
15255 return nullptr;
15256
15257 // Note: The following rules are largely analoguous to the move
15258 // constructor rules.
15259
15260 QualType ArgType = Context.getTypeDeclType(ClassDecl);
15262 ArgType, nullptr);
15264 if (AS != LangAS::Default)
15265 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
15266 QualType RetType = Context.getLValueReferenceType(ArgType);
15267 ArgType = Context.getRValueReferenceType(ArgType);
15268
15270 *this, ClassDecl, CXXSpecialMemberKind::MoveAssignment, false);
15271
15272 // An implicitly-declared move assignment operator is an inline public
15273 // member of its class.
15275 SourceLocation ClassLoc = ClassDecl->getLocation();
15276 DeclarationNameInfo NameInfo(Name, ClassLoc);
15278 Context, ClassDecl, ClassLoc, NameInfo, QualType(),
15279 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
15280 getCurFPFeatures().isFPConstrained(),
15281 /*isInline=*/true,
15283 SourceLocation());
15284 MoveAssignment->setAccess(AS_public);
15285 MoveAssignment->setDefaulted();
15286 MoveAssignment->setImplicit();
15287
15288 setupImplicitSpecialMemberType(MoveAssignment, RetType, ArgType);
15289
15290 if (getLangOpts().CUDA)
15293 /* ConstRHS */ false,
15294 /* Diagnose */ false);
15295
15296 // Add the parameter to the operator.
15298 ClassLoc, ClassLoc,
15299 /*Id=*/nullptr, ArgType,
15300 /*TInfo=*/nullptr, SC_None,
15301 nullptr);
15302 MoveAssignment->setParams(FromParam);
15303
15304 MoveAssignment->setTrivial(
15308 : ClassDecl->hasTrivialMoveAssignment());
15309
15310 // Note that we have added this copy-assignment operator.
15312
15313 Scope *S = getScopeForContext(ClassDecl);
15315
15319 SetDeclDeleted(MoveAssignment, ClassLoc);
15320 }
15321
15322 if (S)
15324 ClassDecl->addDecl(MoveAssignment);
15325
15326 return MoveAssignment;
15327}
15328
15329/// Check if we're implicitly defining a move assignment operator for a class
15330/// with virtual bases. Such a move assignment might move-assign the virtual
15331/// base multiple times.
15333 SourceLocation CurrentLocation) {
15334 assert(!Class->isDependentContext() && "should not define dependent move");
15335
15336 // Only a virtual base could get implicitly move-assigned multiple times.
15337 // Only a non-trivial move assignment can observe this. We only want to
15338 // diagnose if we implicitly define an assignment operator that assigns
15339 // two base classes, both of which move-assign the same virtual base.
15340 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
15341 Class->getNumBases() < 2)
15342 return;
15343
15345 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
15346 VBaseMap VBases;
15347
15348 for (auto &BI : Class->bases()) {
15349 Worklist.push_back(&BI);
15350 while (!Worklist.empty()) {
15351 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
15352 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
15353
15354 // If the base has no non-trivial move assignment operators,
15355 // we don't care about moves from it.
15356 if (!Base->hasNonTrivialMoveAssignment())
15357 continue;
15358
15359 // If there's nothing virtual here, skip it.
15360 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
15361 continue;
15362
15363 // If we're not actually going to call a move assignment for this base,
15364 // or the selected move assignment is trivial, skip it.
15367 /*ConstArg*/ false, /*VolatileArg*/ false,
15368 /*RValueThis*/ true, /*ConstThis*/ false,
15369 /*VolatileThis*/ false);
15370 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
15372 continue;
15373
15374 if (BaseSpec->isVirtual()) {
15375 // We're going to move-assign this virtual base, and its move
15376 // assignment operator is not trivial. If this can happen for
15377 // multiple distinct direct bases of Class, diagnose it. (If it
15378 // only happens in one base, we'll diagnose it when synthesizing
15379 // that base class's move assignment operator.)
15380 CXXBaseSpecifier *&Existing =
15381 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
15382 .first->second;
15383 if (Existing && Existing != &BI) {
15384 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
15385 << Class << Base;
15386 S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
15387 << (Base->getCanonicalDecl() ==
15389 << Base << Existing->getType() << Existing->getSourceRange();
15390 S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
15391 << (Base->getCanonicalDecl() ==
15392 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
15393 << Base << BI.getType() << BaseSpec->getSourceRange();
15394
15395 // Only diagnose each vbase once.
15396 Existing = nullptr;
15397 }
15398 } else {
15399 // Only walk over bases that have defaulted move assignment operators.
15400 // We assume that any user-provided move assignment operator handles
15401 // the multiple-moves-of-vbase case itself somehow.
15402 if (!SMOR.getMethod()->isDefaulted())
15403 continue;
15404
15405 // We're going to move the base classes of Base. Add them to the list.
15406 llvm::append_range(Worklist, llvm::make_pointer_range(Base->bases()));
15407 }
15408 }
15409 }
15410}
15411
15413 CXXMethodDecl *MoveAssignOperator) {
15414 assert((MoveAssignOperator->isDefaulted() &&
15415 MoveAssignOperator->isOverloadedOperator() &&
15416 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
15417 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
15418 !MoveAssignOperator->isDeleted()) &&
15419 "DefineImplicitMoveAssignment called for wrong function");
15420 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
15421 return;
15422
15423 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
15424 if (ClassDecl->isInvalidDecl()) {
15425 MoveAssignOperator->setInvalidDecl();
15426 return;
15427 }
15428
15429 // C++0x [class.copy]p28:
15430 // The implicitly-defined or move assignment operator for a non-union class
15431 // X performs memberwise move assignment of its subobjects. The direct base
15432 // classes of X are assigned first, in the order of their declaration in the
15433 // base-specifier-list, and then the immediate non-static data members of X
15434 // are assigned, in the order in which they were declared in the class
15435 // definition.
15436
15437 // Issue a warning if our implicit move assignment operator will move
15438 // from a virtual base more than once.
15439 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
15440
15441 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
15442
15443 // The exception specification is needed because we are defining the
15444 // function.
15445 ResolveExceptionSpec(CurrentLocation,
15446 MoveAssignOperator->getType()->castAs<FunctionProtoType>());
15447
15448 // Add a context note for diagnostics produced after this point.
15449 Scope.addContextNote(CurrentLocation);
15450
15451 // The statements that form the synthesized function body.
15452 SmallVector<Stmt*, 8> Statements;
15453
15454 // The parameter for the "other" object, which we are move from.
15455 ParmVarDecl *Other = MoveAssignOperator->getNonObjectParameter(0);
15456 QualType OtherRefType =
15457 Other->getType()->castAs<RValueReferenceType>()->getPointeeType();
15458
15459 // Our location for everything implicitly-generated.
15460 SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
15461 ? MoveAssignOperator->getEndLoc()
15462 : MoveAssignOperator->getLocation();
15463
15464 // Builds a reference to the "other" object.
15465 RefBuilder OtherRef(Other, OtherRefType);
15466 // Cast to rvalue.
15467 MoveCastBuilder MoveOther(OtherRef);
15468
15469 // Builds the function object parameter.
15470 std::optional<ThisBuilder> This;
15471 std::optional<DerefBuilder> DerefThis;
15472 std::optional<RefBuilder> ExplicitObject;
15473 QualType ObjectType;
15474 if (MoveAssignOperator->isExplicitObjectMemberFunction()) {
15475 ObjectType = MoveAssignOperator->getParamDecl(0)->getType();
15476 if (ObjectType->isReferenceType())
15477 ObjectType = ObjectType->getPointeeType();
15478 ExplicitObject.emplace(MoveAssignOperator->getParamDecl(0), ObjectType);
15479 } else {
15480 ObjectType = getCurrentThisType();
15481 This.emplace();
15482 DerefThis.emplace(*This);
15483 }
15484 ExprBuilder &ObjectParameter =
15485 ExplicitObject ? *ExplicitObject : static_cast<ExprBuilder &>(*This);
15486
15487 // Assign base classes.
15488 bool Invalid = false;
15489 for (auto &Base : ClassDecl->bases()) {
15490 // C++11 [class.copy]p28:
15491 // It is unspecified whether subobjects representing virtual base classes
15492 // are assigned more than once by the implicitly-defined copy assignment
15493 // operator.
15494 // FIXME: Do not assign to a vbase that will be assigned by some other base
15495 // class. For a move-assignment, this can result in the vbase being moved
15496 // multiple times.
15497
15498 // Form the assignment:
15499 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
15500 QualType BaseType = Base.getType().getUnqualifiedType();
15501 if (!BaseType->isRecordType()) {
15502 Invalid = true;
15503 continue;
15504 }
15505
15506 CXXCastPath BasePath;
15507 BasePath.push_back(&Base);
15508
15509 // Construct the "from" expression, which is an implicit cast to the
15510 // appropriately-qualified base type.
15511 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
15512
15513 // Implicitly cast "this" to the appropriately-qualified base type.
15514 // Dereference "this".
15515 CastBuilder To(
15516 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15517 : static_cast<ExprBuilder &>(*DerefThis),
15518 Context.getQualifiedType(BaseType, ObjectType.getQualifiers()),
15519 VK_LValue, BasePath);
15520
15521 // Build the move.
15522 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
15523 To, From,
15524 /*CopyingBaseSubobject=*/true,
15525 /*Copying=*/false);
15526 if (Move.isInvalid()) {
15527 MoveAssignOperator->setInvalidDecl();
15528 return;
15529 }
15530
15531 // Success! Record the move.
15532 Statements.push_back(Move.getAs<Expr>());
15533 }
15534
15535 // Assign non-static members.
15536 for (auto *Field : ClassDecl->fields()) {
15537 // FIXME: We should form some kind of AST representation for the implied
15538 // memcpy in a union copy operation.
15539 if (Field->isUnnamedBitField() || Field->getParent()->isUnion())
15540 continue;
15541
15542 if (Field->isInvalidDecl()) {
15543 Invalid = true;
15544 continue;
15545 }
15546
15547 // Check for members of reference type; we can't move those.
15548 if (Field->getType()->isReferenceType()) {
15549 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15550 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
15551 Diag(Field->getLocation(), diag::note_declared_at);
15552 Invalid = true;
15553 continue;
15554 }
15555
15556 // Check for members of const-qualified, non-class type.
15557 QualType BaseType = Context.getBaseElementType(Field->getType());
15558 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
15559 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15560 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
15561 Diag(Field->getLocation(), diag::note_declared_at);
15562 Invalid = true;
15563 continue;
15564 }
15565
15566 // Suppress assigning zero-width bitfields.
15567 if (Field->isZeroLengthBitField(Context))
15568 continue;
15569
15570 QualType FieldType = Field->getType().getNonReferenceType();
15571 if (FieldType->isIncompleteArrayType()) {
15572 assert(ClassDecl->hasFlexibleArrayMember() &&
15573 "Incomplete array type is not valid");
15574 continue;
15575 }
15576
15577 // Build references to the field in the object we're copying from and to.
15578 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
15580 MemberLookup.addDecl(Field);
15581 MemberLookup.resolveKind();
15582 MemberBuilder From(MoveOther, OtherRefType,
15583 /*IsArrow=*/false, MemberLookup);
15584 MemberBuilder To(ObjectParameter, ObjectType, /*IsArrow=*/!ExplicitObject,
15585 MemberLookup);
15586
15587 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
15588 "Member reference with rvalue base must be rvalue except for reference "
15589 "members, which aren't allowed for move assignment.");
15590
15591 // Build the move of this field.
15592 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
15593 To, From,
15594 /*CopyingBaseSubobject=*/false,
15595 /*Copying=*/false);
15596 if (Move.isInvalid()) {
15597 MoveAssignOperator->setInvalidDecl();
15598 return;
15599 }
15600
15601 // Success! Record the copy.
15602 Statements.push_back(Move.getAs<Stmt>());
15603 }
15604
15605 if (!Invalid) {
15606 // Add a "return *this;"
15607 Expr *ThisExpr =
15608 (ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15609 : static_cast<ExprBuilder &>(*DerefThis))
15610 .build(*this, Loc);
15611
15612 StmtResult Return = BuildReturnStmt(Loc, ThisExpr);
15613 if (Return.isInvalid())
15614 Invalid = true;
15615 else
15616 Statements.push_back(Return.getAs<Stmt>());
15617 }
15618
15619 if (Invalid) {
15620 MoveAssignOperator->setInvalidDecl();
15621 return;
15622 }
15623
15624 StmtResult Body;
15625 {
15626 CompoundScopeRAII CompoundScope(*this);
15627 Body = ActOnCompoundStmt(Loc, Loc, Statements,
15628 /*isStmtExpr=*/false);
15629 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
15630 }
15631 MoveAssignOperator->setBody(Body.getAs<Stmt>());
15632 MoveAssignOperator->markUsed(Context);
15633
15635 L->CompletedImplicitDefinition(MoveAssignOperator);
15636 }
15637}
15638
15640 CXXRecordDecl *ClassDecl) {
15641 // C++ [class.copy]p4:
15642 // If the class definition does not explicitly declare a copy
15643 // constructor, one is declared implicitly.
15644 assert(ClassDecl->needsImplicitCopyConstructor());
15645
15646 DeclaringSpecialMember DSM(*this, ClassDecl,
15648 if (DSM.isAlreadyBeingDeclared())
15649 return nullptr;
15650
15651 QualType ClassType = Context.getTypeDeclType(ClassDecl);
15652 QualType ArgType = ClassType;
15654 ArgType, nullptr);
15655 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
15656 if (Const)
15657 ArgType = ArgType.withConst();
15658
15660 if (AS != LangAS::Default)
15661 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
15662
15663 ArgType = Context.getLValueReferenceType(ArgType);
15664
15666 *this, ClassDecl, CXXSpecialMemberKind::CopyConstructor, Const);
15667
15668 DeclarationName Name
15670 Context.getCanonicalType(ClassType));
15671 SourceLocation ClassLoc = ClassDecl->getLocation();
15672 DeclarationNameInfo NameInfo(Name, ClassLoc);
15673
15674 // An implicitly-declared copy constructor is an inline public
15675 // member of its class.
15677 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
15678 ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
15679 /*isInline=*/true,
15680 /*isImplicitlyDeclared=*/true,
15683 CopyConstructor->setAccess(AS_public);
15684 CopyConstructor->setDefaulted();
15685
15686 setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
15687
15688 if (getLangOpts().CUDA)
15691 /* ConstRHS */ Const,
15692 /* Diagnose */ false);
15693
15694 // During template instantiation of special member functions we need a
15695 // reliable TypeSourceInfo for the parameter types in order to allow functions
15696 // to be substituted.
15697 TypeSourceInfo *TSI = nullptr;
15698 if (inTemplateInstantiation() && ClassDecl->isLambda())
15699 TSI = Context.getTrivialTypeSourceInfo(ArgType);
15700
15701 // Add the parameter to the constructor.
15702 ParmVarDecl *FromParam =
15703 ParmVarDecl::Create(Context, CopyConstructor, ClassLoc, ClassLoc,
15704 /*IdentifierInfo=*/nullptr, ArgType,
15705 /*TInfo=*/TSI, SC_None, nullptr);
15706 CopyConstructor->setParams(FromParam);
15707
15708 CopyConstructor->setTrivial(
15712 : ClassDecl->hasTrivialCopyConstructor());
15713
15714 CopyConstructor->setTrivialForCall(
15715 ClassDecl->hasAttr<TrivialABIAttr>() ||
15720 : ClassDecl->hasTrivialCopyConstructorForCall()));
15721
15722 // Note that we have declared this constructor.
15724
15725 Scope *S = getScopeForContext(ClassDecl);
15727
15732 }
15733
15734 if (S)
15736 ClassDecl->addDecl(CopyConstructor);
15737
15738 return CopyConstructor;
15739}
15740
15743 assert((CopyConstructor->isDefaulted() &&
15744 CopyConstructor->isCopyConstructor() &&
15745 !CopyConstructor->doesThisDeclarationHaveABody() &&
15746 !CopyConstructor->isDeleted()) &&
15747 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
15748 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
15749 return;
15750
15751 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
15752 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
15753
15755
15756 // The exception specification is needed because we are defining the
15757 // function.
15758 ResolveExceptionSpec(CurrentLocation,
15759 CopyConstructor->getType()->castAs<FunctionProtoType>());
15760 MarkVTableUsed(CurrentLocation, ClassDecl);
15761
15762 // Add a context note for diagnostics produced after this point.
15763 Scope.addContextNote(CurrentLocation);
15764
15765 // C++11 [class.copy]p7:
15766 // The [definition of an implicitly declared copy constructor] is
15767 // deprecated if the class has a user-declared copy assignment operator
15768 // or a user-declared destructor.
15769 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
15771
15772 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
15773 CopyConstructor->setInvalidDecl();
15774 } else {
15775 SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
15776 ? CopyConstructor->getEndLoc()
15777 : CopyConstructor->getLocation();
15778 Sema::CompoundScopeRAII CompoundScope(*this);
15779 CopyConstructor->setBody(
15780 ActOnCompoundStmt(Loc, Loc, std::nullopt, /*isStmtExpr=*/false)
15781 .getAs<Stmt>());
15782 CopyConstructor->markUsed(Context);
15783 }
15784
15786 L->CompletedImplicitDefinition(CopyConstructor);
15787 }
15788}
15789
15791 CXXRecordDecl *ClassDecl) {
15792 assert(ClassDecl->needsImplicitMoveConstructor());
15793
15794 DeclaringSpecialMember DSM(*this, ClassDecl,
15796 if (DSM.isAlreadyBeingDeclared())
15797 return nullptr;
15798
15799 QualType ClassType = Context.getTypeDeclType(ClassDecl);
15800
15801 QualType ArgType = ClassType;
15803 ArgType, nullptr);
15805 if (AS != LangAS::Default)
15806 ArgType = Context.getAddrSpaceQualType(ClassType, AS);
15807 ArgType = Context.getRValueReferenceType(ArgType);
15808
15810 *this, ClassDecl, CXXSpecialMemberKind::MoveConstructor, false);
15811
15812 DeclarationName Name
15814 Context.getCanonicalType(ClassType));
15815 SourceLocation ClassLoc = ClassDecl->getLocation();
15816 DeclarationNameInfo NameInfo(Name, ClassLoc);
15817
15818 // C++11 [class.copy]p11:
15819 // An implicitly-declared copy/move constructor is an inline public
15820 // member of its class.
15822 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
15823 ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
15824 /*isInline=*/true,
15825 /*isImplicitlyDeclared=*/true,
15828 MoveConstructor->setAccess(AS_public);
15829 MoveConstructor->setDefaulted();
15830
15831 setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
15832
15833 if (getLangOpts().CUDA)
15836 /* ConstRHS */ false,
15837 /* Diagnose */ false);
15838
15839 // Add the parameter to the constructor.
15841 ClassLoc, ClassLoc,
15842 /*IdentifierInfo=*/nullptr,
15843 ArgType, /*TInfo=*/nullptr,
15844 SC_None, nullptr);
15845 MoveConstructor->setParams(FromParam);
15846
15847 MoveConstructor->setTrivial(
15851 : ClassDecl->hasTrivialMoveConstructor());
15852
15853 MoveConstructor->setTrivialForCall(
15854 ClassDecl->hasAttr<TrivialABIAttr>() ||
15859 : ClassDecl->hasTrivialMoveConstructorForCall()));
15860
15861 // Note that we have declared this constructor.
15863
15864 Scope *S = getScopeForContext(ClassDecl);
15866
15871 }
15872
15873 if (S)
15875 ClassDecl->addDecl(MoveConstructor);
15876
15877 return MoveConstructor;
15878}
15879
15882 assert((MoveConstructor->isDefaulted() &&
15883 MoveConstructor->isMoveConstructor() &&
15884 !MoveConstructor->doesThisDeclarationHaveABody() &&
15885 !MoveConstructor->isDeleted()) &&
15886 "DefineImplicitMoveConstructor - call it for implicit move ctor");
15887 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
15888 return;
15889
15890 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
15891 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
15892
15894
15895 // The exception specification is needed because we are defining the
15896 // function.
15897 ResolveExceptionSpec(CurrentLocation,
15898 MoveConstructor->getType()->castAs<FunctionProtoType>());
15899 MarkVTableUsed(CurrentLocation, ClassDecl);
15900
15901 // Add a context note for diagnostics produced after this point.
15902 Scope.addContextNote(CurrentLocation);
15903
15904 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
15905 MoveConstructor->setInvalidDecl();
15906 } else {
15907 SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
15908 ? MoveConstructor->getEndLoc()
15909 : MoveConstructor->getLocation();
15910 Sema::CompoundScopeRAII CompoundScope(*this);
15911 MoveConstructor->setBody(
15912 ActOnCompoundStmt(Loc, Loc, std::nullopt, /*isStmtExpr=*/false)
15913 .getAs<Stmt>());
15914 MoveConstructor->markUsed(Context);
15915 }
15916
15918 L->CompletedImplicitDefinition(MoveConstructor);
15919 }
15920}
15921
15923 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
15924}
15925
15927 SourceLocation CurrentLocation,
15928 CXXConversionDecl *Conv) {
15929 SynthesizedFunctionScope Scope(*this, Conv);
15930 assert(!Conv->getReturnType()->isUndeducedType());
15931
15932 QualType ConvRT = Conv->getType()->castAs<FunctionType>()->getReturnType();
15933 CallingConv CC =
15934 ConvRT->getPointeeType()->castAs<FunctionType>()->getCallConv();
15935
15936 CXXRecordDecl *Lambda = Conv->getParent();
15937 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
15938 FunctionDecl *Invoker =
15939 CallOp->hasCXXExplicitFunctionObjectParameter() || CallOp->isStatic()
15940 ? CallOp
15941 : Lambda->getLambdaStaticInvoker(CC);
15942
15943 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
15945 CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
15946 if (!CallOp)
15947 return;
15948
15949 if (CallOp != Invoker) {
15951 Invoker->getDescribedFunctionTemplate(), TemplateArgs,
15952 CurrentLocation);
15953 if (!Invoker)
15954 return;
15955 }
15956 }
15957
15958 if (CallOp->isInvalidDecl())
15959 return;
15960
15961 // Mark the call operator referenced (and add to pending instantiations
15962 // if necessary).
15963 // For both the conversion and static-invoker template specializations
15964 // we construct their body's in this function, so no need to add them
15965 // to the PendingInstantiations.
15966 MarkFunctionReferenced(CurrentLocation, CallOp);
15967
15968 if (Invoker != CallOp) {
15969 // Fill in the __invoke function with a dummy implementation. IR generation
15970 // will fill in the actual details. Update its type in case it contained
15971 // an 'auto'.
15972 Invoker->markUsed(Context);
15973 Invoker->setReferenced();
15974 Invoker->setType(Conv->getReturnType()->getPointeeType());
15975 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
15976 }
15977
15978 // Construct the body of the conversion function { return __invoke; }.
15979 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), VK_LValue,
15980 Conv->getLocation());
15981 assert(FunctionRef && "Can't refer to __invoke function?");
15982 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
15984 Conv->getLocation(), Conv->getLocation()));
15985 Conv->markUsed(Context);
15986 Conv->setReferenced();
15987
15989 L->CompletedImplicitDefinition(Conv);
15990 if (Invoker != CallOp)
15991 L->CompletedImplicitDefinition(Invoker);
15992 }
15993}
15994
15996 SourceLocation CurrentLocation, CXXConversionDecl *Conv) {
15997 assert(!Conv->getParent()->isGenericLambda());
15998
15999 SynthesizedFunctionScope Scope(*this, Conv);
16000
16001 // Copy-initialize the lambda object as needed to capture it.
16002 Expr *This = ActOnCXXThis(CurrentLocation).get();
16003 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
16004
16005 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
16006 Conv->getLocation(),
16007 Conv, DerefThis);
16008
16009 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
16010 // behavior. Note that only the general conversion function does this
16011 // (since it's unusable otherwise); in the case where we inline the
16012 // block literal, it has block literal lifetime semantics.
16013 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
16014 BuildBlock = ImplicitCastExpr::Create(
16015 Context, BuildBlock.get()->getType(), CK_CopyAndAutoreleaseBlockObject,
16016 BuildBlock.get(), nullptr, VK_PRValue, FPOptionsOverride());
16017
16018 if (BuildBlock.isInvalid()) {
16019 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
16020 Conv->setInvalidDecl();
16021 return;
16022 }
16023
16024 // Create the return statement that returns the block from the conversion
16025 // function.
16026 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
16027 if (Return.isInvalid()) {
16028 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
16029 Conv->setInvalidDecl();
16030 return;
16031 }
16032
16033 // Set the body of the conversion function.
16034 Stmt *ReturnS = Return.get();
16036 Conv->getLocation(), Conv->getLocation()));
16037 Conv->markUsed(Context);
16038
16039 // We're done; notify the mutation listener, if any.
16041 L->CompletedImplicitDefinition(Conv);
16042 }
16043}
16044
16045/// Determine whether the given list arguments contains exactly one
16046/// "real" (non-default) argument.
16048 switch (Args.size()) {
16049 case 0:
16050 return false;
16051
16052 default:
16053 if (!Args[1]->isDefaultArgument())
16054 return false;
16055
16056 [[fallthrough]];
16057 case 1:
16058 return !Args[0]->isDefaultArgument();
16059 }
16060
16061 return false;
16062}
16063
16065 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
16066 CXXConstructorDecl *Constructor, MultiExprArg ExprArgs,
16067 bool HadMultipleCandidates, bool IsListInitialization,
16068 bool IsStdInitListInitialization, bool RequiresZeroInit,
16069 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16070 bool Elidable = false;
16071
16072 // C++0x [class.copy]p34:
16073 // When certain criteria are met, an implementation is allowed to
16074 // omit the copy/move construction of a class object, even if the
16075 // copy/move constructor and/or destructor for the object have
16076 // side effects. [...]
16077 // - when a temporary class object that has not been bound to a
16078 // reference (12.2) would be copied/moved to a class object
16079 // with the same cv-unqualified type, the copy/move operation
16080 // can be omitted by constructing the temporary object
16081 // directly into the target of the omitted copy/move
16082 if (ConstructKind == CXXConstructionKind::Complete && Constructor &&
16083 // FIXME: Converting constructors should also be accepted.
16084 // But to fix this, the logic that digs down into a CXXConstructExpr
16085 // to find the source object needs to handle it.
16086 // Right now it assumes the source object is passed directly as the
16087 // first argument.
16088 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
16089 Expr *SubExpr = ExprArgs[0];
16090 // FIXME: Per above, this is also incorrect if we want to accept
16091 // converting constructors, as isTemporaryObject will
16092 // reject temporaries with different type from the
16093 // CXXRecord itself.
16094 Elidable = SubExpr->isTemporaryObject(
16095 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
16096 }
16097
16098 return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
16099 FoundDecl, Constructor,
16100 Elidable, ExprArgs, HadMultipleCandidates,
16101 IsListInitialization,
16102 IsStdInitListInitialization, RequiresZeroInit,
16103 ConstructKind, ParenRange);
16104}
16105
16107 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
16108 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg ExprArgs,
16109 bool HadMultipleCandidates, bool IsListInitialization,
16110 bool IsStdInitListInitialization, bool RequiresZeroInit,
16111 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16112 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
16113 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
16114 // The only way to get here is if we did overlaod resolution to find the
16115 // shadow decl, so we don't need to worry about re-checking the trailing
16116 // requires clause.
16117 if (DiagnoseUseOfOverloadedDecl(Constructor, ConstructLoc))
16118 return ExprError();
16119 }
16120
16121 return BuildCXXConstructExpr(
16122 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
16123 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
16124 RequiresZeroInit, ConstructKind, ParenRange);
16125}
16126
16127/// BuildCXXConstructExpr - Creates a complete call to a constructor,
16128/// including handling of its default argument expressions.
16130 SourceLocation ConstructLoc, QualType DeclInitType,
16131 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg ExprArgs,
16132 bool HadMultipleCandidates, bool IsListInitialization,
16133 bool IsStdInitListInitialization, bool RequiresZeroInit,
16134 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16135 assert(declaresSameEntity(
16136 Constructor->getParent(),
16137 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
16138 "given constructor for wrong type");
16139 MarkFunctionReferenced(ConstructLoc, Constructor);
16140 if (getLangOpts().CUDA && !CUDA().CheckCall(ConstructLoc, Constructor))
16141 return ExprError();
16142
16145 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
16146 HadMultipleCandidates, IsListInitialization,
16147 IsStdInitListInitialization, RequiresZeroInit,
16148 static_cast<CXXConstructionKind>(ConstructKind), ParenRange),
16149 Constructor);
16150}
16151
16153 if (VD->isInvalidDecl()) return;
16154 // If initializing the variable failed, don't also diagnose problems with
16155 // the destructor, they're likely related.
16156 if (VD->getInit() && VD->getInit()->containsErrors())
16157 return;
16158
16159 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
16160 if (ClassDecl->isInvalidDecl()) return;
16161 if (ClassDecl->hasIrrelevantDestructor()) return;
16162 if (ClassDecl->isDependentContext()) return;
16163
16164 if (VD->isNoDestroy(getASTContext()))
16165 return;
16166
16168 // The result of `LookupDestructor` might be nullptr if the destructor is
16169 // invalid, in which case it is marked as `IneligibleOrNotSelected` and
16170 // will not be selected by `CXXRecordDecl::getDestructor()`.
16171 if (!Destructor)
16172 return;
16173 // If this is an array, we'll require the destructor during initialization, so
16174 // we can skip over this. We still want to emit exit-time destructor warnings
16175 // though.
16176 if (!VD->getType()->isArrayType()) {
16179 PDiag(diag::err_access_dtor_var)
16180 << VD->getDeclName() << VD->getType());
16182 }
16183
16184 if (Destructor->isTrivial()) return;
16185
16186 // If the destructor is constexpr, check whether the variable has constant
16187 // destruction now.
16188 if (Destructor->isConstexpr()) {
16189 bool HasConstantInit = false;
16190 if (VD->getInit() && !VD->getInit()->isValueDependent())
16191 HasConstantInit = VD->evaluateValue();
16193 if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() &&
16194 HasConstantInit) {
16195 Diag(VD->getLocation(),
16196 diag::err_constexpr_var_requires_const_destruction) << VD;
16197 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
16198 Diag(Notes[I].first, Notes[I].second);
16199 }
16200 }
16201
16202 if (!VD->hasGlobalStorage() || !VD->needsDestruction(Context))
16203 return;
16204
16205 // Emit warning for non-trivial dtor in global scope (a real global,
16206 // class-static, function-static).
16207 if (!VD->hasAttr<AlwaysDestroyAttr>())
16208 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
16209
16210 // TODO: this should be re-enabled for static locals by !CXAAtExit
16211 if (!VD->isStaticLocal())
16212 Diag(VD->getLocation(), diag::warn_global_destructor);
16213}
16214
16215/// Given a constructor and the set of arguments provided for the
16216/// constructor, convert the arguments and add any required default arguments
16217/// to form a proper call to this constructor.
16218///
16219/// \returns true if an error occurred, false otherwise.
16221 QualType DeclInitType, MultiExprArg ArgsPtr,
16223 SmallVectorImpl<Expr *> &ConvertedArgs,
16224 bool AllowExplicit,
16225 bool IsListInitialization) {
16226 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
16227 unsigned NumArgs = ArgsPtr.size();
16228 Expr **Args = ArgsPtr.data();
16229
16230 const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>();
16231 unsigned NumParams = Proto->getNumParams();
16232
16233 // If too few arguments are available, we'll fill in the rest with defaults.
16234 if (NumArgs < NumParams)
16235 ConvertedArgs.reserve(NumParams);
16236 else
16237 ConvertedArgs.reserve(NumArgs);
16238
16239 VariadicCallType CallType =
16240 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
16241 SmallVector<Expr *, 8> AllArgs;
16243 Loc, Constructor, Proto, 0, llvm::ArrayRef(Args, NumArgs), AllArgs,
16244 CallType, AllowExplicit, IsListInitialization);
16245 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
16246
16247 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
16248
16249 CheckConstructorCall(Constructor, DeclInitType,
16250 llvm::ArrayRef(AllArgs.data(), AllArgs.size()), Proto,
16251 Loc);
16252
16253 return Invalid;
16254}
16255
16256static inline bool
16258 const FunctionDecl *FnDecl) {
16259 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
16260 if (isa<NamespaceDecl>(DC)) {
16261 return SemaRef.Diag(FnDecl->getLocation(),
16262 diag::err_operator_new_delete_declared_in_namespace)
16263 << FnDecl->getDeclName();
16264 }
16265
16266 if (isa<TranslationUnitDecl>(DC) &&
16267 FnDecl->getStorageClass() == SC_Static) {
16268 return SemaRef.Diag(FnDecl->getLocation(),
16269 diag::err_operator_new_delete_declared_static)
16270 << FnDecl->getDeclName();
16271 }
16272
16273 return false;
16274}
16275
16277 const PointerType *PtrTy) {
16278 auto &Ctx = SemaRef.Context;
16279 Qualifiers PtrQuals = PtrTy->getPointeeType().getQualifiers();
16280 PtrQuals.removeAddressSpace();
16281 return Ctx.getPointerType(Ctx.getCanonicalType(Ctx.getQualifiedType(
16282 PtrTy->getPointeeType().getUnqualifiedType(), PtrQuals)));
16283}
16284
16285static inline bool
16287 CanQualType ExpectedResultType,
16288 CanQualType ExpectedFirstParamType,
16289 unsigned DependentParamTypeDiag,
16290 unsigned InvalidParamTypeDiag) {
16291 QualType ResultType =
16292 FnDecl->getType()->castAs<FunctionType>()->getReturnType();
16293
16294 if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
16295 // The operator is valid on any address space for OpenCL.
16296 // Drop address space from actual and expected result types.
16297 if (const auto *PtrTy = ResultType->getAs<PointerType>())
16298 ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
16299
16300 if (auto ExpectedPtrTy = ExpectedResultType->getAs<PointerType>())
16301 ExpectedResultType = RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);
16302 }
16303
16304 // Check that the result type is what we expect.
16305 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) {
16306 // Reject even if the type is dependent; an operator delete function is
16307 // required to have a non-dependent result type.
16308 return SemaRef.Diag(
16309 FnDecl->getLocation(),
16310 ResultType->isDependentType()
16311 ? diag::err_operator_new_delete_dependent_result_type
16312 : diag::err_operator_new_delete_invalid_result_type)
16313 << FnDecl->getDeclName() << ExpectedResultType;
16314 }
16315
16316 // A function template must have at least 2 parameters.
16317 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
16318 return SemaRef.Diag(FnDecl->getLocation(),
16319 diag::err_operator_new_delete_template_too_few_parameters)
16320 << FnDecl->getDeclName();
16321
16322 // The function decl must have at least 1 parameter.
16323 if (FnDecl->getNumParams() == 0)
16324 return SemaRef.Diag(FnDecl->getLocation(),
16325 diag::err_operator_new_delete_too_few_parameters)
16326 << FnDecl->getDeclName();
16327
16328 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
16329 if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
16330 // The operator is valid on any address space for OpenCL.
16331 // Drop address space from actual and expected first parameter types.
16332 if (const auto *PtrTy =
16333 FnDecl->getParamDecl(0)->getType()->getAs<PointerType>())
16334 FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
16335
16336 if (auto ExpectedPtrTy = ExpectedFirstParamType->getAs<PointerType>())
16337 ExpectedFirstParamType =
16338 RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);
16339 }
16340
16341 // Check that the first parameter type is what we expect.
16342 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
16343 ExpectedFirstParamType) {
16344 // The first parameter type is not allowed to be dependent. As a tentative
16345 // DR resolution, we allow a dependent parameter type if it is the right
16346 // type anyway, to allow destroying operator delete in class templates.
16347 return SemaRef.Diag(FnDecl->getLocation(), FirstParamType->isDependentType()
16348 ? DependentParamTypeDiag
16349 : InvalidParamTypeDiag)
16350 << FnDecl->getDeclName() << ExpectedFirstParamType;
16351 }
16352
16353 return false;
16354}
16355
16356static bool
16358 // C++ [basic.stc.dynamic.allocation]p1:
16359 // A program is ill-formed if an allocation function is declared in a
16360 // namespace scope other than global scope or declared static in global
16361 // scope.
16363 return true;
16364
16365 CanQualType SizeTy =
16367
16368 // C++ [basic.stc.dynamic.allocation]p1:
16369 // The return type shall be void*. The first parameter shall have type
16370 // std::size_t.
16372 SizeTy,
16373 diag::err_operator_new_dependent_param_type,
16374 diag::err_operator_new_param_type))
16375 return true;
16376
16377 // C++ [basic.stc.dynamic.allocation]p1:
16378 // The first parameter shall not have an associated default argument.
16379 if (FnDecl->getParamDecl(0)->hasDefaultArg())
16380 return SemaRef.Diag(FnDecl->getLocation(),
16381 diag::err_operator_new_default_arg)
16382 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
16383
16384 return false;
16385}
16386
16387static bool
16389 // C++ [basic.stc.dynamic.deallocation]p1:
16390 // A program is ill-formed if deallocation functions are declared in a
16391 // namespace scope other than global scope or declared static in global
16392 // scope.
16394 return true;
16395
16396 auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
16397
16398 // C++ P0722:
16399 // Within a class C, the first parameter of a destroying operator delete
16400 // shall be of type C *. The first parameter of any other deallocation
16401 // function shall be of type void *.
16402 CanQualType ExpectedFirstParamType =
16403 MD && MD->isDestroyingOperatorDelete()
16407
16408 // C++ [basic.stc.dynamic.deallocation]p2:
16409 // Each deallocation function shall return void
16411 SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
16412 diag::err_operator_delete_dependent_param_type,
16413 diag::err_operator_delete_param_type))
16414 return true;
16415
16416 // C++ P0722:
16417 // A destroying operator delete shall be a usual deallocation function.
16418 if (MD && !MD->getParent()->isDependentContext() &&
16421 SemaRef.Diag(MD->getLocation(),
16422 diag::err_destroying_operator_delete_not_usual);
16423 return true;
16424 }
16425
16426 return false;
16427}
16428
16429/// CheckOverloadedOperatorDeclaration - Check whether the declaration
16430/// of this overloaded operator is well-formed. If so, returns false;
16431/// otherwise, emits appropriate diagnostics and returns true.
16433 assert(FnDecl && FnDecl->isOverloadedOperator() &&
16434 "Expected an overloaded operator declaration");
16435
16437
16438 // C++ [over.oper]p5:
16439 // The allocation and deallocation functions, operator new,
16440 // operator new[], operator delete and operator delete[], are
16441 // described completely in 3.7.3. The attributes and restrictions
16442 // found in the rest of this subclause do not apply to them unless
16443 // explicitly stated in 3.7.3.
16444 if (Op == OO_Delete || Op == OO_Array_Delete)
16445 return CheckOperatorDeleteDeclaration(*this, FnDecl);
16446
16447 if (Op == OO_New || Op == OO_Array_New)
16448 return CheckOperatorNewDeclaration(*this, FnDecl);
16449
16450 // C++ [over.oper]p7:
16451 // An operator function shall either be a member function or
16452 // be a non-member function and have at least one parameter
16453 // whose type is a class, a reference to a class, an enumeration,
16454 // or a reference to an enumeration.
16455 // Note: Before C++23, a member function could not be static. The only member
16456 // function allowed to be static is the call operator function.
16457 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
16458 if (MethodDecl->isStatic()) {
16459 if (Op == OO_Call || Op == OO_Subscript)
16460 Diag(FnDecl->getLocation(),
16461 (LangOpts.CPlusPlus23
16462 ? diag::warn_cxx20_compat_operator_overload_static
16463 : diag::ext_operator_overload_static))
16464 << FnDecl;
16465 else
16466 return Diag(FnDecl->getLocation(), diag::err_operator_overload_static)
16467 << FnDecl;
16468 }
16469 } else {
16470 bool ClassOrEnumParam = false;
16471 for (auto *Param : FnDecl->parameters()) {
16472 QualType ParamType = Param->getType().getNonReferenceType();
16473 if (ParamType->isDependentType() || ParamType->isRecordType() ||
16474 ParamType->isEnumeralType()) {
16475 ClassOrEnumParam = true;
16476 break;
16477 }
16478 }
16479
16480 if (!ClassOrEnumParam)
16481 return Diag(FnDecl->getLocation(),
16482 diag::err_operator_overload_needs_class_or_enum)
16483 << FnDecl->getDeclName();
16484 }
16485
16486 // C++ [over.oper]p8:
16487 // An operator function cannot have default arguments (8.3.6),
16488 // except where explicitly stated below.
16489 //
16490 // Only the function-call operator (C++ [over.call]p1) and the subscript
16491 // operator (CWG2507) allow default arguments.
16492 if (Op != OO_Call) {
16493 ParmVarDecl *FirstDefaultedParam = nullptr;
16494 for (auto *Param : FnDecl->parameters()) {
16495 if (Param->hasDefaultArg()) {
16496 FirstDefaultedParam = Param;
16497 break;
16498 }
16499 }
16500 if (FirstDefaultedParam) {
16501 if (Op == OO_Subscript) {
16502 Diag(FnDecl->getLocation(), LangOpts.CPlusPlus23
16503 ? diag::ext_subscript_overload
16504 : diag::error_subscript_overload)
16505 << FnDecl->getDeclName() << 1
16506 << FirstDefaultedParam->getDefaultArgRange();
16507 } else {
16508 return Diag(FirstDefaultedParam->getLocation(),
16509 diag::err_operator_overload_default_arg)
16510 << FnDecl->getDeclName()
16511 << FirstDefaultedParam->getDefaultArgRange();
16512 }
16513 }
16514 }
16515
16516 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
16517 { false, false, false }
16518#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
16519 , { Unary, Binary, MemberOnly }
16520#include "clang/Basic/OperatorKinds.def"
16521 };
16522
16523 bool CanBeUnaryOperator = OperatorUses[Op][0];
16524 bool CanBeBinaryOperator = OperatorUses[Op][1];
16525 bool MustBeMemberOperator = OperatorUses[Op][2];
16526
16527 // C++ [over.oper]p8:
16528 // [...] Operator functions cannot have more or fewer parameters
16529 // than the number required for the corresponding operator, as
16530 // described in the rest of this subclause.
16531 unsigned NumParams = FnDecl->getNumParams() +
16532 (isa<CXXMethodDecl>(FnDecl) &&
16534 ? 1
16535 : 0);
16536 if (Op != OO_Call && Op != OO_Subscript &&
16537 ((NumParams == 1 && !CanBeUnaryOperator) ||
16538 (NumParams == 2 && !CanBeBinaryOperator) || (NumParams < 1) ||
16539 (NumParams > 2))) {
16540 // We have the wrong number of parameters.
16541 unsigned ErrorKind;
16542 if (CanBeUnaryOperator && CanBeBinaryOperator) {
16543 ErrorKind = 2; // 2 -> unary or binary.
16544 } else if (CanBeUnaryOperator) {
16545 ErrorKind = 0; // 0 -> unary
16546 } else {
16547 assert(CanBeBinaryOperator &&
16548 "All non-call overloaded operators are unary or binary!");
16549 ErrorKind = 1; // 1 -> binary
16550 }
16551 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
16552 << FnDecl->getDeclName() << NumParams << ErrorKind;
16553 }
16554
16555 if (Op == OO_Subscript && NumParams != 2) {
16556 Diag(FnDecl->getLocation(), LangOpts.CPlusPlus23
16557 ? diag::ext_subscript_overload
16558 : diag::error_subscript_overload)
16559 << FnDecl->getDeclName() << (NumParams == 1 ? 0 : 2);
16560 }
16561
16562 // Overloaded operators other than operator() and operator[] cannot be
16563 // variadic.
16564 if (Op != OO_Call &&
16565 FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) {
16566 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
16567 << FnDecl->getDeclName();
16568 }
16569
16570 // Some operators must be member functions.
16571 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
16572 return Diag(FnDecl->getLocation(),
16573 diag::err_operator_overload_must_be_member)
16574 << FnDecl->getDeclName();
16575 }
16576
16577 // C++ [over.inc]p1:
16578 // The user-defined function called operator++ implements the
16579 // prefix and postfix ++ operator. If this function is a member
16580 // function with no parameters, or a non-member function with one
16581 // parameter of class or enumeration type, it defines the prefix
16582 // increment operator ++ for objects of that type. If the function
16583 // is a member function with one parameter (which shall be of type
16584 // int) or a non-member function with two parameters (the second
16585 // of which shall be of type int), it defines the postfix
16586 // increment operator ++ for objects of that type.
16587 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
16588 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
16589 QualType ParamType = LastParam->getType();
16590
16591 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
16592 !ParamType->isDependentType())
16593 return Diag(LastParam->getLocation(),
16594 diag::err_operator_overload_post_incdec_must_be_int)
16595 << LastParam->getType() << (Op == OO_MinusMinus);
16596 }
16597
16598 return false;
16599}
16600
16601static bool
16603 FunctionTemplateDecl *TpDecl) {
16604 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
16605
16606 // Must have one or two template parameters.
16607 if (TemplateParams->size() == 1) {
16608 NonTypeTemplateParmDecl *PmDecl =
16609 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
16610
16611 // The template parameter must be a char parameter pack.
16612 if (PmDecl && PmDecl->isTemplateParameterPack() &&
16614 return false;
16615
16616 // C++20 [over.literal]p5:
16617 // A string literal operator template is a literal operator template
16618 // whose template-parameter-list comprises a single non-type
16619 // template-parameter of class type.
16620 //
16621 // As a DR resolution, we also allow placeholders for deduced class
16622 // template specializations.
16623 if (SemaRef.getLangOpts().CPlusPlus20 && PmDecl &&
16624 !PmDecl->isTemplateParameterPack() &&
16625 (PmDecl->getType()->isRecordType() ||
16627 return false;
16628 } else if (TemplateParams->size() == 2) {
16629 TemplateTypeParmDecl *PmType =
16630 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
16631 NonTypeTemplateParmDecl *PmArgs =
16632 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
16633
16634 // The second template parameter must be a parameter pack with the
16635 // first template parameter as its type.
16636 if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
16637 PmArgs->isTemplateParameterPack()) {
16638 const TemplateTypeParmType *TArgs =
16639 PmArgs->getType()->getAs<TemplateTypeParmType>();
16640 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
16641 TArgs->getIndex() == PmType->getIndex()) {
16643 SemaRef.Diag(TpDecl->getLocation(),
16644 diag::ext_string_literal_operator_template);
16645 return false;
16646 }
16647 }
16648 }
16649
16651 diag::err_literal_operator_template)
16652 << TpDecl->getTemplateParameters()->getSourceRange();
16653 return true;
16654}
16655
16656/// CheckLiteralOperatorDeclaration - Check whether the declaration
16657/// of this literal operator function is well-formed. If so, returns
16658/// false; otherwise, emits appropriate diagnostics and returns true.
16660 if (isa<CXXMethodDecl>(FnDecl)) {
16661 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
16662 << FnDecl->getDeclName();
16663 return true;
16664 }
16665
16666 if (FnDecl->isExternC()) {
16667 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
16668 if (const LinkageSpecDecl *LSD =
16669 FnDecl->getDeclContext()->getExternCContext())
16670 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
16671 return true;
16672 }
16673
16674 // This might be the definition of a literal operator template.
16676
16677 // This might be a specialization of a literal operator template.
16678 if (!TpDecl)
16679 TpDecl = FnDecl->getPrimaryTemplate();
16680
16681 // template <char...> type operator "" name() and
16682 // template <class T, T...> type operator "" name() are the only valid
16683 // template signatures, and the only valid signatures with no parameters.
16684 //
16685 // C++20 also allows template <SomeClass T> type operator "" name().
16686 if (TpDecl) {
16687 if (FnDecl->param_size() != 0) {
16688 Diag(FnDecl->getLocation(),
16689 diag::err_literal_operator_template_with_params);
16690 return true;
16691 }
16692
16694 return true;
16695
16696 } else if (FnDecl->param_size() == 1) {
16697 const ParmVarDecl *Param = FnDecl->getParamDecl(0);
16698
16699 QualType ParamType = Param->getType().getUnqualifiedType();
16700
16701 // Only unsigned long long int, long double, any character type, and const
16702 // char * are allowed as the only parameters.
16703 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
16704 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
16705 Context.hasSameType(ParamType, Context.CharTy) ||
16706 Context.hasSameType(ParamType, Context.WideCharTy) ||
16707 Context.hasSameType(ParamType, Context.Char8Ty) ||
16708 Context.hasSameType(ParamType, Context.Char16Ty) ||
16709 Context.hasSameType(ParamType, Context.Char32Ty)) {
16710 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
16711 QualType InnerType = Ptr->getPointeeType();
16712
16713 // Pointer parameter must be a const char *.
16714 if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
16715 Context.CharTy) &&
16716 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
16717 Diag(Param->getSourceRange().getBegin(),
16718 diag::err_literal_operator_param)
16719 << ParamType << "'const char *'" << Param->getSourceRange();
16720 return true;
16721 }
16722
16723 } else if (ParamType->isRealFloatingType()) {
16724 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
16725 << ParamType << Context.LongDoubleTy << Param->getSourceRange();
16726 return true;
16727
16728 } else if (ParamType->isIntegerType()) {
16729 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
16730 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
16731 return true;
16732
16733 } else {
16734 Diag(Param->getSourceRange().getBegin(),
16735 diag::err_literal_operator_invalid_param)
16736 << ParamType << Param->getSourceRange();
16737 return true;
16738 }
16739
16740 } else if (FnDecl->param_size() == 2) {
16741 FunctionDecl::param_iterator Param = FnDecl->param_begin();
16742
16743 // First, verify that the first parameter is correct.
16744
16745 QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
16746
16747 // Two parameter function must have a pointer to const as a
16748 // first parameter; let's strip those qualifiers.
16749 const PointerType *PT = FirstParamType->getAs<PointerType>();
16750
16751 if (!PT) {
16752 Diag((*Param)->getSourceRange().getBegin(),
16753 diag::err_literal_operator_param)
16754 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16755 return true;
16756 }
16757
16758 QualType PointeeType = PT->getPointeeType();
16759 // First parameter must be const
16760 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
16761 Diag((*Param)->getSourceRange().getBegin(),
16762 diag::err_literal_operator_param)
16763 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16764 return true;
16765 }
16766
16767 QualType InnerType = PointeeType.getUnqualifiedType();
16768 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
16769 // const char32_t* are allowed as the first parameter to a two-parameter
16770 // function
16771 if (!(Context.hasSameType(InnerType, Context.CharTy) ||
16772 Context.hasSameType(InnerType, Context.WideCharTy) ||
16773 Context.hasSameType(InnerType, Context.Char8Ty) ||
16774 Context.hasSameType(InnerType, Context.Char16Ty) ||
16775 Context.hasSameType(InnerType, Context.Char32Ty))) {
16776 Diag((*Param)->getSourceRange().getBegin(),
16777 diag::err_literal_operator_param)
16778 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16779 return true;
16780 }
16781
16782 // Move on to the second and final parameter.
16783 ++Param;
16784
16785 // The second parameter must be a std::size_t.
16786 QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
16787 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
16788 Diag((*Param)->getSourceRange().getBegin(),
16789 diag::err_literal_operator_param)
16790 << SecondParamType << Context.getSizeType()
16791 << (*Param)->getSourceRange();
16792 return true;
16793 }
16794 } else {
16795 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
16796 return true;
16797 }
16798
16799 // Parameters are good.
16800
16801 // A parameter-declaration-clause containing a default argument is not
16802 // equivalent to any of the permitted forms.
16803 for (auto *Param : FnDecl->parameters()) {
16804 if (Param->hasDefaultArg()) {
16805 Diag(Param->getDefaultArgRange().getBegin(),
16806 diag::err_literal_operator_default_argument)
16807 << Param->getDefaultArgRange();
16808 break;
16809 }
16810 }
16811
16812 const IdentifierInfo *II = FnDecl->getDeclName().getCXXLiteralIdentifier();
16815 !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
16816 // C++23 [usrlit.suffix]p1:
16817 // Literal suffix identifiers that do not start with an underscore are
16818 // reserved for future standardization. Literal suffix identifiers that
16819 // contain a double underscore __ are reserved for use by C++
16820 // implementations.
16821 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
16822 << static_cast<int>(Status)
16824 }
16825
16826 return false;
16827}
16828
16829/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
16830/// linkage specification, including the language and (if present)
16831/// the '{'. ExternLoc is the location of the 'extern', Lang is the
16832/// language string literal. LBraceLoc, if valid, provides the location of
16833/// the '{' brace. Otherwise, this linkage specification does not
16834/// have any braces.
16836 Expr *LangStr,
16837 SourceLocation LBraceLoc) {
16838 StringLiteral *Lit = cast<StringLiteral>(LangStr);
16839 assert(Lit->isUnevaluated() && "Unexpected string literal kind");
16840
16841 StringRef Lang = Lit->getString();
16843 if (Lang == "C")
16845 else if (Lang == "C++")
16847 else {
16848 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
16849 << LangStr->getSourceRange();
16850 return nullptr;
16851 }
16852
16853 // FIXME: Add all the various semantics of linkage specifications
16854
16856 LangStr->getExprLoc(), Language,
16857 LBraceLoc.isValid());
16858
16859 /// C++ [module.unit]p7.2.3
16860 /// - Otherwise, if the declaration
16861 /// - ...
16862 /// - ...
16863 /// - appears within a linkage-specification,
16864 /// it is attached to the global module.
16865 ///
16866 /// If the declaration is already in global module fragment, we don't
16867 /// need to attach it again.
16868 if (getLangOpts().CPlusPlusModules && isCurrentModulePurview()) {
16869 Module *GlobalModule = PushImplicitGlobalModuleFragment(ExternLoc);
16870 D->setLocalOwningModule(GlobalModule);
16871 }
16872
16873 CurContext->addDecl(D);
16874 PushDeclContext(S, D);
16875 return D;
16876}
16877
16878/// ActOnFinishLinkageSpecification - Complete the definition of
16879/// the C++ linkage specification LinkageSpec. If RBraceLoc is
16880/// valid, it's the position of the closing '}' brace in a linkage
16881/// specification that uses braces.
16883 Decl *LinkageSpec,
16884 SourceLocation RBraceLoc) {
16885 if (RBraceLoc.isValid()) {
16886 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
16887 LSDecl->setRBraceLoc(RBraceLoc);
16888 }
16889
16890 // If the current module doesn't has Parent, it implies that the
16891 // LinkageSpec isn't in the module created by itself. So we don't
16892 // need to pop it.
16893 if (getLangOpts().CPlusPlusModules && getCurrentModule() &&
16894 getCurrentModule()->isImplicitGlobalModule() &&
16896 PopImplicitGlobalModuleFragment();
16897
16899 return LinkageSpec;
16900}
16901
16903 const ParsedAttributesView &AttrList,
16904 SourceLocation SemiLoc) {
16905 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
16906 // Attribute declarations appertain to empty declaration so we handle
16907 // them here.
16908 ProcessDeclAttributeList(S, ED, AttrList);
16909
16910 CurContext->addDecl(ED);
16911 return ED;
16912}
16913
16914/// Perform semantic analysis for the variable declaration that
16915/// occurs within a C++ catch clause, returning the newly-created
16916/// variable.
16918 SourceLocation StartLoc,
16920 const IdentifierInfo *Name) {
16921 bool Invalid = false;
16922 QualType ExDeclType = TInfo->getType();
16923
16924 // Arrays and functions decay.
16925 if (ExDeclType->isArrayType())
16926 ExDeclType = Context.getArrayDecayedType(ExDeclType);
16927 else if (ExDeclType->isFunctionType())
16928 ExDeclType = Context.getPointerType(ExDeclType);
16929
16930 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
16931 // The exception-declaration shall not denote a pointer or reference to an
16932 // incomplete type, other than [cv] void*.
16933 // N2844 forbids rvalue references.
16934 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
16935 Diag(Loc, diag::err_catch_rvalue_ref);
16936 Invalid = true;
16937 }
16938
16939 if (ExDeclType->isVariablyModifiedType()) {
16940 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
16941 Invalid = true;
16942 }
16943
16944 QualType BaseType = ExDeclType;
16945 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
16946 unsigned DK = diag::err_catch_incomplete;
16947 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
16948 BaseType = Ptr->getPointeeType();
16949 Mode = 1;
16950 DK = diag::err_catch_incomplete_ptr;
16951 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
16952 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
16953 BaseType = Ref->getPointeeType();
16954 Mode = 2;
16955 DK = diag::err_catch_incomplete_ref;
16956 }
16957 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
16958 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
16959 Invalid = true;
16960
16961 if (!Invalid && BaseType.isWebAssemblyReferenceType()) {
16962 Diag(Loc, diag::err_wasm_reftype_tc) << 1;
16963 Invalid = true;
16964 }
16965
16966 if (!Invalid && Mode != 1 && BaseType->isSizelessType()) {
16967 Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType;
16968 Invalid = true;
16969 }
16970
16971 if (!Invalid && !ExDeclType->isDependentType() &&
16972 RequireNonAbstractType(Loc, ExDeclType,
16973 diag::err_abstract_type_in_decl,
16975 Invalid = true;
16976
16977 // Only the non-fragile NeXT runtime currently supports C++ catches
16978 // of ObjC types, and no runtime supports catching ObjC types by value.
16979 if (!Invalid && getLangOpts().ObjC) {
16980 QualType T = ExDeclType;
16981 if (const ReferenceType *RT = T->getAs<ReferenceType>())
16982 T = RT->getPointeeType();
16983
16984 if (T->isObjCObjectType()) {
16985 Diag(Loc, diag::err_objc_object_catch);
16986 Invalid = true;
16987 } else if (T->isObjCObjectPointerType()) {
16988 // FIXME: should this be a test for macosx-fragile specifically?
16990 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
16991 }
16992 }
16993
16994 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
16995 ExDeclType, TInfo, SC_None);
16996 ExDecl->setExceptionVariable(true);
16997
16998 // In ARC, infer 'retaining' for variables of retainable type.
16999 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(ExDecl))
17000 Invalid = true;
17001
17002 if (!Invalid && !ExDeclType->isDependentType()) {
17003 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
17004 // Insulate this from anything else we might currently be parsing.
17007
17008 // C++ [except.handle]p16:
17009 // The object declared in an exception-declaration or, if the
17010 // exception-declaration does not specify a name, a temporary (12.2) is
17011 // copy-initialized (8.5) from the exception object. [...]
17012 // The object is destroyed when the handler exits, after the destruction
17013 // of any automatic objects initialized within the handler.
17014 //
17015 // We just pretend to initialize the object with itself, then make sure
17016 // it can be destroyed later.
17017 QualType initType = Context.getExceptionObjectType(ExDeclType);
17018
17019 InitializedEntity entity =
17021 InitializationKind initKind =
17023
17024 Expr *opaqueValue =
17025 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
17026 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
17027 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
17028 if (result.isInvalid())
17029 Invalid = true;
17030 else {
17031 // If the constructor used was non-trivial, set this as the
17032 // "initializer".
17033 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
17034 if (!construct->getConstructor()->isTrivial()) {
17035 Expr *init = MaybeCreateExprWithCleanups(construct);
17036 ExDecl->setInit(init);
17037 }
17038
17039 // And make sure it's destructable.
17041 }
17042 }
17043 }
17044
17045 if (Invalid)
17046 ExDecl->setInvalidDecl();
17047
17048 return ExDecl;
17049}
17050
17051/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
17052/// handler.
17055 bool Invalid = D.isInvalidType();
17056
17057 // Check for unexpanded parameter packs.
17061 D.getIdentifierLoc());
17062 Invalid = true;
17063 }
17064
17065 const IdentifierInfo *II = D.getIdentifier();
17066 if (NamedDecl *PrevDecl =
17068 RedeclarationKind::ForVisibleRedeclaration)) {
17069 // The scope should be freshly made just for us. There is just no way
17070 // it contains any previous declaration, except for function parameters in
17071 // a function-try-block's catch statement.
17072 assert(!S->isDeclScope(PrevDecl));
17073 if (isDeclInScope(PrevDecl, CurContext, S)) {
17074 Diag(D.getIdentifierLoc(), diag::err_redefinition)
17075 << D.getIdentifier();
17076 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
17077 Invalid = true;
17078 } else if (PrevDecl->isTemplateParameter())
17079 // Maybe we will complain about the shadowed template parameter.
17081 }
17082
17083 if (D.getCXXScopeSpec().isSet() && !Invalid) {
17084 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
17085 << D.getCXXScopeSpec().getRange();
17086 Invalid = true;
17087 }
17088
17090 S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
17091 if (Invalid)
17092 ExDecl->setInvalidDecl();
17093
17094 // Add the exception declaration into this scope.
17095 if (II)
17096 PushOnScopeChains(ExDecl, S);
17097 else
17098 CurContext->addDecl(ExDecl);
17099
17100 ProcessDeclAttributes(S, ExDecl, D);
17101 return ExDecl;
17102}
17103
17105 Expr *AssertExpr,
17106 Expr *AssertMessageExpr,
17107 SourceLocation RParenLoc) {
17109 return nullptr;
17110
17111 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
17112 AssertMessageExpr, RParenLoc, false);
17113}
17114
17115static void WriteCharTypePrefix(BuiltinType::Kind BTK, llvm::raw_ostream &OS) {
17116 switch (BTK) {
17117 case BuiltinType::Char_S:
17118 case BuiltinType::Char_U:
17119 break;
17120 case BuiltinType::Char8:
17121 OS << "u8";
17122 break;
17123 case BuiltinType::Char16:
17124 OS << 'u';
17125 break;
17126 case BuiltinType::Char32:
17127 OS << 'U';
17128 break;
17129 case BuiltinType::WChar_S:
17130 case BuiltinType::WChar_U:
17131 OS << 'L';
17132 break;
17133 default:
17134 llvm_unreachable("Non-character type");
17135 }
17136}
17137
17138/// Convert character's value, interpreted as a code unit, to a string.
17139/// The value needs to be zero-extended to 32-bits.
17140/// FIXME: This assumes Unicode literal encodings
17141static void WriteCharValueForDiagnostic(uint32_t Value, const BuiltinType *BTy,
17142 unsigned TyWidth,
17143 SmallVectorImpl<char> &Str) {
17144 char Arr[UNI_MAX_UTF8_BYTES_PER_CODE_POINT];
17145 char *Ptr = Arr;
17146 BuiltinType::Kind K = BTy->getKind();
17147 llvm::raw_svector_ostream OS(Str);
17148
17149 // This should catch Char_S, Char_U, Char8, and use of escaped characters in
17150 // other types.
17151 if (K == BuiltinType::Char_S || K == BuiltinType::Char_U ||
17152 K == BuiltinType::Char8 || Value <= 0x7F) {
17153 StringRef Escaped = escapeCStyle<EscapeChar::Single>(Value);
17154 if (!Escaped.empty())
17155 EscapeStringForDiagnostic(Escaped, Str);
17156 else
17157 OS << static_cast<char>(Value);
17158 return;
17159 }
17160
17161 switch (K) {
17162 case BuiltinType::Char16:
17163 case BuiltinType::Char32:
17164 case BuiltinType::WChar_S:
17165 case BuiltinType::WChar_U: {
17166 if (llvm::ConvertCodePointToUTF8(Value, Ptr))
17167 EscapeStringForDiagnostic(StringRef(Arr, Ptr - Arr), Str);
17168 else
17169 OS << "\\x"
17170 << llvm::format_hex_no_prefix(Value, TyWidth / 4, /*Upper=*/true);
17171 break;
17172 }
17173 default:
17174 llvm_unreachable("Non-character type is passed");
17175 }
17176}
17177
17178/// Convert \V to a string we can present to the user in a diagnostic
17179/// \T is the type of the expression that has been evaluated into \V
17183 if (!V.hasValue())
17184 return false;
17185
17186 switch (V.getKind()) {
17188 if (T->isBooleanType()) {
17189 // Bools are reduced to ints during evaluation, but for
17190 // diagnostic purposes we want to print them as
17191 // true or false.
17192 int64_t BoolValue = V.getInt().getExtValue();
17193 assert((BoolValue == 0 || BoolValue == 1) &&
17194 "Bool type, but value is not 0 or 1");
17195 llvm::raw_svector_ostream OS(Str);
17196 OS << (BoolValue ? "true" : "false");
17197 } else {
17198 llvm::raw_svector_ostream OS(Str);
17199 // Same is true for chars.
17200 // We want to print the character representation for textual types
17201 const auto *BTy = T->getAs<BuiltinType>();
17202 if (BTy) {
17203 switch (BTy->getKind()) {
17204 case BuiltinType::Char_S:
17205 case BuiltinType::Char_U:
17206 case BuiltinType::Char8:
17207 case BuiltinType::Char16:
17208 case BuiltinType::Char32:
17209 case BuiltinType::WChar_S:
17210 case BuiltinType::WChar_U: {
17211 unsigned TyWidth = Context.getIntWidth(T);
17212 assert(8 <= TyWidth && TyWidth <= 32 && "Unexpected integer width");
17213 uint32_t CodeUnit = static_cast<uint32_t>(V.getInt().getZExtValue());
17214 WriteCharTypePrefix(BTy->getKind(), OS);
17215 OS << '\'';
17216 WriteCharValueForDiagnostic(CodeUnit, BTy, TyWidth, Str);
17217 OS << "' (0x"
17218 << llvm::format_hex_no_prefix(CodeUnit, /*Width=*/2,
17219 /*Upper=*/true)
17220 << ", " << V.getInt() << ')';
17221 return true;
17222 }
17223 default:
17224 break;
17225 }
17226 }
17227 V.getInt().toString(Str);
17228 }
17229
17230 break;
17231
17233 V.getFloat().toString(Str);
17234 break;
17235
17237 if (V.isNullPointer()) {
17238 llvm::raw_svector_ostream OS(Str);
17239 OS << "nullptr";
17240 } else
17241 return false;
17242 break;
17243
17245 llvm::raw_svector_ostream OS(Str);
17246 OS << '(';
17247 V.getComplexFloatReal().toString(Str);
17248 OS << " + ";
17249 V.getComplexFloatImag().toString(Str);
17250 OS << "i)";
17251 } break;
17252
17254 llvm::raw_svector_ostream OS(Str);
17255 OS << '(';
17256 V.getComplexIntReal().toString(Str);
17257 OS << " + ";
17258 V.getComplexIntImag().toString(Str);
17259 OS << "i)";
17260 } break;
17261
17262 default:
17263 return false;
17264 }
17265
17266 return true;
17267}
17268
17269/// Some Expression types are not useful to print notes about,
17270/// e.g. literals and values that have already been expanded
17271/// before such as int-valued template parameters.
17272static bool UsefulToPrintExpr(const Expr *E) {
17273 E = E->IgnoreParenImpCasts();
17274 // Literals are pretty easy for humans to understand.
17277 return false;
17278
17279 // These have been substituted from template parameters
17280 // and appear as literals in the static assert error.
17281 if (isa<SubstNonTypeTemplateParmExpr>(E))
17282 return false;
17283
17284 // -5 is also simple to understand.
17285 if (const auto *UnaryOp = dyn_cast<UnaryOperator>(E))
17286 return UsefulToPrintExpr(UnaryOp->getSubExpr());
17287
17288 // Only print nested arithmetic operators.
17289 if (const auto *BO = dyn_cast<BinaryOperator>(E))
17290 return (BO->isShiftOp() || BO->isAdditiveOp() || BO->isMultiplicativeOp() ||
17291 BO->isBitwiseOp());
17292
17293 return true;
17294}
17295
17296/// Try to print more useful information about a failed static_assert
17297/// with expression \E
17299 if (const auto *Op = dyn_cast<BinaryOperator>(E);
17300 Op && Op->getOpcode() != BO_LOr) {
17301 const Expr *LHS = Op->getLHS()->IgnoreParenImpCasts();
17302 const Expr *RHS = Op->getRHS()->IgnoreParenImpCasts();
17303
17304 // Ignore comparisons of boolean expressions with a boolean literal.
17305 if ((isa<CXXBoolLiteralExpr>(LHS) && RHS->getType()->isBooleanType()) ||
17306 (isa<CXXBoolLiteralExpr>(RHS) && LHS->getType()->isBooleanType()))
17307 return;
17308
17309 // Don't print obvious expressions.
17310 if (!UsefulToPrintExpr(LHS) && !UsefulToPrintExpr(RHS))
17311 return;
17312
17313 struct {
17314 const clang::Expr *Cond;
17316 SmallString<12> ValueString;
17317 bool Print;
17318 } DiagSide[2] = {{LHS, Expr::EvalResult(), {}, false},
17319 {RHS, Expr::EvalResult(), {}, false}};
17320 for (unsigned I = 0; I < 2; I++) {
17321 const Expr *Side = DiagSide[I].Cond;
17322
17323 Side->EvaluateAsRValue(DiagSide[I].Result, Context, true);
17324
17325 DiagSide[I].Print =
17326 ConvertAPValueToString(DiagSide[I].Result.Val, Side->getType(),
17327 DiagSide[I].ValueString, Context);
17328 }
17329 if (DiagSide[0].Print && DiagSide[1].Print) {
17330 Diag(Op->getExprLoc(), diag::note_expr_evaluates_to)
17331 << DiagSide[0].ValueString << Op->getOpcodeStr()
17332 << DiagSide[1].ValueString << Op->getSourceRange();
17333 }
17334 }
17335}
17336
17338 std::string &Result,
17339 ASTContext &Ctx,
17340 bool ErrorOnInvalidMessage) {
17341 assert(Message);
17342 assert(!Message->isTypeDependent() && !Message->isValueDependent() &&
17343 "can't evaluate a dependant static assert message");
17344
17345 if (const auto *SL = dyn_cast<StringLiteral>(Message)) {
17346 assert(SL->isUnevaluated() && "expected an unevaluated string");
17347 Result.assign(SL->getString().begin(), SL->getString().end());
17348 return true;
17349 }
17350
17351 SourceLocation Loc = Message->getBeginLoc();
17352 QualType T = Message->getType().getNonReferenceType();
17353 auto *RD = T->getAsCXXRecordDecl();
17354 if (!RD) {
17355 Diag(Loc, diag::err_static_assert_invalid_message);
17356 return false;
17357 }
17358
17359 auto FindMember = [&](StringRef Member, bool &Empty,
17360 bool Diag = false) -> std::optional<LookupResult> {
17362 LookupResult MemberLookup(*this, DN, Loc, Sema::LookupMemberName);
17363 LookupQualifiedName(MemberLookup, RD);
17364 Empty = MemberLookup.empty();
17365 OverloadCandidateSet Candidates(MemberLookup.getNameLoc(),
17367 if (MemberLookup.empty())
17368 return std::nullopt;
17369 return std::move(MemberLookup);
17370 };
17371
17372 bool SizeNotFound, DataNotFound;
17373 std::optional<LookupResult> SizeMember = FindMember("size", SizeNotFound);
17374 std::optional<LookupResult> DataMember = FindMember("data", DataNotFound);
17375 if (SizeNotFound || DataNotFound) {
17376 Diag(Loc, diag::err_static_assert_missing_member_function)
17377 << ((SizeNotFound && DataNotFound) ? 2
17378 : SizeNotFound ? 0
17379 : 1);
17380 return false;
17381 }
17382
17383 if (!SizeMember || !DataMember) {
17384 if (!SizeMember)
17385 FindMember("size", SizeNotFound, /*Diag=*/true);
17386 if (!DataMember)
17387 FindMember("data", DataNotFound, /*Diag=*/true);
17388 return false;
17389 }
17390
17391 auto BuildExpr = [&](LookupResult &LR) {
17393 Message, Message->getType(), Message->getBeginLoc(), false,
17394 CXXScopeSpec(), SourceLocation(), nullptr, LR, nullptr, nullptr);
17395 if (Res.isInvalid())
17396 return ExprError();
17397 Res = BuildCallExpr(nullptr, Res.get(), Loc, std::nullopt, Loc, nullptr,
17398 false, true);
17399 if (Res.isInvalid())
17400 return ExprError();
17401 if (Res.get()->isTypeDependent() || Res.get()->isValueDependent())
17402 return ExprError();
17404 };
17405
17406 ExprResult SizeE = BuildExpr(*SizeMember);
17407 ExprResult DataE = BuildExpr(*DataMember);
17408
17409 QualType SizeT = Context.getSizeType();
17410 QualType ConstCharPtr =
17412
17413 ExprResult EvaluatedSize =
17414 SizeE.isInvalid() ? ExprError()
17416 SizeE.get(), SizeT, CCEK_StaticAssertMessageSize);
17417 if (EvaluatedSize.isInvalid()) {
17418 Diag(Loc, diag::err_static_assert_invalid_mem_fn_ret_ty) << /*size*/ 0;
17419 return false;
17420 }
17421
17422 ExprResult EvaluatedData =
17423 DataE.isInvalid()
17424 ? ExprError()
17425 : BuildConvertedConstantExpression(DataE.get(), ConstCharPtr,
17427 if (EvaluatedData.isInvalid()) {
17428 Diag(Loc, diag::err_static_assert_invalid_mem_fn_ret_ty) << /*data*/ 1;
17429 return false;
17430 }
17431
17432 if (!ErrorOnInvalidMessage &&
17433 Diags.isIgnored(diag::warn_static_assert_message_constexpr, Loc))
17434 return true;
17435
17436 Expr::EvalResult Status;
17438 Status.Diag = &Notes;
17439 if (!Message->EvaluateCharRangeAsString(Result, EvaluatedSize.get(),
17440 EvaluatedData.get(), Ctx, Status) ||
17441 !Notes.empty()) {
17442 Diag(Message->getBeginLoc(),
17443 ErrorOnInvalidMessage ? diag::err_static_assert_message_constexpr
17444 : diag::warn_static_assert_message_constexpr);
17445 for (const auto &Note : Notes)
17446 Diag(Note.first, Note.second);
17447 return !ErrorOnInvalidMessage;
17448 }
17449 return true;
17450}
17451
17453 Expr *AssertExpr, Expr *AssertMessage,
17454 SourceLocation RParenLoc,
17455 bool Failed) {
17456 assert(AssertExpr != nullptr && "Expected non-null condition");
17457 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
17458 (!AssertMessage || (!AssertMessage->isTypeDependent() &&
17459 !AssertMessage->isValueDependent())) &&
17460 !Failed) {
17461 // In a static_assert-declaration, the constant-expression shall be a
17462 // constant expression that can be contextually converted to bool.
17463 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
17464 if (Converted.isInvalid())
17465 Failed = true;
17466
17467 ExprResult FullAssertExpr =
17468 ActOnFinishFullExpr(Converted.get(), StaticAssertLoc,
17469 /*DiscardedValue*/ false,
17470 /*IsConstexpr*/ true);
17471 if (FullAssertExpr.isInvalid())
17472 Failed = true;
17473 else
17474 AssertExpr = FullAssertExpr.get();
17475
17476 llvm::APSInt Cond;
17477 Expr *BaseExpr = AssertExpr;
17478 AllowFoldKind FoldKind = NoFold;
17479
17480 if (!getLangOpts().CPlusPlus) {
17481 // In C mode, allow folding as an extension for better compatibility with
17482 // C++ in terms of expressions like static_assert("test") or
17483 // static_assert(nullptr).
17484 FoldKind = AllowFold;
17485 }
17486
17487 if (!Failed && VerifyIntegerConstantExpression(
17488 BaseExpr, &Cond,
17489 diag::err_static_assert_expression_is_not_constant,
17490 FoldKind).isInvalid())
17491 Failed = true;
17492
17493 // If the static_assert passes, only verify that
17494 // the message is grammatically valid without evaluating it.
17495 if (!Failed && AssertMessage && Cond.getBoolValue()) {
17496 std::string Str;
17497 EvaluateStaticAssertMessageAsString(AssertMessage, Str, Context,
17498 /*ErrorOnInvalidMessage=*/false);
17499 }
17500
17501 // CWG2518
17502 // [dcl.pre]/p10 If [...] the expression is evaluated in the context of a
17503 // template definition, the declaration has no effect.
17504 bool InTemplateDefinition =
17505 getLangOpts().CPlusPlus && CurContext->isDependentContext();
17506
17507 if (!Failed && !Cond && !InTemplateDefinition) {
17508 SmallString<256> MsgBuffer;
17509 llvm::raw_svector_ostream Msg(MsgBuffer);
17510 bool HasMessage = AssertMessage;
17511 if (AssertMessage) {
17512 std::string Str;
17513 HasMessage =
17515 AssertMessage, Str, Context, /*ErrorOnInvalidMessage=*/true) ||
17516 !Str.empty();
17517 Msg << Str;
17518 }
17519 Expr *InnerCond = nullptr;
17520 std::string InnerCondDescription;
17521 std::tie(InnerCond, InnerCondDescription) =
17522 findFailedBooleanCondition(Converted.get());
17523 if (InnerCond && isa<ConceptSpecializationExpr>(InnerCond)) {
17524 // Drill down into concept specialization expressions to see why they
17525 // weren't satisfied.
17526 Diag(AssertExpr->getBeginLoc(), diag::err_static_assert_failed)
17527 << !HasMessage << Msg.str() << AssertExpr->getSourceRange();
17528 ConstraintSatisfaction Satisfaction;
17529 if (!CheckConstraintSatisfaction(InnerCond, Satisfaction))
17530 DiagnoseUnsatisfiedConstraint(Satisfaction);
17531 } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond)
17532 && !isa<IntegerLiteral>(InnerCond)) {
17533 Diag(InnerCond->getBeginLoc(),
17534 diag::err_static_assert_requirement_failed)
17535 << InnerCondDescription << !HasMessage << Msg.str()
17536 << InnerCond->getSourceRange();
17537 DiagnoseStaticAssertDetails(InnerCond);
17538 } else {
17539 Diag(AssertExpr->getBeginLoc(), diag::err_static_assert_failed)
17540 << !HasMessage << Msg.str() << AssertExpr->getSourceRange();
17542 }
17543 Failed = true;
17544 }
17545 } else {
17546 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
17547 /*DiscardedValue*/false,
17548 /*IsConstexpr*/true);
17549 if (FullAssertExpr.isInvalid())
17550 Failed = true;
17551 else
17552 AssertExpr = FullAssertExpr.get();
17553 }
17554
17556 AssertExpr, AssertMessage, RParenLoc,
17557 Failed);
17558
17560 return Decl;
17561}
17562
17563/// Handle a friend tag declaration where the scope specifier was
17564/// templated.
17566 Scope *S, SourceLocation FriendLoc, unsigned TagSpec, SourceLocation TagLoc,
17567 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
17568 const ParsedAttributesView &Attr, MultiTemplateParamsArg TempParamLists) {
17570
17571 bool IsMemberSpecialization = false;
17572 bool Invalid = false;
17573
17574 if (TemplateParameterList *TemplateParams =
17576 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
17577 IsMemberSpecialization, Invalid)) {
17578 if (TemplateParams->size() > 0) {
17579 // This is a declaration of a class template.
17580 if (Invalid)
17581 return true;
17582
17583 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
17584 NameLoc, Attr, TemplateParams, AS_public,
17585 /*ModulePrivateLoc=*/SourceLocation(),
17586 FriendLoc, TempParamLists.size() - 1,
17587 TempParamLists.data()).get();
17588 } else {
17589 // The "template<>" header is extraneous.
17590 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
17591 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
17592 IsMemberSpecialization = true;
17593 }
17594 }
17595
17596 if (Invalid) return true;
17597
17598 bool isAllExplicitSpecializations = true;
17599 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
17600 if (TempParamLists[I]->size()) {
17601 isAllExplicitSpecializations = false;
17602 break;
17603 }
17604 }
17605
17606 // FIXME: don't ignore attributes.
17607
17608 // If it's explicit specializations all the way down, just forget
17609 // about the template header and build an appropriate non-templated
17610 // friend. TODO: for source fidelity, remember the headers.
17611 if (isAllExplicitSpecializations) {
17612 if (SS.isEmpty()) {
17613 bool Owned = false;
17614 bool IsDependent = false;
17615 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, Attr,
17616 AS_public,
17617 /*ModulePrivateLoc=*/SourceLocation(),
17618 MultiTemplateParamsArg(), Owned, IsDependent,
17619 /*ScopedEnumKWLoc=*/SourceLocation(),
17620 /*ScopedEnumUsesClassTag=*/false,
17621 /*UnderlyingType=*/TypeResult(),
17622 /*IsTypeSpecifier=*/false,
17623 /*IsTemplateParamOrArg=*/false, /*OOK=*/OOK_Outside);
17624 }
17625
17627 ElaboratedTypeKeyword Keyword
17629 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
17630 *Name, NameLoc);
17631 if (T.isNull())
17632 return true;
17633
17635 if (isa<DependentNameType>(T)) {
17638 TL.setElaboratedKeywordLoc(TagLoc);
17639 TL.setQualifierLoc(QualifierLoc);
17640 TL.setNameLoc(NameLoc);
17641 } else {
17643 TL.setElaboratedKeywordLoc(TagLoc);
17644 TL.setQualifierLoc(QualifierLoc);
17645 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
17646 }
17647
17648 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
17649 TSI, FriendLoc, TempParamLists);
17650 Friend->setAccess(AS_public);
17651 CurContext->addDecl(Friend);
17652 return Friend;
17653 }
17654
17655 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
17656
17657
17658
17659 // Handle the case of a templated-scope friend class. e.g.
17660 // template <class T> class A<T>::B;
17661 // FIXME: we don't support these right now.
17662 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
17663 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
17668 TL.setElaboratedKeywordLoc(TagLoc);
17670 TL.setNameLoc(NameLoc);
17671
17672 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
17673 TSI, FriendLoc, TempParamLists);
17674 Friend->setAccess(AS_public);
17675 Friend->setUnsupportedFriend(true);
17676 CurContext->addDecl(Friend);
17677 return Friend;
17678}
17679
17680/// Handle a friend type declaration. This works in tandem with
17681/// ActOnTag.
17682///
17683/// Notes on friend class templates:
17684///
17685/// We generally treat friend class declarations as if they were
17686/// declaring a class. So, for example, the elaborated type specifier
17687/// in a friend declaration is required to obey the restrictions of a
17688/// class-head (i.e. no typedefs in the scope chain), template
17689/// parameters are required to match up with simple template-ids, &c.
17690/// However, unlike when declaring a template specialization, it's
17691/// okay to refer to a template specialization without an empty
17692/// template parameter declaration, e.g.
17693/// friend class A<T>::B<unsigned>;
17694/// We permit this as a special case; if there are any template
17695/// parameters present at all, require proper matching, i.e.
17696/// template <> template <class T> friend class A<int>::B;
17698 MultiTemplateParamsArg TempParams) {
17700 SourceLocation FriendLoc = DS.getFriendSpecLoc();
17701
17702 assert(DS.isFriendSpecified());
17704
17705 // C++ [class.friend]p3:
17706 // A friend declaration that does not declare a function shall have one of
17707 // the following forms:
17708 // friend elaborated-type-specifier ;
17709 // friend simple-type-specifier ;
17710 // friend typename-specifier ;
17711 //
17712 // If the friend keyword isn't first, or if the declarations has any type
17713 // qualifiers, then the declaration doesn't have that form.
17715 Diag(FriendLoc, diag::err_friend_not_first_in_declaration);
17716 if (DS.getTypeQualifiers()) {
17718 Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
17720 Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
17722 Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
17724 Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
17726 Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
17727 }
17728
17729 // Try to convert the decl specifier to a type. This works for
17730 // friend templates because ActOnTag never produces a ClassTemplateDecl
17731 // for a TUK_Friend.
17732 Declarator TheDeclarator(DS, ParsedAttributesView::none(),
17734 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator);
17735 QualType T = TSI->getType();
17736 if (TheDeclarator.isInvalidType())
17737 return nullptr;
17738
17740 return nullptr;
17741
17742 if (!T->isElaboratedTypeSpecifier()) {
17743 if (TempParams.size()) {
17744 // C++23 [dcl.pre]p5:
17745 // In a simple-declaration, the optional init-declarator-list can be
17746 // omitted only when declaring a class or enumeration, that is, when
17747 // the decl-specifier-seq contains either a class-specifier, an
17748 // elaborated-type-specifier with a class-key, or an enum-specifier.
17749 //
17750 // The declaration of a template-declaration or explicit-specialization
17751 // is never a member-declaration, so this must be a simple-declaration
17752 // with no init-declarator-list. Therefore, this is ill-formed.
17753 Diag(Loc, diag::err_tagless_friend_type_template) << DS.getSourceRange();
17754 return nullptr;
17755 } else if (const RecordDecl *RD = T->getAsRecordDecl()) {
17756 SmallString<16> InsertionText(" ");
17757 InsertionText += RD->getKindName();
17758
17760 ? diag::warn_cxx98_compat_unelaborated_friend_type
17761 : diag::ext_unelaborated_friend_type)
17762 << (unsigned)RD->getTagKind() << T
17764 InsertionText);
17765 } else {
17766 Diag(FriendLoc, getLangOpts().CPlusPlus11
17767 ? diag::warn_cxx98_compat_nonclass_type_friend
17768 : diag::ext_nonclass_type_friend)
17769 << T << DS.getSourceRange();
17770 }
17771 }
17772
17773 // C++98 [class.friend]p1: A friend of a class is a function
17774 // or class that is not a member of the class . . .
17775 // This is fixed in DR77, which just barely didn't make the C++03
17776 // deadline. It's also a very silly restriction that seriously
17777 // affects inner classes and which nobody else seems to implement;
17778 // thus we never diagnose it, not even in -pedantic.
17779 //
17780 // But note that we could warn about it: it's always useless to
17781 // friend one of your own members (it's not, however, worthless to
17782 // friend a member of an arbitrary specialization of your template).
17783
17784 Decl *D;
17785 if (!TempParams.empty())
17786 D = FriendTemplateDecl::Create(Context, CurContext, Loc, TempParams, TSI,
17787 FriendLoc);
17788 else
17790 TSI, FriendLoc);
17791
17792 if (!D)
17793 return nullptr;
17794
17795 D->setAccess(AS_public);
17796 CurContext->addDecl(D);
17797
17798 return D;
17799}
17800
17802 MultiTemplateParamsArg TemplateParams) {
17803 const DeclSpec &DS = D.getDeclSpec();
17804
17805 assert(DS.isFriendSpecified());
17807
17810
17811 // C++ [class.friend]p1
17812 // A friend of a class is a function or class....
17813 // Note that this sees through typedefs, which is intended.
17814 // It *doesn't* see through dependent types, which is correct
17815 // according to [temp.arg.type]p3:
17816 // If a declaration acquires a function type through a
17817 // type dependent on a template-parameter and this causes
17818 // a declaration that does not use the syntactic form of a
17819 // function declarator to have a function type, the program
17820 // is ill-formed.
17821 if (!TInfo->getType()->isFunctionType()) {
17822 Diag(Loc, diag::err_unexpected_friend);
17823
17824 // It might be worthwhile to try to recover by creating an
17825 // appropriate declaration.
17826 return nullptr;
17827 }
17828
17829 // C++ [namespace.memdef]p3
17830 // - If a friend declaration in a non-local class first declares a
17831 // class or function, the friend class or function is a member
17832 // of the innermost enclosing namespace.
17833 // - The name of the friend is not found by simple name lookup
17834 // until a matching declaration is provided in that namespace
17835 // scope (either before or after the class declaration granting
17836 // friendship).
17837 // - If a friend function is called, its name may be found by the
17838 // name lookup that considers functions from namespaces and
17839 // classes associated with the types of the function arguments.
17840 // - When looking for a prior declaration of a class or a function
17841 // declared as a friend, scopes outside the innermost enclosing
17842 // namespace scope are not considered.
17843
17844 CXXScopeSpec &SS = D.getCXXScopeSpec();
17846 assert(NameInfo.getName());
17847
17848 // Check for unexpanded parameter packs.
17852 return nullptr;
17853
17854 // The context we found the declaration in, or in which we should
17855 // create the declaration.
17856 DeclContext *DC;
17857 Scope *DCScope = S;
17858 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
17859 RedeclarationKind::ForExternalRedeclaration);
17860
17861 bool isTemplateId = D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
17862
17863 // There are five cases here.
17864 // - There's no scope specifier and we're in a local class. Only look
17865 // for functions declared in the immediately-enclosing block scope.
17866 // We recover from invalid scope qualifiers as if they just weren't there.
17867 FunctionDecl *FunctionContainingLocalClass = nullptr;
17868 if ((SS.isInvalid() || !SS.isSet()) &&
17869 (FunctionContainingLocalClass =
17870 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
17871 // C++11 [class.friend]p11:
17872 // If a friend declaration appears in a local class and the name
17873 // specified is an unqualified name, a prior declaration is
17874 // looked up without considering scopes that are outside the
17875 // innermost enclosing non-class scope. For a friend function
17876 // declaration, if there is no prior declaration, the program is
17877 // ill-formed.
17878
17879 // Find the innermost enclosing non-class scope. This is the block
17880 // scope containing the local class definition (or for a nested class,
17881 // the outer local class).
17882 DCScope = S->getFnParent();
17883
17884 // Look up the function name in the scope.
17886 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
17887
17888 if (!Previous.empty()) {
17889 // All possible previous declarations must have the same context:
17890 // either they were declared at block scope or they are members of
17891 // one of the enclosing local classes.
17892 DC = Previous.getRepresentativeDecl()->getDeclContext();
17893 } else {
17894 // This is ill-formed, but provide the context that we would have
17895 // declared the function in, if we were permitted to, for error recovery.
17896 DC = FunctionContainingLocalClass;
17897 }
17899
17900 // - There's no scope specifier, in which case we just go to the
17901 // appropriate scope and look for a function or function template
17902 // there as appropriate.
17903 } else if (SS.isInvalid() || !SS.isSet()) {
17904 // C++11 [namespace.memdef]p3:
17905 // If the name in a friend declaration is neither qualified nor
17906 // a template-id and the declaration is a function or an
17907 // elaborated-type-specifier, the lookup to determine whether
17908 // the entity has been previously declared shall not consider
17909 // any scopes outside the innermost enclosing namespace.
17910
17911 // Find the appropriate context according to the above.
17912 DC = CurContext;
17913
17914 // Skip class contexts. If someone can cite chapter and verse
17915 // for this behavior, that would be nice --- it's what GCC and
17916 // EDG do, and it seems like a reasonable intent, but the spec
17917 // really only says that checks for unqualified existing
17918 // declarations should stop at the nearest enclosing namespace,
17919 // not that they should only consider the nearest enclosing
17920 // namespace.
17921 while (DC->isRecord())
17922 DC = DC->getParent();
17923
17924 DeclContext *LookupDC = DC->getNonTransparentContext();
17925 while (true) {
17926 LookupQualifiedName(Previous, LookupDC);
17927
17928 if (!Previous.empty()) {
17929 DC = LookupDC;
17930 break;
17931 }
17932
17933 if (isTemplateId) {
17934 if (isa<TranslationUnitDecl>(LookupDC)) break;
17935 } else {
17936 if (LookupDC->isFileContext()) break;
17937 }
17938 LookupDC = LookupDC->getParent();
17939 }
17940
17941 DCScope = getScopeForDeclContext(S, DC);
17942
17943 // - There's a non-dependent scope specifier, in which case we
17944 // compute it and do a previous lookup there for a function
17945 // or function template.
17946 } else if (!SS.getScopeRep()->isDependent()) {
17947 DC = computeDeclContext(SS);
17948 if (!DC) return nullptr;
17949
17950 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
17951
17953
17954 // C++ [class.friend]p1: A friend of a class is a function or
17955 // class that is not a member of the class . . .
17956 if (DC->Equals(CurContext))
17959 diag::warn_cxx98_compat_friend_is_member :
17960 diag::err_friend_is_member);
17961
17962 // - There's a scope specifier that does not match any template
17963 // parameter lists, in which case we use some arbitrary context,
17964 // create a method or method template, and wait for instantiation.
17965 // - There's a scope specifier that does match some template
17966 // parameter lists, which we don't handle right now.
17967 } else {
17968 DC = CurContext;
17969 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
17970 }
17971
17972 if (!DC->isRecord()) {
17973 int DiagArg = -1;
17974 switch (D.getName().getKind()) {
17977 DiagArg = 0;
17978 break;
17980 DiagArg = 1;
17981 break;
17983 DiagArg = 2;
17984 break;
17986 DiagArg = 3;
17987 break;
17993 break;
17994 }
17995 // This implies that it has to be an operator or function.
17996 if (DiagArg >= 0) {
17997 Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
17998 return nullptr;
17999 }
18000 }
18001
18002 // FIXME: This is an egregious hack to cope with cases where the scope stack
18003 // does not contain the declaration context, i.e., in an out-of-line
18004 // definition of a class.
18005 Scope FakeDCScope(S, Scope::DeclScope, Diags);
18006 if (!DCScope) {
18007 FakeDCScope.setEntity(DC);
18008 DCScope = &FakeDCScope;
18009 }
18010
18011 bool AddToScope = true;
18012 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
18013 TemplateParams, AddToScope);
18014 if (!ND) return nullptr;
18015
18016 assert(ND->getLexicalDeclContext() == CurContext);
18017
18018 // If we performed typo correction, we might have added a scope specifier
18019 // and changed the decl context.
18020 DC = ND->getDeclContext();
18021
18022 // Add the function declaration to the appropriate lookup tables,
18023 // adjusting the redeclarations list as necessary. We don't
18024 // want to do this yet if the friending class is dependent.
18025 //
18026 // Also update the scope-based lookup if the target context's
18027 // lookup context is in lexical scope.
18029 DC = DC->getRedeclContext();
18031 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
18032 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
18033 }
18034
18036 D.getIdentifierLoc(), ND,
18037 DS.getFriendSpecLoc());
18038 FrD->setAccess(AS_public);
18039 CurContext->addDecl(FrD);
18040
18041 if (ND->isInvalidDecl()) {
18042 FrD->setInvalidDecl();
18043 } else {
18044 if (DC->isRecord()) CheckFriendAccess(ND);
18045
18046 FunctionDecl *FD;
18047 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
18048 FD = FTD->getTemplatedDecl();
18049 else
18050 FD = cast<FunctionDecl>(ND);
18051
18052 // C++ [class.friend]p6:
18053 // A function may be defined in a friend declaration of a class if and
18054 // only if the class is a non-local class, and the function name is
18055 // unqualified.
18056 if (D.isFunctionDefinition()) {
18057 // Qualified friend function definition.
18058 if (SS.isNotEmpty()) {
18059 // FIXME: We should only do this if the scope specifier names the
18060 // innermost enclosing namespace; otherwise the fixit changes the
18061 // meaning of the code.
18063 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
18064
18065 DB << SS.getScopeRep();
18066 if (DC->isFileContext())
18068
18069 // Friend function defined in a local class.
18070 } else if (FunctionContainingLocalClass) {
18071 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
18072
18073 // Per [basic.pre]p4, a template-id is not a name. Therefore, if we have
18074 // a template-id, the function name is not unqualified because these is
18075 // no name. While the wording requires some reading in-between the
18076 // lines, GCC, MSVC, and EDG all consider a friend function
18077 // specialization definitions // to be de facto explicit specialization
18078 // and diagnose them as such.
18079 } else if (isTemplateId) {
18080 Diag(NameInfo.getBeginLoc(), diag::err_friend_specialization_def);
18081 }
18082 }
18083
18084 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
18085 // default argument expression, that declaration shall be a definition
18086 // and shall be the only declaration of the function or function
18087 // template in the translation unit.
18089 // We can't look at FD->getPreviousDecl() because it may not have been set
18090 // if we're in a dependent context. If the function is known to be a
18091 // redeclaration, we will have narrowed Previous down to the right decl.
18092 if (D.isRedeclaration()) {
18093 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
18094 Diag(Previous.getRepresentativeDecl()->getLocation(),
18095 diag::note_previous_declaration);
18096 } else if (!D.isFunctionDefinition())
18097 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
18098 }
18099
18100 // Mark templated-scope function declarations as unsupported.
18101 if (FD->getNumTemplateParameterLists() && SS.isValid()) {
18102 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
18103 << SS.getScopeRep() << SS.getRange()
18104 << cast<CXXRecordDecl>(CurContext);
18105 FrD->setUnsupportedFriend(true);
18106 }
18107 }
18108
18110
18111 return ND;
18112}
18113
18115 StringLiteral *Message) {
18117
18118 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
18119 if (!Fn) {
18120 Diag(DelLoc, diag::err_deleted_non_function);
18121 return;
18122 }
18123
18124 // Deleted function does not have a body.
18125 Fn->setWillHaveBody(false);
18126
18127 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
18128 // Don't consider the implicit declaration we generate for explicit
18129 // specializations. FIXME: Do not generate these implicit declarations.
18130 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
18131 Prev->getPreviousDecl()) &&
18132 !Prev->isDefined()) {
18133 Diag(DelLoc, diag::err_deleted_decl_not_first);
18134 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
18135 Prev->isImplicit() ? diag::note_previous_implicit_declaration
18136 : diag::note_previous_declaration);
18137 // We can't recover from this; the declaration might have already
18138 // been used.
18139 Fn->setInvalidDecl();
18140 return;
18141 }
18142
18143 // To maintain the invariant that functions are only deleted on their first
18144 // declaration, mark the implicitly-instantiated declaration of the
18145 // explicitly-specialized function as deleted instead of marking the
18146 // instantiated redeclaration.
18147 Fn = Fn->getCanonicalDecl();
18148 }
18149
18150 // dllimport/dllexport cannot be deleted.
18151 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
18152 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
18153 Fn->setInvalidDecl();
18154 }
18155
18156 // C++11 [basic.start.main]p3:
18157 // A program that defines main as deleted [...] is ill-formed.
18158 if (Fn->isMain())
18159 Diag(DelLoc, diag::err_deleted_main);
18160
18161 // C++11 [dcl.fct.def.delete]p4:
18162 // A deleted function is implicitly inline.
18163 Fn->setImplicitlyInline();
18164 Fn->setDeletedAsWritten(true, Message);
18165}
18166
18168 if (!Dcl || Dcl->isInvalidDecl())
18169 return;
18170
18171 auto *FD = dyn_cast<FunctionDecl>(Dcl);
18172 if (!FD) {
18173 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) {
18174 if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) {
18175 Diag(DefaultLoc, diag::err_defaulted_comparison_template);
18176 return;
18177 }
18178 }
18179
18180 Diag(DefaultLoc, diag::err_default_special_members)
18181 << getLangOpts().CPlusPlus20;
18182 return;
18183 }
18184
18185 // Reject if this can't possibly be a defaultable function.
18187 if (!DefKind &&
18188 // A dependent function that doesn't locally look defaultable can
18189 // still instantiate to a defaultable function if it's a constructor
18190 // or assignment operator.
18191 (!FD->isDependentContext() ||
18192 (!isa<CXXConstructorDecl>(FD) &&
18193 FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) {
18194 Diag(DefaultLoc, diag::err_default_special_members)
18195 << getLangOpts().CPlusPlus20;
18196 return;
18197 }
18198
18199 // Issue compatibility warning. We already warned if the operator is
18200 // 'operator<=>' when parsing the '<=>' token.
18201 if (DefKind.isComparison() &&
18203 Diag(DefaultLoc, getLangOpts().CPlusPlus20
18204 ? diag::warn_cxx17_compat_defaulted_comparison
18205 : diag::ext_defaulted_comparison);
18206 }
18207
18208 FD->setDefaulted();
18209 FD->setExplicitlyDefaulted();
18210 FD->setDefaultLoc(DefaultLoc);
18211
18212 // Defer checking functions that are defaulted in a dependent context.
18213 if (FD->isDependentContext())
18214 return;
18215
18216 // Unset that we will have a body for this function. We might not,
18217 // if it turns out to be trivial, and we don't need this marking now
18218 // that we've marked it as defaulted.
18219 FD->setWillHaveBody(false);
18220
18221 if (DefKind.isComparison()) {
18222 // If this comparison's defaulting occurs within the definition of its
18223 // lexical class context, we have to do the checking when complete.
18224 if (auto const *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext()))
18225 if (!RD->isCompleteDefinition())
18226 return;
18227 }
18228
18229 // If this member fn was defaulted on its first declaration, we will have
18230 // already performed the checking in CheckCompletedCXXClass. Such a
18231 // declaration doesn't trigger an implicit definition.
18232 if (isa<CXXMethodDecl>(FD)) {
18233 const FunctionDecl *Primary = FD;
18234 if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
18235 // Ask the template instantiation pattern that actually had the
18236 // '= default' on it.
18237 Primary = Pattern;
18238 if (Primary->getCanonicalDecl()->isDefaulted())
18239 return;
18240 }
18241
18242 if (DefKind.isComparison()) {
18243 if (CheckExplicitlyDefaultedComparison(nullptr, FD, DefKind.asComparison()))
18244 FD->setInvalidDecl();
18245 else
18246 DefineDefaultedComparison(DefaultLoc, FD, DefKind.asComparison());
18247 } else {
18248 auto *MD = cast<CXXMethodDecl>(FD);
18249
18251 DefaultLoc))
18252 MD->setInvalidDecl();
18253 else
18254 DefineDefaultedFunction(*this, MD, DefaultLoc);
18255 }
18256}
18257
18259 for (Stmt *SubStmt : S->children()) {
18260 if (!SubStmt)
18261 continue;
18262 if (isa<ReturnStmt>(SubStmt))
18263 Self.Diag(SubStmt->getBeginLoc(),
18264 diag::err_return_in_constructor_handler);
18265 if (!isa<Expr>(SubStmt))
18266 SearchForReturnInStmt(Self, SubStmt);
18267 }
18268}
18269
18271 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
18272 CXXCatchStmt *Handler = TryBlock->getHandler(I);
18273 SearchForReturnInStmt(*this, Handler);
18274 }
18275}
18276
18278 StringLiteral *DeletedMessage) {
18279 switch (BodyKind) {
18280 case FnBodyKind::Delete:
18281 SetDeclDeleted(D, Loc, DeletedMessage);
18282 break;
18285 break;
18286 case FnBodyKind::Other:
18287 llvm_unreachable(
18288 "Parsed function body should be '= delete;' or '= default;'");
18289 }
18290}
18291
18293 const CXXMethodDecl *Old) {
18294 const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
18295 const auto *OldFT = Old->getType()->castAs<FunctionProtoType>();
18296
18297 if (OldFT->hasExtParameterInfos()) {
18298 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
18299 // A parameter of the overriding method should be annotated with noescape
18300 // if the corresponding parameter of the overridden method is annotated.
18301 if (OldFT->getExtParameterInfo(I).isNoEscape() &&
18302 !NewFT->getExtParameterInfo(I).isNoEscape()) {
18303 Diag(New->getParamDecl(I)->getLocation(),
18304 diag::warn_overriding_method_missing_noescape);
18305 Diag(Old->getParamDecl(I)->getLocation(),
18306 diag::note_overridden_marked_noescape);
18307 }
18308 }
18309
18310 // SME attributes must match when overriding a function declaration.
18311 if (IsInvalidSMECallConversion(Old->getType(), New->getType())) {
18312 Diag(New->getLocation(), diag::err_conflicting_overriding_attributes)
18313 << New << New->getType() << Old->getType();
18314 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
18315 return true;
18316 }
18317
18318 // Virtual overrides must have the same code_seg.
18319 const auto *OldCSA = Old->getAttr<CodeSegAttr>();
18320 const auto *NewCSA = New->getAttr<CodeSegAttr>();
18321 if ((NewCSA || OldCSA) &&
18322 (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
18323 Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
18324 Diag(Old->getLocation(), diag::note_previous_declaration);
18325 return true;
18326 }
18327
18328 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
18329
18330 // If the calling conventions match, everything is fine
18331 if (NewCC == OldCC)
18332 return false;
18333
18334 // If the calling conventions mismatch because the new function is static,
18335 // suppress the calling convention mismatch error; the error about static
18336 // function override (err_static_overrides_virtual from
18337 // Sema::CheckFunctionDeclaration) is more clear.
18338 if (New->getStorageClass() == SC_Static)
18339 return false;
18340
18341 Diag(New->getLocation(),
18342 diag::err_conflicting_overriding_cc_attributes)
18343 << New->getDeclName() << New->getType() << Old->getType();
18344 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
18345 return true;
18346}
18347
18349 const CXXMethodDecl *Old) {
18350 // CWG2553
18351 // A virtual function shall not be an explicit object member function.
18353 return true;
18354 Diag(New->getParamDecl(0)->getBeginLoc(),
18355 diag::err_explicit_object_parameter_nonmember)
18356 << New->getSourceRange() << /*virtual*/ 1 << /*IsLambda*/ false;
18357 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
18358 New->setInvalidDecl();
18359 return false;
18360}
18361
18363 const CXXMethodDecl *Old) {
18364 QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType();
18365 QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType();
18366
18367 if (Context.hasSameType(NewTy, OldTy) ||
18368 NewTy->isDependentType() || OldTy->isDependentType())
18369 return false;
18370
18371 // Check if the return types are covariant
18372 QualType NewClassTy, OldClassTy;
18373
18374 /// Both types must be pointers or references to classes.
18375 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
18376 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
18377 NewClassTy = NewPT->getPointeeType();
18378 OldClassTy = OldPT->getPointeeType();
18379 }
18380 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
18381 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
18382 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
18383 NewClassTy = NewRT->getPointeeType();
18384 OldClassTy = OldRT->getPointeeType();
18385 }
18386 }
18387 }
18388
18389 // The return types aren't either both pointers or references to a class type.
18390 if (NewClassTy.isNull()) {
18391 Diag(New->getLocation(),
18392 diag::err_different_return_type_for_overriding_virtual_function)
18393 << New->getDeclName() << NewTy << OldTy
18394 << New->getReturnTypeSourceRange();
18395 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18396 << Old->getReturnTypeSourceRange();
18397
18398 return true;
18399 }
18400
18401 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
18402 // C++14 [class.virtual]p8:
18403 // If the class type in the covariant return type of D::f differs from
18404 // that of B::f, the class type in the return type of D::f shall be
18405 // complete at the point of declaration of D::f or shall be the class
18406 // type D.
18407 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
18408 if (!RT->isBeingDefined() &&
18409 RequireCompleteType(New->getLocation(), NewClassTy,
18410 diag::err_covariant_return_incomplete,
18411 New->getDeclName()))
18412 return true;
18413 }
18414
18415 // Check if the new class derives from the old class.
18416 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
18417 Diag(New->getLocation(), diag::err_covariant_return_not_derived)
18418 << New->getDeclName() << NewTy << OldTy
18419 << New->getReturnTypeSourceRange();
18420 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18421 << Old->getReturnTypeSourceRange();
18422 return true;
18423 }
18424
18425 // Check if we the conversion from derived to base is valid.
18427 NewClassTy, OldClassTy,
18428 diag::err_covariant_return_inaccessible_base,
18429 diag::err_covariant_return_ambiguous_derived_to_base_conv,
18431 New->getDeclName(), nullptr)) {
18432 // FIXME: this note won't trigger for delayed access control
18433 // diagnostics, and it's impossible to get an undelayed error
18434 // here from access control during the original parse because
18435 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
18436 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18437 << Old->getReturnTypeSourceRange();
18438 return true;
18439 }
18440 }
18441
18442 // The qualifiers of the return types must be the same.
18443 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
18444 Diag(New->getLocation(),
18445 diag::err_covariant_return_type_different_qualifications)
18446 << New->getDeclName() << NewTy << OldTy
18447 << New->getReturnTypeSourceRange();
18448 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18449 << Old->getReturnTypeSourceRange();
18450 return true;
18451 }
18452
18453
18454 // The new class type must have the same or less qualifiers as the old type.
18455 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
18456 Diag(New->getLocation(),
18457 diag::err_covariant_return_type_class_type_more_qualified)
18458 << New->getDeclName() << NewTy << OldTy
18459 << New->getReturnTypeSourceRange();
18460 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18461 << Old->getReturnTypeSourceRange();
18462 return true;
18463 }
18464
18465 return false;
18466}
18467
18468/// Mark the given method pure.
18469///
18470/// \param Method the method to be marked pure.
18471///
18472/// \param InitRange the source range that covers the "0" initializer.
18474 SourceLocation EndLoc = InitRange.getEnd();
18475 if (EndLoc.isValid())
18476 Method->setRangeEnd(EndLoc);
18477
18478 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
18479 Method->setIsPureVirtual();
18480 return false;
18481 }
18482
18483 if (!Method->isInvalidDecl())
18484 Diag(Method->getLocation(), diag::err_non_virtual_pure)
18485 << Method->getDeclName() << InitRange;
18486 return true;
18487}
18488
18490 if (D->getFriendObjectKind())
18491 Diag(D->getLocation(), diag::err_pure_friend);
18492 else if (auto *M = dyn_cast<CXXMethodDecl>(D))
18493 CheckPureMethod(M, ZeroLoc);
18494 else
18495 Diag(D->getLocation(), diag::err_illegal_initializer);
18496}
18497
18498/// Invoked when we are about to parse an initializer for the declaration
18499/// 'Dcl'.
18500///
18501/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
18502/// static data member of class X, names should be looked up in the scope of
18503/// class X. If the declaration had a scope specifier, a scope will have
18504/// been created and passed in for this purpose. Otherwise, S will be null.
18506 assert(D && !D->isInvalidDecl());
18507
18508 // We will always have a nested name specifier here, but this declaration
18509 // might not be out of line if the specifier names the current namespace:
18510 // extern int n;
18511 // int ::n = 0;
18512 if (S && D->isOutOfLine())
18514
18517}
18518
18519/// Invoked after we are finished parsing an initializer for the declaration D.
18521 assert(D);
18522
18523 if (S && D->isOutOfLine())
18525
18526 if (getLangOpts().CPlusPlus23) {
18527 // An expression or conversion is 'manifestly constant-evaluated' if it is:
18528 // [...]
18529 // - the initializer of a variable that is usable in constant expressions or
18530 // has constant initialization.
18531 if (auto *VD = dyn_cast<VarDecl>(D);
18534 // An expression or conversion is in an 'immediate function context' if it
18535 // is potentially evaluated and either:
18536 // [...]
18537 // - it is a subexpression of a manifestly constant-evaluated expression
18538 // or conversion.
18539 ExprEvalContexts.back().InImmediateFunctionContext = true;
18540 }
18541 }
18542
18543 // Unless the initializer is in an immediate function context (as determined
18544 // above), this will evaluate all contained immediate function calls as
18545 // constant expressions. If the initializer IS an immediate function context,
18546 // the initializer has been determined to be a constant expression, and all
18547 // such evaluations will be elided (i.e., as if we "knew the whole time" that
18548 // it was a constant expression).
18550}
18551
18552/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
18553/// C++ if/switch/while/for statement.
18554/// e.g: "if (int x = f()) {...}"
18556 // C++ 6.4p2:
18557 // The declarator shall not specify a function or an array.
18558 // The type-specifier-seq shall not contain typedef and shall not declare a
18559 // new class or enumeration.
18561 "Parser allowed 'typedef' as storage class of condition decl.");
18562
18563 Decl *Dcl = ActOnDeclarator(S, D);
18564 if (!Dcl)
18565 return true;
18566
18567 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
18568 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
18569 << D.getSourceRange();
18570 return true;
18571 }
18572
18573 if (auto *VD = dyn_cast<VarDecl>(Dcl))
18574 VD->setCXXCondDecl();
18575
18576 return Dcl;
18577}
18578
18580 if (!ExternalSource)
18581 return;
18582
18584 ExternalSource->ReadUsedVTables(VTables);
18586 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
18587 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
18588 = VTablesUsed.find(VTables[I].Record);
18589 // Even if a definition wasn't required before, it may be required now.
18590 if (Pos != VTablesUsed.end()) {
18591 if (!Pos->second && VTables[I].DefinitionRequired)
18592 Pos->second = true;
18593 continue;
18594 }
18595
18596 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
18597 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
18598 }
18599
18600 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
18601}
18602
18604 bool DefinitionRequired) {
18605 // Ignore any vtable uses in unevaluated operands or for classes that do
18606 // not have a vtable.
18607 if (!Class->isDynamicClass() || Class->isDependentContext() ||
18609 return;
18610 // Do not mark as used if compiling for the device outside of the target
18611 // region.
18612 if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice &&
18613 !OpenMP().isInOpenMPDeclareTargetContext() &&
18614 !OpenMP().isInOpenMPTargetExecutionDirective()) {
18615 if (!DefinitionRequired)
18617 return;
18618 }
18619
18620 // Try to insert this class into the map.
18622 Class = Class->getCanonicalDecl();
18623 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
18624 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
18625 if (!Pos.second) {
18626 // If we already had an entry, check to see if we are promoting this vtable
18627 // to require a definition. If so, we need to reappend to the VTableUses
18628 // list, since we may have already processed the first entry.
18629 if (DefinitionRequired && !Pos.first->second) {
18630 Pos.first->second = true;
18631 } else {
18632 // Otherwise, we can early exit.
18633 return;
18634 }
18635 } else {
18636 // The Microsoft ABI requires that we perform the destructor body
18637 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
18638 // the deleting destructor is emitted with the vtable, not with the
18639 // destructor definition as in the Itanium ABI.
18641 CXXDestructorDecl *DD = Class->getDestructor();
18642 if (DD && DD->isVirtual() && !DD->isDeleted()) {
18643 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
18644 // If this is an out-of-line declaration, marking it referenced will
18645 // not do anything. Manually call CheckDestructor to look up operator
18646 // delete().
18647 ContextRAII SavedContext(*this, DD);
18648 CheckDestructor(DD);
18649 } else {
18650 MarkFunctionReferenced(Loc, Class->getDestructor());
18651 }
18652 }
18653 }
18654 }
18655
18656 // Local classes need to have their virtual members marked
18657 // immediately. For all other classes, we mark their virtual members
18658 // at the end of the translation unit.
18659 if (Class->isLocalClass())
18660 MarkVirtualMembersReferenced(Loc, Class->getDefinition());
18661 else
18662 VTableUses.push_back(std::make_pair(Class, Loc));
18663}
18664
18667 if (VTableUses.empty())
18668 return false;
18669
18670 // Note: The VTableUses vector could grow as a result of marking
18671 // the members of a class as "used", so we check the size each
18672 // time through the loop and prefer indices (which are stable) to
18673 // iterators (which are not).
18674 bool DefinedAnything = false;
18675 for (unsigned I = 0; I != VTableUses.size(); ++I) {
18676 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
18677 if (!Class)
18678 continue;
18680 Class->getTemplateSpecializationKind();
18681
18682 SourceLocation Loc = VTableUses[I].second;
18683
18684 bool DefineVTable = true;
18685
18686 // If this class has a key function, but that key function is
18687 // defined in another translation unit, we don't need to emit the
18688 // vtable even though we're using it.
18689 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
18690 if (KeyFunction && !KeyFunction->hasBody()) {
18691 // The key function is in another translation unit.
18692 DefineVTable = false;
18694 KeyFunction->getTemplateSpecializationKind();
18697 "Instantiations don't have key functions");
18698 (void)TSK;
18699 } else if (!KeyFunction) {
18700 // If we have a class with no key function that is the subject
18701 // of an explicit instantiation declaration, suppress the
18702 // vtable; it will live with the explicit instantiation
18703 // definition.
18704 bool IsExplicitInstantiationDeclaration =
18706 for (auto *R : Class->redecls()) {
18708 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
18710 IsExplicitInstantiationDeclaration = true;
18711 else if (TSK == TSK_ExplicitInstantiationDefinition) {
18712 IsExplicitInstantiationDeclaration = false;
18713 break;
18714 }
18715 }
18716
18717 if (IsExplicitInstantiationDeclaration)
18718 DefineVTable = false;
18719 }
18720
18721 // The exception specifications for all virtual members may be needed even
18722 // if we are not providing an authoritative form of the vtable in this TU.
18723 // We may choose to emit it available_externally anyway.
18724 if (!DefineVTable) {
18726 continue;
18727 }
18728
18729 // Mark all of the virtual members of this class as referenced, so
18730 // that we can build a vtable. Then, tell the AST consumer that a
18731 // vtable for this class is required.
18732 DefinedAnything = true;
18734 CXXRecordDecl *Canonical = Class->getCanonicalDecl();
18735 if (VTablesUsed[Canonical])
18737
18738 // Warn if we're emitting a weak vtable. The vtable will be weak if there is
18739 // no key function or the key function is inlined. Don't warn in C++ ABIs
18740 // that lack key functions, since the user won't be able to make one.
18742 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation &&
18744 const FunctionDecl *KeyFunctionDef = nullptr;
18745 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
18746 KeyFunctionDef->isInlined()))
18747 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
18748 }
18749 }
18750 VTableUses.clear();
18751
18752 return DefinedAnything;
18753}
18754
18756 const CXXRecordDecl *RD) {
18757 for (const auto *I : RD->methods())
18758 if (I->isVirtual() && !I->isPureVirtual())
18759 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
18760}
18761
18763 const CXXRecordDecl *RD,
18764 bool ConstexprOnly) {
18765 // Mark all functions which will appear in RD's vtable as used.
18766 CXXFinalOverriderMap FinalOverriders;
18767 RD->getFinalOverriders(FinalOverriders);
18768 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
18769 E = FinalOverriders.end();
18770 I != E; ++I) {
18771 for (OverridingMethods::const_iterator OI = I->second.begin(),
18772 OE = I->second.end();
18773 OI != OE; ++OI) {
18774 assert(OI->second.size() > 0 && "no final overrider");
18775 CXXMethodDecl *Overrider = OI->second.front().Method;
18776
18777 // C++ [basic.def.odr]p2:
18778 // [...] A virtual member function is used if it is not pure. [...]
18779 if (!Overrider->isPureVirtual() &&
18780 (!ConstexprOnly || Overrider->isConstexpr()))
18781 MarkFunctionReferenced(Loc, Overrider);
18782 }
18783 }
18784
18785 // Only classes that have virtual bases need a VTT.
18786 if (RD->getNumVBases() == 0)
18787 return;
18788
18789 for (const auto &I : RD->bases()) {
18790 const auto *Base =
18791 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
18792 if (Base->getNumVBases() == 0)
18793 continue;
18795 }
18796}
18797
18798static
18803 Sema &S) {
18804 if (Ctor->isInvalidDecl())
18805 return;
18806
18808
18809 // Target may not be determinable yet, for instance if this is a dependent
18810 // call in an uninstantiated template.
18811 if (Target) {
18812 const FunctionDecl *FNTarget = nullptr;
18813 (void)Target->hasBody(FNTarget);
18814 Target = const_cast<CXXConstructorDecl*>(
18815 cast_or_null<CXXConstructorDecl>(FNTarget));
18816 }
18817
18818 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
18819 // Avoid dereferencing a null pointer here.
18820 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
18821
18822 if (!Current.insert(Canonical).second)
18823 return;
18824
18825 // We know that beyond here, we aren't chaining into a cycle.
18826 if (!Target || !Target->isDelegatingConstructor() ||
18827 Target->isInvalidDecl() || Valid.count(TCanonical)) {
18828 Valid.insert(Current.begin(), Current.end());
18829 Current.clear();
18830 // We've hit a cycle.
18831 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
18832 Current.count(TCanonical)) {
18833 // If we haven't diagnosed this cycle yet, do so now.
18834 if (!Invalid.count(TCanonical)) {
18835 S.Diag((*Ctor->init_begin())->getSourceLocation(),
18836 diag::warn_delegating_ctor_cycle)
18837 << Ctor;
18838
18839 // Don't add a note for a function delegating directly to itself.
18840 if (TCanonical != Canonical)
18841 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
18842
18844 while (C->getCanonicalDecl() != Canonical) {
18845 const FunctionDecl *FNTarget = nullptr;
18846 (void)C->getTargetConstructor()->hasBody(FNTarget);
18847 assert(FNTarget && "Ctor cycle through bodiless function");
18848
18849 C = const_cast<CXXConstructorDecl*>(
18850 cast<CXXConstructorDecl>(FNTarget));
18851 S.Diag(C->getLocation(), diag::note_which_delegates_to);
18852 }
18853 }
18854
18855 Invalid.insert(Current.begin(), Current.end());
18856 Current.clear();
18857 } else {
18858 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
18859 }
18860}
18861
18862
18865
18866 for (DelegatingCtorDeclsType::iterator
18869 I != E; ++I)
18870 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
18871
18872 for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
18873 (*CI)->setInvalidDecl();
18874}
18875
18876namespace {
18877 /// AST visitor that finds references to the 'this' expression.
18878 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
18879 Sema &S;
18880
18881 public:
18882 explicit FindCXXThisExpr(Sema &S) : S(S) { }
18883
18884 bool VisitCXXThisExpr(CXXThisExpr *E) {
18885 S.Diag(E->getLocation(), diag::err_this_static_member_func)
18886 << E->isImplicit();
18887 return false;
18888 }
18889 };
18890}
18891
18893 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
18894 if (!TSInfo)
18895 return false;
18896
18897 TypeLoc TL = TSInfo->getTypeLoc();
18899 if (!ProtoTL)
18900 return false;
18901
18902 // C++11 [expr.prim.general]p3:
18903 // [The expression this] shall not appear before the optional
18904 // cv-qualifier-seq and it shall not appear within the declaration of a
18905 // static member function (although its type and value category are defined
18906 // within a static member function as they are within a non-static member
18907 // function). [ Note: this is because declaration matching does not occur
18908 // until the complete declarator is known. - end note ]
18909 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
18910 FindCXXThisExpr Finder(*this);
18911
18912 // If the return type came after the cv-qualifier-seq, check it now.
18913 if (Proto->hasTrailingReturn() &&
18914 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
18915 return true;
18916
18917 // Check the exception specification.
18919 return true;
18920
18921 // Check the trailing requires clause
18922 if (Expr *E = Method->getTrailingRequiresClause())
18923 if (!Finder.TraverseStmt(E))
18924 return true;
18925
18927}
18928
18930 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
18931 if (!TSInfo)
18932 return false;
18933
18934 TypeLoc TL = TSInfo->getTypeLoc();
18936 if (!ProtoTL)
18937 return false;
18938
18939 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
18940 FindCXXThisExpr Finder(*this);
18941
18942 switch (Proto->getExceptionSpecType()) {
18943 case EST_Unparsed:
18944 case EST_Uninstantiated:
18945 case EST_Unevaluated:
18946 case EST_BasicNoexcept:
18947 case EST_NoThrow:
18948 case EST_DynamicNone:
18949 case EST_MSAny:
18950 case EST_None:
18951 break;
18952
18954 case EST_NoexceptFalse:
18955 case EST_NoexceptTrue:
18956 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
18957 return true;
18958 [[fallthrough]];
18959
18960 case EST_Dynamic:
18961 for (const auto &E : Proto->exceptions()) {
18962 if (!Finder.TraverseType(E))
18963 return true;
18964 }
18965 break;
18966 }
18967
18968 return false;
18969}
18970
18972 FindCXXThisExpr Finder(*this);
18973
18974 // Check attributes.
18975 for (const auto *A : Method->attrs()) {
18976 // FIXME: This should be emitted by tblgen.
18977 Expr *Arg = nullptr;
18978 ArrayRef<Expr *> Args;
18979 if (const auto *G = dyn_cast<GuardedByAttr>(A))
18980 Arg = G->getArg();
18981 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
18982 Arg = G->getArg();
18983 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
18984 Args = llvm::ArrayRef(AA->args_begin(), AA->args_size());
18985 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
18986 Args = llvm::ArrayRef(AB->args_begin(), AB->args_size());
18987 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
18988 Arg = ETLF->getSuccessValue();
18989 Args = llvm::ArrayRef(ETLF->args_begin(), ETLF->args_size());
18990 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
18991 Arg = STLF->getSuccessValue();
18992 Args = llvm::ArrayRef(STLF->args_begin(), STLF->args_size());
18993 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
18994 Arg = LR->getArg();
18995 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
18996 Args = llvm::ArrayRef(LE->args_begin(), LE->args_size());
18997 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
18998 Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());
18999 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
19000 Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());
19001 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
19002 Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());
19003 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
19004 Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());
19005
19006 if (Arg && !Finder.TraverseStmt(Arg))
19007 return true;
19008
19009 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
19010 if (!Finder.TraverseStmt(Args[I]))
19011 return true;
19012 }
19013 }
19014
19015 return false;
19016}
19017
19019 bool IsTopLevel, ExceptionSpecificationType EST,
19020 ArrayRef<ParsedType> DynamicExceptions,
19021 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
19022 SmallVectorImpl<QualType> &Exceptions,
19024 Exceptions.clear();
19025 ESI.Type = EST;
19026 if (EST == EST_Dynamic) {
19027 Exceptions.reserve(DynamicExceptions.size());
19028 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
19029 // FIXME: Preserve type source info.
19030 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
19031
19032 if (IsTopLevel) {
19034 collectUnexpandedParameterPacks(ET, Unexpanded);
19035 if (!Unexpanded.empty()) {
19037 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
19038 Unexpanded);
19039 continue;
19040 }
19041 }
19042
19043 // Check that the type is valid for an exception spec, and
19044 // drop it if not.
19045 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
19046 Exceptions.push_back(ET);
19047 }
19048 ESI.Exceptions = Exceptions;
19049 return;
19050 }
19051
19052 if (isComputedNoexcept(EST)) {
19053 assert((NoexceptExpr->isTypeDependent() ||
19054 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
19055 Context.BoolTy) &&
19056 "Parser should have made sure that the expression is boolean");
19057 if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
19058 ESI.Type = EST_BasicNoexcept;
19059 return;
19060 }
19061
19062 ESI.NoexceptExpr = NoexceptExpr;
19063 return;
19064 }
19065}
19066
19068 Decl *D, ExceptionSpecificationType EST, SourceRange SpecificationRange,
19069 ArrayRef<ParsedType> DynamicExceptions,
19070 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr) {
19071 if (!D)
19072 return;
19073
19074 // Dig out the function we're referring to.
19075 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
19076 D = FTD->getTemplatedDecl();
19077
19078 FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
19079 if (!FD)
19080 return;
19081
19082 // Check the exception specification.
19085 checkExceptionSpecification(/*IsTopLevel=*/true, EST, DynamicExceptions,
19086 DynamicExceptionRanges, NoexceptExpr, Exceptions,
19087 ESI);
19088
19089 // Update the exception specification on the function type.
19090 Context.adjustExceptionSpec(FD, ESI, /*AsWritten=*/true);
19091
19092 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
19093 if (MD->isStatic())
19095
19096 if (MD->isVirtual()) {
19097 // Check overrides, which we previously had to delay.
19098 for (const CXXMethodDecl *O : MD->overridden_methods())
19100 }
19101 }
19102}
19103
19104/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
19105///
19107 SourceLocation DeclStart, Declarator &D,
19108 Expr *BitWidth,
19109 InClassInitStyle InitStyle,
19110 AccessSpecifier AS,
19111 const ParsedAttr &MSPropertyAttr) {
19112 const IdentifierInfo *II = D.getIdentifier();
19113 if (!II) {
19114 Diag(DeclStart, diag::err_anonymous_property);
19115 return nullptr;
19116 }
19118
19120 QualType T = TInfo->getType();
19121 if (getLangOpts().CPlusPlus) {
19123
19126 D.setInvalidType();
19127 T = Context.IntTy;
19129 }
19130 }
19131
19133
19135 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
19136 << getLangOpts().CPlusPlus17;
19139 diag::err_invalid_thread)
19141
19142 // Check to see if this name was declared as a member previously
19143 NamedDecl *PrevDecl = nullptr;
19145 RedeclarationKind::ForVisibleRedeclaration);
19146 LookupName(Previous, S);
19147 switch (Previous.getResultKind()) {
19150 PrevDecl = Previous.getAsSingle<NamedDecl>();
19151 break;
19152
19154 PrevDecl = Previous.getRepresentativeDecl();
19155 break;
19156
19160 break;
19161 }
19162
19163 if (PrevDecl && PrevDecl->isTemplateParameter()) {
19164 // Maybe we will complain about the shadowed template parameter.
19166 // Just pretend that we didn't see the previous declaration.
19167 PrevDecl = nullptr;
19168 }
19169
19170 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
19171 PrevDecl = nullptr;
19172
19173 SourceLocation TSSL = D.getBeginLoc();
19174 MSPropertyDecl *NewPD =
19175 MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
19176 MSPropertyAttr.getPropertyDataGetter(),
19177 MSPropertyAttr.getPropertyDataSetter());
19178 ProcessDeclAttributes(TUScope, NewPD, D);
19179 NewPD->setAccess(AS);
19180
19181 if (NewPD->isInvalidDecl())
19182 Record->setInvalidDecl();
19183
19185 NewPD->setModulePrivate();
19186
19187 if (NewPD->isInvalidDecl() && PrevDecl) {
19188 // Don't introduce NewFD into scope; there's already something
19189 // with the same name in the same scope.
19190 } else if (II) {
19191 PushOnScopeChains(NewPD, S);
19192 } else
19193 Record->addDecl(NewPD);
19194
19195 return NewPD;
19196}
19197
19199 Declarator &Declarator, unsigned TemplateParameterDepth) {
19200 auto &Info = InventedParameterInfos.emplace_back();
19201 TemplateParameterList *ExplicitParams = nullptr;
19202 ArrayRef<TemplateParameterList *> ExplicitLists =
19204 if (!ExplicitLists.empty()) {
19205 bool IsMemberSpecialization, IsInvalid;
19208 Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr,
19209 ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid,
19210 /*SuppressDiagnostic=*/true);
19211 }
19212 // C++23 [dcl.fct]p23:
19213 // An abbreviated function template can have a template-head. The invented
19214 // template-parameters are appended to the template-parameter-list after
19215 // the explicitly declared template-parameters.
19216 //
19217 // A template-head must have one or more template-parameters (read:
19218 // 'template<>' is *not* a template-head). Only append the invented
19219 // template parameters if we matched the nested-name-specifier to a non-empty
19220 // TemplateParameterList.
19221 if (ExplicitParams && !ExplicitParams->empty()) {
19222 Info.AutoTemplateParameterDepth = ExplicitParams->getDepth();
19223 llvm::append_range(Info.TemplateParams, *ExplicitParams);
19224 Info.NumExplicitTemplateParams = ExplicitParams->size();
19225 } else {
19226 Info.AutoTemplateParameterDepth = TemplateParameterDepth;
19227 Info.NumExplicitTemplateParams = 0;
19228 }
19229}
19230
19232 auto &FSI = InventedParameterInfos.back();
19233 if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) {
19234 if (FSI.NumExplicitTemplateParams != 0) {
19235 TemplateParameterList *ExplicitParams =
19239 Context, ExplicitParams->getTemplateLoc(),
19240 ExplicitParams->getLAngleLoc(), FSI.TemplateParams,
19241 ExplicitParams->getRAngleLoc(),
19242 ExplicitParams->getRequiresClause()));
19243 } else {
19246 Context, SourceLocation(), SourceLocation(), FSI.TemplateParams,
19247 SourceLocation(), /*RequiresClause=*/nullptr));
19248 }
19249 }
19250 InventedParameterInfos.pop_back();
19251}
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3285
NodeId Parent
Definition: ASTDiff.cpp:191
This file provides some common utility functions for processing Lambda related AST Constructs.
DynTypedNode Node
StringRef P
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
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...
int Category
Definition: Format.cpp:2978
LangStandard::Kind Std
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:50
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.
llvm::SmallVector< std::pair< const MemRegion *, SVal >, 4 > Bindings
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
This file declares semantic analysis for CUDA constructs.
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 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 RefersToRValueRef(Expr *MemRef)
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.
static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T, llvm::APSInt &Size)
#define CheckPolymorphic(Type)
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 bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, QualType SubType, bool ConstRHS, CXXSpecialMemberKind CSM, TrivialSubobjectKind Kind, Sema::TrivialABIHandling TAH, bool Diagnose)
Check whether the special member selected for a given type would be trivial.
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 Expr * CastForMoving(Sema &SemaRef, Expr *E)
static void extendLeft(SourceRange &R, SourceRange Before)
static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, CXXSpecialMemberKind CSM, bool ConstArg, Sema::TrivialABIHandling TAH, bool Diagnose)
Check whether the members of a class type allow a special member to be trivial.
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 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 findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, CXXSpecialMemberKind CSM, unsigned Quals, bool ConstRHS, Sema::TrivialABIHandling TAH, CXXMethodDecl **Selected)
Perform lookup for a special member of the specified kind, and determine whether it is trivial.
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 bool CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, CanQualType ExpectedResultType, CanQualType ExpectedFirstParamType, unsigned DependentParamTypeDiag, unsigned InvalidParamTypeDiag)
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 Sema::ImplicitExceptionSpecification ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD, Sema::DefaultedComparisonKind DCK)
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 checkTupleLikeDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, VarDecl *Src, QualType DecompType, const llvm::APSInt &TupleSize)
static void NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set, const QualType &Type)
Recursively add the bases of Type. Don't add Type itself.
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 CXXConstructorDecl * findUserDeclaredCtor(CXXRecordDecl *RD)
static bool checkMemberDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, ValueDecl *Src, QualType DecompType, const CXXRecordDecl *OrigRD)
static void checkForMultipleExportedDefaultConstructors(Sema &S, CXXRecordDecl *Class)
static bool checkSimpleDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, ValueDecl *Src, QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType, llvm::function_ref< ExprResult(SourceLocation, Expr *, unsigned)> GetInit)
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 NamespaceDecl * getNamespaceDecl(NamedDecl *D)
getNamespaceDecl - Returns the namespace a decl represents.
static bool checkArrayDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, ValueDecl *Src, QualType DecompType, const ConstantArrayType *CAT)
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 ClassTemplateDecl * LookupStdInitializerList(Sema &S, SourceLocation Loc)
static bool CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl)
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 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.
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 void DefineDefaultedFunction(Sema &S, FunctionDecl *FD, SourceLocation DefaultLoc)
static bool BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, ImplicitInitializerKind ImplicitInitKind, FieldDecl *Field, IndirectFieldDecl *Indirect, CXXCtorInitializer *&CXXMemberInit)
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 lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup, SourceLocation Loc, StringRef Trait, TemplateArgumentListInfo &Args, unsigned DiagID)
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 bool checkComplexDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, ValueDecl *Src, QualType DecompType, const ComplexType *CT)
static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, CXXScopeSpec &SS, SourceLocation IdentLoc, IdentifierInfo *Ident)
static bool InitializationHasSideEffects(const FieldDecl &FD)
static bool CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, const FunctionDecl *FnDecl)
static bool checkArrayLikeDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, ValueDecl *Src, QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType)
static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, DeclStmt *DS, SourceLocation &Cxx1yLoc, Sema::CheckConstexprKind Kind)
Check the given declaration statement is legal within a constexpr function body.
static bool IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2)
Determine whether a using declaration considers the given declarations as "equivalent",...
static TemplateArgumentLoc getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T, uint64_t I)
static bool CheckConstexprDestructorSubobjects(Sema &SemaRef, const CXXDestructorDecl *DD, Sema::CheckConstexprKind Kind)
Determine whether a destructor cannot be constexpr due to.
static bool CheckConstexprCtorInitializer(Sema &SemaRef, const FunctionDecl *Dcl, FieldDecl *Field, llvm::SmallSet< Decl *, 16 > &Inits, bool &Diagnosed, Sema::CheckConstexprKind Kind)
Check that the given field is initialized within a constexpr constructor.
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.
SourceRange Range
Definition: SemaObjC.cpp:754
SourceLocation Loc
Definition: SemaObjC.cpp:755
bool Indirect
Definition: SemaObjC.cpp:756
This file declares semantic analysis for Objective-C.
This file declares semantic analysis for OpenMP constructs and clauses.
static bool isInvalid(LocType Loc, bool *Invalid)
Defines various enumerations that describe declaration and type specifiers.
Defines the clang::TypeLoc interface and its subclasses.
Allows QualTypes to be sorted and hence used in maps and sets.
const NestedNameSpecifier * Specifier
StateNode * Previous
__DEVICE__ void * memcpy(void *__a, const void *__b, size_t __c)
__device__ int
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)
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition: APValue.h:122
virtual void HandleVTable(CXXRecordDecl *RD)
Callback involved at the end of a translation unit to notify the consumer that a vtable for the given...
Definition: ASTConsumer.h:123
virtual bool HandleTopLevelDecl(DeclGroupRef D)
HandleTopLevelDecl - Handle the specified top-level declaration.
Definition: ASTConsumer.cpp:18
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:182
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1073
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2768
QualType getRValueReferenceType(QualType T) const
Return the uniqued reference to the type for an rvalue reference to the specified type.
unsigned getIntWidth(QualType T) const
QualType getTagDeclType(const TagDecl *Decl) const
Return the unique reference to the type for the specified TagDecl (struct/union/class/enum) decl.
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:648
QualType getRecordType(const RecordDecl *Decl) const
unsigned NumImplicitCopyAssignmentOperatorsDeclared
The number of implicitly-declared copy assignment operators for which declarations were built.
Definition: ASTContext.h:3235
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2575
unsigned NumImplicitDestructorsDeclared
The number of implicitly-declared destructors for which declarations were built.
Definition: ASTContext.h:3249
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2591
CanQualType LongDoubleTy
Definition: ASTContext.h:1103
CanQualType Char16Ty
Definition: ASTContext.h:1098
CallingConv getDefaultCallingConvention(bool IsVariadic, bool IsCXXMethod, bool IsBuiltin=false) const
Retrieves the default calling convention for the current target.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
const CXXMethodDecl * getCurrentKeyFunction(const CXXRecordDecl *RD)
Get our current best idea for the key function of the given record decl, or nullptr if there isn't on...
CanQualType VoidPtrTy
Definition: ASTContext.h:1118
void Deallocate(void *Ptr) const
Definition: ASTContext.h:724
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
CanQualType DependentTy
Definition: ASTContext.h:1119
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1591
CanQualType WideCharTy
Definition: ASTContext.h:1095
IdentifierTable & Idents
Definition: ASTContext.h:644
const LangOptions & getLangOpts() const
Definition: ASTContext.h:775
QualType getConstType(QualType T) const
Return the uniqued reference to the type for a const qualified type.
Definition: ASTContext.h:1299
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<=>,...
Definition: ASTContext.h:2272
QualType AutoDeductTy
Definition: ASTContext.h:1149
CanQualType BoolTy
Definition: ASTContext.h:1092
unsigned NumImplicitDefaultConstructorsDeclared
The number of implicitly-declared default constructors for which declarations were built.
Definition: ASTContext.h:3214
bool hasSameTemplateName(const TemplateName &X, const TemplateName &Y) const
Determine whether the given template names refer to the same template.
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
CanQualType CharTy
Definition: ASTContext.h:1093
unsigned NumImplicitMoveConstructorsDeclared
The number of implicitly-declared move constructors for which declarations were built.
Definition: ASTContext.h:3228
unsigned NumImplicitCopyConstructorsDeclared
The number of implicitly-declared copy constructors for which declarations were built.
Definition: ASTContext.h:3221
CanQualType IntTy
Definition: ASTContext.h:1100
unsigned NumImplicitDestructors
The number of implicitly-declared destructors.
Definition: ASTContext.h:3245
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2157
QualType getElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, QualType NamedType, TagDecl *OwnedTagDecl=nullptr) const
void adjustExceptionSpec(FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI, bool AsWritten=false)
Change the exception specification on a function once it is delay-parsed, instantiated,...
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:697
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2618
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2341
CanQualType BuiltinFnTy
Definition: ASTContext.h:1121
unsigned NumImplicitDefaultConstructors
The number of implicitly-declared default constructors.
Definition: ASTContext.h:3210
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
unsigned NumImplicitMoveAssignmentOperatorsDeclared
The number of implicitly-declared move assignment operators for which declarations were built.
Definition: ASTContext.h:3242
CanQualType VoidTy
Definition: ASTContext.h:1091
unsigned NumImplicitMoveConstructors
The number of implicitly-declared move constructors.
Definition: ASTContext.h:3224
TypeSourceInfo * CreateTypeSourceInfo(QualType T, unsigned Size=0) const
Allocate an uninitialized TypeSourceInfo.
QualType getExceptionObjectType(QualType T) const
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1102
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Definition: ASTContext.h:1569
QualType getDependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, QualType Canon=QualType()) const
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.
Definition: ASTContext.h:3026
CanQualType Char32Ty
Definition: ASTContext.h:1099
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:757
QualType getAutoDeductType() const
C++11 deduction pattern for 'auto' type.
unsigned NumImplicitCopyConstructors
The number of implicitly-declared copy constructors.
Definition: ASTContext.h:3217
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any.
Definition: ASTContext.h:1189
unsigned NumImplicitCopyAssignmentOperators
The number of implicitly-declared copy assignment operators.
Definition: ASTContext.h:3231
void adjustDeducedFunctionResultType(FunctionDecl *FD, QualType ResultType)
Change the result type of a function type once it is deduced.
NestedNameSpecifier * getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const
Retrieves the "canonical" nested name specifier for a given nested name specifier.
CanQualType Char8Ty
Definition: ASTContext.h:1097
unsigned NumImplicitMoveAssignmentOperators
The number of implicitly-declared move assignment operators.
Definition: ASTContext.h:3238
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:167
PtrTy get() const
Definition: Ownership.h:170
bool isInvalid() const
Definition: Ownership.h:166
bool isUsable() const
Definition: Ownership.h:168
Wrapper for source info for arrays.
Definition: TypeLoc.h:1561
TypeLoc getElementLoc() const
Definition: TypeLoc.h:1591
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3518
QualType getElementType() const
Definition: Type.h:3530
Attr - This represents one attribute.
Definition: Attr.h:42
attr::Kind getKind() const
Definition: Attr.h:88
bool isInherited() const
Definition: Attr.h:97
Attr * clone(ASTContext &C) const
SourceLocation getLocation() const
Definition: Attr.h:95
Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained by a type-constraint.
Definition: Type.h:5981
AutoTypeKeyword getKeyword() const
Definition: Type.h:6012
Represents a C++ declaration that introduces decls from somewhere else.
Definition: DeclCXX.h:3417
unsigned shadow_size() const
Return the number of shadowed declarations associated with this using declaration.
Definition: DeclCXX.h:3495
void addShadowDecl(UsingShadowDecl *S)
Definition: DeclCXX.cpp:3142
shadow_iterator shadow_begin() const
Definition: DeclCXX.h:3487
void removeShadowDecl(UsingShadowDecl *S)
Definition: DeclCXX.cpp:3151
BinaryConditionalOperator - The GNU extension to the conditional operator which allows the middle ope...
Definition: Expr.h:4241
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3840
Expr * getLHS() const
Definition: Expr.h:3889
Expr * getRHS() const
Definition: Expr.h:3891
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:4786
static bool isCompoundAssignmentOp(Opcode Opc)
Definition: Expr.h:3980
Opcode getOpcode() const
Definition: Expr.h:3884
static Opcode getOverloadedOpcode(OverloadedOperatorKind OO)
Retrieve the binary opcode that corresponds to the given overloaded operator.
Definition: Expr.cpp:2143
A binding in a decomposition declaration.
Definition: DeclCXX.h:4107
static BindingDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation IdLoc, IdentifierInfo *Id)
Definition: DeclCXX.cpp:3336
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:6173
Wrapper for source info for block pointers.
Definition: TypeLoc.h:1314
This class is used for builtin types like 'int'.
Definition: Type.h:2981
Kind getKind() const
Definition: Type.h:3023
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...
std::list< CXXBasePath >::iterator paths_iterator
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:720
CXXCatchStmt - This represents a C++ catch block.
Definition: StmtCXX.h:28
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1542
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:1110
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition: ExprCXX.h:1685
bool isImmediateEscalating() const
Definition: ExprCXX.h:1700
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition: ExprCXX.h:1605
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2535
CXXConstructorDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:2777
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:2767
ExplicitSpecifier getExplicitSpecifier()
Definition: DeclCXX.h:2606
init_iterator init_begin()
Retrieve an iterator to the first initializer.
Definition: DeclCXX.h:2631
CXXConstructorDecl * getTargetConstructor() const
When this constructor delegates to another, retrieve the target.
Definition: DeclCXX.cpp:2744
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:2762
bool isDefaultConstructor() const
Whether this constructor is a default constructor (C++ [class.ctor]p5), which can be used to default-...
Definition: DeclCXX.cpp:2753
InheritedConstructor getInheritedConstructor() const
Get the constructor that this inheriting constructor is based on.
Definition: DeclCXX.h:2772
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(), Expr *TrailingRequiresClause=nullptr)
Definition: DeclCXX.cpp:2723
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2862
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition: DeclCXX.h:2902
Represents a C++ base or member initializer.
Definition: DeclCXX.h:2300
bool isWritten() const
Determine whether this initializer is explicitly written in the source code.
Definition: DeclCXX.h:2472
SourceRange getSourceRange() const LLVM_READONLY
Determine the source range covering the entire initializer.
Definition: DeclCXX.cpp:2672
SourceLocation getSourceLocation() const
Determine the source location of the initializer.
Definition: DeclCXX.cpp:2659
FieldDecl * getAnyMember() const
Definition: DeclCXX.h:2446
A use of a default initializer in a constructor or in aggregate initialization.
Definition: ExprCXX.h:1371
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2799
static CXXDestructorDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, bool UsesFPIntrin, bool isInline, bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind, Expr *TrailingRequiresClause=nullptr)
Definition: DeclCXX.cpp:2857
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:1733
Represents a call to a member function that may be written either with member call syntax (e....
Definition: ExprCXX.h:176
CXXMethodDecl * getMethodDecl() const
Retrieve the declaration of the called method.
Definition: ExprCXX.cpp:673
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2060
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:2455
bool isImplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An implicit object member function is a non-static member function without an exp...
Definition: DeclCXX.cpp:2462
bool isVirtual() const
Definition: DeclCXX.h:2115
unsigned getNumExplicitParams() const
Definition: DeclCXX.h:2214
bool isVolatile() const
Definition: DeclCXX.h:2113
CXXMethodDecl * getMostRecentDecl()
Definition: DeclCXX.h:2163
overridden_method_range overridden_methods() const
Definition: DeclCXX.cpp:2534
unsigned size_overridden_methods() const
Definition: DeclCXX.cpp:2528
RefQualifierKind getRefQualifier() const
Retrieve the ref-qualifier associated with this method.
Definition: DeclCXX.h:2236
method_iterator begin_overridden_methods() const
Definition: DeclCXX.cpp:2518
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2186
bool isInstance() const
Definition: DeclCXX.h:2087
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition: DeclCXX.cpp:2488
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, Expr *TrailingRequiresClause=nullptr)
Definition: DeclCXX.cpp:2274
QualType getFunctionObjectParameterType() const
Definition: DeclCXX.h:2210
bool isStatic() const
Definition: DeclCXX.cpp:2186
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition: DeclCXX.cpp:2466
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:2156
The null pointer literal (C++11 [lex.nullptr])
Definition: ExprCXX.h:765
A call to an overloaded operator written using operator syntax.
Definition: ExprCXX.h:81
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:1271
friend_range friends() const
Definition: DeclFriend.h:246
bool hasTrivialMoveAssignment() const
Determine whether this class has a trivial move assignment operator (C++11 [class....
Definition: DeclCXX.h:1342
bool isTriviallyCopyable() const
Determine whether this class is considered trivially copyable per (C++11 [class]p6).
Definition: DeclCXX.cpp:576
bool hasTrivialDefaultConstructor() const
Determine whether this class has a trivial default constructor (C++11 [class.ctor]p5).
Definition: DeclCXX.h:1241
bool isGenericLambda() const
Determine whether this class describes a generic lambda function object (i.e.
Definition: DeclCXX.cpp:1564
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
Definition: DeclCXX.h:1367
bool hasUserDeclaredDestructor() const
Determine whether this class has a user-declared destructor.
Definition: DeclCXX.h:1005
bool implicitCopyConstructorHasConstParam() const
Determine whether an implicit copy constructor for this type would have a parameter with a const-qual...
Definition: DeclCXX.h:831
bool defaultedDestructorIsDeleted() const
true if a defaulted destructor for this class would be deleted.
Definition: DeclCXX.h:725
bool hasInheritedAssignment() const
Determine whether this class has a using-declaration that names a base class assignment operator.
Definition: DeclCXX.h:1421
bool allowConstDefaultInit() const
Determine whether declaring a const variable with this type is ok per core issue 253.
Definition: DeclCXX.h:1392
bool hasTrivialDestructorForCall() const
Definition: DeclCXX.h:1371
bool defaultedMoveConstructorIsDeleted() const
true if a defaulted move constructor for this class would be deleted.
Definition: DeclCXX.h:717
bool isLiteral() const
Determine whether this class is a literal type.
Definition: DeclCXX.cpp:1390
bool hasUserDeclaredMoveAssignment() const
Determine whether this class has had a move assignment declared by the user.
Definition: DeclCXX.h:965
bool defaultedDestructorIsConstexpr() const
Determine whether a defaulted default constructor for this class would be constexpr.
Definition: DeclCXX.h:1357
base_class_range bases()
Definition: DeclCXX.h:619
bool hasAnyDependentBases() const
Determine whether this class has any dependent base classes which are not the current instantiation.
Definition: DeclCXX.cpp:569
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition: DeclCXX.h:1022
bool hasTrivialMoveConstructor() const
Determine whether this class has a trivial move constructor (C++11 [class.copy]p12)
Definition: DeclCXX.h:1302
bool needsImplicitDefaultConstructor() const
Determine if we need to declare a default constructor for this class.
Definition: DeclCXX.h:777
bool needsImplicitMoveConstructor() const
Determine whether this class should get an implicit move constructor or if any existing special membe...
Definition: DeclCXX.h:896
bool hasUserDeclaredCopyAssignment() const
Determine whether this class has a user-declared copy assignment operator.
Definition: DeclCXX.h:914
method_range methods() const
Definition: DeclCXX.h:661
CXXRecordDecl * getDefinition() const
Definition: DeclCXX.h:564
bool needsOverloadResolutionForCopyAssignment() const
Determine whether we need to eagerly declare a defaulted copy assignment operator for this class.
Definition: DeclCXX.h:935
static AccessSpecifier MergeAccess(AccessSpecifier PathAccess, AccessSpecifier DeclAccess)
Calculates the access of a decl that is reached along a path.
Definition: DeclCXX.h:1723
bool defaultedDefaultConstructorIsConstexpr() const
Determine whether a defaulted default constructor for this class would be constexpr.
Definition: DeclCXX.h:1264
bool hasTrivialCopyConstructor() const
Determine whether this class has a trivial copy constructor (C++ [class.copy]p6, C++11 [class....
Definition: DeclCXX.h:1279
void setImplicitMoveAssignmentIsDeleted()
Set that we attempted to declare an implicit move assignment operator, but overload resolution failed...
Definition: DeclCXX.h:977
bool hasConstexprDestructor() const
Determine whether this class has a constexpr destructor.
Definition: DeclCXX.cpp:564
bool isPolymorphic() const
Whether this class is polymorphic (C++ [class.virtual]), which means that the class contains or inher...
Definition: DeclCXX.h:1215
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition: DeclCXX.h:613
bool defaultedCopyConstructorIsDeleted() const
true if a defaulted copy constructor for this class would be deleted.
Definition: DeclCXX.h:708
bool hasTrivialCopyConstructorForCall() const
Definition: DeclCXX.h:1283
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:692
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine whether this particular class is a specialization or instantiation of a class template or m...
Definition: DeclCXX.cpp:1905
bool hasTrivialCopyAssignment() const
Determine whether this class has a trivial copy assignment operator (C++ [class.copy]p11,...
Definition: DeclCXX.h:1329
base_class_range vbases()
Definition: DeclCXX.h:636
base_class_iterator vbases_begin()
Definition: DeclCXX.h:643
ctor_range ctors() const
Definition: DeclCXX.h:681
void setImplicitMoveConstructorIsDeleted()
Set that we attempted to declare an implicit move constructor, but overload resolution failed so we d...
Definition: DeclCXX.h:878
bool isAbstract() const
Determine whether this class has a pure virtual function.
Definition: DeclCXX.h:1222
bool hasVariantMembers() const
Determine whether this class has any variant members.
Definition: DeclCXX.h:1237
void setImplicitCopyConstructorIsDeleted()
Set that we attempted to declare an implicit copy constructor, but overload resolution failed so we d...
Definition: DeclCXX.h:869
bool isDynamicClass() const
Definition: DeclCXX.h:585
bool hasInClassInitializer() const
Whether this class has any in-class initializers for non-static data members (including those in anon...
Definition: DeclCXX.h:1152
bool needsImplicitCopyConstructor() const
Determine whether this class needs an implicit copy constructor to be lazily declared.
Definition: DeclCXX.h:810
bool hasIrrelevantDestructor() const
Determine whether this class has a destructor which has no semantic effect.
Definition: DeclCXX.h:1403
bool hasNonTrivialCopyConstructorForCall() const
Definition: DeclCXX.h:1294
bool hasDirectFields() const
Determine whether this class has direct non-static data members.
Definition: DeclCXX.h:1208
bool hasUserDeclaredCopyConstructor() const
Determine whether this class has a user-declared copy constructor.
Definition: DeclCXX.h:804
bool hasDefinition() const
Definition: DeclCXX.h:571
void setImplicitCopyAssignmentIsDeleted()
Set that we attempted to declare an implicit copy assignment operator, but overload resolution failed...
Definition: DeclCXX.h:920
bool needsImplicitDestructor() const
Determine whether this class needs an implicit destructor to be lazily declared.
Definition: DeclCXX.h:1011
ClassTemplateDecl * getDescribedClassTemplate() const
Retrieves the class template that is described by this class declaration.
Definition: DeclCXX.cpp:1897
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:906
bool needsOverloadResolutionForMoveAssignment() const
Determine whether we need to eagerly declare a move assignment operator for this class.
Definition: DeclCXX.h:998
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
Definition: DeclCXX.cpp:1975
bool hasNonTrivialDestructorForCall() const
Definition: DeclCXX.h:1381
bool needsOverloadResolutionForDestructor() const
Determine whether we need to eagerly declare a destructor for this class.
Definition: DeclCXX.h:1017
bool hasInheritedConstructor() const
Determine whether this class has a using-declaration that names a user-declared base class constructo...
Definition: DeclCXX.h:1415
CXXMethodDecl * getLambdaStaticInvoker() const
Retrieve the lambda static invoker, the address of which is returned by the conversion operator,...
Definition: DeclCXX.cpp:1606
bool needsOverloadResolutionForCopyConstructor() const
Determine whether we need to eagerly declare a defaulted copy constructor for this class.
Definition: DeclCXX.h:816
bool hasUserDeclaredMoveConstructor() const
Determine whether this class has had a move constructor declared by the user.
Definition: DeclCXX.h:857
bool needsImplicitMoveAssignment() const
Determine whether this class should get an implicit move assignment operator or if any existing speci...
Definition: DeclCXX.h:987
bool isInterfaceLike() const
Definition: DeclCXX.cpp:2004
bool needsImplicitCopyAssignment() const
Determine whether this class needs an implicit copy assignment operator to be lazily declared.
Definition: DeclCXX.h:929
bool hasTrivialMoveConstructorForCall() const
Definition: DeclCXX.h:1307
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition: DeclCXX.cpp:1594
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:523
unsigned getNumVBases() const
Retrieves the number of virtual base classes of this class.
Definition: DeclCXX.h:634
bool isDerivedFrom(const CXXRecordDecl *Base) const
Determine whether this class is derived from the class Base.
bool implicitCopyAssignmentHasConstParam() const
Determine whether an implicit copy assignment operator for this type would have a parameter with a co...
Definition: DeclCXX.h:950
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:74
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition: DeclSpec.h:210
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition: DeclSpec.h:215
void MakeTrivial(ASTContext &Context, NestedNameSpecifier *Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
Definition: DeclSpec.cpp:126
SourceRange getRange() const
Definition: DeclSpec.h:80
SourceLocation getBeginLoc() const
Definition: DeclSpec.h:84
bool isSet() const
Deprecated.
Definition: DeclSpec.h:228
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
Definition: DeclSpec.cpp:152
NestedNameSpecifier * getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition: DeclSpec.h:95
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition: DeclSpec.h:213
bool isEmpty() const
No scope specifier.
Definition: DeclSpec.h:208
Represents the this expression in C++.
Definition: ExprCXX.h:1148
SourceLocation getBeginLoc() const
Definition: ExprCXX.h:1168
bool isImplicit() const
Definition: ExprCXX.h:1171
SourceLocation getLocation() const
Definition: ExprCXX.h:1165
CXXTryStmt - A C++ try block, including all handlers.
Definition: StmtCXX.h:69
CXXCatchStmt * getHandler(unsigned i)
Definition: StmtCXX.h:108
unsigned getNumHandlers() const
Definition: StmtCXX.h:107
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2820
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: Expr.h:3011
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition: Expr.h:2990
bool isCallToStdMove() const
Definition: Expr.cpp:3510
Expr * getCallee()
Definition: Expr.h:2970
arg_range arguments()
Definition: Expr.h:3059
CanQual< T > getUnqualifiedType() const
Retrieve the unqualified form of this type.
CanProxy< U > getAs() const
Retrieve a canonical type pointer with a different static type, upcasting or downcasting as needed.
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
Definition: CanonicalType.h:83
CastKind getCastKind() const
Definition: Expr.h:3527
Expr * getSubExpr()
Definition: Expr.h:3533
static CharSourceRange getTokenRange(SourceRange R)
SourceLocation getBegin() const
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.
ClassTemplateDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this 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
const ComparisonCategoryInfo & getInfoForType(QualType Ty) const
Return the comparison category information as specified by getCategoryForType(Ty).
const ComparisonCategoryInfo * lookupInfo(ComparisonCategoryType Kind) const
Return the cached comparison category information for the specified 'Kind'.
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.
const ValueInfo * getValueInfo(ComparisonCategoryResult ValueKind) const
ComparisonCategoryType Kind
The Kind of the comparison category type.
Complex values, per C99 6.2.5p11.
Definition: Type.h:3086
QualType getElementType() const
Definition: Type.h:3096
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition: Stmt.h:1606
body_range body()
Definition: Stmt.h:1664
static CompoundStmt * Create(const ASTContext &C, ArrayRef< Stmt * > Stmts, FPOptionsOverride FPFeatures, SourceLocation LB, SourceLocation RB)
Definition: Stmt.cpp:383
ConditionalOperator - The ?: ternary operator.
Definition: Expr.h:4179
ConstStmtVisitor - This class implements a simple visitor for Stmt subclasses.
Definition: StmtVisitor.h:195
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:3556
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition: Type.h:3612
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition: ASTConcept.h:35
Represents a shadow constructor declaration introduced into a class by a C++11 using-declaration that...
Definition: DeclCXX.h:3598
const CXXRecordDecl * getParent() const
Returns the parent of this using shadow declaration, which is the class in which this is declared.
Definition: DeclCXX.h:3662
static ConstructorUsingShadowDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation Loc, UsingDecl *Using, NamedDecl *Target, bool IsVirtual)
Definition: DeclCXX.cpp:3124
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:1369
specific_decl_iterator - Iterates over a subrange of declarations stored in a DeclContext,...
Definition: DeclBase.h:2342
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1436
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2066
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition: DeclBase.h:2191
bool isFileContext() const
Definition: DeclBase.h:2137
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
Definition: DeclBase.cpp:1993
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1282
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition: DeclBase.h:2082
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1802
bool isTranslationUnit() const
Definition: DeclBase.h:2142
bool isRecord() const
Definition: DeclBase.h:2146
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1938
void removeDecl(Decl *D)
Removes a declaration from this context.
Definition: DeclBase.cpp:1635
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1716
decl_iterator decls_end() const
Definition: DeclBase.h:2324
bool isStdNamespace() const
Definition: DeclBase.cpp:1266
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:2322
bool isFunctionOrMethod() const
Definition: DeclBase.h:2118
const LinkageSpecDecl * getExternCContext() const
Retrieve the nearest enclosing C linkage specification context.
Definition: DeclBase.cpp:1337
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context encloses the declaration context DC.
Definition: DeclBase.cpp:1352
void addHiddenDecl(Decl *D)
Add the declaration D to this context without modifying any lookup tables.
Definition: DeclBase.cpp:1690
Decl::Kind getDeclKind() const
Definition: DeclBase.h:2059
DeclContext * getNonTransparentContext()
Definition: DeclBase.cpp:1363
decl_iterator decls_begin() const
Definition: DeclBase.cpp:1572
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1260
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:551
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:488
ValueDecl * getDecl()
Definition: Expr.h:1328
NonOdrUseReason isNonOdrUse() const
Is this expression a non-odr-use reference, and if so, why?
Definition: Expr.h:1452
bool isImmediateEscalating() const
Definition: Expr.h:1462
Captures information about "declaration specifiers".
Definition: DeclSpec.h:247
bool isVirtualSpecified() const
Definition: DeclSpec.h:645
bool isModulePrivateSpecified() const
Definition: DeclSpec.h:826
bool hasTypeSpecifier() const
Return true if any type-specifier has been found.
Definition: DeclSpec.h:688
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:641
Expr * getPackIndexingExpr() const
Definition: DeclSpec.h:557
void ClearStorageClassSpecs()
Definition: DeclSpec.h:512
TST getTypeSpecType() const
Definition: DeclSpec.h:534
SourceLocation getStorageClassSpecLoc() const
Definition: DeclSpec.h:507
SCS getStorageClassSpec() const
Definition: DeclSpec.h:498
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:572
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclSpec.h:571
unsigned getTypeQualifiers() const
getTypeQualifiers - Return a set of TQs.
Definition: DeclSpec.h:613
SourceLocation getExplicitSpecLoc() const
Definition: DeclSpec.h:651
SourceLocation getFriendSpecLoc() const
Definition: DeclSpec.h:824
ParsedType getRepAsType() const
Definition: DeclSpec.h:544
TSCS getThreadStorageClassSpec() const
Definition: DeclSpec.h:499
bool isFriendSpecifiedFirst() const
Definition: DeclSpec.h:822
ParsedAttributes & getAttributes()
Definition: DeclSpec.h:870
SourceLocation getEllipsisLoc() const
Definition: DeclSpec.h:620
SourceLocation getConstSpecLoc() const
Definition: DeclSpec.h:614
SourceRange getExplicitSpecRange() const
Definition: DeclSpec.h:652
Expr * getRepAsExpr() const
Definition: DeclSpec.h:552
bool isInlineSpecified() const
Definition: DeclSpec.h:634
SourceLocation getRestrictSpecLoc() const
Definition: DeclSpec.h:615
bool SetTypeQual(TQ T, SourceLocation Loc)
Definition: DeclSpec.cpp:1013
void ClearConstexprSpec()
Definition: DeclSpec.h:838
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:558
SourceLocation getThreadStorageClassSpecLoc() const
Definition: DeclSpec.h:508
SourceLocation getAtomicSpecLoc() const
Definition: DeclSpec.h:617
SourceLocation getVirtualSpecLoc() const
Definition: DeclSpec.h:646
SourceLocation getConstexprSpecLoc() const
Definition: DeclSpec.h:833
SourceLocation getTypeSpecTypeLoc() const
Definition: DeclSpec.h:579
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:453
SourceLocation getInlineSpecLoc() const
Definition: DeclSpec.h:637
SourceLocation getUnalignedSpecLoc() const
Definition: DeclSpec.h:618
SourceLocation getVolatileSpecLoc() const
Definition: DeclSpec.h:616
FriendSpecified isFriendSpecified() const
Definition: DeclSpec.h:818
bool hasExplicitSpecifier() const
Definition: DeclSpec.h:648
bool hasConstexprSpecifier() const
Definition: DeclSpec.h:834
static const TST TST_auto
Definition: DeclSpec.h:318
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Definition: Stmt.h:1497
decl_range decls()
Definition: Stmt.h:1545
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.h:1523
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:1051
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclBase.h:441
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition: DeclBase.h:1216
T * getAttr() const
Definition: DeclBase.h:579
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:501
void addAttr(Attr *A)
Definition: DeclBase.cpp:991
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:599
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:132
Kind
Lists the kind of concrete classes of Decl.
Definition: DeclBase.h:89
void clearIdentifierNamespace()
Clears the namespace of this declaration.
Definition: DeclBase.h:1204
void markUsed(ASTContext &C)
Mark the declaration used, in the sense of odr-use.
Definition: DeclBase.cpp:545
@ FOK_Undeclared
A friend of a previously-undeclared entity.
Definition: DeclBase.h:1209
@ FOK_None
Not a friend object.
Definition: DeclBase.h:1207
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition: DeclBase.cpp:227
bool isTemplateParameter() const
isTemplateParameter - Determines whether this declaration is a template parameter.
Definition: DeclBase.h:2739
bool isInvalidDecl() const
Definition: DeclBase.h:594
unsigned getIdentifierNamespace() const
Definition: DeclBase.h:879
bool isLocalExternDecl() const
Determine whether this is a block-scope declaration with linkage.
Definition: DeclBase.h:1159
void setAccess(AccessSpecifier AS)
Definition: DeclBase.h:508
SourceLocation getLocation() const
Definition: DeclBase.h:445
@ IDNS_Ordinary
Ordinary names.
Definition: DeclBase.h:144
bool isTemplateParameterPack() const
isTemplateParameter - Determines whether this declaration is a template parameter pack.
Definition: DeclBase.cpp:210
void setLocalOwningModule(Module *M)
Definition: DeclBase.h:820
void setImplicit(bool I=true)
Definition: DeclBase.h:600
void setReferenced(bool R=true)
Definition: DeclBase.h:629
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required.
Definition: DeclBase.cpp:530
DeclContext * getDeclContext()
Definition: DeclBase.h:454
attr_range attrs() const
Definition: DeclBase.h:541
AccessSpecifier getAccess() const
Definition: DeclBase.h:513
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclBase.h:437
void dropAttr()
Definition: DeclBase.h:562
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:908
bool hasAttr() const
Definition: DeclBase.h:583
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:968
@ VisibleWhenImported
This declaration has an owning module, and is visible when that module is imported.
void setModuleOwnershipKind(ModuleOwnershipKind MOK)
Set whether this declaration is hidden from name lookup.
Definition: DeclBase.h:871
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition: DeclBase.h:433
DeclarationName getCXXDestructorName(CanQualType Ty)
Returns the name of a C++ destructor for the given Type.
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
Get the name of the overloadable C++ operator corresponding to Op.
DeclarationName getCXXConstructorName(CanQualType Ty)
Returns the name of a C++ constructor for the given Type.
The name of a declaration.
IdentifierInfo * getAsIdentifierInfo() const
Retrieve the IdentifierInfo * stored in this declaration name, or null if this declaration name isn't...
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:770
SourceLocation getTypeSpecStartLoc() const
Definition: Decl.cpp:1985
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:822
unsigned getNumTemplateParameterLists() const
Definition: Decl.h:858
void setTypeSourceInfo(TypeSourceInfo *TI)
Definition: Decl.h:805
Expr * getTrailingRequiresClause()
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition: Decl.h:846
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:799
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1900
bool isFunctionDeclarator(unsigned &idx) const
isFunctionDeclarator - This method returns true if the declarator is a function declarator (looking t...
Definition: DeclSpec.h:2456
bool isDeclarationOfFunction() const
Determine whether the declaration that will be produced from this declaration will be a function.
Definition: DeclSpec.cpp:325
const DeclaratorChunk & getTypeObject(unsigned i) const
Return the specified TypeInfo from this declarator.
Definition: DeclSpec.h:2398
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition: DeclSpec.h:2047
bool isFunctionDeclarationContext() const
Return true if this declaration appears in a context where a function declarator would be a function ...
Definition: DeclSpec.h:2510
SourceLocation getIdentifierLoc() const
Definition: DeclSpec.h:2336
void SetIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Set the name of this declarator to be the given identifier.
Definition: DeclSpec.h:2339
type_object_range type_objects() const
Returns the range of type objects, from the identifier outwards.
Definition: DeclSpec.h:2411
bool hasGroupingParens() const
Definition: DeclSpec.h:2719
void setInvalidType(bool Val=true)
Definition: DeclSpec.h:2713
unsigned getNumTypeObjects() const
Return the number of types applied to this declarator.
Definition: DeclSpec.h:2394
bool isRedeclaration() const
Definition: DeclSpec.h:2765
DeclaratorContext getContext() const
Definition: DeclSpec.h:2072
const DecompositionDeclarator & getDecompositionDeclarator() const
Definition: DeclSpec.h:2068
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:2083
bool isFunctionDefinition() const
Definition: DeclSpec.h:2737
UnqualifiedId & getName()
Retrieve the name specified by this declarator.
Definition: DeclSpec.h:2066
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition: DeclSpec.h:2062
ArrayRef< TemplateParameterList * > getTemplateParameterLists() const
The template parameter lists that preceded the declarator.
Definition: DeclSpec.h:2649
void setInventedTemplateParameterList(TemplateParameterList *Invented)
Sets the template parameter list generated from the explicit template parameters along with any inven...
Definition: DeclSpec.h:2656
bool mayHaveDecompositionDeclarator() const
Return true if the context permits a C++17 decomposition declarator.
Definition: DeclSpec.h:2211
bool isInvalidType() const
Definition: DeclSpec.h:2714
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition: DeclSpec.h:2082
bool isDecompositionDeclarator() const
Return whether this declarator is a decomposition declarator.
Definition: DeclSpec.h:2326
bool isStaticMember()
Returns true if this declares a static member.
Definition: DeclSpec.cpp:416
DeclSpec & getMutableDeclSpec()
getMutableDeclSpec - Return a non-const version of the DeclSpec.
Definition: DeclSpec.h:2054
DeclaratorChunk::FunctionTypeInfo & getFunctionTypeInfo()
getFunctionTypeInfo - Retrieves the function type info object (looking through parentheses).
Definition: DeclSpec.h:2487
const IdentifierInfo * getIdentifier() const
Definition: DeclSpec.h:2330
A decomposition declaration.
Definition: DeclCXX.h:4166
ArrayRef< BindingDecl * > bindings() const
Definition: DeclCXX.h:4198
A parsed C++17 decomposition declarator of the form '[' identifier-list ']'.
Definition: DeclSpec.h:1789
ArrayRef< Binding > bindings() const
Definition: DeclSpec.h:1828
SourceRange getSourceRange() const
Definition: DeclSpec.h:1836
SourceLocation getLSquareLoc() const
Definition: DeclSpec.h:1834
Represents a C++17 deduced template specialization type.
Definition: Type.h:6029
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:2423
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2403
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2412
A little helper class (which is basically a smart pointer that forwards info from DiagnosticsEngine) ...
Definition: Diagnostic.h:1571
bool isLastDiagnosticIgnored() const
Determine whether the previous diagnostic was ignored.
Definition: Diagnostic.h:770
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:916
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2323
TypeLoc getNamedTypeLoc() const
Definition: TypeLoc.h:2361
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2337
static EmptyDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L)
Definition: Decl.cpp:5629
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:3297
Represents an enum.
Definition: Decl.h:3867
enumerator_range enumerators() const
Definition: Decl.h:4000
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:5575
EvaluatedExprVisitor - This class visits 'Expr *'s.
Store information needed for an explicit specifier.
Definition: DeclCXX.h:1897
const Expr * getExpr() const
Definition: DeclCXX.h:1906
void setExpr(Expr *E)
Definition: DeclCXX.h:1931
void setKind(ExplicitSpecKind Kind)
Definition: DeclCXX.h:1930
This represents one expression.
Definition: Expr.h:110
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:175
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition: Expr.h:192
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition: Expr.cpp:3059
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3047
bool containsErrors() const
Whether this expression contains subexpressions which had errors, e.g.
Definition: Expr.h:245
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3055
bool isPRValue() const
Definition: Expr.h:278
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition: Expr.h:277
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:3193
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:277
QualType getType() const
Definition: Expr.h:142
Represents difference between two FPOptions values.
Definition: LangOptions.h:915
Represents a member of a struct/union/class.
Definition: Decl.h:3057
Expr * getInClassInitializer() const
Get the C++11 default member initializer for this member, or null if one has not been set.
Definition: Decl.cpp:4570
bool hasInClassInitializer() const
Determine whether this member has a C++11 default member initializer.
Definition: Decl.h:3218
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition: Decl.cpp:4644
bool isAnonymousStructOrUnion() const
Determines whether this field is a representative for an anonymous struct or union.
Definition: Decl.cpp:4560
InClassInitStyle getInClassInitStyle() const
Get the kind of (C++11) default member initializer that this field has.
Definition: Decl.h:3212
void removeInClassInitializer()
Remove the C++11 in-class initializer from this member.
Definition: Decl.h:3241
void setInClassInitializer(Expr *NewInit)
Set the C++11 in-class initializer for this member.
Definition: Decl.cpp:4580
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3270
FieldDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this field.
Definition: Decl.h:3281
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:71
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:110
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:134
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:123
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:97
FriendDecl - Represents the declaration of a friend entity, which can be a function,...
Definition: DeclFriend.h:54
static FriendDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, FriendUnion Friend_, SourceLocation FriendL, ArrayRef< TemplateParameterList * > FriendTypeTPLists=std::nullopt)
Definition: DeclFriend.cpp:34
void setUnsupportedFriend(bool Unsupported)
Definition: DeclFriend.h:176
static FriendTemplateDecl * Create(ASTContext &Context, DeclContext *DC, SourceLocation Loc, MutableArrayRef< TemplateParameterList * > Params, FriendUnion Friend, SourceLocation FriendLoc)
static DefaultedOrDeletedFunctionInfo * Create(ASTContext &Context, ArrayRef< DeclAccessPair > Lookups, StringLiteral *DeletedMessage=nullptr)
Definition: Decl.cpp:3096
Represents a function declaration or definition.
Definition: Decl.h:1971
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2706
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition: Decl.cpp:3236
ExceptionSpecificationType getExceptionSpecType() const
Gets the ExceptionSpecificationType as declared.
Definition: Decl.h:2778
bool isTrivialForCall() const
Definition: Decl.h:2342
ConstexprSpecKind getConstexprKind() const
Definition: Decl.h:2438
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to call this function.
Definition: Decl.cpp:3713
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition: Decl.cpp:4054
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition: Decl.cpp:4042
void setIsPureVirtual(bool P=true)
Definition: Decl.cpp:3255
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
Definition: Decl.h:2283
bool isImmediateFunction() const
Definition: Decl.cpp:3288
void setDefaultedOrDeletedInfo(DefaultedOrDeletedFunctionInfo *Info)
Definition: Decl.cpp:3117
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type.
Definition: Decl.cpp:3873
bool isDestroyingOperatorDelete() const
Determine whether this is a destroying operator delete.
Definition: Decl.cpp:3474
bool hasCXXExplicitFunctionObjectParameter() const
Definition: Decl.cpp:3731
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition: Decl.h:2830
SourceLocation getDefaultLoc() const
Definition: Decl.h:2360
QualType getReturnType() const
Definition: Decl.h:2754
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2683
bool isExplicitlyDefaulted() const
Whether this function is explicitly defaulted.
Definition: Decl.h:2351
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition: Decl.h:2339
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition: Decl.cpp:4162
MutableArrayRef< ParmVarDecl * >::iterator param_iterator
Definition: Decl.h:2691
void setWillHaveBody(bool V=true)
Definition: Decl.h:2596
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:3617
FunctionTypeLoc getFunctionTypeLoc() const
Find the source location information for how the type of this function was written.
Definition: Decl.cpp:3867
param_iterator param_begin()
Definition: Decl.h:2695
const ParmVarDecl * getNonObjectParameter(unsigned I) const
Definition: Decl.h:2732
bool isVariadic() const
Whether this function is variadic.
Definition: Decl.cpp:3089
bool doesThisDeclarationHaveABody() const
Returns whether this specific declaration of the function has a body.
Definition: Decl.h:2295
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:2502
void setBodyContainsImmediateEscalatingExpressions(bool Set)
Definition: Decl.h:2448
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition: Decl.cpp:4178
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition: Decl.cpp:4106
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:2797
bool isStatic() const
Definition: Decl.h:2838
void setTrivial(bool IT)
Definition: Decl.h:2340
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition: Decl.cpp:3993
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:2432
bool isPureVirtual() const
Whether this virtual function is pure, i.e.
Definition: Decl.h:2322
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition: Decl.cpp:3492
bool isImmediateEscalating() const
Definition: Decl.cpp:3268
bool isMain() const
Determines whether this function is "main", which is the entry point into an executable program.
Definition: Decl.cpp:3306
void setImplicitlyInline(bool I=true)
Flag that this function is implicitly inline.
Definition: Decl.h:2825
bool isThisDeclarationInstantiatedFromAFriendDefinition() const
Determine whether this specific declaration of the function is a friend declaration that was instanti...
Definition: Decl.cpp:3180
void setRangeEnd(SourceLocation E)
Definition: Decl.h:2189
bool isDefaulted() const
Whether this function is defaulted.
Definition: Decl.h:2347
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:4395
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
Definition: Decl.h:2842
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition: Decl.cpp:3979
void setConstexprKind(ConstexprSpecKind CSK)
Definition: Decl.h:2435
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition: Decl.cpp:4266
void setDefaulted(bool D=true)
Definition: Decl.h:2348
bool isConsteval() const
Definition: Decl.h:2444
bool isUserProvided() const
True if this method is user-declared and was not deleted or defaulted on its first declaration.
Definition: Decl.h:2372
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:2771
void setBody(Stmt *B)
Definition: Decl.cpp:3248
bool isVirtualAsWritten() const
Whether this function is marked as virtual explicitly.
Definition: Decl.h:2313
bool hasOneParamOrDefaultArgs() const
Determine whether this function has a single parameter, or multiple parameters where all but the firs...
Definition: Decl.cpp:3745
void setDeletedAsWritten(bool D=true, StringLiteral *Message=nullptr)
Definition: Decl.cpp:3126
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3692
size_t param_size() const
Definition: Decl.h:2699
DeclarationNameInfo getNameInfo() const
Definition: Decl.h:2182
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition: Decl.cpp:3156
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:3203
bool isInlineSpecified() const
Determine whether the "inline" keyword was specified for this function.
Definition: Decl.h:2808
DefaultedOrDeletedFunctionInfo * getDefalutedOrDeletedInfo() const
Definition: Decl.cpp:3151
void setParams(ArrayRef< ParmVarDecl * > NewParamInfo)
Definition: Decl.h:2714
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition: Decl.h:2595
Represents a prototype with parameter type info, e.g.
Definition: Type.h:4656
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition: Type.h:5101
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition: Type.h:4915
unsigned getNumParams() const
Definition: Type.h:4889
bool hasTrailingReturn() const
Whether this function prototype has a trailing return type.
Definition: Type.h:5028
QualType getParamType(unsigned i) const
Definition: Type.h:4891
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:4900
Expr * getNoexceptExpr() const
Return the expression inside noexcept(expression), or a null pointer if there is none (because the ex...
Definition: Type.h:4973
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:4896
ArrayRef< QualType > exceptions() const
Definition: Type.h:5058
bool hasExtParameterInfos() const
Is there any interesting extra information for any of the parameters of this function type?
Definition: Type.h:5073
Declaration of a template function.
Definition: DeclTemplate.h:957
Wrapper for source info for functions.
Definition: TypeLoc.h:1428
unsigned getNumParams() const
Definition: TypeLoc.h:1500
ParmVarDecl * getParam(unsigned i) const
Definition: TypeLoc.h:1506
void setParam(unsigned i, ParmVarDecl *VD)
Definition: TypeLoc.h:1507
TypeLoc getReturnLoc() const
Definition: TypeLoc.h:1509
ExtInfo withCallingConv(CallingConv cc) const
Definition: Type.h:4482
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4256
CallingConv getCallConv() const
Definition: Type.h:4584
QualType getReturnType() const
Definition: Type.h:4573
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...
bool isPlaceholder() const
StringRef getName() const
Return the actual identifier string.
void RemoveDecl(NamedDecl *D)
RemoveDecl - Unlink the decl from its shadowed decl chain.
void AddDecl(NamedDecl *D)
AddDecl - Link the decl to its shadowed decl chain.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
IfStmt - This represents an if/then/else.
Definition: Stmt.h:2138
ImaginaryLiteral - We support imaginary integer and floating point literals, like "1....
Definition: Expr.h:1712
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:3655
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition: Expr.cpp:2074
Represents an implicitly-generated value initialization of an object of a given type.
Definition: Expr.h:5600
Represents a field injected from an anonymous union/struct into the parent scope.
Definition: Decl.h:3341
void setInherited(bool I)
Definition: Attr.h:154
Description of a constructor that was inherited from a base class.
Definition: DeclCXX.h:2506
ConstructorUsingShadowDecl * getShadowDecl() const
Definition: DeclCXX.h:2518
const TypeClass * getTypePtr() const
Definition: TypeLoc.h:514
Describes an C or C++ initializer list.
Definition: Expr.h:4847
unsigned getNumInits() const
Definition: Expr.h:4877
const Expr * getInit(unsigned Init) const
Definition: Expr.h:4893
child_range children()
Definition: Expr.h:5039
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.
Definition: SemaInit.cpp:8601
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.
Definition: SemaInit.cpp:3471
static InitializedEntity InitializeMember(FieldDecl *Member, const InitializedEntity *Parent=nullptr, bool Implicit=false)
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 InitializeDelegation(QualType Type)
Create the initialization entity for a delegated constructor.
The injected class name of a C++ class template or class template partial specialization.
Definition: Type.h:6221
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:977
Describes the capture of a variable or of this, or of a C++1y init-capture.
Definition: LambdaCapture.h:25
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1950
bool isInitCapture(const LambdaCapture *Capture) const
Determine whether one of this lambda's captures is an init-capture.
Definition: ExprCXX.cpp:1290
capture_range captures() const
Retrieve this lambda's captures.
Definition: ExprCXX.cpp:1303
@ Ver4
Attempt to be ABI-compatible with code generated by Clang 4.0.x (SVN r291814).
@ Ver14
Attempt to be ABI-compatible with code generated by Clang 14.0.x.
bool isCompatibleWithMSVC(MSVCMajorVersion MajorVersion) const
Definition: LangOptions.h:625
void push_back(const T &LocalValue)
iterator begin(Source *source, bool LocalOnly=false)
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:1024
Represents a linkage specification.
Definition: DeclCXX.h:2934
static LinkageSpecDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation ExternLoc, SourceLocation LangLoc, LinkageSpecLanguageIDs Lang, bool HasBraces)
Definition: DeclCXX.cpp:2920
void setRBraceLoc(SourceLocation L)
Definition: DeclCXX.h:2976
bool isLocalPackExpansion(const Decl *D)
Determine whether D is a pack expansion created in this scope.
A class for iterating through a result set and possibly filtering out results.
Definition: Lookup.h:675
void erase()
Erase the last element returned from this iterator.
Definition: Lookup.h:721
bool hasNext() const
Definition: Lookup.h:706
NamedDecl * next()
Definition: Lookup.h:710
Represents the results of name lookup.
Definition: Lookup.h:46
@ FoundOverloaded
Name lookup found a set of overloaded functions that met the criteria.
Definition: Lookup.h:63
@ FoundUnresolvedValue
Name lookup found an unresolvable value declaration and cannot yet complete.
Definition: Lookup.h:68
@ Ambiguous
Name lookup results in an ambiguity; use getAmbiguityKind to figure out what kind of ambiguity we hav...
Definition: Lookup.h:73
@ NotFound
No entity found met the criteria.
Definition: Lookup.h:50
@ NotFoundInCurrentInstantiation
No entity found met the criteria within the current instantiation,, but there were dependent base cla...
Definition: Lookup.h:55
@ Found
Name lookup found a single declaration that met the criteria.
Definition: Lookup.h:59
LLVM_ATTRIBUTE_REINITIALIZES void clear()
Clears out any current state.
Definition: Lookup.h:605
void setBaseObjectType(QualType T)
Sets the base object type for this lookup.
Definition: Lookup.h:469
DeclClass * getAsSingle() const
Definition: Lookup.h:558
void addDecl(NamedDecl *D)
Add a declaration to these results with its natural access.
Definition: Lookup.h:475
void setLookupName(DeclarationName Name)
Sets the name to look up.
Definition: Lookup.h:270
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.
Definition: SemaLookup.cpp:484
SourceLocation getNameLoc() const
Gets the location of the identifier.
Definition: Lookup.h:664
Filter makeFilter()
Create a filter for this result set.
Definition: Lookup.h:749
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition: Lookup.h:568
void setHideTags(bool Hide)
Sets whether tag declarations should be hidden by non-tag declarations during resolution.
Definition: Lookup.h:311
bool isAmbiguous() const
Definition: Lookup.h:324
NamedDecl * getAcceptableDecl(NamedDecl *D) const
Retrieve the accepted (re)declaration of the given declaration, if there is one.
Definition: Lookup.h:408
bool isSingleResult() const
Determines if this names a single result which is not an unresolved value using decl.
Definition: Lookup.h:331
Sema::LookupNameKind getLookupKind() const
Gets the kind of lookup to perform.
Definition: Lookup.h:275
NamedDecl * getRepresentativeDecl() const
Fetches a representative decl. Useful for lazy diagnostics.
Definition: Lookup.h:575
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition: Lookup.h:634
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
const DeclarationNameInfo & getLookupNameInfo() const
Gets the name info to look up.
Definition: Lookup.h:255
An instance of this class represents the declaration of a property member.
Definition: DeclCXX.h:4235
static MSPropertyDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName N, QualType T, TypeSourceInfo *TInfo, SourceLocation StartL, IdentifierInfo *Getter, IdentifierInfo *Setter)
Definition: DeclCXX.cpp:3401
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:3172
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition: Expr.h:3255
Expr * getBase() const
Definition: Expr.h:3249
SourceLocation getExprLoc() const LLVM_READONLY
Definition: Expr.h:3367
Wrapper for source info for member pointers.
Definition: TypeLoc.h:1332
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3460
Describes a module or submodule.
Definition: Module.h:105
StringRef getTopLevelModuleName() const
Retrieve the name of the top-level module.
Definition: Module.h:676
bool isExplicitGlobalModule() const
Definition: Module.h:203
This represents a decl that may have a name.
Definition: Decl.h:249
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition: Decl.h:462
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:270
bool isPlaceholderVar(const LangOptions &LangOpts) const
Definition: Decl.cpp:1082
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:315
void setModulePrivate()
Specify that this declaration was marked as being private to the module in which it was defined.
Definition: DeclBase.h:686
bool isCXXClassMember() const
Determine whether this declaration is a C++ class member.
Definition: Decl.h:372
Represents a C++ namespace alias.
Definition: DeclCXX.h:3120
static NamespaceAliasDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation NamespaceLoc, SourceLocation AliasLoc, IdentifierInfo *Alias, NestedNameSpecifierLoc QualifierLoc, SourceLocation IdentLoc, NamedDecl *Namespace)
Definition: DeclCXX.cpp:3038
Represent a C++ namespace.
Definition: Decl.h:547
bool isInline() const
Returns true if this is an inline namespace declaration.
Definition: Decl.h:610
static NamespaceDecl * Create(ASTContext &C, DeclContext *DC, bool Inline, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, NamespaceDecl *PrevDecl, bool Nested)
Definition: DeclCXX.cpp:2982
NamespaceDecl * getAnonymousNamespace() const
Retrieve the anonymous namespace nested inside this namespace, if any.
Definition: Decl.h:665
void setRBraceLoc(SourceLocation L)
Definition: Decl.h:688
Class that aids in the construction of nested-name-specifiers along with source-location information ...
A C++ nested-name-specifier augmented with source location information.
SourceRange getSourceRange() const LLVM_READONLY
Retrieve the source range covering the entirety of this nested-name-specifier.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
bool isDependent() const
Whether this nested name specifier refers to a dependent type or not.
static NestedNameSpecifier * Create(const ASTContext &Context, NestedNameSpecifier *Prefix, const IdentifierInfo *II)
Builds a specifier combining a prefix and an identifier.
@ Global
The global specifier '::'. There is no stored value.
bool containsUnexpandedParameterPack() const
Whether this nested-name-specifier contains an unexpanded parameter pack (for C++11 variadic template...
const Type * getAsType() const
Retrieve the type stored in this nested name specifier.
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:80
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition: Expr.h:1168
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition: Overload.h:980
@ CSK_Normal
Normal lookup.
Definition: Overload.h:984
@ CSK_Operator
C++ [over.match.oper]: Lookup of operator function candidates in a call using operator syntax.
Definition: Overload.h:991
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition: Overload.h:1153
MapType::iterator iterator
MapType::const_iterator const_iterator
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition: Attr.h:250
static ParenListExpr * Create(const ASTContext &Ctx, SourceLocation LParenLoc, ArrayRef< Expr * > Exprs, SourceLocation RParenLoc)
Create a paren list.
Definition: Expr.cpp:4728
Represents a parameter to a function.
Definition: Decl.h:1761
void setDefaultArg(Expr *defarg)
Definition: Decl.cpp:2980
SourceLocation getExplicitObjectParamThisLoc() const
Definition: Decl.h:1857
void setUnparsedDefaultArg()
Specify that this parameter has an unparsed default argument.
Definition: Decl.h:1902
bool hasUnparsedDefaultArg() const
Determines whether this parameter has a default argument that has not yet been parsed.
Definition: Decl.h:1890
SourceRange getDefaultArgRange() const
Retrieve the source range that covers the entire default argument.
Definition: Decl.cpp:2985
void setUninstantiatedDefaultArg(Expr *arg)
Definition: Decl.cpp:3005
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition: Decl.h:1794
bool hasUninstantiatedDefaultArg() const
Definition: Decl.h:1894
bool hasInheritedDefaultArg() const
Definition: Decl.h:1906
bool isExplicitObjectParameter() const
Definition: Decl.h:1849
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:2915
Expr * getDefaultArg()
Definition: Decl.cpp:2968
Expr * getUninstantiatedDefaultArg()
Definition: Decl.cpp:3010
bool hasDefaultArg() const
Determines whether this parameter has a default argument, either parsed or not.
Definition: Decl.cpp:3016
void setHasInheritedDefaultArg(bool I=true)
Definition: Decl.h:1910
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:2938
ParsedAttr - Represents a syntactic attribute.
Definition: ParsedAttr.h:129
IdentifierInfo * getPropertyDataSetter() const
Definition: ParsedAttr.h:487
IdentifierInfo * getPropertyDataGetter() const
Definition: ParsedAttr.h:481
static const ParsedAttributesView & none()
Definition: ParsedAttr.h:838
const ParsedAttr * getMSPropertyAttr() const
Definition: ParsedAttr.h:924
bool hasAttribute(ParsedAttr::Kind K) const
Definition: ParsedAttr.h:918
Wrapper for source info for pointers.
Definition: TypeLoc.h:1301
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3139
QualType getPointeeType() const
Definition: Type.h:3149
IdentifierInfo * getIdentifierInfo(StringRef Name) const
Return information about the specified preprocessor identifier token.
IdentifierTable & getIdentifierTable()
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition: Expr.h:6305
ArrayRef< Expr * > semantics()
Definition: Expr.h:6384
A (possibly-)qualified type.
Definition: Type.h:940
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:7443
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:7448
QualType withConst() const
Definition: Type.h:1154
QualType getLocalUnqualifiedType() const
Return this type with all of the instance-specific qualifiers removed, but without removing any quali...
Definition: Type.h:1220
void addConst()
Add the const type qualifier to this QualType.
Definition: Type.h:1151
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:1007
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7399
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1432
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition: Type.h:7560
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:7453
bool isWebAssemblyReferenceType() const
Returns true if it is a WebAssembly Reference Type.
Definition: Type.cpp:2849
unsigned getLocalCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers local to this particular QualType instan...
Definition: Type.h:1092
bool isMoreQualifiedThan(QualType Other) const
Determine whether this type is more qualified than the other given type, requiring exact equality for...
Definition: Type.h:7531
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:7432
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition: Type.h:7405
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: Type.h:1327
bool hasNonTrivialObjCLifetime() const
Definition: Type.h:1436
bool isPODType(const ASTContext &Context) const
Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
Definition: Type.cpp:2582
The collection of all-type qualifiers we support.
Definition: Type.h:318
void addAddressSpace(LangAS space)
Definition: Type.h:583
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition: Type.h:350
void removeConst()
Definition: Type.h:445
void removeAddressSpace()
Definition: Type.h:582
void addConst()
Definition: Type.h:446
void removeVolatile()
Definition: Type.h:455
LangAS getAddressSpace() const
Definition: Type.h:557
An rvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3442
Represents a struct/union/class.
Definition: Decl.h:4168
bool hasFlexibleArrayMember() const
Definition: Decl.h:4201
field_iterator field_end() const
Definition: Decl.h:4377
field_range fields() const
Definition: Decl.h:4374
bool isInjectedClassName() const
Determines whether this declaration represents the injected class name.
Definition: Decl.cpp:5035
bool isAnonymousStructOrUnion() const
Whether this is an anonymous struct or union.
Definition: Decl.h:4220
bool field_empty() const
Definition: Decl.h:4382
field_iterator field_begin() const
Definition: Decl.cpp:5069
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5549
RecordDecl * getDecl() const
Definition: Type.h:5559
A class that does preorder or postorder depth-first traversal on the entire Clang AST and visits each...
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
Definition: Redeclarable.h:216
decl_type * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
Definition: Redeclarable.h:204
decl_type * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
Definition: Redeclarable.h:226
void setPreviousDecl(decl_type *PrevDecl)
Set the previous declaration.
Definition: Decl.h:4994
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: Redeclarable.h:296
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3380
QualType getPointeeType() const
Definition: Type.h:3398
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition: Stmt.h:3019
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:392
void AddDecl(Decl *D)
Definition: Scope.h:345
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition: Scope.h:270
@ DeclScope
This is a scope that can contain a declaration.
Definition: Scope.h:63
A generic diagnostic builder for errors which may or may not be deferred.
Definition: SemaBase.h:110
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: SemaBase.cpp:56
Sema & SemaRef
Definition: SemaBase.h:40
bool inferTargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, CXXMethodDecl *MemberDecl, bool ConstRHS, bool Diagnose)
Given a implicit special member, infer its CUDA target from the calls it needs to make to underlying ...
Definition: SemaCUDA.cpp:372
void checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, SourceLocation IdLoc=SourceLocation())
Check declaration inside target region.
A RAII object to enter scope of a compound statement.
Definition: Sema.h:855
bool isInvalid() const
Definition: Sema.h:5808
A RAII object to temporarily push a declaration context.
Definition: Sema.h:2531
For a defaulted function, the kind of defaulted function that it is.
Definition: Sema.h:4642
DefaultedComparisonKind asComparison() const
Definition: Sema.h:4674
CXXSpecialMemberKind asSpecialMember() const
Definition: Sema.h:4671
Helper class that collects exception specifications for implicitly-declared special member functions.
Definition: Sema.h:3983
void CalledStmt(Stmt *S)
Integrate an invoked statement into the collected data.
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:7239
CXXMethodDecl * getMethod() const
Definition: Sema.h:7251
RAII object to handle the state changes required to synthesize a function body.
Definition: Sema.h:10100
Abstract base class used for diagnosing integer constant expression violations.
Definition: Sema.h:5706
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:451
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.
Definition: SemaDecl.cpp:11038
MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, CXXRecordDecl *ClassDecl)
void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D)
Definition: SemaDecl.cpp:6793
QualType getCurrentThisType()
Try to retrieve the type of the 'this' pointer.
bool EvaluateStaticAssertMessageAsString(Expr *Message, std::string &Result, ASTContext &Ctx, bool ErrorOnInvalidMessage)
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:9702
Decl * ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS, MultiTemplateParamsArg TemplateParams, SourceLocation UsingLoc, UnqualifiedId &Name, const ParsedAttributesView &AttrList, TypeResult Type, Decl *DeclFromDeclSpec)
TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, QualType NTTPType, SourceLocation Loc, NamedDecl *TemplateParam=nullptr)
Allocate a TemplateArgumentLoc where all locations have been initialized to the given location.
NamedDecl * ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope)
Definition: SemaDecl.cpp:9808
bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New, const CXXMethodDecl *Old)
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:4795
void ActOnParamUnparsedDefaultArgument(Decl *param, SourceLocation EqualLoc, SourceLocation ArgLoc)
ActOnParamUnparsedDefaultArgument - We've seen a default argument for a function parameter,...
DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD)
Determine the kind of defaulting that would be done for a given function.
ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs, const Scope *S, ActOnMemberAccessExtraArgs *ExtraArgs=nullptr)
bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S=nullptr, bool AllowInlineNamespace=false) const
isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true if 'D' is in Scope 'S',...
Definition: SemaDecl.cpp:1585
bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs=true)
ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val)
Definition: SemaExpr.cpp:3648
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr, bool IsAfterAmp=false)
Definition: SemaExpr.cpp:15385
void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath)
void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old)
Merge the exception specifications of two variable declarations.
CXXSpecialMemberKind getSpecialMember(const CXXMethodDecl *MD)
Definition: Sema.h:4599
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:7287
@ LookupUsingDeclName
Look up all declarations in a scope with the given name, including resolved using declarations.
Definition: Sema.h:7314
@ LookupLocalFriendName
Look up a friend of a local class.
Definition: Sema.h:7322
@ LookupNamespaceName
Look up a namespace name within a C++ using directive or namespace alias definition,...
Definition: Sema.h:7310
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition: Sema.h:7295
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:424
void DiagnoseFunctionSpecifiers(const DeclSpec &DS)
Diagnose function specifiers on a declaration of an identifier that does not identify a function.
Definition: SemaDecl.cpp:6729
VariadicCallType
Definition: Sema.h:2004
@ VariadicDoesNotApply
Definition: Sema.h:2009
@ VariadicConstructor
Definition: Sema.h:2008
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.
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)
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.
Definition: SemaDecl.cpp:6198
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)
void PrintContextStack()
Definition: Sema.h:10242
SemaOpenMP & OpenMP()
Definition: Sema.h:1013
void CheckDelegatingCtorCycles()
SmallVector< CXXMethodDecl *, 4 > DelayedDllExportMemberFunctions
Definition: Sema.h:4590
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,...
Definition: SemaDecl.cpp:6165
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:815
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:4772
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:4753
void AddPragmaAttributes(Scope *S, Decl *D)
Adds the attributes that have been specified using the '#pragma clang attribute push' directives to t...
Definition: SemaAttr.cpp:1093
SemaCUDA & CUDA()
Definition: Sema.h:993
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)
Definition: SemaExpr.cpp:17253
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'.
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 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:1077
@ AR_accessible
Definition: Sema.h:1075
@ AR_inaccessible
Definition: Sema.h:1076
@ AR_delayed
Definition: Sema.h:1078
PoppedFunctionScopePtr PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP=nullptr, const Decl *D=nullptr, QualType BlockType=QualType())
Pop a function (or block or lambda or captured region) scope from the stack.
Definition: Sema.cpp:2251
Scope * getScopeForContext(DeclContext *Ctx)
Determines the active Scope associated with the given declaration context.
Definition: Sema.cpp:2113
CXXConstructorDecl * DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl)
Declare the implicit move constructor for the given class.
bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl, const ParsedAttributesView &AttrList)
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)
CheckForFunctionMarkedFinal - Checks whether a virtual member function overrides a virtual member fun...
NamedDecl * HandleDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists)
Definition: SemaDecl.cpp:6326
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, AllowFoldKind CanFold=NoFold)
VerifyIntegerConstantExpression - Verifies that an expression is an ICE, and reports the appropriate ...
Definition: SemaExpr.cpp:17038
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)
Definition: SemaDecl.cpp:4869
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...
@ Other
C++26 [dcl.fct.def.general]p1 function-body: ctor-initializer[opt] compound-statement function-try-bl...
@ Delete
deleted-function-body
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:52
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.
Definition: SemaDecl.cpp:18473
FPOptionsOverride CurFPFeatureOverrides()
Definition: Sema.h:1422
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.
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:848
void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method)
ActOnFinishDelayedCXXMethodDeclaration - We have finished processing the delayed method declaration f...
DeclarationNameInfo GetNameForDeclarator(Declarator &D)
GetNameForDeclarator - Determine the full declaration name for the given Declarator.
Definition: SemaDecl.cpp:5864
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:514
AccessResult CheckDestructorAccess(SourceLocation Loc, CXXDestructorDecl *Dtor, const PartialDiagnostic &PDiag, QualType objectType=QualType())
Decl * ActOnUsingEnumDeclaration(Scope *CurScope, AccessSpecifier AS, SourceLocation UsingLoc, SourceLocation EnumLoc, SourceLocation IdentLoc, IdentifierInfo &II, CXXScopeSpec *SS=nullptr)
SemaObjC & ObjC()
Definition: Sema.h:1003
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...
NamedDecl * ActOnFriendFunctionDecl(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParams)
void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, TypedefNameDecl *NewTD)
Definition: SemaDecl.cpp:4979
void CheckDelayedMemberExceptionSpecs()
void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param)
This is used to implement the constant expression evaluation part of the attribute enable_if extensio...
AllowFoldKind
Definition: Sema.h:5720
@ AllowFold
Definition: Sema.h:5722
@ NoFold
Definition: Sema.h:5721
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
Definition: SemaDecl.cpp:1523
ASTContext & getASTContext() const
Definition: Sema.h:517
ClassTemplateDecl * StdInitializerList
The C++ "std::initializer_list" template, which is defined in <initializer_list>.
Definition: Sema.h:4779
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,...
Definition: SemaExpr.cpp:19733
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:4857
bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method)
Check whether 'this' shows up in the type of a static member function after the (naturally empty) cv-...
void PopExpressionEvaluationContext()
Definition: SemaExpr.cpp:17679
NamespaceDecl * getOrCreateStdNamespace()
Retrieve the special "std" namespace, which may require us to implicitly define the namespace.
ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, bool RequiresADL=true, bool AllowRewrittenCandidates=true, FunctionDecl *DefaultedFn=nullptr)
Create a binary operation that may resolve to an overloaded operator.
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:645
bool isInitListConstructor(const FunctionDecl *Ctor)
Determine whether Ctor is an initializer-list constructor, as defined in [dcl.init....
void ActOnStartFunctionDeclarationDeclarator(Declarator &D, unsigned TemplateParameterDepth)
Called before parsing a function declarator belonging to a function declaration.
std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths)
Builds a string representing ambiguous paths from a specific derived class to different subobjects of...
DefaultedComparisonKind
Kinds of defaulted comparison operator functions.
Definition: Sema.h:4444
@ Relational
This is an <, <=, >, or >= that should be implemented as a rewrite in terms of a <=> comparison.
@ NotEqual
This is an operator!= that should be implemented as a rewrite in terms of a == comparison.
@ ThreeWay
This is an operator<=> that should be implemented as a series of subobject comparisons.
@ None
This is not a defaultable comparison operator.
@ Equal
This is an operator== that should be implemented as a series of subobject comparisons.
bool RequireLiteralType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Ensure that the type T is a literal type.
Definition: SemaType.cpp:9217
llvm::PointerIntPair< CXXRecordDecl *, 3, CXXSpecialMemberKind > SpecialMemberDecl
Definition: Sema.h:4790
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:765
DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS=nullptr)
Definition: SemaExpr.cpp:2208
ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, llvm::APSInt &Value, CCEKind CCE)
bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, ArrayRef< CXXCtorInitializer * > Initializers=std::nullopt)
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:9167
EnumDecl * getStdAlignValT() const
void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record)
LangAS getDefaultCXXMethodAddrSpace() const
Returns default addr space for method qualifiers.
Definition: Sema.cpp:1518
LazyDeclPtr StdBadAlloc
The C++ "std::bad_alloc" class, which is defined by the C++ standard library.
Definition: Sema.h:6400
QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs, const DeclSpec *DS=nullptr)
Definition: SemaType.cpp:1553
void PushFunctionScope()
Enter a new function scope.
Definition: Sema.cpp:2132
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:512
ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr, ConditionKind CK, bool MissingOK=false)
Definition: SemaExpr.cpp:20249
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:65
@ UPPC_RequiresClause
Definition: Sema.h:10777
@ UPPC_UsingDeclaration
A using declaration.
Definition: Sema.h:10732
@ UPPC_ExceptionType
The type of an exception.
Definition: Sema.h:10750
@ UPPC_Initializer
An initializer.
Definition: Sema.h:10741
@ UPPC_BaseType
The base type of a class type.
Definition: Sema.h:10711
@ UPPC_FriendDeclaration
A friend declaration.
Definition: Sema.h:10735
@ UPPC_DefaultArgument
A default argument.
Definition: Sema.h:10744
@ UPPC_DeclarationType
The type of an arbitrary declaration.
Definition: Sema.h:10714
@ UPPC_DataMemberType
The type of a data member.
Definition: Sema.h:10717
@ UPPC_StaticAssertExpression
The expression in a static assertion.
Definition: Sema.h:10723
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:510
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:4334
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.
Definition: SemaDecl.cpp:1413
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:847
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.
Definition: SemaExpr.cpp:6464
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.
void collectUnexpandedParameterPacks(TemplateArgument Arg, SmallVectorImpl< UnexpandedParameterPack > &Unexpanded)
Collect the set of unexpanded parameter packs within the given template argument.
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)
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 ...
Definition: SemaDecl.cpp:8267
void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet)
AddBuiltinOperatorCandidates - Add the appropriate built-in operator overloads to the candidate set (...
ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind)
ActOnCXXBoolLiteral - Parse {true,false} literals.
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.
bool CheckConstraintSatisfaction(const NamedDecl *Template, ArrayRef< const Expr * > ConstraintExprs, const MultiLevelTemplateArgumentList &TemplateArgLists, SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction)
Check whether the given list of constraint expressions are satisfied (as if in a 'conjunction') given...
Definition: Sema.h:11163
const LangOptions & LangOpts
Definition: Sema.h:846
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.
Definition: SemaExpr.cpp:17375
ExprResult TemporaryMaterializationConversion(Expr *E)
If E is a prvalue denoting an unmaterialized temporary, materialize it as an xvalue.
Definition: SemaInit.cpp:8564
NamedDeclSetType UnusedPrivateFields
Set containing all declared private fields that are not used.
Definition: Sema.h:4757
SemaHLSL & HLSL()
Definition: Sema.h:998
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.
Definition: SemaDecl.cpp:11983
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:4340
void CheckCXXDefaultArguments(FunctionDecl *FD)
Helpers for dealing with blocks and functions.
ComparisonCategoryUsage
Definition: Sema.h:3836
@ DefaultedOperator
A defaulted 'operator<=>' needed the comparison category.
SmallVector< InventedTemplateParameterInfo, 4 > InventedParameterInfos
Stack containing information needed when in C++2a an 'auto' is encountered in a function declaration ...
Definition: Sema.h:4750
void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse)
Perform marking for a reference to an arbitrary declaration.
Definition: SemaExpr.cpp:19890
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
Definition: SemaStmt.cpp:3686
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:4849
llvm::DenseMap< ParmVarDecl *, SourceLocation > UnparsedDefaultArgLocs
Definition: Sema.h:4783
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)
QualType getElaboratedType(ElaboratedTypeKeyword Keyword, const CXXScopeSpec &SS, QualType T, TagDecl *OwnedTagDecl=nullptr)
Retrieve a version of the type 'T' that is elaborated by Keyword, qualified by the nested-name-specif...
Definition: SemaType.cpp:9316
bool RequireCompleteEnumDecl(EnumDecl *D, SourceLocation L, CXXScopeSpec *SS=nullptr)
Require that the EnumDecl is completed with its enumerators defined or instantiated.
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 CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl)
CheckOverloadedOperatorDeclaration - Check whether the declaration of this overloaded operator is wel...
void ExitDeclaratorContext(Scope *S)
Definition: SemaDecl.cpp:1400
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.
CXXRecordDecl * getCurrentClass(Scope *S, const CXXScopeSpec *SS)
Get the class that is directly named by the current context.
void pushCodeSynthesisContext(CodeSynthesisContext Ctx)
QualType BuildReferenceType(QualType T, bool LValueRef, SourceLocation Loc, DeclarationName Entity)
Build a reference type.
Definition: SemaType.cpp:1856
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)
ActOnBaseSpecifier - Parsed a base specifier.
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, SkipBodyInfo *SkipBody=nullptr)
UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations
A mapping from parameters with unparsed default arguments to the set of instantiations of each parame...
Definition: Sema.h:9714
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:4330
ExprResult DefaultLvalueConversion(Expr *E)
Definition: SemaExpr.cpp:652
bool CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Target, const LookupResult &PreviousDecls, UsingShadowDecl *&PrevShadow)
Determines whether to create a using shadow decl for a particular decl, given the set of decls existi...
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
Definition: SemaExpr.cpp:3232
bool isVisible(const NamedDecl *D)
Determine whether a declaration is visible to name lookup.
Definition: Sema.h:11608
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:7661
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)
Definition: SemaDecl.cpp:15509
bool DiagnoseUseOfOverloadedDecl(NamedDecl *D, SourceLocation Loc)
Definition: Sema.h:5172
std::unique_ptr< RecordDeclSetTy > PureVirtualClassDiagSet
PureVirtualClassDiagSet - a set of class declarations which we have emitted a list of pure virtual fu...
Definition: Sema.h:4764
void ActOnFinishInlineFunctionDef(FunctionDecl *D)
Definition: SemaDecl.cpp:15436
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:986
bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, DeclarationName Name, FunctionDecl *&Operator, bool Diagnose=true, bool WantSize=false, bool WantAligned=false)
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.
Definition: SemaDecl.cpp:15010
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name)
Retrieves the declaration name from a parsed unqualified-id.
Definition: SemaDecl.cpp:5870
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 SetDelegatingInitializer(CXXConstructorDecl *Constructor, CXXCtorInitializer *Initializer)
TrivialABIHandling
Definition: Sema.h:4629
@ TAH_IgnoreTrivialABI
The triviality of a method unaffected by "trivial_abi".
Definition: Sema.h:4631
@ TAH_ConsiderTrivialABI
The triviality of a method affected by "trivial_abi".
Definition: Sema.h:4634
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5.
Definition: Sema.h:6211
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 MarkVirtualBaseDestructorsReferenced(SourceLocation Location, CXXRecordDecl *ClassDecl, llvm::SmallPtrSetImpl< const RecordType * > *DirectVirtualBases=nullptr)
Mark destructors of virtual bases of this class referenced.
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.
Definition: SemaExpr.cpp:19837
StmtResult ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc, Stmt *First, ConditionResult Second, FullExprArg Third, SourceLocation RParenLoc, Stmt *Body)
Definition: SemaStmt.cpp:2165
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:10401
SourceManager & getSourceManager() const
Definition: Sema.h:515
@ AA_Passing
Definition: Sema.h:5159
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)
Decl * ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, MultiTemplateParamsArg TemplateParams)
Handle a friend type declaration.
ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow, SourceLocation OpLoc, const CXXScopeSpec &SS, FieldDecl *Field, DeclAccessPair FoundDecl, const DeclarationNameInfo &MemberNameInfo)
void EnterDeclaratorContext(Scope *S, DeclContext *DC)
EnterDeclaratorContext - Used when we must lookup names in the context of a declarator's nested name ...
Definition: SemaDecl.cpp:1365
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.
llvm::FoldingSet< SpecialMemberOverloadResultEntry > SpecialMemberCache
A cache of special member function overload resolution results for C++ records.
Definition: Sema.h:7267
QualType BuildPackIndexingType(QualType Pattern, Expr *IndexExpr, SourceLocation Loc, SourceLocation EllipsisLoc, bool FullySubstituted=false, ArrayRef< QualType > Expansions={})
Definition: SemaType.cpp:9468
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.
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl, SourceLocation EqualLoc, Expr *Init)
This is invoked after parsing an in-class initializer for a non-static C++ class member,...
QualType CheckTemplateIdType(TemplateName Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs)
void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr, SourceLocation Loc)
PushNamespaceVisibilityAttr - Note that we've entered a namespace with a visibility attribute.
Definition: SemaAttr.cpp:1364
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 ...
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReciever=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition: SemaExpr.cpp:228
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.
Definition: SemaDecl.cpp:8301
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)
StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp, bool AllowRecovery=false)
Definition: SemaStmt.cpp:3849
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition: Sema.h:11583
bool CheckImmediateEscalatingFunctionDefinition(FunctionDecl *FD, const sema::FunctionScopeInfo *FSI)
void InstantiateDefaultCtorDefaultArgs(CXXConstructorDecl *Ctor)
In the MS ABI, we need to instantiate default arguments of dllexported default constructors along wit...
@ CTK_ErrorRecovery
Definition: Sema.h:7527
void CheckCompleteVariableDeclaration(VarDecl *VD)
Definition: SemaDecl.cpp:14370
ExprResult ActOnRequiresClause(ExprResult ConstraintExpr)
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:4775
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.
@ CCEK_StaticAssertMessageSize
Call to size() in a static assert message.
Definition: Sema.h:7953
@ CCEK_ExplicitBool
Condition in an explicit(bool) specifier.
Definition: Sema.h:7951
@ CCEK_StaticAssertMessageData
Call to data() in a static assert message.
Definition: Sema.h:7955
void mergeDeclAttributes(NamedDecl *New, Decl *Old, AvailabilityMergeKind AMK=AMK_Redeclaration)
mergeDeclAttributes - Copy attributes from the Old decl to the New one.
Definition: SemaDecl.cpp:3157
ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec *SS=nullptr, bool isClassName=false, bool HasTrailingDot=false, ParsedType ObjectType=nullptr, bool IsCtorOrDtorName=false, bool WantNontrivialTypeSourceInfo=false, bool IsClassTemplateDeductionContext=true, ImplicitTypenameContext AllowImplicitTypename=ImplicitTypenameContext::No, IdentifierInfo **CorrectedII=nullptr)
If the identifier refers to a type name within this scope, return the declaration of that type.
Definition: SemaDecl.cpp:291
ASTConsumer & Consumer
Definition: Sema.h:849
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:3391
@ Ovl_NonFunction
This is not an overload because the lookup results contain a non-function.
Definition: Sema.h:7856
@ Ovl_Overload
This is a legitimate overload: the existing declarations are functions or function templates with dif...
Definition: Sema.h:7848
@ Ovl_Match
This is not an overload because the signature exactly matches an existing declaration.
Definition: Sema.h:7852
void NoteDeletedFunction(FunctionDecl *FD)
Emit a note explaining that this function is deleted.
Definition: SemaExpr.cpp:121
ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc)
Definition: SemaExpr.cpp:5168
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...
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
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...
Definition: SemaType.cpp:9436
TypeSourceInfo * GetTypeForDeclarator(Declarator &D)
GetTypeForDeclarator - Convert the type for the specified declarator to Type instances.
Definition: SemaType.cpp:5678
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 {'.
Definition: SemaDecl.cpp:17230
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.
Definition: SemaType.cpp:8831
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:820
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaInternal.h:24
void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, ArrayRef< Decl * > Fields, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList)
Definition: SemaDecl.cpp:19081
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' ...
Definition: SemaAttr.cpp:1373
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...
Definition: SemaInit.cpp:8137
void CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record)
Perform semantic checks on a class definition that has been completing, introducing implicitly-declar...
void DiscardCleanupsInEvaluationContext()
Definition: SemaExpr.cpp:17757
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition: Sema.h:6362
void PushDeclContext(Scope *S, DeclContext *DC)
Set the current declaration context until it gets popped.
Definition: SemaDecl.cpp:1330
bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New)
bool isDependentScopeSpecifier(const CXXScopeSpec &SS)
SourceManager & SourceMgr
Definition: Sema.h:851
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:850
FullExprArg MakeFullDiscardedValueExpr(Expr *Arg)
Definition: Sema.h:5778
CXXConstructorDecl * DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl)
Declare the implicit copy constructor for the given class.
NamespaceDecl * getStdNamespace() const
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...
@ TUK_Friend
Definition: Sema.h:3169
static bool adjustContextForLocalExternDecl(DeclContext *&DC)
Adjust the DeclContext for a function or variable that might be a function-local external declaration...
Definition: SemaDecl.cpp:7320
@ TPC_TypeAliasTemplate
Definition: Sema.h:8903
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,...
Definition: SemaDecl.cpp:6833
ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field)
Definition: SemaExpr.cpp:5600
Decl * ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList, SourceLocation SemiLoc)
Handle a C++11 empty-declaration and attribute-declaration.
void PopDeclContext()
Definition: SemaDecl.cpp:1337
void diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals, SourceLocation FallbackLoc, SourceLocation ConstQualLoc=SourceLocation(), SourceLocation VolatileQualLoc=SourceLocation(), SourceLocation RestrictQualLoc=SourceLocation(), SourceLocation AtomicQualLoc=SourceLocation(), SourceLocation UnalignedQualLoc=SourceLocation())
Definition: SemaType.cpp:2925
llvm::MapVector< NamedDecl *, SourceLocation > UndefinedButUsed
UndefinedInternals - all the used, undefined objects which require a definition in this translation u...
Definition: Sema.h:4787
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.
Definition: SemaDecl.cpp:1607
FunctionDecl * FindDeallocationFunctionForDestructor(SourceLocation StartLoc, CXXRecordDecl *RD)
ExprResult ConvertMemberDefaultInitExpression(FieldDecl *FD, Expr *InitExpr, SourceLocation InitLoc)
bool IsInvalidSMECallConversion(QualType FromType, QualType ToType)
Definition: SemaExpr.cpp:8933
static Scope * getScopeForDeclContext(Scope *S, DeclContext *DC)
Finds the scope corresponding to the given decl context, if it happens to be an enclosing scope.
Definition: SemaDecl.cpp:1590
@ OOK_Outside
Definition: Sema.h:3174
void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit)
AddInitializerToDecl - Adds the initializer Init to the declaration dcl.
Definition: SemaDecl.cpp:13439
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:298
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:4589
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,...
Definition: SemaExpr.cpp:17940
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,...
bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, const FunctionProtoType *Proto, unsigned FirstParam, ArrayRef< Expr * > Args, SmallVectorImpl< Expr * > &AllArgs, VariadicCallType CallType=VariadicDoesNotApply, bool AllowExplicit=false, bool IsListInitialization=false)
GatherArgumentsForCall - Collector argument expressions for various form of call prototypes.
Definition: SemaExpr.cpp:5950
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
Definition: SemaExpr.cpp:20999
Decl * ActOnDeclarator(Scope *S, Declarator &D)
Definition: SemaDecl.cpp:6132
AbstractDiagSelID
Definition: Sema.h:4544
@ AbstractVariableType
Definition: Sema.h:4548
@ AbstractReturnType
Definition: Sema.h:4546
@ AbstractNone
Definition: Sema.h:4545
@ AbstractFieldType
Definition: Sema.h:4549
@ AbstractArrayType
Definition: Sema.h:4552
@ AbstractParamType
Definition: Sema.h:4547
StmtResult ActOnIfStmt(SourceLocation IfLoc, IfStatementKind StatementKind, SourceLocation LParenLoc, Stmt *InitStmt, ConditionResult Cond, SourceLocation RParenLoc, Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal)
Definition: SemaStmt.cpp:909
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)
void ProcessAPINotes(Decl *D)
Map any API notes provided for this declaration to attributes on the declaration.
bool CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old)
Definition: SemaDecl.cpp:1730
LazyDeclPtr StdAlignValT
The C++ "std::align_val_t" enum class, which is defined by the C++ standard library.
Definition: Sema.h:6404
ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr)
CreateBuiltinBinOp - Creates a new built-in binary operation with operator Opc at location TokLoc.
Definition: SemaExpr.cpp:14696
void DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction, bool First=true)
Emit diagnostics explaining why a constraint expression was deemed unsatisfied.
void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc)
bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base)
Determine whether the type Derived is a C++ class that is derived from the type Base.
CheckConstexprKind
Definition: Sema.h:4695
@ CheckValid
Identify whether this function satisfies the formal rules for constexpr functions in the current lanu...
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
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)
Definition: SemaType.cpp:2805
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:415
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:2524
DeclResult ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, unsigned TagSpec, SourceLocation TagLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, MultiTemplateParamsArg TempParamLists)
Handle a friend tag declaration where the scope specifier was templated.
DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class)
Look up the constructors for the given class.
void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record)
bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMemberKind CSM, TrivialABIHandling TAH=TAH_IgnoreTrivialABI, bool Diagnose=false)
Determine whether a defaulted or deleted special member function is trivial, as specified in C++11 [c...
ExprResult ActOnCXXThis(SourceLocation Loc)
bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc, UnexpandedParameterPackContext UPPC, ArrayRef< UnexpandedParameterPack > Unexpanded)
Diagnose unexpanded parameter packs.
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)
Definition: SemaDecl.cpp:6119
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.
NamedDecl * ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope, ArrayRef< BindingDecl * > Bindings=std::nullopt)
Definition: SemaDecl.cpp:7488
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)
bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param, Expr *Init=nullptr, bool SkipImmediateInvocations=true)
Instantiate or parse a C++ default argument expression as necessary.
Definition: SemaExpr.cpp:5396
ValueDecl * tryLookupUnambiguousFieldDecl(RecordDecl *ClassDecl, const IdentifierInfo *MemberOrBase)
ASTMutationListener * getASTMutationListener() const
Definition: Sema.cpp:550
ExprResult CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl=nullptr, bool RecoverUncorrectedTypos=false, llvm::function_ref< ExprResult(Expr *)> Filter=[](Expr *E) -> ExprResult { return E;})
Process any TypoExprs in the given Expr and its children, generating diagnostics as appropriate and r...
void DiagnoseImmediateEscalatingReason(FunctionDecl *FD)
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition: Sema.h:6650
void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType)
FinalizeVarWithDestructor - Prepare for calling destructor on the constructed variable.
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 isInMainFile(SourceLocation Loc) const
Returns whether the PresumedLoc for a given SourceLocation is in the main file.
SourceLocation getSpellingLoc(SourceLocation Loc) const
Given a SourceLocation object, return the spelling location referenced by the ID.
CharSourceRange getImmediateExpansionRange(SourceLocation Loc) const
Return the start/end of the expansion information for an expansion location.
SourceLocation getExpansionLoc(SourceLocation Loc) const
Given a SourceLocation object Loc, return the expansion location referenced by the ID.
A trivial tuple used to represent a source range.
void setBegin(SourceLocation b)
bool isInvalid() const
SourceLocation getEnd() const
SourceLocation getBegin() const
bool isValid() const
void setEnd(SourceLocation e)
static StaticAssertDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StaticAssertLoc, Expr *AssertExpr, Expr *Message, SourceLocation RParenLoc, bool Failed)
Definition: DeclCXX.cpp:3309
Stmt - This represents one statement.
Definition: Stmt.h:84
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:350
child_range children()
Definition: Stmt.cpp:287
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:326
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:338
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:1773
bool isUnevaluated() const
Definition: Expr.h:1902
StringRef getString() const
Definition: Expr.h:1850
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3584
bool isBeingDefined() const
Return true if this decl is currently being defined.
Definition: Decl.h:3707
StringRef getKindName() const
Definition: Decl.h:3775
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition: Decl.h:3687
TagDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:4726
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:4720
bool isUnion() const
Definition: Decl.h:3790
TagKind getTagKind() const
Definition: Decl.h:3779
bool isDependentType() const
Whether this declaration declares a type that is dependent, i.e., a type that somehow depends on temp...
Definition: Decl.h:3738
bool areArgsDestroyedLeftToRightInCallee() const
Are arguments to a call destroyed left to right in the callee? This is a fundamental language change,...
Definition: TargetCXXABI.h:188
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:136
bool hasKeyFunctions() const
Does this ABI use key functions? If so, class data such as the vtable is emitted with strong linkage ...
Definition: TargetCXXABI.h:206
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1256
virtual CallingConvKind getCallingConvKind(bool ClangABICompat4) const
Definition: TargetInfo.cpp:593
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1327
virtual bool shouldDLLImportComdatSymbols() const
Does this target aim for semantic compatibility with Microsoft C++ code using dllimport/export attrib...
Definition: TargetInfo.h:1294
A convenient class for passing around template argument information.
Definition: TemplateBase.h:632
void addArgument(const TemplateArgumentLoc &Loc)
Definition: TemplateBase.h:667
llvm::ArrayRef< TemplateArgumentLoc > arguments() const
Definition: TemplateBase.h:659
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:524
const TemplateArgument & getArgument() const
Definition: TemplateBase.h:574
TypeSourceInfo * getTypeSourceInfo() const
Definition: TemplateBase.h:578
Represents a template argument.
Definition: TemplateBase.h:61
@ Type
The template argument is a type.
Definition: TemplateBase.h:70
ArgKind getKind() const
Return the kind of stored template argument.
Definition: TemplateBase.h:295
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:394
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:413
Represents a C++ template name within the type system.
Definition: TemplateName.h:202
TemplateDecl * getAsTemplateDecl() const
Retrieve the underlying template declaration that this template name refers to, if known.
NameKind getKind() const
@ UsingTemplate
A template name that refers to a template declaration found through a specific using shadow declarati...
Definition: TemplateName.h:247
@ Template
A single template declaration.
Definition: TemplateName.h:219
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:73
NamedDecl * getParam(unsigned Idx)
Definition: DeclTemplate.h:144
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclTemplate.h:203
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.
Definition: DeclTemplate.h:180
SourceLocation getRAngleLoc() const
Definition: DeclTemplate.h:201
SourceLocation getLAngleLoc() const
Definition: DeclTemplate.h:200
static bool shouldIncludeTypeForArgument(const PrintingPolicy &Policy, const TemplateParameterList *TPL, unsigned Idx)
SourceLocation getTemplateLoc() const
Definition: DeclTemplate.h:199
TemplateArgumentLoc getArgLoc(unsigned i) const
Definition: TypeLoc.h:1695
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:6089
ArrayRef< TemplateArgument > template_arguments() const
Definition: Type.h:6157
TemplateName getTemplateName() const
Retrieve the name of the template that we are specializing.
Definition: Type.h:6155
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.
unsigned getIndex() const
Definition: Type.h:5779
unsigned getDepth() const
Definition: Type.h:5778
The top declaration context.
Definition: Decl.h:84
Represents the declaration of a typedef-name via a C++11 alias-declaration.
Definition: Decl.h:3555
static TypeAliasDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition: Decl.cpp:5554
void setDescribedAliasTemplate(TypeAliasTemplateDecl *TAT)
Definition: Decl.h:3574
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:3390
const Type * getTypeForDecl() const
Definition: Decl.h:3414
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:170
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:89
TypeLoc IgnoreParens() const
Definition: TypeLoc.h:1225
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:153
SourceRange getLocalSourceRange() const
Get the local source range.
Definition: TypeLoc.h:159
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:235
T getAsAdjusted() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:2684
SourceLocation getBeginLoc() const
Get the begin source location.
Definition: TypeLoc.cpp:192
A container of type source information.
Definition: Type.h:7330
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:256
QualType getType() const
Return the type wrapped by this type source info.
Definition: Type.h:7341
A reasonable base class for TypeLocs that correspond to types that are written as a type-specifier.
Definition: TypeLoc.h:528
static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag)
Converts a TagTypeKind into an elaborated type keyword.
Definition: Type.cpp:3160
static StringRef getTagTypeKindName(TagTypeKind Kind)
Definition: Type.h:6352
static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into a tag type kind.
Definition: Type.cpp:3142
The base class of the type hierarchy.
Definition: Type.h:1813
bool isSizelessType() const
As an extension, we classify types as one of "sized" or "sizeless"; every type is one or the other.
Definition: Type.cpp:2463
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1871
bool isVoidType() const
Definition: Type.h:7905
bool isBooleanType() const
Definition: Type.h:8033
bool isLiteralType(const ASTContext &Ctx) const
Return true if this is a literal type (C++11 [basic.types]p10)
Definition: Type.cpp:2901
bool isIncompleteArrayType() const
Definition: Type.h:7686
bool isUndeducedAutoType() const
Definition: Type.h:7761
bool isRValueReferenceType() const
Definition: Type.h:7632
bool isArrayType() const
Definition: Type.h:7678
bool isPointerType() const
Definition: Type.h:7612
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:7945
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8193
bool isReferenceType() const
Definition: Type.h:7624
bool isEnumeralType() const
Definition: Type.h:7710
bool isElaboratedTypeSpecifier() const
Determine wither this type is a C++ elaborated-type-specifier.
Definition: Type.cpp:3267
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:695
bool isLValueReferenceType() const
Definition: Type.h:7628
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition: Type.h:7874
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2653
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition: Type.h:2320
QualType getCanonicalTypeInternal() const
Definition: Type.h:2936
bool containsErrors() const
Whether this type is an error type.
Definition: Type.h:2647
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: Type.h:8076
bool isFunctionProtoType() const
Definition: Type.h:2494
bool isOverloadableType() const
Determines whether this is a type for which one can define an overloaded operator.
Definition: Type.h:8046
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2671
bool isObjCObjectType() const
Definition: Type.h:7748
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:8039
bool isFunctionType() const
Definition: Type.h:7608
bool isObjCObjectPointerType() const
Definition: Type.h:7744
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:2255
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8126
bool isRecordType() const
Definition: Type.h:7706
bool isUnionType() const
Definition: Type.cpp:661
TagDecl * getAsTagDecl() const
Retrieves the TagDecl that this type refers to, either because the type is a TagType or because it is...
Definition: Type.cpp:1879
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition: Type.cpp:1875
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3432
QualType getUnderlyingType() const
Definition: Decl.h:3487
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...
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition: Expr.h:2183
Expr * getSubExpr() const
Definition: Expr.h:2228
Opcode getOpcode() const
Definition: Expr.h:2223
static bool isIncrementDecrementOp(Opcode Op)
Definition: Expr.h:2283
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:4843
Represents a C++ unqualified-id that has been parsed.
Definition: DeclSpec.h:1025
UnionParsedType ConversionFunctionId
When Kind == IK_ConversionFunctionId, the type that the conversion function names.
Definition: DeclSpec.h:1061
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:1237
SourceRange getSourceRange() const LLVM_READONLY
Return the source range that covers this unqualified-id.
Definition: DeclSpec.h:1234
UnionParsedType DestructorName
When Kind == IK_DestructorName, the type referred to by the class-name.
Definition: DeclSpec.h:1069
UnionParsedTemplateTy TemplateName
When Kind == IK_DeductionGuideName, the parsed template-name.
Definition: DeclSpec.h:1072
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition: DeclSpec.h:1107
TemplateIdAnnotation * TemplateId
When Kind == IK_TemplateId or IK_ConstructorTemplateId, the template-id annotation that contains the ...
Definition: DeclSpec.h:1077
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, UnresolvedSetIterator Begin, UnresolvedSetIterator End, bool KnownDependent)
Definition: ExprCXX.cpp:372
A set of unresolved declarations.
Definition: UnresolvedSet.h:61
ArrayRef< DeclAccessPair > pairs() const
Definition: UnresolvedSet.h:89
The iterator over UnresolvedSets.
Definition: UnresolvedSet.h:35
A set of unresolved declarations.
This node is generated when a using-declaration that was annotated with attribute((using_if_exists)) ...
Definition: DeclCXX.h:4040
static UnresolvedUsingIfExistsDecl * Create(ASTContext &Ctx, DeclContext *DC, SourceLocation Loc, DeclarationName Name)
Definition: DeclCXX.cpp:3288
Represents a dependent using declaration which was marked with typename.
Definition: DeclCXX.h:3959
static UnresolvedUsingTypenameDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc, SourceLocation TypenameLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TargetNameLoc, DeclarationName TargetName, SourceLocation EllipsisLoc)
Definition: DeclCXX.cpp:3267
Represents a dependent using declaration which was not marked with typename.
Definition: DeclCXX.h:3862
static UnresolvedUsingValueDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, SourceLocation EllipsisLoc)
Definition: DeclCXX.cpp:3239
Represents a C++ using-declaration.
Definition: DeclCXX.h:3512
bool hasTypename() const
Return true if the using declaration has 'typename'.
Definition: DeclCXX.h:3561
DeclarationNameInfo getNameInfo() const
Definition: DeclCXX.h:3553
static UsingDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingL, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool HasTypenameKeyword)
Definition: DeclCXX.cpp:3173
NestedNameSpecifier * getQualifier() const
Retrieve the nested-name-specifier that qualifies the name.
Definition: DeclCXX.h:3549
SourceLocation getUsingLoc() const
Return the source location of the 'using' keyword.
Definition: DeclCXX.h:3539
Represents C++ using-directive.
Definition: DeclCXX.h:3015
static UsingDirectiveDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc, SourceLocation NamespaceLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation IdentLoc, NamedDecl *Nominated, DeclContext *CommonAncestor)
Definition: DeclCXX.cpp:2937
Represents a C++ using-enum-declaration.
Definition: DeclCXX.h:3713
static UsingEnumDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingL, SourceLocation EnumL, SourceLocation NameL, TypeSourceInfo *EnumType)
Definition: DeclCXX.cpp:3194
static UsingPackDecl * Create(ASTContext &C, DeclContext *DC, NamedDecl *InstantiatedFrom, ArrayRef< NamedDecl * > UsingDecls)
Definition: DeclCXX.cpp:3217
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition: DeclCXX.h:3320
static UsingShadowDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation Loc, DeclarationName Name, BaseUsingDecl *Introducer, NamedDecl *Target)
Definition: DeclCXX.h:3356
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition: DeclCXX.h:3384
BaseUsingDecl * getIntroducer() const
Gets the (written or instantiated) using declaration that introduced this declaration.
Definition: DeclCXX.cpp:3113
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:706
void setType(QualType newType)
Definition: Decl.h:718
QualType getType() const
Definition: Decl.h:717
Represents a variable declaration or definition.
Definition: Decl.h:918
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition: Decl.cpp:2787
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition: Decl.cpp:2148
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition: Decl.h:1549
DefinitionKind isThisDeclarationADefinition(ASTContext &) const
Check whether this declaration is a definition.
Definition: Decl.cpp:2257
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:2187
bool isNoDestroy(const ASTContext &) const
Is destruction of this variable entirely suppressed? If so, the variable need not have a usable destr...
Definition: Decl.cpp:2813
void setCXXCondDecl()
Definition: Decl.h:1599
bool isInlineSpecified() const
Definition: Decl.h:1534
APValue * evaluateValue() const
Attempt to evaluate the value of the initializer attached to this declaration, and produce notes expl...
Definition: Decl.cpp:2551
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1270
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition: Decl.h:1213
bool hasConstantInitialization() const
Determine whether this variable has constant initialization.
Definition: Decl.cpp:2624
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:1195
QualType::DestructionKind needsDestruction(const ASTContext &Ctx) const
Would the destruction of this variable have any effect, and if so, what kind?
Definition: Decl.cpp:2820
ThreadStorageClassSpecifier getTSCSpec() const
Definition: Decl.h:1164
const Expr * getInit() const
Definition: Decl.h:1355
@ TLS_Dynamic
TLS with a dynamic initializer.
Definition: Decl.h:944
void setInit(Expr *I)
Definition: Decl.cpp:2454
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:1155
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:2505
void setExceptionVariable(bool EV)
Definition: Decl.h:1477
bool isParameterPack() const
Determine whether this variable is actually a function parameter pack or init-capture pack.
Definition: Decl.cpp:2663
Declaration of a variable template.
Represents a GCC generic vector type.
Definition: Type.h:3969
unsigned getNumElements() const
Definition: Type.h:3984
QualType getElementType() const
Definition: Type.h:3983
Represents a C++11 virt-specifier-seq.
Definition: DeclSpec.h:2780
SourceLocation getOverrideLoc() const
Definition: DeclSpec.h:2800
SourceLocation getLastLocation() const
Definition: DeclSpec.h:2812
bool isOverrideSpecified() const
Definition: DeclSpec.h:2799
SourceLocation getFinalLoc() const
Definition: DeclSpec.h:2804
bool isFinalSpecified() const
Definition: DeclSpec.h:2802
bool isFinalSpelledSealed() const
Definition: DeclSpec.h:2803
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
Defines the clang::TargetInfo interface.
#define UINT_MAX
Definition: limits.h:64
const AstTypeMatcher< RecordType > recordType
Matches record types (e.g.
bool Inc(InterpState &S, CodePtr OpPC)
1) Pops a pointer from the stack 2) Load the value from the pointer 3) Writes the value increased by ...
Definition: Interp.h:589
bool Zero(InterpState &S, CodePtr OpPC)
Definition: Interp.h:1873
bool Comp(InterpState &S, CodePtr OpPC)
1) Pops the value from the stack.
Definition: Interp.h:708
Stencil access(llvm::StringRef BaseId, Stencil Member)
Constructs a MemberExpr that accesses the named member (Member) of the object bound to BaseId.
The JSON file list parser is used to communicate input to InstallAPI.
@ 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.
bool FTIHasNonVoidParameters(const DeclaratorChunk::FunctionTypeInfo &FTI)
Definition: SemaInternal.h:36
TypeSpecifierType
Specifies the kind of type.
Definition: Specifiers.h:55
@ TST_decltype
Definition: Specifiers.h:89
@ TST_typename_pack_indexing
Definition: Specifiers.h:97
@ TST_decltype_auto
Definition: Specifiers.h:93
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
Definition: OperatorKinds.h:21
@ OO_None
Not an overloaded operator.
Definition: OperatorKinds.h:22
@ NUM_OVERLOADED_OPERATORS
Definition: OperatorKinds.h:26
bool isa(CodeGen::Address addr)
Definition: Address.h:294
bool isTemplateInstantiation(TemplateSpecializationKind Kind)
Determine whether this template specialization kind refers to an instantiation of an entity (as oppos...
Definition: Specifiers.h:209
@ CPlusPlus23
Definition: LangStandard.h:60
@ CPlusPlus20
Definition: LangStandard.h:59
@ CPlusPlus
Definition: LangStandard.h:55
@ CPlusPlus11
Definition: LangStandard.h:56
@ CPlusPlus14
Definition: LangStandard.h:57
@ CPlusPlus26
Definition: LangStandard.h:61
@ CPlusPlus17
Definition: LangStandard.h:58
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
@ Specialization
We are substituting template parameters for template arguments in order to form a template specializa...
LinkageSpecLanguageIDs
Represents the language in a linkage specification.
Definition: DeclCXX.h:2926
InClassInitStyle
In-class initialization styles for non-static data members.
Definition: Specifiers.h:268
@ ICIS_ListInit
Direct list-initialization.
Definition: Specifiers.h:271
@ ICIS_NoInit
No in-class initializer.
Definition: Specifiers.h:269
@ RQ_None
No ref-qualifier was provided.
Definition: Type.h:1762
@ RQ_RValue
An rvalue ref-qualifier was provided (&&).
Definition: Type.h:1768
@ 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:1534
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition: Specifiers.h:148
BinaryOperatorKind
@ IK_DeductionGuideName
A deduction-guide name (a template-name)
@ IK_ImplicitSelfParam
An implicit 'self' parameter.
@ IK_TemplateId
A template-id, e.g., f<int>.
@ IK_ConstructorTemplateId
A constructor named via a template-id.
@ IK_ConstructorName
A constructor name.
@ IK_LiteralOperatorId
A user-defined literal name, e.g., operator "" _i.
@ IK_Identifier
An identifier.
@ IK_DestructorName
A destructor name.
@ IK_OperatorFunctionId
An overloaded operator name, e.g., operator+.
@ IK_ConversionFunctionId
A conversion function name, e.g., operator int.
std::optional< ComparisonCategoryType > getComparisonCategoryForBuiltinCmp(QualType T)
Get the comparison category that should be used when comparing values of type T.
StorageClass
Storage classes.
Definition: Specifiers.h:245
@ SC_Static
Definition: Specifiers.h:249
@ SC_None
Definition: Specifiers.h:247
ThreadStorageClassSpecifier
Thread storage-class-specifier.
Definition: Specifiers.h:232
ComparisonCategoryType commonComparisonType(ComparisonCategoryType A, ComparisonCategoryType B)
Determine the common comparison type, as defined in C++2a [class.spaceship]p4.
ComparisonCategoryResult
An enumeration representing the possible results of a three-way comparison.
Language
The language for the input, used to select and validate the language standard and possible actions.
Definition: LangStandard.h:23
StmtResult StmtError()
Definition: Ownership.h:265
@ Result
The result type of a method or function.
InheritableAttr * getDLLAttr(Decl *D)
Return a DLL attribute from the declaration.
Definition: SemaInternal.h:54
bool isComputedNoexcept(ExceptionSpecificationType ESpecType)
void EscapeStringForDiagnostic(StringRef Str, SmallVectorImpl< char > &OutStr)
EscapeStringForDiagnostic - Append Str to the diagnostic buffer, escaping non-printable characters an...
Definition: Diagnostic.cpp:805
ReservedLiteralSuffixIdStatus
ActionResult< Expr * > ExprResult
Definition: Ownership.h:248
TagTypeKind
The kind of a tag type.
Definition: Type.h:6299
@ Interface
The "__interface" keyword.
@ Struct
The "struct" keyword.
@ Class
The "class" keyword.
MutableArrayRef< TemplateParameterList * > MultiTemplateParamsArg
Definition: Ownership.h:262
ExprResult ExprError()
Definition: Ownership.h:264
LangAS
Defines the address space values used by the address space qualifier of QualType.
Definition: AddressSpaces.h:25
@ CanPassInRegs
The argument of this type can be passed directly in registers.
@ CanNeverPassInRegs
The argument of this type cannot be passed directly in registers.
@ CannotPassInRegs
The argument of this type cannot be passed directly in registers.
@ TU_Prefix
The translation unit is a prefix to a translation unit, and is not complete.
Definition: LangOptions.h:1039
ComparisonCategoryType
An enumeration representing the different comparison categories types.
ActionResult< Stmt * > StmtResult
Definition: Ownership.h:249
CXXSpecialMemberKind
Kinds of C++ special members.
Definition: Sema.h:425
OverloadedOperatorKind getRewrittenOverloadedOperator(OverloadedOperatorKind Kind)
Get the other overloaded operator that the given operator can be rewritten into, if any such operator...
Definition: OperatorKinds.h:36
@ TNK_Concept_template
The name refers to a concept.
Definition: TemplateKinds.h:52
ActionResult< ParsedType > TypeResult
Definition: Ownership.h:250
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition: Specifiers.h:129
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:132
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition: Specifiers.h:141
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:136
const FunctionProtoType * T
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1275
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
@ Incomplete
Template argument deduction did not deduce a value for every template parameter.
@ Inconsistent
Template argument deduction produced inconsistent deduced values for the given template parameter.
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition: Specifiers.h:185
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition: Specifiers.h:203
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition: Specifiers.h:199
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition: Specifiers.h:195
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:191
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition: Specifiers.h:188
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:275
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition: Type.h:6274
@ None
No keyword precedes the qualified type name.
@ Class
The "class" keyword introduces the elaborated-type-specifier.
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
bool isExternallyVisible(Linkage L)
Definition: Linkage.h:90
ExceptionSpecificationType
The various types of exception specifications that exist in C++11.
@ EST_DependentNoexcept
noexcept(expression), value-dependent
@ EST_DynamicNone
throw()
@ 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)
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition: Specifiers.h:120
@ AS_public
Definition: Specifiers.h:121
@ AS_protected
Definition: Specifiers.h:122
@ AS_none
Definition: Specifiers.h:124
@ AS_private
Definition: Specifiers.h:123
MutableArrayRef< Expr * > MultiExprArg
Definition: Ownership.h:258
@ NOUR_Unevaluated
This name appears in an unevaluated operand.
Definition: Specifiers.h:174
#define true
Definition: stdbool.h:25
#define false
Definition: stdbool.h:26
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:1365
ParamInfo * Params
Params - This is a pointer to a new[]'d array of ParamInfo objects that describe the parameters speci...
Definition: DeclSpec.h:1425
unsigned RefQualifierIsLValueRef
Whether the ref-qualifier (if any) is an lvalue reference.
Definition: DeclSpec.h:1374
DeclSpec * MethodQualifiers
DeclSpec for the function with the qualifier related info.
Definition: DeclSpec.h:1428
SourceLocation getRefQualifierLoc() const
Retrieve the location of the ref-qualifier, if any.
Definition: DeclSpec.h:1526
unsigned NumParams
NumParams - This is the number of formal parameters specified by the declarator.
Definition: DeclSpec.h:1400
bool hasMutableQualifier() const
Determine whether this lambda-declarator contains a 'mutable' qualifier.
Definition: DeclSpec.h:1555
bool hasMethodTypeQualifiers() const
Determine whether this method has qualifiers.
Definition: DeclSpec.h:1558
void freeParams()
Reset the parameter list to having zero parameters.
Definition: DeclSpec.h:1464
bool hasRefQualifier() const
Determine whether this function declaration contains a ref-qualifier.
Definition: DeclSpec.h:1551
std::unique_ptr< CachedTokens > DefaultArgTokens
DefaultArgTokens - When the parameter's default argument cannot be parsed immediately (because it occ...
Definition: DeclSpec.h:1340
One instance of this struct is used for each type in a declarator that is parsed.
Definition: DeclSpec.h:1248
enum clang::DeclaratorChunk::@221 Kind
FunctionTypeInfo Fun
Definition: DeclSpec.h:1639
EvalResult is a struct with detailed info about an evaluated expression.
Definition: Expr.h:642
Holds information about the various types of exception specification.
Definition: Type.h:4707
FunctionDecl * SourceDecl
The function whose exception specification this is, for EST_Unevaluated and EST_Uninstantiated.
Definition: Type.h:4719
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition: Type.h:4709
ArrayRef< QualType > Exceptions
Explicitly-specified list of exception types.
Definition: Type.h:4712
Expr * NoexceptExpr
Noexcept expression, if this is a computed noexcept specification.
Definition: Type.h:4715
Extra information about a function prototype.
Definition: Type.h:4735
ExceptionSpecInfo ExceptionSpec
Definition: Type.h:4742
FunctionType::ExtInfo ExtInfo
Definition: Type.h:4736
T * get(ExternalASTSource *Source) const
Retrieve the pointer to the AST node that this lazy pointer points to.
Information about operator rewrites to consider when adding operator functions to a candidate set.
Definition: Overload.h:1006
Describes how types, statements, expressions, and declarations should be printed.
Definition: PrettyPrinter.h:57
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition: Sema.h:9719
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
SourceLocation PointOfInstantiation
The point of instantiation or synthesis within the source code.
Definition: Sema.h:9836
@ MarkingClassDllexported
We are marking a class as __dllexport.
Definition: Sema.h:9813
@ InitializingStructuredBinding
We are initializing a structured binding.
Definition: Sema.h:9810
@ ExceptionSpecEvaluation
We are computing the exception specification for a defaulted special member function.
Definition: Sema.h:9763
@ DeclaringSpecialMember
We are declaring an implicit special member function.
Definition: Sema.h:9777
@ DeclaringImplicitEqualityComparison
We are declaring an implicit 'operator==' for a defaulted 'operator<=>'.
Definition: Sema.h:9781
Decl * Entity
The entity that is being synthesized.
Definition: Sema.h:9839
CXXSpecialMemberKind SpecialMember
The special member being declared or defined.
Definition: Sema.h:9865
Abstract class used to diagnose incomplete types.
Definition: Sema.h:6303
virtual void diagnose(Sema &S, SourceLocation Loc, QualType T)=0
Information about a template-id annotation token.
TemplateNameKind Kind
The kind of template that Template refers to.
SourceLocation TemplateNameLoc
TemplateNameLoc - The location of the template name within the source.
SourceLocation RAngleLoc
The location of the '>' after the template argument list.
SourceLocation LAngleLoc
The location of the '<' before the template argument list.
OpaquePtr< T > get() const
Definition: Ownership.h:104